Repository navigation
refactor(security)!: decouple access control - #290
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]>
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]>
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]>
# 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]>
`GET /permissions` returned all rules as a bare list (optionally
limited via `limit`, in reverse natural order), and only subjects
allowed by the policies (e.g., admins) could see any rules.
Pagination (as per the GA4GH API pagination guide, page-based):
- `page_size` (default 100, at most 1000) and `page` (from 0) replace
`limit`; the response is `{"results": [...], "pagination": {"page",
"page_size", "total", "total_pages"}}`, in creation order
- out-of-range pages and page sizes are rejected with 400
Self-service (opt-in via `access_control.self_service`):
- any authenticated subject may list and get the rules that apply to
them (subject is their prefixed identifier, one of their roles from
group claims, or `*`); other rules are not found (404)
- subjects allowed by the policies still get all rules; write
operations are still enforced
- operations opt in via `x-foca-self-service: true`; the resolver
leaves enforcement to their controllers, which use the new
`is_permitted()`
BREAKING CHANGE: `GET /permissions` returns an object with `results`
and `pagination` instead of a list, and `limit` is replaced by
`page_size` and `page`.
Closes #113
Closes #112
Co-Authored-By: Claude Opus 5.5 <[email protected]>
`security.auth.required` (default `True`) did not enforce authentication, which is defined per operation in the API specs. It only decided whether FOCA registered access control, so every app with default settings mounted the permissions API and connected to an access control database. Inconsistent settings only logged an error. - add `security.access_control.enabled` (default `False`); only then register the policy collection, Casbin adapter and permissions API - remove `security.auth.required` - reject access control options (`enforce`, `api_specs`, `api_controllers`, `self_service`) without `enabled`, and `enabled` without trusted token issuers (`auth.issuers`) - log warnings about authentication settings on the first token validation instead of on app creation, as only then is it known that the app validates tokens BREAKING CHANGE: `security.auth.required` is removed (configs using it fail validation). Apps using the permissions API or `enforce` must set `security.access_control.enabled: True` and `security.auth.issuers`; apps not using access control no longer get an access control database. Closes #279 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThis PR decouples authentication requirements from access-control registration: access control is now explicitly enabled and requires trusted issuers, while operation-level specs determine authentication. It also replaces legacy JWT and header-based authorization paths with issuer-aware token validation and Casbin enforcement, adds validated and paginated permission management with self-service visibility, strengthens policy persistence and rule validation, and updates documentation, examples, and comprehensive tests. Sequence diagram for operation authentication and policy enforcementsequenceDiagram
participant Client
participant Connexion
participant Auth as validate_token
participant Issuer as OIDC issuer
participant Resolver as AccessControlResolver
participant Casbin as is_permitted
participant Controller
Client->>Connexion: Request protected operation
Connexion->>Auth: validate_token(token)
Auth->>Auth: Decode unverified issuer
Auth->>Issuer: Fetch OIDC discovery and JWKs
Issuer-->>Auth: Public keys
Auth-->>Connexion: Verified token claims
Connexion->>Resolver: Resolve operation
Resolver->>Casbin: is_permitted()
alt Policy permits request
Casbin-->>Resolver: true
Resolver->>Controller: Invoke controller
Controller-->>Client: Response
else Policy denies request
Casbin-->>Resolver: false
Resolver-->>Client: Forbidden
end
Sequence diagram for paginated self-service permission listingsequenceDiagram
participant Client
participant API as getAllPermissions
participant Access as _get_visibility_filter
participant Casbin as is_permitted
participant DB as MongoDB policy collection
Client->>API: GET /permissions?page_size&page
API->>Access: _get_visibility_filter()
alt Subject may access all permissions
Access-->>API: Empty filter
else self_service visibility applies
Access->>Casbin: is_permitted()
Casbin-->>Access: false
Access-->>API: Subject, groups, and wildcard filter
end
API->>DB: count_documents(filter)
API->>DB: find(filter).sort().skip().limit()
DB-->>API: Permission page and total
API-->>Client: results and pagination
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 #290 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 22 22
Lines 1213 1219 +6
=========================================
+ Hits 1213 1219 +6
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:
|
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]>
There was a problem hiding this comment.
Hey - I've found 2 issues
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="89" />
<code_context>
+ """
+ if self._id_index_created:
+ return
+ self._id_index_created = True
+ try:
+ self._collection.create_index(
</code_context>
<issue_to_address>
**Permission IDs lose uniqueness**
When mongoDB index creation fails for a reason other than duplicate stored IDs, `_ensure_id_index()` sets `_id_index_created` before `create_index()` succeeds, so later writes skip index creation and can store duplicate identifiers without the uniqueness guarantee.
Set `_id_index_created` only after index creation succeeds or the duplicate-key case is safely handled, and leave it false after other errors.
</issue_to_address>
### Comment 2
<location path="foca/models/config.py" line_range="769-792" />
<code_context>
)
return v
+ @field_validator("id_charset")
+ @classmethod
+ def validate_id_charset(cls, v: str) -> str:
+ """Validate the characters of policy rule identifiers.
+
+ Args:
+ v: Characters of policy rule identifiers.
</code_context>
<issue_to_address>
**Small ID charset exhausts writes**
When `id_charset` contains one character and a rule with the resulting identifier already exists, `validate_id_charset()` accepts a one-character charset, so every generated ID is identical; after the first rule, `save_policy_line()` hits the unique index on every attempt and raises `DuplicateKeyError`, preventing further permission creation.
Validate that the configured charset and length provide an adequate identifier space, or reject charsets that cannot support unique IDs.
Also at `foca/security/access_control/foca_casbin_adapter/adapter.py:161-168`.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 2 findings to address first, and the adapter now deletes every document in the policy collection before rewriting it in save_policy; if a later write fails, existing permissions are lost, and reverting the code will not restore them. The authentication and enforcement changes also alter token trust and authorization behavior, so a defect could admit or deny requests.
Blocking findings: foca/security/access_control/foca_casbin_adapter/adapter.py:89, foca/models/config.py:792
- 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]>
# Conflicts: # foca/security/access_control/constants.py
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
…r/permissions-api
…eat/permissions-pagination
…o refactor/decouple-access-control
Summary
Sixth PR of the v0.14.0 production-readiness series. Builds on #289 (← #288 ← #287 ← #286 ← #274); please merge those first. Until then, this diff includes their commits; the change of this PR is the last commit.
security.auth.required(defaultTrue) did not enforce authentication; per-operationsecurityrequirements in the specs do that. Its only effect was inFoca.create_app, where it decided whether to register access control. So every app with default settings, including the plain petstore, mounted the admin permissions API and connected toaccess_control_db. Inconsistent settings only logged an error.Changes
security.access_control.enabled(defaultFalse): only when set does FOCA register the policy collection, the Casbin adapter and the permissions API.security.auth.requiredremoved.enforce,api_specs,api_controllersorself_servicewithoutenabled;enabledwithout trusted token issuers (auth.issuers), which would reject every request to the permissions API.create_appcannot tell whether an app validates tokens. Each config logs them only once.enabled.petstore-access-controlsetsenabled: True; both droprequired) and the test fixtures are updated.Closes #279
Breaking changes
security.auth.requiredfrom configs (configs using it fail validation).enforcemust setsecurity.access_control.enabled: Trueandsecurity.auth.issuers.access_control_db.Verification
/permissionsroutes (app.url_map).enabled: True: all three are registered, with defaults when onlyenabledandissuersare set, and repeatedly from the sameFocainstance.ValidationError: each option withoutenabled, andenabledwithout issuers; consistent combinations pass;requiredis rejected.foca;ruff check,ruff format --check,mypy focaclean.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
Decouple access-control registration from authentication configuration and require explicit, validated enablement for access-control features.
Bug Fixes:
Enhancements:
Documentation:
Tests: