1#[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 pub upstreams: tokio::sync::watch::Receiver<Arc<Upstreams>>,
36 pub(crate) chatgpt_cookies: Arc<chatgpt_cookies::ChatGptCloudflareCookieStore>,
40 pub mcp_servers: Arc<Vec<crate::core::config::ResolvedMcpServer>>,
45}
46
47impl ProxyState {
48 pub fn upstream_snapshot(&self) -> Arc<Upstreams> {
50 self.upstreams.borrow().clone()
51 }
52
53 pub(crate) fn break_even_summary(&self) -> break_even::BreakEvenSummary {
55 self.break_even.summary()
56 }
57
58 pub fn anthropic_upstream(&self) -> String {
60 self.upstreams.borrow().anthropic.clone()
61 }
62
63 pub fn openai_upstream(&self) -> String {
65 self.upstreams.borrow().openai.clone()
66 }
67
68 pub fn chatgpt_upstream(&self) -> String {
70 self.upstreams.borrow().chatgpt.clone()
71 }
72
73 pub fn gemini_upstream(&self) -> String {
75 self.upstreams.borrow().gemini.clone()
76 }
77
78 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 pub grok: ProviderStats,
103 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 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
254fn 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
263fn 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
275fn 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
285pub(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
316fn 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
342pub(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
352pub(super) fn install_default_crypto_provider() {
363 crate::core::crypto_provider::install_default();
364}
365
366pub(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 install_default_crypto_provider();
379
380 let auth_token = effective_auth_token(auth_token);
381
382 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 usage_meter::resume_from_disk();
398 crate::core::gain::live_pricing::spawn_background_refresh();
403 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 let bind_host = cfg.resolved_proxy_bind_host();
417 let loopback_bind = bind_host.is_loopback();
418 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 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 let (upstream_tx, upstream_rx) = tokio::sync::watch::channel(Arc::new(initial.clone()));
446 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 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 .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 .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 .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 .route("/v1/retrieve/{hash}", get(v1_retrieve_ccr))
527 .route("/v1/models", get(models_api::handler))
532 .route("/models", get(models_api::handler))
533 .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 .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 #[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 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 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 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 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
729pub(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 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
762pub(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 let up = state.upstream_snapshot();
808
809 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 "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 "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 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 #[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 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#[derive(Debug, Clone, Copy)]
978pub(super) struct ProviderKeyFallback;
979
980pub(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#[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 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 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 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 return !credential.is_empty() && !credential.eq_ignore_ascii_case("bearer");
1090 }
1091 false
1092}
1093
1094fn 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
1111fn 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 || path == "/models"
1134 || path.starts_with("/providers/")
1140}
1141
1142#[allow(clippy::fn_params_excessive_bools)] pub(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
1174pub(super) fn canonical_provider_path(path: &str) -> Option<String> {
1185 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
1211pub(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
1223async 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
1236async 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
1268pub(super) fn host_allowed(host_header: &str, allowed: &[String]) -> bool {
1273 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
1290async 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
1303pub(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}