Skip to content

feat(access-control): add configured policies - #311

Merged
uniqueg merged 4 commits into
devfrom
feat/seed-policies
Oct 19, 2026
Merged

uniqueg merged 4 commits into
devfrom
feat/seed-policies

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

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:

security:
  access_control:
    policies:
      - [p, "*", /services, POST]
      - [p, owner, "/services/:id", "(PUT)|(DELETE)"]
  • Each rule is its policy type followed by its values.
  • The configuration is authoritative for configured rules. On startup, all rules are first validated against the model (FOCA refuses to start if any is invalid, and then changes nothing). Then stored configured rules are reconciled: rules no longer configured are removed, duplicates (e.g., from replicas starting concurrently) are removed, matching stored rules are adopted, and missing ones are added with identifiers.
  • Configured rules are marked configured in 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.
  • policies defaults to unset, in which case rules are not managed and the database is not accessed on startup; an empty list removes all configured rules.
  • Requires access_control.enabled, like the other access control options.
  • The access control example uses it instead of seeding rules in app.py; its README, model comments and smoke test are updated.
  • New Adapter.set_configured_policies() and Adapter.is_configured(); the exact-match query treats unset and null trailing fields alike, as loading does, and is shared with rule deletion.

Verification

  • New tests: rules added with identifiers; not managed if unset; all removed if empty; marked as configured; not duplicated across restarts with other stored rules kept; rules removed from the configuration and duplicates removed; matching stored rules adopted; invalid rules (unknown policy type, wrong number of values, invalid action regex, invalid value, no values) prevent startup and keep stored rules; policies requires enabled; permissions API returns 409 for configured rules.
  • pytest: all pass except the 7 tests marked mongodb, which need a live MongoDB (CI runs them); coverage 100%. ruff check, ruff format --check, mypy foca, mkdocs build --strict: pass.
  • Merged locally on top of dev after feat(auth): add claims from user info #308 and feat(api)!: keep operation fields set in specs #310 without conflicts: 684 tests pass, ruff and mypy pass.
  • CI on 240f899: all checks pass.
  • Sourcery review: 4 findings fixed, 2 declined with reasons (threads resolved).

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:

  • Add configuration-driven access control policies that are validated and reconciled with stored rules during startup.
  • Mark configured policy rules and prevent them from being modified or deleted through the permissions API.

Enhancements:

  • Preserve unmanaged access control rules while removing stale or duplicate configured rules and adopting matching existing rules.
  • Update the petstore access-control example to define its policies through application configuration.

Documentation:

  • Document access control policy configuration, reconciliation behavior, and API restrictions.

Tests:

  • Add coverage for policy validation, startup reconciliation, configuration requirements, and protected permissions API operations.

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]>
@sourcery-ai

sourcery-ai Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This 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 startup

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

File-Level Changes

Change Details Files
Add validated, configuration-driven policy seeding during access-control registration while preserving existing stored rules.
  • Introduce the policies access-control configuration field and require it to be used only when access control is enabled.
  • Validate every configured rule against the loaded Casbin model before writing any rule.
  • Add only exact policy lines that are not already stored, allowing generated identifiers and preserving API-managed rules.
  • Expose an exact-match adapter lookup and share its query logic with policy deletion.
foca/models/config.py
foca/security/access_control/register_access_control.py
foca/security/access_control/foca_casbin_adapter/adapter.py
Update documentation and the example application to define startup policies declaratively.
  • Document policy syntax, validation, persistence, and removal behavior.
  • Move petstore policy definitions from startup code into config.yaml.
  • Update example comments, README guidance, and smoke-test setup to rely on automatic registration.
docs/access-control.md
docs/configuration/access-control.md
examples/petstore-access-control/README.md
examples/petstore-access-control/app.py
examples/petstore-access-control/config.yaml
examples/petstore-access-control/petstore_policies.conf
tests/examples/test_petstore_access_control.py
Cover policy registration, validation, persistence, and configuration constraints with focused tests.
  • Verify insertion with identifiers, empty defaults, duplicate avoidance, retention of unrelated stored rules, and distinction between exact matches and extended rules.
  • Verify invalid policy types, arity, values, actions, and empty rules fail startup without partial writes.
  • Verify configured policies are rejected when access control is disabled.
tests/security/access_control/test_register_casbin_enforcer.py
tests/models/test_config.py

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 19, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (9f0ba7c) to head (0131a02).

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     
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 pushed a commit to elixir-cloud-aai/cloud-registry that referenced this pull request Oct 19, 2026
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]>
@uniqueg
uniqueg marked this pull request as ready for review October 19, 2026 21:12

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


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

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]>
@uniqueg
uniqueg merged commit adbe0e0 into dev Oct 19, 2026
13 checks passed
@uniqueg
uniqueg deleted the feat/seed-policies branch October 19, 2026 23:53
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