Skip to main content

agentmux_srv_core/backend/container/
credential.rs

1//! A scoped credential for container agents, in place of the instance auth key.
2//!
3//! A container agent is meant to see only its `/workspace` mount, but the
4//! instance key (`AGENTMUX_AUTH_KEY`) reaches every route srv serves: host
5//! shell creation, `stream-local-file`, editor reads, attachment ingest by
6//! path. Its `docker exec` env therefore carries a token minted here instead,
7//! which srv accepts only on [`container_route_allowed`] and attributes to the
8//! agent it was minted for.
9
10use sha2::{Digest, Sha256};
11use std::collections::HashMap;
12use std::sync::{Mutex, OnceLock};
13
14/// Prefix that marks a container token in logs and bug reports.
15pub const TOKEN_PREFIX: &str = "amxc_";
16
17/// What a container token was minted for.
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct ContainerGrant {
20    pub block_id: String,
21    /// The agent's own `AGENTMUX_AGENT_TOKEN` when the token was last handed
22    /// out. `caller_middleware` attributes every request to it, ignoring any
23    /// `X-Agent-Token` header the container sends.
24    pub agent_token: Option<String>,
25}
26
27#[derive(Default)]
28struct Registry {
29    by_digest: HashMap<[u8; 32], ContainerGrant>,
30    by_block: HashMap<String, String>,
31}
32
33fn registry() -> &'static Mutex<Registry> {
34    static REGISTRY: OnceLock<Mutex<Registry>> = OnceLock::new();
35    REGISTRY.get_or_init(Default::default)
36}
37
38// Looked up by digest so a lookup's timing depends on the digest, not on how
39// much of a guessed token matches a real one.
40fn digest(token: &str) -> [u8; 32] {
41    Sha256::digest(token.as_bytes()).into()
42}
43
44fn mint() -> String {
45    let token = format!(
46        "{TOKEN_PREFIX}{}{}",
47        uuid::Uuid::new_v4().simple(),
48        uuid::Uuid::new_v4().simple()
49    );
50    token
51}
52
53/// Who holds a block's token in the transcript withhold registry: dropped with the token ([`revoke_block`]).
54fn withhold_owner(block_id: &str) -> String {
55    format!("container-token:{block_id}")
56}
57
58/// The block's container token: minted on first use, reused on later turns,
59/// with the grant's identity refreshed from this turn's env.
60pub fn token_for_block(block_id: &str, agent_token: Option<&str>) -> String {
61    let mut reg = registry().lock().unwrap();
62    let token = reg.by_block.get(block_id).cloned().unwrap_or_else(mint);
63    // A token an agent's process holds is never written into a transcript, for as long as it works.
64    crate::backend::transcript::withhold::hold(&withhold_owner(block_id), &token, None);
65    reg.by_block.insert(block_id.to_string(), token.clone());
66    reg.by_digest.insert(
67        digest(&token),
68        ContainerGrant {
69            block_id: block_id.to_string(),
70            agent_token: agent_token.map(str::trim).filter(|t| !t.is_empty()).map(str::to_string),
71        },
72    );
73    token
74}
75
76pub fn grant_for(token: &str) -> Option<ContainerGrant> {
77    if !token.starts_with(TOKEN_PREFIX) {
78        return None;
79    }
80    registry().lock().unwrap().by_digest.get(&digest(token)).cloned()
81}
82
83/// Invalidate the block's token; its container can no longer reach srv.
84pub fn revoke_block(block_id: &str) {
85    let mut reg = registry().lock().unwrap();
86    if let Some(token) = reg.by_block.remove(block_id) {
87        reg.by_digest.remove(&digest(&token));
88    }
89    crate::backend::transcript::withhold::release(&withhold_owner(block_id));
90}
91
92/// Whether a container agent may call `path`. A route srv serves (`served`) is open to it unless its audience
93/// ([`crate::backend::route_audience`]) refuses it, with a reason each: commands on the host, the host's
94/// files outside its mounts, the app's own plumbing. A path under srv's route namespaces that is neither served
95/// nor named there is refused too. Matched on the raw path, exactly as the router matches it.
96pub fn container_route_allowed(path: &str, served: crate::backend::route_audience::Served) -> bool {
97    crate::backend::container::routes::refusal(path, served).is_none()
98}
99
100/// The routes a container token has always been accepted on. They work for a grant that carries no
101/// agent identity (they bind to the grant's own block, or to nobody in particular).
102fn accepted_without_identity(path: &str) -> bool {
103    const EXACT: &[&str] = &[
104        "/agentmux/reactive/inject",
105        "/agentmux/reactive/agent",
106        "/agentmux/reactive/agent-names",
107        "/agentmux/discovery",
108        "/agentmux/work",
109        "/agentmux/work/claim",
110        "/api/v1/self",
111        "/api/v1/agent/self/quit",
112        "/api/v1/agent/pane/close",
113        "/api/v1/agent/tool-chunk",
114        "/api/v1/agent/compaction-started",
115    ];
116    let is_id = |s: &str| !s.is_empty() && s.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_');
117    EXACT.contains(&path)
118        || path == "/"
119        || path == "/health"
120        || ["/docsite/", "/schema/", "/agentmux/widget-sdk/"].iter().any(|p| path.starts_with(p))
121        || path.strip_prefix("/agentmux/work/").is_some_and(|rest| match rest.split('/').collect::<Vec<_>>().as_slice() {
122            [id] => is_id(id),
123            [id, "heartbeat" | "complete" | "release" | "update" | "ask" | "submit"] => is_id(id),
124            _ => false,
125        })
126        || path.strip_prefix("/api/v1/agent/shutdown/").is_some_and(is_id)
127}
128
129/// Routes that act on the calling agent's own data, and so are refused to a
130/// container token that carries no agent identity rather than falling back to
131/// an agent named in the request body. Every route a container has been given since the
132/// denylist (`routes`) opened them all does: a handler that takes the agent from
133/// the caller serves it, one that takes it from the body does not. The memory routes always
134/// did, the session-start delivery included.
135pub fn route_needs_identity(path: &str) -> bool {
136    path.starts_with("/api/v1/agent/memory/") || !accepted_without_identity(path)
137}
138
139/// File watchers poll where the workspace is a file-sharing mount that sends no change events:
140/// Docker Desktop on Windows and macOS (a 9p or virtiofs share). On Linux a bind mount reports changes
141/// and polling would only cost CPU. What the agent's own environment already sets is left alone.
142pub(crate) fn watcher_polling_env(shared_mount: bool, set: &[(String, String)]) -> Vec<(String, String)> {
143    if !shared_mount {
144        return Vec::new();
145    }
146    [("CHOKIDAR_USEPOLLING", "1"), ("CHOKIDAR_INTERVAL", "300"), ("WATCHPACK_POLLING", "true")]
147        .into_iter()
148        .filter(|(k, _)| !set.iter().any(|(have, _)| have == k))
149        .map(|(k, v)| (k.to_string(), v.to_string()))
150        .collect()
151}
152
153/// A container turn's `docker exec` env: host-only names left out (`agent_env_scope`), and
154/// the instance key replaced by this block's container token.
155pub fn container_exec_env(block_id: &str, env_vars: &HashMap<String, String>) -> Vec<(String, String)> {
156    let agent_token = env_vars.get("AGENTMUX_AGENT_TOKEN").map(String::as_str);
157    // The publish guard's hooks directory is a host path; the agent's other
158    // GIT_CONFIG_* settings still apply inside the container.
159    let env_vars = crate::backend::publish_guard::without_hooks_path(env_vars);
160    // A host agent's git setup is for the host; a container gets its own where tokens can be given
161    // (`github_tokens::container_git_hooks`), with the hooks where the image finds them.
162    let mut env_vars = crate::identity::github_tokens::without_agent_git(&env_vars);
163    if crate::identity::github_tokens::container_git_hooks().is_some() {
164        crate::identity::github_tokens::apply_container_git(&mut env_vars);
165    }
166    let build_info = crate::backend::pane_env::build_info();
167    let is_build_info = |k: &str| build_info.iter().any(|(b, _)| *b == k);
168    let mut out: Vec<(String, String)> = env_vars
169        .iter()
170        .filter(|(k, _)| !crate::backend::agent_env_scope::host_only(k))
171        .filter(|(k, _)| !is_build_info(k))
172        .map(|(k, v)| {
173            if k == "AGENTMUX_AUTH_KEY" {
174                (k.clone(), token_for_block(block_id, agent_token))
175            } else {
176                (k.clone(), v.clone())
177            }
178        })
179        .collect();
180    // Which AgentMux this is, as every host pane is told: a container exec
181    // doesn't go through `pane_env`'s sanitizers, and srv's values win over
182    // any the agent's own env carried.
183    out.extend(build_info.iter().map(|(k, v)| (k.to_string(), v.clone())));
184    // A hint for the client only: the in-container MCP doesn't ask srv for signing keys it is refused. srv
185    // never trusts this variable for anything (it comes from the container's own environment).
186    out.push(("AGENTMUX_IN_CONTAINER".to_string(), "1".to_string()));
187    out.extend(watcher_polling_env(cfg!(any(windows, target_os = "macos")), &out));
188    // The AWS SDK and CLI ask srv for credentials through the mounted config, where the host shares AWS with
189    // container agents (`identity::aws_broker`). Its variables replace any of the same names the agent's own
190    // environment carried; the rest of the agent's `AWS_*` is its own business.
191    let aws = crate::identity::aws_broker::container::exec_env();
192    out.retain(|(k, _)| !aws.iter().any(|(a, _)| a == k));
193    out.extend(aws);
194    // On Linux a container cannot reach srv's loopback; when srv listens on the agents network's
195    // gateway that is where the container is pointed.
196    crate::backend::container::listener::point_env_at_listener(&mut out);
197    point_gateway_at_srv(&mut out);
198    // What this machine has for the container's pre-push hook to ask, said only here (see [`publish_guard_marker`]).
199    // An AgentMux that predates the check sets none, which the hook says out loud.
200    out.retain(|(k, _)| k != crate::identity::gh_agent_token::PUBLISH_GUARD_ENV);
201    let installed = crate::identity::gh_agent_token::installed().is_some();
202    let marker = publish_guard_marker(installed, installed && crate::backend::publish_guard::container_scan_ready());
203    out.push((crate::identity::gh_agent_token::PUBLISH_GUARD_ENV.to_string(), marker.to_string()));
204    out
205}
206
207/// The marker's value: `1` where gh-agent's own hooks can judge a container's push (the hook asks srv),
208/// `older-gh-agent` where gh-agent is installed but cannot (the hook refuses a push to a GitHub repository and
209/// says how to fix the host), `0` where there is no gh-agent (the hook does nothing and says nothing, and never refuses a push for want
210/// of an answer).
211fn publish_guard_marker(gh_agent_installed: bool, can_judge: bool) -> &'static str {
212    match (gh_agent_installed, can_judge) {
213        (false, _) => "0",
214        (true, true) => "1",
215        (true, false) => "older-gh-agent",
216    }
217}
218
219/// A model-route agent's `ANTHROPIC_BASE_URL` names srv's gateway at the host's address; in a container it
220/// names the address `AGENTMUX_LOCAL_URL` now holds, which the container can reach.
221pub(crate) fn point_gateway_at_srv(env: &mut [(String, String)]) {
222    let prefix = crate::backend::model_gateway::PATH_PREFIX;
223    let Some(local) = env.iter().find(|(k, _)| k == "AGENTMUX_LOCAL_URL").map(|(_, v)| v.trim_end_matches('/').to_string()) else { return };
224    if let Some((_, url)) = env.iter_mut().find(|(k, v)| k == "ANTHROPIC_BASE_URL" && v.contains(prefix)) {
225        if let Some(at) = url.find(prefix) {
226            *url = format!("{local}{}", &url[at..]);
227        }
228    }
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    #[test]
236    fn tokens_are_reused_per_block_and_revocable() {
237        let a = token_for_block("cc-block-a", Some("tok-a"));
238        assert!(a.starts_with(TOKEN_PREFIX));
239        assert_eq!(token_for_block("cc-block-a", Some("tok-a2")), a);
240        assert_ne!(token_for_block("cc-block-b", None), a);
241        let grant = grant_for(&a).unwrap();
242        assert_eq!(grant.block_id, "cc-block-a");
243        assert_eq!(grant.agent_token.as_deref(), Some("tok-a2"));
244        revoke_block("cc-block-a");
245        assert_eq!(grant_for(&a), None);
246        assert_ne!(token_for_block("cc-block-a", None), a);
247    }
248
249    #[test]
250    fn unknown_and_unprefixed_tokens_have_no_grant() {
251        assert_eq!(grant_for("amxc_not-a-real-token"), None);
252        assert_eq!(grant_for("0b8e0c52-1b4e-4d3f-9a53-8a0c1d2e3f40"), None);
253        assert_eq!(grant_for(""), None);
254    }
255
256    #[test]
257    fn blank_agent_token_counts_as_none() {
258        let t = token_for_block("cc-block-blank", Some("  "));
259        assert_eq!(grant_for(&t).unwrap().agent_token, None);
260    }
261
262    #[test]
263    fn a_container_agent_has_the_routes_a_native_agent_has_except_the_hosts() {
264        for ok in [
265            "/agentmux/reactive/inject",
266            "/agentmux/discovery",
267            "/agentmux/work",
268            "/agentmux/work/claim",
269            "/agentmux/work/7f3a/heartbeat",
270            "/api/v1/self",
271            "/api/v1/agent/memory/write",
272            "/api/v1/agent/globalmemory/read",
273            "/api/v1/agent/pane/close",
274            "/api/v1/agent/shutdown/req-12",
275            "/api/v1/agent/tool-chunk",
276            "/api/v1/agent/dev_server/register",
277            "/api/v1/work-facts/who",
278            "/api/v1/vault",
279            "/api/v1/ui/browser/open",
280            "/api/v1/ui/browser/set_files",
281            "/api/v1/ui/screenshot",
282            "/api/v1/ui/shortcuts/list",
283            "/agentmux/cron",
284            "/api/v1/agent/open",
285            "/api/v1/attachments/upload",
286            "/api/v1/pane/open",
287            "/api/v1/widgets/install",
288        ] {
289            assert!(container_route_allowed(ok, |_| true), "{ok} should be allowed");
290        }
291        for denied in [
292            "/api/v1/shell/create",
293            "/api/v1/ptyshell/create",
294            "/agentmux/stream-local-file",
295            "/agentmux/service",
296            "/ws",
297            "/api/v1/host/browser_bypass",
298            "/api/v1/agent/desktop/authorize",
299            "/api/v1/agent/globalmemory/write",
300            "/api/v1/agent/globalmemory/remove",
301            "/api/v1/agent/globalmemory/reach",
302            "/agentmux/wps/publish",
303            "/agentmux/jobs/stop-run",
304            "/agentmux/agents/self/keys",
305            "/api/v1/agent/self/mcp-beat",
306        ] {
307            assert!(!container_route_allowed(denied, |_| true), "{denied} should be refused");
308        }
309    }
310
311    #[test]
312    fn only_the_routes_a_container_always_had_work_without_an_identity() {
313        for old in ["/agentmux/reactive/inject", "/agentmux/work/claim", "/agentmux/work/7f3a/ask", "/api/v1/self", "/api/v1/agent/tool-chunk", "/api/v1/agent/compaction-started", "/health"] {
314            assert!(!route_needs_identity(old), "{old}");
315        }
316        for new in ["/api/v1/agent/memory/session-start/part", "/api/v1/agent/memory/write", "/api/v1/agent/dev_server/register", "/api/v1/github/token", "/api/v1/github/push-scan", "/api/v1/vault", "/api/v1/ui/browser/open", "/api/v1/ui/screenshot", "/agentmux/cron", "/api/v1/agent/open", "/agentmux/work/7f3a/hold"] {
317            assert!(route_needs_identity(new), "{new}");
318        }
319    }
320
321    #[test]
322    fn file_watchers_poll_only_where_the_workspace_is_a_file_sharing_mount() {
323        assert!(watcher_polling_env(false, &[]).is_empty(), "a Linux bind mount reports changes");
324        let on = watcher_polling_env(true, &[]);
325        let get = |k: &str| on.iter().find(|(n, _)| n == k).map(|(_, v)| v.as_str());
326        assert_eq!((get("CHOKIDAR_USEPOLLING"), get("CHOKIDAR_INTERVAL"), get("WATCHPACK_POLLING")), (Some("1"), Some("300"), Some("true")));
327        // The agent's own choice wins.
328        let own = watcher_polling_env(true, &[("CHOKIDAR_USEPOLLING".into(), "0".into())]);
329        assert!(own.iter().all(|(k, _)| k != "CHOKIDAR_USEPOLLING") && own.len() == 2);
330    }
331
332    #[test]
333    fn exec_env_swaps_the_instance_key_for_the_container_token() {
334        let env: HashMap<String, String> = [
335            ("AGENTMUX_AUTH_KEY", "instance-key-value"),
336            ("AGENTMUX_AGENT_TOKEN", "agent-tok"),
337            ("AGENTMUX_LOCAL_URL", "http://host.docker.internal:1"),
338            ("HOME", "/host/home"),
339        ]
340        .into_iter()
341        .map(|(k, v)| (k.to_string(), v.to_string()))
342        .collect();
343        let out: HashMap<_, _> = container_exec_env("cc-block-env", &env).into_iter().collect();
344        let token = &out["AGENTMUX_AUTH_KEY"];
345        assert!(token.starts_with(TOKEN_PREFIX));
346        assert!(!out.values().any(|v| v == "instance-key-value"));
347        assert_eq!(grant_for(token).unwrap().agent_token.as_deref(), Some("agent-tok"));
348        assert_eq!(out["AGENTMUX_LOCAL_URL"], "http://host.docker.internal:1");
349        assert!(!out.contains_key("HOME"), "a host-only name is left out");
350        assert_eq!(out["AGENTMUX_IN_CONTAINER"], "1", "the hint the in-container MCP reads");
351        assert!(
352            !out.keys().any(|k| k.ends_with("_JEKT_KEY") || k.ends_with("_LAN_KEY") || k.ends_with("_WAN_KEY")),
353            "and no signing key"
354        );
355    }
356
357    #[test]
358    fn a_model_route_agents_gateway_address_is_one_the_container_can_reach() {
359        let env: HashMap<String, String> = [
360            ("AGENTMUX_LOCAL_URL", "http://host.docker.internal:7"),
361            ("ANTHROPIC_BASE_URL", "http://127.0.0.1:7/api/v1/model/openrouter"),
362        ]
363        .into_iter()
364        .map(|(k, v)| (k.to_string(), v.to_string()))
365        .collect();
366        let out: HashMap<_, _> = container_exec_env("cc-block-route", &env).into_iter().collect();
367        assert_eq!(out["ANTHROPIC_BASE_URL"], "http://host.docker.internal:7/api/v1/model/openrouter");
368        let own: HashMap<String, String> = [("ANTHROPIC_BASE_URL".to_string(), "https://proxy.example/anthropic".to_string())].into_iter().collect();
369        let own: HashMap<_, _> = container_exec_env("cc-block-own", &own).into_iter().collect();
370        assert_eq!(own["ANTHROPIC_BASE_URL"], "https://proxy.example/anthropic", "an address that is not the gateway is left alone");
371    }
372
373    #[test]
374    fn the_publish_guard_marker_is_srvs_to_say_once_and_is_one_only_where_the_guard_can_judge() {
375        let ask = |own: &str| {
376            let env: HashMap<String, String> = [("AGENTMUX_PUBLISH_GUARD".to_string(), own.to_string())].into_iter().collect();
377            container_exec_env("cc-block-guard", &env).into_iter().filter(|(k, _)| k == "AGENTMUX_PUBLISH_GUARD").map(|(_, v)| v).collect::<Vec<_>>()
378        };
379        let installed = crate::identity::gh_agent_token::installed().is_some();
380        let want = vec![publish_guard_marker(installed, installed && crate::backend::publish_guard::container_scan_ready()).to_string()];
381        assert_eq!(ask("1"), want, "once, and not carried in from the agent's own environment");
382        assert_eq!(ask("0"), want);
383    }
384
385    #[test]
386    fn the_marker_says_which_of_three_a_machine_is() {
387        assert_eq!(publish_guard_marker(false, false), "0", "no gh-agent: nothing to ask");
388        assert_eq!(publish_guard_marker(true, true), "1", "gh-agent that can judge a push");
389        assert_eq!(publish_guard_marker(true, false), "older-gh-agent", "gh-agent that cannot: said out loud, not silent");
390    }
391
392    #[test]
393    fn exec_env_without_a_key_gets_no_token() {
394        let env: HashMap<String, String> = [("FOO".to_string(), "bar".to_string())].into_iter().collect();
395        let out = container_exec_env("cc-block-nokey", &env);
396        assert!(out.iter().all(|(k, _)| k != "AGENTMUX_AUTH_KEY"));
397    }
398
399    #[test]
400    fn a_container_agent_is_told_which_build_it_runs_in() {
401        let env: HashMap<String, String> = [("AGENTMUX_VERSION".to_string(), "0.0.1-stale".to_string())].into_iter().collect();
402        let out = container_exec_env("cc-block-build", &env);
403        let versions: Vec<&str> = out.iter().filter(|(k, _)| k == "AGENTMUX_VERSION").map(|(_, v)| v.as_str()).collect();
404        assert_eq!(versions, [env!("CARGO_PKG_VERSION")], "srv's value, once, over the agent's own");
405        assert!(out.iter().any(|(k, _)| k == "AGENTMUX_BUILD"));
406    }
407}