1use std::net::{IpAddr, SocketAddr};
14use std::time::Duration;
15
16use agentmux_common::gateway_stamp::{self, HEADER_PEER, HEADER_PREFIX, HEADER_PROOF, HEADER_TS};
17use axum::body::Body;
18use axum::extract::{ConnectInfo, State};
19use axum::http::{header, HeaderMap, HeaderName, HeaderValue, Request, StatusCode};
20use axum::response::{IntoResponse, Response};
21use axum::Router;
22
23const ENV_SECRET: &str = "AGENTMUX_GWFWD_SECRET";
24const ENV_UPSTREAM: &str = "AGENTMUX_GWFWD_UPSTREAM";
25const ENV_PORT: &str = "AGENTMUX_GWFWD_PORT";
26const DEFAULT_PORT: u16 = 4799;
27
28const HOP_BY_HOP: &[&str] = &["connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade", "host", "content-length"];
30
31#[derive(Clone)]
32struct Forwarder {
33 client: reqwest::Client,
34 upstream: String,
36 secret: Vec<u8>,
37}
38
39fn upstream_headers(from: &HeaderMap, secret: &[u8], peer: IpAddr, ts: u64, method: &str, target: &str) -> HeaderMap {
41 let mut out = HeaderMap::new();
42 for (name, value) in from {
43 let n = name.as_str();
44 if n.starts_with(HEADER_PREFIX) || HOP_BY_HOP.contains(&n) {
45 continue;
46 }
47 out.append(name.clone(), value.clone());
48 }
49 let proof = gateway_stamp::proof(secret, peer, ts, method, target);
50 for (name, value) in [(HEADER_PEER, peer.to_string()), (HEADER_TS, ts.to_string()), (HEADER_PROOF, proof)] {
51 if let Ok(value) = HeaderValue::from_str(&value) {
52 out.insert(HeaderName::from_static(name), value);
53 }
54 }
55 out
56}
57
58fn plain(status: StatusCode, text: &'static str) -> Response {
59 (status, text).into_response()
60}
61
62async fn forward(State(fwd): State<Forwarder>, ConnectInfo(from): ConnectInfo<SocketAddr>, request: Request<Body>) -> Response {
63 let (parts, body) = request.into_parts();
64 let target = parts.uri.path_and_query().map(|p| p.as_str().to_string()).unwrap_or_default();
65 if !gateway_stamp::covered_target(&target) {
67 return plain(StatusCode::NOT_FOUND, "not a model gateway path");
68 }
69 let headers = upstream_headers(&parts.headers, &fwd.secret, from.ip(), agentmux_common::time::now_secs_u64(), parts.method.as_str(), &target);
70 let sent = fwd.client.request(parts.method, format!("{}{}", fwd.upstream, target)).headers(headers).body(reqwest::Body::wrap_stream(body.into_data_stream())).send().await;
71 let Ok(answer) = sent else {
72 return plain(StatusCode::BAD_GATEWAY, "AgentMux could not be reached");
73 };
74 let (status, answer_headers) = (answer.status(), answer.headers().clone());
75 let mut out = Response::new(Body::from_stream(answer.bytes_stream()));
76 *out.status_mut() = status;
77 for (name, value) in &answer_headers {
78 if !HOP_BY_HOP.contains(&name.as_str()) && name != header::CONTENT_ENCODING {
79 out.headers_mut().append(name.clone(), value.clone());
80 }
81 }
82 out
83}
84
85fn app(fwd: Forwarder) -> Router {
86 Router::new().fallback(forward).with_state(fwd)
87}
88
89fn client() -> reqwest::Client {
90 agentmux_common::local_http::builder()
91 .no_proxy()
92 .connect_timeout(Duration::from_secs(15))
93 .read_timeout(Duration::from_secs(300))
94 .build()
95 .unwrap_or_else(|e| panic!("the TLS provider is missing, so no HTTP client can be built: {e}"))
96}
97
98pub async fn run() -> i32 {
100 let (Ok(secret), Ok(upstream)) = (std::env::var(ENV_SECRET), std::env::var(ENV_UPSTREAM)) else {
101 eprintln!("gateway-fwd: {ENV_SECRET} and {ENV_UPSTREAM} are needed; AgentMux starts this itself");
102 return 2;
103 };
104 std::env::remove_var(ENV_SECRET);
106 let port = std::env::var(ENV_PORT).ok().and_then(|p| p.parse().ok()).unwrap_or(DEFAULT_PORT);
107 let fwd = Forwarder { client: client(), upstream: upstream.trim_end_matches('/').to_string(), secret: secret.into_bytes() };
108 let listener = match tokio::net::TcpListener::bind(("0.0.0.0", port)).await {
109 Ok(l) => l,
110 Err(e) => {
111 eprintln!("gateway-fwd: could not listen on port {port}: {e}");
112 return 1;
113 }
114 };
115 match axum::serve(listener, app(fwd).into_make_service_with_connect_info::<SocketAddr>()).await {
116 Ok(()) => 0,
117 Err(e) => {
118 eprintln!("gateway-fwd: stopped: {e}");
119 1
120 }
121 }
122}
123
124#[cfg(test)]
125mod tests {
126 use super::*;
127 use axum::routing::any;
128 use std::sync::{Arc, Mutex};
129
130 const SECRET: &[u8] = b"a-test-secret";
131
132 fn headers(pairs: &[(&str, &str)]) -> HeaderMap {
133 let mut h = HeaderMap::new();
134 for (n, v) in pairs {
135 h.append(HeaderName::from_bytes(n.as_bytes()).unwrap(), HeaderValue::from_str(v).unwrap());
136 }
137 h
138 }
139
140 fn peer() -> IpAddr {
141 "172_30_0_9".replace('_', ".").parse().unwrap()
142 }
143
144 #[test]
145 fn a_stamp_a_client_sent_is_removed_whatever_its_case_and_the_forwarders_own_is_added() {
146 let target = "/api/v1/model/anthropic/v1/messages";
147 let sent = headers(&[
148 ("Authorization", "Bearer amxg_token"),
149 ("X-Amx-Fwd-Peer", "not-the-real-peer"),
150 ("x-amx-fwd-ts", "1"),
151 ("X-AMX-FWD-PROOF", "00"),
152 ("x-amx-fwd-extra", "whatever"),
153 ("Host", "agentmux-gateway-fwd:4799"),
154 ("Connection", "keep-alive"),
155 ("anthropic-version", "2023-06-01"),
156 ]);
157 let out = upstream_headers(&sent, SECRET, peer(), 1000, "POST", target);
158 assert_eq!(out.get("authorization").unwrap(), "Bearer amxg_token", "the token goes through untouched");
159 assert_eq!(out.get("anthropic-version").unwrap(), "2023-06-01");
160 assert!(out.get("host").is_none() && out.get("connection").is_none(), "this hop's headers are not passed on");
161 assert!(out.get("x-amx-fwd-extra").is_none());
162 for name in [HEADER_PEER, HEADER_TS, HEADER_PROOF] {
163 assert_eq!(out.get_all(name).iter().count(), 1, "exactly one {name}, the forwarder's");
164 }
165 let get = |n: &str| out.get(n).and_then(|v| v.to_str().ok());
166 assert_eq!(gateway_stamp::verify(SECRET, get(HEADER_PEER), get(HEADER_TS), get(HEADER_PROOF), "POST", target, 1000), Ok(peer()), "the stamp names the connection's own address");
167 }
168
169 async fn upstream(seen: Arc<Mutex<Vec<(String, HeaderMap, Vec<u8>)>>>) -> SocketAddr {
171 let router = Router::new().fallback(any(move |request: Request<Body>| {
172 let seen = seen.clone();
173 async move {
174 let (parts, body) = request.into_parts();
175 let bytes = axum::body::to_bytes(body, 1 << 20).await.unwrap().to_vec();
176 seen.lock().unwrap().push((parts.uri.to_string(), parts.headers, bytes));
177 let chunks = futures_chunks();
178 let mut answer = Response::new(Body::from_stream(chunks));
179 answer.headers_mut().insert("x-answer", HeaderValue::from_static("yes"));
180 answer
181 }
182 }));
183 let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
184 let addr = listener.local_addr().unwrap();
185 tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
186 addr
187 }
188
189 fn futures_chunks() -> impl futures_util::Stream<Item = Result<axum::body::Bytes, std::io::Error>> {
190 futures_util::stream::iter(vec![Ok(axum::body::Bytes::from_static(b"data: one\n\n")), Ok(axum::body::Bytes::from_static(b"data: two\n\n"))])
191 }
192
193 #[tokio::test]
194 async fn it_forwards_gateway_paths_with_the_stamp_streams_the_answer_and_refuses_every_other_path() {
195 let seen = Arc::new(Mutex::new(Vec::new()));
196 let srv = upstream(seen.clone()).await;
197 let fwd = Forwarder { client: client(), upstream: format!("http://{srv}"), secret: SECRET.to_vec() };
198 let listener = tokio::net::TcpListener::bind(("127.0.0.1", 0)).await.unwrap();
199 let at = listener.local_addr().unwrap();
200 tokio::spawn(async move { axum::serve(listener, app(fwd).into_make_service_with_connect_info::<SocketAddr>()).await.unwrap() });
201 let http = client();
202
203 let ok = http
204 .post(format!("http://{at}/api/v1/model/anthropic/v1/messages?beta=true"))
205 .header("authorization", "Bearer amxg_t")
206 .header("x-amx-fwd-peer", "10_9_9_9".replace('_', "."))
207 .body("{\"model\":\"m\"}")
208 .send()
209 .await
210 .unwrap();
211 assert_eq!(ok.status(), 200);
212 assert_eq!(ok.headers().get("x-answer").unwrap(), "yes");
213 assert_eq!(ok.text().await.unwrap(), "data: one\n\ndata: two\n\n");
214 let (uri, headers, body) = seen.lock().unwrap().pop().expect("srv was asked");
215 assert!(uri.ends_with("/api/v1/model/anthropic/v1/messages?beta=true"), "{uri}");
216 assert_eq!(body, b"{\"model\":\"m\"}");
217 assert_eq!(headers.get("authorization").unwrap(), "Bearer amxg_t");
218 let get = |n: &str| headers.get(n).and_then(|v| v.to_str().ok());
219 let now = agentmux_common::time::now_secs_u64();
220 let named = gateway_stamp::verify(SECRET, get(HEADER_PEER), get(HEADER_TS), get(HEADER_PROOF), "POST", "/api/v1/model/anthropic/v1/messages?beta=true", now);
221 assert_eq!(named, Ok(IpAddr::from([127, 0, 0, 1])), "the address of the connection, never the one the client wrote");
222
223 for path in ["/api/v1/containers", "/agentmux/hook/x", "/", "/api/v1/model/../containers", "/api/v1/%6dodel/anthropic/v1/messages", "/API/v1/model/anthropic"] {
224 let refused = http.get(format!("http://{at}{path}")).send().await.unwrap();
225 assert_eq!(refused.status(), 404, "{path}");
226 }
227 assert!(seen.lock().unwrap().is_empty(), "none of them reached srv");
228 }
229}