Skip to content

fix: harden access control enforcement - #263

Merged
uniqueg merged 4 commits into
devfrom
issue-262-review-findings
Oct 17, 2026
Merged

uniqueg merged 4 commits into
devfrom
issue-262-review-findings

Conversation

@uniqueg

@uniqueg uniqueg commented Oct 17, 2026 •

Copy link
Copy Markdown
Member

Closes #262

Summary

Addresses the automated review findings (Sourcery, Copilot) on #259, which was merged before they were handled. Nothing affected has been released yet (last tag: v0.13.0).

Fixes

  • $ref path items were not enforced (security): AccessControlResolver now decides per operation as resolved by Connexion (references resolved, effective security), instead of register_openapi pre-scanning the raw spec. _get_enforced_operations() is removed.
  • Optional authentication returned 401: operations whose security requirements include an empty alternative (e.g. security: [{}, {bearerAuth: []}]) are treated as public, like security: [].
  • Custom resolvers broke registration: resolvers are normalized exactly like Connexion's App.add_api() does: callables are wrapped in Resolver(function_resolver=...), any other resolver object (with a resolve() method) is used as is.
  • enforce: true with auth.required: false failed open: SecurityConfig now rejects this combination, so FOCA refuses to start (previously only an error was logged and enforcement was skipped).
  • Namespace collisions via subject_prefix: an empty prefix, or one overlapping with group:, is rejected at config validation. GROUP_PREFIX moved to constants.py for that.

Docs

  • Rules, including those for the permissions API, must use prefixed subjects (user:<id>).
  • check_permissions is a separate, header-based mechanism and should not be combined with enforce: true.
  • The enforcement changes above.

Declined (rationale in #262 and in the #259 threads): duplicate rules from concurrent identical grants (harmless; needs a unique index in the shared adapter), and non-atomic resource and grant changes (app's transaction design).

Automated reviews of this PR

  • Copilot (high): the first version of the resolver normalization wrapped resolver objects not inheriting from Resolver as functions. Agreed and fixed in 25b1100 (same rule as Connexion, plus a regression test); thread resolved.
  • Copilot's latest review has no open issues and recommends a human look at the reliance on Connexion's internal operation dict (see Risks). Sourcery: no findings.

Verification

CI: all checks pass on 25b1100: lint, mypy and unit tests on Python 3.9–3.12 × MongoDB 4.4–7.0 (16 jobs, including the MongoDB-backed tests), petstore integration tests, Docker builds (4 jobs), Codecov patch and project (coverage stays at 100%), Read the Docs, Sourcery.

Local venv (Python 3.12, pip install -e .[dev]):

  • flake8: clean
  • mypy foca: no issues
  • pytest tests/security/access_control/test_enforcement.py tests/api tests/test_foca.py tests/models tests/security/test_auth.py tests/config: 206 passed; coverage of all changed modules 100%
  • New regression tests, written first and failing before each change: $ref path item enforced (non-member 403, admin 200); optional authentication not enforced (anonymous and authenticated 200); custom resolvers as a function, a Resolver instance and a resolver object not inheriting from Resolver (registration works, policies enforced); invalid subject_prefix values ("", group:, group:x, g, group) rejected; enforce without auth.required rejected, also when starting Foca.
  • Behaviour of plain Connexion 2.15 with the three resolver forms checked separately (all accepted), to match its semantics.

Risks

  • Apps with enforce: true and auth.required: false now fail to start. That configuration never enforced anything, so this surfaces an existing misconfiguration.
  • Apps with subject_prefix: "" (or overlapping group:) now fail config validation; "" was documented as an option only as an unsafe one, in an unreleased version.
  • x-foca-access-control is read from Connexion's internal operation dict (_operation), as Connexion has no public accessor for vendor extensions (Connexion reads its own vendor extensions the same way). FOCA pins connexion~=2.11; a Connexion 3 migration would need to revisit this.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 2 commits October 17, 2026 16:32
Address automated review findings on #259:

- Decide whether to enforce policies per operation as resolved by
  Connexion, instead of pre-scanning the raw spec, so that operations of
  path items defined via `$ref` are enforced, too.
- Do not enforce operations with optional authentication, i.e., with an
  empty security requirement alternative (e.g., `security: [{}]`).
- Wrap callable resolvers, as accepted by Connexion, in a `Resolver`.
- Refuse configurations enforcing access control without authentication,
  instead of silently skipping enforcement.
- Reject an empty `subject_prefix` and prefixes overlapping with `group:`,
  which would let subjects collide with roles or groups.

Refs #262

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Document prefixed subjects in rules (including for the permissions API),
the relation to `check_permissions`, and the enforcement changes.

Refs #262

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 17, 2026 14:33
@sourcery-ai

sourcery-ai Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The PR hardens access-control enforcement by basing policy wrapping on Connexion’s fully resolved operations, correctly handling references and optional authentication, supporting callable resolvers, and failing fast on configurations or subject namespaces that could bypass or undermine enforcement; documentation and regression coverage are updated accordingly.

Sequence diagram for resolved access-control enforcement

sequenceDiagram
    participant App
    participant Connexion
    participant Resolver as AccessControlResolver
    participant Handler

    App->>Connexion: add_api(resolver)
    Connexion->>Resolver: resolve(operation)
    Resolver->>Resolver: resolver.resolve(operation)
    alt security requires authentication
        Resolver->>Handler: enforce_access_control(function)
    else public, optional auth, or opted out
        Resolver-->>Connexion: Resolution(function)
    end
    Connexion-->>App: registered resolved operation
Loading

Flow diagram for access-control configuration validation

flowchart TD
    A[Load SecurityConfig] --> B{access_control.enforce?}
    B -- No --> C[Start normally]
    B -- Yes --> D{auth.required?}
    D -- No --> E[Reject configuration]
    D -- Yes --> C
    F[Validate subject_prefix] --> G{Empty or overlaps group:?}
    G -- Yes --> H[Reject configuration]
    G -- No --> C
Loading

File-Level Changes

Change Details Files
Move enforcement decisions from raw OpenAPI pre-scanning into Connexion’s resolved operation flow.
  • Remove static operation discovery from API registration.
  • Evaluate effective security requirements and vendor opt-out per resolved operation.
  • Treat empty security alternatives as public and enforce referenced path-item operations.
  • Preserve permissions API enforcement with an enforce-all resolver mode.
foca/api/register_openapi.py
foca/security/access_control/enforcement.py
foca/security/access_control/register_access_control.py
tests/security/access_control/test_enforcement.py
Harden resolver compatibility and prevent silent enforcement bypasses.
  • Wrap callable Connexion resolvers in a Resolver instance.
  • Reject configurations that enable enforcement while authentication is optional or disabled.
  • Change application startup behavior from logging and skipping enforcement to validation failure.
foca/security/access_control/enforcement.py
foca/models/config.py
foca/foca.py
tests/models/test_config.py
tests/test_foca.py
tests/security/access_control/test_enforcement.py
Prevent subject namespace collisions through centralized prefix validation.
  • Centralize the group subject prefix constant.
  • Reject empty or overlapping subject prefixes during configuration validation.
  • Document prefixed policy subjects and distinguish header-based permission checks from token-based enforcement.
foca/security/access_control/constants.py
foca/security/access_control/enforcement.py
foca/models/config.py
docs/access_control/README.md
tests/models/test_config.py

Assessment against linked issues

Issue Objective Addressed Explanation
#262 Enforce policy checks on operations of $ref path items and treat operations with an empty security alternative as public, while supporting callable Connexion resolvers. ✅
#262 Reject configurations that enable enforcement without required authentication, or use an empty or group-overlapping subject_prefix. ✅
#262 Document the required prefixed policy subjects and clarify how config-driven enforcement relates to the separate check_permissions mechanism. ✅

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 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (4a9c55a) to head (25b1100).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #263   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           22        22           
  Lines         1099      1113   +14     
=========================================
+ Hits          1099      1113   +14     
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.

Copilot AI 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.

🟢 Approval recommended

The focused changes address the stated enforcement gaps with regression coverage and no unresolved findings.

No open issues 🎉

What changed in this PR

Hardens FOCA’s access-control enforcement to address #262 and the unreleased gaps from #259.

Changes:

  • Enforces resolved operations, handles optional authentication, and supports callable resolvers.
  • Rejects unsafe authentication settings and subject prefixes.
  • Adds regression tests and clarifies policy subjects and enforcement modes.
File Description
tests/​test_foca.py Checks startup rejection of invalid enforcement settings.
tests/​security/​access_control/​test_enforcement.py Tests references, optional authentication, and callable resolvers.
tests/​models/​test_config.py Tests prefix and enforcement validation.
foca/​security/​access_control/​register_access_control.py Keeps permissions API enforcement unconditional.
foca/​security/​access_control/​enforcement.py Selects resolved operations and wraps callable resolvers.
foca/​security/​access_control/​constants.py Centralizes the group prefix.
foca/​models/​config.py Rejects unsafe access-control configurations.
foca/​foca.py Removes the log-only enforcement fallback.
foca/​api/​register_openapi.py Removes raw-spec enforcement selection.
docs/​access_control/​README.md Clarifies enforcement, namespaces, and legacy permission checks.

Review effort: Balanced

@uniqueg
uniqueg marked this pull request as ready for review October 17, 2026 14:39
Test enforcement with a `Resolver` instance as well as a callable, as
both are accepted by Connexion; restores 100% coverage.

Refs #262

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 17, 2026 14: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 reviewed your changes and they look great!

Sourcery assessment

Needs a human reviewer. If operation resolution or security-requirement handling skips enforcement, callers may reach protected endpoints without the policy check; any data or access exposed before the defect is fixed cannot be undone by reverting. The configuration validation and prefix checks also change authorization behavior, so verify those boundaries carefully.


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

Copilot AI 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.

🟡 Changes recommended

Resolver normalization breaks previously supported non-callable custom resolvers.

1 open issue

Review effort: Balanced

Normalize resolvers the same way as Connexion's `App.add_api()`: wrap
only callables in a `Resolver`, and use any other resolver object (with
a `resolve()` method) as is. Previously, resolver objects not inheriting
from `Resolver` were wrongly wrapped as function resolvers, breaking API
registration with enforcement enabled.

Refs #262

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Copilot AI balanced review requested due to automatic review settings October 17, 2026 14:56

Copilot AI 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.

🔵 Needs a closer look

Security-critical enforcement relies on private Connexion metadata and warrants human validation of integration behavior.

No open issues 🎉

1 resolved since last review

Review effort: Balanced

@uniqueg
uniqueg merged commit 42300c6 into dev Oct 17, 2026
25 checks passed
@uniqueg
uniqueg deleted the issue-262-review-findings branch October 17, 2026 15:07
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.

Address review findings on access control

2 participants