Repository navigation
fix(access-control)!: validate and anchor rules - #287
Conversation
Bearer token validation fetched the OpenID Connect discovery document from whatever issuer a token named, and validated the token against that issuer's keys and user info endpoint. Tokens minted by any OpenID Connect provider could therefore be accepted, and the service could be made to send requests to arbitrary URLs. - accept only tokens of the trusted issuers listed in the new `security.auth.issuers` setting; reject all others before any network request; reject all tokens if no issuers are configured - check that the discovery document was issued for the token's issuer and pass the issuer to `jwt.decode` - always verify the signature locally; the user info endpoint is only an additional check (`validate_userinfo`), done after verification, whose `sub` must match the token's - require `exp`, `iat`, `iss` and the identity claim - return the verified claims; `add_key_to_claims` works again - fetch documents with timeouts and without following redirects; cache discovery documents and JWK sets (`timeout`, `cache_ttl`), refetching JWK sets on unknown key IDs at most every 30 seconds - log warnings on app creation if no issuers are configured, audience validation is disabled or expired tokens are accepted BREAKING CHANGE: `security.auth.issuers` must list the trusted token issuers; otherwise, all tokens are rejected. `validation_methods`, `validation_checks` and `claim_issuer` are removed; use `validate_userinfo: True` to additionally validate tokens via the user info endpoint. Signatures are always verified locally. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Also drop the unreachable error handling for decoding the token header, which can always be decoded once the token itself was decoded. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There were two ways of enforcing access control: config-driven enforcement (`access_control.enforce`, `enforce_access_control`) based on validated token claims, and the `check_permissions` decorator based on flask-authz, which took subjects from request headers. The latter only worked because `validate_token` copied all token claims into the request headers (replacing the original headers), and used client-set headers where no token was validated. - remove `check_permissions`, the flask-authz dependency and the `owner_headers`/`user_headers` settings; use `enforce_access_control` to enforce policies on single controllers - stop copying token claims into request headers; use `get_current_subject()`, `get_current_groups()` or `token_info` - read validated token info from Connexion's request context directly instead of treating any `AttributeError` as "no claims" - depend on pycasbin, the maintained successor of the casbin package (previously pulled in via flask-authz) BREAKING CHANGE: `check_permissions` and the `owner_headers` and `user_headers` settings are removed (configs using them fail validation), and token claims are no longer available as request headers. Use `access_control.enforce` or the `enforce_access_control` decorator, and `get_current_subject()`/`get_current_groups()`. Closes #276 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Connexion raises `BadRequestProblem` for requests failing schema validation (e.g., request bodies with unknown properties or values not matching a pattern). The exception is not in FOCA's default exception mapping, so such requests were answered with 500 instead of 400. Add `BadRequestProblem` to the default mapping. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Rules were serialized to comma-separated lines and split again when loaded, so values containing commas (e.g., identity claims passed to `add_resource_role`) turned into extra fields, and malformed rules could break enforcement for all requests. Stored documents were copied onto rules as a whole, the permissions API accepted and stored arbitrary rule objects, and actions in the reference model matched as substrings. - validate rules on every write path (adapter, permissions API, resource role helpers): policy type defined in the model, matching number of values, values non-empty strings of at most 1024 characters without commas or line breaks and not starting with `#`, and `act` values valid regular expressions - load rules from `ptype` and `v0` to `v5` only, passed as lists; skip invalid stored rules with a warning - deny requests with subjects that are not valid rule values (403) - respond with 400 to invalid rules in the permissions API; disallow additional properties in its `Permission` and `Rule` schemas, drop the unused `rule_section`, and return only rule fields - anchor action patterns in the reference model and petstore example - add `api_swagger_ui` and `api_serve_spec` (default: off) to serve the Swagger UI and spec of the permissions API BREAKING CHANGE: action patterns of the reference model must match the whole HTTP method. The permissions API rejects rules with unknown policy types, extra keys or a wrong number of values, and no longer serves its Swagger UI and spec unless `api_swagger_ui` and `api_serve_spec` are set. Closes #277 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThis PR hardens access control by validating and safely loading policy rules across every write path, anchoring action matching, sanitizing permissions API persistence and responses, and making API documentation endpoints opt-in. It also replaces legacy header/flask-authz authorization and JWT validation configuration with trusted-issuer, cached OIDC/JWKS verification and claim-based enforcement, while correcting schema-validation errors to 400 and updating examples, documentation, and regression tests. Sequence diagram for validated permission rule creationsequenceDiagram
actor Admin
participant API as PermissionsAPI
participant Validator as validate_rule
participant Adapter as CasbinAdapter
participant Store as MongoDB
Admin->>API: POST /permissions
API->>Validator: validate_rule(policy_type, values, model)
alt invalid rule
Validator-->>API: ValueError
API-->>Admin: 400 Bad Request
else valid rule
Validator-->>API: validated values
API->>Adapter: save_policy_line(ptype, rule)
Adapter->>Validator: validate_rule(ptype, rule)
Adapter->>Store: insert CasbinRule
Store-->>Admin: permission id
end
Sequence diagram for safe policy loading and enforcementsequenceDiagram
participant Store as MongoDB
participant Adapter as CasbinAdapter
participant Model as CasbinModel
participant Enforcement as AccessControl
Store-->>Adapter: stored policy documents
loop each document
Adapter->>Adapter: validate_rule(ptype, values, model)
alt invalid stored rule
Adapter-->>Adapter: log warning and skip
else valid stored rule
Adapter->>Model: add_policy(ptype, values)
end
end
Enforcement->>Model: enforce(subject, path, method)
alt invalid subject
Enforcement-->>Enforcement: validate_rule_value(subject)
Enforcement-->>Enforcement: deny with 403
else valid subject
Model-->>Enforcement: policy decision
end
Flow diagram for trusted JWT validation and claim-based access controlflowchart LR
Request[Bearer token request] --> Decode[Decode JWT claims]
Decode --> Issuer{Trusted issuer?}
Issuer -->|No| Reject[401 Unauthorized]
Issuer -->|Yes| Discovery[_get_oidc_config]
Discovery --> JWKS[_get_jwk_set]
JWKS --> Verify[_verify_signature]
Verify --> UserInfo{validate_userinfo enabled?}
UserInfo -->|Yes| ValidateInfo[_validate_userinfo]
UserInfo -->|No| Claims[Verified claims]
ValidateInfo --> Claims
Claims --> Enforce[enforce_access_control]
Enforce --> Decision[Casbin enforcement decision]
File-Level Changes
Assessment against linked issues
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 #287 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 22 22
Lines 1091 1156 +65
=========================================
+ Hits 1091 1156 +65
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:
|
Discovery documents and JWK sets were only cached after successful fetches, so while an identity provider was unavailable, every request fetched them again, amplifying load on the provider during an outage. Do not fetch a discovery document or JWK set again within `JWKS_REFETCH_COOLDOWN` seconds after a failed attempt. User info requests depend on the token and are not throttled. Also test that tokens without key ID are verified with all signing keys, not only the first one. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Explain that without `audience`, tokens that trusted issuers issued for other services are accepted, and recommend setting it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Hey - I've found 1 issue
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="90" />
<code_context>
+ Raises:
+ ValueError: The rule is invalid (cf. :py:func:`validate_rule`).
"""
+ validate_rule(ptype, rule)
line = CasbinRule(ptype=ptype)
for index, value in enumerate(rule):
</code_context>
<issue_to_address>
**Invalid rules are saved successfully**
When a caller writes directly through `Adapter.save_policy_line` or `Adapter.add_policy` with a rule that is invalid for the configured model, `save_policy_line` calls `validate_rule` without a model, so undefined policy types, incorrect value counts, and invalid action regexes pass validation and are written. `load_policy` later skips the rules, leaving callers with successful writes that never take effect.
Validate each rule against the configured model before saving it.
Also at `foca/security/access_control/foca_casbin_adapter/casbin_rule.py:72`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 1 finding to address first, and a flaw in JWT verification or policy enforcement could accept an untrusted token or grant access to a protected operation, exposing data or access that a revert cannot recover. The change also replaces core authentication and authorization behavior, so errors can affect who is trusted and which rules are enforced.
Blocking findings: foca/security/access_control/foca_casbin_adapter/adapter.py:90
The section on header properties was removed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Writing through `Adapter.save_policy_line` (e.g., via `Enforcer.add_policy`) only checked rule values, so rules with policy types not defined in the model, a wrong number of values or invalid action patterns were stored successfully, but skipped when loading policies. Let the adapter take the path to the Casbin model and validate rules against it before storing them; FOCA passes the configured model. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Tokens without key ID are verified with each signing key of the issuer. Keys of another type or algorithm than the token (e.g., an EC key for an RS256 token) raised `InvalidAlgorithmError`, which rejected the token instead of trying the remaining keys. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…efactor/drop-header-checks
…o fix/validate-rules
Summary
Third PR of the v0.14.0 production-readiness series. Builds on #286 (which builds on #274); please merge those first. Until then, this diff includes their commits; the changes of this PR are the last two commits.
Problems
CasbinRule.__str__) and split again by pycasbin on load. A value containing a comma, e.g., an identity claim passed toadd_resource_role, turned into extra fields, so crafted identities could become unintended rules. Malformed rules (e.g., an unbalanced)) could make loading, and so every enforced request, fail.load_policycopied every stored document key onto rules,putPermissionstored the client'sruleobject as is, and the permissions API schemas allowed additional properties;policy_typewas free text andrule_sectionwas ignored.regexMatch(r.act, p.act), so a rule forGETmatched any method containingGET.BadRequestProblem) were answered with 500 instead of 400 in all FOCA apps, as the exception was not in FOCA's default mapping.Changes
validate_rule,validate_rule_valueinfoca_casbin_adapter/casbin_rule.py) on every write path: adapter (save_policy_line), permissions API (POST/PUT),add_resource_role/remove_resource_role. Rules must use a policy type defined in the model with a matching number of values. Values must be non-empty strings of at most 1024 characters, must not contain commas or line breaks, and must not start with#.actvalues must be valid regular expressions.Adapter(..., model=...)(FOCA passesaccess_control.model) checks policy types, value counts and action patterns before storing, also for writes viaEnforcer.add_policy.ptypeandv0..v5only and added as lists viamodel.add_policy(no re-joined strings). Invalid stored rules are skipped with a warning instead of breaking enforcement.additionalProperties: falseonPermissionandRule;policy_typepattern;rule_sectiondropped;PUTstores only validated fields;GETreturns only rule fields (stored documents with extra fields would otherwise fail response validation).resource_role_model.confand the petstore access control example:regexMatch(r.act, "^(" + p.act + ")$").access_control.api_swagger_uiandapi_serve_spec(defaultFalse); the petstore access control example enables both.BadRequestProblemis mapped to 400. The general subclass lookup stays in fix: disable_auth crash, exception status mapping #280.Closes #277
Breaking changes
rule_section) or a wrong number of values (400).api_swagger_ui/api_serve_specare set.add_resource_role/remove_resource_roleandAdapter.save_policy_lineraiseValueErrorfor invalid values.Verification
#values rejected on each write path (adapter,POST/PUT, resource role helpers); stored documents with extra keys load as exactlyv0..v5; invalid stored rules are skipped with a warning while valid ones still apply;GETreturns only rule fields;GETrules do not matchXGETX/GETX, while(GET)|(POST)still matchesPOST; 400 for unknownpolicy_type, extra keys,rule_section, missing values, invalid values and invalid regex via the full app (POST and PUT); UI/spec 404 by default and 200 if enabled; invalid subject gets 403;BadRequestProblemgets 400.test_adapter.py,test_access_control_server.py) run against mongomock via a local, uncommitted pytest plugin; 100% line coverage offoca;ruff check,ruff format --check,mypy focaclean.Review follow-up (Sourcery): rules written via the adapter are validated against the configured model (
test_save_rule_invalid_for_model); "Rule values" added to the docs' table of contents.CI: all checks pass (lint/type-check/build, unit tests on Python 3.10–3.14 with MongoDB 7.0/8.0, petstore integration tests, Codecov patch and project, Sourcery). All automated review threads are resolved.
Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Harden access-control policy handling by validating rules against configured models, safely loading persisted policies, and tightening enforcement and API behavior.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: