Repository navigation
feat: add request and claims accessors - #720
Conversation
Add foca.context.current_request(), a read-only snapshot of the request being handled (method, path below the root path, root path, URL, case-insensitive headers, content length, client address, and the route template and path parameters from the route table), and foca.security.auth.current_token_info() and current_claims(), which return copies and are empty without a validated token. get_current_claims() returns current_claims(). The accessors read from Flask and Connexion 2 for now; only their bodies change on ASGI. Closes #715 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Represent headers by their names only and leave the URL out of the representation of request snapshots, so that logging one doesn't log tokens or cookies. Percent-encode non-ASCII characters of the URL, as documented. Return no values from Headers.getlist() for names that aren't strings. Fix the route example of the migration guide, and explain the import cycle and the uncopied claim helpers. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Percent-encode only the path and query of the snapshot's URL: IDNA encoding of the whole URL failed on hosts that Werkzeug accepts, e.g., with empty or overlong labels, which made current_request() raise in before-request hooks and error handlers. Describe the URL as the server reconstructs it. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideIntroduces framework-neutral request snapshots and token/claims accessors, backed by immutable copied data and shared enforcement logic, with comprehensive tests and documentation to support migration away from Flask and Connexion-specific context APIs. Sequence diagram for framework-neutral request and claims accesssequenceDiagram
participant Controller
participant RequestAccessor as foca.context.current_request
participant Flask as Flask request context
participant Routes as foca.api.routes.match
participant ClaimsAccessor as foca.security.auth.current_claims
participant Connexion as Connexion token context
Controller->>RequestAccessor: current_request()
RequestAccessor->>Flask: has_request_context()
RequestAccessor->>Routes: match(request.path, request.method)
Routes-->>RequestAccessor: route and path parameters
RequestAccessor-->>Controller: frozen RequestSnapshot
Controller->>ClaimsAccessor: current_claims()
ClaimsAccessor->>Connexion: _get_token_info()
Connexion-->>ClaimsAccessor: validated token info
ClaimsAccessor-->>Controller: copied claims
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 #720 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 71 71
Lines 9010 9066 +56
=========================================
+ Hits 9010 9066 +56
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 4 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="foca/context.py" line_range="150" />
<code_context>
+ """
+
+ method: str
+ path: str
+ root_path: str
+ url: str = field(repr=False)
</code_context>
<issue_to_address>
**Credentials appear in snapshot logs**
When an application logs a snapshot whose request path contains a token or other credential, `RequestSnapshot`'s generated representation includes both `path` and `path_params`, so logging the snapshot writes the credential to logs even though URL and header values are omitted.
Exclude or redact sensitive path data, including `path_params`, from the generated representation.
Also at `foca/context.py:157`.
</issue_to_address>
### Comment 2
<location path="foca/context.py" line_range="172" />
<code_context>
+ host and not all hosts can be IDNA-encoded.
+ """
+ prefix = host_url.rstrip("/")
+ return prefix + quote(url[len(prefix) :], safe=_URL_SAFE)
+
+
</code_context>
<issue_to_address>
**Invalid percent escapes reach callers**
When the reconstructed request path or query contains a literal `%` not followed by two hexadecimal digits, `_encode_url()` passes every `%` through via `_URL_SAFE`, so `current_request().url` retains the malformed escape and URL parsers or consumers reject or misinterpret it.
Preserve only valid percent-escape sequences and percent-encode other `%` characters when building the URL.
</issue_to_address>
### Comment 3
<location path="foca/context.py" line_range="197" />
<code_context>
+ )
+ found = match(request.path, request.method)
+ return RequestSnapshot(
+ method=request.method,
+ path=request.path,
+ root_path=request.script_root,
</code_context>
<issue_to_address>
**Method is not always uppercase**
When a server supplies a lowercase method in the request environment, `current_request()` copies the raw WSGI method while `RequestSnapshot` promises an upper-case method, so callers comparing the snapshot method to standard uppercase names receive a value that violates the accessor contract.
Normalize the captured method to uppercase, or change the documented contract if preserving the raw method is intentional.
</issue_to_address>
### Comment 4
<location path="foca/context.py" line_range="175" />
<code_context>
+ return prefix + quote(url[len(prefix) :], safe=_URL_SAFE)
+
+
+def current_request() -> RequestSnapshot:
+ """Get a snapshot of the request being handled.
+
</code_context>
<issue_to_address>
**Request accessors omitted from reference**
The API reference’s `foca.context` section does not list `current_request`, `RequestSnapshot`, or `Headers`, so users following the stated API-reference documentation cannot find these public additions there.
Add the request accessor and snapshot types to the `foca.context` members listed in the API reference.
</issue_to_address>Linked issues
#715 feat: add request and claims accessors · 4 of 4 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | current_request() returns the specified read-only request snapshot and raises outside a request. |
✅ Met | Implemented as a frozen RequestSnapshot; current_request() raises RuntimeError without an active request. |
| 2 | current_token_info() and current_claims() return copies, are empty without a validated token, and get_current_claims() uses them. |
✅ Met | Both accessors return deep copies; get_current_claims() delegates to current_claims(). |
| 3 | The 0.22.0 implementation reads from Flask and Connexion 2. | ✅ Met | current_request() reads Flask's request, and token accessors read Connexion's request context. |
| 4 | The three accessors are public, typed, documented in the API reference, and tested with a root path, base path, and headers. | ✅ Met | The accessors have public names and return annotations, are included in the API reference modules, and tests cover a root path, base path, and headers. |
Sourcery assessment
Approval pending. 3 findings to address first.
Blocking findings: foca/context.py:150, foca/context.py:172, foca/context.py:197
Build the URL of request snapshots from the decoded path, encoded anew, and the raw query string, in which percent signs that don't start escapes are encoded: Werkzeug's URL keeps decoded percent signs of the path. Leave the path and path parameters out of the representation of snapshots, as they may hold credentials. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Adds the request and claims accessors of #634 (names as decided there), so that apps and FOCA read the request in one way that means the same on Connexion 2 and on ASGI:
foca.context.current_request()returns a read-only, frozenRequestSnapshot:method,path(below the root path, as Flask'srequest.path, i.e., what policies and owners are keyed by),root_path,url(percent-encoded),headers(a case-insensitive, read-onlyHeadersmapping withgetlist()),content_length,client_address, androute(the path template from the route table'smatch(), refactor: check routes from specs, not url_map #632) withpath_params. It raises aRuntimeErroroutside requests. The representation of a snapshot leaves out the path, URL, path parameters and header values, so logging one doesn't log tokens or cookies; the URL is built from the decoded path, encoded anew, and the raw query string.foca.security.auth.current_token_info()andcurrent_claims()return copies of Connexion's token info of the request and its claims; they are empty if no token was validated, also outside requests.get_current_claims()returnscurrent_claims(), and enforcement's internal claim reads go through the same code.Switching FOCA's internals to the accessors is #717/#718, and the "Writing controllers" page is #719.
Docs: API reference (
foca.contextmembers,current_token_info,current_claims), "Reading the current request" indocs/utilities.md,current_claims()in "Using token claims" (docs/authentication.md), and a section with a replacement table indocs/migration-0.22.md.Closes #715
Verification
coverage run -m pytestwith MongoDB 7.0: 4631 passed, 2 skipped, 100% coverageruff check,ruff format --check,mypy,ast-grep scan,semgrep scan --config .semgrep --error,mkdocs build --strict: pass/root), a base path (/api/v1), path parameters, headers,HEAD/no route, snapshot immutability, non-ASCII URLs, representations without credentials, and the claims accessors with and without token info.helm dependency build deploymentwith Helm 3.22.1, as CI):dev(4e707a9): all pass. Mongomock with coverage: 2065 passed, 11 skipped, 100% coverage; against MongoDB 7.0: 2076 passed. The 272 Helm-dependent tests of both runs failed only because my runner lacked Helm on its path;tests/test_chart.pyandtests/test_config.pyrerun with Helm 3.22.1: 297 passed.dev(e47cac2): all pass. Mongomock with coverage: 1428 passed, 11 skipped, 100% coverage; against MongoDB 7.0: 1438 passed. The 185 Helm-dependent tests, as above;tests/test_chart.pyandtests/test_config_examples.pyrerun with Helm 3.22.1: 220 passed.Declined review findings
__init__docstring ofHeaders: the codebase's convention (cf.RequestIdMiddleware).foca.security.authinenforcement.py: the cycle is real (models.config->access_control->enforcement->auth->models.config), now named in a comment; the wrappers keep the names that callers and tests patch, which refactor(security): read the request via accessors #717 switches.getlist()is covered withHeadersdirectly.Headers: would tie the snapshot to Werkzeug, which it is meant to hide.Open questions
None.
🤖 Generated with Claude Code