Repository navigation
refactor(security): read requests via accessors - #722
Conversation
Access control, ownership, token validation and the plugin adapter read the request via foca.context.current_request() and the token info via foca.security.auth.current_token_info() instead of flask.request, request_ctx or connexion.request. The framework glue lives in foca.context only: private helpers give the token info and a per-request key for the enforcement mark. The permissions API controllers take the rule as the body argument that Connexion passes instead of reading request.get_json(). The plugin adapter parses query parameters from the snapshot's URL, as Werkzeug does, and no longer fails on query strings that aren't UTF-8. A test checks that the security modules don't import the request objects of Flask or Connexion. Closes #717 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Make body a required argument of postPermission() and putPermission(), so that operations renaming the body fail clearly. Document that the permissions API controllers take the body as body, including for custom api_specs, and that plugin path parameters come from the operations of the app's specifications. Test the token info helper of foca.context directly. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideThe PR makes FOCA security and plugin code framework-neutral by routing request data through context accessors and snapshot-based adaptation, while updating permission controllers to accept Connexion’s explicit body argument and documenting the resulting custom-spec migration requirement. Sequence diagram for snapshot-based security enforcementsequenceDiagram
participant Client
participant Framework as Flask_or_Connexion
participant Context as foca.context
participant Enforcement as enforcement.py
participant Handler as Protected_handler
Client->>Framework: HTTP request
Framework->>Context: current_request()
Context-->>Enforcement: RequestSnapshot
Enforcement->>Enforcement: is_permitted()
Enforcement->>Context: current_request()
Context-->>Enforcement: path and method
Enforcement->>Handler: enforce_access_control()
Handler-->>Client: Response
Sequence diagram for explicit permission request bodiessequenceDiagram
participant Client
participant Connexion
participant Controller as postPermission_or_putPermission
participant RuleParser as _get_rule
participant Store as Casbin_adapter
Client->>Connexion: POST_or_PUT_permission(body)
Connexion->>Controller: body
Controller->>RuleParser: _get_rule(body)
RuleParser-->>Controller: policy_type_and_values
Controller->>Store: save_policy_line()
Store-->>Controller: permission_id
Controller-->>Client: Permission response
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 #722 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 71 71
Lines 9099 9127 +28
=========================================
+ Hits 9099 9127 +28
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/plugins/adapter.py" line_range="136" />
<code_context>
+ {
+ name.title(): ", ".join(request.headers.getlist(name))
+ for name in request.headers
+ if name not in CREDENTIAL_HEADERS
+ }
+ )
</code_context>
<issue_to_address>
**Credentials reach plugins and backends**
When an incoming request carries a standard credential header, `request.headers` yields title-cased names, but `CREDENTIAL_HEADERS` contains lowercase names, so the case-sensitive filter retains credentials in `InboundRequest.headers` and exposes them to plugins and downstream backends.
Compare header names to `CREDENTIAL_HEADERS` case-insensitively while preserving the names used in `InboundRequest.headers`.
</issue_to_address>
### Comment 2
<location path="foca/plugins/adapter.py" line_range="143" />
<code_context>
return InboundRequest(
- method=request.method.upper(),
+ method=request.method,
path=request.path,
route=route if route is not None else rule,
- path_params={
</code_context>
<issue_to_address>
**Plugins receive lowercase methods**
When the WSGI request method is lowercase, `inbound_from_request()` copies `request.method` unchanged, so `InboundRequest.method` violates its uppercase contract and plugins that dispatch on it can mishandle the request.
Uppercase `request.method` when assigning `InboundRequest.method`.
</issue_to_address>
### Comment 3
<location path="tests/security/test_framework_neutral.py" line_range="48-58" />
<code_context>
+ for alias in node.names
+ if names is None or alias.name in names
+ )
+ elif isinstance(node, ast.Import):
+ found.extend(
+ f"import {alias.name}"
+ for alias in node.names
+ if alias.name in _FORBIDDEN and _FORBIDDEN[alias.name] is None
+ )
+ elif (
+ isinstance(node, ast.Attribute)
+ and isinstance(node.value, ast.Name)
+ and node.value.id in _FORBIDDEN
+ and node.attr in (_FORBIDDEN[node.value.id] or ())
+ ):
+ found.append(f"{node.value.id}.{node.attr}")
</code_context>
<issue_to_address>
**Forbidden framework reads go undetected**
When a checked security module imports Flask or Connexion under an alias and accesses its request through that alias, `_forbidden_uses()` recognizes attribute access only when the base name is a key in `_FORBIDDEN`, so it reports no finding and `test_no_framework_request` passes despite the forbidden framework request read.
Resolve framework import aliases in `_forbidden_uses()` when checking attribute access.
</issue_to_address>
### Comment 4
<location path="foca/plugins/adapter.py" line_range="167" />
<code_context>
+ """
+ query: dict[str, list[str]] = {}
+ for key, value in parse_qsl(
+ urlsplit(url).query, keep_blank_values=True, errors=_INVALID_UTF8
+ ):
+ query.setdefault(key, []).append(value)
</code_context>
<issue_to_address>
**Malformed hosts break gateway requests**
When a WSGI request has a malformed bracketed Host value, such as an unmatched `[`, `urlsplit(url)` rejects a malformed bracketed host with `ValueError` before extracting the query, so `inbound_from_request` fails instead of processing the request.
Extract and parse the query independently of the URL authority, or handle invalid authorities without failing query parsing.
</issue_to_address>Linked issues
#717 refactor(security): read the request via accessors · 2 of 2 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | These modules read no request data from flask.request, request_ctx or connexion.request. | ✅ Met | The enforcement, ownership, auth and plugin adapter code uses FOCA accessors; the AST regression test checks for direct framework request imports and accesses. |
| 2 | Policies and owners match exactly as before: the existing access-control and ownership tests pass unchanged. | ✅ Met | Policy checks use the snapshot path and method, while ownership uses its path parameters; the permission-controller test-call updates reflect the new required body argument, not changed policy or ownership assertions. |
Sourcery assessment
Needs a human reviewer. 4 findings to address first, and if the new request accessors or body binding supply the wrong values, a permission rule could be stored that grants unintended access; reverting would not undo the stored rule or any access already exposed.
Blocking findings: foca/plugins/adapter.py:136, foca/plugins/adapter.py:143, tests/security/test_framework_neutral.py:58, foca/plugins/adapter.py:167
Upper-case the method of inbound requests again, take the query from what follows the first ? of the URL rather than parsing its host, and resolve module aliases in the framework-neutrality test, from review. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Let postPermission() and putPermission() take the request body as the keyword argument body or, for specifications that still set x-body-name: permission as FOCA's did before 0.22.0, as permission, with a DeprecationWarning. Calls with neither or both raise a TypeError. Test both variants end to end through Connexion, and document that old specifications keep working. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
FOCA's security code no longer reads the request from
flask.request,request_ctxorconnexion.request. It uses the accessors from #715 / PR 720 instead:enforcement.py): the request path and method for policies, theon_behalf_of_headerand the opt-in roles header now come fromcurrent_request().ownership_server.py): path and method for matching the route, andpath_paramsinstead ofview_args, also come fromcurrent_request().auth.py: the bearer token is read fromcurrent_request().headers. The token info comes fromfoca.context.plugins/adapter.py):url, the same way Werkzeug parsesrequest.args. A parametrised test and a 30,000-case fuzz comparison in review show the results are identical. The one difference: query strings that aren't UTF-8 no longer raise. Bytes that aren't valid UTF-8 stay percent-encoded.Content-Typeheader viawerkzeug.http.parse_options_header.foca.contextonly: two private helpers hold the remaining Flask/Connexion reads._get_token_info()is moved there fromauth.py._get_request_key()gives a per-request identity for the enforcement mark onflask.g. It is the same object as before, so the ownership controllers' enforcement check keeps its meaning.postPermission()andputPermission()take the rule as the keyword-only argumentbodyinstead of callingrequest.get_json(), and FOCA's spec no longer setsx-body-name: permission.access_control.api_specscopied from FOCA's spec before 0.22.0, which still setx-body-name: permission, get the body as keyword-onlypermission, with aDeprecationWarning.TypeErrorwith a clear message.tests/security/test_framework_neutral.py: an AST check that the modules underfoca/securityandfoca/plugins/adapter.pydon't import or access the request objects of Flask or Connexion.The snapshot is not extended. The adapter gets the query from
url.Public changes and docs
docs/migration-0.22.mdanddocs/access-control.mdnow say that the permissions API controllers takebody, sox-body-nameis optional.x-body-name: permissionkeep working, but that name is deprecated. The warning only shows where deprecation warnings are enabled, which the migration guide says.body.docs/utilities.md(Reading the current request) needs no update.Existing tests
Assertions are unchanged. Changed call signatures and fixtures only:
tests/security/access_control/test_access_control_server.pyandtests/test_audit.pypass the payload asbody=instead of throughtest_request_context(json=...).gmark setup are untouched.New tests:
test_enforcement.py::TestSelfService::test_writes_get_bodycovers POST/PUT end to end through Connexion. It also passes ondev.test_context.pytests the request key and the token info helper directly.Closes #717
Verification
Run locally in the agent clone; MongoDB 7.0.34 on port 12345 for the tests.
coverage run -m pytest && coverage report -m: 4695 passed, 3 skipped, 100% coverage (at 7b5120a; 03e1183 changes only docs).test_enforcement.py::TestSelfService::test_writes_get_bodycovers FOCA's current spec and a copy of the old spec withx-body-name: permission, POST and PUT. It also checks that only the old spec gets the deprecation warning.test_access_control_server.py::TestBodyNamescoverspermissionwith a warning, and neither or both with aTypeError.ruff format --check,ruff check foca tests,mypy: clean.ast-grep scanandsemgrep --config=.semgrepon the changed files: no findings.mkdocs build --strict: OK.devand proTESdev, with this branch installed editable and Helm 3.22.1 on PATH (chart dependencies built and checksums OK), using mongomock.x-body-name: permissionbelongs to its own controllers.CI passed, codecov patch/project and Read the Docs).?, independent of the host; the AST test resolves module aliases.Declined review findings
_get_request_key,_get_token_info; quality, medium). The repo already does this, e.g._ENFORCED_MARKandauth._get_claims. Making them public would add API surface the ASGI port would have to keep.RequestSnapshot(quality, medium). Out of scope: the brief for refactor(security): read the request via accessors #717 rules out extending the snapshot. The parsing lives in the adapter, which FOCA 1.0 replaces.EnvironHeadersgives the same spelling under WSGI.path_params. This is documented in theinbound_from_requestdocstring rather than kept on Flask'sview_args.x-body-namein custom specs (adversarial, low). Superseded: the controllers now accept the old namepermission, with a deprecation warning.foca/utils/logging.py). FOCA's other deprecations behave the same, so I kept the warning and documented when it shows. A once-per-process log line would also make it visible.flask.requestreads throughfoca.utils(get_page_links,log_traffic_if; adversarial, low). These are the utilities left to refactor(utils): read the request via accessors #718, which awaits design decisions.Open questions
None.
🤖 Generated with Claude Code