Skip to main content

lean_ctx/proxy/
mod.rs

1pub mod anthropic;
2pub mod compress;
3pub mod cost;
4pub mod forward;
5pub mod google;
6pub mod history_prune;
7pub mod introspect;
8pub mod metrics;
9pub mod openai;
10pub mod openai_responses;
11pub mod tool_kind;
12
13use std::net::SocketAddr;
14use std::sync::atomic::{AtomicU64, Ordering};
15use std::sync::Arc;
16
17use axum::{
18    body::Body,
19    extract::State,
20    http::{Request, StatusCode},
21    response::{IntoResponse, Response},
22    routing::{any, get},
23    Router,
24};
25
26#[derive(Clone)]
27pub struct ProxyState {
28    pub client: reqwest::Client,
29    pub port: u16,
30    pub stats: Arc<ProxyStats>,
31    pub introspect: Arc<introspect::IntrospectState>,
32    pub anthropic_upstream: String,
33    pub openai_upstream: String,
34    pub gemini_upstream: String,
35}
36
37pub struct ProxyStats {
38    pub requests_total: AtomicU64,
39    pub requests_compressed: AtomicU64,
40    pub tokens_saved: AtomicU64,
41    pub bytes_original: AtomicU64,
42    pub bytes_compressed: AtomicU64,
43}
44
45impl Default for ProxyStats {
46    fn default() -> Self {
47        Self {
48            requests_total: AtomicU64::new(0),
49            requests_compressed: AtomicU64::new(0),
50            tokens_saved: AtomicU64::new(0),
51            bytes_original: AtomicU64::new(0),
52            bytes_compressed: AtomicU64::new(0),
53        }
54    }
55}
56
57impl ProxyStats {
58    pub fn record_request(&self) {
59        self.requests_total.fetch_add(1, Ordering::Relaxed);
60    }
61
62    pub fn record_compression(&self, original: usize, compressed: usize) {
63        self.requests_compressed.fetch_add(1, Ordering::Relaxed);
64        self.bytes_original
65            .fetch_add(original as u64, Ordering::Relaxed);
66        self.bytes_compressed
67            .fetch_add(compressed as u64, Ordering::Relaxed);
68        let saved_tokens = (original.saturating_sub(compressed) / 4) as u64;
69        self.tokens_saved.fetch_add(saved_tokens, Ordering::Relaxed);
70    }
71
72    pub fn compression_ratio(&self) -> f64 {
73        let original = self.bytes_original.load(Ordering::Relaxed);
74        if original == 0 {
75            return 0.0;
76        }
77        let compressed = self.bytes_compressed.load(Ordering::Relaxed);
78        (1.0 - compressed as f64 / original as f64) * 100.0
79    }
80}
81
82/// TCP connect timeout (seconds). Configurable via `LEAN_CTX_PROXY_CONNECT_TIMEOUT_SECS`.
83fn connect_timeout_secs() -> u64 {
84    std::env::var("LEAN_CTX_PROXY_CONNECT_TIMEOUT_SECS")
85        .ok()
86        .and_then(|v| v.trim().parse::<u64>().ok())
87        .filter(|s| *s > 0)
88        .unwrap_or(15)
89}
90
91/// Idle read timeout (seconds) between bytes from upstream. Generous by default
92/// so long extended-thinking phases (which still emit SSE keepalives) are never
93/// cut, while a truly dead connection eventually fails. Configurable via
94/// `LEAN_CTX_PROXY_READ_TIMEOUT_SECS`.
95fn read_idle_timeout_secs() -> u64 {
96    std::env::var("LEAN_CTX_PROXY_READ_TIMEOUT_SECS")
97        .ok()
98        .and_then(|v| v.trim().parse::<u64>().ok())
99        .filter(|s| *s > 0)
100        .unwrap_or(300)
101}
102
103pub async fn start_proxy(port: u16) -> anyhow::Result<()> {
104    let token = crate::core::session_token::resolve_proxy_token("LEAN_CTX_PROXY_TOKEN");
105    start_proxy_with_token(port, Some(token)).await
106}
107
108/// Security invariant: the proxy NEVER runs unauthenticated. `None` does not
109/// mean "no auth" — it means "resolve the session token for me". Provider
110/// routes additionally accept provider API keys (see `proxy_auth_guard`), so
111/// IDE clients keep working without any setup.
112fn effective_auth_token(auth_token: Option<String>) -> String {
113    auth_token
114        .filter(|t| !t.trim().is_empty())
115        .unwrap_or_else(|| crate::core::session_token::resolve_proxy_token("LEAN_CTX_PROXY_TOKEN"))
116}
117
118pub async fn start_proxy_with_token(port: u16, auth_token: Option<String>) -> anyhow::Result<()> {
119    use crate::core::config::{Config, ProxyProvider};
120
121    let auth_token = effective_auth_token(auth_token);
122
123    // A single total timeout aborts long streaming generations (e.g. Opus doing
124    // a big refactor) mid-response. Use a connect timeout plus a read (idle)
125    // timeout instead: a genuinely hung upstream still fails, but a slow-but-
126    // alive stream is never cut off. Both are configurable for edge networks.
127    let client = reqwest::Client::builder()
128        .connect_timeout(std::time::Duration::from_secs(connect_timeout_secs()))
129        .read_timeout(std::time::Duration::from_secs(read_idle_timeout_secs()))
130        .build()?;
131
132    let cfg = Config::load();
133    let anthropic_upstream = cfg.proxy.resolve_upstream(ProxyProvider::Anthropic);
134    let openai_upstream = cfg.proxy.resolve_upstream(ProxyProvider::OpenAi);
135    let gemini_upstream = cfg.proxy.resolve_upstream(ProxyProvider::Gemini);
136
137    let state = ProxyState {
138        client,
139        port,
140        stats: Arc::new(ProxyStats::default()),
141        introspect: Arc::new(introspect::IntrospectState::default()),
142        anthropic_upstream: anthropic_upstream.clone(),
143        openai_upstream: openai_upstream.clone(),
144        gemini_upstream: gemini_upstream.clone(),
145    };
146
147    let mut app = Router::new()
148        .route("/health", get(health))
149        .route("/status", get(status_handler))
150        .route("/v1/messages", any(anthropic::handler))
151        .route("/v1/messages/{*rest}", any(anthropic::handler))
152        .route("/v1/chat/completions", any(openai::handler))
153        .route("/v1/responses", any(openai_responses::handler))
154        .route("/v1/responses/{*rest}", any(openai_responses::handler))
155        // Bare provider endpoints (no `/v1` prefix). Clients whose base URL points
156        // at the proxy root — notably OpenCode via `@ai-sdk/openai`, whose
157        // Responses-API requests hit `/responses` — dispatch here. The
158        // `normalize_provider_path` layer rewrites the URI to its canonical
159        // `/v1/...` form before the handler forwards upstream (#353).
160        .route("/messages", any(anthropic::handler))
161        .route("/messages/{*rest}", any(anthropic::handler))
162        .route("/chat/completions", any(openai::handler))
163        .route("/responses", any(openai_responses::handler))
164        .route("/responses/{*rest}", any(openai_responses::handler))
165        .route("/v1/references/{id}", get(v1_resolve_reference))
166        .fallback(fallback_router)
167        .layer(axum::middleware::from_fn(host_guard))
168        .with_state(state);
169
170    {
171        let expected = auth_token.clone();
172        app = app.layer(axum::middleware::from_fn(move |req, next| {
173            let expected = expected.clone();
174            proxy_auth_guard(req, next, expected)
175        }));
176    }
177
178    // Outermost layer (runs first): normalize bare provider endpoints to their
179    // canonical `/v1/...` form so auth, routing and upstream forwarding all agree,
180    // regardless of whether the client's base URL includes `/v1` (#353).
181    app = app.layer(axum::middleware::from_fn(normalize_provider_path));
182
183    let addr = SocketAddr::from(([127, 0, 0, 1], port));
184    println!("lean-ctx proxy listening on http://{addr} (token auth enabled)");
185    println!("  Anthropic: POST /v1/messages → {anthropic_upstream}");
186    println!("  OpenAI:    POST /v1/chat/completions → {openai_upstream}");
187    println!("  OpenAI:    POST /v1/responses → {openai_upstream}");
188    println!("  Gemini:    POST /v1beta/models/... → {gemini_upstream}");
189
190    let listener = tokio::net::TcpListener::bind(addr).await?;
191    axum::serve(listener, app)
192        .with_graceful_shutdown(shutdown_signal())
193        .await?;
194
195    println!("lean-ctx proxy shut down cleanly.");
196    Ok(())
197}
198
199async fn shutdown_signal() {
200    let ctrl_c = tokio::signal::ctrl_c();
201
202    #[cfg(unix)]
203    {
204        // Fall back to Ctrl-C only if the SIGTERM handler cannot be installed,
205        // rather than panicking the proxy on startup.
206        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
207            Ok(mut sigterm) => {
208                tokio::select! {
209                    _ = ctrl_c => {},
210                    _ = sigterm.recv() => {},
211                }
212            }
213            Err(e) => {
214                tracing::warn!("lean-ctx proxy: SIGTERM handler unavailable ({e}); Ctrl-C only");
215                ctrl_c.await.ok();
216            }
217        }
218    }
219
220    #[cfg(not(unix))]
221    {
222        ctrl_c.await.ok();
223    }
224
225    println!("lean-ctx proxy: received shutdown signal, draining…");
226}
227
228async fn health() -> impl IntoResponse {
229    let body = serde_json::json!({
230        "status": "ok",
231        "pid": std::process::id(),
232    });
233    (StatusCode::OK, axum::Json(body))
234}
235
236async fn v1_resolve_reference(
237    axum::extract::Path(id): axum::extract::Path<String>,
238) -> impl IntoResponse {
239    match crate::server::reference_store::resolve(&id) {
240        Some(content) => (StatusCode::OK, content),
241        None => (
242            StatusCode::NOT_FOUND,
243            "Reference expired or not found".to_string(),
244        ),
245    }
246}
247
248async fn status_handler(State(state): State<ProxyState>) -> impl IntoResponse {
249    use std::sync::atomic::Ordering::Relaxed;
250    let s = &state.stats;
251    let i = &state.introspect;
252
253    let last_breakdown = i
254        .last_breakdown
255        .lock()
256        .ok()
257        .and_then(|guard| guard.as_ref().map(|b| serde_json::to_value(b).ok()))
258        .flatten();
259
260    let body = serde_json::json!({
261        "status": "running",
262        "port": state.port,
263        "requests_total": s.requests_total.load(Relaxed),
264        "requests_compressed": s.requests_compressed.load(Relaxed),
265        "tokens_saved": s.tokens_saved.load(Relaxed),
266        "tokens_saved_estimated": true,
267        "bytes_original": s.bytes_original.load(Relaxed),
268        "bytes_compressed": s.bytes_compressed.load(Relaxed),
269        "compression_ratio_pct": format!("{:.1}", s.compression_ratio()),
270        "per_model": cost::snapshot(),
271        "note": "Savings are request-side (tokens removed before forwarding); they do not subtract any re-reads the agent performs. Token figures are estimates; USD uses the shared model price table.",
272        "introspect": {
273            "total_requests_analyzed": i.total_requests.load(Relaxed),
274            "total_system_prompt_tokens": i.total_system_prompt_tokens.load(Relaxed),
275            "last_breakdown": last_breakdown,
276        }
277    });
278    (StatusCode::OK, axum::Json(body))
279}
280
281async fn proxy_auth_guard(
282    req: axum::extract::Request,
283    next: axum::middleware::Next,
284    expected_token: String,
285) -> Result<Response, Response> {
286    let path = req.uri().path();
287    if path == "/health" {
288        return Ok(next.run(req).await);
289    }
290
291    // Accept Bearer token (lean-ctx session token)
292    if let Some(auth) = req
293        .headers()
294        .get("authorization")
295        .and_then(|v| v.to_str().ok())
296    {
297        if let Some(token) = auth.strip_prefix("Bearer ") {
298            if constant_time_eq(token.as_bytes(), expected_token.as_bytes()) {
299                return Ok(next.run(req).await);
300            }
301        }
302    }
303
304    // Accept provider API keys on provider routes (loopback-only, host_guard runs first).
305    // AI tools like Claude Code send x-api-key, not Bearer tokens. Since the proxy
306    // only binds to 127.0.0.1, the presence of a valid API key header is sufficient
307    // to authenticate the request as coming from a local AI tool.
308    if has_provider_api_key(&req) && is_provider_route(path) {
309        return Ok(next.run(req).await);
310    }
311
312    let cfg = crate::core::config::Config::load();
313    let hint = match cfg.proxy_enabled {
314        Some(true) => "lean-ctx proxy requires authentication. Use a Bearer token (LEAN_CTX_PROXY_TOKEN) or configure your AI tool's API key.",
315        Some(false) => "lean-ctx proxy is disabled but still running. Run: lean-ctx proxy cleanup",
316        None => "lean-ctx proxy is not configured. Your AI tool's ANTHROPIC_BASE_URL may be pointing here by mistake. Fix: lean-ctx proxy cleanup  OR  lean-ctx proxy enable",
317    };
318
319    let body = serde_json::json!({
320        "type": "error",
321        "error": {
322            "type": "authentication_error",
323            "message": format!("401 Unauthorized — {hint}")
324        }
325    });
326
327    Err((StatusCode::UNAUTHORIZED, axum::Json(body)).into_response())
328}
329
330fn has_provider_api_key(req: &axum::extract::Request) -> bool {
331    let headers = req.headers();
332    // Provider-specific key headers: Anthropic `x-api-key`, Google
333    // `x-goog-api-key`, Azure `api-key`. Any non-empty value authenticates.
334    for key in ["x-api-key", "x-goog-api-key", "api-key"] {
335        if headers
336            .get(key)
337            .and_then(|v| v.to_str().ok())
338            .is_some_and(|v| !v.trim().is_empty())
339        {
340            return true;
341        }
342    }
343    // OpenAI-style `Authorization` auth. Accept ANY non-empty credential, not
344    // just `Bearer sk-`/`gsk_`: OpenAI-*compatible* providers driven through
345    // OpenCode/Codex (Azure, OpenRouter, Groq, vLLM/Ollama gateways, project &
346    // service-account keys) issue keys that don't carry those prefixes. The proxy
347    // binds to loopback only and never injects upstream credentials — it forwards
348    // this header verbatim, so an invalid key is rejected by the real upstream,
349    // never silently honoured. Gating provider routes on key *shape* only ever
350    // produced false 401s for those clients (#362).
351    if let Some(auth) = headers.get("authorization").and_then(|v| v.to_str().ok()) {
352        let auth = auth.trim();
353        let credential = auth
354            .strip_prefix("Bearer ")
355            .or_else(|| auth.strip_prefix("bearer "))
356            .unwrap_or(auth)
357            .trim();
358        // Reject an empty value or a bare scheme keyword carrying no token.
359        return !credential.is_empty() && !credential.eq_ignore_ascii_case("bearer");
360    }
361    false
362}
363
364fn is_provider_route(path: &str) -> bool {
365    path.starts_with("/v1/")
366        || path.starts_with("/v1beta/")
367        || path.starts_with("/chat/completions")
368        || path.starts_with("/responses")
369        || path.starts_with("/messages")
370}
371
372/// Maps a bare provider endpoint to its canonical `/v1/...` form, preserving any
373/// sub-path. Returns `None` when the path is already canonical or not a known
374/// provider endpoint.
375///
376/// Some OpenAI-compatible clients treat the configured base URL as the API root
377/// and append the bare endpoint, so they send `POST /responses` or
378/// `/chat/completions` instead of `/v1/responses` — notably OpenCode via
379/// `@ai-sdk/openai`, whose Responses-API requests land on `/responses`. The proxy
380/// and every upstream only know the `/v1/...` paths, so an un-prefixed request
381/// would 401 (not a provider route) and then 404 (no handler). (#353)
382fn canonical_provider_path(path: &str) -> Option<String> {
383    const BARE_TO_CANONICAL: &[(&str, &str)] = &[
384        ("/responses", "/v1/responses"),
385        ("/chat/completions", "/v1/chat/completions"),
386        ("/messages", "/v1/messages"),
387    ];
388    for (bare, canonical) in BARE_TO_CANONICAL {
389        if path == *bare {
390            return Some((*canonical).to_string());
391        }
392        if let Some(rest) = path.strip_prefix(&format!("{bare}/")) {
393            return Some(format!("{canonical}/{rest}"));
394        }
395    }
396    None
397}
398
399/// Returns the canonicalized URI for a bare provider endpoint (query preserved),
400/// or `None` when no rewrite is needed. Pure, so the rewrite is unit-testable
401/// without constructing axum middleware plumbing.
402fn normalized_provider_uri(uri: &axum::http::Uri) -> Option<axum::http::Uri> {
403    let canonical = canonical_provider_path(uri.path())?;
404    let new_path_and_query = match uri.query() {
405        Some(q) => format!("{canonical}?{q}"),
406        None => canonical,
407    };
408    new_path_and_query.parse::<axum::http::Uri>().ok()
409}
410
411/// Rewrites the request URI in place when it targets a bare provider endpoint, so
412/// downstream auth (`is_provider_route`), routing and upstream forwarding all see
413/// the canonical `/v1/...` path. (#353)
414async fn normalize_provider_path(
415    mut req: axum::extract::Request,
416    next: axum::middleware::Next,
417) -> Response {
418    if let Some(uri) = normalized_provider_uri(req.uri()) {
419        *req.uri_mut() = uri;
420    }
421    next.run(req).await
422}
423
424fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
425    use subtle::ConstantTimeEq;
426    if a.len() != b.len() {
427        return false;
428    }
429    bool::from(a.ct_eq(b))
430}
431
432async fn host_guard(
433    req: axum::extract::Request,
434    next: axum::middleware::Next,
435) -> Result<Response, StatusCode> {
436    if let Some(host) = req.headers().get("host").and_then(|v| v.to_str().ok()) {
437        let h = host.split(':').next().unwrap_or(host);
438        if matches!(h, "127.0.0.1" | "localhost" | "[::1]") {
439            return Ok(next.run(req).await);
440        }
441    }
442    Err(StatusCode::FORBIDDEN)
443}
444
445async fn fallback_router(State(state): State<ProxyState>, req: Request<Body>) -> Response {
446    let path = req.uri().path().to_string();
447
448    if path.starts_with("/v1beta/models/") || path.starts_with("/v1/models/") {
449        match google::handler(State(state), req).await {
450            Ok(resp) => resp,
451            Err(status) => Response::builder()
452                .status(status)
453                .body(Body::from("proxy error"))
454                .expect("BUG: building error response with valid status should never fail"),
455        }
456    } else {
457        let method = req.method().to_string();
458        eprintln!("lean-ctx proxy: unmatched {method} {path}");
459        Response::builder()
460            .status(StatusCode::NOT_FOUND)
461            .body(Body::from(format!(
462                "lean-ctx proxy: no handler for {method} {path}"
463            )))
464            .expect("BUG: building 404 response should never fail")
465    }
466}
467
468#[cfg(test)]
469mod auth_tests {
470    use super::*;
471
472    // P0-4 (#416): the proxy must never run unauthenticated — `None` means
473    // "resolve the session token", not "no auth".
474    #[test]
475    fn effective_auth_token_never_yields_empty() {
476        let _env = crate::core::data_dir::test_env_lock();
477        let tmp = tempfile::tempdir().unwrap();
478        std::env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
479
480        assert_eq!(effective_auth_token(Some("tok".into())), "tok");
481        let auto = effective_auth_token(None);
482        assert!(!auto.trim().is_empty(), "None must auto-resolve a token");
483        let blank = effective_auth_token(Some("   ".into()));
484        assert!(!blank.trim().is_empty(), "blank tokens must be replaced");
485
486        std::env::remove_var("LEAN_CTX_DATA_DIR");
487    }
488
489    #[test]
490    fn is_provider_route_v1() {
491        assert!(is_provider_route("/v1/chat/completions"));
492        assert!(is_provider_route("/v1/messages"));
493        assert!(is_provider_route("/v1/completions"));
494    }
495
496    #[test]
497    fn is_provider_route_anthropic_subpaths() {
498        assert!(is_provider_route("/v1/messages/count_tokens"));
499        assert!(is_provider_route("/v1/messages/batches"));
500        assert!(is_provider_route("/v1/messages/batches/batch_123"));
501    }
502
503    #[test]
504    fn is_provider_route_v1beta() {
505        assert!(is_provider_route("/v1beta/models"));
506    }
507
508    #[test]
509    fn is_provider_route_chat() {
510        assert!(is_provider_route("/chat/completions"));
511    }
512
513    #[test]
514    fn is_provider_route_rejects_non_provider() {
515        assert!(!is_provider_route("/health"));
516        assert!(!is_provider_route("/api/v2/test"));
517        assert!(!is_provider_route("/"));
518    }
519
520    fn build_request(headers: &[(&str, &str)], path: &str) -> axum::extract::Request {
521        let mut builder = axum::http::Request::builder().uri(path);
522        for (k, v) in headers {
523            builder = builder.header(*k, *v);
524        }
525        builder.body(axum::body::Body::empty()).unwrap()
526    }
527
528    #[test]
529    fn has_provider_api_key_x_api_key() {
530        let req = build_request(&[("x-api-key", "sk-ant-abc123")], "/v1/messages");
531        assert!(has_provider_api_key(&req));
532    }
533
534    #[test]
535    fn has_provider_api_key_x_goog() {
536        let req = build_request(&[("x-goog-api-key", "AIzaSyAbc")], "/v1beta/models");
537        assert!(has_provider_api_key(&req));
538    }
539
540    #[test]
541    fn has_provider_api_key_azure() {
542        let req = build_request(&[("api-key", "deadbeef")], "/v1/completions");
543        assert!(has_provider_api_key(&req));
544    }
545
546    #[test]
547    fn has_provider_api_key_bearer_sk() {
548        let req = build_request(
549            &[("authorization", "Bearer sk-proj-abc123")],
550            "/v1/chat/completions",
551        );
552        assert!(has_provider_api_key(&req));
553    }
554
555    #[test]
556    fn has_provider_api_key_empty_rejected() {
557        let req = build_request(&[("x-api-key", "  ")], "/v1/messages");
558        assert!(!has_provider_api_key(&req));
559    }
560
561    #[test]
562    fn has_provider_api_key_no_headers() {
563        let req = build_request(&[], "/v1/messages");
564        assert!(!has_provider_api_key(&req));
565    }
566
567    #[test]
568    fn has_provider_api_key_accepts_non_sk_bearer() {
569        // #362: OpenAI-*compatible* providers (Azure, OpenRouter, Groq, vLLM/
570        // Ollama gateways, project/service keys) issue keys without the sk-/gsk_
571        // prefix. OpenCode (@ai-sdk/openai) forwards them as `Bearer <key>`; they
572        // must authenticate on a loopback provider route. The upstream validates
573        // the real key — the proxy never injects one.
574        for key in [
575            "Bearer or-v1-9f8e7d6c", // OpenRouter
576            "Bearer gsk_live_1234",  // (still works)
577            "Bearer abc.def.ghi",    // gateway/service token
578            "Bearer 0123456789",     // opaque
579        ] {
580            let req = build_request(&[("authorization", key)], "/v1/responses");
581            assert!(
582                has_provider_api_key(&req),
583                "non-sk Bearer must count as a provider credential: {key}"
584            );
585        }
586    }
587
588    #[test]
589    fn has_provider_api_key_empty_bearer_rejected() {
590        // A blank credential — or a bare scheme word with no token (some HTTP
591        // stacks trim trailing whitespace down to just "Bearer") — is not auth.
592        for bad in ["Bearer    ", "", "Bearer", "bearer", "   "] {
593            let req = build_request(&[("authorization", bad)], "/responses");
594            assert!(
595                !has_provider_api_key(&req),
596                "blank/scheme-only Authorization must not authenticate: {bad:?}"
597            );
598        }
599    }
600
601    // --- #353: bare provider endpoints (OpenCode / @ai-sdk/openai) ---
602
603    #[test]
604    fn is_provider_route_bare_responses_and_messages() {
605        // Clients that point their base URL at the proxy root (no `/v1`) send the
606        // bare endpoint; auth must still recognise it as a provider route.
607        assert!(is_provider_route("/responses"));
608        assert!(is_provider_route("/responses/resp_123/input_items"));
609        assert!(is_provider_route("/messages"));
610    }
611
612    #[test]
613    fn canonical_provider_path_rewrites_bare_endpoints() {
614        assert_eq!(
615            canonical_provider_path("/responses").as_deref(),
616            Some("/v1/responses")
617        );
618        assert_eq!(
619            canonical_provider_path("/chat/completions").as_deref(),
620            Some("/v1/chat/completions")
621        );
622        assert_eq!(
623            canonical_provider_path("/messages").as_deref(),
624            Some("/v1/messages")
625        );
626    }
627
628    #[test]
629    fn canonical_provider_path_preserves_subpaths() {
630        assert_eq!(
631            canonical_provider_path("/responses/resp_abc/cancel").as_deref(),
632            Some("/v1/responses/resp_abc/cancel")
633        );
634        assert_eq!(
635            canonical_provider_path("/messages/batches/batch_1").as_deref(),
636            Some("/v1/messages/batches/batch_1")
637        );
638    }
639
640    #[test]
641    fn canonical_provider_path_ignores_already_canonical_and_unknown() {
642        // Already canonical → no rewrite (avoids `/v1/v1/...`).
643        assert_eq!(canonical_provider_path("/v1/responses"), None);
644        assert_eq!(canonical_provider_path("/v1/chat/completions"), None);
645        // Unrelated paths are untouched.
646        assert_eq!(canonical_provider_path("/health"), None);
647        assert_eq!(canonical_provider_path("/responsesx"), None);
648        assert_eq!(canonical_provider_path("/"), None);
649    }
650
651    #[test]
652    fn normalized_provider_uri_rewrites_path_and_preserves_query() {
653        use axum::http::Uri;
654        let uri: Uri = "/responses?stream=true".parse().unwrap();
655        let rewritten = normalized_provider_uri(&uri).expect("bare /responses must rewrite");
656        assert_eq!(rewritten.path(), "/v1/responses");
657        assert_eq!(rewritten.query(), Some("stream=true"));
658        assert_eq!(
659            rewritten
660                .path_and_query()
661                .map(axum::http::uri::PathAndQuery::as_str),
662            Some("/v1/responses?stream=true")
663        );
664    }
665
666    #[test]
667    fn normalized_provider_uri_noop_for_canonical() {
668        use axum::http::Uri;
669        let uri: Uri = "/v1/responses".parse().unwrap();
670        assert!(normalized_provider_uri(&uri).is_none());
671    }
672}