Skip to content

feat(access-control): add API switch, base path - #678

Merged
uniqueg merged 7 commits into
devfrom
feat/611-permissions-api-switch
Nov 4, 2026
Merged

uniqueg merged 7 commits into
devfrom
feat/611-permissions-api-switch

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Closes #611.

  • security.access_control.api_enabled (default true): with false, the permissions API, its Swagger UI and specification aren't registered, and policies are still enforced.
  • security.access_control.api_base_path (default /admin/access-control) moves the default API; a custom api_specs wins, with a warning.
  • Startup warnings:
    • api_specs or self_service without the API.
    • policies of type p other than those of admins that match the API; they can be deliberate, so they aren't refused, unlike rules with {base_path}.
    • policies for the default path after a move.
    • A base path that overlaps with one of the app's APIs. The same base path as one of them is refused, naming the setting.
  • Docs: docs/access-control.md, docs/configuration/access-control.md.

Verification

  • Local: ruff, mypy, mkdocs strict and pytest with 100% coverage (3531 passed, 1 skipped), before merging dev.
  • Reviewers: both rounds done. Round 2 compared the {base_path} refusal before and after the refactor on 1620 combinations: same outcomes.

Declined review findings

  • **base_path dict style (low): kept, so that custom specifications keep Connexion's handling of the base path.
  • Warning for stored rules that aren't configured when the API is off (medium): stored rules include the roles of owners, so it would fire on each start. The docs and docstring now say that these rules stay in effect and policies doesn't remove them.
  • Refusing exact path and method collisions with an overlapping app API (medium): a warning covers overlapping base paths, and a collision check per method is more than this issue needs.
  • Changelog and release notes: written at the release.

🤖 Generated with Claude Code

Summary by Sourcery

Add configurable registration and routing controls for the access-control management API while preserving policy enforcement and warning about potentially affected configurations.

New Features:

  • Add configuration switches to disable the access-control management API or move its default base path.
  • Allow custom API specifications to define the API base path while warning when the configured base path is overridden.

Enhancements:

  • Validate access-control API base paths and detect conflicts or overlaps with application API paths.
  • Add startup warnings for policies that reference the old or newly configured access-control API paths, while continuing to enforce policies when the API is disabled.
  • Document the new API settings and their policy and routing implications.

Documentation:

  • Document disabling and relocating the access-control API, custom specification precedence, and related policy warnings.

Tests:

  • Add coverage for API disabling, base-path relocation and validation, custom specification precedence, route conflicts, and policy warnings.

uniqueg and others added 4 commits November 4, 2026 06:34
Operators who manage roles through the configuration only can take the
permissions API off the internet with api_enabled, or move it with
api_base_path, without supplying a whole specification. A custom
specification wins, with a warning.

Closes #611

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Warn about literal rules that match the permissions API and rules for
its default path after a move, and about a base path under an API of
the app; refuse the same base path, naming the setting. Say what
happens to stored rules, and warn about self-service without the API.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Check the objects of `p` rules only, so that wildcards such as `*` are
found, and leave out rules of admins and invalid patterns. Warn about
overlaps of base paths both ways, and not about rules for the default
path if the API moved below it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…pi-switch

# Conflicts:
#	foca/security/access_control/register_access_control.py
@uniqueg uniqueg added this to the v0.21.0 milestone Nov 4, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The pull request introduces an access-control API switch and configurable base path, retaining policy enforcement when management endpoints are disabled. It also adds path-conflict validation, policy safety diagnostics, custom-specification precedence handling, documentation, and comprehensive tests.

Sequence diagram for configurable access-control API registration

sequenceDiagram
    participant Startup
    participant register_permission_specs
    participant Connexion
    participant AccessControlAPI

    Startup->>register_permission_specs: register_permission_specs()
    alt api_enabled is false
        register_permission_specs-->>Startup: Return app without API registration
    else api_enabled is true and api_specs is unset
        register_permission_specs->>_check_api_base_path: _check_api_base_path(app, api_base_path)
        _check_api_base_path-->>register_permission_specs: Validate path and detect conflicts
        register_permission_specs->>Connexion: add_api(specification, base_path)
        Connexion-->>AccessControlAPI: Register permissions API
    else api_specs is set
        register_permission_specs->>Connexion: add_api(specification)
        Connexion-->>AccessControlAPI: Use specification-defined base path
    end
Loading

Flow diagram for access-control API configuration outcomes

flowchart TD
    Config[AccessControlConfig] --> Enabled{api_enabled?}
    Enabled -->|No| Enforce[Enforce configured and stored policies]
    Enabled -->|Yes| Spec{api_specs set?}
    Spec -->|Yes| Custom[Register custom specification path]
    Spec -->|No| Validate[Validate api_base_path]
    Validate --> Conflict{Exact app API base path?}
    Conflict -->|Yes| Reject[Raise configuration error]
    Conflict -->|No| Register[Register default API at api_base_path]
    Validate --> Overlap[Warn on overlapping app API paths]
    Overlap --> Register
Loading

File-Level Changes

Change Details Files
Added configurable registration and routing for the access-control management API while preserving policy enforcement when the API is disabled.
  • Added api_enabled and api_base_path configuration with validation and defaults.
  • Skipped API, Swagger UI, and specification registration when disabled, while retaining enforcement and warning about ineffective API settings.
  • Applied the configured base path to the default specification and documented custom-specification precedence.
foca/models/config.py
foca/security/access_control/register_access_control.py
docs/access-control.md
docs/configuration/access-control.md
Added startup diagnostics and safeguards for interactions between the permissions API, application APIs, and policy rules.
  • Rejected exact base-path collisions and warned on overlapping application API paths.
  • Warned about non-admin literal policies matching the permissions API and stale policies targeting the former default path.
  • Continued rejecting {base_path} rules that expand into permissions API paths, while refactoring path matching into reusable helpers.
foca/security/access_control/register_access_control.py
docs/access-control.md
Expanded automated coverage for API switching, custom routing, validation, policy diagnostics, and compatibility behavior.
  • Tested disabled and relocated API registration, enforcement, warnings, and custom specification precedence.
  • Covered application API path conflicts, literal and placeholder policy interactions, default-path warnings, and valid/invalid base paths.
tests/security/access_control/test_path_helpers.py

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 Nov 4, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (0d01ccc) to head (898ed57).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #678   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           58        58           
  Lines         7538      7592   +54     
=========================================
+ Hits          7538      7592   +54     
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 November 4, 2026 06:32

@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 6 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="foca/security/access_control/register_access_control.py" line_range="574" />
<code_context>
     specification: Path | dict[str, Any]
+    base_path: dict[str, str] = {}
     if access_control_config.api_specs is None:
+        _check_api_base_path(app.app, access_control_config.api_base_path)
+        base_path["base_path"] = access_control_config.api_base_path
         spec_path = str(files(ACCESS_CONTROL_BASE_PATH).joinpath(DEFAULT_API_SPEC_PATH))
</code_context>
<issue_to_address>
**Overlapping routes go unchecked**

When a custom specification resolves to a base path that equals or overlaps an app API's base path, `register_permission_specs` skips `_check_api_base_path` for custom specifications, so the overlap warning or refusal never runs and the routes can shadow one another or have policy rules grant access across them.

Resolve the custom specification's base path and pass it to `_check_api_base_path` as well as checking the default specification's path.

Also at `foca/security/access_control/register_access_control.py:585-586`, `foca/security/access_control/register_access_control.py:588`.
</issue_to_address>

### Comment 2
<location path="foca/security/access_control/register_access_control.py" line_range="644-645" />
<code_context>
+                "'security.access_control.api_base_path' must differ from the "
+                f"base paths of the app's APIs: '{base_path}'"
+            )
+        if (base_path and api_base_path.startswith(f"{base_path}/")) or (
+            base_path.startswith(f"{api_base_path}/")
+        ):
+            logger.warning(
</code_context>
<issue_to_address>
**Root API route collisions go unnoticed**

When an app API has a root base path and declares a path and method also registered by the permissions API, `_check_api_base_path` skips the overlap check when an app API has an empty root base path, without checking its registered paths. If that API declares a route also used by the permissions API, the conflict is not warned about and one route can shadow the other.

Check the registered operation paths for collisions when either API has a root base path, and warn or refuse overlapping routes.
</issue_to_address>

### Comment 3
<location path="foca/models/config.py" line_range="944" />
<code_context>
     """

     enabled: bool = False
+    api_enabled: bool = True
+    api_base_path: str = "/admin/access-control"
     api_specs: str | None = None
</code_context>
<issue_to_address>
**Disabled API settings prevent startup**

When `api_enabled` is false, `api_swagger_ui` is true, and `api_serve_spec` is explicitly false, `AccessControlConfig.validate_swagger_ui` raises before `register_permission_specs` can skip registration, so the app does not start even though the API and its settings are inactive.

Skip the Swagger UI validation when `api_enabled` is false.

Also at `docs/access-control.md:215`.
</issue_to_address>

### Comment 4
<location path="foca/security/access_control/register_access_control.py" line_range="752" />
<code_context>
+        not access_control_config.api_enabled
+        or access_control_config.api_specs is not None
+        or access_control_config.api_base_path == default
+        or access_control_config.api_base_path.startswith(f"{default}/")
+    ):
+        return
</code_context>
<issue_to_address>
**Stale policy warning is suppressed**

When the API moves below the default path and a configured policy targets only an old endpoint, `_warn_default_base_path` returns for every base path below the default, so it never checks the policy and operators miss that the rule no longer applies to the moved API.

Allow the stale-policy check to run for base paths below the default.
</issue_to_address>

### Comment 5
<location path="foca/security/access_control/register_access_control.py" line_range="756" />
<code_context>
+    ):
+        return
+    for rule in access_control_config.policies or []:
+        if any(value.startswith(f"{default}/") for value in rule[1:]):
+            logger.warning(
+                "Policy rule %r names the default path of the permissions API, "
</code_context>
<issue_to_address>
**Stale policy warnings are inaccurate**

When the API moves and a policy has a path-like subject or action, or its object matches a former API path through a wildcard, `_warn_default_base_path` scans every policy value with a literal prefix test, so it warns for subjects or actions that do not target the API and misses wildcard object matches; operators receive misleading diagnostics or miss stale-rule warnings.

Check the policy object against the former API paths using path-pattern matching rather than scanning every value with a literal prefix test.
</issue_to_address>

### Comment 6
<location path="foca/models/config.py" line_range="944-945" />
<code_context>
     """

     enabled: bool = False
+    api_enabled: bool = True
+    api_base_path: str = "/admin/access-control"
     api_specs: str | None = None
     api_swagger_ui: bool = False
</code_context>
<issue_to_address>
**API settings are silently ignored**

When `security.access_control.enabled` is false and either new setting is explicitly configured, `SecurityConfig.validate_access_control` omits the new API settings from its disabled-access-control checks, and `Foca.create_app` skips registration when `enabled` is false. An explicitly configured `api_enabled: false` or non-default `api_base_path` is therefore accepted but has no effect.

Have the disabled-access-control validator reject explicitly configured API settings that differ from their defaults.
</issue_to_address>

Linked issues

#611 feat(access-control): add API switch and base path · 6 of 6 met

# Requirement Status Notes
1 Disable the permissions API without disabling policy enforcement ✅ Met Registration returns early when api_enabled is false; tests check that the API routes return 404 and policies still allow or deny requests.
2 Add api_base_path, defaulting to /admin/access-control ✅ Met The config field defaults to /admin/access-control and is passed to Connexion for the default specification; tests cover the default and a custom path.
3 Let an explicit api_specs specification win, with a warning ✅ Met A custom specification takes precedence, and an explicitly set api_base_path triggers a warning; the behavior is documented and tested.
4 Test disabled routes, unchanged enforcement, custom base path, defaults, and 100% coverage ✅ Met The added tests cover these cases, and the PR description reports pytest with 100% coverage.
5 Update the documentation ✅ Met The access-control guide and configuration reference describe the switch, base path, and custom-spec precedence.
6 Keep existing behavior by default ✅ Met api_enabled defaults to true and api_base_path defaults to the existing API path.

Sourcery assessment

Needs a human reviewer. 6 findings to address first, and moving the permissions API beneath a path covered by a broad policy can let users use that API to change permissions, potentially granting themselves admin access. Reverting the path can close the exposure, but it does not undo permission rules already written through the API.

Blocking findings: foca/security/access_control/register_access_control.py:574, foca/security/access_control/register_access_control.py:645, foca/models/config.py:944, foca/security/access_control/register_access_control.py:752, foca/security/access_control/register_access_control.py:756, and 1 more


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

Comment thread foca/models/config.py Resolved
Comment thread foca/models/config.py Resolved
uniqueg and others added 2 commits November 4, 2026 08:20
Warn about rules for the former path of the API by their objects only,
also for wildcards and below the default. Refuse API settings without
access control, and don't check those of a disabled API.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit 39d6787 into dev Nov 4, 2026
56 checks passed
@uniqueg
uniqueg deleted the feat/611-permissions-api-switch branch November 4, 2026 07:48
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.

feat(access-control): add API switch and base path

1 participant