Skip to content

feat: add public path helpers - #667

Merged
uniqueg merged 5 commits into
devfrom
feat/606-public-path-helpers
Nov 4, 2026
Merged

uniqueg merged 5 commits into
devfrom
feat/606-public-path-helpers

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 4, 2026 •

Copy link
Copy Markdown
Member

Summary

Generalizes what cloud-registry does with may_read_service and _api_base_path:

  • foca.security.access_control.is_permitted_for(path, method="GET"): may the current caller do this on that path? False if no route serves it directly; True if the route doesn't enforce policies; False for anonymous callers otherwise.
  • foca.utils.urls.get_api_base_path(operation_id=None) and get_resource_path(*segments, operation_id=None): the base path of the API and a path below it, during requests and on startup. Apps with several APIs name an operation.
  • {base_path} in configured policies (security.access_control.policies) expands to one rule per app API. Startup fails if the value would match the permissions API, or if no API exists.
  • Docs: access control ("Checking other paths", placeholder), utilities, reference, configuration.

Closes #606

Verification

  • ruff check, ruff format --check, mypy, ast-grep scan, mkdocs build --strict: pass.
  • coverage run -m pytest with MongoDB 7.0: 3436 passed, 1 skipped, 100% coverage.
  • Both reviewer subagents, then a second adversarial round; findings of both rounds fixed except as below.
  • CI: see the checks of this PR.

Declined review findings

  • A batch API for many permission checks: the cost of per-item checks is documented; add one when an app needs it.
  • Entries in the 0.20.0 release docs: 0.20.0 is released, and this PR does no release preparation.
  • Rejecting all pattern syntax in get_resource_path() segments: rule values are regular expressions, so this would refuse common identifiers (dots, URNs). The docs and docstring instead say that paths with identifiers from clients don't belong in policy rules; roles on resources and is_permitted_for() match them literally.

🤖 Generated with Claude Code

Summary by Sourcery

Provide public helpers for resolving API resource paths, checking permissions on other routes, and configuring policies relative to API base paths.

New Features:

  • Add is_permitted_for() for checking the current caller’s access to other API paths and methods.
  • Add helpers for resolving API base paths and constructing resource paths during requests and application startup.
  • Support {base_path} expansion in configured access-control policies across one or more application APIs.

Enhancements:

  • Register API metadata and resolved operations so path helpers can identify APIs and operation IDs, including referenced path items.
  • Prevent base-path policies from unintentionally covering the permissions API and reject ambiguous or unavailable API mappings.

Documentation:

  • Document path permission checks, API and resource path helpers, base-path policy placeholders, and their configuration and usage.

Tests:

  • Add comprehensive coverage for permission decisions, path construction, multi-API resolution, referenced operations, policy expansion, and permissions-API protection.

Apps need to ask whether the caller may act on another path, and to name
paths below the base path of their API; cloud-registry carries its own
code for both. Add is_permitted_for(), get_api_base_path() and
get_resource_path(), and a {base_path} placeholder in configured
policies, which expands to one rule per API of the app.

Closes #606

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@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

Introduces public API/resource path and arbitrary-path permission helpers, backed by registered and reference-resolved OpenAPI operations, and makes configured access-control rules portable through protected {base_path} expansion across one or multiple application APIs; documentation and comprehensive tests cover the new behavior.

Sequence diagram for arbitrary-path permission checking

sequenceDiagram
    participant Caller
    participant is_permitted_for
    participant Router
    participant Policies

    Caller->>is_permitted_for: is_permitted_for(path, method)
    is_permitted_for->>Router: match(path, method)
    alt no direct route
        Router-->>is_permitted_for: no match
        is_permitted_for-->>Caller: False
    else route does not enforce policies
        Router-->>is_permitted_for: unenforced route
        is_permitted_for-->>Caller: True
    else route enforces policies
        Router-->>is_permitted_for: enforced route
        is_permitted_for->>Policies: _is_permitted_on(subject, path, method)
        Policies-->>is_permitted_for: policy decision
        is_permitted_for-->>Caller: True or False
    end
Loading

Sequence diagram for API resource path resolution

sequenceDiagram
    participant App
    participant get_resource_path
    participant get_api_base_path
    participant RegisteredAPIs

    App->>get_resource_path: get_resource_path(segments, operation_id)
    get_resource_path->>get_api_base_path: get_api_base_path(operation_id)
    get_api_base_path->>RegisteredAPIs: resolve registered API
    RegisteredAPIs-->>get_api_base_path: base_path
    get_api_base_path-->>get_resource_path: base_path
    get_resource_path-->>App: base_path + resource segments
Loading

Flow diagram for base path policy expansion

flowchart TD
    Config["Configured policy containing {base_path}"] --> APIs{Application APIs exist?}
    APIs -- No --> Fail[Startup fails with ValueError]
    APIs -- Yes --> Expand[_expand_base_path]
    Expand --> Protected{Matches permissions API?}
    Protected -- Yes --> Fail
    Protected -- No --> Store[Store one expanded rule per application API]
Loading

File-Level Changes

Change Details Files
Add public helpers for resolving API base paths and constructing literal resource paths across request and startup contexts.
  • Track registered application and permissions APIs, including operation IDs and base paths.
  • Resolve APIs by the current request, a named operation, or a single configured API, with validation for ambiguous or invalid resource segments.
  • Register resolved OpenAPI operations, including referenced path items, so helpers can identify the correct API.
foca/utils/urls.py
foca/api/register_openapi.py
foca/security/access_control/register_access_control.py
Add arbitrary-path authorization checks that evaluate the matched route and current caller without issuing request denials.
  • Expose is_permitted_for() and factor policy evaluation into a reusable path/method helper.
  • Reject malformed, redirected, nonexistent, catch-all, or unauthenticated policy-enforced paths; allow routes that do not enforce access-control policies.
  • Use the current subject, service client, and opt-in roles while logging helper denials at DEBUG.
foca/security/access_control/enforcement.py
foca/security/access_control/__init__.py
Make configured access-control policies portable across API base paths through {base_path} expansion.
  • Expand placeholder-containing rules once per application API before validation and storage.
  • Handle root APIs and no-API failures, and validate expanded rules.
  • Reject expansions that could match the permissions API, including catch-all rules for root APIs.
foca/security/access_control/constants.py
foca/security/access_control/register_access_control.py
foca/models/config.py
Document and comprehensively test the new path and authorization APIs and policy behavior.
  • Document helper semantics, request/startup behavior, path safety restrictions, caller handling, and placeholder configuration.
  • Add coverage for single and multi-API resolution, operation references, root/absolute server paths, arbitrary authorization decisions, and placeholder expansion/protection.
  • Update reference documentation and adapt registration tests to mocked API return values.
docs/access-control.md
docs/utilities.md
docs/reference.md
tests/security/access_control/test_path_helpers.py
tests/api/test_register_openapi.py
tests/security/access_control/test_register_access_control.py

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

@uniqueg
uniqueg marked this pull request as ready for review November 4, 2026 03:40
@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 (78a18c9) to head (f1b0d44).

Additional details and impacted files
@@            Coverage Diff            @@
##               dev      #667   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files           56        56           
  Lines         7231      7328   +97     
=========================================
+ Hits          7231      7328   +97     
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.

@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 8 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="668" />
<code_context>
+            protected_paths=[
+                f"{base_path}{path}"
+                for base_path in _get_api_base_paths(app.app, is_app_api=False)
+                for path in ("/permissions", "/permissions/id")
+            ],
         )
</code_context>
<issue_to_address>
**Custom permission routes stay unprotected**

When a custom permissions specification uses management paths outside `/permissions` and `/permissions/{id}`, and a `{base_path}` rule matches one of those paths, `_expand_base_path()` checks only the hard-coded paths, so the rule passes startup validation and grants access to management routes the app intended to protect.

Derive the protected management paths from the permissions specification and validate placeholder rules against those paths.
</issue_to_address>

### Comment 2
<location path="foca/security/access_control/register_access_control.py" line_range="668" />
<code_context>
+            protected_paths=[
+                f"{base_path}{path}"
+                for base_path in _get_api_base_paths(app.app, is_app_api=False)
+                for path in ("/permissions", "/permissions/id")
+            ],
         )
</code_context>
<issue_to_address>
**Permission items bypass startup protection**

When a placeholder rule matches a valid permission-item path with an ID other than the literal `id`, `_expand_base_path()` checks the dynamic permissions endpoint only as `/permissions/id`, so the rule passes startup validation and can grant access to matching permission items.

Validate placeholder rules against the dynamic permissions route rather than a sample item path.

Also at `foca/security/access_control/register_access_control.py:806-809`.
</issue_to_address>

### Comment 3
<location path="foca/security/access_control/register_access_control.py" line_range="807-808" />
<code_context>
+        for base in base_paths:
+            for value in rule[1:]:
+                if BASE_PATH_PLACEHOLDER in value and key_match2(
+                    path, value.replace(BASE_PATH_PLACEHOLDER, base)
+                ):
+                    raise ValueError(
+                        f"Policy rule {rule!r} has the placeholder "
</code_context>
<issue_to_address>
**Regex policies bypass startup protection**

When the configured model matches paths differently from `key_match2`, and a `{base_path}` rule matches a protected permissions path under that model, `_expand_base_path()` uses `key_match2` for validation, so a rule accepted by the configured model can pass startup validation and grant access to the permissions API.

Validate placeholder rules using the configured model’s path-matching semantics.
</issue_to_address>

### Comment 4
<location path="foca/security/access_control/enforcement.py" line_range="858-864" />
<code_context>
+        if it would redirect, or the method is empty and the path doesn't
+        start with one slash).
+    """
+    method = method.upper()
+    # Werkzeug would normalize these, unlike requests
+    if not method or not path.startswith("/") or path.startswith("//"):
+        return False
+    # No host-specific routes: FOCA's APIs don't have any
+    try:
+        rule, _ = current_app.url_map.bind("localhost").match(
+            path, method=method, return_rule=True
+        )
</code_context>
<issue_to_address>
**OPTIONS decisions contradict Flask behavior**

When a caller checks `OPTIONS` for a route with Flask’s automatic OPTIONS handling, `is_permitted_for()` matches the automatic OPTIONS route and evaluates its policy, returning an allow or deny decision for a request Flask serves itself.

Exclude automatically handled OPTIONS requests from policy decisions in `is_permitted_for()`.

Also at `foca/security/access_control/enforcement.py:873-879`.
</issue_to_address>

### Comment 5
<location path="foca/utils/urls.py" line_range="409-411" />
<code_context>
+
+    apis = _get_apis(current_app)
+    if operation_id is not None:
+        for api in apis:
+            if operation_id in api.operation_ids:
+                return api.base_path
+        raise LookupError(f"No API of the app has the operation '{operation_id}'")
+    if has_request_context() and request.blueprint is not None:
</code_context>
<issue_to_address>
**Repeated operation IDs select wrong API**

When separate API specifications register the same operation ID and a caller uses it to select an API, `get_api_base_path()` returns the first matching API, so callers selecting the later API get the wrong base path and `get_resource_path()` builds a path under the wrong API.

Detect ambiguous operation IDs and avoid returning an arbitrary API base path.
</issue_to_address>

### Comment 6
<location path="foca/api/register_openapi.py" line_range="161-163" />
<code_context>
+        # e.g., specification extensions (`x-...`), which may have any value
+        if not isinstance(path_item_object, dict):
+            continue
+        resolved = _resolve_path_item(spec, path_item_object)
+        for _, operation_object in _iter_path_item(resolved):
+            yield operation_object
+
+
</code_context>
<issue_to_address>
**Referenced operations cannot select API**

When an API uses an external `$ref` for a Path Item Object and a caller selects the API by an operation ID in that reference, `_resolve_path_item()` leaves the external reference unresolved, so operation collection omits its IDs and `get_api_base_path()` raises `LookupError`.

Resolve external Path Item Object references when collecting operation IDs.

Also at `foca/utils/urls.py:346-349`.
</issue_to_address>

### Comment 7
<location path="tests/security/access_control/test_path_helpers.py" line_range="332-335" />
<code_context>
+    ) -> None:
+        """No request was denied, so denials aren't logged as for requests."""
+        logger = "foca.security.access_control.enforcement"
+        with caplog.at_level(logging.INFO, logger=logger):
+            result = _request(app, "bob", lambda: is_permitted_for("/api/v1/pets/1"))
+        assert result is False
+        assert "Access denied" not in caplog.text
+
+    def test_default_method(self, app: Flask) -> None:
</code_context>
<issue_to_address>
**Missing denial logs pass**

When the implementation stops logging denials, `test_denial_logged_as_debug` only checks at line 335 that the message is absent; with no denial logging at all, that assertion passes, so the test does not verify the expected DEBUG log.

Capture DEBUG logs and assert that a denial record is present at DEBUG level.
</issue_to_address>

### Comment 8
<location path="tests/security/access_control/test_path_helpers.py" line_range="339" />
<code_context>
+
+    def test_default_method(self, app: Flask) -> None:
+        """The method defaults to `GET`."""
+        assert _request(app, "alice", lambda: is_permitted_for("/api/v1/pets/1"))
+
+    def test_no_request(self, app: Flask) -> None:
</code_context>
<issue_to_address>
**Truthy values hide wrong results**

When `is_permitted_for()` returns a non-boolean truthy or falsy value in these scenarios, the bare assertions in `test_default_method` (line 339), `test_matches_route` (line 528), and the placeholder tests (lines 572, 594–597) accept any truthy or falsy value. A regression returning `1` or `None` instead of the documented boolean result would pass these checks, so callers relying on the boolean contract would see a break the tests miss.

Assert the expected boolean explicitly, such as with `is True` or `is False`.

Also at `tests/security/access_control/test_path_helpers.py:528`, `tests/security/access_control/test_path_helpers.py:573`, `tests/security/access_control/test_path_helpers.py:594-596`.
</issue_to_address>

Linked issues

#606 feat(access-control): add public path helpers · 6 of 6 met

# Requirement Status Notes
1 Publicly check whether the current caller may access another path ✅ Met is_permitted_for() is exported from foca.security.access_control and checks the matched route and policies for the current caller.
2 Provide API base-path and resource-path helpers for requests and startup ✅ Met get_api_base_path() and get_resource_path() support request and app-context use; callers can name an operation to select an API when needed.
3 Expand {base_path} to one configured policy rule per app API ✅ Met Configured rules are expanded for each registered app API, and startup rejects placeholder rules when there is no app API or when they match the permissions API.
4 Document the helpers and include access-control examples ✅ Met The access-control page documents the helpers and placeholder with examples; the utilities page and reference are updated too.
5 Test permitted and denied checks, unauthenticated callers, multiple API base paths, and startup use; maintain 100% coverage ✅ Met The added tests cover those cases, coverage is configured to fail below 100%, and the PR reports 100% coverage.
6 Keep helper signatures free of Flask and Connexion types ✅ Met The public helpers use string and built-in Python types; Flask is imported locally inside get_api_base_path() rather than exposed in a signature.

Sourcery assessment

Needs a human reviewer. 8 findings to address first, and if placeholder expansion scopes a policy too broadly, callers could gain access to protected routes or the permissions API. Reverting would stop the incorrect rule from applying going forward, but it cannot undo data or access already exposed.

Blocking findings: foca/security/access_control/register_access_control.py:668, foca/security/access_control/register_access_control.py:668, foca/security/access_control/register_access_control.py:808, foca/security/access_control/enforcement.py:864, foca/utils/urls.py:411, and 3 more


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

Comment thread foca/utils/urls.py Resolved
Comment thread foca/api/register_openapi.py Resolved
uniqueg and others added 4 commits November 4, 2026 05:40
Protect all paths of the permissions API from its specification, and
rules naming one item. Permit OPTIONS requests that Flask answers
itself. Refuse to pick an API for an operation of several APIs without
a request to one of them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@uniqueg
uniqueg merged commit ba8ab31 into dev Nov 4, 2026
56 checks passed
@uniqueg
uniqueg deleted the feat/606-public-path-helpers branch November 4, 2026 05:29
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 public path helpers

1 participant