Skip to main content

agentmux_srv_core/backend/model_gateway/
request.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What the gateway forwards: which paths, which of the harness's headers, and which model the request
5//! names. Pure, so each is tested without a network.
6
7use super::catalog::Route;
8use axum::http::{HeaderMap, HeaderName, HeaderValue};
9use serde_json::Value;
10
11/// The harness's own paths a route serves. Anything else is refused, so the gateway is not a way to
12/// reach the rest of the upstream's API with the person's key.
13pub fn path_allowed(harness: &str, tail: &str) -> bool {
14    match harness {
15        "claude" => matches!(tail, "v1/messages" | "v1/messages/count_tokens" | "v1/models"),
16        _ => false,
17    }
18}
19
20pub fn upstream_url(route: &Route, region: &str, tail: &str, query: Option<&str>) -> String {
21    match query {
22        Some(q) if !q.is_empty() => format!("{}/{tail}?{q}", route.base_in(region)),
23        _ => format!("{}/{tail}", route.base_in(region)),
24    }
25}
26
27/// The headers worth forwarding. The harness's own credential is the gateway token and is never sent
28/// on; the upstream gets the route's key instead.
29const FORWARDED: &[&str] = &["content-type", "accept", "anthropic-version", "anthropic-beta", "user-agent"];
30
31pub fn forwarded_headers(from: &HeaderMap) -> HeaderMap {
32    let mut out = HeaderMap::new();
33    for name in FORWARDED {
34        let name = HeaderName::from_static(name);
35        for value in from.get_all(&name) {
36            out.append(name.clone(), value.clone());
37        }
38    }
39    // Plain bytes back, so what the usage tap reads is what the harness gets.
40    out.insert(HeaderName::from_static("accept-encoding"), HeaderValue::from_static("identity"));
41    out
42}
43
44/// The gateway token the harness sent: `Authorization: Bearer ...` (Claude Code with
45/// `ANTHROPIC_AUTH_TOKEN`) or `x-api-key`.
46pub fn bearer_token(headers: &HeaderMap) -> Option<String> {
47    let text = |name: &str| headers.get(name).and_then(|v| v.to_str().ok()).map(str::trim);
48    text("authorization")
49        .and_then(|v| v.strip_prefix("Bearer ").or_else(|| v.strip_prefix("bearer ")))
50        .or_else(|| text("x-api-key"))
51        .filter(|t| !t.is_empty())
52        .map(str::to_string)
53}
54
55/// The request body with its `model` made one the route serves. A harness that insists on a Claude
56/// name (the small model it uses for titles, an alias, a `[1m]` context suffix) is mapped to `chosen`,
57/// the model the agent was given. A body that is not JSON, or names no model, goes on as it is.
58pub fn with_served_model(body: &[u8], chosen: &str, serves: impl Fn(&str) -> bool) -> Vec<u8> {
59    let Ok(mut json) = serde_json::from_slice::<Value>(body) else { return body.to_vec() };
60    let Some(named) = json.get("model").and_then(Value::as_str) else { return body.to_vec() };
61    let bare = named.trim_end_matches("[1m]");
62    let model = if serves(bare) { bare } else { chosen };
63    if model == named {
64        return body.to_vec();
65    }
66    json["model"] = Value::String(model.to_string());
67    serde_json::to_vec(&json).unwrap_or_else(|_| body.to_vec())
68}
69
70/// The `model` the request body names, when it is JSON and names one.
71pub fn named_model(body: &[u8]) -> Option<String> {
72    serde_json::from_slice::<Value>(body).ok()?.get("model").and_then(Value::as_str).map(str::to_string)
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78    use crate::backend::model_gateway::catalog;
79
80    #[test]
81    fn only_the_harnesss_own_paths_are_forwarded() {
82        assert!(path_allowed("claude", "v1/messages"));
83        assert!(path_allowed("claude", "v1/messages/count_tokens"));
84        assert!(!path_allowed("claude", "v1/credits"));
85        assert!(!path_allowed("claude", "../keys"));
86        assert!(!path_allowed("codex", "v1/messages"));
87    }
88
89    #[test]
90    fn the_upstream_address_comes_from_the_route_alone() {
91        let route = catalog::route("openrouter").unwrap();
92        assert_eq!(upstream_url(route, "us-east-1", "v1/messages", None), "https://openrouter.ai/api/v1/messages");
93        assert_eq!(upstream_url(route, "us-east-1", "v1/messages", Some("beta=true")), "https://openrouter.ai/api/v1/messages?beta=true");
94    }
95
96    #[test]
97    fn bedrocks_address_has_the_persons_region_and_nothing_else_of_theirs() {
98        let route = catalog::route("bedrock").unwrap();
99        assert_eq!(upstream_url(route, "eu-west-1", "v1/messages", None), "https://bedrock-runtime.eu-west-1.amazonaws.com/anthropic/v1/messages");
100        assert!(route.key_in_x_api_key());
101        assert!(!catalog::route("openrouter").unwrap().key_in_x_api_key());
102    }
103
104    #[test]
105    fn the_harnesss_credential_is_not_forwarded() {
106        let mut from = HeaderMap::new();
107        from.insert("authorization", HeaderValue::from_static("Bearer amxg_secret"));
108        from.insert("x-api-key", HeaderValue::from_static("amxg_secret"));
109        from.insert("anthropic-version", HeaderValue::from_static("2023-06-01"));
110        from.insert("content-type", HeaderValue::from_static("application/json"));
111        let out = forwarded_headers(&from);
112        assert!(out.get("authorization").is_none() && out.get("x-api-key").is_none());
113        assert_eq!(out.get("anthropic-version").unwrap(), "2023-06-01");
114        assert_eq!(out.get("accept-encoding").unwrap(), "identity");
115    }
116
117    #[test]
118    fn the_token_is_read_from_either_header() {
119        let mut h = HeaderMap::new();
120        h.insert("authorization", HeaderValue::from_static("Bearer amxg_a"));
121        assert_eq!(bearer_token(&h).as_deref(), Some("amxg_a"));
122        let mut h = HeaderMap::new();
123        h.insert("x-api-key", HeaderValue::from_static("amxg_b"));
124        assert_eq!(bearer_token(&h).as_deref(), Some("amxg_b"));
125        assert_eq!(bearer_token(&HeaderMap::new()), None);
126    }
127
128    #[test]
129    fn a_claude_name_is_mapped_to_the_chosen_model() {
130        let route = catalog::route("openrouter").unwrap();
131        let serves = |m: &str| route.model(m).is_some();
132        let chosen = "deepseek/deepseek-v4.1-flash-1017";
133        let rewritten = |model: &str| {
134            let body = format!(r#"{{"model":"{model}","max_tokens":5}}"#);
135            let out = with_served_model(body.as_bytes(), chosen, serves);
136            serde_json::from_slice::<Value>(&out).unwrap()["model"].as_str().unwrap().to_string()
137        };
138        assert_eq!(rewritten("claude-haiku-4-5-20251001"), chosen);
139        assert_eq!(rewritten("sonnet"), chosen);
140        assert_eq!(rewritten("deepseek/deepseek-v4-pro-0813"), "deepseek/deepseek-v4-pro-0813");
141        assert_eq!(rewritten("deepseek/deepseek-v4-pro-0813[1m]"), "deepseek/deepseek-v4-pro-0813");
142        assert_eq!(with_served_model(b"not json", chosen, serves), b"not json");
143    }
144}