fix(codex): strip stale compression framing on the Responses subpath passthrough (#3792)

## Description

`handle_chatgpt_codex_responses_subpath` (the ChatGPT-auth passthrough
for `/v1/responses/{id}` subpaths — retrieve, cancel, etc.) forwarded
the upstream response verbatim:

```python
return Response(content=resp.content, status_code=resp.status_code, headers=dict(resp.headers))
```

`resp.content` (httpx) is the **already-decoded** plaintext body, but
`dict(resp.headers)` still carries the upstream's `content-encoding:
gzip` and its (compressed) `content-length`. And
`normalize_codex_responses_headers` dropped only `host`, leaving the
client's `accept-encoding` intact so the upstream was free to gzip.

So a Codex client sending `Accept-Encoding: gzip` that hits a responses
subpath under a ChatGPT-auth account gets a **decoded** body labelled
`content-encoding: gzip` with a **compressed** `content-length` — the
client's gunzip fails, or the shorter length truncates the body. This is
the exact framing-corruption class the codebase already documents (#3019
/ `helpers.FRAMING_RESPONSE_HEADERS`).

The sibling **image** passthrough (`providers/codex/images.py`) already
handles this: `normalize_codex_image_headers` drops `accept-encoding`,
and `sanitize_codex_image_response_headers` drops
`content-encoding`/`content-length`/`server` before returning. The
responses subpath was never given the same treatment.

This mirrors images.py:
- drop `accept-encoding` in `normalize_codex_responses_headers` so the
upstream returns plaintext;
- add `sanitize_codex_responses_response_headers` (drops
`content-encoding`/`content-length`/`server`) and return through it
(Starlette recomputes `content-length`);
- guard the `await request.body()` read with `ClientDisconnect` → `204`,
matching images.py, so a disconnect during body read no longer 500s.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/providers/codex/responses.py`:
`normalize_codex_responses_headers` now drops `accept-encoding`; new
`sanitize_codex_responses_response_headers` drops stale framing headers;
`handle_chatgpt_codex_responses_subpath` returns through the sanitizer
and wraps the body read in a `ClientDisconnect` → 204 guard.
- `tests/test_provider_codex_responses.py`: added a header-drop test
(`accept-encoding` removed), a sanitizer test (drops
`content-encoding`/`content-length`/`server`, case-insensitive, keeps
others), and an end-to-end handler test driving a fake gzip-framing
upstream and asserting the forwarded response has no `content-encoding`,
preserves the plaintext body, and that `accept-encoding` was stripped
from the upstream call.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality

### Test Output

```text
tests/test_provider_codex_responses.py  ->  7 passed
uvx ruff@0.16.8 check headroom/providers/codex/responses.py tests/test_provider_codex_responses.py  ->  All checks passed!
uvx mypy@1.20.2 headroom/providers/codex/responses.py  ->  clean (no error in this file)
```

## Real Behavior Proof

- Environment: Windows 11, Python 3.12.11, project venv, pytest 9.1.1,
ruff 0.16.8 and mypy 1.20.2 via uvx.
- Exact command / steps: drove `handle_chatgpt_codex_responses_subpath`
with a fake upstream returning plaintext JSON under `content-encoding:
gzip` + a compressed `content-length`. The forwarded `Response` carries
the plaintext body with no `content-encoding` header, and the upstream
request was made without `accept-encoding`. Verified the sibling image
passthrough was already correct.
- Observed result: the client receives a well-framed plaintext response
instead of a decoded body mislabelled as gzip.
- Not tested: a live ChatGPT-Codex account round-trip (requires
ChatGPT-auth credentials); the framing behavior is covered by the
fake-upstream handler test.

## Runtime Rollout Safety

- Rollout-managed feature(s): none.
- Minimum rollout channel: N/A.
- Stable/default behavior changed: only the forwarded framing headers on
Codex `/v1/responses/{id}` subpath passthrough — stale compression
headers are dropped, matching the image passthrough. The body content is
unchanged.
- Kill switch / disable path: N/A.
- Unsafe override required: no.
- Qualification impact: none.
- Rollback path: revert this commit; the subpath again replays upstream
framing headers.

## 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
- [ ] I have made corresponding changes to the documentation (N/A:
internal passthrough framing)
- [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`

## Additional Notes

Kept the sanitizer local to the codex module
(`sanitize_codex_responses_response_headers`) to mirror
`sanitize_codex_image_response_headers` exactly, rather than reaching
for `helpers.sanitize_forwarded_response_headers`, so the two Codex
passthroughs stay symmetric and independently readable.

Co-authored-by: JD Davis <mxjerrett@gmail.com>
This commit is contained in:
Abhay Singh
2026-09-30 11:15:24 -05:00
committed by GitHub
co-authored by JD Davis
parent 08dda4cb0b
commit 0eba65ca4a
2 changed files with 141 additions and 2 deletions
+28 -2
View File
@@ -8,6 +8,7 @@ from typing import Any, Protocol
from fastapi import Request
from fastapi.responses import Response
from starlette.requests import ClientDisconnect
from .endpoints import codex_backend_url, codex_backend_ws_url
from .headers import drop_header, header_name
@@ -41,10 +42,31 @@ def normalize_codex_responses_headers(headers: Mapping[str, str]) -> tuple[dict[
"""Prepare inbound headers for ChatGPT Codex Responses passthrough."""
upstream_headers = dict(headers)
drop_header(upstream_headers, "host")
# Drop the client's Accept-Encoding so the upstream returns plaintext. httpx
# decodes the body before we read ``resp.content``, so if we let the upstream
# gzip we would forward a decoded body under a ``content-encoding: gzip`` /
# compressed ``content-length`` (see sanitize below) -- the #3019 framing
# corruption. Mirrors the image passthrough.
drop_header(upstream_headers, "accept-encoding")
decision = resolve_codex_routing(upstream_headers)
return decision.headers, decision.is_chatgpt_auth
def sanitize_codex_responses_response_headers(headers: Mapping[str, str]) -> dict[str, str]:
"""Drop stale compression/framing headers after materializing response bytes.
``resp.content`` is already-decoded plaintext, so the upstream's
``content-encoding`` and ``content-length`` (measured on the compressed
bytes) no longer describe what we forward; replaying them makes the client
fail to gunzip or truncate the body. Starlette recomputes ``content-length``.
"""
response_headers = dict(headers)
drop_header(response_headers, "content-encoding")
drop_header(response_headers, "content-length")
drop_header(response_headers, "server")
return response_headers
def codex_responses_subpath_url(sub_path: str, query: str = "") -> str:
"""Return the ChatGPT Codex Responses upstream URL for a route subpath."""
return codex_backend_url(f"/responses/{sub_path}", query)
@@ -75,7 +97,11 @@ async def handle_chatgpt_codex_responses_subpath(
if not is_chatgpt_auth:
return None
body = await request.body()
try:
body = await request.body()
except ClientDisconnect:
logger.debug("Client disconnected during body read for /v1/responses passthrough")
return Response(status_code=204)
try:
resp = await http_client.request(
request.method,
@@ -87,7 +113,7 @@ async def handle_chatgpt_codex_responses_subpath(
return Response(
content=resp.content,
status_code=resp.status_code,
headers=dict(resp.headers),
headers=sanitize_codex_responses_response_headers(resp.headers),
)
except Exception:
logger.exception("Passthrough /v1/responses/%s failed", sub_path)
+113
View File
@@ -1,9 +1,13 @@
import pytest
from headroom.providers.codex.responses import (
codex_responses_http_url,
codex_responses_subpath_url,
codex_responses_websocket_url,
handle_chatgpt_codex_responses_subpath,
has_chatgpt_account_header,
normalize_codex_responses_headers,
sanitize_codex_responses_response_headers,
)
@@ -57,3 +61,112 @@ def test_codex_responses_headers_return_false_for_regular_openai_auth() -> None:
assert is_chatgpt_auth is False
assert headers == {"authorization": "Bearer sk-proj-test"}
assert has_chatgpt_account_header(headers) is False
def test_codex_responses_headers_drop_accept_encoding() -> None:
"""accept-encoding must be dropped so the upstream returns plaintext; httpx
decodes the body before we read it, so a gzip upstream would corrupt framing."""
headers, _ = normalize_codex_responses_headers(
{
"Host": "localhost:8787",
"authorization": "Bearer token",
"chatgpt-account-id": "acct",
"Accept-Encoding": "gzip, deflate, br",
}
)
assert "accept-encoding" not in {k.lower() for k in headers}
def test_codex_responses_response_headers_drop_stale_framing_case_insensitive() -> None:
assert sanitize_codex_responses_response_headers(
{
"Content-Encoding": "gzip",
"Content-Length": "9999",
"Server": "cloudflare",
"Content-Type": "application/json",
"x-request-id": "kept",
}
) == {
"Content-Type": "application/json",
"x-request-id": "kept",
}
class _FakeResp:
def __init__(self, content: bytes, status_code: int, headers: dict[str, str]):
self.content = content
self.status_code = status_code
self.headers = headers
class _FakeClient:
def __init__(self, resp: _FakeResp):
self._resp = resp
self.last_headers: dict[str, str] | None = None
async def request(self, method, url, *, headers, content, timeout):
self.last_headers = headers
return self._resp
def _request(method: str, path: str, headers: dict[str, str], body: bytes):
from starlette.requests import Request
raw = [(k.lower().encode(), v.encode()) for k, v in headers.items()]
scope = {
"type": "http",
"method": method,
"path": path,
"query_string": b"",
"headers": raw,
}
sent = False
async def receive():
nonlocal sent
if sent:
return {"type": "http.request", "body": b"", "more_body": False}
sent = True
return {"type": "http.request", "body": body, "more_body": False}
return Request(scope, receive)
@pytest.mark.asyncio
async def test_subpath_passthrough_strips_upstream_compression_framing() -> None:
"""The upstream body is already-decoded plaintext, so the forwarded response
must not replay content-encoding / a compressed content-length (#3019)."""
plaintext = b'{"id":"resp_1","status":"completed"}'
upstream = _FakeResp(
content=plaintext,
status_code=200,
headers={
"content-encoding": "gzip", # stale: content is already decoded
"content-length": "17", # stale: compressed length
"content-type": "application/json",
"x-request-id": "req-123",
},
)
client = _FakeClient(upstream)
request = _request(
"GET",
"/v1/responses/resp_1",
{
"host": "localhost:8787",
"authorization": "Bearer token",
"chatgpt-account-id": "acct",
"accept-encoding": "gzip",
},
body=b"",
)
response = await handle_chatgpt_codex_responses_subpath(client, request, "resp_1")
assert response is not None
assert response.status_code == 200
assert response.body == plaintext
out = {k.lower() for k, _ in response.raw_headers}
assert b"content-encoding" not in out
# accept-encoding was stripped before the upstream call.
assert client.last_headers is not None
assert "accept-encoding" not in {k.lower() for k in client.last_headers}