Skip to content

fix: bound redirect bodies, tell sent from unsent - #643

Merged
uniqueg merged 5 commits into
devfrom
fix/guarded-client-limits
Nov 3, 2026
Merged

uniqueg merged 5 commits into
devfrom
fix/guarded-client-limits

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

Closes #640

Summary

  • Redirect bodies: with allow_redirects=False, requests.Session.send() still reads the whole body of a redirect, without limit, to prepare Response.next. A session subclass without redirect targets returns redirects unread, so they go through max_response_size and the deadline, and redirects to invalid URLs are returned instead of raising InvalidRequestURL.
  • Response hooks: handlers such as HTTPDigestAuth read bodies without limit and send further requests from a hook. Requests with response hooks are now refused before sending (InvalidRequest), also by FakeHttp.
  • Sent or not: RequestNotSent or RequestMaybeSent now 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: docs/utilities.md, docs/migration-0.20.md.

No caller in FOCA passes hook-installing auth; backends' auth is a credential name, not an HTTP handler.

Verification

  • ruff check, ruff format --check, mypy, ast-grep scan, mkdocs build --strict: pass
  • coverage run -m pytest -m "not mongodb": see the numbers in CI; foca/utils/http.py at 100% locally. Tests marked mongodb run in CI.
  • New tests failed before the fix.
  • The reviewer ran the tests on urllib3 2.6.0 with requests 2.33.0 and on urllib3 2.8.0 with requests 2.34.2.

Declined review findings

  • The deadline timer can't interrupt a hanging TLS handshake, so a request with slow DNS or TCP can overrun its deadline by the rest of the connect timeout. Pre-existing and unrelated to sent or not (the error is correctly DeadlineExceeded); fits the separate timeouts in the GuardedClient item of 0.21.0.
  • except (AddressNotAllowed, DeadlineExceeded): raise doesn't check the flag: only reachable after sending through a second send, and hooks, the only way to one, are refused now.
  • Test patching HTTPConnection.connect for plain http: test_connection_refused already 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:

  • Bound redirect response bodies by the configured response-size and deadline limits, while returning redirects without validating or following their targets.
  • Correctly classify request failures as sent or unsent based on whether request transmission began, including TLS, connection, timeout, and deadline errors.
  • Reject authentication or session response hooks that can read unbounded bodies or issue additional requests, consistently in real and fake HTTP clients.

Enhancements:

  • Document the updated redirect, response-hook, and request-delivery error semantics.

Documentation:

  • Update utility and migration documentation for bounded redirects, refused response hooks, and sent-versus-unsent error classification.

Tests:

  • Add coverage for bounded redirect bodies, invalid redirect targets, response-hook rejection, and request error classification before and after transmission.

uniqueg and others added 3 commits November 3, 2026 07:02
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
@uniqueg uniqueg added this to the v0.20.0 milestone Nov 3, 2026
@uniqueg uniqueg added type: bug Something isn't working type: security Related to security labels Nov 3, 2026
@sourcery-ai

sourcery-ai Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

The 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 classification

sequenceDiagram
    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
Loading

Sequence diagram for bounded redirect and response-hook handling

sequenceDiagram
    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
Loading

File-Level Changes

Change Details Files
Bound redirect handling to normal response safeguards and neutralized redirect preparation.
  • Added a guarded session that returns redirects unread and suppresses redirect target parsing.
  • Applied response-size and deadline enforcement to redirect bodies.
  • Returned invalid redirect locations as responses instead of raising URL errors.
foca/utils/http.py
tests/utils/test_http.py
docs/utilities.md
docs/migration-0.20.md
Changed request outcome classification to track whether request transmission actually started.
  • Recorded sent state immediately before writing request bytes on new and reused connections.
  • Classified connection, TLS, timeout, and read failures using sent state rather than exception type.
  • Preserved deadline, invalid-request, and invalid-URL handling based on the transmission point.
foca/utils/http.py
tests/utils/test_http.py
docs/utilities.md
docs/migration-0.20.md
Rejected response-hook authentication and session behavior that can perform unbounded reads or follow-up requests.
  • Added response-hook validation for prepared requests and authentication handlers.
  • Applied the same rejection behavior to FakeHttp before any canned request is recorded or sent.
  • Allowed header-only credentials such as basic-auth tuples.
foca/utils/http.py
foca/plugins/testing.py
tests/utils/test_http.py
tests/plugins/test_plugin_testing.py
docs/utilities.md
docs/migration-0.20.md

Possibly linked issues


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 3, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (16812d8) to head (ff513f4).

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     
Flag Coverage Δ
test_unit 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review November 3, 2026 06:51

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread foca/utils/http.py Resolved
Comment thread foca/plugins/testing.py Resolved
Comment thread foca/plugins/testing.py Resolved
@uniqueg
uniqueg merged commit 0223366 into dev Nov 3, 2026
56 checks passed
@uniqueg
uniqueg deleted the fix/guarded-client-limits branch November 3, 2026 07:31
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type: bug Something isn't working type: security Related to security

Projects

None yet

Development

Successfully merging this pull request may close these issues.

fix: bound redirect bodies, tell sent from unsent

1 participant