agentmux_srv/server/app_api/
aws_credentials.rs1use axum::extract::{Extension, State};
13use axum::http::StatusCode;
14use axum::response::{IntoResponse, Response};
15use axum::Json;
16use serde::Deserialize;
17use serde_json::json;
18
19use super::AppState;
20use crate::identity::aws_broker::mint::{HostRunner, Runner};
21use crate::identity::aws_broker::request::{credentials_for, Ask, Granted, Refusal};
22use crate::identity::aws_broker::sessions::Source;
23use crate::identity::aws_broker::{policy, sessions};
24use crate::sagas::credential_notice::{self, Cause};
25use crate::server::caller::Caller;
26
27pub(crate) const AUDIT_ACTION: &str = "aws.credentials";
29
30#[derive(Debug, Deserialize)]
31pub(crate) struct AwsCredentialsRequest {
32 pub(crate) profile: String,
33 #[serde(default)]
34 pub(crate) reason: Option<String>,
35 #[serde(default)]
37 pub(crate) tag: Option<String>,
38 #[serde(default)]
39 pub(crate) duration_seconds: Option<u64>,
40}
41
42fn refuse(status: StatusCode, message: &str) -> Response {
43 (status, Json(json!({ "error": message }))).into_response()
44}
45
46fn audit(state: &AppState, slug: &str, uid: &str, profile: &str, ok: bool, error: Option<&str>, note: &str) {
49 let block_id = state.reactive_handler.block_for_uid(uid).unwrap_or_default();
50 let reason = format!("{slug} (uid {uid}): grant {profile}: {note}");
51 state.reactive_handler.log_fleet_action_audit(Some(slug), slug, &block_id, AUDIT_ACTION, ok, error, &uuid::Uuid::new_v4().to_string(), Some(&reason));
52}
53
54pub(crate) fn audit_granted(state: &AppState, slug: &str, uid: &str, granted: &Granted) {
56 if granted.source == Source::Fresh {
57 tracing::info!(target: "identity", agent = %slug, grant = %granted.grant.name, seconds = granted.seconds, "identity.aws: credentials minted for a container agent");
58 audit(state, slug, uid, &granted.grant.name, true, None, &granted_note(granted));
59 }
60}
61
62fn granted_note(g: &Granted) -> String {
63 let renewed = if g.source == Source::Fresh { "minted" } else { "reused" };
64 let reason = if g.reason.is_empty() { "no reason given".to_string() } else { format!("reason: {}", g.reason) };
65 let tag = g.tag.as_ref().map(|(k, v)| format!("; tag {k}: {v}")).unwrap_or_default();
67 format!("{} tier, {} s, {renewed}; {reason}{tag}", g.grant.tier.as_str(), g.seconds)
68}
69
70pub(crate) async fn handle_aws_credentials(
72 State(state): State<AppState>,
73 caller: Option<Extension<Caller>>,
74 Json(req): Json<AwsCredentialsRequest>,
75) -> Response {
76 let Some(uid) = caller.as_ref().and_then(|Extension(c)| c.uid()).map(str::to_string) else {
77 return refuse(StatusCode::UNAUTHORIZED, "no agent token: AWS credentials are for an agent's own commands");
78 };
79 let mstore = state.mstore.clone();
80 let lookup = uid.clone();
81 let def = match tokio::task::spawn_blocking(move || mstore.agent_def_get(&lookup)).await {
82 Ok(Ok(Some(def))) => def,
83 Ok(Ok(None)) => return refuse(StatusCode::UNAUTHORIZED, "the agent token names no agent on this machine"),
84 _ => return refuse(StatusCode::INTERNAL_SERVER_ERROR, "couldn't read the agent"),
85 };
86 let policy = tokio::task::spawn_blocking(policy::current).await.unwrap_or_else(|e| Err(format!("couldn't read the grants file: {e}")));
87 serve(&state, &uid, &def, req, policy, sessions::global(), &HostRunner).await
88}
89
90pub(crate) async fn serve<R: Runner>(
92 state: &AppState,
93 uid: &str,
94 def: &crate::backend::storage::AgentDefinition,
95 req: AwsCredentialsRequest,
96 policy: Result<Option<std::sync::Arc<policy::Policy>>, String>,
97 sessions: &sessions::Sessions,
98 runner: &R,
99) -> Response {
100 let ask = Ask {
101 agent_uid: uid,
102 agent_slug: &def.slug,
103 in_container: def.runtime().is_container(),
104 profile: shown_profile(req.profile.trim()),
105 reason: req.reason.as_deref(),
106 tag: req.tag.as_deref(),
107 seconds: req.duration_seconds,
108 };
109 match credentials_for(policy, sessions, runner, &ask, chrono::Utc::now()).await {
110 Ok(granted) => {
111 hold_in_transcripts(uid, ask.profile, &granted.creds);
112 audit_granted(state, &def.slug, uid, &granted);
113 credential_notice::worked(state, uid, &def.slug, Cause::Aws);
114 Json(granted.creds.to_json()).into_response()
115 }
116 Err(refusal) => {
117 if the_persons_to_fix(&refusal) {
118 credential_notice::refused(state, uid, &def.slug, Cause::Aws, &refusal.message);
120 }
121 refused(state, &def.slug, uid, ask.profile, refusal)
122 }
123 }
124}
125
126fn hold_in_transcripts(uid: &str, profile: &str, creds: &crate::identity::aws_broker::mint::Minted) {
130 let until = creds.expiration.timestamp_millis();
131 let owner = |what: &str| format!("aws-credentials:{uid}:{profile}:{what}");
132 crate::backend::transcript::withhold::hold_until(&owner("secret"), &creds.secret_access_key, until);
133 crate::backend::transcript::withhold::hold_until(&owner("session"), &creds.session_token, until);
134}
135
136fn the_persons_to_fix(refusal: &Refusal) -> bool {
140 matches!(refusal.code, "AWS_HOST_LOGIN_NEEDED" | "AWS_HOST_REFUSED" | "GRANT_DISABLED" | "GRANT_HELD")
141}
142
143fn shown_profile(profile: &str) -> &str {
146 if policy::is_grant_name(profile) { profile } else { "<not a grant name>" }
147}
148
149pub(crate) fn audit_refused(state: &AppState, slug: &str, uid: &str, profile: &str, refusal: &Refusal) {
151 let profile = shown_profile(profile);
152 tracing::info!(target: "identity", agent = %slug, grant = %profile, code = refusal.code, "identity.aws: credentials refused");
153 audit(state, slug, uid, profile, false, Some(refusal.code), &format!("refused: {}", refusal.code));
154}
155
156fn refused(state: &AppState, slug: &str, uid: &str, profile: &str, refusal: Refusal) -> Response {
157 audit_refused(state, slug, uid, profile, &refusal);
158 refuse(refusal.status, &refusal.text())
159}
160
161#[cfg(test)]
162#[path = "tests/aws_credentials_tests.rs"]
163mod tests;