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 openai_responses_ws;
12pub mod tool_kind;
13pub mod usage;
14pub mod usage_meter;
15
16use std::net::SocketAddr;
17use std::sync::Arc;
18use std::sync::atomic::{AtomicU64, Ordering};
19
20use crate::core::config::Upstreams;
21
22use axum::{
23    Router,
24    body::Body,
25    extract::State,
26    http::{Request, StatusCode},
27    response::{IntoResponse, Response},
28    routing::{any, get, post},
29};
30
31#[derive(Clone)]
32pub struct ProxyState {
33    pub client: reqwest::Client,
34    pub port: u16,
35    pub stats: Arc<ProxyStats>,
36    pub introspect: Arc<introspect::IntrospectState>,
37    /// Live provider upstreams, refreshed from config.toml without a proxy
38    /// restart (#449). Read per request via [`ProxyState::openai_upstream`] etc.
39    pub upstreams: tokio::sync::watch::Receiver<Arc<Upstreams>>,
40}
41
42impl ProxyState {
43    /// Consistent snapshot of all upstreams for the current request/response.
44    pub fn upstream_snapshot(&self) -> Arc<Upstreams> {
45        self.upstreams.borrow().clone()
46    }
47
48    /// Current Anthropic upstream (live).
49    pub fn anthropic_upstream(&self) -> String {
50        self.upstreams.borrow().anthropic.clone()
51    }
52
53    /// Current OpenAI upstream (live).
54    pub fn openai_upstream(&self) -> String {
55        self.upstreams.borrow().openai.clone()
56    }
57
58    /// Current Gemini upstream (live).
59    pub fn gemini_upstream(&self) -> String {
60        self.upstreams.borrow().gemini.clone()
61    }
62}
63
64pub struct ProxyStats {
65    pub requests_total: AtomicU64,
66    pub requests_compressed: AtomicU64,
67    pub tokens_saved: AtomicU64,
68    pub bytes_original: AtomicU64,
69    pub bytes_compressed: AtomicU64,
70}
71
72impl Default for ProxyStats {
73    fn default() -> Self {
74        Self {
75            requests_total: AtomicU64::new(0),
76            requests_compressed: AtomicU64::new(0),
77            tokens_saved: AtomicU64::new(0),
78            bytes_original: AtomicU64::new(0),
79            bytes_compressed: AtomicU64::new(0),
80        }
81    }
82}
83
84impl ProxyStats {
85    pub fn record_request(&self) {
86        self.requests_total.fetch_add(1, Ordering::Relaxed);
87    }
88
89    pub fn record_compression(&self, original: usize, compressed: usize) {
90        self.requests_compressed.fetch_add(1, Ordering::Relaxed);
91        self.bytes_original
92            .fetch_add(original as u64, Ordering::Relaxed);
93        self.bytes_compressed
94            .fetch_add(compressed as u64, Ordering::Relaxed);
95        let saved_tokens = (original.saturating_sub(compressed) / 4) as u64;
96        self.tokens_saved.fetch_add(saved_tokens, Ordering::Relaxed);
97    }
98
99    pub fn compression_ratio(&self) -> f64 {
100        let original = self.bytes_original.load(Ordering::Relaxed);
101        if original == 0 {
102            return 0.0;
103        }
104        let compressed = self.bytes_compressed.load(Ordering::Relaxed);
105        (1.0 - compressed as f64 / original as f64) * 100.0
106    }
107}
108
109/// TCP connect timeout (seconds). Configurable via `LEAN_CTX_PROXY_CONNECT_TIMEOUT_SECS`.
110fn connect_timeout_secs() -> u64 {
111    std::env::var("LEAN_CTX_PROXY_CONNECT_TIMEOUT_SECS")
112        .ok()
113        .and_then(|v| v.trim().parse::<u64>().ok())
114        .filter(|s| *s > 0)
115        .unwrap_or(15)
116}
117
118/// Idle read timeout (seconds) between bytes from upstream. Generous by default
119/// so long extended-thinking phases (which still emit SSE keepalives) are never
120/// cut, while a truly dead connection eventually fails. Configurable via
121/// `LEAN_CTX_PROXY_READ_TIMEOUT_SECS`.
122fn read_idle_timeout_secs() -> u64 {
123    std::env::var("LEAN_CTX_PROXY_READ_TIMEOUT_SECS")
124        .ok()
125        .and_then(|v| v.trim().parse::<u64>().ok())
126        .filter(|s| *s > 0)
127        .unwrap_or(300)
128}
129
130/// How often (seconds) a running proxy re-reads config.toml for upstream
131/// changes. `LEAN_CTX_PROXY_RELOAD_SECS` overrides; default 5s.
132fn upstream_reload_secs() -> u64 {
133    std::env::var("LEAN_CTX_PROXY_RELOAD_SECS")
134        .ok()
135        .and_then(|v| v.trim().parse::<u64>().ok())
136        .filter(|s| *s > 0)
137        .unwrap_or(5)
138}
139
140/// Background task: re-resolves the provider upstreams from config.toml on an
141/// interval and publishes any change to the live request handlers (#449). Ends
142/// once every receiver (the proxy itself) has been dropped.
143///
144/// `Config::load()` already keeps an internal content-hash cache, so re-reading
145/// an unchanged `config.toml` skips the TOML parse + merge and costs only a small
146/// file read; combined with the relaxed default interval (#453) the idle steady
147/// state is negligible without needing a separate stat pre-check.
148fn spawn_upstream_refresh(tx: tokio::sync::watch::Sender<Arc<Upstreams>>, initial: Upstreams) {
149    let interval = std::time::Duration::from_secs(upstream_reload_secs());
150    tokio::spawn(async move {
151        let mut last = initial;
152        loop {
153            tokio::time::sleep(interval).await;
154            let next = crate::core::config::Config::load()
155                .proxy
156                .refresh_upstreams(&last);
157            if next != last {
158                log_upstream_change(&last, &next);
159                last = next.clone();
160                if tx.send(Arc::new(next)).is_err() {
161                    break;
162                }
163            }
164        }
165    });
166}
167
168/// One stdout line per changed provider, matching the startup banner style so a
169/// running proxy's log shows when (and to what) an upstream switched.
170fn log_upstream_change(old: &Upstreams, new: &Upstreams) {
171    if old.anthropic != new.anthropic {
172        println!("  ↻ Anthropic upstream → {}", new.anthropic);
173    }
174    if old.openai != new.openai {
175        println!("  ↻ OpenAI upstream → {}", new.openai);
176    }
177    if old.gemini != new.gemini {
178        println!("  ↻ Gemini upstream → {}", new.gemini);
179    }
180}
181
182pub async fn start_proxy(port: u16) -> anyhow::Result<()> {
183    let token = crate::core::session_token::resolve_proxy_token("LEAN_CTX_PROXY_TOKEN");
184    start_proxy_with_token(port, Some(token)).await
185}
186
187/// Security invariant: the proxy NEVER runs unauthenticated. `None` does not
188/// mean "no auth" — it means "resolve the session token for me". Provider
189/// routes additionally accept provider API keys (see `proxy_auth_guard`), so
190/// IDE clients keep working without any setup.
191fn effective_auth_token(auth_token: Option<String>) -> String {
192    auth_token
193        .filter(|t| !t.trim().is_empty())
194        .unwrap_or_else(|| crate::core::session_token::resolve_proxy_token("LEAN_CTX_PROXY_TOKEN"))
195}
196
197pub async fn start_proxy_with_token(port: u16, auth_token: Option<String>) -> anyhow::Result<()> {
198    use crate::core::config::{Config, is_local_proxy_url};
199
200    let auth_token = effective_auth_token(auth_token);
201
202    // A single total timeout aborts long streaming generations (e.g. Opus doing
203    // a big refactor) mid-response. Use a connect timeout plus a read (idle)
204    // timeout instead: a genuinely hung upstream still fails, but a slow-but-
205    // alive stream is never cut off. Both are configurable for edge networks.
206    let client = reqwest::Client::builder()
207        .connect_timeout(std::time::Duration::from_secs(connect_timeout_secs()))
208        .read_timeout(std::time::Duration::from_secs(read_idle_timeout_secs()))
209        .build()?;
210
211    // Seed the measured-spend meter from disk so a proxy restart never zeroes
212    // the user's cumulative real provider bill.
213    usage_meter::resume_from_disk();
214
215    let cfg = Config::load();
216    let initial = cfg.proxy.resolve_all();
217
218    // The proxy reads its upstreams live from a watch channel: a background task
219    // re-resolves them from config.toml on an interval and publishes any change,
220    // so `lean-ctx config set proxy.*_upstream` (or any config.toml edit) takes
221    // effect on the running proxy within seconds, without a restart (#449).
222    let (upstream_tx, upstream_rx) = tokio::sync::watch::channel(Arc::new(initial.clone()));
223    spawn_upstream_refresh(upstream_tx, initial.clone());
224
225    let Upstreams {
226        anthropic: anthropic_upstream,
227        openai: openai_upstream,
228        gemini: gemini_upstream,
229    } = initial;
230
231    let state = ProxyState {
232        client,
233        port,
234        stats: Arc::new(ProxyStats::default()),
235        introspect: Arc::new(introspect::IntrospectState::default()),
236        upstreams: upstream_rx,
237    };
238
239    let mut app = Router::new()
240        .route("/health", get(health))
241        .route("/status", get(status_handler))
242        .route("/v1/messages", any(anthropic::handler))
243        .route("/v1/messages/{*rest}", any(anthropic::handler))
244        .route("/v1/chat/completions", any(openai::handler))
245        // POST → HTTP/SSE forwarder; GET → Codex/OpenAI WebSocket bridge (#440).
246        .route(
247            "/v1/responses",
248            post(openai_responses::handler).get(openai_responses::ws_handler),
249        )
250        .route("/v1/responses/{*rest}", any(openai_responses::handler))
251        // Bare provider endpoints (no `/v1` prefix). Clients whose base URL points
252        // at the proxy root — notably OpenCode via `@ai-sdk/openai`, whose
253        // Responses-API requests hit `/responses` — dispatch here. The
254        // `normalize_provider_path` layer rewrites the URI to its canonical
255        // `/v1/...` form before the handler forwards upstream (#353).
256        .route("/messages", any(anthropic::handler))
257        .route("/messages/{*rest}", any(anthropic::handler))
258        .route("/chat/completions", any(openai::handler))
259        .route(
260            "/responses",
261            post(openai_responses::handler).get(openai_responses::ws_handler),
262        )
263        .route("/responses/{*rest}", any(openai_responses::handler))
264        .route("/v1/references/{id}", get(v1_resolve_reference))
265        .fallback(fallback_router)
266        .layer(axum::middleware::from_fn(host_guard))
267        .with_state(state);
268
269    {
270        let expected = auth_token.clone();
271        app = app.layer(axum::middleware::from_fn(move |req, next| {
272            let expected = expected.clone();
273            proxy_auth_guard(req, next, expected)
274        }));
275    }
276
277    // Outermost layer (runs first): normalize bare provider endpoints to their
278    // canonical `/v1/...` form so auth, routing and upstream forwarding all agree,
279    // regardless of whether the client's base URL includes `/v1` (#353).
280    app = app.layer(axum::middleware::from_fn(normalize_provider_path));
281
282    let addr = SocketAddr::from(([127, 0, 0, 1], port));
283    println!("lean-ctx proxy listening on http://{addr} (token auth enabled)");
284    println!("  Anthropic: POST /v1/messages → {anthropic_upstream}");
285    println!("  OpenAI:    POST /v1/chat/completions → {openai_upstream}");
286    println!(
287        "  OpenAI:    POST /v1/responses → {openai_upstream}  (bare /responses also accepted)"
288    );
289    println!("  Gemini:    POST /v1beta/models/... → {gemini_upstream}");
290    // Codex defaults to a WebSocket Responses transport (ws://…/responses). The
291    // proxy now bridges it to the HTTP/SSE upstream (#440), so Codex works as a
292    // drop-in without a `supports_websockets = false` workaround.
293    println!(
294        "  Codex:     WS  ws://{addr}/responses → bridged to {openai_upstream} (HTTP/SSE, #440)"
295    );
296    if openai_upstream.starts_with("http://") && !is_local_proxy_url(&openai_upstream) {
297        println!(
298            "  ⚠ OpenAI upstream is plaintext HTTP to a non-loopback host \
299             (allow_insecure_http_upstream) — use only on a trusted local network"
300        );
301    }
302
303    let listener = tokio::net::TcpListener::bind(addr).await?;
304    axum::serve(listener, app)
305        .with_graceful_shutdown(shutdown_signal())
306        .await?;
307
308    println!("lean-ctx proxy shut down cleanly.");
309    Ok(())
310}
311
312async fn shutdown_signal() {
313    let ctrl_c = tokio::signal::ctrl_c();
314
315    #[cfg(unix)]
316    {
317        // Fall back to Ctrl-C only if the SIGTERM handler cannot be installed,
318        // rather than panicking the proxy on startup.
319        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
320            Ok(mut sigterm) => {
321                tokio::select! {
322                    _ = ctrl_c => {},
323                    _ = sigterm.recv() => {},
324                }
325            }
326            Err(e) => {
327                tracing::warn!("lean-ctx proxy: SIGTERM handler unavailable ({e}); Ctrl-C only");
328                ctrl_c.await.ok();
329            }
330        }
331    }
332
333    #[cfg(not(unix))]
334    {
335        ctrl_c.await.ok();
336    }
337
338    println!("lean-ctx proxy: received shutdown signal, draining…");
339}
340
341async fn health() -> impl IntoResponse {
342    let body = serde_json::json!({
343        "status": "ok",
344        "pid": std::process::id(),
345    });
346    (StatusCode::OK, axum::Json(body))
347}
348
349async fn v1_resolve_reference(
350    axum::extract::Path(id): axum::extract::Path<String>,
351) -> impl IntoResponse {
352    match crate::server::reference_store::resolve(&id) {
353        Some(content) => (StatusCode::OK, content),
354        None => (
355            StatusCode::NOT_FOUND,
356            "Reference expired or not found".to_string(),
357        ),
358    }
359}
360
361async fn status_handler(State(state): State<ProxyState>) -> impl IntoResponse {
362    use std::sync::atomic::Ordering::Relaxed;
363    let s = &state.stats;
364    let i = &state.introspect;
365
366    let last_breakdown = i
367        .last_breakdown
368        .lock()
369        .ok()
370        .and_then(|guard| guard.as_ref().map(|b| serde_json::to_value(b).ok()))
371        .flatten();
372
373    // Measured spend: real model + billed tokens read from provider responses.
374    let spend = usage_meter::snapshot();
375    let spend_total: f64 = spend.iter().map(|m| m.cost_usd).sum();
376
377    // Live upstreams the proxy is forwarding to right now (#449). This is the
378    // single source of truth for "where is my traffic actually going" — it
379    // reflects config.toml hot-reloads and any start-time env override.
380    let up = state.upstream_snapshot();
381
382    let body = serde_json::json!({
383        "status": "running",
384        "port": state.port,
385        "upstreams": {
386            "anthropic": up.anthropic.clone(),
387            "openai": up.openai.clone(),
388            "gemini": up.gemini.clone(),
389        },
390        "requests_total": s.requests_total.load(Relaxed),
391        "requests_compressed": s.requests_compressed.load(Relaxed),
392        "tokens_saved": s.tokens_saved.load(Relaxed),
393        "tokens_saved_estimated": true,
394        "bytes_original": s.bytes_original.load(Relaxed),
395        "bytes_compressed": s.bytes_compressed.load(Relaxed),
396        "compression_ratio_pct": format!("{:.1}", s.compression_ratio()),
397        "per_model": cost::snapshot(),
398        "spend": {
399            "source": "measured",
400            "total_usd": spend_total,
401            "per_model": spend,
402            "note": "Actual provider bill: real model + billed tokens (incl. cache reads/writes & reasoning) read from upstream responses for proxy-routed clients."
403        },
404        "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.",
405        "introspect": {
406            "total_requests_analyzed": i.total_requests.load(Relaxed),
407            "total_system_prompt_tokens": i.total_system_prompt_tokens.load(Relaxed),
408            "last_breakdown": last_breakdown,
409        }
410    });
411    (StatusCode::OK, axum::Json(body))
412}
413
414async fn proxy_auth_guard(
415    req: axum::extract::Request,
416    next: axum::middleware::Next,
417    expected_token: String,
418) -> Result<Response, Response> {
419    let path = req.uri().path();
420    if path == "/health" {
421        return Ok(next.run(req).await);
422    }
423
424    // Accept Bearer token (lean-ctx session token)
425    if let Some(auth) = req
426        .headers()
427        .get("authorization")
428        .and_then(|v| v.to_str().ok())
429        && let Some(token) = auth.strip_prefix("Bearer ")
430        && constant_time_eq(token.as_bytes(), expected_token.as_bytes())
431    {
432        return Ok(next.run(req).await);
433    }
434
435    // Accept provider API keys on provider routes (loopback-only, host_guard runs first).
436    // AI tools like Claude Code send x-api-key, not Bearer tokens. Since the proxy
437    // only binds to 127.0.0.1, the presence of a valid API key header is sufficient
438    // to authenticate the request as coming from a local AI tool.
439    if has_provider_api_key(&req) && is_provider_route(path) {
440        return Ok(next.run(req).await);
441    }
442
443    let cfg = crate::core::config::Config::load();
444    let hint = match cfg.proxy_enabled {
445        Some(true) => {
446            "lean-ctx proxy requires authentication. Use a Bearer token (LEAN_CTX_PROXY_TOKEN) or configure your AI tool's API key."
447        }
448        Some(false) => "lean-ctx proxy is disabled but still running. Run: lean-ctx proxy cleanup",
449        None => {
450            "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"
451        }
452    };
453
454    let body = serde_json::json!({
455        "type": "error",
456        "error": {
457            "type": "authentication_error",
458            "message": format!("401 Unauthorized — {hint}")
459        }
460    });
461
462    Err((StatusCode::UNAUTHORIZED, axum::Json(body)).into_response())
463}
464
465fn has_provider_api_key(req: &axum::extract::Request) -> bool {
466    let headers = req.headers();
467    // Provider-specific key headers: Anthropic `x-api-key`, Google
468    // `x-goog-api-key`, Azure `api-key`. Any non-empty value authenticates.
469    for key in ["x-api-key", "x-goog-api-key", "api-key"] {
470        if headers
471            .get(key)
472            .and_then(|v| v.to_str().ok())
473            .is_some_and(|v| !v.trim().is_empty())
474        {
475            return true;
476        }
477    }
478    // OpenAI-style `Authorization` auth. Accept ANY non-empty credential, not
479    // just `Bearer sk-`/`gsk_`: OpenAI-*compatible* providers driven through
480    // OpenCode/Codex (Azure, OpenRouter, Groq, vLLM/Ollama gateways, project &
481    // service-account keys) issue keys that don't carry those prefixes. The proxy
482    // binds to loopback only and never injects upstream credentials — it forwards
483    // this header verbatim, so an invalid key is rejected by the real upstream,
484    // never silently honoured. Gating provider routes on key *shape* only ever
485    // produced false 401s for those clients (#362).
486    if let Some(auth) = headers.get("authorization").and_then(|v| v.to_str().ok()) {
487        let auth = auth.trim();
488        let credential = auth
489            .strip_prefix("Bearer ")
490            .or_else(|| auth.strip_prefix("bearer "))
491            .unwrap_or(auth)
492            .trim();
493        // Reject an empty value or a bare scheme keyword carrying no token.
494        return !credential.is_empty() && !credential.eq_ignore_ascii_case("bearer");
495    }
496    false
497}
498
499fn is_provider_route(path: &str) -> bool {
500    path.starts_with("/v1/")
501        || path.starts_with("/v1beta/")
502        || path.starts_with("/chat/completions")
503        || path.starts_with("/responses")
504        || path.starts_with("/messages")
505}
506
507/// Maps a bare provider endpoint to its canonical `/v1/...` form, preserving any
508/// sub-path. Returns `None` when the path is already canonical or not a known
509/// provider endpoint.
510///
511/// Some OpenAI-compatible clients treat the configured base URL as the API root
512/// and append the bare endpoint, so they send `POST /responses` or
513/// `/chat/completions` instead of `/v1/responses` — notably OpenCode via
514/// `@ai-sdk/openai`, whose Responses-API requests land on `/responses`. The proxy
515/// and every upstream only know the `/v1/...` paths, so an un-prefixed request
516/// would 401 (not a provider route) and then 404 (no handler). (#353)
517fn canonical_provider_path(path: &str) -> Option<String> {
518    // Inverse case of the bare-endpoint rewrite below: the advertised
519    // OPENAI_BASE_URL includes `/v1` (#366), so a client that treats the base URL
520    // as an origin and appends `/v1/...` itself produces `/v1/v1/...`.
521    if let Some(rest) = path.strip_prefix("/v1/v1/") {
522        return Some(format!("/v1/{rest}"));
523    }
524    const BARE_TO_CANONICAL: &[(&str, &str)] = &[
525        ("/responses", "/v1/responses"),
526        ("/chat/completions", "/v1/chat/completions"),
527        ("/messages", "/v1/messages"),
528    ];
529    for (bare, canonical) in BARE_TO_CANONICAL {
530        if path == *bare {
531            return Some((*canonical).to_string());
532        }
533        if let Some(rest) = path.strip_prefix(&format!("{bare}/")) {
534            return Some(format!("{canonical}/{rest}"));
535        }
536    }
537    None
538}
539
540/// Returns the canonicalized URI for a bare provider endpoint (query preserved),
541/// or `None` when no rewrite is needed. Pure, so the rewrite is unit-testable
542/// without constructing axum middleware plumbing.
543fn normalized_provider_uri(uri: &axum::http::Uri) -> Option<axum::http::Uri> {
544    let canonical = canonical_provider_path(uri.path())?;
545    let new_path_and_query = match uri.query() {
546        Some(q) => format!("{canonical}?{q}"),
547        None => canonical,
548    };
549    new_path_and_query.parse::<axum::http::Uri>().ok()
550}
551
552/// Rewrites the request URI in place when it targets a bare provider endpoint, so
553/// downstream auth (`is_provider_route`), routing and upstream forwarding all see
554/// the canonical `/v1/...` path. (#353)
555async fn normalize_provider_path(
556    mut req: axum::extract::Request,
557    next: axum::middleware::Next,
558) -> Response {
559    if let Some(uri) = normalized_provider_uri(req.uri()) {
560        *req.uri_mut() = uri;
561    }
562    next.run(req).await
563}
564
565fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
566    use subtle::ConstantTimeEq;
567    if a.len() != b.len() {
568        return false;
569    }
570    bool::from(a.ct_eq(b))
571}
572
573async fn host_guard(
574    req: axum::extract::Request,
575    next: axum::middleware::Next,
576) -> Result<Response, StatusCode> {
577    if let Some(host) = req.headers().get("host").and_then(|v| v.to_str().ok()) {
578        let h = host.split(':').next().unwrap_or(host);
579        if matches!(h, "127.0.0.1" | "localhost" | "[::1]") {
580            return Ok(next.run(req).await);
581        }
582    }
583    Err(StatusCode::FORBIDDEN)
584}
585
586async fn fallback_router(State(state): State<ProxyState>, req: Request<Body>) -> Response {
587    let path = req.uri().path().to_string();
588
589    if path.starts_with("/v1beta/models/") || path.starts_with("/v1/models/") {
590        match google::handler(State(state), req).await {
591            Ok(resp) => resp,
592            Err(status) => Response::builder()
593                .status(status)
594                .body(Body::from("proxy error"))
595                .expect("BUG: building error response with valid status should never fail"),
596        }
597    } else {
598        let method = req.method().to_string();
599        eprintln!("lean-ctx proxy: unmatched {method} {path}");
600        Response::builder()
601            .status(StatusCode::NOT_FOUND)
602            .body(Body::from(format!(
603                "lean-ctx proxy: no handler for {method} {path}"
604            )))
605            .expect("BUG: building 404 response should never fail")
606    }
607}
608
609#[cfg(test)]
610mod auth_tests {
611    use super::*;
612
613    // P0-4 (#416): the proxy must never run unauthenticated — `None` means
614    // "resolve the session token", not "no auth".
615    #[test]
616    fn effective_auth_token_never_yields_empty() {
617        let _env = crate::core::data_dir::test_env_lock();
618        let tmp = tempfile::tempdir().unwrap();
619        crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
620
621        assert_eq!(effective_auth_token(Some("tok".into())), "tok");
622        let auto = effective_auth_token(None);
623        assert!(!auto.trim().is_empty(), "None must auto-resolve a token");
624        let blank = effective_auth_token(Some("   ".into()));
625        assert!(!blank.trim().is_empty(), "blank tokens must be replaced");
626
627        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
628    }
629
630    #[test]
631    fn is_provider_route_v1() {
632        assert!(is_provider_route("/v1/chat/completions"));
633        assert!(is_provider_route("/v1/messages"));
634        assert!(is_provider_route("/v1/completions"));
635    }
636
637    #[test]
638    fn is_provider_route_anthropic_subpaths() {
639        assert!(is_provider_route("/v1/messages/count_tokens"));
640        assert!(is_provider_route("/v1/messages/batches"));
641        assert!(is_provider_route("/v1/messages/batches/batch_123"));
642    }
643
644    #[test]
645    fn is_provider_route_v1beta() {
646        assert!(is_provider_route("/v1beta/models"));
647    }
648
649    #[test]
650    fn is_provider_route_chat() {
651        assert!(is_provider_route("/chat/completions"));
652    }
653
654    #[test]
655    fn is_provider_route_rejects_non_provider() {
656        assert!(!is_provider_route("/health"));
657        assert!(!is_provider_route("/api/v2/test"));
658        assert!(!is_provider_route("/"));
659    }
660
661    fn build_request(headers: &[(&str, &str)], path: &str) -> axum::extract::Request {
662        let mut builder = axum::http::Request::builder().uri(path);
663        for (k, v) in headers {
664            builder = builder.header(*k, *v);
665        }
666        builder.body(axum::body::Body::empty()).unwrap()
667    }
668
669    #[test]
670    fn has_provider_api_key_x_api_key() {
671        let req = build_request(&[("x-api-key", "sk-ant-abc123")], "/v1/messages");
672        assert!(has_provider_api_key(&req));
673    }
674
675    #[test]
676    fn has_provider_api_key_x_goog() {
677        let req = build_request(&[("x-goog-api-key", "AIzaSyAbc")], "/v1beta/models");
678        assert!(has_provider_api_key(&req));
679    }
680
681    #[test]
682    fn has_provider_api_key_azure() {
683        let req = build_request(&[("api-key", "deadbeef")], "/v1/completions");
684        assert!(has_provider_api_key(&req));
685    }
686
687    #[test]
688    fn has_provider_api_key_bearer_sk() {
689        let req = build_request(
690            &[("authorization", "Bearer sk-proj-abc123")],
691            "/v1/chat/completions",
692        );
693        assert!(has_provider_api_key(&req));
694    }
695
696    #[test]
697    fn has_provider_api_key_empty_rejected() {
698        let req = build_request(&[("x-api-key", "  ")], "/v1/messages");
699        assert!(!has_provider_api_key(&req));
700    }
701
702    #[test]
703    fn has_provider_api_key_no_headers() {
704        let req = build_request(&[], "/v1/messages");
705        assert!(!has_provider_api_key(&req));
706    }
707
708    #[test]
709    fn has_provider_api_key_accepts_non_sk_bearer() {
710        // #362: OpenAI-*compatible* providers (Azure, OpenRouter, Groq, vLLM/
711        // Ollama gateways, project/service keys) issue keys without the sk-/gsk_
712        // prefix. OpenCode (@ai-sdk/openai) forwards them as `Bearer <key>`; they
713        // must authenticate on a loopback provider route. The upstream validates
714        // the real key — the proxy never injects one.
715        for key in [
716            "Bearer or-v1-9f8e7d6c", // OpenRouter
717            "Bearer gsk_live_1234",  // (still works)
718            "Bearer abc.def.ghi",    // gateway/service token
719            "Bearer 0123456789",     // opaque
720        ] {
721            let req = build_request(&[("authorization", key)], "/v1/responses");
722            assert!(
723                has_provider_api_key(&req),
724                "non-sk Bearer must count as a provider credential: {key}"
725            );
726        }
727    }
728
729    #[test]
730    fn has_provider_api_key_empty_bearer_rejected() {
731        // A blank credential — or a bare scheme word with no token (some HTTP
732        // stacks trim trailing whitespace down to just "Bearer") — is not auth.
733        for bad in ["Bearer    ", "", "Bearer", "bearer", "   "] {
734            let req = build_request(&[("authorization", bad)], "/responses");
735            assert!(
736                !has_provider_api_key(&req),
737                "blank/scheme-only Authorization must not authenticate: {bad:?}"
738            );
739        }
740    }
741
742    // --- #353: bare provider endpoints (OpenCode / @ai-sdk/openai) ---
743
744    #[test]
745    fn is_provider_route_bare_responses_and_messages() {
746        // Clients that point their base URL at the proxy root (no `/v1`) send the
747        // bare endpoint; auth must still recognise it as a provider route.
748        assert!(is_provider_route("/responses"));
749        assert!(is_provider_route("/responses/resp_123/input_items"));
750        assert!(is_provider_route("/messages"));
751    }
752
753    #[test]
754    fn canonical_provider_path_rewrites_bare_endpoints() {
755        assert_eq!(
756            canonical_provider_path("/responses").as_deref(),
757            Some("/v1/responses")
758        );
759        assert_eq!(
760            canonical_provider_path("/chat/completions").as_deref(),
761            Some("/v1/chat/completions")
762        );
763        assert_eq!(
764            canonical_provider_path("/messages").as_deref(),
765            Some("/v1/messages")
766        );
767    }
768
769    #[test]
770    fn canonical_provider_path_preserves_subpaths() {
771        assert_eq!(
772            canonical_provider_path("/responses/resp_abc/cancel").as_deref(),
773            Some("/v1/responses/resp_abc/cancel")
774        );
775        assert_eq!(
776            canonical_provider_path("/messages/batches/batch_1").as_deref(),
777            Some("/v1/messages/batches/batch_1")
778        );
779    }
780
781    #[test]
782    fn canonical_provider_path_ignores_already_canonical_and_unknown() {
783        // Already canonical → no rewrite (avoids `/v1/v1/...`).
784        assert_eq!(canonical_provider_path("/v1/responses"), None);
785        assert_eq!(canonical_provider_path("/v1/chat/completions"), None);
786        // Unrelated paths are untouched.
787        assert_eq!(canonical_provider_path("/health"), None);
788        assert_eq!(canonical_provider_path("/responsesx"), None);
789        assert_eq!(canonical_provider_path("/"), None);
790    }
791
792    #[test]
793    fn canonical_provider_path_collapses_double_v1_prefix() {
794        // OPENAI_BASE_URL now advertises `/v1` (#366); a client treating it as an
795        // origin and appending `/v1/...` itself produces a double prefix.
796        assert_eq!(
797            canonical_provider_path("/v1/v1/responses").as_deref(),
798            Some("/v1/responses")
799        );
800        assert_eq!(
801            canonical_provider_path("/v1/v1/chat/completions").as_deref(),
802            Some("/v1/chat/completions")
803        );
804    }
805
806    #[test]
807    fn normalized_provider_uri_rewrites_path_and_preserves_query() {
808        use axum::http::Uri;
809        let uri: Uri = "/responses?stream=true".parse().unwrap();
810        let rewritten = normalized_provider_uri(&uri).expect("bare /responses must rewrite");
811        assert_eq!(rewritten.path(), "/v1/responses");
812        assert_eq!(rewritten.query(), Some("stream=true"));
813        assert_eq!(
814            rewritten
815                .path_and_query()
816                .map(axum::http::uri::PathAndQuery::as_str),
817            Some("/v1/responses?stream=true")
818        );
819    }
820
821    #[test]
822    fn normalized_provider_uri_noop_for_canonical() {
823        use axum::http::Uri;
824        let uri: Uri = "/v1/responses".parse().unwrap();
825        assert!(normalized_provider_uri(&uri).is_none());
826    }
827}
828
829#[cfg(test)]
830mod upstream_tests {
831    use super::*;
832
833    fn upstreams_with_openai(openai: &str) -> Upstreams {
834        Upstreams {
835            anthropic: "https://api.anthropic.com".into(),
836            openai: openai.into(),
837            gemini: "https://generativelanguage.googleapis.com".into(),
838        }
839    }
840
841    /// The #449 core wiring: provider handlers read the upstream per request from
842    /// the watch channel, so a published change is served immediately, without
843    /// rebuilding the `ProxyState`.
844    #[tokio::test]
845    async fn proxy_state_reads_upstream_live_from_watch() {
846        let (tx, rx) =
847            tokio::sync::watch::channel(Arc::new(upstreams_with_openai("https://old.example")));
848        let state = ProxyState {
849            client: reqwest::Client::new(),
850            port: 0,
851            stats: Arc::new(ProxyStats::default()),
852            introspect: Arc::new(introspect::IntrospectState::default()),
853            upstreams: rx,
854        };
855        assert_eq!(state.openai_upstream(), "https://old.example");
856
857        tx.send(Arc::new(upstreams_with_openai("https://new.example")))
858            .unwrap();
859        assert_eq!(
860            state.openai_upstream(),
861            "https://new.example",
862            "a live handler read must reflect the published change"
863        );
864        assert_eq!(state.upstream_snapshot().openai, "https://new.example");
865    }
866
867    /// End-to-end #449 repro (in-process, no network): a `config set`-style edit
868    /// to config.toml is picked up by a *running* proxy's refresh task within the
869    /// reload interval — without any restart. Before the fix this value stayed
870    /// frozen at the start-time upstream forever.
871    ///
872    /// The process-global env lock is intentionally held across the polling
873    /// `.await`s to keep `LEAN_CTX_*` isolated for the whole test; safe because
874    /// each `#[tokio::test]` owns its current-thread runtime, so this std guard
875    /// only makes *other* test threads wait — it can never deadlock this one.
876    #[tokio::test]
877    #[allow(clippy::await_holding_lock)]
878    async fn config_change_is_picked_up_live_without_restart() {
879        use crate::core::config::Config;
880
881        let _lock = crate::core::data_dir::test_env_lock();
882        let tmp = tempfile::tempdir().unwrap();
883        crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
884        // Isolate from a developer shell that exports the env override (#449),
885        // and make the reload fast + deterministic.
886        crate::test_env::remove_var("LEAN_CTX_OPENAI_UPSTREAM");
887        crate::test_env::set_var("LEAN_CTX_PROXY_RELOAD_SECS", "1");
888
889        // Start state: config.toml points OpenAI at a loopback upstream.
890        Config::update_global(|c| {
891            c.proxy.openai_upstream = Some("http://127.0.0.1:19101".into());
892        })
893        .unwrap();
894        let initial = Config::load().proxy.resolve_all();
895        assert_eq!(initial.openai, "http://127.0.0.1:19101");
896
897        let (tx, rx) = tokio::sync::watch::channel(Arc::new(initial.clone()));
898        spawn_upstream_refresh(tx, initial);
899
900        // `lean-ctx config set proxy.openai_upstream …` (same safe write path).
901        Config::update_global(|c| {
902            c.proxy.openai_upstream = Some("http://127.0.0.1:19102".into());
903        })
904        .unwrap();
905
906        // Poll the live value the handlers would read — no restart in between.
907        let mut live = rx.borrow().openai.clone();
908        for _ in 0..80 {
909            if live == "http://127.0.0.1:19102" {
910                break;
911            }
912            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
913            live = rx.borrow().openai.clone();
914        }
915        assert_eq!(
916            live, "http://127.0.0.1:19102",
917            "running proxy must serve the new config.toml upstream without a restart"
918        );
919
920        crate::test_env::remove_var("LEAN_CTX_PROXY_RELOAD_SECS");
921        crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
922    }
923}