Skip to main content

lean_ctx/proxy/
chatgpt.rs

1use axum::{
2    body::Body,
3    extract::State,
4    http::{HeaderName, Request, StatusCode},
5    response::Response,
6};
7
8use super::admitted::{self, AdmittedBody};
9use super::{ProxyState, forward, openai_responses};
10use crate::core::context_admission::egress::{EgressTarget, TrustedDestinationBinding};
11
12/// Codex subscription model turns hit ChatGPT's Responses-compatible rail:
13/// `/backend-api/codex/responses`. Forward through the same compressor/metering
14/// path as OpenAI Responses, but target `https://chatgpt.com`.
15pub async fn codex_responses_handler(
16    State(state): State<ProxyState>,
17    mut req: Request<Body>,
18) -> Result<Response, StatusCode> {
19    // Drop the "responses-lite" marker before forwarding. Codex requests the
20    // reduced lite transport on its HTTP path (`supports_websockets = false`),
21    // but chatgpt.com rejects newer subscription models there
22    // ("This model is not supported when using X-OpenAI-Internal-Codex-Responses-Lite",
23    // seen with gpt-5.5). Stripping it makes chatgpt.com serve the full Responses
24    // rail every model supports; Codex parses the full stream identically
25    // (verified single- + multi-turn `previous_response_id` continuation). #623
26    req.headers_mut().remove(CODEX_RESPONSES_LITE_HEADER);
27    let upstream = state.chatgpt_upstream();
28    forward::forward_request(
29        State(state),
30        req,
31        &upstream,
32        "/backend-api/codex/responses",
33        openai_responses::compress_request_body,
34        "ChatGPT",
35        &[],
36    )
37    .await
38}
39
40/// Codex's HTTP fallback marks the reduced "responses-lite" transport with this
41/// header. chatgpt.com gates newer subscription models behind the full rail, so
42/// the Codex ChatGPT handler strips it (see [`codex_responses_handler`]).
43const CODEX_RESPONSES_LITE_HEADER: &str = "x-openai-internal-codex-responses-lite";
44
45/// ChatGPT's Codex rail rejects WS-only continuation fields such as
46/// `previous_response_id`; ask Codex to retry through the HTTP/SSE path.
47pub async fn codex_responses_ws_handler(
48    State(_state): State<ProxyState>,
49    _headers: axum::http::HeaderMap,
50    _ws: axum::extract::ws::WebSocketUpgrade,
51) -> Response {
52    chatgpt_responses_ws_fallback_response()
53}
54
55fn chatgpt_responses_ws_fallback_response() -> Response {
56    Response::builder()
57        .status(StatusCode::UPGRADE_REQUIRED)
58        .header("content-type", "application/json")
59        .body(Body::from(
60            r#"{"error":{"type":"unsupported_transport","message":"ChatGPT codex responses use HTTP/SSE; retry without WebSocket."}}"#,
61        ))
62        .expect("static response is valid")
63}
64
65/// Provider label of the ChatGPT backend rail in receipts and refusals.
66pub(super) const BACKEND_PROVIDER: &str = "ChatGPT";
67
68/// ChatGPT backend calls outside the model rail are not model JSON and must not be
69/// compressed or cost-metered. They are credential-preserving passthroughs —
70/// of headers. Their bodies are context leaving this machine like any other:
71/// each one is admitted by the gateway, bound to the configured ChatGPT
72/// upstream in its receipt, and refused with the typed reason when it may not
73/// leave. An admitted body is forwarded byte for byte.
74///
75/// A WebSocket upgrade (Codex Desktop remote-control pairing, #597) is tunnelled
76/// to chatgpt.com by [`super::chatgpt_ws`], frame by admitted frame; plain
77/// HTTP/SSE falls through to the forward below.
78pub async fn backend_api_handler(
79    State(state): State<ProxyState>,
80    req: Request<Body>,
81) -> Result<Response, StatusCode> {
82    if super::chatgpt_ws::is_websocket_upgrade(req.headers()) {
83        return Ok(super::chatgpt_ws::passthrough(state, req).await);
84    }
85
86    let (parts, body) = req.into_parts();
87    let body_bytes = axum::body::to_bytes(body, forward::max_body_bytes())
88        .await
89        .map_err(|_| StatusCode::PAYLOAD_TOO_LARGE)?;
90    let upstream = state.chatgpt_upstream();
91    let path = parts
92        .uri
93        .path_and_query()
94        .map_or("/backend-api", axum::http::uri::PathAndQuery::as_str);
95    let url = format!("{upstream}{path}");
96
97    // The destination is the configured upstream; no caller header selects it.
98    let target = EgressTarget {
99        provider: BACKEND_PROVIDER,
100        model: None,
101        upstream_base: &upstream,
102    };
103    // The path, query and relayed header values leave as surely as the body
104    // (AP10-C2).
105    if let Err(refusal) = admitted::admit_request_target(
106        path,
107        parts
108            .headers
109            .iter()
110            .filter(|(key, _)| is_backend_passthrough_request_header(key)),
111        &target,
112        TrustedDestinationBinding::default(),
113        forward::sealed_principal(&parts).as_deref(),
114    )
115    .await
116    {
117        return Ok(refusal.response(BACKEND_PROVIDER));
118    }
119    let admission = admitted::admit_passthrough(
120        &parts,
121        &body_bytes,
122        forward::max_body_bytes(),
123        &target,
124        TrustedDestinationBinding::default(),
125    );
126    // The relayed header set is bound with the body; the relay rule itself
127    // (everything but hop-by-hop and this proxy's own namespace) is kept.
128    let head = admitted::RequestHead::new(
129        parts.method.clone(),
130        parts
131            .headers
132            .iter()
133            .filter(|(key, _)| is_backend_passthrough_request_header(key))
134            .map(|(key, value)| (key.clone(), value.clone())),
135    );
136    let admitted_body = match admission {
137        Ok((outcome, bytes)) => {
138            AdmittedBody::bind(
139                outcome,
140                bytes,
141                &upstream,
142                &url,
143                head,
144                body_bytes.len(),
145                None,
146            )
147            .await
148        }
149        Err(refusal) => Err(refusal),
150    };
151    let admitted_body = match admitted_body {
152        Ok(admitted_body) => admitted_body,
153        Err(refusal) => return Ok(refusal.response(BACKEND_PROVIDER)),
154    };
155
156    let attempt = admitted_body
157        .send(&state.client, 1, |request| request)
158        .await;
159    let attempt = match attempt {
160        Ok(attempt) => attempt,
161        Err(refusal) => return Ok(refusal.response(BACKEND_PROVIDER)),
162    };
163    let response = attempt.response.map_err(|e| {
164        tracing::error!(
165            "lean-ctx proxy: ChatGPT backend upstream error: {}",
166            admitted::transport_failure(&e)
167        );
168        StatusCode::BAD_GATEWAY
169    })?;
170
171    let status = StatusCode::from_u16(response.status().as_u16()).unwrap_or(StatusCode::OK);
172    let headers = response.headers().clone();
173    let is_stream = headers
174        .get("content-type")
175        .and_then(|v| v.to_str().ok())
176        .is_some_and(|ct| ct.contains("text/event-stream"));
177
178    let mut out = Response::builder().status(status);
179    for (key, value) in &headers {
180        if is_backend_passthrough_response_header(key) {
181            out = out.header(key, value);
182        }
183    }
184
185    if is_stream {
186        return out
187            .body(Body::from_stream(super::sse_keepalive::keepalive_stream(
188                Box::pin(response.bytes_stream()),
189            )))
190            .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR);
191    }
192
193    let bytes = response
194        .bytes()
195        .await
196        .map_err(|_| StatusCode::BAD_GATEWAY)?;
197
198    out.body(Body::from(bytes))
199        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)
200}
201
202fn is_backend_passthrough_request_header(name: &HeaderName) -> bool {
203    let lower = name.as_str().to_ascii_lowercase();
204    // `x-leanctx-*` is this proxy's own namespace (project path, agent and
205    // session ids, the presenter capability). This relay passes everything it
206    // does not name, so the whole prefix is named: a header added to the
207    // namespace later is never relayed either.
208    !lower.starts_with(LEANCTX_INTERNAL_HEADER_PREFIX)
209        && !matches!(
210            lower.as_str(),
211            "host"
212                | "connection"
213                | "content-length"
214                | "transfer-encoding"
215                | "upgrade"
216                | "keep-alive"
217                | "proxy-authenticate"
218                | "proxy-authorization"
219                | "te"
220                | "trailer"
221                | "accept-encoding"
222        )
223}
224
225/// Prefix of the headers that are addressed to this proxy and never leave it.
226pub(super) const LEANCTX_INTERNAL_HEADER_PREFIX: &str = "x-leanctx-";
227
228fn is_backend_passthrough_response_header(name: &HeaderName) -> bool {
229    let lower = name.as_str().to_ascii_lowercase();
230    !matches!(
231        lower.as_str(),
232        "connection"
233            | "content-length"
234            | "transfer-encoding"
235            | "upgrade"
236            | "keep-alive"
237            | "proxy-authenticate"
238            | "proxy-authorization"
239            | "te"
240            | "trailer"
241    )
242}
243
244#[cfg(test)]
245mod tests {
246    use std::sync::Arc;
247    use std::time::Duration;
248
249    use tokio::io::{AsyncReadExt, AsyncWriteExt};
250
251    use super::*;
252    use crate::core::config::Upstreams;
253
254    fn proxy_state(chatgpt_upstream: String) -> ProxyState {
255        let (_tx, rx) = tokio::sync::watch::channel(Arc::new(Upstreams {
256            anthropic: "https://api.anthropic.com".into(),
257            openai: "https://api.openai.com".into(),
258            chatgpt: chatgpt_upstream,
259            gemini: "https://generativelanguage.googleapis.com".into(),
260            providers: Vec::new(),
261        }));
262        ProxyState {
263            client: reqwest::Client::new(),
264            port: 0,
265            stats: Arc::new(crate::proxy::ProxyStats::default()),
266            break_even: Arc::new(crate::proxy::break_even::BreakEvenCalculator::new(1500)),
267            introspect: Arc::new(crate::proxy::introspect::IntrospectState::default()),
268            ocla_cache: None,
269            upstreams: rx,
270            chatgpt_cookies: crate::proxy::chatgpt_cookies::shared_chatgpt_cloudflare_cookie_store(
271            ),
272            mcp_servers: Arc::new(Vec::new()),
273        }
274    }
275
276    #[test]
277    fn codex_responses_ws_requests_trigger_http_fallback() {
278        let response = chatgpt_responses_ws_fallback_response();
279        assert_eq!(response.status(), StatusCode::UPGRADE_REQUIRED);
280        assert_eq!(
281            response
282                .headers()
283                .get(axum::http::header::CONTENT_TYPE)
284                .unwrap(),
285            "application/json"
286        );
287    }
288
289    async fn spawn_streaming_upstream() -> (String, tokio::sync::oneshot::Receiver<String>) {
290        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
291        let addr = listener.local_addr().unwrap();
292        let (tx, rx) = tokio::sync::oneshot::channel();
293        tokio::spawn(async move {
294            let (mut socket, _) = listener.accept().await.unwrap();
295            let mut buf = Vec::new();
296            loop {
297                let mut chunk = [0_u8; 1024];
298                let n = socket.read(&mut chunk).await.unwrap();
299                if n == 0 {
300                    break;
301                }
302                buf.extend_from_slice(&chunk[..n]);
303                if buf.windows(4).any(|w| w == b"\r\n\r\n") {
304                    break;
305                }
306            }
307            let _ = tx.send(String::from_utf8_lossy(&buf).into_owned());
308            socket
309                .write_all(
310                    b"HTTP/1.1 200 OK\r\n\
311                      content-type: text/event-stream\r\n\
312                      mcp-session-id: server-session\r\n\
313                      cache-control: no-cache\r\n\
314                      x-custom-backend-state: passthrough\r\n\
315                      \r\n\
316                      event: message\n\
317                      data: {\"jsonrpc\":\"2.0\"}\n\n",
318                )
319                .await
320                .unwrap();
321            tokio::time::sleep(Duration::from_secs(2)).await;
322        });
323        (format!("http://{addr}"), rx)
324    }
325
326    /// The backend rail passes headers through, not unexamined content: a
327    /// protected value in the body — also in a member called `name` — is
328    /// masked before the body reaches the upstream.
329    #[tokio::test]
330    async fn backend_api_body_is_admitted_before_it_is_forwarded() {
331        let _data = crate::core::data_dir::isolated_data_dir();
332        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
333        let key = concat!("AK", "IAIOSFODNN7EXAMPLE");
334        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
335        let upstream = format!("http://{}", listener.local_addr().unwrap());
336        let server = tokio::spawn(async move {
337            let (mut socket, _) = listener.accept().await.unwrap();
338            let mut request = Vec::new();
339            let mut chunk = [0_u8; 1024];
340            let (header_end, length) = loop {
341                let read = socket.read(&mut chunk).await.unwrap();
342                assert!(read > 0, "upstream closed before the request headers");
343                request.extend_from_slice(&chunk[..read]);
344                if let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") {
345                    let head = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
346                    let length = head
347                        .lines()
348                        .find_map(|line| line.strip_prefix("content-length:"))
349                        .map_or(0, |value| value.trim().parse::<usize>().unwrap());
350                    break (end + 4, length);
351                }
352            };
353            while request.len() < header_end + length {
354                let read = socket.read(&mut chunk).await.unwrap();
355                assert!(read > 0, "upstream closed before the request body");
356                request.extend_from_slice(&chunk[..read]);
357            }
358            socket
359                .write_all(
360                    b"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: 2\r\nconnection: close\r\n\r\n{}",
361                )
362                .await
363                .unwrap();
364            String::from_utf8_lossy(&request[header_end..]).into_owned()
365        });
366        let body = serde_json::json!({
367            "note": format!("deploy with {key} today"),
368            "name": key,
369        });
370        let req = Request::builder()
371            .method("POST")
372            .uri("/backend-api/wham/tasks")
373            .header("content-type", "application/json")
374            .body(Body::from(body.to_string()))
375            .unwrap();
376
377        let response = tokio::time::timeout(
378            Duration::from_secs(5),
379            backend_api_handler(State(proxy_state(upstream)), req),
380        )
381        .await
382        .expect("bounded backend request")
383        .expect("backend request should succeed");
384        assert_eq!(response.status(), StatusCode::OK);
385
386        let received = server.await.unwrap();
387        assert!(
388            !received.contains(key),
389            "the upstream received the raw value: {received}"
390        );
391        assert!(received.contains("deploy with"), "{received}");
392    }
393
394    #[tokio::test]
395    async fn backend_api_streams_mcp_sse_and_preserves_session_headers() {
396        let _data = crate::core::data_dir::isolated_data_dir();
397        let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
398        let (upstream, seen_request) = spawn_streaming_upstream().await;
399        let state = proxy_state(upstream);
400        let req = Request::builder()
401            .method("POST")
402            .uri("/backend-api/ps/mcp?transport=streamable")
403            .header("Authorization", "Bearer codex-token")
404            .header("Mcp-Session-Id", "client-session")
405            .header("Last-Event-ID", "event-7")
406            .header("X-OpenAI-Product-Sku", "codex")
407            .header("X-OpenAI-Internal-Codex-Residency", "us")
408            .header("Originator", "codex_cli_rs")
409            .header("Accept", "application/json, text/event-stream")
410            // The proxy's own namespace, under a name no list knows.
411            .header("X-LeanCTX-Later-Id", "internal")
412            .body(Body::empty())
413            .unwrap();
414
415        let response = tokio::time::timeout(
416            Duration::from_millis(500),
417            backend_api_handler(State(state), req),
418        )
419        .await
420        .expect("SSE passthrough must return after upstream headers")
421        .expect("backend request should succeed");
422
423        assert_eq!(response.status(), StatusCode::OK);
424        assert_eq!(
425            response.headers().get("mcp-session-id").unwrap(),
426            "server-session"
427        );
428        assert_eq!(
429            response.headers().get("x-custom-backend-state").unwrap(),
430            "passthrough"
431        );
432
433        let request = seen_request.await.unwrap().to_ascii_lowercase();
434        assert!(request.contains("post /backend-api/ps/mcp?transport=streamable http/1.1"));
435        assert!(request.contains("authorization: bearer codex-token"));
436        assert!(request.contains("mcp-session-id: client-session"));
437        assert!(request.contains("last-event-id: event-7"));
438        assert!(request.contains("x-openai-product-sku: codex"));
439        assert!(request.contains("x-openai-internal-codex-residency: us"));
440        assert!(request.contains("originator: codex_cli_rs"));
441        assert!(
442            !request.contains(LEANCTX_INTERNAL_HEADER_PREFIX),
443            "no x-leanctx-* header is relayed"
444        );
445    }
446}