Skip to content

refactor: use FOCA's ownership and URL helpers - #169

Merged
uniqueg merged 7 commits into
devfrom
refactor/foca-ownership-urls
Oct 22, 2026
Merged

uniqueg merged 7 commits into
devfrom
refactor/foca-ownership-urls

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Closes #157.

Summary

  • Ownership: cloud_registry/ga4gh/registry/permissions.py now 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 /me listing. The app keeps its own controllers, so the API paths (/services/{serviceId}/permissions/{userId}, /permissions/groups/{entitlement}) and response shapes stay the same. FOCA's ownership_server isn't used: its users/ + groups/ layout would change the API, and the app also serves display names. The app keeps what FOCA leaves to apps:

    • display names (user_names);
    • the check that the service exists (passed as exists);
    • which groups users may grant roles to.

    Deleting a service still revokes its roles before and after the deletion (remove_resource()).

  • security.access_control.resource_roles (owner, maintainer) is set in config.yaml. A test checks it against the API's Role enum.

  • 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.py checks and normalizes URLs with foca.utils.urls (normalize_url, check_url, check_url_fields). This removes about 300 lines of URL code, and idna is no longer a direct dependency. The allowed schemes are unchanged: https by default for service URLs, HTTP(S) for links, plus mailto for contactUrl. 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:

    • access control: FOCA helpers, resource_roles, the new 400s, service clients;
    • configuration and operations (audit logs now come from FOCA's logger);
    • the API and upgrading pages, the spec description and the 0.3.0 release notes (stricter URL checks).
  • resource_filter() isn't used: the app has no owner-filtered listings, since GET /services is 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).

  • maintainer is only granted on services that have an owner (400 otherwise). Admins grant owner first, e.g., on services stored before owners existed.

  • Roles are not granted to groups while group_mapping is set and keep_group_subjects is not (400). The base config sets keep_group_subjects, and the app already warned when it was unset.

  • URL checks are stricter. These are now rejected:

    • ASCII characters that must be percent-encoded (e.g., <, |, \);
    • hosts with percent-encodings or empty labels;
    • IPv4 addresses not in dotted-decimal form (e.g., 127.1).

    Some 400 messages 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

  • No data migration is needed. Stored policy rules stay valid: FOCA's helpers read and write the same g2 rules as the app did before (user:<sub> or group:<entitlement>, role, /ga4gh/registry/v1/services/<id>).
  • Keys of stored services (used for duplicate detection) don't change for URLs that were valid before and still are. FOCA's normalization gives the same result; the reviewer compared about 40 tricky URLs. Some URLs are now invalid:
    • Services without a key that have such a URL make the app refuse to start, naming them, as before.
    • Services with a key that have such a URL are still served and are now warned of at startup. They can only be updated with a valid URL. Fix them as described under "Stored services" on the Upgrading page.
  • Service clients: the app refuses to start if security.auth.service_clients or security.auth.on_behalf_of_header is set.
  • Audit tooling that parses logs must match FOCA's message format and logger (see above).

Verification

All on Python 3.13 with FOCA 0.16.0:

  • ruff check ., ruff format --check . and mypy: 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=… pytest against MongoDB 7.0: 906 passed.
  • mkdocs build --strict: OK.
  • ast-grep scan and ast-grep test: OK.
  • The grant race tests fail if FOCA doesn't revoke a role granted on a deleted service. This was checked with a plugin that disables the revocation.
  • CI: all checks pass (tests with mongomock and MongoDB 7.0, static analysis, Helm chart, Docker Compose, docs, Read the Docs, codecov patch and project).

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 exists callback (count() starts at 0), and they fail if FOCA's revocation is disabled.

  • Sourcery: sort /me roles in the app. FOCA's list_subject_roles() already returns them in the documented order, and test_me_group_roles checks it.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 6 commits October 22, 2026 21:02
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]>
@sourcery-ai

sourcery-ai Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Refactors 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 changes

sequenceDiagram
    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
Loading

Sequence diagram for startup validation and legacy URL warnings

sequenceDiagram
    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
Loading

File-Level Changes

Change Details Files
Delegates service role ownership, listing, administration, and race-safe grant/revoke behavior to FOCA 0.16 while preserving the registry’s controllers and API contracts.
  • Replaced custom last-owner, role-replacement, existence re-check, and /me logic with FOCA ownership helpers.
  • Kept application-specific display-name persistence, service-existence callbacks, group-grant restrictions, and deletion cleanup.
  • Configured resource_roles and rejected unsupported FOCA service-client settings at startup.
  • Updated permission tests and audit-log expectations for FOCA behavior and logger output.
cloud_registry/ga4gh/registry/permissions.py
cloud_registry/ga4gh/registry/server.py
cloud_registry/app.py
cloud_registry/config.yaml
tests/test_access_control.py
tests/test_app.py
tests/test_config.py
docs/access-control.md
docs/operations.md
docs/configuration.md
Replaces the registry’s URL validation and normalization implementation with FOCA URL utilities, including compatibility handling for previously stored invalid URLs.
  • Uses FOCA normalization and validation for service URLs and link fields while retaining allowed schemes and service-URL whitespace compatibility.
  • Removes the direct idna dependency and approximately 300 lines of local URL parsing and validation code.
  • Adds startup warnings for keyed services whose stored URLs are now invalid, while continuing to serve them.
  • Expands API documentation, upgrade guidance, and tests for stricter host and percent-encoding checks.
cloud_registry/ga4gh/registry/service.py
cloud_registry/api/additions.openapi.yaml
pyproject.toml
tests/ga4gh/registry/test_service.py
docs/api.md
docs/releases/0.3.0.md
docs/upgrading.md

Assessment against linked issues

Issue Objective Addressed Explanation
#157 Replace the app’s service ownership and role-management logic with FOCA’s ownership helpers while preserving the permissions API and its behavior. ✅
#157 Replace the app’s URL validation and normalization logic with FOCA’s helpers, preserving the configured HTTPS-only option and documenting or handling compatibility effects of stricter validation. ✅
#157 Remove duplicated or unused ownership and URL logic and retain full test coverage. ✅

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (b648b19) to head (bcca338).

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review October 22, 2026 19:49

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread tests/test_access_control.py Resolved
Comment thread tests/test_access_control.py Resolved
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]>
@uniqueg
uniqueg merged commit 8d06ee8 into dev Oct 22, 2026
12 checks passed
@uniqueg
uniqueg deleted the refactor/foca-ownership-urls branch October 22, 2026 19:58
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

refactor: use FOCA's ownership and URL helpers

1 participant