Skip to main content

lean_ctx/proxy/
server.rs

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