Skip to main content

agentmux_srv/server/app_api/
aws_credentials.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `POST /api/v1/aws/credentials`: the AWS credentials a container agent's SDK gets through `credential_process`.
5//! Spec: docs/specs/SPEC_CONTAINER_AGENT_AWS_CREDENTIALS_2026_10_31.md ยง5.
6//!
7//! `agentmux-bashwrap aws-credentials` asks here from the container with the container's token. Who is asking is the
8//! agent that token was minted for, never a name in the request. The checks, the cache and the mint are
9//! `identity::aws_broker`; this adds the identity and the audit row. A fresh session and every refusal are recorded in
10//! the Audit view; a cache hit is not (the layer in `http_action` leaves this route to the handler for that reason).
11
12use 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
27/// The audit entry's action.
28pub(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    /// The value of the one tag a grant takes from the caller (`AGENTMUX_AWS_TAG`).
36    #[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
46/// One Audit row: the actor is the container agent. Holds the grant, tier, reason, seconds and outcome; never a key,
47/// a token or any part of a credential.
48fn 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
54/// The Audit row of a session a container agent was granted, when it is a fresh one (a cache hit is not recorded).
55pub(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    // The tag's value was checked (letters, digits and _.:/=+-@, at most 256), so it is safe to record.
66    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
70/// `POST /api/v1/aws/credentials`
71pub(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
90/// The request once the agent is known: the checks, the cache or the mint, the audit row, the answer.
91pub(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                // The sentence the agent reads, in its pane.
119                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
126/// The secret key and session token of the credentials an agent was given are never written into its transcript,
127/// until they run out. Credentials an agent's profile is given next do not end these: they still work until their
128/// own expiration, so they stay withheld until then.
129fn 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
136/// Whether a refusal is one the person can fix on this computer, so the agent's pane says so: the host's AWS login
137/// lapsed or was refused, the grant is switched off, or a new or wider grant waits to be allowed. A wrong profile name, a missing reason, a cap or a slow mint is
138/// the agent's own to correct or a bad moment.
139fn the_persons_to_fix(refusal: &Refusal) -> bool {
140    matches!(refusal.code, "AWS_HOST_LOGIN_NEEDED" | "AWS_HOST_REFUSED" | "GRANT_DISABLED" | "GRANT_HELD")
141}
142
143/// What the request's profile is called in the audit row, the log and the refusal. The string is the container's to
144/// choose, so one that can't be a grant name (too long, control characters, newlines) is never recorded or echoed.
145fn shown_profile(profile: &str) -> &str {
146    if policy::is_grant_name(profile) { profile } else { "<not a grant name>" }
147}
148
149/// The Audit row of a refusal.
150pub(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;