mirror of
https://github.com/headroomlabs-ai/headroom.git
synced 2026-11-24 19:52:53 +08:00
fix(proxy): keep hop-by-hop request headers off upstream calls (#4775)
## Description
Handlers copy the inbound request headers before calling the provider
(`headers = dict(request.headers.items())`, minus host, content-length
and the encodings). `Connection` is not removed, so a client that sends
`Connection: close` has it forwarded to api.anthropic.com or
chatgpt.com. The provider then closes the connection after each
response, and the keep-alive pool never reuses one. Every request pays a
fresh DNS lookup, TCP connect and TLS handshake, and every DNS or
handshake hiccup on the client's network becomes a failed request.
Extra Headroom's local intercept sends `Connection: close` on every
request, so all of its traffic was affected. curl and any client that
wants one request per connection hit the same thing.
Hop-by-hop fields describe the client's connection to the proxy, not the
proxy's connection to the provider (RFC 9110 7.6.1). This adds a request
hook to the provider httpx clients that drops them on every upstream
call, wherever the handler built its headers.
## Type of Change
- [x] Bug fix (non-breaking change that fixes an issue)
- [x] Performance improvement
## Changes Made
- `_provider_httpx_client_options` adds a request event hook to both
provider clients (`http_client` and `http_client_h1`). The hook drops
`Connection`, `Keep-Alive`, `Proxy-Connection`, `TE`, `Trailer`,
`Upgrade` and any header the `Connection` value names.
- The hook never touches `Host`, `Content-Length` or
`Transfer-Encoding`, which are httpx's own framing by the time it runs.
- New `tests/test_upstream_hop_by_hop_headers.py`: hop-by-hop headers
stay local, headers named by `Connection` are dropped while framing is
kept, ordinary requests are unchanged.
## Testing
- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [x] Manual testing performed
### Test Output
```text
$ uv run --frozen --extra dev pytest tests/test_upstream_hop_by_hop_headers.py tests/test_upstream_write_timeout.py tests/test_proxy_scalability.py -q
28 passed in 0.91s
# with the hook line removed (revert check):
FAILED tests/test_upstream_hop_by_hop_headers.py::test_connection_close_and_other_hop_by_hop_headers_stay_local
FAILED tests/test_upstream_hop_by_hop_headers.py::test_headers_named_by_connection_are_dropped_but_framing_is_kept
2 failed, 1 passed in 0.23s
$ ruff check . (0.17.3) All checks passed!
$ ruff format --check . (0.17.3) 1933 files already formatted
$ mypy headroom/proxy/server.py --ignore-missing-imports Success: no issues found
$ pytest tests scripts/tests -n 6 19202 passed, 27 failed, 619 skipped in 301s. The failures sit in five files (test_proxy_uds, test_proxy_health, test_proxy_scalability Windows selector loop, test_read_maturation_handler_nobust, test_transforms_tabular timing) and fail the same way on unmodified main on this machine: 13 vs 12 failures in those files, with the read-maturation ones varying run to run on both branches.
```
## Real Behavior Proof
- Environment: macOS 27.2 (Apple Silicon), Python 3.12, this branch's
`headroom proxy --port 6799 --no-http2 --no-rate-limit` with an empty
HOME, talking to the real api.anthropic.com.
- Exact command / steps: Three unauthenticated `POST /v1/messages` with
`Connection: close` (Anthropic answers 401), listing the proxy's sockets
to 160.79.104.10:443 after each request; the same on this branch with
the hook line removed. Then 1,000 streaming requests with `Connection:
close`, 24 at a time, against a local TLS server that counts
connections.
- Observed result: With the fix, all three requests rode one upstream
connection (local port 53147 each time); without it, no upstream
connection survived a single request. Local stress: 1,000 requests used
24 upstream connections on this branch and 1,000 on main.
- Not tested: HTTP/2 upstreams (Extra Headroom runs `--no-http2`),
Bedrock and Gemini routes, which share the same client.
```text
with-fix req1: HTTP 401 7.09s upstream 192.168.1.20:53147
with-fix req2: HTTP 401 0.22s upstream 192.168.1.20:53147
with-fix req3: HTTP 401 0.35s upstream 192.168.1.20:53147
without-fix req1..3: HTTP 401 upstream (none open after each request)
main: 1000 ok, upstream {"connections": 1000, "requests": 1001}
this branch: 1000 ok, upstream {"connections": 24, "requests": 1001}
```
## Runtime Rollout Safety
- Rollout-managed feature(s): None.
- Minimum rollout channel: Stable.
- Stable/default behavior changed: Yes. Upstream requests no longer
carry the client's hop-by-hop headers, so requests from clients that
send `Connection: close` now reuse pooled connections like every other
request.
- Kill switch / disable path: `HEADROOM_MAX_KEEPALIVE=0` keeps the pool
empty and restores one connection per request.
- Unsafe override required: No.
- Qualification impact: None.
- Rollback path: Revert this commit.
## Review Readiness
- [x] I have performed a self-review
- [x] This PR is ready for human review
## Checklist
- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [x] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [x] I did **not** edit `CHANGELOG.md` — it is generated by
release-please from my Conventional Commit PR title (a CI guard enforces
this)
## Screenshots (if applicable)
Not applicable.
## Additional Notes
- Documentation: no user-facing doc describes the forwarded headers, so
there is nothing to update.
- Reuse under cancellation, since reuse now actually happens for these
clients: with this PR and #4776 (TLS error retry on a reused
connection), a local TLS upstream took 2,000 streaming requests, half
cancelled at a random point, and 1,500 requests with 1.5 MB bodies, 60%
cancelled early. There were zero upstream errors in both runs, and every
cancelled request's connection was closed rather than returned to the
pool.
- Related: #4265 / #4350 fixed the response side of the same RFC rule.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
622df2962b
commit
8f47a86410
@@ -910,11 +910,35 @@ def _apply_stateless_persistence(config: ProxyConfig) -> None:
|
||||
detach_compression_store()
|
||||
|
||||
|
||||
# Hop-by-hop fields (RFC 9110 7.6.1) describe the client's connection to the
|
||||
# proxy, not the proxy's connection to the provider. Handlers copy the inbound
|
||||
# headers, so a client's `Connection: close` reached the provider and made
|
||||
# every pooled upstream connection single-use: a fresh DNS lookup, TCP connect
|
||||
# and TLS handshake per request. Framing (content-length, transfer-encoding)
|
||||
# is httpx's own by the time the hook runs and is never touched.
|
||||
_HOP_BY_HOP_REQUEST_HEADERS = frozenset(
|
||||
{"connection", "keep-alive", "proxy-connection", "te", "trailer", "upgrade"}
|
||||
)
|
||||
_FRAMING_REQUEST_HEADERS = frozenset({"host", "content-length", "transfer-encoding"})
|
||||
|
||||
|
||||
async def _drop_hop_by_hop_request_headers(request: httpx.Request) -> None:
|
||||
named = {
|
||||
token.strip().lower()
|
||||
for token in request.headers.get_list("connection", split_commas=True)
|
||||
if token.strip()
|
||||
}
|
||||
for name in (_HOP_BY_HOP_REQUEST_HEADERS | named) - _FRAMING_REQUEST_HEADERS:
|
||||
if name in request.headers:
|
||||
del request.headers[name]
|
||||
|
||||
|
||||
def _provider_httpx_client_options(
|
||||
config: ProxyConfig,
|
||||
verify: Any,
|
||||
) -> tuple[bool, dict[str, Any]]:
|
||||
client_kwargs: dict[str, Any] = {
|
||||
"event_hooks": {"request": [_drop_hop_by_hop_request_headers]},
|
||||
"timeout": httpx.Timeout(
|
||||
connect=config.connect_timeout_seconds,
|
||||
read=config.request_timeout_seconds,
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Provider clients must not forward the client's hop-by-hop headers.
|
||||
|
||||
Handlers copy the inbound request headers, so a client that sent
|
||||
`Connection: close` (curl, or a local proxy that wants one request per
|
||||
connection) had it forwarded to the provider, which then closed the upstream
|
||||
connection after every response. The keep-alive pool never reused a
|
||||
connection: each request paid a fresh DNS lookup, TCP connect and TLS
|
||||
handshake, and was exposed to every DNS or handshake hiccup on the way.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import httpx
|
||||
|
||||
from headroom.proxy.models import ProxyConfig
|
||||
from headroom.proxy.server import _provider_httpx_client_options
|
||||
|
||||
|
||||
async def _sent_headers(headers: dict[str, str], content: bytes = b"{}") -> httpx.Headers:
|
||||
seen: list[httpx.Headers] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
seen.append(request.headers)
|
||||
return httpx.Response(200)
|
||||
|
||||
_http2, kwargs = _provider_httpx_client_options(ProxyConfig(), verify=True)
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(handler), **kwargs) as client:
|
||||
await client.post("https://api.example.com/v1/messages", headers=headers, content=content)
|
||||
return seen[0]
|
||||
|
||||
|
||||
async def test_connection_close_and_other_hop_by_hop_headers_stay_local() -> None:
|
||||
sent = await _sent_headers(
|
||||
{
|
||||
"Connection": "close",
|
||||
"Keep-Alive": "timeout=5",
|
||||
"Proxy-Connection": "keep-alive",
|
||||
"TE": "trailers",
|
||||
"Trailer": "x-checksum",
|
||||
"Upgrade": "websocket",
|
||||
"x-api-key": "k",
|
||||
}
|
||||
)
|
||||
|
||||
for name in ("connection", "keep-alive", "proxy-connection", "te", "trailer", "upgrade"):
|
||||
assert name not in sent, name
|
||||
assert sent["x-api-key"] == "k"
|
||||
|
||||
|
||||
async def test_headers_named_by_connection_are_dropped_but_framing_is_kept() -> None:
|
||||
sent = await _sent_headers(
|
||||
{"Connection": "x-session-hint, content-length", "x-session-hint": "1"},
|
||||
content=b'{"a":1}',
|
||||
)
|
||||
|
||||
assert "x-session-hint" not in sent
|
||||
assert sent["content-length"] == "7"
|
||||
assert sent["host"] == "api.example.com"
|
||||
|
||||
|
||||
async def test_ordinary_requests_are_unchanged() -> None:
|
||||
sent = await _sent_headers({"anthropic-version": "2023-06-01", "x-api-key": "k"})
|
||||
|
||||
assert sent["anthropic-version"] == "2023-06-01"
|
||||
assert sent["x-api-key"] == "k"
|
||||
Reference in New Issue
Block a user