agentmux_srv_core/identity/aws_broker/
container.rs1use std::path::{Path, PathBuf};
14
15use super::policy::{self, Policy};
16
17pub const CONTAINER_AWS_DIR: &str = "/opt/agentmux/aws";
19const CONFIG_FILE: &str = "config";
20
21pub 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
32pub 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
46fn shared() -> Option<std::sync::Arc<Policy>> {
48 policy::current().ok().flatten().filter(|p| !p.grants.is_empty())
49}
50
51pub fn config_dir() -> Option<String> {
54 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
69pub 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 assert_eq!(config_dir(), None);
149 assert!(exec_env().is_empty());
150 }
151}