Skip to main content

agentmux_srv/server/
vault_inspect.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `POST /api/v1/vault/{show,update,verify,health}`: what an agent can ask the Vault about an entry and about itself
5//! (docs/specs/SPEC_VAULT_PARITY_ENTRY_HISTORY_REASONS_AND_IMPORT_2026_11_06.md ยง8). Each answers ids, names, states
6//! and counts, for the Vaults the proven agent may use; none returns a value. `update` changes details only and needs
7//! the agent's signed identity and a reason, as the record names who changed what. Nobody is asked, a change to where the
8//! entry's machine copy is included: the history line is the record
9//! (docs/specs/SPEC_VAULT_AGENT_ADDS_AND_EDITS_WITHOUT_ASKING_2026_11_25.md).
10
11use std::time::Duration;
12
13use axum::extract::State;
14use axum::http::StatusCode;
15use axum::response::{IntoResponse, Response};
16use axum::Json;
17use serde::{Deserialize, Serialize};
18use serde_json::json;
19
20use super::vault_handlers::{asking_agent, publish};
21use super::AppState;
22use crate::backend::vault::inspect::{self, KeyResult, UpdateRequest};
23use crate::backend::vault::pace;
24use crate::backend::vault::seal;
25use crate::backend::vault::shares::{self, Ask, Asked};
26use crate::backend::vault::uses::{Ended, UseHttpPrompt, UseRequest};
27
28/// The longest the person has to answer a share.
29const ANSWER_WAIT_MAX: Duration = Duration::from_secs(600);
30
31type Auth = Option<agentmux_common::api_types::UiAutomationAuth>;
32
33fn error(status: StatusCode, message: impl Into<String>) -> Response {
34    (status, Json(json!({ "error": message.into() }))).into_response()
35}
36
37/// The agent whose signed identity verified, else none (which sees only the Vaults open to every agent).
38fn who(state: &AppState, caller: Option<&super::caller::Caller>, auth: &Auth) -> Option<String> {
39    let (agent, pane) = asking_agent(state, caller, auth.as_ref());
40    pane.map(|_| agent)
41}
42
43/// The Vault key as it reads now, or why it can't be.
44async fn key() -> KeyResult {
45    tokio::task::spawn_blocking(|| seal::key(false)).await.unwrap_or_else(|e| Err(e.to_string()))
46}
47
48/// Runs `read` on the blocking pool; a refusal is a 404 (the entry isn't one this agent may use, or isn't there), a
49/// 400 or a 500.
50async fn blocking<T: Send + 'static>(read: impl FnOnce() -> Result<T, String> + Send + 'static) -> Result<T, Response> {
51    match tokio::task::spawn_blocking(read).await {
52        Ok(Ok(out)) => Ok(out),
53        Ok(Err(e)) if e.starts_with("no entry") => Err(error(StatusCode::NOT_FOUND, e)),
54        Ok(Err(e)) => Err(error(StatusCode::BAD_REQUEST, e)),
55        Err(e) => Err(error(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
56    }
57}
58
59/// [`blocking`], answering its result as JSON.
60async fn answer<T: Serialize + Send + 'static>(read: impl FnOnce() -> Result<T, String> + Send + 'static) -> Response {
61    match blocking(read).await {
62        Ok(out) => Json(out).into_response(),
63        Err(refusal) => refusal,
64    }
65}
66
67#[derive(Debug, Deserialize)]
68pub(crate) struct IdBody {
69    #[serde(default)]
70    id: Option<String>,
71    #[serde(default)]
72    auth: Auth,
73}
74
75/// `POST /api/v1/vault/show`
76pub(crate) async fn handle_vault_show(State(state): State<AppState>, caller: Option<axum::Extension<super::caller::Caller>>, Json(body): Json<IdBody>) -> Response {
77    let agent = who(&state, caller.as_deref(), &body.auth);
78    let Some(id) = body.id.filter(|i| !i.trim().is_empty()) else { return error(StatusCode::BAD_REQUEST, "show needs an id: the entry to look at (list shows them)") };
79    let uid = agent.as_deref().and_then(|a| state.reactive_handler.get_agent(a)).and_then(|a| a.uid);
80    let (store, key) = (state.identity_store.clone(), key().await);
81    answer(move || inspect::show_as(&store, &id, (agent.as_deref(), uid.as_deref()), &key, crate::backend::vault::expiry::today())).await
82}
83
84/// `POST /api/v1/vault/verify`
85pub(crate) async fn handle_vault_verify(State(state): State<AppState>, caller: Option<axum::Extension<super::caller::Caller>>, Json(body): Json<IdBody>) -> Response {
86    let agent = who(&state, caller.as_deref(), &body.auth);
87    let (store, key) = (state.identity_store.clone(), key().await);
88    answer(move || inspect::verify(&store, body.id.as_deref(), agent.as_deref(), &key, crate::backend::vault::expiry::today())).await
89}
90
91/// `POST /api/v1/vault/health`
92pub(crate) async fn handle_vault_health(State(state): State<AppState>, caller: Option<axum::Extension<super::caller::Caller>>, Json(body): Json<IdBody>) -> Response {
93    let agent = who(&state, caller.as_deref(), &body.auth);
94    let (store, key) = (state.identity_store.clone(), key().await);
95    let backend = crate::identity::secret_store::backend_name();
96    answer(move || inspect::health(&store, agent.as_deref(), &key, backend, crate::backend::vault::expiry::today())).await
97}
98
99#[derive(Debug, Deserialize)]
100pub(crate) struct UpdateBody {
101    #[serde(flatten)]
102    request: UpdateRequest,
103    #[serde(default)]
104    auth: Auth,
105}
106
107/// `POST /api/v1/vault/update`
108pub(crate) async fn handle_vault_update(State(state): State<AppState>, caller: Option<axum::Extension<super::caller::Caller>>, Json(body): Json<UpdateBody>) -> Response {
109    let (agent, pane) = asking_agent(&state, caller.as_deref(), body.auth.as_ref());
110    if pane.is_none() {
111        return error(StatusCode::FORBIDDEN, "update needs to know which agent asks (its token or its signed identity, neither of which verified): the Vault records who changed each entry; respawn the agent if it has neither");
112    }
113    let request = body.request;
114    // The call is checked before the pace is spent, and before a refusal is written for it: an invalid call costs nothing and
115    // leaves nothing on an entry.
116    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)));
117    let (store, checking, by, own) = (state.identity_store.clone(), request.clone(), agent.clone(), own_profile.clone());
118    let checked = match blocking(move || inspect::check_update(&store, &checking, &by, own.as_deref())).await {
119        Ok(checked) => checked,
120        Err(refusal) => return refusal,
121    };
122    let spent = [pace::Act::Edit];
123    if let Err(why) = pace::admit(&agent, &spent) {
124        if pace::may_note_refusal(&agent) {
125            let (store, by) = (state.identity_store.clone(), agent.clone());
126            let _ = tokio::task::spawn_blocking(move || {
127                let line = crate::backend::vault::Line { entry_id: &checked.id, label: &checked.label, actor: &by, action: inspect::CHANGED_DETAILS, target: "", outcome: "refused: pace", reason: &checked.reason };
128                crate::backend::vault::record_line(&store, line);
129            })
130            .await;
131        }
132        return error(StatusCode::TOO_MANY_REQUESTS, why);
133    }
134    let store = state.identity_store.clone();
135    let by = agent.clone();
136    let response = answer(move || inspect::update_details_for(&store, &request, &by, own_profile.as_deref())).await;
137    if response.status().is_success() {
138        publish(&state);
139    } else {
140        pace::refund(&agent, &spent);
141    }
142    response
143}
144
145/// How long the person has to answer an agent's request to be given a login by default, and at most.
146const SHARE_WAIT: Duration = Duration::from_secs(300);
147
148#[derive(Debug, Deserialize)]
149pub(crate) struct ShareBody {
150    #[serde(default)]
151    id: Option<String>,
152    #[serde(default)]
153    reason: Option<String>,
154    /// An agent may name only itself: a share for another agent, or for every agent, is the person's to make.
155    #[serde(default)]
156    agent: Option<String>,
157    #[serde(default)]
158    auth: Auth,
159    #[serde(default)]
160    wait_secs: Option<u64>,
161}
162
163/// The question for the person: the login, its site and who asks to be able to sign in with it.
164fn share_card(ask: &Ask, agent: &str, pane: &str) -> UseRequest {
165    UseRequest {
166        id: uuid::Uuid::new_v4().to_string(),
167        agent: agent.to_string(),
168        block_id: pane.to_string(),
169        entry_id: ask.entry_id.clone(),
170        entry_label: ask.label.clone(),
171        what: "share".into(),
172        origin: ask.site.clone(),
173        field: ask.user.clone(),
174        // A form login's "Always" is given at its first sign-in. A prompt's is given here: the browser answers it
175        // with no call of the agent's to ask about (A11).
176        offer_always: ask.prompt,
177        reason: if ask.prompt { "an agent asked for its browser to answer this sign-in prompt with this login".into() } else { "an agent asked to be able to sign in with this login".into() },
178        agent_reason: ask.reason.clone(),
179        kind: "login".into(),
180        requested_ms: agentmux_common::time::now_ms_u64(),
181        share: true,
182        prompt: ask.prompt.then(|| UseHttpPrompt { realm: ask.realm.clone(), proxy: ask.proxy }),
183        ..Default::default()
184    }
185}
186
187/// The card's headline, as the attention list shows it.
188fn share_headline(ask: &Ask, agent: &str) -> String {
189    if ask.prompt {
190        return format!("{agent} wants its browser to answer the sign-in prompt of {} with {}", ask.site, ask.label);
191    }
192    format!("{agent} wants to sign in to {} with {}", ask.site, ask.label)
193}
194
195/// What the agent is told of a share the person made: for a sign-in the browser answers a prompt with, also that it
196/// is not typed by `signin` and what to do next.
197fn shared_answer(ask: &Ask, always: bool) -> serde_json::Value {
198    let mut out = json!({ "status": "shared", "id": ask.entry_id, "label": ask.label, "site": ask.site });
199    if ask.prompt {
200        out["prompt"] = json!(true);
201        out["always"] = json!(always);
202        out["next"] = json!("load the page again in a tab of your own browser profile: the browser answers the site's sign-in prompt with it, you never see it, and you are told what became of it");
203    }
204    out
205}
206
207/// What the agent is told when the card didn't end in a yes: silence is a no.
208fn share_not_allowed(ended: Ended) -> String {
209    match ended {
210        Ended::Expired | Ended::NoAnswer => "nobody answered, and a login is shared only on a yes: nothing was shared; ask the person".to_string(),
211        other => other.refusal("nothing was shared"),
212    }
213}
214
215/// `POST /api/v1/vault/share`: an agent asks the person to share a login with its own browser profile, so that it can
216/// sign in to the login's site with it (docs/specs/SPEC_VAULT_AGENTS_ENTER_CREDENTIALS_WHEREVER_ASKED_2026_11_16.md
217/// A2). Only the person's yes makes the share, and only for the agent that proved who it is. The agent learns the
218/// login's label and site, never its user name or its password.
219pub(crate) async fn handle_vault_share(State(state): State<AppState>, caller: Option<axum::Extension<super::caller::Caller>>, Json(body): Json<ShareBody>) -> Response {
220    let (agent, pane) = asking_agent(&state, caller.as_deref(), body.auth.as_ref());
221    let Some(pane) = pane else {
222        return error(StatusCode::FORBIDDEN, "share needs to know which agent asks (its token or its signed identity, neither of which verified): a login is shared with the agent that proved who it is; respawn the agent if it has neither");
223    };
224    let uid = state.reactive_handler.get_agent(&agent).and_then(|a| a.uid).unwrap_or_default();
225    if let Some(named) = body.agent.as_deref().map(str::trim).filter(|a| !a.is_empty()) {
226        if !named.eq_ignore_ascii_case(&agent) && named != uid {
227            return error(StatusCode::FORBIDDEN, "an agent asks for a share for itself only: leave agent out. A login shared with another agent, or with every agent, is the person's to share, from the login's card in the Vault pane");
228        }
229    }
230    let Some(id) = body.id.map(|i| i.trim().to_string()).filter(|i| !i.is_empty()) else {
231        return error(StatusCode::BAD_REQUEST, "share needs an id: the login to be given (list shows them)");
232    };
233    let (store, reason, who, who_uid) = (state.identity_store.clone(), body.reason, agent.clone(), uid.clone());
234    let planned = {
235        let id = id.clone();
236        blocking(move || shares::plan_ask(&store, &id, &who, &who_uid, reason.as_deref())).await
237    };
238    let ask = match planned {
239        Ok(Asked::Already(label)) => return Json(json!({ "status": "shared", "id": id, "label": label, "already": true })).into_response(),
240        Ok(Asked::Ask(ask)) => ask,
241        Err(refusal) => return refusal,
242    };
243    let wait = body.wait_secs.map(Duration::from_secs).unwrap_or(SHARE_WAIT).min(ANSWER_WAIT_MAX);
244    let headline = share_headline(&ask, &agent);
245    let (ended, _) = super::vault_ask::ask(&state, &pane, share_card(&ask, &agent, &pane), wait, &headline).await;
246    if !ended.allowed() {
247        let (store, ask, who) = (state.identity_store.clone(), ask.clone(), agent.clone());
248        let _ = tokio::task::spawn_blocking(move || shares::note_ask(&store, &ask, &who, ended.outcome())).await;
249        publish(&state);
250        return error(StatusCode::FORBIDDEN, share_not_allowed(ended));
251    }
252    // "Always" is only on the card of a sign-in the browser answers a prompt with (A11).
253    let always = ask.prompt && ended == Ended::Always;
254    let (store, made, who, to) = (state.identity_store.clone(), ask.clone(), agent.clone(), uid.clone());
255    let granted = blocking(move || {
256        if always {
257            let profile = format!("profile:{}", crate::backend::browser_profiles_store::agent_profile_id(&to));
258            shares::grant_asked_always(&store, &made, &to, &profile)?;
259        } else {
260            shares::grant_asked(&store, &made, &to)?;
261        }
262        shares::note_ask(&store, &made, &who, "done");
263        Ok(())
264    })
265    .await;
266    publish(&state);
267    match granted {
268        Ok(()) => {
269            // The yes also answers the prompt that waited for it, once.
270            if ask.prompt && !always {
271                super::vault_prompt_share::yes_given(&ask.entry_id, &uid);
272            }
273            Json(shared_answer(&ask, always)).into_response()
274        }
275        Err(refusal) => refusal,
276    }
277}