Skip to main content

agentmux_srv_core/identity/aws_broker/
policy.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The AWS grants a host shares with its container agents (`~/.agentmux/aws-grants.json`).
5//! Spec: docs/specs/SPEC_CONTAINER_AGENT_AWS_CREDENTIALS_2026_10_31.md §6.
6//!
7//! Closed by default: no file, no grants. A file that does not parse is an error naming the line, and the version
8//! that last parsed stays in force until it is fixed.
9
10use 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
19/// STS refuses a session shorter than 15 minutes, and the roles AgentMux fleets use allow at most an hour.
20pub 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;
25/// What a recipe may be given, substituted whole into one argument each.
26const PLACEHOLDERS: [&str; 6] = ["reason", "seconds", "session", "agent", "tag", "tag_key"];
27/// The most characters a caller-supplied session tag value, and a tag key, may have.
28pub const TAG_VALUE_MAX: usize = 256;
29const TAG_KEY_MAX: usize = 128;
30/// The characters a caller-supplied tag may hold, besides letters and digits: no space, and none that is a wildcard.
31const TAG_CHARS: &str = "_.:/=+-@";
32/// The environment variable that points at another policy file (tests, an isolated instance).
33pub 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/// Why a grant in the file is not honoured yet (`record`): it is new or wider than what was last allowed.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub enum Hold {
53    /// Waiting for a native agent or a person to allow it.
54    Awaiting,
55    /// Someone said it must not be used.
56    Refused,
57}
58
59/// One session tag the caller supplies on each mint, under a key the grant fixes. A grant for a role whose own policy builds
60/// what it may reach from a tag takes the tag's value from the caller, so the value is checked here: it starts with the
61/// prefix the grant fixes, and holds only letters, digits and `_.:/=+-@`, at most 256 characters.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub struct CallerTag {
64    /// The tag's key as the recipe sets it (`{tag_key}`).
65    pub key: String,
66    /// What every value starts with. May be empty.
67    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    /// The value the caller gave, or the sentence that says why it is not allowed. Nothing is cleaned: a value that is not
76    /// allowed is refused, not changed into one that is.
77    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        // The value is one whole argument of a program, which reads one that starts with '-' as an option: never given to it.
85        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/// How srv gets the credentials (spec §7).
102#[derive(Debug, Clone, PartialEq, Eq)]
103pub enum Mint {
104    /// The host's own AWS profile, through the AWS CLI.
105    HostProfile { profile: String },
106    /// A program that prints `credential_process` JSON.
107    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    /// Agent slugs (lower case), or `*`.
119    pub agents: Vec<String>,
120    pub max_mints_per_hour: u32,
121    pub disabled: bool,
122    pub note: Option<String>,
123    /// One tag the caller names on each mint (`None`: the grant takes none).
124    pub caller_tag: Option<CallerTag>,
125    /// Set when the file's version of this grant has not been allowed: it is refused. Always none from `parse`.
126    pub hold: Option<Hold>,
127}
128
129impl Grant {
130    /// Whether the agent with this slug may have the grant.
131    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
185/// A grant's name: what the container's profile is called.
186pub 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
199/// The placeholders an argument uses (`{name}`), or what is wrong with it.
200fn 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
219/// A grant's `caller_tag`, checked: it needs a command recipe, and a key and prefix with only the characters a tag may hold.
220fn 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    // Both reach the program as whole arguments, which it would read as options.
232    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    /// Parse and check a policy file's text. The error names the line (JSON errors) or the grant.
240    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(&region) {
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    /// The grant names an agent may be told about: every grant, disabled or not (a refusal says why).
332    pub fn names(&self) -> Vec<&str> {
333        self.grants.keys().map(String::as_str).collect()
334    }
335
336    /// The names of the grants open to `slug`.
337    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    /// The AWS config a container reads: one profile per grant, `default` when the policy names one. Names and the
342    /// command only; no secret is ever in it.
343    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
356/// The policy file's path: the override in [`FILE_ENV`], else `aws-grants.json` in the AgentMux root.
357pub 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    /// The version that last parsed, as the broker honours it: a new or wider grant is held (`record`).
368    good: Option<Arc<Policy>>,
369    /// The same version as the file says it, to work the holds out again when a grant is allowed.
370    raw: Option<Arc<Policy>>,
371    /// What the current file said, once, so a bad edit is logged when it is made and not on every request.
372    error: Option<String>,
373}
374
375static CACHE: Mutex<Option<Cached>> = Mutex::new(None);
376
377/// The policy now in force. `Ok(None)`: no file, nothing shared. `Err`: the file does not parse and no earlier
378/// version exists.
379pub 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        // Gone: nothing is shared any more.
399        *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        // The stamp is kept only once the file has been read: a read that failed (a lock, a permission) is tried again
404        // on the next request and says so, instead of looking like a file that was already dealt with.
405        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
428/// The audit action of a change to the grants file, and of an answer to a held grant.
429pub const AUDIT_ACTION: &str = "aws.grants";
430
431/// The file's grants compared with the record: what changed is recorded in the Audit view, the record is brought up to
432/// date, and the policy comes back with every new or wider grant held. A record that can't be read holds everything.
433fn 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
452/// Puts each event in the Audit view: a held grant as a failure, so the view marks it; never a credential.
453fn 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
463/// Answers a held grant: allows it or refuses it, with the reason, by an agent or a person, and puts that in the record
464/// and the Audit view. The grant works (or stays refused) from the next request.
465pub 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
480/// The grants as the record has them, with what changed lately: when each was added and by which change.
481pub 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/// The policy cache and `AGENTMUX_AWS_GRANTS_FILE` are one per process: tests that use either take turns.
489#[cfg(test)]
490pub(crate) static TEST_LOCK: Mutex<()> = Mutex::new(());
491
492#[cfg(test)]
493#[path = "policy_tests.rs"]
494mod tests;