refactor(proxy): reuse shared Codex decompression and header filtering

This commit is contained in:
Dmitry Chepurovskiy 2026-10-22 16:40:11 +03:00
parent f4c6f6a872
commit fa6f998ce3
No known key found for this signature in database
GPG key ID: 5B3A5FDCBFF9B3A4
9 changed files with 102 additions and 54 deletions

View file

@ -2,7 +2,7 @@
Compatible Codex clients can send subscription requests through an authenticated LiteLLM gateway. The client signs into ChatGPT and refreshes its own tokens. LiteLLM does not sign in, refresh tokens, or store subscription credentials.
This route supports HTTP and server-sent events with uncompressed JSON requests. Set `features.enable_request_compression = false` in Codex. Requests declaring a content encoding other than `identity` return HTTP 415 before gateway authentication or body parsing. Subscription WebSockets, voice, and gateway OAuth sign-in are not supported. It does not change the API-key-backed `/v1/responses` endpoint.
This route supports HTTP and server-sent events with JSON requests. The proxy's shared request middleware decodes gzip and zstd before authentication and model authorization, with its normal size, expansion, and concurrency limits. Subscription WebSockets, voice, and gateway OAuth sign-in are not supported. It does not change the API-key-backed `/v1/responses` endpoint.
## Configure the gateway
@ -14,7 +14,7 @@ LiteLLM forwards requests only to the corresponding endpoint under `https://chat
## Pi
Pi 1.0.4 compresses SSE request bodies when its runtime supports zstd. Direct compressed Pi requests are not supported. Use the configuration below only behind an ingress explicitly configured to decompress requests before forwarding them to LiteLLM. TLS termination or response compression alone is insufficient. The ingress must enforce decompression limits and update the content encoding and length headers.
Pi can send zstd-compressed SSE requests directly to LiteLLM. No ingress decompression configuration is needed when the proxy has its standard zstd decoder installed.
Sign into the built-in `openai-codex` provider through Pi's `/login`. Keep the subscription credential in Pi, not in the gateway configuration.
@ -47,14 +47,7 @@ Pi retains responsibility for its normal ChatGPT login and refresh flow. Restart
## Codex
Use a Codex build supporting OpenAI's [ChatGPT gateway flow](https://developers.openai.com/codex/enterprise/sign-in-with-chatgpt-through-a-gateway). Disable request compression in the client's `config.toml`.
```toml
[features]
enable_request_compression = false
```
This is a client setting, not a LiteLLM gateway setting. Codex selects request compression locally rather than negotiating support from server headers. A client sending `Content-Encoding: zstd` receives HTTP 415 unless an ingress decompresses the request first.
Use a Codex build supporting OpenAI's [ChatGPT gateway flow](https://developers.openai.com/codex/enterprise/sign-in-with-chatgpt-through-a-gateway). Request compression can remain enabled when the proxy has its standard zstd decoder installed.
For a managed workspace, configure the provider in `requirements.toml`.
@ -83,4 +76,4 @@ Subscription credentials are redacted in gateway logging and callback header cop
## Compressed requests
Native zstd request decoding is deferred. Supporting `enable_request_compression = true` requires a maintainer follow-up that declares the zstd dependency and adds bounded decoding before authentication and body parsing. Adding the dependency alone does not enable compressed requests. Other proxy routes retain their existing request-body behavior.
These routes reuse the proxy's shared gzip and zstd decoder rather than installing a subscription-specific decoder. Python versions before 3.14 use the proxy's declared `backports.zstd` dependency. Unsupported or repeated content encodings are rejected. A deployment missing its zstd decoder must install the standard proxy dependencies or disable request compression in the client.

View file

@ -8705,7 +8705,7 @@
},
"/backend-api/codex/responses": {
"post": {
"description": "Relay uncompressed ChatGPT subscription Responses over HTTP/SSE. Set features.enable_request_compression = false in Codex. The client owns login and token refresh.",
"description": "Relay ChatGPT subscription Responses over HTTP/SSE using the proxy's shared request decompression. The client owns login and token refresh.",
"operationId": "codex_responses_backend_api_codex_responses_post",
"requestBody": {
"content": {

View file

@ -25,7 +25,7 @@ async def validate_codex_request(request: Request) -> None:
if any(encoding.strip().lower() != "identity" for encoding in request.headers.getlist("content-encoding")):
raise HTTPException(
status_code=415,
detail="Compressed Codex requests are unsupported. Set features.enable_request_compression = false in Codex.",
detail="Unsupported request content encoding. Send identity, gzip, or zstd with proxy decoding enabled.",
)
custom_header: Final = general_settings_view().get("litellm_key_header_name")
gateway_key: Final = request.headers.get("x-litellm-api-key") or (
@ -73,7 +73,7 @@ async def _relay_codex(
stream=body.get("stream") is True,
custom_llm_provider="openai",
follow_redirects=False,
use_custom_headers_only=True,
upstream_headers_filter=lambda _: headers,
response_owner=owner,
)
@ -95,8 +95,8 @@ async def codex_models(
"/backend-api/codex/responses",
tags=["ChatGPT subscription Pass-through", "pass-through"],
description=(
"Relay uncompressed ChatGPT subscription Responses over HTTP/SSE. "
"Set features.enable_request_compression = false in Codex. The client owns login and token refresh."
"Relay ChatGPT subscription Responses over HTTP/SSE using the proxy's shared request decompression. "
"The client owns login and token refresh."
),
openapi_extra={
"requestBody": {

View file

@ -25,7 +25,11 @@ def _loaded_httpx_content(message: httpx.Request | httpx.Response) -> bytes:
def passthrough_logging_response(response: httpx.Response) -> httpx.Response:
return httpx.Response(
status_code=response.status_code,
headers=response.headers,
headers={
name: value
for name, value in response.headers.items()
if name.lower() not in {"content-encoding", "content-length", "transfer-encoding"}
},
content=_loaded_httpx_content(response),
request=httpx.Request(
response.request.method,

View file

@ -1129,7 +1129,6 @@ async def pass_through_request(
timeout: float | None = None,
upstream_headers_filter: Callable[[Mapping[str, str]], Mapping[str, str]] = _unfiltered_headers,
follow_redirects: bool | None = None,
use_custom_headers_only: bool = False,
response_owner: AsyncExitStack | None = None,
) -> Response:
"""
@ -1179,14 +1178,10 @@ async def pass_through_request(
#########################################################
try:
url = httpx.URL(target)
forwarded_headers: Final = (
custom_headers
if use_custom_headers_only
else HttpPassThroughEndpointHelpers.forward_headers_from_request(
request_headers=safe_get_request_headers(request).copy(),
headers=custom_headers,
forward_headers=forward_headers,
)
forwarded_headers: Final = HttpPassThroughEndpointHelpers.forward_headers_from_request(
request_headers=safe_get_request_headers(request).copy(),
headers=custom_headers,
forward_headers=forward_headers,
)
upstream_headers: Final = _with_trace_context(
upstream_headers_filter(forwarded_headers),

View file

@ -4203,10 +4203,10 @@ class ProxyLogging:
from litellm.proxy.pass_through_endpoints.common_utils import passthrough_logging_response
callback_response: Final = (
passthrough_logging_response(response) if isinstance(response, HTTPXResponse) else response
)
try:
callback_response: Final = (
passthrough_logging_response(response) if isinstance(response, HTTPXResponse) else response
)
# Build litellm_call_info — normalized routing metadata for callbacks
litellm_call_info: Final = self._build_litellm_call_info(data=data, response=response)

View file

@ -1,4 +1,6 @@
import gzip
import json
import sys
from collections.abc import Iterator
from concurrent.futures import ThreadPoolExecutor
from dataclasses import dataclass
@ -19,6 +21,11 @@ from integration._support.process import owned_proxy_process
from integration._support.tls import server_context, write_self_signed_cert
from integration._support.wire import Reply, Request, Wire, wire_server
if sys.version_info >= (3, 14):
from compression import zstd
else:
from backports import zstd
_MODEL: Final = "litellm-test-native-unpriced"
_FALLBACK_MODEL: Final = "litellm-test-native-fallback"
_CATALOG: Final = {"models": [{"slug": _MODEL, "supported_reasoning_levels": ["medium"], "native_field": True}]}
@ -72,6 +79,8 @@ def _reply(request: Request, cancellation: Event) -> Reply:
content_type="text/event-stream",
chunks=(first, last),
gate_after_first=cancellation if marker.startswith("cancel-") else None,
heartbeat=b": keepalive\n\n" if marker.startswith("cancel-") else None,
pause_between_chunks=0.05 if marker.startswith("cancel-") else 0,
headers={"x-request-id": marker, "x-codex-primary-used-percent": "7"},
)
@ -161,18 +170,23 @@ def test_form_media_type_cannot_authorize_a_different_json_model(codex_rig: Code
@pytest.mark.parametrize("encoding", ["zstd", "gzip"])
def test_encoded_requests_are_rejected_without_upstream_traffic(codex_rig: CodexRig, encoding: str) -> None:
def test_compressed_denied_models_never_reach_provider(codex_rig: CodexRig, encoding: str) -> None:
candidate: Final = codex_rig.gateway
marker: Final = uuid4().hex
with candidate.scenario() as scenario:
key: Final = scenario.key(models=[_MODEL])
raw: Final = json.dumps({"model": "synthetic-denied-model", "input": marker}).encode()
encoded: Final = gzip.compress(raw, mtime=0) if encoding == "gzip" else zstd.compress(raw)
response: Final = candidate.client.post(
"/backend-api/codex/responses",
json={"model": _MODEL, "input": marker},
headers={**_headers(key, f"synthetic-{marker}"), "content-encoding": encoding},
content=encoded,
headers={
**_headers(key, f"synthetic-{marker}"),
"content-type": "application/json",
"content-encoding": encoding,
},
)
assert response.status_code == 415, response.text
assert "enable_request_compression = false" in response.json()["detail"]
assert response.status_code in (401, 403), response.text
assert not tuple(
request for request in codex_rig.provider.drain() if marker in request.headers.get("authorization", "")
)
@ -240,8 +254,9 @@ def test_concurrent_callers_rotate_tokens_without_crossing_accounts(codex_rig: C
@pytest.mark.parametrize("stream", [False, True])
@pytest.mark.parametrize("encoding", ["identity", "gzip", "zstd"])
def test_native_usage_is_attributed_and_secrets_are_absent_from_logs_and_rows(
codex_rig: CodexRig, stream: bool
codex_rig: CodexRig, stream: bool, encoding: str
) -> None:
candidate: Final = codex_rig.gateway
marker: Final = uuid4().hex
@ -256,12 +271,17 @@ def test_native_usage_is_attributed_and_secrets_are_absent_from_logs_and_rows(
"stream": stream,
"custom_body": {"target": "https://untrusted.example/collect"},
}
raw: Final = json.dumps(payload).encode()
encoded: Final = (
gzip.compress(raw, mtime=0) if encoding == "gzip" else zstd.compress(raw) if encoding == "zstd" else raw
)
response: Final = candidate.client.post(
"/backend-api/codex/responses",
json=payload,
content=encoded,
headers={
**_headers(key, subscription),
"content-type": "application/json",
"content-encoding": encoding,
"x-alias": f"Bearer {key}",
"x-pass-authorization": f"Bearer {key}",
},
@ -371,16 +391,16 @@ def test_client_cancellation_releases_the_keys_parallel_request_reservation(code
) as response:
assert response.status_code == 200
assert marker.encode() in next(response.iter_bytes())
followup: Final = eventually(
lambda: candidate.client.post(
"/backend-api/codex/responses",
json={"model": _MODEL, "input": marker, "stream": True},
headers=_headers(key, f"synthetic-{marker}"),
),
lambda response: response.status_code != 429,
)
assert followup.status_code == 200, followup.text
assert f"resp_{marker}" in followup.text
assert eventually(codex_rig.provider.open_connections, lambda count: count == 0) == 0
finally:
codex_rig.cancellation.set()
followup: Final = eventually(
lambda: candidate.client.post(
"/backend-api/codex/responses",
json={"model": _MODEL, "input": marker, "stream": True},
headers=_headers(key, f"synthetic-{marker}"),
),
lambda response: response.status_code != 429,
)
assert followup.status_code == 200, followup.text
assert f"resp_{marker}" in followup.text
assert eventually(codex_rig.provider.open_connections, lambda count: count == 0) == 0

View file

@ -1,5 +1,7 @@
import asyncio
import gzip
import json
import sys
from collections.abc import AsyncIterator
from pathlib import Path
from queue import SimpleQueue
@ -20,6 +22,11 @@ from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER
from litellm.proxy._types import UserAPIKeyAuth
from tests._master_key import MASTER_KEY
if sys.version_info >= (3, 14):
from compression import zstd
else:
from backports import zstd
pytestmark: Final = pytest.mark.usefixtures("httpx_transport")
_CREDENTIALS: Final = {"authorization": "Bearer synthetic-subscription", "x-litellm-api-key": MASTER_KEY}
@ -184,7 +191,7 @@ async def test_invalid_json_object_never_contacts_provider(codex_gateway: httpx.
@pytest.mark.asyncio
@pytest.mark.parametrize("encodings", [("zstd",), ("gzip",), ("br",), ("",), ("identity", "zstd")])
@pytest.mark.parametrize("encodings", [("br",), ("",), ("identity", "zstd")])
@pytest.mark.parametrize("authenticated", [False, True])
async def test_encoded_requests_are_rejected_before_reading_or_authentication(
codex_gateway: httpx.AsyncClient, encodings: tuple[str, ...], authenticated: bool
@ -201,11 +208,32 @@ async def test_encoded_requests_are_rejected_before_reading_or_authentication(
),
)
assert response.status_code == 415, response.text
assert "enable_request_compression = false" in response.json()["detail"]
assert "Unsupported request content encoding" in response.json()["detail"]
assert not body.started.is_set()
assert not provider.called
@pytest.mark.asyncio
@pytest.mark.parametrize("encoding", ["gzip", "zstd"])
async def test_compressed_json_is_decoded_before_forwarding(
codex_gateway: httpx.AsyncClient, encoding: str
) -> None:
payload: Final = {"model": "synthetic-native", "input": "hello"}
raw: Final = json.dumps(payload).encode()
encoded: Final = gzip.compress(raw, mtime=0) if encoding == "gzip" else zstd.compress(raw)
with respx.mock() as upstream:
observed: Final = upstream.post(f"{_BASE}/responses").respond(429, json={"error": "synthetic"})
response: Final = await codex_gateway.post(
"/backend-api/codex/responses",
content=encoded,
headers={**_CREDENTIALS, "content-type": "application/json", "content-encoding": encoding},
)
assert response.status_code == 429, response.text
assert json.loads(observed.calls.last.request.content) == payload
assert "content-encoding" not in observed.calls.last.request.headers
assert MASTER_KEY not in str(observed.calls.last.request.headers)
@pytest.mark.asyncio
async def test_gateway_credentials_in_aliases_and_x_pass_headers_cannot_escape(
codex_gateway: httpx.AsyncClient,
@ -268,9 +296,12 @@ async def test_stream_keeps_native_events_ids_usage_and_quota_headers(codex_gate
@pytest.mark.asyncio
@pytest.mark.parametrize("mode", ["catalog", "stream", "failure"])
@pytest.mark.parametrize(
("mode", "encoding"),
[("catalog", "identity"), ("catalog", "gzip"), ("stream", "identity"), ("failure", "identity"), ("failure", "gzip")],
)
async def test_custom_auth_and_callback_copies_cannot_expose_credentials(
codex_gateway: httpx.AsyncClient, tmp_path: Path, mode: str
codex_gateway: httpx.AsyncClient, tmp_path: Path, mode: str, encoding: str
) -> None:
from litellm.proxy.proxy_server import initialize
@ -285,11 +316,15 @@ async def test_custom_auth_and_callback_copies_cannot_expose_credentials(
)
await initialize(config=str(config))
credentials: Final = {"authorization": _CREDENTIALS["authorization"], "x-gateway-key": f"Bearer {MASTER_KEY}"}
raw: Final = b'data: {"type":"response.output_text.delta","delta":"hello"}\n\n' if mode == "stream" else b"{}"
with respx.mock() as upstream:
provider: Final = upstream.route(host="chatgpt.com").respond(
status_code=429 if mode == "failure" else 200,
content=b'data: {"type":"response.output_text.delta","delta":"hello"}\n\n' if mode == "stream" else b"{}",
headers={"content-type": "text/event-stream" if mode == "stream" else "application/json"},
content=gzip.compress(raw, mtime=0) if encoding == "gzip" else raw,
headers={
"content-type": "text/event-stream" if mode == "stream" else "application/json",
"content-encoding": encoding,
},
)
response: Final = await codex_gateway.request(
"GET" if mode == "catalog" else "POST",
@ -303,6 +338,7 @@ async def test_custom_auth_and_callback_copies_cannot_expose_credentials(
headers_observer.observed.get_nowait() for _ in range(headers_observer.observed.qsize())
)
assert response.status_code == (429 if mode == "failure" else 200), response.text
assert response.content == raw
assert response.headers["x-test-headers-observed"] == "1"
assert {stage for stage, _ in observations} == {"pre", "headers", "attached-request"}
assert "synthetic-subscription" not in repr(observations)

View file

@ -1823,7 +1823,7 @@ export interface paths {
put?: never;
/**
* Codex Responses
* @description Relay uncompressed ChatGPT subscription Responses over HTTP/SSE. Set features.enable_request_compression = false in Codex. The client owns login and token refresh.
* @description Relay ChatGPT subscription Responses over HTTP/SSE using the proxy's shared request decompression. The client owns login and token refresh.
*/
post: operations["codex_responses_backend_api_codex_responses_post"];
delete?: never;