Skip to main content

lean_ctx/proxy/
providers.rs

1//! Universal provider routes — the request-path half of the
2//! universal-provider-framework (enterprise#7).
3//!
4//! `/providers/{id}/...` forwards to the `[[proxy.providers]]` registry entry
5//! with that id, speaking the entry's declared [`WireShape`]. A new
6//! OpenAI/Anthropic/Gemini-compatible endpoint (Azure AI Foundry, OpenRouter,
7//! Groq, vLLM, a corporate gateway…) is therefore pure configuration — no code
8//! change, no rebuild:
9//!
10//! ```toml
11//! [[proxy.providers]]
12//! id = "foundry"
13//! shape = "openai"
14//! base_url = "https://my-resource.services.ai.azure.com"
15//! api_key_env = "FOUNDRY_API_KEY"   # optional: gateway-held credential
16//! ```
17//!
18//! Shape ≠ identity: the proxy understands four wire dialects (the shapes) and
19//! any number of provider identities map onto them. Compression, introspection
20//! and usage metering all run exactly as they do for the built-in routes of the
21//! same shape.
22//!
23//! When `api_key_env` is set, the gateway holds the upstream credential and the
24//! caller authenticates with the lean-ctx Bearer token only: every incoming
25//! credential header is stripped and replaced by the configured key (the caller
26//! never needs — or sees — the provider key). Without `api_key_env` the
27//! caller's own credentials are forwarded verbatim, exactly like the built-ins.
28
29use axum::{
30    body::Body,
31    extract::{Path, State},
32    http::{HeaderMap, HeaderValue, Request, StatusCode, Uri},
33    response::Response,
34};
35
36use super::{ProxyState, forward};
37use crate::core::config::{ResolvedProvider, WireShape};
38
39/// Request extension carrying the registry identity of the serving provider.
40///
41/// Shape ≠ identity (module docs): the forward path only knows the wire shape
42/// ("OpenAI"), but usage metering must attribute to the provider *identity*
43/// ("foundry", "local") — otherwise every OpenAI-shaped registry entry shows
44/// up as "OpenAI" in `usage_events` and the admin breakdown (enterprise#20).
45/// `local` carries the entry's resolved local-inference flag so shadow-rate
46/// billing works for non-loopback local endpoints too (host.docker.internal).
47#[derive(Debug, Clone)]
48pub(super) struct RegistryProviderId {
49    pub id: String,
50    pub local: bool,
51    pub account_ref: Option<String>,
52    pub region: Option<String>,
53    pub gateway_managed_credential: bool,
54}
55
56/// Registry ids that share the Grok / xAI dual-rail (subscription `grok-chat`,
57/// API-key `xai`). OpenAI wire shape; separate `proxy status` bucket.
58pub(super) fn is_grok_provider_id(id: &str) -> bool {
59    matches!(
60        id.trim().to_ascii_lowercase().as_str(),
61        "grok-chat" | "xai" | "grok"
62    )
63}
64
65/// Registry ids that share the Command Code gateway rail (`commandcode`).
66/// Separate `proxy status` bucket so traffic does not fold into the wire-shape
67/// line.
68pub(super) fn is_commandcode_provider_id(id: &str) -> bool {
69    matches!(
70        id.trim().to_ascii_lowercase().as_str(),
71        "commandcode" | "command-code"
72    )
73}
74
75/// Per-upstream stats label for a registry route.
76///
77/// Wire shape stays `OpenAI`/`Anthropic`/… for compression; identity for
78/// `ProxyStats` may differ (Grok must not fold into the OpenAI line).
79pub(super) fn stats_label<'a>(registry_id: Option<&str>, shape_label: &'a str) -> &'a str {
80    match registry_id {
81        Some(id) if is_grok_provider_id(id) => "Grok",
82        Some(id) if is_commandcode_provider_id(id) => "CommandCode",
83        _ => shape_label,
84    }
85}
86
87/// True when an OpenAI-shaped registry request should use the Responses
88/// compressor (`input` / `function_call_output`) rather than Chat Completions.
89pub(super) fn is_openai_responses_path(path: &str) -> bool {
90    let path = path.trim_end_matches('/');
91    path == "/responses"
92        || path == "/v1/responses"
93        || path.starts_with("/responses/")
94        || path.starts_with("/v1/responses/")
95}
96
97pub async fn handler(
98    State(state): State<ProxyState>,
99    Path((id, rest)): Path<(String, String)>,
100    mut req: Request<Body>,
101) -> Result<Response, StatusCode> {
102    let Some(provider) = state.upstream_snapshot().provider_by_id(&id).cloned() else {
103        tracing::warn!("lean-ctx proxy: unknown registry provider '{id}' (404)");
104        return Err(StatusCode::NOT_FOUND);
105    };
106    req.extensions_mut().insert(RegistryProviderId {
107        id: provider.id.clone(),
108        local: provider.local,
109        account_ref: provider.account_ref.clone(),
110        region: provider.region.clone(),
111        gateway_managed_credential: provider.api_key_env.is_some()
112            || provider.shape == WireShape::Bedrock,
113    });
114
115    // Strip the `/providers/{id}` prefix so the upstream sees the bare provider
116    // path: `/providers/foundry/v1/chat/completions` → `/v1/chat/completions`.
117    let path = format!("/{rest}");
118    let uri = match req.uri().query() {
119        Some(q) => format!("{path}?{q}").parse::<axum::http::Uri>(),
120        None => path.parse::<axum::http::Uri>(),
121    }
122    .map_err(|_| StatusCode::BAD_REQUEST)?;
123    *req.uri_mut() = uri;
124
125    if provider.shape == WireShape::Bedrock {
126        super::bedrock::validate_invoke_request(&req)?;
127        super::bedrock::attach_signing_context(&provider, &mut req)?;
128    } else if provider.api_key_env.is_some() {
129        if provider.shape == WireShape::Gemini {
130            strip_gemini_api_key_query(req.uri_mut())?;
131        }
132        inject_gateway_credential(&provider, req.headers_mut())?;
133    }
134
135    match provider.shape {
136        WireShape::Anthropic => {
137            forward::forward_request(
138                State(state),
139                req,
140                &provider.base_url,
141                "/v1/messages",
142                super::bedrock::passthrough_request_body,
143                "Anthropic",
144                &[],
145            )
146            .await
147        }
148        WireShape::OpenAi => {
149            // Built-in OpenAI routes pick Chat Completions vs Responses by path
150            // (`/v1/chat/completions` vs `/v1/responses`). Registry providers
151            // must do the same: Grok CLI hits `/providers/grok-chat/v1/responses`
152            // with `function_call_output` in `input`, which the Chat compressor
153            // ignores (it only rewrites `messages`). Path already has the
154            // `/providers/{id}` prefix stripped above.
155            if is_openai_responses_path(req.uri().path()) {
156                forward::forward_request(
157                    State(state),
158                    req,
159                    &provider.base_url,
160                    "/v1/responses",
161                    super::openai_responses::compress_request_body,
162                    "OpenAI",
163                    &[],
164                )
165                .await
166            } else {
167                forward::forward_request(
168                    State(state),
169                    req,
170                    &provider.base_url,
171                    "/v1/chat/completions",
172                    super::openai::compress_request_body,
173                    "OpenAI",
174                    &[],
175                )
176                .await
177            }
178        }
179        WireShape::Gemini => {
180            // Gemini carries the model in the URL path, not the body (#840).
181            let model = super::usage::gemini_model_from_path(req.uri().path());
182            forward::forward_request(
183                State(state),
184                req,
185                &provider.base_url,
186                "/",
187                move |body, size| {
188                    super::google::compress_request_body(body, size, model.as_deref())
189                },
190                "Gemini",
191                &["application/x-ndjson"],
192            )
193            .await
194        }
195        WireShape::Bedrock => {
196            forward::forward_request(
197                State(state),
198                req,
199                &provider.base_url,
200                "/",
201                super::bedrock::passthrough_request_body,
202                "Bedrock",
203                &["application/vnd.amazon.eventstream"],
204            )
205            .await
206        }
207    }
208}
209
210fn query_component_name(component: &str) -> Result<Option<String>, StatusCode> {
211    if component.is_empty() {
212        return Ok(None);
213    }
214    let url = reqwest::Url::parse(&format!("http://leanctx.invalid/?{component}"))
215        .map_err(|_| StatusCode::BAD_REQUEST)?;
216    Ok(url.query_pairs().next().map(|(name, _)| name.into_owned()))
217}
218
219fn is_api_key_query_component(component: &str) -> Result<bool, StatusCode> {
220    Ok(query_component_name(component)?.is_some_and(|name| name.eq_ignore_ascii_case("key")))
221}
222
223/// Gemini accepts API credentials through `?key=` as well as `x-goog-api-key`.
224/// For gateway-managed credentials, discard every decoded `key` query parameter
225/// so a caller cannot override the configured credential at the upstream.
226pub(super) fn strip_gemini_api_key_query(uri: &mut Uri) -> Result<(), StatusCode> {
227    let Some(query) = uri.query() else {
228        return Ok(());
229    };
230
231    let mut removed_key = false;
232    let mut retained = Vec::new();
233    for component in query.split('&') {
234        if is_api_key_query_component(component)? {
235            removed_key = true;
236        } else {
237            retained.push(component);
238        }
239    }
240    if !removed_key {
241        return Ok(());
242    }
243
244    let mut path_and_query = uri.path().to_string();
245    if retained.iter().any(|component| !component.is_empty()) {
246        path_and_query.push('?');
247        path_and_query.push_str(&retained.join("&"));
248    }
249    *uri = path_and_query
250        .parse()
251        .map_err(|_| StatusCode::BAD_REQUEST)?;
252    Ok(())
253}
254
255/// Any caller-supplied `key` parameter is a possible upstream credential or
256/// account selector. Treat undecodable query components conservatively when
257/// deciding whether a configured account label can be trusted.
258pub(super) fn has_untrusted_key_query(uri: &Uri) -> bool {
259    uri.query().is_some_and(|query| {
260        query.split('&').any(|component| {
261            query_component_name(component).map_or(true, |name| {
262                name.is_some_and(|name| name.eq_ignore_ascii_case("key"))
263            })
264        })
265    })
266}
267
268/// Replace every caller credential header with the gateway-held key from the
269/// entry's `api_key_env`, in the header dialect of the provider's shape. A
270/// configured-but-missing env var is a deployment error and must surface
271/// loudly (502), never silently forward the caller's lean-ctx token upstream.
272pub(super) fn inject_gateway_credential(
273    provider: &ResolvedProvider,
274    headers: &mut HeaderMap,
275) -> Result<(), StatusCode> {
276    let env_name = provider
277        .api_key_env
278        .as_deref()
279        .expect("caller checked api_key_env");
280    let key = std::env::var(env_name)
281        .ok()
282        .filter(|k| !k.trim().is_empty());
283    let Some(key) = key else {
284        tracing::error!(
285            "lean-ctx proxy: provider '{}' configures api_key_env='{env_name}' but the \
286             variable is unset/empty — cannot authenticate upstream (502)",
287            provider.id
288        );
289        return Err(StatusCode::BAD_GATEWAY);
290    };
291
292    // The caller authenticated against the gateway (Bearer token); none of its
293    // credential headers may leak upstream.
294    for h in ["authorization", "x-api-key", "api-key", "x-goog-api-key"] {
295        headers.remove(h);
296    }
297
298    let value = |v: String| {
299        HeaderValue::from_str(&v).map_err(|_| {
300            tracing::error!(
301                "lean-ctx proxy: provider '{}' key from {env_name} contains invalid header bytes",
302                provider.id
303            );
304            StatusCode::BAD_GATEWAY
305        })
306    };
307    match provider.shape {
308        WireShape::Anthropic => {
309            headers.insert("x-api-key", value(key)?);
310        }
311        WireShape::OpenAi => {
312            // Bearer for OpenAI-compatible endpoints; `api-key` additionally
313            // covers Azure deployments that only read that header.
314            headers.insert("api-key", value(key.clone())?);
315            headers.insert("authorization", value(format!("Bearer {key}"))?);
316        }
317        WireShape::Gemini => {
318            headers.insert("x-goog-api-key", value(key)?);
319        }
320        WireShape::Bedrock => unreachable!("Bedrock uses SigV4, not api_key_env"),
321    }
322    Ok(())
323}
324
325#[cfg(test)]
326mod tests {
327    use super::*;
328
329    #[test]
330    fn stats_label_maps_grok_rails_to_grok_bucket() {
331        assert_eq!(stats_label(Some("grok-chat"), "OpenAI"), "Grok");
332        assert_eq!(stats_label(Some("xai"), "OpenAI"), "Grok");
333        assert_eq!(stats_label(Some("GROK"), "OpenAI"), "Grok");
334        assert_eq!(stats_label(Some("foundry"), "OpenAI"), "OpenAI");
335        assert_eq!(stats_label(None, "OpenAI"), "OpenAI");
336        assert_eq!(stats_label(Some("local"), "OpenAI"), "OpenAI");
337    }
338
339    #[test]
340    fn is_grok_provider_id_accepts_dual_rail_ids() {
341        assert!(is_grok_provider_id("grok-chat"));
342        assert!(is_grok_provider_id("xai"));
343        assert!(is_grok_provider_id(" Grok "));
344        assert!(!is_grok_provider_id("openai"));
345        assert!(!is_grok_provider_id("foundry"));
346    }
347
348    #[test]
349    fn stats_label_maps_commandcode_rail_to_commandcode_bucket() {
350        assert_eq!(stats_label(Some("commandcode"), "OpenAI"), "CommandCode");
351        assert_eq!(stats_label(Some("command-code"), "OpenAI"), "CommandCode");
352        assert_eq!(stats_label(Some(" CommandCode "), "OpenAI"), "CommandCode");
353    }
354
355    #[test]
356    fn is_commandcode_provider_id_accepts_rail_ids() {
357        assert!(is_commandcode_provider_id("commandcode"));
358        assert!(is_commandcode_provider_id("command-code"));
359        assert!(is_commandcode_provider_id(" COMMANDCODE "));
360        assert!(!is_commandcode_provider_id("openai"));
361        assert!(!is_commandcode_provider_id("grok"));
362    }
363
364    #[test]
365    fn is_openai_responses_path_detects_responses_api() {
366        assert!(is_openai_responses_path("/v1/responses"));
367        assert!(is_openai_responses_path("/v1/responses/"));
368        assert!(is_openai_responses_path("/responses"));
369        assert!(is_openai_responses_path(
370            "/v1/responses/resp_123/input_items"
371        ));
372        assert!(!is_openai_responses_path("/v1/chat/completions"));
373        assert!(!is_openai_responses_path("/v1/models"));
374        assert!(!is_openai_responses_path("/v1/responsesx"));
375    }
376
377    fn provider(shape: WireShape, api_key_env: Option<&str>) -> ResolvedProvider {
378        ResolvedProvider {
379            id: "test".into(),
380            shape,
381            base_url: "https://example.invalid".into(),
382            api_key_env: api_key_env.map(str::to_string),
383            aws_region: None,
384            account_ref: None,
385            region: None,
386            local: false,
387        }
388    }
389
390    #[test]
391    fn injection_replaces_caller_credentials_per_shape() {
392        let _lock = crate::core::data_dir::test_env_lock();
393        crate::test_env::set_var("LC_TEST_PROVIDER_KEY", "sk-upstream");
394
395        for (shape, expect_header, expect_value) in [
396            (WireShape::Anthropic, "x-api-key", "sk-upstream"),
397            (WireShape::OpenAi, "authorization", "Bearer sk-upstream"),
398            (WireShape::Gemini, "x-goog-api-key", "sk-upstream"),
399        ] {
400            let mut headers = HeaderMap::new();
401            headers.insert("authorization", "Bearer lean-ctx-token".parse().unwrap());
402            headers.insert("x-api-key", "caller-key".parse().unwrap());
403            inject_gateway_credential(&provider(shape, Some("LC_TEST_PROVIDER_KEY")), &mut headers)
404                .expect("key present");
405
406            assert_eq!(
407                headers.get(expect_header).unwrap().to_str().unwrap(),
408                expect_value,
409                "{shape:?} must carry the gateway key in its native header"
410            );
411            // The caller's gateway token must never leak upstream.
412            let leaked = headers
413                .iter()
414                .any(|(_, v)| v.to_str().is_ok_and(|v| v.contains("lean-ctx-token")));
415            assert!(!leaked, "caller bearer token leaked upstream for {shape:?}");
416            if shape != WireShape::Anthropic {
417                assert!(
418                    headers.get("x-api-key").is_none(),
419                    "stale caller x-api-key must be stripped for {shape:?}"
420                );
421            }
422        }
423        crate::test_env::remove_var("LC_TEST_PROVIDER_KEY");
424    }
425
426    #[test]
427    fn gemini_gateway_credential_strips_decoded_and_duplicate_key_query_parameters() {
428        let mut uri: Uri = "/v1/models?alt=sse&%6Bey=caller-key&key=second-key&pretty=1"
429            .parse()
430            .expect("valid request URI");
431
432        strip_gemini_api_key_query(&mut uri).expect("query is valid");
433
434        assert_eq!(uri.to_string(), "/v1/models?alt=sse&pretty=1");
435        assert!(!has_untrusted_key_query(&uri));
436    }
437
438    #[test]
439    fn gemini_gateway_query_sanitizer_preserves_unrelated_query_parameters() {
440        let mut uri: Uri = "/v1/models?alt=sse&pretty=1"
441            .parse()
442            .expect("valid request URI");
443
444        strip_gemini_api_key_query(&mut uri).expect("query is valid");
445
446        assert_eq!(uri.to_string(), "/v1/models?alt=sse&pretty=1");
447        assert!(!has_untrusted_key_query(&uri));
448    }
449
450    #[test]
451    fn openai_shape_also_sets_azure_api_key_header() {
452        let _lock = crate::core::data_dir::test_env_lock();
453        crate::test_env::set_var("LC_TEST_PROVIDER_KEY2", "fk-123");
454        let mut headers = HeaderMap::new();
455        inject_gateway_credential(
456            &provider(WireShape::OpenAi, Some("LC_TEST_PROVIDER_KEY2")),
457            &mut headers,
458        )
459        .unwrap();
460        assert_eq!(headers.get("api-key").unwrap(), "fk-123");
461        crate::test_env::remove_var("LC_TEST_PROVIDER_KEY2");
462    }
463
464    #[test]
465    fn missing_key_env_is_a_loud_bad_gateway() {
466        let _lock = crate::core::data_dir::test_env_lock();
467        crate::test_env::remove_var("LC_TEST_PROVIDER_KEY_MISSING");
468        let mut headers = HeaderMap::new();
469        headers.insert("authorization", "Bearer lean-ctx-token".parse().unwrap());
470        let err = inject_gateway_credential(
471            &provider(WireShape::OpenAi, Some("LC_TEST_PROVIDER_KEY_MISSING")),
472            &mut headers,
473        )
474        .unwrap_err();
475        assert_eq!(err, StatusCode::BAD_GATEWAY);
476    }
477}