Skip to content

fix(access-control): let newest policies win - #680

Merged
uniqueg merged 7 commits into
devfrom
fix/612-newest-policies-win
Nov 4, 2026
Merged

uniqueg merged 7 commits into
devfrom
fix/612-newest-policies-win

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #612.

Keeps older pods from overwriting or removing the configured policy rules of newer ones during rolling upgrades.

  • security.access_control.policies_revision: optional integer stamp for the configured rules, stored on the marker document. A pod with an older revision than the stored one leaves the stored rules alone and logs a warning. Activation of a generation is conditional on the stored revision, so concurrent starts can't undo this either.
  • security.access_control.policies_force: a deliberate rollback, for example, writes the rules and revision whatever is stored.
  • Adapter.set_configured_policies(rules, revision=None, force=False) returns whether the rules are now in effect; feat(cli): add foca CLI and startup switches #621's sync-policies can use it.
  • Docs: docs/deployment.md (rolling upgrades), docs/access-control.md, configuration reference.

Verification

  • ruff check, ruff format --check, mypy foca, strict docs build, full pytest against a local MongoDB: 3570 passed, 1 skipped, 100% coverage, before merging dev; after the merge, the affected test files again (337 passed).
  • Concurrency is covered on mongomock only, not against a real MongoDB under concurrent starts.
  • Helm rendering of integers (toYaml, values and --set) was checked by the reviewer on a minimal chart, not on foca-common.

Declined review findings

  • Pods of FOCA before 0.21.0 can leave a stale revision stamp: their update only sets generation. Documented rather than solved: an optional revision_generation field would add state for one upgrade only. Protection needs all pods on this version.
  • The warning may be logged twice on a race: harmless.
  • A pod without policies on an empty collection stores no revision: an idle restart should stay a no-op. Documented; it's not the normal upgrade path.
  • Forcing without a revision stores none: that's the documented behaviour, and clears the protection.

Open questions

None. Design choices for the maintainer to look at when reading this: an integer revision (rather than a version string), and rollbacks staying sticky until a newer revision.

🤖 Generated with Claude Code

Summary by Sourcery

Protect configured access-control policies from stale instances during rolling upgrades while supporting deliberate revisioned rollbacks.

New Features:

  • Add revision-aware configured policy management to prevent older application instances from overwriting newer policy rules during rolling upgrades.
  • Add an explicit force option for deliberate policy rollbacks and expose whether configured policies were applied.

Bug Fixes:

  • Prevent concurrent or stale policy updates from replacing rules associated with a newer stored revision.

Enhancements:

  • Extend access-control configuration validation and policy activation to track policy revisions while preserving existing last-started-wins behavior when revisions are not configured.

Documentation:

  • Document policy revisions, forced rollbacks, upgrade prerequisites, and shared policy collection considerations.

Tests:

  • Add coverage for revision ordering, stale instances, forced rollbacks, empty policies, and concurrent activation races.

uniqueg and others added 4 commits November 4, 2026 07:23
Add `policies_revision`: instances with an older revision than the
stored one leave configured rules alone, with a warning, so that old
pods restarting in a rolling upgrade don't bring back old rules. The
check is part of the write that activates the rules. `policies_force`
is the deliberate way to overwrite, for rollbacks.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Force also without rules, for the revision, and limit revisions to
MongoDB's integers. Describe what old pods enforce, rollbacks, versions
before revisions and shared policy collections.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Revision options without access control have no effect, so refuse them
like the other options. Say what an unset `policies` stores.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…s-win

# Conflicts:
#	tests/models/test_config.py
@uniqueg uniqueg added this to the v0.21.0 milestone Nov 4, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Introduces revision-stamped access-control policies with conditional generation activation, preventing stale pods from overwriting newer rules during rolling upgrades while supporting explicit forced rollbacks; configuration, startup behavior, documentation, and concurrency-related tests are updated accordingly.

Sequence diagram for revisioned policy activation

sequenceDiagram
    participant Pod as Application pod
    participant Adapter
    participant MongoDB

    Pod->>Adapter: set_configured_policies(rules, revision, force)
    Adapter->>MongoDB: find_one(_id=configured_policies)
    alt stored revision is newer and force is false
        Adapter-->>Pod: false
        Adapter-->>Pod: Log warning
    else eligible or forced update
        Adapter->>MongoDB: Store new policy generation
        Adapter->>MongoDB: find_one_and_update(marker, revision condition)
        alt activation succeeds
            MongoDB-->>Adapter: Previous generation
            Adapter-->>Pod: true
        else concurrent newer revision wins
            MongoDB-->>Adapter: No activation
            Adapter-->>Pod: false
        end
    end
Loading

File-Level Changes

Change Details Files
Add revision-aware policy persistence so newer configured rules cannot be overwritten during rolling upgrades.
  • Add optional, strictly validated revision and force settings to access-control configuration.
  • Persist the revision on the configured-policy marker and reject stale or unversioned updates with a warning.
  • Make generation activation conditional on the stored revision to protect against concurrent startup races.
  • Return whether policy replacement was applied and propagate that result through add/remove startup paths.
foca/models/config.py
foca/security/access_control/constants.py
foca/security/access_control/foca_casbin_adapter/adapter.py
foca/security/access_control/register_access_control.py
Document revision-based upgrades, deliberate rollbacks, compatibility boundaries, and shared-collection behavior.
  • Describe revision increments, sticky rollback behavior, and force-based rollback procedure.
  • Document configuration fields and restrictions for apps sharing a policy collection.
  • Explain behavior with pre-0.21.0 pods and unset policies.
docs/access-control.md
docs/configuration/access-control.md
docs/deployment.md
Cover revision ordering, forced updates, startup removal, validation, and activation races with tests.
  • Test first use, equal/newer revisions, stale or missing revisions, and forced rollbacks.
  • Verify stale pods do not remove or report named policies as applied.
  • Validate configuration constraints and concurrent newer-revision activation behavior.
tests/models/test_config.py
tests/security/access_control/foca_casbin_adapter/test_adapter.py
tests/security/access_control/test_enforcer_cache.py
tests/security/access_control/test_register_casbin_enforcer.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 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 (1b94723) to head (9c15715).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #680   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           60        60           
  Lines         7807      7828   +21     
=========================================
+ Hits          7807      7828   +21     
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 November 4, 2026 07:06

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

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

## Individual Comments

### Comment 1
<location path="tests/security/access_control/test_register_casbin_enforcer.py" line_range="484-486" />
<code_context>
+        assert self._start(collection, new, revision=2) == {"new"}
+        assert self._start(collection, None, revision=1) == {"new"}
+        assert "Removed stored" not in caplog.text
+        assert self._start(collection, None, revision=1, force=True) == set()
+        assert "Removed stored" in caplog.text
+
+    def test_forced_without_rules(self) -> None:
+        """Forcing also stores the revision if there are no rules to remove."""
+        collection: Collection[dict[str, Any]] = (
+            mongomock.MongoClient().db.revisions_empty
+        )
+        self._start(collection, [], revision=3)
+        assert self._start(collection, None, revision=1, force=True) == set()
+        rules = [["p", "new", "/a", "GET"]]
+        assert self._start(collection, rules, revision=2) == {"new"}
+
+    def test_rollback(self) -> None:
</code_context>
<issue_to_address>
**Cleared revision passes test**

When forced removal clears the stored revision instead of storing revision 1, `test_forced_without_rules` accepts a cleared revision just as it accepts revision 1: the later revision-2 write succeeds in either case, so the test passes even though older pods would no longer be blocked by the forced revision.

Assert that the stored marker revision is 1 after the forced removal, or verify that an older revision is rejected afterward.
</issue_to_address>

Linked issues

#612 fix(access-control): let newest policies win · 7 of 7 met

# Requirement Status Notes
1 Stamp configured policies with an ordered revision; older pods must leave newer rules alone and log a warning. ✅ Met policies_revision is stored on the generation marker; older or unversioned updates are skipped with a warning.
2 Make activation conditional on the stored revision so concurrent starts cannot undo newer rules. ✅ Met _activate_generation includes the revision condition in the marker update, and handles a conflicting newer marker.
3 Document a deliberate way to overwrite rules for rollbacks. ✅ Met The deployment guide documents policies_force: true for rollback and advises removing it afterward.
4 Test old-after-new, new-after-old, rollback, and first start without a stamp. ✅ Met The revision adapter tests cover each scenario, including skipped older and unversioned updates.
5 Maintain 100% test coverage. ✅ Met The PR reports 100% coverage; the added tests exercise the revision and forced-update paths.
6 Document the behavior in the deployment guide. ✅ Met docs/deployment.md adds a section on revisions, rolling upgrades, rollbacks, older versions, and shared collections.
7 Let the foca CLI issue's sync-policies use the same code. ✅ Met Adapter.set_configured_policies provides the shared revision-aware operation and returns whether the update took effect.

Sourcery assessment

Needs a human reviewer. 1 finding to address first, and the stored revision controls which configured policy generation becomes active, so a faulty revision check or forced rollback could leave rules active that grant unintended access. Reverting the code would not undo requests already authorized under those rules or restore the previous stored policies.

Blocking findings: tests/security/access_control/test_register_casbin_enforcer.py:486


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

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

Linked issues

#612 fix(access-control): let newest policies win · 6 of 7 met

# Requirement Status Notes
1 Older pods leave newer configured rules alone and log a warning, including when starts race. ✅ Met Revision checks and conditional activation are implemented; tests cover older and unrevisioned pods, plus a newer revision stored between the initial check and activation.
2 A new pod replaces older rules. ✅ Met Tests cover replacement by the same or a newer revision, and replacement of unstamped rules.
3 Provide a deliberate rollback path. ✅ Met policies_force bypasses the stored-revision check, and the docs explain how to use it for rollbacks.
4 Handle the first start without a stamp. ✅ Met Tests verify that a revisioned update takes over from previously unstamped rules.
5 Keep 100% coverage. ✅ Met The PR reports 100% coverage, and adds tests for revision ordering, rollback, startup removal, and concurrent activation.
6 Document the behavior in the deployment guide. ✅ Met docs/deployment.md describes revisions, rollbacks, old-version pods, and shared policy collections.
7 Have the CLI sync-policies use the same code. 🟡 Partly met The adapter exposes the revision-aware update method and its applied-status result, but this diff adds no CLI sync-policies caller.

uniqueg and others added 2 commits November 4, 2026 09:01
…s-win

# Conflicts:
#	docs/configuration/access-control.md
#	foca/security/access_control/register_access_control.py
@uniqueg
uniqueg merged commit cd2dc70 into dev Nov 4, 2026
78 of 80 checks passed
@uniqueg
uniqueg deleted the fix/612-newest-policies-win branch November 4, 2026 08:30
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.

fix(access-control): let newest policies win

1 participant