Repository navigation
refactor(utils): read the request via accessors - #726
Conversation
The request snapshot gains `query` (read-only `QueryParams`, decoded as by Werkzeug, invalid UTF-8 kept percent-encoded), `operation_id` (as in the specification, else as resolved) and `protocol`. URLs, logging, pagination, validation and response-validation errors read the request via `current_request()`; the base path of the API handling a request comes from FOCA's registry of APIs instead of Flask blueprints. The plugin adapter takes the query from the snapshot. The body-size limit stays the one function reading Flask's request, as middleware rewriting `wsgi.input`. The AST check now covers all of `foca/` except `foca.context`, with that function exempt. Refs #718 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Document the new snapshot fields (`protocol`, `query`, `operation_id`), how the base path of a request's API is found, the `operation_id` log field, the body-size limit as the one place reading raw input, and the replacements and behaviour changes in the 0.22 migration guide. Refs #718 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Read the operation and route of a request without a whole snapshot (`_match_request()`, `_get_operation_id()` in `foca.context`), so log records don't copy headers or parse the query; use `_has_request()` throughout `foca.context`; simplify the operation ID fallback of routes; also forbid `flask.ctx` in the AST check; keep log records via the resolver in the logging test; fix doc wrapping and the paragraph split in the migration guide; clarify the `operation_id` log field. Refs #718 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Test `_match_request()` and `_get_operation_id()` outside requests, for unmatched paths and for operations; say in the log docs that `operation_id` is set for all APIs added via Connexion. Refs #718 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideData structuresRecord the API base path and the specification-facing operation identifier on each route so request lookups can rely on route metadata.
Define the read-only multi-value query mapping and extend the request snapshot with query, protocol, and operation metadata.
APIExpose the current request's route-derived operation identifier and use route metadata to resolve the API base path for request-scoped URL helpers.
Uses of the APIReplace direct framework request reads with FOCA accessors in validation, plugin adaptation, logging, pagination, response-validation logging, and URL construction, while keeping the body-size middleware exception explicit.
DocumentationDocument the new request snapshot fields, query semantics, operation identifiers, API lookup behavior, middleware exception, and migration guidance.
TestsCover route metadata, request snapshot semantics, API selection, logging behavior, and the framework-neutral request-access rule.
Other changesFiles not grouped.
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 #726 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 71 71
Lines 9127 9141 +14
=========================================
+ Hits 9127 9141 +14
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 3 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/utils/urls.py" line_range="488" />
<code_context>
+ owners = [
+ api for api in candidates if found.route.operation_id in api.operation_ids
+ ]
+ return max((api.base_path for api in owners or candidates), key=len, default=None)
+
+
</code_context>
<issue_to_address>
**Resource checks use wrong API path**
When nested API base paths overlap and the matched route belongs to the outer API, while its operation ID is shared by both APIs or is resolver-generated and absent from the registry, `get_api_base_path()` selects the longest matching base path even when the matched operation belongs to an outer API, so callers that build a resource path with `get_resource_path()` check permissions against the wrong namespace and can allow access to a resource the caller is not authorized to access.
Retain the serving API's base path on each route and use that association when resolving the current request's API.
</issue_to_address>
### Comment 2
<location path="foca/context.py" line_range="310" />
<code_context>
root_path=request.script_root,
url=_get_url(),
+ query=QueryParams(
+ parse_qsl(_get_query_string(), keep_blank_values=True, errors=_INVALID_UTF8)
+ ),
headers=Headers(request.headers.items()),
</code_context>
<issue_to_address>
**Large queries amplify request memory**
When the server accepts unusually long query strings containing many parameters and several such requests are handled concurrently, `current_request()` materializes every query pair into strings and per-name lists. `log_traffic()` now calls it for every decorated request just to format the request line, so concurrent requests with very large accepted query strings consume substantially more memory and CPU than before, potentially exhausting worker memory.
Avoid parsing the query when callers only need request-line fields, or enforce a query-size limit before constructing the snapshot.
</issue_to_address>
### Comment 3
<location path="foca/context.py" line_range="355" />
<code_context>
"No request: current_request() works only while a request is handled"
)
- found = match(request.path, request.method)
+ found = _match_request()
return RequestSnapshot(
method=request.method,
</code_context>
<issue_to_address>
**Catch-all routes misidentify UI requests**
When a request to a non-operation Connexion route, such as the served specification or Swagger UI, overlaps a catch-all operation route, `match()` sees only FOCA’s operation table, so a catch-all operation can win its lookup even when Connexion routes the request to a static Swagger or specification endpoint. `_get_operation_id()` then logs the catch-all operation, and `_get_request_base_path()` treats the non-operation request as belonging to that API instead of using the documented fallback.
Make route identification account for Connexion’s non-operation route precedence before reporting an operation or API base path.
Also at `foca/utils/urls.py:476`.
</issue_to_address>Linked issues
#718 refactor(utils): read the request via accessors · 2 of 2 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Switch the listed remaining modules to read request data via FOCA's accessors. | ✅ Met | URLs, logging, pagination, validation, and response-validation logging use helpers from foca.context; the body-size check remains the documented middleware exception. |
| 2 | Keep request reads outside the accessor module only where the design answers exempt them. | ✅ Met | The AST check covers foca/ outside foca/context.py and exempts only _check_body_size, with tests for the exemption. |
Sourcery assessment
Needs a human reviewer. 3 findings to address first, and if route matching assigns a request to the wrong API, resource paths can be built under the wrong base path and access-control checks may apply the wrong policy, potentially allowing access that should be denied. Reverting restores the previous API lookup, but any access or data exposure that occurred before the revert cannot be undone.
Blocking findings: foca/utils/urls.py:488, foca/context.py:310, foca/context.py:355
Routes record the base path of their API (`Route.base_path`), and the API of a request is the registered API with that base path. With nested base paths, the API was inferred from the path template and operation IDs, which picked the inner API when both shared an operation ID or it was resolver-generated (Sourcery review). Refs #718 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
FOCA no longer reads the request from
flask.request,request_ctxorconnexion.requestoutsidefoca.context. The one exception is the body-size limit, as decided in #718. Implements the maintainer's decisions:queryin the snapshot:RequestSnapshot.queryis a read-onlyQueryParamsmapping of the raw query. Names are case-sensitive, a name gives its first value, andgetlist()gives all values. Values are decoded as by Werkzeug:+as space, blank values kept, and bytes that aren't UTF-8 left percent-encoded instead of raising. The representation shows names only, so tokens in queries aren't logged. The plugin adapter's parser moved intofoca.context, and the adapter now readsrequest.query.operation_idin the snapshot, base path from FOCA's registry:RequestSnapshot.operation_idis theoperationIdof the specification, or the resolved one if the spec has none.Route.operation_id(route table, unreleased) has the same meaning, sox-openapi-router-controllerspecs givefindPets, notcontrollers.findPets.get_operation_id(), used for the log fieldoperation_idand for logs of nonconforming responses, reads it from the route table instead ofrequest.endpoint.get_api_base_path()/get_resource_path()find the API of a request from FOCA's registry of APIs (_RegisteredApi) instead of Flask blueprints. Each route records the base path of its API (Route.base_path), and the API of a request is the registered API with that base path. Routes of unregistered APIs, e.g.,GET /me, fall back as before._check_body_size()(rewriteswsgi.input) imports Flask's request locally. Its docstring,docs/configuration/server.mdand the migration guide document it as middleware and the one place that touches raw input, which moves to ASGI middleware later.Other changes:
RequestSnapshot.protocol(e.g.,HTTP/1.1) keeps thelog_trafficrequest line unchanged.get_public_url()(root_path), pagination links (query,path) and the strict-validation check for unexpected query parameters (query)._match_request()/_get_operation_id()read only the route, e.g., for each log record, without copying headers or parsing the query.tests/test_framework_neutral.py) now covers all offoca/exceptfoca/context.py. It exempts only_check_body_size, with a test that the exemption isn't stale, and also forbidsflask.ctx.Behaviour changes, in the migration guide
operation_id: for router-controller specs it is now the bareoperationId; before, it was e.g.controllers_findPets. It is empty for routes that aren't Connexion operations, e.g., Flask routes, the Swagger UI or automaticOPTIONS, and in Connexion apps not created by FOCA.Docs:
docs/utilities.md: the snapshot fields androot_pathinget_public_url().docs/writing-controllers.md: whatqueryis for.docs/configuration/log.md: theoperation_idfield.docs/access-control.md: how the API of a request is found.docs/configuration/server.md: the body-size limit as middleware.docs/migration-0.22.md: new replacement rows (SERVER_PROTOCOL,args,endpoint,blueprint) and the list of behaviour changes.Closes #718
Verification
coverage run -m pytestwith a private MongoDB 7.0 (--nounixsocket, port 12345), at c3e77b3: 4794 passed, 2 skipped, 100% coverage.ruff check,ruff format --check,mypy,ast-grep scan,ast-grep test,semgrep scan --config .semgrep --errorandmkdocs build --strict: pass. pre-commit can't fetch its hook repos through the sandbox proxy, so I ran the tools directly and rely on CI's pre-commit job.--no-deps) over their locked environments (uv sync --locked --extra dev), withhelm dependency build deploymentusing Helm 3.22.1, and run with-W ignore::DeprecationWarningas in their CI:dev(d237a18): mongomock with coverage, at c3e77b3: 1615 passed, 11 skipped, 100% coverage. Against MongoDB 7.0, at cec4547: 1625 passed, 1 skipped.dev(31c7b8f): mongomock with coverage, at c3e77b3: 2338 passed, 11 skipped, 100% coverage. Against MongoDB 7.0, at cec4547: 2349 passed.Route.operation_id,get_operation_id,RequestSnapshotor the moved adapter internals (checked by the reviewer).CI passed). Sourcery: 3 threads; the base-path one fixed in c3e77b3, the other two answered; all resolved.Declined review findings
_has_request()public: private helpers shared across modules are the codebase's convention, e.g.,_get_request_key()and_get_token_info(), and a public API should wait for the ASGI design.RequestSnapshotfields: the class is new in the unreleased 0.22.0.getattr(flask, "request")in the AST check: that's deliberate obfuscation, which the check isn't meant to stop.flask.ctxwas added.Open questions
None.
🤖 Generated with Claude Code