Repository navigation
feat: add public path helpers - #667
Conversation
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]>
Reviewer's GuideIntroduces 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 Sequence diagram for arbitrary-path permission checkingsequenceDiagram
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
Sequence diagram for API resource path resolutionsequenceDiagram
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
Flow diagram for base path policy expansionflowchart 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]
File-Level Changes
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #667 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 56 56
Lines 7231 7328 +97
=========================================
+ Hits 7231 7328 +97
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
There was a problem hiding this comment.
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
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]>
…to feat/606-public-path-helpers
Summary
Generalizes what cloud-registry does with
may_read_serviceand_api_base_path:foca.security.access_control.is_permitted_for(path, method="GET"): may the current caller do this on that path?Falseif no route serves it directly;Trueif the route doesn't enforce policies;Falsefor anonymous callers otherwise.foca.utils.urls.get_api_base_path(operation_id=None)andget_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.Closes #606
Verification
ruff check,ruff format --check,mypy,ast-grep scan,mkdocs build --strict: pass.coverage run -m pytestwith MongoDB 7.0: 3436 passed, 1 skipped, 100% coverage.Declined review findings
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 andis_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:
is_permitted_for()for checking the current caller’s access to other API paths and methods.{base_path}expansion in configured access-control policies across one or more application APIs.Enhancements:
Documentation:
Tests: