Repository navigation
refactor(access-control)!: drop header checks - #286
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]>
Reviewer's GuideThis breaking refactor removes header-based access-control enforcement and flask-authz, consolidates authorization on validated token claims, and rewrites JWT validation around trusted OIDC issuers with cached JWKS-based signature verification, while updating dependencies, configuration, documentation, and tests. Sequence diagram for validated token authorizationsequenceDiagram
participant Client
participant Connexion
participant Auth as validate_token
participant Issuer
participant Controller
participant Enforcer
Client->>Connexion: Bearer token request
Connexion->>Auth: validate_token(token)
Auth->>Issuer: _get_oidc_config(issuer, conf)
Issuer-->>Auth: OIDC discovery and jwks_uri
Auth->>Issuer: _get_jwk_set(jwks_uri, conf)
Issuer-->>Auth: Cached or fetched JWKS
Auth->>Auth: _verify_signature(token, issuer, jwks_uri, conf)
Auth-->>Connexion: token_info with verified claims
Connexion->>Controller: Invoke authenticated operation
Controller->>Enforcer: enforce_access_control()
Enforcer->>Enforcer: _get_claims()
Enforcer-->>Controller: Allow or deny by token subject and groups
Flow diagram for trusted OIDC issuer validationflowchart TD
Start["validate_token(token)"] --> Decode["Decode unverified claims"]
Decode --> Trusted{"Issuer in auth.issuers?"}
Trusted -- No --> Reject["Reject token"]
Trusted -- Yes --> Discovery["_get_oidc_config(issuer, conf)"]
Discovery --> JWKS["_get_jwk_set(jwks_uri, conf)"]
JWKS --> Verify["_verify_signature(token, issuer, jwks_uri, conf)"]
Verify --> UserInfo{"validate_userinfo enabled?"}
UserInfo -- Yes --> ValidateUserInfo["_validate_userinfo(token, subject, url, conf)"]
UserInfo -- No --> Return["Return token_info with claims"]
ValidateUserInfo --> Return
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 #286 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 22 22
Lines 1121 1091 -30
=========================================
- Hits 1121 1091 -30
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="docs/access_control/README.md" line_range="195" />
<code_context>
on writing your own custom models, refer to the [Casbin
documentation][res-casbin-models].
-### Configuring header properties
-
-For access control to work, we must provide specific properties for every
</code_context>
<issue_to_address>
**Table of contents links to removed section**
When a reader clicks the “Configuring header properties” table-of-contents entry, readers following the “Configuring header properties” link land on no matching section, so the navigation link to that guidance is broken.
Remove the stale table-of-contents entry or replace it with a link to an existing section.
</issue_to_address>Sourcery assessment
Needs a human reviewer. A regression in issuer/JWKS verification or in deriving the Casbin subject from validated claims could authenticate the wrong principal and grant access under that principal’s policies. Reverting would stop future requests, but could not undo data already exposed or changes already made.
The section on header properties was removed. 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
Summary
Second PR of the v0.14.0 production-readiness series. Builds on #274 (please merge that first; until then, this diff includes its commits).
FOCA had two ways of enforcing access control:
access_control.enforce, and theenforce_access_controldecorator) based on validated token claims, andcheck_permissionsdecorator (via flask-authz), which took subjects from request headers (owner_headers/user_headers).The latter only worked because
validate_tokencopied all token claims intorequest.headers(replacing the original headers object, dropping real headers and making lookups case-sensitive), and on operations without token validation it used whatever headers the client sent.Changes
check_permissions, theflask-authzdependency, theCASBIN_OWNER_HEADERS/CASBIN_USER_NAME_HEADERSapp settings, andowner_headers/user_headersfromAccessControlConfig.validate_tokenleavesrequest.headersuntouched; claims are available viatoken_infoandget_current_subject()/get_current_groups().access_control.enforce: True, or decorate single controllers withfoca.security.access_control.enforce_access_control(same checks, now with direct tests)._get_claims()reads Connexion's request context directly (request_ctx.connexion_context) instead of treating everyAttributeErroras "no claims", so programming errors surface.pycasbin(maintained successor of thecasbinpackage, which was previously only pulled in via flask-authz and has not been released since May 2025) is now declared explicitly.Closes #276
Breaking changes
check_permissionsis removed; useaccess_control.enforceor@enforce_access_control.owner_headers/user_headersare removed (configs using them fail validation).user_id) are no longer available as request headers; useget_current_subject(),get_current_groups()ortoken_info.flask-authzis no longer installed with FOCA;casbinis now provided bypycasbin.Verification
request.headersunchanged aftervalidate_token;enforce_access_controlon single controllers (allowed, denied, no subject); claim retrieval outside requests, outside Connexion, and with a broken Connexion context (raises); removedcheck_permissionstests.git grepfinds no references tocheck_permissions, flask-authz,owner_headers/user_headersor claims in headers.casbinand flask-authz uninstalled): all unit tests without live MongoDB: 312 passed on Python 3.13 and 3.10;ruff check,ruff format --check,mypy focaclean.Review follow-up (Sourcery): stale table-of-contents entry removed.
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).
Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Replace header-based access-control checks with unified enforcement based on validated token claims.
New Features:
Bug Fixes:
Enhancements:
Build:
Documentation:
Tests:
Chores: