Skip to main content

asimov_proxy/
openai.rs

1// This is free and unencumbered software released into the public domain.
2
3//! OpenAI-compatible proxy support, currently forwarding to OpenRouter.
4//!
5//! ```no_run
6//! # extern crate alloc;
7//! # async fn example() -> Result<(), alloc::boxed::Box<dyn core::error::Error>> {
8//! use asimov_proxy::openai::{Proxy, ProxyOptions};
9//!
10//! let proxy = Proxy::openrouter("my-api-key", ProxyOptions::default())?;
11//! let listener = tokio::net::TcpListener::bind("127.0.0.1:1920").await?;
12//! // Replace this future with the application's shutdown notification.
13//! proxy.serve(listener, core::future::pending()).await?;
14//! # Ok(())
15//! # }
16//! ```
17
18use crate::{
19    BodyLogger, Error, ProxyConfig,
20    proxy_connector::{ConnectTimeout, ProxyConnector},
21};
22use alloc::{format, string::String, sync::Arc, vec::Vec};
23use axum::{
24    Router,
25    body::{Body, Bytes},
26    extract::{Request, State},
27    http::{self, HeaderMap, HeaderValue, StatusCode, Version},
28    response::Response,
29    routing::any,
30};
31use core::time::Duration;
32use http_body_util::{BodyExt, Full};
33use hyper_rustls::{ConfigBuilderExt as _, HttpsConnector};
34use hyper_util::{client::legacy::Client, rt::TokioExecutor};
35use tokio::{
36    net::TcpListener,
37    sync::{OwnedSemaphorePermit, Semaphore},
38};
39
40const UPSTREAM_BASE_URL: &str = "https://openrouter.ai/api";
41const DEFAULT_MAX_BODY_BYTES: usize = 16 * 1024 * 1024;
42const DEFAULT_MAX_CONCURRENT_REQUESTS: usize = 32;
43
44/// The upstream HTTP client: a hyper client speaking rustls-based TLS to the
45/// target, over a connection that is either direct or tunneled through a
46/// proxy (see the `proxy_connector` module).
47type UpstreamClient = Client<ConnectTimeout<HttpsConnector<ProxyConnector>>, Full<Bytes>>;
48
49/// Builds the upstream client, bounding each connection by `connect_limit`.
50fn upstream_client(
51    connector: HttpsConnector<ProxyConnector>,
52    connect_limit: Duration,
53) -> UpstreamClient {
54    Client::builder(TokioExecutor::new()).build(ConnectTimeout::new(connector, connect_limit))
55}
56
57/// Transport, resource limits, and optional logging for a [`Proxy`].
58#[derive(Clone)]
59pub struct ProxyOptions {
60    /// How to connect upstream; defaults to shared environment/native discovery.
61    pub upstream_proxy: ProxyConfig,
62    /// Maximum buffered request body size; defaults to 16 MiB.
63    pub max_body_bytes: usize,
64    /// Maximum requests in progress, including streaming responses; defaults
65    /// to 32. Further requests receive HTTP 503 immediately.
66    pub max_concurrent_requests: usize,
67    /// Deadline for upstream response headers; defaults to 120 seconds.
68    ///
69    /// Includes connection establishment, but does not limit response streaming.
70    /// Each connection, including one Hyper finishes in the background for its
71    /// pool, is also limited separately to this duration.
72    pub upstream_timeout: Duration,
73    /// Deadline for receiving HTTP/1 request headers in [`Proxy::serve`];
74    /// defaults to 30 seconds. Slower clients are disconnected.
75    pub header_timeout: Duration,
76    /// Deadline for receiving the complete request body; defaults to 60
77    /// seconds. Slower uploads receive HTTP 408 without reaching upstream.
78    pub body_timeout: Duration,
79    /// Longest wait for each upstream response chunk; defaults to 120 seconds.
80    ///
81    /// A stalled stream is aborted on expiry, so that it cannot delay graceful
82    /// shutdown indefinitely. Total streaming time remains unlimited.
83    pub idle_timeout: Duration,
84    /// Optional request and response body log; disabled by default.
85    pub logger: Option<BodyLogger>,
86}
87
88impl Default for ProxyOptions {
89    fn default() -> Self {
90        Self {
91            upstream_proxy: ProxyConfig::Automatic,
92            max_body_bytes: DEFAULT_MAX_BODY_BYTES,
93            max_concurrent_requests: DEFAULT_MAX_CONCURRENT_REQUESTS,
94            upstream_timeout: Duration::from_secs(120),
95            header_timeout: Duration::from_secs(30),
96            body_timeout: Duration::from_secs(60),
97            idle_timeout: Duration::from_secs(120),
98            logger: None,
99        }
100    }
101}
102
103#[derive(Clone)]
104struct ProxyState {
105    client: UpstreamClient,
106    upstream_base_url: String,
107    logger: Option<BodyLogger>,
108    authorization: HeaderValue,
109    max_body_bytes: usize,
110    permits: Arc<Semaphore>,
111    upstream_timeout: Duration,
112    header_timeout: Duration,
113    body_timeout: Duration,
114    idle_timeout: Duration,
115}
116
117/// An OpenAI-compatible proxy forwarding requests to OpenRouter.
118///
119/// Requests retain their path, query, method, and body. The upstream API key
120/// replaces inbound authorization, and ASIMOV attribution headers are added.
121/// Hop-by-hop headers are stripped in both directions. Responses, including
122/// SSE, are streamed without buffering.
123#[derive(Clone)]
124pub struct Proxy {
125    state: ProxyState,
126}
127
128impl Proxy {
129    /// Creates an OpenRouter proxy with explicit credentials and options.
130    ///
131    /// Loads native TLS roots, validates the API key, and resolves proxy policy
132    /// for the OpenRouter origin. Defaults use `asimov-http` environment/native
133    /// discovery, uppercase-first precedence, and shared bypass rules. Choose
134    /// [`ProxyConfig::Direct`] for direct access or a parsed explicit route.
135    /// Discovery failures are returned before serving. Responses are streamed
136    /// through Hyper; redirects are forwarded without replaying requests.
137    pub fn openrouter(api_key: &str, options: ProxyOptions) -> Result<Self, Error> {
138        let authorization = authorization_header(api_key)?;
139        let target = url::Url::parse(UPSTREAM_BASE_URL)?;
140        let upstream_proxy = options.upstream_proxy.for_target(&target)?;
141
142        // Select a provider explicitly, even when downstream dependencies also
143        // enable rustls's aws-lc provider.
144        let tls_config = Arc::new(
145            rustls::ClientConfig::builder_with_provider(Arc::new(
146                rustls::crypto::ring::default_provider(),
147            ))
148            .with_safe_default_protocol_versions()?
149            .with_native_roots()?
150            .with_no_client_auth(),
151        );
152        let connector = ProxyConnector::new(&target, upstream_proxy, Arc::clone(&tls_config))?;
153        let https_connector = hyper_rustls::HttpsConnectorBuilder::new()
154            .with_tls_config((*tls_config).clone())
155            .https_only()
156            .enable_http1()
157            .wrap_connector(connector);
158        let client = upstream_client(https_connector, options.upstream_timeout);
159
160        Ok(Self {
161            state: ProxyState {
162                client,
163                upstream_base_url: UPSTREAM_BASE_URL.into(),
164                logger: options.logger,
165                authorization,
166                max_body_bytes: options.max_body_bytes,
167                permits: permits(options.max_concurrent_requests),
168                upstream_timeout: options.upstream_timeout,
169                header_timeout: options.header_timeout,
170                body_timeout: options.body_timeout,
171                idle_timeout: options.idle_timeout,
172            },
173        })
174    }
175
176    /// Creates a router for embedding in an existing Axum application.
177    ///
178    /// Invalid bodies return HTTP 400, slow uploads 408, oversized bodies 413,
179    /// upstream failures 502, requests over the concurrency limit 503, and
180    /// upstream header timeouts 504. Upstream status codes pass through.
181    pub fn router(self) -> Router {
182        Router::new()
183            .route("/{*path}", any(proxy_handler))
184            .with_state(self.state)
185    }
186
187    /// Serves a caller-owned listener until `shutdown` completes.
188    ///
189    /// Stops accepting connections on shutdown and waits for in-flight
190    /// responses to finish; [`ProxyOptions::idle_timeout`] aborts stalled ones.
191    /// The caller controls signals and overall shutdown deadlines.
192    pub async fn serve(
193        self,
194        listener: TcpListener,
195        shutdown: impl core::future::Future<Output = ()> + Send + 'static,
196    ) -> std::io::Result<()> {
197        let header_timeout = self.state.header_timeout;
198        serve_until_shutdown(listener, self.router(), header_timeout, shutdown).await
199    }
200}
201
202/// Serves like `axum::serve` with graceful shutdown, but also enforces a
203/// deadline for HTTP/1 request headers, which requires a Hyper timer that
204/// `axum::serve` does not set.
205async fn serve_until_shutdown(
206    listener: TcpListener,
207    router: Router,
208    header_timeout: Duration,
209    shutdown: impl core::future::Future<Output = ()> + Send + 'static,
210) -> std::io::Result<()> {
211    use hyper_util::{
212        rt::{TokioIo, TokioTimer},
213        server::{conn::auto::Builder, graceful::GracefulShutdown},
214        service::TowerToHyperService,
215    };
216
217    let mut builder = Builder::new(TokioExecutor::new());
218    builder
219        .http1()
220        .timer(TokioTimer::new())
221        .header_read_timeout(header_timeout);
222    let graceful = GracefulShutdown::new();
223    let mut shutdown = core::pin::pin!(shutdown);
224    loop {
225        let stream = tokio::select! {
226            accepted = listener.accept() => match accepted {
227                Ok((stream, _)) => stream,
228                Err(error) => {
229                    handle_accept_error(error).await;
230                    continue;
231                },
232            },
233            () = &mut shutdown => break,
234        };
235        let service = TowerToHyperService::new(router.clone());
236        let connection = builder
237            .serve_connection_with_upgrades(TokioIo::new(stream), service)
238            .into_owned();
239        let connection = graceful.watch(connection);
240        tokio::spawn(async move {
241            if let Err(_error) = connection.await {
242                #[cfg(feature = "tracing")]
243                tracing::trace!("failed to serve connection: {_error:#}");
244            }
245        });
246    }
247    // Stop accepting, then let in-flight connections finish.
248    drop(listener);
249    graceful.shutdown().await;
250    Ok(())
251}
252
253/// Skips per-connection accept errors and backs off on others, such as file
254/// descriptor exhaustion, as `axum::serve` does.
255async fn handle_accept_error(error: std::io::Error) {
256    use std::io::ErrorKind;
257    if matches!(
258        error.kind(),
259        ErrorKind::ConnectionRefused | ErrorKind::ConnectionAborted | ErrorKind::ConnectionReset
260    ) {
261        return;
262    }
263    #[cfg(feature = "tracing")]
264    tracing::error!("accept error: {error}");
265    #[cfg(not(feature = "tracing"))]
266    let _ = error;
267    tokio::time::sleep(Duration::from_secs(1)).await;
268}
269
270/// Creates the concurrency limit, clamped to Tokio's maximum permit count.
271fn permits(limit: usize) -> Arc<Semaphore> {
272    Arc::new(Semaphore::new(limit.min(Semaphore::MAX_PERMITS)))
273}
274
275async fn proxy_handler(
276    State(state): State<ProxyState>,
277    req: Request,
278) -> Result<Response, StatusCode> {
279    let Ok(permit) = Arc::clone(&state.permits).try_acquire_owned() else {
280        #[cfg(feature = "tracing")]
281        tracing::warn!("Rejecting request over the concurrency limit");
282        return Err(StatusCode::SERVICE_UNAVAILABLE);
283    };
284
285    let request_path = req.uri().path();
286    let request_query = req
287        .uri()
288        .query()
289        .map(|q| format!("?{q}"))
290        .unwrap_or_default();
291
292    #[cfg(feature = "tracing")]
293    tracing::info!("Proxying request: {} {}", request_path, request_query);
294
295    // https://openrouter.ai/api/v1/chat/completions
296    let target_url = format!(
297        "{}{}{}",
298        state.upstream_base_url, request_path, request_query
299    );
300
301    let (mut head, body) = req.into_parts();
302
303    let upstream_request_body =
304        read_request_body(body, state.max_body_bytes, state.body_timeout).await?;
305
306    if let Some(logger) = &state.logger {
307        logger.log_request_body(&upstream_request_body);
308    }
309
310    // Retarget the request at the upstream server:
311    head.uri = target_url
312        .parse()
313        .map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
314    head.version = Version::HTTP_11; // regardless of the inbound HTTP version
315
316    // Modify request headers:
317    strip_hop_by_hop_headers(&mut head.headers);
318    head.headers.remove("host"); // don't send "Host: 127.0.0.1"
319    head.headers.remove("content-length"); // hyper recomputes the buffered length
320    head.headers
321        .insert("Authorization", state.authorization.clone());
322
323    // See: https://openrouter.ai/docs/app-attribution
324    insert_attribution_headers(&mut head.headers);
325
326    let upstream_request = http::Request::from_parts(head, Full::new(upstream_request_body));
327
328    let upstream_response = wait_for_upstream(
329        state.upstream_timeout,
330        state.client.request(upstream_request),
331    )
332    .await?;
333
334    Ok(forward_response(
335        upstream_response,
336        state.logger.clone(),
337        state.idle_timeout,
338        permit,
339    ))
340}
341
342fn forward_response(
343    response: http::Response<hyper::body::Incoming>,
344    logger: Option<BodyLogger>,
345    idle_timeout: Duration,
346    permit: OwnedSemaphorePermit,
347) -> Response {
348    // Stream the upstream response body back to the client, teeing each data
349    // frame into the body log (if enabled):
350    let (mut head, upstream_response_body) = response.into_parts();
351    strip_hop_by_hop_headers(&mut head.headers);
352    let upstream_response_body = upstream_response_body.map_frame(move |frame| {
353        // Hold the concurrency permit until the response body is dropped.
354        let _permit = &permit;
355        if let (Some(logger), Some(data)) = (&logger, frame.data_ref()) {
356            logger.log_response_chunk(data);
357        }
358        frame
359    });
360
361    Response::from_parts(
362        head,
363        Body::new(IdleTimeout::new(upstream_response_body, idle_timeout)),
364    )
365}
366
367/// Ends a response body with an error once `limit` passes without a frame.
368struct IdleTimeout<B> {
369    inner: B,
370    limit: Duration,
371    deadline: core::pin::Pin<alloc::boxed::Box<tokio::time::Sleep>>,
372}
373
374impl<B> IdleTimeout<B> {
375    fn new(inner: B, limit: Duration) -> Self {
376        Self {
377            inner,
378            limit,
379            deadline: alloc::boxed::Box::pin(tokio::time::sleep(limit)),
380        }
381    }
382}
383
384impl<B> hyper::body::Body for IdleTimeout<B>
385where
386    B: hyper::body::Body + Unpin,
387    B::Error: Into<crate::BoxError>,
388{
389    type Data = B::Data;
390    type Error = crate::BoxError;
391
392    fn poll_frame(
393        mut self: core::pin::Pin<&mut Self>,
394        cx: &mut core::task::Context<'_>,
395    ) -> core::task::Poll<Option<Result<hyper::body::Frame<Self::Data>, Self::Error>>> {
396        use core::{future::Future as _, pin::Pin, task::Poll};
397        let this = &mut *self;
398        match Pin::new(&mut this.inner).poll_frame(cx) {
399            Poll::Ready(frame) => {
400                let next = tokio::time::Instant::now() + this.limit;
401                this.deadline.as_mut().reset(next);
402                Poll::Ready(frame.map(|frame| frame.map_err(Into::into)))
403            },
404            Poll::Pending => match this.deadline.as_mut().poll(cx) {
405                Poll::Ready(()) => {
406                    #[cfg(feature = "tracing")]
407                    tracing::warn!("Upstream response stream stalled");
408                    Poll::Ready(Some(Err("upstream response stream stalled".into())))
409                },
410                Poll::Pending => Poll::Pending,
411            },
412        }
413    }
414
415    fn is_end_stream(&self) -> bool {
416        self.inner.is_end_stream()
417    }
418
419    fn size_hint(&self) -> hyper::body::SizeHint {
420        self.inner.size_hint()
421    }
422}
423
424fn strip_hop_by_hop_headers(headers: &mut HeaderMap) {
425    let nominated: Vec<_> = headers
426        .get_all(http::header::CONNECTION)
427        .iter()
428        .flat_map(|value| value.as_bytes().split(|byte| *byte == b','))
429        .filter_map(|name| http::header::HeaderName::from_bytes(name.trim_ascii()).ok())
430        .collect();
431    for name in nominated {
432        headers.remove(name);
433    }
434    for name in [
435        "connection",
436        "keep-alive",
437        "proxy-connection",
438        "proxy-authenticate",
439        "proxy-authorization",
440        "te",
441        "trailer",
442        "transfer-encoding",
443        "upgrade",
444    ] {
445        headers.remove(name);
446    }
447}
448
449async fn wait_for_upstream<T, E: core::fmt::Display>(
450    limit: Duration,
451    request: impl core::future::Future<Output = Result<T, E>>,
452) -> Result<T, StatusCode> {
453    match tokio::time::timeout(limit, request).await {
454        Ok(Ok(response)) => Ok(response),
455        Ok(Err(_error)) => {
456            #[cfg(feature = "tracing")]
457            tracing::error!("Upstream request failed: {_error}");
458            Err(StatusCode::BAD_GATEWAY)
459        },
460        Err(_) => {
461            #[cfg(feature = "tracing")]
462            tracing::error!("Upstream response headers timed out");
463            Err(StatusCode::GATEWAY_TIMEOUT)
464        },
465    }
466}
467
468async fn read_request_body(
469    body: Body,
470    limit: usize,
471    deadline: Duration,
472) -> Result<Bytes, StatusCode> {
473    use core::error::Error;
474    let Ok(result) = tokio::time::timeout(deadline, axum::body::to_bytes(body, limit)).await else {
475        #[cfg(feature = "tracing")]
476        tracing::warn!("Request body upload timed out");
477        return Err(StatusCode::REQUEST_TIMEOUT);
478    };
479    result.map_err(|error| {
480        if error
481            .source()
482            .is_some_and(|cause| cause.is::<http_body_util::LengthLimitError>())
483        {
484            StatusCode::PAYLOAD_TOO_LARGE
485        } else {
486            StatusCode::BAD_REQUEST
487        }
488    })
489}
490
491fn authorization_header(api_key: &str) -> Result<HeaderValue, Error> {
492    if api_key.trim().is_empty() {
493        return Err(Error::MissingApiKey);
494    }
495    let mut header =
496        HeaderValue::from_str(&format!("Bearer {api_key}")).map_err(|_| Error::InvalidApiKey)?;
497    header.set_sensitive(true);
498    Ok(header)
499}
500
501fn insert_attribution_headers(headers: &mut HeaderMap<HeaderValue>) {
502    // See: https://openrouter.ai/docs/app-attribution
503    headers.insert(
504        "HTTP-Referer",
505        HeaderValue::from_static("https://asimov.sh"),
506    );
507    headers.insert("X-OpenRouter-Title", HeaderValue::from_static("ASIMOV"));
508    headers.insert(
509        "X-OpenRouter-Categories",
510        HeaderValue::from_static("cli-agent,personal-agent"),
511    );
512}
513
514#[cfg(test)]
515mod tests {
516    use super::*;
517    use asimov_http::reqwest;
518    mod proxy;
519
520    #[tokio::test]
521    async fn serves_requests_with_upstream_credentials_and_streamed_logged_responses() {
522        use tokio::io::{AsyncReadExt, AsyncWriteExt};
523
524        let upstream = TcpListener::bind("127.0.0.1:0").await.unwrap();
525        let upstream_address = upstream.local_addr().unwrap();
526        let (release, released) = tokio::sync::oneshot::channel();
527        let body = b"{\"model\": \"openrouter/free\", \"stream\": true}";
528        let upstream_task = tokio::spawn(async move {
529            let (mut socket, _) = upstream.accept().await.unwrap();
530            let headers = read_request_headers(&mut socket).await.to_ascii_lowercase();
531            assert!(headers.starts_with("post /api/v1/chat/completions?test=1 http/1.1\r\n"));
532            for header in [
533                format!("host: {upstream_address}\r\n"),
534                format!("content-length: {}\r\n", body.len()),
535                "authorization: bearer test-key\r\n".into(),
536                "http-referer: https://asimov.sh\r\n".into(),
537                "x-openrouter-title: asimov\r\n".into(),
538                "x-openrouter-categories: cli-agent,personal-agent\r\n".into(),
539                "content-type: application/json\r\n".into(),
540            ] {
541                assert!(headers.contains(&header), "{headers}");
542            }
543            for removed in [
544                "inbound-key",
545                "x-private:",
546                "proxy-authorization:",
547                "connection:",
548            ] {
549                assert!(!headers.contains(removed), "{headers}");
550            }
551            let mut received_body = alloc::vec![0; body.len()];
552            socket.read_exact(&mut received_body).await.unwrap();
553            assert_eq!(received_body, body);
554
555            socket.write_all(b"HTTP/1.1 201 Created\r\nContent-Type: text/event-stream\r\nConnection: keep-alive, x-private\r\nX-Private: secret\r\nTransfer-Encoding: chunked\r\n\r\nd\r\ndata: first\n\n\r\n").await.unwrap();
556            released.await.unwrap();
557            socket
558                .write_all(b"e\r\ndata: second\n\n\r\n0\r\n\r\n")
559                .await
560                .unwrap();
561            drop(socket);
562
563            // Close the next request without a response to trigger HTTP 502.
564            // Connecting to a closed port can outlast the deadline on Windows.
565            let (mut socket, _) = upstream.accept().await.unwrap();
566            read_request_headers(&mut socket).await;
567        });
568
569        // Use a local cleartext upstream to exercise the entire serving path.
570        let tls = rustls::ClientConfig::builder_with_provider(Arc::new(
571            rustls::crypto::ring::default_provider(),
572        ))
573        .with_safe_default_protocol_versions()
574        .unwrap()
575        .with_root_certificates(rustls::RootCertStore::empty())
576        .with_no_client_auth();
577        let target = url::Url::parse(&format!("http://{upstream_address}/api")).unwrap();
578        let connector =
579            ProxyConnector::new(&target, ProxyConfig::Direct, Arc::new(tls.clone())).unwrap();
580        let connector = hyper_rustls::HttpsConnectorBuilder::new()
581            .with_tls_config(tls)
582            .https_or_http()
583            .enable_http1()
584            .wrap_connector(connector);
585        let root = tempfile::tempdir().unwrap();
586        let log_path = root.path().join("bodies.log");
587        let proxy = Proxy {
588            state: ProxyState {
589                client: upstream_client(connector, Duration::from_secs(2)),
590                upstream_base_url: format!("http://{upstream_address}/api"),
591                authorization: authorization_header("test-key").unwrap(),
592                logger: Some(BodyLogger::open(&log_path).unwrap()),
593                max_body_bytes: body.len(),
594                permits: permits(8),
595                upstream_timeout: Duration::from_secs(2),
596                header_timeout: Duration::from_secs(2),
597                body_timeout: Duration::from_secs(2),
598                idle_timeout: Duration::from_secs(2),
599            },
600        };
601        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
602        let address = listener.local_addr().unwrap();
603        let (stop, stopped) = tokio::sync::oneshot::channel();
604        let server = tokio::spawn(proxy.serve(listener, async {
605            let _ = stopped.await;
606        }));
607        let client = reqwest::Client::builder()
608            .no_proxy()
609            .timeout(Duration::from_secs(2))
610            .build()
611            .unwrap();
612        let url = format!("http://{address}/v1/chat/completions?test=1");
613
614        // Rejected uploads must not establish an upstream connection.
615        let oversized = client
616            .post(&url)
617            .body(alloc::vec![0; body.len() + 1])
618            .send()
619            .await
620            .unwrap();
621        assert_eq!(oversized.status(), StatusCode::PAYLOAD_TOO_LARGE);
622        let mut response = client
623            .post(&url)
624            .header("authorization", "Bearer inbound-key")
625            .header("proxy-authorization", "Basic inbound-key")
626            .header("connection", "x-private")
627            .header("x-private", "secret")
628            .header("host", "inbound.example")
629            .header("content-type", "application/json")
630            .body(body.as_slice())
631            .send()
632            .await
633            .unwrap();
634        assert_eq!(response.status(), StatusCode::CREATED);
635        assert_eq!(response.headers()["content-type"], "text/event-stream");
636        assert!(!response.headers().contains_key("x-private"));
637        let first = response.chunk().await.unwrap().unwrap();
638        assert_eq!(first, "data: first\n\n");
639        let partial_log = std::fs::read_to_string(&log_path).unwrap();
640        assert!(partial_log.contains(core::str::from_utf8(body).unwrap()));
641        assert!(partial_log.contains("data: first"));
642        assert!(!partial_log.contains("data: second"));
643        release.send(()).unwrap();
644        assert_eq!(response.text().await.unwrap(), "data: second\n\n");
645        assert!(
646            std::fs::read_to_string(log_path)
647                .unwrap()
648                .contains("data: second")
649        );
650
651        // The upstream closes without responding; errors become HTTP 502.
652        let failed = client.get(&url).send().await.unwrap();
653        assert_eq!(failed.status(), StatusCode::BAD_GATEWAY);
654        upstream_task.await.unwrap();
655        stop.send(()).unwrap();
656        tokio::time::timeout(Duration::from_secs(2), server)
657            .await
658            .unwrap()
659            .unwrap()
660            .unwrap();
661    }
662
663    #[test]
664    fn removes_standard_and_connection_nominated_headers() {
665        let mut headers = HeaderMap::new();
666        for name in [
667            "keep-alive",
668            "proxy-connection",
669            "proxy-authenticate",
670            "proxy-authorization",
671            "te",
672            "trailer",
673            "transfer-encoding",
674            "upgrade",
675            "x-first",
676            "x-second",
677        ] {
678            headers.insert(
679                http::header::HeaderName::from_bytes(name.as_bytes()).unwrap(),
680                HeaderValue::from_static("value"),
681            );
682        }
683        headers.append(
684            "connection",
685            HeaderValue::from_static("keep-alive, X-First"),
686        );
687        headers.append(
688            "connection",
689            HeaderValue::from_static(" X-Second , invalid name"),
690        );
691        headers.insert(
692            "content-type",
693            HeaderValue::from_static("text/event-stream"),
694        );
695        headers.insert("x-end-to-end", HeaderValue::from_static("keep"));
696        strip_hop_by_hop_headers(&mut headers);
697        assert_eq!(headers.len(), 2);
698        assert_eq!(headers["content-type"], "text/event-stream");
699        assert_eq!(headers["x-end-to-end"], "keep");
700    }
701
702    #[tokio::test]
703    async fn sanitized_chunked_responses_remain_streaming() {
704        use tokio::io::AsyncWriteExt;
705        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
706        let address = listener.local_addr().unwrap();
707        let (release, released) = tokio::sync::oneshot::channel();
708        let server = tokio::spawn(async move {
709            let (mut socket, _) = listener.accept().await.unwrap();
710            read_request_headers(&mut socket).await;
711            socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nConnection: keep-alive, x-private\r\nX-Private: secret\r\nProxy-Authenticate: Basic\r\nTransfer-Encoding: chunked\r\n\r\nd\r\ndata: first\n\n\r\n").await.unwrap();
712            released.await.unwrap();
713            socket
714                .write_all(b"e\r\ndata: second\n\n\r\n0\r\n\r\n")
715                .await
716                .unwrap();
717        });
718        let client = Client::builder(TokioExecutor::new()).build_http::<Full<Bytes>>();
719        let request = http::Request::builder()
720            .uri(format!("http://{address}/"))
721            .body(Full::new(Bytes::new()))
722            .unwrap();
723        let upstream = tokio::time::timeout(Duration::from_secs(2), client.request(request))
724            .await
725            .unwrap()
726            .unwrap();
727        let permit = permits(1).try_acquire_owned().unwrap();
728        let mut response = forward_response(upstream, None, Duration::from_secs(2), permit);
729        for name in [
730            "connection",
731            "x-private",
732            "proxy-authenticate",
733            "transfer-encoding",
734        ] {
735            assert!(!response.headers().contains_key(name));
736        }
737        assert_eq!(response.headers()["content-type"], "text/event-stream");
738        let first = tokio::time::timeout(Duration::from_secs(2), response.body_mut().frame())
739            .await
740            .unwrap()
741            .unwrap()
742            .unwrap();
743        assert_eq!(first.into_data().unwrap(), "data: first\n\n");
744        release.send(()).unwrap();
745        let rest = tokio::time::timeout(Duration::from_secs(2), response.into_body().collect())
746            .await
747            .unwrap()
748            .unwrap()
749            .to_bytes();
750        assert_eq!(rest, "data: second\n\n");
751        server.await.unwrap();
752    }
753
754    #[tokio::test]
755    async fn graceful_shutdown_allows_in_flight_responses_to_finish() {
756        let entered = Arc::new(tokio::sync::Notify::new());
757        let release = Arc::new(tokio::sync::Notify::new());
758        let router = Router::new().route(
759            "/",
760            any({
761                let entered = entered.clone();
762                let release = release.clone();
763                move || {
764                    let entered = entered.clone();
765                    let release = release.clone();
766                    async move {
767                        entered.notify_one();
768                        release.notified().await;
769                        "completed response"
770                    }
771                }
772            }),
773        );
774        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
775        let address = listener.local_addr().unwrap();
776        let (stop, stopped) = tokio::sync::oneshot::channel();
777        let server = tokio::spawn(serve_until_shutdown(listener, router, DEADLINE, async {
778            let _ = stopped.await;
779        }));
780        let client = reqwest::Client::builder()
781            .no_proxy()
782            .timeout(Duration::from_secs(2))
783            .build()
784            .unwrap();
785        let request = tokio::spawn(async move {
786            client
787                .get(format!("http://{address}/"))
788                .send()
789                .await
790                .unwrap()
791                .text()
792                .await
793                .unwrap()
794        });
795        tokio::time::timeout(Duration::from_secs(2), entered.notified())
796            .await
797            .unwrap();
798        stop.send(()).unwrap();
799        tokio::task::yield_now().await;
800        assert!(!server.is_finished());
801        release.notify_one();
802        assert_eq!(request.await.unwrap(), "completed response");
803        tokio::time::timeout(Duration::from_secs(2), server)
804            .await
805            .unwrap()
806            .unwrap()
807            .unwrap();
808    }
809
810    #[tokio::test]
811    async fn upstream_deadline_bounds_headers_without_buffering_the_body() {
812        use tokio::io::AsyncWriteExt;
813        for send_headers in [false, true] {
814            let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
815            let address = listener.local_addr().unwrap();
816            let server = tokio::spawn(async move {
817                let (mut socket, _) = listener.accept().await.unwrap();
818                read_request_headers(&mut socket).await;
819                if send_headers {
820                    socket
821                        .write_all(b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n")
822                        .await
823                        .unwrap();
824                }
825                core::future::pending::<()>().await;
826            });
827            let client = Client::builder(TokioExecutor::new()).build_http::<Full<Bytes>>();
828            let request = http::Request::builder()
829                .uri(format!("http://{address}/"))
830                .body(Full::new(Bytes::new()))
831                .unwrap();
832            let result = tokio::time::timeout(
833                Duration::from_secs(2),
834                wait_for_upstream(Duration::from_millis(100), client.request(request)),
835            )
836            .await;
837            server.abort();
838            let _ = server.await;
839            let result = result.expect("header wait must finish");
840            if send_headers {
841                assert_eq!(result.unwrap().status(), StatusCode::OK);
842            } else {
843                assert_eq!(result.unwrap_err(), StatusCode::GATEWAY_TIMEOUT);
844            }
845        }
846    }
847
848    const BODY_DEADLINE: Duration = Duration::from_secs(2);
849    const DEADLINE: Duration = Duration::from_secs(2);
850
851    #[tokio::test]
852    async fn request_body_limits_apply_to_buffered_and_streamed_bodies() {
853        assert_eq!(
854            read_request_body(Body::from("1234"), 4, BODY_DEADLINE)
855                .await
856                .unwrap(),
857            "1234"
858        );
859        assert_eq!(
860            read_request_body(Body::from("12345"), 4, BODY_DEADLINE)
861                .await
862                .unwrap_err(),
863            StatusCode::PAYLOAD_TOO_LARGE
864        );
865        let chunks = [
866            Ok::<_, std::io::Error>(Bytes::from_static(b"12")),
867            Ok(Bytes::from_static(b"345")),
868        ];
869        let body = Body::from_stream(futures_lite::stream::iter(chunks));
870        assert_eq!(
871            read_request_body(body, 4, BODY_DEADLINE).await.unwrap_err(),
872            StatusCode::PAYLOAD_TOO_LARGE
873        );
874        assert!(
875            read_request_body(Body::empty(), 0, BODY_DEADLINE)
876                .await
877                .unwrap()
878                .is_empty()
879        );
880        let body = Body::from_stream(futures_lite::stream::iter([Err::<Bytes, _>(
881            std::io::Error::other("interrupted upload"),
882        )]));
883        assert_eq!(
884            read_request_body(body, 4, BODY_DEADLINE).await.unwrap_err(),
885            StatusCode::BAD_REQUEST
886        );
887    }
888
889    /// A proxy for a local cleartext upstream with short limits.
890    fn local_proxy(upstream: core::net::SocketAddr) -> Proxy {
891        let tls = rustls::ClientConfig::builder_with_provider(Arc::new(
892            rustls::crypto::ring::default_provider(),
893        ))
894        .with_safe_default_protocol_versions()
895        .unwrap()
896        .with_root_certificates(rustls::RootCertStore::empty())
897        .with_no_client_auth();
898        let target = url::Url::parse(&format!("http://{upstream}/api")).unwrap();
899        let connector =
900            ProxyConnector::new(&target, ProxyConfig::Direct, Arc::new(tls.clone())).unwrap();
901        let connector = hyper_rustls::HttpsConnectorBuilder::new()
902            .with_tls_config(tls)
903            .https_or_http()
904            .enable_http1()
905            .wrap_connector(connector);
906        Proxy {
907            state: ProxyState {
908                client: upstream_client(connector, Duration::from_secs(2)),
909                upstream_base_url: target.as_str().into(),
910                authorization: authorization_header("test-key").unwrap(),
911                logger: None,
912                max_body_bytes: 1024,
913                permits: permits(8),
914                upstream_timeout: Duration::from_secs(2),
915                header_timeout: Duration::from_secs(2),
916                body_timeout: Duration::from_secs(2),
917                idle_timeout: Duration::from_secs(2),
918            },
919        }
920    }
921
922    #[tokio::test]
923    async fn stalled_uploads_time_out_without_reaching_upstream() {
924        use tokio::io::{AsyncReadExt, AsyncWriteExt};
925
926        let upstream = TcpListener::bind("127.0.0.1:0").await.unwrap();
927        let mut proxy = local_proxy(upstream.local_addr().unwrap());
928        proxy.state.body_timeout = Duration::from_millis(100);
929        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
930        let address = listener.local_addr().unwrap();
931        let server = tokio::spawn(axum::serve(listener, proxy.router()).into_future());
932
933        // Announce ten bytes, send four, and stall.
934        let mut client = tokio::net::TcpStream::connect(address).await.unwrap();
935        client
936            .write_all(b"POST /v1/chat/completions HTTP/1.1\r\nHost: proxy\r\nContent-Length: 10\r\n\r\n{\"a\"")
937            .await
938            .unwrap();
939        let mut response = alloc::vec![0; 12];
940        tokio::time::timeout(Duration::from_secs(2), client.read_exact(&mut response))
941            .await
942            .expect("the upload deadline must fire")
943            .unwrap();
944        assert_eq!(response, b"HTTP/1.1 408");
945        assert!(
946            tokio::time::timeout(Duration::from_millis(50), upstream.accept())
947                .await
948                .is_err()
949        );
950        server.abort();
951    }
952
953    #[tokio::test]
954    async fn slow_request_headers_disconnect_and_release_shutdown() {
955        use tokio::io::{AsyncReadExt, AsyncWriteExt};
956
957        let upstream = TcpListener::bind("127.0.0.1:0").await.unwrap();
958        let mut proxy = local_proxy(upstream.local_addr().unwrap());
959        proxy.state.header_timeout = Duration::from_millis(200);
960        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
961        let address = listener.local_addr().unwrap();
962        let (stop, stopped) = tokio::sync::oneshot::channel();
963        let server = tokio::spawn(proxy.serve(listener, async {
964            let _ = stopped.await;
965        }));
966
967        // Send an incomplete request head and stall. The deadline closes the
968        // connection, cleanly or with a reset, before any response.
969        let mut client = tokio::net::TcpStream::connect(address).await.unwrap();
970        client
971            .write_all(b"POST /v1/chat/completions HTTP/1.1\r\nHost: proxy\r\n")
972            .await
973            .unwrap();
974        let mut response = Vec::new();
975        let read = tokio::time::timeout(DEADLINE, client.read_to_end(&mut response))
976            .await
977            .expect("the header deadline must close the connection");
978        assert!(read.is_ok() || read.unwrap_err().kind() == std::io::ErrorKind::ConnectionReset);
979        assert!(!response.starts_with(b"HTTP/1.1 2"));
980        stop.send(()).unwrap();
981        tokio::time::timeout(DEADLINE, server)
982            .await
983            .expect("shutdown must complete")
984            .unwrap()
985            .unwrap();
986        assert!(
987            tokio::time::timeout(Duration::from_millis(50), upstream.accept())
988                .await
989                .is_err()
990        );
991    }
992
993    #[tokio::test]
994    async fn requests_over_the_concurrency_limit_are_rejected() {
995        use core::sync::atomic::{AtomicUsize, Ordering};
996        use futures_lite::StreamExt as _;
997
998        let upstream = TcpListener::bind("127.0.0.1:0").await.unwrap();
999        let mut proxy = local_proxy(upstream.local_addr().unwrap());
1000        proxy.state.permits = permits(1);
1001        // The first upstream response streams one chunk, then waits for
1002        // `release` before ending; later responses complete immediately.
1003        let release = Arc::new(tokio::sync::Notify::new());
1004        let calls = Arc::new(AtomicUsize::new(0));
1005        let upstream_router = Router::new().route(
1006            "/{*path}",
1007            any({
1008                let (release, calls) = (release.clone(), calls.clone());
1009                move || {
1010                    let (release, calls) = (release.clone(), calls.clone());
1011                    async move {
1012                        if calls.fetch_add(1, Ordering::SeqCst) > 0 {
1013                            return Body::from("next");
1014                        }
1015                        let first = futures_lite::stream::once(Ok::<_, std::io::Error>(
1016                            Bytes::from_static(b"first"),
1017                        ));
1018                        let end = futures_lite::stream::once_future(async move {
1019                            release.notified().await;
1020                            Ok(Bytes::new())
1021                        });
1022                        Body::from_stream(first.chain(end))
1023                    }
1024                }
1025            }),
1026        );
1027        let upstream_server = tokio::spawn(axum::serve(upstream, upstream_router).into_future());
1028        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1029        let address = listener.local_addr().unwrap();
1030        let server = tokio::spawn(axum::serve(listener, proxy.router()).into_future());
1031        let client = reqwest::Client::builder()
1032            .no_proxy()
1033            .timeout(DEADLINE)
1034            .build()
1035            .unwrap();
1036        let url = format!("http://{address}/v1/models");
1037
1038        // While the first response streams, it holds the only permit.
1039        let mut first = client.get(&url).send().await.unwrap();
1040        assert_eq!(first.chunk().await.unwrap().unwrap(), "first");
1041        let rejected = client.get(&url).send().await.unwrap();
1042        assert_eq!(rejected.status(), StatusCode::SERVICE_UNAVAILABLE);
1043        assert_eq!(calls.load(Ordering::SeqCst), 1, "rejected before upstream");
1044
1045        // Completing the first response body releases the permit.
1046        release.notify_one();
1047        assert_eq!(first.text().await.unwrap(), "");
1048        let after = client.get(&url).send().await.unwrap();
1049        assert_eq!(after.text().await.unwrap(), "next");
1050        server.abort();
1051        upstream_server.abort();
1052    }
1053
1054    #[tokio::test]
1055    async fn client_disconnection_cancels_upstream_and_releases_its_permit() {
1056        use tokio::io::{AsyncReadExt, AsyncWriteExt};
1057
1058        for streaming in [false, true] {
1059            let upstream = TcpListener::bind("127.0.0.1:0").await.unwrap();
1060            let mut proxy = local_proxy(upstream.local_addr().unwrap());
1061            proxy.state.permits = permits(1);
1062            let (entered, entered_rx) = tokio::sync::oneshot::channel();
1063            let (closed, closed_rx) = tokio::sync::oneshot::channel();
1064            let upstream_task = tokio::spawn(async move {
1065                let (mut socket, _) = upstream.accept().await.unwrap();
1066                read_request_headers(&mut socket).await;
1067                if streaming {
1068                    socket
1069                        .write_all(
1070                            b"HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nfirst\r\n",
1071                        )
1072                        .await
1073                        .unwrap();
1074                }
1075                entered.send(()).unwrap();
1076                // The proxy must close this connection after its client leaves.
1077                let mut buffer = [0; 64];
1078                let read = tokio::time::timeout(DEADLINE, socket.read(&mut buffer)).await;
1079                assert!(
1080                    matches!(read, Ok(Ok(0) | Err(_))),
1081                    "streaming={streaming}: upstream request was not cancelled"
1082                );
1083                closed.send(()).unwrap();
1084                let (mut socket, _) = upstream.accept().await.unwrap();
1085                read_request_headers(&mut socket).await;
1086                socket
1087                    .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 4\r\n\r\nnext")
1088                    .await
1089                    .unwrap();
1090            });
1091            let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1092            let address = listener.local_addr().unwrap();
1093            let server = tokio::spawn(proxy.serve(listener, core::future::pending()));
1094
1095            let mut client = tokio::net::TcpStream::connect(address).await.unwrap();
1096            client
1097                .write_all(b"GET /v1/stream HTTP/1.1\r\nHost: proxy\r\n\r\n")
1098                .await
1099                .unwrap();
1100            tokio::time::timeout(DEADLINE, entered_rx)
1101                .await
1102                .unwrap()
1103                .unwrap();
1104            if streaming {
1105                // Receive the first chunk before disconnecting mid-stream.
1106                let mut received = Vec::new();
1107                while !received.windows(5).any(|window| window == b"first") {
1108                    let mut buffer = [0; 256];
1109                    let count = tokio::time::timeout(DEADLINE, client.read(&mut buffer))
1110                        .await
1111                        .unwrap()
1112                        .unwrap();
1113                    assert!(count > 0);
1114                    received.extend_from_slice(&buffer[..count]);
1115                }
1116            }
1117            drop(client);
1118            tokio::time::timeout(DEADLINE, closed_rx)
1119                .await
1120                .unwrap_or_else(|_| panic!("streaming={streaming}: upstream left open"))
1121                .unwrap_or_else(|_| panic!("streaming={streaming}: upstream task failed"));
1122
1123            // The single permit must be available again.
1124            let after = reqwest::Client::builder()
1125                .no_proxy()
1126                .timeout(DEADLINE)
1127                .build()
1128                .unwrap()
1129                .get(format!("http://{address}/v1/models"))
1130                .send()
1131                .await
1132                .unwrap();
1133            assert_eq!(after.status(), StatusCode::OK, "streaming={streaming}");
1134            assert_eq!(after.text().await.unwrap(), "next");
1135            tokio::time::timeout(DEADLINE, upstream_task)
1136                .await
1137                .unwrap()
1138                .unwrap();
1139            server.abort();
1140        }
1141    }
1142
1143    #[tokio::test]
1144    async fn stalled_response_streams_abort_and_release_shutdown() {
1145        use tokio::io::AsyncWriteExt;
1146
1147        let upstream = TcpListener::bind("127.0.0.1:0").await.unwrap();
1148        let mut proxy = local_proxy(upstream.local_addr().unwrap());
1149        proxy.state.idle_timeout = Duration::from_millis(200);
1150        let upstream_task = tokio::spawn(async move {
1151            let (mut socket, _) = upstream.accept().await.unwrap();
1152            read_request_headers(&mut socket).await;
1153            socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\nTransfer-Encoding: chunked\r\n\r\nd\r\ndata: first\n\n\r\n").await.unwrap();
1154            // Hold the connection open without sending anything further.
1155            core::future::pending::<()>().await;
1156        });
1157        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
1158        let address = listener.local_addr().unwrap();
1159        let (stop, stopped) = tokio::sync::oneshot::channel();
1160        let server = tokio::spawn(proxy.serve(listener, async {
1161            let _ = stopped.await;
1162        }));
1163        let client = reqwest::Client::builder().no_proxy().build().unwrap();
1164        let mut response = client
1165            .get(format!("http://{address}/v1/stream"))
1166            .send()
1167            .await
1168            .unwrap();
1169        let first = response.chunk().await.unwrap().unwrap();
1170        assert_eq!(first, "data: first\n\n");
1171        stop.send(()).unwrap();
1172        let rest = tokio::time::timeout(Duration::from_secs(2), response.chunk())
1173            .await
1174            .expect("the idle limit must fire");
1175        assert!(rest.is_err(), "{rest:?}");
1176        tokio::time::timeout(Duration::from_secs(2), server)
1177            .await
1178            .expect("shutdown must not wait for the stalled stream")
1179            .unwrap()
1180            .unwrap();
1181        upstream_task.abort();
1182    }
1183
1184    #[test]
1185    fn authorization_is_validated_and_marked_sensitive() {
1186        let header = authorization_header("test-key").unwrap();
1187        assert_eq!(header, "Bearer test-key");
1188        assert!(header.is_sensitive());
1189        assert!(!format!("{header:?}").contains("test-key"));
1190        for key in ["", "   ", "secret\nvalue", "secret\rvalue"] {
1191            assert!(matches!(
1192                authorization_header(key),
1193                Err(Error::MissingApiKey | Error::InvalidApiKey)
1194            ));
1195        }
1196    }
1197
1198    async fn read_request_headers(socket: &mut tokio::net::TcpStream) -> String {
1199        use tokio::io::AsyncReadExt;
1200        let mut headers = Vec::new();
1201        while !headers.ends_with(b"\r\n\r\n") {
1202            headers.push(socket.read_u8().await.unwrap());
1203            assert!(headers.len() <= 8192);
1204        }
1205        String::from_utf8(headers).unwrap()
1206    }
1207}