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