1pub mod anthropic;
2pub mod cache_safety;
3pub mod ccr;
4pub mod chatgpt;
5pub mod chatgpt_cookies;
6pub mod cold_prefix;
7pub mod compress;
8pub mod compress_api;
9pub mod cost;
10pub mod effort;
11pub mod forward;
12pub mod google;
13pub mod history_prune;
14pub mod holdout;
15pub mod introspect;
16pub mod metrics;
17pub mod openai;
18pub mod openai_responses;
19pub mod openai_responses_ws;
20pub mod output_savings;
21pub mod prose;
22pub mod prose_ranker;
23pub mod tool_kind;
24pub mod usage;
25pub mod usage_meter;
26pub mod verbosity;
27
28use std::net::SocketAddr;
29use std::sync::Arc;
30use std::sync::atomic::{AtomicU64, Ordering};
31
32use crate::core::config::Upstreams;
33
34use axum::{
35 Router,
36 body::Body,
37 extract::State,
38 http::{Request, StatusCode},
39 response::{IntoResponse, Response},
40 routing::{any, get, post},
41};
42
43#[derive(Clone)]
44pub struct ProxyState {
45 pub client: reqwest::Client,
46 pub port: u16,
47 pub stats: Arc<ProxyStats>,
48 pub introspect: Arc<introspect::IntrospectState>,
49 pub upstreams: tokio::sync::watch::Receiver<Arc<Upstreams>>,
52}
53
54impl ProxyState {
55 pub fn upstream_snapshot(&self) -> Arc<Upstreams> {
57 self.upstreams.borrow().clone()
58 }
59
60 pub fn anthropic_upstream(&self) -> String {
62 self.upstreams.borrow().anthropic.clone()
63 }
64
65 pub fn openai_upstream(&self) -> String {
67 self.upstreams.borrow().openai.clone()
68 }
69
70 pub fn chatgpt_upstream(&self) -> String {
72 self.upstreams.borrow().chatgpt.clone()
73 }
74
75 pub fn gemini_upstream(&self) -> String {
77 self.upstreams.borrow().gemini.clone()
78 }
79}
80
81pub struct ProxyStats {
82 pub requests_total: AtomicU64,
83 pub requests_compressed: AtomicU64,
84 pub tokens_saved: AtomicU64,
85 pub bytes_original: AtomicU64,
86 pub bytes_compressed: AtomicU64,
87}
88
89impl Default for ProxyStats {
90 fn default() -> Self {
91 Self {
92 requests_total: AtomicU64::new(0),
93 requests_compressed: AtomicU64::new(0),
94 tokens_saved: AtomicU64::new(0),
95 bytes_original: AtomicU64::new(0),
96 bytes_compressed: AtomicU64::new(0),
97 }
98 }
99}
100
101impl ProxyStats {
102 pub fn record_request(&self, original: usize, compressed: usize) {
103 self.requests_total.fetch_add(1, Ordering::Relaxed);
104 self.bytes_original
105 .fetch_add(original as u64, Ordering::Relaxed);
106 let effective_compressed = compressed.min(original);
107 self.bytes_compressed
108 .fetch_add(effective_compressed as u64, Ordering::Relaxed);
109 if compressed < original {
110 self.requests_compressed.fetch_add(1, Ordering::Relaxed);
111 }
112 let saved_tokens = (original.saturating_sub(effective_compressed) / 4) as u64;
113 self.tokens_saved.fetch_add(saved_tokens, Ordering::Relaxed);
114 }
115
116 pub fn compression_ratio(&self) -> f64 {
117 let original = self.bytes_original.load(Ordering::Relaxed);
118 if original == 0 {
119 return 0.0;
120 }
121 let compressed = self.bytes_compressed.load(Ordering::Relaxed);
122 (1.0 - compressed as f64 / original as f64) * 100.0
123 }
124}
125
126#[cfg(test)]
127mod stats_tests {
128 use super::*;
129 use std::sync::atomic::Ordering;
130
131 #[test]
132 fn compression_ratio_includes_uncompressed_requests() {
133 let stats = ProxyStats::default();
134
135 stats.record_request(1_000, 500);
136 stats.record_request(1_000, 1_000);
137
138 assert_eq!(stats.requests_total.load(Ordering::Relaxed), 2);
139 assert_eq!(stats.requests_compressed.load(Ordering::Relaxed), 1);
140 assert_eq!(stats.tokens_saved.load(Ordering::Relaxed), 125);
141 assert_eq!(stats.compression_ratio(), 25.0);
142 }
143
144 #[test]
145 fn expanded_requests_count_as_zero_savings() {
146 let stats = ProxyStats::default();
147
148 stats.record_request(1_000, 1_500);
149
150 assert_eq!(stats.requests_total.load(Ordering::Relaxed), 1);
151 assert_eq!(stats.requests_compressed.load(Ordering::Relaxed), 0);
152 assert_eq!(stats.tokens_saved.load(Ordering::Relaxed), 0);
153 assert_eq!(stats.compression_ratio(), 0.0);
154 }
155}
156
157fn connect_timeout_secs() -> u64 {
159 std::env::var("LEAN_CTX_PROXY_CONNECT_TIMEOUT_SECS")
160 .ok()
161 .and_then(|v| v.trim().parse::<u64>().ok())
162 .filter(|s| *s > 0)
163 .unwrap_or(15)
164}
165
166fn read_idle_timeout_secs() -> u64 {
171 std::env::var("LEAN_CTX_PROXY_READ_TIMEOUT_SECS")
172 .ok()
173 .and_then(|v| v.trim().parse::<u64>().ok())
174 .filter(|s| *s > 0)
175 .unwrap_or(300)
176}
177
178fn upstream_reload_secs() -> u64 {
181 std::env::var("LEAN_CTX_PROXY_RELOAD_SECS")
182 .ok()
183 .and_then(|v| v.trim().parse::<u64>().ok())
184 .filter(|s| *s > 0)
185 .unwrap_or(5)
186}
187
188fn spawn_upstream_refresh(tx: tokio::sync::watch::Sender<Arc<Upstreams>>, initial: Upstreams) {
197 let interval = std::time::Duration::from_secs(upstream_reload_secs());
198 tokio::spawn(async move {
199 let mut last = initial;
200 loop {
201 tokio::time::sleep(interval).await;
202 let next = crate::core::config::Config::load()
203 .proxy
204 .refresh_upstreams(&last);
205 if next != last {
206 log_upstream_change(&last, &next);
207 last = next.clone();
208 if tx.send(Arc::new(next)).is_err() {
209 break;
210 }
211 }
212 }
213 });
214}
215
216fn log_upstream_change(old: &Upstreams, new: &Upstreams) {
219 if old.anthropic != new.anthropic {
220 println!(" ↻ Anthropic upstream → {}", new.anthropic);
221 }
222 if old.openai != new.openai {
223 println!(" ↻ OpenAI upstream → {}", new.openai);
224 }
225 if old.chatgpt != new.chatgpt {
226 println!(" ↻ ChatGPT upstream → {}", new.chatgpt);
227 }
228 if old.gemini != new.gemini {
229 println!(" ↻ Gemini upstream → {}", new.gemini);
230 }
231}
232
233pub async fn start_proxy(port: u16) -> anyhow::Result<()> {
234 let token = crate::core::session_token::resolve_proxy_token("LEAN_CTX_PROXY_TOKEN");
235 start_proxy_with_token(port, Some(token)).await
236}
237
238fn effective_auth_token(auth_token: Option<String>) -> String {
243 auth_token
244 .filter(|t| !t.trim().is_empty())
245 .unwrap_or_else(|| crate::core::session_token::resolve_proxy_token("LEAN_CTX_PROXY_TOKEN"))
246}
247
248pub async fn start_proxy_with_token(port: u16, auth_token: Option<String>) -> anyhow::Result<()> {
249 use crate::core::config::{Config, is_local_proxy_url};
250
251 let auth_token = effective_auth_token(auth_token);
252
253 let client = chatgpt_cookies::with_chatgpt_cloudflare_cookie_store(reqwest::Client::builder())
258 .connect_timeout(std::time::Duration::from_secs(connect_timeout_secs()))
259 .read_timeout(std::time::Duration::from_secs(read_idle_timeout_secs()))
260 .build()?;
261
262 usage_meter::resume_from_disk();
265 cold_prefix::resume_from_disk();
268
269 let cfg = Config::load();
270 let require_token = cfg.proxy_require_token;
272 let initial = cfg.proxy.resolve_all();
273
274 let (upstream_tx, upstream_rx) = tokio::sync::watch::channel(Arc::new(initial.clone()));
279 spawn_upstream_refresh(upstream_tx, initial.clone());
280
281 let Upstreams {
282 anthropic: anthropic_upstream,
283 openai: openai_upstream,
284 chatgpt: chatgpt_upstream,
285 gemini: gemini_upstream,
286 } = initial;
287
288 let state = ProxyState {
289 client,
290 port,
291 stats: Arc::new(ProxyStats::default()),
292 introspect: Arc::new(introspect::IntrospectState::default()),
293 upstreams: upstream_rx,
294 };
295
296 let mut app = Router::new()
297 .route("/health", get(health))
298 .route("/status", get(status_handler))
299 .route("/v1/messages", any(anthropic::handler))
300 .route("/v1/messages/{*rest}", any(anthropic::handler))
301 .route("/v1/chat/completions", any(openai::handler))
302 .route(
304 "/v1/responses",
305 post(openai_responses::handler).get(openai_responses::ws_handler),
306 )
307 .route("/v1/responses/{*rest}", any(openai_responses::handler))
308 .route("/messages", any(anthropic::handler))
314 .route("/messages/{*rest}", any(anthropic::handler))
315 .route("/chat/completions", any(openai::handler))
316 .route(
317 "/responses",
318 post(openai_responses::handler).get(openai_responses::ws_handler),
319 )
320 .route("/responses/{*rest}", any(openai_responses::handler))
321 .route(
322 "/backend-api/codex/responses",
323 post(chatgpt::codex_responses_handler).get(chatgpt::codex_responses_ws_handler),
324 )
325 .route(
326 "/backend-api/codex/responses/{*rest}",
327 any(chatgpt::codex_responses_handler),
328 )
329 .route("/backend-api", any(chatgpt::backend_api_handler))
332 .route("/backend-api/{*rest}", any(chatgpt::backend_api_handler))
333 .route("/v1/references/{id}", get(v1_resolve_reference))
334 .route("/v1/compress", post(compress_api::handler))
337 .fallback(fallback_router)
338 .layer(axum::middleware::from_fn(host_guard))
339 .with_state(state);
340
341 {
342 let expected = auth_token.clone();
343 app = app.layer(axum::middleware::from_fn(move |req, next| {
344 let expected = expected.clone();
345 proxy_auth_guard(req, next, expected, require_token)
346 }));
347 }
348
349 app = app.layer(axum::middleware::from_fn(normalize_provider_path));
353
354 let addr = SocketAddr::from(([127, 0, 0, 1], port));
355 println!("lean-ctx proxy listening on http://{addr} (token auth enabled)");
356 println!(" Anthropic: POST /v1/messages → {anthropic_upstream}");
357 println!(" OpenAI: POST /v1/chat/completions → {openai_upstream}");
358 println!(
359 " OpenAI: POST /v1/responses → {openai_upstream} (bare /responses also accepted)"
360 );
361 println!(" ChatGPT: POST /backend-api/codex/responses → {chatgpt_upstream}");
362 println!(" ChatGPT: any /backend-api/* → {chatgpt_upstream}");
363 println!(" Gemini: POST /v1beta/models/... → {gemini_upstream}");
364 println!(" Compress: POST /v1/compress (deterministic messages-in/out, local)");
365 println!(
369 " Codex: WS ws://{addr}/responses → bridged to {openai_upstream} (HTTP/SSE, #440)"
370 );
371 if openai_upstream.starts_with("http://") && !is_local_proxy_url(&openai_upstream) {
372 println!(
373 " ⚠ OpenAI upstream is plaintext HTTP to a non-loopback host \
374 (allow_insecure_http_upstream) — use only on a trusted local network"
375 );
376 }
377
378 let listener = tokio::net::TcpListener::bind(addr).await?;
379 axum::serve(listener, app)
380 .with_graceful_shutdown(shutdown_signal())
381 .await?;
382
383 println!("lean-ctx proxy shut down cleanly.");
384 Ok(())
385}
386
387async fn shutdown_signal() {
388 let ctrl_c = tokio::signal::ctrl_c();
389
390 #[cfg(unix)]
391 {
392 match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
395 Ok(mut sigterm) => {
396 tokio::select! {
397 _ = ctrl_c => {},
398 _ = sigterm.recv() => {},
399 }
400 }
401 Err(e) => {
402 tracing::warn!("lean-ctx proxy: SIGTERM handler unavailable ({e}); Ctrl-C only");
403 ctrl_c.await.ok();
404 }
405 }
406 }
407
408 #[cfg(not(unix))]
409 {
410 ctrl_c.await.ok();
411 }
412
413 println!("lean-ctx proxy: received shutdown signal, draining…");
414}
415
416async fn health() -> impl IntoResponse {
417 let body = serde_json::json!({
418 "status": "ok",
419 "pid": std::process::id(),
420 });
421 (StatusCode::OK, axum::Json(body))
422}
423
424async fn v1_resolve_reference(
425 axum::extract::Path(id): axum::extract::Path<String>,
426) -> impl IntoResponse {
427 match crate::server::reference_store::resolve(&id) {
428 Some(content) => (StatusCode::OK, content),
429 None => (
430 StatusCode::NOT_FOUND,
431 "Reference expired or not found".to_string(),
432 ),
433 }
434}
435
436async fn status_handler(State(state): State<ProxyState>) -> impl IntoResponse {
437 use std::sync::atomic::Ordering::Relaxed;
438 let s = &state.stats;
439 let i = &state.introspect;
440
441 let last_breakdown = i
442 .last_breakdown
443 .lock()
444 .ok()
445 .and_then(|guard| guard.as_ref().map(|b| serde_json::to_value(b).ok()))
446 .flatten();
447
448 let spend = usage_meter::snapshot();
449 let spend_total: f64 = spend.iter().map(|m| m.cost_usd).sum();
450
451 let up = state.upstream_snapshot();
455
456 let active_effort = crate::core::config::Config::load().proxy.resolved_effort();
459
460 let body = serde_json::json!({
461 "status": "running",
462 "port": state.port,
463 "upstreams": {
464 "anthropic": up.anthropic.clone(),
465 "openai": up.openai.clone(),
466 "chatgpt": up.chatgpt.clone(),
467 "gemini": up.gemini.clone(),
468 },
469 "requests_total": s.requests_total.load(Relaxed),
470 "requests_compressed": s.requests_compressed.load(Relaxed),
471 "tokens_saved": s.tokens_saved.load(Relaxed),
472 "tokens_saved_estimated": true,
473 "bytes_original": s.bytes_original.load(Relaxed),
474 "bytes_compressed": s.bytes_compressed.load(Relaxed),
475 "compression_ratio_pct": format!("{:.1}", s.compression_ratio()),
476 "cache_safety": cache_safety::snapshot(),
477 "effort": effort::snapshot(active_effort),
478 "per_model": cost::snapshot(),
479 "spend": {
480 "source": "measured",
481 "total_usd": spend_total,
482 "per_model": spend,
483 "note": "Actual provider bill: real model + billed tokens (incl. cache reads/writes & reasoning) read from upstream responses for proxy-routed clients."
484 },
485 "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.",
486 "introspect": {
487 "total_requests_analyzed": i.total_requests.load(Relaxed),
488 "total_system_prompt_tokens": i.total_system_prompt_tokens.load(Relaxed),
489 "last_breakdown": last_breakdown,
490 }
491 });
492 (StatusCode::OK, axum::Json(body))
493}
494
495#[allow(clippy::result_large_err)]
496async fn proxy_auth_guard(
497 req: axum::extract::Request,
498 next: axum::middleware::Next,
499 expected_token: String,
500 require_token: bool,
501) -> Result<Response, Response> {
502 let path = req.uri().path();
503 if path == "/health" {
504 return Ok(next.run(req).await);
505 }
506
507 if let Some(auth) = req
508 .headers()
509 .get("authorization")
510 .and_then(|v| v.to_str().ok())
511 && let Some(token) = auth.strip_prefix("Bearer ")
512 && constant_time_eq(token.as_bytes(), expected_token.as_bytes())
513 {
514 return Ok(next.run(req).await);
515 }
516
517 if provider_key_fallback_allowed(
523 require_token,
524 has_provider_api_key(&req),
525 is_provider_route(path),
526 ) {
527 return Ok(next.run(req).await);
528 }
529
530 let cfg = crate::core::config::Config::load();
531 let hint = match cfg.proxy_enabled {
532 Some(true) => {
533 "lean-ctx proxy requires authentication. Use a Bearer token (LEAN_CTX_PROXY_TOKEN) or configure your AI tool's API key."
534 }
535 Some(false) => "lean-ctx proxy is disabled but still running. Run: lean-ctx proxy cleanup",
536 None => {
537 "lean-ctx proxy is not configured. Your AI tool's ANTHROPIC_BASE_URL may be pointing here by mistake. Fix: lean-ctx proxy cleanup OR lean-ctx proxy enable"
538 }
539 };
540
541 let body = serde_json::json!({
542 "type": "error",
543 "error": {
544 "type": "authentication_error",
545 "message": format!("401 Unauthorized — {hint}")
546 }
547 });
548
549 Err((StatusCode::UNAUTHORIZED, axum::Json(body)).into_response())
550}
551
552fn has_provider_api_key(req: &axum::extract::Request) -> bool {
553 let headers = req.headers();
554 for key in ["x-api-key", "x-goog-api-key", "api-key"] {
557 if headers
558 .get(key)
559 .and_then(|v| v.to_str().ok())
560 .is_some_and(|v| !v.trim().is_empty())
561 {
562 return true;
563 }
564 }
565 if let Some(auth) = headers.get("authorization").and_then(|v| v.to_str().ok()) {
574 let auth = auth.trim();
575 let credential = auth
576 .strip_prefix("Bearer ")
577 .or_else(|| auth.strip_prefix("bearer "))
578 .unwrap_or(auth)
579 .trim();
580 return !credential.is_empty() && !credential.eq_ignore_ascii_case("bearer");
582 }
583 false
584}
585
586fn is_provider_route(path: &str) -> bool {
587 path.starts_with("/v1/")
588 || path.starts_with("/v1beta/")
589 || path.starts_with("/chat/completions")
590 || path.starts_with("/responses")
591 || path.starts_with("/messages")
592 || path.starts_with("/backend-api")
593}
594
595fn provider_key_fallback_allowed(
602 require_token: bool,
603 has_provider_key: bool,
604 is_provider_route: bool,
605) -> bool {
606 !require_token && has_provider_key && is_provider_route
607}
608
609fn canonical_provider_path(path: &str) -> Option<String> {
620 if let Some(rest) = path.strip_prefix("/v1/v1/") {
624 return Some(format!("/v1/{rest}"));
625 }
626 const BARE_TO_CANONICAL: &[(&str, &str, &str)] = &[
627 ("/responses", "/v1/responses", "/responses/"),
628 (
629 "/chat/completions",
630 "/v1/chat/completions",
631 "/chat/completions/",
632 ),
633 ("/messages", "/v1/messages", "/messages/"),
634 ];
635 for (bare, canonical, bare_with_slash) in BARE_TO_CANONICAL {
636 if path == *bare {
637 return Some((*canonical).to_string());
638 }
639 if let Some(rest) = path.strip_prefix(bare_with_slash) {
640 return Some(format!("{canonical}/{rest}"));
641 }
642 }
643 None
644}
645
646fn normalized_provider_uri(uri: &axum::http::Uri) -> Option<axum::http::Uri> {
650 let canonical = canonical_provider_path(uri.path())?;
651 let new_path_and_query = match uri.query() {
652 Some(q) => format!("{canonical}?{q}"),
653 None => canonical,
654 };
655 new_path_and_query.parse::<axum::http::Uri>().ok()
656}
657
658async fn normalize_provider_path(
662 mut req: axum::extract::Request,
663 next: axum::middleware::Next,
664) -> Response {
665 if let Some(uri) = normalized_provider_uri(req.uri()) {
666 *req.uri_mut() = uri;
667 }
668 next.run(req).await
669}
670
671fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
672 use subtle::ConstantTimeEq;
673 if a.len() != b.len() {
674 return false;
675 }
676 bool::from(a.ct_eq(b))
677}
678
679async fn host_guard(
680 req: axum::extract::Request,
681 next: axum::middleware::Next,
682) -> Result<Response, StatusCode> {
683 if let Some(host) = req.headers().get("host").and_then(|v| v.to_str().ok()) {
684 let h = host.split(':').next().unwrap_or(host);
685 if matches!(h, "127.0.0.1" | "localhost" | "[::1]") {
686 return Ok(next.run(req).await);
687 }
688 }
689 Err(StatusCode::FORBIDDEN)
690}
691
692async fn fallback_router(State(state): State<ProxyState>, req: Request<Body>) -> Response {
693 let path = req.uri().path().to_string();
694
695 if path.starts_with("/v1beta/models/") || path.starts_with("/v1/models/") {
696 match google::handler(State(state), req).await {
697 Ok(resp) => resp,
698 Err(status) => Response::builder()
699 .status(status)
700 .body(Body::from("proxy error"))
701 .expect("BUG: building error response with valid status should never fail"),
702 }
703 } else {
704 let method = req.method().to_string();
705 eprintln!("lean-ctx proxy: unmatched {method} {path}");
706 Response::builder()
707 .status(StatusCode::NOT_FOUND)
708 .body(Body::from(format!(
709 "lean-ctx proxy: no handler for {method} {path}"
710 )))
711 .expect("BUG: building 404 response should never fail")
712 }
713}
714
715#[cfg(test)]
716mod auth_tests {
717 use super::*;
718
719 #[test]
722 fn effective_auth_token_never_yields_empty() {
723 let _env = crate::core::data_dir::test_env_lock();
724 let tmp = tempfile::tempdir().unwrap();
725 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
726
727 assert_eq!(effective_auth_token(Some("tok".into())), "tok");
728 let auto = effective_auth_token(None);
729 assert!(!auto.trim().is_empty(), "None must auto-resolve a token");
730 let blank = effective_auth_token(Some(" ".into()));
731 assert!(!blank.trim().is_empty(), "blank tokens must be replaced");
732
733 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
734 }
735
736 #[test]
737 fn is_provider_route_v1() {
738 assert!(is_provider_route("/v1/chat/completions"));
739 assert!(is_provider_route("/v1/messages"));
740 assert!(is_provider_route("/v1/completions"));
741 }
742
743 #[test]
744 fn is_provider_route_anthropic_subpaths() {
745 assert!(is_provider_route("/v1/messages/count_tokens"));
746 assert!(is_provider_route("/v1/messages/batches"));
747 assert!(is_provider_route("/v1/messages/batches/batch_123"));
748 }
749
750 #[test]
751 fn is_provider_route_v1beta() {
752 assert!(is_provider_route("/v1beta/models"));
753 }
754
755 #[test]
756 fn is_provider_route_chat() {
757 assert!(is_provider_route("/chat/completions"));
758 }
759
760 #[test]
761 fn is_provider_route_chatgpt_backend_api() {
762 assert!(is_provider_route("/backend-api/codex/responses"));
763 assert!(is_provider_route("/backend-api/codex/responses/resp_123"));
764 assert!(is_provider_route("/backend-api/wham/session"));
765 assert!(is_provider_route("/backend-api/ps/mcp"));
766 assert!(is_provider_route("/backend-api/codex_apps"));
767 assert!(is_provider_route("/backend-api/codex_apps/mcp"));
768 assert!(is_provider_route("/backend-api/mcp/codex_apps"));
769 assert!(is_provider_route("/backend-api/apps/codex_apps/mcp"));
770 }
771
772 #[test]
773 fn is_provider_route_rejects_non_provider() {
774 assert!(!is_provider_route("/health"));
775 assert!(!is_provider_route("/api/v2/test"));
776 assert!(!is_provider_route("/"));
777 }
778
779 fn build_request(headers: &[(&str, &str)], path: &str) -> axum::extract::Request {
780 let mut builder = axum::http::Request::builder().uri(path);
781 for (k, v) in headers {
782 builder = builder.header(*k, *v);
783 }
784 builder.body(axum::body::Body::empty()).unwrap()
785 }
786
787 #[test]
788 fn has_provider_api_key_x_api_key() {
789 let req = build_request(&[("x-api-key", "sk-ant-abc123")], "/v1/messages");
790 assert!(has_provider_api_key(&req));
791 }
792
793 #[test]
794 fn has_provider_api_key_x_goog() {
795 let req = build_request(&[("x-goog-api-key", "AIzaSyAbc")], "/v1beta/models");
796 assert!(has_provider_api_key(&req));
797 }
798
799 #[test]
800 fn has_provider_api_key_azure() {
801 let req = build_request(&[("api-key", "deadbeef")], "/v1/completions");
802 assert!(has_provider_api_key(&req));
803 }
804
805 #[test]
806 fn has_provider_api_key_bearer_sk() {
807 let req = build_request(
808 &[("authorization", "Bearer sk-proj-abc123")],
809 "/v1/chat/completions",
810 );
811 assert!(has_provider_api_key(&req));
812 }
813
814 #[test]
815 fn has_provider_api_key_empty_rejected() {
816 let req = build_request(&[("x-api-key", " ")], "/v1/messages");
817 assert!(!has_provider_api_key(&req));
818 }
819
820 #[test]
821 fn has_provider_api_key_no_headers() {
822 let req = build_request(&[], "/v1/messages");
823 assert!(!has_provider_api_key(&req));
824 }
825
826 #[test]
827 fn has_provider_api_key_accepts_non_sk_bearer() {
828 for key in [
834 "Bearer or-v1-9f8e7d6c", "Bearer gsk_live_1234", "Bearer abc.def.ghi", "Bearer 0123456789", ] {
839 let req = build_request(&[("authorization", key)], "/v1/responses");
840 assert!(
841 has_provider_api_key(&req),
842 "non-sk Bearer must count as a provider credential: {key}"
843 );
844 }
845 }
846
847 #[test]
848 fn has_provider_api_key_empty_bearer_rejected() {
849 for bad in ["Bearer ", "", "Bearer", "bearer", " "] {
852 let req = build_request(&[("authorization", bad)], "/responses");
853 assert!(
854 !has_provider_api_key(&req),
855 "blank/scheme-only Authorization must not authenticate: {bad:?}"
856 );
857 }
858 }
859
860 #[test]
863 fn provider_key_fallback_allowed_in_default_mode() {
864 assert!(provider_key_fallback_allowed(false, true, true));
868 }
869
870 #[test]
871 fn provider_key_fallback_denied_in_strict_mode() {
872 assert!(!provider_key_fallback_allowed(true, true, true));
876 }
877
878 #[test]
879 fn provider_key_fallback_requires_key_and_provider_route() {
880 assert!(!provider_key_fallback_allowed(false, false, true));
883 assert!(!provider_key_fallback_allowed(false, true, false));
884 assert!(!provider_key_fallback_allowed(true, false, true));
885 }
886
887 #[test]
888 fn proxy_require_token_defaults_off() {
889 assert!(!crate::core::config::Config::default().proxy_require_token);
893 }
894
895 #[test]
898 fn is_provider_route_bare_responses_and_messages() {
899 assert!(is_provider_route("/responses"));
902 assert!(is_provider_route("/responses/resp_123/input_items"));
903 assert!(is_provider_route("/messages"));
904 }
905
906 #[test]
907 fn canonical_provider_path_rewrites_bare_endpoints() {
908 assert_eq!(
909 canonical_provider_path("/responses").as_deref(),
910 Some("/v1/responses")
911 );
912 assert_eq!(
913 canonical_provider_path("/chat/completions").as_deref(),
914 Some("/v1/chat/completions")
915 );
916 assert_eq!(
917 canonical_provider_path("/messages").as_deref(),
918 Some("/v1/messages")
919 );
920 }
921
922 #[test]
923 fn canonical_provider_path_preserves_subpaths() {
924 assert_eq!(
925 canonical_provider_path("/responses/resp_abc/cancel").as_deref(),
926 Some("/v1/responses/resp_abc/cancel")
927 );
928 assert_eq!(
929 canonical_provider_path("/messages/batches/batch_1").as_deref(),
930 Some("/v1/messages/batches/batch_1")
931 );
932 }
933
934 #[test]
935 fn canonical_provider_path_ignores_already_canonical_and_unknown() {
936 assert_eq!(canonical_provider_path("/v1/responses"), None);
938 assert_eq!(canonical_provider_path("/v1/chat/completions"), None);
939 assert_eq!(canonical_provider_path("/health"), None);
941 assert_eq!(canonical_provider_path("/responsesx"), None);
942 assert_eq!(canonical_provider_path("/"), None);
943 }
944
945 #[test]
946 fn canonical_provider_path_collapses_double_v1_prefix() {
947 assert_eq!(
950 canonical_provider_path("/v1/v1/responses").as_deref(),
951 Some("/v1/responses")
952 );
953 assert_eq!(
954 canonical_provider_path("/v1/v1/chat/completions").as_deref(),
955 Some("/v1/chat/completions")
956 );
957 }
958
959 #[test]
960 fn normalized_provider_uri_rewrites_path_and_preserves_query() {
961 use axum::http::Uri;
962 let uri: Uri = "/responses?stream=true".parse().unwrap();
963 let rewritten = normalized_provider_uri(&uri).expect("bare /responses must rewrite");
964 assert_eq!(rewritten.path(), "/v1/responses");
965 assert_eq!(rewritten.query(), Some("stream=true"));
966 assert_eq!(
967 rewritten
968 .path_and_query()
969 .map(axum::http::uri::PathAndQuery::as_str),
970 Some("/v1/responses?stream=true")
971 );
972 }
973
974 #[test]
975 fn normalized_provider_uri_noop_for_canonical() {
976 use axum::http::Uri;
977 let uri: Uri = "/v1/responses".parse().unwrap();
978 assert!(normalized_provider_uri(&uri).is_none());
979 }
980}
981
982#[cfg(test)]
983mod upstream_tests {
984 use super::*;
985
986 fn upstreams_with_openai(openai: &str) -> Upstreams {
987 Upstreams {
988 anthropic: "https://api.anthropic.com".into(),
989 openai: openai.into(),
990 chatgpt: "https://chatgpt.com".into(),
991 gemini: "https://generativelanguage.googleapis.com".into(),
992 }
993 }
994
995 #[tokio::test]
999 async fn proxy_state_reads_upstream_live_from_watch() {
1000 let (tx, rx) =
1001 tokio::sync::watch::channel(Arc::new(upstreams_with_openai("https://old.example")));
1002 let state = ProxyState {
1003 client: reqwest::Client::new(),
1004 port: 0,
1005 stats: Arc::new(ProxyStats::default()),
1006 introspect: Arc::new(introspect::IntrospectState::default()),
1007 upstreams: rx,
1008 };
1009 assert_eq!(state.openai_upstream(), "https://old.example");
1010
1011 tx.send(Arc::new(upstreams_with_openai("https://new.example")))
1012 .unwrap();
1013 assert_eq!(
1014 state.openai_upstream(),
1015 "https://new.example",
1016 "a live handler read must reflect the published change"
1017 );
1018 assert_eq!(state.upstream_snapshot().openai, "https://new.example");
1019 }
1020
1021 #[tokio::test]
1031 #[allow(clippy::await_holding_lock)]
1032 async fn config_change_is_picked_up_live_without_restart() {
1033 use crate::core::config::Config;
1034
1035 let _lock = crate::core::data_dir::test_env_lock();
1036 let tmp = tempfile::tempdir().unwrap();
1037 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
1038 crate::test_env::remove_var("LEAN_CTX_OPENAI_UPSTREAM");
1041 crate::test_env::set_var("LEAN_CTX_PROXY_RELOAD_SECS", "1");
1042
1043 Config::update_global(|c| {
1045 c.proxy.openai_upstream = Some("http://127.0.0.1:19101".into());
1046 })
1047 .unwrap();
1048 let initial = Config::load().proxy.resolve_all();
1049 assert_eq!(initial.openai, "http://127.0.0.1:19101");
1050
1051 let (tx, rx) = tokio::sync::watch::channel(Arc::new(initial.clone()));
1052 spawn_upstream_refresh(tx, initial);
1053
1054 Config::update_global(|c| {
1056 c.proxy.openai_upstream = Some("http://127.0.0.1:19102".into());
1057 })
1058 .unwrap();
1059
1060 let mut live = rx.borrow().openai.clone();
1062 for _ in 0..80 {
1063 if live == "http://127.0.0.1:19102" {
1064 break;
1065 }
1066 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
1067 live = rx.borrow().openai.clone();
1068 }
1069 assert_eq!(
1070 live, "http://127.0.0.1:19102",
1071 "running proxy must serve the new config.toml upstream without a restart"
1072 );
1073
1074 crate::test_env::remove_var("LEAN_CTX_PROXY_RELOAD_SECS");
1075 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
1076 }
1077}