1use sha2::{Digest, Sha256};
11use std::collections::HashMap;
12use std::sync::{Mutex, OnceLock};
13
14pub const TOKEN_PREFIX: &str = "amxc_";
16
17#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct ContainerGrant {
20 pub block_id: String,
21 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
38fn 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
53fn withhold_owner(block_id: &str) -> String {
55 format!("container-token:{block_id}")
56}
57
58pub 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 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
83pub 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
92pub 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
100fn 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
129pub fn route_needs_identity(path: &str) -> bool {
136 path.starts_with("/api/v1/agent/memory/") || !accepted_without_identity(path)
137}
138
139pub(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
153pub 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 let env_vars = crate::backend::publish_guard::without_hooks_path(env_vars);
160 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 out.extend(build_info.iter().map(|(k, v)| (k.to_string(), v.clone())));
184 out.push(("AGENTMUX_IN_CONTAINER".to_string(), "1".to_string()));
187 out.extend(watcher_polling_env(cfg!(any(windows, target_os = "macos")), &out));
188 let aws = crate::identity::aws_broker::container::exec_env();
192 out.retain(|(k, _)| !aws.iter().any(|(a, _)| a == k));
193 out.extend(aws);
194 crate::backend::container::listener::point_env_at_listener(&mut out);
197 point_gateway_at_srv(&mut out);
198 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
207fn 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
219pub(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 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}