1use hmac::{Hmac, Mac};
13use sha2::Sha256;
14use std::net::IpAddr;
15
16pub const PATH_PREFIX: &str = "/api/v1/model/";
18pub 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";
23pub const WINDOW_SECS: u64 = 30;
25const AHEAD_SECS: u64 = 5;
27
28type HmacSha256 = Hmac<Sha256>;
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32pub enum Refusal {
33 Missing,
35 Malformed,
37 Expired,
39 OutsidePrefix,
41 BadProof,
43}
44
45pub 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
72pub 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
77pub 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 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 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}