Skip to content

feat: support several token issuers - #264

Merged
uniqueg merged 26 commits into
devfrom
feat/several-issuers
Oct 27, 2026
Merged

uniqueg merged 26 commits into
devfrom
feat/several-issuers

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 27, 2026 •

Copy link
Copy Markdown
Member

Summary

Deployments can trust several token issuers. With several, FOCA namespaces the subjects of users by issuer (<namespace>|<sub>; by default, the namespace is the issuer), so equal subjects of different issuers are different users, also as owners and maintainers of services and as the users who added service types.

Builds on #263 (#240, admin mode) and #261 (#226, FOCA 0.18), both merged; dev is merged in, so the diff shows only this PR. FOCA is pinned to the release 0.18.0 (from dev); v0.5.0 is tagged.

Closes #257

What changes

  • Permissions API: user identifiers may contain slashes (userId has format: path), encoded or not. Paths of the roles of groups (.../permissions/groups/<group>) stay routed to the group routes; groups, groups/ and groups\x as user identifiers are not found (404). Dot segments are still rejected (400). The policy owners-change-permissions covers nested paths (/permissions/*).
  • Migration: python -m cloud_registry.namespace_subjects <namespace> [--dry-run] namespaces the stored subjects of the issuer trusted so far (rules, service types, display names), for deployments that add an issuer without keeping that issuer's subjects bare. It refuses empty or unknown namespaces, and refuses to run while a trusted issuer keeps its subjects bare (namespace: ""), as the bare subjects are then that issuer's. It reloads the rules on running instances, also after partial runs. Configured rules with bare users are counted, not changed (a warning says to namespace them in the config). It can be run again.
  • Chart: issuers may be maps (FOCA's IssuerConfig: issuer, namespace, audience, claim_groups, userinfo_claims). A global audience is required only unless each issuer has an audience of its own (requireAudience, computed). Group mappings need a group claim of at least one issuer, as in FOCA: an issuer's claim_groups replaces the global one, unless unset or null.
  • Docs: configuration.md "Several token issuers" (namespacing, issuer settings, group claim values are not namespaced: take groups only from issuers that can't issue each other's groups, e.g., claim_groups: "" for the others). upgrading.md "Several token issuers": recommended namespace: "" for the issuer trusted so far, or the migration. access-control.md, the chart README and values.yaml point to it; the API reference lists the migration module.

Verification

  • Full suite on MongoDB 7.0.34 with Helm 3.19 (chart tests included), FOCA 0.18.0 from PyPI: 1652 passed, coverage 100% (after the Sourcery fixes).
  • ruff check, ruff format --check, mypy cloud_registry tests scripts: clean.
  • mkdocs build --strict: clean.
  • pre-commit run --all-files: passed.
  • Reviews: two rounds with the adversarial and quality reviewer subagents.
    • Round 1, fixed: the migration could move bare subjects to another issuer while one issuer keeps its subjects bare (medium; now refused); backslashes after groups in user identifiers; the chart's per-issuer group claims (now as in FOCA); clearer errors for empty namespaces; rules reloaded after partial runs; CLI errors on stderr; tests for groups paths and dot segments in namespaced identifiers; docs on the migration's prerequisites.
    • Sourcery, fixed: namespaces starting with groups/ are refused on startup; the migration namespaces subjects that contain the separator (e.g., auth0|123). Documented: running the migration while users do not change roles; the user rule also covers the roles of groups.
    • Round 2, fixed: a null claim_groups of an issuer means the global claim (as in FOCA); more precise test expectations; docs wording.

Declined review findings

  • Sourcery: serialize the migration with permission changes and display-name writes: documented instead (run it in a short maintenance window right after the rollout); locking the API for a one-off step would add a mechanism for a window of seconds.
  • Sourcery: keep the user rule from matching the roles of groups: keyMatch2 cannot exclude a subtree; the comment says to override both rules to restrict owners on groups.
  • Sourcery: duplicate rules stop the migration: not possible, as FOCA indexes rules uniquely by identifier only.
  • User identifiers starting with / are merged by Werkzeug's path converter and redirected (308). Namespaced identifiers start with an issuer URL or a validated namespace, and bare subjects come from identity providers, so this isn't fixed: turning off merge_slashes would change the routing of all paths.
  • Exact pydantic messages for invalid namespaces in tests: the tests match the field name, as the messages are FOCA's (pydantic's) and may change wording.
  • Separate commit messages per review fix: the PR is squash-merged.

Notes

  • foca-common 0.2.0's checkAudience requires a global audience. This chart works around that by computing requireAudience (false if each issuer is a map with its own audience). A fix in foca-common may be wanted.

🤖 Generated with Claude Code

uniqueg and others added 23 commits October 26, 2026 17:09
Validation details come from FOCA (exceptions.validation_details), and
problem() builds on FOCA's problem_response(), adding only the codes of
conflicts. Tests use locked_enforcer() instead of the removed
get_enforcer().

Refs #226

Co-Authored-By: Claude Opus 5.5 <[email protected]>
FOCA checks the group settings, requires admins
(security.access_control.require_admin, moved from
custom.access_control.require_admin), warns of placeholders in the
service info and refuses service clients
(require_no_service_clients()); the app's own copies are removed. The
chart reads require_admin from its new place and rejects the old key.

Refs #226

Co-Authored-By: Claude Opus 5.5 <[email protected]>
server.public_url replaces custom.endpoints.service; the app refuses to
start without it, and FOCA's get_public_url() builds the Location
header. The chart sets it from hostName or the new value publicUrl and
rejects the old key. FOCA's get_custom_config() replaces the app's.

Refs #226

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The image loads foca.gunicorn_config (same settings);
cloud_registry.gunicorn_config is removed. Tests keep the checks of
the image command and its health check port.

Refs #226

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Refs #226

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Chart docs name the required image version, tests render publicUrl,
docstrings and the dev overlay are clearer.

Refs #226

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Admins act as admins only in requests that ask for the role in the
header X-Request-Roles (FOCA opt-in roles, opt_in_roles: [admin] in
the base config). GET /me reports whether the user may switch to
admin mode (admin_available). The duplicate check passes the header
on to the read check, so admins in admin mode learn the registered
service. Document the header for clients and scripts, and the
upgrade (stored rules granting admin).

Closes #240

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Pin FOCA and its development image to 6214325, which allows opt-in
roles that no group is mapped to (elixir-cloud-aai/foca#530), so
that configs without an admin mapping still load with admin mode.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
GET /me reports admin_available whenever admin is true, e.g., without
the opt-in. Test each admin operation with and without admin mode,
the permissions API, Vary and the opt-out; clarify the upgrade notes
(GET /me, configured admin rules), the config comment and the docs on
making users admins.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The Docker Compose config turns admin mode off, as it maps no admin
group. Describe when admin is true without the header, and when
configured rules count as admins; tidy a docstring and test constants.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Trust several token issuers: FOCA namespaces the subjects of users by
issuer, so user identifiers may contain slashes. The permissions API
accepts them (format: path), still routing group paths to the group
routes, and the owners policy covers nested paths.

Add python -m cloud_registry.namespace_subjects, which namespaces the
stored subjects of an issuer (rules, service types, user names), for
deployments that add an issuer without keeping its subjects bare.

Refs #257

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Accept issuer maps (FOCA IssuerConfig), count their group claims for
group mappings, and require a global audience only unless each issuer
has one.

Refs #257

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes #257

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Refuse to namespace bare subjects while an issuer keeps its subjects
bare (they are that issuer's), and empty namespaces with a clear
message; reload the rules also after partial runs; print errors to
stderr. Treat backslashes as slashes after groups in user ids. Mirror
FOCA's per-issuer group claims in the chart. Add tests and docs.

Refs #257

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	Dockerfile
#	cloud_registry/config.yaml
#	cloud_registry/ga4gh/registry/permissions.py
#	config.dev.yaml
#	deployment/README.md
#	docs/upgrading.md
#	pyproject.toml
#	tests/test_image_command.py
In the chart, a null claim_groups of an issuer means the global claim,
as in FOCA. Pin more test expectations and clarify the migration docs.

Refs #257

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@sourcery-ai

sourcery-ai Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR adds end-to-end support for multiple token issuers by adopting FOCA's issuer-namespaced user identities, updating permission routing and Helm validation, migrating pre-existing bare subjects safely, and documenting deployment and upgrade procedures.

Sequence diagram for namespaced user permissions

sequenceDiagram
    actor User
    participant Issuer as TokenIssuer
    participant Registry as CloudRegistry
    participant Policy as PermissionStore

    User->>Issuer: Obtain token
    User->>Registry: GET /me
    Registry-->>User: user_id = namespace|sub
    User->>Registry: PUT /services/{id}/permissions/{userId}
    Registry->>Policy: Store role for namespaced user_id
    Policy-->>Registry: Role stored
Loading

Flow diagram for subject migration

flowchart TD
    Start([Run namespace_subjects]) --> Validate[check_namespace]
    Validate -->|valid trusted namespace| Rules[_namespace_rules]
    Rules --> Types[_namespace_service_types]
    Types --> Names[_namespace_user_names]
    Names --> Reload[mark_changed]
    Reload --> Done([Stored bare subjects namespaced])
    Validate -->|invalid or bare issuer remains| Error([Fail without migration])
    Start -->|--dry-run| Count[Count bare subjects only]
    Count --> DoneDry([Report counts])
Loading

File-Level Changes

Change Details Files
Add issuer-aware user identity handling across authentication, permissions, service types, and display names.
  • Support FOCA issuer configurations with per-issuer namespaces and settings.
  • Keep equal subjects from different issuers distinct, including ownership, maintenance, service-type creators, and display names.
  • Extend permission user paths to accept slash-containing identifiers while preserving group-route behavior and rejecting dot segments.
cloud_registry/api/additions.openapi.yaml
cloud_registry/config.yaml
cloud_registry/ga4gh/registry/permissions.py
tests/conftest.py
tests/test_issuers.py
Provide a migration for data created before issuer namespacing was enabled.
  • Rewrite bare subjects in stored policy rules, service types, and user names, while preserving already namespaced data.
  • Support dry runs, repeatable and partial-run behavior, configured-rule warnings, validation of trusted namespaces, and reloading running policy adapters.
  • Expose the migration as a Python module and document upgrade sequencing.
cloud_registry/namespace_subjects.py
docs/upgrading.md
docs/reference.md
tests/test_namespace_subjects.py
Update Helm validation and deployment configuration for multiple issuer formats.
  • Accept issuer URLs or FOCA IssuerConfig maps with per-issuer audience, namespace, group-claim, and userinfo settings.
  • Compute whether a global audience is required and validate that group mappings have a usable claim from at least one issuer.
  • Update chart comments, deployment guidance, and validation tests.
deployment/README.md
deployment/templates/_helpers.tpl
deployment/values.yaml
tests/test_config.py
Document configuration and identity semantics for deployments trusting several issuers.
  • Describe namespaced user identifiers, URL encoding, issuer-specific settings, and non-namespaced group claims.
  • Link the multi-issuer configuration from access-control and deployment documentation.
  • Document the recommended bare-subject upgrade path and the migration alternative.
docs/configuration.md
docs/access-control.md
docs/upgrading.md
deployment/README.md

Assessment against linked issues

Issue Objective Addressed Explanation
#257 Support multiple token issuers while distinguishing users with equal subjects by issuer, including in service ownership, maintenance, service-type creation, and issuer-specific authentication settings. ✅
#257 Allow namespaced user identifiers containing slashes to be used to grant and revoke roles through the permissions API, without breaking group-permission routing. ✅
#257 Provide and test an upgrade path for existing deployments, covering stored subjects and documenting issuer configuration, safe namespace choices, and the fact that group claims are not namespaced. ✅

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 27, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #264    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           19        20     +1     
  Lines         1866      1976   +110     
==========================================
+ Hits          1866      1976   +110     

☔ 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 27, 2026 15:14

@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 6 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="cloud_registry/namespace_subjects.py" line_range="151" />
<code_context>
+            and value.startswith(prefix)
+            and _is_bare(value[len(prefix) :])
+        }
+        collection.update_one({"_id": rule["_id"]}, {"$set": changed})
+    return rewritten, configured
+
</code_context>
<issue_to_address>
**Revoked roles reappear after migration**

When an owner revokes a namespaced user's role on a service while the migration has not yet rewritten that user's bare rule, `_delete_roles()` finds no role for the namespaced user and returns `404`; the migration then rewrites the still-stored bare rule to that user, leaving the role granted after the caller's revocation attempt.

Serialize migration rule rewrites with permission changes, or prevent permission mutations until the migration has completed.
</issue_to_address>

### Comment 2
<location path="cloud_registry/config.yaml" line_range="128" />
<code_context>
+            # users (namespaced by issuer, with several issuers) and groups
+            # may contain slashes; the first rule also covers the roles of
+            # groups, the second one is kept for overrides of either
+            owners-change-permissions: [p, owner, "/ga4gh/registry/v1/services/:id/permissions/*", "(PUT)|(DELETE)"]
             owners-change-group-permissions: [p, owner, "/ga4gh/registry/v1/services/:id/permissions/groups/*", "(PUT)|(DELETE)"]
             maintainers-update-services: [p, maintainer, "/ga4gh/registry/v1/services/:id", PUT]
</code_context>
<issue_to_address>
**Group policy overrides stop working**

When a deployment removes or narrows `owners-change-group-permissions` to restrict owner access to group permissions, the broad `owners-change-permissions` rule matches group-permission paths as well as user paths, and the model combines matching allow rules with an `some(where allow)` effect. Removing or narrowing `owners-change-group-permissions` therefore no longer prevents owners from changing group permissions, so deployments cannot use that named rule to disable or restrict group grants while retaining user grants.

Keep the user-permission rule from matching the reserved `permissions/groups/` subtree, or provide an explicit deny/override mechanism for the group-permission policy.
</issue_to_address>

### Comment 3
<location path="cloud_registry/ga4gh/registry/permissions.py" line_range="605" />
<code_context>
+            or starts with `groups/`.
     """
-    if userId == "groups":
+    if userId.replace("\\", "/").split("/", 1)[0] == "groups":
         raise NotFound

</code_context>
<issue_to_address>
**Namespaced users cannot change roles**

When a trusted issuer uses a valid namespace beginning with `groups/`, `_check_user_id()` rejects the resulting user IDs because their first path segment is `groups`, so the permissions API returns 404 instead of letting callers grant or revoke those users’ roles.

Distinguish group IDs from valid issuer-namespaced user IDs when checking the reserved `groups/` path.

Also at `cloud_registry/ga4gh/registry/permissions.py:606`, `cloud_registry/namespace_subjects.py:92`.
</issue_to_address>

### Comment 4
<location path="cloud_registry/namespace_subjects.py" line_range="151" />
<code_context>
+            and value.startswith(prefix)
+            and _is_bare(value[len(prefix) :])
+        }
+        collection.update_one({"_id": rule["_id"]}, {"$set": changed})
+    return rewritten, configured
+
</code_context>
<issue_to_address>
**Migration stops on duplicate rules**

When a namespaced user already has the same policy rule as the bare user being migrated, `_namespace_rules()` updates the bare rule to the namespaced subject, and MongoDB raises `DuplicateKeyError`; the migration stops with some roles still stored under the bare ID.

Handle an existing identical namespaced rule as a migration duplicate instead of allowing the update to abort.
</issue_to_address>

### Comment 5
<location path="cloud_registry/namespace_subjects.py" line_range="67" />
<code_context>
+    Returns:
+        Whether the subject is a string without the separator of namespaces.
+    """
+    return isinstance(subject, str) and NAMESPACE_SEPARATOR not in subject
+
+
</code_context>
<issue_to_address>
**Legacy subjects lose associated data**

When a legacy subject contains the namespace separator `|`, `_is_bare()` treats the subject as already namespaced, so the migration skips its policy rules, service-type ownership, and display names; the new namespaced identity no longer matches those records.

Determine whether a subject is already namespaced without treating every occurrence of `|` as proof that it is.

Also at `cloud_registry/namespace_subjects.py:135`.
</issue_to_address>

### Comment 6
<location path="cloud_registry/namespace_subjects.py" line_range="204" />
<code_context>
+            continue
+        user_id = f"{namespace}{NAMESPACE_SEPARATOR}{name['user_id']}"
+        try:
+            collection.update_one({"_id": name["_id"]}, {"$set": {"user_id": user_id}})
+        except DuplicateKeyError:
+            collection.delete_one({"_id": name["_id"]})
</code_context>
<issue_to_address>
**Display-name requests fail during migration**

When a namespaced user calls `GET /me` for a service while the migration rewrites that user's existing bare display-name row, the migration changes a bare row to the namespaced unique key while `remember_current_user()` upserts that same key; if the upsert's lookup precedes the migration update but its insert follows it, MongoDB raises `DuplicateKeyError` and the request fails.

Coordinate display-name writes with the migration or retry the upsert after a duplicate-key error.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 6 findings to address first, and issuer namespacing changes which identity matches stored owner and maintainer rules, and the migration rewrites those policy subjects and may delete duplicate display-name records. Reverting the code does not automatically restore those stored values, so a mistaken namespace or migration needs deliberate repair.

Blocking findings: cloud_registry/namespace_subjects.py:151, cloud_registry/config.yaml:128, cloud_registry/ga4gh/registry/permissions.py:605, cloud_registry/namespace_subjects.py:151, cloud_registry/namespace_subjects.py:67, and 1 more


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

Comment thread cloud_registry/namespace_subjects.py Resolved
Comment thread cloud_registry/config.yaml Resolved
Comment thread cloud_registry/namespace_subjects.py Resolved
Comment thread cloud_registry/namespace_subjects.py Resolved
Comment thread cloud_registry/namespace_subjects.py Resolved
Refuse to start if the namespace of a trusted issuer starts with
groups/, as its users could not be managed via the permissions API.
The migration takes only subjects that start with a configured
namespace as namespaced, as subjects may contain the separator (e.g.,
auth0|123). Document how to run the migration and the policy rules
for the roles of groups.

Refs #257

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 1503b69 into dev Oct 27, 2026
19 checks passed
@uniqueg
uniqueg deleted the feat/several-issuers branch October 27, 2026 18:31
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.

feat: support several token issuers

1 participant