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