From 2e10a1bd564bde7987f0246f1ae4247358541845 Mon Sep 17 00:00:00 2001 From: Chris Kucharczyk <23062974+chrisjkuch@users.noreply.github.com> Date: Tue, 24 Nov 2026 07:58:20 +0000 Subject: [PATCH 01/11] Add organization members and get_organizations Regenerate from PDC 0.43.0, which adds the Keycloak identity, disabledAt, members, and formerMembers to Organization and a GET /organizations bundle. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 8 + integration_tests/test_operations.py | 5 + src/pdc_api/_generated.py | 96 +++++- src/pdc_api/client.py | 6 + src/pdc_api/openapi.json | 427 ++++++++++++++++++++++++++- src/pdc_api/testing.py | 32 +- tests/test_client.py | 15 + tests/test_client_operations.py | 29 +- 8 files changed, 599 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0662251..32a855a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ This project follows [Semantic Versioning](https://semver.org). Until 1.0, a min PDC does not bump its spec version for every API change, so each entry names the spec version and the date the spec was downloaded. +## Unreleased + +Spec: PDC 0.43.0, downloaded 2026-11-24. + +- `Organization` has `keycloak_organization_id`, `keycloak_organization_name`, `disabled_at`, `members`, and `former_members`. `members` and `former_members` are `None` when the caller may not see membership, or when PDC has not yet synced the organization from Keycloak. +- `get_organizations` walks `GET /organizations`. +- `pdc_api.testing` adds `user_payload`, and `organization_payload` takes the new fields. + ## 0.4.1 (2026-11-20) - `pdc-api` is published on [PyPI](https://pypi.org/project/pdc-api/). Install it with `pip install pdc-api`. diff --git a/integration_tests/test_operations.py b/integration_tests/test_operations.py index 5c53252..443901a 100644 --- a/integration_tests/test_operations.py +++ b/integration_tests/test_operations.py @@ -28,6 +28,7 @@ get_initiative_field_values, get_initiatives, get_organization_by_keycloak_id, + get_organizations, get_proposal, get_proposals, link_changemaker_to_proposal, @@ -50,6 +51,7 @@ NewProposalFieldValue, NewProposalVersion, OpportunityBundle, + Organization, Proposal, ProposalBundle, ) @@ -531,6 +533,9 @@ def test_get_organization_by_keycloak_id_404(self, api_session): with pytest.raises(PDCNotFoundError): get_organization_by_keycloak_id(api_session, keycloak_id=str(uuid.uuid4())) + def test_get_organizations_parses_every_entry(self, api_session): + assert all(isinstance(o, Organization) for o in get_organizations(api_session)) + class TestApplicationForm: def test_get_application_form_returns_seeded_form(self, api_session): diff --git a/src/pdc_api/_generated.py b/src/pdc_api/_generated.py index 2488f04..355302f 100644 --- a/src/pdc_api/_generated.py +++ b/src/pdc_api/_generated.py @@ -132,6 +132,45 @@ class InitiativePatch(BaseSchema): title: Annotated[str | None, Field(examples=["Clean Water for the Upper Valley"], min_length=1)] = None +class Memberships(BaseSchema): + added: Annotated[int, Field(description="The number of memberships created in the local cache by the sync run.")] + disabled: Annotated[ + int, + Field( + description="The number of local membership rows marked disabled by the sync run because Keycloak no longer reports them." + ), + ] + seen: Annotated[int, Field(description="The number of memberships found in Keycloak during the sync run.")] + updated: Annotated[ + int, Field(description="The number of existing memberships confirmed against Keycloak by the sync run.") + ] + + +class Organizations(BaseSchema): + added: Annotated[int, Field(description="The number of organizations created in the local cache by the sync run.")] + disabled: Annotated[ + int, + Field( + description="The number of local organization rows marked disabled by the sync run because Keycloak reports them as absent or not enabled." + ), + ] + seen: Annotated[int, Field(description="The number of organizations found in Keycloak during the sync run.")] + updated: Annotated[ + int, Field(description="The number of existing organizations confirmed against Keycloak by the sync run.") + ] + + +class Details(BaseSchema): + error: Annotated[ + str | None, + Field( + description="The message of the error that caused the sync run to fail; present only when the task status is `failed`." + ), + ] = None + memberships: Memberships | None = None + organizations: Organizations | None = None + + class PdcError(BaseSchema): details: list[Any] | None = [] message: str | None = None @@ -167,6 +206,7 @@ class PermissionGrantGranteeType(StrEnum): USER = "user" USER_GROUP = "userGroup" AUTHENTICATED_USERS = "authenticatedUsers" + ALL_FUNDERS = "allFunders" class PermissionGrantVerb(StrEnum): @@ -265,7 +305,7 @@ class Users(BaseSchema): ] -class Details(BaseSchema): +class Details1(BaseSchema): users: Users @@ -488,6 +528,22 @@ class InitiativeFieldValuePatch(BaseSchema): value: Annotated[str | None, Field(examples=["A program that brings clean water to the upper valley."])] = None +class OrganizationSyncTask(BaseSchema): + created_at: Annotated[AwareDatetime, Field(alias="createdAt")] + created_by: Annotated[ + UUID, Field(alias="createdBy", description="The keycloak user id of the PDC user that requested this sync.") + ] + details: Annotated[ + Details | None, + Field( + description="The summary of a completed sync run (counts for organizations and memberships), or an `error` message describing why the run failed; null until the task finishes." + ), + ] + id: Annotated[int, Field(examples=[3407])] + status: Status + status_updated_at: Annotated[AwareDatetime, Field(alias="statusUpdatedAt")] + + class PartialChangemaker(BaseSchema): keycloak_organization_id: Annotated[ UUID | None, @@ -612,7 +668,7 @@ class UserSyncTask(BaseSchema): UUID, Field(alias="createdBy", description="The keycloak user id of the PDC user that requested this sync.") ] details: Annotated[ - Details | None, Field(description="The summary of the completed sync run; null until the task completes.") + Details1 | None, Field(description="The summary of the completed sync run; null until the task completes.") ] id: Annotated[int, Field(examples=[3407])] status: Status @@ -727,7 +783,43 @@ class OpportunityBundle(Bundle): class Organization(BaseSchema): changemaker: ShallowChangemaker | None = None data_provider: Annotated[DataProvider | None, Field(alias="dataProvider")] = None + disabled_at: Annotated[ + AwareDatetime | None, + Field( + alias="disabledAt", + description="The time this organization was observed as absent from or not enabled in Keycloak by a sync; null if the organization is still live in Keycloak.", + ), + ] = None + former_members: Annotated[ + list[User] | None, + Field( + alias="formerMembers", + description="The organization's former members, the cached users whose cached membership Keycloak no longer reports; null when the caller may not see membership data.", + validate_default=True, + ), + ] = [] funder: Funder | None = None + keycloak_organization_id: Annotated[ + UUID, Field(alias="keycloakOrganizationId", description="The Keycloak-assigned UUID of the organization.") + ] + keycloak_organization_name: Annotated[ + str | None, + Field( + alias="keycloakOrganizationName", + description="The organization name as reported by Keycloak; null until the first successful organization sync.", + ), + ] = None + members: Annotated[ + list[User] | None, + Field( + description="The organization's current cached members as cached users; null when the caller may not see membership data.", + validate_default=True, + ), + ] = [] + + +class OrganizationBundle(Bundle): + entries: Annotated[list[Organization], Field(description="The collection of requested resources.")] class ProposalFieldValue(FieldValueBase): diff --git a/src/pdc_api/client.py b/src/pdc_api/client.py index 58b96ad..2f5a77a 100644 --- a/src/pdc_api/client.py +++ b/src/pdc_api/client.py @@ -76,6 +76,12 @@ def get_funders(session: APISession) -> Generator[Funder, None, None]: yield Funder.model_validate(entry) +def get_organizations(session: APISession) -> Generator[Organization, None, None]: + for payload in _iterate_pages(session, endpoint="organizations"): + for entry in payload["entries"]: + yield Organization.model_validate(entry) + + def get_data_providers(session: APISession) -> Generator[DataProvider, None, None]: for payload in _iterate_pages(session, endpoint="dataProviders"): for entry in payload["entries"]: diff --git a/src/pdc_api/openapi.json b/src/pdc_api/openapi.json index 6123316..c9e54ee 100644 --- a/src/pdc_api/openapi.json +++ b/src/pdc_api/openapi.json @@ -3,7 +3,7 @@ "info": { "title": "Philanthropy Data Commons API", "description": "An API for a common data platform to make the process of submitting data requests to funders less burdensome for changemakers seeking grants.", - "version": "0.42.0", + "version": "0.43.0", "license": { "name": "GNU Affero General Public License v3.0 only", "url": "https://spdx.org/licenses/AGPL-3.0-only.html" @@ -1148,6 +1148,24 @@ }, { "$ref": "#/components/parameters/verbParam" + }, + { + "$ref": "#/components/parameters/contextEntityTypeParam" + }, + { + "$ref": "#/components/parameters/scopeParam" + }, + { + "$ref": "#/components/parameters/createdByParam" + }, + { + "$ref": "#/components/parameters/granteeUserParam" + }, + { + "$ref": "#/components/parameters/granteeOrganizationParam" + }, + { + "$ref": "#/components/parameters/permissionGrantSortParam" } ], "responses": { @@ -2442,9 +2460,6 @@ "401": { "$ref": "#/components/responses/Unauthorized" }, - "403": { - "$ref": "#/components/responses/Forbidden" - }, "404": { "$ref": "#/components/responses/NotFound" }, @@ -2500,9 +2515,6 @@ "401": { "$ref": "#/components/responses/Unauthorized" }, - "403": { - "$ref": "#/components/responses/Forbidden" - }, "404": { "$ref": "#/components/responses/NotFound" }, @@ -2690,9 +2702,6 @@ "401": { "$ref": "#/components/responses/Unauthorized" }, - "403": { - "$ref": "#/components/responses/Forbidden" - }, "404": { "$ref": "#/components/responses/NotFound" }, @@ -3702,6 +3711,133 @@ } } }, + "/organizations": { + "get": { + "operationId": "getOrganizations", + "summary": "Gets a list of organizations as cached from Keycloak.", + "description": "Returns the cached Keycloak organizations, each including its role bundle (changemaker, data provider, and/or funder) and its current cached members. The caller's JWT must carry the PDC-service `pdc-admin` realm role or at least one of the Keycloak `realm-management` organization-visibility roles (`view-organizations`, `manage-organizations`, or `manage-realm`).", + "tags": [ + "Organizations" + ], + "security": [ + { + "auth": [] + } + ], + "parameters": [ + { + "$ref": "#/components/parameters/pageParam" + }, + { + "$ref": "#/components/parameters/countParam" + } + ], + "responses": { + "200": { + "description": "A list of organizations.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OrganizationBundle" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "500": { + "$ref": "#/components/responses/InternalServerError" + } + } + } + }, + "/organizations/sync": { + "post": { + "operationId": "syncOrganizationsFromKeycloak", + "summary": "Kicks off an asynchronous task that replicates all Keycloak organizations and their memberships into the PDC organizations cache.", + "description": "Creates an `organizationSyncTask` and enqueues a background job that lists the realm's organizations and their members at the Keycloak Admin REST API using the caller's own credentials, then merges them into the local `organizations` and `user_organization_memberships` cache. The caller's JWT must carry at least one of the `view-organizations`, `manage-organizations`, or `manage-realm` realm-management roles, and at least one of the `view-users` or `manage-users` realm-management roles, mirroring the sets Keycloak accepts on the equivalent organizations and members listing calls. The sync sets `disabledAt` for organizations that Keycloak reports as deleted or not enabled and for memberships Keycloak no longer reports, rather than deleting rows. Poll `GET /organizations/sync/{organizationSyncTaskId}` for completion.", + "tags": [ + "Organizations" + ], + "security": [ + { + "auth": [] + } + ], + "responses": { + "201": { + "description": "The created organization sync task, initially pending.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OrganizationSyncTask" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "500": { + "$ref": "#/components/responses/InternalServerError" + } + } + } + }, + "/organizations/sync/{organizationSyncTaskId}": { + "get": { + "operationId": "getOrganizationSyncTask", + "summary": "Gets the status of an organization sync task.", + "description": "Returns the requested organization sync task, including its `details` summary once completed. The requester can see their own tasks; administrators can see all tasks.", + "tags": [ + "Organizations" + ], + "security": [ + { + "auth": [] + } + ], + "parameters": [ + { + "name": "organizationSyncTaskId", + "in": "path", + "required": true, + "schema": { + "$ref": "#/components/schemas/id" + }, + "description": "The ID of the organization sync task to retrieve." + } + ], + "responses": { + "200": { + "description": "The requested organization sync task.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/OrganizationSyncTask" + } + } + } + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "404": { + "$ref": "#/components/responses/NotFound" + }, + "500": { + "$ref": "#/components/responses/InternalServerError" + } + } + } + }, "/organizations/{keycloakOrganizationId}": { "get": { "operationId": "getOrganizationByKeycloakId", @@ -4509,6 +4645,74 @@ "required": false, "description": "Filters permission grants to those that include the given verb." }, + "contextEntityTypeParam": { + "schema": { + "$ref": "#/components/schemas/PermissionGrantEntityType" + }, + "in": "query", + "name": "contextEntityType", + "required": false, + "description": "Applies a filter based on permission grant context entity type." + }, + "scopeParam": { + "schema": { + "$ref": "#/components/schemas/PermissionGrantEntityType" + }, + "in": "query", + "name": "scope", + "required": false, + "description": "Applies a filter based on permission grant scope." + }, + "granteeUserParam": { + "schema": { + "oneOf": [ + { + "type": "string", + "format": "uuid" + }, + { + "enum": [ + "me" + ] + } + ] + }, + "in": "query", + "name": "granteeUser", + "required": false, + "description": "Applies a filter based on permission grant grantee user, or 'me'." + }, + "granteeOrganizationParam": { + "schema": { + "type": "string", + "format": "uuid" + }, + "in": "query", + "name": "granteeOrganization", + "required": false, + "description": "Applies a filter based on permission grant grantee organization." + }, + "permissionGrantSortParam": { + "schema": { + "type": "string", + "enum": [ + "id", + "-id", + "createdAt", + "-createdAt", + "granteeType", + "-granteeType", + "contextEntityType", + "-contextEntityType", + "createdByUserName", + "-createdByUserName" + ] + }, + "in": "query", + "name": "_sort", + "required": false, + "description": "Applies a sort based on the given field. Prefix with `-` for descending order. Defaults to `id` descending, which also breaks ties." + }, "baseFieldSensitivityClassificationParam": { "schema": { "type": "string" @@ -4532,7 +4736,8 @@ "scopes": { "openid": "Use OpenID Connect (recommended).", "roles": "Read your roles (recommended).", - "profile": "Read your profile (recommended)." + "profile": "Read your profile (recommended).", + "kc-admin-api": "Access the Keycloak Admin REST API (required by the sync endpoints)." } } } @@ -6489,8 +6694,31 @@ }, "Organization": { "type": "object", - "description": "Up to three entities related to roles played by an organization, as registered in the PDC: a changemaker role, a data provider role, and/or a funder role.", + "description": "Up to three entities related to roles played by an organization, as registered in the PDC: a changemaker role, a data provider role, and/or a funder role, alongside the organization's cached Keycloak identity.", "properties": { + "keycloakOrganizationId": { + "description": "The Keycloak-assigned UUID of the organization.", + "type": "string", + "format": "uuid", + "readOnly": true + }, + "keycloakOrganizationName": { + "description": "The organization name as reported by Keycloak; null until the first successful organization sync.", + "type": [ + "string", + "null" + ], + "readOnly": true + }, + "disabledAt": { + "description": "The time this organization was observed as absent from or not enabled in Keycloak by a sync; null if the organization is still live in Keycloak.", + "type": [ + "string", + "null" + ], + "format": "date-time", + "readOnly": true + }, "changemaker": { "$ref": "#/components/schemas/ShallowChangemaker", "readOnly": true, @@ -6505,14 +6733,175 @@ "$ref": "#/components/schemas/Funder", "readOnly": true, "nullable": true + }, + "members": { + "description": "The organization's current cached members as cached users; null when the caller may not see membership data.", + "type": [ + "array", + "null" + ], + "items": { + "$ref": "#/components/schemas/User" + }, + "readOnly": true + }, + "formerMembers": { + "description": "The organization's former members, the cached users whose cached membership Keycloak no longer reports; null when the caller may not see membership data.", + "type": [ + "array", + "null" + ], + "items": { + "$ref": "#/components/schemas/User" + }, + "readOnly": true } }, "required": [ + "keycloakOrganizationId", "changemaker", "dataProvider", "funder" ] }, + "OrganizationBundle": { + "allOf": [ + { + "$ref": "#/components/schemas/Bundle" + }, + { + "type": "object", + "properties": { + "entries": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Organization" + } + } + }, + "required": [ + "entries" + ] + } + ] + }, + "OrganizationSyncTask": { + "type": "object", + "properties": { + "id": { + "allOf": [ + { + "$ref": "#/components/schemas/id" + } + ], + "readOnly": true, + "example": 3407 + }, + "status": { + "type": "string", + "readOnly": true, + "enum": [ + "pending", + "in_progress", + "completed", + "failed", + "canceled" + ] + }, + "statusUpdatedAt": { + "type": "string", + "format": "date-time", + "readOnly": true + }, + "details": { + "description": "The summary of a completed sync run (counts for organizations and memberships), or an `error` message describing why the run failed; null until the task finishes.", + "type": [ + "object", + "null" + ], + "readOnly": true, + "properties": { + "error": { + "type": "string", + "description": "The message of the error that caused the sync run to fail; present only when the task status is `failed`." + }, + "organizations": { + "type": "object", + "properties": { + "seen": { + "type": "integer", + "description": "The number of organizations found in Keycloak during the sync run." + }, + "added": { + "type": "integer", + "description": "The number of organizations created in the local cache by the sync run." + }, + "updated": { + "type": "integer", + "description": "The number of existing organizations confirmed against Keycloak by the sync run." + }, + "disabled": { + "type": "integer", + "description": "The number of local organization rows marked disabled by the sync run because Keycloak reports them as absent or not enabled." + } + }, + "required": [ + "seen", + "added", + "updated", + "disabled" + ] + }, + "memberships": { + "type": "object", + "properties": { + "seen": { + "type": "integer", + "description": "The number of memberships found in Keycloak during the sync run." + }, + "added": { + "type": "integer", + "description": "The number of memberships created in the local cache by the sync run." + }, + "updated": { + "type": "integer", + "description": "The number of existing memberships confirmed against Keycloak by the sync run." + }, + "disabled": { + "type": "integer", + "description": "The number of local membership rows marked disabled by the sync run because Keycloak no longer reports them." + } + }, + "required": [ + "seen", + "added", + "updated", + "disabled" + ] + } + } + }, + "createdBy": { + "description": "The keycloak user id of the PDC user that requested this sync.", + "type": "string", + "format": "uuid", + "readOnly": true + }, + "createdAt": { + "type": "string", + "format": "date-time", + "readOnly": true + } + }, + "required": [ + "id", + "status", + "statusUpdatedAt", + "details", + "createdAt", + "createdBy" + ] + }, "Bundle": { "type": "object", "properties": { @@ -7365,7 +7754,8 @@ "enum": [ "user", "userGroup", - "authenticatedUsers" + "authenticatedUsers", + "allFunders" ], "description": "The type of grantee for a permission grant." }, @@ -7831,6 +8221,17 @@ "required": [ "granteeType" ] + }, + { + "properties": { + "granteeType": { + "type": "string", + "const": "allFunders" + } + }, + "required": [ + "granteeType" + ] } ] }, diff --git a/src/pdc_api/testing.py b/src/pdc_api/testing.py index aa6be70..b5c8882 100644 --- a/src/pdc_api/testing.py +++ b/src/pdc_api/testing.py @@ -129,13 +129,39 @@ def changemaker_proposal_payload(*, id: int = 1, changemaker_id: int = 10, propo } +def user_payload( + *, keycloak_user_id: str | UUID, keycloak_user_name: str | None = "Ada Lovelace", disabled_at: str | None = None +) -> dict[str, Any]: + return { + "keycloakUserId": keycloak_user_id, + "keycloakUserName": keycloak_user_name, + "createdAt": CREATED_AT, + "syncedFromKeycloakAt": CREATED_AT, + "disabledAt": disabled_at, + } + + def organization_payload( *, + keycloak_organization_id: str | UUID = "00000000-0000-0000-0000-0000000000a1", + keycloak_organization_name: str | None = "Acme", + disabled_at: str | None = None, changemaker: dict[str, Any] | None = None, funder: dict[str, Any] | None = None, data_provider: dict[str, Any] | None = None, + members: list[dict[str, Any]] | None = None, + former_members: list[dict[str, Any]] | None = None, ) -> dict[str, Any]: - return {"changemaker": changemaker, "funder": funder, "dataProvider": data_provider} + return { + "keycloakOrganizationId": keycloak_organization_id, + "keycloakOrganizationName": keycloak_organization_name, + "disabledAt": disabled_at, + "changemaker": changemaker, + "funder": funder, + "dataProvider": data_provider, + "members": members, + "formerMembers": former_members, + } def application_form_payload(*, id: int = 7, version: int = 1, opportunity_id: int = 5) -> dict[str, Any]: @@ -283,7 +309,9 @@ def add_organization_response( add_json_response( base_url=base_url, path=f"organizations/{keycloak_id}", - payload=payload if payload is not None else organization_payload(**payload_kwargs), + payload=payload + if payload is not None + else organization_payload(keycloak_organization_id=keycloak_id, **payload_kwargs), status=status, ) diff --git a/tests/test_client.py b/tests/test_client.py index b6c94d4..3223d60 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -11,6 +11,7 @@ get_data_providers, get_funders, get_initiatives, + get_organizations, ) from pdc_api.models import ( BaseFieldDataType, @@ -20,6 +21,7 @@ ChangemakerProposal, DataProvider, Funder, + Organization, ) from pdc_api.testing import ( base_field_payload as _basefield, @@ -33,6 +35,7 @@ data_provider_payload, funder_payload, initiative_payload, + organization_payload, ) @@ -79,6 +82,18 @@ def test_yields_validated_models(self, session, add_json_response): assert [f.short_code for f in result] == ["a", "b"] +class TestGetOrganizations: + def test_yields_validated_models(self, session, add_json_response): + keycloak_ids = ["00000000-0000-0000-0000-0000000000a1", "00000000-0000-0000-0000-0000000000a2"] + payload = bundle([organization_payload(keycloak_organization_id=kc_id) for kc_id in keycloak_ids]) + add_json_response(path="/organizations", payload=payload, query_params={"_page": 1, "_count": 50}) + + result = list(get_organizations(session)) + + assert all(isinstance(o, Organization) for o in result) + assert [str(o.keycloak_organization_id) for o in result] == keycloak_ids + + class TestGetDataProviders: def test_yields_validated_models(self, session, add_json_response): payload = bundle( diff --git a/tests/test_client_operations.py b/tests/test_client_operations.py index 0b5357f..14d7fae 100644 --- a/tests/test_client_operations.py +++ b/tests/test_client_operations.py @@ -51,9 +51,12 @@ proposal_payload, proposal_version_payload, source_payload, + user_payload, ) BASE_URL = "https://pdc.test" +ORG_ID = "00000000-0000-0000-0000-0000000000a1" +USER_ID = "00000000-0000-0000-0000-0000000000b1" def _post(path, payload): @@ -123,15 +126,37 @@ def test_raises_proposal_not_found_on_empty_bundle(self, session, add_json_respo class TestGetOrganizationByKeycloakId: def test_parses_organization_with_funder_facet(self, session, add_organization_response): - add_organization_response(keycloak_id="kc-uuid", funder=funder_payload(short_code="acme")) + add_organization_response(keycloak_id=ORG_ID, funder=funder_payload(short_code="acme")) - result = get_organization_by_keycloak_id(session, keycloak_id="kc-uuid") + result = get_organization_by_keycloak_id(session, keycloak_id=ORG_ID) assert isinstance(result, Organization) assert result.funder is not None assert result.funder.short_code == "acme" assert result.changemaker is None + def test_parses_members_and_their_disabled_state(self, session, add_organization_response): + add_organization_response( + keycloak_id=ORG_ID, + members=[user_payload(keycloak_user_id=USER_ID, disabled_at="2026-11-19T20:11:38Z")], + former_members=[], + ) + + result = get_organization_by_keycloak_id(session, keycloak_id=ORG_ID) + + assert result.members is not None + assert [str(member.keycloak_user_id) for member in result.members] == [USER_ID] + assert result.members[0].disabled_at == datetime(2026, 11, 19, 20, 11, 38, tzinfo=UTC) + assert result.former_members == [] + + def test_keeps_members_null_when_hidden_from_the_caller(self, session, add_organization_response): + add_organization_response(keycloak_id=ORG_ID) + + result = get_organization_by_keycloak_id(session, keycloak_id=ORG_ID) + + assert result.members is None + assert result.former_members is None + class TestGetApplicationForm: def test_requests_form_by_id(self, session, add_application_form_response): From 57ebf509f898d57da45fbba4a4b8c5c72d4664c6 Mon Sep 17 00:00:00 2001 From: Chris Kucharczyk <23062974+chrisjkuch@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:13:08 +0000 Subject: [PATCH 02/11] Add Keycloak sync functions and admin API access for seeding PDC fills its user and organization cache only through POST /users/sync and /organizations/sync, which need a token with the kc-admin-api scope. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 ++ integration_tests/conftest.py | 30 +++++++++++++ integration_tests/test_keycloak_admin.py | 12 ++++++ integration_tests/test_operations.py | 23 ++++++++++ src/pdc_api/__init__.py | 2 + src/pdc_api/client.py | 54 +++++++++++++++++++++++- src/pdc_api/errors.py | 4 ++ src/pdc_api/models.py | 8 ++++ src/pdc_api/seeding/keycloak_admin.py | 32 ++++++++++++++ src/pdc_api/token.py | 3 ++ tests/test_client_operations.py | 54 ++++++++++++++++++++++++ tests/test_token.py | 19 +++++++++ 12 files changed, 243 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 32a855a..02543f3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,9 @@ Spec: PDC 0.43.0, downloaded 2026-11-24. - `Organization` has `keycloak_organization_id`, `keycloak_organization_name`, `disabled_at`, `members`, and `former_members`. `members` and `former_members` are `None` when the caller may not see membership, or when PDC has not yet synced the organization from Keycloak. - `get_organizations` walks `GET /organizations`. - `pdc_api.testing` adds `user_payload`, and `organization_payload` takes the new fields. +- `sync_users_from_keycloak` and `sync_organizations_from_keycloak` start PDC's Keycloak sync and wait for it, raising `KeycloakSyncError` if it fails or times out. The token must carry the `kc-admin-api` scope. +- `KeycloakClientCredentialsProvider` takes an optional `scope`. +- Seeding's `KeycloakAdmin.ensure_admin_api_access` lets a client request `kc-admin-api` tokens that can list users and organizations. ## 0.4.1 (2026-11-20) diff --git a/integration_tests/conftest.py b/integration_tests/conftest.py index c5da731..c7a4fcb 100644 --- a/integration_tests/conftest.py +++ b/integration_tests/conftest.py @@ -1,3 +1,5 @@ +import base64 +import json import os import uuid @@ -144,3 +146,31 @@ def add(username: str, *orgs) -> None: keycloak_admin.ensure_user_in_organization(organization_id=org.id, user_id=user.id) return add + + +def _scoped_token_provider(scope: str) -> KeycloakClientCredentialsProvider: + return KeycloakClientCredentialsProvider( + server_url=KEYCLOAK_SERVER_URL, + realm=KEYCLOAK_REALM, + client_id=KEYCLOAK_CLIENT_ID, + client_secret=KEYCLOAK_CLIENT_SECRET, + timeout=PDC_API_TIMEOUT, + scope=scope, + ) + + +@pytest.fixture +def client_token_claims(): + def claims(*, scope: str) -> dict: + payload = _scoped_token_provider(scope).get_token().split(".")[1] + return json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) + + return claims + + +@pytest.fixture(scope="session") +def admin_api_session(keycloak_admin) -> APISession: + keycloak_admin.ensure_admin_api_access(client_id=KEYCLOAK_CLIENT_ID) + return APISession( + base_url=PDC_API_URL, token_provider=_scoped_token_provider("kc-admin-api"), timeout=PDC_API_TIMEOUT + ) diff --git a/integration_tests/test_keycloak_admin.py b/integration_tests/test_keycloak_admin.py index 169c637..79818f2 100644 --- a/integration_tests/test_keycloak_admin.py +++ b/integration_tests/test_keycloak_admin.py @@ -98,3 +98,15 @@ def test_is_idempotent(self, keycloak_admin, keycloak_client_id): keycloak_admin.ensure_direct_grants_enabled(client_id=keycloak_client_id) assert keycloak_admin.is_direct_grants_enabled(client_id=keycloak_client_id) is True + + +class TestEnsureAdminApiAccess: + def test_lets_the_client_request_admin_api_tokens_that_can_list_users_and_organizations( + self, keycloak_admin, keycloak_client_id, client_token_claims + ): + keycloak_admin.ensure_admin_api_access(client_id=keycloak_client_id) + keycloak_admin.ensure_admin_api_access(client_id=keycloak_client_id) + + claims = client_token_claims(scope="kc-admin-api") + assert "kc-admin-api" in claims["scope"].split() + assert {"view-users", "view-organizations"} <= set(claims["resource_access"]["realm-management"]["roles"]) diff --git a/integration_tests/test_operations.py b/integration_tests/test_operations.py index 443901a..a2e3b47 100644 --- a/integration_tests/test_operations.py +++ b/integration_tests/test_operations.py @@ -32,6 +32,8 @@ get_proposal, get_proposals, link_changemaker_to_proposal, + sync_organizations_from_keycloak, + sync_users_from_keycloak, ) from pdc_api.errors import PDCNotFoundError, ProposalNotFoundError from pdc_api.models import ( @@ -533,6 +535,27 @@ def test_get_organization_by_keycloak_id_404(self, api_session): with pytest.raises(PDCNotFoundError): get_organization_by_keycloak_id(api_session, keycloak_id=str(uuid.uuid4())) + def test_sync_from_keycloak_reports_organization_members( + self, + api_session, + admin_api_session, + keycloak_admin, + fresh_keycloak_org, + add_user_to_org, + suffix, + test_user_password, + ): + username = f"sync-member-{suffix}@example.com" + add_user_to_org(username, fresh_keycloak_org) + member = keycloak_admin.ensure_user(username=username, email=username, password=test_user_password) + + sync_users_from_keycloak(admin_api_session) + sync_organizations_from_keycloak(admin_api_session) + + organization = get_organization_by_keycloak_id(api_session, keycloak_id=fresh_keycloak_org.id) + assert organization.members is not None + assert [str(m.keycloak_user_id) for m in organization.members] == [member.id] + def test_get_organizations_parses_every_entry(self, api_session): assert all(isinstance(o, Organization) for o in get_organizations(api_session)) diff --git a/src/pdc_api/__init__.py b/src/pdc_api/__init__.py index 1149545..47bf8e0 100644 --- a/src/pdc_api/__init__.py +++ b/src/pdc_api/__init__.py @@ -3,6 +3,7 @@ ChangemakerFieldValueBatchNotFoundError, ChangemakerNotFoundError, FunderNotFoundError, + KeycloakSyncError, PDCBadRequestError, PDCConflictError, PDCException, @@ -23,6 +24,7 @@ "ChangemakerFieldValueBatchNotFoundError", "ChangemakerNotFoundError", "FunderNotFoundError", + "KeycloakSyncError", "PDCBadRequestError", "PDCConflictError", "PDCException", diff --git a/src/pdc_api/client.py b/src/pdc_api/client.py index 2f5a77a..144e13a 100644 --- a/src/pdc_api/client.py +++ b/src/pdc_api/client.py @@ -1,7 +1,8 @@ import json +import time from collections.abc import Generator from datetime import datetime -from typing import Any, ClassVar, Protocol, Self +from typing import Any, ClassVar, Protocol, Self, TypeVar import requests @@ -20,13 +21,18 @@ InitiativeFieldValue, NewProposalVersion, Organization, + OrganizationSyncTask, PresignedPost, Proposal, ProposalVersion, Source, + SyncTaskStatus, + UserSyncTask, ) from pdc_api.transport import APISession +SyncTask = TypeVar("SyncTask", UserSyncTask, OrganizationSyncTask) + def _iterate_pages( session: APISession, @@ -336,3 +342,49 @@ def upload_file_to_s3_presigned_url( response.raise_for_status() except requests.RequestException as exc: raise errors.PDCServiceError(detail=f"Could not upload file to S3: {exc}") from exc + + +def sync_users_from_keycloak( + session: APISession, *, poll_interval_seconds: float = 0.5, timeout_seconds: float = 120.0 +) -> UserSyncTask: + return _run_sync_task( + session, + endpoint="users/sync", + task_type=UserSyncTask, + poll_interval_seconds=poll_interval_seconds, + timeout_seconds=timeout_seconds, + ) + + +def sync_organizations_from_keycloak( + session: APISession, *, poll_interval_seconds: float = 0.5, timeout_seconds: float = 120.0 +) -> OrganizationSyncTask: + return _run_sync_task( + session, + endpoint="organizations/sync", + task_type=OrganizationSyncTask, + poll_interval_seconds=poll_interval_seconds, + timeout_seconds=timeout_seconds, + ) + + +def _run_sync_task( + session: APISession, + *, + endpoint: str, + task_type: type[SyncTask], + poll_interval_seconds: float, + timeout_seconds: float, +) -> SyncTask: + task = task_type.model_validate(session.post(endpoint).json()) + deadline = time.monotonic() + timeout_seconds + while task.status in (SyncTaskStatus.PENDING, SyncTaskStatus.IN_PROGRESS): + if time.monotonic() >= deadline: + raise errors.KeycloakSyncError( + detail=f"{endpoint} task {task.id} still {task.status} after {timeout_seconds}s" + ) + time.sleep(poll_interval_seconds) + task = task_type.model_validate(session.get(f"{endpoint}/{task.id}").json()) + if task.status != SyncTaskStatus.COMPLETED: + raise errors.KeycloakSyncError(detail=f"{endpoint} task {task.id} {task.status}: {task.details}") + return task diff --git a/src/pdc_api/errors.py b/src/pdc_api/errors.py index 699e72c..c45abc1 100644 --- a/src/pdc_api/errors.py +++ b/src/pdc_api/errors.py @@ -37,6 +37,10 @@ class PDCUnprocessableEntityError(PDCException): pass +class KeycloakSyncError(PDCException): + pass + + class TokenRequestError(PDCException): pass diff --git a/src/pdc_api/models.py b/src/pdc_api/models.py index c3d0b88..7aa1994 100644 --- a/src/pdc_api/models.py +++ b/src/pdc_api/models.py @@ -25,6 +25,7 @@ InitiativeFieldValue, Opportunity, Organization, + OrganizationSyncTask, PermissionGrantEntityType, PermissionGrantGranteeType, PermissionGrantVerb, @@ -36,10 +37,14 @@ SensitivityClassification, ShallowChangemaker, Source, + UserSyncTask, ) from pdc_api._generated import ( ApplicationFormFieldInputType as InputType, ) +from pdc_api._generated import ( + Status as SyncTaskStatus, +) from pdc_api._generated import ( DataType as BaseFieldDataType, ) @@ -73,6 +78,7 @@ "Opportunity", "OpportunityBundle", "Organization", + "OrganizationSyncTask", "PermissionGrantEntityType", "PermissionGrantGranteeType", "PermissionGrantVerb", @@ -85,6 +91,8 @@ "SensitivityClassification", "ShallowChangemaker", "Source", + "SyncTaskStatus", + "UserSyncTask", ] diff --git a/src/pdc_api/seeding/keycloak_admin.py b/src/pdc_api/seeding/keycloak_admin.py index 88ae217..bca9207 100644 --- a/src/pdc_api/seeding/keycloak_admin.py +++ b/src/pdc_api/seeding/keycloak_admin.py @@ -4,6 +4,9 @@ from keycloak import KeycloakAdmin as _KeycloakAdminClient from keycloak.exceptions import KeycloakGetError +ADMIN_API_SCOPE = "kc-admin-api" +ADMIN_API_VIEW_ROLES = ("view-users", "view-organizations") + @dataclass class KeycloakOrganization: @@ -171,6 +174,35 @@ def set_direct_grants_enabled(self, *, client_id: str, enabled: bool) -> None: target = self._find_client(client_id) self._admin.update_client(target["id"], {"directAccessGrantsEnabled": enabled}) + def ensure_admin_api_access(self, *, client_id: str) -> None: + client = self._find_client(client_id) + self._admin.add_client_optional_client_scope(client["id"], self._ensure_admin_api_client_scope(), {}) + service_account = self._admin.get_client_service_account_user(client["id"]) + realm_management_id = self._find_client("realm-management")["id"] + roles = [self._admin.get_client_role(realm_management_id, name) for name in ADMIN_API_VIEW_ROLES] + self._admin.assign_client_role(service_account["id"], realm_management_id, roles) + + # Keycloak 26.8.2 creates this built-in scope for new and migrated realms, but not for imported ones. + def _ensure_admin_api_client_scope(self) -> str: + for scope in self._admin.get_client_scopes(): + if scope["name"] == ADMIN_API_SCOPE: + return str(scope["id"]) + return self._admin.create_client_scope( + { + "name": ADMIN_API_SCOPE, + "protocol": "openid-connect", + "attributes": {"include.in.token.scope": "true", "display.on.consent.screen": "false"}, + "protocolMappers": [ + { + "name": "admin-api-audience", + "protocol": "openid-connect", + "protocolMapper": "oidc-admin-api-audience-mapper", + "config": {"access.token.claim": "true", "introspection.token.claim": "true"}, + } + ], + } + ) + def _find_client(self, client_id: str) -> dict[str, Any]: clients: list[dict[str, Any]] = self._admin.get_clients() for client in clients: diff --git a/src/pdc_api/token.py b/src/pdc_api/token.py index d2aec5d..5d5325d 100644 --- a/src/pdc_api/token.py +++ b/src/pdc_api/token.py @@ -22,12 +22,14 @@ def __init__( client_id: str, client_secret: str, timeout: float, + scope: str | None = None, expiry_leeway_seconds: float = 30.0, ) -> None: self._token_url = f"{server_url.rstrip('/')}/realms/{realm}/protocol/openid-connect/token" self._client_id = client_id self._client_secret = client_secret self._timeout = timeout + self._scope = scope self._leeway = expiry_leeway_seconds self._token: str | None = None self._expires_at: float = 0.0 @@ -48,6 +50,7 @@ def _request_token(self) -> tuple[str, float]: "grant_type": "client_credentials", "client_id": self._client_id, "client_secret": self._client_secret, + **({"scope": self._scope} if self._scope else {}), }, timeout=self._timeout, ) diff --git a/tests/test_client_operations.py b/tests/test_client_operations.py index 14d7fae..df729ce 100644 --- a/tests/test_client_operations.py +++ b/tests/test_client_operations.py @@ -22,11 +22,14 @@ get_organization_by_keycloak_id, get_proposal, link_changemaker_to_proposal, + sync_organizations_from_keycloak, + sync_users_from_keycloak, ) from pdc_api.errors import ( ApplicationFormNotFoundError, ChangemakerNotFoundError, FunderNotFoundError, + KeycloakSyncError, PDCNotFoundError, ProposalNotFoundError, ) @@ -379,3 +382,54 @@ def test_formats_endpoint_with_path_params(self, session, add_page_response): ) assert result.total == 0 + + +def _sync_task(*, id: int = 7, status: str, details: dict | None = None) -> dict: + return { + "id": id, + "status": status, + "details": details, + "createdAt": "2026-11-19T20:11:38Z", + "createdBy": USER_ID, + "statusUpdatedAt": "2026-11-19T20:11:38Z", + } + + +class TestSyncUsersFromKeycloak: + def test_polls_until_the_task_completes(self, session, add_json_response): + _post("users/sync", _sync_task(status="pending")) + add_json_response(path="users/sync/7", payload=_sync_task(status="in_progress")) + add_json_response( + path="users/sync/7", + payload=_sync_task( + status="completed", details={"users": {"seen": 2, "added": 1, "updated": 1, "disabled": 0}} + ), + ) + + task = sync_users_from_keycloak(session, poll_interval_seconds=0) + + assert task.status == "completed" + assert len(responses.calls) == 3 + + def test_raises_when_the_task_fails(self, session, add_json_response): + _post("users/sync", _sync_task(status="pending")) + add_json_response(path="users/sync/7", payload=_sync_task(status="failed")) + + with pytest.raises(KeycloakSyncError, match="failed"): + sync_users_from_keycloak(session, poll_interval_seconds=0) + + def test_raises_when_the_task_outlasts_the_timeout(self, session): + _post("users/sync", _sync_task(status="pending")) + + with pytest.raises(KeycloakSyncError, match="pending"): + sync_users_from_keycloak(session, poll_interval_seconds=0, timeout_seconds=0) + + +class TestSyncOrganizationsFromKeycloak: + def test_polls_the_organization_sync_task(self, session, add_json_response): + _post("organizations/sync", _sync_task(status="pending")) + add_json_response(path="organizations/sync/7", payload=_sync_task(status="completed")) + + task = sync_organizations_from_keycloak(session, poll_interval_seconds=0) + + assert task.status == "completed" diff --git a/tests/test_token.py b/tests/test_token.py index 878576b..51a10ac 100644 --- a/tests/test_token.py +++ b/tests/test_token.py @@ -41,6 +41,25 @@ def _add_token(*, access_token="abc", expires_in=300, status=200): class TestKeycloakClientCredentialsProvider: + def test_requests_the_given_scope(self): + responses.add( + responses.POST, + TOKEN_URL, + json={"access_token": "admin", "expires_in": 300}, + match=[ + responses.matchers.urlencoded_params_matcher( + { + "grant_type": "client_credentials", + "client_id": "svc", + "client_secret": "shh", + "scope": "kc-admin-api", + } + ) + ], + ) + + assert _provider(scope="kc-admin-api").get_token() == "admin" + def test_obtains_and_caches_token(self): _add_token(access_token="abc", expires_in=300) From 6bb848a608017c84f34b0756adabd39fbf78cd16 Mon Sep 17 00:00:00 2001 From: Chris Kucharczyk <23062974+chrisjkuch@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:13:35 +0000 Subject: [PATCH 03/11] Fix lint in sync task polling Co-Authored-By: Claude Opus 5.5 --- src/pdc_api/client.py | 6 ++---- src/pdc_api/models.py | 4 ++-- 2 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/pdc_api/client.py b/src/pdc_api/client.py index 144e13a..9e2bc6c 100644 --- a/src/pdc_api/client.py +++ b/src/pdc_api/client.py @@ -2,7 +2,7 @@ import time from collections.abc import Generator from datetime import datetime -from typing import Any, ClassVar, Protocol, Self, TypeVar +from typing import Any, ClassVar, Protocol, Self import requests @@ -31,8 +31,6 @@ ) from pdc_api.transport import APISession -SyncTask = TypeVar("SyncTask", UserSyncTask, OrganizationSyncTask) - def _iterate_pages( session: APISession, @@ -368,7 +366,7 @@ def sync_organizations_from_keycloak( ) -def _run_sync_task( +def _run_sync_task[SyncTask: (UserSyncTask, OrganizationSyncTask)]( session: APISession, *, endpoint: str, diff --git a/src/pdc_api/models.py b/src/pdc_api/models.py index 7aa1994..54f7859 100644 --- a/src/pdc_api/models.py +++ b/src/pdc_api/models.py @@ -43,10 +43,10 @@ ApplicationFormFieldInputType as InputType, ) from pdc_api._generated import ( - Status as SyncTaskStatus, + DataType as BaseFieldDataType, ) from pdc_api._generated import ( - DataType as BaseFieldDataType, + Status as SyncTaskStatus, ) __all__ = [ From 23b9946ba9be3bbdddcc8bed761802b428205f35 Mon Sep 17 00:00:00 2001 From: Chris Kucharczyk <23062974+chrisjkuch@users.noreply.github.com> Date: Tue, 24 Nov 2026 08:36:50 +0000 Subject: [PATCH 04/11] Drop ensure_admin_api_access in favor of the realm The kc-admin-api scope belongs in the realm (PDC's realm.json and its Keycloak checklist), not in runtime setup. The sync integration test skips until Keycloak offers the scope. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 - integration_tests/conftest.py | 35 +++++++++--------------- integration_tests/test_keycloak_admin.py | 12 -------- src/pdc_api/seeding/keycloak_admin.py | 32 ---------------------- 4 files changed, 13 insertions(+), 67 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 02543f3..4f9b096 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,6 @@ Spec: PDC 0.43.0, downloaded 2026-11-24. - `pdc_api.testing` adds `user_payload`, and `organization_payload` takes the new fields. - `sync_users_from_keycloak` and `sync_organizations_from_keycloak` start PDC's Keycloak sync and wait for it, raising `KeycloakSyncError` if it fails or times out. The token must carry the `kc-admin-api` scope. - `KeycloakClientCredentialsProvider` takes an optional `scope`. -- Seeding's `KeycloakAdmin.ensure_admin_api_access` lets a client request `kc-admin-api` tokens that can list users and organizations. ## 0.4.1 (2026-11-20) diff --git a/integration_tests/conftest.py b/integration_tests/conftest.py index c7a4fcb..88cb23c 100644 --- a/integration_tests/conftest.py +++ b/integration_tests/conftest.py @@ -1,11 +1,10 @@ -import base64 -import json import os import uuid import pytest import requests +from pdc_api.errors import TokenRequestError from pdc_api.models import FunderCollaborativeMemberBundle from pdc_api.seeding.keycloak_admin import KeycloakAdmin from pdc_api.seeding.pdc_entities import ( @@ -148,29 +147,21 @@ def add(username: str, *orgs) -> None: return add -def _scoped_token_provider(scope: str) -> KeycloakClientCredentialsProvider: - return KeycloakClientCredentialsProvider( +# PDC's CI realm offers kc-admin-api only once service's realm.json defines it; until then the sync can't run. +@pytest.fixture(scope="session") +def admin_api_session() -> APISession: + token_provider = KeycloakClientCredentialsProvider( server_url=KEYCLOAK_SERVER_URL, realm=KEYCLOAK_REALM, client_id=KEYCLOAK_CLIENT_ID, client_secret=KEYCLOAK_CLIENT_SECRET, timeout=PDC_API_TIMEOUT, - scope=scope, - ) - - -@pytest.fixture -def client_token_claims(): - def claims(*, scope: str) -> dict: - payload = _scoped_token_provider(scope).get_token().split(".")[1] - return json.loads(base64.urlsafe_b64decode(payload + "=" * (-len(payload) % 4))) - - return claims - - -@pytest.fixture(scope="session") -def admin_api_session(keycloak_admin) -> APISession: - keycloak_admin.ensure_admin_api_access(client_id=KEYCLOAK_CLIENT_ID) - return APISession( - base_url=PDC_API_URL, token_provider=_scoped_token_provider("kc-admin-api"), timeout=PDC_API_TIMEOUT + scope="kc-admin-api", ) + try: + token_provider.get_token() + except TokenRequestError as error: + if "invalid_scope" not in str(error.detail): + raise + pytest.skip(f"Keycloak does not offer the kc-admin-api scope to {KEYCLOAK_CLIENT_ID}") + return APISession(base_url=PDC_API_URL, token_provider=token_provider, timeout=PDC_API_TIMEOUT) diff --git a/integration_tests/test_keycloak_admin.py b/integration_tests/test_keycloak_admin.py index 79818f2..169c637 100644 --- a/integration_tests/test_keycloak_admin.py +++ b/integration_tests/test_keycloak_admin.py @@ -98,15 +98,3 @@ def test_is_idempotent(self, keycloak_admin, keycloak_client_id): keycloak_admin.ensure_direct_grants_enabled(client_id=keycloak_client_id) assert keycloak_admin.is_direct_grants_enabled(client_id=keycloak_client_id) is True - - -class TestEnsureAdminApiAccess: - def test_lets_the_client_request_admin_api_tokens_that_can_list_users_and_organizations( - self, keycloak_admin, keycloak_client_id, client_token_claims - ): - keycloak_admin.ensure_admin_api_access(client_id=keycloak_client_id) - keycloak_admin.ensure_admin_api_access(client_id=keycloak_client_id) - - claims = client_token_claims(scope="kc-admin-api") - assert "kc-admin-api" in claims["scope"].split() - assert {"view-users", "view-organizations"} <= set(claims["resource_access"]["realm-management"]["roles"]) diff --git a/src/pdc_api/seeding/keycloak_admin.py b/src/pdc_api/seeding/keycloak_admin.py index bca9207..88ae217 100644 --- a/src/pdc_api/seeding/keycloak_admin.py +++ b/src/pdc_api/seeding/keycloak_admin.py @@ -4,9 +4,6 @@ from keycloak import KeycloakAdmin as _KeycloakAdminClient from keycloak.exceptions import KeycloakGetError -ADMIN_API_SCOPE = "kc-admin-api" -ADMIN_API_VIEW_ROLES = ("view-users", "view-organizations") - @dataclass class KeycloakOrganization: @@ -174,35 +171,6 @@ def set_direct_grants_enabled(self, *, client_id: str, enabled: bool) -> None: target = self._find_client(client_id) self._admin.update_client(target["id"], {"directAccessGrantsEnabled": enabled}) - def ensure_admin_api_access(self, *, client_id: str) -> None: - client = self._find_client(client_id) - self._admin.add_client_optional_client_scope(client["id"], self._ensure_admin_api_client_scope(), {}) - service_account = self._admin.get_client_service_account_user(client["id"]) - realm_management_id = self._find_client("realm-management")["id"] - roles = [self._admin.get_client_role(realm_management_id, name) for name in ADMIN_API_VIEW_ROLES] - self._admin.assign_client_role(service_account["id"], realm_management_id, roles) - - # Keycloak 26.8.2 creates this built-in scope for new and migrated realms, but not for imported ones. - def _ensure_admin_api_client_scope(self) -> str: - for scope in self._admin.get_client_scopes(): - if scope["name"] == ADMIN_API_SCOPE: - return str(scope["id"]) - return self._admin.create_client_scope( - { - "name": ADMIN_API_SCOPE, - "protocol": "openid-connect", - "attributes": {"include.in.token.scope": "true", "display.on.consent.screen": "false"}, - "protocolMappers": [ - { - "name": "admin-api-audience", - "protocol": "openid-connect", - "protocolMapper": "oidc-admin-api-audience-mapper", - "config": {"access.token.claim": "true", "introspection.token.claim": "true"}, - } - ], - } - ) - def _find_client(self, client_id: str) -> dict[str, Any]: clients: list[dict[str, Any]] = self._admin.get_clients() for client in clients: From e244a623b5a05b17d8c3d2d86617d995aedf9cca Mon Sep 17 00:00:00 2001 From: Chris Kucharczyk <23062974+chrisjkuch@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:06:59 +0000 Subject: [PATCH 05/11] Test the disabled-member sync path and flag the breaking change KeycloakAdmin.set_user_enabled lets the sync integration test disable a member and see PDC mark them disabled. The get_organizations test now checks the synced organization appears instead of only parsing. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 +++ integration_tests/test_operations.py | 12 ++++++++---- src/pdc_api/seeding/keycloak_admin.py | 3 +++ 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4f9b096..b4a745e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,11 +8,14 @@ PDC does not bump its spec version for every API change, so each entry names the Spec: PDC 0.43.0, downloaded 2026-11-24. +Breaking: `Organization.keycloak_organization_id` is now required, as PDC always returns it. Code that builds an `Organization` without it, such as test fixtures, must add it. + - `Organization` has `keycloak_organization_id`, `keycloak_organization_name`, `disabled_at`, `members`, and `former_members`. `members` and `former_members` are `None` when the caller may not see membership, or when PDC has not yet synced the organization from Keycloak. - `get_organizations` walks `GET /organizations`. - `pdc_api.testing` adds `user_payload`, and `organization_payload` takes the new fields. - `sync_users_from_keycloak` and `sync_organizations_from_keycloak` start PDC's Keycloak sync and wait for it, raising `KeycloakSyncError` if it fails or times out. The token must carry the `kc-admin-api` scope. - `KeycloakClientCredentialsProvider` takes an optional `scope`. +- Seeding's `KeycloakAdmin.set_user_enabled` enables or disables a Keycloak user. ## 0.4.1 (2026-11-20) diff --git a/integration_tests/test_operations.py b/integration_tests/test_operations.py index a2e3b47..19cfd8e 100644 --- a/integration_tests/test_operations.py +++ b/integration_tests/test_operations.py @@ -53,7 +53,6 @@ NewProposalFieldValue, NewProposalVersion, OpportunityBundle, - Organization, Proposal, ProposalBundle, ) @@ -554,10 +553,15 @@ def test_sync_from_keycloak_reports_organization_members( organization = get_organization_by_keycloak_id(api_session, keycloak_id=fresh_keycloak_org.id) assert organization.members is not None - assert [str(m.keycloak_user_id) for m in organization.members] == [member.id] + assert [(str(m.keycloak_user_id), m.disabled_at) for m in organization.members] == [(member.id, None)] + assert fresh_keycloak_org.id in {str(o.keycloak_organization_id) for o in get_organizations(api_session)} - def test_get_organizations_parses_every_entry(self, api_session): - assert all(isinstance(o, Organization) for o in get_organizations(api_session)) + keycloak_admin.set_user_enabled(user_id=member.id, enabled=False) + sync_users_from_keycloak(admin_api_session) + + organization = get_organization_by_keycloak_id(api_session, keycloak_id=fresh_keycloak_org.id) + assert organization.members is not None + assert [m.disabled_at is not None for m in organization.members] == [True] class TestApplicationForm: diff --git a/src/pdc_api/seeding/keycloak_admin.py b/src/pdc_api/seeding/keycloak_admin.py index 88ae217..4e3e8ec 100644 --- a/src/pdc_api/seeding/keycloak_admin.py +++ b/src/pdc_api/seeding/keycloak_admin.py @@ -96,6 +96,9 @@ def ensure_user( ) return KeycloakUser(id=user_id, username=username, email=email) + def set_user_enabled(self, *, user_id: str, enabled: bool) -> None: + self._admin.update_user(user_id, {"enabled": enabled}) + def _find_user_by_username(self, username: str) -> dict[str, Any] | None: users: list[dict[str, Any]] = self._admin.get_users({"username": username, "exact": True}) for user in users: From 363c4b5a761662c8a1ffb61e4b2bd3cc91f802e5 Mon Sep 17 00:00:00 2001 From: Chris Kucharczyk <23062974+chrisjkuch@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:36:20 +0000 Subject: [PATCH 06/11] Accept allFunders grantees and test every grantee type The grantee validator rejected any type it didn't name, so a grant to all funders failed to parse. It now reads the keys each type requires from one table, treats every other type as keyless, and its tests cover every PermissionGrantGranteeType. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + src/pdc_api/permission_grants.py | 33 +++++------- tests/test_permission_grants.py | 87 +++++++++++++++----------------- 3 files changed, 53 insertions(+), 68 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b4a745e..733ecfb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ Breaking: `Organization.keycloak_organization_id` is now required, as PDC always - `sync_users_from_keycloak` and `sync_organizations_from_keycloak` start PDC's Keycloak sync and wait for it, raising `KeycloakSyncError` if it fails or times out. The token must carry the `kc-admin-api` scope. - `KeycloakClientCredentialsProvider` takes an optional `scope`. - Seeding's `KeycloakAdmin.set_user_enabled` enables or disables a Keycloak user. +- Permission grants accept the `allFunders` grantee type, which grants to every funder, and the `reference` verb. ## 0.4.1 (2026-11-20) diff --git a/src/pdc_api/permission_grants.py b/src/pdc_api/permission_grants.py index f432b52..8a7d9e9 100644 --- a/src/pdc_api/permission_grants.py +++ b/src/pdc_api/permission_grants.py @@ -19,6 +19,11 @@ _DEFAULT_PAGE_SIZE = 50 +_GRANTEE_KEYS = { + PermissionGrantGranteeType.USER: "grantee_user_keycloak_user_id", + PermissionGrantGranteeType.USER_GROUP: "grantee_keycloak_organization_id", +} + class PermissionGrantConditionRule(BaseSchema): property: Literal["baseFieldCategory"] @@ -44,27 +49,13 @@ class _PermissionGrantBase(BaseSchema): @model_validator(mode="after") def _check_grantee_keys_match_type(self) -> Self: - if self.grantee_type == PermissionGrantGranteeType.USER: - if self.grantee_user_keycloak_user_id is None: - raise ValueError("grantee_user_keycloak_user_id is required when grantee_type is 'user'") - if self.grantee_keycloak_organization_id is not None: - raise ValueError("grantee_keycloak_organization_id must not be set when grantee_type is 'user'") - elif self.grantee_type == PermissionGrantGranteeType.USER_GROUP: - if self.grantee_keycloak_organization_id is None: - raise ValueError("grantee_keycloak_organization_id is required when grantee_type is 'userGroup'") - if self.grantee_user_keycloak_user_id is not None: - raise ValueError("grantee_user_keycloak_user_id must not be set when grantee_type is 'userGroup'") - elif self.grantee_type == PermissionGrantGranteeType.AUTHENTICATED_USERS: - if self.grantee_user_keycloak_user_id is not None: - raise ValueError( - "grantee_user_keycloak_user_id must not be set when grantee_type is 'authenticatedUsers'" - ) - if self.grantee_keycloak_organization_id is not None: - raise ValueError( - "grantee_keycloak_organization_id must not be set when grantee_type is 'authenticatedUsers'" - ) - else: - raise ValueError(f"Unknown grantee_type: {self.grantee_type!r}") + required_key = _GRANTEE_KEYS.get(self.grantee_type) + for key in _GRANTEE_KEYS.values(): + is_set = getattr(self, key) is not None + if key == required_key and not is_set: + raise ValueError(f"{key} is required when grantee_type is '{self.grantee_type}'") + if key != required_key and is_set: + raise ValueError(f"{key} must not be set when grantee_type is '{self.grantee_type}'") return self diff --git a/tests/test_permission_grants.py b/tests/test_permission_grants.py index db60785..be47632 100644 --- a/tests/test_permission_grants.py +++ b/tests/test_permission_grants.py @@ -4,6 +4,7 @@ import pytest from pdc_api.permission_grants import ( + _GRANTEE_KEYS, ChangemakerPermissionGrant, DefaultPermissionGrant, InitiativeFieldValuePermissionGrant, @@ -37,57 +38,49 @@ def _changemaker_grant_payload(*, grant_id: int, changemaker_id: int, grantee_or } -class TestGranteeKeyValidator: - def test_user_grantee_requires_user_uuid(self): - with pytest.raises(ValueError, match="grantee_user_keycloak_user_id is required"): - ChangemakerPermissionGrant( - changemaker_id=7, - grantee_type=PermissionGrantGranteeType.USER, - grantee_keycloak_organization_id=ORG_UUID, - verbs=[PermissionGrantVerb.VIEW], - scope=[PermissionGrantEntityType.PROPOSAL], - ) +GRANTEE_KEY_VALUES = {"grantee_user_keycloak_user_id": USER_UUID, "grantee_keycloak_organization_id": ORG_UUID} - def test_user_group_grantee_rejects_user_uuid(self): - with pytest.raises(ValueError, match="grantee_user_keycloak_user_id must not be set"): - ChangemakerPermissionGrant( - changemaker_id=7, - grantee_type=PermissionGrantGranteeType.USER_GROUP, - grantee_keycloak_organization_id=ORG_UUID, - grantee_user_keycloak_user_id=USER_UUID, - verbs=[PermissionGrantVerb.VIEW], - scope=[PermissionGrantEntityType.PROPOSAL], - ) - def test_authenticated_users_grantee_allows_both_keys_null(self): - grant = ChangemakerPermissionGrant( - changemaker_id=7, - grantee_type=PermissionGrantGranteeType.AUTHENTICATED_USERS, - verbs=[PermissionGrantVerb.VIEW], - scope=[PermissionGrantEntityType.PROPOSAL], - ) - assert grant.grantee_user_keycloak_user_id is None - assert grant.grantee_keycloak_organization_id is None +def _required_keys(grantee_type: PermissionGrantGranteeType) -> set[str]: + return {key for key in [_GRANTEE_KEYS.get(grantee_type)] if key} - def test_authenticated_users_grantee_rejects_org_uuid(self): - with pytest.raises(ValueError, match="grantee_keycloak_organization_id must not be set"): - ChangemakerPermissionGrant( - changemaker_id=7, - grantee_type=PermissionGrantGranteeType.AUTHENTICATED_USERS, - grantee_keycloak_organization_id=ORG_UUID, - verbs=[PermissionGrantVerb.VIEW], - scope=[PermissionGrantEntityType.PROPOSAL], - ) - def test_authenticated_users_grantee_rejects_user_uuid(self): - with pytest.raises(ValueError, match="grantee_user_keycloak_user_id must not be set"): - ChangemakerPermissionGrant( - changemaker_id=7, - grantee_type=PermissionGrantGranteeType.AUTHENTICATED_USERS, - grantee_user_keycloak_user_id=USER_UUID, - verbs=[PermissionGrantVerb.VIEW], - scope=[PermissionGrantEntityType.PROPOSAL], - ) +def _grant_with_keys(grantee_type: PermissionGrantGranteeType, keys: set[str]) -> ChangemakerPermissionGrant: + return ChangemakerPermissionGrant.model_validate( + { + "changemaker_id": 7, + "grantee_type": grantee_type, + "verbs": [PermissionGrantVerb.VIEW], + "scope": [PermissionGrantEntityType.PROPOSAL], + **{key: GRANTEE_KEY_VALUES[key] for key in keys}, + } + ) + + +class TestGranteeKeyValidator: + @pytest.mark.parametrize("grantee_type", list(PermissionGrantGranteeType)) + def test_accepts_the_keys_its_type_requires(self, grantee_type): + grant = _grant_with_keys(grantee_type, _required_keys(grantee_type)) + + assert {key for key in GRANTEE_KEY_VALUES if getattr(grant, key)} == _required_keys(grantee_type) + + @pytest.mark.parametrize(("grantee_type", "key"), list(_GRANTEE_KEYS.items())) + def test_requires_the_key_its_type_names(self, grantee_type, key): + with pytest.raises(ValueError, match=f"{key} is required"): + _grant_with_keys(grantee_type, set()) + + @pytest.mark.parametrize( + ("grantee_type", "key"), + [ + (grantee_type, key) + for grantee_type in PermissionGrantGranteeType + for key in GRANTEE_KEY_VALUES + if key not in _required_keys(grantee_type) + ], + ) + def test_rejects_keys_its_type_does_not_take(self, grantee_type, key): + with pytest.raises(ValueError, match=f"{key} must not be set"): + _grant_with_keys(grantee_type, _required_keys(grantee_type) | {key}) class TestDefaultPermissionGrantContext: From 84e2b74f5cd5de194d22bb1cd169c2fe64ec9c88 Mon Sep 17 00:00:00 2001 From: Chris Kucharczyk <23062974+chrisjkuch@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:36:20 +0000 Subject: [PATCH 07/11] Parametrize sync tests over both functions and every status Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 1 + tests/test_client_operations.py | 60 ++++++++++++++++++--------------- 2 files changed, 33 insertions(+), 28 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 31b59d7..729f256 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,6 +34,7 @@ A framework-free Python client for the Philanthropy Data Commons (PDC) API. The - Readability, simplicity, and elegance, in that order. - Write the test before the code. Assert transformations and branch behavior, not that a mock returned what it was given. +- When behavior varies by enum member, union variant, or function, parametrize over the enum, union, or table the code uses rather than listing cases by hand, so a value that codegen adds is tested without a test change. - Every client function gets an integration test against PDC as well as unit tests, unless PDC's CI stack can't support it. - Tests live in `Test` classes named for the function or class under test, with methods named `test_` in the present tense, such as `TestGetProposal.test_raises_proposal_not_found_on_404`. Integration tests that cover a workflow across several functions may group by area instead, such as `TestProposals`. - No docstrings, and comments only for a non-obvious why such as a PDC quirk, in one line. diff --git a/tests/test_client_operations.py b/tests/test_client_operations.py index df729ce..0be4525 100644 --- a/tests/test_client_operations.py +++ b/tests/test_client_operations.py @@ -40,6 +40,7 @@ NewProposalFieldValue, NewProposalVersion, Organization, + SyncTaskStatus, ) from pdc_api.testing import ( application_form_payload, @@ -395,41 +396,44 @@ def _sync_task(*, id: int = 7, status: str, details: dict | None = None) -> dict } -class TestSyncUsersFromKeycloak: - def test_polls_until_the_task_completes(self, session, add_json_response): - _post("users/sync", _sync_task(status="pending")) - add_json_response(path="users/sync/7", payload=_sync_task(status="in_progress")) - add_json_response( - path="users/sync/7", - payload=_sync_task( - status="completed", details={"users": {"seen": 2, "added": 1, "updated": 1, "disabled": 0}} - ), - ) +IN_FLIGHT_STATUSES = [SyncTaskStatus.PENDING, SyncTaskStatus.IN_PROGRESS] +UNSUCCESSFUL_STATUSES = [s for s in SyncTaskStatus if s not in [*IN_FLIGHT_STATUSES, SyncTaskStatus.COMPLETED]] - task = sync_users_from_keycloak(session, poll_interval_seconds=0) - assert task.status == "completed" - assert len(responses.calls) == 3 +@pytest.fixture( + params=[(sync_users_from_keycloak, "users/sync"), (sync_organizations_from_keycloak, "organizations/sync")], + ids=["users", "organizations"], +) +def sync(request): + return request.param - def test_raises_when_the_task_fails(self, session, add_json_response): - _post("users/sync", _sync_task(status="pending")) - add_json_response(path="users/sync/7", payload=_sync_task(status="failed")) - with pytest.raises(KeycloakSyncError, match="failed"): - sync_users_from_keycloak(session, poll_interval_seconds=0) +class TestRunSyncTask: + @pytest.mark.parametrize("in_flight_status", IN_FLIGHT_STATUSES) + def test_polls_until_the_task_completes(self, session, add_json_response, sync, in_flight_status): + sync_function, endpoint = sync + _post(endpoint, _sync_task(status=in_flight_status)) + add_json_response(path=f"{endpoint}/7", payload=_sync_task(status=in_flight_status)) + add_json_response(path=f"{endpoint}/7", payload=_sync_task(status=SyncTaskStatus.COMPLETED)) - def test_raises_when_the_task_outlasts_the_timeout(self, session): - _post("users/sync", _sync_task(status="pending")) + task = sync_function(session, poll_interval_seconds=0) - with pytest.raises(KeycloakSyncError, match="pending"): - sync_users_from_keycloak(session, poll_interval_seconds=0, timeout_seconds=0) + assert task.status == SyncTaskStatus.COMPLETED + assert len(responses.calls) == 3 + @pytest.mark.parametrize("unsuccessful_status", UNSUCCESSFUL_STATUSES) + def test_raises_when_the_task_ends_unsuccessfully(self, session, add_json_response, sync, unsuccessful_status): + sync_function, endpoint = sync + _post(endpoint, _sync_task(status=SyncTaskStatus.PENDING)) + add_json_response(path=f"{endpoint}/7", payload=_sync_task(status=unsuccessful_status)) -class TestSyncOrganizationsFromKeycloak: - def test_polls_the_organization_sync_task(self, session, add_json_response): - _post("organizations/sync", _sync_task(status="pending")) - add_json_response(path="organizations/sync/7", payload=_sync_task(status="completed")) + with pytest.raises(KeycloakSyncError, match=unsuccessful_status): + sync_function(session, poll_interval_seconds=0) - task = sync_organizations_from_keycloak(session, poll_interval_seconds=0) + @pytest.mark.parametrize("in_flight_status", IN_FLIGHT_STATUSES) + def test_raises_when_the_task_outlasts_the_timeout(self, session, sync, in_flight_status): + sync_function, endpoint = sync + _post(endpoint, _sync_task(status=in_flight_status)) - assert task.status == "completed" + with pytest.raises(KeycloakSyncError, match=in_flight_status): + sync_function(session, poll_interval_seconds=0, timeout_seconds=0) From 503f24be3844db692baff9fc8533a1bb2914712a Mon Sep 17 00:00:00 2001 From: Chris Kucharczyk <23062974+chrisjkuch@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:36:20 +0000 Subject: [PATCH 08/11] Document Keycloak sync, token scope, and set_user_enabled Co-Authored-By: Claude Opus 5.5 --- README.md | 30 +++++++++++++++++++++++++++--- 1 file changed, 27 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index eab5034..b7f0e14 100644 --- a/README.md +++ b/README.md @@ -67,7 +67,7 @@ class TokenProvider(Protocol): def refresh_if_necessary(self) -> None: ... ``` -The package ships one: `KeycloakClientCredentialsProvider` runs the OAuth2 client-credentials grant against PDC's Keycloak and caches the token until 30 seconds before it expires. Use it for a service account. +The package ships one: `KeycloakClientCredentialsProvider` runs the OAuth2 client-credentials grant against PDC's Keycloak and caches the token until 30 seconds before it expires. Use it for a service account. Pass `scope` to request an optional client scope, such as `kc-admin-api`. To call PDC as a signed-in user, write your own provider that returns the user's access token and refreshes it as your app requires. The protocol is structural, so your class doesn't need to import or subclass anything from this package. @@ -124,9 +124,33 @@ A changemaker can also write its own profile values. `create_changemaker_source` Uploading a file takes two steps. `create_file` creates the file record and returns a presigned S3 POST, and `upload_file_to_s3_presigned_url` sends the bytes to it. +## Syncing from Keycloak + +PDC caches Keycloak's users, organizations, and memberships, and an `Organization`'s `members` and `former_members` come from that cache. `sync_users_from_keycloak` and `sync_organizations_from_keycloak` start PDC's sync, wait for it to finish, and return the completed task, or raise `KeycloakSyncError` if it fails or outlasts `timeout_seconds`. The token must carry the `kc-admin-api` scope: + +```python +from pdc_api.client import sync_organizations_from_keycloak, sync_users_from_keycloak + +admin_session = APISession( + base_url="https://api.philanthropydatacommons.org/", + token_provider=KeycloakClientCredentialsProvider( + server_url="https://auth.philanthropydatacommons.org", + realm="pdc", + client_id="your-client-id", + client_secret="your-client-secret", + timeout=15, + scope="kc-admin-api", + ), +) +sync_users_from_keycloak(admin_session) +sync_organizations_from_keycloak(admin_session) +``` + +`members` and `former_members` are `None` when the caller may not see membership, or when PDC has not yet synced the organization. + ## Permission grants -PDC controls access with permission grants. Each grant gives a grantee (a user, a Keycloak organization, or every authenticated user) a set of verbs (such as `view` or `edit`) over a set of scopes, in the context of one entity such as a changemaker or a proposal. `pdc_api.permission_grants` models each context as its own class, so a grant parses into, say, `ChangemakerPermissionGrant` with a typed `changemaker_id`: +PDC controls access with permission grants. Each grant gives a grantee (a user, a Keycloak organization, every authenticated user, or every funder) a set of verbs (such as `view` or `edit`) over a set of scopes, in the context of one entity such as a changemaker or a proposal. `pdc_api.permission_grants` models each context as its own class, so a grant parses into, say, `ChangemakerPermissionGrant` with a typed `changemaker_id`: ```python from pdc_api.models import PermissionGrantEntityType, PermissionGrantGranteeType, PermissionGrantVerb @@ -232,7 +256,7 @@ def test_lists_changemakers(): `pdc_api.seeding` (extra: `seeding`) creates realistic data on a PDC stack through the public PDC API and the Keycloak admin API. It is for local development and integration tests, not production: - **`pdc_api.seeding.pdc_entities`:** `seed_*` functions for funders, collaboratives, changemakers, fiscal sponsorships, data providers, opportunities, application forms, proposals, initiatives, and field values. `seed_proposal_bundle` creates a full proposal and everything it depends on in one call. -- **`pdc_api.seeding.keycloak_admin`:** `KeycloakAdmin`, whose `ensure_*` methods create Keycloak organizations, users, memberships, and realm roles only if they don't already exist, so re-running a seed script is safe. +- **`pdc_api.seeding.keycloak_admin`:** `KeycloakAdmin`, whose `ensure_*` methods create Keycloak organizations, users, memberships, and realm roles only if they don't already exist, so re-running a seed script is safe. `set_user_enabled` enables or disables a user. ## Contributing From 8fcb31bfec18c8ae4e644ddeb12ae35bd60102ae Mon Sep 17 00:00:00 2001 From: Chris Kucharczyk <23062974+chrisjkuch@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:41:08 +0000 Subject: [PATCH 09/11] State grantee key expectations as literals The grantee tests derived expected keys from the validator's own table, so a wrong entry passed. They now state the keyed types literally and still cover every other type as keyless. AGENTS.md says to parametrize over enums but write expectations as literals. Drop the reference verb from the changelog; it was already supported. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- CHANGELOG.md | 2 +- tests/test_permission_grants.py | 10 +++++++--- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 729f256..e377b67 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,7 +34,7 @@ A framework-free Python client for the Philanthropy Data Commons (PDC) API. The - Readability, simplicity, and elegance, in that order. - Write the test before the code. Assert transformations and branch behavior, not that a mock returned what it was given. -- When behavior varies by enum member, union variant, or function, parametrize over the enum, union, or table the code uses rather than listing cases by hand, so a value that codegen adds is tested without a test change. +- When behavior varies by enum member, union variant, or function, parametrize over the enum or union rather than listing cases by hand, so a value that codegen adds is tested without a test change. State expected outcomes as literals in the test, not by reading the code's own lookup table, so a wrong entry in that table fails a test. - Every client function gets an integration test against PDC as well as unit tests, unless PDC's CI stack can't support it. - Tests live in `Test` classes named for the function or class under test, with methods named `test_` in the present tense, such as `TestGetProposal.test_raises_proposal_not_found_on_404`. Integration tests that cover a workflow across several functions may group by area instead, such as `TestProposals`. - No docstrings, and comments only for a non-obvious why such as a PDC quirk, in one line. diff --git a/CHANGELOG.md b/CHANGELOG.md index 733ecfb..7a77c57 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,7 +16,7 @@ Breaking: `Organization.keycloak_organization_id` is now required, as PDC always - `sync_users_from_keycloak` and `sync_organizations_from_keycloak` start PDC's Keycloak sync and wait for it, raising `KeycloakSyncError` if it fails or times out. The token must carry the `kc-admin-api` scope. - `KeycloakClientCredentialsProvider` takes an optional `scope`. - Seeding's `KeycloakAdmin.set_user_enabled` enables or disables a Keycloak user. -- Permission grants accept the `allFunders` grantee type, which grants to every funder, and the `reference` verb. +- Permission grants accept the `allFunders` grantee type, which grants to every funder. ## 0.4.1 (2026-11-20) diff --git a/tests/test_permission_grants.py b/tests/test_permission_grants.py index be47632..866c5ba 100644 --- a/tests/test_permission_grants.py +++ b/tests/test_permission_grants.py @@ -4,7 +4,6 @@ import pytest from pdc_api.permission_grants import ( - _GRANTEE_KEYS, ChangemakerPermissionGrant, DefaultPermissionGrant, InitiativeFieldValuePermissionGrant, @@ -40,9 +39,14 @@ def _changemaker_grant_payload(*, grant_id: int, changemaker_id: int, grantee_or GRANTEE_KEY_VALUES = {"grantee_user_keycloak_user_id": USER_UUID, "grantee_keycloak_organization_id": ORG_UUID} +KEYED_GRANTEE_TYPES = { + PermissionGrantGranteeType.USER: "grantee_user_keycloak_user_id", + PermissionGrantGranteeType.USER_GROUP: "grantee_keycloak_organization_id", +} + def _required_keys(grantee_type: PermissionGrantGranteeType) -> set[str]: - return {key for key in [_GRANTEE_KEYS.get(grantee_type)] if key} + return {KEYED_GRANTEE_TYPES[grantee_type]} if grantee_type in KEYED_GRANTEE_TYPES else set() def _grant_with_keys(grantee_type: PermissionGrantGranteeType, keys: set[str]) -> ChangemakerPermissionGrant: @@ -64,7 +68,7 @@ def test_accepts_the_keys_its_type_requires(self, grantee_type): assert {key for key in GRANTEE_KEY_VALUES if getattr(grant, key)} == _required_keys(grantee_type) - @pytest.mark.parametrize(("grantee_type", "key"), list(_GRANTEE_KEYS.items())) + @pytest.mark.parametrize(("grantee_type", "key"), list(KEYED_GRANTEE_TYPES.items())) def test_requires_the_key_its_type_names(self, grantee_type, key): with pytest.raises(ValueError, match=f"{key} is required"): _grant_with_keys(grantee_type, set()) From 2c5c53dbea4c66a8f52cf621cc97547d2118f460 Mon Sep 17 00:00:00 2001 From: Chris Kucharczyk <23062974+chrisjkuch@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:42:26 +0000 Subject: [PATCH 10/11] Fail by name when an enum gains a member the tests don't cover Grantee-key and sync-status tests now list an expected outcome for every enum member, parametrize over that list, and assert it covers the enum. A new member such as allChangemakers fails one named test until someone records how it behaves. AGENTS.md states the pattern. Co-Authored-By: Claude Opus 5.5 --- AGENTS.md | 2 +- tests/test_client_operations.py | 15 +++++++++++++-- tests/test_permission_grants.py | 18 +++++++++++++----- 3 files changed, 27 insertions(+), 8 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index e377b67..2139d0a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -34,7 +34,7 @@ A framework-free Python client for the Philanthropy Data Commons (PDC) API. The - Readability, simplicity, and elegance, in that order. - Write the test before the code. Assert transformations and branch behavior, not that a mock returned what it was given. -- When behavior varies by enum member, union variant, or function, parametrize over the enum or union rather than listing cases by hand, so a value that codegen adds is tested without a test change. State expected outcomes as literals in the test, not by reading the code's own lookup table, so a wrong entry in that table fails a test. +- When behavior varies by enum member or union variant, write the expected outcome for every member as a literal table in the test, parametrize over that table, and assert the table covers the whole enum or union. A value that codegen adds then fails a test by name until someone records how it behaves, and a wrong entry in the code's own lookup table fails too, because the test doesn't read it. - Every client function gets an integration test against PDC as well as unit tests, unless PDC's CI stack can't support it. - Tests live in `Test` classes named for the function or class under test, with methods named `test_` in the present tense, such as `TestGetProposal.test_raises_proposal_not_found_on_404`. Integration tests that cover a workflow across several functions may group by area instead, such as `TestProposals`. - No docstrings, and comments only for a non-obvious why such as a PDC quirk, in one line. diff --git a/tests/test_client_operations.py b/tests/test_client_operations.py index 0be4525..09f393d 100644 --- a/tests/test_client_operations.py +++ b/tests/test_client_operations.py @@ -396,8 +396,19 @@ def _sync_task(*, id: int = 7, status: str, details: dict | None = None) -> dict } -IN_FLIGHT_STATUSES = [SyncTaskStatus.PENDING, SyncTaskStatus.IN_PROGRESS] -UNSUCCESSFUL_STATUSES = [s for s in SyncTaskStatus if s not in [*IN_FLIGHT_STATUSES, SyncTaskStatus.COMPLETED]] +EXPECTED_SYNC_OUTCOME = { + SyncTaskStatus.PENDING: "polls", + SyncTaskStatus.IN_PROGRESS: "polls", + SyncTaskStatus.COMPLETED: "returns", + SyncTaskStatus.FAILED: "raises", + SyncTaskStatus.CANCELED: "raises", +} +IN_FLIGHT_STATUSES = [status for status, outcome in EXPECTED_SYNC_OUTCOME.items() if outcome == "polls"] +UNSUCCESSFUL_STATUSES = [status for status, outcome in EXPECTED_SYNC_OUTCOME.items() if outcome == "raises"] + + +def test_every_sync_task_status_has_an_expected_outcome(): + assert set(SyncTaskStatus) - set(EXPECTED_SYNC_OUTCOME) == set() @pytest.fixture( diff --git a/tests/test_permission_grants.py b/tests/test_permission_grants.py index 866c5ba..519c8cb 100644 --- a/tests/test_permission_grants.py +++ b/tests/test_permission_grants.py @@ -39,14 +39,17 @@ def _changemaker_grant_payload(*, grant_id: int, changemaker_id: int, grantee_or GRANTEE_KEY_VALUES = {"grantee_user_keycloak_user_id": USER_UUID, "grantee_keycloak_organization_id": ORG_UUID} -KEYED_GRANTEE_TYPES = { +EXPECTED_GRANTEE_KEY = { PermissionGrantGranteeType.USER: "grantee_user_keycloak_user_id", PermissionGrantGranteeType.USER_GROUP: "grantee_keycloak_organization_id", + PermissionGrantGranteeType.AUTHENTICATED_USERS: None, + PermissionGrantGranteeType.ALL_FUNDERS: None, } def _required_keys(grantee_type: PermissionGrantGranteeType) -> set[str]: - return {KEYED_GRANTEE_TYPES[grantee_type]} if grantee_type in KEYED_GRANTEE_TYPES else set() + key = EXPECTED_GRANTEE_KEY[grantee_type] + return {key} if key else set() def _grant_with_keys(grantee_type: PermissionGrantGranteeType, keys: set[str]) -> ChangemakerPermissionGrant: @@ -62,13 +65,18 @@ def _grant_with_keys(grantee_type: PermissionGrantGranteeType, keys: set[str]) - class TestGranteeKeyValidator: - @pytest.mark.parametrize("grantee_type", list(PermissionGrantGranteeType)) + def test_every_grantee_type_has_an_expected_key(self): + assert set(PermissionGrantGranteeType) - set(EXPECTED_GRANTEE_KEY) == set() + + @pytest.mark.parametrize("grantee_type", list(EXPECTED_GRANTEE_KEY)) def test_accepts_the_keys_its_type_requires(self, grantee_type): grant = _grant_with_keys(grantee_type, _required_keys(grantee_type)) assert {key for key in GRANTEE_KEY_VALUES if getattr(grant, key)} == _required_keys(grantee_type) - @pytest.mark.parametrize(("grantee_type", "key"), list(KEYED_GRANTEE_TYPES.items())) + @pytest.mark.parametrize( + ("grantee_type", "key"), [(grantee_type, key) for grantee_type, key in EXPECTED_GRANTEE_KEY.items() if key] + ) def test_requires_the_key_its_type_names(self, grantee_type, key): with pytest.raises(ValueError, match=f"{key} is required"): _grant_with_keys(grantee_type, set()) @@ -77,7 +85,7 @@ def test_requires_the_key_its_type_names(self, grantee_type, key): ("grantee_type", "key"), [ (grantee_type, key) - for grantee_type in PermissionGrantGranteeType + for grantee_type in EXPECTED_GRANTEE_KEY for key in GRANTEE_KEY_VALUES if key not in _required_keys(grantee_type) ], From ce1a45dbc3756c21e768d022e5a415512af0f9f8 Mon Sep 17 00:00:00 2001 From: Chris Kucharczyk <23062974+chrisjkuch@users.noreply.github.com> Date: Tue, 24 Nov 2026 09:54:19 +0000 Subject: [PATCH 11/11] Patch the fetched realm so the Keycloak sync test runs PDC's realm.json lacks the kc-admin-api scope, so the sync integration test skipped. just/patch_realm.py adds the scope and organization roles from the pending service realm change, and warns once upstream defines it. CI now starts the stack with `just pdc up` so it gets the patch too. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 17 ++++---------- CONTRIBUTING.md | 2 +- integration_tests/conftest.py | 8 ------- just/patch_realm.py | 44 +++++++++++++++++++++++++++++++++++ just/pdc.just | 3 ++- 5 files changed, 52 insertions(+), 22 deletions(-) create mode 100644 just/patch_realm.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d0bfd61..dffad29 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -119,18 +119,6 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: persist-credentials: false - - name: Check out the PDC service repository - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - persist-credentials: false - repository: PhilanthropyDataCommons/service - path: service - - name: Add hosts entries for the PDC stack - run: echo "127.0.0.1 pdc-api pdc-auth pdc-s3" | sudo tee -a /etc/hosts - - name: Start the PDC stack - working-directory: service - run: docker compose -f compose-ci.yml up -d --wait - timeout-minutes: 5 - name: Install just uses: extractions/setup-just@53165ef7e734c5c07cb06b3c8e7b647c5aa16db3 # v4.0.0 with: @@ -139,6 +127,11 @@ jobs: uses: astral-sh/setup-uv@68559e99cc807c1eb7e9238fd43a15bba460eec2 # v10.3.3 with: cache-suffix: integration + - name: Add hosts entries for the PDC stack + run: echo "127.0.0.1 pdc-api pdc-auth pdc-s3" | sudo tee -a /etc/hosts + - name: Start the PDC stack + run: just pdc up + timeout-minutes: 5 - name: Run the integration tests run: just integration ${UPGRADE:+--upgrade} timeout-minutes: 5 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index c6e0427..1b7e7ee 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -26,7 +26,7 @@ just test --python 3.12 --lowest-direct -- -k token `uv.lock` pins the versions used for development and CI. Update it with `uv lock --upgrade`. CI also runs both suites weekly with `--upgrade`, and opens an issue when that run or a push to main fails. -`just pdc up` downloads PDC's [`compose-ci.yml`](https://github.com/PhilanthropyDataCommons/service/blob/main/compose-ci.yml) and Keycloak realm from the service repo's main branch and starts the stack: the PDC API, Keycloak, Postgres, and S3. The integration tests reach Keycloak at `pdc-auth`, so add this line to `/etc/hosts`: +`just pdc up` downloads PDC's [`compose-ci.yml`](https://github.com/PhilanthropyDataCommons/service/blob/main/compose-ci.yml) and Keycloak realm from the service repo's main branch and starts the stack: the PDC API, Keycloak, Postgres, and S3. `just/patch_realm.py` adds the `kc-admin-api` scope the Keycloak sync needs, which the realm lacks; it warns once the realm defines it, and then should be deleted. CI starts the stack the same way. The integration tests reach Keycloak at `pdc-auth`, so add this line to `/etc/hosts`: ```text 127.0.0.1 pdc-api pdc-auth pdc-s3 diff --git a/integration_tests/conftest.py b/integration_tests/conftest.py index 88cb23c..ed9e327 100644 --- a/integration_tests/conftest.py +++ b/integration_tests/conftest.py @@ -4,7 +4,6 @@ import pytest import requests -from pdc_api.errors import TokenRequestError from pdc_api.models import FunderCollaborativeMemberBundle from pdc_api.seeding.keycloak_admin import KeycloakAdmin from pdc_api.seeding.pdc_entities import ( @@ -147,7 +146,6 @@ def add(username: str, *orgs) -> None: return add -# PDC's CI realm offers kc-admin-api only once service's realm.json defines it; until then the sync can't run. @pytest.fixture(scope="session") def admin_api_session() -> APISession: token_provider = KeycloakClientCredentialsProvider( @@ -158,10 +156,4 @@ def admin_api_session() -> APISession: timeout=PDC_API_TIMEOUT, scope="kc-admin-api", ) - try: - token_provider.get_token() - except TokenRequestError as error: - if "invalid_scope" not in str(error.detail): - raise - pytest.skip(f"Keycloak does not offer the kc-admin-api scope to {KEYCLOAK_CLIENT_ID}") return APISession(base_url=PDC_API_URL, token_provider=token_provider, timeout=PDC_API_TIMEOUT) diff --git a/just/patch_realm.py b/just/patch_realm.py new file mode 100644 index 0000000..eaad7ed --- /dev/null +++ b/just/patch_realm.py @@ -0,0 +1,44 @@ +import json +import sys +from pathlib import Path + +ADMIN_API_SCOPE = { + "name": "kc-admin-api", + "description": "Grants access to the Keycloak Admin REST API by adding its required audience to the token", + "protocol": "openid-connect", + "attributes": {"include.in.token.scope": "true", "display.on.consent.screen": "false"}, + "protocolMappers": [ + { + "name": "admin-api-audience", + "protocol": "openid-connect", + "protocolMapper": "oidc-admin-api-audience-mapper", + "consentRequired": False, + "config": {"access.token.claim": "true", "introspection.token.claim": "true"}, + } + ], +} +ADMIN_API_CLIENTS = {"pdc-dev-ingest", "pdc-openapi-docs"} +ORGANIZATION_ROLES = ["query-organizations", "view-organizations", "manage-organizations"] + + +# Keycloak creates kc-admin-api for new and migrated realms but not imported ones; remove once service's realm.json defines it. +def add_admin_api_access(realm: dict) -> None: + realm["clientScopes"].append(ADMIN_API_SCOPE) + for client in realm["clients"]: + if client["clientId"] in ADMIN_API_CLIENTS: + client["optionalClientScopes"].append(ADMIN_API_SCOPE["name"]) + [admin_group] = [group for group in realm["groups"] if group["name"] == "pdc-admin"] + admin_group["clientRoles"]["realm-management"].extend(ORGANIZATION_ROLES) + + +def main(path: Path) -> None: + realm = json.loads(path.read_text()) + if any(scope["name"] == ADMIN_API_SCOPE["name"] for scope in realm["clientScopes"]): + print(f"warning: {path} already defines kc-admin-api; delete just/patch_realm.py", file=sys.stderr) + return + add_admin_api_access(realm) + path.write_text(json.dumps(realm, indent="\t") + "\n") + + +if __name__ == "__main__": + main(Path(sys.argv[1])) diff --git a/just/pdc.just b/just/pdc.just index 91a5b40..c50ac79 100644 --- a/just/pdc.just +++ b/just/pdc.just @@ -9,11 +9,12 @@ compose := 'docker compose -f ' + cache + '/compose-ci.yml' _default: @just --list pdc --unsorted -# Fetch PDC's compose file and Keycloak realm +# Fetch PDC's compose file and Keycloak realm, adding the admin API access the realm lacks fetch: mkdir -p {{cache}}/keycloak curl -fsSL {{base}}/compose-ci.yml -o {{cache}}/compose-ci.yml curl -fsSL {{base}}/keycloak/realm.json -o {{cache}}/keycloak/realm.json + uv run --no-project python -I just/patch_realm.py {{cache}}/keycloak/realm.json # Start the stack and wait until it is healthy up: fetch