1pub mod anthropic;
2pub mod compress;
3pub mod cost;
4pub mod forward;
5pub mod google;
6pub mod history_prune;
7pub mod introspect;
8pub mod metrics;
9pub mod openai;
10pub mod openai_responses;
11pub mod openai_responses_ws;
12pub mod tool_kind;
13pub mod usage;
14pub mod usage_meter;
15
16use std::net::SocketAddr;
17use std::sync::Arc;
18use std::sync::atomic::{AtomicU64, Ordering};
19
20use crate::core::config::Upstreams;
21
22use axum::{
23 Router,
24 body::Body,
25 extract::State,
26 http::{Request, StatusCode},
27 response::{IntoResponse, Response},
28 routing::{any, get, post},
29};
30
31#[derive(Clone)]
32pub struct ProxyState {
33 pub client: reqwest::Client,
34 pub port: u16,
35 pub stats: Arc<ProxyStats>,
36 pub introspect: Arc<introspect::IntrospectState>,
37 pub upstreams: tokio::sync::watch::Receiver<Arc<Upstreams>>,
40}
41
42impl ProxyState {
43 pub fn upstream_snapshot(&self) -> Arc<Upstreams> {
45 self.upstreams.borrow().clone()
46 }
47
48 pub fn anthropic_upstream(&self) -> String {
50 self.upstreams.borrow().anthropic.clone()
51 }
52
53 pub fn openai_upstream(&self) -> String {
55 self.upstreams.borrow().openai.clone()
56 }
57
58 pub fn gemini_upstream(&self) -> String {
60 self.upstreams.borrow().gemini.clone()
61 }
62}
63
64pub struct ProxyStats {
65 pub requests_total: AtomicU64,
66 pub requests_compressed: AtomicU64,
67 pub tokens_saved: AtomicU64,
68 pub bytes_original: AtomicU64,
69 pub bytes_compressed: AtomicU64,
70}
71
72impl Default for ProxyStats {
73 fn default() -> Self {
74 Self {
75 requests_total: AtomicU64::new(0),
76 requests_compressed: AtomicU64::new(0),
77 tokens_saved: AtomicU64::new(0),
78 bytes_original: AtomicU64::new(0),
79 bytes_compressed: AtomicU64::new(0),
80 }
81 }
82}
83
84impl ProxyStats {
85 pub fn record_request(&self) {
86 self.requests_total.fetch_add(1, Ordering::Relaxed);
87 }
88
89 pub fn record_compression(&self, original: usize, compressed: usize) {
90 self.requests_compressed.fetch_add(1, Ordering::Relaxed);
91 self.bytes_original
92 .fetch_add(original as u64, Ordering::Relaxed);
93 self.bytes_compressed
94 .fetch_add(compressed as u64, Ordering::Relaxed);
95 let saved_tokens = (original.saturating_sub(compressed) / 4) as u64;
96 self.tokens_saved.fetch_add(saved_tokens, Ordering::Relaxed);
97 }
98
99 pub fn compression_ratio(&self) -> f64 {
100 let original = self.bytes_original.load(Ordering::Relaxed);
101 if original == 0 {
102 return 0.0;
103 }
104 let compressed = self.bytes_compressed.load(Ordering::Relaxed);
105 (1.0 - compressed as f64 / original as f64) * 100.0
106 }
107}
108
109fn connect_timeout_secs() -> u64 {
111 std::env::var("LEAN_CTX_PROXY_CONNECT_TIMEOUT_SECS")
112 .ok()
113 .and_then(|v| v.trim().parse::<u64>().ok())
114 .filter(|s| *s > 0)
115 .unwrap_or(15)
116}
117
118fn read_idle_timeout_secs() -> u64 {
123 std::env::var("LEAN_CTX_PROXY_READ_TIMEOUT_SECS")
124 .ok()
125 .and_then(|v| v.trim().parse::<u64>().ok())
126 .filter(|s| *s > 0)
127 .unwrap_or(300)
128}
129
130fn upstream_reload_secs() -> u64 {
133 std::env::var("LEAN_CTX_PROXY_RELOAD_SECS")
134 .ok()
135 .and_then(|v| v.trim().parse::<u64>().ok())
136 .filter(|s| *s > 0)
137 .unwrap_or(5)
138}
139
140fn spawn_upstream_refresh(tx: tokio::sync::watch::Sender<Arc<Upstreams>>, initial: Upstreams) {
149 let interval = std::time::Duration::from_secs(upstream_reload_secs());
150 tokio::spawn(async move {
151 let mut last = initial;
152 loop {
153 tokio::time::sleep(interval).await;
154 let next = crate::core::config::Config::load()
155 .proxy
156 .refresh_upstreams(&last);
157 if next != last {
158 log_upstream_change(&last, &next);
159 last = next.clone();
160 if tx.send(Arc::new(next)).is_err() {
161 break;
162 }
163 }
164 }
165 });
166}
167
168fn log_upstream_change(old: &Upstreams, new: &Upstreams) {
171 if old.anthropic != new.anthropic {
172 println!(" ↻ Anthropic upstream → {}", new.anthropic);
173 }
174 if old.openai != new.openai {
175 println!(" ↻ OpenAI upstream → {}", new.openai);
176 }
177 if old.gemini != new.gemini {
178 println!(" ↻ Gemini upstream → {}", new.gemini);
179 }
180}
181
182pub async fn start_proxy(port: u16) -> anyhow::Result<()> {
183 let token = crate::core::session_token::resolve_proxy_token("LEAN_CTX_PROXY_TOKEN");
184 start_proxy_with_token(port, Some(token)).await
185}
186
187fn effective_auth_token(auth_token: Option<String>) -> String {
192 auth_token
193 .filter(|t| !t.trim().is_empty())
194 .unwrap_or_else(|| crate::core::session_token::resolve_proxy_token("LEAN_CTX_PROXY_TOKEN"))
195}
196
197pub async fn start_proxy_with_token(port: u16, auth_token: Option<String>) -> anyhow::Result<()> {
198 use crate::core::config::{Config, is_local_proxy_url};
199
200 let auth_token = effective_auth_token(auth_token);
201
202 let client = reqwest::Client::builder()
207 .connect_timeout(std::time::Duration::from_secs(connect_timeout_secs()))
208 .read_timeout(std::time::Duration::from_secs(read_idle_timeout_secs()))
209 .build()?;
210
211 usage_meter::resume_from_disk();
214
215 let cfg = Config::load();
216 let initial = cfg.proxy.resolve_all();
217
218 let (upstream_tx, upstream_rx) = tokio::sync::watch::channel(Arc::new(initial.clone()));
223 spawn_upstream_refresh(upstream_tx, initial.clone());
224
225 let Upstreams {
226 anthropic: anthropic_upstream,
227 openai: openai_upstream,
228 gemini: gemini_upstream,
229 } = initial;
230
231 let state = ProxyState {
232 client,
233 port,
234 stats: Arc::new(ProxyStats::default()),
235 introspect: Arc::new(introspect::IntrospectState::default()),
236 upstreams: upstream_rx,
237 };
238
239 let mut app = Router::new()
240 .route("/health", get(health))
241 .route("/status", get(status_handler))
242 .route("/v1/messages", any(anthropic::handler))
243 .route("/v1/messages/{*rest}", any(anthropic::handler))
244 .route("/v1/chat/completions", any(openai::handler))
245 .route(
247 "/v1/responses",
248 post(openai_responses::handler).get(openai_responses::ws_handler),
249 )
250 .route("/v1/responses/{*rest}", any(openai_responses::handler))
251 .route("/messages", any(anthropic::handler))
257 .route("/messages/{*rest}", any(anthropic::handler))
258 .route("/chat/completions", any(openai::handler))
259 .route(
260 "/responses",
261 post(openai_responses::handler).get(openai_responses::ws_handler),
262 )
263 .route("/responses/{*rest}", any(openai_responses::handler))
264 .route("/v1/references/{id}", get(v1_resolve_reference))
265 .fallback(fallback_router)
266 .layer(axum::middleware::from_fn(host_guard))
267 .with_state(state);
268
269 {
270 let expected = auth_token.clone();
271 app = app.layer(axum::middleware::from_fn(move |req, next| {
272 let expected = expected.clone();
273 proxy_auth_guard(req, next, expected)
274 }));
275 }
276
277 app = app.layer(axum::middleware::from_fn(normalize_provider_path));
281
282 let addr = SocketAddr::from(([127, 0, 0, 1], port));
283 println!("lean-ctx proxy listening on http://{addr} (token auth enabled)");
284 println!(" Anthropic: POST /v1/messages → {anthropic_upstream}");
285 println!(" OpenAI: POST /v1/chat/completions → {openai_upstream}");
286 println!(
287 " OpenAI: POST /v1/responses → {openai_upstream} (bare /responses also accepted)"
288 );
289 println!(" Gemini: POST /v1beta/models/... → {gemini_upstream}");
290 println!(
294 " Codex: WS ws://{addr}/responses → bridged to {openai_upstream} (HTTP/SSE, #440)"
295 );
296 if openai_upstream.starts_with("http://") && !is_local_proxy_url(&openai_upstream) {
297 println!(
298 " ⚠ OpenAI upstream is plaintext HTTP to a non-loopback host \
299 (allow_insecure_http_upstream) — use only on a trusted local network"
300 );
301 }
302
303 let listener = tokio::net::TcpListener::bind(addr).await?;
304 axum::serve(listener, app)
305 .with_graceful_shutdown(shutdown_signal())
306 .await?;
307
308 println!("lean-ctx proxy shut down cleanly.");
309 Ok(())
310}
311
312async fn shutdown_signal() {
313 let ctrl_c = tokio::signal::ctrl_c();
314
315 #[cfg(unix)]
316 {
317 match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
320 Ok(mut sigterm) => {
321 tokio::select! {
322 _ = ctrl_c => {},
323 _ = sigterm.recv() => {},
324 }
325 }
326 Err(e) => {
327 tracing::warn!("lean-ctx proxy: SIGTERM handler unavailable ({e}); Ctrl-C only");
328 ctrl_c.await.ok();
329 }
330 }
331 }
332
333 #[cfg(not(unix))]
334 {
335 ctrl_c.await.ok();
336 }
337
338 println!("lean-ctx proxy: received shutdown signal, draining…");
339}
340
341async fn health() -> impl IntoResponse {
342 let body = serde_json::json!({
343 "status": "ok",
344 "pid": std::process::id(),
345 });
346 (StatusCode::OK, axum::Json(body))
347}
348
349async fn v1_resolve_reference(
350 axum::extract::Path(id): axum::extract::Path<String>,
351) -> impl IntoResponse {
352 match crate::server::reference_store::resolve(&id) {
353 Some(content) => (StatusCode::OK, content),
354 None => (
355 StatusCode::NOT_FOUND,
356 "Reference expired or not found".to_string(),
357 ),
358 }
359}
360
361async fn status_handler(State(state): State<ProxyState>) -> impl IntoResponse {
362 use std::sync::atomic::Ordering::Relaxed;
363 let s = &state.stats;
364 let i = &state.introspect;
365
366 let last_breakdown = i
367 .last_breakdown
368 .lock()
369 .ok()
370 .and_then(|guard| guard.as_ref().map(|b| serde_json::to_value(b).ok()))
371 .flatten();
372
373 let spend = usage_meter::snapshot();
375 let spend_total: f64 = spend.iter().map(|m| m.cost_usd).sum();
376
377 let up = state.upstream_snapshot();
381
382 let body = serde_json::json!({
383 "status": "running",
384 "port": state.port,
385 "upstreams": {
386 "anthropic": up.anthropic.clone(),
387 "openai": up.openai.clone(),
388 "gemini": up.gemini.clone(),
389 },
390 "requests_total": s.requests_total.load(Relaxed),
391 "requests_compressed": s.requests_compressed.load(Relaxed),
392 "tokens_saved": s.tokens_saved.load(Relaxed),
393 "tokens_saved_estimated": true,
394 "bytes_original": s.bytes_original.load(Relaxed),
395 "bytes_compressed": s.bytes_compressed.load(Relaxed),
396 "compression_ratio_pct": format!("{:.1}", s.compression_ratio()),
397 "per_model": cost::snapshot(),
398 "spend": {
399 "source": "measured",
400 "total_usd": spend_total,
401 "per_model": spend,
402 "note": "Actual provider bill: real model + billed tokens (incl. cache reads/writes & reasoning) read from upstream responses for proxy-routed clients."
403 },
404 "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.",
405 "introspect": {
406 "total_requests_analyzed": i.total_requests.load(Relaxed),
407 "total_system_prompt_tokens": i.total_system_prompt_tokens.load(Relaxed),
408 "last_breakdown": last_breakdown,
409 }
410 });
411 (StatusCode::OK, axum::Json(body))
412}
413
414async fn proxy_auth_guard(
415 req: axum::extract::Request,
416 next: axum::middleware::Next,
417 expected_token: String,
418) -> Result<Response, Response> {
419 let path = req.uri().path();
420 if path == "/health" {
421 return Ok(next.run(req).await);
422 }
423
424 if let Some(auth) = req
426 .headers()
427 .get("authorization")
428 .and_then(|v| v.to_str().ok())
429 && let Some(token) = auth.strip_prefix("Bearer ")
430 && constant_time_eq(token.as_bytes(), expected_token.as_bytes())
431 {
432 return Ok(next.run(req).await);
433 }
434
435 if has_provider_api_key(&req) && is_provider_route(path) {
440 return Ok(next.run(req).await);
441 }
442
443 let cfg = crate::core::config::Config::load();
444 let hint = match cfg.proxy_enabled {
445 Some(true) => {
446 "lean-ctx proxy requires authentication. Use a Bearer token (LEAN_CTX_PROXY_TOKEN) or configure your AI tool's API key."
447 }
448 Some(false) => "lean-ctx proxy is disabled but still running. Run: lean-ctx proxy cleanup",
449 None => {
450 "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"
451 }
452 };
453
454 let body = serde_json::json!({
455 "type": "error",
456 "error": {
457 "type": "authentication_error",
458 "message": format!("401 Unauthorized — {hint}")
459 }
460 });
461
462 Err((StatusCode::UNAUTHORIZED, axum::Json(body)).into_response())
463}
464
465fn has_provider_api_key(req: &axum::extract::Request) -> bool {
466 let headers = req.headers();
467 for key in ["x-api-key", "x-goog-api-key", "api-key"] {
470 if headers
471 .get(key)
472 .and_then(|v| v.to_str().ok())
473 .is_some_and(|v| !v.trim().is_empty())
474 {
475 return true;
476 }
477 }
478 if let Some(auth) = headers.get("authorization").and_then(|v| v.to_str().ok()) {
487 let auth = auth.trim();
488 let credential = auth
489 .strip_prefix("Bearer ")
490 .or_else(|| auth.strip_prefix("bearer "))
491 .unwrap_or(auth)
492 .trim();
493 return !credential.is_empty() && !credential.eq_ignore_ascii_case("bearer");
495 }
496 false
497}
498
499fn is_provider_route(path: &str) -> bool {
500 path.starts_with("/v1/")
501 || path.starts_with("/v1beta/")
502 || path.starts_with("/chat/completions")
503 || path.starts_with("/responses")
504 || path.starts_with("/messages")
505}
506
507fn canonical_provider_path(path: &str) -> Option<String> {
518 if let Some(rest) = path.strip_prefix("/v1/v1/") {
522 return Some(format!("/v1/{rest}"));
523 }
524 const BARE_TO_CANONICAL: &[(&str, &str)] = &[
525 ("/responses", "/v1/responses"),
526 ("/chat/completions", "/v1/chat/completions"),
527 ("/messages", "/v1/messages"),
528 ];
529 for (bare, canonical) in BARE_TO_CANONICAL {
530 if path == *bare {
531 return Some((*canonical).to_string());
532 }
533 if let Some(rest) = path.strip_prefix(&format!("{bare}/")) {
534 return Some(format!("{canonical}/{rest}"));
535 }
536 }
537 None
538}
539
540fn normalized_provider_uri(uri: &axum::http::Uri) -> Option<axum::http::Uri> {
544 let canonical = canonical_provider_path(uri.path())?;
545 let new_path_and_query = match uri.query() {
546 Some(q) => format!("{canonical}?{q}"),
547 None => canonical,
548 };
549 new_path_and_query.parse::<axum::http::Uri>().ok()
550}
551
552async fn normalize_provider_path(
556 mut req: axum::extract::Request,
557 next: axum::middleware::Next,
558) -> Response {
559 if let Some(uri) = normalized_provider_uri(req.uri()) {
560 *req.uri_mut() = uri;
561 }
562 next.run(req).await
563}
564
565fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
566 use subtle::ConstantTimeEq;
567 if a.len() != b.len() {
568 return false;
569 }
570 bool::from(a.ct_eq(b))
571}
572
573async fn host_guard(
574 req: axum::extract::Request,
575 next: axum::middleware::Next,
576) -> Result<Response, StatusCode> {
577 if let Some(host) = req.headers().get("host").and_then(|v| v.to_str().ok()) {
578 let h = host.split(':').next().unwrap_or(host);
579 if matches!(h, "127.0.0.1" | "localhost" | "[::1]") {
580 return Ok(next.run(req).await);
581 }
582 }
583 Err(StatusCode::FORBIDDEN)
584}
585
586async fn fallback_router(State(state): State<ProxyState>, req: Request<Body>) -> Response {
587 let path = req.uri().path().to_string();
588
589 if path.starts_with("/v1beta/models/") || path.starts_with("/v1/models/") {
590 match google::handler(State(state), req).await {
591 Ok(resp) => resp,
592 Err(status) => Response::builder()
593 .status(status)
594 .body(Body::from("proxy error"))
595 .expect("BUG: building error response with valid status should never fail"),
596 }
597 } else {
598 let method = req.method().to_string();
599 eprintln!("lean-ctx proxy: unmatched {method} {path}");
600 Response::builder()
601 .status(StatusCode::NOT_FOUND)
602 .body(Body::from(format!(
603 "lean-ctx proxy: no handler for {method} {path}"
604 )))
605 .expect("BUG: building 404 response should never fail")
606 }
607}
608
609#[cfg(test)]
610mod auth_tests {
611 use super::*;
612
613 #[test]
616 fn effective_auth_token_never_yields_empty() {
617 let _env = crate::core::data_dir::test_env_lock();
618 let tmp = tempfile::tempdir().unwrap();
619 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
620
621 assert_eq!(effective_auth_token(Some("tok".into())), "tok");
622 let auto = effective_auth_token(None);
623 assert!(!auto.trim().is_empty(), "None must auto-resolve a token");
624 let blank = effective_auth_token(Some(" ".into()));
625 assert!(!blank.trim().is_empty(), "blank tokens must be replaced");
626
627 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
628 }
629
630 #[test]
631 fn is_provider_route_v1() {
632 assert!(is_provider_route("/v1/chat/completions"));
633 assert!(is_provider_route("/v1/messages"));
634 assert!(is_provider_route("/v1/completions"));
635 }
636
637 #[test]
638 fn is_provider_route_anthropic_subpaths() {
639 assert!(is_provider_route("/v1/messages/count_tokens"));
640 assert!(is_provider_route("/v1/messages/batches"));
641 assert!(is_provider_route("/v1/messages/batches/batch_123"));
642 }
643
644 #[test]
645 fn is_provider_route_v1beta() {
646 assert!(is_provider_route("/v1beta/models"));
647 }
648
649 #[test]
650 fn is_provider_route_chat() {
651 assert!(is_provider_route("/chat/completions"));
652 }
653
654 #[test]
655 fn is_provider_route_rejects_non_provider() {
656 assert!(!is_provider_route("/health"));
657 assert!(!is_provider_route("/api/v2/test"));
658 assert!(!is_provider_route("/"));
659 }
660
661 fn build_request(headers: &[(&str, &str)], path: &str) -> axum::extract::Request {
662 let mut builder = axum::http::Request::builder().uri(path);
663 for (k, v) in headers {
664 builder = builder.header(*k, *v);
665 }
666 builder.body(axum::body::Body::empty()).unwrap()
667 }
668
669 #[test]
670 fn has_provider_api_key_x_api_key() {
671 let req = build_request(&[("x-api-key", "sk-ant-abc123")], "/v1/messages");
672 assert!(has_provider_api_key(&req));
673 }
674
675 #[test]
676 fn has_provider_api_key_x_goog() {
677 let req = build_request(&[("x-goog-api-key", "AIzaSyAbc")], "/v1beta/models");
678 assert!(has_provider_api_key(&req));
679 }
680
681 #[test]
682 fn has_provider_api_key_azure() {
683 let req = build_request(&[("api-key", "deadbeef")], "/v1/completions");
684 assert!(has_provider_api_key(&req));
685 }
686
687 #[test]
688 fn has_provider_api_key_bearer_sk() {
689 let req = build_request(
690 &[("authorization", "Bearer sk-proj-abc123")],
691 "/v1/chat/completions",
692 );
693 assert!(has_provider_api_key(&req));
694 }
695
696 #[test]
697 fn has_provider_api_key_empty_rejected() {
698 let req = build_request(&[("x-api-key", " ")], "/v1/messages");
699 assert!(!has_provider_api_key(&req));
700 }
701
702 #[test]
703 fn has_provider_api_key_no_headers() {
704 let req = build_request(&[], "/v1/messages");
705 assert!(!has_provider_api_key(&req));
706 }
707
708 #[test]
709 fn has_provider_api_key_accepts_non_sk_bearer() {
710 for key in [
716 "Bearer or-v1-9f8e7d6c", "Bearer gsk_live_1234", "Bearer abc.def.ghi", "Bearer 0123456789", ] {
721 let req = build_request(&[("authorization", key)], "/v1/responses");
722 assert!(
723 has_provider_api_key(&req),
724 "non-sk Bearer must count as a provider credential: {key}"
725 );
726 }
727 }
728
729 #[test]
730 fn has_provider_api_key_empty_bearer_rejected() {
731 for bad in ["Bearer ", "", "Bearer", "bearer", " "] {
734 let req = build_request(&[("authorization", bad)], "/responses");
735 assert!(
736 !has_provider_api_key(&req),
737 "blank/scheme-only Authorization must not authenticate: {bad:?}"
738 );
739 }
740 }
741
742 #[test]
745 fn is_provider_route_bare_responses_and_messages() {
746 assert!(is_provider_route("/responses"));
749 assert!(is_provider_route("/responses/resp_123/input_items"));
750 assert!(is_provider_route("/messages"));
751 }
752
753 #[test]
754 fn canonical_provider_path_rewrites_bare_endpoints() {
755 assert_eq!(
756 canonical_provider_path("/responses").as_deref(),
757 Some("/v1/responses")
758 );
759 assert_eq!(
760 canonical_provider_path("/chat/completions").as_deref(),
761 Some("/v1/chat/completions")
762 );
763 assert_eq!(
764 canonical_provider_path("/messages").as_deref(),
765 Some("/v1/messages")
766 );
767 }
768
769 #[test]
770 fn canonical_provider_path_preserves_subpaths() {
771 assert_eq!(
772 canonical_provider_path("/responses/resp_abc/cancel").as_deref(),
773 Some("/v1/responses/resp_abc/cancel")
774 );
775 assert_eq!(
776 canonical_provider_path("/messages/batches/batch_1").as_deref(),
777 Some("/v1/messages/batches/batch_1")
778 );
779 }
780
781 #[test]
782 fn canonical_provider_path_ignores_already_canonical_and_unknown() {
783 assert_eq!(canonical_provider_path("/v1/responses"), None);
785 assert_eq!(canonical_provider_path("/v1/chat/completions"), None);
786 assert_eq!(canonical_provider_path("/health"), None);
788 assert_eq!(canonical_provider_path("/responsesx"), None);
789 assert_eq!(canonical_provider_path("/"), None);
790 }
791
792 #[test]
793 fn canonical_provider_path_collapses_double_v1_prefix() {
794 assert_eq!(
797 canonical_provider_path("/v1/v1/responses").as_deref(),
798 Some("/v1/responses")
799 );
800 assert_eq!(
801 canonical_provider_path("/v1/v1/chat/completions").as_deref(),
802 Some("/v1/chat/completions")
803 );
804 }
805
806 #[test]
807 fn normalized_provider_uri_rewrites_path_and_preserves_query() {
808 use axum::http::Uri;
809 let uri: Uri = "/responses?stream=true".parse().unwrap();
810 let rewritten = normalized_provider_uri(&uri).expect("bare /responses must rewrite");
811 assert_eq!(rewritten.path(), "/v1/responses");
812 assert_eq!(rewritten.query(), Some("stream=true"));
813 assert_eq!(
814 rewritten
815 .path_and_query()
816 .map(axum::http::uri::PathAndQuery::as_str),
817 Some("/v1/responses?stream=true")
818 );
819 }
820
821 #[test]
822 fn normalized_provider_uri_noop_for_canonical() {
823 use axum::http::Uri;
824 let uri: Uri = "/v1/responses".parse().unwrap();
825 assert!(normalized_provider_uri(&uri).is_none());
826 }
827}
828
829#[cfg(test)]
830mod upstream_tests {
831 use super::*;
832
833 fn upstreams_with_openai(openai: &str) -> Upstreams {
834 Upstreams {
835 anthropic: "https://api.anthropic.com".into(),
836 openai: openai.into(),
837 gemini: "https://generativelanguage.googleapis.com".into(),
838 }
839 }
840
841 #[tokio::test]
845 async fn proxy_state_reads_upstream_live_from_watch() {
846 let (tx, rx) =
847 tokio::sync::watch::channel(Arc::new(upstreams_with_openai("https://old.example")));
848 let state = ProxyState {
849 client: reqwest::Client::new(),
850 port: 0,
851 stats: Arc::new(ProxyStats::default()),
852 introspect: Arc::new(introspect::IntrospectState::default()),
853 upstreams: rx,
854 };
855 assert_eq!(state.openai_upstream(), "https://old.example");
856
857 tx.send(Arc::new(upstreams_with_openai("https://new.example")))
858 .unwrap();
859 assert_eq!(
860 state.openai_upstream(),
861 "https://new.example",
862 "a live handler read must reflect the published change"
863 );
864 assert_eq!(state.upstream_snapshot().openai, "https://new.example");
865 }
866
867 #[tokio::test]
877 #[allow(clippy::await_holding_lock)]
878 async fn config_change_is_picked_up_live_without_restart() {
879 use crate::core::config::Config;
880
881 let _lock = crate::core::data_dir::test_env_lock();
882 let tmp = tempfile::tempdir().unwrap();
883 crate::test_env::set_var("LEAN_CTX_DATA_DIR", tmp.path());
884 crate::test_env::remove_var("LEAN_CTX_OPENAI_UPSTREAM");
887 crate::test_env::set_var("LEAN_CTX_PROXY_RELOAD_SECS", "1");
888
889 Config::update_global(|c| {
891 c.proxy.openai_upstream = Some("http://127.0.0.1:19101".into());
892 })
893 .unwrap();
894 let initial = Config::load().proxy.resolve_all();
895 assert_eq!(initial.openai, "http://127.0.0.1:19101");
896
897 let (tx, rx) = tokio::sync::watch::channel(Arc::new(initial.clone()));
898 spawn_upstream_refresh(tx, initial);
899
900 Config::update_global(|c| {
902 c.proxy.openai_upstream = Some("http://127.0.0.1:19102".into());
903 })
904 .unwrap();
905
906 let mut live = rx.borrow().openai.clone();
908 for _ in 0..80 {
909 if live == "http://127.0.0.1:19102" {
910 break;
911 }
912 tokio::time::sleep(std::time::Duration::from_millis(100)).await;
913 live = rx.borrow().openai.clone();
914 }
915 assert_eq!(
916 live, "http://127.0.0.1:19102",
917 "running proxy must serve the new config.toml upstream without a restart"
918 );
919
920 crate::test_env::remove_var("LEAN_CTX_PROXY_RELOAD_SECS");
921 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
922 }
923}