agentmux_srv_core/identity/aws_broker/
tools.rs1use std::path::{Path, PathBuf};
13use std::sync::atomic::{AtomicU64, Ordering};
14
15use super::policy;
16
17pub const CONTAINER_TOOLS_DIR: &str = "/opt/agentmux/tools";
19
20pub struct Tool {
22 pub command: &'static str,
23 pub package: &'static str,
24 pub script: &'static str,
25}
26
27pub const TOOLS: [Tool; 2] = [
28 Tool { command: "secrets", package: "@a5af/secrets", script: "bin/secrets.js" },
29 Tool { command: "deploy", package: "@a5af/deploy-cli", script: "dist/cli.js" },
30];
31
32const KEEP: [&str; 4] = ["package.json", "bin", "dist", "node_modules"];
34
35#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct Found {
38 pub command: &'static str,
39 pub version: String,
40 pub dir: PathBuf,
41}
42
43fn tool(command: &str) -> Option<&'static Tool> {
44 TOOLS.iter().find(|t| t.command == command)
45}
46
47fn is_plain_version(v: &str) -> bool {
49 !v.is_empty() && v.len() <= 32 && v.bytes().all(|b| b.is_ascii_alphanumeric() || b".-_+".contains(&b))
50}
51
52fn package_at(tool: &'static Tool, dir: &Path) -> Option<Found> {
54 let json: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(dir.join("package.json")).ok()?).ok()?;
55 let version = json.get("version")?.as_str()?.to_string();
56 (json.get("name")?.as_str()? == tool.package && is_plain_version(&version) && dir.join(tool.script).is_file())
57 .then(|| Found { command: tool.command, version, dir: dir.to_path_buf() })
58}
59
60pub fn find(command: &str, which: &dyn Fn(&str) -> Option<PathBuf>) -> Option<Found> {
63 let tool = tool(command)?;
64 let exe = which(command)?;
65 let beside = exe.parent().map(|d| d.join("node_modules").join(tool.package));
66 let through_link = std::fs::canonicalize(&exe).ok().map(|real| real.ancestors().skip(1).take(4).map(Path::to_path_buf).collect::<Vec<_>>());
67 through_link.into_iter().flatten().chain(beside).find_map(|dir| package_at(tool, &dir))
68}
69
70fn copy_tree(from: &Path, to: &Path) -> std::io::Result<()> {
71 std::fs::create_dir_all(to)?;
72 for entry in std::fs::read_dir(from)? {
73 let entry = entry?;
74 let kind = entry.file_type()?;
75 if kind.is_dir() {
77 copy_tree(&entry.path(), &to.join(entry.file_name()))?;
78 } else if kind.is_file() {
79 std::fs::copy(entry.path(), to.join(entry.file_name()))?;
80 }
81 }
82 Ok(())
83}
84
85fn copy_package(from: &Path, to: &Path) -> std::io::Result<()> {
86 std::fs::create_dir_all(to)?;
87 for entry in KEEP.iter().map(|e| (e, from.join(e))).filter(|(_, p)| p.exists()) {
88 if entry.1.is_dir() {
89 copy_tree(&entry.1, &to.join(entry.0))?;
90 } else {
91 std::fs::copy(&entry.1, to.join(entry.0))?;
92 }
93 }
94 Ok(())
95}
96
97static SEQ: AtomicU64 = AtomicU64::new(0);
98
99fn temp_name(stem: &str) -> String {
100 format!(".{stem}.{}.{}", std::process::id(), SEQ.fetch_add(1, Ordering::Relaxed))
101}
102
103pub fn write_replacing(file: &Path, text: &str, executable: bool) -> std::io::Result<()> {
106 if std::fs::read_to_string(file).ok().as_deref() == Some(text) {
107 return Ok(());
108 }
109 let temp = file.with_file_name(temp_name(&file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default()));
110 std::fs::write(&temp, text)?;
111 #[cfg(unix)]
112 {
113 use std::os::unix::fs::PermissionsExt;
114 std::fs::set_permissions(&temp, std::fs::Permissions::from_mode(if executable { 0o755 } else { 0o644 }))?;
115 }
116 #[cfg(not(unix))]
117 let _ = executable;
118 std::fs::rename(&temp, file).inspect_err(|_| {
119 let _ = std::fs::remove_file(&temp);
120 })
121}
122
123fn launcher(tool: &Tool, found: Option<&Found>) -> String {
124 match found {
125 Some(f) => format!(
126 "#!/bin/sh\n# Written by AgentMux; read-only. {} {} from this computer, run with the image's node.\nexec node {CONTAINER_TOOLS_DIR}/pkg/{}-{}/{} \"$@\"\n",
127 tool.package,
128 f.version,
129 tool.command,
130 f.version,
131 tool.script
132 ),
133 None => format!(
134 "#!/bin/sh\necho \"{} is not installed on the computer this container runs on, so this container has the AWS CLI only; a person installs it there (npm i -g {}) and the container picks it up.\" >&2\nexit 127\n",
135 tool.command, tool.package
136 ),
137 }
138}
139
140pub fn render_into(root: &Path, found: &[Found]) -> std::io::Result<PathBuf> {
143 let dir = root.join("container-tools");
144 let (bin, pkg) = (dir.join("bin"), dir.join("pkg"));
145 std::fs::create_dir_all(&bin)?;
146 std::fs::create_dir_all(&pkg)?;
147 for tool in &TOOLS {
148 let here = found.iter().find(|f| f.command == tool.command);
149 if let Some(f) = here {
150 let name = format!("{}-{}", f.command, f.version);
151 let published = pkg.join(&name);
152 if !published.join("package.json").is_file() {
153 let staging = pkg.join(temp_name(&name));
155 if let Err(e) = copy_package(&f.dir, &staging).and_then(|_| std::fs::rename(&staging, &published)) {
156 let _ = std::fs::remove_dir_all(&staging);
157 if !published.join("package.json").is_file() {
159 return Err(e);
160 }
161 }
162 }
163 let _ = std::fs::remove_file(published.join(SUPERSEDED));
165 }
166 write_replacing(&bin.join(tool.command), &launcher(tool, here), true)?;
168 prune(&pkg, tool.command, here.map(|f| format!("{}-{}", f.command, f.version)).as_deref(), UNUSED_FOR);
169 }
170 Ok(dir)
171}
172
173const SUPERSEDED: &str = ".superseded";
176const UNUSED_FOR: std::time::Duration = std::time::Duration::from_secs(24 * 3600);
178
179fn prune(pkg: &Path, command: &str, keep: Option<&str>, unused_for: std::time::Duration) {
182 let prefix = format!("{command}-");
183 for entry in std::fs::read_dir(pkg).into_iter().flatten().flatten() {
184 let name = entry.file_name().to_string_lossy().into_owned();
185 if !name.starts_with(&prefix) || Some(name.as_str()) == keep || !entry.path().join("package.json").is_file() {
186 continue;
187 }
188 let marker = entry.path().join(SUPERSEDED);
189 match std::fs::metadata(&marker).and_then(|m| m.modified()) {
190 Err(_) => {
191 let _ = std::fs::write(&marker, "");
192 }
193 Ok(since) if since.elapsed().is_ok_and(|age| age >= unused_for) => {
194 let _ = std::fs::remove_dir_all(entry.path());
195 }
196 Ok(_) => {}
197 }
198 }
199}
200
201pub fn config_dir_for(slug: &str) -> Option<String> {
204 if cfg!(any(test, feature = "test-support")) {
206 return None;
207 }
208 if !policy::current().ok().flatten().is_some_and(|p| !p.open_to(slug).is_empty()) {
209 return None;
210 }
211 let root = crate::srv_info::agentmux_root()?;
212 let which = |c: &str| which::which(c).ok();
213 let found: Vec<Found> = TOOLS.iter().filter_map(|t| find(t.command, &which)).collect();
214 match render_into(&root, &found) {
215 Ok(dir) => Some(dir.to_string_lossy().into_owned()),
216 Err(e) => {
217 tracing::warn!(target: "identity", error = %e, "identity.aws: the container's tools folder couldn't be written");
218 None
219 }
220 }
221}
222
223#[cfg(test)]
224#[path = "tools_tests.rs"]
225mod tests;