Skip to content

feat: invite users to services by link - #274

Merged
uniqueg merged 7 commits into
devfrom
feat/invitations
Oct 28, 2026
Merged

uniqueg merged 7 commits into
devfrom
feat/invitations

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

Summary

Owners can invite users to their services by link without knowing their sub. An owner creates an invitation for a role and sends the link through any channel. The colleague logs in and accepts it, which grants the role to their own identifier. No email addresses are involved. This follows the design in the issue, as decided in the 2026-10-20 review: point 7 B for invitations and point 9 for display names.

Closes #101

Merge only after the v0.6.0 tag. This is part of v1.0.0-rc1, and the upgrade notes go into a new "From 0.6.0" section.

What changes

  • Endpoints (additions spec, tag cloud-registry). Owners and admins can use these:

    • POST /services/{serviceId}/invitations with {"role": "owner" | "maintainer"}. It returns 201 with the invitation and its one-time token. This is the only response that contains the token.
    • GET /services/{serviceId}/invitations lists the open and accepted invitations that haven't expired, without tokens. Accepted ones include accepted: user_id, plus name and email if the identity provider releases them, and accepted_at.
    • DELETE /services/{serviceId}/invitations/{invitationId} revokes an open invitation. Accepted ones return 409 with code invitation-accepted; revoke the role instead.

    Any authenticated user can call POST /invitations/accept with {"token": ...}. The token is in the body so that it stays out of access logs. Accepting grants the role like PUT .../permissions/{userId} and replaces any other role the user has on the service. It also stores the user's display name for the service.

  • Storage. A new collection, invitations, holds only the SHA-256 hash of each token (secrets.token_urlsafe(32)), never the token itself. Each invitation has an expiry, by default 7 days (custom.access_control.invitations.expiry_days), and a TTL index on expires_at; reads skip expired invitations until MongoDB deletes them.

  • Single use. Accepting claims the invitation atomically with find_one_and_update on an open, unexpired invitation. If the role can't be granted (e.g. last-owner, the service being renamed, or the service deleted), the claim is released.

  • Service lifecycle. Invitations are deleted with the roles on their service, i.e. when the service is deleted or stale roles are cleared, and they move with the roles when the service is renamed, including resumed renames.

  • Policies in config.yaml: owners-manage-invitations (GET, POST), owners-revoke-invitations (DELETE) and accept-invitations (*). Maintainers and other users get 403.

  • Docs:

    • access-control.md has a new "Invitations" section: links with the token in the URL fragment, single use, expiry, creators, identifiers, listing and revoking, the limit, storage, the forwarding risk, and the options.
    • api.md lists the endpoints and the conflict codes.
    • configuration.md describes the options.
    • upgrading.md has a new "From 0.6.0" section: a new collection and indexes, and three new policy rules that overlays which list the policies must add.

Beyond the issue (from the reviews)

  • Creators. Each invitation records how its creator was allowed to create it: as an admin, as an owner, or as a member of an owner group. Accepting checks, while the service is locked, that the creator is still an owner. If not, the invitation is deleted and the request returns 404. Without this, removed owners could regain the role with invitations they had created earlier.
    • Admins are trusted, because their admin groups can't be checked without their token. The docs say how to find the invitations of a removed admin.
    • Creators who were owners through a group and have since left it can't accept their own invitations.
  • Limit. A service can have at most custom.access_control.invitations.max_per_service invitations that haven't expired, open or accepted. The default is 20; null means no limit. Above the limit, creating returns 409 with code invitations-limit. Accepted invitations count so that owners can't grow the collection by accepting their own invitations.
  • Identifiers. Users whose roles the permissions API couldn't revoke can't accept invitations (400). These are identifiers that are groups, start with groups/ or a slash, or contain ./.. segments.
  • Privacy. A user's name and email are removed from the invitations they accepted when their roles on the service are revoked, just as display names are removed with the role.
  • Refactor. put_role() in permissions.py now takes the role as an argument, plus an optional check that runs inside the lock. The helpers require_subject() and get_current_claims() are now public.

Verification

  • Full suite on MongoDB 7.0.34 (own instance on its own port, removed afterwards): 1449 passed, 255 skipped (Helm chart tests skip without Helm). This includes a threaded test of 8 concurrent acceptances of one invitation (one 200, seven 409). Coverage: 100%.
  • pre-commit run --all-files (ruff, mypy, semgrep, ast-grep, gitleaks, actionlint): passed.
  • mkdocs build --strict: passed.
  • Not run locally: the Helm chart tests, because Helm isn't installed. The chart is unchanged; CI runs them.
  • Reviews: two rounds with the adversarial and quality reviewer subagents.
    • Round 1, fixed: removed owners regaining the role with their own invitations (high); a limit bypass by accepting your own invitations (medium); identifiers that the permissions API can't manage; names and emails outliving the role; missing upgrade and configuration docs (medium); smaller cleanups.
    • Round 2, fixed: the creator check now runs inside the service lock, so renames don't delete valid invitations; group creators who left the group; docs for removed admins.
  • CI: all checks pass. The first run's "Scan image" failure (msgpack CVE in the base image, also failing on dev) was fixed on dev by ci: accept msgpack CVE vendored by pip #273, which is merged in.
  • Sourcery: three threads (served names of revoked users if the cleanup fails; a creator revoked while the invitation is stored; a docstring), all fixed in d8e1712, answered and resolved. CI after the fixes: all checks pass, including CI passed and Sourcery.

Declined review findings

  • A revoke that runs at the same moment as an acceptance can still be followed by the grant. The service lock is shared between changes, and revokes don't exclude each other either; this is the same for PUT .../permissions. Each invitation gives exactly one try, and owners see who accepted and can revoke the role.
  • The repeated Args/Attributes in the new config model's docstring: this is the repo's convention.

Notes

  • The issue's decision that accepting replaces any other role still applies. An owner who accepts a maintainer invitation is downgraded, unless they are the last owner (409).
  • After merging, the UI issue for invitations can be posted to cloud-registry-ui. It is listed in to-post.md as D-10, to be posted once feat: invite users to services by link #101 is in the backend.

🤖 Generated with Claude Code

Summary by Sourcery

Enable secure, configurable link-based invitations for granting service roles to authenticated users.

New Features:

  • Add link-based service invitations that let owners and admins invite users to owner or maintainer roles without knowing their identifiers.
  • Add invitation listing, revocation, and authenticated acceptance endpoints with single-use tokens and acceptance details.

Bug Fixes:

  • Protect invitations from being used after their creator loses the authority that created them.
  • Remove stored acceptance names and email addresses when the accepted user's service roles are revoked.

Enhancements:

  • Store only hashed invitation tokens with configurable expiry and per-service limits, and integrate invitations with service deletion and renaming.
  • Refactor permission role assignment to support invitation acceptance checks within service locks.

Documentation:

  • Document invitation workflows, policies, configuration, API conflicts, and upgrade requirements.

Tests:

  • Add comprehensive invitation coverage, including expiry, limits, authorization, lifecycle behavior, creator validation, and concurrent acceptance.

uniqueg and others added 4 commits October 28, 2026 06:37
Owners (and admins) create an invitation to a service for a role
(POST /services/{serviceId}/invitations), which returns a one-time
token; the invited user accepts it (POST /invitations/accept), which
grants the role to their own identifier, as PUT .../permissions/{userId}
would. Owners list the invitations with who accepted them, and revoke
open ones (GET, DELETE).

- Collection `invitations` with the SHA-256 hash of the token only,
  expiry (default 7 days, `custom.access_control.invitations
  .expiry_days`), TTL index, and acceptance (user, name, email if
  released, time).
- Accepting claims the invitation atomically (single use), and
  releases it if the role can't be granted (e.g., last owner).
- At most 20 open invitations per service by default
  (`max_open_per_service`, `null` for no limit; 409
  `invitations-limit`); accepted ones: 409 `invitation-accepted`.
- Invitations are deleted with the roles of a service and move with
  them on renames.
- Policies for the new paths; maintainers and other users get 403.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add the "Invitations" section to the access control docs: links with
the token in the fragment, single use, expiry, listing and revoking,
the limit per service, storage, the risk of forwarded links, and the
options; link it from "Roles on services".

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review findings on the invitations:

- Invitations store how their creator was allowed to create them
  (admin, owner, or member of an owner group) and are deleted instead
  of accepted once that owner role is gone, so that removed owners
  can't regain the role with their own invitations.
- The limit counts all invitations until they expire, also accepted
  ones, so that owners can't grow the collection by accepting their
  own invitations (`max_open_per_service` -> `max_per_service`).
- Users whose roles the permissions API couldn't revoke (`groups/...`,
  leading slash, dot segments) can't accept invitations (400).
- Names and email addresses in accepted invitations are removed with
  the user's roles on the service.
- Docs: configuration and upgrade notes, accept description; smaller
  cleanups (shared filters, return type, role read once).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Second review round:

- Check the creator of an invitation while the service is locked
  (`put_role(check=...)`), so that a rename, which moves the roles
  before the invitations, can't make a valid invitation look orphaned
  and get it deleted; the acceptance fails and releases it instead.
- Creators who were owners through a group and left it can't accept
  their own invitations (their token shows their groups); others can,
  while the group is owner.
- Docs: how to find the invitations of a removed admin.

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

sourcery-ai Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces secure, link-based service invitations with one-time atomic acceptance, configurable expiry and limits, creator-authority safeguards, lifecycle-aware storage, new policies and API documentation, and extensive concurrency and integration tests.

Sequence diagram for link-based service invitation acceptance

sequenceDiagram
    actor Owner
    actor User
    participant API
    participant Invitations
    participant Permissions

    Owner->>API: postServiceInvitation
    API->>Invitations: insert_one token_hash
    Invitations-->>API: invitation and token
    API-->>Owner: 201 InvitationCreated with token
    Owner->>User: Send invitation link
    User->>API: acceptInvitation with token
    API->>Invitations: find_one_and_update open unexpired invitation
    Invitations-->>API: atomically claimed invitation
    API->>Permissions: put_role(service_id, user_id, user, role, check)
    Permissions-->>API: role granted
    API->>Permissions: remember_current_user
    API-->>User: 200 ServiceRole
Loading

State diagram for invitation lifecycle

stateDiagram-v2
    [*] --> Open: postServiceInvitation
    Open --> Accepted: acceptInvitation
    Open --> Revoked: deleteServiceInvitation
    Open --> Expired: expires_at reached
    Accepted --> Expired: expires_at reached
    Open --> Deleted: service deleted or creator loses authority
    Accepted --> Deleted: service deleted
    Revoked --> [*]
    Expired --> [*]
    Deleted --> [*]
Loading

File-Level Changes

Change Details Files
Adds owner/admin invitation management and authenticated link acceptance with role replacement and one-time semantics.
  • Defines create, list, revoke, and accept endpoints with OpenAPI schemas and stable conflict codes.
  • Implements token generation, SHA-256-only storage, expiry filtering, TTL cleanup, service limits, and atomic acceptance claims.
  • Records acceptance identity metadata and removes it when service roles are revoked.
  • Adds owner/group/admin creator validation so invitations cannot outlive the creator’s authority.
  • Adds invitation-specific access-control policies and integrates authorization with the existing permissions lock and role-grant flow.
cloud_registry/api/additions.openapi.yaml
cloud_registry/config.yaml
cloud_registry/ga4gh/registry/invitations.py
cloud_registry/ga4gh/registry/permissions.py
cloud_registry/service_models/custom_config.py
Integrates invitation data with service deletion, stale-role cleanup, and service renames.
  • Deletes invitations when a service and its roles are removed.
  • Moves invitations during normal and resumed renames and removes them when an interrupted rename cannot be completed.
  • Keeps acceptance creator checks inside the service lock to avoid races with renames and role changes.
cloud_registry/ga4gh/registry/permissions.py
cloud_registry/ga4gh/registry/rename.py
Documents the invitation API, security model, configuration, and upgrade requirements.
  • Explains fragment-based links, token privacy, forwarding risk, expiry, single use, creator rules, limits, identifiers, and listing/revocation behavior.
  • Documents endpoints, conflict codes, invitation options, collection/index creation, and policy overlay changes for upgrades from 0.6.0.
docs/access-control.md
docs/api.md
docs/configuration.md
docs/upgrading.md
Adds comprehensive coverage for invitation behavior and concurrency.
  • Tests endpoint authorization, validation, token hashing, TTL indexes, expiry, revocation, limits, role replacement, and display metadata.
  • Tests concurrent acceptance, failed-claim release, creator authority changes, group/admin creators, service lifecycle, renames, and manageable identifiers.
tests/test_invitations.py
tests/test_access_control.py

Assessment against linked issues

Issue Objective Addressed Explanation
#101 Provide invitation creation, listing, revocation, and acceptance endpoints with the specified role and access-control rules. ✅
#101 Store invitations securely and enforce expiry, revocation, and atomic single-use acceptance that grants the role to the accepting user's identifier. ✅
#101 Track acceptance identity for owners, handle invitations through service deletion and renaming, and document and test the feature. ✅

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

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (58fdb66) to head (050af1e).

Additional details and impacted files
@@            Coverage Diff             @@
##               dev      #274    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           20        21     +1     
  Lines         2008      2179   +171     
==========================================
+ Hits          2008      2179   +171     

☔ 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 28, 2026 07:02

@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="cloud_registry/ga4gh/registry/permissions.py" line_range="601-604" />
<code_context>
             _forget_names(serviceId, subject)
+            # the user's name and email address in the invitations they
+            # accepted, as names are deleted with the role
+            get_collection(INVITATIONS).update_many(
+                {"service_id": serviceId, "accepted.user_id": subject},
+                {"$unset": {"accepted.name": "", "accepted.email": ""}},
+            )


</code_context>
<issue_to_address>
**Revoked users’ details remain visible**

When the worker crashes or the invitation update fails after role revocation, `_delete_roles`/`revoke_roles` removes the role before the invitation update clears accepted names and email addresses. The details remain visible, and a retry can return not found without retrying the cleanup.

Make the accepted-detail cleanup reliably retryable after role revocation.
</issue_to_address>

### Comment 2
<location path="cloud_registry/ga4gh/registry/invitations.py" line_range="335" />
<code_context>
+        "expires_at": created_at + timedelta(days=expiry_days),
+    }
+    collection = get_collection(INVITATIONS)
+    collection.insert_one(document)
+    # the service may have been deleted (with its invitations) meanwhile
+    if not service_exists(serviceId):
</code_context>
<issue_to_address>
**Revoked owners create unusable invitations**

When the creator loses their owner role after `_created_as` returns but before the invitation is inserted, `postServiceInvitation` inserts the invitation after `_created_as` checks the creator's owner role, without holding the service lock. If that role is revoked before insertion, creation still returns a token, but acceptance finds the creator is no longer an owner, deletes the invitation, and returns `404`.

Perform the owner check and insertion while holding the service lock, or recheck under that lock before returning the created invitation.
</issue_to_address>

### Comment 3
<location path="cloud_registry/ga4gh/registry/invitations.py" line_range="300" />
<code_context>
+    Returns:
+        The invitation (cf. `_serve()`), with its token (`token`), only
+        returned here; with status `201`. Or an error response: `409` if the
+        service has as many open invitations as allowed.
+
+    Raises:
</code_context>
<issue_to_address>
**Limit description excludes accepted invitations**

When the service has accepted but unexpired invitations, `postServiceInvitation`'s docstring describes the limit as counting open invitations, but `_check_limit` counts every unexpired invitation, including accepted ones. Maintainers relying on this controller contract will misread why creation returns `409`.

Describe the limit in the docstring as applying to all unexpired invitations, open or accepted.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 2 findings to address first, and anyone who obtains an invitation token can accept it and gain the selected service role, including owner access; a leaked or misdirected link can therefore expose service data or control. Reverting removes the invitation flow but does not undo granted roles or access that already occurred, so affected roles must be revoked explicitly.

Blocking findings: cloud_registry/ga4gh/registry/permissions.py:604, cloud_registry/ga4gh/registry/invitations.py:335


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

uniqueg and others added 2 commits October 28, 2026 08:19
Recheck the creator after storing an invitation and delete it if the
role was revoked meanwhile. Serve the name and email address of users
who accepted an invitation only while they have a role on the service.
Describe the invitation limit precisely.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts:
#	cloud_registry/ga4gh/registry/permissions.py
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: invite users to services by link

1 participant