Repository navigation
fix(access-control): replace roles atomically - #413
Conversation
`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]>
Reviewer's GuideReplaces 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 replacementsequenceDiagram
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
Sequence diagram for failed ownership downgrade recoverysequenceDiagram
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
Flow diagram for concurrent role grant convergenceflowchart 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]
File-Level Changes
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. 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
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
- 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]>
Summary
Closes #398.
grant_role()used to revoke a subject's other roles ofaccess_control.resource_roleson a resource before adding the new role. That left a window without any role (e.g.,403for a maintainer being promoted to owner), and two concurrent grants could leave the subject with two roles.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 ($currentDateof BSON type timestamp, which is unique per server). The timestamp goes in the new stored fieldgranted. It then removes the subject's other unmarked rules with one ofroleson 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.access_control.policiesare neither replaced nor marked, and a warning is logged as before.ownership.py.grant_role()and the restore of concurrently removed owners use the change through the private_replace_resource_role(), which shares its validation withadd_resource_role()(_validate_grantable_rule()). The restore check now runs after the grant, and also when the grant fails (exceptNotFound), so a failed downgrade does not leave the resource without owners.grant_role()docstring and docs/access-control.md are updated. The release-notes entry is collected for 0.17.0.Design choices
How it was verified
coverage run -m pytest+coverage report(MongoDB 7.0 on port 12345, Python 3.13): 1698 passed, 100% coveragetests/securitypassruff check,ruff format --check,mypy: cleanmkdocs build --strict: cleanTestReplaceRoleRule): 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 collisionsTestGrantRole): promote and demote without a window, concurrent grants, restore after a failed downgrade with a concurrent owner leaving, configured roles keptDeclined 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:_grant()conditional when the existence check fails or returnsFalse(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.grant_role()for the subject repairs leftover roles), and coordination with older FOCA versions during rolling deploys (not a regression; repaired the same way).ROLESand_roles()in the adapter tests into the test class (quality, low). They are module-level helpers like the others in that module;ROLESis now a tuple.Open questions
None.
🤖 Generated with Claude Code