From 0b9d5c0a48fb301d2eaf534b70937f20419137dd Mon Sep 17 00:00:00 2001 From: Dmitry Chepurovskiy Date: Thu, 15 Oct 2026 17:04:05 +0300 Subject: [PATCH] feat(proxy): add per-user ChatGPT subscription passthrough Signed-off-by: Dmitry Chepurovskiy --- .../chatgpt_subscription_passthrough.md | 72 ++++ cookbook/ai_coding_tool_guides/index.json | 13 + litellm/llms/chatgpt/common_utils.py | 6 + litellm/proxy/_lazy_features.py | 5 + litellm/proxy/_lazy_openapi_snapshot.json | 76 ++++ litellm/proxy/_types.py | 1 + litellm/proxy/auth/auth_utils.py | 6 +- litellm/proxy/auth/user_api_key_auth.py | 4 +- .../codex_request_decompression_middleware.py | 89 +++++ .../codex_passthrough_endpoints.py | 112 ++++++ .../pass_through_endpoints/common_utils.py | 33 ++ .../llm_passthrough_endpoints.py | 3 + .../openai_passthrough_logging_handler.py | 75 ++-- .../pass_through_endpoints.py | 57 ++- litellm/proxy/proxy_server.py | 2 + litellm/proxy/utils.py | 10 +- pyproject.toml | 2 + .../providers/test_codex_passthrough_wire.py | 329 +++++++++++++++++ tests/unit/proxy/auth/test_auth_utils.py | 17 + .../unit/proxy/auth/test_user_api_key_auth.py | 22 +- ..._codex_request_decompression_middleware.py | 166 +++++++++ ...test_openai_passthrough_logging_handler.py | 36 +- .../test_codex_passthrough_endpoints.py | 332 ++++++++++++++++++ .../test_pass_through_endpoints.py | 28 ++ ...test_passthrough_endpoints_common_utils.py | 23 ++ .../test_success_handler.py | 40 +++ tests/unit/proxy/test__lazy_features.py | 17 + ui/litellm-dashboard/src/lib/http/schema.d.ts | 89 +++++ uv.lock | 4 + 29 files changed, 1609 insertions(+), 60 deletions(-) create mode 100644 cookbook/ai_coding_tool_guides/chatgpt_subscription_passthrough.md create mode 100644 litellm/proxy/middleware/codex_request_decompression_middleware.py create mode 100644 litellm/proxy/pass_through_endpoints/codex_passthrough_endpoints.py create mode 100644 tests/integration/providers/test_codex_passthrough_wire.py create mode 100644 tests/unit/proxy/middleware/test_codex_request_decompression_middleware.py create mode 100644 tests/unit/proxy/pass_through_endpoints/test_codex_passthrough_endpoints.py diff --git a/cookbook/ai_coding_tool_guides/chatgpt_subscription_passthrough.md b/cookbook/ai_coding_tool_guides/chatgpt_subscription_passthrough.md new file mode 100644 index 00000000000..f001d34f246 --- /dev/null +++ b/cookbook/ai_coding_tool_guides/chatgpt_subscription_passthrough.md @@ -0,0 +1,72 @@ +# Use a personal ChatGPT subscription through LiteLLM + +Pi and 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, including zstd-compressed requests. 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 + +Start a proxy with a master key and a database, then create a virtual key for each gateway user through the usual key-management workflow. No `OPENAI_API_KEY`, server-side ChatGPT login, or model deployment is required for these routes. Existing virtual-key model and route restrictions still apply to inference requests. + +Set the client base URL to `https://litellm.example.com/backend-api/codex`. The client sends its ChatGPT token in `Authorization: Bearer ` and its gateway virtual key in `x-litellm-api-key`. If the deployment uses `general_settings.litellm_key_header_name`, send `Bearer ` in that configured header instead. + +LiteLLM forwards requests only to the corresponding endpoint under `https://chatgpt.com/backend-api/codex`, with redirects disabled. Gateway credentials and cookies are not forwarded. `ChatGPT-Account-ID` and client protocol headers are preserved. Missing gateway or subscription credentials are rejected before an upstream request. + +## Pi + +Sign into the built-in `openai-codex` provider through Pi's `/login`. Keep the subscription credential in Pi, not in the gateway configuration. + +Add an override to Pi's `models.json`, merging it with any existing providers. + +```json +{ + "providers": { + "openai-codex": { + "baseUrl": "https://litellm.example.com/backend-api/codex", + "headers": { + "x-litellm-api-key": "${LITELLM_GATEWAY_KEY}" + } + } + } +} +``` + +Set `LITELLM_GATEWAY_KEY` in the environment of the Pi process. Do not replace Pi's subscription credential with the virtual key. Select an available model from the built-in provider with `/model`. + +Set the transport in Pi's `settings.json` to HTTP/SSE. + +```json +{ + "transport": "sse" +} +``` + +Pi retains responsibility for its normal ChatGPT login and refresh flow. Restart Pi after changing its process environment. + +## Codex + +Use a Codex build supporting OpenAI's [ChatGPT gateway flow](https://developers.openai.com/codex/enterprise/sign-in-with-chatgpt-through-a-gateway). For a managed workspace, configure the provider in `requirements.toml`. + +```toml +model_provider = "litellm_subscription" + +[model_providers.litellm_subscription] +name = "LiteLLM subscription gateway" +base_url = "https://litellm.example.com/backend-api/codex" +requires_openai_auth = true +env_http_headers = { "x-litellm-api-key" = "LITELLM_GATEWAY_KEY" } +``` + +Provide the gateway key in the Codex process environment and sign in with ChatGPT normally. Use HTTP/SSE rather than WebSocket-only transport. Older clients might not support these managed settings. This configuration does not install an OAuth server or move ChatGPT login into LiteLLM. + +## Verify routing and usage + +`GET https://litellm.example.com/backend-api/codex/models?client_version=` returns the upstream Codex catalog, including its native `models` array. It is not the gateway's API-backed `/v1/models` catalog. OpenAI determines subscription model availability, while the gateway enforces its inference restrictions separately. + +Send a prompt from Pi or Codex. `POST https://litellm.example.com/backend-api/codex/responses` streams the provider's SSE events without translating the response ID. Open `https://litellm.example.com/ui/?page=logs` and locate the request under the caller's gateway virtual key and user. Token counts come from the terminal Responses usage event. + +Gateway cost estimates are API-equivalent estimates, not subscription invoices, remaining subscription quota, or charges from OpenAI. When a model has no local price, LiteLLM still records its reported token usage with zero estimated cost. + +Subscription credentials are redacted in gateway logging and callback header copies. Keep credentials out of request bodies, URLs, screenshots, shell history, and custom application logs. Do not enable shell tracing or verbose curl output when testing with real credentials. + +Compressed subscription requests have a 32 MiB compressed-input, decoded-output, and decoder-window limit. Malformed or unsupported encodings are rejected. Other proxy routes retain their existing request-body behavior. diff --git a/cookbook/ai_coding_tool_guides/index.json b/cookbook/ai_coding_tool_guides/index.json index 3e71670d623..2e3dea1a146 100644 --- a/cookbook/ai_coding_tool_guides/index.json +++ b/cookbook/ai_coding_tool_guides/index.json @@ -84,6 +84,19 @@ "Quickstart" ] }, +{ + "title": "ChatGPT Subscription Passthrough", + "description": "Use a personal ChatGPT subscription through an authenticated LiteLLM gateway with Pi or Codex.", + "url": "https://github.com/BerriAI/litellm/blob/main/cookbook/ai_coding_tool_guides/chatgpt_subscription_passthrough.md", + "date": "2026-10-14", + "version": "1.0.0", + "tags": [ + "Pi", + "OpenAI Codex CLI", + "ChatGPT", + "LiteLLM" + ] +}, { "title": "OpenWebUI Quickstart", "description": "This is a quickstart guide to using OpenWebUI with LiteLLM.", diff --git a/litellm/llms/chatgpt/common_utils.py b/litellm/llms/chatgpt/common_utils.py index fe33219f110..06c5ec5fa17 100644 --- a/litellm/llms/chatgpt/common_utils.py +++ b/litellm/llms/chatgpt/common_utils.py @@ -5,6 +5,7 @@ Constants and helpers for ChatGPT subscription OAuth. import os import platform from typing import Any, Final +from urllib.parse import urlsplit from uuid import uuid4 import httpx @@ -105,6 +106,11 @@ You are producing plain text that will later be styled by the CLI. Follow these """ +def is_chatgpt_codex_responses_url(url: str) -> bool: + parsed: Final = urlsplit(url) + return parsed.scheme == "https" and parsed.netloc == "chatgpt.com" and parsed.path == "/backend-api/codex/responses" + + class ChatGPTAuthError(BaseLLMException): def __init__( self, diff --git a/litellm/proxy/_lazy_features.py b/litellm/proxy/_lazy_features.py index 0e2eed73364..005dfc52aee 100644 --- a/litellm/proxy/_lazy_features.py +++ b/litellm/proxy/_lazy_features.py @@ -207,6 +207,11 @@ LAZY_FEATURES: Final[tuple[LazyFeature, ...]] = ( module_path="litellm.proxy.management_endpoints.config_override_endpoints", path_prefixes=("/config_overrides",), ), + LazyFeature( + name="codex_passthrough", + module_path="litellm.proxy.pass_through_endpoints.codex_passthrough_endpoints", + path_prefixes=("/backend-api/codex/",), + ), LazyFeature( name="llm_passthrough", module_path="litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints", diff --git a/litellm/proxy/_lazy_openapi_snapshot.json b/litellm/proxy/_lazy_openapi_snapshot.json index 4572e59944b..de128e8866d 100644 --- a/litellm/proxy/_lazy_openapi_snapshot.json +++ b/litellm/proxy/_lazy_openapi_snapshot.json @@ -8673,6 +8673,82 @@ } } }, + "codex_passthrough": { + "components": { + "schemas": {} + }, + "paths": { + "/backend-api/codex/models": { + "get": { + "description": "Forward the signed-in user's native Codex catalog using a separate LiteLLM gateway credential.", + "operationId": "codex_models_backend_api_codex_models_get", + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Codex Models", + "tags": [ + "codex_passthrough" + ] + } + }, + "/backend-api/codex/responses": { + "post": { + "description": "Relay ChatGPT subscription Responses over HTTP/SSE. The client owns login and token refresh.", + "operationId": "codex_responses_backend_api_codex_responses_post", + "requestBody": { + "content": { + "application/json": { + "schema": { + "additionalProperties": true, + "type": "object" + } + } + }, + "required": true + }, + "responses": { + "200": { + "content": { + "application/json": { + "schema": { + "additionalProperties": true, + "type": "object" + } + }, + "text/event-stream": { + "schema": { + "type": "string" + } + } + }, + "description": "The upstream Responses payload or unchanged server-sent events" + } + }, + "security": [ + { + "APIKeyHeader": [] + } + ], + "summary": "Codex Responses", + "tags": [ + "codex_passthrough" + ] + } + } + } + }, "compliance": { "components": { "schemas": { diff --git a/litellm/proxy/_types.py b/litellm/proxy/_types.py index 54acf59ef80..4075537a9cc 100644 --- a/litellm/proxy/_types.py +++ b/litellm/proxy/_types.py @@ -390,6 +390,7 @@ class LiteLLMRoutes(enum.Enum): ] mapped_pass_through_routes = [ + "/backend-api/codex", "/bedrock", "/comprehendmedical", "/azure_speech", diff --git a/litellm/proxy/auth/auth_utils.py b/litellm/proxy/auth/auth_utils.py index 7a186d84aa5..49295e104cc 100644 --- a/litellm/proxy/auth/auth_utils.py +++ b/litellm/proxy/auth/auth_utils.py @@ -2254,7 +2254,11 @@ def request_dispatched_to_pass_through_endpoint(request: Request | None) -> bool def request_dispatched_to_provider_pass_through(request: Request) -> bool: """Built-in provider pass-through handlers (``/anthropic/{endpoint:path}``, ...) bind ``endpoint``.""" - return "endpoint" in request.path_params + return ( + "endpoint" in request.path_params + or getattr(request.scope.get("endpoint"), "__module__", "") + == "litellm.proxy.pass_through_endpoints.codex_passthrough_endpoints" + ) def get_model_from_request( diff --git a/litellm/proxy/auth/user_api_key_auth.py b/litellm/proxy/auth/user_api_key_auth.py index 27fa4731baf..674e192b886 100644 --- a/litellm/proxy/auth/user_api_key_auth.py +++ b/litellm/proxy/auth/user_api_key_auth.py @@ -4382,9 +4382,9 @@ def get_api_key_from_custom_header(request: Request, custom_litellm_key_header_n custom_litellm_key_header_name = custom_litellm_key_header_name.lower() _headers: Final = {k.lower(): v for k, v in request.headers.items()} verbose_proxy_logger.debug( - "searching for custom_litellm_key_header_name= %s, in headers=%s", + "searching for custom_litellm_key_header_name= %s, in header names=%s", custom_litellm_key_header_name, - _headers, + tuple(_headers), ) custom_api_key: Final = _headers.get(custom_litellm_key_header_name) if custom_api_key: diff --git a/litellm/proxy/middleware/codex_request_decompression_middleware.py b/litellm/proxy/middleware/codex_request_decompression_middleware.py new file mode 100644 index 00000000000..5711277fa03 --- /dev/null +++ b/litellm/proxy/middleware/codex_request_decompression_middleware.py @@ -0,0 +1,89 @@ +from io import BytesIO +from typing import Final + +import zstandard +from starlette._utils import get_route_path +from starlette.datastructures import Headers +from starlette.requests import ClientDisconnect, Request +from starlette.responses import JSONResponse +from starlette.types import ASGIApp, Message, Receive, Scope, Send + +CODEX_REQUEST_LIMIT_BYTES: Final = 32 * 1024 * 1024 + + +def decode_codex_body(body: bytes) -> bytes | JSONResponse: + try: + frame: Final = zstandard.get_frame_parameters(body) + if frame.window_size > CODEX_REQUEST_LIMIT_BYTES or ( + frame.content_size != zstandard.CONTENTSIZE_UNKNOWN and frame.content_size > CODEX_REQUEST_LIMIT_BYTES + ): + return JSONResponse({"error": "Codex request exceeds the decompression limit"}, status_code=413) + decoded: Final = zstandard.ZstdDecompressor(max_window_size=CODEX_REQUEST_LIMIT_BYTES).decompress( + body, max_output_size=CODEX_REQUEST_LIMIT_BYTES, allow_extra_data=False + ) + except zstandard.ZstdError: + return JSONResponse({"error": "Invalid or oversized zstd request body"}, status_code=400) + return decoded + + +async def _read_compressed_body(request: Request) -> bytes | JSONResponse | None: + buffer: Final = BytesIO() + try: + async for chunk in request.stream(): + if buffer.tell() + len(chunk) > CODEX_REQUEST_LIMIT_BYTES: + return JSONResponse({"error": "Compressed Codex request is too large"}, status_code=413) + buffer.write(chunk) + except ClientDisconnect: + return None + return buffer.getvalue() + + +class CodexRequestDecompressionMiddleware: + def __init__(self, app: ASGIApp) -> None: + self.app = app + + async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: + if ( + scope["type"] != "http" + or scope["method"] != "POST" + or get_route_path(scope) != "/backend-api/codex/responses" + ): + await self.app(scope, receive, send) + return + headers: Final = Headers(scope=scope) + encoding: Final = headers.get("content-encoding", "identity").strip().lower() + if encoding == "identity": + await self.app(scope, receive, send) + return + if encoding != "zstd": + await JSONResponse({"error": "Unsupported Codex request encoding"}, status_code=415)(scope, receive, send) + return + compressed: Final = await _read_compressed_body(Request(scope, receive)) + if compressed is None: + return + if isinstance(compressed, JSONResponse): + await compressed(scope, receive, send) + return + decoded: Final = decode_codex_body(compressed) + if isinstance(decoded, JSONResponse): + await decoded(scope, receive, send) + return + + body: Final = iter((decoded,)) + + async def decoded_receive() -> Message: + try: + chunk: Final = next(body) + except StopIteration: + return await receive() + return {"type": "http.request", "body": chunk, "more_body": False} + + decoded_scope: Final[Scope] = { + **scope, + "headers": [ + (name, value) + for name, value in headers.raw + if name.lower() not in {b"content-encoding", b"content-length"} + ], + } + await self.app(decoded_scope, decoded_receive, send) diff --git a/litellm/proxy/pass_through_endpoints/codex_passthrough_endpoints.py b/litellm/proxy/pass_through_endpoints/codex_passthrough_endpoints.py new file mode 100644 index 00000000000..66459fa361d --- /dev/null +++ b/litellm/proxy/pass_through_endpoints/codex_passthrough_endpoints.py @@ -0,0 +1,112 @@ +from collections.abc import AsyncIterator +from contextlib import AsyncExitStack +from typing import Annotated, Final, Literal + +from fastapi import APIRouter, Depends, HTTPException, Request, Response +from pydantic import TypeAdapter, ValidationError +from starlette.responses import JSONResponse + +from litellm.llms.chatgpt.common_utils import CHATGPT_API_BASE +from litellm.proxy._types import SpecialHeaders, UserAPIKeyAuth +from litellm.proxy.auth.user_api_key_auth import user_api_key_auth +from litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints import caller_headers_without_litellm_secrets +from litellm.proxy.pass_through_endpoints.pass_through_endpoints import pass_through_request + +router: Final = APIRouter() +_NEVER_FORWARDED: Final = frozenset( + {"host", "content-length", "content-encoding", "accept-encoding", "cookie", "connection", "transfer-encoding"} +) | (SpecialHeaders.litellm_credential_header_names() - {"authorization"}) +_BODY: Final = TypeAdapter(dict[str, object]) + + +def require_codex_credentials(request: Request) -> None: + from litellm.proxy.proxy_server import general_settings_view + + custom_header: Final = general_settings_view().get("litellm_key_header_name") + gateway_key: Final = request.headers.get("x-litellm-api-key") or ( + request.headers.get(custom_header) if isinstance(custom_header, str) else None + ) + if not gateway_key: + raise HTTPException(status_code=401, detail="A separate LiteLLM gateway credential is required") + scheme, _, token = request.headers.get("authorization", "").partition(" ") + if scheme.lower() != "bearer" or not token.strip(): + raise HTTPException(status_code=401, detail="A ChatGPT subscription bearer token is required") + + +async def codex_gateway_auth( + request: Request, + _: Annotated[None, Depends(require_codex_credentials)], + user: Annotated[UserAPIKeyAuth, Depends(user_api_key_auth)], +) -> UserAPIKeyAuth: + return user + + +async def codex_response_lifetime() -> AsyncIterator[AsyncExitStack]: + async with AsyncExitStack() as owner: + yield owner + + +async def _relay_codex( + request: Request, user: UserAPIKeyAuth, endpoint: Literal["models", "responses"], owner: AsyncExitStack +) -> Response: + headers: Final = caller_headers_without_litellm_secrets(request, user, _NEVER_FORWARDED) + if "authorization" not in headers: + raise HTTPException(status_code=401, detail="The ChatGPT credential must differ from the gateway credential") + raw: Final = await request.body() + try: + body: Final = _BODY.validate_json(raw) if raw else {} + except ValidationError: + return JSONResponse({"error": "A JSON object is required"}, status_code=400) + return await pass_through_request( + request=request, + target=f"{CHATGPT_API_BASE}/{endpoint}", + custom_headers=dict(headers), + user_api_key_dict=user, + custom_body=body, + stream=body.get("stream") is True, + custom_llm_provider="openai", + follow_redirects=False, + use_custom_headers_only=True, + response_owner=owner, + ) + + +@router.get( + "/backend-api/codex/models", + tags=["ChatGPT subscription Pass-through", "pass-through"], + description="Forward the signed-in user's native Codex catalog using a separate LiteLLM gateway credential.", +) +async def codex_models( + request: Request, + user: Annotated[UserAPIKeyAuth, Depends(codex_gateway_auth)], + owner: Annotated[AsyncExitStack, Depends(codex_response_lifetime, scope="request")], +) -> Response: + return await _relay_codex(request, user, "models", owner) + + +@router.post( + "/backend-api/codex/responses", + tags=["ChatGPT subscription Pass-through", "pass-through"], + description="Relay ChatGPT subscription Responses over HTTP/SSE. The client owns login and token refresh.", + openapi_extra={ + "requestBody": { + "required": True, + "content": {"application/json": {"schema": {"type": "object", "additionalProperties": True}}}, + } + }, + responses={ + 200: { + "description": "The upstream Responses payload or unchanged server-sent events", + "content": { + "application/json": {"schema": {"type": "object", "additionalProperties": True}}, + "text/event-stream": {"schema": {"type": "string"}}, + }, + } + }, +) +async def codex_responses( + request: Request, + user: Annotated[UserAPIKeyAuth, Depends(codex_gateway_auth)], + owner: Annotated[AsyncExitStack, Depends(codex_response_lifetime, scope="request")], +) -> Response: + return await _relay_codex(request, user, "responses", owner) diff --git a/litellm/proxy/pass_through_endpoints/common_utils.py b/litellm/proxy/pass_through_endpoints/common_utils.py index 3ae83cbe906..babfcdf3eff 100644 --- a/litellm/proxy/pass_through_endpoints/common_utils.py +++ b/litellm/proxy/pass_through_endpoints/common_utils.py @@ -1,7 +1,40 @@ +from collections.abc import Mapping from typing import Final +import httpx from fastapi import Request +from litellm.proxy._types import UserAPIKeyAuth +from litellm.proxy.litellm_pre_call_utils import redact_credential_headers + + +def passthrough_logging_headers(request: Request, user: UserAPIKeyAuth) -> Mapping[str, str]: + from litellm.proxy.pass_through_endpoints.llm_passthrough_endpoints import caller_headers_without_litellm_secrets + + return redact_credential_headers(caller_headers_without_litellm_secrets(request, user, frozenset())) + + +def _loaded_httpx_content(message: httpx.Request | httpx.Response) -> bytes: + try: + content: Final = message.content + except (httpx.RequestNotRead, httpx.ResponseNotRead): + return b"" + return content + + +def passthrough_logging_response(response: httpx.Response) -> httpx.Response: + return httpx.Response( + status_code=response.status_code, + headers=response.headers, + content=_loaded_httpx_content(response), + request=httpx.Request( + response.request.method, + response.request.url, + headers=redact_credential_headers(response.request.headers), + content=_loaded_httpx_content(response.request), + ), + ) + def get_litellm_virtual_key(request: Request) -> str: """ diff --git a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py index 16fbd1de376..42ce3c908db 100644 --- a/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py +++ b/litellm/proxy/pass_through_endpoints/llm_passthrough_endpoints.py @@ -2806,6 +2806,9 @@ def _caller_headers_without_litellm_secrets( ) +caller_headers_without_litellm_secrets: Final = _caller_headers_without_litellm_secrets + + def _forwarded_headers_for_credentialless_vertex_passthrough( request: Request, user_api_key_dict: UserAPIKeyAuth ) -> Mapping[str, str]: diff --git a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/openai_passthrough_logging_handler.py b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/openai_passthrough_logging_handler.py index c763b5dc26e..a0f0169bd48 100644 --- a/litellm/proxy/pass_through_endpoints/llm_provider_handlers/openai_passthrough_logging_handler.py +++ b/litellm/proxy/pass_through_endpoints/llm_provider_handlers/openai_passthrough_logging_handler.py @@ -10,6 +10,7 @@ from typing import Final, Literal, TypeAlias from urllib.parse import urlparse import httpx +from pydantic import TypeAdapter import litellm from litellm._logging import verbose_proxy_logger @@ -20,6 +21,7 @@ from litellm.litellm_core_utils.litellm_logging import ( get_standard_logging_object_payload, ) from litellm.litellm_core_utils.token_counter import high_detail_image_token_upper_bound +from litellm.llms.chatgpt.common_utils import is_chatgpt_codex_responses_url from litellm.llms.openai.openai import OpenAIConfig from litellm.llms.openai.openai import OpenAIConfig as OpenAIConfigType from litellm.llms.openai.responses.transformation import OpenAIResponsesAPIConfig @@ -91,6 +93,8 @@ def is_openai_compatible_url(url_route: str | None) -> bool: """ if not url_route: return False + if is_chatgpt_codex_responses_url(url_route): + return True parsed_url: Final = urlparse(url_route) hostname: Final = parsed_url.hostname if not hostname: @@ -155,6 +159,18 @@ def count_relayed_prompt_tokens(model: str, messages: Sequence[Mapping[str, obje ) +def _responses_cost( + response: ResponsesAPIResponse | ModelResponse | TextCompletionResponse, model: str, provider: str +) -> float: + try: + return litellm.completion_cost( + completion_response=response, model=model, custom_llm_provider=provider, call_type="responses" + ) + except Exception as exc: # noqa: BLE001 # missing prices must not discard provider-reported usage + verbose_proxy_logger.warning("Could not price Responses usage for %s: %s", model, exc) + return 0.0 + + class OpenAIPassthroughLoggingHandler(BasePassthroughLoggingHandler): """ OpenAI-specific passthrough logging handler that provides cost tracking for /chat/completions endpoints. @@ -198,8 +214,9 @@ class OpenAIPassthroughLoggingHandler(BasePassthroughLoggingHandler): if not url_route: return False parsed_url: Final = urlparse(url_route) - return _is_openai_compatible_host(parsed_url.hostname) and ( - "/v1/responses" in parsed_url.path or "/responses" in parsed_url.path + return is_chatgpt_codex_responses_url(url_route) or ( + _is_openai_compatible_host(parsed_url.hostname) + and ("/v1/responses" in parsed_url.path or "/responses" in parsed_url.path) ) @staticmethod @@ -359,12 +376,7 @@ class OpenAIPassthroughLoggingHandler(BasePassthroughLoggingHandler): raw_response=httpx_response, logging_obj=logging_obj, ) - response_cost: Final = litellm.completion_cost( - completion_response=litellm_model_response, - model=model, - custom_llm_provider=custom_llm_provider, - call_type="responses", - ) + response_cost: Final = _responses_cost(litellm_model_response, model, custom_llm_provider) return litellm_model_response, response_cost @staticmethod @@ -708,12 +720,7 @@ class OpenAIPassthroughLoggingHandler(BasePassthroughLoggingHandler): custom_llm_provider: Final = litellm_logging_obj.model_call_details.get("custom_llm_provider", "openai") # Calculate cost using LiteLLM's cost calculator response_cost: Final = ( - litellm.completion_cost( - completion_response=complete_response, - model=model, - custom_llm_provider=custom_llm_provider, - call_type="responses", - ) + _responses_cost(complete_response, model, custom_llm_provider) if is_responses else litellm.completion_cost( completion_response=complete_response, @@ -730,11 +737,21 @@ class OpenAIPassthroughLoggingHandler(BasePassthroughLoggingHandler): else None ) - # Preserve existing litellm_params to maintain metadata tags - existing_litellm_params: Final = litellm_logging_obj.model_call_details.get("litellm_params", {}) or {} - litellm_params: Final = existing_litellm_params.copy() - - # Prepare kwargs for logging + existing_litellm_params: Final = TypeAdapter(dict[str, object]).validate_python( + litellm_logging_obj.model_call_details.get("litellm_params", {}) or {} + ) + passthrough_logging_payload: Final[PassthroughStandardLoggingPayload | None] = ( + litellm_logging_obj.model_call_details.get("passthrough_logging_payload") + ) + user: Final = ( + handler_instance._get_user_from_metadata(passthrough_logging_payload=passthrough_logging_payload) + if passthrough_logging_payload + else None + ) + proxy_request: Final = TypeAdapter(dict[str, object]).validate_python( + existing_litellm_params.get("proxy_server_request", {}) + ) + proxy_body: Final = TypeAdapter(dict[str, object]).validate_python(proxy_request.get("body", {})) kwargs: Final = { "response_cost": response_cost, SETTLES_BACKGROUND_RESPONSE_KWARG: settles_background_response, @@ -742,20 +759,16 @@ class OpenAIPassthroughLoggingHandler(BasePassthroughLoggingHandler): "custom_llm_provider": custom_llm_provider, "call_type": litellm_logging_obj.call_type, "messages": litellm_logging_obj.model_call_details.get("messages"), - "litellm_params": litellm_params, + "litellm_params": { + **existing_litellm_params, + **( + {"proxy_server_request": {**proxy_request, "body": {**proxy_body, "user": user}}} + if user + else {} + ), + }, } - # Extract user information for tracking - passthrough_logging_payload: Final[PassthroughStandardLoggingPayload | None] = ( - litellm_logging_obj.model_call_details.get("passthrough_logging_payload") - ) - if passthrough_logging_payload: - user: Final = handler_instance._get_user_from_metadata( - passthrough_logging_payload=passthrough_logging_payload, - ) - if user: - litellm_params.setdefault("proxy_server_request", {}).setdefault("body", {})["user"] = user - # Attach the payload to kwargs so the success handler adopts it; # its later rebuild runs on a copy whose Responses usage was # coerced to chat shape and serializes as total_tokens only, diff --git a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py index e1e8864678e..63e9858f718 100644 --- a/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py +++ b/litellm/proxy/pass_through_endpoints/pass_through_endpoints.py @@ -6,6 +6,7 @@ import posixpath import traceback from base64 import b64encode from collections.abc import AsyncGenerator, AsyncIterator, Callable, Iterable, Mapping, Sequence +from contextlib import AsyncExitStack from dataclasses import dataclass from datetime import datetime from itertools import chain, count, groupby @@ -62,7 +63,6 @@ from litellm.litellm_core_utils.core_helpers import ( from litellm.litellm_core_utils.initialize_dynamic_callback_params import validate_no_callback_env_reference from litellm.litellm_core_utils.internal_call_metadata import MODEL_ACCESS_GROUP_METADATA_KEY from litellm.litellm_core_utils.litellm_logging import Logging as LiteLLMLoggingObj -from litellm.litellm_core_utils.litellm_logging import get_masked_values from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER from litellm.litellm_core_utils.redact_messages import should_redact_message_logging from litellm.litellm_core_utils.safe_json_dumps import safe_dumps @@ -70,6 +70,7 @@ from litellm.llms.anthropic.common_utils import is_anthropic_messages_url from litellm.llms.base_llm.managed_resources.utils import ( resolve_passthrough_managed_id_provider, ) +from litellm.llms.chatgpt.common_utils import is_chatgpt_codex_responses_url from litellm.llms.custom_httpx.http_handler import get_async_httpx_client from litellm.llms.oss_decision import validate_oss_request from litellm.passthrough import BasePassthroughUtils @@ -118,7 +119,9 @@ from litellm.proxy.litellm_pre_call_utils import ( # noqa: F401 # legacy modul _key_or_team_allows_client_pricing_override, # pyright: ignore[reportPrivateUsage] # reuse the proxy's pricing trust policy _strip_client_pricing_overrides, # pyright: ignore[reportPrivateUsage] # sanitize before trusted hooks add guardrail costs get_dynamic_logging_metadata, # pyright: ignore[reportPrivateUsage] # shared proxy helper, same import style as _read_request_body above + redact_credential_headers, ) +from litellm.proxy.pass_through_endpoints.common_utils import passthrough_logging_headers from litellm.proxy.route_llm_request import ProxyModelNotFoundError from litellm.proxy.route_priority import ( builtin_pass_through_routes_first, @@ -423,7 +426,8 @@ class HttpPassThroughEndpointHelpers(BasePassthroughUtils): elif is_anthropic_messages_url(url): return EndpointType.ANTHROPIC elif ( - parsed_url.hostname == "api.openai.com" + is_chatgpt_codex_responses_url(url) + or parsed_url.hostname == "api.openai.com" or parsed_url.hostname == "openai.azure.com" or (parsed_url.hostname and "openai.com" in parsed_url.hostname) ): @@ -723,7 +727,7 @@ class HttpPassThroughEndpointHelpers(BasePassthroughUtils): "url": str(request.url), "method": request.method, "body": copy.copy(_parsed_body), # use copy instead of deepcopy - "headers": request.headers, + "headers": passthrough_logging_headers(request, user_api_key_dict), }, }, "call_type": "pass_through_endpoint", @@ -1111,12 +1115,12 @@ def _unfiltered_headers(headers: Mapping[str, str]) -> Mapping[str, str]: async def pass_through_request( request: Request, target: str, - custom_headers: dict, + custom_headers: dict[str, str], user_api_key_dict: UserAPIKeyAuth, - custom_body: dict | None = None, + custom_body: dict[str, object] | None = None, forward_headers: bool | None = False, merge_query_params: bool | None = False, - query_params: dict | None = None, + query_params: dict[str, object] | None = None, default_query_params: dict | None = None, stream: bool | None = None, cost_per_request: float | None = None, @@ -1124,7 +1128,10 @@ async def pass_through_request( guardrails_config: dict | None = None, 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: """ Pass through endpoint handler, makes the httpx request for pass-through endpoints and ensures logging hooks are called @@ -1172,10 +1179,14 @@ async def pass_through_request( ######################################################### try: url = httpx.URL(target) - forwarded_headers: Final = HttpPassThroughEndpointHelpers.forward_headers_from_request( - request_headers=safe_get_request_headers(request).copy(), - headers=custom_headers, - forward_headers=forward_headers, + 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, + ) ) upstream_headers: Final = _with_trace_context( upstream_headers_filter(forwarded_headers), @@ -1216,7 +1227,7 @@ async def pass_through_request( verbose_proxy_logger.debug( "Pass through endpoint sending request to \nURL %s\nheaders: %s\nbody: %s\n", url, - get_masked_values(upstream_headers), + redact_credential_headers(upstream_headers), _parsed_body, ) @@ -1310,7 +1321,10 @@ async def pass_through_request( resolved_timeout: Final = resolve_pass_through_request_timeout(timeout) async_client_obj: Final = get_async_httpx_client( llm_provider=httpxSpecialProvider.PassThroughEndpoint, - params={"timeout": resolved_timeout}, + params={ + "timeout": resolved_timeout, + **({"follow_redirects": follow_redirects} if follow_redirects is not None else {}), + }, ) async_client: Final = async_client_obj.client passthrough_logging_payload: Final = PassthroughStandardLoggingPayload( @@ -1490,7 +1504,7 @@ async def pass_through_request( additional_args={ "complete_input_dict": _parsed_body, "api_base": str(logging_url), - "headers": upstream_headers, + "headers": redact_credential_headers(upstream_headers), }, ) stream = HttpPassThroughEndpointHelpers.update_stream_param_based_on_request_body( @@ -1534,6 +1548,9 @@ async def pass_through_request( response = await async_client.send(req, stream=stream) + if response_owner is not None: + response_owner.push_async_callback(response.aclose) + upstream_usage = apply_upstream_reported_usage( logging_obj=logging_obj, headers=response.headers, @@ -1561,7 +1578,7 @@ async def pass_through_request( data=_parsed_body or {}, user_api_key_dict=user_api_key_dict, response=relay_response, - request_headers=dict(request.headers), + request_headers=dict(passthrough_logging_headers(request, user_api_key_dict)), ) if callback_headers: _response_headers.update(callback_headers) @@ -1620,6 +1637,8 @@ async def pass_through_request( _parsed_body=_parsed_body, forward_multipart=is_multipart, ) + if response_owner is not None: + response_owner.push_async_callback(response.aclose) verbose_proxy_logger.debug("response.headers= %s", response.headers) upstream_usage = apply_upstream_reported_usage( @@ -1653,7 +1672,7 @@ async def pass_through_request( data=_parsed_body or {}, user_api_key_dict=user_api_key_dict, response=detected_relay_response, - request_headers=dict(request.headers), + request_headers=dict(passthrough_logging_headers(request, user_api_key_dict)), ) if callback_headers: _response_headers.update(callback_headers) @@ -1703,7 +1722,7 @@ async def pass_through_request( data=_parsed_body or {}, user_api_key_dict=user_api_key_dict, response=response, - request_headers=dict(request.headers), + request_headers=dict(passthrough_logging_headers(request, user_api_key_dict)), ) if relay_callback_headers: relay_custom_headers.update(relay_callback_headers) @@ -1878,7 +1897,7 @@ async def pass_through_request( data=_parsed_body or {}, user_api_key_dict=user_api_key_dict, response=response, - request_headers=dict(request.headers), + request_headers=dict(passthrough_logging_headers(request, user_api_key_dict)), ) if callback_headers: custom_headers.update(callback_headers) @@ -2266,7 +2285,7 @@ def create_pass_through_route( return await pass_through_request( request=request, target=full_target, - custom_headers=headers_dict, + custom_headers=TypeAdapter(dict[str, str]).validate_python(headers_dict), user_api_key_dict=user_api_key_dict, forward_headers=cast(bool | None, param_forward_headers), merge_query_params=cast(bool | None, param_merge_query_params), diff --git a/litellm/proxy/proxy_server.py b/litellm/proxy/proxy_server.py index f632317d9a8..51e75dea6b2 100644 --- a/litellm/proxy/proxy_server.py +++ b/litellm/proxy/proxy_server.py @@ -832,6 +832,7 @@ from litellm.proxy.middleware.admission_control_middleware import ( admission_control_state, get_admission_control_settings, ) +from litellm.proxy.middleware.codex_request_decompression_middleware import CodexRequestDecompressionMiddleware from litellm.proxy.middleware.gzip_middleware import GZipBufferedResponseMiddleware from litellm.proxy.middleware.in_flight_requests_middleware import ( InFlightRequestsMiddleware, @@ -2827,6 +2828,7 @@ app.add_middleware(LensInternalMiddleware) app.add_middleware(InFlightRequestsMiddleware) app.add_middleware(SecurityHeadersMiddleware) app.add_middleware(GZipBufferedResponseMiddleware) +app.add_middleware(CodexRequestDecompressionMiddleware) def mount_swagger_ui(): diff --git a/litellm/proxy/utils.py b/litellm/proxy/utils.py index 28be11509ae..553ced981ef 100644 --- a/litellm/proxy/utils.py +++ b/litellm/proxy/utils.py @@ -51,6 +51,7 @@ from typing import ( import anyio import httpx +from httpx import Response as HTTPXResponse from typing_extensions import Never, ReadOnly, TypedDict from litellm import _custom_logger_compatible_callbacks_literal @@ -4200,6 +4201,11 @@ class ProxyLogging: if not ProxyLogging.callback_capabilities().has_post_call_response_headers: return merged_headers + 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: # Build litellm_call_info — normalized routing metadata for callbacks litellm_call_info: Final = self._build_litellm_call_info(data=data, response=response) @@ -4218,7 +4224,7 @@ class ProxyLogging: result = await _callback.async_post_call_response_headers_hook( data=data, user_api_key_dict=user_api_key_dict, - response=response, + response=callback_response, request_headers=request_headers, litellm_call_info=litellm_call_info, ) @@ -4227,7 +4233,7 @@ class ProxyLogging: result = await _callback.async_post_call_response_headers_hook( data=data, user_api_key_dict=user_api_key_dict, - response=response, + response=callback_response, request_headers=request_headers, ) if result is not None: diff --git a/pyproject.toml b/pyproject.toml index 3aefd911937..74bc5ffe845 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -63,6 +63,7 @@ proxy = [ "pyyaml>=6.0.3,<7.0", "rq>=2.7.0,<3.0", "orjson>=3.11.6,<4.0", + "zstandard>=0.25.0,<1.0", # redis-py's C response parser. It arrives with redis (via rq) either way; naming # it here is what makes redis-py select _HiredisParser instead of the Python one. "hiredis>=3.0.0,<4.0", @@ -251,6 +252,7 @@ admin-mcp = [ ] proxy-dev = [ { include-group = "admin-mcp" }, + "zstandard==0.25.0", "prisma==0.11.0", "hypercorn==0.17.3", "prometheus-client==0.20.0", diff --git a/tests/integration/providers/test_codex_passthrough_wire.py b/tests/integration/providers/test_codex_passthrough_wire.py new file mode 100644 index 00000000000..d8058d42d08 --- /dev/null +++ b/tests/integration/providers/test_codex_passthrough_wire.py @@ -0,0 +1,329 @@ +import json +from collections.abc import Iterator +from concurrent.futures import ThreadPoolExecutor +from dataclasses import dataclass +from hashlib import sha256 +from pathlib import Path +from threading import Event +from typing import Final +from urllib.parse import urlsplit +from uuid import uuid4 + +import httpx +import pytest +import yaml +import zstandard +from integration._support.client import Gateway, eventually +from integration._support.database import read_rows +from integration._support.forward_proxy import ForwardProxy, tunnelling_forward_proxy +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 + +_MODEL: Final = "litellm-test-native-unpriced" +_CATALOG: Final = {"models": [{"slug": _MODEL, "supported_reasoning_levels": ["medium"], "native_field": True}]} + + +@dataclass(frozen=True, slots=True) +class CodexRig: + gateway: Gateway + provider: Wire + sink: Wire + tunnel: ForwardProxy + log: Path + cancellation: Event + + +def _reply(request: Request, cancellation: Event) -> Reply: + if request.target.startswith("/backend-api/codex/models"): + return Reply(body=json.dumps(_CATALOG).encode(), headers={"x-request-id": "native-catalog"}) + body: Final = json.loads(request.body) + marker: Final = body["input"] + if marker.startswith("redirect-"): + return Reply( + status=307, body=b'{"error":"redirect"}', headers={"location": "https://untrusted.example/collect"} + ) + if marker.startswith("unauthorized-"): + return Reply(status=401, body=b'{"error":{"message":"synthetic expired token"}}') + if marker.startswith("error-"): + return Reply(status=429, body=b'{"error":{"message":"synthetic quota"}}', headers={"retry-after": "3"}) + terminal: Final = { + "id": f"resp_{marker}", + "object": "response", + "created_at": 1786374786, + "model": _MODEL, + "status": "completed", + "output": [ + { + "id": f"msg_{marker}", + "type": "message", + "role": "assistant", + "status": "completed", + "content": [{"type": "output_text", "text": marker, "annotations": []}], + } + ], + "usage": {"input_tokens": 11, "output_tokens": 4, "total_tokens": 15}, + } + if not body.get("stream"): + return Reply(body=json.dumps(terminal).encode(), headers={"x-request-id": marker}) + first: Final = f'event: response.output_text.delta\ndata: {{"type":"response.output_text.delta","delta":"{marker}"}}\n\n'.encode() + last: Final = f"event: response.completed\ndata: {json.dumps({'type': 'response.completed', 'response': terminal})}\n\n".encode() + return Reply( + content_type="text/event-stream", + chunks=(first, last), + gate_after_first=cancellation if marker.startswith("cancel-") else None, + headers={"x-request-id": marker, "x-codex-primary-used-percent": "7"}, + ) + + +@pytest.fixture(scope="module") +def codex_rig(session_gateway: Gateway, tmp_path_factory: pytest.TempPathFactory) -> Iterator[CodexRig]: + directory: Final = tmp_path_factory.mktemp("codex-native") + cert, key = write_self_signed_cert(directory, ("chatgpt.com",)) + cancellation: Final = Event() + + def reply(request: Request) -> Reply: + return _reply(request, cancellation) + + def callback(_: Request) -> Reply: + return Reply() + + with wire_server(reply, tls=server_context(cert, key)) as provider, wire_server(callback) as sink: + port: Final = urlsplit(provider.url).port + assert port is not None + with tunnelling_forward_proxy(port) as tunnel: + config: Final = directory / "codex.yaml" + config.write_text( + yaml.safe_dump( + { + "general_settings": { + "master_key": "os.environ/LITELLM_MASTER_KEY", + "database_url": "os.environ/DATABASE_URL", + "store_prompts_in_spend_logs": True, + "proxy_batch_write_at": 1, + }, + "litellm_settings": { + "callbacks": ["generic_api"], + "DEFAULT_FLUSH_INTERVAL_SECONDS": 1, + "model_alias_map": {_MODEL: "must-not-rewrite"}, + "disable_aiohttp_transport": True, + }, + "model_list": [ + { + "model_name": _MODEL, + "litellm_params": {"model": f"openai/{_MODEL}", "api_key": "synthetic-unused"}, + } + ], + } + ) + ) + with owned_proxy_process( + session_gateway, + directory, + { + "HTTPS_PROXY": tunnel.url, + "SSL_VERIFY": str(cert), + "SSL_CERT_FILE": str(cert), + "NO_PROXY": "127.0.0.1,localhost,::1", + "GENERIC_LOGGER_ENDPOINT": sink.url, + "LITELLM_LOG": "DEBUG", + }, + config=config, + ) as owned: + yield CodexRig(owned.gateway, provider, sink, tunnel, owned.log, cancellation) + cancellation.set() + + +def _headers(key: str, subscription: str) -> dict[str, str]: + return { + "x-litellm-api-key": key, + "authorization": f"Bearer {subscription}", + "chatgpt-account-id": f"account-{sha256(subscription.encode()).hexdigest()}", + } + + +def test_concurrent_callers_rotate_tokens_without_crossing_accounts(codex_rig: CodexRig) -> None: + candidate: Final = codex_rig.gateway + marker: Final = uuid4().hex + with candidate.scenario() as scenario: + first: Final = scenario.key(models=[_MODEL]) + second: Final = scenario.key(models=[_MODEL]) + callers: Final = ( + (first, f"synthetic-a-{marker}"), + (second, f"synthetic-b-{marker}"), + (first, f"synthetic-rotated-{marker}"), + ) + + def catalog(caller: tuple[str, str]) -> httpx.Response: + return candidate.client.get( + "/backend-api/codex/models?client_version=synthetic-version", headers=_headers(*caller) + ) + + with ThreadPoolExecutor(max_workers=3) as pool: + responses: Final = tuple(pool.map(catalog, callers)) + assert tuple(response.json() for response in responses) == (_CATALOG,) * len(callers) + observed: Final = tuple( + request for request in codex_rig.provider.drain() if marker in request.headers.get("authorization", "") + ) + assert len(observed) == len(callers) + assert {request.headers["authorization"] for request in observed} == {f"Bearer {token}" for _, token in callers} + for request in observed: + subscription: Final = request.headers["authorization"].removeprefix("Bearer ") + assert request.headers["chatgpt-account-id"] == _headers("unused", subscription)["chatgpt-account-id"] + assert request.target == "/backend-api/codex/models?client_version=synthetic-version" + assert first not in str(request.headers) and second not in str(request.headers) + assert all(target == "chatgpt.com:443" for target in codex_rig.tunnel.targets()) + + +@pytest.mark.parametrize("stream", [False, True]) +def test_native_usage_is_attributed_and_secrets_are_absent_from_logs_and_rows( + codex_rig: CodexRig, stream: bool +) -> None: + candidate: Final = codex_rig.gateway + marker: Final = uuid4().hex + subscription: Final = f"synthetic-subscription-{marker}" + with candidate.scenario() as scenario: + team: Final = scenario.team(models=[_MODEL]) + user: Final = scenario.user() + key: Final = scenario.key(models=[_MODEL], user_id=user, team_id=team) + payload: Final = { + "model": _MODEL, + "input": marker, + "stream": stream, + "custom_body": {"target": "https://untrusted.example/collect"}, + } + response: Final = candidate.client.post( + "/backend-api/codex/responses", + content=zstandard.ZstdCompressor().compress(json.dumps(payload).encode()), + headers={ + **_headers(key, subscription), + "content-encoding": "zstd", + "content-type": "application/json", + "x-alias": f"Bearer {key}", + "x-pass-authorization": f"Bearer {key}", + }, + ) + assert response.status_code == 200, response.text + assert marker in response.text + assert f"resp_{marker}" in response.text + assert response.headers["x-request-id"] == marker + observed: Final = tuple(request for request in codex_rig.provider.drain() if marker.encode() in request.body) + assert len(observed) == 1 + assert json.loads(observed[0].body) == payload + assert observed[0].headers["authorization"] == f"Bearer {subscription}" + assert key not in str(observed[0].headers) + assert "content-encoding" not in observed[0].headers + rows: Final = eventually( + lambda: read_rows( + 'SELECT api_key, "user", team_id, prompt_tokens, completion_tokens, total_tokens, spend, metadata FROM "LiteLLM_SpendLogs" WHERE request_id=%s', + (f"resp_{marker}",), + ), + lambda rows: len(rows) == 1, + seconds=30, + ) + assert rows[0]["api_key"] == sha256(key.encode()).hexdigest() + assert rows[0]["user"] == user + assert rows[0]["team_id"] == team + assert (rows[0]["prompt_tokens"], rows[0]["completion_tokens"], rows[0]["total_tokens"], rows[0]["spend"]) == ( + 11, + 4, + 15, + 0.0, + ) + assert subscription not in str(rows) and key not in str(rows) + batches: Final = eventually( + lambda: tuple(codex_rig.sink.drain()), + lambda batches: any(marker.encode() in request.body for request in batches), + seconds=15, + ) + assert subscription not in str(batches) and key not in str(batches) + assert subscription not in codex_rig.log.read_text() + assert key not in codex_rig.log.read_text() + + +def test_denied_compressed_models_and_invalid_keys_never_reach_provider(codex_rig: CodexRig) -> None: + candidate: Final = codex_rig.gateway + marker: Final = uuid4().hex + with candidate.scenario() as scenario: + key: Final = scenario.key(models=[_MODEL]) + denied: Final = candidate.client.post( + "/backend-api/codex/responses", + content=zstandard.ZstdCompressor().compress( + json.dumps({"model": "synthetic-denied-model", "input": marker}).encode() + ), + headers={ + **_headers(key, f"synthetic-{marker}"), + "content-encoding": "zstd", + "content-type": "application/json", + }, + ) + invalid: Final = candidate.client.get( + "/backend-api/codex/models", headers=_headers("synthetic-invalid-key", marker) + ) + missing: Final = candidate.client.get( + "/backend-api/codex/models", headers={"authorization": f"Bearer {marker}"} + ) + route_key: Final = scenario.key(models=[_MODEL], allowed_routes=["/chat/completions"]) + denied_route: Final = candidate.client.post( + "/backend-api/codex/responses", + json={"model": _MODEL, "input": marker}, + headers=_headers(route_key, f"synthetic-{marker}"), + ) + assert denied_route.status_code in {401, 403}, denied_route.text + assert denied.status_code in {401, 403}, denied.text + assert invalid.status_code in {401, 403}, invalid.text + assert missing.status_code == 401 + assert not any( + marker.encode() in request.body or marker in str(request.headers) for request in codex_rig.provider.drain() + ) + + +@pytest.mark.parametrize("prefix,status", [("redirect", 307), ("error", 429), ("unauthorized", 401)]) +def test_upstream_errors_and_redirects_are_not_followed(codex_rig: CodexRig, prefix: str, status: int) -> None: + candidate: Final = codex_rig.gateway + marker: Final = f"{prefix}-{uuid4().hex}" + subscription: Final = f"synthetic-secret-{uuid4().hex}" + with candidate.scenario() as scenario: + key: Final = scenario.key(models=[_MODEL]) + response: Final = candidate.client.post( + "/backend-api/codex/responses", json={"model": _MODEL, "input": marker}, headers=_headers(key, subscription) + ) + assert response.status_code == status, response.text + expected: Final = { + "redirect": "redirect", + "error": {"message": "synthetic quota"}, + "unauthorized": {"message": "synthetic expired token"}, + } + assert response.json()["error"] == expected[prefix] + tunnels: Final = codex_rig.tunnel.targets() + assert all(target == "chatgpt.com:443" for target in tunnels) + assert subscription not in codex_rig.log.read_text() + + +def test_client_cancellation_releases_the_keys_parallel_request_reservation(codex_rig: CodexRig) -> None: + candidate: Final = codex_rig.gateway + marker: Final = uuid4().hex + with candidate.scenario() as scenario: + key: Final = scenario.key(models=[_MODEL], max_parallel_requests=1) + try: + with candidate.client.stream( + "POST", + "/backend-api/codex/responses", + json={"model": _MODEL, "input": f"cancel-{marker}", "stream": True}, + headers=_headers(key, f"synthetic-{marker}"), + ) as response: + assert response.status_code == 200 + assert marker.encode() in next(response.iter_bytes()) + 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 diff --git a/tests/unit/proxy/auth/test_auth_utils.py b/tests/unit/proxy/auth/test_auth_utils.py index ee1ae43fd3a..8b9aa6838d9 100644 --- a/tests/unit/proxy/auth/test_auth_utils.py +++ b/tests/unit/proxy/auth/test_auth_utils.py @@ -40,6 +40,23 @@ from litellm.types.utils import oauth_token_exchange_litellm_params, server_owne from litellm.types.workload_identity import ANTHROPIC_WIF_KWARGS_KEYS, OPENAI_WIF_KWARGS_KEYS +def test_codex_subscription_model_remains_visible_to_gateway_access_and_budget_checks() -> None: + from litellm.proxy.pass_through_endpoints.codex_passthrough_endpoints import codex_responses + + request: Final = Request( + { + "type": "http", + "method": "POST", + "path": "/backend-api/codex/responses", + "endpoint": codex_responses, + "headers": [], + } + ) + assert get_model_from_request( + {"model": "synthetic-native"}, request.url.path, request=request + ) == "synthetic-native" + + @pytest.mark.parametrize( "field", [ diff --git a/tests/unit/proxy/auth/test_user_api_key_auth.py b/tests/unit/proxy/auth/test_user_api_key_auth.py index 60a8dd73a34..9c1d06ebaf3 100644 --- a/tests/unit/proxy/auth/test_user_api_key_auth.py +++ b/tests/unit/proxy/auth/test_user_api_key_auth.py @@ -506,6 +506,26 @@ async def test_auth_not_connected_to_db(): assert valid_token.token == "failed-to-connect-to-db" +def test_custom_key_auth_diagnostics_never_include_header_values(caplog: pytest.LogCaptureFixture) -> None: + from starlette.requests import Request as StarletteRequest + + request: Final = StarletteRequest( + { + "type": "http", + "headers": [ + (b"x-custom-key", b"Bearer synthetic-gateway-secret"), + (b"authorization", b"Bearer synthetic-subscription-secret"), + ], + } + ) + with caplog.at_level(logging.DEBUG, logger=verbose_proxy_logger.name): + result: Final = get_api_key_from_custom_header(request=request, custom_litellm_key_header_name="x-custom-key") + assert result == "synthetic-gateway-secret" + assert "x-custom-key" in caplog.text + assert "synthetic-gateway-secret" not in caplog.text + assert "synthetic-subscription-secret" not in caplog.text + + def _assert_api_key_from_custom_header(headers, custom_header_name, expected_api_key): verbose_proxy_logger.setLevel(logging.DEBUG) request = MagicMock(spec=Request) @@ -548,8 +568,6 @@ def test_get_api_key_from_custom_header_different_casing(): ) - - @pytest.mark.parametrize( "user_role, auth_user_id, requested_user_id, expected_result", [ diff --git a/tests/unit/proxy/middleware/test_codex_request_decompression_middleware.py b/tests/unit/proxy/middleware/test_codex_request_decompression_middleware.py new file mode 100644 index 00000000000..274595e11a8 --- /dev/null +++ b/tests/unit/proxy/middleware/test_codex_request_decompression_middleware.py @@ -0,0 +1,166 @@ +from queue import SimpleQueue +from typing import Final + +import pytest +import zstandard +from starlette.applications import Starlette +from starlette.middleware import Middleware +from starlette.requests import Request +from starlette.responses import JSONResponse +from starlette.routing import Route +from starlette.testclient import TestClient +from starlette.types import Message, Receive, Scope, Send + +from litellm.proxy.middleware.codex_request_decompression_middleware import ( + CODEX_REQUEST_LIMIT_BYTES, + CodexRequestDecompressionMiddleware, +) + +_BODY: Final = b'{"model":"test-native","stream":true}' + + +async def _echo(request: Request) -> JSONResponse: + return JSONResponse( + { + "body": (await request.body()).hex(), + "encoding": request.headers.get("content-encoding"), + "length": request.headers.get("content-length"), + } + ) + + +def _client(root_path: str = "") -> TestClient: + return TestClient( + Starlette( + routes=[ + Route("/backend-api/codex/responses", _echo, methods=["POST"]), + Route("/v1/responses", _echo, methods=["POST"]), + ], + middleware=[Middleware(CodexRequestDecompressionMiddleware)], + ), + root_path=root_path, + ) + + +@pytest.mark.asyncio +async def test_empty_decoded_body_is_delivered_once_then_disconnect_is_preserved() -> None: + incoming: Final = iter( + ( + {"type": "http.request", "body": zstandard.ZstdCompressor().compress(b""), "more_body": False}, + {"type": "http.disconnect"}, + ) + ) + observed: Final[SimpleQueue[Message]] = SimpleQueue() + + async def receive() -> Message: + return next(incoming) + + async def send(_: Message) -> None: + return None + + async def downstream(scope: Scope, receive: Receive, send: Send) -> None: + observed.put(await receive()) + observed.put(await receive()) + + await CodexRequestDecompressionMiddleware(downstream)( + { + "type": "http", + "method": "POST", + "path": "/backend-api/codex/responses", + "headers": [(b"content-encoding", b"zstd")], + }, + receive, + send, + ) + assert observed.get_nowait() == {"type": "http.request", "body": b"", "more_body": False} + assert observed.get_nowait() == {"type": "http.disconnect"} + + +@pytest.mark.parametrize("root_path", ["", "/gateway"]) +def test_decodes_before_body_consumers_and_clears_stale_headers(root_path: str) -> None: + encoded: Final = zstandard.ZstdCompressor().compress(_BODY) + with _client(root_path) as client: + response: Final = client.post( + f"{root_path}/backend-api/codex/responses", content=encoded, headers={"content-encoding": "zstd"} + ) + assert response.status_code == 200 + assert response.json() == {"body": _BODY.hex(), "encoding": None, "length": None} + + +@pytest.mark.parametrize("encoded", [b"invalid", zstandard.ZstdCompressor().compress(_BODY)[:-1]]) +def test_invalid_frames_never_reach_body_consumer(encoded: bytes) -> None: + with _client() as client: + response: Final = client.post( + "/backend-api/codex/responses", content=encoded, headers={"content-encoding": "zstd"} + ) + assert response.status_code == 400 + assert "error" in response.json() + + +def test_extra_frames_are_rejected() -> None: + encoded: Final = zstandard.ZstdCompressor().compress(_BODY) + with _client() as client: + response: Final = client.post( + "/backend-api/codex/responses", content=encoded + encoded, headers={"content-encoding": "zstd"} + ) + assert response.status_code == 400 + + +@pytest.mark.parametrize("encoding", ["gzip", "zstd, gzip"]) +def test_unsupported_encodings_are_rejected(encoding: str) -> None: + with _client() as client: + response: Final = client.post( + "/backend-api/codex/responses", content=_BODY, headers={"content-encoding": encoding} + ) + assert response.status_code == 415 + + +def test_decoded_body_limit_is_enforced() -> None: + encoded: Final = zstandard.ZstdCompressor().compress(b"x" * (CODEX_REQUEST_LIMIT_BYTES + 1)) + with _client() as client: + response: Final = client.post( + "/backend-api/codex/responses", content=encoded, headers={"content-encoding": "zstd"} + ) + assert response.status_code == 413 + + +def test_valid_medium_unknown_content_size_frame_is_not_mistaken_for_an_oversized_window() -> None: + body: Final = b'{"input":"' + b"x" * (64 * 1024) + b'"}' + parameters: Final = zstandard.ZstdCompressionParameters.from_level(1, window_log=20, write_content_size=0) + compressor: Final = zstandard.ZstdCompressor(compression_params=parameters).compressobj() + encoded: Final = compressor.compress(body) + compressor.flush() + with _client() as client: + response: Final = client.post( + "/backend-api/codex/responses", content=encoded, headers={"content-encoding": "zstd"} + ) + assert response.status_code == 200, response.text + assert response.json()["body"] == body.hex() + + +def test_decoder_window_is_bounded_even_when_content_size_is_unknown() -> None: + parameters: Final = zstandard.ZstdCompressionParameters.from_level(1, window_log=26, write_content_size=0) + compressor: Final = zstandard.ZstdCompressor(compression_params=parameters).compressobj() + encoded: Final = compressor.compress(_BODY) + compressor.flush() + with _client() as client: + response: Final = client.post( + "/backend-api/codex/responses", content=encoded, headers={"content-encoding": "zstd"} + ) + assert response.status_code == 413 + + +def test_compressed_input_limit_is_enforced() -> None: + with _client() as client: + response: Final = client.post( + "/backend-api/codex/responses", + content=b"x" * (CODEX_REQUEST_LIMIT_BYTES + 1), + headers={"content-encoding": "zstd"}, + ) + assert response.status_code == 413 + + +@pytest.mark.parametrize("path,encoding", [("/v1/responses", "zstd"), ("/backend-api/codex/responses", "identity")]) +def test_other_routes_and_identity_requests_are_not_rewritten(path: str, encoding: str) -> None: + with _client() as client: + response: Final = client.post(path, content=_BODY, headers={"content-encoding": encoding}) + assert response.status_code == 200 + assert response.json() == {"body": _BODY.hex(), "encoding": encoding, "length": str(len(_BODY))} diff --git a/tests/unit/proxy/pass_through_endpoints/llm_provider_handlers/test_openai_passthrough_logging_handler.py b/tests/unit/proxy/pass_through_endpoints/llm_provider_handlers/test_openai_passthrough_logging_handler.py index c9064caf929..6a29b031c76 100644 --- a/tests/unit/proxy/pass_through_endpoints/llm_provider_handlers/test_openai_passthrough_logging_handler.py +++ b/tests/unit/proxy/pass_through_endpoints/llm_provider_handlers/test_openai_passthrough_logging_handler.py @@ -1922,12 +1922,16 @@ class TestOpenAIPassthroughResponsesStreamingSpendLog: logging_obj.model_call_details["custom_llm_provider"] = "openai" return logging_obj - def test_streamed_responses_passthrough_spend_log_is_priced(self, local_model_cost_map): + @pytest.mark.parametrize( + "url_route", + ["https://api.openai.com/v1/responses", "https://chatgpt.com/backend-api/codex/responses"], + ) + def test_streamed_responses_passthrough_spend_log_is_priced(self, local_model_cost_map, url_route): """The spend row books the same tokens, spend and `resp_` id as the buffered call.""" result = OpenAIPassthroughLoggingHandler._handle_logging_openai_collected_chunks( litellm_logging_obj=self._logging_obj(), passthrough_success_handler_obj=None, - url_route="https://api.openai.com/v1/responses", + url_route=url_route, request_body={ "model": "gpt-4o-mini", "input": "Say hi in one word.", @@ -1975,10 +1979,36 @@ class TestOpenAIPassthroughResponsesStreamingSpendLog: start_time=self.start_time, end_time=self.end_time, ) - assert spend_log_row["model"] == self.MODEL_MAP_KEY assert spend_log_row["spend"] == pytest.approx(self._expected_spend()) + def test_unpriced_codex_responses_preserve_terminal_usage(self) -> None: + from typing import Final + + native_model: Final = "litellm-test-native-unpriced" + result: Final = OpenAIPassthroughLoggingHandler._handle_logging_openai_collected_chunks( + litellm_logging_obj=self._logging_obj(), + passthrough_success_handler_obj=None, + url_route="https://chatgpt.com/backend-api/codex/responses", + request_body={"model": native_model, "input": "hi", "stream": True}, + endpoint_type=None, + start_time=self.start_time, + all_chunks=[chunk.replace(self.MODEL_MAP_KEY, native_model) for chunk in self._responses_stream_chunks()], + end_time=self.end_time, + ) + spend_log_row: Final = get_logging_payload( + kwargs=result["kwargs"], + response_obj=result["result"], + start_time=self.start_time, + end_time=self.end_time, + ) + assert spend_log_row["prompt_tokens"] == self.INPUT_TOKENS + assert spend_log_row["completion_tokens"] == self.OUTPUT_TOKENS + assert spend_log_row["total_tokens"] == self.INPUT_TOKENS + self.OUTPUT_TOKENS + assert spend_log_row["request_id"] == self.RESPONSE_ID + assert spend_log_row["model"] == native_model + assert spend_log_row["spend"] == 0.0 + class TestOpenAIPassthroughEmbeddingsSpendLog: """An OpenAI-passthrough `/v1/embeddings` call must write a priced spend log row diff --git a/tests/unit/proxy/pass_through_endpoints/test_codex_passthrough_endpoints.py b/tests/unit/proxy/pass_through_endpoints/test_codex_passthrough_endpoints.py new file mode 100644 index 00000000000..74b99287ec0 --- /dev/null +++ b/tests/unit/proxy/pass_through_endpoints/test_codex_passthrough_endpoints.py @@ -0,0 +1,332 @@ +import asyncio +import json +from collections.abc import AsyncIterator +from pathlib import Path +from queue import SimpleQueue +from threading import Event +from typing import Final + +import httpx +import pytest +import pytest_asyncio +import respx +import zstandard +from fastapi import FastAPI +from starlette.types import Message, Receive, Scope, Send + +from litellm.caching.dual_cache import DualCache +from litellm.integrations.custom_logger import CustomLogger +from litellm.litellm_core_utils.litellm_logging import Logging +from litellm.litellm_core_utils.logging_worker import GLOBAL_LOGGING_WORKER +from litellm.proxy._types import UserAPIKeyAuth +from tests._master_key import MASTER_KEY + +pytestmark: Final = pytest.mark.usefixtures("httpx_transport") + +_CREDENTIALS: Final = {"authorization": "Bearer synthetic-subscription", "x-litellm-api-key": MASTER_KEY} +_BASE: Final = "https://chatgpt.com/backend-api/codex" + + +class HeaderObserver(CustomLogger): + def __init__(self) -> None: + super().__init__() + self.observed: Final[SimpleQueue[tuple[str, str]]] = SimpleQueue() + + async def async_pre_call_hook( + self, user_api_key_dict: UserAPIKeyAuth, cache: DualCache, data: dict[str, object], call_type: str + ) -> dict[str, object]: + logging_obj: Final = data.get("litellm_logging_obj") + if isinstance(logging_obj, Logging): + logging_obj.add_dynamic_callback(self) + return data + + def log_pre_api_call(self, model: object, messages: object, kwargs: object) -> None: + self.observed.put(("pre", repr(kwargs))) + + async def async_post_call_response_headers_hook( + self, + data: object, + user_api_key_dict: UserAPIKeyAuth, + response: object, + request_headers: dict[str, str] | None = None, + litellm_call_info: dict[str, object] | None = None, + ) -> dict[str, str]: + self.observed.put(("headers", repr(request_headers))) + if isinstance(response, httpx.Response): + self.observed.put(("attached-request", repr(response.request.headers))) + return {"x-test-headers-observed": "1"} + + +headers_observer: Final = HeaderObserver() + + +@pytest_asyncio.fixture +async def codex_gateway(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> AsyncIterator[httpx.AsyncClient]: + from litellm.proxy.proxy_server import app, initialize + + monkeypatch.setenv("PYTHON_DOTENV_DISABLED", "1") + monkeypatch.delenv("DATABASE_URL", raising=False) + config: Final = tmp_path / "proxy.yaml" + config.write_text( + json.dumps( + { + "general_settings": {"master_key": MASTER_KEY}, + "litellm_settings": {"model_alias_map": {"synthetic-native": "must-not-rewrite"}}, + } + ) + ) + await initialize(config=str(config)) + async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://gateway") as client: + yield client + try: + await asyncio.wait_for(GLOBAL_LOGGING_WORKER.flush(), timeout=10) + finally: + await GLOBAL_LOGGING_WORKER.stop() + + +@pytest.mark.asyncio +async def test_native_catalog_and_query_with_separate_credentials(codex_gateway: httpx.AsyncClient) -> None: + catalog: Final = {"models": [{"slug": "synthetic-native-model", "custom_field": {"effort": ["medium"]}}]} + with respx.mock() as upstream: + observed: Final = upstream.get(f"{_BASE}/models", params={"client_version": "synthetic-version"}).respond( + json=catalog, headers={"x-request-id": "catalog-request", "x-codex-primary-used-percent": "7"} + ) + response: Final = await codex_gateway.get( + "/backend-api/codex/models?client_version=synthetic-version", + headers={**_CREDENTIALS, "chatgpt-account-id": "synthetic-account", "cookie": "session=synthetic-cookie"}, + ) + assert response.status_code == 200, response.text + assert response.json() == catalog + assert response.headers["x-request-id"] == "catalog-request" + assert response.headers["x-codex-primary-used-percent"] == "7" + assert observed.calls.last.request.headers["authorization"] == _CREDENTIALS["authorization"] + assert observed.calls.last.request.headers["chatgpt-account-id"] == "synthetic-account" + assert MASTER_KEY not in str(observed.calls.last.request.headers) + assert "cookie" not in observed.calls.last.request.headers + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "headers", + [ + {}, + {"authorization": _CREDENTIALS["authorization"]}, + {"x-litellm-api-key": MASTER_KEY}, + {**_CREDENTIALS, "x-litellm-api-key": "synthetic-invalid-key"}, + {**_CREDENTIALS, "authorization": f"Bearer {MASTER_KEY}"}, + ], +) +async def test_missing_invalid_or_shared_credentials_never_contact_provider( + codex_gateway: httpx.AsyncClient, headers: dict[str, str] +) -> None: + with respx.mock(assert_all_called=False) as upstream: + provider: Final = upstream.get(f"{_BASE}/models").respond(json={"models": []}) + response: Final = await codex_gateway.get("/backend-api/codex/models", headers=headers) + assert response.is_client_error, response.text + assert not provider.called + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [307, 401, 429]) +async def test_status_body_and_headers_are_relayed_without_redirects( + codex_gateway: httpx.AsyncClient, status: int +) -> None: + payload: Final = {"error": {"message": "synthetic-provider-error", "type": "synthetic-error"}} + with respx.mock(assert_all_called=False) as upstream: + observed: Final = upstream.post(f"{_BASE}/responses").respond( + status, json=payload, headers={"location": "https://untrusted.example/collect", "retry-after": "3"} + ) + redirect: Final = upstream.post("https://untrusted.example/collect").respond(200) + response: Final = await codex_gateway.post( + "/backend-api/codex/responses", headers=_CREDENTIALS, json={"model": "synthetic-native", "input": "hello"} + ) + assert observed.called + assert not redirect.called + assert response.status_code == status, response.text + assert response.json() == payload + assert response.headers["retry-after"] == "3" + + +@pytest.mark.asyncio +async def test_compressed_native_envelope_is_not_interpreted_as_relay_configuration( + codex_gateway: httpx.AsyncClient, +) -> None: + payload: Final = { + "model": "synthetic-native", + "input": "hello", + "custom_body": {"target": "https://untrusted.example/collect"}, + "query_params": {"target": "https://untrusted.example/collect"}, + } + with respx.mock() as upstream: + observed: Final = upstream.post(f"{_BASE}/responses").respond(429, json={"error": {"message": "synthetic"}}) + response: Final = await codex_gateway.post( + "/backend-api/codex/responses", + content=zstandard.ZstdCompressor().compress(json.dumps(payload).encode()), + headers={**_CREDENTIALS, "content-type": "application/json", "content-encoding": "zstd"}, + ) + 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 + + +@pytest.mark.asyncio +async def test_gateway_credentials_in_aliases_and_x_pass_headers_cannot_escape( + codex_gateway: httpx.AsyncClient, +) -> None: + with respx.mock() as upstream: + observed: Final = upstream.get(f"{_BASE}/models").respond(json={"models": []}) + response: Final = await codex_gateway.get( + "/backend-api/codex/models", + headers={ + **_CREDENTIALS, + "x-alias": f"Bearer {MASTER_KEY}", + "x-api-key": MASTER_KEY, + "x-pass-authorization": f"Bearer {MASTER_KEY}", + "x-pass-chatgpt-account-id": "cannot-replace-account", + "chatgpt-account-id": "real-account", + }, + ) + assert response.status_code == 200, response.text + assert MASTER_KEY not in str(observed.calls.last.request.headers) + assert observed.calls.last.request.headers["chatgpt-account-id"] == "real-account" + + +@pytest.mark.asyncio +async def test_stream_keeps_native_events_ids_usage_and_quota_headers(codex_gateway: httpx.AsyncClient) -> None: + terminal: Final = { + "type": "response.completed", + "response": { + "id": "resp_litellm_test_native", + "object": "response", + "created_at": 1786374786, + "model": "litellm-test-native-unpriced", + "status": "completed", + "output": [], + "usage": {"input_tokens": 5, "output_tokens": 2, "total_tokens": 7}, + }, + } + events: Final = ( + 'event: response.output_text.delta\ndata: {"type":"response.output_text.delta","delta":"hello"}\n\n' + f"event: response.completed\ndata: {json.dumps(terminal)}\n\n" + ).encode() + with respx.mock() as upstream: + observed: Final = upstream.post(f"{_BASE}/responses").respond( + content=events, + headers={ + "content-type": "text/event-stream", + "x-request-id": "native-stream", + "x-codex-primary-used-percent": "8", + }, + ) + response: Final = await codex_gateway.post( + "/backend-api/codex/responses", + headers=_CREDENTIALS, + json={"model": "litellm-test-native-unpriced", "input": "hello", "stream": True}, + ) + assert response.status_code == 200, response.text + assert response.content == events + assert response.headers["x-request-id"] == "native-stream" + assert response.headers["x-codex-primary-used-percent"] == "8" + assert json.loads(observed.calls.last.request.content)["model"] == terminal["response"]["model"] + + +@pytest.mark.asyncio +@pytest.mark.parametrize("mode", ["catalog", "stream", "failure"]) +async def test_custom_auth_and_callback_copies_cannot_expose_credentials( + codex_gateway: httpx.AsyncClient, tmp_path: Path, mode: str +) -> None: + from litellm.proxy.proxy_server import initialize + + config: Final = tmp_path / "custom-auth.yaml" + config.write_text( + json.dumps( + { + "general_settings": {"master_key": MASTER_KEY, "litellm_key_header_name": "x-gateway-key"}, + "litellm_settings": {"callbacks": [f"{__name__}.headers_observer"]}, + } + ) + ) + await initialize(config=str(config)) + credentials: Final = {"authorization": _CREDENTIALS["authorization"], "x-gateway-key": f"Bearer {MASTER_KEY}"} + 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"}, + ) + response: Final = await codex_gateway.request( + "GET" if mode == "catalog" else "POST", + "/backend-api/codex/models" if mode == "catalog" else "/backend-api/codex/responses", + headers=credentials, + json=None + if mode == "catalog" + else {"model": "synthetic-native", "stream": mode == "stream", "input": "hello"}, + ) + observations: Final = tuple( + 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.headers["x-test-headers-observed"] == "1" + assert {stage for stage, _ in observations} == {"pre", "headers", "attached-request"} + assert "synthetic-subscription" not in repr(observations) + assert MASTER_KEY not in repr(observations) + assert provider.calls.last.request.headers["authorization"] == credentials["authorization"] + assert MASTER_KEY not in str(provider.calls.last.request.headers) + + +class ObservedUpstreamStream(httpx.AsyncByteStream): + def __init__(self) -> None: + self.started: Final = Event() + self.closed: Final = Event() + + async def __aiter__(self) -> AsyncIterator[bytes]: + self.started.set() + yield b'data: {"type":"response.output_text.delta","delta":"hello"}\n\n' + + async def aclose(self) -> None: + self.closed.set() + + +@pytest.mark.asyncio +async def test_upstream_is_closed_if_downstream_header_delivery_fails_before_iteration( + codex_gateway: httpx.AsyncClient, +) -> None: + from litellm.proxy.pass_through_endpoints.codex_passthrough_endpoints import router + + isolated: Final = FastAPI() + isolated.include_router(router) + + async def broken_downstream(scope: Scope, receive: Receive, send: Send) -> None: + async def fail_start(message: Message) -> None: + if message["type"] == "http.response.start": + raise OSError("synthetic downstream header failure") + await send(message) + + await isolated(scope, receive, fail_start) + + stream: Final = ObservedUpstreamStream() + with respx.mock() as upstream: + upstream.post(f"{_BASE}/responses").mock( + return_value=httpx.Response(200, headers={"content-type": "text/event-stream"}, stream=stream) + ) + async with httpx.AsyncClient( + transport=httpx.ASGITransport(app=broken_downstream), base_url="http://gateway" + ) as client: + with pytest.raises(OSError, match="synthetic downstream header failure"): + await client.post( + "/backend-api/codex/responses", + headers=_CREDENTIALS, + json={"model": "synthetic-native", "input": "hello", "stream": True}, + ) + assert not stream.started.is_set() + assert stream.closed.is_set() + + +@pytest.mark.asyncio +@pytest.mark.parametrize("path", ["/backend-api/codex/login", "/backend-api/codex/responses/arbitrary-id"]) +async def test_only_native_allowlisted_endpoints_exist(codex_gateway: httpx.AsyncClient, path: str) -> None: + with respx.mock(assert_all_called=False) as upstream: + provider: Final = upstream.route().respond(200) + response: Final = await codex_gateway.post(path, headers=_CREDENTIALS, json={}) + assert response.status_code == 404 + assert not provider.called diff --git a/tests/unit/proxy/pass_through_endpoints/test_pass_through_endpoints.py b/tests/unit/proxy/pass_through_endpoints/test_pass_through_endpoints.py index db0a74d360a..df395caec90 100644 --- a/tests/unit/proxy/pass_through_endpoints/test_pass_through_endpoints.py +++ b/tests/unit/proxy/pass_through_endpoints/test_pass_through_endpoints.py @@ -8075,6 +8075,34 @@ async def test_user_defined_passthrough_is_neither_tracked_nor_enforced(metadata }) +def test_codex_passthrough_snapshot_redacts_credentials_and_keeps_gateway_attribution() -> None: + from litellm.proxy.pass_through_endpoints.codex_passthrough_endpoints import codex_responses + + request: Final = Request( + { + "type": "http", "method": "POST", "path": "/backend-api/codex/responses", "query_string": b"", + "endpoint": codex_responses, + "headers": [(b"authorization", b"Bearer synthetic-subscription"), (b"x-litellm-api-key", b"synthetic-gateway")], + } + ) + start: Final = datetime.now() + logging_obj: Final = LiteLLMLoggingObj( + model="synthetic-native", messages=[], stream=False, call_type="pass_through_endpoint", start_time=start, + litellm_call_id="codex-snapshot", function_id="codex-snapshot", kwargs={}, + ) + payload: Final = {"url": "https://chatgpt.com/backend-api/codex/responses", "request_method": "POST", "request_body": {"model": "synthetic-native"}} + kwargs: Final = HttpPassThroughEndpointHelpers._init_kwargs_for_pass_through_endpoint( + request=request, user_api_key_dict=UserAPIKeyAuth(user_id="synthetic-user", team_id="synthetic-team"), + passthrough_logging_payload=payload, logging_obj=logging_obj, _parsed_body={"model": "synthetic-native"}, + ) + snapshot: Final = kwargs["litellm_params"]["proxy_server_request"] + assert "synthetic-subscription" not in repr(snapshot) + assert "synthetic-gateway" not in repr(snapshot) + assert kwargs["litellm_params"]["metadata"]["user_api_key_user_id"] == "synthetic-user" + assert kwargs["litellm_params"]["metadata"]["user_api_key_team_id"] == "synthetic-team" + assert request.headers["authorization"] == "Bearer synthetic-subscription" + + @pytest.mark.parametrize("metadata_slot", ["metadata", "litellm_metadata"]) def test_builtin_passthrough_pins_model_group_to_the_resolved_model(metadata_slot: str) -> None: request: Final = Request({ diff --git a/tests/unit/proxy/pass_through_endpoints/test_passthrough_endpoints_common_utils.py b/tests/unit/proxy/pass_through_endpoints/test_passthrough_endpoints_common_utils.py index 078bd4dd402..601bd867942 100644 --- a/tests/unit/proxy/pass_through_endpoints/test_passthrough_endpoints_common_utils.py +++ b/tests/unit/proxy/pass_through_endpoints/test_passthrough_endpoints_common_utils.py @@ -16,6 +16,29 @@ from unittest.mock import Mock from litellm.proxy.pass_through_endpoints.common_utils import get_litellm_virtual_key +def test_passthrough_logging_headers_redact_credentials_without_changing_the_request() -> None: + from typing import Final + + from litellm.proxy._types import UserAPIKeyAuth + from litellm.proxy.pass_through_endpoints.common_utils import passthrough_logging_headers + + request: Final = Request( + { + "type": "http", + "headers": [ + (b"authorization", b"Bearer synthetic-subscription"), + (b"x-litellm-api-key", b"synthetic-gateway"), + (b"chatgpt-account-id", b"synthetic-account"), + ], + } + ) + logged: Final = passthrough_logging_headers(request, UserAPIKeyAuth()) + assert "synthetic-subscription" not in repr(logged) + assert "synthetic-gateway" not in repr(logged) + assert logged["chatgpt-account-id"] == "synthetic-account" + assert request.headers["authorization"] == "Bearer synthetic-subscription" + + @pytest.mark.asyncio async def test_get_litellm_virtual_key(): """ diff --git a/tests/unit/proxy/pass_through_endpoints/test_success_handler.py b/tests/unit/proxy/pass_through_endpoints/test_success_handler.py index 2cc03949ff1..5f395c89beb 100644 --- a/tests/unit/proxy/pass_through_endpoints/test_success_handler.py +++ b/tests/unit/proxy/pass_through_endpoints/test_success_handler.py @@ -587,6 +587,46 @@ _FIRST_TURN_USAGE: Final = {"promptTokenCount": 10, "candidatesTokenCount": 4, " _SECOND_TURN_USAGE: Final = {"promptTokenCount": 30, "candidatesTokenCount": 6, "totalTokenCount": 36} +def test_codex_native_responses_normalize_provider_usage_instead_of_falling_through() -> None: + from litellm.types.llms.openai import ResponsesAPIResponse + + body: Final = { + "id": "resp_litellm_native_usage", + "object": "response", + "created_at": 1786374786, + "model": "litellm-test-native-unpriced", + "status": "completed", + "output": [], + "usage": {"input_tokens": 11, "output_tokens": 4, "total_tokens": 15}, + } + url: Final = "https://chatgpt.com/backend-api/codex/responses" + logging_obj: Final = LiteLLMLoggingObj( + model="litellm-test-native-unpriced", + messages=[], + stream=False, + call_type="pass_through_endpoint", + start_time=_START, + litellm_call_id="native-usage", + function_id="native-usage", + ) + normalized: Final = PassThroughEndpointLogging().normalize_llm_passthrough_logging_payload( + httpx_response=httpx.Response(200, request=httpx.Request("POST", url), json=body), + response_body=body, + request_body={"model": body["model"]}, + logging_obj=logging_obj, + url_route=url, + result=json.dumps(body), + start_time=_START, + end_time=_END, + cache_hit=False, + ) + response: Final = TypeAdapter(ResponsesAPIResponse).validate_python(normalized["standard_logging_response_object"]) + assert response.id == body["id"] + assert response.usage is not None + assert (response.usage.input_tokens, response.usage.output_tokens, response.usage.total_tokens) == (11, 4, 15) + assert logging_obj.model_call_details["response_cost"] == 0.0 + + def _logging_obj() -> LiteLLMLoggingObj: return LiteLLMLoggingObj( model="unknown", diff --git a/tests/unit/proxy/test__lazy_features.py b/tests/unit/proxy/test__lazy_features.py index adc4de8c8fa..41148aaaf72 100644 --- a/tests/unit/proxy/test__lazy_features.py +++ b/tests/unit/proxy/test__lazy_features.py @@ -23,6 +23,23 @@ FLAG: Final = "LITELLM_DISABLE_LAZY_ROUTES" WARMUP_PATH: Final = "/lazy/warm/{name}" +@pytest.mark.parametrize("root_path", ("", "/gateway")) +@pytest.mark.parametrize("disable_lazy_routes", ("false", "true")) +def test_codex_routes_enforce_credentials_on_cold_requests( + monkeypatch: pytest.MonkeyPatch, root_path: str, disable_lazy_routes: str +) -> None: + monkeypatch.setenv(FLAG, disable_lazy_routes) + app: Final = FastAPI() + attach_lazy_features(app) + with TestClient(app, root_path=root_path) as client: + catalog: Final = client.get(f"{root_path}/backend-api/codex/models?client_version=synthetic-version") + response: Final = client.post(f"{root_path}/backend-api/codex/responses", json={"model": "synthetic-native"}) + unrelated: Final = client.get(f"{root_path}/backend-api/codex/login") + assert catalog.status_code == 401 + assert response.status_code == 401 + assert unrelated.status_code == 404 + + def test_cimd_metadata_is_available_before_any_oauth_request(monkeypatch: pytest.MonkeyPatch) -> None: monkeypatch.setenv(FLAG, "false") monkeypatch.setenv("PROXY_BASE_URL", "https://gateway.example.com") diff --git a/ui/litellm-dashboard/src/lib/http/schema.d.ts b/ui/litellm-dashboard/src/lib/http/schema.d.ts index bd08b743c7d..56031c86915 100644 --- a/ui/litellm-dashboard/src/lib/http/schema.d.ts +++ b/ui/litellm-dashboard/src/lib/http/schema.d.ts @@ -1792,6 +1792,46 @@ export interface paths { patch: operations["azure_speech_proxy_route_azure_speech__endpoint__patch"]; trace?: never; }; + "/backend-api/codex/models": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Codex Models + * @description Forward the signed-in user's native Codex catalog using a separate LiteLLM gateway credential. + */ + get: operations["codex_models_backend_api_codex_models_get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/backend-api/codex/responses": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Codex Responses + * @description Relay ChatGPT subscription Responses over HTTP/SSE. The client owns login and token refresh. + */ + post: operations["codex_responses_backend_api_codex_responses_post"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/batches": { parameters: { query?: never; @@ -53660,6 +53700,55 @@ export interface operations { }; }; }; + codex_models_backend_api_codex_models_get: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + }; + }; + codex_responses_backend_api_codex_responses_post: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody: { + content: { + "application/json": { + [key: string]: unknown; + }; + }; + }; + responses: { + /** @description The upstream Responses payload or unchanged server-sent events */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + [key: string]: unknown; + }; + "text/event-stream": string; + }; + }; + }; + }; list_batches_batches_get: { parameters: { query?: { diff --git a/uv.lock b/uv.lock index 8d2a38c1806..cade44270ff 100644 --- a/uv.lock +++ b/uv.lock @@ -4711,6 +4711,7 @@ proxy = [ { name = "uvicorn" }, { name = "uvloop", marker = "sys_platform != 'win32'" }, { name = "websockets" }, + { name = "zstandard" }, ] proxy-runtime = [ { name = "anthropic", extra = ["vertex"] }, @@ -4862,6 +4863,7 @@ proxy-dev = [ { name = "prisma" }, { name = "prometheus-client" }, { name = "sentry-sdk" }, + { name = "zstandard" }, ] [package.metadata] @@ -4977,6 +4979,7 @@ requires-dist = [ { name = "uvicorn", marker = "extra == 'proxy'", specifier = ">=0.33.0,<1.0" }, { name = "uvloop", marker = "sys_platform != 'win32' and extra == 'proxy'", specifier = ">=0.22.1,<1.0" }, { name = "websockets", marker = "extra == 'proxy'", specifier = ">=15.0.1,<16.0" }, + { name = "zstandard", marker = "extra == 'proxy'", specifier = ">=0.25.0,<1.0" }, ] provides-extras = ["proxy", "cli", "extra-proxy", "utils", "caching", "mcp", "saml", "semantic-router", "mlflow", "grpc", "stt-vertex-chirp", "stt-nvidia-riva", "google", "bedrock-realtime", "proxy-runtime"] @@ -5085,6 +5088,7 @@ proxy-dev = [ { name = "prisma", specifier = "==0.11.0" }, { name = "prometheus-client", specifier = "==0.20.0" }, { name = "sentry-sdk", specifier = "==2.21.0" }, + { name = "zstandard", specifier = "==0.25.0" }, ] [[package]]