Skip to main content

agentmux_srv_core/backend/container/
key_route.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A container turn on the model gateway: a model route, or an API-key account (`model_gateway::catalog::KEY_ROUTE_ID`).
5//! The container is given only the gateway's address and a token for that one agent (and account); a key stays in the
6//! keychain. At the start of each turn this module makes that token current (a changed address or account, or a container
7//! made again, gets a new one and the earlier ends; a turn that overlaps another on the same grant shares its token) and ties
8//! it to the container's own address on the agents network, so the gateway accepts it from that container and no other:
9//!
10//! - **Linux:** srv listens on the network's gateway address and sees each container's own
11//!   ([`listener::check_gateway`](super::listener::check_gateway)).
12//! - **Docker Desktop (macOS, Windows):** every container reaches srv from one address, so the container is pointed at a
13//!   small forwarder on the agents network ([`gateway_fwd`]) which sees the container's own address and says it to srv in a
14//!   stamp ([`agentmux_common::gateway_stamp`]). With no forwarder there is no way in, and the turn is refused.
15
16use std::net::IpAddr;
17
18use super::{gateway_fwd, listener, ContainerError, ContainerManager};
19use crate::backend::model_gateway::{catalog::KEY_ROUTE_ID, token, PATH_PREFIX};
20
21/// Linux, and srv is not serving the agents network (a rootless daemon keeps its networks out of reach, or the bind failed).
22const NO_PATH: &str = "This agent's model access can't be used in a container on this machine: AgentMux could not open its gateway on the agents network (rootless Docker does this). Run the agent on this machine instead of in a container, or move it to a plan account.";
23/// The container has no address on the agents network yet.
24const NO_ADDRESS: &str = "This agent's container is not on the agents network yet, so its model access can't be tied to it. Send the message again; if it keeps failing, restart the agent.";
25/// The agent's token is gone (it was moved off the key, or the route was left, while the turn was starting).
26const GONE: &str = "This agent's model access for this turn has ended. Send the message again.";
27
28/// Ends every gateway token of the agent whose container this is (named from its id, `container_name_for_slug`).
29/// Called when the container is stopped, recreated (which stops and removes it) or removed, whatever the daemon answers.
30pub(super) fn revoke_container_tokens(container_name: &str) {
31    if let Some(agent) = container_name.strip_prefix("agentmux-") {
32        token::revoke_agent_everywhere(agent);
33    }
34}
35
36/// The route a base URL names on the gateway, if it names one.
37pub(super) fn route_named(base_url: &str) -> Option<&str> {
38    let tail = &base_url[base_url.find(PATH_PREFIX)? + PATH_PREFIX.len()..];
39    Some(tail.split(['/', '?']).next().unwrap_or("")).filter(|r| !r.is_empty())
40}
41
42/// Whether a base URL names the gateway's key route.
43pub(super) fn names_key_route(base_url: &str) -> bool {
44    route_named(base_url) == Some(KEY_ROUTE_ID)
45}
46
47/// The route the turn's environment points the agent at, if it is the gateway's.
48fn gateway_route(env: &[(String, String)]) -> Option<&str> {
49    env.iter().find(|(k, _)| k == "ANTHROPIC_BASE_URL").and_then(|(_, v)| route_named(v))
50}
51
52/// The address the turn's token is tied to, or why it can't be. On Linux that needs the listener on the agents network.
53fn address_plan(linux: bool, listener_up: bool, address: Option<&str>) -> Result<IpAddr, &'static str> {
54    if linux && !listener_up {
55        return Err(NO_PATH);
56    }
57    address.and_then(|a| a.trim().parse().ok()).ok_or(NO_ADDRESS)
58}
59
60/// Whose gateway token a turn is for, taken before the container is made ready: readying it can recreate the container,
61/// which ends the token the spawn made, and the turn's own token is made after.
62pub(crate) struct Claim {
63    agent: String,
64    def_id: String,
65    route: String,
66    account: String,
67}
68
69/// The agent, route and account of a turn on the gateway, or `None` for any other turn. A turn whose token is already gone
70/// is refused.
71pub(crate) fn claim(env: &[(String, String)]) -> Result<Option<Claim>, ContainerError> {
72    let Some(route) = gateway_route(env) else {
73        return Ok(None);
74    };
75    // A message queued during the agent's first turn was set up with the token that turn then replaced: it names the agent's
76    // current one while the agent still holds one.
77    let grant = env
78        .iter()
79        .find(|(k, _)| k == "ANTHROPIC_AUTH_TOKEN")
80        .and_then(|(_, t)| token::grant_for(t).or_else(|| token::current_grant_of_replaced(t)))
81        .filter(|g| g.route == route);
82    match grant {
83        Some(g) => Ok(Some(Claim { agent: g.agent, def_id: g.def_id, route: g.route, account: g.account })),
84        None => Err(ContainerError::KeyRoute(GONE.to_string())),
85    }
86}
87
88/// Makes the turn's gateway token current and tied to the container, in place in `env`; where there is no listener on the
89/// agents network, also points the container at the forwarder. Called once the container is up (the listener is bound by
90/// then) and before the exec starts.
91pub(crate) async fn bind(cm: &ContainerManager, container_name: &str, env: &mut [(String, String)], claim: &Claim) -> Result<(), ContainerError> {
92    let linux = cfg!(target_os = "linux");
93    // A fresh look at the container at every turn start, never one kept from when it was made.
94    let address = cm.agent_network_ip(container_name).await;
95    let forwarder = if linux { Ok(None) } else { gateway_fwd::ensure(cm, container_name, env).await.map(Some) };
96    tie(env, claim, linux, listener::url().is_some(), address.as_deref(), forwarder)
97}
98
99/// The part of [`bind`] that follows from what it found. `forwarder` is the forwarder's base URL where one is used.
100fn tie(env: &mut [(String, String)], claim: &Claim, linux: bool, listener_up: bool, address: Option<&str>, forwarder: Result<Option<String>, String>) -> Result<(), ContainerError> {
101    let refuse = |why: String| {
102        // The turn does not run, so nothing is to hold the token the spawn made for it.
103        token::revoke(&claim.def_id, &claim.route);
104        Err(ContainerError::KeyRoute(why))
105    };
106    let peer = match address_plan(linux, listener_up, address) {
107        Ok(peer) => peer,
108        Err(why) => return refuse(why.to_string()),
109    };
110    let forwarder = match forwarder {
111        Ok(url) => url,
112        Err(why) => return refuse(why),
113    };
114    if let Some(base) = forwarder {
115        point_at_forwarder(env, &base);
116    }
117    let fresh = token::renew_for_account(&claim.agent, &claim.def_id, &claim.route, &claim.account, Some(peer));
118    if let Some(slot) = env.iter_mut().find(|(k, _)| k == "ANTHROPIC_AUTH_TOKEN") {
119        slot.1 = fresh;
120    }
121    Ok(())
122}
123
124/// The gateway's base URL, on the forwarder's address instead of srv's.
125fn point_at_forwarder(env: &mut [(String, String)], forwarder: &str) {
126    if let Some((_, url)) = env.iter_mut().find(|(k, v)| k == "ANTHROPIC_BASE_URL" && v.contains(PATH_PREFIX)) {
127        if let Some(at) = url.find(PATH_PREFIX) {
128            *url = format!("{}{}", forwarder.trim_end_matches('/'), &url[at..]);
129        }
130    }
131}
132
133#[cfg(test)]
134mod tests {
135    use super::*;
136
137    fn env_for(route: &str) -> Vec<(String, String)> {
138        vec![
139            ("ANTHROPIC_BASE_URL".to_string(), format!("http://host.docker.internal:1{PATH_PREFIX}{route}")),
140            ("ANTHROPIC_AUTH_TOKEN".to_string(), "x".to_string()),
141        ]
142    }
143
144    fn at() -> String {
145        // Written with `_` so no dotted private address sits in the source.
146        "172_30_0_9".replace('_', ".")
147    }
148
149    #[test]
150    fn only_a_turn_pointed_at_the_gateway_is_one_and_it_names_its_route() {
151        assert_eq!(gateway_route(&env_for(KEY_ROUTE_ID)), Some(KEY_ROUTE_ID));
152        assert_eq!(gateway_route(&env_for("openrouter")), Some("openrouter"), "a model route's turn is tied to its container too");
153        assert_eq!(gateway_route(&[("ANTHROPIC_BASE_URL".to_string(), "https://api.anthropic.com".to_string())]), None);
154        assert_eq!(gateway_route(&[("ANTHROPIC_BASE_URL".to_string(), format!("http://h:1{PATH_PREFIX}")) ]), None, "no route named");
155        assert_eq!(gateway_route(&[]), None);
156        assert_eq!(route_named(&format!("http://h:1{PATH_PREFIX}anthropic/v1?x=1")), Some("anthropic"));
157    }
158
159    #[test]
160    fn the_token_is_tied_to_the_containers_address_and_on_linux_without_a_way_in_it_is_refused() {
161        let at = at();
162        let here: IpAddr = at.parse().unwrap();
163        assert_eq!(address_plan(true, true, Some(&at)), Ok(here));
164        assert_eq!(address_plan(true, true, Some(&format!(" {at}\n"))), Ok(here));
165        assert_eq!(address_plan(true, false, Some(&at)), Err(NO_PATH), "no listener on the agents network: no path, and nothing falls back");
166        assert_eq!(address_plan(true, true, None), Err(NO_ADDRESS));
167        assert_eq!(address_plan(true, true, Some("")), Err(NO_ADDRESS));
168        assert_eq!(address_plan(true, true, Some("not an address")), Err(NO_ADDRESS));
169    }
170
171    #[test]
172    fn elsewhere_the_token_is_tied_to_the_address_too_and_the_listener_is_not_needed() {
173        let at = at();
174        assert_eq!(address_plan(false, false, Some(&at)), Ok(at.parse().unwrap()));
175        assert_eq!(address_plan(false, false, None), Err(NO_ADDRESS), "an address is what the forwarder vouches for: without it, no token");
176        assert_eq!(address_plan(false, true, Some("not an address")), Err(NO_ADDRESS));
177    }
178
179    #[test]
180    fn the_refusals_say_what_to_do_and_name_no_key_or_account() {
181        for why in [NO_PATH, NO_ADDRESS, GONE] {
182            assert!(why.contains("agent"), "{why}");
183            assert!(!why.contains("amxg_") && !why.contains("sk-ant"), "{why}");
184        }
185        assert!(NO_PATH.contains("Run the agent on this machine") && NO_PATH.contains("plan account"));
186    }
187
188    #[test]
189    fn a_turn_not_on_the_gateway_has_no_claim_and_one_with_no_live_token_is_refused_with_a_plain_reason() {
190        assert!(claim(&[("ANTHROPIC_BASE_URL".to_string(), "https://api.anthropic.com".to_string())]).unwrap().is_none());
191        assert!(claim(&[]).unwrap().is_none());
192        let err = claim(&env_for(KEY_ROUTE_ID)).err().expect("no live token");
193        assert!(matches!(&err, ContainerError::KeyRoute(why) if why == GONE), "{err}");
194        let err = claim(&env_for("openrouter")).err().expect("no live token on a model route either");
195        assert!(matches!(&err, ContainerError::KeyRoute(why) if why == GONE), "{err}");
196    }
197
198    #[test]
199    fn a_message_queued_behind_the_first_turn_is_still_that_agents_when_the_turn_replaced_its_token() {
200        let here: IpAddr = at().parse().unwrap();
201        let queued_with = token::renew_for_account("kq-slug", "kq-def", KEY_ROUTE_ID, "kq-acct", None);
202        let mut env = env_for(KEY_ROUTE_ID);
203        env[1].1 = queued_with.clone();
204        // The running turn binds the token to the container's address, which replaces the one the message holds.
205        token::renew_for_account("kq-slug", "kq-def", KEY_ROUTE_ID, "kq-acct", Some(here));
206        assert_eq!(token::grant_for(&queued_with), None);
207        let taken = claim(&env).unwrap().expect("still a turn of that agent");
208        assert_eq!((taken.agent.as_str(), taken.def_id.as_str(), taken.account.as_str()), ("kq-slug", "kq-def", "kq-acct"));
209        // Once the agent's token ends (the container was stopped, or the agent left the key) the message is refused.
210        revoke_container_tokens("agentmux-kq-def");
211        assert!(matches!(claim(&env), Err(ContainerError::KeyRoute(why)) if why == GONE));
212    }
213
214    #[test]
215    fn a_stopped_container_ends_every_route_of_its_agent_not_only_the_key() {
216        let key = token::token_for_account("ev-slug", "ev-def", KEY_ROUTE_ID, "acct");
217        let model = token::token_for("ev-slug", "ev-def", "openrouter");
218        let other = token::token_for("ev-other", "ev-def-2", "openrouter");
219        revoke_container_tokens("agentmux-ev-def");
220        assert_eq!((token::grant_for(&key), token::grant_for(&model)), (None, None));
221        assert!(token::grant_for(&other).is_some(), "another agent's token stays");
222        token::revoke("ev-def-2", "openrouter");
223    }
224
225    /// What `tie` does with each way a turn can reach the gateway: the claim, taken before the container was readied, holds when
226    /// readying it ended the spawn's token.
227    #[test]
228    fn a_turn_gets_a_fresh_token_tied_to_its_container_or_the_way_out() {
229        let here: IpAddr = at().parse().unwrap();
230        for route in [KEY_ROUTE_ID, "openrouter"] {
231            let first = token::renew_for_account("kr-slug", "kr-def", route, "kr-acct", None);
232            let mut env = env_for(route);
233            env[1].1 = first.clone();
234            let taken = claim(&env).unwrap().expect("a gateway turn");
235            // The container is recreated while it is readied: that ends the token the spawn made.
236            revoke_container_tokens("agentmux-kr-def");
237            assert_eq!(token::grant_for(&first), None);
238            // Linux: the listener sees the address; the base URL stays.
239            tie(&mut env, &taken, true, true, Some(&at()), Ok(None)).unwrap();
240            let grant = token::grant_for(&env[1].1).unwrap();
241            assert_eq!((grant.agent.as_str(), grant.def_id.as_str(), grant.route.as_str(), grant.account.as_str(), grant.peer), ("kr-slug", "kr-def", route, "kr-acct", Some(here)));
242            assert!(env[0].1.starts_with("http://host.docker.internal:1"), "{}", env[0].1);
243            assert_ne!(env[1].1, first, "each turn has a token of its own");
244            token::revoke("kr-def", route);
245        }
246    }
247
248    #[test]
249    fn on_docker_desktop_the_turn_is_pointed_at_the_forwarder_and_with_none_it_is_refused_with_no_new_token() {
250        let here: IpAddr = at().parse().unwrap();
251        let first = token::renew_for_account("kf-slug", "kf-def", KEY_ROUTE_ID, "kf-acct", None);
252        let mut env = env_for(KEY_ROUTE_ID);
253        env[1].1 = first.clone();
254        let taken = claim(&env).unwrap().unwrap();
255        tie(&mut env, &taken, false, false, Some(&at()), Ok(Some("http://agentmux-gateway-fwd:4799".to_string()))).unwrap();
256        assert_eq!(env[0].1, format!("http://agentmux-gateway-fwd:4799{PATH_PREFIX}{KEY_ROUTE_ID}"));
257        assert_eq!(token::grant_for(&env[1].1).unwrap().peer, Some(here), "the token holds for one container's address");
258        // No forwarder: the turn is refused with the plain reason, the token ends and nothing falls back to srv's own address.
259        let mut down = env_for(KEY_ROUTE_ID);
260        down[1].1 = env[1].1.clone();
261        let current = env[1].1.clone();
262        let refused = tie(&mut down, &taken, false, false, Some(&at()), Err("the gateway forwarder is not running".to_string()));
263        assert!(matches!(&refused, Err(ContainerError::KeyRoute(why)) if why == "the gateway forwarder is not running"), "{refused:?}");
264        assert_eq!(down[0].1, env_for(KEY_ROUTE_ID)[0].1, "not pointed anywhere else");
265        assert_eq!(token::grant_for(&current), None, "the refused turn leaves no live token");
266        // No address either: refused.
267        let again = token::renew_for_account("kf-slug", "kf-def", KEY_ROUTE_ID, "kf-acct", None);
268        down[1].1 = again.clone();
269        assert!(matches!(tie(&mut down, &taken, false, false, None, Ok(Some("http://f:1".to_string()))), Err(ContainerError::KeyRoute(why)) if why == NO_ADDRESS));
270        assert_eq!(token::grant_for(&again), None);
271    }
272}