Skip to main content

agentmux_srv/server/
vault_handlers.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Vault's routes (docs/specs/SPEC_VAULT_PANE_AGENTS_USE_SECRETS_UNSEEN_2026_10_19.md §5.4).
5//!
6//! - `POST /api/v1/host/vault`: everything the pane does, relayed by the
7//!   host. `X-Host-Token` must be the host's IPC token, which agents never
8//!   see: the instance auth key every agent holds isn't enough, so no agent
9//!   can read a tail, or plant, change or delete an entry.
10//! - `GET /api/v1/vault`: for agents, each entry's id, label, kind and
11//!   section. No value, tail, field or grant.
12//! - `POST /api/v1/vault/request`: an agent asks the person for a new entry
13//!   and waits for the answer: the new entry's id, or declined.
14//! - `POST /api/v1/vault/generate`: an agent creates an entry whose value the
15//!   Vault makes; it gets the id back, never the value.
16
17use std::time::Duration;
18
19use axum::extract::State;
20use axum::http::{HeaderMap, StatusCode};
21use axum::response::{IntoResponse, Response};
22use axum::Json;
23use serde::Deserialize;
24use serde_json::{json, Value};
25
26use crate::backend::storage::vault::PERSONAL_VAULT;
27use crate::backend::vault::{self, requests, EntryChange, NewEntry};
28
29use super::AppState;
30
31/// How long one "a Vault pane is showing" note lasts: the pane renews it
32/// every 10 seconds while shown, so a crashed window doesn't hold it.
33const ON_SCREEN_MS: i64 = 30_000;
34
35const DEFAULT_WAIT: Duration = Duration::from_secs(300);
36const MAX_WAIT: Duration = Duration::from_secs(600);
37
38fn error(status: StatusCode, message: impl Into<String>) -> Response {
39    (status, Json(json!({ "error": message.into() }))).into_response()
40}
41
42/// The host's export to the file the person chose: the entries named (all when none is), in the format asked for.
43/// The answer's `links_only` is what was written, not what was asked for: the dialog says "no value" on this word.
44fn export(store: &crate::backend::storage::store::Store, body: &Value) -> Result<Value, String> {
45    let out = export_to(store, body)?;
46    Ok(json!({ "count": out.count, "file_name": out.file_name, "links_only": out.links_only }))
47}
48
49fn export_to(store: &crate::backend::storage::store::Store, body: &Value) -> Result<vault::transfer::ExportResult, String> {
50    let path = file_path(body)?;
51    let pass = body.get("passphrase").and_then(Value::as_str).unwrap_or("");
52    let ids: Option<Vec<String>> = body.get("ids").and_then(|v| serde_json::from_value(v.clone()).ok());
53    // The linked entries only, in a `.vault` file with no value in it: no other format carries a link.
54    let links_only = body.get("links_only").and_then(Value::as_bool).unwrap_or(false);
55    // `.vault` (an age file), or a KeePass database for the person to take to another manager.
56    match body.get("format").and_then(Value::as_str).unwrap_or("vault") {
57        "vault" if links_only => vault::transfer::export_links(store, ids.as_deref(), pass, &path),
58        other if links_only => Err(format!("the linked entries are exported as a Vault file, not as {other:?}")),
59        "kdbx" => vault::kdbx_export::export(store, ids.as_deref(), pass, &path),
60        "vault" => vault::transfer::export(store, ids.as_deref(), pass, &path),
61        // Unencrypted, for another manager. The host asked the person and the OS first.
62        plain @ ("csv" | "json") => vault::plain_export::export(store, ids.as_deref(), plain, &path),
63        other => Err(format!("unknown export format {other:?}")),
64    }
65}
66
67/// The file the host chose, which must be an absolute path.
68fn file_path(body: &Value) -> Result<std::path::PathBuf, String> {
69    let p = std::path::PathBuf::from(body.get("path").and_then(Value::as_str).unwrap_or(""));
70    if !p.is_absolute() {
71        return Err("a file path is needed".into());
72    }
73    Ok(p)
74}
75
76/// A malformed entry or change, said without serde's own message, which can
77/// quote the value it couldn't read.
78fn shape_error(what: &str) -> String {
79    format!("{what} for the Vault isn't in the expected shape")
80}
81
82/// Tells every UI the Vault or its requests changed. Carries no entry.
83pub(crate) fn publish(state: &AppState) {
84    // A moved agent that waited for a route's key takes the route now that the Vault may hold it.
85    super::needs_key::settle_all(state);
86    publish_change(&state.broker);
87    // A sign-in page already open lists what the Vault holds now.
88    super::browser_signin_fill::refresh_all(state);
89}
90
91/// [`publish`] without the sign-in pages: for a change to an entry no sign-in page lists (an account's key).
92pub(crate) fn publish_change(broker: &crate::backend::mps::Broker) {
93    let event = crate::backend::mps_events::VaultEvent {
94        requests: requests::requests().list(),
95        uses: crate::backend::vault::uses::uses().list(),
96        changed_ms: agentmux_common::time::now_ms_u64(),
97    };
98    broker.publish_event::<crate::backend::mps_events::Vault>(&event, vec![], 0);
99}
100
101/// What AgentMux already keeps in the keychain, managed elsewhere: named,
102/// never read (§5.2 "Kept by AgentMux").
103fn kept(state: &AppState) -> Vec<Value> {
104    let mut out = Vec::new();
105    if let Ok(accounts) = state.id_store.identity_list(None) {
106        for a in accounts {
107            if matches!(a.secret_ref, crate::backend::storage::identities::SecretRef::Keychain { .. }) {
108                let name = if a.display_name.is_empty() { a.name } else { a.display_name };
109                out.push(json!({ "label": name, "what": format!("{} account key", a.provider), "managed_in": "accounts" }));
110            }
111        }
112    }
113    if let Ok(Some(email)) = state.mstore.vault_kept_muxbus_user() {
114        let label = if email.is_empty() { "MuxBus sign-in".to_string() } else { format!("MuxBus sign-in ({email})") };
115        out.push(json!({ "label": label, "what": "cloud messages sign-in", "managed_in": "muxbus" }));
116    }
117    // Sign-ins a browser pane saved in the keychain before the Vault held them, that haven't
118    // moved in yet (the keychain couldn't be read at the last start).
119    if let Ok(signins) = state.identity_store.browser_signins() {
120        for (origin, realm, is_proxy, username) in signins {
121            let site = if realm.is_empty() { origin } else { format!("{origin} ({realm})") };
122            let who = if username.is_empty() { String::new() } else { format!(" for {username}") };
123            let what = if is_proxy { format!("proxy sign-in{who} saved by a browser pane") } else { format!("sign-in{who} saved by a browser pane") };
124            out.push(json!({ "label": site, "what": what, "managed_in": "browser" }));
125        }
126    }
127    for p in crate::backend::tower::peers::Peers::global().list() {
128        out.push(json!({ "label": p.hostname, "what": "paired Tower computer's token", "managed_in": "tower" }));
129    }
130    out
131}
132
133/// Who may use a Vault, from a host op's body: `agents` is `all`, `none`, or `named` with `agent_ids`.
134fn vault_agents(body: &Value) -> Result<vault::vaults::VaultAgents, String> {
135    use vault::vaults::VaultAgents;
136    match body.get("agents").and_then(Value::as_str).unwrap_or("all") {
137        "all" => Ok(VaultAgents::All),
138        "none" => Ok(VaultAgents::None),
139        "named" => {
140            let ids = body.get("agent_ids").and_then(Value::as_array).ok_or("named needs agent_ids, a list of agent ids")?;
141            Ok(VaultAgents::Named(ids.iter().filter_map(Value::as_str).map(str::to_string).collect()))
142        }
143        other => Err(format!("agents is all, none or named, not {other:?}")),
144    }
145}
146
147/// `import_commit`: writes what the person previewed. `vault` (a name or an id) is where the new entries go;
148/// Personal when left out. `profile` is the browser profile a browser export's logins with a site belong to
149/// (`personal` when left out): they go to its sign-in Vault, which is where the browser offers them from.
150fn import_commit(store: &crate::backend::storage::store::Store, body: &Value) -> Result<(Value, bool), String> {
151    let token = body.get("token").and_then(Value::as_str).unwrap_or("");
152    let duplicates: vault::transfer::Duplicates = serde_json::from_value(body.get("duplicates").cloned().unwrap_or(json!("skip")))
153        .map_err(|_| "duplicates is skip, replace or keep_both".to_string())?;
154    let vault = match body.get("vault").and_then(Value::as_str).map(str::trim).filter(|v| !v.is_empty()) {
155        Some(v) => vault::vaults::resolve(store, v, None)?.id,
156        None => crate::backend::storage::vault::PERSONAL_VAULT.to_string(),
157    };
158    let profile = body.get("profile").and_then(Value::as_str);
159    Ok((json!({ "result": vault::transfer::commit_for(store, token, duplicates, &vault, profile)? }), true))
160}
161
162/// A share names an agent this computer has, and a Vault the agent may use: a login in a Vault closed to it would
163/// not be offered, so the person is told to open the Vault first (A5).
164fn check_share_target(state: &AppState, id: &str, agent: &str) -> Result<(), String> {
165    if agent == vault::shares::EVERY_AGENT {
166        return Ok(());
167    }
168    let def = state.mstore.agent_def_get(agent).ok().flatten().ok_or_else(|| format!("no agent {agent} on this computer"))?;
169    let store = &state.identity_store;
170    if vault::vaults::entry_usable(store, id, Some(&def.slug))? || vault::vaults::entry_usable(store, id, Some(&def.id))? {
171        return Ok(());
172    }
173    Err(format!("the Vault this login is in isn't open to {}: open the Vault to it first (in the Vault pane, the Vault's agents), then share the login", def.name))
174}
175
176/// What the pane shows of an entry's shares: each agent it is shared with (or every agent), how often it signed in
177/// with the login and when it last did, and the agents the person can still share it with. Never a value: the sign-ins
178/// are read from the entry's history, and an agent is named by its permanent uid, which is its definition's id.
179fn share_list(state: &AppState, id: &str) -> Result<Value, String> {
180    let store = &state.identity_store;
181    let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
182    let listed = vault::shares::listed(&vault::signins::fields_of(&row));
183    let defs = state.mstore.agent_def_list().map_err(|e| e.to_string())?;
184    let signed_in = store.vault_activity_for_entry(id, &[vault::signins::SIGNED_IN], row.created_at, 1000).map_err(|e| e.to_string())?;
185    let uses: Vec<(String, i64)> = signed_in
186        .iter()
187        .filter(|r| r.outcome == "done")
188        .map(|r| (state.reactive_handler.get_agent(vault::history::agent_of(&r.actor)).and_then(|a| a.uid).unwrap_or_default(), r.at))
189        .collect();
190    let shares: Vec<Value> = listed
191        .iter()
192        .map(|who| {
193            let every = who == vault::shares::EVERY_AGENT;
194            let mine: Vec<i64> = uses.iter().filter(|(uid, _)| every || uid == who).map(|(_, at)| *at).collect();
195            let name = if every { "Every agent".to_string() } else { defs.iter().find(|d| &d.id == who).map_or_else(|| "an agent that is gone".to_string(), |d| d.name.clone()) };
196            // The person's "Always" for a sign-in the browser answers a prompt with, in this agent's own profile (A11).
197            let profile = format!("profile:{}", crate::backend::browser_profiles_store::agent_profile_id(who));
198            let always = !every && vault::shares::prompt_always(store, &row, who, &profile);
199            json!({ "agent": who, "name": name, "uses": mine.len(), "last_used_ms": mine.iter().copied().max().unwrap_or(0), "always": always })
200        })
201        .collect();
202    let agents: Vec<Value> = defs.iter().filter(|d| !listed.contains(&d.id)).map(|d| json!({ "uid": d.id, "name": d.name })).collect();
203    Ok(json!({ "shares": shares, "agents": agents }))
204}
205
206/// The host ops on Vaults and on an entry's earlier values.
207fn entry_ops(state: &AppState, op: &str, body: &Value) -> Result<(Value, bool), String> {
208    let store: &crate::backend::storage::store::Store = &state.identity_store;
209    let s = |k: &str| body.get(k).and_then(Value::as_str).unwrap_or("").to_string();
210    match op {
211        // The person's Vaults: made, renamed or given other agents, deleted when empty, and
212        // an entry moved between them. Only the host: a move can open a value to more agents.
213        "vault_create" => Ok((json!({ "vault": vault::vaults::create(store, &s("name"), vault_agents(body)?)? }), true)),
214        "vault_update" => {
215            vault::vaults::update(store, &s("id"), &s("name"), vault_agents(body)?)?;
216            Ok((json!({}), true))
217        }
218        "vault_delete" => {
219            vault::vaults::remove(store, &s("id"))?;
220            Ok((json!({}), true))
221        }
222        "move_entry" => {
223            vault::vaults::move_entry(store, &s("id"), &s("vault_id"))?;
224            Ok((json!({}), true))
225        }
226        // The person shares a login with an agent's own browser profile, or stops (spec section 5). The agent is
227        // named by its permanent uid, `*` for every agent.
228        "share_add" => {
229            check_share_target(state, &s("id"), &s("agent"))?;
230            Ok((json!({ "changed": vault::shares::add(store, &s("id"), &s("agent"))? }), true))
231        }
232        // Who a login is shared with, and the agents it could still be shared with (the Share dialog and the card's list).
233        "share_list" => Ok((share_list(state, &s("id"))?, false)),
234        "share_remove" => {
235            let changed = vault::shares::remove(store, &s("id"), &s("agent"))?;
236            if changed {
237                super::browser_signin::share_removed(state, &s("id"), &s("agent"));
238                super::vault_prompt_share::share_removed(&s("id"), &s("agent"));
239            }
240            Ok((json!({ "changed": changed }), true))
241        }
242        // The Vault a browser profile saves its sign-ins to and offers them from.
243        "signin_vault" => {
244            vault::vaults::set_signin_vault(store, &s("profile"), &s("vault_id"))?;
245            Ok((json!({}), true))
246        }
247        // The person's pick in Settings of the entry a setting reads its key from: the grant that lets srv
248        // read it for that setting (a setting that only names an entry reads nothing).
249        "allow_setting" => {
250            vault::setting_key::allow(store, &s("entry_id"), &s("setting"), vault::PERSON)?;
251            Ok((json!({}), true))
252        }
253        // The person's check of an entry's machine copy, read with this computer's own AWS and GitHub logins.
254        "check_source" => Ok((json!({ "checked": super::vault_source::person_check(state, &s("id"))? }), true)),
255        // An entry's earlier values, and putting one back (spec §4.4 of the generate spec).
256        "versions" => Ok((json!({ "versions": vault::versions::list(store, &s("id"))? }), false)),
257        // An entry's history, and whether the record of it still holds together (the History dialog).
258        "history" => {
259            let limit = body.get("limit").and_then(Value::as_i64).unwrap_or(500);
260            Ok((json!({ "history": vault::history::history_for(store, &s("id"), vault::history::Asker::Person, limit)? }), false))
261        }
262        "history_check" => Ok((json!({ "chain": vault::history::check(store)? }), false)),
263        // What agents changed that the person has not looked at, one entry's or all (spec: the strip and the History tab), and
264        // what the person does about each: marks it seen, undoes it, accepts or dismisses a proposal.
265        "agent_changes" => {
266            let entry = Some(s("id")).filter(|id| !id.is_empty());
267            let all = body.get("include_seen").and_then(Value::as_bool).unwrap_or(false);
268            Ok((json!({ "changes": vault::agent_changes::list(store, entry.as_deref(), all)? }), false))
269        }
270        "change_seen" => {
271            vault::agent_changes::seen(store, body.get("seq").and_then(Value::as_i64).ok_or("seen needs the change's seq")?)?;
272            Ok((json!({}), true))
273        }
274        "changes_seen_all" => {
275            vault::agent_changes::seen_all(store)?;
276            Ok((json!({}), true))
277        }
278        "change_undo" => {
279            vault::agent_changes::undo(store, body.get("seq").and_then(Value::as_i64).ok_or("undo needs the change's seq")?)?;
280            Ok((json!({}), true))
281        }
282        "proposal_accept" => {
283            let shown = body.get("at").and_then(Value::as_i64).ok_or("accept needs the time of the proposal that was shown")?;
284            vault::proposals::accept_shown(store, &s("id"), &s("field"), Some(shown))?;
285            Ok((json!({}), true))
286        }
287        "proposal_dismiss" => {
288            let shown = body.get("at").and_then(Value::as_i64).ok_or("dismiss needs the time of the proposal that was shown")?;
289            Ok((json!({ "dismissed": vault::proposals::dismiss_shown(store, &s("id"), &s("field"), Some(shown))? }), true))
290        }
291        _ => {
292            let seq = body.get("seq").and_then(Value::as_i64).ok_or("restore needs the version's seq")?;
293            vault::versions::restore(store, &s("id"), seq)?;
294            Ok((json!({}), true))
295        }
296    }
297}
298
299/// `POST /api/v1/host/vault`: the pane's operations, from the host only.
300pub(crate) async fn handle_host_vault(State(state): State<AppState>, headers: HeaderMap, Json(body): Json<Value>) -> Response {
301    if !super::ui_handlers::from_host(&state, &headers).await {
302        return error(StatusCode::FORBIDDEN, "only the AgentMux host can reach the Vault");
303    }
304    let op = body.get("op").and_then(Value::as_str).unwrap_or("").to_string();
305    let store = state.identity_store.clone();
306    let st = state.clone();
307    let result = tokio::task::spawn_blocking(move || host_op(&st, &store, &op, body)).await;
308    match result {
309        Ok(Ok((data, changed))) => {
310            if changed {
311                publish(&state);
312            }
313            Json(json!({ "ok": true, "data": data })).into_response()
314        }
315        Ok(Err(e)) => error(StatusCode::BAD_REQUEST, e),
316        Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
317    }
318}
319
320type Store = crate::backend::storage::store::Store;
321/// What an operation answers: the data, and whether it changed what the panes show.
322type OpResult = Result<(Value, bool), String>;
323
324/// A string field of an operation's body, empty when it is not there.
325fn text_arg(body: &Value, key: &str) -> String {
326    body.get(key).and_then(Value::as_str).unwrap_or("").to_string()
327}
328
329/// One operation of the pane's route, by name.
330fn host_op(state: &AppState, store: &Store, op: &str, body: Value) -> OpResult {
331    match op {
332        "list" => op_list(store),
333        "create" => op_create(store, body),
334        "update" => {
335            let change: EntryChange = serde_json::from_value(body).map_err(|_| shape_error("a change"))?;
336            vault::update(store, change)?;
337            Ok((json!({}), true))
338        }
339        // One part's value, for Reveal and Copy. The host asks only after
340        // the OS has confirmed the person.
341        "reveal" => {
342            let value = vault::reveal(store, &text_arg(&body, "id"), &text_arg(&body, "part"), &text_arg(&body, "action"))?;
343            Ok((json!({ "value": value.as_str() }), true))
344        }
345        // The host's report on a copy, after it tried the clipboard.
346        "record_copy" => {
347            vault::record_copy(store, &text_arg(&body, "id"), &text_arg(&body, "part"), body.get("done").and_then(Value::as_bool).unwrap_or(false))?;
348            Ok((json!({}), true))
349        }
350        "delete" => {
351            vault::delete(store, body.get("id").and_then(Value::as_str).unwrap_or(""))?;
352            Ok((json!({}), true))
353        }
354        "vault_create" | "vault_update" | "vault_delete" | "move_entry" | "share_add" | "share_remove" | "share_list" | "signin_vault" | "allow_setting" | "check_source" | "versions" | "restore" | "history" | "history_check" | "agent_changes" | "change_seen" | "changes_seen_all" | "change_undo" | "proposal_accept" | "proposal_dismiss" => entry_ops(state, op, &body),
355        "decline_request" => op_decline_request(store, &body),
356        "requests" => Ok((json!({ "requests": requests::requests().list(), "uses": vault::uses::uses().list() }), false)),
357        "answer_use" => op_answer_use(&body),
358        "hold_use" => hold_use(&body),
359        "grants" => op_grants(store),
360        "revoke_grant" => op_revoke_grant(store, &body),
361        "on_screen" => op_on_screen(store, &body),
362        "activity" => {
363            let limit = body.get("limit").and_then(Value::as_i64).unwrap_or(200);
364            Ok((json!({ "activity": vault::activity(store, limit)? }), false))
365        }
366        "kept" => Ok((json!({ "kept": kept(state) }), false)),
367        // Export and import: the host picks the file in its native dialog and
368        // passes the path, so no agent chooses one (spec section 8.1).
369        "suggest_passphrase" => Ok((json!({ "passphrase": vault::transfer::suggest_passphrase()? }), false)),
370        "export" => Ok((export(store, &body)?, true)),
371        "import_inspect" => op_import_inspect(store, &body),
372        "import_commit" => import_commit(store, &body),
373        "import_cancel" => {
374            vault::transfer::cancel(body.get("token").and_then(Value::as_str).unwrap_or(""));
375            Ok((json!({}), false))
376        }
377        other => Err(format!("unknown Vault operation {other:?}")),
378    }
379}
380
381fn op_list(store: &Store) -> OpResult {
382    let (entries, problem) = vault::list_for_pane(store)?;
383    Ok((
384        json!({
385            "entries": entries,
386            "vaults": vault::vaults::list(store)?,
387            "signin_vaults": vault::vaults::signin_vaults(store)?,
388            "problem": problem,
389            "requests": requests::requests().list(),
390            "uses": vault::uses::uses().list(),
391            "backend": crate::identity::secret_store::backend_name(),
392        }),
393        false,
394    ))
395}
396
397/// A new entry, which may fill an agent's request.
398fn op_create(store: &Store, body: Value) -> OpResult {
399    let request_id = body.get("request_id").and_then(Value::as_str).unwrap_or("").to_string();
400    let vault_id = body.get("vault").and_then(Value::as_str).filter(|v| !v.is_empty()).unwrap_or(PERSONAL_VAULT).to_string();
401    let entry: NewEntry = serde_json::from_value(body).map_err(|_| shape_error("an entry"))?;
402    let id = vault::create_in(store, entry, &vault_id)?;
403    if !request_id.is_empty() {
404        if let Some(req) = requests::requests().get(&request_id) {
405            vault::record(store, &id, &req.label, vault::PERSON, "filled a request", &req.agent, "done");
406        }
407        requests::requests().answer(&request_id, requests::Answer::Created(id.clone()));
408    }
409    Ok((json!({ "id": id }), true))
410}
411
412fn op_decline_request(store: &Store, body: &Value) -> OpResult {
413    let id = body.get("request_id").and_then(Value::as_str).unwrap_or("");
414    if let Some(req) = requests::requests().get(id) {
415        vault::record(store, "", &req.label, vault::PERSON, "declined a request", &req.agent, "declined");
416    }
417    requests::requests().answer(id, requests::Answer::Declined);
418    Ok((json!({}), true))
419}
420
421/// The person's answer to an agent's use of an entry (spec section 6.4).
422fn op_answer_use(body: &Value) -> OpResult {
423    let (id, word) = (text_arg(body, "id"), text_arg(body, "decision"));
424    let decision = vault::uses::Decision::parse(&word).ok_or_else(|| "decision is once, always or deny".to_string())?;
425    let request = vault::uses::uses().get(&id).ok_or_else(|| "that request is no longer waiting".to_string())?;
426    if decision == vault::uses::Decision::Always && !request.offer_always && request.choices.as_ref().is_none_or(|c| c.is_empty()) {
427        return Err("Always isn't offered here: the field doesn't look like what the entry is".into());
428    }
429    // A value the person typed because no entry exists: required to allow, and
430    // never kept unless they ticked the box.
431    let value = body.get("value").and_then(Value::as_str).map(|v| zeroize::Zeroizing::new(v.to_string())).filter(|v| !v.is_empty());
432    if request.needs_value && decision != vault::uses::Decision::Deny {
433        match &value {
434            None => return Err("type the value to fill, or deny".into()),
435            Some(v) if v.len() > 1024 * 1024 => return Err("that value is too long".into()),
436            _ => {}
437        }
438    }
439    let save = request.needs_value && body.get("save").and_then(Value::as_bool).unwrap_or(false);
440    let answer = vault::uses::UseAnswer { decision, value: if request.needs_value { value } else { None }, save, by: vault::uses::By::Person, choice: chosen_card(&request, body.get("choice").and_then(Value::as_str), decision)?, share: super::vault_import::ticked_share(&request, body.get("share"), decision) };
441    if !vault::uses::uses().answer(&id, answer) {
442        return Err("that request is no longer waiting".into());
443    }
444    Ok((json!({}), true))
445}
446
447/// Who may use which entry without asking, with no value and no key: Warden's
448/// view of the standing permissions, which must not make the OS ask for the key.
449fn op_grants(store: &Store) -> OpResult {
450    let mut grants = store.vault_grants().map_err(|e| e.to_string())?;
451    let rows = store.vault_list().map_err(|e| e.to_string())?;
452    let granted: Vec<Value> = rows
453        .into_iter()
454        .filter_map(|r| {
455            let g = grants.remove(&r.id)?;
456            Some(json!({ "id": r.id, "label": r.label, "kind": r.kind, "grants": g }))
457        })
458        .collect();
459    Ok((json!({ "granted": granted }), false))
460}
461
462fn op_revoke_grant(store: &Store, body: &Value) -> OpResult {
463    let (entry, origin) = (text_arg(body, "entry_id"), text_arg(body, "origin"));
464    if !store.vault_grant_revoke(&entry, &origin).map_err(|e| e.to_string())? {
465        return Err("there is no such grant".into());
466    }
467    vault::record(store, &entry, "", vault::PERSON, "revoked a site", &origin, "done");
468    Ok((json!({}), true))
469}
470
471/// A pane says it is showing (or no longer is). Only the host can
472/// say so: an agent clearing it could then capture the window. Each
473/// pane has its own note, so one pane hiding can't clear another's.
474fn op_on_screen(store: &Store, body: &Value) -> OpResult {
475    let pane = body.get("pane").and_then(Value::as_str).unwrap_or("").trim();
476    if pane.is_empty() || pane.len() > 128 {
477        return Err("on_screen needs the pane's id".into());
478    }
479    let on = body.get("on").and_then(Value::as_bool).unwrap_or(false);
480    let now = agentmux_common::time::now_ms();
481    let until = if on { now + ON_SCREEN_MS } else { 0 };
482    store.vault_on_screen_set(&on_screen_key(pane), until, now).map_err(|e| e.to_string())?;
483    Ok((json!({}), false))
484}
485
486fn op_import_inspect(store: &Store, body: &Value) -> OpResult {
487    let path = file_path(body)?;
488    let pass = body.get("passphrase").and_then(Value::as_str);
489    // For a CSV no reader knows: the person's choice of columns.
490    let mapping: Option<vault::import::Mapping> = match body.get("mapping").filter(|m| !m.is_null()) {
491        Some(m) => Some(serde_json::from_value(m.clone()).map_err(|e| format!("invalid column mapping: {e}"))?),
492        None => None,
493    };
494    // The key file of a KeePass database: its bytes, read by the host, from the person's own pick. One that is
495    // present but empty is still a key file (a refused one), never "no key file".
496    let keyfile: Option<zeroize::Zeroizing<Vec<u8>>> = match body.get("keyfile").and_then(Value::as_str) {
497        Some(k) if k.len() > vault::import::MAX_KEY_FILE * 2 => return Err("that key file is too large to be a KeePass key file".into()),
498        Some(k) => {
499            use base64::Engine as _;
500            Some(zeroize::Zeroizing::new(base64::engine::general_purpose::STANDARD.decode(k).map_err(|_| "the key file wasn't passed on intact".to_string())?))
501        }
502        None => None,
503    };
504    match vault::transfer::inspect_keyed(store, &path, pass, mapping.as_ref(), keyfile.as_deref().map(|k| k.as_slice())) {
505        Ok(preview) => Ok((json!({ "preview": preview }), false)),
506        Err(vault::transfer::InspectError::NeedsPassphrase) => Ok((json!({ "needs_passphrase": true }), false)),
507        Err(vault::transfer::InspectError::NeedsMapping(m)) => Ok((json!({ "needs_mapping": m }), false)),
508        Err(vault::transfer::InspectError::Other(why)) => Err(why),
509    }
510}
511
512/// A pane's key among the AgentMux instances that share the identity store:
513/// this srv and the pane.
514fn on_screen_key(pane: &str) -> String {
515    format!("srv-{}:{pane}", std::process::id())
516}
517
518/// `GET /api/v1/vault/on_screen`: whether any AgentMux on this computer shows
519/// a Vault pane now. `UI window` refuses to capture AgentMux windows while one
520/// does (SPEC_VAULT_PANE_AGENTS_USE_SECRETS_UNSEEN_2026_10_19.md §5.3).
521pub(crate) async fn handle_vault_on_screen(State(state): State<AppState>) -> Response {
522    let store = state.identity_store.clone();
523    let now = agentmux_common::time::now_ms();
524    match tokio::task::spawn_blocking(move || store.vault_on_screen(now)).await {
525        Ok(Ok(on)) => Json(json!({ "on_screen": on })).into_response(),
526        Ok(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
527        Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
528    }
529}
530
531/// `GET /api/v1/vault`: the entries an agent can name. Reads no value, so it
532/// never touches the keychain.
533pub(crate) async fn handle_vault_list(State(state): State<AppState>) -> Response {
534    let store = state.identity_store.clone();
535    match tokio::task::spawn_blocking(move || vault::list_for_agent(&store, None)).await {
536        Ok(Ok(entries)) => Json(json!({ "entries": entries })).into_response(),
537        Ok(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e),
538        Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
539    }
540}
541
542#[derive(Debug, Deserialize)]
543pub(crate) struct ListBody {
544    /// The asking agent's signed identity: the Vaults it may use depend on who it is.
545    #[serde(default)]
546    auth: Option<agentmux_common::api_types::UiAutomationAuth>,
547}
548
549/// `POST /api/v1/vault/list`: the entries of the Vaults the proven agent may use. An agent that
550/// doesn't prove who it is sees only the Vaults open to every agent, as `GET /api/v1/vault` does.
551pub(crate) async fn handle_vault_list_for(State(state): State<AppState>, caller: Option<axum::Extension<super::caller::Caller>>, Json(body): Json<ListBody>) -> Response {
552    let (agent, pane) = asking_agent(&state, caller.as_deref(), body.auth.as_ref());
553    let proven = pane.is_some();
554    let uid = proven.then(|| state.reactive_handler.get_agent(&agent).and_then(|a| a.uid)).flatten();
555    let store = state.identity_store.clone();
556    match tokio::task::spawn_blocking(move || vault::list_for_agent_as(&store, proven.then_some(agent.as_str()), uid.as_deref())).await {
557        Ok(Ok(entries)) => Json(json!({ "entries": entries })).into_response(),
558        Ok(Err(e)) => error(StatusCode::INTERNAL_SERVER_ERROR, e),
559        Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
560    }
561}
562
563#[derive(Debug, Deserialize)]
564pub(crate) struct GenerateBody {
565    #[serde(flatten)]
566    request: vault::GenerateRequest,
567    /// The asking agent's signed identity: the record names it, so it must be proven.
568    #[serde(default)]
569    auth: Option<agentmux_common::api_types::UiAutomationAuth>,
570}
571
572#[derive(Debug, Deserialize)]
573pub(crate) struct HistoryBody {
574    id: String,
575    #[serde(default)]
576    limit: Option<i64>,
577    #[serde(default)]
578    auth: Option<agentmux_common::api_types::UiAutomationAuth>,
579}
580
581/// `POST /api/v1/vault/history`: an entry's history (who did what, when, under which version, and why), for an
582/// entry in a Vault the proven agent may use. It holds no value
583/// (docs/specs/SPEC_VAULT_PARITY_ENTRY_HISTORY_REASONS_AND_IMPORT_2026_11_06.md §5.3).
584pub(crate) async fn handle_vault_history(State(state): State<AppState>, caller: Option<axum::Extension<super::caller::Caller>>, Json(body): Json<HistoryBody>) -> Response {
585    let (agent, pane) = asking_agent(&state, caller.as_deref(), body.auth.as_ref());
586    let proven = pane.is_some();
587    let store = state.identity_store.clone();
588    let limit = body.limit.unwrap_or(100);
589    let asked = tokio::task::spawn_blocking(move || {
590        let agent = proven.then_some(agent.as_str());
591        vault::history::history_for(&store, &body.id, vault::history::Asker::Agent(agent), limit)
592    })
593    .await;
594    match asked {
595        Ok(Ok(rows)) => Json(json!({ "history": rows })).into_response(),
596        Ok(Err(e)) => error(StatusCode::NOT_FOUND, e),
597        Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
598    }
599}
600
601/// `POST /api/v1/vault/generate`: a new entry whose value the Vault makes
602/// (SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md §4.1). The
603/// person isn't asked: the value is no secret of theirs, nobody has seen it, and
604/// using it later asks as every use does. The answer names the entry, never the
605/// value.
606pub(crate) async fn handle_vault_generate(State(state): State<AppState>, caller: Option<axum::Extension<super::caller::Caller>>, Json(body): Json<GenerateBody>) -> Response {
607    let Some(auth) = body.auth.as_ref() else {
608        return error(StatusCode::FORBIDDEN, "generate needs to know which agent asks (its token or its signed identity): the Vault records who made each entry");
609    };
610    let agent: String = match super::ui_handlers::verified_block_id(&state, caller.as_deref(), auth) {
611        Ok(_) => auth.agent_id.chars().take(64).collect(),
612        Err(e) => return error(StatusCode::FORBIDDEN, format!("generate needs to know which agent asks (its token or its signed identity): {e}")),
613    };
614    let store = state.identity_store.clone();
615    let request = body.request;
616    // A login with a site is made for the agent's own browser profile, named by its permanent uid.
617    let own_profile = state.reactive_handler.get_agent(&agent).and_then(|a| a.uid).map(|uid| format!("profile:{}", crate::backend::browser_profiles_store::agent_profile_id(&uid)));
618    match tokio::task::spawn_blocking(move || vault::generate_entry_in(&store, request, &agent, own_profile.as_deref())).await {
619        Ok(Ok(made)) => {
620            publish(&state);
621            Json(json!({ "status": "created", "id": made.id, "label": made.label, "kind": made.kind, "made": made.made })).into_response()
622        }
623        Ok(Err(e)) => error(StatusCode::BAD_REQUEST, e),
624        Err(e) => error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
625    }
626}
627
628#[derive(Debug, Deserialize)]
629pub(crate) struct RequestBody {
630    kind: String,
631    label: String,
632    #[serde(default)]
633    why: String,
634    /// Why the agent needs it (`why` is the same thing, as it was called): required.
635    #[serde(default)]
636    reason: Option<String>,
637    /// The asking agent's signed identity: a name in the body proves nothing.
638    #[serde(default)]
639    auth: Option<agentmux_common::api_types::UiAutomationAuth>,
640    #[serde(default)]
641    wait_secs: Option<u64>,
642    /// The Vault the entry should go in, by name or id; the form starts on it.
643    #[serde(default)]
644    vault: Option<String>,
645}
646
647/// The card the person picked for a whole-card fill: one of the request's own choices (the preselected
648/// one when they picked none), never an id the agent or the page made up. "Always" is never for an expired
649/// card. `None` for any other use, and for a no.
650fn chosen_card(request: &vault::uses::UseRequest, picked: Option<&str>, decision: vault::uses::Decision) -> Result<Option<String>, String> {
651    let Some(choices) = request.choices.as_ref().filter(|c| !c.is_empty()) else { return Ok(None) };
652    if decision == vault::uses::Decision::Deny {
653        return Ok(None);
654    }
655    let id = picked.filter(|p| !p.is_empty()).unwrap_or(&request.entry_id);
656    if id.is_empty() {
657        return Err("choose a card, or deny".into());
658    }
659    let card = choices.iter().find(|c| c.id == id).ok_or_else(|| "that card isn't one of the choices".to_string())?;
660    if decision == vault::uses::Decision::Always && (card.expired || !request.offer_always) {
661        return Err("Always isn't offered for that card".into());
662    }
663    Ok(Some(card.id.clone()))
664}
665
666/// The person is reading or acting in a use's prompt: its countdown holds
667/// (SPEC_VAULT_REQUESTS_AS_CARDS_IN_THE_AGENT_PANE_2026_11_01.md §5, "Hold").
668/// Only the host's route reaches it, like the answer itself.
669fn hold_use(body: &Value) -> Result<(Value, bool), String> {
670    let id = body.get("id").and_then(Value::as_str).unwrap_or("");
671    if !vault::uses::uses().hold(id) {
672        return Err("that request is no longer waiting".into());
673    }
674    Ok((json!({}), true))
675}
676
677/// Who the request says is asking, and its pane: the agent whose token or signature
678/// verified (a container agent has a token and no signing key), else a plain "not a verified agent".
679pub(super) fn asking_agent(
680    state: &AppState,
681    caller: Option<&super::caller::Caller>,
682    auth: Option<&agentmux_common::api_types::UiAutomationAuth>,
683) -> (String, Option<String>) {
684    const UNVERIFIED: &str = "Something on this computer (not a verified agent)";
685    match auth.map(|a| (a, super::ui_handlers::verified_block_id(state, caller, a))) {
686        Some((a, Ok(pane))) => (a.agent_id.chars().take(64).collect(), Some(pane)),
687        Some((a, Err(e))) => {
688            tracing::warn!(claimed = %a.agent_id, error = %e, "a Vault request's identity didn't verify");
689            (UNVERIFIED.to_string(), None)
690        }
691        None => (UNVERIFIED.to_string(), None),
692    }
693}
694
695/// `POST /api/v1/vault/request`: ask the person for a new entry; answer when
696/// they save or dismiss it, or when the wait runs out (the request stays
697/// open in the Vault, and the agent finds the entry with `list` later).
698///
699/// Asking again for the same kind and label is safe: a verified agent whose
700/// session ended mid-wait joins the request already open, or gets the answer
701/// the person gave, and no second form opens. Every answer carries `request_id`.
702pub(crate) async fn handle_vault_request(State(state): State<AppState>, caller: Option<axum::Extension<super::caller::Caller>>, Json(body): Json<RequestBody>) -> Response {
703    if vault::kinds::kind(&body.kind).is_none() {
704        let kinds: Vec<&str> = vault::kinds::KINDS.iter().map(|k| k.name).collect();
705        return error(StatusCode::BAD_REQUEST, format!("unknown kind {:?}; one of {}", body.kind, kinds.join(", ")));
706    }
707    let label = body.label.trim().chars().take(200).collect::<String>();
708    if label.is_empty() {
709        return error(StatusCode::BAD_REQUEST, "a request needs a label: what the entry is, e.g. \"Stripe test key\"");
710    }
711    // The agent says why, before anything is opened for the person.
712    let reason = match vault::history::require_reason(body.reason.as_deref().filter(|r| !r.trim().is_empty()).or(Some(body.why.as_str()))) {
713        Ok(r) => r,
714        Err(e) => return error(StatusCode::BAD_REQUEST, e),
715    };
716    let (agent, pane) = asking_agent(&state, caller.as_deref(), body.auth.as_ref());
717    let vault_id = match body.vault.as_deref().map(str::trim).filter(|v| !v.is_empty()) {
718        None => String::new(),
719        Some(which) => {
720            let store = state.identity_store.clone();
721            let who = pane.is_some().then(|| agent.clone());
722            let which = which.to_string();
723            match tokio::task::spawn_blocking(move || vault::vaults::resolve(&store, &which, Some(who.as_deref())).map(|v| v.id)).await {
724                Ok(Ok(id)) => id,
725                Ok(Err(e)) => return error(StatusCode::BAD_REQUEST, e),
726                Err(e) => return error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()),
727            }
728        }
729    };
730    let req = requests::VaultRequest {
731        vault: vault_id,
732        id: uuid::Uuid::new_v4().to_string(),
733        agent: agent.clone(),
734        kind: body.kind.clone(),
735        label: label.clone(),
736        why: reason.clone(),
737        requested_ms: agentmux_common::time::now_ms_u64(),
738        block_id: super::vault_ask::shown_pane(&state, pane.as_deref().unwrap_or("")),
739    };
740    let (request_id, answer) = match requests::requests().ask(req, pane.is_some()) {
741        // The person already answered this agent's ask for this entry.
742        requests::Asked::Answered { request_id, answer } => return answered(&request_id, Ok(answer)),
743        requests::Asked::Waiting { request_id, new, answer } => {
744            if new {
745                let store = state.identity_store.clone();
746                let (label, agent, kind, reason) = (label.clone(), agent.clone(), body.kind.clone(), reason.clone());
747                let line = move || vault::record_line(&store, vault::Line { entry_id: "", label: &label, actor: &agent, action: "requested an entry", target: &kind, outcome: "asked", reason: &reason });
748                let _ = tokio::task::spawn_blocking(line).await;
749                publish(&state);
750            }
751            (request_id, answer)
752        }
753    };
754    let _asking = crate::backend::user_attention::Asking::start(
755        &state.broker,
756        &state.mstore,
757        pane.as_deref().unwrap_or(""),
758        "vault",
759        &format!("{agent} asks for a Vault entry: {label}"),
760    );
761    let wait = body.wait_secs.map(Duration::from_secs).unwrap_or(DEFAULT_WAIT).min(MAX_WAIT);
762    match tokio::time::timeout(wait, answer).await {
763        Ok(a) => answered(&request_id, a.map_err(|_| ())),
764        Err(_) => Json(json!({
765            "status": "pending",
766            "request_id": request_id,
767            "message": "the person hasn't answered yet; the request stays open in the Vault for an hour. Ask again with the same kind and label to wait again or get the answer: it opens no second form. A saved entry also shows up in list",
768        }))
769        .into_response(),
770    }
771}
772
773/// The answer to a request, with its id.
774fn answered(request_id: &str, answer: Result<requests::Answer, ()>) -> Response {
775    match answer {
776        Ok(requests::Answer::Created(id)) => Json(json!({ "status": "created", "id": id, "request_id": request_id })).into_response(),
777        Ok(requests::Answer::Declined) | Err(()) => {
778            Json(json!({ "status": "declined", "request_id": request_id, "message": "the person dismissed the request" })).into_response()
779        }
780    }
781}
782
783#[cfg(test)]
784mod tests;
785
786#[cfg(test)]
787mod identity_tests;
788#[cfg(test)]
789mod share_tests;
790#[cfg(test)]
791mod share_ask_tests;