Skip to main content

agentmux_srv_core/identity/aws_broker/
container.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What a container agent is given so its AWS SDK and CLI find the broker (spec ยง4): a config file with one
5//! `credential_process` profile per grant, mounted read-only, and up to four environment variables. The file is the
6//! same for every agent (who may have which grant is srv's decision on each request, not the file's), so there is one
7//! folder, not one per agent: no agent name is ever a folder name.
8//!
9//! Nothing here is a security boundary (an agent can unset the variables or write its own config): srv decides on every
10//! request. The file is a convenience that makes `aws`, `cdk` and the SDKs ask the right place, and it holds names and
11//! one command, never a secret.
12
13use std::path::{Path, PathBuf};
14
15use super::policy::{self, Policy};
16
17/// Where the config folder is mounted, read-only, in the container.
18pub const CONTAINER_AWS_DIR: &str = "/opt/agentmux/aws";
19const CONFIG_FILE: &str = "config";
20
21/// Write the AWS config under `root` (`container-aws/config`) if it differs from what is there, and return the folder.
22/// A new file replaces the old one in one step, so a container reading the mount never sees half of it.
23pub fn render_into(root: &Path, policy: &Policy) -> std::io::Result<PathBuf> {
24    let dir = root.join("container-aws");
25    std::fs::create_dir_all(&dir)?;
26    let file = dir.join(CONFIG_FILE);
27    let text = policy.render_config();
28    super::tools::write_replacing(&file, &text, false)?;
29    Ok(dir)
30}
31
32/// The variables a container's exec gets when `policy` shares grants. `AWS_PROFILE` is the policy's default grant, so
33/// a bare `aws s3 ls` uses it; without one, a profile is named per command.
34pub fn env_for(policy: &Policy) -> Vec<(String, String)> {
35    let mut env = vec![
36        ("AWS_CONFIG_FILE".to_string(), format!("{CONTAINER_AWS_DIR}/{CONFIG_FILE}")),
37        ("AWS_SHARED_CREDENTIALS_FILE".to_string(), "/dev/null".to_string()),
38        ("AWS_EC2_METADATA_DISABLED".to_string(), "true".to_string()),
39    ];
40    if let Some(default) = &policy.default_grant {
41        env.push(("AWS_PROFILE".to_string(), default.clone()));
42    }
43    env
44}
45
46/// The policy now in force, if it shares anything.
47fn shared() -> Option<std::sync::Arc<Policy>> {
48    policy::current().ok().flatten().filter(|p| !p.grants.is_empty())
49}
50
51/// The host folder to mount, with the config freshly written, or `None` when this host shares no AWS (or the folder
52/// can't be written: the container then has no AWS, as before).
53pub fn config_dir() -> Option<String> {
54    // The machine running the tests has its own answer; the tests give theirs.
55    if cfg!(any(test, feature = "test-support")) {
56        return None;
57    }
58    let policy = shared()?;
59    let root = crate::srv_info::agentmux_root()?;
60    match render_into(&root, &policy) {
61        Ok(dir) => Some(dir.to_string_lossy().into_owned()),
62        Err(e) => {
63            tracing::warn!(target: "identity", error = %e, "identity.aws: the container's AWS config couldn't be written");
64            None
65        }
66    }
67}
68
69/// The variables to add to a container exec's environment: none when nothing is shared, and none when the config
70/// folder can't be written, so they never point the SDK at a file the container doesn't have.
71pub fn exec_env() -> Vec<(String, String)> {
72    if cfg!(any(test, feature = "test-support")) {
73        return Vec::new();
74    }
75    match (shared(), config_dir()) {
76        (Some(policy), Some(_)) => env_for(&policy),
77        _ => Vec::new(),
78    }
79}
80
81#[cfg(test)]
82mod tests {
83    use super::*;
84
85    const POLICY: &str = r#"{ "version": 1, "default_grant": "read", "grants": {
86        "read": { "tier": "read", "mint": { "kind": "host_profile", "profile": "work" }, "agents": ["*"] },
87        "deploy": { "tier": "write", "mint": { "kind": "command", "argv": ["/opt/escalate"] }, "agents": ["jcont"] } } }"#;
88
89    #[test]
90    fn the_config_is_written_in_one_folder_for_every_agent() {
91        let root = tempfile::tempdir().unwrap();
92        let policy = Policy::parse(POLICY).unwrap();
93        let dir = render_into(root.path(), &policy).unwrap();
94        assert_eq!(dir, root.path().join("container-aws"));
95        let text = std::fs::read_to_string(dir.join("config")).unwrap();
96        assert!(text.contains("[default]") && text.contains("[profile deploy]") && !text.contains("/opt/escalate") && !text.contains("work"), "{text}");
97    }
98
99    #[test]
100    fn a_changed_policy_rewrites_the_file_and_an_unchanged_one_leaves_it_alone() {
101        let root = tempfile::tempdir().unwrap();
102        let policy = Policy::parse(POLICY).unwrap();
103        let dir = render_into(root.path(), &policy).unwrap();
104        let file = dir.join("config");
105        let first = std::fs::metadata(&file).unwrap().modified().unwrap();
106        render_into(root.path(), &policy).unwrap();
107        assert_eq!(std::fs::metadata(&file).unwrap().modified().unwrap(), first, "same text, not written again");
108        let moved = Policy::parse(&POLICY.replace(r#""default_grant": "read","#, r#""default_grant": "read", "region": "eu-west-1","#)).unwrap();
109        render_into(root.path(), &moved).unwrap();
110        assert!(std::fs::read_to_string(&file).unwrap().contains("region = eu-west-1"), "a changed policy is written");
111        assert!(std::fs::read_dir(&dir).unwrap().all(|e| !e.unwrap().file_name().to_string_lossy().starts_with('.')), "no temp file is left");
112    }
113
114    #[test]
115    fn execs_rendering_at_once_never_publish_half_a_file_or_fail() {
116        let root = tempfile::tempdir().unwrap();
117        let policy = Policy::parse(POLICY).unwrap();
118        let want = policy.render_config();
119        std::thread::scope(|s| {
120            for _ in 0..8 {
121                s.spawn(|| {
122                    for _ in 0..20 {
123                        let dir = render_into(root.path(), &policy).expect("a concurrent render must not fail");
124                        assert_eq!(std::fs::read_to_string(dir.join("config")).unwrap(), want);
125                    }
126                });
127            }
128        });
129        let leftovers: Vec<_> = std::fs::read_dir(root.path().join("container-aws")).unwrap().flatten().map(|e| e.file_name()).collect();
130        assert_eq!(leftovers.len(), 1, "no temp file is left behind: {leftovers:?}");
131    }
132
133    #[test]
134    fn the_four_variables_point_the_sdk_at_the_mounted_config_and_nothing_else() {
135        let env: std::collections::HashMap<_, _> = env_for(&Policy::parse(POLICY).unwrap()).into_iter().collect();
136        assert_eq!(env["AWS_CONFIG_FILE"], "/opt/agentmux/aws/config");
137        assert_eq!(env["AWS_SHARED_CREDENTIALS_FILE"], "/dev/null");
138        assert_eq!(env["AWS_EC2_METADATA_DISABLED"], "true");
139        assert_eq!(env["AWS_PROFILE"], "read");
140        assert_eq!(env.len(), 4);
141        let no_default = Policy::parse(r#"{ "version": 1, "grants": { "x": { "tier": "read", "mint": { "kind": "host_profile", "profile": "p" } } } }"#).unwrap();
142        assert!(!env_for(&no_default).iter().any(|(k, _)| k == "AWS_PROFILE"), "no default grant, no AWS_PROFILE");
143    }
144
145    #[test]
146    fn under_test_nothing_is_asked_of_the_host() {
147        // The machine running the tests has its own policy, which is not asked: no folder, no variables.
148        assert_eq!(config_dir(), None);
149        assert!(exec_env().is_empty());
150    }
151}