Skip to main content

agentmux_srv/server/
browser_vault_fill.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! `Browser` `fill` with `vault`: an agent names a Vault entry, the person says
5//! where it may go, and the host types it
6//! (docs/specs/SPEC_VAULT_PANE_AGENTS_USE_SECRETS_UNSEEN_2026_10_19.md §6).
7//!
8//! The value never reaches the agent. It goes from the sealed row to the host in
9//! the request that types it, and the agent's answer says only that the field was
10//! filled. Every use is in the Vault's Activity: who, which entry, which site and
11//! field, and what became of it; never the value.
12
13use std::time::Duration;
14
15use axum::extract::State;
16use axum::http::StatusCode;
17use axum::response::{IntoResponse, Response};
18use axum::Json;
19use serde::Deserialize;
20use serde_json::{json, Value};
21
22use crate::backend::vault::uses::{self, Ended, UseAnswer, UseRequest};
23use crate::backend::vault::{self, FillTarget};
24use agentmux_common::api_types::UiAutomationAuth;
25
26use super::browser_actions::{note, How, Kind};
27use super::ui_handlers::{err_response, proxy_value, target_block_id};
28use super::AppState;
29
30/// How long the person has to answer.
31const ANSWER_WAIT: Duration = Duration::from_secs(10 * 60);
32const HOST_WAIT: Duration = Duration::from_secs(30);
33
34#[derive(Debug, Deserialize)]
35pub(crate) struct VaultFillRequest {
36    auth: UiAutomationAuth,
37    #[serde(default)]
38    pane: Option<String>,
39    #[serde(rename = "ref")]
40    ref_: String,
41    /// `"id"` or `"id.part"`: fill from an entry. A card named by its id alone (or `card`, the default card) is filled whole.
42    #[serde(default)]
43    vault: Option<String>,
44    /// Or, with no entry yet: the kind and label of the value the person is asked to
45    /// type (`request_value`).
46    #[serde(default)]
47    request_kind: Option<String>,
48    #[serde(default)]
49    request_label: Option<String>,
50    /// Why the agent fills the form from an entry: one line of 8 to 300 characters, required with `vault`.
51    #[serde(default)]
52    reason: Option<String>,
53}
54
55/// The site a use is asked about and granted for: the origin of the frame the field is in, and when that is another
56/// site's frame (Stripe Elements, Braintree, Adyen, a bank's hosted field), the page it is on too. A grant is for that
57/// pair, so a look-alike frame on the page, or the provider's frame on another page, never inherits it.
58pub(crate) fn grant_site(origin: &str, page_origin: &str) -> String {
59    if page_origin.is_empty() || origin == page_origin || origin.is_empty() {
60        origin.to_string()
61    } else {
62        format!("{origin} on {page_origin}")
63    }
64}
65
66/// The page's origin when the field is in another site's frame, else empty: what a question shows beside `origin`.
67pub(crate) fn framed_in(origin: &str, page_origin: &str) -> String {
68    if page_origin.is_empty() || origin.is_empty() || origin == page_origin {
69        String::new()
70    } else {
71        page_origin.to_string()
72    }
73}
74
75/// What the host says about the field.
76struct Field {
77    origin: String,
78    /// The page's own origin (see [`grant_site`]).
79    page_origin: String,
80    label: String,
81    fingerprint: String,
82    slots: Vec<String>,
83    password_like: bool,
84    fillable: bool,
85}
86
87impl Field {
88    /// The site this field is asked about and granted for (see [`grant_site`]).
89    fn grant_key(&self) -> String {
90        grant_site(&self.origin, &self.page_origin)
91    }
92}
93
94fn parse_field(v: &Value) -> Result<Field, String> {
95    let s = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").to_string();
96    Ok(Field {
97        origin: s("origin"),
98        page_origin: s("page_origin"),
99        label: s("label"),
100        fingerprint: s("fingerprint"),
101        slots: v.get("slots").and_then(Value::as_array).map(|a| a.iter().filter_map(|x| x.as_str().map(String::from)).collect()).unwrap_or_default(),
102        password_like: v.get("password_like").and_then(Value::as_bool).unwrap_or(false),
103        fillable: v.get("fillable").and_then(Value::as_bool).unwrap_or(false),
104    })
105}
106
107/// What happens before the host types: refused, allowed without asking, or asked.
108#[derive(Debug, PartialEq, Eq)]
109pub(crate) enum Plan {
110    Refuse(&'static str),
111    Go,
112    Ask { offer_always: bool, reason: &'static str },
113}
114
115/// The table in spec §6.3: a granted site and a field that looks like the entry's
116/// kind fill without asking; anything else asks, and "Always" is offered only
117/// when the field looks like the entry's kind.
118pub(crate) fn plan(origin_known: bool, password_like: bool, fillable: bool, granted: bool, fits: bool) -> Plan {
119    if !origin_known {
120        return Plan::Refuse("AgentMux can't tell which site this field is on, so nothing was typed");
121    }
122    if password_like {
123        return Plan::Refuse("this is a password or one-time-code field: the Vault doesn't fill those; ask the person to fill it");
124    }
125    if !fillable {
126        return Plan::Refuse("this isn't a field that takes typed text");
127    }
128    match (granted, fits) {
129        (true, true) => Plan::Go,
130        (true, false) => Plan::Ask { offer_always: false, reason: "the field doesn't look like what this entry is" },
131        (false, true) => Plan::Ask { offer_always: true, reason: "the first time this entry is used on this site" },
132        (false, false) => Plan::Ask { offer_always: false, reason: "a new site, and the field doesn't look like what this entry is" },
133    }
134}
135
136/// How an outcome reads in the pane's Log.
137fn how_of(outcome: &str) -> How {
138    match outcome {
139        o if o.starts_with("done") => How::Allowed,
140        "denied" => How::Declined,
141        "timed out" => How::TimedOut,
142        other => How::Refused(other.to_string()),
143    }
144}
145
146fn record(state: &AppState, block_id: &str, target: &FillTarget, agent: &str, where_: &str, outcome: &str, reason: &str) {
147    crate::backend::vault::record_line(
148        &state.identity_store,
149        crate::backend::vault::Line { entry_id: &target.id, label: &target.label, actor: agent, action: "filled a web form", target: where_, outcome, reason },
150    );
151    // The pane's own Log shows it too, with what was filled and never its value.
152    note(block_id, agent, Kind::Fill).detail(&format!("{} from the Vault", target.what)).how(how_of(outcome)).record(state);
153    // Every window's Vault pane shows the new line of the record.
154    super::vault_handlers::publish(state);
155}
156
157/// Takes a use request down, and tells every window, however the wait ends: the
158/// agent's call can be dropped (it disconnected, or was stopped) while the person
159/// still has the prompt open, and the prompt must go then too.
160pub(super) struct Waiting {
161    id: String,
162    state: AppState,
163}
164
165impl Waiting {
166    pub(super) fn new(id: String, state: AppState) -> Self {
167        Self { id, state }
168    }
169}
170
171impl Drop for Waiting {
172    fn drop(&mut self) {
173        uses::uses().forget(&self.id);
174        super::vault_handlers::publish(&self.state);
175    }
176}
177
178/// The question for the person about filling `field` from `target`: why they are asked (`ask`: whether "Always" is
179/// offered, and the reason) and what the agent says it is for.
180fn fill_request(agent: &str, block_id: String, target: &FillTarget, field: &Field, ask: (bool, &str), agent_reason: &str) -> UseRequest {
181    UseRequest {
182        id: uuid::Uuid::new_v4().to_string(),
183        agent: agent.to_string(),
184        block_id,
185        entry_id: target.id.clone(),
186        entry_label: target.label.clone(),
187        what: target.what.clone(),
188        origin: field.origin.clone(),
189        page: framed_in(&field.origin, &field.page_origin),
190        field: field.label.clone(),
191        offer_always: ask.0,
192        reason: ask.1.to_string(),
193        agent_reason: agent_reason.to_string(),
194        needs_value: target.typed,
195        kind: target.kind.to_string(),
196        requested_ms: agentmux_common::time::now_ms_u64(),
197        ..Default::default()
198    }
199}
200
201/// From an entry, the agent says why, before anything is read or asked.
202fn reason_given(req: &VaultFillRequest) -> Result<String, Response> {
203    if req.vault.is_none() {
204        return Ok(String::new());
205    }
206    vault::history::require_reason(req.reason.as_deref()).map_err(|e| err_response(StatusCode::BAD_REQUEST, e))
207}
208
209/// One fill, as the steps after the field is known see it.
210struct Fill<'a> {
211    state: &'a AppState,
212    block_id: &'a str,
213    agent: &'a str,
214    reason_given: &'a str,
215    target: &'a FillTarget,
216    field: &'a Field,
217    /// Where the use is logged: the site and the field's label.
218    site: String,
219}
220
221impl Fill<'_> {
222    /// Writes the use into the Vault's Activity and the pane's Log, with what became of it.
223    fn record(&self, outcome: &str) {
224        record(self.state, self.block_id, self.target, self.agent, &self.site, outcome, self.reason_given);
225    }
226}
227
228/// What the person's answer, or the standing grant, settled.
229struct Approval {
230    always: bool,
231    went_ahead: bool,
232    /// A value the person typed because no entry exists.
233    typed_answer: Option<UseAnswer>,
234    /// Whether the field looks like what the entry is.
235    fits: bool,
236    /// Whether the person asked to keep a typed value.
237    save: bool,
238}
239
240/// `POST /api/v1/ui/browser/vault_fill`.
241pub(crate) async fn handle_vault_fill(
242    State(state): State<AppState>,
243    caller: Option<axum::Extension<crate::server::caller::Caller>>,
244    Json(req): Json<VaultFillRequest>,
245) -> Response {
246    let block_id = match target_block_id(&state, caller.as_deref(), &req.auth, req.pane.as_deref()) {
247        Ok(b) => b,
248        Err((code, e)) => return err_response(code, e),
249    };
250    let agent = req.auth.agent_id.chars().take(64).collect::<String>();
251    let reason_given = match reason_given(&req) {
252        Ok(r) => r,
253        Err(refused) => return refused,
254    };
255    // A card's id with no part, or `card`: the whole card, filled after one question.
256    if let Some(done) = card::whole_card(&state, caller.as_deref(), &req, &block_id, &agent, &reason_given).await {
257        return done;
258    }
259    let target = match find_target(&state, &req, &agent).await {
260        Ok(t) => t,
261        Err(refused) => return refused,
262    };
263    tracing::info!(agent = %agent, block_id = %block_id, entry = %target.id, "[vault] a web form fill was asked for");
264
265    let field = match field_of(&state, &block_id, &req.ref_).await {
266        Ok(f) => f,
267        Err(refused) => return refused,
268    };
269    let fill = Fill { state: &state, block_id: &block_id, agent: &agent, reason_given: &reason_given, target: &target, field: &field, site: format!("{} ({})", field.grant_key(), field.label) };
270    let Approval { always, went_ahead, typed_answer, fits, save } = match approve(&fill, caller.as_deref(), &req.auth).await {
271        Ok(a) => a,
272        Err(refused) => return refused,
273    };
274    if always {
275        let (store, entry, origin, created) = (state.identity_store.clone(), target.id.clone(), field.grant_key(), target.created_at);
276        let _ = tokio::task::spawn_blocking(move || store.vault_grant_add(&entry, &origin, agentmux_common::time::now_ms(), created)).await;
277    }
278
279    // The value leaves the sealed row only now, for the host's request.
280    let value = match value_to_type(&fill, typed_answer).await {
281        Ok(v) => v,
282        Err(refused) => return refused,
283    };
284    // Kept only if the person asked, and only once the page has taken it.
285    let to_keep = save.then(|| value.clone());
286    let (filled, invalid) = type_into_field(&fill, &req.ref_, value).await;
287    match filled {
288        Ok(data) => {
289            fill.record(if target.typed { "done (typed by the person)" } else { "done" });
290            let (entry_id, saved_note) = keep_or_touch(&fill, to_keep, fits).await;
291            let out = answer_body(&fill, &entry_id, saved_note, &data, invalid, (save, went_ahead));
292            (StatusCode::OK, Json(json!({ "ok": true, "data": out }))).into_response()
293        }
294        Err((code, e)) => {
295            fill.record("failed");
296            err_response(code, e)
297        }
298    }
299}
300
301/// The entry and part, by name only: nothing here reads the value yet.
302async fn find_target(state: &AppState, req: &VaultFillRequest, agent: &str) -> Result<FillTarget, Response> {
303    let store = state.identity_store.clone();
304    let (wanted, kind, label, who) = (req.vault.clone(), req.request_kind.clone(), req.request_label.clone(), agent.to_string());
305    match tokio::task::spawn_blocking(move || match (wanted, kind) {
306        (Some(v), None) => vault::fill_target(&store, &v, Some(&who)),
307        (None, Some(k)) => vault::request_target(&k, &label.unwrap_or_default()),
308        _ => Err("name an entry (vault), or ask for a value (request_value), not both".to_string()),
309    })
310    .await
311    {
312        Ok(Ok(t)) => Ok(t),
313        Ok(Err(e)) => Err(err_response(StatusCode::BAD_REQUEST, e)),
314        Err(e) => Err(err_response(StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
315    }
316}
317
318/// What the host says about the field `ref_` of the pane `block_id`.
319async fn field_of(state: &AppState, block_id: &str, ref_: &str) -> Result<Field, Response> {
320    match proxy_value(state, "field_info", json!({ "block_id": block_id, "ref": ref_ }), HOST_WAIT).await {
321        Ok(v) => parse_field(&v).map_err(|e| err_response(StatusCode::BAD_GATEWAY, e)),
322        Err((code, e)) => Err(err_response(code, e)),
323    }
324}
325
326/// Whether the field is refused, filled on a standing grant, or the person is asked, and what they answered.
327async fn approve(fill: &Fill<'_>, caller: Option<&crate::server::caller::Caller>, auth: &UiAutomationAuth) -> Result<Approval, Response> {
328    let (state, target, field) = (fill.state, fill.target, fill.field);
329    let store = state.identity_store.clone();
330    let (entry, origin) = (target.id.clone(), field.grant_key());
331    let granted = !target.typed && tokio::task::spawn_blocking(move || store.vault_grant_check(&entry, &origin).unwrap_or(false)).await.unwrap_or(false);
332    let fits = target.slot.is_some_and(|s| field.slots.iter().any(|x| x == s));
333
334    let (mut always, mut went_ahead) = (false, false);
335    let mut typed_answer: Option<UseAnswer> = None;
336    let mut decided = plan(!field.origin.is_empty(), field.password_like, field.fillable, granted, fits);
337    // A value nobody has stored yet is always asked for: the person types it.
338    if target.typed && !matches!(decided, Plan::Refuse(_)) {
339        decided = Plan::Ask { offer_always: false, reason: "there is no Vault entry for this yet, so you type it here" };
340    }
341    match decided {
342        Plan::Refuse(why) => {
343            fill.record("refused");
344            return Err(err_response(StatusCode::BAD_REQUEST, why.to_string()));
345        }
346        Plan::Go => {}
347        Plan::Ask { offer_always, reason } => {
348            let request = fill_request(fill.agent, super::vault_ask::agent_pane(state, caller, auth), target, field, (offer_always, reason), fill.reason_given);
349            let headline = format!("{} wants to fill your {} on {}", fill.agent, target.what, field.origin);
350            let (ended, answer) = super::vault_ask::ask(state, fill.block_id, request, ANSWER_WAIT, &headline).await;
351            if !ended.allowed() {
352                fill.record(ended.outcome());
353                let code = if ended == Ended::NoAnswer { StatusCode::REQUEST_TIMEOUT } else { StatusCode::FORBIDDEN };
354                return Err(err_response(code, ended.refusal("nothing was typed")));
355            }
356            always = ended == Ended::Always;
357            went_ahead = ended == Ended::WentAhead;
358            typed_answer = answer;
359        }
360    }
361    let save = target.typed && typed_answer.as_ref().is_some_and(|a| a.save);
362    Ok(Approval { always, went_ahead, typed_answer, fits, save })
363}
364
365/// The value to type: what the person typed, or the entry's, read from the sealed row.
366async fn value_to_type(fill: &Fill<'_>, typed_answer: Option<UseAnswer>) -> Result<zeroize::Zeroizing<String>, Response> {
367    let target = fill.target;
368    if target.typed {
369        return match typed_answer.and_then(|a| a.value).filter(|v| !v.is_empty()) {
370            Some(v) => Ok(v),
371            None => Err(err_response(StatusCode::BAD_REQUEST, "the person didn't type a value: nothing was typed".to_string())),
372        };
373    }
374    let store = fill.state.identity_store.clone();
375    let (entry, part, created) = (target.id.clone(), target.part, target.created_at);
376    match tokio::task::spawn_blocking(move || vault::value_for_fill(&store, &entry, created, part)).await {
377        Ok(Ok(v)) => Ok(v),
378        Ok(Err(e)) => {
379            fill.record("failed");
380            Err(err_response(StatusCode::BAD_REQUEST, e))
381        }
382        Err(e) => {
383            fill.record("failed");
384            Err(err_response(StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))
385        }
386    }
387}
388
389/// Asks the host to type `value`; returns its answer and whether the page flagged the value as invalid.
390async fn type_into_field(fill: &Fill<'_>, ref_: &str, value: zeroize::Zeroizing<String>) -> (Result<Value, (StatusCode, String)>, bool) {
391    let body = json!({
392        "block_id": fill.block_id,
393        "ref": ref_,
394        "text": value.as_str(),
395        "expect_origin": fill.field.origin,
396        "expect_fingerprint": fill.field.fingerprint,
397    });
398    let filled = proxy_value(fill.state, "vault_fill", body, HOST_WAIT).await;
399    // Whatever the host says, the value isn't in it: an error that quotes it (a
400    // parser's, a page's) is cleaned before the agent can see it.
401    let filled = filled.map_err(|(code, e)| (code, if value.is_empty() { e } else { e.replace(value.as_str(), "[hidden]") }));
402    // The page's own validation message is page-controlled text: it can echo the
403    // value it was given, reformatted (dashes stripped, spaces added) so that no
404    // replacement of the original finds it. The agent is told only that there is one.
405    let invalid = filled.as_ref().ok().and_then(|d| d.get("validation").and_then(Value::as_str)).is_some_and(|v| !v.is_empty());
406    drop(value);
407    (filled, invalid)
408}
409
410/// After the page took the value: keep a typed one in the Vault if the person asked (the new entry's id, or a note
411/// saying why not), or mark the entry used.
412async fn keep_or_touch(fill: &Fill<'_>, to_keep: Option<zeroize::Zeroizing<String>>, fits: bool) -> (String, Option<String>) {
413    let (state, target, field) = (fill.state, fill.target, fill.field);
414    let mut entry_id = target.id.clone();
415    let mut saved_note = None;
416    if let Some(kept) = to_keep {
417        let (store, kind, label, part) = (state.identity_store.clone(), target.kind.to_string(), target.label.clone(), target.part);
418        let origin = field.grant_key();
419        let made = tokio::task::spawn_blocking(move || {
420            let parts = vault::seal::Parts([(part.to_string(), kept.to_string())].into());
421            let id = vault::create(&store, vault::NewEntry { kind, label, fields: Default::default(), tags: vec![], parts })?;
422            if fits {
423                let created = store.vault_get(&id).map_err(|e| e.to_string())?.map(|r| r.created_at).unwrap_or(0);
424                store.vault_grant_add(&id, &origin, agentmux_common::time::now_ms(), created).map_err(|e| e.to_string())?;
425            }
426            Ok::<String, String>(id)
427        })
428        .await;
429        match made {
430            Ok(Ok(id)) => {
431                entry_id = id;
432                super::vault_handlers::publish(state);
433            }
434            Ok(Err(e)) => saved_note = Some(format!("it was typed in but couldn't be kept in the Vault: {e}")),
435            Err(e) => saved_note = Some(format!("it was typed in but couldn't be kept in the Vault: {e}")),
436        }
437    } else if !target.id.is_empty() {
438        let (store, entry) = (state.identity_store.clone(), target.id.clone());
439        let _ = tokio::task::spawn_blocking(move || store.vault_touch(&entry, agentmux_common::time::now_ms())).await;
440    }
441    (entry_id, saved_note)
442}
443
444/// What the agent is told: that the field was filled, never with what.
445fn answer_body(fill: &Fill<'_>, entry_id: &str, saved_note: Option<String>, data: &Value, invalid: bool, (save, went_ahead): (bool, bool)) -> Value {
446    let (target, field) = (fill.target, fill.field);
447    let mut out = json!({
448        "filled_from_vault": entry_id,
449        "part": target.part,
450        "value": "[secret: hidden]",
451        "site": field.origin,
452        "field": field.label,
453    });
454    if let Some(o) = out.as_object_mut() {
455        if invalid {
456            o.insert("validation".into(), json!("the page flagged the value as invalid (its message isn't shown, since a page can put the value in it)"));
457        }
458        if data.get("changed_by_page").and_then(Value::as_bool) == Some(true) {
459            o.insert("note".into(), json!("the page shortened or reformatted the value"));
460        }
461        if target.typed {
462            o.insert("typed_by_the_person".into(), json!(true));
463            o.insert("kept_in_vault".into(), json!(save && saved_note.is_none()));
464        }
465        if let Some(n) = saved_note {
466            o.insert("kept_note".into(), json!(n));
467        }
468        if went_ahead {
469            o.insert("approval".into(), json!(uses::WENT_AHEAD));
470        }
471    }
472    out
473}
474
475mod card;
476
477#[cfg(test)]
478mod tests;