agentmux_srv_core/identity/aws_broker/
request.rs1use std::sync::Arc;
9
10use axum::http::StatusCode;
11use chrono::{DateTime, Utc};
12
13use super::mint::{self, clean_reason, MintCtx, MintError, Minted, Runner};
14use super::policy::{Grant, Hold, Policy};
15use super::sessions::{SessionError, Sessions, Source};
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct Refusal {
20 pub status: StatusCode,
21 pub code: &'static str,
22 pub message: String,
23}
24
25impl Refusal {
26 fn new(status: StatusCode, code: &'static str, message: impl Into<String>) -> Self {
27 Self { status, code, message: message.into() }
28 }
29
30 pub fn text(&self) -> String {
32 format!("{}: {}", self.code, self.message)
33 }
34}
35
36pub struct Ask<'a> {
38 pub agent_uid: &'a str,
39 pub agent_slug: &'a str,
40 pub in_container: bool,
41 pub profile: &'a str,
42 pub reason: Option<&'a str>,
43 pub tag: Option<&'a str>,
45 pub seconds: Option<u64>,
46}
47
48pub struct Granted {
49 pub creds: Minted,
50 pub grant: Grant,
51 pub source: Source,
52 pub reason: String,
54 pub tag: Option<(String, String)>,
56 pub seconds: u64,
58}
59
60fn list(names: &[&str]) -> String {
61 if names.is_empty() {
62 "none".to_string()
63 } else {
64 names.join(", ")
65 }
66}
67
68fn held_refusal(grant: &Grant, hold: Hold) -> Refusal {
70 let (code, what) = match hold {
71 Hold::Awaiting => ("GRANT_HELD", "was added or widened in the grants file and waits for a native agent or a person to allow it"),
72 Hold::Refused => ("GRANT_REFUSED", "was added or widened in the grants file and was refused"),
73 };
74 Refusal::new(
75 StatusCode::FORBIDDEN,
76 code,
77 format!("The grant '{}' {what}. A native agent can read the change with Identity aws_grants and answer it with aws_grant, saying why.", grant.name),
78 )
79}
80
81pub async fn credentials_for<R: Runner>(
83 policy: Result<Option<Arc<Policy>>, String>,
84 sessions: &Sessions,
85 runner: &R,
86 ask: &Ask<'_>,
87 now: DateTime<Utc>,
88) -> Result<Granted, Refusal> {
89 if !ask.in_container {
90 return Err(Refusal::new(
91 StatusCode::FORBIDDEN,
92 "NATIVE_AGENT",
93 "This is for container agents. A native agent has the host's own AWS setup.",
94 ));
95 }
96 let policy = match policy {
97 Ok(Some(policy)) if !policy.grants.is_empty() => policy,
98 Ok(_) => {
99 return Err(Refusal::new(
100 StatusCode::FORBIDDEN,
101 "AWS_NOT_SHARED",
102 "AWS isn't shared with container agents on this machine. A person adds grants in ~/.agentmux/aws-grants.json \
103 (the AgentMux docs have a page on it); until then there is no AWS from here.",
104 ));
105 }
106 Err(e) => {
107 return Err(Refusal::new(
108 StatusCode::SERVICE_UNAVAILABLE,
109 "AWS_POLICY_UNREADABLE",
110 format!("The grants file on this machine doesn't parse, so AWS can't be shared until a person fixes it: {e}"),
111 ));
112 }
113 };
114 let Some(grant) = policy.grants.get(ask.profile) else {
115 return Err(Refusal::new(
116 StatusCode::NOT_FOUND,
117 "UNKNOWN_PROFILE",
118 format!("No AWS grant named '{}'. This machine shares: {}.", ask.profile, list(&policy.names())),
119 ));
120 };
121 if grant.disabled {
122 let why = grant.note.as_deref().map(|n| format!(" {n}")).unwrap_or_default();
123 return Err(Refusal::new(StatusCode::FORBIDDEN, "GRANT_DISABLED", format!("The grant '{}' is switched off on this machine.{why}", grant.name)));
124 }
125 if let Some(hold) = grant.hold {
126 return Err(held_refusal(grant, hold));
127 }
128 if !grant.open_to(ask.agent_slug) {
129 let open: Vec<&str> = grant.agents.iter().map(String::as_str).collect();
130 return Err(Refusal::new(
131 StatusCode::FORBIDDEN,
132 "NOT_ALLOWED_FOR_YOU",
133 format!(
134 "The grant '{}' isn't open to you. It is open to: {}. Ask the person, or an agent that can edit the policy, to add you.",
135 grant.name,
136 list(&open)
137 ),
138 ));
139 }
140 let reason = clean_reason(ask.reason.unwrap_or_default());
141 if grant.needs_reason && reason.is_empty() {
142 return Err(Refusal::new(
143 StatusCode::BAD_REQUEST,
144 "REASON_REQUIRED",
145 format!("The grant '{}' needs a reason. Run the command with AGENTMUX_AWS_REASON='what and why' in front of it.", grant.name),
146 ));
147 }
148 let tag = match &grant.caller_tag {
150 Some(spec) => match spec.check(&grant.name, ask.tag) {
151 Ok(value) => Some((spec.key.clone(), value)),
152 Err(sentence) => return Err(Refusal::new(StatusCode::BAD_REQUEST, "TAG_REFUSED", sentence)),
153 },
154 None => None,
155 };
156 let seconds = ask.seconds.unwrap_or(grant.default_seconds).clamp(super::policy::MIN_SECONDS, grant.max_seconds);
157 let tag_value = tag.as_ref().map_or("", |(_, v)| v.as_str());
158 let ctx = MintCtx { agent_slug: ask.agent_slug, grant, reason: &reason, tag: tag_value, seconds, now_ms: now.timestamp_millis() };
159 let variant = if tag_value.is_empty() { reason.clone() } else { format!("{reason}\u{1f}{tag_value}") };
161 let got = sessions
162 .get_or_mint(ask.agent_uid, &grant.name, &variant, grant.max_mints_per_hour, now, || mint::mint(runner, &ctx, now))
163 .await;
164 match got {
165 Ok((creds, source)) => Ok(Granted { creds, grant: grant.clone(), source, reason, tag, seconds }),
166 Err(SessionError::TooMany { cap }) => Err(Refusal::new(
167 StatusCode::TOO_MANY_REQUESTS,
168 "TOO_MANY_MINTS",
169 format!(
170 "You asked for '{}' credentials {cap} times in the last hour. The job may be looping; wait, or ask for a higher cap.",
171 grant.name
172 ),
173 )),
174 Err(SessionError::Mint(e)) => Err(mint_refusal(e, grant)),
175 }
176}
177
178fn mint_refusal(e: MintError, grant: &Grant) -> Refusal {
180 match e {
181 MintError::CliMissing(why) => Refusal::new(StatusCode::SERVICE_UNAVAILABLE, "AWS_CLI_MISSING", format!("{why}.")),
182 MintError::LoginNeeded(said) => {
183 let profile = match &grant.mint {
184 super::policy::Mint::HostProfile { profile } => profile.clone(),
185 super::policy::Mint::Command { .. } => grant.name.clone(),
186 };
187 Refusal::new(
188 StatusCode::SERVICE_UNAVAILABLE,
189 "AWS_HOST_LOGIN_NEEDED",
190 format!("The host's AWS login for '{profile}' has lapsed. A person runs `aws sso login --profile {profile}` on this computer. ({said})"),
191 )
192 }
193 MintError::Refused(said) => Refusal::new(StatusCode::SERVICE_UNAVAILABLE, "AWS_HOST_REFUSED", format!("The host's AWS refused: {said}")),
194 MintError::TookTooLong => Refusal::new(
195 StatusCode::SERVICE_UNAVAILABLE,
196 "AWS_TOOK_TOO_LONG",
197 format!("AWS credentials took too long ({} s). Try again in a minute.", mint::RECIPE_TIMEOUT.as_secs()),
198 ),
199 }
200}
201
202#[cfg(test)]
203#[path = "request_tests.rs"]
204mod tests;