Skip to main content

agentmux_srv_core/identity/aws_broker/
mint.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Getting credentials on the host for a grant (spec §7). srv never runs a shell: a recipe is an argument vector, a
5//! placeholder is substituted whole into one argument, and the program's output is parsed and dropped.
6
7use std::future::Future;
8use std::path::PathBuf;
9use std::time::Duration;
10
11use agentmux_common::win32::NoWindow;
12use chrono::{DateTime, Utc};
13use serde::Deserialize;
14use zeroize::Zeroizing;
15
16use super::policy::{Grant, Mint};
17
18/// How long a recipe may take: a cached login is instant, a fresh one is a round trip or two, and a slow one on a
19/// busy machine has been seen to take 20 to 26 seconds, so the limit is well past that (a recipe that is stopped part
20/// way leaves nothing behind, and the next ask starts it over). It stays under the container's own wait
21/// (`ASK_TIMEOUT` in `crates/bashwrap/src/aws.rs`), so the container is always answered, with the credentials or with
22/// the reason they were not.
23pub const RECIPE_TIMEOUT: Duration = Duration::from_secs(50);
24/// What of a recipe's stderr reaches the person.
25const STDERR_KEPT: usize = 400;
26/// AWS accepts only these in a session tag, and at most 256 characters.
27const REASON_MAX: usize = 256;
28
29/// Credentials as `credential_process` prints them. The secret and the token are zeroed when dropped.
30#[derive(Clone)]
31pub struct Minted {
32    pub access_key_id: Zeroizing<String>,
33    pub secret_access_key: Zeroizing<String>,
34    pub session_token: Zeroizing<String>,
35    pub expiration: DateTime<Utc>,
36}
37
38impl std::fmt::Debug for Minted {
39    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
40        f.debug_struct("Minted").field("expiration", &self.expiration).finish_non_exhaustive()
41    }
42}
43
44impl Minted {
45    /// What the SDKs read.
46    pub fn to_json(&self) -> serde_json::Value {
47        serde_json::json!({
48            "Version": 1,
49            "AccessKeyId": self.access_key_id.as_str(),
50            "SecretAccessKey": self.secret_access_key.as_str(),
51            "SessionToken": self.session_token.as_str(),
52            "Expiration": self.expiration.format("%Y-%m-%dT%H:%M:%SZ").to_string(),
53        })
54    }
55}
56
57/// Why a mint failed, in the words the person is told (spec §10).
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub enum MintError {
60    /// The AWS CLI (or the recipe's program) is not on this machine, or is too old.
61    CliMissing(String),
62    /// The host's own login has lapsed.
63    LoginNeeded(String),
64    /// The recipe ran and refused, or printed something that is not credentials.
65    Refused(String),
66    TookTooLong,
67}
68
69pub struct RunSpec {
70    pub program: PathBuf,
71    pub args: Vec<String>,
72    /// Added to the clean environment.
73    pub env: Vec<(String, String)>,
74    pub timeout: Duration,
75}
76
77pub struct RunOutput {
78    pub success: bool,
79    pub stdout: Vec<u8>,
80    pub stderr: String,
81}
82
83pub enum RunError {
84    Spawn(String),
85    TimedOut,
86}
87
88/// How a recipe's program is found and run: the real one below, a fake in the tests.
89pub trait Runner: Send + Sync {
90    fn which(&self, program: &str) -> Option<PathBuf>;
91    fn run(&self, spec: RunSpec) -> impl Future<Output = Result<RunOutput, RunError>> + Send;
92}
93
94/// Cleaned for a session tag: letters, digits, spaces and `_.:/=+-@`, one line, at most [`REASON_MAX`] characters.
95pub fn clean_reason(reason: &str) -> String {
96    let kept: String = reason.chars().map(|c| if c.is_alphanumeric() || " _.:/=+-@".contains(c) { c } else { ' ' }).collect();
97    let flat = kept.split_whitespace().collect::<Vec<_>>().join(" ");
98    // Never starts with `-`: a program given `--reason <this>` must not read it as an option.
99    flat.chars().take(REASON_MAX).collect::<String>().trim_matches(|c: char| c == '-' || c == ' ').to_string()
100}
101
102pub struct MintCtx<'a> {
103    pub agent_slug: &'a str,
104    pub grant: &'a Grant,
105    /// Already cleaned ([`clean_reason`]).
106    pub reason: &'a str,
107    /// The caller's tag value, already checked (`CallerTag::check`); empty when the grant takes none.
108    pub tag: &'a str,
109    pub seconds: u64,
110    pub now_ms: i64,
111}
112
113impl MintCtx<'_> {
114    /// `<agent slug>-<grant>-<unix ms>`, the session name a cloud record shows; at most 64 characters, as AWS allows.
115    pub fn session_name(&self) -> String {
116        let name = format!("{}-{}-{}", self.agent_slug, self.grant.name, self.now_ms);
117        let cut = name.len().saturating_sub(64);
118        // The slug and grant are ASCII, so cutting at a byte offset is safe; the tail (the time) is what must survive.
119        name[cut..].trim_start_matches('-').to_string()
120    }
121}
122
123/// The recipe's program and arguments, with the placeholders filled in.
124pub fn recipe_argv(ctx: &MintCtx<'_>) -> Vec<String> {
125    match &ctx.grant.mint {
126        Mint::HostProfile { profile } => {
127            ["aws", "configure", "export-credentials", "--profile", profile.as_str(), "--format", "process"].iter().map(|s| s.to_string()).collect()
128        }
129        Mint::Command { argv } => argv
130            .iter()
131            .map(|arg| {
132                arg.replace("{reason}", ctx.reason)
133                    .replace("{tag_key}", ctx.grant.caller_tag.as_ref().map_or("", |t| t.key.as_str()))
134                    .replace("{tag}", ctx.tag)
135                    .replace("{seconds}", &ctx.seconds.to_string())
136                    .replace("{session}", &ctx.session_name())
137                    .replace("{agent}", ctx.agent_slug)
138            })
139            .collect(),
140    }
141}
142
143#[derive(Deserialize)]
144struct ProcessJson {
145    #[serde(rename = "Version")]
146    version: Option<u32>,
147    #[serde(rename = "AccessKeyId")]
148    access_key_id: Option<String>,
149    #[serde(rename = "SecretAccessKey")]
150    secret_access_key: Option<String>,
151    #[serde(rename = "SessionToken")]
152    session_token: Option<String>,
153    #[serde(rename = "Expiration")]
154    expiration: Option<String>,
155}
156
157/// The credentials in a recipe's stdout: the last non-empty line, which must be the JSON object (a tool may print a
158/// banner first). Long-lived keys, with no session token or no expiry, are refused: nothing that does not expire
159/// is ever handed to a container.
160pub fn parse_process_json(stdout: &[u8], now: DateTime<Utc>) -> Result<Minted, String> {
161    let text = String::from_utf8_lossy(stdout);
162    let line = text.lines().map(str::trim).rfind(|l| !l.is_empty()).ok_or("it printed nothing")?;
163    let parsed: ProcessJson = serde_json::from_str(line).map_err(|_| "what it printed is not credential JSON".to_string())?;
164    if parsed.version != Some(1) {
165        return Err("what it printed is not credential_process version 1".to_string());
166    }
167    let field = |v: Option<String>, name: &str| v.filter(|s| !s.is_empty()).ok_or_else(|| format!("its credentials have no {name}"));
168    let expiration = field(parsed.expiration, "Expiration (a key that does not expire is never handed to a container)")?;
169    let expiration = DateTime::parse_from_rfc3339(&expiration).map_err(|_| "its Expiration is not a time".to_string())?.with_timezone(&Utc);
170    if expiration <= now {
171        return Err("its credentials have already expired".to_string());
172    }
173    Ok(Minted {
174        access_key_id: Zeroizing::new(field(parsed.access_key_id, "AccessKeyId")?),
175        secret_access_key: Zeroizing::new(field(parsed.secret_access_key, "SecretAccessKey")?),
176        session_token: Zeroizing::new(field(parsed.session_token, "SessionToken (a long-lived key is never handed to a container)")?),
177        expiration,
178    })
179}
180
181fn short(s: &str) -> String {
182    let flat = s.split_whitespace().collect::<Vec<_>>().join(" ");
183    if flat.chars().count() <= STDERR_KEPT {
184        flat
185    } else {
186        format!("{}…", flat.chars().take(STDERR_KEPT).collect::<String>())
187    }
188}
189
190/// What the host's AWS CLI says when its login has lapsed.
191pub(crate) fn login_lapsed(stderr: &str) -> bool {
192    let s = stderr.to_lowercase();
193    ["sso login", "sso session", "token has expired", "error loading sso token", "refresh token", "expiredtoken"].iter().any(|m| s.contains(m))
194}
195
196/// Run the grant's recipe and parse what it prints.
197pub async fn mint<R: Runner>(runner: &R, ctx: &MintCtx<'_>, now: DateTime<Utc>) -> Result<Minted, MintError> {
198    let argv = recipe_argv(ctx);
199    let (program_name, args) = argv.split_first().ok_or_else(|| MintError::Refused("the recipe is empty".to_string()))?;
200    let is_cli = matches!(ctx.grant.mint, Mint::HostProfile { .. });
201    let Some(program) = runner.which(program_name) else {
202        return Err(if is_cli {
203            MintError::CliMissing("this computer has no AWS CLI (v2.9 or newer), which this grant uses".to_string())
204        } else {
205            MintError::CliMissing(format!("{program_name} isn't installed on this computer (or isn't at that path)"))
206        });
207    };
208    let spec = RunSpec {
209        program,
210        args: args.to_vec(),
211        env: vec![("AGENTMUX_AGENT_ID".to_string(), ctx.agent_slug.to_string())],
212        timeout: RECIPE_TIMEOUT,
213    };
214    let out = match runner.run(spec).await {
215        Ok(out) => out,
216        Err(RunError::TimedOut) => return Err(MintError::TookTooLong),
217        Err(RunError::Spawn(e)) => return Err(MintError::Refused(format!("couldn't run {program_name}: {e}"))),
218    };
219    if !out.success {
220        let said = short(&out.stderr);
221        if is_cli {
222            let s = out.stderr.to_lowercase();
223            if s.contains("invalid choice") || s.contains("unknown command") || s.contains("export-credentials") && s.contains("usage") {
224                return Err(MintError::CliMissing("the AWS CLI here is too old (v2.9 or newer is needed)".to_string()));
225            }
226            if login_lapsed(&out.stderr) {
227                return Err(MintError::LoginNeeded(said));
228            }
229        }
230        return Err(MintError::Refused(if said.is_empty() { "it exited with an error and said nothing".to_string() } else { said }));
231    }
232    parse_process_json(&out.stdout, now).map_err(|why| MintError::Refused(format!("{program_name}: {why}")))
233}
234
235/// Runs the recipe as a child of srv with a clean environment.
236pub struct HostRunner;
237
238/// What the host's own AWS setup and a program on PATH need, and nothing of the agent's or srv's instance identity.
239fn passes(name: &str) -> bool {
240    passes_with(name, cfg!(windows))
241}
242
243/// Windows stores the names as they were written (`Path`, `SystemRoot`) and treats them without regard to case, so
244/// there the allowlist must too: matching `PATH` exactly left the child with no PATH and `node` not found.
245fn passes_with(name: &str, ignore_case: bool) -> bool {
246    const FIXED: [&str; 20] = [
247        "PATH", "PATHEXT", "COMSPEC", "WINDIR", "HOME", "USERPROFILE", "APPDATA", "LOCALAPPDATA", "SYSTEMROOT", "TEMP", "TMP", "TMPDIR", "USER", "USERNAME",
248        "LANG", "LC_ALL", "HTTPS_PROXY", "HTTP_PROXY", "NO_PROXY", "SSL_CERT_FILE",
249    ];
250    let name = if ignore_case { name.to_ascii_uppercase() } else { name.to_string() };
251    FIXED.contains(&name.as_str()) || name.starts_with("AWS_") || name == "XDG_CONFIG_HOME" || (!ignore_case && name == "SystemRoot")
252}
253
254impl Runner for HostRunner {
255    fn which(&self, program: &str) -> Option<PathBuf> {
256        which::which(program).ok()
257    }
258
259    async fn run(&self, spec: RunSpec) -> Result<RunOutput, RunError> {
260        let mut cmd = tokio::process::Command::new(&spec.program);
261        cmd.env_clear();
262        // The environment is rebuilt from the allowlist below; the sanitizer keeps this spawn on the same footing as every
263        // other external program srv runs (the spawn inventory in `pane_env.rs`).
264        crate::backend::pane_env::sanitize_external_command(&mut cmd);
265        for (k, v) in std::env::vars().filter(|(k, _)| passes(k)) {
266            cmd.env(k, v);
267        }
268        for (k, v) in &spec.env {
269            cmd.env(k, v);
270        }
271        cmd.args(&spec.args).stdin(std::process::Stdio::null()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).kill_on_drop(true);
272        cmd.no_window();
273        match tokio::time::timeout(spec.timeout, cmd.output()).await {
274            Ok(Ok(out)) => Ok(RunOutput { success: out.status.success(), stdout: out.stdout, stderr: String::from_utf8_lossy(&out.stderr).into_owned() }),
275            Ok(Err(e)) => Err(RunError::Spawn(e.to_string())),
276            Err(_) => Err(RunError::TimedOut),
277        }
278    }
279}
280
281#[cfg(any(test, feature = "test-support"))]
282#[path = "mint_tests.rs"]
283pub mod tests;