Skip to content

fix: delete invitations with a user's roles - #355

Merged
uniqueg merged 2 commits into
devfrom
fix/revoke-created-invitations
Nov 4, 2026
Merged

uniqueg merged 2 commits into
devfrom
fix/revoke-created-invitations

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Revoking a user's roles on a service now also deletes the invitations to that service that the user created and nobody accepted, open or expired, also those created as an admin or through a group that stays owner, which stayed valid until now. So a removed user's open links stop working, and their identifier and times go with them. Accepted invitations stay until they expire, as they hold an acceptance.

The cleanup runs only after the revocation succeeded: 409 for the last owner and 404 for a user without a role delete nothing. Each deleted invitation is logged.

The docs now say which invitations go and which stay, and name what they keep (createdBy, createdAs, createdAt), in docs/access-control.md and docs/upgrading.md, as the pre-release review asked (finding L4). Also docs/operations.md, the OpenAPI description and the release notes.

Closes #354

How it was verified

  • Test first: the new tests in tests/test_invitations.py failed before the change. File result now: 107 passed, 4 skipped.
  • pre-commit run --all-files (without gitleaks locally), mypy cloud_registry tests, mkdocs build --strict.
  • Full suite and coverage: in CI, on both mongomock and MongoDB 7.0.

Declined review findings

  • A cleanup that fails after the role is gone can't be retried (404): needs a database failure between two writes; the request fails with an error, and the docs say how to find such invitations by createdBy.
  • An accept in flight that fails after the role is revoked can reopen an invitation created as an admin or through a group: needs a narrow race plus a failed grant, and a marker field would be more than the problem is worth.

Known limit

  • A global admin who has no role on a service can't be revoked there (404), so their invitations on such services stay; docs/access-control.md keeps the advice to delete them by createdBy.

🤖 Generated with Claude Code

Summary by Sourcery

Remove unaccepted service invitations created by users whose roles are successfully revoked, while preserving accepted invitations and documenting the behavior.

Bug Fixes:

  • Delete unaccepted invitations created by a user when their roles on the service are successfully revoked, including invitations created as an admin or through a group.

Enhancements:

  • Preserve accepted invitations while removing creator metadata from them when the creator's roles are revoked.
  • Log each invitation removed during role revocation and document the resulting invitation lifecycle and operational behavior.

Documentation:

  • Update access-control, operations, upgrading, OpenAPI, and release documentation to describe invitation cleanup and retention behavior.

Tests:

  • Add coverage for invitation cleanup across open, expired, accepted, cross-service, admin, group-created, failed-revocation, race, and logging scenarios.

uniqueg and others added 2 commits November 4, 2026 03:44
Revoking a user's roles on a service also deletes the invitations to it
that the user created and nobody accepted, also those that do not depend
on their role, so that their links stop working. Accepted ones hold
another user's acceptance and stay until they expire.

Closes #354

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Log each deleted invitation, correct what the docs say about downgrades
and admins, and test creators by admin and group.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg added this to the v1.0.0-rc2 milestone Nov 4, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Successful service-role revocation now removes all unaccepted invitations created by the revoked user on that service—including admin- and group-created invitations—while preserving accepted invitations and logging each deletion; tests and documentation define the behavior and edge cases.

Sequence diagram for invitation cleanup after role revocation

sequenceDiagram
    actor Admin
    participant API as permissions API
    participant Roles as _delete_roles
    participant Invitations as invitations collection
    participant Logger as logger

    Admin->>API: deleteServicePermission
    API->>Roles: _delete_roles
    alt role revocation succeeds
        Roles->>Invitations: update accepted invitations
        Roles->>Invitations: _delete_created_invitations
        Invitations-->>Roles: unaccepted invitations created by user
        loop each invitation
            Roles->>Invitations: delete_one
            Invitations-->>Roles: deleted_count
            alt invitation deleted
                Roles->>Logger: logger.info
            end
        end
    else last owner or user has no role
        API-->>Admin: 409 or 404
    end
Loading

File-Level Changes

Change Details Files
Delete unaccepted invitations created by a user when all of that user’s roles on a service are successfully revoked.
  • Query invitations by service and creator while excluding accepted records.
  • Delete candidates individually with a conditional accepted-state check to protect invitations accepted during cleanup.
  • Run cleanup only after role revocation succeeds, including invitations created as an admin or through a still-owning group.
  • Log each invitation deleted by the cleanup.
cloud_registry/ga4gh/registry/permissions.py
Expand automated coverage for invitation cleanup behavior and edge cases.
  • Verify deletion of open and expired invitations while retaining accepted, cross-service, and other-user invitations.
  • Cover admin-created and group-created invitations, failed revocations, logging, and acceptance races.
  • Verify downgraded users’ invitations remain listed but cannot be accepted through the existing cleanup path.
tests/test_invitations.py
Document the lifecycle, retained metadata, operational effects, and API contract of invitation cleanup.
  • Describe which invitations are deleted on role revocation and which accepted invitations remain until expiry.
  • Document retained or removed creator and acceptance metadata and the global-admin limitation.
  • Update operations guidance, upgrade notes, release notes, and the OpenAPI revoke-permissions description.
docs/access-control.md
docs/operations.md
docs/releases/1.0.0rc2.md
docs/upgrading.md
cloud_registry/api/additions.openapi.yaml

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

Copy link
Copy Markdown

Codecov Report

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

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #355   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           23        23           
  Lines         2572      2579    +7     
=========================================
+ Hits          2572      2579    +7     

☔ 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 4, 2026 02:54

@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 4 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="593" />
<code_context>
+    query = {
+        "serviceId": serviceId,
+        "createdBy": user,
+        "accepted": {"$exists": False},
+    }
+    for invitation in list(collection.find(query, {"_id": True})):
</code_context>
<issue_to_address>
**Revoked invitation becomes usable again**

When an invitation is claimed before cleanup, its role grant fails, and `acceptInvitation` resets the claim afterward, `_delete_created_invitations` skips the claimed invitation, then `acceptInvitation` unsets `accepted` after `put_role` fails, leaving an admin- or still-owner-group-created link usable after revocation.

Ensure a failed acceptance cannot restore an invitation that revocation has already skipped.

Also at `cloud_registry/ga4gh/registry/permissions.py:596`.
</issue_to_address>

### Comment 2
<location path="cloud_registry/ga4gh/registry/permissions.py" line_range="595" />
<code_context>
+        "createdBy": user,
+        "accepted": {"$exists": False},
+    }
+    for invitation in list(collection.find(query, {"_id": True})):
+        if collection.delete_one({**query, "_id": invitation["_id"]}).deleted_count:
+            logger.info(
</code_context>
<issue_to_address>
**New invitations survive revocation**

When an invitation is inserted after the cleanup scan and its creator still qualifies as an admin or through an owner group, `_delete_created_invitations` misses the new invitation, while `postServiceInvitation`'s final `_created_as` check still passes, leaving the link usable after revocation.

Coordinate invitation creation with revocation so an invitation cannot be inserted after cleanup and pass its final authorization check.

Also at `cloud_registry/ga4gh/registry/permissions.py:652`.
</issue_to_address>

### Comment 3
<location path="cloud_registry/ga4gh/registry/permissions.py" line_range="652" />
<code_context>
                 {"serviceId": serviceId, "accepted.userId": subject},
                 {"$unset": {"accepted.name": "", "accepted.email": "", "label": ""}},
             )
+            _delete_created_invitations(serviceId, subject)


</code_context>
<issue_to_address>
**Failed cleanup cannot be retried**

When a database operation after `revoke_roles` succeeds fails before invitation cleanup completes, `_forget_names`, the accepted-invitation update, or `_delete_created_invitations` propagates the error after the role is removed; a retry returns `404` before cleanup, leaving invitations and possibly creator metadata behind, with links still usable.

Make invitation cleanup complete or remain retryable when a database operation fails after role revocation.
</issue_to_address>

### Comment 4
<location path="cloud_registry/ga4gh/registry/permissions.py" line_range="590-595" />
<code_context>
+        user: User identifier.
+    """
+    collection = get_collection(INVITATIONS)
+    query = {
+        "serviceId": serviceId,
+        "createdBy": user,
+        "accepted": {"$exists": False},
+    }
+    for invitation in list(collection.find(query, {"_id": True})):
+        if collection.delete_one({**query, "_id": invitation["_id"]}).deleted_count:
+            logger.info(
</code_context>
<issue_to_address>
**Revocations scan invitation history**

When the invitations collection or a service's retained invitation history is large, `collection.find` must scan invitations to match `createdBy`, then materializes matching IDs before deleting them individually, making role revocations increasingly expensive and prone to timing out or failing partway through cleanup.

Add an index that supports the cleanup query on `serviceId`, `createdBy`, and acceptance status.
</issue_to_address>

Linked issues

#354 Clear invitations a user created when revoking · 5 of 5 met

# Requirement Status Notes
1 Delete invitations on the service that the user created and nobody accepted. ✅ Met The cleanup filters by service, creator, and absence of an acceptance; it covers open and expired invitations, including those created as an admin or through a group.
2 Keep accepted invitations until they expire. ✅ Met Accepted invitations are excluded from the deletion query; the existing cleanup removes acceptance details without deleting the invitation.
3 Only clean up after successful revocation; 409 and 404 clear nothing. ✅ Met The invitation cleanup runs only after revoke_roles succeeds and after the no-role check; the tests cover last-owner 409 and no-role 404.
4 Add tests for the cleanup behavior. ✅ Met Tests cover accepted, open, expired, cross-service, admin-created, group-created, unsuccessful-revocation, and concurrent-acceptance cases.
5 Document the behavior and the retained creator fields in docs/access-control.md and docs/upgrading.md. ✅ Met Both documents describe which invitations are removed or retained and name createdBy, createdAs, and createdAt.

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and revoking a user's roles now permanently deletes every unaccepted invitation they created for that service, including invitations created as an admin or through a group that would otherwise remain valid. If that deletion policy is wrong, the invitation records and working links are not restored by reverting; affected invitations must be created again.

Blocking findings: cloud_registry/ga4gh/registry/permissions.py:593, cloud_registry/ga4gh/registry/permissions.py:595, cloud_registry/ga4gh/registry/permissions.py:652, cloud_registry/ga4gh/registry/permissions.py:595


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

@uniqueg
uniqueg merged commit d3e4fd7 into dev Nov 4, 2026
44 checks passed
@uniqueg
uniqueg deleted the fix/revoke-created-invitations branch November 4, 2026 03:10
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.

Clear invitations a user created when revoking

1 participant