Skip to main content

agentmux_srv/server/
drone_vault.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A drone's API node calling a site with a Vault entry's value: the one place a drone gets a
5//! credential, the same way a command does (`shell_secrets`): the person is asked the first time,
6//! "Always" is a grant, the value leaves its sealed row only after that, and the response is
7//! cleaned of it before anything is kept (Drone real-world jobs spec, the Vault slice of phase 3).
8//!
9//! The drone is the actor, as `drone:<id>`. It is never a named agent, so a Vault open to named
10//! agents only is refused to it as if the entry weren't there; a Vault open to all agents is not.
11//! A grant is for one drone, one site (its origin) and one part of one entry: editing the node's
12//! URL to another site, or the node to use another entry, asks again.
13//!
14//! Silence is a no: a drone often runs unattended, so the Vault's "goes ahead after 30 s" rule does
15//! not apply to it ([`uses::goes_ahead`]). The run fails that block and the next run asks again.
16//! A key that records the site or service it was saved for is bound to it: sent anywhere else, the
17//! card says so and offers Allow once only, and an earlier grant doesn't count.
18
19use std::time::Duration;
20
21use crate::backend::vault::scrub::{self, Scrubber};
22use crate::backend::vault::uses::{self, Ended, UseRequest};
23use crate::backend::vault::{self, FillTarget};
24
25use super::AppState;
26
27/// Under the call's own timeout, so a drone waiting for the person doesn't hold a run for long.
28const ANSWER_WAIT: Duration = Duration::from_secs(120);
29/// The Activity line's action.
30const CALLED: &str = "called an API";
31const NOT_SENT: &str = "the request was not sent";
32/// The Activity outcome of a use nobody answered, which a drone's never goes ahead on.
33const NOT_ANSWERED: &str = "not answered";
34
35/// The value to send and what takes it back out of what comes back.
36pub(crate) struct Resolved {
37    pub value: zeroize::Zeroizing<String>,
38    pub scrubber: Scrubber,
39}
40
41/// The actor a drone's use of the Vault is recorded and granted under.
42pub(crate) fn actor(drone_id: &str) -> String {
43    // The whole id: two drones whose ids share a beginning are two actors, with a grant each.
44    format!("{}{drone_id}", uses::DRONE_ACTOR)
45}
46
47/// The key a drone's grant is stored under, in the grants table that web forms and commands use:
48/// `drone:<id>:<origin>:<part>` is neither a site's origin nor a command's key. It names the part
49/// and the site, so a grant for one site's call is not one for another's.
50pub(crate) fn grant_key(drone_id: &str, origin: &str, part: &str) -> String {
51    format!("{}:{origin}:{part}", actor(drone_id))
52}
53
54/// Whether a call may be given this part of this kind of entry: an API key's value or a login's
55/// password. An ID, a card, a bank account, a note or a login's one-time code is never an
56/// Authorization header, and a drone has nobody to ask for them.
57pub(crate) fn part_allowed(kind: &str, part: &str) -> Result<(), String> {
58    match (kind, part) {
59        ("api-key", "value") | ("login", "password") => Ok(()),
60        _ => Err(format!("a drone's API call can use an api-key entry's value or a login's password, not the {part} of a {kind} entry")),
61    }
62}
63
64/// The entry text of a node: `entry` or `entry.part`, never a `{{reference}}` (the entry is the
65/// graph's, never a run's input) and never a version (`@previous`, `@pending` are a command's).
66pub(crate) fn entry_text_ok(entry: &str) -> Result<&str, String> {
67    let entry = entry.trim();
68    if entry.is_empty() {
69        return Err("the API block's auth names no Vault entry".into());
70    }
71    if entry.contains("{{") || entry.contains("}}") {
72        return Err("the API block's Vault entry is written in the drone, not taken from a {{...}} value".into());
73    }
74    if entry.contains('@') {
75        return Err("the API block takes the entry's current value: no @version".into());
76    }
77    Ok(entry)
78}
79
80/// Whether the site an entry says it was saved for is the one the drone sends it to.
81#[derive(Debug, Clone, PartialEq)]
82pub(crate) enum Binding {
83    /// The entry records no site or service: nothing to compare.
84    Unrecorded,
85    Matches,
86    /// It was saved for `recorded`, as the person wrote it.
87    Differs { recorded: String },
88}
89
90/// The recorded site or service of an entry's plain fields: an api-key's `service`, a login's `site`.
91fn recorded_of(kind: &str, fields: &str) -> String {
92    let key = if kind == "login" { "site" } else { "service" };
93    serde_json::from_str::<serde_json::Value>(fields).ok().and_then(|v| v.get(key).and_then(|x| x.as_str()).map(|x| x.trim().to_string())).unwrap_or_default()
94}
95
96/// The host a recorded value names, when it names one: a URL (`https://api.github.com/x`) or a bare host name
97/// (`api.github.com`). A service's name (`GitHub`, `Acme Billing`) names none.
98fn host_in(recorded: &str) -> Option<String> {
99    let text = recorded.trim().trim_end_matches('/');
100    let candidate = text.split("://").nth(1).unwrap_or(text);
101    let host = candidate.split(['/', '?', '#']).next().unwrap_or("").split(':').next().unwrap_or("").trim().trim_start_matches("www.").to_ascii_lowercase();
102    let host_like = !host.is_empty() && host.contains('.') && host.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.');
103    host_like.then_some(host)
104}
105
106/// Whether the entry's recorded `site` fits `origin` (`https://host[:port]`): a recorded host fits that host and its
107/// subdomains; a recorded name (`GitHub`) fits a host whose registrable name is it (`api.github.com`, not
108/// `github.evil.example`). With no public-suffix list the name check is the host's second label from the end, so
109/// `shop.example.co.uk` doesn't fit `Example`: a refusal to bind, never a wrong yes.
110pub(crate) fn binding(recorded: &str, origin: &str) -> Binding {
111    let recorded = recorded.trim();
112    if recorded.is_empty() {
113        return Binding::Unrecorded;
114    }
115    let host = reqwest::Url::parse(origin).ok().and_then(|u| u.host_str().map(str::to_ascii_lowercase)).unwrap_or_default();
116    let fits = match host_in(recorded) {
117        Some(want) => host == want || host.ends_with(&format!(".{want}")),
118        None => {
119            let name: String = recorded.chars().filter(|c| c.is_ascii_alphanumeric()).collect::<String>().to_ascii_lowercase();
120            let labels: Vec<&str> = host.split('.').collect();
121            !name.is_empty() && labels.len() >= 2 && labels[labels.len() - 2] == name
122        }
123    };
124    if fits {
125        Binding::Matches
126    } else {
127        Binding::Differs { recorded: recorded.to_string() }
128    }
129}
130
131/// The host of `origin`, for the card.
132fn host_of(origin: &str) -> String {
133    reqwest::Url::parse(origin).ok().and_then(|u| u.host_str().map(str::to_string)).unwrap_or_else(|| origin.to_string())
134}
135
136/// Whether a use that has no "Always" grant may ask the person.
137#[derive(Clone, Copy, PartialEq, Eq, Debug)]
138pub(crate) enum Asking {
139    /// A run the person can see: the first use asks (the API block).
140    Person,
141    /// A background poll: nobody is at the desk, and a poll every few minutes would stack up cards that silence then
142    /// denies, so with no grant it fails at once, with no card and no line in the Vault's Activity. The grant is given
143    /// where a person is: a manual run of the drone, answered "Always".
144    Never,
145}
146
147/// How many polls a Vault Activity line stands for: one line per this long, with the count in it.
148const POLL_LINE_EVERY_MS: i64 = 3_600_000;
149
150/// When a poll last wrote its Activity line, and how many polls since, per drone and entry.
151fn poll_lines() -> &'static std::sync::Mutex<std::collections::HashMap<(String, String), (i64, u32)>> {
152    static LINES: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<(String, String), (i64, u32)>>> = std::sync::OnceLock::new();
153    LINES.get_or_init(Default::default)
154}
155
156/// Counts a poll's use of `entry` and says whether this one writes the Activity line, and for how many polls.
157fn poll_line_due(drone_id: &str, entry_id: &str, now_ms: i64) -> Option<u32> {
158    let mut map = poll_lines().lock().unwrap_or_else(|p| p.into_inner());
159    let slot = map.entry((drone_id.to_string(), entry_id.to_string())).or_insert((i64::MIN, 0));
160    slot.1 += 1;
161    if now_ms.saturating_sub(slot.0) < POLL_LINE_EVERY_MS {
162        return None;
163    }
164    let polls = slot.1;
165    *slot = (now_ms, 0);
166    Some(polls)
167}
168
169/// What to say when the entry was saved for another site than `origin`; `None` when it fits or says no site.
170async fn site_mismatch(state: &AppState, target: &FillTarget, drone_id: &str, origin: &str) -> Option<String> {
171    let (store, id) = (state.identity_store.clone(), target.id.clone());
172    let fields = tokio::task::spawn_blocking(move || store.vault_get(&id).ok().flatten().map(|r| r.fields).unwrap_or_default()).await.unwrap_or_default();
173    match binding(&recorded_of(target.kind, &fields), origin) {
174        Binding::Differs { recorded } => Some(format!("This key was saved for {recorded}; the drone {drone_id} sends it to {}", host_of(origin))),
175        _ => None,
176    }
177}
178
179/// Why a poll, which can't ask a person, is not sent the key: no "Always" yet, or the key is for another site.
180fn poll_cannot_ask(mismatch: Option<&str>, drone_id: &str, label: &str, origin: &str) -> String {
181    match mismatch {
182        Some(why) => format!("{why}: a poll can't ask, so it doesn't send it; run the drone by hand and choose Allow once"),
183        None => format!("the drone {drone_id} has no \"Always\" for {label} at {origin}, and a poll can't ask: run the drone by hand once, answer \"Always\", then the poll goes ahead"),
184    }
185}
186
187/// Resolves, asks for and reads the entry `entry` for a call to `origin` by drone `drone_id`.
188/// Nothing is read and nothing is sent unless this returns `Ok`.
189pub(crate) async fn resolve(state: &AppState, drone_id: &str, entry: &str, origin: &str) -> Result<Resolved, String> {
190    resolve_with(state, drone_id, entry, origin, Asking::Person).await
191}
192
193/// [`resolve`], saying whether a use with no grant may ask the person.
194pub(crate) async fn resolve_with(state: &AppState, drone_id: &str, entry: &str, origin: &str, asking: Asking) -> Result<Resolved, String> {
195    let entry = entry_text_ok(entry)?.to_string();
196    let who = actor(drone_id);
197    let (store, e, a) = (state.identity_store.clone(), entry, who.clone());
198    let target: FillTarget = tokio::task::spawn_blocking(move || vault::command_target(&store, &e, Some(&a)))
199        .await
200        .map_err(|e| e.to_string())??;
201    part_allowed(target.kind, target.part)?;
202
203    // The site or service the entry says it was saved for, against the one this call goes to.
204    let mismatch = site_mismatch(state, &target, drone_id, origin).await;
205
206    let note = mismatch.clone().unwrap_or_default();
207    let record = |outcome: &str| {
208        vault::record_line(
209            &state.identity_store,
210            vault::Line { entry_id: &target.id, label: &target.label, actor: &who, action: CALLED, target: origin, outcome, reason: &note },
211        );
212        // Every window's Vault pane shows the new line of the record.
213        super::vault_handlers::publish(state);
214    };
215
216    // An earlier "Always" doesn't cover a key that is now for another site: the card asks again.
217    let key = grant_key(drone_id, origin, target.part);
218    let granted = if mismatch.is_some() {
219        false
220    } else {
221        let (store, id, k) = (state.identity_store.clone(), target.id.clone(), key.clone());
222        tokio::task::spawn_blocking(move || store.vault_grant_check(&id, &k).unwrap_or(false)).await.unwrap_or(false)
223    };
224    if !granted && asking == Asking::Never {
225        // Nothing is asked and nothing is written to the Activity: a poll that runs every few minutes would fill it.
226        return Err(poll_cannot_ask(mismatch.as_deref(), drone_id, &target.label, origin));
227    }
228    if !granted {
229        let request = UseRequest {
230            id: uuid::Uuid::new_v4().to_string(),
231            agent: who.clone(),
232            entry_id: target.id.clone(),
233            entry_label: target.label.clone(),
234            what: target.what.clone(),
235            origin: origin.to_string(),
236            field: "an authorization header".into(),
237            // Only Allow once for a key saved for another site.
238            offer_always: mismatch.is_none(),
239            reason: mismatch.clone().unwrap_or_else(|| format!("it is the first time the drone {drone_id} calls {origin} with this entry")),
240            kind: target.kind.to_string(),
241            requested_ms: agentmux_common::time::now_ms_u64(),
242            ..Default::default()
243        };
244        let headline = format!("The drone {drone_id} wants to call {origin} with your {}", target.what);
245        // No pane of its own to answer in: asked in every window.
246        let (ended, _) = super::vault_ask::ask(state, "", request, ANSWER_WAIT, &headline).await;
247        if !ended.allowed() {
248            // Silence is a no for a drone ([`uses::goes_ahead`]): said so, not as the person's refusal.
249            if matches!(ended, Ended::Expired | Ended::NoAnswer) {
250                record(NOT_ANSWERED);
251                return Err(format!("nobody answered the Vault request to send {} to {origin}, and a drone's first use of a site needs a yes: {NOT_SENT}; the next run asks again", target.label));
252            }
253            record(ended.outcome());
254            return Err(ended.refusal(NOT_SENT));
255        }
256        if ended == Ended::Always && mismatch.is_none() {
257            let (store, id, k, created) = (state.identity_store.clone(), target.id.clone(), key, target.created_at);
258            let _ = tokio::task::spawn_blocking(move || store.vault_grant_add(&id, &k, agentmux_common::time::now_ms(), created)).await;
259        }
260    }
261
262    // Allowed: the value leaves its sealed row now, into this one request.
263    let (store, t) = (state.identity_store.clone(), target.clone());
264    let value = match tokio::task::spawn_blocking(move || vault::value_for_command(&store, &t)).await {
265        Ok(Ok(v)) => v,
266        Ok(Err(e)) => {
267            record("failed");
268            return Err(e);
269        }
270        Err(e) => return Err(e.to_string()),
271    };
272    if value.chars().count() < scrub::MIN_LEN {
273        record("failed");
274        return Err(format!("{} is too short to send: the response couldn't be cleaned of it", target.label));
275    }
276    if asking == Asking::Never {
277        // One line an hour for a poll, with the number of polls it stands for; never the value.
278        if let Some(polls) = poll_line_due(drone_id, &target.id, agentmux_common::time::now_ms()) {
279            let reason = format!("a poll, {polls} time(s) since the last line");
280            vault::record_line(
281                &state.identity_store,
282                vault::Line { entry_id: &target.id, label: &target.label, actor: &who, action: CALLED, target: origin, outcome: "done", reason: &reason },
283            );
284            super::vault_handlers::publish(state);
285        }
286    } else {
287        record("done");
288    }
289    let (store, id) = (state.identity_store.clone(), target.id.clone());
290    let _ = tokio::task::spawn_blocking(move || store.vault_touch(&id, agentmux_common::time::now_ms())).await;
291    let scrubber = Scrubber::new(&[(target.id.clone(), value.to_string())]);
292    Ok(Resolved { value, scrubber })
293}
294
295#[cfg(test)]
296mod unit_tests {
297    use super::*;
298
299    #[test]
300    fn a_drone_is_its_own_actor_and_never_a_named_agent() {
301        assert_eq!(actor("nightly"), "drone:nightly");
302        // Two drones whose ids share a long beginning are two actors, and a grant is for one.
303        let (a, b) = (format!("{}a", "x".repeat(80)), format!("{}b", "x".repeat(80)));
304        assert_ne!(actor(&a), actor(&b));
305        assert_ne!(grant_key(&a, "https://api.example.com", "value"), grant_key(&b, "https://api.example.com", "value"));
306    }
307
308    #[test]
309    fn a_grant_is_for_one_drone_one_site_and_one_part() {
310        let k = grant_key("nightly", "https://api.example.com", "value");
311        assert_eq!(k, "drone:nightly:https://api.example.com:value");
312        assert_ne!(k, grant_key("nightly", "https://api.example.org", "value"));
313        assert_ne!(k, grant_key("other", "https://api.example.com", "value"));
314        assert_ne!(k, grant_key("nightly", "https://api.example.com", "password"));
315        // Neither a site's origin (a web form's grant) nor a command's key.
316        assert!(!k.starts_with("command:") && !k.starts_with("http"));
317    }
318
319    #[test]
320    fn only_an_api_keys_value_or_a_logins_password_may_go_in_a_header() {
321        assert!(part_allowed("api-key", "value").is_ok());
322        assert!(part_allowed("login", "password").is_ok());
323        assert!(part_allowed("login", "totp").is_err());
324        assert!(part_allowed("login", "username").is_err());
325        assert!(part_allowed("card", "number").is_err());
326        assert!(part_allowed("note", "value").is_err());
327        assert!(part_allowed("api-key", "other").is_err());
328    }
329
330    #[test]
331    fn the_entry_is_written_in_the_drone() {
332        assert_eq!(entry_text_ok(" api-key-stripe ").unwrap(), "api-key-stripe");
333        assert_eq!(entry_text_ok("login-bank.password").unwrap(), "login-bank.password");
334        assert!(entry_text_ok("").is_err());
335        assert!(entry_text_ok("  ").is_err());
336        assert!(entry_text_ok("{{trigger.entry}}").is_err());
337        assert!(entry_text_ok("api-key-stripe@previous").is_err());
338        assert!(entry_text_ok("api-key-stripe@pending").is_err());
339    }
340}
341
342#[cfg(test)]
343#[path = "drone_vault/tests.rs"]
344mod tests;