Skip to content

fix(access-control)!: validate and anchor rules - #287

Merged
uniqueg merged 14 commits into
devfrom
fix/validate-rules
Oct 19, 2026
Merged

uniqueg merged 14 commits into
devfrom
fix/validate-rules

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 18, 2026 •

Copy link
Copy Markdown
Member

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

  • Rules were serialized to comma-separated lines (CasbinRule.__str__) and split again by pycasbin on load. A value containing a comma, e.g., an identity claim passed to add_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_policy copied every stored document key onto rules, putPermission stored the client's rule object as is, and the permissions API schemas allowed additional properties; policy_type was free text and rule_section was ignored.
  • The reference model used unanchored regexMatch(r.act, p.act), so a rule for GET matched any method containing GET.
  • The permissions API always served its Swagger UI and spec.
  • Requests failing Connexion's schema validation (BadRequestProblem) were answered with 500 instead of 400 in all FOCA apps, as the exception was not in FOCA's default mapping.

Changes

  • Rule validation (validate_rule, validate_rule_value in foca_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 #. act values must be valid regular expressions.
  • Adapter validates against the model: Adapter(..., model=...) (FOCA passes access_control.model) checks policy types, value counts and action patterns before storing, also for writes via Enforcer.add_policy.
  • Loading: rules are built from ptype and v0..v5 only and added as lists via model.add_policy (no re-joined strings). Invalid stored rules are skipped with a warning instead of breaking enforcement.
  • Enforcement: subjects that are not valid rule values are denied with 403.
  • Permissions API: invalid rules get 400; additionalProperties: false on Permission and Rule; policy_type pattern; rule_section dropped; PUT stores only validated fields; GET returns only rule fields (stored documents with extra fields would otherwise fail response validation).
  • Anchored actions in resource_role_model.conf and the petstore access control example: regexMatch(r.act, "^(" + p.act + ")$").
  • Config: access_control.api_swagger_ui and api_serve_spec (default False); the petstore access control example enables both.
  • Errors (separate commit): BadRequestProblem is mapped to 400. The general subclass lookup stays in fix: disable_auth crash, exception status mapping #280.
  • Docs: rule values, action matching, UI/spec options.

Closes #277

Breaking changes

  • Action patterns of the reference model must match the whole HTTP method; substring rules stop matching.
  • The permissions API rejects rules with unknown policy types, extra keys (including rule_section) or a wrong number of values (400).
  • The permissions API serves its Swagger UI and spec only if api_swagger_ui/api_serve_spec are set.
  • add_resource_role/remove_resource_role and Adapter.save_policy_line raise ValueError for invalid values.
  • Schema validation errors return 400 instead of 500.

Verification

  • New tests: validators (valid/invalid values, policy types, counts, patterns); comma, newline and # values rejected on each write path (adapter, POST/PUT, resource role helpers); stored documents with extra keys load as exactly v0..v5; invalid stored rules are skipped with a warning while valid ones still apply; GET returns only rule fields; GET rules do not match XGETX/GETX, while (GET)|(POST) still matches POST; 400 for unknown policy_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; BadRequestProblem gets 400.
  • Locally on Python 3.13 and 3.10: 424 passed, with the two suites that need a live MongoDB (test_adapter.py, test_access_control_server.py) run against mongomock via a local, uncommitted pytest plugin; 100% line coverage of foca; ruff check, ruff format --check, mypy foca clean.

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:

  • Add configurable options for serving the permissions API Swagger UI and OpenAPI specification.

Bug Fixes:

  • Prevent malformed or unexpected stored policy data from breaking policy loading and enforcement.
  • Return HTTP 400 for Connexion request validation failures instead of HTTP 500.
  • Prevent substring HTTP action matches from authorizing unintended methods.

Enhancements:

  • Validate access-control rules across API, adapter, and resource-role write paths against the configured model and enforce safe rule values.
  • Load and expose only canonical policy fields while skipping invalid persisted rules with warnings.
  • Reject invalid subjects during enforcement with HTTP 403.

Documentation:

  • Document rule-value constraints, whole-method action matching, and permissions API UI/spec configuration.

Tests:

  • Add coverage for rule validation, safe policy loading, anchored action matching, permissions API validation, configurable API documentation endpoints, invalid subjects, and error responses.

uniqueg and others added 5 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]>
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]>
@sourcery-ai

sourcery-ai Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

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

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

Sequence diagram for safe policy loading and enforcement

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

Flow diagram for trusted JWT validation and claim-based access control

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

File-Level Changes

Change Details Files
Harden access-control policy handling against malformed, ambiguous, and overly broad rules.
  • Added shared validation for policy types, field counts, values, and action regular expressions across adapter, API, and resource-role writes.
  • Loaded policies from explicit ptype/v0–v5 fields, ignoring metadata and skipping invalid persisted rules with warnings.
  • Denied enforcement for invalid subjects and anchored reference-model action matching to the complete HTTP method.
foca/security/access_control/foca_casbin_adapter/casbin_rule.py
foca/security/access_control/foca_casbin_adapter/adapter.py
foca/security/access_control/access_control_server.py
foca/security/access_control/enforcement.py
foca/security/access_control/api/access-control-specs.yaml
foca/security/access_control/api/resource_role_model.conf
examples/petstore-access-control/petstore_policies.conf
tests/security/access_control/foca_casbin_adapter/test_casbin_rule.py
tests/security/access_control/test_access_control_server.py
tests/security/access_control/test_enforcement.py
Constrain and sanitize the permissions API and its exposure.
  • Rejected unknown policy types, extra properties, rule_section, missing/non-consecutive fields, invalid values, and invalid patterns with 400 responses.
  • Stored only validated rule fields and projected GET responses to id, policy type, and v0–v5 values.
  • Made Swagger UI and OpenAPI serving opt-in through new access-control settings.
foca/security/access_control/access_control_server.py
foca/security/access_control/api/access-control-specs.yaml
foca/security/access_control/register_access_control.py
foca/models/config.py
docs/access_control/README.md
tests/security/access_control/test_enforcement.py
Replace legacy authentication and access-control integration with trusted-issuer JWT verification and claim-based enforcement.
  • Reworked JWT validation around configured trusted issuers, OIDC discovery, cached JWKS, signature/audience/claim checks, optional user-info validation, and key rotation handling.
  • Removed legacy validation-method, header-based permission, and flask-authz integration in favor of the controller enforcement decorator and validated token claims.
  • Added startup warnings for missing issuers, disabled audience validation, and accepted expired tokens; updated configuration, examples, and dependency declarations.
foca/security/auth.py
foca/models/config.py
foca/security/access_control/enforcement.py
foca/security/access_control/register_access_control.py
pyproject.toml
README.md
templates/config.yaml
examples/petstore/config.yaml
examples/petstore-access-control/config.yaml
tests/security/test_auth.py
tests/test_foca.py
Correct request-validation error handling and update documentation and regression coverage.
  • Mapped Connexion BadRequestProblem to HTTP 400.
  • Documented validated rule values, anchored actions, optional API UI/spec serving, trusted issuers, and the new enforcement API.
  • Expanded unit and full-app tests for validation, loading, enforcement, authentication, API behavior, configuration, and error responses.
foca/errors/exceptions.py
docs/access_control/README.md
README.md
tests/errors/test_errors.py
tests/test_files/conf_invalid_access_control.yaml
tests/test_files/conf_valid_access_control.yaml

Assessment against linked issues

Issue Objective Addressed Explanation
#277 Validate rule values and policy definitions on write, restrict permissions payloads to valid fields and policy types, and load stored rules using only ptype and v0–v5. ✅
#277 Make reference-model action matching exact and validate action regex patterns on write. ❌ The reference model anchors action matching, and the permissions API and resource-role helpers validate patterns against the model. However, Adapter.save_policy_line calls validate_rule without a model, so invalid action regex patterns are accepted through that write path.
#277 Disable the permissions API Swagger UI and specification by default, allow them to be enabled by configuration, and document the behavior and rule restrictions. ✅

Possibly linked issues


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 (ccbff33) to head (0c461ee).

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     
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="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


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

uniqueg and others added 2 commits October 18, 2026 19:50
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]>
uniqueg and others added 5 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 f0e7707 into dev Oct 19, 2026
13 checks passed
@uniqueg
uniqueg deleted the fix/validate-rules branch October 19, 2026 00:13
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.

fix(access-control): validate and anchor rules

1 participant