Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 5 additions & 12 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<Subject>` classes named for the function or class under test, with methods named `test_<behavior>` 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.
Expand Down
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand Down
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
30 changes: 27 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
13 changes: 13 additions & 0 deletions integration_tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
32 changes: 32 additions & 0 deletions integration_tests/test_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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):
Expand Down
44 changes: 44 additions & 0 deletions just/patch_realm.py
Original file line number Diff line number Diff line change
@@ -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]))
3 changes: 2 additions & 1 deletion just/pdc.just
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions src/pdc_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
ChangemakerFieldValueBatchNotFoundError,
ChangemakerNotFoundError,
FunderNotFoundError,
KeycloakSyncError,
PDCBadRequestError,
PDCConflictError,
PDCException,
Expand All @@ -23,6 +24,7 @@
"ChangemakerFieldValueBatchNotFoundError",
"ChangemakerNotFoundError",
"FunderNotFoundError",
"KeycloakSyncError",
"PDCBadRequestError",
"PDCConflictError",
"PDCException",
Expand Down
Loading