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/AGENTS.md b/AGENTS.md index 31b59d7..2139d0a 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 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/CHANGELOG.md b/CHANGELOG.md index 0662251..7a77c57 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,20 @@ 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. + +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. +- Permission grants accept the `allFunders` grantee type, which grants to every funder. + ## 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/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/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 diff --git a/integration_tests/conftest.py b/integration_tests/conftest.py index c5da731..ed9e327 100644 --- a/integration_tests/conftest.py +++ b/integration_tests/conftest.py @@ -144,3 +144,16 @@ def add(username: str, *orgs) -> None: keycloak_admin.ensure_user_in_organization(organization_id=org.id, user_id=user.id) return add + + +@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="kc-admin-api", + ) + return APISession(base_url=PDC_API_URL, token_provider=token_provider, timeout=PDC_API_TIMEOUT) diff --git a/integration_tests/test_operations.py b/integration_tests/test_operations.py index 5c53252..19cfd8e 100644 --- a/integration_tests/test_operations.py +++ b/integration_tests/test_operations.py @@ -28,9 +28,12 @@ get_initiative_field_values, get_initiatives, get_organization_by_keycloak_id, + get_organizations, 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 ( @@ -531,6 +534,35 @@ 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), 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)} + + 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: def test_get_application_form_returns_seeded_form(self, api_session): 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 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/_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..9e2bc6c 100644 --- a/src/pdc_api/client.py +++ b/src/pdc_api/client.py @@ -1,4 +1,5 @@ import json +import time from collections.abc import Generator from datetime import datetime from typing import Any, ClassVar, Protocol, Self @@ -20,10 +21,13 @@ InitiativeFieldValue, NewProposalVersion, Organization, + OrganizationSyncTask, PresignedPost, Proposal, ProposalVersion, Source, + SyncTaskStatus, + UserSyncTask, ) from pdc_api.transport import APISession @@ -76,6 +80,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"]: @@ -330,3 +340,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[SyncTask: (UserSyncTask, OrganizationSyncTask)]( + 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..54f7859 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,6 +37,7 @@ SensitivityClassification, ShallowChangemaker, Source, + UserSyncTask, ) from pdc_api._generated import ( ApplicationFormFieldInputType as InputType, @@ -43,6 +45,9 @@ from pdc_api._generated import ( DataType as BaseFieldDataType, ) +from pdc_api._generated import ( + Status as SyncTaskStatus, +) __all__ = [ "ApplicationFormField", @@ -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/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/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/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: 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/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.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..09f393d 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, ) @@ -37,6 +40,7 @@ NewProposalFieldValue, NewProposalVersion, Organization, + SyncTaskStatus, ) from pdc_api.testing import ( application_form_payload, @@ -51,9 +55,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 +130,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): @@ -354,3 +383,68 @@ 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", + } + + +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( + params=[(sync_users_from_keycloak, "users/sync"), (sync_organizations_from_keycloak, "organizations/sync")], + ids=["users", "organizations"], +) +def sync(request): + return request.param + + +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)) + + task = sync_function(session, poll_interval_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)) + + with pytest.raises(KeycloakSyncError, match=unsuccessful_status): + sync_function(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)) + + with pytest.raises(KeycloakSyncError, match=in_flight_status): + sync_function(session, poll_interval_seconds=0, timeout_seconds=0) diff --git a/tests/test_permission_grants.py b/tests/test_permission_grants.py index db60785..519c8cb 100644 --- a/tests/test_permission_grants.py +++ b/tests/test_permission_grants.py @@ -37,57 +37,62 @@ 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} + +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]: + key = EXPECTED_GRANTEE_KEY[grantee_type] + return {key} if key else set() + + +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: - 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], - ) + def test_every_grantee_type_has_an_expected_key(self): + assert set(PermissionGrantGranteeType) - set(EXPECTED_GRANTEE_KEY) == set() - 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], - ) + @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)) - 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 + assert {key for key in GRANTEE_KEY_VALUES if getattr(grant, key)} == _required_keys(grantee_type) - 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], - ) + @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()) - 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], - ) + @pytest.mark.parametrize( + ("grantee_type", "key"), + [ + (grantee_type, key) + for grantee_type in EXPECTED_GRANTEE_KEY + 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: 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)