Skip to content

feat: keep expired invitations for a set time - #335

Merged
uniqueg merged 4 commits into
devfrom
feat/keep-expired-invitations
Nov 3, 2026
Merged

uniqueg merged 4 commits into
devfrom
feat/keep-expired-invitations

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

Summary

Expired invitations used to disappear at once, so nobody could tell who needed a nudge. Now they stay for a set time.

  • Listing: GET /services/{id}/invitations lists invitations that weren't accepted, with a new status (open, expired, accepted). Accepted ones are hidden unless asked for (?include_accepted=true). No token or token hash is ever listed.
  • Removal: DELETE also removes expired invitations. An expired link is still refused on accept with 404.
  • Setting: custom.access_control.invitations.keep_expired_days: default 30, minimum 0 (removed on expiry), maximum 365; no value for keeping them forever.
  • Accepted invitations are removed when they expire, as before, not after the retention period.
  • Limit: the counting of max_per_service is unchanged (unexpired, open or accepted). Its 409 detail now says that accepted invitations count until they expire, and how to see them, as lists hide them.
  • Docs: access control (including how long labels are kept), API, configuration, operations and upgrade notes. docs/reference.md renders the docstrings.

Closes #332

Index design

  • MongoDB refuses an index with the same key and other options, and FOCA only creates what's in its config, so a TTL whose value comes from a setting can't be listed there. Two TTL indexes on expires_at do the work:
    • accepted_expires_at (in config.yaml): partial on accepted, TTL 0, removes accepted invitations on expiry. It coexists with the old index, so FOCA can create it during the upgrade.
    • expires_at_1 (by set_ttl_index() on startup): TTL of keep_expired_days, removes everything else. It's the name of the old index, so an upgrade and a later change of the value are the same code path.
  • set_ttl_index() in cloud_registry/utils.py drops and creates the index when the value differs. It has no registry-specific dependencies, so TRS-Filer could reuse it.
  • It doesn't use collMod, the obvious choice, because the role readWrite, the only one the chart gives the app, doesn't allow it: every authenticated deployment would have crashed on upgrade (confirmed on a real MongoDB with --auth). Concurrent starts that interfere with each other try again, up to 5 times.
  • Other readers of the collection were checked for expired documents: accepting, revoking and counting filter on expiry explicitly; service deletion and rename act on all of a service's invitations, which is right for expired ones too; revoking a role and the subject migration only touch fields of the users concerned.

Verification

  • Pre-commit, all hooks (ruff, semgrep, gitleaks, actionlint, ast-grep, mypy): passed.

  • Tests in the repo, also run in CI against MongoDB 7.0: upgrade from the old index (test_upgrade_from_old_index), later changes of the value (test_keep_expired_days_changed), what MongoDB actually removes, with the TTL monitor set to 1 second (test_ttl_removal), concurrent starts (test_set_ttl_index_concurrent), single use under concurrent accepts, accept against revoke, and accepts of an expired link.

  • tests/conftest.py makes mongomock skip partial TTL indexes, as it would otherwise ignore their filter and delete every expired invitation.

  • Upgrade with the real old code (origin/dev before this PR), then the new code, on one real MongoDB 7.0, in checks/cr-332-upgrade/upgrade_run.sh in the work folder (not in the repo, as the test suite can't run two versions):

    • The old index (TTL 0) is replaced by 30 days at the first start, and restarts change nothing.
    • After that, an accepted invitation that had just expired and an open one 40 days past expiry were removed; one 2 days past expiry stayed, as did unexpired ones.
    • Values 1, 0 and 30 each apply on restart, and lowering the value removes what's past it.
    • Going back without the documented step: the old version refuses to start. After dropping the index, it starts.
  • checks/cr-332-upgrade/ttl_auth_race.py, on MongoDB 7.0 with --auth, as a user with only readWrite, 20000 documents: the upgrade from the old index works; 40 rounds of 4 processes starting at once gave no errors and the right value each time.

  • Full suite locally on MongoDB 7.0: 1933 passed; mkdocs build --strict: clean. CI on the same commit: all checks passed, including Test (mongomock), Test (MongoDB 7.0), Chart, Docs, Smoke test, Scan image and codecov (project and patch).

  • Sourcery reviewed: three threads, one fixed (the race test now uses a barrier), two declined below, all resolved. Copilot posted no review within 15 minutes; it hasn't reviewed recent PRs in this repo.

Declined review findings

  • Retention index can disappear (Sourcery, medium): a failed create after the drop leaves no retention index until the next start, which creates it. Expired invitations are only kept longer meanwhile, and collMod isn't allowed for readWrite.
  • Unusable invitations shown as open (Sourcery, medium): open is documented as depending on the creator still being able to grant the role; computing that per listed invitation isn't worth it.
  • Listing size (adversarial, low): expired invitations don't count towards the limit, and lists aren't paginated, so expiry_days: 1, keep_expired_days: 365 allows about 7300 stored invitations per service. The limit is as decided, pagination is out of scope here, and the bound is documented in docs/configuration.md.
  • Last start wins (adversarial, low): an instance with an older config that restarts during a rollout sets the value back until the next start. Changes are logged as warnings and this is documented; a periodic check isn't worth it.
  • Patching mongomock at import in tests/conftest.py (quality, low): kept simple, as it applies to all tests that use mongomock and only skips partial TTL indexes.

The reviewer rounds are used up (2 of 2). The last fix, moving from collMod to dropping and creating the index, came out of round 2 and got no further reviewer round; it's covered by the checks above.

Open questions

None.

🤖 Generated with Claude Code

https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG

uniqueg and others added 3 commits November 3, 2026 04:25
People who never accepted dropped out of sight at once. Keep expired
invitations that weren't accepted, list them with a status, allow DELETE
on them, and remove them automatically after `keep_expired_days` (default
30, 0 to 365). Accepted ones are hidden by default and removed on expiry,
as before; the limit still counts them, and its error now says so.

As the days can change and MongoDB refuses a changed TTL on the same key,
the app sets that index on startup, which also replaces the old one. A
partial TTL index in the config removes accepted invitations on expiry.

Closes #332

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
Dropping and creating the index let workers starting together abort
each other's index builds. Use `collMod`, which is atomic and needs no
rebuild. Log changes as warnings, as the last instance to start sets the
value, and correct docs and log lines for removing expired invitations.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
The role `readWrite`, the only one the chart gives the app, doesn't
allow `collMod`, so every authenticated deployment would have crashed
on upgrade. Drop and create the index, as that role allows, and try
again when concurrent starts interfere with each other.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
@sourcery-ai

sourcery-ai Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR changes invitation persistence from immediate deletion to configurable retention for unaccepted expired invitations, updates the API and documentation to expose lifecycle status safely, and manages the corresponding MongoDB TTL indexes at startup with upgrade and concurrency safeguards.

Sequence diagram for invitation listing and lifecycle

sequenceDiagram
    actor Owner
    participant API
    participant MongoDB

    Owner->>API: GET /services/{serviceId}/invitations
    API->>MongoDB: Find unaccepted invitations
    MongoDB-->>API: Open and expired invitations
    API->>API: _status(invitation)
    API-->>Owner: Invitations with status and no token

    Owner->>API: GET /services/{serviceId}/invitations?include_accepted=true
    API->>MongoDB: Find unaccepted or unexpired accepted invitations
    MongoDB-->>API: Matching invitations
    API->>API: _serve(invitation)
    API-->>Owner: Invitations including accepted status

    Owner->>API: DELETE /services/{serviceId}/invitations/{invitationId}
    API->>MongoDB: find_one_and_delete(unaccepted invitation)
    MongoDB-->>API: Deleted open or expired invitation
    API-->>Owner: Revoked or removed invitation
Loading

Sequence diagram for invitation acceptance after expiry

sequenceDiagram
    actor User
    participant API
    participant MongoDB

    User->>API: POST /invitations/accept
    API->>MongoDB: Find invitation matching token and _unexpired()
    MongoDB-->>API: No matching unexpired invitation
    API-->>User: 404 Not Found

    Note over MongoDB: Expired unaccepted invitation remains stored until TTL removal
Loading

File-Level Changes

Change Details Files
Retain and expose unaccepted expired invitations while preserving accepted-invitation expiry behavior.
  • Added open, expired, and accepted response statuses.
  • Excluded accepted invitations by default, with opt-in inclusion via include_accepted.
  • Allowed owners to delete expired invitations while continuing to reject expired links with 404.
  • Kept token and token-hash data out of listings and preserved atomic accept/revoke behavior.
cloud_registry/ga4gh/registry/invitations.py
cloud_registry/api/additions.openapi.yaml
docs/access-control.md
docs/api.md
docs/operations.md
docs/upgrading.md
Added configurable retention and dynamic MongoDB TTL index management for expired invitations.
  • Added keep_expired_days with defaults and 0–365 validation.
  • Configured a partial TTL index to remove accepted invitations at expiry and a startup-managed TTL index for unaccepted retention.
  • Implemented index replacement, race retries, permission/error handling, and change warnings.
  • Applied the setting during application startup and documented upgrade/rollback implications.
cloud_registry/service_models/custom_config.py
cloud_registry/config.yaml
cloud_registry/utils.py
cloud_registry/app.py
docs/configuration.md
docs/upgrading.md
Expanded automated coverage for invitation lifecycle, retention, API behavior, and index upgrades.
  • Tested listing, status transitions, filtering, deletion, limits, privacy, concurrency, and expired-link handling.
  • Tested TTL removal on MongoDB, upgrades from the legacy index, configuration changes, and concurrent startup races.
  • Adjusted mongomock handling for partial TTL indexes.
tests/test_invitations.py
tests/test_utils.py
tests/service_models/test_custom_config.py
tests/conftest.py

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 Nov 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (92f990a) to head (cbb3c41).
⚠️ Report is 1 commits behind head on dev.

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #335   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           22        22           
  Lines         2375      2418   +43     
=========================================
+ Hits          2375      2418   +43     

☔ 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 November 3, 2026 03:59

@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/utils.py" line_range="83-84" />
<code_context>
+            return
+        try:
+            if index is not None:
+                collection.drop_index(name)
+            collection.create_index([(field, 1)], expireAfterSeconds=seconds)
+        except OperationFailure as exc:
+            if exc.code not in TTL_INDEX_RACES or attempt == TTL_INDEX_ATTEMPTS:
</code_context>
<issue_to_address>
**Retention index can disappear**

When the process stops or index creation fails after the old index has been dropped, `set_ttl_index()` drops the existing TTL index before creating its replacement, so a crash or failed create leaves no general retention index. Surviving app instances then retain expired unaccepted invitations beyond the configured period until a later successful startup repairs the index.

Make index replacement recoverable after a failed create, or ensure a later-running instance detects and repairs a missing retention index.
</issue_to_address>

### Comment 2
<location path="cloud_registry/ga4gh/registry/invitations.py" line_range="245" />
<code_context>
         "id": invitation["_id"],
         "service_id": invitation["service_id"],
         "role": invitation["role"],
+        "status": _status(invitation),
         "created_by": invitation["created_by"],
         "created_at": format_time(invitation["created_at"]),
</code_context>
<issue_to_address>
**Unusable invitations shown as open**

When the creator of an unaccepted invitation loses permission to grant its role before the invitation expires, `_status()` checks only acceptance and expiry, while `_creator_may_grant()` is checked only during acceptance. An invitation whose creator has lost permission to grant its role is therefore listed as `open` even though accepting it returns 404, so owners see a misleading status.

Ensure invitations whose creators can no longer grant their roles are not served with `open` status, or revise the status contract to account for that state.
</issue_to_address>

### Comment 3
<location path="tests/test_invitations.py" line_range="517-518" />
<code_context>
+    for _ in range(5):
+        created = invite(client, service_id).get_json()
+        with ThreadPoolExecutor(max_workers=2) as pool:
+            accepting = pool.submit(accept, client, created["token"])
+            revoking = pool.submit(revoke_invitation, client, service_id, created["id"])
+        outcome = (accepting.result().status_code, revoking.result().status_code)
+        assert outcome in ((200, 409), (404, 200))
</code_context>
<issue_to_address>
**Concurrent race goes undetected**

When the worker requests are scheduled serially, `test_concurrent_accept_and_revoke` submits both requests without coordinating their overlap (lines 516–519), and its accepted outcomes at line 520 are also the serial outcomes. A non-atomic implementation that fails only when the operations overlap therefore passes when the requests run one after the other.

Coordinate both workers at a barrier immediately before the operations whose atomicity the test is intended to verify.
</issue_to_address>

Linked issues

#332 feat: keep expired invitations for a set time · 6 of 6 met

# Requirement Status Notes
1 List expired invitations with a status; keep accepted invitations out of the default view. ✅ Met getServiceInvitations() lists unaccepted invitations, including expired ones, and lists unexpired accepted invitations only when include_accepted=true.
2 Allow DELETE on expired invitations; continue refusing expired links with 404. ✅ Met deleteServiceInvitation() removes unaccepted invitations whether open or expired; acceptance filters for open, unexpired invitations. Tests cover both behaviors.
3 Add keep_expired_days with default 30 and bounds 0–365; apply changes without manual database work. ✅ Met The config validates the range, and apply_keep_expired_days() sets the TTL index at app startup. Tests cover changed values.
4 Keep the single-use guarantee, including under concurrent requests, with tests. ✅ Met acceptInvitation() atomically claims only open invitations; the tests cover concurrent acceptance and concurrent accept/revoke.
5 Test the TTL-index upgrade and describe it in the upgrade notes. ✅ Met test_upgrade_from_old_index covers replacement of the old TTL index, and docs/upgrading.md describes the index changes and upgrade behavior.
6 Update the API and access control docs. ✅ Met The OpenAPI spec and docs/access-control.md document listing, statuses, accepted-invitation visibility, and removal.

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and expired, unaccepted invitations and their labels are now retained and listed to service owners for up to the configured period, 30 days by default. Changing the setting can purge retained records, but it cannot undo any access to invitation metadata during that period.

Blocking findings: cloud_registry/utils.py:84, cloud_registry/ga4gh/registry/invitations.py:245, tests/test_invitations.py:518


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

Comment thread cloud_registry/utils.py Resolved
Comment thread tests/test_invitations.py Resolved
@uniqueg
uniqueg merged commit 32dca62 into dev Nov 3, 2026
42 checks passed
@uniqueg
uniqueg deleted the feat/keep-expired-invitations branch November 3, 2026 04:28
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: keep expired invitations for a set time

1 participant