Skip to main content

agentmux_srv_core/identity/aws_broker/
tools.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The host's private CLIs (`secrets`, `deploy`) for a container agent that has AWS grants.
5//!
6//! They are private packages (GitHub Packages), so they can't be in the public image and no registry token ever
7//! enters a container. Instead srv copies the host's installed packages into one folder under the AgentMux root and
8//! mounts it read-only at [`CONTAINER_TOOLS_DIR`]; two small `sh` launchers in `bin/` (on the image's `PATH`) run them
9//! with the image's own `node`. A host that doesn't have a CLI installed gets a launcher that says so in one sentence,
10//! so the container then has the AWS CLI only. Spec: docs/specs/SPEC_CONTAINER_AGENT_AWS_CREDENTIALS_2026_10_31.md.
11
12use std::path::{Path, PathBuf};
13use std::sync::atomic::{AtomicU64, Ordering};
14
15use super::policy;
16
17/// Where the folder is mounted, read-only, in the container. Its `bin/` is on the image's `PATH`.
18pub const CONTAINER_TOOLS_DIR: &str = "/opt/agentmux/tools";
19
20/// One private CLI: the command the agent types, its npm package, and the script (inside the package) that runs it.
21pub 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
32/// What of a package the container runs; the rest (docs, examples) stays on the host.
33const KEEP: [&str; 4] = ["package.json", "bin", "dist", "node_modules"];
34
35/// An installed package on the host.
36#[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
47/// A version that is safe in a folder name and a shell word.
48fn 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
52/// The package folder at `dir` if its `package.json` names `tool`'s package and the script is there.
53fn 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
60/// Find the host's install of `command`'s package, from where `which` puts the command: on Unix the command is a link
61/// into `<prefix>/lib/node_modules/<package>`, on Windows a `.cmd` beside `node_modules\<package>`. No program is run.
62pub 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        // Links are not followed: a package that links outside itself gets nothing there.
76        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
103/// Replace `file` with `text` in one step (a container reading the mount never sees half of it), unless it already
104/// says that. `executable` sets the mode on Unix hosts; Docker shows a Windows host's files as executable.
105pub 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
140/// Put the tools folder under `root` (`container-tools/`) in order and return it: each found package copied once (a
141/// new version gets its own folder, so a running command keeps the files it started from), and a launcher per tool.
142pub 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                // Copied beside it and renamed in, so the folder is there whole or not at all.
154                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                    // Another srv instance may have published the same folder first.
158                    if !published.join("package.json").is_file() {
159                        return Err(e);
160                    }
161                }
162            }
163            // In use again (a rollback): its clock stops.
164            let _ = std::fs::remove_file(published.join(SUPERSEDED));
165        }
166        // The launcher moves to the new version first; only then does an old one start its day.
167        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
173/// Written into a version's folder when the launcher stops pointing at it; its age is how long the folder has been
174/// unused.
175const SUPERSEDED: &str = ".superseded";
176/// How long a version nothing points at stays, so a command still running from it is never pulled out from under it.
177const UNUSED_FOR: std::time::Duration = std::time::Duration::from_secs(24 * 3600);
178
179/// Start the clock on `command`'s folders that the launcher no longer points at (all of them, when `keep` is none), and
180/// remove the ones whose clock has run for `unused_for`.
181fn 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
201/// The host folder to mount for the agent `slug`, freshly put in order, or `None`: this host shares no AWS with that
202/// agent, or the folder can't be written (the container then has no tools folder, as before).
203pub fn config_dir_for(slug: &str) -> Option<String> {
204    // The machine running the tests has its own answer; the tests give theirs.
205    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;