1use 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
31const 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
42fn 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 let links_only = body.get("links_only").and_then(Value::as_bool).unwrap_or(false);
55 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 plain @ ("csv" | "json") => vault::plain_export::export(store, ids.as_deref(), plain, &path),
63 other => Err(format!("unknown export format {other:?}")),
64 }
65}
66
67fn 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
76fn shape_error(what: &str) -> String {
79 format!("{what} for the Vault isn't in the expected shape")
80}
81
82pub(crate) fn publish(state: &AppState) {
84 super::needs_key::settle_all(state);
86 publish_change(&state.broker);
87 super::browser_signin_fill::refresh_all(state);
89}
90
91pub(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
101fn 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 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
133fn 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
147fn 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
162fn 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
176fn 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 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
206fn 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 "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 "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 "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 "signin_vault" => {
244 vault::vaults::set_signin_vault(store, &s("profile"), &s("vault_id"))?;
245 Ok((json!({}), true))
246 }
247 "allow_setting" => {
250 vault::setting_key::allow(store, &s("entry_id"), &s("setting"), vault::PERSON)?;
251 Ok((json!({}), true))
252 }
253 "check_source" => Ok((json!({ "checked": super::vault_source::person_check(state, &s("id"))? }), true)),
255 "versions" => Ok((json!({ "versions": vault::versions::list(store, &s("id"))? }), false)),
257 "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 "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
299pub(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;
321type OpResult = Result<(Value, bool), String>;
323
324fn text_arg(body: &Value, key: &str) -> String {
326 body.get(key).and_then(Value::as_str).unwrap_or("").to_string()
327}
328
329fn 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 "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 "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 "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
397fn 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
421fn 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 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
447fn 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
471fn 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 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 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
512fn on_screen_key(pane: &str) -> String {
515 format!("srv-{}:{pane}", std::process::id())
516}
517
518pub(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
531pub(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 #[serde(default)]
546 auth: Option<agentmux_common::api_types::UiAutomationAuth>,
547}
548
549pub(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 #[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
581pub(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
601pub(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 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 #[serde(default)]
636 reason: Option<String>,
637 #[serde(default)]
639 auth: Option<agentmux_common::api_types::UiAutomationAuth>,
640 #[serde(default)]
641 wait_secs: Option<u64>,
642 #[serde(default)]
644 vault: Option<String>,
645}
646
647fn 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
666fn 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
677pub(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
695pub(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 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 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
773fn 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;