Repository navigation
fix: bound redirect bodies, tell sent from unsent - #643
Conversation
With allow_redirects=False, requests still reads the whole body of a redirect, without limit, to prepare Response.next, and raises for invalid Location headers. Use a session that knows no redirects, so that their bodies go through the size limit and they are returned. Tell errors before sending from errors after by whether sending has started, noted when the first byte goes out, rather than by the kind of error: a TLS error while waiting for a response was reported as RequestNotSent, and a connection lost in the handshake as RequestMaybeSent. Each reason code now means one or the other. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
Handlers such as HTTPDigestAuth read the bodies of responses without limit and send further requests from a response hook, past the checks of the size limit and of what was sent. Refuse them before sending. Also list the changes of errors in the migration guide. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
Plugin tests should fail where the real client refuses a request. Name response hooks in the error, as hooks on the session count as well. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
Reviewer's GuideThe PR hardens guarded HTTP behavior by limiting redirect-body reads, refusing response hooks that bypass those safeguards, and deriving RequestNotSent versus RequestMaybeSent from whether request bytes began transmitting, with matching fake-client behavior, tests, and migration documentation. Sequence diagram for guarded HTTP request sent-state classificationsequenceDiagram
participant Caller
participant GuardedClient
participant Guard
participant Connection
participant Server
Caller->>GuardedClient: request()
GuardedClient->>Guard: create guard(sent=false)
GuardedClient->>Connection: connect()
alt Connection or TLS handshake fails
Connection-->>GuardedClient: RequestException
GuardedClient->>GuardedClient: _error(exc, url, guard)
GuardedClient-->>Caller: RequestNotSent
else Connection is open
GuardedClient->>Guard: set sent=true
GuardedClient->>Connection: send(data)
Connection->>Server: request bytes
alt Response read fails
Server-->>Connection: response or connection error
Connection-->>GuardedClient: RequestException
GuardedClient->>GuardedClient: _classify(exc, url, sent=true)
GuardedClient-->>Caller: RequestMaybeSent
else Response succeeds
Server-->>GuardedClient: response
GuardedClient-->>Caller: response body
end
end
Sequence diagram for bounded redirect and response-hook handlingsequenceDiagram
participant Caller
participant GuardedClient
participant GuardedSession
participant Server
Caller->>GuardedClient: request(auth, allow_redirects=false)
GuardedClient->>GuardedSession: prepare and send request
GuardedSession->>GuardedSession: _check_response_hooks(request.hooks)
alt Response hooks present
GuardedSession-->>GuardedClient: InvalidRequest
GuardedClient-->>Caller: reject before sending
else No response hooks
GuardedSession->>Server: send request
Server-->>GuardedSession: redirect response
GuardedSession->>GuardedSession: get_redirect_target(response)
GuardedSession-->>GuardedClient: redirect response without following
GuardedClient->>GuardedClient: _read(response, url, guard)
alt Body exceeds max_response_size or deadline
GuardedClient-->>Caller: ResponseTooLarge or DeadlineExceeded
else Body is within limits
GuardedClient-->>Caller: bounded redirect response
end
end
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 #643 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 56 56
Lines 7119 7142 +23
=========================================
+ Hits 7119 7142 +23
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/http.py" line_range="591" />
<code_context>
+ conn: Any = self
+ if conn.sock is None:
+ conn.connect()
+ self.guards.current().sent = True
+ super().send(data) # type: ignore[misc]
+
</code_context>
<issue_to_address>
**Unsent requests suppress retries**
When the deadline fires after connection setup but before the first write, or a reused connection's first write fails without sending bytes, `_GuardedConnectionMixin.send()` sets `guard.sent` before `super().send(data)` writes, so `_error()` reports `RequestMaybeSent` for a request that sent no bytes and callers suppress retries or skip the next backend.
Set `guard.sent` only when the first request byte is actually transmitted, rather than before `super().send(data)`.
Also at `foca/utils/http.py:592`.
</issue_to_address>
### Comment 2
<location path="foca/plugins/testing.py" line_range="473" />
<code_context>
_check_json_body(json, url)
+ if auth is not None:
+ _check_response_hooks(
+ requests.Request(method, url, auth=auth).prepare().hooks
+ )
if not self.allow_private_addresses:
</code_context>
<issue_to_address>
**Fake tests accept rejected requests**
When a test configures response hooks on `FakeHttp.session` or uses session auth that installs hooks based on request headers or body, `FakeHttp.request` prepares a bare `requests.Request` with only the explicit `auth` argument, so inherited session hooks and hooks installed by session auth go unchecked; plugin tests pass although `GuardedClient` rejects the same request with `InvalidRequest`.
Prepare the request through `self.session` and validate the merged response hooks before returning the fake response.
</issue_to_address>
### Comment 3
<location path="foca/plugins/testing.py" line_range="471-474" />
<code_context>
raise InvalidRequestURL("Invalid HTTP method")
if json is not None:
_check_json_body(json, url)
+ if auth is not None:
+ _check_response_hooks(
+ requests.Request(method, url, auth=auth).prepare().hooks
+ )
if not self.allow_private_addresses:
try:
</code_context>
<issue_to_address>
**Fake client leaks preparation errors**
When `auth` is supplied and Requests rejects the URL during preparation, `_split` accepts URLs such as `https://` without a host, then `requests.Request(...).prepare()` raises before `FakeHttp` reaches its URL-error handler; callers get a raw Requests exception instead of `InvalidRequestURL`, unlike `GuardedClient` and `FakeHttp` calls without `auth`.
Put auth preparation inside the same error-normalization path as URL preparation, or validate the URL before preparing auth.
</issue_to_address>Linked issues
#640 fix: bound redirect bodies, tell sent from unsent · 6 of 6 met
| # | Requirement | Status | Notes |
|---|---|---|---|
| 1 | Bound redirect response bodies by the normal size and deadline limits. | ✅ Met | The session avoids preparing redirect targets, leaving redirect bodies to the normal guarded response reader; a test covers an endless redirect body exceeding the limit. |
| 2 | Return redirects to invalid URLs instead of raising InvalidRequestURL. | ✅ Met | A test verifies that a redirect with an invalid Location is returned as a response. |
| 3 | Refuse authentication handlers with response hooks before sending. | ✅ Met | The guarded session checks prepared request hooks, and FakeHttp applies the same check to authentication handlers. |
| 4 | Classify RequestNotSent versus RequestMaybeSent by whether sending has started, not by error kind. | ✅ Met | The connection records the sent state before sending data; error mapping uses that state, including for TLS and connection errors. |
| 5 | Add tests for TLS errors and lost connections before and after sending. | ✅ Met | Tests cover pre-send and post-send classification, including TLS errors and lost connections. |
| 6 | Update docs/utilities.md and the migration guide. | ✅ Met | Both documents describe the redirect limits, response-hook restriction, and revised error classification. |
Sourcery assessment
Needs a human reviewer. 3 findings to address first, and if the send-state tracking is wrong, a request the server already received could be reported as not sent, prompting a caller to retry it and repeat an external action; reverting cannot undo that action. The new refusal of response-hook authentication handlers also changes which authentication flows clients can use.
Blocking findings: foca/utils/http.py:591, foca/plugins/testing.py:473, foca/plugins/testing.py:474
Invalid URLs with auth gave errors of requests rather than InvalidRequestURL. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
Closes #640
Summary
allow_redirects=False,requests.Session.send()still reads the whole body of a redirect, without limit, to prepareResponse.next. A session subclass without redirect targets returns redirects unread, so they go throughmax_response_sizeand the deadline, and redirects to invalid URLs are returned instead of raisingInvalidRequestURL.HTTPDigestAuthread bodies without limit and send further requests from a hook. Requests with response hooks are now refused before sending (InvalidRequest), also byFakeHttp.RequestNotSentorRequestMaybeSentnow follows from a flag set when the first byte goes out, not from the kind of error. A TLS error while waiting for a response used to be "not sent", so a gateway could submit a task twice; a connection lost in the TLS handshake used to be "maybe sent". Each reason code now means one or the other.docs/utilities.md,docs/migration-0.20.md.No caller in FOCA passes hook-installing
auth; backends'authis a credential name, not an HTTP handler.Verification
ruff check,ruff format --check,mypy,ast-grep scan,mkdocs build --strict: passcoverage run -m pytest -m "not mongodb": see the numbers in CI;foca/utils/http.pyat 100% locally. Tests markedmongodbrun in CI.Declined review findings
DeadlineExceeded); fits the separate timeouts in the GuardedClient item of 0.21.0.except (AddressNotAllowed, DeadlineExceeded): raisedoesn't check the flag: only reachable after sending through a second send, and hooks, the only way to one, are refused now.HTTPConnection.connectfor plainhttp:test_connection_refusedalready fails if connecting moves after the flag.🤖 Generated with Claude Code
https://claude.ai/code/session_011FSoqMUX3EU35poH13xMgG
Summary by Sourcery
Make guarded HTTP requests enforce response limits and accurately report whether a request may have reached the server.
Bug Fixes:
Enhancements:
Documentation:
Tests: