Repository navigation
feat: config-driven access control - #259
Conversation
- Add `access_control.enforce` (default: false) to enforce Casbin policies on all operations of the app's specs that require authentication; skip operations with `security: []` or `x-foca-access-control: false`. Enforcement wraps resolved controllers via a Connexion resolver, so it runs after token validation. - Take the subject from validated token claims (`claim_identity`, default `sub`) and roles from `claim_groups`, optionally mapped via `group_mapping`. - Secure the permissions API: require `bearerAuth` and always enforce policies on it, so that unauthenticated and unauthorized users can no longer manage rules. - Add public helpers for resource-scoped roles and a reference model `resource_role_model.conf`. Refs #258 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Refs #258 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThis PR makes Casbin authorization configurable across authenticated API operations, derives safely namespaced subjects and roles from already validated OIDC claims, and secures the permissions API independently of the global enforcement flag. It also adds resource-scoped role helpers and a reference model, with extensive tests and documentation covering authorization semantics, fail-closed behavior, and compatibility fixes. Sequence diagram for config-driven access control enforcementsequenceDiagram
participant Client
participant Connexion
participant Auth as validate_token
participant Resolver as AccessControlResolver
participant AC as enforce_access_control
participant Casbin as CasbinEnforcer
participant Controller
Client->>Connexion: HTTP request
Connexion->>Auth: validate_token
Auth-->>Connexion: Validated token claims
Connexion->>Resolver: resolve operation
Resolver->>AC: Wrapped controller
Connexion->>AC: Execute request
AC->>AC: get_current_subject()
AC->>AC: get_current_groups()
AC->>Casbin: enforce(subjects, request.path, request.method)
alt Policy allows access
Casbin-->>AC: allowed
AC->>Controller: Invoke controller
Controller-->>Client: Response
else Missing identity or denied
Casbin-->>AC: denied
AC-->>Client: 401 or 403
end
Flow diagram for enforced and public API operationsflowchart TD
A[Request] --> B{Requires authentication?}
B -->|No: security: []| P[Public operation]
B -->|Yes| C[Validate bearer token]
C --> D{Access control opt-out?}
D -->|Yes: x-foca-access-control: false| O[Invoke controller]
D -->|No| E{Identity claim present?}
E -->|No| U[401 Unauthorized]
E -->|Yes| F[Build namespaced user and group subjects]
F --> G[Load current Casbin policies]
G --> H{Any subject is allowed?}
H -->|Yes| O
H -->|No| X[403 Forbidden]
File-Level Changes
Assessment against linked issues
Possibly linked issues
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
- Prefix user identifiers in rules with `access_control.subject_prefix` (default: `user:`) and group claim values without `group_mapping` with `group:`, so that a user identifier or identity provider group equal to a role name (e.g., `admin`, `owner`) no longer grants that role. - Resource role helpers take and return unprefixed user identifiers, accept a `ptype` argument (default: `g2`) and raise a `ValueError` if the model does not define that role type with three fields, instead of silently writing meaningless rules (e.g., with the default model). - `access_control.claim_identity` now defaults to `auth.claim_identity`. Refs #258 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Refs #258 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Recent PyJWT versions type `options` of `jwt.decode()` as a TypedDict, which makes `mypy foca` (and thus CI) fail. Ignore the argument type, as already done for `key`, to stay compatible with older PyJWT versions allowed by `PyJWT~=2.4`. Refs #258 Co-Authored-By: Claude Opus 5.5 <[email protected]>
`pkg_resources` is no longer shipped with recent setuptools, which CI installs, so test collection failed. Resolve the default model path the same way `AccessControlConfig` does. Refs #258 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #259 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 20 22 +2
Lines 969 1087 +118
==========================================
+ Hits 969 1087 +118
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:
|
Restore 100% line coverage (required by Codecov): unprefixed subjects in resource role listings, invalid group claim values, and the error logged when enforcement is enabled without auth. Refs #258 Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Hey - I've found 11 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/models/config.py" line_range="737" />
<code_context>
user_headers: Optional[set] = None
+ enforce: bool = False
+ claim_identity: Optional[str] = None
+ subject_prefix: str = "user:"
+ claim_groups: Optional[str] = None
+ group_mapping: Optional[Dict[str, str]] = None
</code_context>
<issue_to_address>
**Role-name identities gain access**
When `subject_prefix` is configured as an empty string and a user's identity matches a privileged role, `_prefix_subject()` returns the identity unchanged, so the reference model treats an identity such as `admin` as the `admin` role and grants its permissions.
Reject an empty `subject_prefix` in `AccessControlConfig`.
Also at `foca/security/access_control/enforcement.py:69`.
</issue_to_address>
### Comment 2
<location path="foca/models/config.py" line_range="738" />
<code_context>
+ enforce: bool = False
+ claim_identity: Optional[str] = None
+ subject_prefix: str = "user:"
+ claim_groups: Optional[str] = None
+ group_mapping: Optional[Dict[str, str]] = None
</code_context>
<issue_to_address>
**Users inherit matching group access**
When `subject_prefix` is `group:` and an unmapped group value matches a user's identifier, `_prefix_subject()` gives the user the same subject as the group, so the user receives access granted to that group even when the token does not contain it.
Prevent user subjects from sharing the namespace used for unmapped group subjects.
Also at `foca/security/access_control/enforcement.py:19`, `foca/security/access_control/enforcement.py:69`, `foca/security/access_control/enforcement.py:106`, `foca/models/config.py:737`.
</issue_to_address>
### Comment 3
<location path="foca/foca.py" line_range="113-115" />
<code_context>
cnx_app = register_openapi(
app=cnx_app,
specs=self.conf.api.specs,
+ enforce_access_control=(
+ self.conf.security.auth.required
+ and self.conf.security.access_control.enforce
+ ),
)
</code_context>
<issue_to_address>
**Enforcement skipped with per-operation authentication**
When `access_control.enforce` is true, `auth.required` is false, and an API spec independently declares an operation requiring authentication, `auth.required` being false prevents `register_openapi` from installing the access-control resolver, even when an API operation declares authentication in its OpenAPI spec and Connexion validates its bearer token. That authenticated caller reaches the controller without a policy check.
Reject this conflicting configuration when secured operations are present, or enable the resolver and register the access-control backend for those operations regardless of `auth.required`.
</issue_to_address>
### Comment 4
<location path="foca/api/register_openapi.py" line_range="135-136" />
<code_context>
+ global_security = spec.get('security')
+ operations = set()
+ for path, path_item_object in spec.get('paths', {}).items():
+ for operation, operation_object in path_item_object.items():
+ if operation not in _OPERATION_OBJECT_FIELDS:
+ continue
+ if operation_object.get('x-foca-access-control') is False:
</code_context>
<issue_to_address>
**Referenced operations skip enforcement**
When an authenticated path item is defined through a `$ref`, `_get_enforced_operations` scans only methods present directly in each path item and does not resolve path-item `$ref`s. Connexion can register the referenced authenticated operations, but they are absent from the enforcement set, so their controllers run without policy checks.
Resolve path-item references before collecting enforced operations, or derive the enforcement set from the resolved operations Connexion registers.
</issue_to_address>
### Comment 5
<location path="foca/api/register_openapi.py" line_range="140" />
<code_context>
+ continue
+ if operation_object.get('x-foca-access-control') is False:
+ continue
+ if not operation_object.get('security', global_security):
+ continue
+ operations.add((path, operation))
</code_context>
<issue_to_address>
**Public operations reject anonymous callers**
When an operation's security requirements include an empty requirement object, such as `security: [{}]`, `_get_enforced_operations()` treats the non-empty security list as requiring authentication and wraps the operation. `enforce_access_control()` then rejects anonymous callers with 401, despite the specification allowing them.
Exclude operations with an empty security requirement alternative from the enforced operations set.
Also at `foca/api/register_openapi.py:141`.
</issue_to_address>
### Comment 6
<location path="foca/security/access_control/enforcement.py" line_range="67-69" />
<code_context>
+ return None if subject is None else str(subject)
+
+
+def _prefix_subject(subject: str) -> str:
+ """Add configured prefix to a subject, as used in policy rules."""
+ return f"{_get_access_control_config().subject_prefix}{subject}"
+
+
</code_context>
<issue_to_address>
**Existing policy grants stop matching**
When persisted rules contain unprefixed user identifiers when enforcement is enabled, `_prefix_subject()` checks the request using a prefixed subject, while `get_enforcer()` loads the existing rules unchanged. Casbin no longer matches those grants, so previously authorized users, including administrators relying on them to manage the permissions API, are denied.
Preserve compatibility with persisted unprefixed subjects or migrate those policy rows when enabling the prefix.
Also at `foca/security/access_control/enforcement.py:150`.
</issue_to_address>
### Comment 7
<location path="foca/security/access_control/enforcement.py" line_range="214" />
<code_context>
+ f"{operation.path}"
+ )
+ return Resolution(
+ function=enforce_access_control(resolution.function),
+ operation_id=resolution.operation_id,
+ )
</code_context>
<issue_to_address>
**Decorated routes reject allowed callers**
When config-driven enforcement wraps a controller already decorated with `check_permissions`, and the new policy allows a request that the legacy check rejects, `AccessControlResolver` wraps the controller, so the request must pass both the new claim-based check and the separate legacy check. The legacy check rejects the request, and the caller receives 403.
Avoid running the separate legacy permission check after config-driven enforcement has authorized the request.
</issue_to_address>
### Comment 8
<location path="foca/security/access_control/enforcement.py" line_range="69" />
<code_context>
+
+def _prefix_subject(subject: str) -> str:
+ """Add configured prefix to a subject, as used in policy rules."""
+ return f"{_get_access_control_config().subject_prefix}{subject}"
+
+
</code_context>
<issue_to_address>
**Decorated controllers reject namespaced rules**
When a controller uses `check_permissions` and its rules use the documented `subject_prefix` format, `check_permissions` still authorizes using the legacy header-based subject, without applying `subject_prefix`; rules created for this feature use `user:<id>`. A controller protected by `check_permissions` therefore denies a user whose namespaced rule would allow access, including when `access_control.enforce` is false and the decorator is the only enforcement path.
Make the legacy decorator evaluate subjects using the same namespacing and validated-claim rules, or keep its rule format explicitly separate and ensure the documentation and helper APIs do not imply the new format applies to it.
</issue_to_address>
### Comment 9
<location path="foca/api/register_openapi.py" line_range="106-108" />
<code_context>
spec.connexion = {} if spec.connexion is None else spec.connexion
+ connexion_kwargs = spec.model_dump().get('connexion', {})
+ if enforce_access_control:
+ connexion_kwargs['resolver'] = AccessControlResolver(
+ resolver=connexion_kwargs.get('resolver'),
+ operations=_get_enforced_operations(spec_parsed),
+ )
app.add_api(
</code_context>
<issue_to_address>
**Custom resolver fails at runtime**
When access control enforcement is enabled and `connexion.resolver` is configured in a Connexion-supported form other than a resolver instance, `connexion.resolver` is passed through as `resolver` without checking its type, then `AccessControlResolver.resolve()` calls `.resolve()` on it. If an app configures a resolver in a form accepted by Connexion but not as a resolver instance, resolving API operations fails and those endpoints are unavailable.
Normalize supported resolver classes or import strings into resolver instances before wrapping them, or reject unsupported values during configuration validation.
</issue_to_address>
### Comment 10
<location path="foca/security/access_control/enforcement.py" line_range="267-268" />
<code_context>
+ Raises:
+ ValueError: The model does not define resource-scoped roles.
+ """
+ return _get_resource_role_enforcer(ptype).add_named_grouping_policy(
+ ptype, _prefix_subject(subject), role, resource
+ )
+
</code_context>
<issue_to_address>
**Concurrent grants create duplicates**
When two requests concurrently grant the same subject, role, and resource while that grant is absent, each `add_resource_role()` call loads an enforcer before either inserts the rule, so both persist an identical row. `list_resource_roles()` then returns duplicate entries.
Make the grant operation atomic or enforce uniqueness for resource-role rows.
</issue_to_address>
### Comment 11
<location path="docs/access_control/README.md" line_range="302-306" />
<code_context>
+
+def postService(**kwargs):
+ service_id = ... # create resource
+ add_resource_role(
+ subject=get_current_subject(),
+ role="owner",
+ resource=f"{request.path.rstrip('/')}/{service_id}",
+ )
+ return service_id
+
</code_context>
<issue_to_address>
**Resource and policy state diverge**
When resource creation or deletion and its separate ACL helper call fail or overlap, creation can persist a resource before its owner grant is written, leaving an orphaned resource; a retry can create another one. Deletion cleanup can also race with a grant and leave a stale rule that grants access if the path is reused.
Make resource lifecycle changes and their ACL updates atomic, including cleanup during deletion.
Also at `docs/access_control/README.md:312`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 11 findings to address first, and a flaw in the policy evaluation or token-claim handling could let an authenticated user reach protected API operations or manage permissions they should not access. Reverting would stop the new enforcement behavior, but it cannot undo data or access already exposed.
Blocking findings: foca/models/config.py:737, foca/models/config.py:738, foca/foca.py:115, foca/api/register_openapi.py:136, foca/api/register_openapi.py:140, and 6 more
There was a problem hiding this comment.
🟡 Changes recommended
Referenced paths bypass authorization, and optional-authentication and callable-resolver configurations regress.
3 open issues
What changed in this PR
Adds configuration-driven Casbin authorization using validated token claims, secures the permissions API, and provides resource-role helpers.
Changes:
- Adds enforcement configuration, claim-based identity, and group mapping.
- Introduces resource-role helpers and a reference policy model.
- Documents usage and adds regression tests and compatibility fixes.
| File | Description |
|---|---|
| tests/test_foca.py | Tests enforcement without authentication configuration. |
| tests/test_files/conf_enforce_access_control_without_auth.yaml | Adds disabled-authentication fixture. |
| tests/security/access_control/test_enforcement.py | Tests enforcement, claims, permissions, and helpers. |
| tests/security/access_control/test_access_control_server.py | Replaces deprecated resource lookup. |
| README.md | Links configuration-driven enforcement documentation. |
| foca/security/auth.py | Adds PyJWT type-check suppression. |
| foca/security/access_control/register_access_control.py | Enforces permissions-API authorization. |
| foca/security/access_control/enforcement.py | Implements enforcement and resource-role helpers. |
| foca/security/access_control/constants.py | Identifies the reference model. |
| foca/security/access_control/api/resource_role_model.conf | Defines resource-scoped authorization. |
| foca/security/access_control/api/access-control-specs.yaml | Requires validated bearer authentication. |
| foca/security/access_control/__init__.py | Exports public helpers. |
| foca/models/config.py | Adds access-control configuration fields. |
| foca/foca.py | Connects configuration to enforcement. |
| foca/api/register_openapi.py | Wraps selected operations with authorization. |
| docs/access_control/README.md | Documents configuration, roles, and permissions security. |
Review effort: Balanced


Closes #258
Summary
Makes FOCA's Casbin-based access control usable through config alone and closes the privilege escalation hole in the permissions API.
access_control.enforce(defaultfalse). When enabled, policies are enforced on every operation of the app's specs that requires authentication. Operations withsecurity: []orx-foca-access-control: falseare skipped. Enforcement wraps resolved controllers via a Connexion resolver (AccessControlResolver), so it runs after token validation.access_control.claim_identity, defaulting toauth.claim_identity, i.e.sub), not by re-decoding the token or reading headers.claim_groups(e.g.eduperson_entitlement) plus optionalgroup_mapping(claim value -> role). The resulting roles are checked as additional subjects, so no per-user rules are needed (e.g. for admins).subject_prefix(defaultuser:), and group claim values withoutgroup_mappingwithgroup:. Roles (fromgroup_mappingorgrules) are used as is. A user ID or IdP group equal to a role name (admin,owner, …) therefore does not grant that role.access-control-specs.yamlnow requiresbearerAuth(validated byfoca.security.auth.validate_token), and policies are always enforced on it, irrespective ofenforce. Unauthenticated requests get 401, unauthorized ones 403.foca.security.access_control:get_current_subject(),get_current_groups(),add_resource_role(),remove_resource_role(),list_resource_roles(),remove_resource(). The resource-role helpers take and return unprefixed user IDs, acceptptype(defaultg2), and raiseValueErrorif the model does not define that role type with three fields (e.g. the default model, whoseg2groups objects).resource_role_model.conf: resource-scoped roles (g2 = _, _, _),*= any authenticated user,owner/maintainerexamples,adminrole = everything.docs/access_control/README.md(config, claims, subject namespaces, resource roles with an ownership-on-create example, permissions API), and a pointer inREADME.md.dev):mypy focafailed onfoca/security/auth.pybecause recent PyJWT typesjwt.decode(options=…)as a TypedDict; silenced with# type: ignore[arg-type](as forkeyon the line above), keeping compatibility with older PyJWT allowed byPyJWT~=2.4. A test importedpkg_resources, which recent setuptools (installed in CI) no longer ships; replaced withimportlib.resources.Decisions
Raised as open questions in the first version of this PR and decided since:
subject_prefix, defaultuser:) by enforcement and the helpers.group_mappingis set; without a mapping, raw values are prefixed withgroup:.ptypeargument (defaultg2) plus a model check that raises instead of silently writing wrong rules.access_control.claim_identitydefaults toauth.claim_identityand can be overridden. Docs recommend a stable, IdP-assigned claim such assub.Verification
CI: all checks pass: lint, mypy and unit tests on Python 3.9–3.12 × MongoDB 4.4–7.0 (16 jobs), petstore integration tests, Docker builds (4 jobs), Codecov patch and project (coverage stays at 100%), Read the Docs.
Locally (Python 3.12 venv,
pip install -e .[dev], latest setuptools):flake8: cleanmypy foca: no issuespytest tests/security/access_control/test_enforcement.py: 53 passed (no MongoDB needed; uses mongomock and a mocked bearer-info function). Covers: public ops, authentication before enforcement, any-authenticated create, owner/maintainer/non-member, admin via group mapping, unmapped group values ignored, rawgroup:values without mapping, user IDs and groups equal to role names, missing identity claim, identity claim fallback/override, per-op opt-out,enforce: false, permissions API (401/403/200, also withenforce: false), subject/group helpers, resource-role helpers (persistence, custom prefix, customptype, incompatible models).subject_prefixset to empty, the collision tests fail (usersowner/admingain those roles). Both pass with the change.pytestlocally: all tests pass except the 22 existing ones that need a real MongoDB onlocalhost:12345(adapter, permission controllers,check_permissions), which wasn't running locally; they pass in CI.Risks
auth.requiredis true (the default). It now needs a valid bearer token plus a Casbin rule (or theadminrole in the reference model). Admins of apps usingdefault_model.confneed explicit rules for the permissions API routes, added directly to the database or via group mapping.access_control.api_specs) withoutsecuritynow deny all requests (fail-closed).user:alice,group:…).casbin.Enforcer), ascheck_permissionsalready does: never stale, but adds latency under load.Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Enable secure, configuration-driven access control enforcement across authenticated APIs while closing the permissions API privilege-escalation gap.
New Features:
Bug Fixes:
Enhancements:
CI:
Documentation:
Tests: