Skip to content

fix!: OpenAPI auth removal and error mapping - #291

Merged
uniqueg merged 36 commits into
devfrom
fix/openapi-and-errors
Oct 19, 2026
Merged

uniqueg merged 36 commits into
devfrom
fix/openapi-and-errors

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 18, 2026 •

Copy link
Copy Markdown
Member

Summary

Seventh PR of the v0.14.0 production-readiness series. Builds on #290 (← #289 ← #288 ← #287 ← #286 ← #274); please merge those first. Until then, this diff includes their commits; the changes of this PR are the last two commits.

Changes

  • disable_auth crash: with disable_auth: true, register_openapi called .pop("security", None) on every field of a Path Item Object, including path-level parameters (a list), and failed with TypeError: pop expected at most 1 argument, got 2. Reproduced with openapi_3_petstore_pathitemparam.original.yaml. A new _iter_operations() yields only Operation Objects (dict values of HTTP method fields) and is used both for removing security requirements and for adding operation fields.
  • ServiceUnavailable → 503 (was 502).
  • Exception lookup along the MRO: subclasses of mapped exceptions (e.g., class TaskNotFound(NotFound)) get the status of their closest mapped base class instead of 500.
  • One log record per handled exception: the problem details are logged together with the exception, not as a separate record.

Closes #280

Breaking changes

  • ServiceUnavailable returns 503 instead of 502.
  • Unmapped subclasses of mapped exceptions return their closest mapped base class's status instead of 500. Custom mappings keep working, and more specific mappings take precedence.

There's no changelog file in the repository, so these go into the release notes.

Verification

  • Tests:
    • The spec passed to App.add_api (patched) for the path-item fixture with disable_auth: true contains no security/securitySchemes, and path-level parameters are kept.
    • Operation fields are only added to operations.
    • _iter_operations skips summary, description, parameters, servers, extensions, $ref-only path items and non-dict path items.
    • ServiceUnavailable returns 503; subclasses and sub-subclasses of NotFound return 404; the closest mapped base class wins; unknown exceptions return 500; exactly one log record per handled exception, containing the problem details.
  • Local runs on Python 3.13 and 3.10: 486 passed, with the two live-MongoDB suites run against mongomock via a local, uncommitted pytest plugin. foca has 100% line coverage, and ruff check, ruff format --check and mypy foca are clean.

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. Possible follow-up for #240: other HTTP errors raised by Flask/Connexion that are not in the default mapping still return 500, e.g., MethodNotAllowed (405) and UnsupportedMediaTypeProblem (415).

🤖 Generated with Claude Code

Summary by Sourcery

Correct OpenAPI authentication removal and exception handling so path-level metadata is preserved and mapped errors produce accurate responses and logs.

Bug Fixes:

  • Prevent OpenAPI registration from crashing when disabling authentication on path items with path-level parameters or other non-operation fields.
  • Resolve exception mappings through the exception class hierarchy so unmapped subclasses inherit the nearest mapped base class status and details.
  • Return HTTP 503 for ServiceUnavailable errors instead of 502.
  • Combine mapped problem details and exception information into a single log record for handled exceptions.

Enhancements:

  • Reuse operation-only OpenAPI traversal for modifying operation fields and security settings while preserving path-level metadata.

Tests:

  • Add coverage for OpenAPI path-item handling, operation-only field updates, inherited exception mappings, status codes, and single-record error logging.

uniqueg and others added 19 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]>
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]>
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]>
With `disable_auth: true`, `register_openapi` called `.pop("security",
None)` on every field of each Path Item Object, including path-level
`parameters` (a list), so registering such specs failed with a
`TypeError`.

Add `_iter_operations()`, yielding only Operation Objects, and use it
both for removing security requirements and for adding operation
fields. Test the specifications passed to Connexion, not only the
return type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- map `ServiceUnavailable` to status 503 (was 502)
- look up exceptions along their method resolution order, so that
  subclasses of mapped exceptions (e.g., `class TaskNotFound(NotFound)`)
  are handled like their closest mapped base class instead of as 500
- log each handled exception once, with its problem details, instead of
  logging the problem details and the exception separately

BREAKING CHANGE: `ServiceUnavailable` returns 503 instead of 502, and
unmapped subclasses of mapped exceptions return the status of their
closest mapped base class instead of 500.

Closes #280

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg uniqueg changed the title fix: OpenAPI auth removal and error mapping fix!: OpenAPI auth removal and error mapping Oct 18, 2026
@sourcery-ai

sourcery-ai Bot commented Oct 18, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

This PR makes authentication explicitly issuer-trusted and locally verifiable through OIDC discovery, replaces the former header-based access-control integration with Casbin-backed token-claim enforcement, and substantially evolves the permissions API with validated rules, unique IDs, pagination, and self-service reads. It also fixes OpenAPI path-item traversal and improves HTTP exception mapping/logging, with corresponding configuration, documentation, examples, dependency, and regression-test updates.

Sequence diagram for issuer-trusted JWT validation

sequenceDiagram
    participant Client
    participant Connexion
    participant Auth as validate_token
    participant Issuer
    participant JWKS

    Client->>Connexion: Bearer token
    Connexion->>Auth: validate_token(token)
    Auth->>Auth: jwt.decode(token, verify_signature=false)
    alt issuer not in AuthConfig.issuers
        Auth-->>Connexion: Unauthorized
    else trusted issuer
        Auth->>Issuer: _get_oidc_config(issuer, conf)
        Issuer-->>Auth: OIDC discovery document
        Auth->>JWKS: _get_jwk_set(jwks_uri, conf)
        JWKS-->>Auth: PyJWKSet
        Auth->>Auth: _verify_signature(token, issuer, jwks_uri, conf)
        opt validate_userinfo
            Auth->>Issuer: _validate_userinfo(token, subject, url, conf)
            Issuer-->>Auth: User info
        end
        Auth-->>Connexion: Verified claims
    end
Loading

Sequence diagram for token-claim access-control enforcement

sequenceDiagram
    participant Client
    participant Resolver as AccessControlResolver
    participant Controller
    participant Enforcement as is_permitted
    participant Casbin as CasbinEnforcer

    Client->>Resolver: Operation request
    Resolver->>Resolver: _is_enforced(operation)
    alt access control enforced
        Resolver->>Controller: enforce_access_control wrapper
        Controller->>Enforcement: is_permitted()
        Enforcement->>Enforcement: get_current_subject()
        Enforcement->>Enforcement: get_current_groups()
        Enforcement->>Casbin: enforce(subject, request.path, request.method)
        alt policy permits request
            Casbin-->>Enforcement: true
            Enforcement-->>Controller: permitted
            Controller-->>Client: Operation response
        else policy denies request
            Casbin-->>Enforcement: false
            Enforcement-->>Controller: Forbidden
            Controller-->>Client: 403
        end
    else self-service operation
        Resolver->>Controller: Resolve without automatic enforcement
    end
Loading

Sequence diagram for validated permission rule persistence

sequenceDiagram
    participant Client
    participant API as postPermission
    participant Server as _get_rule
    participant Adapter as save_policy_line
    participant MongoDB

    Client->>API: POST /permissions
    API->>Server: _get_rule()
    Server->>Server: validate_rule(ptype, values, model)
    alt invalid rule
        Server-->>API: BadRequest
        API-->>Client: 400
    else valid rule
        API->>Adapter: save_policy_line(ptype, rule)
        Adapter->>Adapter: _ensure_id_index()
        Adapter->>Adapter: generate_id(charset, length)
        Adapter->>MongoDB: insert_one(rule with id)
        MongoDB-->>Adapter: Stored rule
        Adapter-->>API: permission id
        API-->>Client: Created permission
    end
Loading

Sequence diagram for MRO-based exception mapping and logging

sequenceDiagram
    participant Request
    participant Handler as _problem_handler_json
    participant Mapping as exception mapping
    participant Logger

    Request->>Handler: Handled exception
    Handler->>Mapping: Search type(exception).__mro__
    Mapping-->>Handler: Closest mapped class or Exception
    Handler->>Handler: Resolve status and problem details
    Handler->>Logger: _log_exception(exception, format, problem)
    Logger-->>Handler: One combined log record
    Handler-->>Request: Problem JSON response

    Note over Handler: ServiceUnavailable maps to 503
Loading

Flow diagram for paginated self-service permission reads

flowchart TD
    A[GET /permissions] --> B[getAllPermissions]
    B --> C[_get_visibility_filter]
    C --> D{self_service and not is_permitted}
    D -->|yes| E[get_current_subject and get_current_groups]
    E --> F[Filter v0 by subject roles and wildcard]
    D -->|no| G[Use unrestricted filter]
    F --> H[_get_permissions_collection]
    G --> H
    H --> I[Count and page policy rules]
    I --> J[_to_permission]
    J --> K[Return results and pagination]
Loading

Flow diagram for OpenAPI operation-only mutation

flowchart TD
    A[OpenAPI specification] --> B[register_openapi]
    B --> C["_iter_operations(spec)"]
    C --> D{Path item field is an HTTP operation with dict value}
    D -->|yes| E[Mutate Operation Object]
    D -->|no| F[Skip path parameters summary description servers extensions and refs]
    E --> G{disable_auth}
    G -->|true| H[Remove operation security]
    G -->|false| I[Keep operation security]
    E --> J[Add operation fields]
    F --> K[Preserve path-item fields]
Loading

File-Level Changes

Change Details Files
Reworks authentication and access-control configuration around trusted OIDC issuers and an explicit access-control enablement switch.
  • Replaces legacy JWT validation-method settings with issuer discovery, local JWKS signature verification, optional userinfo validation, caching, timeouts, and security warnings.
  • Registers the permissions API and Casbin integration only when access control is enabled, with validation for incompatible settings and required trusted issuers.
  • Removes the header-based permission decorator in favor of token-claim-based enforcement and exposes is_permitted, subject/group helpers, and a controller decorator.
foca/security/auth.py
foca/models/config.py
foca/foca.py
foca/security/access_control/enforcement.py
foca/security/access_control/register_access_control.py
foca/security/access_control/__init__.py
pyproject.toml
README.md
docs/access_control/README.md
examples/petstore-access-control/README.md
examples/petstore-access-control/config.yaml
examples/petstore/config.yaml
templates/config.yaml
Expands the permissions API with validated Casbin rules, generated unique identifiers, pagination, and self-service visibility.
  • Validates policy types, rule arity, values, and action regular expressions against the configured Casbin model before writes and when loading stored rules.
  • Adds configurable identifier charset/length, unique MongoDB indexing with collision retries, stable replacement behavior, and filtering of malformed legacy records.
  • Changes listing to page-based results with metadata, gates Swagger/spec serving behind configuration, and supports subject/group/wildcard self-service reads while preserving policy enforcement for writes.
  • Anchors action matching to the complete HTTP method and updates API schemas, examples, and resource-role handling.
foca/security/access_control/access_control_server.py
foca/security/access_control/foca_casbin_adapter/adapter.py
foca/security/access_control/foca_casbin_adapter/casbin_rule.py
foca/security/access_control/constants.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
Hardens OpenAPI mutation and exception-to-problem mapping behavior.
  • Adds an operation iterator that excludes path-level parameters, metadata, extensions, references, and non-operation values when adding fields or removing security.
  • Maps ServiceUnavailable to 503, resolves unmapped exception subclasses through their closest mapped MRO base, includes problem details in the same log record, and recognizes Connexion bad-request problems.
foca/api/register_openapi.py
foca/errors/exceptions.py
Updates and broadens regression coverage for the new authentication, access-control, OpenAPI, and error-handling behavior.
  • Adds tests for OIDC discovery/signature validation, issuer trust, caching, key rotation, claims, userinfo, and configuration compatibility.
  • Adds tests for rule validation, adapter persistence/index behavior, pagination, self-service authorization, access-control registration, and action matching.
  • Adds focused tests for OpenAPI path-item handling and exception status/MRO/logging semantics.
tests/api/test_register_openapi.py
tests/errors/test_errors.py
tests/models/test_config.py
tests/security/test_auth.py
tests/security/access_control/foca_casbin_adapter/test_adapter.py
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
tests/security/access_control/test_register_access_control.py
tests/security/access_control/test_register_casbin_enforcer.py
tests/test_foca.py
tests/mock_data.py
tests/test_files/conf_access_control_enabled.yaml
tests/test_files/conf_enforce_access_control_without_enabled.yaml
tests/test_files/conf_invalid_access_control.yaml
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_access_control.yaml
tests/test_files/conf_valid_cors_disabled.yaml
tests/test_files/conf_valid_cors_enabled.yaml
tests/test_files/conf_valid_custom_invalid.yaml

Assessment against linked issues

Issue Objective Addressed Explanation
#280 Prevent disable_auth from crashing on non-operation Path Item fields, and ensure authentication security is removed from the OpenAPI spec passed to Connexion. ✅
#280 Map ServiceUnavailable to 503 and resolve exception status mappings through the exception class MRO, including support for custom, more-specific mappings. ✅
#280 Log each handled exception once, with its problem details included in the same record. ✅

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 (3c55931) to head (b833731).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #291   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           22        22           
  Lines         1219      1221    +2     
=========================================
+ Hits          1219      1221    +2     
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
uniqueg marked this pull request as ready for review October 18, 2026 18:39

@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 3 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>
**Failed index creation disables uniqueness checks**

When index creation fails for a non-duplicate error, or another writer arrives while the first index creation is in progress, `_ensure_id_index` sets `_id_index_created` before MongoDB confirms the unique index exists, so later or concurrent writes skip index creation and can store duplicate identifiers, making permission lookups and updates ambiguous.

Serialize index initialization and set `_id_index_created` only after index creation succeeds or the intentional duplicate-ID fallback is handled.
</issue_to_address>

### Comment 2
<location path="foca/models/config.py" line_range="784-786" />
<code_context>
+            ValueError: No characters are given, or characters other than
+                letters, digits, `-`, `.`, `_` and `~` are given.
+        """
+        if not v:
+            raise ValueError("'id_charset' must not be empty")
+        if not set(v) <= set(f"{DEFAULT_ID_CHARSET}-._~"):
+            raise ValueError(
+                "'id_charset' may only contain letters, digits, '-', '.', "
</code_context>
<issue_to_address>
**Small charsets exhaust permission IDs**

When the configured charset and length provide too few identifiers for the rules being created, `validate_id_charset` accepts a one-character alphabet, which permits only one identifier for any configured length; after it is used, `save_policy_line` exhausts its collision retries and permission creation fails.

Reject charsets and lengths that do not provide a sufficient identifier space.

Also at `foca/security/access_control/foca_casbin_adapter/adapter.py:161-168`.
</issue_to_address>

### Comment 3
<location path="foca/security/access_control/foca_casbin_adapter/adapter.py" line_range="192" />
<code_context>
             return 0
         else:
-            line_dict = line.dict()
+            line_dict = line.to_dict()
             line_dict_keys_len = len(line_dict)
             results = self._collection.find(
</code_context>
<issue_to_address>
**Legacy rules cannot be revoked**

When a stored rule has extra fields, as can happen with legacy or directly written documents, `_delete_policy_lines` finds the rule but rejects documents with extra fields in its key-count check, returns zero, and leaves the stored rule to be loaded again after restart. Remove matching rules based on their policy fields without requiring an exact document shape.

Delete documents matching the rule fields regardless of unrelated stored fields.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 3 findings to address first, and save_policy() deletes every document in the policy collection before writing the enforcer’s current rules; if saving fails or the loaded rules are incomplete, removed permissions are not restored by reverting. The authentication and enforcement rewrite also changes which tokens and requests are accepted, so an authorization error could expose protected data while deployed.

Blocking findings: foca/security/access_control/foca_casbin_adapter/adapter.py:89, foca/models/config.py:786, foca/security/access_control/foca_casbin_adapter/adapter.py:192


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

Comment thread foca/models/config.py Resolved
uniqueg and others added 4 commits October 18, 2026 20:56
- 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
uniqueg and others added 13 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 bb0c23d into dev Oct 19, 2026
13 checks passed
@uniqueg
uniqueg deleted the fix/openapi-and-errors branch October 19, 2026 00:27
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: disable_auth crash, exception status mapping

1 participant