Repository navigation
feat(access-control): add configured policies - #311
Conversation
Apps relying on policy rules (e.g., which roles may do what) had to add them in code on startup. Add security.access_control.policies: rules, each given as its policy type followed by its values, are validated against the model (FOCA refuses to start if any is invalid) and added on startup unless stored already. Stored rules are never removed or changed on startup. Use them in the access control example. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThis PR adds declarative access-control policy configuration that is model-validated atomically at startup, seeds only missing exact rules while preserving stored/API-managed policies, and updates the adapter, documentation, example, and tests accordingly. Sequence diagram for validated access-control policy startupsequenceDiagram
participant App
participant Register as register_casbin_enforcer
participant Adapter
participant Model
participant PolicyStore
App->>Register: register_casbin_enforcer()
Register->>Model: validate_rule(ptype, rule, model)
alt any configured rule is invalid
Model-->>Register: ValueError
Register-->>App: Startup fails, no rules added
else all rules are valid
loop each configured policy
Register->>Adapter: has_policy_line(ptype, rule)
Adapter->>PolicyStore: exact-match query
PolicyStore-->>Adapter: stored or missing
alt rule is missing
Register->>Adapter: save_policy_line(ptype, rule)
Adapter->>PolicyStore: store rule with identifier
end
end
Register-->>App: Enforcer registered
end
File-Level Changes
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 #311 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 22 22
Lines 1357 1394 +37
=========================================
+ Hits 1357 1394 +37
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:
|
Use FOCA options proposed for 0.14.0: policy rules are set via security.access_control.policies instead of being added in code on startup (elixir-cloud-aai/foca#311), and the permission endpoints are routed to their own controller module via x-openapi-router-controller instead of being re-exported from the server module (elixir-cloud-aai/foca#310). Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Hey - I've found 6 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/security/access_control/register_access_control.py" line_range="249-251" />
<code_context>
+ for ptype, *rule in policies:
+ validate_rule(ptype, rule, adapter.model)
+ for ptype, *rule in policies:
+ if adapter.has_policy_line(ptype, rule):
+ continue
+ adapter.save_policy_line(ptype, rule)
+ logger.info(f"Added policy rule: {', '.join([ptype, *rule])}")
</code_context>
<issue_to_address>
**Old permissions return after restart**
When an administrator changes a configured rule through the permissions API and restarts the app without updating the configuration, `_add_policies` checks the configured values, not the rule ID or origin. After the API changes the stored values, startup inserts the old configured rule as a second permission, restoring the old grant or undoing the restriction.
Track configured rules by ID or origin and reconcile API edits instead of reinserting stale configured values.
</issue_to_address>
### Comment 2
<location path="foca/security/access_control/register_access_control.py" line_range="249-251" />
<code_context>
+ for ptype, *rule in policies:
+ validate_rule(ptype, rule, adapter.model)
+ for ptype, *rule in policies:
+ if adapter.has_policy_line(ptype, rule):
+ continue
+ adapter.save_policy_line(ptype, rule)
+ logger.info(f"Added policy rule: {', '.join([ptype, *rule])}")
</code_context>
<issue_to_address>
**Deleting one duplicate leaves access allowed**
When multiple replicas start concurrently while a configured rule is absent, both replicas can pass `has_policy_line` before either calls `save_policy_line`, which inserts the same rule under different IDs. The permissions API lists both, and deleting one by ID leaves the other stored and enforced.
Make checking and inserting a rule atomic, such as with a unique constraint and an upsert on the rule values.
</issue_to_address>
### Comment 3
<location path="foca/security/access_control/register_access_control.py" line_range="248-251" />
<code_context>
+ ValueError: A rule is invalid for the adapter's model (cf.
+ :py:func:`validate_rule`).
+ """
+ for ptype, *rule in policies:
+ validate_rule(ptype, rule, adapter.model)
+ for ptype, *rule in policies:
+ if adapter.has_policy_line(ptype, rule):
+ continue
+ adapter.save_policy_line(ptype, rule)
+ logger.info(f"Added policy rule: {', '.join([ptype, *rule])}")
</code_context>
<issue_to_address>
**Partial policy remains after failed startup**
When a multi-rule startup fails or is interrupted after at least one rule is saved, `_add_policies` saves rules one at a time without rollback, so the shared collection retains only part of the configured set when startup aborts. Existing replicas can load and enforce that partial policy before startup is retried.
Save the configured rules transactionally or roll back earlier inserts if a later write fails.
</issue_to_address>
### Comment 4
<location path="foca/security/access_control/register_access_control.py" line_range="249-250" />
<code_context>
+ for ptype, *rule in policies:
+ validate_rule(ptype, rule, adapter.model)
+ for ptype, *rule in policies:
+ if adapter.has_policy_line(ptype, rule):
+ continue
+ adapter.save_policy_line(ptype, rule)
+ logger.info(f"Added policy rule: {', '.join([ptype, *rule])}")
</code_context>
<issue_to_address>
**Deleted configured rule stays absent**
When a running replica deletes a configured rule after another replica's startup check but before startup completes, `has_policy_line` returns true, then the startup loop skips the rule after the concurrent deletion. The new replica finishes startup with the configured rule absent until another restart.
Coordinate startup reconciliation with permission deletions, or recheck and restore configured rules before startup completes.
</issue_to_address>
### Comment 5
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="193" />
<code_context>
+ Whether a rule with exactly these values is stored.
+ """
+ return (
+ self._collection.count_documents(_rule_query(ptype, rule), limit=1)
+ > 0
+ )
</code_context>
<issue_to_address>
**Null-padded rules are duplicated**
When a stored rule has explicit BSON nulls in trailing `vN` fields, `_rule_query` requires trailing fields to be absent, but `load_policy` treats trailing nulls as unset. Startup therefore misses the stored rule and inserts a duplicate; the exact-match query also cannot delete the null-padded row through the permissions API.
Normalize trailing nulls consistently with `load_policy` when querying rules for startup and deletion.
Also at `foca/security/access_control/foca_casbin_adapter/adapter.py:275-289`.
</issue_to_address>
### Comment 6
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="193-194" />
<code_context>
+ Whether a rule with exactly these values is stored.
+ """
+ return (
+ self._collection.count_documents(_rule_query(ptype, rule), limit=1)
+ > 0
+ )
</code_context>
<issue_to_address>
**Unindexed checks slow startup**
When the policy collection is large and one or more configured rules are absent, `has_policy_line` runs an exact-match query for each configured rule, but the adapter only creates an index on `id`. For each configured rule that is not stored, MongoDB scans the policy collection, so startup slows as the collection and configured policy list grow.
Add an index that supports the exact-match query over `ptype` and the rule value fields, or otherwise avoid a collection scan for each configured rule.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 6 findings to address first, and a configured rule that grants access can expose protected endpoints, and reverting the configuration will not remove that rule because it remains stored in the policy collection. The access must be revoked explicitly through the permissions API; until then, exposed data or access cannot be taken back.
Blocking findings: foca/security/access_control/register_access_control.py:251, foca/security/access_control/register_access_control.py:251, foca/security/access_control/register_access_control.py:251, foca/security/access_control/register_access_control.py:250, foca/security/access_control/foca_casbin_adapter/adapter.py:193, and 1 more
Address review findings on configured policies: - Configured rules are marked and the configuration is authoritative for them: on startup, missing rules are added (or stored ones with the same values marked), and configured rules removed from the configuration, as well as duplicates (e.g., added by replicas starting concurrently), are removed. The permissions API responds with 409 to requests to change or delete them, so that such changes cannot be reverted silently on restart. - Stored rules with trailing null values match rules without them, as when loading rules. - Without policies, stored rules are not changed on startup (and the database is not accessed); with an empty list, all configured rules are removed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Apps relying on policy rules (e.g., which roles may do what on which paths) had to add them in code on startup, as FOCA's access control example did. This adds
security.access_control.policies:configuredin the database. The permissions API responds with 409 Conflict to requests to change or delete them (documented in the specs); other rules (e.g., role assignments) are untouched and remain managed via the API.policiesdefaults to unset, in which case rules are not managed and the database is not accessed on startup; an empty list removes all configured rules.access_control.enabled, like the other access control options.app.py; its README, model comments and smoke test are updated.Adapter.set_configured_policies()andAdapter.is_configured(); the exact-match query treats unset and null trailing fields alike, as loading does, and is shared with rule deletion.Verification
policiesrequiresenabled; permissions API returns 409 for configured rules.pytest: all pass except the 7 tests markedmongodb, which need a live MongoDB (CI runs them); coverage 100%.ruff check,ruff format --check,mypy foca,mkdocs build --strict: pass.devafter feat(auth): add claims from user info #308 and feat(api)!: keep operation fields set in specs #310 without conflicts: 684 tests pass,ruffandmypypass.Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Manage access control policy rules declaratively through application configuration while preserving API-managed rules.
New Features:
Enhancements:
Documentation:
Tests: