Files
headroom/tests/test_provider_codex_responses.py
Abhay SinghandJD Davis 0eba65ca4a 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>
2026-09-30 11:15:24 -05:00

173 lines
5.5 KiB
Python

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,
)
def test_codex_responses_subpath_url_includes_optional_query() -> None:
assert (
codex_responses_subpath_url("items/resp_1", "trace=2")
== "https://chatgpt.com/backend-api/codex/responses/items/resp_1?trace=2"
)
assert (
codex_responses_subpath_url("compact")
== "https://chatgpt.com/backend-api/codex/responses/compact"
)
def test_codex_responses_endpoint_urls_are_provider_owned() -> None:
assert codex_responses_http_url() == "https://chatgpt.com/backend-api/codex/responses"
assert (
codex_responses_http_url("stream=true")
== "https://chatgpt.com/backend-api/codex/responses?stream=true"
)
assert codex_responses_websocket_url() == "wss://chatgpt.com/backend-api/codex/responses"
def test_codex_responses_headers_drop_host_and_resolve_explicit_chatgpt_auth() -> None:
headers, is_chatgpt_auth = normalize_codex_responses_headers(
{
"Host": "localhost:8787",
"authorization": "Bearer token",
"chatgpt-account-id": "acct",
"originator": "Codex Desktop",
}
)
assert is_chatgpt_auth is True
assert headers == {
"authorization": "Bearer token",
"chatgpt-account-id": "acct",
"originator": "Codex Desktop",
}
assert has_chatgpt_account_header(headers) is True
def test_codex_responses_headers_return_false_for_regular_openai_auth() -> None:
headers, is_chatgpt_auth = normalize_codex_responses_headers(
{
"Host": "localhost:8787",
"authorization": "Bearer sk-proj-test",
}
)
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}