1use sha2::{Digest, Sha256};
9use std::collections::HashMap;
10use std::net::IpAddr;
11use std::sync::{Mutex, OnceLock};
12use std::time::{Duration, Instant};
13
14pub const TOKEN_PREFIX: &str = "amxg_";
16
17#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct Grant {
20 pub agent: String,
22 pub def_id: String,
24 pub route: String,
25 pub account: String,
27 pub peer: Option<IpAddr>,
31}
32
33#[derive(Default)]
34struct Registry {
35 by_digest: HashMap<[u8; 32], Grant>,
36 by_agent: HashMap<(String, String), String>,
37 replaced: HashMap<[u8; 32], (String, String)>,
41 minted: HashMap<[u8; 32], Instant>,
43}
44
45fn registry() -> &'static Mutex<Registry> {
46 static REGISTRY: OnceLock<Mutex<Registry>> = OnceLock::new();
47 REGISTRY.get_or_init(Default::default)
48}
49
50fn digest(token: &str) -> [u8; 32] {
51 Sha256::digest(token.as_bytes()).into()
52}
53
54fn mint() -> String {
55 let token = format!("{TOKEN_PREFIX}{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple());
56 token
57}
58
59fn withhold_owner(key: &(String, String)) -> String {
62 format!("gateway-token:{}:{}", key.0, key.1)
63}
64
65pub fn token_for(agent: &str, def_id: &str, route: &str) -> String {
68 token_for_account(agent, def_id, route, "")
69}
70
71pub fn token_for_account(agent: &str, def_id: &str, route: &str, account: &str) -> String {
74 let mut reg = registry().lock().unwrap();
75 let key = (def_id.to_string(), route.to_string());
76 let token = reg.by_agent.get(&key).cloned().unwrap_or_else(mint);
77 reg.minted.entry(digest(&token)).or_insert_with(Instant::now);
78 crate::backend::transcript::withhold::hold(&withhold_owner(&key), &token, None);
80 reg.by_agent.insert(key, token.clone());
81 let peer = reg.by_digest.get(&digest(&token)).and_then(|g| g.peer);
83 reg.by_digest.insert(digest(&token), Grant { agent: agent.to_string(), def_id: def_id.to_string(), route: route.to_string(), account: account.to_string(), peer });
84 token
85}
86
87pub fn renew_for_account(agent: &str, def_id: &str, route: &str, account: &str, peer: Option<IpAddr>) -> String {
93 let mut reg = registry().lock().unwrap();
94 let key = (def_id.to_string(), route.to_string());
95 let grant = Grant { agent: agent.to_string(), def_id: def_id.to_string(), route: route.to_string(), account: account.to_string(), peer };
96 if let Some(old) = reg.by_agent.get(&key).cloned() {
97 if reg.by_digest.get(&digest(&old)) == Some(&grant) {
98 return old;
99 }
100 reg.by_agent.remove(&key);
101 let account = reg.by_digest.get(&digest(&old)).map(|grant| grant.account.clone()).unwrap_or_default();
102 tracing::info!(def_id = %key.0, route = %key.1, account = %account, "model gateway: a token was ended");
103 reg.by_digest.remove(&digest(&old));
104 reg.minted.remove(&digest(&old));
105 reg.replaced.retain(|_, k| *k != key);
107 reg.replaced.insert(digest(&old), key.clone());
108 }
109 let token = mint();
110 crate::backend::transcript::withhold::hold(&withhold_owner(&key), &token, None);
111 reg.by_agent.insert(key, token.clone());
112 reg.by_digest.insert(digest(&token), grant);
113 reg.minted.insert(digest(&token), Instant::now());
114 token
115}
116
117pub fn current_grant_of_replaced(token: &str) -> Option<Grant> {
121 let reg = registry().lock().unwrap();
122 let key = reg.replaced.get(&digest(token))?;
123 reg.by_digest.get(&digest(reg.by_agent.get(key)?)).cloned()
124}
125
126pub fn grant_for(token: &str) -> Option<Grant> {
127 if !token.starts_with(TOKEN_PREFIX) {
128 return None;
129 }
130 registry().lock().unwrap().by_digest.get(&digest(token)).cloned()
131}
132
133pub fn revoke(def_id: &str, route: &str) {
135 let mut reg = registry().lock().unwrap();
136 let key = (def_id.to_string(), route.to_string());
137 end_token(&mut reg, &key);
138}
139
140pub fn revoke_agent(name: &str, route: &str) {
143 revoke_agent_older_than(name, route, Duration::ZERO);
144}
145
146pub fn revoke_agent_older_than(name: &str, route: &str, min_age: Duration) {
149 end_agent_tokens(name, Some(route), min_age);
150}
151
152pub fn revoke_agent_everywhere(name: &str) {
154 end_agent_tokens(name, None, Duration::ZERO);
155}
156
157pub fn revoke_agent_everywhere_older_than(name: &str, min_age: Duration) {
160 end_agent_tokens(name, None, min_age);
161}
162
163fn end_agent_tokens(name: &str, route: Option<&str>, min_age: Duration) {
164 let mut reg = registry().lock().unwrap();
165 let ended: Vec<(String, String)> = reg
166 .by_agent
167 .iter()
168 .filter(|((_, r), _)| route.map_or(true, |route| r == route))
169 .filter(|(_, token)| reg.by_digest.get(&digest(token)).is_some_and(|g| g.def_id == name || g.agent == name))
170 .filter(|(_, token)| reg.minted.get(&digest(token)).map_or(true, |at| at.elapsed() >= min_age))
171 .map(|(key, _)| key.clone())
172 .collect();
173 for key in ended {
174 end_token(&mut reg, &key);
175 }
176}
177
178pub fn unknown_token_reason(presented: Option<&str>) -> &'static str {
183 match presented {
184 None => "the model gateway needs the agent's gateway token: the request carried no credential",
185 Some(t) if t.starts_with(TOKEN_PREFIX) => {
186 "this gateway token is not current: AgentMux started again, or the agent was moved to another account or relaunched, since it was made; relaunch the agent to give it a new one"
187 }
188 Some(_) => "the model gateway needs the agent's gateway token, not another credential",
189 }
190}
191
192fn end_token(reg: &mut Registry, key: &(String, String)) {
194 if let Some(token) = reg.by_agent.remove(key) {
195 let account = reg.by_digest.get(&digest(&token)).map(|g| g.account.clone()).unwrap_or_default();
197 tracing::info!(def_id = %key.0, route = %key.1, account = %account, "model gateway: a token was ended");
198 reg.by_digest.remove(&digest(&token));
199 reg.minted.remove(&digest(&token));
200 }
201 reg.replaced.retain(|_, k| k != key);
202 crate::backend::transcript::withhold::release(&withhold_owner(key));
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208
209 #[test]
210 fn replacing_and_revoking_tokens_logs_the_ended_grant_without_secrets() {
211 #[derive(Clone, Default)]
212 struct Capture(std::sync::Arc<Mutex<Vec<u8>>>);
213 impl std::io::Write for Capture {
214 fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
215 self.0.lock().unwrap().extend_from_slice(bytes);
216 Ok(bytes.len())
217 }
218 fn flush(&mut self) -> std::io::Result<()> {
219 Ok(())
220 }
221 }
222 impl<'writer> tracing_subscriber::fmt::MakeWriter<'writer> for Capture {
223 type Writer = Capture;
224 fn make_writer(&'writer self) -> Capture {
225 self.clone()
226 }
227 }
228 let output = Capture::default();
229 let subscriber = tracing_subscriber::fmt().json().with_writer(output.clone()).with_max_level(tracing::Level::INFO).finish();
230 let (old, renewed) = tracing::subscriber::with_default(subscriber, || {
231 let old = renew_for_account("log-agent", "log-def", "anthropic", "old-account", None);
232 assert_eq!(renew_for_account("log-agent", "log-def", "anthropic", "old-account", None), old);
233 assert!(output.0.lock().unwrap().is_empty(), "minting and reusing do not end a token");
234 let renewed = renew_for_account("log-agent", "log-def", "anthropic", "new-account", None);
235 assert_ne!(renewed, old);
236 assert_eq!(grant_for(&old), None);
237 assert_eq!(current_grant_of_replaced(&old), grant_for(&renewed));
238 assert_eq!(grant_for(&renewed).unwrap().account, "new-account");
239 revoke("log-def", "anthropic");
240 assert_eq!(current_grant_of_replaced(&old), None);
241 (old, renewed)
242 });
243 let text = String::from_utf8(output.0.lock().unwrap().clone()).unwrap();
244 assert!(!text.contains(&old) && !text.contains(&renewed));
245 assert!(!text.contains(TOKEN_PREFIX));
246 let events: Vec<serde_json::Value> = text.lines().map(|line| serde_json::from_str(line).unwrap()).collect();
247 assert_eq!(events.len(), 2, "{text}");
248 for (event, account) in events.iter().zip(["old-account", "new-account"]) {
249 assert_eq!(event["level"], "INFO");
250 assert_eq!(event["fields"], serde_json::json!({
251 "message": "model gateway: a token was ended",
252 "def_id": "log-def",
253 "route": "anthropic",
254 "account": account,
255 }));
256 }
257 }
258
259 #[test]
260 fn a_refusal_says_whether_no_credential_another_credential_or_a_gateway_token_srv_does_not_hold_was_shown() {
261 let none = unknown_token_reason(None);
262 let other = unknown_token_reason(Some("sk-ant-not-a-gateway-token"));
263 let stale = unknown_token_reason(Some(&format!("{TOKEN_PREFIX}0123456789abcdef")));
264 assert_eq!(std::collections::HashSet::from([none, other, stale]).len(), 3, "three causes, three answers");
265 assert!(none.contains("no credential"));
266 assert!(stale.contains("started again") && stale.contains("relaunch"));
267 for text in [none, other, stale] {
268 assert!(!text.contains("sk-ant") && !text.contains("0123456789abcdef"), "nothing of what was shown is repeated");
269 }
270 }
271
272 #[test]
273 fn a_token_is_reused_per_agent_and_route_and_can_be_revoked() {
274 let a = token_for("gw-agent", "gw-def", "openrouter");
275 assert!(a.starts_with(TOKEN_PREFIX));
276 assert_eq!(token_for("gw-agent", "gw-def", "openrouter"), a);
277 assert_ne!(token_for("gw-other", "gw-def-2", "openrouter"), a);
278 let grant = grant_for(&a).unwrap();
279 assert_eq!((grant.agent.as_str(), grant.route.as_str()), ("gw-agent", "openrouter"));
280 revoke("gw-def", "openrouter");
281 assert_eq!(grant_for(&a), None);
282 assert_ne!(token_for("gw-agent", "gw-def", "openrouter"), a);
283 }
284
285 #[test]
286 fn a_renewed_token_replaces_the_old_one_and_holds_its_address() {
287 let ip: IpAddr = "172_30_0_9".replace('_', ".").parse().unwrap();
288 let first = token_for_account("tk-agent", "tk-def", "anthropic", "acct");
289 let second = renew_for_account("tk-agent", "tk-def", "anthropic", "acct", Some(ip));
290 assert_ne!(first, second);
291 assert_eq!(grant_for(&first), None, "the earlier token ends when the next turn's begins");
292 assert_eq!(grant_for(&second).unwrap().peer, Some(ip));
293 assert_eq!(token_for_account("tk-agent", "tk-def", "anthropic", "acct"), second);
295 assert_eq!(grant_for(&second).unwrap().peer, Some(ip));
296 revoke("tk-def", "anthropic");
297 }
298
299 #[test]
300 fn a_turn_that_overlaps_another_on_the_same_grant_keeps_its_token_and_any_change_ends_it() {
301 let ip: IpAddr = "172_30_0_9".replace('_', ".").parse().unwrap();
302 let other: IpAddr = "172_30_0_10".replace('_', ".").parse().unwrap();
303 let first = renew_for_account("ov-agent", "ov-def", "anthropic", "acct", Some(ip));
304 assert_eq!(renew_for_account("ov-agent", "ov-def", "anthropic", "acct", Some(ip)), first);
306 assert!(grant_for(&first).is_some());
307 let moved = renew_for_account("ov-agent", "ov-def", "anthropic", "acct", Some(other));
309 assert_ne!(moved, first);
310 assert_eq!(grant_for(&first), None);
311 let switched = renew_for_account("ov-agent", "ov-def", "anthropic", "acct-2", Some(other));
312 assert_ne!(switched, moved);
313 assert_eq!(grant_for(&moved), None);
314 revoke("ov-def", "anthropic");
315 }
316
317 #[test]
318 fn a_replaced_token_names_the_agents_current_grant_only_while_the_agent_holds_one() {
319 let ip: IpAddr = "172_30_0_9".replace('_', ".").parse().unwrap();
320 let spawned = token_for_account("rp-agent", "rp-def", "anthropic", "acct");
321 let bound = renew_for_account("rp-agent", "rp-def", "anthropic", "acct", Some(ip));
322 assert_eq!(grant_for(&spawned), None, "the replaced token is never accepted");
323 assert_eq!(current_grant_of_replaced(&spawned), grant_for(&bound));
324 assert_eq!(current_grant_of_replaced(&bound), None, "a live token is not a replaced one");
325 assert_eq!(current_grant_of_replaced("amxg_never-made"), None);
326 revoke_agent("rp-def", "anthropic");
327 assert_eq!(current_grant_of_replaced(&spawned), None, "it ends with the agent's token");
328 let spawned = token_for_account("rp-agent", "rp-def", "anthropic", "acct");
330 renew_for_account("rp-agent", "rp-def", "anthropic", "acct", Some(ip));
331 revoke("rp-def", "anthropic");
332 assert_eq!(current_grant_of_replaced(&spawned), None);
333 }
334
335 #[test]
336 fn revoking_an_agent_ends_its_token_for_that_route_only() {
337 let key = token_for_account("rv-agent", "rv-def", "anthropic", "acct");
338 let model = token_for("rv-agent", "rv-def", "openrouter");
339 let other = token_for_account("rv-other", "rv-def-2", "anthropic", "acct");
340 revoke_agent("rv-def", "anthropic");
341 assert_eq!(grant_for(&key), None);
342 assert!(grant_for(&model).is_some(), "another route's token stays");
343 assert!(grant_for(&other).is_some(), "another agent's token stays");
344 revoke("rv-def", "openrouter");
345 revoke("rv-def-2", "anthropic");
346 }
347
348 #[test]
349 fn unknown_and_foreign_tokens_have_no_grant() {
350 assert_eq!(grant_for("amxg_not-a-real-token"), None);
351 assert_eq!(grant_for("amxc_not-a-gateway-token"), None);
352 assert_eq!(grant_for(""), None);
353 }
354
355 #[test]
356 fn only_the_latest_replaced_token_is_kept_for_an_agent_and_route() {
357 let ip: IpAddr = "172_30_0_9".replace('_', ".").parse().unwrap();
358 let other: IpAddr = "172_30_0_10".replace('_', ".").parse().unwrap();
359 let first = token_for_account("lr-agent", "lr-def", "anthropic", "acct");
360 let second = renew_for_account("lr-agent", "lr-def", "anthropic", "acct", Some(ip));
361 let third = renew_for_account("lr-agent", "lr-def", "anthropic", "acct", Some(other));
362 assert_ne!(second, third);
363 let reg = registry().lock().unwrap();
364 let kept = reg.replaced.values().filter(|k| **k == ("lr-def".to_string(), "anthropic".to_string())).count();
365 assert_eq!(kept, 1, "one entry per agent and route, not one per renewal");
366 drop(reg);
367 assert_eq!(current_grant_of_replaced(&second), grant_for(&third), "the latest replaced token still names the agent's turn");
368 assert_eq!(current_grant_of_replaced(&first), None);
369 assert_eq!(grant_for(&first), None);
370 revoke("lr-def", "anthropic");
371 }
372
373 #[test]
374 fn an_older_token_ends_with_a_container_that_stopped_and_a_newer_one_stays() {
375 let old = token_for_account("ag-agent", "ag-def", "anthropic", "acct");
376 revoke_agent_older_than("ag-agent", "anthropic", Duration::from_secs(3600));
378 assert!(grant_for(&old).is_some(), "a token made within the age is left alone");
379 revoke_agent_older_than("ag-agent", "anthropic", Duration::ZERO);
381 assert_eq!(grant_for(&old), None);
382 let next = token_for_account("ag-agent", "ag-def", "anthropic", "acct");
384 assert_ne!(next, old);
385 revoke("ag-def", "anthropic");
386 }
387}