Skip to content

fix(access-control): replace roles atomically - #413

Merged
uniqueg merged 4 commits into
devfrom
fix/398-atomic-roles
Oct 22, 2026
Merged

uniqueg merged 4 commits into
devfrom
fix/398-atomic-roles

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #398.

grant_role() used to revoke a subject's other roles of access_control.resource_roles on a resource before adding the new role. That left a window without any role (e.g., 403 for a maintainer being promoted to owner), and two concurrent grants could leave the subject with two roles.

  • New Adapter.replace_role_rule(ptype, rule, roles). It first stores the new rule, or marks a stored unmarked copy as granted anew, with a timestamp of the database server ($currentDate of BSON type timestamp, which is unique per server). The timestamp goes in the new stored field granted. It then removes the subject's other unmarked rules with one of roles on the resource, keeping only the latest (rules without a timestamp count as the oldest). Each removal is conditional on the timestamp, values and configured mark that were read, so a rule granted again, changed or configured concurrently is kept. New rules are upserted with a new MongoDB _id, so a rollback only ever removes the call's own insertion; failures of the rollback are logged. If the cleanup fails, a rule stored by the call is removed again (unless it was granted again concurrently), so the subject ends up with fewer rights, not more.
  • Concurrency guarantees. The subject keeps a role throughout. Concurrent grants for the same subject and resource converge to one role, that of the grant stored last. The latest timestamped version is never removed by a cleanup, and the last cleanup to read sees every rule.
  • Configured rules. Rules set via access_control.policies are neither replaced nor marked, and a warning is logged as before.
  • Callers in ownership.py. grant_role() and the restore of concurrently removed owners use the change through the private _replace_resource_role(), which shares its validation with add_resource_role() (_validate_grantable_rule()). The restore check now runs after the grant, and also when the grant fails (except NotFound), so a failed downgrade does not leave the resource without owners.
  • Docs. The grant_role() docstring and docs/access-control.md are updated. The release-notes entry is collected for 0.17.0.

Design choices

  • Insert first, then converge, instead of transactions. FOCA supports standalone MongoDB servers, so multi-document transactions are not available. A single compare-and-set on one document does not fit either, because rules are separate documents and the Casbin adapter loads them as such. Ordering by a server-side timestamp makes all instances agree on which rule wins, without relying on their clocks.
  • "Last grant stored wins" for concurrent grants. Both requests succeed, the subject ends up with one role, and both grants are logged.

How it was verified

  • coverage run -m pytest + coverage report (MongoDB 7.0 on port 12345, Python 3.13): 1698 passed, 100% coverage
  • Lowest direct dependencies (Python 3.11): tests/security pass
  • ruff check, ruff format --check, mypy: clean
  • mkdocs build --strict: clean
  • New tests run on both mongomock and MongoDB:
    • adapter (TestReplaceRoleRule): replace, other rules kept, configured rules, duplicates, no window without a role, concurrent replacements interleaved before and after cleanup, a rule granted again during another call's cleanup, rollback when the cleanup fails (also after a concurrent grant of the same role), invalid rules, identifier collisions
    • ownership (TestGrantRole): promote and demote without a window, concurrent grants, restore after a failed downgrade with a concurrent owner leaving, configured roles kept
  • CI: all checks pass (unit tests on Python 3.11-3.14 with MongoDB 7.0 and 8.0, lowest direct dependencies, integration, kind chart install, lint/type-check/build, Codecov, Read the Docs)

Declined review findings

The first round (adversarial-reviewer and quality-reviewer) found two medium races, a stale cleanup undoing a re-grant and a skipped owner restore after a failed downgrade. Both are fixed with regression tests, along with the quality findings (explicit cleanup query, validation helper returning the rule only, comments, docs on granted, clearer tests). A second adversarial round confirmed both fixes and found one more medium race: the rollback could undo a concurrent grant of the same role that had succeeded. It is fixed, so the rollback is now conditional on the call's own timestamp, and has a regression test. Declined:

  • Making the existing revoke in _grant() conditional when the existence check fails or returns False (adversarial round 2, low). This code predates the PR, and the failure path only leaves fewer rights: a concurrent grant of the same role may be revoked along with it. Changing it would mean revoking through the adapter instead of the enforcer.
  • Sourcery: 4 of 7 comments fixed in 3cd11ed (conditional deletes also on values and the configured mark, upserts always inserting their own document, logged rollback failures, stored-document count in a test). Declined: durable recovery from crashes or ambiguous write errors (needs transactions, which FOCA cannot require with standalone MongoDB servers; the next grant_role() for the subject repairs leftover roles), and coordination with older FOCA versions during rolling deploys (not a regression; repaired the same way).
  • Moving ROLES and _roles() in the adapter tests into the test class (quality, low). They are module-level helpers like the others in that module; ROLES is now a tuple.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 3 commits October 22, 2026 23:44
`grant_role()` revoked the subject's other resource roles before adding
the new one, leaving it without a role in between (e.g., `403` for a
maintainer promoted to owner), and two concurrent grants could leave it
with two roles.

The new `Adapter.replace_role_rule()` stores the new rule first (or
marks a stored copy as granted anew) with a timestamp of the database
server (`granted`), then removes the subject's other rules of
`resource_roles` on the resource but the latest one. So the subject
keeps a role throughout, and concurrent grants converge to one role,
that of the grant stored last. If removing the other roles fails, a
rule stored by the call is removed again (fewer rights, not more).
Configured rules are kept, with a warning, as before.

`grant_role()` and the restoring of concurrently removed owners use it
via the private `_replace_resource_role()`; the check for a restored
owner now runs after the grant.

Closes #398

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

- Rules read for removal are only removed if they were not granted
  again since (conditional on their `granted` timestamp), so that a
  concurrent re-grant of a role is not undone, which could leave the
  subject without any role.
- If granting a role fails after an owner downgraded itself (e.g., the
  existence check fails), owners removed concurrently are restored, as
  before, so that the resource keeps an owner.
- `_keep_latest_role()` takes the granted rule explicitly; the
  validation shared with `add_resource_role()` returns the rule only.
- Comments on the rollback and the return value; the `granted` field
  is documented; clearer concurrency tests.

Refs #398

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Round-2 review finding: if removing other roles fails, the rule stored
by the call is only removed if it was not granted again since (by its
timestamp), so that a concurrent grant of the same role that succeeded
is not undone.

Refs #398

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

Replaces revoke-then-grant role updates with an insert-first, server-timestamped convergence algorithm that keeps subjects authorized throughout and makes concurrent grants resolve to the last stored role. Ownership flows now use the atomic adapter operation and recover owners after failed downgrades, with extensive concurrency and rollback regression coverage plus updated documentation.

Sequence diagram for atomic resource role replacement

sequenceDiagram
    participant Caller
    participant Ownership
    participant Adapter
    participant MongoDB

    Caller->>Ownership: grant_role(resource, subject, role)
    Ownership->>Ownership: _validate_grantable_rule()
    Ownership->>Adapter: replace_role_rule(ptype, rule, roles)
    Adapter->>MongoDB: Store or re-mark rule with $currentDate granted
    MongoDB-->>Adapter: Granted timestamp
    Adapter->>MongoDB: Read matching unconfigured role rules
    Adapter->>MongoDB: Conditional delete of older rules
    MongoDB-->>Adapter: Cleanup result
    Adapter-->>Ownership: True or False
    Ownership-->>Caller: Grant result
Loading

Sequence diagram for failed ownership downgrade recovery

sequenceDiagram
    participant Caller
    participant Ownership
    participant Adapter
    participant MongoDB

    Caller->>Ownership: grant_role(resource, subject, non_owner_role)
    Ownership->>Ownership: _check_other_owners()
    Ownership->>Adapter: replace_role_rule(ptype, rule, roles)
    Adapter->>MongoDB: Store new role first
    Adapter->>MongoDB: Remove older role rules
    MongoDB-->>Adapter: Cleanup failure
    Adapter-->>Ownership: Raise exception
    Ownership->>Ownership: _restore_owner_if_none()
    Ownership-->>Caller: Raise original failure
Loading

Flow diagram for concurrent role grant convergence

flowchart LR
    A[Concurrent grant requests] --> B[replace_role_rule]
    B --> C[Store or re-mark each rule with server timestamp]
    C --> D[Read subject roles on resource]
    D --> E[Keep latest granted rule]
    E --> F[Conditional cleanup of older rules]
    F --> G[Subject retains one effective role]
Loading

File-Level Changes

Change Details Files
Introduces atomic role replacement in the MongoDB Casbin adapter using server-generated timestamps and compare-and-set cleanup.
  • Adds replace_role_rule() to grant first, timestamp grants with BSON server timestamps, and converge concurrent role updates to the latest stored grant.
  • Preserves configured policy rules and handles duplicates, identifier collisions, concurrent re-grants, and cleanup rollback safely.
  • Removes only rules whose timestamps have not changed since they were read, preventing stale cleanup from deleting a concurrent grant.
foca/security/access_control/foca_casbin_adapter/adapter.py
foca/security/access_control/constants.py
Refactors resource-role enforcement and ownership flows to use atomic replacement while retaining shared validation and configured-role behavior.
  • Extracts grant-rule validation for reuse by regular additions and replacement grants.
  • Routes ownership grants through _replace_resource_role() so subjects never temporarily lose a role.
  • Restores owners after failed downgrades, including failures following concurrent owner removal, while preserving existing validation and warning behavior.
foca/security/access_control/enforcement.py
foca/security/access_control/ownership.py
Documents the new grant ordering and atomicity guarantees.
  • Updates the grant_role() API documentation and docstring to describe no-role windows, concurrent-grant resolution, rollback, and configured-rule handling.
  • Defines the persisted granted field semantics for stored role rules.
docs/access-control.md
foca/security/access_control/ownership.py
foca/security/access_control/constants.py
Adds regression coverage for replacement concurrency, rollback, ownership restoration, and configured rules.
  • Tests replacement ordering, duplicate and configured rules, validation, ID collision retries, and no-role windows.
  • Exercises interleaved cleanups, re-grants, cleanup failures, and conditional rollback on both in-memory and MongoDB-backed paths.
  • Verifies ownership promotion/demotion, concurrent grants, failed-downgrade owner restoration, and configured-role retention.
tests/security/access_control/foca_casbin_adapter/test_adapter.py
tests/security/access_control/test_ownership.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 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 (db6998c) to head (3cd11ed).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #413   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           27        27           
  Lines         2708      2777   +69     
=========================================
+ Hits          2708      2777   +69     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ 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 22:36

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

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

## Individual Comments

### Comment 1
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="322" />
<code_context>
+            "v1": {"$in": [role, *roles]},
+            "v2": resource,
+            CONFIGURED_FIELD: {"$ne": True},
+        }
+        for index in range(3, MAX_RULE_VALUES):
+            query[f"v{index}"] = None
</code_context>
<issue_to_address>
**Configured rules disappear**

When a competing rule is marked configured or a legacy rule is edited after cleanup reads it but before its delete, `_keep_latest_role()` deletes stale documents using only `_id` and `granted`, so it removes a rule even after its values change or it is marked configured. The configured policy is then missing from storage, or the edited rule is lost.

Make the conditional delete match the observed rule values and configured state as well as `_id` and `granted`.
</issue_to_address>

### Comment 2
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="275-276" />
<code_context>
+                return cast(
+                    dict[str, Any],
+                    self._collection.find_one_and_update(
+                        {**document, "id": id},
+                        _GRANTED_UPDATE,
+                        projection=[GRANTED_FIELD],
+                        upsert=True,
</code_context>
<issue_to_address>
**Configured grant is deleted**

When the generated rule ID collides with a configured copy of the exact rule and cleanup fails, `_insert_granted()` can match the configured document because its upsert filter does not exclude configured rules; `replace_role_rule()` then treats it as its insertion and deletes it during rollback, removing its grant until configuration is reapplied.

Exclude configured documents from the upsert filter and only roll back a document that this call actually inserted.

Also at `foca/security/access_control/foca_casbin_adapter/adapter.py:243`.
</issue_to_address>

### Comment 3
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="243" />
<code_context>
+        except BaseException:
+            # Unless granted again concurrently, by a call that succeeds
+            if inserted is not None:
+                self._collection.delete_one(inserted)
+            raise
+        # A configured copy grants the role already, also without our copy
</code_context>
<issue_to_address>
**Rollback deletes a concurrent grant**

When a same-rule document is inserted after `update_many`, the generated ID matches its ID, and cleanup fails, `_insert_granted()` can match and timestamp an exact-rule document inserted concurrently when its generated ID matches; if `_keep_latest_role()` then fails, `replace_role_rule()` treats that pre-existing document as its own insertion and deletes it, so the concurrent grant disappears.

Use an insertion path that retries on ID collisions, or otherwise track whether this call created the document and only delete documents it created during rollback.

Also at `foca/security/access_control/foca_casbin_adapter/adapter.py:274`.
</issue_to_address>

### Comment 4
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="243" />
<code_context>
+        except BaseException:
+            # Unless granted again concurrently, by a call that succeeds
+            if inserted is not None:
+                self._collection.delete_one(inserted)
+            raise
+        # A configured copy grants the role already, also without our copy
</code_context>
<issue_to_address>
**Failed rollback leaves extra access**

When `_keep_latest_role()` fails and MongoDB also fails the rollback delete, `delete_one()` propagates its own error and leaves the newly inserted role in place alongside other managed roles; it also masks the original cleanup error. The caller sees a failure while the subject retains more access than intended.

Handle and report rollback failures explicitly, and provide a reconciliation path to remove the inserted rule once the database is available.
</issue_to_address>

### Comment 5
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="274-280" />
<code_context>
+            try:
+                return cast(
+                    dict[str, Any],
+                    self._collection.find_one_and_update(
+                        {**document, "id": id},
+                        _GRANTED_UPDATE,
+                        projection=[GRANTED_FIELD],
+                        upsert=True,
+                        return_document=ReturnDocument.AFTER,
+                    ),
+                )
+            except DuplicateKeyError:
</code_context>
<issue_to_address>
**Role replacement leaves inconsistent access**

When mongoDB applies an upsert but reports an error, the process stops before cleanup, or cleanup commits but the client receives an error, `replace_role_rule()` has no durable recovery for its separate writes: it can leave both roles after an applied upsert error or interruption, and can remove the new role after cleanup is reported as failed. `Adapter.load_policy()` reloads the inconsistent state, so callers see extra or missing access.

Make role replacement recoverable across interruptions and ambiguous write errors, and reconcile stored roles when loading policy.

Also at `foca/security/access_control/foca_casbin_adapter/adapter.py:236-238`, `foca/security/access_control/foca_casbin_adapter/adapter.py:240-243`.
</issue_to_address>

### Comment 6
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="236" />
<code_context>
+            {**_rule_query(ptype, rule), CONFIGURED_FIELD: {"$ne": True}},
+            _GRANTED_UPDATE,
+        ).matched_count
+        inserted = None if marked else self._insert_granted(ptype, rule)
+        try:
+            self._keep_latest_role(ptype, rule, roles)
</code_context>
<issue_to_address>
**Rolling deploy leaves multiple roles**

When an older application instance grants a role after a newer instance has finished cleanup for the same subject and resource, the older instance’s write is not ordered against the newer instance’s cleanup, so both managed roles remain stored during the rolling deploy.

Coordinate role writes across application versions so a legacy grant cannot be stored after newer-version cleanup without reconciliation.

Also at `foca/security/access_control/foca_casbin_adapter/adapter.py:238`, `foca/security/access_control/foca_casbin_adapter/adapter.py:543`.
</issue_to_address>

### Comment 7
<location path="tests/security/access_control/foca_casbin_adapter/test_adapter.py" line_range="640" />
<code_context>
+        )
+        assert _roles(adapter) == ["maintainer"]
+        assert adapter.replace_role_rule("g2", ["user:a", "owner", "/x"], ROLES)
+        assert _roles(adapter) == ["owner"]
+        # stored rules get identifiers
+        assert adapter._collection.find_one({"v1": "owner"})["id"]  # type: ignore[index]  # found
</code_context>
<issue_to_address>
**Duplicate stored rules go undetected**

When the cleanup leaves duplicate identical owner documents, `test_duplicates_removed` passes because `_roles(adapter)` reads through `get_filtered_rules()`, which deduplicates identical rule values; the test therefore cannot detect that duplicate owner documents remain in storage.

Assert the number of matching stored documents after cleanup, in addition to the loaded roles.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 7 findings to address first, and if the replacement or ordering logic is wrong, it can remove a subject’s stored role rule or leave the wrong role active, changing what that subject is authorized to do. Reverting the code does not restore role rules already removed from MongoDB, so those access changes may need repair.

Blocking findings: foca/security/access_control/foca_casbin_adapter/adapter.py:322, foca/security/access_control/foca_casbin_adapter/adapter.py:276, foca/security/access_control/foca_casbin_adapter/adapter.py:243, foca/security/access_control/foca_casbin_adapter/adapter.py:243, foca/security/access_control/foca_casbin_adapter/adapter.py:280, and 2 more


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

- Rules read for removal are only removed if their values and the
  configured mark are unchanged, too.
- New rules are upserted with a new MongoDB identifier, so that only
  rules stored by the call itself are removed on rollback, never a
  copy stored concurrently with the same rule identifier.
- Failures to remove a rule on rollback are logged, and the original
  error is raised.
- Check the number of stored rules after replacing duplicates.

Refs #398

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit da7edde into dev Oct 22, 2026
15 checks passed
@uniqueg
uniqueg deleted the fix/398-atomic-roles branch October 22, 2026 22:52
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.

1 participant