Skip to main content

agentmux_srv/drone/executor/blocks/
api_auth.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The API block's `auth`: a Vault entry whose value is sent as one header
5//! (the Vault slice of Drone phase 3).
6//!
7//! ```json
8//! { "auth": { "vault": "api-key-github", "as": "bearer" } }
9//! { "auth": { "vault": "api-key-acme", "as": "header:X-Api-Key" } }
10//! ```
11//!
12//! The drone's definition names the entry and the site; the value never appears in it, in a run's
13//! input, in the ledger or in what the node outputs. What keeps it from going anywhere else:
14//!
15//! * The URL's site (scheme, host and port) is written out in the drone: nothing from a run (a
16//!   `{{...}}` value, which may be something an outsider wrote) can pick or change it. It must be
17//!   `https`.
18//! * The resolved URL must have exactly that site, and no user name or password.
19//! * A call with a credential follows no redirect: the one site is the only site.
20//! * The header is the one the node names; the node's own `headers` can't set it as well.
21//!
22//! The pure checks are here; asking the person, the grant and reading the value are
23//! `server::drone_vault`.
24
25use std::collections::HashMap;
26
27use reqwest::header::{HeaderName, HeaderValue};
28use serde_json::Value;
29
30/// Headers a credential can't be put in: the request's framing, not its authorization.
31const REFUSED: [&str; 8] = ["host", "content-length", "transfer-encoding", "connection", "upgrade", "te", "trailer", "proxy-authorization"];
32
33/// How the value is sent.
34#[derive(Debug, Clone, PartialEq)]
35pub enum How {
36    /// `Authorization: Bearer <value>`.
37    Bearer,
38    /// `<name>: <value>`.
39    Header(HeaderName),
40}
41
42/// A node's `auth`, checked.
43#[derive(Debug, Clone, PartialEq)]
44pub struct Auth {
45    /// The Vault entry, `id` or `id.part`.
46    pub entry: String,
47    pub how: How,
48}
49
50/// The node's `auth`: none when the node has none (absent, `null` or an empty entry), or why it
51/// can't be used. Nothing is read from the Vault here.
52pub fn parse(data: &Value) -> Result<Option<Auth>, String> {
53    let Some(auth) = data.get("auth").filter(|a| !a.is_null()) else { return Ok(None) };
54    let obj = auth.as_object().ok_or("the API block's `auth` is an object: { \"vault\": \"<entry>\", \"as\": \"bearer\" }")?;
55    for key in obj.keys() {
56        if !matches!(key.as_str(), "vault" | "as") {
57            return Err(format!("the API block's `auth` has no `{key}`: it takes `vault` and `as`"));
58        }
59    }
60    let entry = obj.get("vault").and_then(Value::as_str).unwrap_or("").trim();
61    if entry.is_empty() {
62        return Ok(None);
63    }
64    let how = match obj.get("as").and_then(Value::as_str).unwrap_or("bearer").trim() {
65        "bearer" => How::Bearer,
66        other => match other.strip_prefix("header:") {
67            Some(name) => {
68                let name = name.trim();
69                let header = HeaderName::from_bytes(name.as_bytes()).map_err(|_| format!("`{name}` isn't a header name"))?;
70                if REFUSED.contains(&header.as_str()) {
71                    return Err(format!("the `{header}` header can't carry a Vault value"));
72                }
73                How::Header(header)
74            }
75            None => return Err(format!("the API block's auth `as` is `bearer` or `header:<Name>`, not `{other}`")),
76        },
77    };
78    Ok(Some(Auth { entry: entry.to_string(), how }))
79}
80
81impl How {
82    /// The header's name.
83    pub fn name(&self) -> HeaderName {
84        match self {
85            How::Bearer => reqwest::header::AUTHORIZATION,
86            How::Header(n) => n.clone(),
87        }
88    }
89
90    /// The header's value for `secret`, marked sensitive so it is never shown in a debug print. Its
91    /// error never holds the value.
92    pub fn value(&self, secret: &str) -> Result<HeaderValue, String> {
93        let text = match self {
94            How::Bearer => format!("Bearer {secret}"),
95            How::Header(_) => secret.to_string(),
96        };
97        let mut v = HeaderValue::from_str(&text).map_err(|_| "the Vault value can't be sent in a header (it has a line break or a character a header can't hold)".to_string())?;
98        v.set_sensitive(true);
99        Ok(v)
100    }
101}
102
103/// Whether the node's own `headers` set `name` too: the credential is the Vault's alone.
104pub fn sets_it_too(headers: &HashMap<String, String>, name: &HeaderName) -> bool {
105    headers.keys().any(|k| k.trim().eq_ignore_ascii_case(name.as_str()))
106}
107
108/// The site a call with a credential goes to, from the URL as the drone has it written (`raw`) and
109/// as it resolved: `https://host[:port]`. The site must be written out in `raw`, and the resolved
110/// URL must be the same site.
111pub fn site(raw: &str, resolved: &str) -> Result<String, String> {
112    let rest = raw.trim().strip_prefix("https://").ok_or("a call with a Vault credential goes to an https:// URL")?;
113    let end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
114    let authority = &rest[..end];
115    if authority.is_empty() || authority.contains("{{") || authority.contains("}}") {
116        return Err("a call with a Vault credential has its site written out in the URL (https://host/...): no {{...}} in it".into());
117    }
118    if authority.contains(['@', '\\']) {
119        return Err("a call with a Vault credential has no user name or password in its URL".into());
120    }
121    let written = reqwest::Url::parse(&format!("https://{authority}")).map_err(|e| format!("invalid URL: {e}"))?;
122    let want = agentmux_common::url_guard::checked_origin(&written).ok_or("a call with a Vault credential goes to a site with a host name")?;
123    if !want.is_tuple() {
124        return Err("a call with a Vault credential goes to a site with a host name".into());
125    }
126    let got = reqwest::Url::parse(resolved).map_err(|e| format!("invalid URL: {e}"))?;
127    if !got.username().is_empty() || got.password().is_some() {
128        return Err("a call with a Vault credential has no user name or password in its URL".into());
129    }
130    let Some(got_origin) = agentmux_common::url_guard::checked_origin(&got) else {
131        return Err(format!("the URL resolved to an address with no site, not the site the drone names ({})", want.ascii_serialization()));
132    };
133    if got_origin != want {
134        return Err(format!("the URL resolved to {}, not the site the drone names ({})", got_origin.ascii_serialization(), want.ascii_serialization()));
135    }
136    Ok(want.ascii_serialization())
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142    use serde_json::json;
143
144    #[test]
145    fn a_node_with_no_auth_has_none() {
146        assert_eq!(parse(&json!({})), Ok(None));
147        assert_eq!(parse(&json!({ "auth": null })), Ok(None));
148        assert_eq!(parse(&json!({ "auth": { "vault": "  ", "as": "bearer" } })), Ok(None));
149    }
150
151    #[test]
152    fn auth_names_an_entry_and_how_it_is_sent() {
153        let a = parse(&json!({ "auth": { "vault": " api-key-github ", "as": "bearer" } })).unwrap().unwrap();
154        assert_eq!(a, Auth { entry: "api-key-github".into(), how: How::Bearer });
155        assert_eq!(parse(&json!({ "auth": { "vault": "k" } })).unwrap().unwrap().how, How::Bearer);
156        let h = parse(&json!({ "auth": { "vault": "k", "as": "header:X-Api-Key" } })).unwrap().unwrap();
157        assert_eq!(h.how.name().as_str(), "x-api-key");
158    }
159
160    #[test]
161    fn auth_that_is_not_understood_is_refused_not_ignored() {
162        assert!(parse(&json!({ "auth": "api-key-github" })).is_err());
163        assert!(parse(&json!({ "auth": { "vault": "k", "as": "basic" } })).is_err());
164        assert!(parse(&json!({ "auth": { "vault": "k", "as": "header:" } })).is_err());
165        assert!(parse(&json!({ "auth": { "vault": "k", "as": "header:bad name" } })).is_err());
166        assert!(parse(&json!({ "auth": { "vault": "k", "extra": 1 } })).is_err());
167        for name in ["Host", "content-length", "Transfer-Encoding", "Connection", "Proxy-Authorization"] {
168            assert!(parse(&json!({ "auth": { "vault": "k", "as": format!("header:{name}") } })).is_err(), "{name}");
169        }
170    }
171
172    #[test]
173    fn the_header_holds_the_value_and_is_sensitive() {
174        let v = How::Bearer.value("sk-test-1234").unwrap();
175        assert_eq!(v.to_str().unwrap(), "Bearer sk-test-1234");
176        assert!(v.is_sensitive());
177        assert_eq!(format!("{v:?}"), "Sensitive");
178        assert_eq!(How::Bearer.name(), reqwest::header::AUTHORIZATION);
179        let h = How::Header(HeaderName::from_static("x-api-key")).value("sk-test-1234").unwrap();
180        assert_eq!(h.to_str().unwrap(), "sk-test-1234");
181    }
182
183    #[test]
184    fn a_value_a_header_cannot_hold_is_refused_without_naming_it() {
185        let err = How::Bearer.value("sk-test\r\nX-Evil: 1").unwrap_err();
186        assert!(!err.contains("sk-test") && !err.contains("X-Evil"), "{err}");
187    }
188
189    #[test]
190    fn the_node_cannot_set_the_credentials_header_too() {
191        let headers: HashMap<String, String> = [("authorization".to_string(), "x".to_string()), ("Accept".to_string(), "y".to_string())].into();
192        assert!(sets_it_too(&headers, &reqwest::header::AUTHORIZATION));
193        assert!(sets_it_too(&[(" Authorization ".to_string(), String::new())].into(), &reqwest::header::AUTHORIZATION));
194        assert!(!sets_it_too(&headers, &HeaderName::from_static("x-api-key")));
195    }
196
197    #[test]
198    fn the_site_is_written_out_and_https() {
199        assert_eq!(site("https://api.example.com/v1/{{var.x}}", "https://api.example.com/v1/7").unwrap(), "https://api.example.com");
200        assert_eq!(site("https://API.example.com:8443/x", "https://api.example.com:8443/x").unwrap(), "https://api.example.com:8443");
201        assert_eq!(site("https://api.example.com", "https://api.example.com/").unwrap(), "https://api.example.com");
202        assert_eq!(site("https://api.example.com?q={{var.q}}", "https://api.example.com/?q=1").unwrap(), "https://api.example.com");
203        assert!(site("http://api.example.com/x", "http://api.example.com/x").is_err());
204        assert!(site("{{var.base}}/x", "https://api.example.com/x").is_err());
205    }
206
207    #[test]
208    fn nothing_from_a_run_can_pick_or_change_the_site() {
209        // A reference in the host, in the port, or standing for the whole of it.
210        assert!(site("https://{{var.host}}/x", "https://api.example.com/x").is_err());
211        assert!(site("https://api.example.com:{{var.port}}/x", "https://api.example.com:443/x").is_err());
212        assert!(site("https://api.{{var.tld}}/x", "https://api.example.com/x").is_err());
213        assert!(site("https://{{trigger.url}}", "https://evil.example.net").is_err());
214        // A user name that makes the real host the part after the @.
215        assert!(site("https://api.example.com@evil.example.net/x", "https://api.example.com@evil.example.net/x").is_err());
216        assert!(site("https://api.example.com\\@evil.example.net/x", "https://evil.example.net/x").is_err());
217        // The path can be a run's value; a path that tries to leave the site stays on it, or is refused.
218        assert_eq!(site("https://api.example.com/{{var.p}}", "https://api.example.com//evil.example.net/x").unwrap(), "https://api.example.com");
219        assert!(site("https://api.example.com/{{var.p}}", "https://evil.example.net/x").is_err());
220        // The host written out can't be a different one once resolved (the check is on the parsed URLs).
221        assert!(site("https://api.example.com/x", "https://api.example.com.evil.example.net/x").is_err());
222        assert!(site("https://api.example.com/x", "https://user:pass@api.example.com/x").is_err());
223    }
224
225    #[test]
226    fn a_resolved_address_that_is_a_nested_blob_is_refused() {
227        let deep = format!("{}https://api.example.com/x", "blob:".repeat(50_000));
228        for resolved in ["blob:blob:https://api.example.com/x", deep.as_str()] {
229            assert!(site("https://api.example.com/x", resolved).is_err(), "{}", &resolved[..resolved.len().min(40)]);
230        }
231    }
232}