1use 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
30const 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 #[serde(default)]
43 vault: Option<String>,
44 #[serde(default)]
47 request_kind: Option<String>,
48 #[serde(default)]
49 request_label: Option<String>,
50 #[serde(default)]
52 reason: Option<String>,
53}
54
55pub(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
66pub(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
75struct Field {
77 origin: String,
78 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 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#[derive(Debug, PartialEq, Eq)]
109pub(crate) enum Plan {
110 Refuse(&'static str),
111 Go,
112 Ask { offer_always: bool, reason: &'static str },
113}
114
115pub(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
136fn 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 note(block_id, agent, Kind::Fill).detail(&format!("{} from the Vault", target.what)).how(how_of(outcome)).record(state);
153 super::vault_handlers::publish(state);
155}
156
157pub(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
178fn 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
201fn 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
209struct 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 site: String,
219}
220
221impl Fill<'_> {
222 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
228struct Approval {
230 always: bool,
231 went_ahead: bool,
232 typed_answer: Option<UseAnswer>,
234 fits: bool,
236 save: bool,
238}
239
240pub(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 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 let value = match value_to_type(&fill, typed_answer).await {
281 Ok(v) => v,
282 Err(refused) => return refused,
283 };
284 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
301async 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
318async 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
326async 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 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
365async 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
389async 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 let filled = filled.map_err(|(code, e)| (code, if value.is_empty() { e } else { e.replace(value.as_str(), "[hidden]") }));
402 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
410async 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
444fn 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;