Repository navigation
perf(access-control): cache the policy enforcer - #454
Conversation
Let FOCA's Casbin adapter record which rules each write may have changed, in a versioned document of a collection next to the policy collection (`<collection_name>_changes`). App instances can thus notice changes with one small read and reload only the changed rules. Add filtered rule loading, indexes for it, `mark_changed()` for rules changed in the database directly, and `remove_policy_by_id()`. Refs #450 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Keep one Casbin enforcer per app instance, shared by its threads and used under a lock, instead of creating one and loading all rules for each enforced request. Before each use, apply the recorded changes of stored rules incrementally, falling back to loading all rules where needed, so that grants and revocations apply from the next request in every worker and replica. Index resource-scoped roles by path and subject in a role manager, so that role lookups need not scan all rules, and create the enforcer without an adapter first, so that Casbin does not log all rules (incl. subjects) at level INFO. Add `locked_enforcer()`; `get_enforcer()` now returns the shared enforcer. Closes #450 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Describe how app instances keep and update the shared enforcer, its trade-offs, and the changes collection, and add migration notes for 0.18.0. Refs #450 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address the review of the cached enforcer: - Record rules removed or replaced by identifier before the write, too, as a retry would not find them to record their removal. - Record all rules as changed if recording configured changes fails after the new generation was activated. - Make enforcers reload all rules after filtered removals with empty values, which Casbin matches as wildcards in memory only. - Refuse rule updates (e.g., update_policy()) before they change the shared enforcer, as the adapter cannot store them. - List locked_enforcer() in the API reference, warn against get_enforcer() in threaded apps, and label breaking changes. Refs #450 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Deduplicate recorded changes of writes by identifier in one helper, share one method refusing rule updates, fix the docstring order, and document reloads after removals with empty filter values. Refs #450 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Casbin removes rules from the enforcer before storing the removal. Let the shared enforcer be discarded if storing fails, so that all rules are loaded again on its next use, and refuse removing several rules at once, which FOCA's adapter does not support. Refs #450 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThis PR replaces per-request Casbin construction and full policy loading with a per-app shared enforcer synchronized through MongoDB change records, applying targeted rule updates where safe and performing full reloads for unsupported cases. It adds indexed resource-role lookups, lock-aware access, failure safeguards, change-aware mutation paths, reduced Casbin logging, and migration/scaling documentation, backed by extensive adapter, cache, concurrency, and cross-instance tests. Sequence diagram for cached policy enforcement and incremental synchronizationsequenceDiagram
participant Request
participant Cache as EnforcerCache
participant Changes as MongoDBChanges
participant Adapter
participant Enforcer
participant Policies as MongoDBPolicies
Request->>Cache: locked_enforcer()
Cache->>Changes: get_changes(with_changes=False)
alt version unchanged
Cache-->>Request: shared enforcer
else recorded changes available
Cache->>Changes: get_changes()
Cache->>Adapter: load_filtered_rules()
Adapter->>Policies: read changed rule filters
Policies-->>Adapter: matching rules
Cache->>Enforcer: apply targeted rule updates
Cache-->>Request: shared enforcer
else full reload required
Cache->>Enforcer: create SharedEnforcer
Cache->>Adapter: load_policy()
Adapter->>Policies: read all active rules
Policies-->>Adapter: active rules
Adapter-->>Cache: loaded rules
Cache-->>Request: shared enforcer
end
Request->>Enforcer: enforce()
Request-->>Cache: release lock
Sequence diagram for recording a policy mutation across app instancessequenceDiagram
participant Caller
participant Adapter
participant Policies as MongoDBPolicies
participant Changes as MongoDBChanges
participant OtherCache as EnforcerCache
participant OtherEnforcer as SharedEnforcer
Caller->>Adapter: add_policy()
Adapter->>Policies: write policy rule
Adapter->>Changes: _record_changes()
Changes-->>Adapter: increment version and append filter
Adapter-->>Caller: mutation result
OtherCache->>Changes: get_changes(with_changes=False)
OtherCache->>Changes: get_changes()
OtherCache->>Adapter: load_filtered_rules()
Adapter->>Policies: read matching rules
Policies-->>Adapter: current matching rules
OtherCache->>OtherEnforcer: apply targeted update
File-Level Changes
Assessment against linked issues
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 #454 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 27 28 +1
Lines 2872 3238 +366
==========================================
+ Hits 2872 3238 +366
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 8 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/security/access_control/enforcer_cache.py" line_range="492" />
<code_context>
+ """
+ # If no changes were recorded when rules were loaded, the document
+ # recording changes was created since, starting from version 0
+ same_record = changes.epoch == self._epoch or self._epoch is None
+ count = changes.version - self._version
+ if not same_record or not 0 < count <= len(changes.changes):
</code_context>
<issue_to_address>
**Revoked permissions stay cached**
When the cache loads before a change record exists, then that record is created, changed, and recreated before the cache checks it, `EnforcerCache._apply()` accepts the new epoch because `self._epoch` is `None`, applies only the new record’s changes, and leaves earlier policy changes stale, so revoked permissions remain effective.
Treat a newly observed epoch as incompatible when `self._epoch` is `None` and reload the enforcer.
</issue_to_address>
### Comment 2
<location path="foca/security/access_control/enforcer_cache.py" line_range="445" />
<code_context>
+ could not be read.
+ """
+ with self.lock:
+ state = self.adapter.get_changes(with_changes=False)
+ if self._enforcer is not None and (state.epoch, state.version) == (
+ self._epoch,
</code_context>
<issue_to_address>
**Lagging replicas preserve revoked access**
When `MONGO_URI` enables secondary reads and separate operations reach secondaries with different replication lag, `EnforcerCache` reads the change version and policy rules in separate operations, then records that version as current. If those reads go to secondaries with different replication lag, it stores stale rules under the newer version and does not reload them until another change, so revoked access remains effective.
Ensure change-marker and policy reads use a causally consistent read path, such as primary reads or an appropriately configured causal session.
Also at `foca/security/access_control/enforcer_cache.py:510`, `foca/security/access_control/enforcer_cache.py:523`.
</issue_to_address>
### Comment 3
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="432-433" />
<code_context>
+ changes = _distinct_changes(current, _document_change(replaced), *changes)
+ else:
+ id = self._insert(document)
+ self._record_changes(changes)
+ return id
def _insert(self, document: dict[str, Any]) -> str:
</code_context>
<issue_to_address>
**Crashes leave cached policies stale**
When a process stops after a policy write commits but before its change record is durably updated, the worker can stop after `_insert()` commits the rule but before `_record_changes()` persists its filter. Other app instances then keep their old enforcers indefinitely because no version change tells them to reload, so they miss the grant until another change is recorded or they restart.
Make the policy mutation and its change record atomic, or use a durable recovery mechanism that guarantees pending mutations are eventually recorded.
</issue_to_address>
### Comment 4
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="662" />
<code_context>
+ # enforcers see the subject with both roles meanwhile, as
+ # when loading all rules
+ if inserted is not None:
+ self._record_changes([_change(ptype, 0, rule)])
+ self._keep_latest_role(ptype, rule, roles)
+ # Also if interrupted, so that the subject is not left with more
</code_context>
<issue_to_address>
**Revoked permissions stay cached**
When mongoDB applies some or all of a delete before the call raises, or the delete succeeds but writing its change record fails, `_delete_policy_lines()` and `remove_filtered_policy()` record changes only after the delete returns, so a failed delete or journal write leaves other app instances enforcing cached revoked rules.
Make policy deletion and change recording reliable together, including when the delete call or journal write fails.
Also at `foca/security/access_control/foca_casbin_adapter/adapter.py:1144`.
</issue_to_address>
### Comment 5
<location path="foca/security/access_control/enforcer_cache.py" line_range="117" />
<code_context>
+ _update_policy = _update_policies = _update_filtered_policies = _refuse_update
+ _remove_policies = _refuse_update
+
+ def _remove_policy(self, *args: Any, **kwargs: Any) -> Any:
+ """Remove a rule (cf. Casbin's method).
+
</code_context>
<issue_to_address>
**Unpersisted grants remain effective**
When an enforcer-driven policy addition mutates Casbin’s model but the adapter write fails, `SharedEnforcer` does not discard its cache on failed additions, so the unpersisted grant remains in the shared model and later requests in that worker are authorized.
Discard the shared enforcer cache when an enforcer-driven policy addition fails.
Also at `foca/security/access_control/enforcement.py:810`.
</issue_to_address>
### Comment 6
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="126" />
<code_context>
- ptype
- for ptype, assertion in model.model.get("g", {}).items()
- if assertion.value.count("_") == 3
- ]
-
-
</code_context>
<issue_to_address>
**Application data gets modified**
When an app collection in the policy database is named `<collection_name>_changes`, `Adapter` uses that application collection as its change journal, so `_record_changes()` adds or modifies FOCA’s marker there, or fails when existing fields conflict with journal fields.
Use a change-journal collection name that cannot collide with an application collection, or reject the collision before writing.
</issue_to_address>
### Comment 7
<location path="foca/security/access_control/enforcer_cache.py" line_range="565" />
<code_context>
+ if (
+ not isinstance(ptype, str)
+ or not ptype
+ or not isinstance(field_index, int)
+ or not isinstance(values, list)
+ or not all(isinstance(value, str) for value in values)
</code_context>
<issue_to_address>
**Changed rules remain stale**
When a change record contains a negative or otherwise out-of-range integer filter index, `_get_filters()` accepts the index, so `_apply()` queries a nonexistent or mismatched rule field and advances the cached version without updating affected rules; app instances then keep stale policy.
Reject filter indexes outside the adapter’s supported rule-field range so `_apply()` falls back to a full reload.
</issue_to_address>
### Comment 8
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="331" />
<code_context>
+ changes = document.get(CHANGES_FIELD, [])
+ return PolicyChanges(
+ epoch=str(document.get(CHANGES_EPOCH_FIELD)),
+ version=document.get(CHANGES_VERSION_FIELD, 0),
+ changes=tuple(changes) if isinstance(changes, list) else (),
+ )
</code_context>
<issue_to_address>
**Malformed journal breaks enforcement**
When the changes document’s version is changed to a non-integer after an app instance has cached its enforcer, `get_changes()` passes the malformed version through to `EnforcerCache._apply()`, where subtracting the cached version raises `TypeError`; subsequent enforcement calls fail instead of recovering from the malformed journal.
Validate the journal version and route invalid values to a recovery path that does not pass them to `_apply()` arithmetic.
Also at `foca/security/access_control/enforcer_cache.py:493`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 8 findings to address first, and if change records are missed or applied incorrectly, an app instance can keep enforcing a revoked role and permit requests that should be denied; data accessed through those requests cannot be recovered by reverting. Reverting restores the previous enforcement behavior, but cannot undo any exposure that already occurred.
Blocking findings: foca/security/access_control/enforcer_cache.py:492, foca/security/access_control/enforcer_cache.py:445, foca/security/access_control/foca_casbin_adapter/adapter.py:433, foca/security/access_control/foca_casbin_adapter/adapter.py:662, foca/security/access_control/enforcer_cache.py:117, and 3 more
Address the automated review of the cached enforcer: - Reload all rules on the first recorded change after loading, as the record may have been re-created meanwhile. - Read rules and recorded changes from the primary, so that rules are not older than the version they are cached under. - Record removals also if deleting fails midway. - Reload all rules for out-of-range filters and malformed versions in change records. - Refuse app collections named like the changes collection. Refs #450 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
FOCA 0.17 creates a Casbin enforcer and loads all policy rules for every enforced request (and for each permissions-API, self-service and ownership-helper call), so
GET /taskstakes ~2.5 s with 100k rules. Casbin also logs allg2rules (i.e., subjects) atINFOwhen an enforcer is created with an adapter.This PR keeps one shared, cached enforcer per app instance (worker process) and keeps it consistent across threads, workers and replicas:
foca_casbin_adapter/adapter.py): every write of FOCA's adapter records which rules it may have changed, with one atomic update of a versioned document in<collection_name>_changes($incversion,$push/$sliceof the last 100 changes,$setOnInsertepoch). Covered writes: Casbin auto-save (add_policyetc.), the resource-role and ownership helpers, the permissions API (nowremove_policy_by_id()), configured policies (only the diff between generations),save_policy(). Rules removed or replaced by identifier are recorded before and after the write. New publicmark_changed()for rules changed in the database directly. New indexes(ptype, v0, v1)and(ptype, v2)for filtered reads.enforcer_cache.py): before each use, one small read of the version; if changed, only the recorded filters are reloaded and applied (all filters are read before the enforcer is mutated; a failed mutation discards the enforcer). Full reload on epoch change (also on the first record after loading without one), malformed versions or filters, more than 100 changes,save_policy/mark_changed, malformed records, models whose rules Casbin sorts (priority, subject priority) or with conditional role managers.ResourceRoleManager: aDomainManagersubclass that indexes resource-scoped role links by path (prefix lookup withis_within_path) and by subject, without Casbin's per-domain role-manager cache (no unbounded growth), so enforcement and role listings don't scan all rules.RLock; new public context managerlocked_enforcer().get_enforcer()keeps its signature and returns the shared enforcer (documented warning for threaded apps). Rule updates (update_policy()etc.) and batch removals (remove_policies()etc.), which the adapter cannot store, are refused before they change the shared enforcer; if a removal via the enforcer fails to be stored (Casbin removes in memory first), the enforcer is discarded and all rules are reloaded on next use.docs/migration-0.18.md(in nav and changelog),locked_enforcerin the API reference.Public API stays backward compatible (new optional
Adapter(changes_collection=...), new methods only); behaviour changes are listed in the migration notes.Benchmarks
Local machine, MongoDB 7, Python 3.13, reference resource-role model; 2
g2rules per task (owner user, owner client) plus 3prules, as proTES stores them. Medians, in ms. Script:bench.py(scratch, not committed): "before" = FOCA 0.17's per-request enforcer (load all rules, then enforce); "after" = the cached enforcer.Memory: ~55 MB per instance for 100k
g2rules.Verification
coverage run -m pytest(with MongoDB 7 on port 12345): 2049 passed, coverage 100%ruff check .,ruff format --check .: cleanmypy foca: no issuesmkdocs build --strict: OKast-grep scan,ast-grep test --skip-snapshot-tests: clean / 5 passedsemgrep --config=.semgrep --error ...: no findingsCI: all checks passed (unit tests on Python 3.11–3.14 with MongoDB 7.0/8.0 and lowest direct dependencies, lint/type-check/build, integration tests, chart install on kind, image scans, CodeQL, codecov patch/project, Read the Docs).
Declined review findings
get_enforcer()returns the shared enforcer without the lock (deep copy or deprecation suggested): a deep copy of a ~55 MB enforcer per call would defeat the purpose, and a deprecation warning would be noisy for single-threaded apps, for which it is safe. The docstring has a warning, and the docs and migration notes point tolocked_enforcer(). See open question.mark_changed()as remedy.locked_enforcer(): helpers raise HTTP errors (e.g., 404) inside the block, so this would let any client force full reloads (~2 s at 100k rules). Instead, only failed removals via the enforcer discard it, and updates/batch removals are refused before they touch it.get_changes(with_changes=...)boolean flag / two reads on a version change: kept; the second read only happens when rules changed.MAX_RECORDED_CHANGES: the docs are for operators; the limit is not configurable.test_policy_changes_default/test_is_for: kept, they cover the dataclass default and the cache identity check.Open questions
get_enforcer()be deprecated in favour oflocked_enforcer()(e.g., in 0.19)? Downstream, cloud-registry'spermissions.pyusesget_enforcer()(two call sites) and should switch tolocked_enforcer()or FOCA's helpers when it upgrades to 0.18.Closes #450
🤖 Generated with Claude Code