Repository navigation
feat(utils): add a guarded HTTP client - #500
Conversation
Add `foca.plugins`, a framework-neutral engine for gateway plugins: - plain request model (`InboundRequest`, `Backend`, `OutboundRequest`, `BackendResponse`, `Principal`, case-insensitive `Headers`) and an explicit `Context` per hook call; no Flask, Werkzeug or Connexion types, so plugins run unchanged after the move to Connexion 3 - `Plugin` base with `on_request`, `on_route`, `on_forward` and `on_response` hooks, `NotApplicable`, `Rejected` and `PluginError` - allowlisted loading of entry points (group `foca.plugins`) with distribution and version pins, `RECORD` digests, `enabled: false` kill switch and a startup error with a migration hint for legacy `middlewares` keys - steps with ordered alternatives, copy-and-commit per alternative, failure semantics, timeouts via a bounded thread pool, forwarding attempts with "not accepted" / "outcome unknown" outcomes, a total `forward_timeout`, `Via` headers, loop detection (508) and no routing to the gateway's own public URL - `foca.plugins.adapter`, the only module using Connexion 2 / Flask - config section `plugins`, docs pages, and an ast-grep rule that keeps framework imports out of `foca/plugins` except the adapter Co-Authored-By: Claude Opus 5.5 <[email protected]>
What proTES needs to adopt the engine: - `Foca(gateway=GatewayApp(api, validate, sanitize, validate_outbound))` declares a gateway app; `create_app()` loads its plugins once to fail fast, and `foca.plugins.runtime.get_host()` gives controllers and Celery tasks the host of their process, created on first use after forks (no Flask app context needed) - legacy `middlewares` keys are refused before the app's strict `custom` model is validated - errors of the app's `sanitize` (e.g. 413) stop the request unchanged; `validate` failures stay invalid output - `validate_outbound` per attempt (reason `invalid_outbound`) - `NotAccepted`/`OutcomeUnknown` exceptions with reason codes for the app's client, and `Attempt.report()` - adapter: `request_id()` from a safe `X-Request-ID` or a new one; `Principal.groups` are the mapped roles of access control - string short form of steps (`- <plugin id>`) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Let clients choose the pipeline and the backends of a request in two
reserved tags, under the configurable prefix `plugins.tags.prefix`
(default `gateway.`):
- `gateway.pipeline`: a preset name (`plugins.presets`) or a pipeline
as JSON, validated and authorized before any plugin runs (limits,
roles, `client_selectable`, uniform "plugin not available" errors)
and framed by `client_pipelines.prepend`/`append` (`if_missing_phase`
for a default route step)
- `gateway.backends`: `{"type": "order" | "allow" | "forbid",
"backends": [...]}`, applied to the routed candidates; items that are
no candidates are discarded and recorded
- any other client tag under the prefix is refused with 400
Presets and frames are resolved on startup; presets that need a
disabled plugin are unavailable. Gateway errors move to
`foca.plugins.errors`. `foca.utils.urls` imports Flask only in
`get_public_url()`.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
`run.provenance()` describes a pipeline run as plain JSON data for the app to store with its resource: - prospective: pipeline source, preset, the client's tag by reference, the resolved pipeline and its `sha256:` hash of the RFC 8785 canonical JSON (own implementation, tested with the RFC's vectors) - retrospective: hook calls with build keys, outcomes, timings, sanitized errors, annotations and changes as hashes and JSON Pointers without values (`plugins.provenance.detail: paths`); route candidates, the client's backend selection, attempts and the final reason - engine: FOCA, plugin API and app versions (`GatewayApp(name, version)`) `ProvenanceStore` takes collections of the app: plugin builds (with an optional image digest from `FOCA_IMAGE_DIGEST`) and default or preset pipelines are stored once by hash; client pipelines stay inline. Failed runs are stored only with `plugins.provenance.record_failed` (default off), with documented TTL index specs. Hook records keep changes instead of the data before and after. The engine's usage example now catches `OutcomeUnknown` before its base class. Co-Authored-By: Claude Opus 5.5 <[email protected]>
`foca.utils.http` sends requests to URLs from users and registries without becoming an SSRF vector, on requests/urllib3 only: - `GuardedClient` checks the peer address of each new connection after connecting and before sending (so DNS rebinding cannot reach internal hosts), never follows redirects, ignores proxies and `.netrc` of the environment, allows `https` only and always verifies TLS, bounds requests by a deadline (connect timeout capped at 10 s) and response bodies by size, and returns a plain `HttpResponse` - errors carry reason codes and tell requests that certainly did not reach the server (`RequestNotSent`) from those that may have (`RequestMaybeSent`), for gateway outcomes - `is_public_address()`, `check_public_host()` and `fetch_json()`, moved from proTES Plugins get a client bound to their deadline as `ctx.http`, configured by `plugins.defaults.http`. The framework-import rule covers the client. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes: - outbound `Via` headers are the inbound request's with this gateway's entry appended (RFC 9110, section 7.6.3), whatever plugins or the app's builder set, so that loops through several gateways are detected (A -> B -> A) - each call gets its own deep copy of the step's parameters, and the caller's claims as a read-only deep copy, so that a hook cannot change them for later calls, requests or provenance - hooks raising `SystemExit` and other `BaseException`s fail like others; `KeyboardInterrupt` and `GeneratorExit` propagate Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
`foca.security.access_control.get_current_claims()` returns a copy of the claims of the current request's token, next to `get_current_subject()` and `get_current_groups()`; the plugin adapter uses it instead of a private helper. Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Apps that configure `plugins` without `Foca(gateway=...)` get a startup warning, as the section is validated but not used. The docs say that there is no runtime API for operators, summarize the steps for gateway app authors, and note that plugins are instantiated once more per process after the startup check. Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
`foca.plugins.engine` keeps the host, runs and attempts; the rest moves along its seams, with the public imports from `foca.plugins` and `foca.plugins.engine` unchanged: - `errors`: gateway errors with problem details - `outcomes`: `NotAccepted`, `OutcomeUnknown`, `sanitize_error()` and the engine's internal errors - `records`: resolved pipelines, hook call and attempt records - `executor`: the bounded thread pool of hook calls - `checks`: outbound requests, `Via` names and hook output checks Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes of #486; the engine split is redone on this branch's engine module. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes of #486; the engine split is redone on this branch's engine module. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review fixes and engine split of #486. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address the second review round of the plugin engine: - Claims of the caller are a FrozenMapping, which plugins can keep in their state: unlike MappingProxyType, it can be deep-copied and pickled. The engine copies state and candidates inside the guarded block, so a failing copy fails that alternative only, not the request. - The engine sets Via before the app's outbound check; inbound Via headers longer than 1024 characters are refused (400, InvalidVia). Docs say that the inbound Via is passed through verbatim. - The default gateway_id is the host and port of the public URL, without user information, and only if it matches the gateway_id pattern. - setup() of plugins may run more than once per process (docstring and author docs); tests import internals from their new modules. Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # foca/plugins/__init__.py # foca/plugins/engine.py
# Conflicts: # foca/plugins/engine.py
# Conflicts: # foca/plugins/engine.py # tests/plugins/test_plugin_engine.py
CodeQL flagged reflected XSS in a view that only exists for its URL rule. Return a constant instead. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Principal.token is set only if a token was validated (claims). - Repeated header fields of inbound requests are combined (e.g., Via). - Problem responses keep the custom title of a plugin's rejection; problem_response() takes a request-specific title. - Annotations reject NaN and infinite numbers. - Plugins loaded before a load or pipeline error are closed. - Gateway names bracket IPv6 addresses (pattern GATEWAY_ID_PATTERN), and the outbound Via header, with this gateway's entry, stays within 1024 characters. - One gateway app per process: configure() refuses other settings while a host is in use; reset() closes it; the host is closed at exit. - Docs: app callbacks run outside plugin deadlines and must be fast; rejections in the response phase count as errors. Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # foca/plugins/config.py # foca/plugins/engine.py
# Conflicts: # foca/plugins/config.py
Guard against names in foca.plugins.__all__ that do not resolve (e.g., a missing import), as noticed by proTES. Refs #486 Co-Authored-By: Claude Opus 5.5 <[email protected]>
After an attempt whose outcome is unknown, attempts() ends without raising; final_reason is now outcome_unknown, so that provenance and apps can tell this from a success. Docs and the module example check it after the loop. Refs #488 Co-Authored-By: Claude Opus 5.5 <[email protected]>
A merge dropped InvalidVia from the imports of foca.plugins, though it is still in __all__; the test of the exported names catches this now. Refs #487 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address the second review round of client pipelines: - Tag values with unpaired surrogates are refused with 400 instead of failing with a UnicodeEncodeError; client pipelines must be valid Unicode (strings and keys) and are nested 32 levels deep at most. - Identifiers of client pipelines and presets clash only with the frame steps that are kept: appended defaults (if_missing_phase) that are left out no longer block the same identifiers; presets are checked against them at startup. Errors say to set an explicit id, and the client's error no longer names the gateway's steps. - A _has_role() helper replaces three role checks; InvalidSelection sits next to InvalidVia; STEP_ID_PATTERN has its docstring back. - Docs no longer say that discarded backends are recorded (#488 adds that). Refs #487 Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Backend selections match items with :// against candidate URLs and other items against identifiers only, so that an identifier that equals another candidate's URL cannot select the wrong backend. - Choice tags that are present count whatever their value: null and other non-strings get 400, also when the choice is disabled. - Objects of client pipelines must not have duplicate keys (I-JSON). - Clashes of preset steps with the frame are checked by the engine only, against the frame steps that are kept (no steps dropped for lack of enabled plugins, no left-out appended defaults). Refs #487 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Address the second review round of provenance: - Response hooks must keep the client's Headers (as forward hooks do), and describing changes never raises (error: internal), so that a hook cannot fail a request that a backend accepted. - Changed paths are collected up to the cap only, pointers longer than 512 characters are recorded as their parent, and the paths of a run take at most 64 KiB (then truncated: true), so that records stay far below the BSON limit. - Annotations must be I-JSON (exact integers, valid Unicode). - save() also catches errors while building the record, with a minimal fallback record. - Client address headers (Forwarded, X-Forwarded-For, X-Real-IP) are left out of hashes; docs say to put low-entropy headers in secret_headers and to declare secret params as SecretStr, which is redacted (tested). - Tests: TTL index on mongomock from FAILURE_INDEXES, app_info of create_host(). Refs #488 Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # foca/plugins/context.py
Address the Sourcery review of PR #499: - Records keep only the type of errors of plugins and other code, as their messages may hold secrets; logs get the message (describe_error). FOCA's gateway errors, rejections and its own timeout and invalid-output texts keep their message. - Set-Cookie of responses is left out of hashes; hashes of changes are keyed (HMAC-SHA256, random key per process), content hashes of pipelines and builds stay plain RFC 8785 SHA-256. - Backend URLs in records lose user info, query and fragment. - A budget that runs out during the last attempt gives forward_timeout, not no_backend. - Pipelines that are no I-JSON are recorded without resolved. - Records are cut to 1 MiB of JSON (changed paths, then annotations, then the resolved pipeline; truncated: true). - If storing builds fails, the record keeps their documents inline. - save_failure() is idempotent: _id is the request ID, else the run's random run_id, written with replace_one(upsert=True). - The pointer length cap applies to array items too. - Docs: map keys in changed paths, MongoDB client timeouts. Refs #488 Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # tests/plugins/test_plugin_engine.py
Compare the URL fields of the record exactly instead of testing for URL substrings in its JSON text (CodeQL: incomplete URL substring sanitization). Refs #488 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Dev has the squash of #499 (provenance), whose tree equals feat/plugin-provenance, already merged here; conflicts in foca/plugins/context.py and tests/plugins/test_plugin_engine.py are resolved to this branch's tree.
One GuardedClient shared its end, timer and sockets across requests, so concurrent requests (e.g., of a plugin that fans out) overwrote each other's deadlines: one request finishing cancelled another's timer, and its own timer then shut the other's sockets down. Each request now gets its own guard, found by its connections per thread (urllib3 connects, sends and reads in the request's thread); pooled connections that a request reuses are tracked in its guard, and the guard finishes before the connection goes back to the pool, so a late timer cannot stop a socket that another request uses. No lock serializes requests. Tests: two concurrent requests with overlapping deadlines, a deadline on a reused connection. Refs #490 Co-Authored-By: Claude Opus 5.5 <[email protected]>
A json body that is no JSON (NaN, a set, other objects) gave an InvalidJSONError classified as connection_lost, or a raw TypeError, although nothing was sent; a header with a line break gave invalid_url. Both now raise InvalidRequest (a RequestNotSent, reason invalid_request or invalid_header) before sending, so all errors stay HttpErrors. The dead InvalidHeader branch of _classify is gone. Refs #490 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Connections checked all resolved addresses but connected only to the first, losing urllib3's fallback across A/AAAA records. They now try the checked addresses in order within one connect budget; the peer of the one that connects is checked as before. Refs #490 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideAdds a framework-neutral, SSRF-resistant HTTP client with strict address and transport guards, whole-request deadlines, bounded responses, and classified errors, then exposes it to plugins through deadline-bound ctx.http clients with configuration and documentation. Sequence diagram for a guarded outbound HTTP requestsequenceDiagram
participant Plugin
participant GuardedClient
participant Resolver
participant Socket
participant Server
Plugin->>GuardedClient: request(method, url)
GuardedClient->>Resolver: _resolve(host, port, timeout)
Resolver-->>GuardedClient: addresses
GuardedClient->>GuardedClient: is_public_address(address)
GuardedClient->>Socket: _connect_any(checked addresses, deadline)
Socket-->>GuardedClient: connected socket
GuardedClient->>GuardedClient: check peer address
GuardedClient->>Server: send HTTP request
Server-->>GuardedClient: response body
GuardedClient->>GuardedClient: enforce max_response_size and deadline
GuardedClient-->>Plugin: HttpResponse
Sequence diagram for plugin deadline-bound HTTP client lifecyclesequenceDiagram
participant Engine
participant Context
participant GuardedClient
participant Plugin
Engine->>GuardedClient: GuardedClient(deadline, timeout, http config)
Engine->>Context: create Context(http)
Context-->>Plugin: ctx.http
Plugin->>GuardedClient: get(url) or post(url)
GuardedClient-->>Plugin: HttpResponse or HttpError
Engine->>GuardedClient: close()
Engine-->>Engine: finish hook execution
File-Level Changes
Assessment against linked issues
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 #500 +/- ##
==========================================
Coverage 100.00% 100.00%
==========================================
Files 45 46 +1
Lines 5044 5430 +386
==========================================
+ Hits 5044 5430 +386
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:
|
Python 3.14 parses unbalanced deep arrays without RecursionError, so the ValueError branch of HttpResponse.json was not covered in CI. The test now also forces the RecursionError. Refs #490 Co-Authored-By: Claude Opus 5.5 <[email protected]>
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/utils/http.py" line_range="182" />
<code_context>
+ public = False
+ if not public:
+ raise AddressNotAllowed(
+ f"Host of {url} has an address that is not public: {address}"
+ )
+
</code_context>
<issue_to_address>
**Failed requests expose URL secrets**
When a request fails for a URL containing userinfo, secrets in its query or fragment, or raw control characters, `_check_address()`, `_classify()`, `_expired()`, and `fetch_json()` interpolate URLs into `HttpError` messages, and `describe_error()` leaves query strings, fragments, and control characters intact. Callers that log or surface these errors expose URL secrets and can have logs forged with extra lines.
Use a shared URL sanitizer for all error messages that removes userinfo and sensitive query or fragment data and escapes control characters.
Also at `foca/utils/http.py:225`, `foca/utils/http.py:666`, `foca/utils/http.py:670-675`, `foca/utils/http.py:899`, `foca/utils/http.py:981`, `foca/utils/http.py:985`, `foca/utils/http.py:987`.
</issue_to_address>
### Comment 2
<location path="foca/utils/http.py" line_range="66-67" />
<code_context>
+# bits: IPv4/IPv6 translation (RFC 6052) and IPv4-compatible addresses
+# (deprecated, RFC 4291)
+_EMBEDDING_PREFIXES = (
+ ipaddress.IPv6Network("64:ff9b::/96"),
+ ipaddress.IPv6Network("::/96"),
+)
+
</code_context>
<issue_to_address>
**Private NAT64 destinations pass validation**
When the client uses a reachable network-specific NAT64 prefix and a URL resolves to an address embedding a non-public IPv4 destination, `is_public_address()` extracts embedded IPv4 addresses only for the listed prefixes, so an address under a custom RFC 6052 prefix passes the global-address check and `GuardedClient` can reach the private destination through the translator.
Recognize RFC 6052 embedded IPv4 addresses under network-specific NAT64 prefixes and reject addresses embedding non-public destinations.
</issue_to_address>
### Comment 3
<location path="foca/utils/http.py" line_range="920-922" />
<code_context>
+ """
+ content = bytearray()
+ try:
+ for chunk in response.iter_content(chunk_size=_CHUNK_SIZE):
+ content.extend(chunk)
+ if len(content) > self.max_response_size:
+ raise ResponseTooLarge(
+ f"{url}: response larger than {self.max_response_size} bytes"
</code_context>
<issue_to_address>
**Decompressed chunks bypass size limit**
When an endpoint returns a highly compressible response whose decompressed chunk is much larger than the configured limit, `response.iter_content()` decompresses a chunk before `_read()` checks its accumulated length, so a small response on the wire can allocate a very large chunk and exhaust process memory despite `max_response_size`.
Enforce the response-size limit while decompressing, before an expanded chunk can be fully allocated.
</issue_to_address>
### Comment 4
<location path="foca/utils/http.py" line_range="360-366" />
<code_context>
+ Args:
+ sock: Socket.
+ """
+ with self._lock:
+ self._sockets.append(sock)
+ stop = self.expired
+ if stop:
+ _shutdown(sock)
+
+ def start(self, seconds: float) -> None:
</code_context>
<issue_to_address>
**Expired timer interrupts reused connection**
When a response completes near its deadline and its connection is returned to the pool before the timer callback shuts down its copied socket, `_stop()` copies sockets under the guard lock and shuts them down after releasing it, while `_read()` can consume a response and return its connection to the pool before `guard.finish()` completes. The old timer then shuts down a socket reused by another request, interrupting that request.
Coordinate `finish()` and timer shutdown so a socket cannot be shut down after its connection has been returned to the pool.
Also at `foca/utils/http.py:349-353`, `foca/utils/http.py:881`, `foca/utils/http.py:920`.
</issue_to_address>
### Comment 5
<location path="foca/utils/http.py" line_range="515" />
<code_context>
+ except BaseException:
+ sock.close()
+ raise
+ guard.track(sock)
+ return sock
+
</code_context>
<issue_to_address>
**HTTPS requests outlive deadlines**
When an HTTPS server trickles response data past the request deadline, when an HTTPS request exceeds its deadline while the server continues sending data, `_new_conn()` tracks the raw socket, but urllib3 replaces it with an `SSLSocket` for TLS. The watchdog then shuts down the detached socket rather than the one doing the read, so a slow-drip response can keep the request—and its plugin worker—running past the deadline.
Track the socket after TLS wrapping as well, so the watchdog can shut down the active TLS socket.
</issue_to_address>
### Comment 6
<location path="foca/utils/http.py" line_range="609" />
<code_context>
+ ValueError: The body is not valid JSON (or nested too deeply).
+ """
+ try:
+ return json.loads(self.content)
+ except RecursionError as exc:
+ raise ValueError("JSON nested too deeply") from exc
</code_context>
<issue_to_address>
**JSON responses exhaust memory**
When an untrusted endpoint returns a valid, highly object-dense JSON body within the response-size limit, `json.loads` expands a size-limited response into Python objects without limiting the parsed structure; a 16 MiB response containing many short values can consume far more memory, and concurrent parses can exhaust the process and take down the service.
Bound JSON parsing by structure or memory cost, or use a streaming parser that enforces such a budget.
Also at `foca/utils/http.py:985`.
</issue_to_address>
### Comment 7
<location path="foca/utils/http.py" line_range="751" />
<code_context>
+ Session without environment settings (proxies, `.netrc`).
+ """
+ if self._session is None:
+ session = requests.Session()
+ session.trust_env = False
+ adapter = _GuardedAdapter(self._guards)
</code_context>
<issue_to_address>
**Concurrent calls share cookies**
When a plugin makes concurrent requests through one `ctx.http` and one response sets a cookie applicable to another request, requests' shared `Session` retains response cookies and attaches them to later requests. If one concurrent call receives `Set-Cookie` before another prepares a request to a matching domain, the second call sends state from the first, making plugin fan-out order-dependent and sending an unintended cookie.
Disable implicit cookie persistence or give each request an isolated cookie jar, with cookie sharing exposed only as an explicit opt-in.
</issue_to_address>
### Comment 8
<location path="foca/utils/http.py" line_range="750-756" />
<code_context>
+ Returns:
+ Session without environment settings (proxies, `.netrc`).
+ """
+ if self._session is None:
+ session = requests.Session()
+ session.trust_env = False
+ adapter = _GuardedAdapter(self._guards)
+ session.mount("https://", adapter)
+ session.mount("http://", adapter)
+ self._session = session
+ return self._session
+
</code_context>
<issue_to_address>
**Concurrent first requests leak sessions**
When multiple threads make the first request on the same client concurrently, `session` checks and assigns `_session` without synchronization, so concurrent first calls can each create a `requests.Session()` and overwrite the stored one. The overwritten session is never closed, leaving its connection pool outside `GuardedClient.close()` cleanup.
Synchronize lazy session creation so all callers use the single stored session.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 8 findings to address first, and if the address checks or connection pinning fail, a plugin-controlled URL could reach an internal service; a POST could also trigger an action there. Reverting removes the client, but cannot undo requests already sent or data already exposed.
Blocking findings: foca/utils/http.py:182, foca/utils/http.py:67, foca/utils/http.py:922, foca/utils/http.py:366, foca/utils/http.py:515, and 3 more
- Error messages name URLs without user info, query and fragment, with control characters escaped (_redact). - Guards track connections, not sockets: a connection belongs to the request that uses it, so a late timer of an earlier request no longer stops it, and one that such a timer stopped is closed before reuse. Timers shut down the current socket of a connection, so TLS sockets that wrap the new one are stopped too. - Sessions keep no cookies, and are created once under a lock. - Docs: cookies, redacted messages, and why network-specific NAT64 prefixes are not checked. Refs #490 Co-Authored-By: Claude Opus 5.5 <[email protected]>
CodeQL flags host substring checks in tests; compare the whole message instead (with an escape character, since urlsplit drops line breaks itself). Refs #490 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Adds
foca.utils.http, a guarded HTTP client for plugins, registry discovery and gateways. Their outbound calls go to URLs from users and registries, so without guards they would be SSRF vectors. This is the fourth PR of the v0.18.0 plugin stack (#485). It is built on requests and urllib3 only, so it doesn't depend on the web framework.is_public_address()andcheck_public_host()move here from proTES.GuardedClient:.netrc.httpsonly (unless allowed), and always verifies TLS.HttpResponse.HttpErrors with reason codes.RequestNotSent(e.g.,InvalidRequestURL,InvalidRequestfor bodies that aren't JSON or invalid headers,dns_error) is kept apart fromRequestMaybeSent, so that gateways can classify failures.fetch_json()for registry reads.ctx.httpis a client bound to the hook's deadline, and it is closed after each call.ctx.http.Documented limitation: the checks run when the host is resolved. Checking every connection's peer mitigates DNS rebinding, and the docs say so.
Closes #490
Verification
Run locally on d402994:
ruff checkandruff format --check: pass.mypy: pass.pytestwithout MongoDB: pass, with 100% coverage offoca/pluginsandfoca/utils/http.py. The tests use no network access (mocked resolver, local servers).mkdocs build --strict: pass.pre-commit: pass.The MongoDB tests and semgrep did not run locally (CI runs them). CI on d402994: all checks pass (MongoDB tests on Python 3.11 to 3.15), and the image jobs are skipped as intended. The first run failed on coverage: Python 3.14 and later parse deep, unbalanced arrays without RecursionError, so d402994 also forces that branch in the test.
Review: two rounds of adversarial and quality review.
InvalidRequestURL;dns_errorreason;HttpResponse.urlwas unused;urllib3wasn't declared as a dependency;All are fixed.
Sourcery: 8 findings. 5 are fixed in 184179a:
3 are declined (see below). CodeQL then flagged a host substring check in the new test; 212fe63 compares the whole message instead. CI on 212fe63: 28 checks pass, and 2 are skipped as intended.
Declined review findings
urllib3>=2.6bounds decompression in its streaming API (CVE-2025-66471).max_response_size, which callers lower for untrusted documents.🤖 Generated with Claude Code