Skip to main content

agentmux_bashwrap/
aws.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! AWS credentials for a container agent's SDK or CLI, as AWS's standard `credential_process`.
5//! Spec: docs/specs/SPEC_CONTAINER_AGENT_AWS_CREDENTIALS_2026_10_31.md ยง12.
6//!
7//! `aws-credentials --profile <grant>` is what each profile of the container's AWS config runs (srv writes the
8//! config). It asks `POST /api/v1/aws/credentials`; who is asking is decided by srv from the agent's token
9//! (`AGENTMUX_AGENT_TOKEN`), never from the request. The reason for a write grant rides in `AGENTMUX_AWS_REASON`
10//! (the SDK process inherits it from the agent's command line), and an optional lifetime in `AGENTMUX_AWS_DURATION`.
11//!
12//! Stdout is the credentials as `credential_process` JSON on success and empty on every failure, so a broken answer
13//! can never be read as credentials. A failure is one sentence on stderr, which the AWS CLI shows after "Error when
14//! retrieving credentials from custom-process".
15
16use std::io::Write;
17use std::time::Duration;
18
19use serde_json::{json, Value};
20
21use crate::mps_client::WpsClient;
22
23/// srv may wait on the host's AWS for 50 seconds (`RECIPE_TIMEOUT` in `identity::aws_broker::mint`), and a slow
24/// mint of 20 to 26 seconds is real. This waits longer than srv does, so srv's answer, credentials or the reason
25/// there are none, is always the one the SDK sees; a stuck call still must not hold a deploy forever.
26const ASK_TIMEOUT: Duration = Duration::from_secs(65);
27
28/// What the route answered.
29#[derive(Debug, PartialEq, Eq)]
30pub enum Answer {
31    /// The `credential_process` JSON, ready to print.
32    Credentials(String),
33    /// The sentence to show.
34    Refused(String),
35}
36
37/// The request body: the grant, and what the agent said about why and for how long, if anything.
38pub fn request_body(profile: &str, reason: Option<&str>, tag: Option<&str>, duration: Option<&str>) -> Value {
39    let mut body = json!({ "profile": profile });
40    if let Some(reason) = reason.map(str::trim).filter(|r| !r.is_empty()) {
41        body["reason"] = json!(reason);
42    }
43    // The value of the one tag a grant takes from the caller; srv checks it, and says why when it is not allowed.
44    if let Some(tag) = tag.map(str::trim).filter(|t| !t.is_empty()) {
45        body["tag"] = json!(tag);
46    }
47    if let Some(seconds) = duration.and_then(|d| d.trim().parse::<u64>().ok()) {
48        body["duration_seconds"] = json!(seconds);
49    }
50    body
51}
52
53/// srv's answer as the SDK should see it: only the five fields of `credential_process`, and only when all are there.
54pub fn answer_of(status: u16, body: &Value) -> Answer {
55    if (200..300).contains(&status) {
56        let text = |key: &str| body.get(key).and_then(Value::as_str).filter(|v| !v.is_empty());
57        return match (text("AccessKeyId"), text("SecretAccessKey"), text("SessionToken"), text("Expiration")) {
58            (Some(id), Some(secret), Some(token), Some(expiration)) => Answer::Credentials(
59                json!({ "Version": 1, "AccessKeyId": id, "SecretAccessKey": secret, "SessionToken": token, "Expiration": expiration }).to_string(),
60            ),
61            _ => Answer::Refused("AgentMux answered, but not with credentials".to_string()),
62        };
63    }
64    Answer::Refused(body.get("error").and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| format!("AgentMux refused ({status})")))
65}
66
67/// Ask srv for the grant `profile`.
68pub fn ask(profile: &str) -> Answer {
69    let Some(client) = WpsClient::from_env() else {
70        return Answer::Refused("AGENTMUX_LOCAL_URL / AGENTMUX_AUTH_KEY aren't set: run this from an agent's own shell".to_string());
71    };
72    let agent_token = std::env::var("AGENTMUX_AGENT_TOKEN").ok();
73    let rt = match tokio::runtime::Runtime::new() {
74        Ok(rt) => rt,
75        Err(e) => return Answer::Refused(format!("couldn't start: {e}")),
76    };
77    let reason = std::env::var("AGENTMUX_AWS_REASON").ok();
78    let tag = std::env::var("AGENTMUX_AWS_TAG").ok();
79    let duration = std::env::var("AGENTMUX_AWS_DURATION").ok();
80    let body = request_body(profile, reason.as_deref(), tag.as_deref(), duration.as_deref());
81    match rt.block_on(client.post_json_status("/api/v1/aws/credentials", agent_token.as_deref(), &body, ASK_TIMEOUT)) {
82        Ok((status, answer)) => answer_of(status, &answer),
83        Err(e) => Answer::Refused(format!("couldn't reach AgentMux: {e}")),
84    }
85}
86
87/// `aws-credentials --profile <name>`: exit 0 with the JSON on stdout, or exit 1 with a sentence on stderr.
88pub fn run_aws_credentials(profile: &str) -> i32 {
89    match ask(profile) {
90        Answer::Credentials(json) => {
91            let mut out = std::io::stdout();
92            let _ = out.write_all(json.as_bytes());
93            let _ = out.write_all(b"\n");
94            let _ = out.flush();
95            0
96        }
97        Answer::Refused(why) => {
98            eprintln!("{why}");
99            1
100        }
101    }
102}
103
104#[cfg(test)]
105mod tests {
106    use super::*;
107
108    const CREDS: &str = r#"{"Version":1,"AccessKeyId":"AKIATEST","SecretAccessKey":"sekret","SessionToken":"tok","Expiration":"2026-10-31T13:00:00Z","Extra":"dropped"}"#;
109
110    #[test]
111    fn the_request_names_the_grant_and_carries_the_reason_and_lifetime_only_when_given() {
112        assert_eq!(request_body("deploy", None, None, None), json!({ "profile": "deploy" }));
113        assert_eq!(request_body("deploy", Some("  "), Some(" "), Some("soon")), json!({ "profile": "deploy" }));
114        assert_eq!(
115            request_body("deploy", Some(" deploy stack X "), None, Some("1800")),
116            json!({ "profile": "deploy", "reason": "deploy stack X", "duration_seconds": 1800 })
117        );
118    }
119
120    #[test]
121    fn credentials_are_passed_on_as_the_five_fields_and_nothing_else() {
122        let Answer::Credentials(out) = answer_of(200, &serde_json::from_str(CREDS).unwrap()) else { panic!("credentials") };
123        let parsed: Value = serde_json::from_str(&out).unwrap();
124        assert_eq!(parsed["Version"], 1);
125        assert_eq!(parsed["SessionToken"], "tok");
126        assert!(parsed.get("Extra").is_none(), "{out}");
127        assert!(!out.contains('\n'), "one line");
128    }
129
130    #[test]
131    fn an_answer_missing_a_field_is_never_credentials() {
132        for key in ["AccessKeyId", "SecretAccessKey", "SessionToken", "Expiration"] {
133            let mut body: Value = serde_json::from_str(CREDS).unwrap();
134            body.as_object_mut().unwrap().remove(key);
135            assert!(matches!(answer_of(200, &body), Answer::Refused(_)), "{key}");
136        }
137        assert!(matches!(answer_of(200, &json!({ "AccessKeyId": "" })), Answer::Refused(_)));
138    }
139
140    #[test]
141    fn a_refusal_is_srvs_own_sentence() {
142        let body = json!({ "error": "REASON_REQUIRED: The grant 'deploy' needs a reason." });
143        assert_eq!(answer_of(400, &body), Answer::Refused("REASON_REQUIRED: The grant 'deploy' needs a reason.".to_string()));
144        assert_eq!(answer_of(502, &json!({})), Answer::Refused("AgentMux refused (502)".to_string()));
145        // Whatever it says, a refusal never prints credentials.
146        assert!(matches!(answer_of(403, &serde_json::from_str(CREDS).unwrap()), Answer::Refused(_)));
147    }
148
149    #[test]
150    fn the_reason_the_agents_token_and_no_name_reach_srv() {
151        let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
152        let (url, srv) = crate::github::tests::stub_srv(200, CREDS);
153        std::env::set_var("AGENTMUX_LOCAL_URL", &url);
154        std::env::set_var("AGENTMUX_AUTH_KEY", "key");
155        std::env::set_var("AGENTMUX_AGENT_TOKEN", "agent-token-1");
156        std::env::set_var("AGENTMUX_AWS_REASON", "deploy stack X");
157        std::env::set_var("AGENTMUX_AWS_DURATION", "1800");
158        let answer = ask("deploy");
159        std::env::remove_var("AGENTMUX_AWS_REASON");
160        std::env::remove_var("AGENTMUX_AWS_DURATION");
161        let seen = srv.join().unwrap();
162        assert!(matches!(&answer, Answer::Credentials(c) if c.contains("AKIATEST")));
163        assert!(seen.starts_with("POST /api/v1/aws/credentials "), "{seen}");
164        assert!(seen.to_ascii_lowercase().contains("x-agent-token: agent-token-1"), "who is asking is the agent's own token: {seen}");
165        assert!(seen.contains(r#""profile":"deploy""#) && seen.contains(r#""reason":"deploy stack X""#) && seen.contains(r#""duration_seconds":1800"#), "{seen}");
166        assert!(!seen.contains("agent_id"), "no name in the request: srv decides who is asking");
167    }
168
169    #[test]
170    fn a_refused_request_prints_nothing_for_the_sdk_to_read() {
171        let _guard = crate::test_env_lock::ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
172        let (url, srv) = crate::github::tests::stub_srv(403, r#"{"error":"AWS_NOT_SHARED: AWS isn't shared with container agents on this machine."}"#);
173        std::env::set_var("AGENTMUX_LOCAL_URL", &url);
174        std::env::set_var("AGENTMUX_AUTH_KEY", "key");
175        std::env::remove_var("AGENTMUX_AGENT_TOKEN");
176        std::env::remove_var("AGENTMUX_AWS_REASON");
177        let answer = ask("read");
178        srv.join().unwrap();
179        assert_eq!(answer, Answer::Refused("AWS_NOT_SHARED: AWS isn't shared with container agents on this machine.".to_string()));
180    }
181}