Repository navigation
refactor(api): check routes from specs - #707
Conversation
Record the operations of registered APIs in a route table, with match() for apps, and use it instead of Flask's routes for FOCA's route checks and lookups, so that they don't pass vacuously when routes are built lazily, as on Connexion 3. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideAdds a Connexion registration hook that records specification operations in an independent route table, then refactors access-control and related integrations to resolve routes through that table rather than Flask internals, with documented semantics and comprehensive parity and regression tests. Sequence diagram for recording and matching an API operationsequenceDiagram
participant App as Connexion app
participant API as Recording API
participant Table as FOCA route table
participant Matcher as match()
participant Caller as Access-control consumer
App->>API: add_api()
API->>API: _add_operation_internal()
API->>Table: _add_route(Route)
Caller->>Matcher: match(path, method)
Matcher->>Table: Werkzeug rule matching
Table-->>Matcher: RouteMatch(route, params)
Matcher-->>Caller: RouteMatch or None
File-Level Changes
Possibly linked issues
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 #707 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 66 67 +1
Lines 8599 8673 +74
=========================================
+ Hits 8599 8673 +74
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:
|
Ownership wrappers also need policies to have run for the request, as a route outside of the table can share a path with an enforced one. Install the table in register_openapi() too, and drop what became unused. Co-Authored-By: Claude Opus 5.5 <[email protected]>
The app context can outlive a request, so keep the request itself. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Hey - I've found 5 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/api/register_openapi.py" line_range="467" />
<code_context>
not a mapping, patches set fields of path items defined via
`$ref`, or the specification is invalid after applying patches.
"""
+ _install_route_table(app)
+
# Iterate over OpenAPI specs
</code_context>
<issue_to_address>
**Earlier API routes are missing**
When a plain Connexion `App` has an API registered before `register_openapi()` installs the table, `_install_route_table()` instruments only future `add_api()` calls, so `match()` finds no operation and the ownership wrapper raises `RuntimeError`, returning a 500 for requests to ownership controllers on those earlier routes.
Install the route recorder before any API registration, or backfill operations from APIs already registered when installing it.
</issue_to_address>
### Comment 2
<location path="foca/api/routes.py" line_range="87-90" />
<code_context>
+
+ routes: list[Route] = field(default_factory=list)
+ rules: Map = field(
+ default_factory=lambda: Map(
+ converters={"float": NumberConverter, "int": IntegerConverter}
+ )
+ )
+
</code_context>
<issue_to_address>
**Accepted slash paths are rejected**
When an app customizes Flask URL-map settings such as `strict_slashes=False`, `_RouteTable` builds its own `Map` with Werkzeug defaults, so `match()` can return no operation for a path Flask serves; ownership checks then reject the request or raise `RuntimeError`.
Initialize the route table with the Flask app’s URL-map settings.
</issue_to_address>
### Comment 3
<location path="foca/api/routes.py" line_range="100-104" />
<code_context>
+ itself, unless the operation is one, so that the order of the
+ rules for a path counts in the same way.
+ """
+ self.routes.append(route)
+ self.rules.add(
+ Rule(
+ route.rule,
+ endpoint=len(self.routes) - 1,
+ methods={route.method, "OPTIONS"},
+ )
</code_context>
<issue_to_address>
**Concurrent registrations return the wrong operation**
When two threads register APIs on the same app at the same time, `_RouteTable.add` appends a route and then derives its endpoint from the shared list length without synchronization, so both rules can point to the same route; `match()` then returns the wrong operation and path parameters.
Assign each rule an endpoint atomically with its route append.
</issue_to_address>
### Comment 4
<location path="foca/api/service_info.py" line_range="175" />
<code_context>
- rule.rule
- for rule in app.url_map.iter_rules()
- if unwrap(app.view_functions[rule.endpoint]) is controller
+ route.rule for route in get_routes(app) if unwrap(route.function) is controller
)
</code_context>
<issue_to_address>
**Direct service-info route escapes startup check**
When an app registers `getServiceInfo` with `Flask.add_url_rule()` instead of an API specification and omits service-info configuration, `_routes_to_controller` no longer finds a plain Flask route to `getServiceInfo`, so `check_service_info` treats the app as having no service-info endpoint and allows startup; requests to that route then fail with an internal server error because no service info is configured.
Preserve direct Flask-route detection for this startup validation while using the operation table for specification routes.
</issue_to_address>
### Comment 5
<location path="foca/security/access_control/enforcement.py" line_range="866-867" />
<code_context>
- # Connexion's route for authenticating all paths (`auth_all_paths`) serves
- # no operation, it only responds with `404`
- if rule.rule.endswith(_CATCH_ALL_RULE_SUFFIX):
+ found = _match_rule(path, method)
+ if found is None:
return False
- if (method == "OPTIONS" and getattr(rule, "provide_automatic_options", False)) or (
</code_context>
<issue_to_address>
**Preserve Connexion 2 behavior**
The issue requires no behavior change on Connexion 2, but is_permitted_for() now matches against the operation table only. As the PR notes, paths served by non-operation routes can therefore receive different decisions than before.
</issue_to_address>Linked issues
#632 refactor: check routes from specs, not url_map · 9 of 10 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Record each operation’s method, base-path path, operation ID, security, x-foca-* extensions, and resolved function. | ✅ Met | The recording API captures these fields, including the resolver’s function after FOCA wrappers. |
| 2 | Expose get_routes() and match(path, method), with path parameters. | ✅ Met | Both helpers are implemented; match() returns the matched route and converted parameters. |
| 3 | Use the route table for the route checks and lookups named in the issue. | ✅ Met | _check_routes_enforced, the ownership wrappers, and the service-info check use the table. |
| 4 | Define and document path semantics, including the API base path and app root path. | ✅ Met | The semantics are described in the module docstring and docs/utilities.md. |
| 5 | Provide and document match() as a helper for apps. | ✅ Met | docs/utilities.md documents how apps can call match() and inspect its result. |
| 6 | No behavior change on Connexion 2. | 🟡 Partly met | Operation routes use the new table, but the PR documents behavior changes for non-operation routes, including Swagger UI, served specifications, and routes added directly to Flask. |
| 7 | Remove url_map, view_functions, url_rule, and test_request_context from route checks or lookups in foca/. | ✅ Met | A search of foca/ found no remaining uses of these route lookup APIs. |
| 8 | Keep the startup checks failing in the same cases and test the ownership and service-info cases. | ✅ Met | The new tests cover an unenforced ownership route; the existing service-info endpoint test verifies startup fails when that route is served without service-info configuration. |
| 9 | Test that the checks do not depend on Flask routes having been built. | ✅ Met | Tests empty Flask’s url_map before checking an ownership route and a service-info route. |
| 10 | Test match() with base paths, path parameters, and an app root path. | ✅ Met | The route tests cover base paths, typed parameters, and SCRIPT_NAME. |
Sourcery assessment
Needs a human reviewer. 5 findings to address first, and access-control decisions now depend on a specification-built route table rather than Flask’s live routing table; if it matches a request to the wrong operation, a protected route could be treated as public and expose data or allow unauthorized changes. Reverting prevents future decisions based on that table, but cannot undo access or changes that already occurred.
Blocking findings: foca/api/register_openapi.py:467, foca/api/routes.py:90, foca/api/routes.py:104, foca/api/service_info.py:175, foca/security/access_control/enforcement.py:867
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes #632
Summary
New
foca.api.routes: a route table filled while APIs are registered, withget_routes()andmatch(path, method)._check_routes_enforced, the ownership wrappers, the service-info check,is_permitted_for, the check ofme_pathand the plugin adapter use it instead of Flask'surl_map,view_functionsandurl_rule. Path semantics are defined once, in the module docstring anddocs/utilities.md.Design decisions
create_connexion_app(), rather than a recording resolver aroundregister_openapi(). It covers everyadd_api()call, including FOCA's permissions and/meAPIs and calls by apps, and failed resolutions. It is the only Connexion-2-specific place, plus readingoperation._resolution(private), for the function the issue asks for; build: add support for Connexion 3+ #188 replaces this hook.Map, with Connexion's converters and the sameOPTIONShandling per rule as Flask, so precedence, redirects and conversions stay identical. Werkzeug stays installed on Connexion 3 (refactor(errors): make errors framework-neutral #633); Flask's routes aren't used. A test compares the table's rules with Flask's.Route.functionis the resolver's result, with FOCA's wrappers but without Connexion's;inspect.unwrap()and_ENFORCING_ATTRIBUTEwork as before.Behaviour differences on Connexion 2
Only routes that aren't operations (Swagger UI,
openapi.json, routes added to Flask directly), which the table doesn't hold:is_permitted_for()on such a path is nowFalse, notTrue.me_pathon such a path is no longer refused or warned about.InboundRequest.routeof the plugin adapter is the path for such requests.An app that doesn't use
create_connexion_app()gets the table fromregister_openapi()and the access control registrations; APIs it added earlier aren't in it, and ownership controllers on them refuse requests.The ownership wrappers now also need policies to have allowed this very request (mark on
flask.g), because the table can find an enforced route with the same path as a route outside it. Apps' tests calling ownership controllers directly in a request context would have to go through an enforced route; those of cloud-registry and proTES don't depend on this (see below).Everything else is unchanged. Two existing tests that used plain Flask routes register them in the table now.
Verification
Local, Python 3.12:
coverage run -m pytest -m 'not mongodb', without the integration test files: 4201 passed, 3 skipped;foca/api/routes.pyand the changed modules at 100%. Total 99%, from tests needing MongoDB; CI runs them.ruff check,ruff format --check,mypy,ast-grep scan,mkdocs build --strict: passed.url_mapemptied, for an unenforced ownership route and a service-info route.Heads of the apps, on this branch (Python 3.13, without chart tests, which need Helm dependencies): proTES 1393 passed, 11 skipped; cloud-registry 87 failed, 2020 passed, 11 skipped, with the same failures on
devof FOCA (chart overlay tests and others, not caused by this PR). MongoDB-backed tests of FOCA and the integration tests run only in CI.CI: see the checks of this PR.
Declined review findings
_match_ruleand_install_route_tablepublic: internal across modules, as_register_apiand others in this code base.Open questions
None.
🤖 Generated with Claude Code
Summary by Sourcery
Replace framework route introspection with a specification-backed route table for consistent API route discovery, matching, and access-control checks.
New Features:
Bug Fixes:
Enhancements:
Documentation:
Tests: