Skip to main content

agentmux_common/
gateway_stamp.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The stamp the container agents' gateway forwarder puts on a model-gateway request, and what srv checks.
5//!
6//! Where srv cannot see which container a request comes from (Docker Desktop: every container arrives from one address),
7//! a small forwarder on the agents network sees the container's own address and says it to srv in three headers: the
8//! address, the time, and a proof. The proof is an HMAC of the address, the time, the request's method and its target
9//! (path and query), made with a secret only srv and the forwarder have, so a stamp cannot be moved to another request,
10//! another address or another time. srv accepts a stamp only on the gateway's own paths and for [`WINDOW_SECS`].
11
12use hmac::{Hmac, Mac};
13use sha2::Sha256;
14use std::net::IpAddr;
15
16/// The model gateway's path prefix: the only paths the forwarder forwards and a stamp is accepted on.
17pub const PATH_PREFIX: &str = "/api/v1/model/";
18/// Every header the forwarder sets starts with this; it removes any such header a client sent.
19pub const HEADER_PREFIX: &str = "x-amx-fwd-";
20pub const HEADER_PEER: &str = "x-amx-fwd-peer";
21pub const HEADER_TS: &str = "x-amx-fwd-ts";
22pub const HEADER_PROOF: &str = "x-amx-fwd-proof";
23/// How long a stamp is good for after the time it names, in seconds.
24pub const WINDOW_SECS: u64 = 30;
25/// How far ahead of this machine's clock a stamp's time may be, in seconds (two clocks on one machine).
26const AHEAD_SECS: u64 = 5;
27
28type HmacSha256 = Hmac<Sha256>;
29
30/// Why a stamp is not accepted. Never shown to the caller beyond "refused".
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum Refusal {
33    /// A stamp header is missing.
34    Missing,
35    /// A header is not an address, a time or a proof.
36    Malformed,
37    /// The time is outside the window.
38    Expired,
39    /// The request's target is not under the gateway's path prefix, or is written in a way that could mean another path.
40    OutsidePrefix,
41    /// The proof does not match.
42    BadProof,
43}
44
45/// The request target a stamp may cover: under [`PATH_PREFIX`] exactly as written, with nothing that could make a
46/// different path of it (an encoded byte, a backslash, an empty or dot segment).
47pub fn covered_target(target: &str) -> bool {
48    let path = target.split('?').next().unwrap_or("");
49    path.starts_with(PATH_PREFIX) && !path.contains('%') && !path.contains('\\') && path[PATH_PREFIX.len()..].split('/').all(|seg| seg != ".." && seg != ".") && !path.contains("//")
50}
51
52fn mac(secret: &[u8], peer: IpAddr, ts: u64, method: &str, target: &str) -> HmacSha256 {
53    let mut mac = HmacSha256::new_from_slice(secret).expect("an HMAC takes a key of any length");
54    for part in [b"amx-gateway-fwd-v1".as_slice(), peer.to_string().as_bytes(), ts.to_string().as_bytes(), method.to_ascii_uppercase().as_bytes(), target.as_bytes()] {
55        mac.update(part);
56        mac.update(b"\n");
57    }
58    mac
59}
60
61fn hex(bytes: &[u8]) -> String {
62    bytes.iter().map(|b| format!("{b:02x}")).collect()
63}
64
65fn unhex(text: &str) -> Option<Vec<u8>> {
66    if text.len() % 2 != 0 || !text.is_ascii() {
67        return None;
68    }
69    (0..text.len()).step_by(2).map(|i| u8::from_str_radix(&text[i..i + 2], 16).ok()).collect()
70}
71
72/// The proof for one request, as hex.
73pub fn proof(secret: &[u8], peer: IpAddr, ts: u64, method: &str, target: &str) -> String {
74    hex(&mac(secret, peer, ts, method, target).finalize().into_bytes())
75}
76
77/// The peer a stamp names, when it is good for this request now. The comparison of the proofs does not depend on where they
78/// differ.
79pub fn verify(secret: &[u8], peer: Option<&str>, ts: Option<&str>, proof: Option<&str>, method: &str, target: &str, now_secs: u64) -> Result<IpAddr, Refusal> {
80    let (Some(peer), Some(ts), Some(proof)) = (peer, ts, proof) else { return Err(Refusal::Missing) };
81    let peer: IpAddr = peer.parse().map_err(|_| Refusal::Malformed)?;
82    let ts: u64 = ts.parse().map_err(|_| Refusal::Malformed)?;
83    let given = unhex(proof).ok_or(Refusal::Malformed)?;
84    if !covered_target(target) {
85        return Err(Refusal::OutsidePrefix);
86    }
87    // The proof first: `Expired` then means a proof made with the secret whose time is off, never a guess.
88    mac(secret, peer, ts, method, target).verify_slice(&given).map_err(|_| Refusal::BadProof)?;
89    if ts > now_secs.saturating_add(AHEAD_SECS) || now_secs.saturating_sub(ts) > WINDOW_SECS {
90        return Err(Refusal::Expired);
91    }
92    Ok(peer)
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    const SECRET: &[u8] = b"test-secret-not-a-real-one";
100    const TARGET: &str = "/api/v1/model/anthropic/v1/messages?beta=true";
101
102    fn ip(last: u8) -> IpAddr {
103        IpAddr::from([172, 30, 0, last])
104    }
105
106    fn stamped(peer: IpAddr, ts: u64, method: &str, target: &str) -> (String, String, String) {
107        (peer.to_string(), ts.to_string(), proof(SECRET, peer, ts, method, target))
108    }
109
110    fn check(s: &(String, String, String), method: &str, target: &str, now: u64) -> Result<IpAddr, Refusal> {
111        verify(SECRET, Some(&s.0), Some(&s.1), Some(&s.2), method, target, now)
112    }
113
114    #[test]
115    fn a_good_stamp_names_its_peer() {
116        let s = stamped(ip(9), 1000, "POST", TARGET);
117        assert_eq!(check(&s, "POST", TARGET, 1000), Ok(ip(9)));
118        assert_eq!(check(&s, "post", TARGET, 1010), Ok(ip(9)), "the method's case does not matter");
119        assert_eq!(check(&s, "POST", TARGET, 1000 + WINDOW_SECS), Ok(ip(9)));
120    }
121
122    #[test]
123    fn a_stamp_cannot_be_moved_to_another_request_address_or_time() {
124        let s = stamped(ip(9), 1000, "POST", TARGET);
125        assert_eq!(check(&s, "GET", TARGET, 1000), Err(Refusal::BadProof), "another method");
126        assert_eq!(check(&s, "POST", "/api/v1/model/anthropic/v1/messages", 1000), Err(Refusal::BadProof), "another target");
127        let other_peer = (ip(10).to_string(), s.1.clone(), s.2.clone());
128        assert_eq!(check(&other_peer, "POST", TARGET, 1000), Err(Refusal::BadProof), "another address");
129        let later = (s.0.clone(), "1001".to_string(), s.2.clone());
130        assert_eq!(check(&later, "POST", TARGET, 1001), Err(Refusal::BadProof), "another time");
131        assert_eq!(verify(b"another-secret", Some(&s.0), Some(&s.1), Some(&s.2), "POST", TARGET, 1000), Err(Refusal::BadProof), "another secret");
132    }
133
134    #[test]
135    fn a_stamp_is_good_only_inside_its_window() {
136        let s = stamped(ip(9), 1000, "POST", TARGET);
137        assert_eq!(check(&s, "POST", TARGET, 1000 + WINDOW_SECS + 1), Err(Refusal::Expired));
138        assert_eq!(check(&s, "POST", TARGET, 1000 - 5), Ok(ip(9)), "a clock a few seconds behind");
139        assert_eq!(check(&s, "POST", TARGET, 1000 - 6), Err(Refusal::Expired), "a time well ahead of this clock");
140    }
141
142    #[test]
143    fn only_a_real_proof_can_be_expired() {
144        let s = stamped(ip(9), 1000, "POST", TARGET);
145        let guessed = (s.0.clone(), s.1.clone(), "00".repeat(32));
146        assert_eq!(check(&guessed, "POST", TARGET, 1000 + WINDOW_SECS + 100), Err(Refusal::BadProof), "a guess with a stale time is a bad proof, not an expired one");
147    }
148
149    #[test]
150    fn a_stamp_is_refused_on_any_path_outside_the_gateway_prefix() {
151        for target in [
152            "/api/v1/MODEL/anthropic/v1/messages",
153            "/API/v1/model/anthropic/v1/messages",
154            "/api/v1/%6dodel/anthropic/v1/messages",
155            "/api/v1/model/anthropic/%2e%2e/%2e%2e/secrets",
156            "/api/v1/model/../containers",
157            "/api/v1/model/./anthropic",
158            "/api/v1/model//anthropic",
159            "/api/v1/model\\anthropic",
160            "/api/v1/models/anthropic",
161            "/api/v1/model",
162            "/api/v1/containers",
163            "/agentmux/hook/x",
164            "",
165        ] {
166            let s = stamped(ip(9), 1000, "POST", target);
167            assert_eq!(check(&s, "POST", target, 1000), Err(Refusal::OutsidePrefix), "{target}");
168        }
169        // A query may hold anything: it is not part of the path.
170        let with_query = "/api/v1/model/anthropic/v1/messages?next=/../x%2f";
171        assert_eq!(check(&stamped(ip(9), 1000, "POST", with_query), "POST", with_query, 1000), Ok(ip(9)));
172    }
173
174    #[test]
175    fn a_missing_or_malformed_stamp_is_refused() {
176        let s = stamped(ip(9), 1000, "POST", TARGET);
177        assert_eq!(verify(SECRET, None, Some(&s.1), Some(&s.2), "POST", TARGET, 1000), Err(Refusal::Missing));
178        assert_eq!(verify(SECRET, Some(&s.0), None, Some(&s.2), "POST", TARGET, 1000), Err(Refusal::Missing));
179        assert_eq!(verify(SECRET, Some(&s.0), Some(&s.1), None, "POST", TARGET, 1000), Err(Refusal::Missing));
180        assert_eq!(verify(SECRET, Some("not-an-address"), Some(&s.1), Some(&s.2), "POST", TARGET, 1000), Err(Refusal::Malformed));
181        assert_eq!(verify(SECRET, Some(&s.0), Some("soon"), Some(&s.2), "POST", TARGET, 1000), Err(Refusal::Malformed));
182        assert_eq!(verify(SECRET, Some(&s.0), Some(&s.1), Some("zz"), "POST", TARGET, 1000), Err(Refusal::Malformed));
183        assert_eq!(verify(SECRET, Some(&s.0), Some(&s.1), Some("abc"), "POST", TARGET, 1000), Err(Refusal::Malformed));
184        assert_eq!(verify(SECRET, Some(&s.0), Some(&s.1), Some(""), "POST", TARGET, 1000), Err(Refusal::BadProof), "an empty proof matches nothing");
185    }
186}