Skip to main content

agentmux_srv_core/backend/vault/
requests.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Agents' requests for a new Vault entry, waiting for the person
5//! (docs/specs/SPEC_VAULT_PANE_AGENTS_USE_SECRETS_UNSEEN_2026_10_19.md ยง5.4).
6//!
7//! `Vault` `request` asks here; the pane shows each request and the person
8//! fills the entry in or dismisses it, through the host. The agent hears the
9//! new entry's id, never its value. An agent can ask; it can never answer.
10//!
11//! An agent's session can end while it waits (a restart, a resume, an upgrade),
12//! and the agent then asks again. The same verified agent asking for the same
13//! kind and label is that retry, so it joins the request already open, or gets
14//! the entry the person already saved, rather than opening a second form. A
15//! dismissed form isn't kept: asking again after it opens a new one.
16
17use std::sync::{Mutex, OnceLock};
18
19use serde::Serialize;
20use tokio::sync::oneshot;
21
22#[derive(Debug, Clone, PartialEq, Serialize, ts_rs::TS)]
23#[ts(export, export_to = "../../../frontend/types/rpc/")]
24pub struct VaultRequest {
25    pub id: String,
26    /// The agent that asked, as its verified identity names it.
27    pub agent: String,
28    pub kind: String,
29    pub label: String,
30    /// The agent's reason, shown to the person.
31    pub why: String,
32    #[ts(type = "number")]
33    pub requested_ms: u64,
34    /// The asking agent's own pane, where the person answers it; empty when
35    /// the agent's identity didn't verify.
36    pub block_id: String,
37    /// The Vault the agent asked the entry to go in (its id), if it named one: the form
38    /// starts on it. Empty when it didn't.
39    pub vault: String,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq)]
43pub enum Answer {
44    /// The person saved it as this entry.
45    Created(String),
46    Declined,
47}
48
49/// What asking gave: a request to wait on, or the answer an earlier ask of the
50/// same entry already got. Each carries the request's id.
51#[derive(Debug)]
52pub enum Asked {
53    /// A new request (`new`), or the one already open for this agent, kind and label.
54    Waiting { request_id: String, new: bool, answer: oneshot::Receiver<Answer> },
55    Answered { request_id: String, answer: Answer },
56}
57
58struct Pending {
59    req: VaultRequest,
60    /// Whether a retry may join it: only a verified agent's request.
61    joinable: bool,
62    waiters: Vec<oneshot::Sender<Answer>>,
63}
64
65struct Answered {
66    req: VaultRequest,
67    answer: Answer,
68    at_ms: u64,
69}
70
71/// Both lists under one lock, so a retry never falls between a request leaving
72/// `pending` and its answer reaching `answered`.
73#[derive(Default)]
74struct Lists {
75    pending: Vec<Pending>,
76    answered: Vec<Answered>,
77}
78
79#[derive(Default)]
80pub struct Requests {
81    lists: Mutex<Lists>,
82}
83
84pub fn requests() -> &'static Requests {
85    static REQUESTS: OnceLock<Requests> = OnceLock::new();
86    REQUESTS.get_or_init(Requests::default)
87}
88
89/// At most this many requests wait at once; the oldest is declined.
90const MAX_PENDING: usize = 16;
91const MAX_AGE_MS: u64 = 60 * 60 * 1000;
92/// Most answers kept for a retry to find.
93const MAX_ANSWERED: usize = 64;
94
95fn same(a: &VaultRequest, b: &VaultRequest) -> bool {
96    a.agent == b.agent && a.kind == b.kind && a.label.trim().to_lowercase() == b.label.trim().to_lowercase()
97}
98
99fn now() -> u64 {
100    agentmux_common::time::now_ms_u64()
101}
102
103impl Requests {
104    /// Asks the person for `req`. `verified` says the agent's identity was proven:
105    /// only then is an ask for the same kind and label taken as a retry, since
106    /// every unverified caller shares one name.
107    pub fn ask(&self, req: VaultRequest, verified: bool) -> Asked {
108        let mut lists = self.lists.lock().unwrap_or_else(|p| p.into_inner());
109        let now = now();
110        lists.answered.retain(|a| now.saturating_sub(a.at_ms) < MAX_AGE_MS);
111        if verified {
112            if let Some(a) = lists.answered.iter().rev().find(|a| same(&a.req, &req)) {
113                return Asked::Answered { request_id: a.req.id.clone(), answer: a.answer.clone() };
114            }
115        }
116        let (tx, rx) = oneshot::channel();
117        let pending = &mut lists.pending;
118        pending.retain(|p| now.saturating_sub(p.req.requested_ms) < MAX_AGE_MS);
119        if verified {
120            if let Some(open) = pending.iter_mut().find(|p| p.joinable && same(&p.req, &req)) {
121                open.waiters.push(tx);
122                return Asked::Waiting { request_id: open.req.id.clone(), new: false, answer: rx };
123            }
124        }
125        if pending.len() >= MAX_PENDING {
126            let oldest = pending.remove(0);
127            for w in oldest.waiters {
128                let _ = w.send(Answer::Declined);
129            }
130        }
131        let request_id = req.id.clone();
132        pending.push(Pending { req, joinable: verified, waiters: vec![tx] });
133        Asked::Waiting { request_id, new: true, answer: rx }
134    }
135
136    /// The person's answer; false if nothing waits under `id`. Every agent waiting
137    /// on it hears it, and a retry within the hour finds the entry it made. A
138    /// dismissal isn't kept, so the agent can ask for the form again.
139    pub fn answer(&self, id: &str, answer: Answer) -> bool {
140        let mut lists = self.lists.lock().unwrap_or_else(|p| p.into_inner());
141        let Some(i) = lists.pending.iter().position(|p| p.req.id == id) else {
142            return false;
143        };
144        let open = lists.pending.remove(i);
145        for w in open.waiters {
146            let _ = w.send(answer.clone());
147        }
148        if open.joinable && matches!(answer, Answer::Created(_)) {
149            if lists.answered.len() >= MAX_ANSWERED {
150                lists.answered.remove(0);
151            }
152            lists.answered.push(Answered { req: open.req, answer, at_ms: now() });
153        }
154        true
155    }
156
157    /// The entry `id` was deleted: a retry must not be told it exists.
158    pub fn forget_entry(&self, id: &str) {
159        let mut lists = self.lists.lock().unwrap_or_else(|p| p.into_inner());
160        lists.answered.retain(|a| a.answer != Answer::Created(id.to_string()));
161    }
162
163    pub fn get(&self, id: &str) -> Option<VaultRequest> {
164        let lists = self.lists.lock().unwrap_or_else(|p| p.into_inner());
165        lists.pending.iter().find(|p| p.req.id == id).map(|p| p.req.clone())
166    }
167
168    /// The requests still open. One stays after its agent stops waiting (the
169    /// agent finds the entry with `list`, or by asking again), until it is an hour old.
170    pub fn list(&self) -> Vec<VaultRequest> {
171        let mut lists = self.lists.lock().unwrap_or_else(|p| p.into_inner());
172        let now = now();
173        lists.pending.retain(|p| now.saturating_sub(p.req.requested_ms) < MAX_AGE_MS);
174        lists.pending.iter().map(|p| p.req.clone()).collect()
175    }
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181
182    fn req(id: &str) -> VaultRequest {
183        VaultRequest {
184            vault: String::new(),
185            id: id.into(),
186            agent: "Agent1".into(),
187            kind: "api-key".into(),
188            label: "Stripe".into(),
189            why: "tests".into(),
190            requested_ms: now(),
191            block_id: "pane-1".into(),
192        }
193    }
194
195    fn waiting(a: Asked) -> (String, bool, oneshot::Receiver<Answer>) {
196        match a {
197            Asked::Waiting { request_id, new, answer } => (request_id, new, answer),
198            other => panic!("expected a wait, got {other:?}"),
199        }
200    }
201
202    #[tokio::test]
203    async fn an_answer_reaches_the_waiting_agent_once() {
204        let r = Requests::default();
205        let (id, new, rx) = waiting(r.ask(req("q1"), true));
206        assert!(new);
207        assert_eq!(id, "q1");
208        assert_eq!(r.list().len(), 1);
209        assert!(r.answer("q1", Answer::Created("api-key-stripe".into())));
210        assert!(!r.answer("q1", Answer::Declined), "answered already");
211        assert_eq!(rx.await.unwrap(), Answer::Created("api-key-stripe".into()));
212        assert!(r.list().is_empty());
213    }
214
215    #[test]
216    fn a_request_outlives_its_wait_but_not_an_hour() {
217        let r = Requests::default();
218        drop(r.ask(req("q1"), true));
219        assert_eq!(r.list().len(), 1, "the person can still answer it");
220        assert!(r.answer("q1", Answer::Declined), "answering a request nobody waits on is fine");
221        let mut old = req("q2");
222        old.requested_ms -= MAX_AGE_MS + 1;
223        drop(r.ask(old, true));
224        assert!(r.list().is_empty());
225    }
226
227    // QTest, 2026-10-27: three asks for one key, each cut off when the session ended,
228    // opened three forms. A retry now joins the one already open.
229    #[tokio::test]
230    async fn asking_again_for_the_same_entry_joins_the_open_request() {
231        let r = Requests::default();
232        let (first, _, rx1) = waiting(r.ask(req("q1"), true));
233        let mut again = req("q2");
234        again.label = "  stripe ".into();
235        let (second, new, rx2) = waiting(r.ask(again, true));
236        assert_eq!(second, first);
237        assert!(!new);
238        assert_eq!(r.list().len(), 1, "no second form");
239        r.answer("q1", Answer::Created("api-key-stripe".into()));
240        assert_eq!(rx1.await.unwrap(), Answer::Created("api-key-stripe".into()));
241        assert_eq!(rx2.await.unwrap(), Answer::Created("api-key-stripe".into()));
242    }
243
244    #[test]
245    fn asking_again_after_the_answer_gets_the_answer() {
246        let r = Requests::default();
247        drop(r.ask(req("q1"), true));
248        r.answer("q1", Answer::Created("api-key-stripe".into()));
249        match r.ask(req("q3"), true) {
250            Asked::Answered { request_id, answer } => {
251                assert_eq!(request_id, "q1");
252                assert_eq!(answer, Answer::Created("api-key-stripe".into()));
253            }
254            other => panic!("expected the earlier answer, got {other:?}"),
255        }
256        assert!(r.list().is_empty(), "nothing new is opened");
257    }
258
259    #[test]
260    fn a_dismissed_form_can_be_asked_for_again() {
261        let r = Requests::default();
262        drop(r.ask(req("q1"), true));
263        r.answer("q1", Answer::Declined);
264        assert!(waiting(r.ask(req("q2"), true)).1, "a new form, not the old no");
265    }
266
267    #[test]
268    fn a_deleted_entry_is_not_handed_to_a_retry() {
269        let r = Requests::default();
270        drop(r.ask(req("q1"), true));
271        r.answer("q1", Answer::Created("api-key-stripe".into()));
272        r.forget_entry("api-key-stripe");
273        assert!(waiting(r.ask(req("q2"), true)).1, "the entry is gone: ask the person again");
274    }
275
276    #[test]
277    fn another_entry_or_another_agent_is_a_new_request() {
278        let r = Requests::default();
279        drop(r.ask(req("q1"), true));
280        let mut other_label = req("q2");
281        other_label.label = "Stripe live".into();
282        let mut other_agent = req("q3");
283        other_agent.agent = "Agent2".into();
284        let mut other_kind = req("q4");
285        other_kind.kind = "login".into();
286        for q in [other_label, other_agent, other_kind] {
287            assert!(waiting(r.ask(q, true)).1, "a different entry gets its own request");
288        }
289        assert_eq!(r.list().len(), 4);
290    }
291
292    #[test]
293    fn unverified_callers_never_join_or_reuse() {
294        let r = Requests::default();
295        drop(r.ask(req("q1"), false));
296        assert!(waiting(r.ask(req("q2"), false)).1);
297        assert!(waiting(r.ask(req("q3"), true)).1, "a verified agent doesn't join an unverified request");
298        r.answer("q1", Answer::Created("x".into()));
299        assert!(matches!(r.ask(req("q5"), false), Asked::Waiting { new: true, .. }), "an unverified answer isn't kept for reuse");
300    }
301}