Skip to main content

agentmux_srv_core/backend/model_gateway/
token.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The per-agent token a harness sends to the gateway in place of a model key, minted the way a
5//! container token is (`container::credential`): kept by digest, valid for one route, attributed to
6//! one agent. It lives for this srv launch, as the instance key an agent is launched with does.
7
8use sha2::{Digest, Sha256};
9use std::collections::HashMap;
10use std::net::IpAddr;
11use std::sync::{Mutex, OnceLock};
12use std::time::{Duration, Instant};
13
14/// Prefix that marks a gateway token in logs and bug reports.
15pub const TOKEN_PREFIX: &str = "amxg_";
16
17/// What a token was minted for.
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct Grant {
20    /// The agent's routing id (its slug), which every other record of it uses.
21    pub agent: String,
22    /// The agent definition's id, whose route and model the gateway reads.
23    pub def_id: String,
24    pub route: String,
25    /// The API-key account the token spends, for the key route (`catalog::KEY_ROUTE_ID`); empty on a model route.
26    pub account: String,
27    /// The one address the token may be used from: the container's own on the agents network, set at the start of each
28    /// container turn, on every platform (on Docker Desktop srv learns it from the gateway forwarder's stamp). `None` only
29    /// for a host agent's token.
30    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    /// The key-route token that [`renew_for_account`] last replaced for an agent and route (one per agent and route), and whose
38    /// it was: only so a turn that was set up with it can still say whose turn it is ([`current_grant_of_replaced`]). It
39    /// authorizes nothing.
40    replaced: HashMap<[u8; 32], (String, String)>,
41    /// When each live token was made, so an event about a container that ended can leave alone a token made after it.
42    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
59/// Who holds an agent's token for a route in the transcript withhold registry: the token that replaces it takes its
60/// place, and ending the token ([`end_token`]) drops it.
61fn withhold_owner(key: &(String, String)) -> String {
62    format!("gateway-token:{}:{}", key.0, key.1)
63}
64
65/// The agent's token for `route`: minted on first use and reused after, so a relaunch of the same
66/// agent keeps the token a running child still holds.
67pub fn token_for(agent: &str, def_id: &str, route: &str) -> String {
68    token_for_account(agent, def_id, route, "")
69}
70
71/// [`token_for`] for the key route: the token also names the account it spends, which the gateway checks against the
72/// agent's link at every request. Asked again with another account, the same token now spends that one.
73pub 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    // A token an agent's process holds is never written into a transcript, for as long as it works.
79    crate::backend::transcript::withhold::hold(&withhold_owner(&key), &token, None);
80    reg.by_agent.insert(key, token.clone());
81    // A token a container turn is running on keeps its address when the next message's environment asks for it again.
82    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
87/// A gateway route's token (the key route or a model route) for a container turn, accepted only from `peer` when there is one. The agent's earlier token stops
88/// working at once unless it already holds exactly this grant (the same agent, account and address): two panes of one
89/// container agent run turns that overlap, and the second must not end the token the first is running on. A container's
90/// token ends with the container ([`revoke_agent`]), so a recreated container, a new address or another account is always
91/// given a new one.
92pub 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        // Only the latest replaced token is kept for this agent and route: the ones before it are not asked for again.
106        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
117/// The agent's current grant for a token that [`renew_for_account`] replaced, while the agent still holds one for that route:
118/// a message queued during a container agent's first turn was set up with the token that turn then replaced. The replaced
119/// token itself is never accepted ([`grant_for`] says none); this only names whose turn it is. Gone with the agent's token.
120pub 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
133/// Ends the agent's access to `route` without touching its environment: the next request is refused.
134pub 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
140/// Ends every token for `route` that was made for the agent `name` names: its definition id or its routing id (slug). A
141/// container is named from the agent's id, so this is what its stop, recreation and removal can say.
142pub fn revoke_agent(name: &str, route: &str) {
143    revoke_agent_older_than(name, route, Duration::ZERO);
144}
145
146/// [`revoke_agent`] for the tokens made at least `min_age` ago. A container that ended outside AgentMux is only heard of
147/// from Docker's event stream, which can run behind: a token made since (for the container that took its place) is left alone.
148pub fn revoke_agent_older_than(name: &str, route: &str, min_age: Duration) {
149    end_agent_tokens(name, Some(route), min_age);
150}
151
152/// [`revoke_agent`] for every route: a container's stop, recreation or removal ends all of its agent's gateway tokens.
153pub fn revoke_agent_everywhere(name: &str) {
154    end_agent_tokens(name, None, Duration::ZERO);
155}
156
157/// [`revoke_agent_older_than`] for every route: a container's stop ends all of its agent's gateway tokens, model routes
158/// and the key route alike.
159pub 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
178/// Why a request that no token matched was refused, in words for the log and the refusal: it carried no credential, or
179/// one that is not a gateway token, or a gateway token this srv does not hold (srv started again since it was made, or
180/// the agent was moved to another account, relaunched or had its access ended). Nothing of the credential is read but its
181/// prefix. A harness shows all of these as a bare "HTTP 401 Not logged in"; this is where the difference is.
182pub 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
192/// Drops the token for `key` and every record of it.
193fn end_token(reg: &mut Registry, key: &(String, String)) {
194    if let Some(token) = reg.by_agent.remove(key) {
195        // Said in the log, so a later refusal of this token ("the gateway needs the agent's token") has its cause beside it.
196        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        // The next message's environment asks for the agent's token again: the running turn's token keeps its address.
294        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        // A second pane's turn on the same container: the first turn's token keeps working.
305        assert_eq!(renew_for_account("ov-agent", "ov-def", "anthropic", "acct", Some(ip)), first);
306        assert!(grant_for(&first).is_some());
307        // A new address (the container was made again) or another account is given a new token and the old one ends.
308        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        // The same after a revoke by id.
329        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        // Just made: an event about the container that ended before it was made must not end it.
377        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        // Made longer ago than the age: it ends.
380        revoke_agent_older_than("ag-agent", "anthropic", Duration::ZERO);
381        assert_eq!(grant_for(&old), None);
382        // A new token is made for the next turn, never the ended one.
383        let next = token_for_account("ag-agent", "ag-def", "anthropic", "acct");
384        assert_ne!(next, old);
385        revoke("ag-def", "anthropic");
386    }
387}