Repository navigation
fix(access-control)!: replace policies atomically - #423
Conversation
Store configured policy rules as generations: a new set is stored under a new generation, which a single write to a marker document in the policy collection makes active; only then are rules of the previous generation removed. Rules are loaded, listed by the permissions API and protected from changes only for the active generation, and loading retries if the generation changes meanwhile, so requests are checked against one complete set, without transactions. Concurrent instances leave the set of the last one to switch; failed startups leave the previous set active; generations that never became active are removed after an hour. Rules stored by FOCA 0.16 (without generations) are used until the first replacement. Without `policies`, stored configured rules are now removed on startup (e.g., after removing the overlay that added them); apps without them only check, and start with a warning if the database is unavailable. Rules stored without the mark (e.g., via the permissions API) are no longer adopted as configured rules. Closes #418 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address review findings: - Add rules to the new generation via their copy in the active generation first, so that identifiers of rules in effect are kept. - Split storing and activating generations; log added rules when stored. - `save_policy_line(configured=True)` stores rules in the active generation instead of without generation. - Rename constants that were easy to confuse. - Say in the warning that rules stay in effect if the database is not available, and document mixed-version deployments, downgrades, clock synchronization and removal of unknown generations. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Log rules as stored (with their generation) rather than added, as the generation may never become active, and say that saving configured rules is not safe while they are replaced concurrently. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideIntroduces generation-based, transaction-free atomic replacement of configured access-control policies, with active-generation-aware enforcement and APIs, legacy migration and cleanup, removal of configured rules when policies are unset, updated documentation, and extensive concurrency and failure regression tests. Sequence diagram for atomic configured policy replacementsequenceDiagram
participant Startup
participant Adapter
participant MongoDB
Startup->>Adapter: set_configured_policies(rules)
Adapter->>MongoDB: _store_generation(generation, rules)
Adapter->>MongoDB: _activate_generation(generation)
MongoDB-->>Adapter: previous generation
Adapter->>MongoDB: _remove_generations(previous)
Adapter->>MongoDB: _remove_stale_generations()
Note over MongoDB: Marker switch makes one complete generation active
Sequence diagram for consistent policy loadingsequenceDiagram
participant Enforcer
participant Adapter
participant MongoDB
Enforcer->>Adapter: load_policy(model)
loop LOAD_POLICY_ATTEMPTS
Adapter->>MongoDB: _active_generation()
MongoDB-->>Adapter: generation
Adapter->>MongoDB: find(_rules_query(generation))
MongoDB-->>Adapter: non-configured rules and active generation
Adapter->>MongoDB: _active_generation()
MongoDB-->>Adapter: generation
end
alt generation unchanged
Adapter-->>Enforcer: load one complete generation
else generation changed on every attempt
Adapter-->>Enforcer: RuntimeError
end
Flow diagram for unset policies handlingflowchart TD
Start[Register Casbin enforcer]
Configured{policies configured?}
Check["has_configured_policies()"]
Replace["set_configured_policies([])"]
Continue[Start with existing rules]
Warn[Log warning]
Start --> Configured
Configured -->|yes| Replace
Configured -->|no| Check
Check -->|configured rules found| Warn
Warn --> Replace
Check -->|none found| Continue
Check -->|database unavailable| Warn
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
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 9 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="661" />
<code_context>
+ previous = self._collection.find_one_and_update(
+ {"_id": GENERATION_MARKER_ID},
+ {"$set": {MARKER_GENERATION_FIELD: generation}},
+ upsert=True,
+ return_document=ReturnDocument.BEFORE,
+ )
</code_context>
<issue_to_address>
**Initial startup fails**
When multiple instances activate their first configured generation before the marker document exists, `_activate_generation` upserts the marker, so concurrent inserts of the same `_id` cause one call to raise `DuplicateKeyError` and that instance's startup fails.
Catch the duplicate-key error and retry the marker update.
</issue_to_address>
### Comment 2
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="503" />
<code_context>
"""
- query = {**query, CONFIGURED_FIELD: True}
+ query = {**query, **self._configured_query(self._active_generation())}
return self._collection.count_documents(query, limit=1) > 0
- def set_configured_policies(self, rules: list[list[str]]) -> None:
</code_context>
<issue_to_address>
**Configured rules bypass protection**
When a permissions API mutation races with a generation activation or targets a stale ID reused for a pending generation, `is_configured` and `_check_not_configured` check the active generation separately from the API write, which has no generation check. The write can bypass the `409` protection, remove a staged configured rule, or change a rule that became active after the check.
Make the configured-rule check and API mutation generation-safe so a rule cannot become active between them.
Also at `foca/security/access_control/foca_casbin_adapter/adapter.py:628`, `foca/security/access_control/foca_casbin_adapter/adapter.py:658-663`.
</issue_to_address>
### Comment 3
<location path="foca/security/access_control/register_access_control.py" line_range="384" />
<code_context>
document = CasbinRule.from_values(ptype, rule).to_dict()
if configured:
document[CONFIGURED_FIELD] = True
+ document[RULE_GENERATIONS_FIELD] = [self._active_generation()]
</code_context>
<issue_to_address>
**Stale generations accumulate**
When a startup leaves an inactive generation and a later startup has no policies while the active generation contains no configured rules, `has_configured_policies` checks only the active generation, so `_remove_policies` skips `set_configured_policies([])` and never runs `_remove_stale_generations`. The orphaned configured documents remain in MongoDB.
Run stale-generation cleanup even when the active generation has no configured rules.
</issue_to_address>
### Comment 4
<location path="foca/security/access_control/access_control_server.py" line_range="250" />
<code_context>
+ **_PERMISSION_FILTER,
+ **_get_visibility_filter(),
+ # Reads the active generation on each request, as rules are loaded
+ **current_app.config["casbin_adapter"].rules_query(),
+ }
total = collection.count_documents(query)
</code_context>
<issue_to_address>
**Permission results become inconsistent**
When a generation is activated and the queried generation is cleaned up while a permissions API request is in flight, `rules_query()` captures one generation, but the API does not verify that it remains active when MongoDB reads the documents. Cleanup can make `getPermission` return `404` or cause `getAllPermissions` to omit rules, return inactive rules, or report totals that disagree with its results.
Keep the generation stable for the full API read, or retry the read if the active generation changes.
Also at `foca/security/access_control/foca_casbin_adapter/adapter.py:678-686`, `foca/security/access_control/access_control_server.py:287-291`.
</issue_to_address>
### Comment 5
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="658-661" />
<code_context>
+ Previously active generation.
+ """
+ # One write, so that the rules of one generation are in effect
+ previous = self._collection.find_one_and_update(
+ {"_id": GENERATION_MARKER_ID},
+ {"$set": {MARKER_GENERATION_FIELD: generation}},
+ upsert=True,
+ return_document=ReturnDocument.BEFORE,
+ )
</code_context>
<issue_to_address>
**Saved rules outlive configuration**
When an application or caller invokes Casbin `Enforcer.save_policy()` after configured rules have been loaded, the Casbin `save_policy()` path deletes the marker and every rule, then rewrites the model via `save_policy_line()` without the configured mark. Configured rules therefore become ordinary stored rules and remain in effect after they are removed from configuration.
Preserve the marker and configured-generation metadata when saving the model, or otherwise ensure this save path cannot convert configured rules into unconfigured ones.
</issue_to_address>
### Comment 6
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="628" />
<code_context>
+ for ptype, *rule in dict.fromkeys(tuple(rule) for rule in rules):
+ query = _rule_query(ptype, rule)
+ if self._collection.update_one(
+ {**query, **self._configured_query(active)}, add
).matched_count:
continue
</code_context>
<issue_to_address>
**Duplicate permissions survive replacement**
When duplicate configured documents with the same values are in the active generation and the two update operations select different copies, `_store_generation()` updates one matching copy in the active generation, then runs another unordered `update_one()` over configured copies. If those calls select different documents with the same rule values, both copies join the new generation, so cleanup retains both and the permissions API lists duplicate entries.
Transfer each rule to the new generation while ensuring only one configured document with those values remains in it.
Also at `foca/security/access_control/foca_casbin_adapter/adapter.py:632`.
</issue_to_address>
### Comment 7
<location path="foca/security/access_control/register_access_control.py" line_range="390" />
<code_context>
+ "Removing stored configured policy rules, as "
+ "'security.access_control.policies' is not set."
+ )
+ adapter.set_configured_policies([])
+
+
</code_context>
<issue_to_address>
**Startup fails on a later database outage**
When `policies` is unset, configured rules are found, and MongoDB becomes unavailable during their replacement, the configured-rule check succeeds, but MongoDB becomes unavailable before `adapter.set_configured_policies([])` completes; that `PyMongoError` escapes and aborts startup instead of logging a warning and continuing.
Handle `PyMongoError` from the replacement as well, logging that the configured rules may remain in effect.
</issue_to_address>
### Comment 8
<location path="foca/security/access_control/register_access_control.py" line_range="359" />
<code_context>
names=None if named is None else list(named),
)
+ else:
+ _remove_policies(adapter=adapter)
logger.info("Casbin enforcer registered.")
</code_context>
<issue_to_address>
**Omitted-policy documentation is stale**
When a caller consults the `AccessControlConfig` description to determine what omitting `policies` does, `register_casbin_enforcer` calls `_remove_policies` when `policies` is unset, so stored configured rules are removed rather than left unchanged; Python users relying on the `AccessControlConfig` documentation are misled about the effect of omitting this key.
Update the `AccessControlConfig` policies description to say that omitting `policies` removes stored configured rules on startup, with the documented database-unavailable exception.
</issue_to_address>
### Comment 9
<location path="tests/security/access_control/foca_casbin_adapter/test_adapter.py" line_range="1070" />
<code_context>
+ assert adapter.is_configured_rule("g", ["erin", "admin"])
+ assert _loaded(self.collection) == _expected(*OLD, ["g", "erin", "admin"])
+ adapter.set_configured_policies(OLD)
+ _check_clean(self.collection, OLD)
+
+ def test_pending_not_in_effect(self) -> None:
</code_context>
<issue_to_address>
**Leftover rules escape cleanup checks**
When replacement cleanup leaves a rule in the collection but removes its configured mark, a replacement that leaves an old rule but clears its `configured` mark makes `test_saved_configured`, `test_added_later_ignored`, and `test_unknown_generations_removed` pass: each ends with `_check_clean`, which only inspects configured documents, while the leftover rule is still loaded as unconfigured.
Assert the loaded rule set after each replacement so leftover unconfigured rules are detected.
Also at `tests/security/access_control/foca_casbin_adapter/test_adapter.py:1143`, `tests/security/access_control/foca_casbin_adapter/test_adapter.py:1198`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 8 findings to address first, and when policies is unset, startup activates an empty configured generation and removes the prior configured rules. If that access-policy default is wrong, requests immediately run under the changed policy; reverting will not restore the deleted rules or undo access that occurred meanwhile.
Blocking findings: foca/security/access_control/foca_casbin_adapter/adapter.py:661, foca/security/access_control/foca_casbin_adapter/adapter.py:503, foca/security/access_control/register_access_control.py:384, foca/security/access_control/access_control_server.py:250, foca/security/access_control/foca_casbin_adapter/adapter.py:661, and 3 more
- Retry activating a generation if the marker document was created concurrently (duplicate key on the upsert). - Permissions API writes never replace or delete configured rules, also if stored after the check (`409`). - `save_policy()` keeps configured rules and the marker, rather than storing configured rules again without the mark. - Without `policies`, also remove rules of inactive generations, and continue startup with a warning if removing them fails. - Document that unset `policies` removes configured rules in `AccessControlConfig`; tests also check the loaded rules when checking for leftovers. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Breaking change of #423: stored configured rules are removed when policies is not set; atomic replacement, shared collections, rules of the permissions API, rolling updates and downgrades (#417). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Closes #418 (
devis not the default branch, so the issue is closed by hand after merging).A. Atomic replacement, without transactions. Configured policy rules are now stored in generations:
find_one_and_updateon a marker document (_id: configured_policies, in the policy collection) makes the new generation active and returns the previous one.$pull), and rules left in no generation are deleted.load_policy()reads the marker, loads the rules that are not configured plus the active generation, and reads the marker again. If the marker changed, it loads again (up toLOAD_POLICY_ATTEMPTS), then fails closed with aRuntimeError.409) only configured rules of the active generation, as do the resource role helpers.legacy. It is active while no marker exists, and is replaced on the first startup.B. Removing configured rules. Option (ii) from the issue: without
policies, stored configured rules are now removed on startup, with a warning. Removing a rule that an overlay added therefore just means removing it from the overlay.Other behaviour change: rules stored via the permissions API with the values of a configured rule are no longer adopted (marked as configured). Adopting them would hide them during the replacement. They stay deletable via the API, and stay stored when the rule is removed from the config.
Marked as breaking (
!), because unsetpoliciesnow removes stored configured rules. Docs: "Configuring policies" indocs/access-control.md(with warnings about apps sharing a policy collection and about mixed 0.16 deployments and downgrades), and "Named entries" indocs/configuration/index.md.How it was verified
tests/security/access_control/foca_casbin_adapter/test_adapter.py(TestConfiguredGenerations,TestLegacyConfiguredRules), on both mongomock and MongoDB 7.0:policies, legacy removal and an unavailable database are tested intest_register_casbin_enforcer.py. Inactive rules are tested as hidden from the permissions API.coverage run -m pytestwith mongod 7.0 (local, mise): all passed, 100% coverage. The only local failure was an artifact of temporarily changing the test port, which also matched an unrelated test value.ruff check,ruff format --check,mypy,mkdocs build --strict,pre-commit run --all-files: passed.Declined review findings
Stale-generation GC relies on the instances' clocks (ObjectId time); a startup pausing for over an hour, or clocks off by over an hour, could let GC remove a generation that is about to become active (low). This is documented ("clocks must be synchronized"). A server-side timestamp would need an extra per-generation document and a conditional switch, which is too much complexity for this edge case.
With secondary reads (
readPreference=secondary*), the marker and the rules could be read from different replication states (low). FOCA does not set a read preference, and the default is the primary.Mixed 0.16/new deployments do not get the guarantee (medium). 0.16 instances ignore generations, and cannot be changed. Documented instead: upgrade all instances before changing configured rules, do not start older instances afterwards, and how to downgrade.
No
serverSelectionTimeoutMSoverride for the unset-policiescheck (low): it would differ from the app's own client settings. The warning says that rules stay in effect.Keep the test for "no marker without configured rules": already asserted (
test_nonechecks that the collection stays empty).Do not document the marker
_id(low): it is needed to downgrade.Sourcery: keep the active generation stable across a whole permissions API read (medium). Enforcement already retries; a listing taken during an activation can show either set. Retrying here would add reads to every API request.
Sourcery: duplicate copies joining the new generation (medium). This cannot happen: the second update only runs if the first matched nothing.
Sourcery's other findings were fixed in 892d319: a concurrent marker upsert, conditional permissions API writes,
save_policy()keeping configured rules, cleanup of inactive generations and database errors whenpoliciesis unset, the config docstring, and test leftovers.Open questions
None.
🤖 Generated with Claude Code