Skip to content

refactor(access-control)!: tidy permissions API - #288

Merged
uniqueg merged 21 commits into
devfrom
refactor/permissions-api
Oct 19, 2026
Merged

uniqueg merged 21 commits into
devfrom
refactor/permissions-api

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 18, 2026 •

Copy link
Copy Markdown
Member

Summary

Fourth PR of the v0.14.0 production-readiness series (part a of the planned PR 4; pagination #113 and self-service #112 follow in a separate PR). Builds on #287 (← #286 ← #274); please merge those first. Until then, this diff includes their commits; the change of this PR is the last commit.

Changes

  • One write path: POST and PUT /permissions both store via the Casbin adapter (save_policy_line, upsert by id for PUT), so both store id, ptype and v0..v5 only.
  • Tolerant reads: GET omits a missing id and skips stored rules without a string ptype (e.g., added to the database directly) instead of failing with 500; non-string values are omitted.
  • No blanket except Exception → 500 in the controllers; the global error handler deals with errors (and logs them once).
  • One collection lookup (_get_permissions_collection()) instead of four copies with type: ignores.
  • Rule identifiers (Implement configurable identifiers for access control #142): new access_control.id_charset (letters, digits, -._~; default: letters and digits) and id_length (4–64, default 6), validated in AccessControlConfig. Identifiers supplied via PUT /permissions/{id} must match them (400 otherwise). The adapter ensures a unique index on id (partial: string identifiers only) on its first write and retries with a new identifier on collisions (ID_ATTEMPTS).
  • Adapter: save_policy replaces the stored rules instead of appending duplicates; ValueError instead of assert for a missing collection; load_policy typed with casbin.model.Model.
  • CasbinRule: dataclass with from_values(), values() and to_dict() (was dict(), which scanned dir(self)); debug print() in __repr__ removed.
  • Docs: identifier settings.

Closes #278
Closes #142

Breaking changes

  • PUT /permissions/{id} rejects identifiers not matching id_charset/id_length (default: 6 letters or digits); check existing custom identifiers before upgrading.
  • Stored rules with duplicate identifiers make the first write fail, as the unique index cannot be created.
  • CasbinRule.dict() → to_dict(); Adapter.save_policy() replaces all stored rules.

Verification

  • Tests:
    • POST and PUT store identically shaped documents.
    • Lists and gets work for stored rules without id/ptype or with non-string values, also through the full app with response validation.
    • Invalid PUT identifiers get 400.
    • Generated identifiers follow the configured charset and length and are unique.
    • The unique index exists; a collision triggers a retry; exhausted retries raise.
    • save_policy twice yields no duplicates.
    • The ID config validation rejects invalid charsets and lengths.
    • Adapter without a collection raises ValueError.
  • Locally on Python 3.13 and 3.10: 444 passed, with the two live-MongoDB suites 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 on #289): if stored rules share identifiers, the unique index cannot be created; the adapter now logs an error with a recovery path once and keeps storing rules instead of failing every write (test_duplicate_stored_ids, docs). Follow-up (Sourcery on #290/#291): index creation is retried after other errors (test_index_retried_after_error); id_charset/id_length must allow for at least one million identifiers; stored rules are removed by policy type and values irrespective of other fields (test_remove_rules_with_extra_fields).

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). A first run exposed a flaky test of mine (too few possible identifiers for 10 rules with 4 characters from 2); fixed with 8 characters. The branch also merges the review fix of #287 (adapter validates against the model).

Open questions

None.

🤖 Generated with Claude Code

Summary by Sourcery

Tidy the permissions API around consistent adapter-backed storage, tolerant reads, and configurable unique rule identifiers.

New Features:

  • Add configurable, validated policy-rule identifiers with uniqueness guarantees and collision retries.

Bug Fixes:

  • Make permission reads tolerate missing identifiers, invalid stored fields, and rules without string policy types.
  • Ensure policy saves replace existing rules instead of creating duplicates and make rule deletion match policy values reliably.

Enhancements:

  • Unify permission creation and updates through the Casbin adapter and simplify collection access and controller error handling.
  • Replace the Casbin rule conversion helper with a typed dataclass API.

Documentation:

  • Document policy-rule identifier configuration, validation, uniqueness behavior, and recovery for legacy duplicates.

Tests:

  • Add coverage for identifier configuration, uniqueness, collision handling, incomplete stored rules, consistent POST/PUT storage, replacement saves, and policy deletion.

Chores:

  • Raise a clear adapter error when no policy collection is configured.

uniqueg and others added 8 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]>
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]>
The permissions API looked up its collection in four places, stored
rules via the Casbin adapter on POST but directly on PUT, failed on
stored rules without identifier or policy type, and turned every error
into 500. Generated rule identifiers were not guaranteed to be unique,
and `save_policy` duplicated stored rules.

- store rules via the adapter on POST and PUT (upsert by identifier),
  so that both store the same fields
- return stored rules without identifier (omitting it) and skip rules
  without policy type when reading; let the global error handler deal
  with errors instead of wrapping them as 500
- add `access_control.id_charset` and `id_length` for generated rule
  identifiers; reject other identifiers in `PUT /permissions/{id}`
- ensure a unique index on rule identifiers and retry with a new
  identifier on collisions
- make `save_policy` replace the stored rules instead of adding them
- make `CasbinRule` a dataclass with `to_dict()` (was `dict()`) and
  `from_values()`; drop the debug `print()`; raise `ValueError` instead
  of asserting a collection is given

BREAKING CHANGE: `PUT /permissions/{id}` rejects identifiers that do not
match `access_control.id_charset` and `id_length` (default: 6 letters or
digits). Stored rules with duplicate identifiers make the first write
fail, as the unique index cannot be created. `CasbinRule.dict()` is
renamed to `to_dict()`, and `Adapter.save_policy()` replaces all stored
rules.

Closes #278
Closes #142

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

Refactors access control around a single validated Casbin persistence path, resilient permission reads, configurable unique rule identifiers, and model-aware rule validation; it also replaces the JWT validation flow with trusted-issuer OIDC discovery and cached local verification, updates enforcement and API configuration, and refreshes documentation and tests.

Sequence diagram for validated permission creation and unique identifier generation

sequenceDiagram
    participant Client
    participant API as PermissionsAPI
    participant Adapter as CasbinAdapter
    participant MongoDB

    Client->>API: POST /permissions
    API->>API: _get_rule()
    API->>Adapter: save_policy_line(ptype, rule)
    Adapter->>Adapter: validate_rule()
    Adapter->>MongoDB: create_index(id, unique, partial)
    Adapter->>MongoDB: insert_one(document)
    alt DuplicateKeyError
        Adapter->>MongoDB: insert_one(document with new generated id)
    end
    MongoDB-->>Adapter: stored rule
    Adapter-->>API: permission id
    API-->>Client: created permission id
Loading

Sequence diagram for tolerant permission reads

sequenceDiagram
    participant Client
    participant API as PermissionsAPI
    participant MongoDB

    Client->>API: GET /permissions
    API->>API: _get_permissions_collection()
    API->>MongoDB: find(_PERMISSION_FILTER)
    MongoDB-->>API: stored documents
    API->>API: _to_permission(document)
    API-->>Client: permissions with string ptype and values
    Note over API: Missing id is omitted, non-string values are omitted
Loading

File-Level Changes

Change Details Files
Unifies permission API writes and makes reads resilient to legacy or malformed stored documents.
  • Routes POST and PUT through the Casbin adapter with identical id/ptype/v0–v5 storage.
  • Validates request rules against the configured Casbin model and maps invalid payloads to 400 responses.
  • Filters unreadable stored rules and returns only supported permission fields without blanket controller exception handling.
  • Consolidates permission collection access and removes the obsolete header-based permission decorator.
foca/security/access_control/access_control_server.py
foca/security/access_control/register_access_control.py
foca/security/access_control/api/access-control-specs.yaml
foca/errors/exceptions.py
Adds validated, configurable, collision-safe policy rule identifiers and changes adapter persistence semantics.
  • Introduces validated id_charset and id_length configuration, generated identifiers, partial unique indexing, collision retries, and upsert-by-ID updates.
  • Replaces dynamic Casbin rule serialization with a dataclass API and validates rule values, policy types, arity, and action regular expressions.
  • Makes save_policy replace existing rules, skips invalid rules during loading, and raises ValueError when no collection is configured.
  • Passes identifier settings and the model into adapter registration.
foca/models/config.py
foca/security/access_control/constants.py
foca/security/access_control/foca_casbin_adapter/adapter.py
foca/security/access_control/foca_casbin_adapter/casbin_rule.py
Reworks access-control enforcement around validated token claims and strengthens policy matching.
  • Adds claim-based enforce_access_control, validates subjects and resource-role values, and denies invalid values with 403.
  • Anchors action regular expressions in the bundled policy models for whole-method matching.
  • Updates Connexion context handling for requests outside normal Connexion processing.
foca/security/access_control/enforcement.py
foca/security/access_control/api/resource_role_model.conf
examples/petstore-access-control/petstore_policies.conf
Replaces JWT validation configuration and implementation with trusted-issuer OIDC discovery and cached local signature verification.
  • Replaces validation-method settings with trusted issuers, optional userinfo validation, timeouts, caching, and configuration warnings.
  • Rejects untrusted issuers before network access, verifies issuer/audience/required claims and signatures, supports key rotation, and optionally exposes the verification key.
  • Updates application setup, templates, examples, and authentication tests for the new configuration.
foca/security/auth.py
foca/models/config.py
foca/foca.py
templates/config.yaml
examples/petstore/config.yaml
examples/petstore-access-control/config.yaml
tests/security/test_auth.py
Updates documentation, examples, dependency declarations, and regression coverage for the new APIs and security behavior.
  • Documents identifier constraints, rule validation, enforcement usage, action matching, and optional permissions API UI/spec serving.
  • Removes the obsolete flask-authz dependency and adds direct pycasbin usage.
  • Expands tests for API behavior, adapter persistence, malformed data, enforcement, configuration, and authentication.
README.md
docs/access_control/README.md
examples/petstore-access-control/README.md
pyproject.toml
tests/security/access_control/test_access_control_server.py
tests/security/access_control/foca_casbin_adapter/test_adapter.py
tests/security/access_control/test_enforcement.py
tests/models/test_config.py

Assessment against linked issues

Issue Objective Addressed Explanation
#142 Allow users to configure the charset and length of identifiers generated for new access-control objects through AccessControlConfig. ✅
#278 Refactor the permissions API to use one collection helper and a shared adapter write path, return consistent stored rule shapes, tolerate incomplete stored rules on list/get, and avoid converting all controller errors to 500. ❌ The shared lookup and adapter write path are implemented, and blanket exception handling is removed. However, getPermission filters for a string ptype, so a stored document with an id but no ptype is returned as 404 rather than being handled as an incomplete rule; the issue’s acceptance criteria require get to work for documents without ptype.
#278 Clean up the Casbin adapter and rule representation: use fixed dataclass fields and to_dict(), remove debug printing and runtime asserts, correct load_policy typing, and replace stored policies rather than appending duplicates. ✅
#278 Cover the related refinements for pagination (#113), own permissions (#112), and configurable rule identifiers (#142). ❌ Configurable and validated identifiers are implemented, but the PR explicitly leaves pagination and self-service permissions for separate PRs.

Possibly linked issues

  • #unknown: The PR directly implements the issue’s permissions API and adapter proposals; its additional authentication changes do not alter that core match.
  • #unspecified: The PR directly implements the issue’s central access-control requirements, including OIDC claim enforcement, protected permissions management, and resource-role helpers.

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

The section on header properties was removed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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 (f0e7707) to head (9503fa8).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #288   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           22        22           
  Lines         1156      1184   +28     
=========================================
+ Hits          1156      1184   +28     
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 3 commits October 18, 2026 19:53
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]>
# Conflicts:
#	foca/security/access_control/foca_casbin_adapter/adapter.py
#	foca/security/access_control/register_access_control.py
#	tests/security/access_control/test_register_casbin_enforcer.py
With 4 characters from 2, only 16 identifiers are possible, so storing
10 rules could exhaust the retries for a unique identifier.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg marked this pull request as ready for review October 18, 2026 18:10

@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 reviewed your changes and they look great!

Sourcery assessment

Needs a human reviewer. save_policy() now deletes every document in the policy collection before writing the current rules; if saving fails partway through, existing permissions can be lost, and reverting the code will not restore them. The new issuer allowlist also changes token acceptance, but its rejection behavior is visible and can be corrected through configuration.


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

If stored rules share identifiers (e.g., rules stored by previous
versions), the unique index on identifiers cannot be created, so every
write failed.

Log an error with a recovery path once and store rules without
guaranteeing unique identifiers instead; document how to resolve this.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- create the unique index on rule identifiers until it succeeds (or
  fails due to duplicate stored identifiers), instead of giving up
  after any first error
- require `id_charset` and `id_length` to allow for at least one
  million identifiers, so that generating unique identifiers cannot
  run out of attempts
- remove stored rules by their policy type and values only, so that
  rules with other fields (e.g., written directly) can be revoked

Co-Authored-By: Claude Opus 5.5 <[email protected]>
uniqueg and others added 7 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 31ca445 into dev Oct 19, 2026
13 checks passed
@uniqueg
uniqueg deleted the refactor/permissions-api branch October 19, 2026 00:16
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): tidy permissions API Implement configurable identifiers for access control

1 participant