Skip to content

refactor(access-control)!: drop header checks - #286

Merged
uniqueg merged 9 commits into
devfrom
refactor/drop-header-checks
Oct 18, 2026
Merged

uniqueg merged 9 commits into
devfrom
refactor/drop-header-checks

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 18, 2026 •

Copy link
Copy Markdown
Member

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:

  • config-driven enforcement (access_control.enforce, and the enforce_access_control decorator) based on validated token claims, and
  • the check_permissions decorator (via flask-authz), which took subjects from request headers (owner_headers/user_headers).

The latter only worked because validate_token copied all token claims into request.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

  • Removed: check_permissions, the flask-authz dependency, the CASBIN_OWNER_HEADERS/CASBIN_USER_NAME_HEADERS app settings, and owner_headers/user_headers from AccessControlConfig.
  • No more claims in headers: validate_token leaves request.headers untouched; claims are available via token_info and get_current_subject()/get_current_groups().
  • One enforcement mechanism: use access_control.enforce: True, or decorate single controllers with foca.security.access_control.enforce_access_control (same checks, now with direct tests).
  • Claim retrieval: _get_claims() reads Connexion's request context directly (request_ctx.connexion_context) instead of treating every AttributeError as "no claims", so programming errors surface.
  • Dependency: pycasbin (maintained successor of the casbin package, which was previously only pulled in via flask-authz and has not been released since May 2025) is now declared explicitly.
  • README and access control docs updated.

Closes #276

Breaking changes

  • check_permissions is removed; use access_control.enforce or @enforce_access_control.
  • owner_headers/user_headers are removed (configs using them fail validation).
  • Token claims (and user_id) are no longer available as request headers; use get_current_subject(), get_current_groups() or token_info.
  • flask-authz is no longer installed with FOCA; casbin is now provided by pycasbin.

Verification

  • Tests: request.headers unchanged after validate_token; enforce_access_control on single controllers (allowed, denied, no subject); claim retrieval outside requests, outside Connexion, and with a broken Connexion context (raises); removed check_permissions tests.
  • git grep finds no references to check_permissions, flask-authz, owner_headers/user_headers or claims in headers.
  • Locally with pycasbin 2.8.0 (old casbin and flask-authz uninstalled): all unit tests without live MongoDB: 312 passed on Python 3.13 and 3.10; ruff check, ruff format --check, mypy foca clean.

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:

  • Add a unified decorator for enforcing access-control policies on individual controllers.

Bug Fixes:

  • Prevent validated token claims from altering or replacing request headers.
  • Make claim retrieval distinguish missing contexts from malformed Connexion contexts so programming errors are surfaced.

Enhancements:

  • Consolidate access-control enforcement around validated token claims and expose current subject and group helpers.

Build:

  • Replace the indirect Casbin dependency with an explicit pycasbin dependency and remove flask-authz.

Documentation:

  • Update the README and access-control documentation for claim-based enforcement and the replacement controller decorator.

Tests:

  • Add coverage for unchanged request headers, claim retrieval contexts, and allowed, denied, and unauthenticated controller enforcement.

Chores:

  • Remove the legacy header-based permission decorator and owner/user header configuration options.

uniqueg and others added 3 commits October 18, 2026 02:31
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]>
@sourcery-ai

sourcery-ai Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This 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 authorization

sequenceDiagram
    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
Loading

Flow diagram for trusted OIDC issuer validation

flowchart 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
Loading

File-Level Changes

Change Details Files
Replace header-based permission checks with validated token-claim enforcement.
  • Remove the check_permissions decorator and flask-authz integration.
  • Add single-controller enforcement through enforce_access_control using the existing Casbin enforcer.
  • Read subject and group claims from Connexion token context rather than request headers.
  • Remove header-specific access-control settings and update documentation and examples.
foca/security/access_control/enforcement.py
foca/security/access_control/register_access_control.py
foca/models/config.py
README.md
docs/access_control/README.md
examples/petstore-access-control/config.yaml
examples/petstore/config.yaml
tests/security/access_control/test_enforcement.py
tests/security/access_control/test_register_access_control.py
tests/mock_data.py
tests/test_files/conf_invalid_access_control.yaml
tests/test_files/conf_valid_access_control.yaml
Redesign JWT validation around trusted OIDC issuers and local signature verification.
  • Replace configurable validation-method combinations with issuer allowlisting, OIDC discovery, JWKS verification, and optional user-info validation.
  • Require issuer, identity, issued-at, and expiration claims, with configured audience and expiration handling.
  • Add discovery/JWKS caching, key-rotation refetch behavior, request timeouts, redirect blocking, and configuration warnings.
  • Stop mutating request.headers; return verified claims through token_info and user identity helpers.
foca/security/auth.py
foca/models/config.py
foca/foca.py
README.md
examples/petstore-access-control/config.yaml
examples/petstore/config.yaml
templates/config.yaml
tests/security/test_auth.py
tests/test_foca.py
tests/test_files/conf_invalid_log_level.yaml
tests/test_files/conf_no_jobs.yaml
tests/test_files/conf_valid.yaml
tests/test_files/conf_valid_custom_invalid.yaml
tests/test_files/conf_valid_cors_disabled.yaml
tests/test_files/conf_valid_cors_enabled.yaml
Make Casbin an explicit maintained dependency and remove the obsolete authorization package.
  • Replace flask-authz with pycasbin in project dependencies.
  • Retain direct Casbin adapter/enforcer registration without header configuration.
pyproject.toml
foca/security/access_control/register_access_control.py
Update tests and configuration fixtures for the breaking authentication and authorization API changes.
  • Add coverage for unchanged request headers, trusted issuer checks, cryptographic validation, caching, key rotation, user-info validation, and configuration warnings.
  • Add allowed, denied, and missing-subject decorator enforcement cases.
  • Remove tests and fixtures for header-based permissions and retired authentication fields.
tests/security/test_auth.py
tests/security/access_control/test_enforcement.py
tests/security/access_control/test_register_access_control.py
tests/test_foca.py
tests/mock_data.py
tests/test_files/

Assessment against linked issues

Issue Objective Addressed Explanation
#276 Remove the header-based check_permissions enforcement path, its flask-authz dependency, and the associated header settings and configuration fields. ✅
#276 Keep validated token claims out of request.headers, and make claim retrieval return no claims only when request or Connexion context is absent while allowing programming errors to surface. ✅
#276 Document the single supported enforcement mechanism and how to access claims, and provide a migration note listing removed symbols and configuration keys. ❌ The README and access-control documentation describe the config-driven enforcement path and claim helpers, but the diff does not include a migration note listing the removed symbols and keys.

Possibly linked issues

  • refactor(access-control)!: drop header checks #276: The PR implements the issue’s requested removal of header checks, flask-authz, and related config, while also changing JWT authentication.
  • #unknown: The PR replaces header-derived identities with validated token claims and consolidates enforcement, directly addressing a core issue requirement.

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 Oct 18, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (e3ef320) to head (9de08a5).

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     
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 and others added 2 commits October 18, 2026 19:40
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]>
@uniqueg
uniqueg marked this pull request as ready for review October 18, 2026 17: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 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.


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

Comment thread docs/access_control/README.md Resolved
The section on header properties was removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
uniqueg and others added 3 commits October 18, 2026 22:17
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]>
@uniqueg
uniqueg merged commit ccbff33 into dev Oct 18, 2026
13 checks passed
@uniqueg
uniqueg deleted the refactor/drop-header-checks branch October 18, 2026 23:58
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.

refactor(access-control)!: drop header checks

1 participant