Skip to main content

waratah_api/ai/
proxy.rs

1//! Egress LLM proxy: `/waratah/ai/upstreams/{id}/*path` → the configured
2//! upstream origin (contract S1).
3//!
4//! Same machinery as the cluster proxy (`routes/cors_proxy.rs`) pointed at
5//! allowlisted third-party hosts instead of cluster members: upstreams come
6//! from `ai.toml` only (never a caller-supplied URL — SSRF), a strict
7//! request-header allowlist rides along, and request/response bodies stream
8//! untouched with no browser CORS headers. Three deliberate departures from
9//! the cluster proxy:
10//!
11//! 1. The upstream is usually HTTPS — a rustls connector wraps the plain
12//!    `HttpConnector` (the cluster proxy dials loopback HTTP only).
13//! 2. Every call carries a whole-request deadline (`request_timeout_secs`).
14//!    A deadline that fires before the response headers is a `504`; one
15//!    that fires after cannot change the status line already on the wire,
16//!    so it ends the body — and when the content type is
17//!    `text/event-stream` it first flushes one SSE comment line
18//!    (`: waratah-proxy-truncated`), which the SSE spec requires event
19//!    parsers to ignore while the frontend can still scan for it.
20//! 3. The request body has a hard byte maximum (`max_request_body_bytes`)
21//!    enforced while streaming (a `Content-Length` pre-check plus a
22//!    counting wrapper), because `DefaultBodyLimit` only applies to
23//!    buffering extractors — a proxy that forwards the live body would
24//!    bypass it.
25//!
26//! Cancellation propagates by drop semantics, as on the other proxies: when
27//! the browser disconnects, the response body (and with it the upstream
28//! request) is dropped mid-stream.
29
30use std::pin::Pin;
31use std::sync::Arc;
32use std::sync::OnceLock;
33use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
34use std::task::{Context, Poll};
35use std::time::Instant;
36
37use axum::body::{Body, HttpBody};
38use axum::extract::{OriginalUri, State};
39use axum::http::header::CONTENT_LENGTH;
40use axum::http::{HeaderMap, HeaderName, Method, StatusCode, Uri, header};
41use axum::response::Response;
42use bytes::Bytes;
43use http_body::Frame;
44use http_body::SizeHint;
45use http_body_util::BodyExt;
46use hyper_util::client::legacy::Client;
47use hyper_util::client::legacy::connect::HttpConnector;
48use hyper_util::rt::TokioExecutor;
49use percent_encoding::percent_decode_str;
50use tokio::time::Instant as TokioInstant;
51use tokio::time::Sleep;
52use tokio_stream::Stream;
53use tokio_stream::StreamExt;
54
55use crate::ai::config::{AiConfig, AiUpstream, valid_upstream_id};
56use crate::ai::json_error;
57use crate::backend::ComputeBackend;
58use crate::state::AppState;
59
60/// SSE comment flushed when the whole-request deadline cuts an
61/// `text/event-stream` response. Comment lines (`:`-prefixed) are ignored
62/// by conformant event parsers, so this never corrupts a client's event
63/// stream — it is a signal for the frontend's own scanner.
64const SSE_TRUNCATION_MARKER: &str = ": waratah-proxy-truncated\n\n";
65
66/// Maximum percent-decode rounds before the text is called unstable and
67/// rejected (see [`percent_decode_fixpoint`]). Five collapses `%2525252e`
68/// four levels deep; anything longer is attack-shaped nesting.
69const MAX_DECODE_ROUNDS: usize = 5;
70
71/// Byte counters and the body-limit trip flag, shared by the request
72/// wrapper, the response stream, and the completion log line.
73#[derive(Default)]
74struct ProxyCounts {
75    bytes_in: AtomicU64,
76    bytes_out: AtomicU64,
77    /// Set when the streaming request body exceeded the configured maximum;
78    /// read when classifying a failed upstream call (the hyper error chain
79    /// does not reliably preserve our marker type).
80    request_exceeded: AtomicBool,
81}
82
83/// Resolved AI service state held by [`crate::state::AppState`]: the
84/// configuration plus one lazily built HTTP client.
85///
86/// The client is built once (first proxied request) so a broken root store
87/// surfaces as a per-request `502`, not a startup panic, and so every
88/// handler state clone shares one connection pool.
89pub struct AiService {
90    /// Resolved configuration (public: discovery and `waratah_bin` read it).
91    pub config: AiConfig,
92    client: OnceLock<Option<Client<hyper_rustls::HttpsConnector<HttpConnector>, CountingBody>>>,
93}
94
95impl std::fmt::Debug for AiService {
96    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
97        // The lazily built client has no meaningful Debug form.
98        f.debug_struct("AiService")
99            .field("config", &self.config)
100            .finish_non_exhaustive()
101    }
102}
103
104impl AiService {
105    /// Build the service state over a resolved config.
106    pub fn new(config: AiConfig) -> Self {
107        Self {
108            config,
109            client: OnceLock::new(),
110        }
111    }
112
113    /// The shared upstream client, or `None` when the TLS connector could
114    /// not be built (e.g. no native root certificates on this host).
115    fn client(&self) -> Option<&Client<hyper_rustls::HttpsConnector<HttpConnector>, CountingBody>> {
116        self.client
117            .get_or_init(|| {
118                let mut http = HttpConnector::new();
119                http.set_connect_timeout(Some(self.config.connect_timeout));
120                // hyper-rustls hands the inner connector the ORIGINAL
121                // https:// URI (it only layers TLS on the stream the inner
122                // one returns), and HttpConnector refuses non-http schemes
123                // by default. The stock `builder.build()` flips exactly
124                // this flag (hyper-rustls builder.rs); `wrap_connector`
125                // leaves the inner connector's configuration to the
126                // caller.
127                http.enforce_http(false);
128                let https = hyper_rustls::HttpsConnectorBuilder::new()
129                    .with_native_roots()
130                    .ok()?
131                    .https_or_http()
132                    .enable_http1()
133                    .wrap_connector(http);
134                Some(Client::builder(TokioExecutor::new()).build(https))
135            })
136            .as_ref()
137    }
138}
139
140/// Streaming request body that counts forwarded bytes and fails the upload
141/// once the configured maximum is exceeded (chunked bodies have no
142/// `Content-Length` to pre-check).
143struct CountingBody {
144    inner: Body,
145    remaining: usize,
146    /// Fuse: once the limit trips, every later poll returns the same
147    /// error and no further frame is read (callers stop after an error by
148    /// contract, but a wrapper that polls again must not see a clean end
149    /// or a fitting frame slip through).
150    exceeded: bool,
151    counts: Arc<ProxyCounts>,
152}
153
154impl CountingBody {
155    fn new(inner: Body, limit: usize, counts: Arc<ProxyCounts>) -> Self {
156        Self {
157            inner,
158            remaining: limit,
159            exceeded: false,
160            counts,
161        }
162    }
163}
164
165impl HttpBody for CountingBody {
166    type Data = Bytes;
167    type Error = axum::BoxError;
168
169    fn poll_frame(
170        self: Pin<&mut Self>,
171        cx: &mut Context<'_>,
172    ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> {
173        let this = self.get_mut();
174        if this.exceeded {
175            // Fused: the same error every poll, never a clean `None`.
176            return Poll::Ready(Some(Err(
177                "request body exceeds the configured maximum".into()
178            )));
179        }
180        let Poll::Ready(frame) = Pin::new(&mut this.inner).poll_frame(cx) else {
181            return Poll::Pending;
182        };
183        let Some(frame) = frame else {
184            return Poll::Ready(None);
185        };
186        let Ok(frame) = frame else {
187            return Poll::Ready(Some(Err("request body read failed".into())));
188        };
189        if let Some(data) = frame.data_ref() {
190            let len = data.len();
191            this.counts
192                .bytes_in
193                .fetch_add(len as u64, Ordering::Relaxed);
194            if len > this.remaining {
195                this.exceeded = true;
196                this.counts.request_exceeded.store(true, Ordering::Relaxed);
197                return Poll::Ready(Some(Err(
198                    "request body exceeds the configured maximum".into()
199                )));
200            }
201            this.remaining -= len;
202        }
203        Poll::Ready(Some(Ok(frame)))
204    }
205
206    fn size_hint(&self) -> SizeHint {
207        self.inner.size_hint()
208    }
209}
210
211/// One completed (or aborted) proxied call, logged when the response body
212/// ends or is dropped. `Authorization` values and `api_key_env` values must
213/// never appear here — only ids, paths, statuses, timings, and byte counts.
214struct ProxyLog {
215    upstream: String,
216    method: String,
217    path: String,
218    status: u16,
219    started: Instant,
220    counts: Arc<ProxyCounts>,
221    /// Response body ended on its own (upstream EOF) rather than being
222    /// dropped mid-stream (client abort).
223    completed: bool,
224    /// The deadline (not the upstream) ended the stream.
225    truncated: bool,
226}
227
228impl Drop for ProxyLog {
229    fn drop(&mut self) {
230        let state = if self.truncated {
231            "truncated"
232        } else if self.completed {
233            "complete"
234        } else {
235            "aborted"
236        };
237        eprintln!(
238            "ai-proxy: upstream={} method={} path={} status={} duration_ms={} bytes_in={} bytes_out={} state={}",
239            self.upstream,
240            self.method,
241            self.path,
242            self.status,
243            self.started.elapsed().as_millis(),
244            self.counts.bytes_in.load(Ordering::Relaxed),
245            self.counts.bytes_out.load(Ordering::Relaxed),
246            state,
247        );
248    }
249}
250
251/// Where a truncation sequence is: `Streaming` (normal forwarding),
252/// `MarkerSent` (the SSE comment was flushed; the next poll ends the body).
253enum Tail {
254    Streaming,
255    MarkerSent,
256}
257
258/// Response body stream: forwards upstream bytes unbuffered, counts them,
259/// and ends the stream at the whole-request deadline (with the SSE comment
260/// first when the content type is `text/event-stream`).
261///
262/// The upstream is polled FIRST; the boxed `Sleep` to the deadline is
263/// consulted only when the upstream returns `Pending`. That ordering keeps
264/// the stall-timeout (a stalled upstream sits in `Pending`, the sleep
265/// still wakes the stream) while removing the race where a due deadline
266/// dropped the upstream's already-ready final chunk or EOF — data the
267/// origin had finished sending must be delivered even if the deadline
268/// elapsed while nobody polled.
269struct ProxiedStream {
270    inner: Pin<Box<dyn Stream<Item = Result<Bytes, axum::BoxError>> + Send>>,
271    deadline: Pin<Box<Sleep>>,
272    sse_content_type: bool,
273    tail: Tail,
274    counts: Arc<ProxyCounts>,
275    log: Option<ProxyLog>,
276}
277
278impl Stream for ProxiedStream {
279    type Item = Result<Bytes, axum::BoxError>;
280
281    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
282        let this = self.get_mut();
283        if matches!(this.tail, Tail::MarkerSent) {
284            // The SSE comment went out on the previous poll: finish.
285            if let Some(log) = this.log.as_mut() {
286                log.truncated = true;
287            }
288            return Poll::Ready(None);
289        }
290        match this.inner.as_mut().poll_next(cx) {
291            Poll::Ready(Some(Ok(chunk))) => {
292                this.counts
293                    .bytes_out
294                    .fetch_add(chunk.len() as u64, Ordering::Relaxed);
295                Poll::Ready(Some(Ok(chunk)))
296            }
297            Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))),
298            Poll::Ready(None) => {
299                if let Some(log) = this.log.as_mut() {
300                    log.completed = true;
301                }
302                Poll::Ready(None)
303            }
304            Poll::Pending => {
305                // The upstream has nothing ready (or is stalled): only now
306                // does the deadline get a say, and both futures have their
307                // wakers registered so whichever resolves first re-polls.
308                if this.deadline.as_mut().poll(cx).is_ready() {
309                    if let Some(log) = this.log.as_mut() {
310                        log.truncated = true;
311                    }
312                    if this.sse_content_type {
313                        this.tail = Tail::MarkerSent;
314                        return Poll::Ready(Some(Ok(Bytes::from_static(
315                            SSE_TRUNCATION_MARKER.as_bytes(),
316                        ))));
317                    }
318                    return Poll::Ready(None);
319                }
320                Poll::Pending
321            }
322        }
323    }
324}
325
326/// Handler: `GET|POST /waratah/ai/upstreams/{id}/*path` (and the bare
327/// `/waratah/ai/upstreams/{id}`). Contract §2 ordering: disabled → 501
328/// (before id resolution), unknown id → 404, method gate, URL join, header
329/// allowlist (+ `api_key_env` replacement), streaming bodies with the byte
330/// maximum, deadlines, pass-through response.
331pub(crate) async fn ai_proxy<C>(
332    State(state): State<AppState<C>>,
333    OriginalUri(uri): OriginalUri,
334    method: Method,
335    headers: HeaderMap,
336    body: Body,
337) -> Response
338where
339    C: ComputeBackend + Clone + Send + Sync + 'static,
340{
341    let started = Instant::now();
342    let Some(ai) = &state.ai else {
343        return json_error(StatusCode::NOT_IMPLEMENTED, "ai features are not enabled");
344    };
345    let Some((id, path)) = split_upstream_path(uri.path()) else {
346        return json_error(StatusCode::NOT_FOUND, "unknown upstream");
347    };
348    let Some(upstream) = ai.config.upstreams.iter().find(|u| u.id == id) else {
349        return json_error(StatusCode::NOT_FOUND, "unknown upstream");
350    };
351    if !matches!(method, Method::GET | Method::POST) {
352        return json_error(StatusCode::METHOD_NOT_ALLOWED, "method not allowed");
353    }
354    // The bare upstream root — `/upstreams/{id}` and its trailing-slash
355    // form — targets the configured base URL itself; everything else must
356    // pass the segment rules.
357    let path = path.unwrap_or_default();
358    if !path.is_empty() && !valid_proxy_path(&path) {
359        return json_error(StatusCode::BAD_REQUEST, "invalid proxy path");
360    }
361    let Ok(target) = upstream_uri(&upstream.base_url, &path, uri.query()) else {
362        return json_error(StatusCode::BAD_REQUEST, "invalid proxy request");
363    };
364
365    let counts = Arc::new(ProxyCounts::default());
366    // Content-Length pre-check covers the common (non-chunked) upload;
367    // CountingBody enforces the same maximum for chunked bodies.
368    if content_length(&headers)
369        .is_some_and(|declared| declared > ai.config.max_request_body_bytes as u64)
370    {
371        eprintln!(
372            "ai-proxy: upstream={} method={} path={} status=413 duration_ms={} state=rejected",
373            upstream.id,
374            method,
375            path,
376            started.elapsed().as_millis()
377        );
378        return json_error(
379            StatusCode::PAYLOAD_TOO_LARGE,
380            "request body exceeds the configured maximum",
381        );
382    }
383
384    let mut builder = axum::http::Request::builder()
385        .method(method.clone())
386        .uri(target);
387    for (name, value) in &headers {
388        if !forward_request_header(name) {
389            continue;
390        }
391        // A server-held key REPLACES the client's Authorization (an
392        // `http::request::Builder` appends duplicates; there must never be
393        // two values on that header).
394        if name == header::AUTHORIZATION && upstream.api_key_env.is_some() {
395            continue;
396        }
397        builder = builder.header(name.clone(), value.clone());
398    }
399    if let Some(env_name) = &upstream.api_key_env {
400        match std::env::var(env_name) {
401            // The env value is the complete header value, verbatim.
402            Ok(value) => builder = builder.header(header::AUTHORIZATION, value),
403            Err(_) => {
404                eprintln!("ai-proxy: api key env {env_name} is not set");
405                return json_error(
406                    StatusCode::BAD_GATEWAY,
407                    "upstream api key environment variable is not set",
408                );
409            }
410        }
411    }
412    let request = match builder.body(CountingBody::new(
413        body,
414        ai.config.max_request_body_bytes,
415        Arc::clone(&counts),
416    )) {
417        Ok(request) => request,
418        Err(_) => return json_error(StatusCode::BAD_REQUEST, "invalid proxy request"),
419    };
420
421    let Some(client) = ai.client() else {
422        return json_error(
423            StatusCode::BAD_GATEWAY,
424            "tls initialization failed (no native root certificates?)",
425        );
426    };
427    let deadline = TokioInstant::now() + ai.config.request_timeout;
428    match tokio::time::timeout_at(deadline, client.request(request)).await {
429        Ok(Ok(upstream_response)) => stream_back(
430            upstream_response,
431            deadline,
432            id,
433            method.to_string(),
434            path,
435            started,
436            counts,
437        ),
438        Ok(Err(error)) => {
439            classify_upstream_error(&error, upstream, &method, &path, &started, &counts)
440        }
441        Err(_) => {
442            eprintln!(
443                "ai-proxy: upstream={} method={} path={} status=504 duration_ms={} bytes_in={} state=timeout",
444                upstream.id,
445                method,
446                path,
447                started.elapsed().as_millis(),
448                counts.bytes_in.load(Ordering::Relaxed),
449            );
450            json_error(StatusCode::GATEWAY_TIMEOUT, "upstream request timed out")
451        }
452    }
453}
454
455/// Map a failed upstream call to a JSON error response (502/504/413) with
456/// an stderr line: the body-limit trip flag wins, then timeout-flavored
457/// errors (io `TimedOut` — the connector's connect deadline surfaces this
458/// way), then connect/other failures as `502`.
459fn classify_upstream_error(
460    error: &hyper_util::client::legacy::Error,
461    upstream: &AiUpstream,
462    method: &Method,
463    path: &str,
464    started: &Instant,
465    counts: &ProxyCounts,
466) -> Response {
467    let status = if counts.request_exceeded.load(Ordering::Relaxed) {
468        StatusCode::PAYLOAD_TOO_LARGE
469    } else if is_timeout_error(error) {
470        StatusCode::GATEWAY_TIMEOUT
471    } else {
472        StatusCode::BAD_GATEWAY
473    };
474    // The top-level hyper error ("client error (Connect)") is useless
475    // without its cause chain — TLS/handshake/root-store failures live in
476    // the sources. Never contains header values; URIs are config-declared.
477    let mut cause = String::new();
478    let mut source = std::error::Error::source(error);
479    while let Some(current) = source {
480        cause.push_str(": ");
481        cause.push_str(&current.to_string());
482        source = current.source();
483    }
484    eprintln!(
485        "ai-proxy: upstream={} method={} path={} status={} duration_ms={} state=error: {error}{cause}",
486        upstream.id,
487        method,
488        path,
489        status.as_u16(),
490        started.elapsed().as_millis(),
491    );
492    match status {
493        StatusCode::PAYLOAD_TOO_LARGE => {
494            json_error(status, "request body exceeds the configured maximum")
495        }
496        StatusCode::GATEWAY_TIMEOUT => json_error(status, "upstream request timed out"),
497        _ => json_error(status, "upstream unavailable"),
498    }
499}
500
501/// Timeout-flavored errors: an `io::Error` of kind `TimedOut` anywhere in
502/// the source chain.
503/// Timeout-flavored errors: an `io::Error` of kind `TimedOut` anywhere in
504/// the source chain (the connector's connect deadline surfaces this way).
505/// `WouldBlock` is deliberately NOT included — EAGAIN is "not ready", not
506/// "deadline elapsed", and classifying it as a timeout would answer
507/// connect/TLS failures with a misleading `504`.
508fn is_timeout_error(error: &(dyn std::error::Error + 'static)) -> bool {
509    let mut source = Some(error);
510    while let Some(current) = source {
511        if let Some(io) = current.downcast_ref::<std::io::Error>()
512            && io.kind() == std::io::ErrorKind::TimedOut
513        {
514            return true;
515        }
516        source = current.source();
517    }
518    false
519}
520
521/// Forward the upstream response: status and the allowlisted headers
522/// verbatim, body streamed through the deadline/counting wrapper.
523fn stream_back<B>(
524    upstream_response: axum::http::Response<B>,
525    deadline: TokioInstant,
526    upstream_id: String,
527    method: String,
528    path: String,
529    started: Instant,
530    counts: Arc<ProxyCounts>,
531) -> Response
532where
533    B: HttpBody<Data = Bytes> + Send + 'static,
534    B::Error: Into<axum::BoxError>,
535{
536    let (parts, incoming) = upstream_response.into_parts();
537    // The deadline marker only makes sense for SSE (see the module doc).
538    // Same media-type parse as the compression skip rules: parameters
539    // split off, case-insensitive — a bare `starts_with` would reject
540    // `Text/Event-Stream` and accept `text/event-stream-not-really`.
541    let sse_content_type = crate::compress::content_media_type(&parts.headers)
542        .is_some_and(|media_type| media_type == "text/event-stream");
543    let mut builder = Response::builder().status(parts.status);
544    for (name, value) in &parts.headers {
545        if forward_response_header(name) {
546            builder = builder.header(name.clone(), value.clone());
547        }
548    }
549    let stream = ProxiedStream {
550        inner: Box::pin(
551            incoming
552                .into_data_stream()
553                .map(|item| item.map_err(|error| -> axum::BoxError { error.into() })),
554        ),
555        deadline: Box::pin(tokio::time::sleep_until(deadline)),
556        sse_content_type,
557        tail: Tail::Streaming,
558        counts: Arc::clone(&counts),
559        log: Some(ProxyLog {
560            upstream: upstream_id,
561            method,
562            path,
563            status: parts.status.as_u16(),
564            started,
565            counts,
566            completed: false,
567            truncated: false,
568        }),
569    };
570    match builder.body(Body::from_stream(stream)) {
571        Ok(response) => response,
572        Err(_) => json_error(StatusCode::BAD_GATEWAY, "upstream unavailable"),
573    }
574}
575
576/// Request headers the proxy forwards (contract: everything else dropped,
577/// which also covers every hop-by-hop header).
578fn forward_request_header(name: &HeaderName) -> bool {
579    name == header::AUTHORIZATION
580        || name == header::CONTENT_TYPE
581        || name == header::ACCEPT
582        || name == header::USER_AGENT
583        || name == HeaderName::from_static("openai-organization")
584}
585
586/// Response headers the proxy forwards (same allowlist as the cluster
587/// proxy — hop-by-hop headers never appear on it).
588fn forward_response_header(name: &HeaderName) -> bool {
589    name == header::CONTENT_TYPE
590        || name == header::CONTENT_ENCODING
591        || name == header::CONTENT_DISPOSITION
592        || name == header::CONTENT_LANGUAGE
593        || name == header::CACHE_CONTROL
594        || name == header::VARY
595}
596
597/// `Content-Length` when the client declared one.
598fn content_length(headers: &HeaderMap) -> Option<u64> {
599    headers
600        .get(CONTENT_LENGTH)
601        .and_then(|value| value.to_str().ok())
602        .and_then(|value| value.parse().ok())
603}
604
605/// `/waratah/ai/upstreams/{id}` or `/waratah/ai/upstreams/{id}/{path}` →
606/// percent-decoded `(id, Option<path>)`; `None` when the id is missing or
607/// either part fails to decode.
608/// `/waratah/ai/upstreams/{id}` or `/waratah/ai/upstreams/{id}/{path}` →
609/// `(id, Option<path>)`, both percent-decoded to a **fixpoint**; `None`
610/// when the id is missing or anything fails to decode.
611fn split_upstream_path(path: &str) -> Option<(String, Option<String>)> {
612    let rest = path.strip_prefix("/waratah/ai/upstreams/")?;
613    let (raw_id, raw_path) = match rest.split_once('/') {
614        Some((id, path)) => (id, Some(path)),
615        None => (rest, None),
616    };
617    // Fixpoint decoding closes the double-decode hole the review caught:
618    // a client `%252e%252e` is `%2e%2e` after ONE decode — not a literal
619    // `..` yet — and would have sailed through validation only to be
620    // decoded again by the origin into a parent-directory hop.
621    let id = percent_decode_fixpoint(raw_id)?;
622    if !valid_upstream_id(&id) {
623        return None;
624    }
625    let path = match raw_path {
626        Some(raw) => Some(percent_decode_fixpoint(raw)?),
627        None => None,
628    };
629    Some((id, path))
630}
631
632/// Percent-decode until the text stops changing.
633///
634/// Validation must see the fully-collapsed form, because what the ORIGIN
635/// does after us is unknowable: some servers normalize `%2e%2e` segments
636/// even when they never re-decode `%2f`. A still-changing text after
637/// [`MAX_DECODE_ROUNDS`] rounds is pathological (attack-shaped nesting)
638/// and rejected outright rather than half-decoded.
639fn percent_decode_fixpoint(raw: &str) -> Option<String> {
640    let mut current = raw.to_owned();
641    for _ in 0..MAX_DECODE_ROUNDS {
642        let decoded = percent_decode_str(&current).decode_utf8().ok()?;
643        if decoded == current {
644            return Some(current);
645        }
646        current = decoded.into_owned();
647    }
648    None
649}
650
651/// Path-segment rules (same shape as the cluster proxy): no empty / `.` /
652/// `..` segments, no backslashes, NULs, or embedded query/fragment markers.
653fn valid_proxy_path(path: &str) -> bool {
654    !path.split('/').any(|segment| {
655        segment.is_empty()
656            || segment == "."
657            || segment == ".."
658            || segment.contains(['\\', '\0', '?', '#'])
659    })
660}
661
662/// Target URL: `base_url + "/" + path` (or the bare base), query string
663/// preserved verbatim. CR/LF/NUL never reach the URL text.
664fn upstream_uri(base: &str, path: &str, query: Option<&str>) -> Result<Uri, ()> {
665    if path.contains(['\r', '\n', '\0']) || base.contains(['\r', '\n', '\0']) {
666        return Err(());
667    }
668    // `path` is the validated, fully-decoded text: re-encode it so the
669    // origin cannot decode its way past the validation (see
670    // [`percent_encode_path`]). `base` is operator config, not caller
671    // input, and passes through as validated at config-load time.
672    let mut raw = if path.is_empty() {
673        base.to_owned()
674    } else {
675        format!("{base}/{}", percent_encode_path(path))
676    };
677    if let Some(query) = query {
678        if query.contains(['\r', '\n', '\0']) {
679            return Err(());
680        }
681        raw.push('?');
682        raw.push_str(query);
683    }
684    raw.parse().map_err(|_| ())
685}
686
687/// Characters sent literally in the proxied path: RFC 3986 `pchar`
688/// (unreserved, sub-delims, `:`, `@`) plus `/` between the segments that
689/// were already validated. EVERYTHING else — crucially including `%`
690/// itself — is percent-encoded.
691const PATH_SAFE: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC
692    .remove(b'-')
693    .remove(b'.')
694    .remove(b'_')
695    .remove(b'~')
696    .remove(b'!')
697    .remove(b'$')
698    .remove(b'&')
699    .remove(b'\'')
700    .remove(b'(')
701    .remove(b')')
702    .remove(b'*')
703    .remove(b'+')
704    .remove(b',')
705    .remove(b';')
706    .remove(b'=')
707    .remove(b':')
708    .remove(b'@')
709    .remove(b'/');
710
711/// Re-encode a validated (fixpoint-decoded) path for the wire.
712///
713/// The invariant this buys: after the origin's decode, the path is exactly
714/// the text validation approved — no origin-side decode, at any depth, can
715/// resurrect a dot-segment (`%2e%2e`) or synthesize a separator (`%2f`),
716/// because the wire carries those bytes only as `%25`-prefixed literals
717/// and `/` only where the validated segments divide. This is the second
718/// half of the double-decode fix (the first half is validating the
719/// fixpoint-decoded form at all).
720fn percent_encode_path(path: &str) -> String {
721    percent_encoding::percent_encode(path.as_bytes(), PATH_SAFE).to_string()
722}
723
724#[cfg(test)]
725mod tests {
726    use super::*;
727    use pretty_assertions::assert_eq;
728
729    #[test]
730    fn request_header_allowlist_matches_the_contract() {
731        for name in [
732            "authorization",
733            "content-type",
734            "accept",
735            "user-agent",
736            "openai-organization",
737        ] {
738            assert!(
739                forward_request_header(&HeaderName::from_static(name)),
740                "{name} forwarded"
741            );
742        }
743        for name in [
744            "cookie",
745            "origin",
746            "referer",
747            "host",
748            "connection",
749            "x-custom",
750            "content-length",
751        ] {
752            assert!(
753                !forward_request_header(&HeaderName::from_static(name)),
754                "{name} dropped"
755            );
756        }
757    }
758
759    #[test]
760    fn response_header_allowlist_matches_the_cluster_proxy() {
761        for name in [
762            "content-type",
763            "content-encoding",
764            "content-disposition",
765            "content-language",
766            "cache-control",
767            "vary",
768        ] {
769            assert!(forward_response_header(&HeaderName::from_static(name)));
770        }
771        for name in ["transfer-encoding", "server", "set-cookie", "date"] {
772            assert!(!forward_response_header(&HeaderName::from_static(name)));
773        }
774    }
775
776    #[test]
777    fn upstream_uri_joins_base_path_and_query() {
778        let uri = upstream_uri(
779            "https://opencode.ai/zen/v1",
780            "chat/completions",
781            Some("a=1"),
782        )
783        .unwrap();
784        assert_eq!(
785            uri.to_string(),
786            "https://opencode.ai/zen/v1/chat/completions?a=1"
787        );
788        // Query preserved verbatim, not re-encoded.
789        let uri = upstream_uri("http://h", "m", Some("x=%2F&y=z")).unwrap();
790        assert_eq!(uri.to_string(), "http://h/m?x=%2F&y=z");
791        assert!(upstream_uri("http://h", "m", Some("a\r\nb")).is_err());
792        assert!(upstream_uri("http://h", "m\n", None).is_err());
793    }
794
795    #[test]
796    fn upstream_uri_sends_only_reencoded_path_bytes() {
797        // Validated text with bytes that must not reach the origin raw:
798        // `%` (would open a decode), spaces, and non-ASCII.
799        let uri = upstream_uri("http://h", "a b%cé", None).unwrap();
800        assert_eq!(
801            uri.path(),
802            "/a%20b%25c%C3%A9",
803            "wire path keeps % only as %25"
804        );
805        // Ordinary API paths are untouched.
806        let uri = upstream_uri("http://h/v1", "chat/completions", None).unwrap();
807        assert_eq!(uri.path(), "/v1/chat/completions");
808    }
809
810    #[test]
811    fn percent_encode_path_leaks_no_decode_candidates() {
812        // The double-decode invariant, over fixpoint-STABLE texts — the
813        // only kind that can reach the encoder. A validated text can never
814        // contain a decodable escape (`%2e%2e`, `%2f`): the fixpoint
815        // decoder would have collapsed it, so samples like "a%2e%2eb" are
816        // unrepresentable by construction, not merely untested.
817        for validated in ["a b", "..a..", "a.b/c", "x", "a%zz"] {
818            assert_eq!(
819                percent_decode_fixpoint(validated).as_deref(),
820                Some(validated),
821                "sample must be fixpoint-stable to be representative"
822            );
823            let wire = percent_encode_path(validated);
824            let once = percent_decode_str(&wire)
825                .decode_utf8()
826                .unwrap()
827                .into_owned();
828            assert_eq!(once, validated, "one decode must round-trip {validated:?}");
829            let twice = percent_decode_str(&once)
830                .decode_utf8()
831                .unwrap()
832                .into_owned();
833            assert_eq!(twice, validated, "second decode must be a no-op");
834            assert!(
835                !wire.contains("%2e")
836                    && !wire.contains("%2E")
837                    && !wire.contains("%2f")
838                    && !wire.contains("%2F"),
839                "wire {wire:?} carries decodable dot/slash escapes"
840            );
841        }
842    }
843
844    #[test]
845    fn double_encoded_traversal_collapses_before_validation() {
846        // The exact attack from the review: %252e%252e decodes once to
847        // %2e%2e (not a literal ".."), which the single-decode version of
848        // this proxy let through to origins that decode again.
849        let (id, path) = split_upstream_path("/waratah/ai/upstreams/zen/%252e%252e/admin")
850            .expect("split succeeds; validation is the next gate");
851        assert_eq!(id, "zen");
852        assert_eq!(path.as_deref(), Some("../admin"));
853        assert!(!valid_proxy_path(path.as_deref().unwrap()), "must 400");
854        // Same for the encoded-separator variant.
855        let (_, path) = split_upstream_path("/waratah/ai/upstreams/zen/a%252fb").unwrap();
856        assert_eq!(path.as_deref(), Some("a/b"));
857        assert!(valid_proxy_path("a/b"), "a legit mid-segment slash is fine");
858    }
859
860    #[test]
861    fn fixpoint_decoding_is_bounded_and_stable() {
862        assert_eq!(percent_decode_fixpoint("plain").as_deref(), Some("plain"));
863        assert_eq!(percent_decode_fixpoint("a%20b").as_deref(), Some("a b"));
864        // Nested escapes collapse fully.
865        assert_eq!(percent_decode_fixpoint("%252e").as_deref(), Some("."));
866        assert_eq!(percent_decode_fixpoint("%25252e").as_deref(), Some("."));
867        // Beyond the round bound: rejected, never half-decoded.
868        assert_eq!(percent_decode_fixpoint("%2525252e").as_deref(), Some("."));
869        assert_eq!(percent_decode_fixpoint("%252525252e"), None);
870        // Invalid UTF-8 after decoding is rejected.
871        assert_eq!(percent_decode_fixpoint("%ff"), None);
872    }
873
874    #[test]
875    fn proxy_paths_reject_traversal_and_empty_segments() {
876        assert!(valid_proxy_path("models"));
877        assert!(valid_proxy_path("chat/completions"));
878        assert!(!valid_proxy_path("models//list"));
879        assert!(!valid_proxy_path("a/../b"));
880        assert!(!valid_proxy_path("a\\b"));
881        assert!(!valid_proxy_path("a?b"));
882    }
883
884    #[test]
885    fn upstream_path_splits_id_and_rest() {
886        let (id, path) = split_upstream_path("/waratah/ai/upstreams/zen/models").unwrap();
887        assert_eq!(id, "zen");
888        assert_eq!(path.as_deref(), Some("models"));
889        let (id, path) = split_upstream_path("/waratah/ai/upstreams/zen").unwrap();
890        assert_eq!(id, "zen");
891        assert_eq!(path, None);
892        // Percent-encoded id decodes before resolution (space would be
893        // rejected — ids are single clean path segments).
894        let (id, _) = split_upstream_path("/waratah/ai/upstreams/lo%2Dcal/m").unwrap();
895        assert_eq!(id, "lo-cal");
896        assert!(split_upstream_path("/waratah/ai/upstreams/").is_none());
897        assert!(split_upstream_path("/waratah/ai/upstreams/../x/m").is_none());
898    }
899
900    /// Error wrapper to synthesize a source chain for `is_timeout_error`
901    /// (the real chain comes from hyper, which cannot be constructed here).
902    #[derive(Debug, thiserror::Error)]
903    #[error("wrapped: {0}")]
904    struct WrappedIo(#[source] std::io::Error);
905
906    #[test]
907    fn only_timedout_is_classified_as_a_timeout() {
908        assert!(is_timeout_error(&WrappedIo(std::io::Error::from(
909            std::io::ErrorKind::TimedOut
910        ))));
911        // WouldBlock is "not ready" (EAGAIN), not a deadline: it must
912        // classify as a connect failure (502), never a timeout (504).
913        assert!(!is_timeout_error(&WrappedIo(std::io::Error::from(
914            std::io::ErrorKind::WouldBlock
915        ))));
916        assert!(!is_timeout_error(&WrappedIo(std::io::Error::other("boom"))));
917    }
918
919    #[tokio::test]
920    async fn elapsed_deadline_never_steals_ready_upstream_frames() {
921        // Finding 8's exact bug: the deadline already elapsed, but the
922        // upstream has a chunk and EOF READY in this very poll. The
923        // upstream is polled first, so the data is delivered and the body
924        // completes — the old order (deadline first) cut to the marker and
925        // dropped the bytes. The synthetic inner stream makes the
926        // coincidence deterministic; hyper's pipe capacity decides real-
927        // world buffering, not this invariant.
928        // Pre-register and settle the elapsed sleep first: a tokio Sleep
929        // created for "now" reports Pending on its first poll (timer
930        // registration) and only Ready once the runtime has turned, so
931        // polling it in-place would not make the elapsed deadline
932        // deterministic at ProxiedStream's first poll.
933        let waker = std::task::Waker::noop();
934        let mut cx = std::task::Context::from_waker(waker);
935        let mut deadline = Box::pin(tokio::time::sleep_until(TokioInstant::now()));
936        let _ = deadline.as_mut().poll(&mut cx);
937        // A real (tiny) sleep, not yield_now: the current-thread timer
938        // driver only settles elapsed timers while parked.
939        tokio::time::sleep(std::time::Duration::from_millis(1)).await;
940
941        let stream = ProxiedStream {
942            inner: Box::pin(tokio_stream::iter(vec![Ok(Bytes::from_static(
943                b"data: one\n\n",
944            ))])),
945            deadline,
946            sse_content_type: true,
947            tail: Tail::Streaming,
948            counts: Arc::new(ProxyCounts::default()),
949            log: Some(ProxyLog {
950                upstream: "up".to_owned(),
951                method: "GET".to_owned(),
952                path: "stream".to_owned(),
953                status: 200,
954                started: Instant::now(),
955                counts: Arc::new(ProxyCounts::default()),
956                completed: false,
957                truncated: false,
958            }),
959        };
960        let mut stream = std::pin::pin!(stream);
961        let first = stream.as_mut().poll_next(&mut cx);
962        assert!(
963            matches!(first, Poll::Ready(Some(Ok(chunk))) if chunk == "data: one\n\n"),
964            "ready data beats the elapsed deadline"
965        );
966        let second = stream.as_mut().poll_next(&mut cx);
967        assert!(
968            matches!(second, Poll::Ready(None)),
969            "clean EOF after the data"
970        );
971        // The log records a completed body, not a truncation.
972        let log = stream.log.take().unwrap();
973        assert!(log.completed);
974        assert!(!log.truncated);
975    }
976
977    #[tokio::test]
978    async fn counting_body_fuses_after_the_limit_error() {
979        // Three 48-byte chunks against a 64-byte maximum: the second frame
980        // trips the limit, and every poll after that must return the same
981        // error — never a clean end, never a frame that "fits" the stale
982        // remaining budget.
983        let (tx, rx) = tokio::sync::mpsc::channel::<Result<bytes::Bytes, std::io::Error>>(8);
984        for _ in 0..3 {
985            tx.send(Ok(bytes::Bytes::from(vec![0u8; 48])))
986                .await
987                .unwrap();
988        }
989        drop(tx);
990        let counts = Arc::new(ProxyCounts::default());
991        let mut body = CountingBody::new(
992            Body::from_stream(tokio_stream::wrappers::ReceiverStream::new(rx)),
993            64,
994            Arc::clone(&counts),
995        );
996        let first = std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await;
997        assert!(matches!(first, Some(Ok(_))), "first frame fits");
998        let second = std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await;
999        assert!(
1000            matches!(second, Some(Err(_))),
1001            "second frame trips the limit"
1002        );
1003        for _ in 0..2 {
1004            let again = std::future::poll_fn(|cx| Pin::new(&mut body).poll_frame(cx)).await;
1005            assert!(
1006                matches!(again, Some(Err(_))),
1007                "fused: later polls repeat the error, not a clean end"
1008            );
1009        }
1010        assert!(counts.request_exceeded.load(Ordering::Relaxed));
1011    }
1012}