agentmux_srv_core/identity/aws_broker/
mint.rs1use 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
18pub const RECIPE_TIMEOUT: Duration = Duration::from_secs(50);
24const STDERR_KEPT: usize = 400;
26const REASON_MAX: usize = 256;
28
29#[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 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#[derive(Debug, Clone, PartialEq, Eq)]
59pub enum MintError {
60 CliMissing(String),
62 LoginNeeded(String),
64 Refused(String),
66 TookTooLong,
67}
68
69pub struct RunSpec {
70 pub program: PathBuf,
71 pub args: Vec<String>,
72 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
88pub 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
94pub 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 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 pub reason: &'a str,
107 pub tag: &'a str,
109 pub seconds: u64,
110 pub now_ms: i64,
111}
112
113impl MintCtx<'_> {
114 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 name[cut..].trim_start_matches('-').to_string()
120 }
121}
122
123pub 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
157pub 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
190pub(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
196pub 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
235pub struct HostRunner;
237
238fn passes(name: &str) -> bool {
240 passes_with(name, cfg!(windows))
241}
242
243fn 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 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;