Repository navigation
refactor: use FOCA's ownership and URL helpers - #169
Conversation
Grant, revoke and list roles on services with FOCA 0.16's ownership helpers (grant_role, revoke_roles, list_roles, list_subject_roles, add_owner, is_admin) instead of the app's own implementation of the last-owner rule, the existence re-check and role replacement. The app keeps its controllers, so the API paths and responses are unchanged, and adds what FOCA leaves to apps: display names of users, the service existence check (passed as `exists`) and which groups users may grant roles to. Set `security.access_control.resource_roles` (owner, maintainer) in the config, checked against the `Role` enum of the API. Role changes are now logged by FOCA (logger `foca.security.access_control.ownership`). As in FOCA, `maintainer` is only granted on services with an owner, and roles are not granted to groups while group claim values are not kept as subjects (`400`). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Check and normalize service URLs and links with `foca.utils.urls` (normalize_url, check_url, check_url_fields) instead of the app's own implementation, which FOCA's is based on. Service URLs keep tolerating surrounding spaces, and the allowed schemes are unchanged (`https` by default for service URLs, HTTP(S) for links, also `mailto` for `contactUrl`). FOCA's checks are stricter: URLs with ASCII characters that must be percent-encoded (e.g., `<`, `|`), hosts with percent-encodings or empty labels, or IPv4 addresses not in dotted-decimal form are rejected, and some messages changed (e.g., "must use one of these schemes"). Normalized URLs, and so the keys of stored services, are the same for URLs valid before and now. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Refuse to start with FOCA service clients (`auth.service_clients`, `auth.on_behalf_of_header`): FOCA's helpers would make the clients, or the users they name, owners, which the app's endpoints neither list nor manage, and which `/me` and the rollback of new services wouldn't match. Warn on startup of stored services with keys whose URLs are invalid now (e.g., accepted before FOCA's stricter checks): they can only be updated with a valid URL, and duplicates of them may go undetected. Also clarify that `check_url_scheme()` checks the whole URL, and how `LastOwner` becomes `409`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Simulate services deleted while a role is granted through the app's `service_exists()`, which it passes to FOCA's helpers as `exists`, instead of patching FOCA's internal `add_resource_role`. Tests that still patch FOCA internals (failures, concurrent owner removals) are marked as tied to FOCA 0.16 in the module docstring. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The app no longer uses idna itself; FOCA requires `idna>=3.15,<4` (CVE-2026-45409) for its URL helpers. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The grant race tests deleted the service's roles along with the service, so they passed even if FOCA's helper didn't revoke the role it granted. Delete only the service document, so that only the revocation removes the role. Also share the URL check of the startup warnings, test the startup warning of invalid URLs, and note on the configuration page that service clients aren't supported. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideRefactors ownership and URL handling onto FOCA 0.16 helpers while preserving the registry API shape, adds startup safeguards for unsupported service clients and legacy invalid URLs, and updates behavior documentation and comprehensive tests for the resulting validation, authorization, logging, and race-safety changes. Sequence diagram for FOCA-managed service permission changessequenceDiagram
actor User
participant API as Registry API
participant FOCA as FOCA ownership helpers
participant Policy as Policy rules
participant Names as user_names
User->>API: PUT permissions
API->>API: service_exists(serviceId)
API->>FOCA: grant_role(resource, subject, role, exists)
FOCA->>Policy: Grant or replace resource role
FOCA-->>API: Success or validation error
API->>Names: Update display name
API-->>User: Existing permission response
User->>API: DELETE permissions
API->>FOCA: revoke_roles(resource, subject, exists)
FOCA->>Policy: Revoke roles while preserving last owner
FOCA-->>API: Success or conflict
API->>Names: Remove user display name
API-->>User: Existing response shape
Sequence diagram for startup validation and legacy URL warningssequenceDiagram
participant App as Application startup
participant Config as FOCA configuration
participant Services as Services collection
participant URLs as FOCA URL helpers
participant Log as Application logger
App->>Config: check_no_service_clients()
Config-->>App: Configuration accepted or startup error
App->>Services: add_service_keys()
App->>Services: warn_invalid_urls()
loop Stored services with keys
Services-->>App: Service id and url
App->>URLs: normalize_url(url)
URLs-->>App: Valid or InvalidURL
end
App->>Log: Warn invalid stored service ids
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #169 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 11 11
Lines 880 737 -143
==========================================
- Hits 880 737 -143 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
Hey - I've found 3 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="tests/test_access_control.py" line_range="980" />
<code_context>
- f"'{ALICE}' (previous roles: maintainer).",
- f"Roles on service '{service_id}' of '{BOB}' revoked by '{ALICE}'.",
+ resource = f"{BASE}/services/{service_id}"
+ assert _role_messages(caplog) == [
+ f"Role 'owner' on '{resource}' granted to user '{ALICE}' by user '{ALICE}'",
+ f"Role 'maintainer' on '{resource}' granted to user '{BOB}' by user "
</code_context>
<issue_to_address>
**INFO audit logs are not captured**
When the tests run with pytest's default WARNING log-capture level, `test_role_changes_logged` and `test_group_role_changes_logged` assert on INFO records, but neither sets the capture level to INFO. Under pytest's default WARNING capture level, `_role_messages(caplog)` omits those records and the assertions fail even when the role logging works correctly.
Set `caplog` to capture INFO in both tests before making the role-message assertions.
Also at `tests/test_access_control.py:1273`.
</issue_to_address>
### Comment 2
<location path="tests/test_access_control.py" line_range="862" />
<code_context>
+
+ def check(serviceId: str) -> bool:
+ """Check whether the service exists, deleting it on the second call."""
+ if next(calls) == 1:
+ deleted.append(True)
+ get_collection("services").delete_one({"id": service_id})
</code_context>
<issue_to_address>
**Delete-race tests skip rollback**
When either race test reaches `_put_role`'s initial `service_exists` check, `_put_role` invokes the patched check before `grant_role`; because the callback deletes the service on that first call, the request returns 404 without granting a role, so the tests pass without exercising FOCA's rollback.
Delete the service on the second `service_exists` call, after FOCA grants the role.
</issue_to_address>
### Comment 3
<location path="cloud_registry/ga4gh/registry/permissions.py" line_range="592-594" />
<code_context>
- )
- )
+ services = [
+ {"service_id": role.id, "role": role.role}
+ | ({"group": role.subject} if role.subject_type == "group" else {})
+ for role in list_subject_roles(services_path())
+ ]
remember_current_user(
</code_context>
<issue_to_address>
**`/me` roles can be unsorted**
When FOCA's `list_subject_roles()` yields roles in an order different from the promised ordering, `getMe()` returns `list_subject_roles()` in its iteration order and no longer sorts the results. If that helper returns roles in policy-storage order rather than the documented service-ID and user-before-group order, callers receive an incorrectly ordered `services` list.
Sort the `services` list by service identifier and put user roles before group roles before returning it.
</issue_to_address>
Sourcery assessment
Needs a human reviewer. 3 findings to address first, and if FOCA’s ownership helpers or the configured resource roles handle a grant or revocation incorrectly, owner or maintainer access could be persisted in policy rules for the wrong subject and remain after reverting. Correcting it would require identifying and removing any affected grants.
Blocking findings: tests/test_access_control.py:980, tests/test_access_control.py:862, cloud_registry/ga4gh/registry/permissions.py:594
The log tests relied on the app's log config for `INFO` records; set the capture level explicitly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes #157.
Summary
Ownership:
cloud_registry/ga4gh/registry/permissions.pynow grants, revokes and lists roles with FOCA 0.16's resource ownership helpers (add_owner,grant_role,revoke_roles,list_roles,list_subject_roles,is_admin) instead of its own last-owner rule, role replacement, existence re-check, admin check and/melisting. The app keeps its own controllers, so the API paths (/services/{serviceId}/permissions/{userId},/permissions/groups/{entitlement}) and response shapes stay the same. FOCA'sownership_serverisn't used: itsusers/+groups/layout would change the API, and the app also serves display names. The app keeps what FOCA leaves to apps:user_names);exists);Deleting a service still revokes its roles before and after the deletion (
remove_resource()).security.access_control.resource_roles(owner,maintainer) is set inconfig.yaml. A test checks it against the API'sRoleenum.Service clients: the app now refuses to start if FOCA's service clients are configured (
security.auth.service_clients,security.auth.on_behalf_of_header). FOCA's helpers would make the clients, or the users they name, owners, and the app's endpoints neither list nor manage those owners. Service-client ownership didn't work before this PR either; neither setting is set by default or exposed by the chart.URLs:
service.pychecks and normalizes URLs withfoca.utils.urls(normalize_url,check_url,check_url_fields). This removes about 300 lines of URL code, andidnais no longer a direct dependency. The allowed schemes are unchanged:httpsby default for service URLs, HTTP(S) for links, plusmailtoforcontactUrl. Service URLs still tolerate surrounding spaces, which are stripped before the FOCA helpers are called.New startup warning: services that already have a key but whose URLs FOCA now rejects are logged at startup, naming them (
warn_invalid_urls()).Docs updated:
resource_roles, the new400s, service clients;resource_filter()isn't used: the app has no owner-filtered listings, sinceGET /servicesis public.Behaviour changes (from FOCA's helpers)
Because of these, a few tests changed beyond their imports:
Audit log messages of role changes now come from FOCA (logger
foca.security.access_control.ownership) and name the service by its path, e.g.,Role 'maintainer' on '/ga4gh/registry/v1/services/ABC123' granted to user 'bob' by user 'alice' (previous roles: none).maintaineris only granted on services that have an owner (400otherwise). Admins grantownerfirst, e.g., on services stored before owners existed.Roles are not granted to groups while
group_mappingis set andkeep_group_subjectsis not (400). The base config setskeep_group_subjects, and the app already warned when it was unset.URL checks are stricter. These are now rejected:
<,|,\);127.1).Some
400messages changed, e.g., "must use one of these schemes: 'https'." instead of "must use an allowed scheme: 'https'.".Some tests still patch FOCA 0.16 internals to simulate failures and concurrent owner removals, which the public API can't produce; the test module's docstring says so. The tests of grants racing deletions go through the app's
service_exists()instead.Deployer notes
g2rules as the app did before (user:<sub>orgroup:<entitlement>, role,/ga4gh/registry/v1/services/<id>).security.auth.service_clientsorsecurity.auth.on_behalf_of_headeris set.Verification
All on Python 3.13 with FOCA 0.16.0:
ruff check .,ruff format --check .andmypy: clean.coverage run --source cloud_registry,scripts -m pytest(mongomock, with helm 3.22.1 on PATH for the chart tests): 906 passed, coverage 100%.MONGODB_TEST_URI=… pytestagainst MongoDB 7.0: 906 passed.mkdocs build --strict: OK.ast-grep scanandast-grep test: OK.Declined review findings
The app reads Connexion's request context for the display name (
_get_current_claims()), a coupling to Connexion internals. FOCA 0.16 has no public claims helper; a possible follow-up is to add one to FOCA.The commit trailer names Claude Opus 5.5. That is correct; the reviewer assumed another model.
The remaining tests that patch FOCA internals (
_check_other_owners,add_resource_role) are kept: there's no public way to simulate concurrent owner removals or failing rule writes. They are documented as tied to FOCA 0.16.Sourcery: the delete-race tests would delete the service on the first existence check. They delete it on the second, which is FOCA's
existscallback (count()starts at 0), and they fail if FOCA's revocation is disabled.Sourcery: sort
/meroles in the app. FOCA'slist_subject_roles()already returns them in the documented order, andtest_me_group_roleschecks it.Open questions
None.
🤖 Generated with Claude Code