Skip to content

fix(access-control)!: replace policies atomically - #423

Merged
uniqueg merged 6 commits into
devfrom
fix/atomic-configured-policies
Oct 23, 2026
Merged

uniqueg merged 6 commits into
devfrom
fix/atomic-configured-policies

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #418 (dev is 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:

  • On startup, the configured rules are stored as a new generation. A stored configured copy of a rule is reused (preferably the one in effect, so its identifier is kept); otherwise the rule is inserted.
  • One find_one_and_update on a marker document (_id: configured_policies, in the policy collection) makes the new generation active and returns the previous one.
  • Only then is the previous generation removed ($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 to LOAD_POLICY_ATTEMPTS), then fails closed with a RuntimeError.
  • The permissions API lists, returns and protects (409) only configured rules of the active generation, as do the resource role helpers.
  • Concurrent startups: the instance that activates its generation last wins. A failed startup leaves the previous set active. Generations that never became active are removed on a later startup once older than an hour, as are generations not created by FOCA.
  • 0.16.0 data: configured rules without generations form the generation 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.

  • Apps that never configure policies only run one count query and create no marker.
  • If the database is unavailable, startup continues with a warning, as before (after pymongo's server selection timeout).

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 unset policies now removes stored configured rules. Docs: "Configuring policies" in docs/access-control.md (with warnings about apps sharing a policy collection and about mixed 0.16 deployments and downgrades), and "Named entries" in docs/configuration/index.md.

How it was verified

  • Regression tests in tests/security/access_control/foca_casbin_adapter/test_adapter.py (TestConfiguredGenerations, TestLegacyConfiguredRules), on both mongomock and MongoDB 7.0:
    • the rules in effect are checked before every single write of a replacement;
    • a concurrent replacement is run before each write;
    • a failure is injected before each write;
    • the marker is switched while rules are loading (reload, and exhaustion);
    • legacy migration, and legacy rules added after the migration;
    • unknown generations.
  • Unset policies, legacy removal and an unavailable database are tested in test_register_casbin_enforcer.py. Inactive rules are tested as hidden from the permissions API.
  • coverage run -m pytest with 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.
  • CI (also after the Sourcery fixes, head 43e3211): all checks passed (unit tests on Python 3.11-3.14 with MongoDB 7.0 and 8.0, lowest direct dependencies, lint/type-check/build, integration, charts, image scans, Codecov patch and project).

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 serverSelectionTimeoutMS override for the unset-policies check (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_none checks 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 when policies is unset, the config docstring, and test leftovers.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 4 commits October 23, 2026 03:02
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]>
@sourcery-ai

sourcery-ai Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces 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 replacement

sequenceDiagram
    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
Loading

Sequence diagram for consistent policy loading

sequenceDiagram
    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
Loading

Flow diagram for unset policies handling

flowchart 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
Loading

File-Level Changes

Change Details Files
Replace configured policy rules using generation-based activation instead of in-place mutation, preserving atomic reads and handling concurrent or failed startups.
  • Store configured rules in a new generation and reuse identifiers from the active generation where possible.
  • Atomically switch the active generation through a marker document, then remove superseded and stale generations.
  • Retry policy loading when the active generation changes and fail closed after repeated instability.
  • Support legacy 0.16 rules, stale-generation cleanup, concurrent startup semantics, and protection against unknown generations.
foca/security/access_control/foca_casbin_adapter/adapter.py
foca/security/access_control/constants.py
Limit enforcement, permissions APIs, and role helpers to configured rules in the active generation.
  • Add active-generation queries for policy loading, configured-rule checks, filtering, and resource role behavior.
  • Filter permission listing and lookup results using the active-generation query.
  • Keep API-created rules unconfigured even when their values match configured rules.
foca/security/access_control/foca_casbin_adapter/adapter.py
foca/security/access_control/access_control_server.py
Change startup reconciliation so an unset policy configuration removes stored configured rules while tolerating unavailable databases.
  • Check for configured policies when the setting is absent and replace them with an empty generation, emitting a warning.
  • Continue startup with a warning if the database check fails.
  • Preserve unconfigured rules and retain configured-rule validation before any replacement occurs.
foca/security/access_control/register_access_control.py
Document the new replacement semantics, operational migration requirements, and overlay behavior.
  • Document atomic generation replacement, concurrent startup behavior, cleanup timing, and active-rule visibility.
  • Document breaking behavior for unset policies, shared collections, 0.16 upgrades, and downgrades.
  • Clarify that overlay-added entries must be removed from the overlay rather than nulled in later files.
docs/access-control.md
docs/configuration/index.md
Add comprehensive regression coverage for atomic replacement, migration, failure handling, API visibility, and startup behavior.
  • Test reads before and after every replacement write, concurrent replacements, injected failures, reload retries, and stale or unknown generations.
  • Test legacy migration, removal with unset policies, unavailable databases, inactive permission visibility, and non-adoption of API rules.
  • Adjust application tests for database-dependent startup checks.
tests/security/access_control/foca_casbin_adapter/test_adapter.py
tests/security/access_control/test_access_control_server.py
tests/security/access_control/test_register_casbin_enforcer.py
tests/test_foca.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 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (0aae032) to head (43e3211).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #423   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           27        27           
  Lines         2777      2869   +92     
=========================================
+ Hits          2777      2869   +92     
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 23, 2026 01:41

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


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

uniqueg and others added 2 commits October 23, 2026 03:53
- 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]>
@uniqueg
uniqueg merged commit 76df7b6 into dev Oct 23, 2026
22 checks passed
@uniqueg
uniqueg deleted the fix/atomic-configured-policies branch October 23, 2026 02:01
uniqueg added a commit that referenced this pull request Oct 23, 2026
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]>
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