Skip to main content

lean_ctx/proxy/
mod.rs

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