Skip to main content

lean_ctx/proxy/
mod.rs

1//! LLM reverse proxy — the core of the **Gateway pillar**.
2//!
3//! Intercepts Anthropic, OpenAI, Gemini and ChatGPT traffic, compresses
4//! prompts, meters usage, and optionally translates request shapes.
5//!
6//! # TLS Requirements
7//!
8//! The proxy does NOT terminate TLS. For production/multi-tenant deployments,
9//! place behind a TLS-terminating reverse proxy (nginx, caddy, traefik).
10//! For mTLS, configure the reverse proxy with client certificates.
11//! See: <https://github.com/yvgude/lean-ctx/issues/1371>
12//!
13//! # Org gateway coupling (ADR-023)
14//!
15//! The self-hosted org gateway (lean-ctx-enterprise) extends this proxy with
16//! admin/usage-store routes. In the OSS build the proxy runs standalone.
17
18pub mod adaptive_policy;
19pub(crate) mod agent_compact;
20pub mod anthropic;
21#[cfg(test)]
22mod auth_tests;
23pub mod auto_routing;
24pub mod bedrock;
25pub mod break_even;
26pub mod cache_aligner;
27pub mod cache_attribution;
28pub mod cache_breakpoint;
29pub mod cache_policy;
30pub mod cache_safety;
31pub mod ccr;
32#[cfg(test)]
33mod ccr_robustness_tests;
34pub mod chatgpt;
35pub mod chatgpt_cookies;
36pub mod chatgpt_ws;
37pub mod circuit_breaker;
38mod codec;
39pub mod cold_prefix;
40pub mod compress;
41pub mod compress_api;
42pub mod compress_shared;
43pub mod compression_savings;
44mod connector;
45pub(crate) mod conversation;
46pub mod cost;
47pub mod counterfactual;
48#[allow(dead_code)]
49pub mod dedup;
50#[allow(warnings)]
51pub mod determinism_guard;
52pub mod effort;
53pub mod effort_routing;
54pub mod eligibility;
55pub mod forward;
56#[cfg(feature = "enterprise")]
57pub mod gateway_identity;
58pub mod google;
59pub mod history_prune;
60pub mod holdout;
61#[cfg(test)]
62mod host_journey_tests;
63pub mod image_compression;
64pub mod inference_manifest_operator;
65#[cfg(test)]
66mod integration_tests;
67mod intent;
68pub mod introspect;
69pub mod latency_guard;
70pub mod leaderboard;
71mod lineage;
72pub mod metrics;
73pub mod models_api;
74pub mod ocla_cache_bridge;
75pub mod openai;
76pub mod openai_responses;
77pub mod openai_responses_ws;
78pub mod outbound_model_policy;
79pub mod output_savings;
80pub mod pii;
81pub mod pipeline_bench;
82#[cfg(feature = "enterprise")]
83pub mod policy_gate;
84pub mod pre_optimize;
85pub mod prefix_cache_stats;
86pub mod prefix_replay;
87pub mod prose;
88#[allow(warnings)]
89pub mod prose_compress;
90pub mod prose_patterns;
91pub mod prose_ranker;
92pub(crate) mod provider_headers;
93pub mod providers;
94pub mod quality_lab_api;
95pub mod reasoning_budget;
96#[cfg(test)]
97mod reference_tests;
98pub mod response_optimizer;
99#[allow(dead_code)]
100pub(crate) mod response_shaper;
101pub mod rollout;
102pub mod routing;
103#[doc(hidden)]
104pub mod sensitive_transport;
105#[cfg(feature = "shape-xlat")]
106pub mod shape_xlat;
107#[allow(dead_code)]
108pub(crate) mod shaping_hook;
109pub mod sse_keepalive;
110#[cfg(test)]
111mod stats_tests;
112pub mod sticky_tools;
113pub mod tool_kind;
114#[allow(dead_code)]
115pub mod tool_output;
116#[cfg(test)]
117mod upstream_tests;
118pub mod usage;
119pub mod usage_accounting;
120pub mod usage_azure;
121pub mod usage_meter;
122pub mod usage_parity;
123pub mod usage_sink;
124pub mod value_gate_proxy;
125pub mod verbosity;
126#[cfg(test)]
127mod via_p0_characterization_tests;
128pub mod web_app;
129#[allow(dead_code)]
130pub(crate) mod web_app_middleware;
131
132use std::net::SocketAddr;
133use std::sync::Arc;
134use std::sync::atomic::{AtomicU64, Ordering};
135#[allow(warnings)]
136pub mod live_zone;
137
138use crate::core::config::Upstreams;
139
140use axum::{
141    Router,
142    body::Body,
143    extract::State,
144    http::{Request, StatusCode},
145    response::{IntoResponse, Response},
146    routing::{any, get, post},
147};
148
149#[derive(Clone)]
150pub struct ProxyState {
151    pub client: reqwest::Client,
152    pub port: u16,
153    pub stats: Arc<ProxyStats>,
154    pub(crate) break_even: Arc<break_even::BreakEvenCalculator>,
155    pub introspect: Arc<introspect::IntrospectState>,
156    pub ocla_cache: Option<Arc<ocla_cache_bridge::OclaCacheBridge>>,
157    /// Live provider upstreams, refreshed from config.toml without a proxy
158    /// restart (#449). Read per request via [`ProxyState::openai_upstream`] etc.
159    pub upstreams: tokio::sync::watch::Receiver<Arc<Upstreams>>,
160    /// Shared Cloudflare cookie jar (also wired into `client`), so the Codex
161    /// ChatGPT WebSocket passthrough replays the same clearance to chatgpt.com
162    /// that the reqwest rail accumulated (#597).
163    pub(crate) chatgpt_cookies: Arc<chatgpt_cookies::ChatGptCloudflareCookieStore>,
164    /// Resolved `[[gateway_server.mcp_servers]]` registry snapshot (GL#100).
165    /// Empty when none are registered; the `/mcp/{server}` routes are only
166    /// mounted with the `gateway-server` feature. Startup snapshot, restart
167    /// to reload — the same lifecycle as `gateway-keys.toml`.
168    pub mcp_servers: Arc<Vec<crate::core::config::ResolvedMcpServer>>,
169    pub(crate) web_app_tracker:
170        Arc<std::sync::Mutex<web_app::conversation_tracker::ConversationTracker>>,
171}
172
173impl ProxyState {
174    /// Consistent snapshot of all upstreams for the current request/response.
175    pub fn upstream_snapshot(&self) -> Arc<Upstreams> {
176        self.upstreams.borrow().clone()
177    }
178
179    /// Snapshot MCP schema-cost break-even status for `/status`.
180    pub(crate) fn break_even_summary(&self) -> break_even::BreakEvenSummary {
181        self.break_even.summary()
182    }
183
184    /// Current Anthropic upstream (live).
185    pub fn anthropic_upstream(&self) -> String {
186        self.upstreams.borrow().anthropic.clone()
187    }
188
189    /// Current OpenAI upstream (live).
190    pub fn openai_upstream(&self) -> String {
191        self.upstreams.borrow().openai.clone()
192    }
193
194    /// Current ChatGPT upstream (live).
195    pub fn chatgpt_upstream(&self) -> String {
196        self.upstreams.borrow().chatgpt.clone()
197    }
198
199    /// Current Gemini upstream (live).
200    pub fn gemini_upstream(&self) -> String {
201        self.upstreams.borrow().gemini.clone()
202    }
203
204    /// Cloudflare `Cookie` header for the current ChatGPT upstream, used by the
205    /// WebSocket passthrough handshake (#597). `None` until a request on the
206    /// reqwest rail has seen Cloudflare clearance.
207    pub fn chatgpt_cookie_header(&self) -> Option<String> {
208        let url = reqwest::Url::parse(&self.chatgpt_upstream()).ok()?;
209        self.chatgpt_cookies
210            .cookie_header(&url)
211            .and_then(|v| v.to_str().ok().map(str::to_owned))
212    }
213}
214
215pub struct ProxyStats {
216    pub requests_total: AtomicU64,
217    pub requests_compressed: AtomicU64,
218    pub tokens_saved: AtomicU64,
219    pub bytes_original: AtomicU64,
220    pub bytes_compressed: AtomicU64,
221    pub anthropic: ProviderStats,
222    pub openai: ProviderStats,
223    pub chatgpt: ProviderStats,
224    pub gemini: ProviderStats,
225    /// Grok dual-rail (`/providers/grok-chat`, `/providers/xai`) — OpenAI wire
226    /// shape, separate identity so `proxy status` does not fold xAI traffic
227    /// into the OpenAI bucket.
228    pub grok: ProviderStats,
229    /// Command Code gateway rail (`/providers/commandcode`) — separate identity
230    /// so `proxy status` does not fold Command Code traffic into the wire-shape
231    /// bucket.
232    pub commandcode: ProviderStats,
233}
234
235#[derive(Default)]
236pub struct ProviderStats {
237    pub requests_total: AtomicU64,
238    pub requests_compressed: AtomicU64,
239    pub tokens_saved: AtomicU64,
240    pub bytes_original: AtomicU64,
241    pub bytes_compressed: AtomicU64,
242}
243
244impl Default for ProxyStats {
245    fn default() -> Self {
246        Self {
247            requests_total: AtomicU64::new(0),
248            requests_compressed: AtomicU64::new(0),
249            tokens_saved: AtomicU64::new(0),
250            bytes_original: AtomicU64::new(0),
251            bytes_compressed: AtomicU64::new(0),
252            anthropic: ProviderStats::default(),
253            openai: ProviderStats::default(),
254            chatgpt: ProviderStats::default(),
255            gemini: ProviderStats::default(),
256            grok: ProviderStats::default(),
257            commandcode: ProviderStats::default(),
258        }
259    }
260}
261
262impl ProxyStats {
263    pub fn record_request(&self, original: usize, compressed: usize) {
264        self.record_totals(original, compressed);
265    }
266
267    pub fn record_provider_request(
268        &self,
269        provider_label: &str,
270        original: usize,
271        compressed: usize,
272    ) {
273        let (effective_compressed, saved_tokens, compressed_request) =
274            self.record_totals(original, compressed);
275
276        if let Some(provider) = self.provider(provider_label) {
277            provider.record(
278                original,
279                effective_compressed,
280                compressed_request,
281                saved_tokens,
282            );
283        }
284    }
285
286    fn record_totals(&self, original: usize, compressed: usize) -> (usize, u64, bool) {
287        self.requests_total.fetch_add(1, Ordering::Relaxed);
288        self.bytes_original
289            .fetch_add(original as u64, Ordering::Relaxed);
290        let effective_compressed = compressed.min(original);
291        self.bytes_compressed
292            .fetch_add(effective_compressed as u64, Ordering::Relaxed);
293        if compressed < original {
294            self.requests_compressed.fetch_add(1, Ordering::Relaxed);
295        }
296        let saved_tokens = (original.saturating_sub(effective_compressed) / 4) as u64;
297        self.tokens_saved.fetch_add(saved_tokens, Ordering::Relaxed);
298        (effective_compressed, saved_tokens, compressed < original)
299    }
300
301    pub fn compression_ratio(&self) -> f64 {
302        let original = self.bytes_original.load(Ordering::Relaxed);
303        if original == 0 {
304            return 0.0;
305        }
306        let compressed = self.bytes_compressed.load(Ordering::Relaxed);
307        (1.0 - compressed as f64 / original as f64) * 100.0
308    }
309
310    /// Maps a proxy `provider_label` to its per-upstream bucket. Unknown labels
311    /// return `None` (still counted in the totals, never misattributed to a bucket);
312    /// every real upstream — Gemini included — passes an explicit label.
313    /// `"Grok"` is the identity label for registry routes `grok-chat` / `xai`
314    /// (OpenAI wire shape; see `providers::stats_label`). `"CommandCode"` is the
315    /// identity label for the `commandcode` registry route.
316    fn provider(&self, provider_label: &str) -> Option<&ProviderStats> {
317        match provider_label {
318            "Anthropic" => Some(&self.anthropic),
319            "OpenAI" => Some(&self.openai),
320            "ChatGPT" => Some(&self.chatgpt),
321            "Gemini" => Some(&self.gemini),
322            "Grok" => Some(&self.grok),
323            "CommandCode" => Some(&self.commandcode),
324            _ => None,
325        }
326    }
327
328    pub fn provider_summary(&self) -> serde_json::Value {
329        serde_json::json!({
330            "anthropic": self.anthropic.summary(),
331            "openai": self.openai.summary(),
332            "chatgpt": self.chatgpt.summary(),
333            "gemini": self.gemini.summary(),
334            "grok": self.grok.summary(),
335            "commandcode": self.commandcode.summary(),
336        })
337    }
338}
339
340impl ProviderStats {
341    fn record(
342        &self,
343        original: usize,
344        effective_compressed: usize,
345        compressed_request: bool,
346        saved_tokens: u64,
347    ) {
348        self.requests_total.fetch_add(1, Ordering::Relaxed);
349        if compressed_request {
350            self.requests_compressed.fetch_add(1, Ordering::Relaxed);
351        }
352        self.tokens_saved.fetch_add(saved_tokens, Ordering::Relaxed);
353        self.bytes_original
354            .fetch_add(original as u64, Ordering::Relaxed);
355        self.bytes_compressed
356            .fetch_add(effective_compressed as u64, Ordering::Relaxed);
357    }
358
359    fn compression_ratio(&self) -> f64 {
360        let original = self.bytes_original.load(Ordering::Relaxed);
361        if original == 0 {
362            return 0.0;
363        }
364        let compressed = self.bytes_compressed.load(Ordering::Relaxed);
365        (1.0 - compressed as f64 / original as f64) * 100.0
366    }
367
368    fn summary(&self) -> serde_json::Value {
369        serde_json::json!({
370            "requests_total": self.requests_total.load(Ordering::Relaxed),
371            "requests_compressed": self.requests_compressed.load(Ordering::Relaxed),
372            "tokens_saved": self.tokens_saved.load(Ordering::Relaxed),
373            "bytes_original": self.bytes_original.load(Ordering::Relaxed),
374            "bytes_compressed": self.bytes_compressed.load(Ordering::Relaxed),
375            "compression_ratio_pct": format!("{:.1}", self.compression_ratio()),
376        })
377    }
378}
379
380/// TCP connect timeout (seconds). Configurable via `LEAN_CTX_PROXY_CONNECT_TIMEOUT_SECS`.
381fn connect_timeout_secs() -> u64 {
382    std::env::var("LEAN_CTX_PROXY_CONNECT_TIMEOUT_SECS")
383        .ok()
384        .and_then(|v| v.trim().parse::<u64>().ok())
385        .filter(|s| *s > 0)
386        .unwrap_or(15)
387}
388
389/// Idle read timeout (seconds) between bytes from upstream. Generous by default
390/// so long extended-thinking phases (which still emit SSE keepalives) are never
391/// cut, while a truly dead connection eventually fails. Configurable via
392/// `LEAN_CTX_PROXY_READ_TIMEOUT_SECS`.
393fn read_idle_timeout_secs() -> u64 {
394    std::env::var("LEAN_CTX_PROXY_READ_TIMEOUT_SECS")
395        .ok()
396        .and_then(|v| v.trim().parse::<u64>().ok())
397        .filter(|s| *s > 0)
398        .unwrap_or(300)
399}
400
401/// How often (seconds) a running proxy re-reads config.toml for upstream
402/// changes. `LEAN_CTX_PROXY_RELOAD_SECS` overrides; default 5s.
403fn upstream_reload_secs() -> u64 {
404    std::env::var("LEAN_CTX_PROXY_RELOAD_SECS")
405        .ok()
406        .and_then(|v| v.trim().parse::<u64>().ok())
407        .filter(|s| *s > 0)
408        .unwrap_or(5)
409}
410
411/// Background task: re-resolves the provider upstreams from config.toml on an
412/// interval and publishes any change to the live request handlers (#449). Ends
413/// once every receiver (the proxy itself) has been dropped.
414///
415/// `Config::load()` already keeps an internal content-hash cache, so re-reading
416/// an unchanged `config.toml` skips the TOML parse + merge and costs only a small
417/// file read; combined with the relaxed default interval (#453) the idle steady
418/// state is negligible without needing a separate stat pre-check.
419fn spawn_upstream_refresh(tx: tokio::sync::watch::Sender<Arc<Upstreams>>, initial: Upstreams) {
420    let interval = std::time::Duration::from_secs(upstream_reload_secs());
421    tokio::spawn(async move {
422        let mut last = initial;
423        loop {
424            tokio::time::sleep(interval).await;
425            let next = crate::core::config::Config::load()
426                .proxy
427                .refresh_upstreams(&last);
428            if next != last {
429                log_upstream_change(&last, &next);
430                last = next.clone();
431                if tx.send(Arc::new(next)).is_err() {
432                    break;
433                }
434            }
435        }
436    });
437}
438
439/// One stdout line per changed provider, matching the startup banner style so a
440/// running proxy's log shows when (and to what) an upstream switched.
441fn log_upstream_change(old: &Upstreams, new: &Upstreams) {
442    if old.anthropic != new.anthropic {
443        println!("  ↻ Anthropic upstream → {}", new.anthropic);
444    }
445    if old.openai != new.openai {
446        println!("  ↻ OpenAI upstream → {}", new.openai);
447    }
448    if old.chatgpt != new.chatgpt {
449        println!("  ↻ ChatGPT upstream → {}", new.chatgpt);
450    }
451    if old.gemini != new.gemini {
452        println!("  ↻ Gemini upstream → {}", new.gemini);
453    }
454    if old.providers != new.providers {
455        let ids: Vec<&str> = new.providers.iter().map(|p| p.id.as_str()).collect();
456        println!("  ↻ provider registry → [{}]", ids.join(", "));
457    }
458}
459
460pub async fn start_proxy(port: u16) -> anyhow::Result<()> {
461    let token = crate::core::session_token::resolve_proxy_token("LEAN_CTX_PROXY_TOKEN");
462    start_proxy_with_token(port, Some(token)).await
463}
464
465/// Security invariant: the proxy NEVER runs unauthenticated. `None` does not
466/// mean "no auth" — it means "resolve the session token for me". Provider
467/// routes additionally accept provider API keys (see `proxy_auth_guard`), so
468/// IDE clients keep working without any setup.
469fn effective_auth_token(auth_token: Option<String>) -> String {
470    auth_token
471        .filter(|t| !t.trim().is_empty())
472        .unwrap_or_else(|| crate::core::session_token::resolve_proxy_token("LEAN_CTX_PROXY_TOKEN"))
473}
474
475/// Install the process-default rustls `CryptoProvider` for the Codex ChatGPT
476/// WebSocket passthrough (#597).
477///
478/// `tokio-tungstenite`'s rustls connector builds its `ClientConfig` from the
479/// process-default provider. Our tree pulls *both* aws-lc-rs (reqwest) and ring
480/// (lettre/ureq), so rustls cannot auto-pick one and the `wss://chatgpt.com`
481/// handshake aborts with *"Could not automatically determine the process-level
482/// CryptoProvider"*. reqwest is unaffected (it configures aws-lc-rs explicitly),
483/// so we match it here. Idempotent: a prior install just returns the provider
484/// back as `Err`, which we ignore.
485fn install_default_crypto_provider() {
486    let _ = rustls::crypto::aws_lc_rs::default_provider().install_default();
487}
488
489pub async fn start_proxy_with_token(port: u16, auth_token: Option<String>) -> anyhow::Result<()> {
490    use crate::core::config::{Config, is_local_proxy_url};
491
492    // Must run before any WebSocket passthrough opens a wss:// upstream (#597).
493    install_default_crypto_provider();
494
495    let auth_token = effective_auth_token(auth_token);
496
497    // A single total timeout aborts long streaming generations (e.g. Opus doing
498    // a big refactor) mid-response. Use a connect timeout plus a read (idle)
499    // timeout instead: a genuinely hung upstream still fails, but a slow-but-
500    // alive stream is never cut off. Both are configurable for edge networks.
501    let chatgpt_cookies = chatgpt_cookies::shared_chatgpt_cloudflare_cookie_store();
502    let client = chatgpt_cookies::with_chatgpt_cloudflare_cookie_store(
503        reqwest::Client::builder(),
504        chatgpt_cookies.clone(),
505    )
506    .connect_timeout(std::time::Duration::from_secs(connect_timeout_secs()))
507    .read_timeout(std::time::Duration::from_secs(read_idle_timeout_secs()))
508    .build()?;
509
510    // Seed the measured-spend meter from disk so a proxy restart never zeroes
511    // the user's cumulative real provider bill.
512    usage_meter::resume_from_disk();
513    // Live model prices (#1179): load the cached provider price list and keep
514    // it fresh in the background, so new models are billed at their real
515    // market rates instead of family heuristics. Fail-open, kill switch:
516    // LEAN_CTX_LIVE_PRICING=off.
517    crate::core::gain::live_pricing::spawn_background_refresh();
518    // Seed the cold-prefix baselines too so a long idle gap that straddles a
519    // proxy restart is still detected and the repack can fire (#499).
520    cold_prefix::resume_from_disk();
521
522    let cfg = Config::load();
523    let break_even_schema_overhead = match cfg.tool_profile_effective() {
524        crate::core::tool_profiles::ToolProfile::Minimal
525        | crate::core::tool_profiles::ToolProfile::Auto => 1500,
526        crate::core::tool_profiles::ToolProfile::Standard => 3000,
527        crate::core::tool_profiles::ToolProfile::Power
528        | crate::core::tool_profiles::ToolProfile::Custom(_) => 5000,
529    };
530    // Read once at startup — avoids a Config::load() on every proxied request.
531    let bind_host = cfg.resolved_proxy_bind_host();
532    let loopback_bind = bind_host.is_loopback();
533    // Gateway mode (non-loopback bind, enterprise#8) hard-requires the Bearer
534    // token: the provider-key fallback's whole justification is "loopback only",
535    // so it is disabled by construction once the listener is reachable from the
536    // network — regardless of the config flag.
537    let require_token = cfg.proxy_require_token || !loopback_bind;
538    let loopback_open = cfg.proxy_loopback_open && loopback_bind;
539    let allowed_hosts: Arc<Vec<String>> = Arc::new(
540        cfg.proxy_allowed_hosts
541            .iter()
542            .map(|h| h.trim().trim_end_matches('.').to_ascii_lowercase())
543            .filter(|h| !h.is_empty())
544            .collect(),
545    );
546    // Rate limit (enterprise#37): explicit config wins; gateway mode ships a
547    // sane default floor; loopback stays unlimited unless configured. `0`
548    // disables the limiter explicitly.
549    let rate_limiter = match (cfg.proxy_max_rps, loopback_bind) {
550        (Some(rps), _) if rps > 0 => Some(Arc::new(RateLimiter::new(rps, rps.saturating_mul(2)))),
551        (None, false) => Some(Arc::new(RateLimiter::new(50, 100))),
552        _ => None,
553    };
554    let initial = cfg.proxy.resolve_all();
555
556    // The proxy reads its upstreams live from a watch channel: a background task
557    // re-resolves them from config.toml on an interval and publishes any change,
558    // so `lean-ctx config set proxy.*_upstream` (or any config.toml edit) takes
559    // effect on the running proxy within seconds, without a restart (#449).
560    let (upstream_tx, upstream_rx) = tokio::sync::watch::channel(Arc::new(initial.clone()));
561    // Clone before moving into ProxyState — auth guard needs live registry
562    // snapshots to decide client-auth provider fallback under require_token.
563    let auth_upstreams = upstream_rx.clone();
564    spawn_upstream_refresh(upstream_tx, initial.clone());
565
566    let Upstreams {
567        anthropic: anthropic_upstream,
568        openai: openai_upstream,
569        chatgpt: chatgpt_upstream,
570        gemini: gemini_upstream,
571        providers: initial_providers,
572    } = initial;
573
574    // Governed MCP reverse proxy registry (GL#91/#100): resolved once at
575    // startup (restart to reload — the gateway-keys.toml lifecycle). The
576    // `/mcp/{server}` routes are mounted below with the gateway-server
577    // feature; the snapshot lives in ProxyState either way.
578    let mcp_servers = Arc::new(
579        cfg.gateway_server
580            .resolve_mcp_servers(cfg.proxy.allows_insecure_http_upstream()),
581    );
582
583    let state = ProxyState {
584        client,
585        port,
586        stats: Arc::new(ProxyStats::default()),
587        break_even: Arc::new(break_even::BreakEvenCalculator::new(
588            break_even_schema_overhead,
589        )),
590        introspect: Arc::new(introspect::IntrospectState::default()),
591        ocla_cache: None,
592        upstreams: upstream_rx,
593        chatgpt_cookies,
594        mcp_servers: mcp_servers.clone(),
595        web_app_tracker: Arc::new(std::sync::Mutex::new(
596            web_app::conversation_tracker::ConversationTracker::default(),
597        )),
598    };
599
600    web_app::dashboard::mark_proxy_started();
601
602    let app = Router::new()
603        .route("/health", get(health))
604        .route("/status", get(status_handler))
605        .route("/v1/messages", any(anthropic::handler))
606        .route("/dashboard", get(web_app::dashboard::page))
607        .route("/api/stats", get(web_app::dashboard::stats))
608        .route("/v1/messages/{*rest}", any(anthropic::handler))
609        .route("/v1/chat/completions", any(openai::handler))
610        // POST → HTTP/SSE forwarder; GET → Codex/OpenAI WebSocket bridge (#440).
611        .route(
612            "/v1/responses",
613            post(openai_responses::handler).get(openai_responses::ws_handler),
614        )
615        .route("/v1/responses/{*rest}", any(openai_responses::handler))
616        // Bare provider endpoints (no `/v1` prefix). Clients whose base URL points
617        // at the proxy root — notably OpenCode via `@ai-sdk/openai`, whose
618        // Responses-API requests hit `/responses` — dispatch here. The
619        // `normalize_provider_path` layer rewrites the URI to its canonical
620        // `/v1/...` form before the handler forwards upstream (#353).
621        .route("/messages", any(anthropic::handler))
622        .route("/messages/{*rest}", any(anthropic::handler))
623        .route("/chat/completions", any(openai::handler))
624        .route(
625            "/responses",
626            post(openai_responses::handler).get(openai_responses::ws_handler),
627        )
628        .route("/responses/{*rest}", any(openai_responses::handler))
629        .route(
630            "/backend-api/codex/responses",
631            post(chatgpt::codex_responses_handler).get(chatgpt::codex_responses_ws_handler),
632        )
633        .route(
634            "/backend-api/codex/responses/{*rest}",
635            any(chatgpt::codex_responses_handler),
636        )
637        // Non-model ChatGPT backend calls (including codex_apps MCP) are not
638        // prompt JSON. Keep them as credential-preserving passthrough traffic.
639        .route("/backend-api", any(chatgpt::backend_api_handler))
640        .route("/backend-api/{*rest}", any(chatgpt::backend_api_handler))
641        .route("/v1/references/{id}", get(v1_resolve_reference))
642        // LiteLLM headroom-guardrail CCR retrieval (#702): resolves the 24-hex
643        // `hash=` marker `/v1/compress` emits back to the verbatim original.
644        .route("/v1/retrieve/{hash}", get(v1_retrieve_ccr))
645        // Org model catalog (enterprise#63): IDE clients discover the curated
646        // alias namespace (`zuehlke/fast` → provider:model) and verify their
647        // key. Exact-match only — `/v1/models/{...}` subpaths stay Gemini
648        // passthrough in the fallback router.
649        .route("/v1/models", get(models_api::handler))
650        .route("/models", get(models_api::handler))
651        // Drop-in `compress(messages, model)` contract (#739): deterministic
652        // messages-in / messages-out compression for SDK clients.
653        .route("/v1/compress", post(compress_api::handler))
654        .route(
655            "/v1/quality-lab",
656            post(quality_lab_api::handler).get(quality_lab_api::handler_get),
657        )
658        // Universal provider registry (`[[proxy.providers]]`, enterprise#7):
659        // `/providers/{id}/...` forwards to the registry entry with that id,
660        // speaking its declared wire shape. New provider = config, not code.
661        .route("/providers/{id}/{*rest}", any(providers::handler))
662        .fallback(fallback_router);
663
664    let mut app = app
665        .layer(axum::middleware::from_fn(
666            web_app_middleware::detect_web_app,
667        ))
668        .layer(axum::middleware::from_fn(move |req, next| {
669            let allowed = allowed_hosts.clone();
670            host_guard(req, next, allowed)
671        }))
672        .with_state(state);
673
674    // Per-person gateway keys (enterprise#11): sha256(bearer) → person/team/
675    // default_project. Loaded once at startup; rotation = restart (the standard
676    // secret-mount flow). A malformed file fails the start loudly.
677    #[cfg(feature = "enterprise")]
678    let gateway_keys = match gateway_identity::GatewayKeys::load_default() {
679        Ok(keys) => {
680            if !keys.is_empty() {
681                println!(
682                    "  Identity:  {} gateway key(s) loaded ({})",
683                    keys.len(),
684                    gateway_identity::GatewayKeys::default_path().display()
685                );
686            }
687            Arc::new(keys)
688        }
689        Err(e) => anyhow::bail!("gateway-keys.toml: {e}"),
690    };
691
692    #[cfg(feature = "enterprise")]
693    {
694        let expected = auth_token.clone();
695        let keys = gateway_keys.clone();
696        let upstreams = auth_upstreams;
697        app = app.layer(axum::middleware::from_fn(move |req, next| {
698            let expected = expected.clone();
699            let keys = keys.clone();
700            let upstreams = upstreams.clone();
701            proxy_auth_guard(
702                req,
703                next,
704                expected,
705                require_token,
706                loopback_open,
707                keys,
708                upstreams,
709            )
710        }));
711    }
712
713    #[cfg(not(feature = "enterprise"))]
714    {
715        let expected = auth_token.clone();
716        let upstreams = auth_upstreams;
717        app = app.layer(axum::middleware::from_fn(move |req, next| {
718            let expected = expected.clone();
719            let upstreams = upstreams.clone();
720            proxy_auth_guard(req, next, expected, require_token, loopback_open, upstreams)
721        }));
722    }
723
724    if let Some(limiter) = rate_limiter {
725        app = app.layer(axum::middleware::from_fn(move |req, next| {
726            let limiter = limiter.clone();
727            rate_limit_guard(req, next, limiter)
728        }));
729    }
730
731    // Outermost layer (runs first): normalize bare provider endpoints to their
732    // canonical `/v1/...` form so auth, routing and upstream forwarding all agree,
733    // regardless of whether the client's base URL includes `/v1` (#353).
734    app = app.layer(axum::middleware::from_fn(normalize_provider_path));
735    app = app.layer(axum::middleware::from_fn(determinism_response_headers));
736
737    let addr = SocketAddr::from((bind_host, port));
738    if loopback_open {
739        println!("lean-ctx proxy listening on http://{addr} (loopback-open: auth disabled)");
740    } else {
741        println!("lean-ctx proxy listening on http://{addr} (token auth enabled)");
742    }
743    if !loopback_bind {
744        println!(
745            "  ⚠ gateway mode: non-loopback bind — Bearer token REQUIRED for gateway-held \
746             keys and non-registry routes; client-auth /providers/* (api_key_env unset) \
747             still accept provider credentials. Host allowlist + rate limit active"
748        );
749    }
750    println!("  Anthropic: POST /v1/messages → {anthropic_upstream}");
751    println!("  OpenAI:    POST /v1/chat/completions → {openai_upstream}");
752    println!(
753        "  OpenAI:    POST /v1/responses → {openai_upstream}  (bare /responses also accepted)"
754    );
755    println!("  ChatGPT:   POST /backend-api/codex/responses → {chatgpt_upstream}");
756    println!("  ChatGPT:   any  /backend-api/* → {chatgpt_upstream}");
757    println!("  Gemini:    POST /v1beta/models/... → {gemini_upstream}");
758    println!("  Compress:  POST /v1/compress (deterministic messages-in/out, local)");
759    // Codex defaults to a WebSocket Responses transport (ws://…/responses). The
760    // proxy now bridges it to the HTTP/SSE upstream (#440), so Codex works as a
761    // drop-in without a `supports_websockets = false` workaround.
762    println!(
763        "  Codex:     WS  ws://{addr}/responses → bridged to {openai_upstream} (HTTP/SSE, #440)"
764    );
765    for p in &initial_providers {
766        println!(
767            "  Provider:  any  /providers/{}/... → {} ({} shape{})",
768            p.id,
769            p.base_url,
770            p.shape.as_str(),
771            if p.api_key_env.is_some() {
772                ", gateway-held key"
773            } else {
774                ""
775            }
776        );
777    }
778    for s in mcp_servers.iter() {
779        println!(
780            "  MCP:       any  /mcp/{} → {} (observed{})",
781            s.id,
782            s.url,
783            if s.auth_env.is_some() {
784                ", gateway-held credential"
785            } else {
786                ""
787            }
788        );
789    }
790    if openai_upstream.starts_with("http://") && !is_local_proxy_url(&openai_upstream) {
791        println!(
792            "  ⚠ OpenAI upstream is plaintext HTTP to a non-loopback host \
793             (allow_insecure_http_upstream) — use only on a trusted local network"
794        );
795    }
796
797    let listener = tokio::net::TcpListener::bind(addr).await?;
798    axum::serve(listener, app)
799        .with_graceful_shutdown(shutdown_signal())
800        .await?;
801
802    println!("lean-ctx proxy shut down cleanly.");
803    Ok(())
804}
805
806async fn shutdown_signal() {
807    let ctrl_c = tokio::signal::ctrl_c();
808
809    #[cfg(unix)]
810    {
811        // Fall back to Ctrl-C only if the SIGTERM handler cannot be installed,
812        // rather than panicking the proxy on startup.
813        match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
814            Ok(mut sigterm) => {
815                tokio::select! {
816                    _ = ctrl_c => {},
817                    _ = sigterm.recv() => {},
818                }
819            }
820            Err(e) => {
821                tracing::warn!("lean-ctx proxy: SIGTERM handler unavailable ({e}); Ctrl-C only");
822                ctrl_c.await.ok();
823            }
824        }
825    }
826
827    #[cfg(not(unix))]
828    {
829        ctrl_c.await.ok();
830    }
831
832    println!("lean-ctx proxy: received shutdown signal, draining…");
833}
834
835async fn health() -> impl IntoResponse {
836    let body = serde_json::json!({
837        "status": "ok",
838        "service": "lean-ctx-proxy",
839        "pid": std::process::id(),
840    });
841    (StatusCode::OK, axum::Json(body))
842}
843
844async fn v1_resolve_reference(
845    axum::extract::Path(id): axum::extract::Path<String>,
846) -> impl IntoResponse {
847    match crate::server::reference_store::resolve(&id) {
848        Some(content) => (StatusCode::OK, content),
849        None => (
850            StatusCode::NOT_FOUND,
851            "Reference expired or not found".to_string(),
852        ),
853    }
854}
855
856/// `GET /v1/retrieve/{hash}` (#702) — LiteLLM headroom-guardrail CCR contract
857/// (BerriAI/litellm#31681): resolve a 24-hex `hash=` marker emitted by
858/// `/v1/compress` back to the verbatim original from the tee store. The reply
859/// carries `original_content` (the field LiteLLM's `_call_retrieve` reads
860/// first). The optional `?query=` the guardrail forwards is accepted but the
861/// full original is always returned — a superset of any ranked slice, and the
862/// stored blobs are single tool outputs, not corpora worth ranking. Auth: the
863/// standard proxy bearer guard wraps this route (LiteLLM sends the configured
864/// `api_key` as a Bearer token); the tee store is loopback-scoped local state.
865async fn v1_retrieve_ccr(
866    axum::extract::Path(hash): axum::extract::Path<String>,
867) -> impl IntoResponse {
868    match ccr::retrieve_litellm(&hash) {
869        Some(content) => (
870            StatusCode::OK,
871            axum::Json(serde_json::json!({ "original_content": content })),
872        ),
873        None => (
874            StatusCode::NOT_FOUND,
875            axum::Json(serde_json::json!({
876                "error": "hash not found or expired",
877                "hash": hash,
878            })),
879        ),
880    }
881}
882
883async fn status_handler(State(state): State<ProxyState>) -> impl IntoResponse {
884    use std::sync::atomic::Ordering::Relaxed;
885    let s = &state.stats;
886    let i = &state.introspect;
887
888    let last_breakdown = i
889        .last_breakdown
890        .lock()
891        .ok()
892        .and_then(|guard| guard.as_ref().map(|b| serde_json::to_value(b).ok()))
893        .flatten();
894
895    let spend = usage_meter::snapshot();
896    let spend_total: f64 = spend.iter().map(|m| m.cost_usd).sum();
897
898    // Live upstreams the proxy is forwarding to right now (#449). This is the
899    // single source of truth for "where is my traffic actually going" — it
900    // reflects config.toml hot-reloads and any start-time env override.
901    let up = state.upstream_snapshot();
902
903    // Resolve the effort level fresh so /status reflects config.toml hot-reloads
904    // and env overrides, matching the upstream snapshot above (#834).
905    let active_effort = crate::core::config::Config::load().proxy.resolved_effort();
906
907    let introspect_total_input = i.total_input_tokens.load(Relaxed);
908    let introspect_bulk_candidates = i.total_bulk_candidate_tokens.load(Relaxed);
909    let introspect_bulk_share =
910        introspect::token_share_basis_points(introspect_bulk_candidates, introspect_total_input);
911    let break_even = state.break_even_summary();
912
913    let body = serde_json::json!({
914        "status": "running",
915        "proxy_mode": format!("{:?}", crate::core::config::Config::load().proxy.resolved_proxy_mode()),
916        "port": state.port,
917        "upstreams": {
918            "anthropic": up.anthropic.clone(),
919            "openai": up.openai.clone(),
920            "chatgpt": up.chatgpt.clone(),
921            "gemini": up.gemini.clone(),
922        },
923        // Universal registry (`[[proxy.providers]]`, enterprise#7). Key names
924        // only — never the key material.
925        "providers": up.providers.iter().map(|p| serde_json::json!({
926            "id": p.id,
927            "shape": p.shape.as_str(),
928            "base_url": p.base_url,
929            "gateway_key": p.api_key_env.is_some(),
930        })).collect::<Vec<_>>(),
931        "requests_total": s.requests_total.load(Relaxed),
932        "requests_compressed": s.requests_compressed.load(Relaxed),
933        "tokens_saved": s.tokens_saved.load(Relaxed),
934        "tokens_saved_estimated": true,
935        // Provider-verified savings (#701, opt-in counterfactual metering):
936        // both sides counted by Anthropic on the same request. `null` until
937        // the first probe-covered request lands.
938        "verified_savings": usage_meter::verified_savings(),
939        "bytes_original": s.bytes_original.load(Relaxed),
940        "bytes_compressed": s.bytes_compressed.load(Relaxed),
941        "compression_ratio_pct": format!("{:.1}", s.compression_ratio()),
942        "break_even": {
943            "proxy_savings": break_even.proxy_savings,
944            "estimated_mcp_overhead": break_even.estimated_mcp_overhead,
945            "net": break_even.net,
946            "mcp_recommended": break_even.mcp_recommended,
947            "reason": break_even.reason,
948        },
949        "per_upstream": s.provider_summary(),
950        "prefix_cache": prefix_cache_stats::snapshot(),
951        "cache_safety": cache_safety::snapshot(),
952        "cache_attribution": cache_attribution::snapshot(),
953        "effort": effort::snapshot(active_effort),
954        "per_model": cost::snapshot(),
955        "spend": {
956            "source": "measured",
957            "total_usd": spend_total,
958            "per_model": spend,
959            "note": "Actual provider bill: real model + billed tokens (incl. cache reads/writes & reasoning) read from upstream responses for proxy-routed clients."
960        },
961        "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.",
962        "introspect": {
963            "total_requests_analyzed": i.total_requests.load(Relaxed),
964            "total_input_tokens": introspect_total_input,
965            "total_system_prompt_tokens": i.total_system_prompt_tokens.load(Relaxed),
966            "total_bulk_candidate_tokens": introspect_bulk_candidates,
967            "bulk_candidate_share_basis_points": introspect_bulk_share,
968            "vision_encoding_decision_gate_met": introspect_bulk_share.is_some_and(|share| share >= 2_000),
969            "last_breakdown": last_breakdown,
970        }
971    });
972    (StatusCode::OK, axum::Json(body))
973}
974
975#[allow(clippy::result_large_err)]
976#[cfg_attr(not(feature = "enterprise"), allow(unused_mut))]
977async fn proxy_auth_guard(
978    mut req: axum::extract::Request,
979    next: axum::middleware::Next,
980    expected_token: String,
981    require_token: bool,
982    loopback_open: bool,
983    #[cfg(feature = "enterprise")] gateway_keys: Arc<gateway_identity::GatewayKeys>,
984    upstreams: tokio::sync::watch::Receiver<Arc<Upstreams>>,
985) -> Result<Response, Response> {
986    let path = req.uri().path();
987    if path == "/health" {
988        return Ok(next.run(req).await);
989    }
990
991    // #755: loopback-open mode skips all auth — every local process is trusted.
992    if loopback_open {
993        #[cfg(feature = "enterprise")]
994        {
995            req.extensions_mut()
996                .insert(gateway_identity::TrustedGatewayRequest);
997            attach_gateway_tags(&mut req, gateway_identity::GatewayTags::default());
998        }
999        return Ok(next.run(req).await);
1000    }
1001
1002    let bearer = req
1003        .headers()
1004        .get("authorization")
1005        .and_then(|v| v.to_str().ok())
1006        .and_then(|auth| auth.strip_prefix("Bearer "))
1007        .map(str::to_string);
1008
1009    if let Some(token) = bearer.as_deref()
1010        && !proxy_token_expired(token, std::time::SystemTime::now())
1011        && constant_time_eq(token.as_bytes(), expected_token.as_bytes())
1012    {
1013        #[cfg(feature = "enterprise")]
1014        {
1015            req.extensions_mut()
1016                .insert(gateway_identity::TrustedGatewayRequest);
1017            attach_gateway_tags(&mut req, gateway_identity::GatewayTags::default());
1018        }
1019        return Ok(next.run(req).await);
1020    }
1021
1022    // Per-person gateway keys (enterprise#11): a bearer key whose SHA-256 is in
1023    // gateway-keys.toml authenticates AND identifies — its person/team/project
1024    // tags travel with the request and end up on the usage record.
1025    #[cfg(feature = "enterprise")]
1026    if let Some(token) = bearer.as_deref()
1027        && let Some(tags) = gateway_keys.lookup(token)
1028    {
1029        req.extensions_mut()
1030            .insert(gateway_identity::TrustedGatewayRequest);
1031        attach_gateway_tags(&mut req, tags);
1032        return Ok(next.run(req).await);
1033    }
1034
1035    // Accept provider API keys on provider routes (host_guard runs first).
1036    // Client-auth registry rails (`/providers/{id}` with api_key_env=None,
1037    // e.g. Grok dual-rail) stay open even when require_token is set — the
1038    // Authorization / x-xai-token-auth header must carry the upstream session
1039    // and cannot also hold the lean-ctx Bearer.
1040    let client_auth_registry = is_client_auth_registry_route(path, &upstreams.borrow());
1041    if provider_key_fallback_allowed(
1042        require_token,
1043        has_provider_api_key(&req),
1044        is_provider_route(path),
1045        client_auth_registry,
1046    ) {
1047        #[cfg(feature = "enterprise")]
1048        attach_gateway_tags(&mut req, gateway_identity::GatewayTags::default());
1049        return Ok(next.run(req).await);
1050    }
1051
1052    Err(auth_error_response(path))
1053}
1054
1055/// Returns true only for `TOKEN.TIMESTAMP` bearer tokens more than 24 hours
1056/// old. Tokens without a valid timestamp suffix remain valid for backwards
1057/// compatibility.
1058fn proxy_token_expired(token: &str, now: std::time::SystemTime) -> bool {
1059    const TOKEN_MAX_AGE: std::time::Duration = std::time::Duration::from_hours(24);
1060
1061    let Some((value, timestamp)) = token.rsplit_once('.') else {
1062        return false;
1063    };
1064    if value.is_empty() {
1065        return false;
1066    }
1067    let Ok(timestamp) = timestamp.parse::<u64>() else {
1068        return false;
1069    };
1070
1071    let issued_at = std::time::UNIX_EPOCH + std::time::Duration::from_secs(timestamp);
1072    now.duration_since(issued_at)
1073        .is_ok_and(|age| age > TOKEN_MAX_AGE)
1074}
1075
1076fn auth_error_response(path: &str) -> Response {
1077    let is_mcp = path.starts_with("/mcp");
1078    let hint = if is_mcp {
1079        "MCP Streamable HTTP requires a Bearer token. Get it with: lean-ctx proxy token"
1080    } else if is_provider_route(path) {
1081        "Provider route requires authentication. Set your API key header or use: lean-ctx proxy token"
1082    } else {
1083        "This endpoint requires a lean-ctx Bearer token. Get it with: lean-ctx proxy token  \
1084         — or set proxy_loopback_open = true to disable auth on localhost"
1085    };
1086
1087    let body = serde_json::json!({
1088        "type": "error",
1089        "error": {
1090            "type": "authentication_error",
1091            "message": format!("401 Unauthorized — {hint}")
1092        }
1093    });
1094
1095    (StatusCode::UNAUTHORIZED, axum::Json(body)).into_response()
1096}
1097
1098/// Resolves the final identity tags for an authenticated request and inserts
1099/// them as a request extension (read by `forward.rs::wire_context`).
1100///
1101/// Project resolution (enterprise#11): the `x-leanctx-project` header wins over
1102/// the key's `default_project` — one person books work onto different projects
1103/// per request. The header also works without a gateway key (solo/local mode:
1104/// project tagging without identity). It is an internal gateway header, not on
1105/// `ALLOWED_REQUEST_HEADERS`, so it never reaches the upstream.
1106#[cfg(feature = "enterprise")]
1107fn attach_gateway_tags(req: &mut axum::extract::Request, mut tags: gateway_identity::GatewayTags) {
1108    if let Some(project) = req
1109        .headers()
1110        .get("x-leanctx-project")
1111        .and_then(|v| v.to_str().ok())
1112        .map(str::trim)
1113        .filter(|p| !p.is_empty() && p.len() <= 128 && !p.chars().any(char::is_control))
1114    {
1115        tags.project = Some(project.to_string());
1116    }
1117    // GDPR pseudonymization (enterprise#39): applied at this single
1118    // choke-point, so budgets, usage rows, dashboards and logs only ever see
1119    // the pseudonym. No-op unless [gateway_server].pseudonymize_persons.
1120    if let Some(person) = tags.person.as_deref()
1121        && pii::enabled()
1122    {
1123        tags.person = Some(pii::pseudonymize(person));
1124    }
1125    if !tags.is_empty() {
1126        req.extensions_mut().insert(tags);
1127    }
1128}
1129
1130fn has_provider_api_key(req: &axum::extract::Request) -> bool {
1131    let headers = req.headers();
1132    // Provider-specific key headers: Anthropic `x-api-key`, Google
1133    // `x-goog-api-key`, Azure `api-key`, Grok subscription `x-xai-token-auth`.
1134    // Any non-empty value authenticates. Grok dual-rail may send only the
1135    // session header (no Authorization) against `/providers/grok-chat`.
1136    for key in ["x-api-key", "x-goog-api-key", "api-key", "x-xai-token-auth"] {
1137        if headers
1138            .get(key)
1139            .and_then(|v| v.to_str().ok())
1140            .is_some_and(|v| !v.trim().is_empty())
1141        {
1142            return true;
1143        }
1144    }
1145    // OpenAI-style `Authorization` auth. Accept ANY non-empty credential, not
1146    // just `Bearer sk-`/`gsk_`: OpenAI-*compatible* providers driven through
1147    // OpenCode/Codex (Azure, OpenRouter, Groq, vLLM/Ollama gateways, project &
1148    // service-account keys) issue keys that don't carry those prefixes. The proxy
1149    // binds to loopback only and never injects upstream credentials — it forwards
1150    // this header verbatim, so an invalid key is rejected by the real upstream,
1151    // never silently honoured. Gating provider routes on key *shape* only ever
1152    // produced false 401s for those clients (#362).
1153    if let Some(auth) = headers.get("authorization").and_then(|v| v.to_str().ok()) {
1154        let auth = auth.trim();
1155        let credential = auth
1156            .strip_prefix("Bearer ")
1157            .or_else(|| auth.strip_prefix("bearer "))
1158            .unwrap_or(auth)
1159            .trim();
1160        // Reject an empty value or a bare scheme keyword carrying no token.
1161        return !credential.is_empty() && !credential.eq_ignore_ascii_case("bearer");
1162    }
1163    false
1164}
1165
1166/// `/providers/{id}/...` where the registered provider has no gateway-held
1167/// key (`api_key_env = None`). These dual-rail / client-auth rails put the
1168/// upstream session in Authorization or provider-specific headers.
1169fn is_client_auth_registry_route(path: &str, upstreams: &Upstreams) -> bool {
1170    let Some(rest) = path.strip_prefix("/providers/") else {
1171        return false;
1172    };
1173    let id = rest.split('/').next().unwrap_or("");
1174    if id.is_empty() {
1175        return false;
1176    }
1177    upstreams
1178        .providers
1179        .iter()
1180        .any(|p| p.id == id && !p.injects_gateway_credential())
1181}
1182
1183fn is_provider_route(path: &str) -> bool {
1184    path.starts_with("/v1/")
1185        || path.starts_with("/v1beta/")
1186        || path.starts_with("/chat/completions")
1187        || path.starts_with("/responses")
1188        || path.starts_with("/messages")
1189        || path.starts_with("/backend-api")
1190        // Bare model-catalog discovery (enterprise#63): clients whose base URL
1191        // omits `/v1` send `GET /models` with their provider key.
1192        || path == "/models"
1193        // Universal provider registry (enterprise#7): clients point their base
1194        // URL at `/providers/{id}/v1` (Grok subscription:
1195        // `GROK_CLI_CHAT_PROXY_BASE_URL`, Azure Foundry, OpenRouter, …) and
1196        // authenticate with their own provider/session Bearer. Without this,
1197        // model-list + chat land as lean-ctx 401s — Grok cannot select a mode.
1198        || path.starts_with("/providers/")
1199}
1200
1201/// Decides whether a request authenticates via a provider API key alone, without
1202/// the lean-ctx Bearer token.
1203///
1204/// * Built-in provider routes (`/v1/*`, bare endpoints, …): only when
1205///   `require_token` is false (loopback-friendly default). Gateway mode
1206///   (non-loopback bind) forces `require_token` so these require the lean-ctx
1207///   Bearer (enterprise#8).
1208/// * Client-auth registry routes (`/providers/{id}` with `api_key_env = None`,
1209///   e.g. Grok dual-rail): always allowed when a provider credential is present.
1210///   The Authorization / `x-xai-token-auth` header must carry the upstream
1211///   session and cannot also hold the lean-ctx Bearer. Gateway-held keys
1212///   (`api_key_env` set) never take this path — those still need the lean-ctx
1213///   token so inject cannot be abused with a forged provider header.
1214///
1215/// Pure (except the precomputed `client_auth_registry` flag), so the policy is
1216/// unit-testable without axum middleware plumbing.
1217#[allow(clippy::fn_params_excessive_bools)] // deliberate pure predicate for unit tests
1218fn provider_key_fallback_allowed(
1219    require_token: bool,
1220    has_provider_key: bool,
1221    is_provider_route: bool,
1222    client_auth_registry: bool,
1223) -> bool {
1224    if !has_provider_key || !is_provider_route {
1225        return false;
1226    }
1227    if client_auth_registry {
1228        return true;
1229    }
1230    !require_token
1231}
1232
1233/// Maps a bare provider endpoint to its canonical `/v1/...` form, preserving any
1234/// sub-path. Returns `None` when the path is already canonical or not a known
1235/// provider endpoint.
1236///
1237/// Some OpenAI-compatible clients treat the configured base URL as the API root
1238/// and append the bare endpoint, so they send `POST /responses` or
1239/// `/chat/completions` instead of `/v1/responses` — notably OpenCode via
1240/// `@ai-sdk/openai`, whose Responses-API requests land on `/responses`. The proxy
1241/// and every upstream only know the `/v1/...` paths, so an un-prefixed request
1242/// would 401 (not a provider route) and then 404 (no handler). (#353)
1243fn canonical_provider_path(path: &str) -> Option<String> {
1244    // Inverse case of the bare-endpoint rewrite below: the advertised
1245    // OPENAI_BASE_URL includes `/v1` (#366), so a client that treats the base URL
1246    // as an origin and appends `/v1/...` itself produces `/v1/v1/...`.
1247    if let Some(rest) = path.strip_prefix("/v1/v1/") {
1248        return Some(format!("/v1/{rest}"));
1249    }
1250    const BARE_TO_CANONICAL: &[(&str, &str, &str)] = &[
1251        ("/responses", "/v1/responses", "/responses/"),
1252        (
1253            "/chat/completions",
1254            "/v1/chat/completions",
1255            "/chat/completions/",
1256        ),
1257        ("/messages", "/v1/messages", "/messages/"),
1258    ];
1259    for (bare, canonical, bare_with_slash) in BARE_TO_CANONICAL {
1260        if path == *bare {
1261            return Some((*canonical).to_string());
1262        }
1263        if let Some(rest) = path.strip_prefix(bare_with_slash) {
1264            return Some(format!("{canonical}/{rest}"));
1265        }
1266    }
1267    None
1268}
1269
1270/// Returns the canonicalized URI for a bare provider endpoint (query preserved),
1271/// or `None` when no rewrite is needed. Pure, so the rewrite is unit-testable
1272/// without constructing axum middleware plumbing.
1273fn normalized_provider_uri(uri: &axum::http::Uri) -> Option<axum::http::Uri> {
1274    let canonical = canonical_provider_path(uri.path())?;
1275    let new_path_and_query = match uri.query() {
1276        Some(q) => format!("{canonical}?{q}"),
1277        None => canonical,
1278    };
1279    new_path_and_query.parse::<axum::http::Uri>().ok()
1280}
1281
1282/// Rewrites the request URI in place when it targets a bare provider endpoint, so
1283/// downstream auth (`is_provider_route`), routing and upstream forwarding all see
1284/// the canonical `/v1/...` path. (#353)
1285async fn normalize_provider_path(
1286    mut req: axum::extract::Request,
1287    next: axum::middleware::Next,
1288) -> Response {
1289    if let Some(uri) = normalized_provider_uri(req.uri()) {
1290        *req.uri_mut() = uri;
1291    }
1292    next.run(req).await
1293}
1294
1295/// Ensures every HTTP response exposes the determinism contract, including
1296/// requests that fail before they reach the shared upstream forwarder.
1297async fn determinism_response_headers(
1298    req: axum::extract::Request,
1299    next: axum::middleware::Next,
1300) -> Response {
1301    let mut response = next.run(req).await;
1302    determinism_guard::ensure_response_headers(&mut response);
1303    response
1304}
1305
1306fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
1307    use subtle::ConstantTimeEq;
1308    if a.len() != b.len() {
1309        return false;
1310    }
1311    bool::from(a.ct_eq(b))
1312}
1313
1314async fn host_guard(
1315    req: axum::extract::Request,
1316    next: axum::middleware::Next,
1317    allowed_hosts: Arc<Vec<String>>,
1318) -> Result<Response, StatusCode> {
1319    if let Some(host) = req.headers().get("host").and_then(|v| v.to_str().ok())
1320        && host_allowed(host, &allowed_hosts)
1321    {
1322        return Ok(next.run(req).await);
1323    }
1324    Err(StatusCode::FORBIDDEN)
1325}
1326
1327/// DNS-rebinding guard: loopback Host headers always pass (today's local
1328/// behavior); in gateway mode the operator additionally allowlists the names
1329/// the gateway is reachable under (`proxy_allowed_hosts`, enterprise#8).
1330/// Matching is case-insensitive on the host with the port stripped.
1331fn host_allowed(host_header: &str, allowed: &[String]) -> bool {
1332    // `[::1]:8080` carries the port after the bracket; plain hosts after `:`.
1333    let host = host_header.trim();
1334    let h = if let Some(bracketed) = host.strip_prefix('[') {
1335        bracketed
1336            .split(']')
1337            .next()
1338            .map(|inner| format!("[{inner}]"))
1339    } else {
1340        host.split(':').next().map(str::to_string)
1341    };
1342    let Some(h) = h else {
1343        return false;
1344    };
1345    let h = h.trim_end_matches('.').to_ascii_lowercase();
1346    matches!(h.as_str(), "127.0.0.1" | "localhost" | "[::1]") || allowed.contains(&h)
1347}
1348
1349/// Proxy-wide token-bucket rate limit (enterprise#37). `/health` is exempt so
1350/// orchestrator liveness probes never get throttled into a false restart.
1351async fn rate_limit_guard(
1352    req: axum::extract::Request,
1353    next: axum::middleware::Next,
1354    limiter: Arc<RateLimiter>,
1355) -> Result<Response, StatusCode> {
1356    if req.uri().path() != "/health" && !limiter.allow().await {
1357        return Err(StatusCode::TOO_MANY_REQUESTS);
1358    }
1359    Ok(next.run(req).await)
1360}
1361
1362/// Token bucket: `max_rps` sustained, `burst` peak. Mirrors the team server's
1363/// limiter; lives here so the proxy stays independent of `http_server`
1364/// internals.
1365pub(crate) struct RateLimiter {
1366    max_rps: f64,
1367    burst: f64,
1368    state: tokio::sync::Mutex<RateLimiterState>,
1369}
1370
1371struct RateLimiterState {
1372    tokens: f64,
1373    last: std::time::Instant,
1374}
1375
1376impl RateLimiter {
1377    pub(crate) fn new(max_rps: u32, burst: u32) -> Self {
1378        Self {
1379            max_rps: f64::from(max_rps.max(1)),
1380            burst: f64::from(burst.max(1)),
1381            state: tokio::sync::Mutex::new(RateLimiterState {
1382                tokens: f64::from(burst.max(1)),
1383                last: std::time::Instant::now(),
1384            }),
1385        }
1386    }
1387
1388    pub(crate) async fn allow(&self) -> bool {
1389        let mut s = self.state.lock().await;
1390        let now = std::time::Instant::now();
1391        let refill = now.saturating_duration_since(s.last).as_secs_f64() * self.max_rps;
1392        s.tokens = (s.tokens + refill).min(self.burst);
1393        s.last = now;
1394        if s.tokens >= 1.0 {
1395            s.tokens -= 1.0;
1396            true
1397        } else {
1398            false
1399        }
1400    }
1401}
1402
1403async fn fallback_router(State(state): State<ProxyState>, req: Request<Body>) -> Response {
1404    let path = req.uri().path().to_string();
1405
1406    if path.starts_with("/v1beta/models/") || path.starts_with("/v1/models/") {
1407        match google::handler(State(state), req).await {
1408            Ok(resp) => resp,
1409            Err(status) => Response::builder()
1410                .status(status)
1411                .body(Body::from("proxy error"))
1412                .expect("BUG: building error response with valid status should never fail"),
1413        }
1414    } else {
1415        let method = req.method().to_string();
1416        eprintln!("lean-ctx proxy: unmatched {method} {path}");
1417        Response::builder()
1418            .status(StatusCode::NOT_FOUND)
1419            .body(Body::from(format!(
1420                "lean-ctx proxy: no handler for {method} {path}"
1421            )))
1422            .expect("BUG: building 404 response should never fail")
1423    }
1424}