1use std::collections::BTreeMap;
11use std::path::{Path, PathBuf};
12use std::sync::{Arc, Mutex};
13use std::time::SystemTime;
14
15use serde::Deserialize;
16
17use super::record;
18
19pub const MIN_SECONDS: u64 = 900;
21pub const MAX_SECONDS: u64 = 3600;
22const DEFAULT_MINTS_PER_HOUR: u32 = 12;
23const DEFAULT_READ_SECONDS: u64 = 3600;
24const DEFAULT_WRITE_SECONDS: u64 = 1800;
25const PLACEHOLDERS: [&str; 6] = ["reason", "seconds", "session", "agent", "tag", "tag_key"];
27pub const TAG_VALUE_MAX: usize = 256;
29const TAG_KEY_MAX: usize = 128;
30const TAG_CHARS: &str = "_.:/=+-@";
32pub const FILE_ENV: &str = "AGENTMUX_AWS_GRANTS_FILE";
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub enum Tier {
37 Read,
38 Write,
39}
40
41impl Tier {
42 pub fn as_str(self) -> &'static str {
43 match self {
44 Tier::Read => "read",
45 Tier::Write => "write",
46 }
47 }
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum Hold {
53 Awaiting,
55 Refused,
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct CallerTag {
64 pub key: String,
66 pub prefix: String,
68}
69
70fn tag_chars_ok(s: &str) -> bool {
71 s.chars().all(|c| c.is_ascii_alphanumeric() || TAG_CHARS.contains(c))
72}
73
74impl CallerTag {
75 pub fn check(&self, grant: &str, given: Option<&str>) -> Result<String, String> {
78 let Some(value) = given.map(str::trim).filter(|v| !v.is_empty()) else {
79 return Err(format!(
80 "The grant '{grant}' needs the {} tag. Run the command with AGENTMUX_AWS_TAG='<value>' in front of it; the value starts with '{}'.",
81 self.key, self.prefix
82 ));
83 };
84 if value.starts_with('-') {
86 return Err(format!("The {} tag for the grant '{grant}' may not start with '-'.", self.key));
87 }
88 if value.chars().count() > TAG_VALUE_MAX || !tag_chars_ok(value) {
89 return Err(format!(
90 "The {} tag for the grant '{grant}' may hold only letters, digits and _.:/=+-@ (no spaces), at most {TAG_VALUE_MAX} characters.",
91 self.key
92 ));
93 }
94 if !value.starts_with(&self.prefix) {
95 return Err(format!("The {} tag for the grant '{grant}' has to start with '{}'.", self.key, self.prefix));
96 }
97 Ok(value.to_string())
98 }
99}
100
101#[derive(Debug, Clone, PartialEq, Eq)]
103pub enum Mint {
104 HostProfile { profile: String },
106 Command { argv: Vec<String> },
108}
109
110#[derive(Debug, Clone, PartialEq, Eq)]
111pub struct Grant {
112 pub name: String,
113 pub tier: Tier,
114 pub mint: Mint,
115 pub default_seconds: u64,
116 pub max_seconds: u64,
117 pub needs_reason: bool,
118 pub agents: Vec<String>,
120 pub max_mints_per_hour: u32,
121 pub disabled: bool,
122 pub note: Option<String>,
123 pub caller_tag: Option<CallerTag>,
125 pub hold: Option<Hold>,
127}
128
129impl Grant {
130 pub fn open_to(&self, slug: &str) -> bool {
132 self.agents.iter().any(|a| a == "*" || a.eq_ignore_ascii_case(slug))
133 }
134}
135
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub struct Policy {
138 pub region: String,
139 pub default_grant: Option<String>,
140 pub grants: BTreeMap<String, Grant>,
141}
142
143#[derive(Deserialize)]
144#[serde(deny_unknown_fields)]
145struct RawPolicy {
146 version: u32,
147 region: Option<String>,
148 default_grant: Option<String>,
149 #[serde(default)]
150 grants: BTreeMap<String, RawGrant>,
151}
152
153#[derive(Deserialize)]
154#[serde(deny_unknown_fields)]
155struct RawGrant {
156 tier: String,
157 mint: RawMint,
158 default_seconds: Option<u64>,
159 max_seconds: Option<u64>,
160 needs_reason: Option<bool>,
161 #[serde(default)]
162 agents: Vec<String>,
163 max_mints_per_hour: Option<u32>,
164 #[serde(default)]
165 disabled: bool,
166 note: Option<String>,
167 caller_tag: Option<RawCallerTag>,
168}
169
170#[derive(Deserialize)]
171#[serde(deny_unknown_fields)]
172struct RawCallerTag {
173 key: String,
174 #[serde(default)]
175 prefix: String,
176}
177
178#[derive(Deserialize)]
179#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
180enum RawMint {
181 HostProfile { profile: String },
182 Command { argv: Vec<String> },
183}
184
185pub fn is_grant_name(s: &str) -> bool {
187 let mut chars = s.chars();
188 chars.next().is_some_and(|c| c.is_ascii_lowercase()) && s.len() <= 41 && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
189}
190
191fn is_profile_name(s: &str) -> bool {
192 !s.is_empty() && s.len() <= 128 && !s.starts_with('-') && s.bytes().all(|b| b.is_ascii_alphanumeric() || b"_.@:/+=-".contains(&b))
193}
194
195fn is_region(s: &str) -> bool {
196 !s.is_empty() && s.len() <= 32 && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-')
197}
198
199fn placeholders_of(arg: &str) -> Result<Vec<&str>, String> {
201 let mut found = Vec::new();
202 let mut rest = arg;
203 while let Some(open) = rest.find('{') {
204 let after = &rest[open + 1..];
205 let close = after.find('}').ok_or_else(|| format!("{arg:?} has an unclosed {{"))?;
206 let name = &after[..close];
207 if !PLACEHOLDERS.contains(&name) {
208 return Err(format!("{arg:?} uses {{{name}}}; the placeholders are {{reason}}, {{seconds}}, {{session}}, {{agent}}, {{tag}} and {{tag_key}}"));
209 }
210 found.push(name);
211 rest = &after[close + 1..];
212 }
213 if rest.contains('}') {
214 return Err(format!("{arg:?} has a stray }}"));
215 }
216 Ok(found)
217}
218
219fn caller_tag_of(raw: Option<RawCallerTag>, mint: &Mint) -> Result<Option<CallerTag>, String> {
221 let Some(t) = raw else { return Ok(None) };
222 if matches!(mint, Mint::HostProfile { .. }) {
223 return Err("a caller_tag needs a command recipe".to_string());
224 }
225 if t.key.is_empty() || t.key.len() > TAG_KEY_MAX || !tag_chars_ok(&t.key) || t.key.to_ascii_lowercase().starts_with("aws:") {
226 return Err(format!("caller_tag key {:?}: letters, digits and _.:/=+-@, at most {TAG_KEY_MAX} characters, and not starting with aws:", t.key));
227 }
228 if t.prefix.len() > TAG_VALUE_MAX || !tag_chars_ok(&t.prefix) {
229 return Err(format!("caller_tag prefix {:?}: letters, digits and _.:/=+-@, at most {TAG_VALUE_MAX} characters", t.prefix));
230 }
231 if t.key.starts_with('-') || t.prefix.starts_with('-') {
233 return Err("caller_tag: the key and the prefix may not start with '-'".to_string());
234 }
235 Ok(Some(CallerTag { key: t.key, prefix: t.prefix }))
236}
237
238impl Policy {
239 pub fn parse(text: &str) -> Result<Policy, String> {
241 let raw: RawPolicy = serde_json::from_str(text).map_err(|e| format!("line {}, column {}: {e}", e.line(), e.column()))?;
242 if raw.version != 1 {
243 return Err(format!("version {} is not known: this AgentMux reads version 1", raw.version));
244 }
245 let region = raw.region.unwrap_or_else(|| "us-east-1".to_string());
246 if !is_region(®ion) {
247 return Err(format!("region {region:?} is not an AWS region name"));
248 }
249 let mut grants = BTreeMap::new();
250 for (name, g) in raw.grants {
251 if !is_grant_name(&name) {
252 return Err(format!("grant name {name:?}: lower case letters, digits and -, starting with a letter, at most 41 characters"));
253 }
254 let at = |m: String| format!("grant {name:?}: {m}");
255 let tier = match g.tier.as_str() {
256 "read" => Tier::Read,
257 "write" => Tier::Write,
258 other => return Err(at(format!("tier {other:?} is not read or write"))),
259 };
260 let mint = match g.mint {
261 RawMint::HostProfile { profile } => {
262 if !is_profile_name(&profile) {
263 return Err(at(format!("profile {profile:?} is not a usable AWS profile name")));
264 }
265 Mint::HostProfile { profile }
266 }
267 RawMint::Command { argv } => {
268 let Some(program) = argv.first() else { return Err(at("the command's argv is empty".to_string())) };
269 if program.is_empty() || program.contains('{') {
270 return Err(at("the program (argv[0]) must be a fixed path or name".to_string()));
271 }
272 let mut used = Vec::new();
273 for arg in &argv {
274 used.extend(placeholders_of(arg).map_err(&at)?);
275 }
276 let takes_tag = g.caller_tag.is_some();
277 if used.iter().any(|p| matches!(*p, "tag" | "tag_key")) && !takes_tag {
278 return Err(at("the command uses {tag} or {tag_key}, and the grant has no caller_tag".to_string()));
279 }
280 if takes_tag && !used.contains(&"tag") {
281 return Err(at("caller_tag is set and no argument of the command uses {tag}".to_string()));
282 }
283 Mint::Command { argv }
284 }
285 };
286 let caller_tag = caller_tag_of(g.caller_tag, &mint).map_err(&at)?;
287 let default_seconds = g.default_seconds.unwrap_or(if tier == Tier::Read { DEFAULT_READ_SECONDS } else { DEFAULT_WRITE_SECONDS });
288 let max_seconds = g.max_seconds.unwrap_or(MAX_SECONDS);
289 for (what, secs) in [("default_seconds", default_seconds), ("max_seconds", max_seconds)] {
290 if !(MIN_SECONDS..=MAX_SECONDS).contains(&secs) {
291 return Err(at(format!("{what} {secs} is outside {MIN_SECONDS} to {MAX_SECONDS}")));
292 }
293 }
294 if default_seconds > max_seconds {
295 return Err(at(format!("default_seconds {default_seconds} is more than max_seconds {max_seconds}")));
296 }
297 let agents: Vec<String> = g.agents.iter().map(|a| a.trim().to_lowercase()).collect();
298 if agents.iter().any(String::is_empty) {
299 return Err(at("agents has an empty name".to_string()));
300 }
301 let max_mints_per_hour = g.max_mints_per_hour.unwrap_or(DEFAULT_MINTS_PER_HOUR);
302 if max_mints_per_hour == 0 {
303 return Err(at("max_mints_per_hour is 0: use disabled to turn a grant off".to_string()));
304 }
305 grants.insert(
306 name.clone(),
307 Grant {
308 name,
309 tier,
310 mint,
311 default_seconds,
312 max_seconds,
313 needs_reason: g.needs_reason.unwrap_or(tier == Tier::Write),
314 agents,
315 max_mints_per_hour,
316 disabled: g.disabled,
317 note: g.note.map(|n| n.trim().to_string()).filter(|n| !n.is_empty()),
318 caller_tag,
319 hold: None,
320 },
321 );
322 }
323 if let Some(default) = raw.default_grant.as_deref() {
324 if !grants.contains_key(default) {
325 return Err(format!("default_grant {default:?} is not one of the grants"));
326 }
327 }
328 Ok(Policy { region, default_grant: raw.default_grant, grants })
329 }
330
331 pub fn names(&self) -> Vec<&str> {
333 self.grants.keys().map(String::as_str).collect()
334 }
335
336 pub fn open_to(&self, slug: &str) -> Vec<&str> {
338 self.grants.values().filter(|g| !g.disabled && g.hold.is_none() && g.open_to(slug)).map(|g| g.name.as_str()).collect()
339 }
340
341 pub fn render_config(&self) -> String {
344 let mut out = String::from("# Written by AgentMux; read-only. Change the grants in ~/.agentmux/aws-grants.json on the host.\n");
345 let profile = |name: &str| format!("credential_process = agentmux-bashwrap aws-credentials --profile {name}\nregion = {}\n", self.region);
346 if let Some(default) = &self.default_grant {
347 out.push_str(&format!("\n[default]\n{}", profile(default)));
348 }
349 for name in self.grants.keys() {
350 out.push_str(&format!("\n[profile {name}]\n{}", profile(name)));
351 }
352 out
353 }
354}
355
356pub fn file_path() -> Option<PathBuf> {
358 if let Some(p) = std::env::var_os(FILE_ENV).filter(|p| !p.is_empty()) {
359 return Some(PathBuf::from(p));
360 }
361 crate::srv_info::agentmux_root().map(|root| root.join("aws-grants.json"))
362}
363
364struct Cached {
365 path: PathBuf,
366 stamp: Option<(SystemTime, u64)>,
367 good: Option<Arc<Policy>>,
369 raw: Option<Arc<Policy>>,
371 error: Option<String>,
373}
374
375static CACHE: Mutex<Option<Cached>> = Mutex::new(None);
376
377pub fn current() -> Result<Option<Arc<Policy>>, String> {
380 match file_path() {
381 Some(path) => load(&path),
382 None => Ok(None),
383 }
384}
385
386fn stamp_of(path: &Path) -> Option<(SystemTime, u64)> {
387 let meta = std::fs::metadata(path).ok()?;
388 Some((meta.modified().ok()?, meta.len()))
389}
390
391fn load(path: &Path) -> Result<Option<Arc<Policy>>, String> {
392 let mut guard = CACHE.lock().unwrap_or_else(|e| e.into_inner());
393 let cached = guard.get_or_insert_with(|| Cached { path: path.to_path_buf(), stamp: None, good: None, raw: None, error: None });
394 if cached.path != path {
395 *cached = Cached { path: path.to_path_buf(), stamp: None, good: None, raw: None, error: None };
396 }
397 let Some(stamp) = stamp_of(path) else {
398 *cached = Cached { path: path.to_path_buf(), stamp: None, good: None, raw: None, error: None };
400 return Ok(None);
401 };
402 if cached.stamp != Some(stamp) {
403 let text = std::fs::read_to_string(path).map_err(|e| format!("can't read {}: {e}", path.display()))?;
406 cached.stamp = Some(stamp);
407 match Policy::parse(&text) {
408 Ok(policy) => {
409 tracing::info!(target: "identity", grants = policy.grants.len(), "identity.aws: the grants file was read");
410 let sha = record::sha256_hex(&text);
411 cached.good = Some(Arc::new(guarded(path, &policy, &sha)));
412 cached.raw = Some(Arc::new(policy));
413 cached.error = None;
414 }
415 Err(e) => {
416 tracing::warn!(target: "identity", error = %e, kept_previous = cached.good.is_some(), "identity.aws: the grants file does not parse");
417 cached.error = Some(e);
418 }
419 }
420 }
421 match (&cached.good, &cached.error) {
422 (Some(good), _) => Ok(Some(good.clone())),
423 (None, Some(e)) => Err(format!("{}: {e}", path.display())),
424 (None, None) => Ok(None),
425 }
426}
427
428pub const AUDIT_ACTION: &str = "aws.grants";
430
431fn guarded(path: &Path, policy: &Policy, sha: &str) -> Policy {
434 let record_path = record::path_beside(path);
435 let old = match record::read(&record_path) {
436 Ok(old) => old,
437 Err(e) => {
438 tracing::warn!(target: "identity", error = %e, "identity.aws: the grants record can't be read, so every grant is held");
439 return record::hold_all(policy);
440 }
441 };
442 let (rec, events) = record::sync(old.clone(), policy, sha, agentmux_common::time::now_ms());
443 if old.as_ref() != Some(&rec) {
444 if let Err(e) = record::write(&record_path, &rec) {
445 tracing::warn!(target: "identity", error = %e, "identity.aws: the grants record was not saved");
446 }
447 }
448 emit(&events);
449 record::effective(policy, &rec)
450}
451
452fn emit(events: &[record::Event]) {
454 let handler = crate::backend::reactive::get_global_handler();
455 for e in events {
456 let target = e.grant.as_deref().unwrap_or("aws grants");
457 let error = e.held.then_some("held");
458 handler.log_fleet_action_audit(Some(e.by.as_deref().unwrap_or("agentmux")), target, "", AUDIT_ACTION, !e.held, error, &e.id, Some(&e.text));
459 tracing::info!(target: "identity", kind = e.kind, held = e.held, "identity.aws: {}", e.text);
460 }
461}
462
463pub fn decide(d: &record::Decision<'_>) -> Result<record::Event, String> {
466 let path = file_path().ok_or_else(|| "this AgentMux has no data folder".to_string())?;
467 current()?;
468 let mut guard = CACHE.lock().unwrap_or_else(|e| e.into_inner());
469 let cached = guard.as_mut().ok_or_else(|| "the grants file has not been read".to_string())?;
470 let raw = cached.raw.clone().ok_or_else(|| "there is no grants file to answer for".to_string())?;
471 let record_path = record::path_beside(&path);
472 let mut rec = record::read(&record_path)?.ok_or_else(|| "there is no record of the grants file yet".to_string())?;
473 let event = record::decide(&mut rec, d, agentmux_common::time::now_ms())?;
474 record::write(&record_path, &rec)?;
475 cached.good = Some(Arc::new(record::effective(&raw, &rec)));
476 emit(std::slice::from_ref(&event));
477 Ok(event)
478}
479
480pub fn view() -> Result<record::View, String> {
482 let path = file_path().ok_or_else(|| "this AgentMux has no data folder".to_string())?;
483 current()?;
484 let rec = record::read(&record::path_beside(&path))?;
485 Ok(rec.map(|r| record::view(&r)).unwrap_or(record::View { grants: Vec::new(), changes: Vec::new() }))
486}
487
488#[cfg(test)]
490pub(crate) static TEST_LOCK: Mutex<()> = Mutex::new(());
491
492#[cfg(test)]
493#[path = "policy_tests.rs"]
494mod tests;