pdc-api 0.4.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,307 @@
1
+ from datetime import datetime
2
+ from typing import Annotated, Any, ClassVar, Literal, Self
3
+ from uuid import UUID
4
+
5
+ from pydantic import Field, TypeAdapter, field_validator, model_validator
6
+
7
+ from pdc_api.client import get_bundle_page
8
+ from pdc_api.models import (
9
+ BaseFieldCategory,
10
+ BaseSchema,
11
+ PermissionGrantEntityType,
12
+ PermissionGrantGranteeType,
13
+ PermissionGrantVerb,
14
+ )
15
+ from pdc_api.transport import APISession
16
+
17
+ _ENDPOINT = "permissionGrants"
18
+ _DEFAULT_ENDPOINT = "defaultPermissionGrants"
19
+
20
+ _DEFAULT_PAGE_SIZE = 50
21
+
22
+
23
+ class PermissionGrantConditionRule(BaseSchema):
24
+ property: Literal["baseFieldCategory"]
25
+ operator: Literal["in"]
26
+ value: list[BaseFieldCategory] = Field(min_length=1)
27
+
28
+
29
+ class PermissionGrantConditions(BaseSchema):
30
+ proposal_field_value: PermissionGrantConditionRule | None = Field(default=None, alias="proposalFieldValue")
31
+ initiative_field_value: PermissionGrantConditionRule | None = Field(default=None, alias="initiativeFieldValue")
32
+
33
+
34
+ class _PermissionGrantBase(BaseSchema):
35
+ id: int | None = None
36
+ grantee_type: PermissionGrantGranteeType = Field(alias="granteeType")
37
+ grantee_user_keycloak_user_id: UUID | None = Field(default=None, alias="granteeUserKeycloakUserId")
38
+ grantee_keycloak_organization_id: UUID | None = Field(default=None, alias="granteeKeycloakOrganizationId")
39
+ verbs: list[PermissionGrantVerb] = Field(min_length=1)
40
+ scope: list[PermissionGrantEntityType] = Field(min_length=1)
41
+ conditions: PermissionGrantConditions | None = None
42
+ created_by: UUID | None = Field(default=None, alias="createdBy")
43
+ created_at: datetime | None = Field(default=None, alias="createdAt")
44
+
45
+ @model_validator(mode="after")
46
+ def _check_grantee_keys_match_type(self) -> Self:
47
+ if self.grantee_type == PermissionGrantGranteeType.USER:
48
+ if self.grantee_user_keycloak_user_id is None:
49
+ raise ValueError("grantee_user_keycloak_user_id is required when grantee_type is 'user'")
50
+ if self.grantee_keycloak_organization_id is not None:
51
+ raise ValueError("grantee_keycloak_organization_id must not be set when grantee_type is 'user'")
52
+ elif self.grantee_type == PermissionGrantGranteeType.USER_GROUP:
53
+ if self.grantee_keycloak_organization_id is None:
54
+ raise ValueError("grantee_keycloak_organization_id is required when grantee_type is 'userGroup'")
55
+ if self.grantee_user_keycloak_user_id is not None:
56
+ raise ValueError("grantee_user_keycloak_user_id must not be set when grantee_type is 'userGroup'")
57
+ elif self.grantee_type == PermissionGrantGranteeType.AUTHENTICATED_USERS:
58
+ if self.grantee_user_keycloak_user_id is not None:
59
+ raise ValueError(
60
+ "grantee_user_keycloak_user_id must not be set when grantee_type is 'authenticatedUsers'"
61
+ )
62
+ if self.grantee_keycloak_organization_id is not None:
63
+ raise ValueError(
64
+ "grantee_keycloak_organization_id must not be set when grantee_type is 'authenticatedUsers'"
65
+ )
66
+ else:
67
+ raise ValueError(f"Unknown grantee_type: {self.grantee_type!r}")
68
+ return self
69
+
70
+
71
+ class ChangemakerPermissionGrant(_PermissionGrantBase):
72
+ context_entity_type: Literal[PermissionGrantEntityType.CHANGEMAKER] = Field(
73
+ default=PermissionGrantEntityType.CHANGEMAKER, alias="contextEntityType"
74
+ )
75
+ changemaker_id: int = Field(alias="changemakerId")
76
+
77
+
78
+ class FunderPermissionGrant(_PermissionGrantBase):
79
+ context_entity_type: Literal[PermissionGrantEntityType.FUNDER] = Field(
80
+ default=PermissionGrantEntityType.FUNDER, alias="contextEntityType"
81
+ )
82
+ funder_short_code: str = Field(alias="funderShortCode")
83
+
84
+
85
+ class DataProviderPermissionGrant(_PermissionGrantBase):
86
+ context_entity_type: Literal[PermissionGrantEntityType.DATA_PROVIDER] = Field(
87
+ default=PermissionGrantEntityType.DATA_PROVIDER, alias="contextEntityType"
88
+ )
89
+ data_provider_short_code: str = Field(alias="dataProviderShortCode")
90
+
91
+
92
+ class OpportunityPermissionGrant(_PermissionGrantBase):
93
+ context_entity_type: Literal[PermissionGrantEntityType.OPPORTUNITY] = Field(
94
+ default=PermissionGrantEntityType.OPPORTUNITY, alias="contextEntityType"
95
+ )
96
+ opportunity_id: int = Field(alias="opportunityId")
97
+
98
+
99
+ class ProposalPermissionGrant(_PermissionGrantBase):
100
+ context_entity_type: Literal[PermissionGrantEntityType.PROPOSAL] = Field(
101
+ default=PermissionGrantEntityType.PROPOSAL, alias="contextEntityType"
102
+ )
103
+ proposal_id: int = Field(alias="proposalId")
104
+
105
+
106
+ class ProposalVersionPermissionGrant(_PermissionGrantBase):
107
+ context_entity_type: Literal[PermissionGrantEntityType.PROPOSAL_VERSION] = Field(
108
+ default=PermissionGrantEntityType.PROPOSAL_VERSION, alias="contextEntityType"
109
+ )
110
+ proposal_version_id: int = Field(alias="proposalVersionId")
111
+
112
+
113
+ class ApplicationFormPermissionGrant(_PermissionGrantBase):
114
+ context_entity_type: Literal[PermissionGrantEntityType.APPLICATION_FORM] = Field(
115
+ default=PermissionGrantEntityType.APPLICATION_FORM, alias="contextEntityType"
116
+ )
117
+ application_form_id: int = Field(alias="applicationFormId")
118
+
119
+
120
+ class ApplicationFormFieldPermissionGrant(_PermissionGrantBase):
121
+ context_entity_type: Literal[PermissionGrantEntityType.APPLICATION_FORM_FIELD] = Field(
122
+ default=PermissionGrantEntityType.APPLICATION_FORM_FIELD, alias="contextEntityType"
123
+ )
124
+ application_form_field_id: int = Field(alias="applicationFormFieldId")
125
+
126
+
127
+ class ProposalFieldValuePermissionGrant(_PermissionGrantBase):
128
+ context_entity_type: Literal[PermissionGrantEntityType.PROPOSAL_FIELD_VALUE] = Field(
129
+ default=PermissionGrantEntityType.PROPOSAL_FIELD_VALUE, alias="contextEntityType"
130
+ )
131
+ proposal_field_value_id: int = Field(alias="proposalFieldValueId")
132
+
133
+
134
+ class SourcePermissionGrant(_PermissionGrantBase):
135
+ context_entity_type: Literal[PermissionGrantEntityType.SOURCE] = Field(
136
+ default=PermissionGrantEntityType.SOURCE, alias="contextEntityType"
137
+ )
138
+ source_id: int = Field(alias="sourceId")
139
+
140
+
141
+ class BulkUploadPermissionGrant(_PermissionGrantBase):
142
+ context_entity_type: Literal[PermissionGrantEntityType.BULK_UPLOAD] = Field(
143
+ default=PermissionGrantEntityType.BULK_UPLOAD, alias="contextEntityType"
144
+ )
145
+ bulk_upload_task_id: int = Field(alias="bulkUploadTaskId")
146
+
147
+
148
+ class ChangemakerFieldValuePermissionGrant(_PermissionGrantBase):
149
+ context_entity_type: Literal[PermissionGrantEntityType.CHANGEMAKER_FIELD_VALUE] = Field(
150
+ default=PermissionGrantEntityType.CHANGEMAKER_FIELD_VALUE, alias="contextEntityType"
151
+ )
152
+ changemaker_field_value_id: int = Field(alias="changemakerFieldValueId")
153
+
154
+
155
+ class TerminologySetPermissionGrant(_PermissionGrantBase):
156
+ context_entity_type: Literal[PermissionGrantEntityType.TERMINOLOGY_SET] = Field(
157
+ default=PermissionGrantEntityType.TERMINOLOGY_SET, alias="contextEntityType"
158
+ )
159
+ terminology_set_id: int = Field(alias="terminologySetId")
160
+
161
+
162
+ class InitiativePermissionGrant(_PermissionGrantBase):
163
+ context_entity_type: Literal[PermissionGrantEntityType.INITIATIVE] = Field(
164
+ default=PermissionGrantEntityType.INITIATIVE, alias="contextEntityType"
165
+ )
166
+ initiative_id: int = Field(alias="initiativeId")
167
+
168
+
169
+ class InitiativeFieldValuePermissionGrant(_PermissionGrantBase):
170
+ context_entity_type: Literal[PermissionGrantEntityType.INITIATIVE_FIELD_VALUE] = Field(
171
+ default=PermissionGrantEntityType.INITIATIVE_FIELD_VALUE, alias="contextEntityType"
172
+ )
173
+ initiative_field_value_id: int = Field(alias="initiativeFieldValueId")
174
+
175
+
176
+ PermissionGrant = Annotated[
177
+ ChangemakerPermissionGrant
178
+ | FunderPermissionGrant
179
+ | DataProviderPermissionGrant
180
+ | OpportunityPermissionGrant
181
+ | ProposalPermissionGrant
182
+ | ProposalVersionPermissionGrant
183
+ | ApplicationFormPermissionGrant
184
+ | ApplicationFormFieldPermissionGrant
185
+ | ProposalFieldValuePermissionGrant
186
+ | SourcePermissionGrant
187
+ | BulkUploadPermissionGrant
188
+ | ChangemakerFieldValuePermissionGrant
189
+ | TerminologySetPermissionGrant
190
+ | InitiativePermissionGrant
191
+ | InitiativeFieldValuePermissionGrant,
192
+ Field(discriminator="context_entity_type"),
193
+ ]
194
+
195
+ _PERMISSION_GRANT_ADAPTER: TypeAdapter[PermissionGrant] = TypeAdapter(PermissionGrant)
196
+
197
+
198
+ class PermissionGrantBundle(BaseSchema):
199
+ pdc_endpoint: ClassVar[str] = _ENDPOINT
200
+ default_page_size: ClassVar[int] = _DEFAULT_PAGE_SIZE
201
+ entries: list[PermissionGrant]
202
+ total: int
203
+
204
+
205
+ class DefaultPermissionGrant(_PermissionGrantBase):
206
+ context_entity_type: PermissionGrantEntityType = Field(alias="contextEntityType")
207
+
208
+ @field_validator("context_entity_type")
209
+ @classmethod
210
+ def _reject_any_context(cls, value: PermissionGrantEntityType) -> PermissionGrantEntityType:
211
+ # PDC accepts "any" in scope but not as a default's context.
212
+ if value == PermissionGrantEntityType.ANY:
213
+ raise ValueError("context_entity_type cannot be 'any'")
214
+ return value
215
+
216
+
217
+ class DefaultPermissionGrantBundle(BaseSchema):
218
+ pdc_endpoint: ClassVar[str] = _DEFAULT_ENDPOINT
219
+ default_page_size: ClassVar[int] = _DEFAULT_PAGE_SIZE
220
+ entries: list[DefaultPermissionGrant]
221
+ total: int
222
+
223
+
224
+ def _validate_grant(payload: dict[str, Any]) -> PermissionGrant:
225
+ return _PERMISSION_GRANT_ADAPTER.validate_python(payload)
226
+
227
+
228
+ def _grant_to_payload(grant: PermissionGrant | DefaultPermissionGrant) -> dict[str, Any]:
229
+ # PDC rejects server-managed fields and the unset grantee key in write bodies.
230
+ return grant.model_dump(mode="json", by_alias=True, exclude={"id", "created_by", "created_at"}, exclude_none=True)
231
+
232
+
233
+ def list_permission_grants(
234
+ session: APISession,
235
+ *,
236
+ page: int = 1,
237
+ count_per_page: int | None = None,
238
+ changemaker_id: int | None = None,
239
+ funder_short_code: str | None = None,
240
+ proposal_id: int | None = None,
241
+ grantee_type: PermissionGrantGranteeType | None = None,
242
+ verb: PermissionGrantVerb | None = None,
243
+ ) -> PermissionGrantBundle:
244
+ extra_params: dict[str, Any] = {}
245
+ if changemaker_id is not None:
246
+ extra_params["changemaker"] = changemaker_id
247
+ if funder_short_code is not None:
248
+ extra_params["funder"] = funder_short_code
249
+ if proposal_id is not None:
250
+ extra_params["proposal"] = proposal_id
251
+ if grantee_type is not None:
252
+ extra_params["granteeType"] = grantee_type.value
253
+ if verb is not None:
254
+ extra_params["verb"] = verb.value
255
+ return get_bundle_page(
256
+ session,
257
+ PermissionGrantBundle,
258
+ page=page,
259
+ count_per_page=count_per_page,
260
+ extra_params=extra_params or None,
261
+ )
262
+
263
+
264
+ def get_permission_grant(session: APISession, *, grant_id: int) -> PermissionGrant:
265
+ response = session.get(f"{_ENDPOINT}/{grant_id}")
266
+ return _validate_grant(response.json())
267
+
268
+
269
+ def create_permission_grant(session: APISession, *, grant: PermissionGrant) -> PermissionGrant:
270
+ response = session.post(_ENDPOINT, json=_grant_to_payload(grant))
271
+ return _validate_grant(response.json())
272
+
273
+
274
+ def update_permission_grant(session: APISession, *, grant_id: int, grant: PermissionGrant) -> PermissionGrant:
275
+ response = session.put(f"{_ENDPOINT}/{grant_id}", json=_grant_to_payload(grant))
276
+ return _validate_grant(response.json())
277
+
278
+
279
+ def delete_permission_grant(session: APISession, *, grant_id: int) -> None:
280
+ session.delete(f"{_ENDPOINT}/{grant_id}")
281
+
282
+
283
+ def list_default_permission_grants(
284
+ session: APISession, *, page: int = 1, count_per_page: int | None = None
285
+ ) -> DefaultPermissionGrantBundle:
286
+ return get_bundle_page(session, DefaultPermissionGrantBundle, page=page, count_per_page=count_per_page)
287
+
288
+
289
+ def get_default_permission_grant(session: APISession, *, grant_id: int) -> DefaultPermissionGrant:
290
+ response = session.get(f"{_DEFAULT_ENDPOINT}/{grant_id}")
291
+ return DefaultPermissionGrant.model_validate(response.json())
292
+
293
+
294
+ def create_default_permission_grant(session: APISession, *, grant: DefaultPermissionGrant) -> DefaultPermissionGrant:
295
+ response = session.post(_DEFAULT_ENDPOINT, json=_grant_to_payload(grant))
296
+ return DefaultPermissionGrant.model_validate(response.json())
297
+
298
+
299
+ def update_default_permission_grant(
300
+ session: APISession, *, grant_id: int, grant: DefaultPermissionGrant
301
+ ) -> DefaultPermissionGrant:
302
+ response = session.put(f"{_DEFAULT_ENDPOINT}/{grant_id}", json=_grant_to_payload(grant))
303
+ return DefaultPermissionGrant.model_validate(response.json())
304
+
305
+
306
+ def delete_default_permission_grant(session: APISession, *, grant_id: int) -> None:
307
+ session.delete(f"{_DEFAULT_ENDPOINT}/{grant_id}")
pdc_api/py.typed ADDED
File without changes
File without changes
@@ -0,0 +1,179 @@
1
+ from dataclasses import dataclass
2
+ from typing import Any
3
+
4
+ from keycloak import KeycloakAdmin as _KeycloakAdminClient
5
+ from keycloak.exceptions import KeycloakGetError
6
+
7
+
8
+ @dataclass
9
+ class KeycloakOrganization:
10
+ id: str
11
+ alias: str
12
+ name: str
13
+
14
+
15
+ @dataclass
16
+ class KeycloakUser:
17
+ id: str
18
+ username: str
19
+ email: str
20
+
21
+
22
+ class KeycloakAdmin:
23
+ def __init__(
24
+ self,
25
+ *,
26
+ keycloak_url: str,
27
+ realm: str,
28
+ admin_username: str,
29
+ admin_password: str,
30
+ ) -> None:
31
+ # The bootstrap admin lives in the master realm and can administer any realm.
32
+ self._admin = _KeycloakAdminClient(
33
+ server_url=keycloak_url.rstrip("/") + "/",
34
+ username=admin_username,
35
+ password=admin_password,
36
+ realm_name=realm,
37
+ user_realm_name="master",
38
+ client_id="admin-cli",
39
+ )
40
+ self.realm = realm
41
+
42
+ def ensure_organization(self, *, name: str, alias: str, domain: str) -> KeycloakOrganization:
43
+ existing = self.get_organization(alias=alias)
44
+ if existing is not None:
45
+ return existing
46
+ org_id = self._admin.create_organization(
47
+ {"name": name, "alias": alias, "domains": [{"name": domain, "verified": False}]}
48
+ )
49
+ if org_id is None:
50
+ raise LookupError(f"Keycloak did not return an id for new organization {alias!r}")
51
+ return KeycloakOrganization(id=org_id, alias=alias, name=name)
52
+
53
+ def get_organization(self, *, alias: str) -> KeycloakOrganization | None:
54
+ existing = self._find_org_by_alias(alias)
55
+ if existing is None:
56
+ return None
57
+ return KeycloakOrganization(id=existing["id"], alias=existing["alias"], name=existing["name"])
58
+
59
+ def _find_org_by_alias(self, alias: str) -> dict[str, Any] | None:
60
+ # Keycloak's org search matches names, not aliases, so filter the full listing.
61
+ organizations: list[dict[str, Any]] = self._admin.get_organizations()
62
+ for org in organizations:
63
+ if org.get("alias") == alias:
64
+ return org
65
+ return None
66
+
67
+ def ensure_user(
68
+ self,
69
+ *,
70
+ username: str,
71
+ email: str,
72
+ password: str,
73
+ first_name: str = "Test",
74
+ last_name: str = "User",
75
+ ) -> KeycloakUser:
76
+ # The realm uses email as username, so a user created elsewhere may only match by email.
77
+ existing = self._find_user_by_username(username) or self._find_user_by_email(email)
78
+ if existing is not None:
79
+ # python-keycloak defaults to temporary=True, which forces a password change at next login.
80
+ self._admin.set_user_password(existing["id"], password, temporary=False)
81
+ return KeycloakUser(
82
+ id=existing["id"],
83
+ username=existing["username"],
84
+ email=existing.get("email") or email,
85
+ )
86
+ user_id = self._admin.create_user(
87
+ {
88
+ "username": username,
89
+ "email": email,
90
+ "emailVerified": True,
91
+ "enabled": True,
92
+ "firstName": first_name,
93
+ "lastName": last_name,
94
+ "credentials": [{"type": "password", "value": password, "temporary": False}],
95
+ }
96
+ )
97
+ return KeycloakUser(id=user_id, username=username, email=email)
98
+
99
+ def _find_user_by_username(self, username: str) -> dict[str, Any] | None:
100
+ users: list[dict[str, Any]] = self._admin.get_users({"username": username, "exact": True})
101
+ for user in users:
102
+ if user.get("username") == username:
103
+ return user
104
+ return None
105
+
106
+ def _find_user_by_email(self, email: str) -> dict[str, Any] | None:
107
+ users: list[dict[str, Any]] = self._admin.get_users({"email": email, "exact": True})
108
+ for user in users:
109
+ if (user.get("email") or "").lower() == email.lower():
110
+ return user
111
+ return None
112
+
113
+ def ensure_user_in_organization(self, *, organization_id: str, user_id: str) -> bool:
114
+ for member in self._admin.get_organization_members(organization_id):
115
+ if member.get("id") == user_id:
116
+ return False
117
+ self._admin.organization_user_add(user_id, organization_id)
118
+ return True
119
+
120
+ def remove_user_from_organization(self, *, organization_id: str, user_id: str) -> bool:
121
+ for member in self._admin.get_organization_members(organization_id):
122
+ if member.get("id") == user_id:
123
+ self._admin.organization_user_remove(user_id, organization_id)
124
+ return True
125
+ return False
126
+
127
+ def assign_realm_role(self, *, user_id: str, role_name: str) -> bool:
128
+ for mapping in self._admin.get_realm_roles_of_user(user_id):
129
+ if mapping.get("name") == role_name:
130
+ return False
131
+ try:
132
+ role = self._admin.get_realm_role(role_name)
133
+ except KeycloakGetError as exc:
134
+ if exc.response_code == 404:
135
+ raise LookupError(f"Keycloak realm role {role_name!r} not found in realm {self.realm!r}") from exc
136
+ raise
137
+ self._admin.assign_realm_roles(user_id, [{"id": role["id"], "name": role["name"]}])
138
+ return True
139
+
140
+ def ensure_oidc_login_enabled(self, *, client_id: str, redirect_uris: list[str]) -> None:
141
+ target = self._find_client(client_id)
142
+ body: dict[str, Any] = {}
143
+ if not target.get("standardFlowEnabled"):
144
+ body["standardFlowEnabled"] = True
145
+ existing_uris = list(target.get("redirectUris") or [])
146
+ merged = [*existing_uris, *(uri for uri in redirect_uris if uri not in existing_uris)]
147
+ if merged != existing_uris:
148
+ body["redirectUris"] = merged
149
+ if not body:
150
+ return
151
+ self._admin.update_client(target["id"], body)
152
+
153
+ def ensure_client_secret(self, *, client_id: str, secret: str) -> bool:
154
+ target = self._find_client(client_id)
155
+ current = self._admin.get_client_secrets(target["id"]).get("value")
156
+ if current == secret:
157
+ return False
158
+ self._admin.update_client(target["id"], {"secret": secret})
159
+ return True
160
+
161
+ def ensure_direct_grants_enabled(self, *, client_id: str) -> None:
162
+ target = self._find_client(client_id)
163
+ if target.get("directAccessGrantsEnabled"):
164
+ return
165
+ self.set_direct_grants_enabled(client_id=client_id, enabled=True)
166
+
167
+ def is_direct_grants_enabled(self, *, client_id: str) -> bool:
168
+ return bool(self._find_client(client_id).get("directAccessGrantsEnabled"))
169
+
170
+ def set_direct_grants_enabled(self, *, client_id: str, enabled: bool) -> None:
171
+ target = self._find_client(client_id)
172
+ self._admin.update_client(target["id"], {"directAccessGrantsEnabled": enabled})
173
+
174
+ def _find_client(self, client_id: str) -> dict[str, Any]:
175
+ clients: list[dict[str, Any]] = self._admin.get_clients()
176
+ for client in clients:
177
+ if client.get("clientId") == client_id:
178
+ return client
179
+ raise LookupError(f"Keycloak client {client_id!r} not found in realm {self.realm!r}")