Repository navigation
feat(access-control): add checks, model options - #682
Conversation
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]>
Reviewer's GuideThis 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 authorizationsequenceDiagram
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
Flow diagram for access-control startup validationflowchart 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]
File-Level Changes
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 #682 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 60 60
Lines 7847 7908 +61
=========================================
+ Hits 7847 7908 +61
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 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
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]>
There was a problem hiding this comment.
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. |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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 ofresource_roles, or granted by agorg2rule ofpolicies.require_enforced: the app refuses to start unlessenforce: true.model: foca:<file>: names a model that FOCA ships. New packaged modelgranted_rights_model.conf: the reference model without the override of admins, for apps where operators must not see all user data.is_admin()isFalsewith such models, so helpers treat admins as anyone else.resource_roles_cover_custom_methods: roles on/tasks/1also apply toPOST /tasks/1:cancel. Off by default.docs/access-control.md,docs/configuration/access-control.md, including whatkeyMatch2can't tell apart inprules, and that write access to the permissions API amounts to all rights.Verification
ruff,mypy foca, strict docs build, fullpytestwith MongoDB on the branch merged withdev: 3674 passed, 1 skipped, 100% coverage._get_matching_domainswith 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
:verbhandling 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.//, empty request paths in the fast path: too contrived._admins_have_all_rightscaches by path: changing a model needs a restart anyway, as the enforcer is cached too.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:
/tasks/1:cancel.Enhancements:
Documentation:
Tests: