Skip to content

feat(access-control): add checks, model options - #682

Merged
uniqueg merged 7 commits into
devfrom
feat/613-checks-model-options
Nov 4, 2026
Merged

uniqueg merged 7 commits into
devfrom
feat/613-checks-model-options

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #613.

Access control options for what cloud-registry and other apps need, without changing defaults:

  • required_roles: the app refuses to start if a named role isn't mapped from a group or service client, one of resource_roles, or granted by a g or g2 rule of policies.
  • require_enforced: the app refuses to start unless enforce: true.
  • model: foca:<file>: names a model that FOCA ships. New packaged model granted_rights_model.conf: the reference model without the override of admins, for apps where operators must not see all user data. is_admin() is False with such models, so helpers treat admins as anyone else.
  • resource_roles_cover_custom_methods: roles on /tasks/1 also apply to POST /tasks/1:cancel. Off by default.
  • Docs: docs/access-control.md, docs/configuration/access-control.md, including what keyMatch2 can't tell apart in p rules, and that write access to the permissions API amounts to all rights.

Verification

  • ruff, mypy foca, strict docs build, full pytest with MongoDB on the branch merged with dev: 3674 passed, 1 skipped, 100% coverage.
  • Reviewers compared the fast path of _get_matching_domains with the plain functions over 13 grants and 20 request paths; the only differences are a grant on // and an empty request path.

Declined review findings

  • :verb handling as a required option, not an opt-in default: the issue says defaults don't change, hence the option. A third dispatch comment was optional.
  • Grants on //, empty request paths in the fast path: too contrived.
  • _admins_have_all_rights caches by path: changing a model needs a restart anyway, as the enforcer is cached too.
  • Semantically equivalent matchers other than a leading g(r.sub, "admin") || count as no override: failing closed on purpose, and documented.

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Strengthen access-control configuration and provide optional models and resource-role behavior for applications with stricter authorization requirements.

New Features:

  • Add startup checks for required roles and mandatory access-control enforcement.
  • Support selecting FOCA-packaged access-control models, including a model where administrators only receive explicitly granted rights.
  • Add optional support for applying resource-scoped roles to custom methods such as /tasks/1:cancel.
  • Treat administrators as ordinary subjects in helper functions when using models without the global administrator override.

Enhancements:

  • Extend access-control configuration validation and enforcer caching to account for the new options.
  • Document custom-method matching behavior, packaged models, administrator permissions, and permissions API security implications.

Documentation:

  • Document the new access-control configuration options and model behaviors.

Tests:

  • Add coverage for startup validation, packaged models, restricted administrator rights, and custom-method role matching.

uniqueg and others added 4 commits November 4, 2026 07:32
Add the startup checks `require_enforced` and `required_roles`, the
packaged model `foca:granted_rights_model.conf`, where admins only have
the rights granted to them, and the option
`resource_roles_cover_custom_methods` for AIP-136 paths such as
`/tasks/1:cancel`. Defaults don't change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Find custom-method domains without scanning, ignore trailing slashes and
tell admin overrides from the model, so that copies fail closed. Say what
`p` rules can't tell apart and what write access to the API amounts to.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Parse models as Casbin does, so that comments and matchers over several
lines count, and only a plain override does. Mapped admins of apps
without a model stay admins.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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

This PR adds opt-in access-control startup safeguards, packaged model selection with a least-privilege administrator model, and optional resource-role inheritance for custom methods, while preserving existing defaults and covering the behavior with documentation and tests.

Sequence diagram for custom-method resource-role authorization

sequenceDiagram
    participant Client
    participant App
    participant Cache as EnforcerCache
    participant Casbin

    Client->>App: POST /tasks/1:cancel
    App->>Cache: _get_domain_matching_func()
    Cache->>Cache: _strip_custom_method()
    Cache->>Casbin: is_within_path_or_custom_method()
    Casbin-->>App: Resource role applies to /tasks/1
    App->>Casbin: Enforce request
    Casbin-->>App: Allow or deny from p rules
    App-->>Client: Response
Loading

Flow diagram for access-control startup validation

flowchart TD
    Config[AccessControlConfig] --> Enforce[validate_require_enforced]
    Enforce -->|require_enforced and enforce false| RejectEnforce[Startup rejected]
    Enforce --> Register[register_access_control]
    Register --> Required[_check_required_roles]
    Required -->|Missing configured role| RejectRole[Startup rejected]
    Required -->|All required roles exist| Start[Application starts]
Loading

File-Level Changes

Change Details Files
Added opt-in startup validation for access-control enforcement and role availability.
  • Reject configurations requiring enforcement when enforce is false.
  • Validate required roles against mappings, resource roles, and configured g/g2 grants during app registration.
  • Preserve defaults and existing access-control enablement constraints.
foca/models/config.py
foca/security/access_control/register_access_control.py
docs/configuration/access-control.md
tests/security/access_control/test_checks_and_model_options.py
Added selectable packaged Casbin models, including a model where administrators only receive explicitly granted rights.
  • Support foca:<file> model references and validate packaged model names.
  • Package granted_rights_model.conf without the implicit administrator override.
  • Make ownership helpers and is_admin() follow the selected model, failing closed for unrecognized resource-role matchers.
foca/models/config.py
foca/security/access_control/constants.py
foca/security/access_control/api/granted_rights_model.conf
foca/security/access_control/api/resource_role_model.conf
foca/security/access_control/ownership.py
docs/access-control.md
docs/configuration/access-control.md
tests/security/access_control/test_checks_and_model_options.py
Added optional inheritance of resource-scoped roles by AIP-136 custom-method paths.
  • Recognize paths such as /tasks/1:cancel as custom methods of /tasks/1.
  • Integrate custom-method matching into the enforcer cache while retaining independent subpath and custom-method options.
  • Include matching options in cache identity and document identifier and keyMatch2 limitations.
foca/security/access_control/enforcer_cache.py
foca/security/access_control/enforcement.py
foca/models/config.py
docs/access-control.md
docs/configuration/access-control.md
tests/security/access_control/test_checks_and_model_options.py
Expanded documentation and automated coverage for the new configuration and authorization behavior.
  • Document permissions API security implications and administrator behavior under granted-rights models.
  • Test startup checks, packaged model resolution, administrator semantics, custom-method matching, cache invalidation, and defaults.
docs/access-control.md
docs/configuration/access-control.md
tests/security/access_control/test_checks_and_model_options.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 (fbc0961) to head (a92701f).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #682   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           60        60           
  Lines         7847      7908   +61     
=========================================
+ Hits          7847      7908   +61     
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: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 4 issues

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

## Individual Comments

### Comment 1
<location path="tests/security/access_control/test_checks_and_model_options.py" line_range="96-101" />
<code_context>
+    )
+    def test_exists(self, options: dict[str, Any]) -> None:
+        """Roles of mappings, of resources and of rules exist."""
+        module._check_required_roles(
+            AccessControlConfig(required_roles=["ops"], **options)
+        )
+
+    def test_client_mapping(self) -> None:
</code_context>
<issue_to_address>
**Required-role startup check untested**

When the call to `_check_required_roles` is removed from `register_access_control`, `TestRequiredRoles.test_missing` calls `_check_required_roles` directly, so it still passes if `register_access_control` stops calling that helper and apps start with missing required roles.

Test registration with a missing required role and assert that startup raises `ValueError`.
</issue_to_address>

### Comment 2
<location path="tests/security/access_control/test_checks_and_model_options.py" line_range="44" />
<code_context>
+            AccessControlConfig(enabled=True, require_enforced=True)
+
+    def test_enforced(self) -> None:
+        """With enforcement, nothing happens."""
+        assert AccessControlConfig(enabled=True, enforce=True, require_enforced=True)
+
</code_context>
<issue_to_address>
**Enforcement setting not asserted**

When configuration handling accepts `require_enforced=True` but returns `enforce=False`, `TestRequireEnforced.test_enforced` only asserts that the returned model is truthy; if configuration handling returns a model with `enforce=False`, this assertion still passes and the test misses that access control is not enforced.

Assert that the returned config has `enforce is True`.
</issue_to_address>

### Comment 3
<location path="foca/models/config.py" line_range="1025" />
<code_context>
     opt_in_header: str = "X-Request-Roles"
+    require_enforced: bool = False
+    required_roles: list[str] = Field(default_factory=list)
+    resource_roles_cover_custom_methods: bool = False
     require_admin: bool = False
     client_mapping: dict[str, str] | None = None
</code_context>
<issue_to_address>
**Custom-method coverage is ignored**

When `security.access_control.enabled` is false and `resource_roles_cover_custom_methods` is true, `SecurityConfig.validate_access_control` omits the option from its disabled-access-control checks, and `Foca.create_app()` skips access-control registration, so the setting has no effect.

Include `resource_roles_cover_custom_methods` in the disabled-access-control checks so this configuration is rejected.
</issue_to_address>

### Comment 4
<location path="tests/security/access_control/test_checks_and_model_options.py" line_range="296-298" />
<code_context>
+        adapter = Adapter(mongomock.MongoClient().db.coll, model=RESOURCE_MODEL)
+        adapter.add_policy("p", "p", ["owner", "/tasks/*", "POST"])
+        adapter.add_policy("g", "g2", ["user:a", "owner", TASK])
+        enforcer = EnforcerCache(
+            RESOURCE_MODEL, adapter, subpaths, methods
+        ).get_enforcer()
+        assert enforcer.enforce("user:a", TASK, "POST") is True
+        assert enforcer.enforce("user:a", f"{TASK}:cancel", "POST") is custom
</code_context>
<issue_to_address>
**Configured custom-method roles untested**

When `_get_enforcer_cache` no longer forwards `conf.resource_roles_cover_custom_methods`, `TestCustomMethods.test_roles` passes the option directly to `EnforcerCache`, so it still passes if `_get_enforcer_cache` stops forwarding the configured value and apps ignore `resource_roles_cover_custom_methods`.

Exercise custom-method role matching through the configured app’s enforcer-cache path with the option enabled and disabled.
</issue_to_address>

Linked issues

#613 feat(access-control): add checks and model options · 7 of 8 met · 1 to check by hand

# Requirement Status Notes
1 Refuse startup when require_enforced is true but access control is not enforced. ✅ Met The configuration validator rejects this combination, and the tests cover both the failure and enforced cases.
2 Refuse startup when a required role is not mapped or granted by configured policies. ✅ Met The check runs during access-control registration and checks group/client mappings, resource roles, and configured g/g2 rules.
3 Provide a packaged model where admins only have granted rights. ✅ Met The new foca:granted_rights_model.conf removes the admin override, and is_admin() treats admins as ordinary subjects for that model.
4 Apply resource roles to custom-method paths such as /tasks/1:cancel. ✅ Met The option is implemented for both subpath-enabled and exact-resource matching, and defaults to off.
5 Add tests for each option, including clear startup failures. ✅ Met Tests cover the startup checks and their failure messages, packaged-model behavior, custom-method matching, and defaults.
6 Achieve 100% coverage. 👀 Check by hand (runtime) Verify the coverage report from the full test run; the PR description reports 100% coverage.
7 Document the changes on the access-control page and configuration reference. ✅ Met Both requested documentation pages describe the new options and model behavior.
8 Keep defaults unchanged. ✅ Met require_enforced and resource_roles_cover_custom_methods default to false, required_roles defaults to an empty list, and the default model remains unchanged.

Sourcery assessment

Needs a human reviewer. 4 findings to address first, and when resource_roles_cover_custom_methods is enabled, a role on a resource can authorize requests such as POST /tasks/1:cancel, including operations that may change or delete data. Reverting removes the authorization behavior but cannot undo operations already performed under it.

Blocking findings: tests/security/access_control/test_checks_and_model_options.py:101, tests/security/access_control/test_checks_and_model_options.py:44, foca/models/config.py:1025, tests/security/access_control/test_checks_and_model_options.py:298


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

Comment thread foca/models/config.py Resolved
uniqueg and others added 2 commits November 4, 2026 08:57
Without access control, resource_roles_cover_custom_methods has no
effect, so it is refused like the other options. Also tests that the
required roles are checked on registration, and that the app's enforcer
follows the option.

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

@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

#613 feat(access-control): add checks and model options · 6 of 7 met

# Requirement Status Notes
1 require_enforced refuses to start unless access control is enforced. ✅ Met The config validator rejects require_enforced: true when enforce is false, with a clear error; tests cover both cases.
2 Required roles must exist, or the app refuses to start. ✅ Met _check_required_roles checks mappings, resource roles and configured g/g2 policies during access-control registration, and reports missing roles.
3 Provide a packaged model where admins have only granted rights. ✅ Met foca:granted_rights_model.conf is selectable by packaged name and omits the admin override; is_admin() treats admins as ordinary subjects with that model.
4 Resource roles also apply to custom-method paths such as /tasks/1:cancel. ✅ Met The opt-in setting handles custom-method paths, is off by default, and its matching behavior is tested.
5 Test each option, including clear failures, and achieve 100% coverage. ✅ Met The added tests cover validation failures, role registration, packaged-model behavior and custom-method matching; the PR verification reports 100% coverage.
6 Document the changes in the access-control page and configuration reference. 🟡 Partly met The access-control page explains custom-method matching, and the configuration reference includes the option in its example, but does not explain what it enables or that it is opt-in.
7 Defaults don't change. ✅ Met The new settings default to disabled or empty, and the existing default model remains unchanged.

Comment thread docs/configuration/access-control.md Resolved
@uniqueg
uniqueg merged commit 0c22684 into dev Nov 4, 2026
56 checks passed
@uniqueg
uniqueg deleted the feat/613-checks-model-options branch November 4, 2026 08:57
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.

feat(access-control): add checks and model options

1 participant