Skip to main content

agentmux_srv_core/backend/vault/
mod.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The Vault: the person's secrets, which agents use by name without seeing
5//! them (docs/specs/SPEC_VAULT_PANE_AGENTS_USE_SECRETS_UNSEEN_2026_10_19.md).
6//!
7//! The person writes the Vault through the host (`server::vault_handlers`).
8//! Agents list entries' names, ask for new ones, and create entries whose value
9//! the Vault makes itself (`generate`), which no one has seen. Everything here
10//! is blocking (the store, the keychain): call it off the async runtime.
11
12pub mod account_key;
13pub mod agent_changes;
14pub mod agent_set;
15pub mod aws_import;
16pub mod aws_import_batch;
17pub mod backed;
18pub mod capture;
19pub mod changes;
20pub mod card;
21pub mod card_fill;
22pub mod card_target;
23pub mod expiry;
24pub mod files;
25pub mod generate;
26pub mod github_secret;
27pub mod history;
28pub mod import;
29pub mod inspect;
30pub mod kdbx_export;
31pub mod kdbx_names;
32pub mod kinds;
33pub mod linked;
34pub mod pace;
35pub mod proposals;
36pub mod plain_export;
37pub mod requests;
38pub mod endpoint_key;
39pub mod route_key;
40pub mod scrub;
41pub mod seal;
42pub mod setting_key;
43pub mod shares;
44pub mod signins;
45pub mod signups;
46pub mod slots;
47pub mod source_link;
48pub mod sync_activity;
49pub mod sync_adapter;
50pub mod sync_capture;
51mod sync_capture_kinds;
52pub mod sync_grant;
53pub mod sync_links;
54pub mod sync_merge;
55pub mod sync_record;
56pub mod sync_seal;
57pub mod sync_store;
58pub mod sync_take;
59mod sync_take_grants;
60pub mod transfer;
61pub mod uses;
62pub mod vaults;
63pub mod versions;
64pub mod wordlist;
65
66use std::collections::BTreeMap;
67
68use agentmux_common::time::now_ms;
69use serde::{Deserialize, Serialize};
70
71use crate::backend::storage::store::Store;
72use crate::backend::storage::vault::{VaultActivityRow, VaultRow, PERSONAL_VAULT};
73use kinds::VaultSection;
74use seal::Parts;
75
76/// The actor the activity log names for the person.
77pub const PERSON: &str = "you";
78
79const MAX_LABEL: usize = 200;
80const MAX_FIELD: usize = 4096;
81/// §8.7's cap on one value.
82const MAX_PART: usize = 1024 * 1024;
83const MAX_TAGS: usize = 50;
84const MAX_ID: usize = 48;
85
86/// An entry as the pane shows it: no value, only which parts are set and
87/// the main value's last characters.
88#[derive(Debug, Clone, Serialize, ts_rs::TS)]
89#[ts(export, export_to = "../../../frontend/types/rpc/")]
90pub struct VaultEntryInfo {
91    pub id: String,
92    /// The entry's opaque id for links (`agentmux://vault/entry/<link_id>`): says nothing about the entry (G2).
93    /// Absent only when none could be assigned.
94    #[serde(default, skip_serializing_if = "Option::is_none")]
95    #[ts(optional)]
96    pub link_id: Option<String>,
97    pub kind: String,
98    pub section: VaultSection,
99    pub label: String,
100    /// The Vault it belongs to (`vaults::VaultInfo::id`).
101    pub vault_id: String,
102    pub fields: BTreeMap<String, String>,
103    pub tags: Vec<String>,
104    /// The parts that hold a value.
105    pub parts_set: Vec<String>,
106    /// The sites an agent may fill this entry into without asking again.
107    pub grants: Vec<String>,
108    pub tail: String,
109    /// Earlier values kept for 7 days, which the person can put back.
110    pub versions: u32,
111    /// The newest check of the entry's machine copy (`source_link`) against its value; absent when the entry has no
112    /// link, or the place it names now was never checked.
113    #[serde(skip_serializing_if = "Option::is_none")]
114    #[ts(optional)]
115    pub source_checked: Option<source_link::VaultSourceCheck>,
116    /// What is known of each other place the entry names (`linked::copy_checks`); absent when it names none.
117    #[serde(skip_serializing_if = "Option::is_none")]
118    #[ts(optional)]
119    pub copies_checked: Option<Vec<linked::VaultCopyCheck>>,
120    #[ts(type = "number")]
121    pub created_at: i64,
122    #[ts(type = "number")]
123    pub updated_at: i64,
124    #[ts(type = "number")]
125    pub last_used_at: i64,
126}
127
128/// An entry as an agent sees it (`Vault` `list`): what it is called, what
129/// kind it is, when it expires (a date being no secret) and where its machine
130/// copy is, if it has one. No value, tail, other field or grant.
131#[derive(Debug, Clone, Serialize, PartialEq)]
132pub struct VaultAgentEntry {
133    pub id: String,
134    /// The entry's opaque id for a link to it (`agentmux://vault/entry/<link_id>`), which names nothing about it.
135    pub link_id: String,
136    pub label: String,
137    pub kind: String,
138    pub section: VaultSection,
139    /// The Vault's name, so an agent can say where an entry is kept and name it in `request`.
140    pub vault: String,
141    #[serde(skip_serializing_if = "Option::is_none")]
142    pub expires: Option<String>,
143    /// Where a copy of its value lives outside the Vault, and what the newest check of it found.
144    #[serde(skip_serializing_if = "Option::is_none")]
145    pub source: Option<source_link::AgentLink>,
146    /// A login the person shared with this agent's own browser profile (never with whom else, A8).
147    #[serde(skip_serializing_if = "std::ops::Not::not")]
148    pub shared_with_you: bool,
149}
150
151#[derive(Debug, Clone, Serialize, ts_rs::TS)]
152#[ts(export, export_to = "../../../frontend/types/rpc/")]
153pub struct VaultActivity {
154    #[ts(type = "number")]
155    pub at: i64,
156    pub entry_id: String,
157    pub entry_label: String,
158    pub actor: String,
159    pub action: String,
160    pub target: String,
161    pub outcome: String,
162    /// Order on this machine.
163    #[ts(type = "number")]
164    pub seq: i64,
165    /// The value version this event made or used; 0 for one that touches no value.
166    #[ts(type = "number")]
167    pub version: i64,
168    /// `agent`, `person` or `srv`; empty for a line made before this was kept.
169    pub actor_kind: String,
170    /// The machine it happened on; empty for a line made before this was kept.
171    pub host: String,
172    /// The agent's own reason; empty for the person's actions and for lines made before reasons were kept.
173    pub reason: String,
174    /// Short references the event relates to (a task, a PR).
175    pub refs: Vec<String>,
176    /// Whether it handed the entry's value to a process, a form or a sign-in (the history's "Uses").
177    pub is_use: bool,
178}
179
180impl From<VaultActivityRow> for VaultActivity {
181    fn from(r: VaultActivityRow) -> Self {
182        VaultActivity {
183            is_use: crate::backend::storage::vault::VALUE_USES.contains(&r.action.as_str()),
184            refs: history::refs_of(&r.refs),
185            at: r.at,
186            entry_id: r.entry_id,
187            entry_label: r.entry_label,
188            actor: r.actor,
189            action: r.action,
190            target: r.target,
191            outcome: r.outcome,
192            seq: r.seq,
193            version: r.version,
194            actor_kind: r.actor_kind,
195            host: r.host,
196            reason: r.reason,
197        }
198    }
199}
200
201/// A new entry from the pane.
202#[derive(Deserialize)]
203pub struct NewEntry {
204    pub kind: String,
205    pub label: String,
206    #[serde(default)]
207    pub fields: BTreeMap<String, String>,
208    #[serde(default)]
209    pub tags: Vec<String>,
210    #[serde(default)]
211    pub parts: Parts,
212}
213
214/// A change to an entry from the pane. A part left out keeps its value;
215/// `clear` empties the parts it names.
216#[derive(Deserialize)]
217pub struct EntryChange {
218    pub id: String,
219    pub label: String,
220    #[serde(default)]
221    pub fields: BTreeMap<String, String>,
222    #[serde(default)]
223    pub tags: Vec<String>,
224    #[serde(default)]
225    pub parts: Parts,
226    #[serde(default)]
227    pub clear: Vec<String>,
228}
229
230fn validate(kind: &kinds::Kind, label: &str, fields: &BTreeMap<String, String>, tags: &[String], parts: &Parts) -> Result<(), String> {
231    if label.trim().is_empty() {
232        return Err("an entry needs a label".into());
233    }
234    if label.chars().count() > MAX_LABEL {
235        return Err(format!("a label is at most {MAX_LABEL} characters"));
236    }
237    for (k, v) in fields {
238        if !kind.fields.contains(&k.as_str()) && !source_link::is_field(k) && !linked::is_field(k) && !shares::is_field(kind.name, k) {
239            return Err(format!("a {} entry has no field {k:?}", kind.name));
240        }
241        if v.len() > MAX_FIELD {
242            return Err(format!("{k} is longer than {MAX_FIELD} bytes"));
243        }
244        if k == expiry::FIELD {
245            expiry::parse(v)?;
246        }
247        if k == signins::PROFILE && !signins::is_profile(v) {
248            return Err(format!("{v:?} isn't a browser profile: personal or profile:<id>"));
249        }
250        if k == shares::SHARED && v.split(',').any(|w| w.trim() != shares::EVERY_AGENT && !shares::is_uid(w.trim())) {
251            return Err("shared lists agents by their permanent uid, or *".into());
252        }
253        if k == signins::PROXY && v != "yes" {
254            return Err("proxy is \"yes\" for a proxy's sign-in, or left out".into());
255        }
256    }
257    source_link::validate(fields)?;
258    linked::validate(fields, !parts.0.is_empty())?;
259    if tags.len() > MAX_TAGS || tags.iter().any(|t| t.chars().count() > MAX_LABEL) {
260        return Err(format!("at most {MAX_TAGS} tags, each at most {MAX_LABEL} characters"));
261    }
262    for (k, v) in &parts.0 {
263        if !kind.parts.contains(&k.as_str()) {
264            return Err(format!("a {} entry has no part {k:?}", kind.name));
265        }
266        if v.len() > MAX_PART {
267            return Err(format!("{k} is longer than 1 MiB"));
268        }
269    }
270    Ok(())
271}
272
273/// Fields and parts with nothing in them aren't kept.
274fn trimmed(fields: BTreeMap<String, String>) -> BTreeMap<String, String> {
275    fields.into_iter().map(|(k, v)| (k, v.trim().to_string())).filter(|(_, v)| !v.is_empty()).collect()
276}
277
278fn drop_empty(parts: &mut Parts) {
279    parts.0.retain(|_, v| !v.is_empty());
280}
281
282/// A card saved as the default takes the flag from the Vault's other cards: at most one has it.
283/// Runs after the save has committed, so a failure here is the caller's to log, not to fail the save
284/// with: the card is saved, and a card picker that finds two defaults takes the one saved last.
285fn keep_one_default(store: &Store, kind: &str, vault_id: &str, id: &str, fields: &BTreeMap<String, String>) -> Result<(), String> {
286    if kind != card::KIND || fields.get(card::DEFAULT).map(String::as_str) != Some("yes") {
287        return Ok(());
288    }
289    let rows = store.vault_list().map_err(|e| format!("couldn't list the cards: {e}"))?;
290    let mut failed = Vec::new();
291    for row in rows.into_iter().filter(|r| r.id != id && r.kind == card::KIND && r.vault_id == vault_id) {
292        let mut other: BTreeMap<String, String> = serde_json::from_str(&row.fields).unwrap_or_default();
293        if other.remove(card::DEFAULT).is_none() {
294            continue;
295        }
296        let cleared = serde_json::to_string(&other).map_err(|e| e.to_string()).and_then(|json| store.vault_set_fields(&row.id, &json).map_err(|e| e.to_string()));
297        if let Err(e) = cleared {
298            failed.push(format!("{}: {e}", row.id));
299        }
300    }
301    if failed.is_empty() {
302        Ok(())
303    } else {
304        Err(format!("couldn't clear the default flag of {}", failed.join("; ")))
305    }
306}
307
308/// A card whose sealed value was swapped for another (a restored version, a rotated number) gets its
309/// brand and expiry date worked out again from the parts it holds now. The parts themselves are not rewritten.
310pub(crate) fn resettle_card(store: &Store, id: &str) -> Result<(), String> {
311    let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
312    if row.kind != card::KIND {
313        return Ok(());
314    }
315    let key = seal::key(false)?;
316    let mut parts = seal::open(&key, &row.id, &row.sealed)?;
317    let before: BTreeMap<String, String> = serde_json::from_str(&row.fields).unwrap_or_default();
318    let mut fields = before.clone();
319    card::settle(card::KIND, &mut fields, &mut parts)?;
320    if fields != before {
321        let json = serde_json::to_string(&fields).map_err(|e| e.to_string())?;
322        store.vault_set_fields(&row.id, &json).map_err(|e| e.to_string())?;
323    }
324    Ok(())
325}
326
327/// A part as a fill or a command asks for it: a card's older `expiry` is read from its month and year when it has no such part.
328fn part_of(kind: &str, parts: &Parts, part: &str) -> Option<String> {
329    if kind == card::KIND {
330        card::part_value(parts, part)
331    } else {
332        parts.get(part).map(str::to_string)
333    }
334}
335
336/// A readable id that never changes: the kind and the label, e.g.
337/// `ssn-alex`, unique with a number when taken. No `.`: P3 names a part as
338/// `<id>.<part>`.
339fn new_id(store: &Store, kind: &str, label: &str) -> Result<String, String> {
340    new_id_besides(store, kind, label, &[])
341}
342
343/// [`new_id`], also skipping the ids in `taken`: ones chosen for entries not
344/// written yet (a capture's rules, written together).
345fn new_id_besides(store: &Store, kind: &str, label: &str, taken: &[String]) -> Result<String, String> {
346    let mut slug = String::new();
347    for c in format!("{kind}-{label}").chars().flat_map(char::to_lowercase) {
348        if c.is_ascii_alphanumeric() {
349            slug.push(c);
350        } else if !slug.ends_with('-') {
351            slug.push('-');
352        }
353    }
354    let mut base: String = slug.trim_matches('-').chars().take(MAX_ID).collect();
355    base = base.trim_end_matches('-').to_string();
356    for n in 1..1000 {
357        let id = if n == 1 { base.clone() } else { format!("{base}-{n}") };
358        if !taken.contains(&id) && store.vault_get(&id).map_err(|e| e.to_string())?.is_none() {
359            return Ok(id);
360        }
361    }
362    Err("too many entries with that label".into())
363}
364
365/// The actions that use an entry's value: one of an expired entry says so.
366const USES: &[&str] = &["filled a web form", signins::SIGNED_IN, "ran a command", "revealed", "copied", route_key::USED];
367
368/// Adds a line to the activity log; a failure to is logged, not raised.
369pub fn record(store: &Store, entry_id: &str, entry_label: &str, actor: &str, action: &str, target: &str, outcome: &str) {
370    let row = VaultActivityRow {
371        entry_id: entry_id.into(),
372        entry_label: entry_label.into(),
373        actor: actor.into(),
374        action: action.into(),
375        target: target.into(),
376        outcome: outcome.into(),
377        ..Default::default()
378    };
379    record_row(store, row);
380}
381
382/// A line of the record for something an agent did with an entry, with the reason it gave.
383pub struct Line<'a> {
384    pub entry_id: &'a str,
385    pub label: &'a str,
386    pub actor: &'a str,
387    pub action: &'a str,
388    pub target: &'a str,
389    pub outcome: &'a str,
390    pub reason: &'a str,
391}
392
393/// [`record`] for an agent's use or change, with its reason.
394pub fn record_line(store: &Store, l: Line<'_>) {
395    record_row(
396        store,
397        VaultActivityRow {
398            entry_id: l.entry_id.into(),
399            entry_label: l.label.into(),
400            actor: l.actor.into(),
401            action: l.action.into(),
402            target: l.target.into(),
403            outcome: l.outcome.into(),
404            reason: l.reason.into(),
405            ..Default::default()
406        },
407    );
408}
409
410/// [`record`] with the line's other parts given too: the agent's reason and references.
411pub fn record_row(store: &Store, mut row: VaultActivityRow) {
412    if USES.contains(&row.action.as_str()) && !row.entry_id.is_empty() {
413        if let Ok(Some(entry)) = store.vault_get(&row.entry_id) {
414            if expiry::expired(&entry, expiry::today()) {
415                row.target = if row.target.is_empty() { "(expired)".into() } else { format!("{} (expired)", row.target) };
416            }
417        }
418    }
419    row.at = now_ms();
420    history::append(store, row);
421}
422
423/// Saves a new entry from the person; returns its id.
424pub fn create(store: &Store, entry: NewEntry) -> Result<String, String> {
425    insert(store, entry, PERSON, "created", "")
426}
427
428/// [`create`] in the Vault `vault_id`, which must exist.
429pub fn create_in(store: &Store, entry: NewEntry, vault_id: &str) -> Result<String, String> {
430    insert_in(store, entry, PERSON, "created", "", vault_id)
431}
432
433/// Saves a new entry and records who made it and how.
434fn insert(store: &Store, entry: NewEntry, actor: &str, action: &str, target: &str) -> Result<String, String> {
435    insert_in(store, entry, actor, action, target, PERSONAL_VAULT)
436}
437
438/// [`insert`] in the Vault `vault_id`.
439fn insert_in(store: &Store, entry: NewEntry, actor: &str, action: &str, target: &str, vault_id: &str) -> Result<String, String> {
440    insert_in_why(store, entry, actor, action, target, vault_id, "")
441}
442
443/// [`insert_in`], recording the agent's `reason` for making the entry.
444fn insert_in_why(store: &Store, entry: NewEntry, actor: &str, action: &str, target: &str, vault_id: &str, reason: &str) -> Result<String, String> {
445    let (id, label) = insert_unrecorded(store, entry, vault_id)?;
446    record_line(store, Line { entry_id: &id, label: &label, actor, action, target, outcome: "done", reason });
447    Ok(id)
448}
449
450/// Saves a new entry in the Vault `vault_id` and leaves the record of it to the caller: its id and label.
451fn insert_unrecorded(store: &Store, entry: NewEntry, vault_id: &str) -> Result<(String, String), String> {
452    insert_unrecorded_bound(store, entry, vault_id, None)
453}
454
455fn insert_unrecorded_bound(store: &Store, mut entry: NewEntry, vault_id: &str, link_id: Option<&str>) -> Result<(String, String), String> {
456    store.vault_info(vault_id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no Vault {vault_id}"))?;
457    let kind = kinds::kind(&entry.kind).ok_or_else(|| format!("unknown kind {:?}", entry.kind))?;
458    drop_empty(&mut entry.parts);
459    let mut fields = trimmed(std::mem::take(&mut entry.fields));
460    if fields.contains_key(shares::SHARED) {
461        return Err("a login is shared with an agent after it is saved (the Share button on its card), never when it is made".into());
462    }
463    signins::normalize_site(kind.name, &mut fields);
464    signins::settle_profile(kind.name, &mut fields);
465    card::settle(kind.name, &mut fields, &mut entry.parts)?;
466    validate(kind, &entry.label, &fields, &entry.tags, &entry.parts)?;
467    // A linked entry is the one kind of entry with no value: it says where the key lives.
468    if !linked::is_linked(&fields) && entry.parts.get(kind.parts[0]).is_none() {
469        return Err(format!("a {} entry needs its {}", kind.name, kind.parts[0]));
470    }
471    let key = seal::key(store.vault_count().map_err(|e| e.to_string())? == 0)?;
472    let label = entry.label.trim().to_string();
473    let id = new_id(store, kind.name, &label)?;
474    let now = now_ms();
475    let row = VaultRow {
476        id: id.clone(),
477        kind: kind.name.into(),
478        label: label.clone(),
479        fields: serde_json::to_string(&fields).map_err(|e| e.to_string())?,
480        tags: serde_json::to_string(&entry.tags).map_err(|e| e.to_string())?,
481        sealed: seal::seal(&key, &id, &entry.parts)?,
482        created_at: now,
483        updated_at: now,
484        last_used_at: 0,
485        vault_id: vault_id.to_string(),
486    };
487    store.vault_insert_bound(&row, link_id).map_err(|e| e.to_string())?;
488    if let Err(e) = keep_one_default(store, kind.name, vault_id, &id, &fields) {
489        tracing::warn!(entry = %id, error = %e, "vault: the new default card is saved, but another card still has the default flag");
490    }
491    Ok((id, label))
492}
493
494/// The kinds `generate` makes, and the part it fills: a value no person needs to
495/// choose. An ID number or a card is the person's, never made up.
496pub const GENERATED_KINDS: &[(&str, &str)] = &[("api-key", "value"), ("login", "password"), ("note", "text")];
497
498/// What an agent asks `generate` for.
499#[derive(Debug, Deserialize)]
500pub struct GenerateRequest {
501    pub kind: String,
502    pub label: String,
503    #[serde(default)]
504    pub why: String,
505    /// Why the agent needs it: one line of 8 to 300 characters, required (`why` is the same thing, as it was called).
506    #[serde(default)]
507    pub reason: Option<String>,
508    /// Plain fields of the kind (a login's site and username, an API key's service).
509    #[serde(default)]
510    pub fields: BTreeMap<String, String>,
511    #[serde(default)]
512    pub rules: generate::RulesRequest,
513    /// When the value stops working (`YYYY-MM-DD`), if the agent knows: the person
514    /// is reminded before then (spec §15.2).
515    #[serde(default)]
516    pub expires: Option<String>,
517    /// The Vault to make it in, by name or id; the agent's first Vault when left out.
518    #[serde(default)]
519    pub vault: Option<String>,
520}
521
522/// What `generate` made: the entry, never its value.
523#[derive(Debug, Serialize, PartialEq)]
524pub struct Generated {
525    pub id: String,
526    pub label: String,
527    pub kind: String,
528    /// The rules it was made under, e.g. "20 characters from 66 choices, 123 bits".
529    pub made: String,
530}
531
532/// Creates an entry whose main value the Vault makes, for `actor` (the agent that
533/// asked). The value goes from the generator into the sealed row and nowhere else. A login with a site is made for no
534/// browser profile ([`generate_entry_in`] says which).
535pub fn generate_entry(store: &Store, req: GenerateRequest, actor: &str) -> Result<Generated, String> {
536    generate_entry_in(store, req, actor, None)
537}
538
539/// [`generate_entry`] for an agent whose own browser profile is `own_profile` (`profile:<id>`). A login it makes with
540/// a site belongs to that profile, and goes in the Vault the profile keeps its sign-ins in when the agent may use it:
541/// never Personal's or another profile's, which are the person's. The site and the user name are the agent's to give; where
542/// the sign-in is offered (a realm, a proxy, a profile) is the person's.
543pub fn generate_entry_in(store: &Store, req: GenerateRequest, actor: &str, own_profile: Option<&str>) -> Result<Generated, String> {
544    let reason = history::require_reason(req.reason.as_deref().filter(|r| !r.trim().is_empty()).or(Some(req.why.as_str())))?;
545    let Some((kind, part)) = GENERATED_KINDS.iter().find(|(k, _)| *k == req.kind) else {
546        let names: Vec<&str> = GENERATED_KINDS.iter().map(|(k, _)| *k).collect();
547        return Err(format!("generate makes {} entries, not {:?}: an ID number or a card is the person's, so ask for it with request", names.join(", "), req.kind));
548    };
549    if let Some(name) = [shares::SHARED, signins::PROFILE].into_iter().find(|f| req.fields.contains_key(*f)) {
550        return Err(inspect::person_only_refusal(name));
551    }
552    if let Some(site) = req.fields.get(signins::SITE).filter(|s| !s.trim().is_empty()) {
553        inspect::agent_origin(site)?;
554    }
555    let signin_profile = match (*kind == "login" && req.fields.get(signins::SITE).is_some_and(|s| !s.trim().is_empty()), own_profile) {
556        (false, _) => None,
557        (true, Some(profile)) => Some(profile.to_string()),
558        (true, None) => return Err("a login for a site is made for your own browser profile, and this call doesn't name one: sign in to AgentMux as the agent, or leave the site out".into()),
559    };
560    let rules = generate::rules(&req.rules)?;
561    let value = generate::generate(&rules)?;
562    let mut parts = Parts::default();
563    parts.0.insert(part.to_string(), value.to_string());
564    let target = generate::describe(&rules);
565    let mut fields = req.fields;
566    if let Some(profile) = &signin_profile {
567        fields.insert(signins::PROFILE.to_string(), profile.clone());
568    }
569    if let Some(date) = req.expires.filter(|d| !d.trim().is_empty()) {
570        fields.insert(expiry::FIELD.to_string(), date);
571    }
572    let entry = NewEntry { kind: kind.to_string(), label: req.label, fields, tags: Vec::new(), parts };
573    let label = entry.label.trim().to_string();
574    let vault_id = match req.vault.as_deref().map(str::trim).filter(|v| !v.is_empty()) {
575        Some(which) => vaults::resolve(store, which, Some(Some(actor)))?.id,
576        None => match &signin_profile {
577            // Offered only from the Vault its profile keeps its sign-ins in.
578            Some(profile) => {
579                let kept = signins::vault_for(store, profile)?;
580                if vaults::entry_row_usable(store, &kept, Some(actor))? {
581                    kept
582                } else {
583                    vaults::default_for(store, Some(actor))?
584                }
585            }
586            None => vaults::default_for(store, Some(actor))?,
587        },
588    };
589    let id = insert_in_why(store, entry, actor, "generated", &target, &vault_id, &reason)?;
590    if signin_profile.is_some() {
591        // A site the person never saw: a use there never goes ahead on silence (R9).
592        agent_set::mark_site(store, &id, actor);
593    }
594    Ok(Generated { id, label, kind: kind.to_string(), made: generate::describe(&rules) })
595}
596
597/// Changes an entry's label, fields, tags and the parts given.
598pub fn update(store: &Store, mut change: EntryChange) -> Result<(), String> {
599    let row = store.vault_get(&change.id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {}", change.id))?;
600    let kind = kinds::kind(&row.kind).ok_or_else(|| format!("entry {} has an unknown kind", row.id))?;
601    drop_empty(&mut change.parts);
602    let mut fields = trimmed(std::mem::take(&mut change.fields));
603    signins::normalize_site(kind.name, &mut fields);
604    signins::settle_profile(kind.name, &mut fields);
605    let old_fields: BTreeMap<String, String> = serde_json::from_str(&row.fields).unwrap_or_default();
606    // Who a login is shared with changes only by `shares::add` and `shares::remove`, which check the Vault and end an
607    // "Always" (A5, A7): an edit of the other fields leaves it as it is.
608    match old_fields.get(shares::SHARED) {
609        Some(v) => fields.insert(shares::SHARED.to_string(), v.clone()),
610        None => fields.remove(shares::SHARED),
611    };
612    validate(kind, &change.label, &fields, &change.tags, &change.parts)?;
613    if linked::mark(&fields) != linked::mark(&old_fields) {
614        return Err(linked::SET_WHEN_MADE.into());
615    }
616    if change.clear.iter().any(|p| p == kind.parts[0]) {
617        return Err(format!("a {} entry needs its {}", kind.name, kind.parts[0]));
618    }
619    let key = seal::key(false)?;
620    let mut parts = seal::open(&key, &row.id, &row.sealed)?;
621    for p in &change.clear {
622        if let Some(mut v) = parts.0.remove(p) {
623            zeroize::Zeroize::zeroize(&mut v);
624        }
625    }
626    // A new main value is the person's: the next rotation is theirs, not the agent's that made the old one.
627    let replaced = change.parts.0.contains_key(kind.parts[0]);
628    let kept = replaced.then(|| versions::of(&row, PERSON, "replaced"));
629    if replaced {
630        versions::prune(store);
631    }
632    let (was, was_fields) = (row.sealed.clone(), row.fields.clone());
633    for (k, v) in std::mem::take(&mut change.parts.0) {
634        if let Some(mut old) = parts.0.insert(k, v) {
635            zeroize::Zeroize::zeroize(&mut old);
636        }
637    }
638    card::settle(kind.name, &mut fields, &mut parts)?;
639    let label = change.label.trim().to_string();
640    let target = match (old_fields.get(expiry::FIELD), fields.get(expiry::FIELD)) {
641        (old, Some(new)) if old != Some(new) => format!("expires {new}"),
642        (Some(_), None) => "no expiry date".to_string(),
643        _ => String::new(),
644    };
645    let changed = VaultRow {
646        label: label.clone(),
647        fields: serde_json::to_string(&fields).map_err(|e| e.to_string())?,
648        tags: serde_json::to_string(&change.tags).map_err(|e| e.to_string())?,
649        sealed: seal::seal(&key, &row.id, &parts)?,
650        updated_at: now_ms(),
651        ..row
652    };
653    // Only over the value read above, and keeping the one it replaces in the same
654    // transaction: a capture or restore that landed meanwhile is never lost.
655    if !store.vault_update_kept(&changed, &was, &was_fields, kept.as_ref()).map_err(|e| e.to_string())? {
656        return Err(format!("{label} changed while you were editing it, so nothing was saved: open it again"));
657    }
658    if let Err(e) = keep_one_default(store, kind.name, &changed.vault_id, &changed.id, &fields) {
659        tracing::warn!(entry = %changed.id, error = %e, "vault: the new default card is saved, but another card still has the default flag");
660    }
661    record(store, &changed.id, &label, PERSON, if replaced { "replaced" } else { "changed" }, &target, "done");
662    Ok(())
663}
664
665/// One part's value, for the person: shown in the pane (`revealed`) or put on
666/// the clipboard by the host (`copied`). Only the host reaches this, after the
667/// OS has confirmed the person. A reveal is logged here, the value never is; a
668/// copy is logged by `record_copy` once the host has put it on the clipboard, so
669/// the trail never says copied when nothing was.
670pub fn reveal(store: &Store, id: &str, part: &str, action: &str) -> Result<zeroize::Zeroizing<String>, String> {
671    if action != "revealed" && action != "copied" {
672        return Err(format!("unknown use {action:?}"));
673    }
674    let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
675    let kind = kinds::kind(&row.kind).ok_or_else(|| format!("entry {id} has an unknown kind"))?;
676    if !kind.parts.contains(&part) {
677        return Err(format!("a {} entry has no part {part:?}", kind.name));
678    }
679    let value = if linked::is_backed_row(&row) {
680        // A backed entry keeps its value in AWS Secrets Manager, so what the person sees is what is there now.
681        backed_part(&row, part)?
682    } else {
683        let key = seal::key(false)?;
684        let parts = seal::open(&key, &row.id, &row.sealed)?;
685        let value = parts.get(part).ok_or_else(|| format!("{} has no {part} saved", row.label))?;
686        zeroize::Zeroizing::new(value.to_string())
687    };
688    if action == "revealed" {
689        store.vault_touch(&row.id, now_ms()).map_err(|e| e.to_string())?;
690        record(store, &row.id, &row.label, PERSON, action, part, "done");
691    }
692    Ok(value)
693}
694
695/// The host's report of what became of a copy: `done` notes the use, `failed`
696/// only says it didn't happen.
697pub fn record_copy(store: &Store, id: &str, part: &str, done: bool) -> Result<(), String> {
698    let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
699    if !kinds::kind(&row.kind).is_some_and(|k| k.parts.contains(&part)) {
700        return Err(format!("{} has no part {part:?}", row.label));
701    }
702    if done {
703        store.vault_touch(&row.id, now_ms()).map_err(|e| e.to_string())?;
704    }
705    record(store, &row.id, &row.label, PERSON, "copied", part, if done { "done" } else { "failed" });
706    Ok(())
707}
708
709/// What a web form fill needs to know about an entry, before anything is asked:
710/// the entry, the part, and the kind of field that part belongs in.
711#[derive(Clone)]
712pub struct FillTarget {
713    /// Empty for a value the person will type, with no entry yet.
714    pub id: String,
715    /// The kind's name.
716    pub kind: &'static str,
717    /// There is no entry: the person types the value (spec section 6.5).
718    pub typed: bool,
719    /// The kind, for keeping what they typed.
720    pub kind_info: &'static kinds::Kind,
721    pub label: String,
722    pub part: &'static str,
723    pub slot: Option<&'static str>,
724    pub what: String,
725    /// Which incarnation of the id this is: a deleted entry's id is reused by a
726    /// new one of the same kind and label, and neither a grant nor a value may
727    /// cross from one to the other while the person decides.
728    pub created_at: i64,
729    /// A version a command names instead of the current value: `previous` (the
730    /// value the last change replaced) or `pending` (a rotation's new value).
731    pub version: Option<&'static str>,
732}
733
734/// The entry `id` for an agent's use. One in a Vault the agent may not use is refused as an
735/// entry that isn't there, so an agent learns nothing about Vaults it can't use.
736fn usable_entry(store: &Store, id: &str, agent: Option<&str>) -> Result<VaultRow, String> {
737    let none = || format!("no Vault entry {id:?}: Vault's list action shows the entries");
738    let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(none)?;
739    if !vaults::entry_row_usable(store, &row.vault_id, agent)? {
740        return Err(none());
741    }
742    if let Some(no_value) = linked::no_value(&row) {
743        return Err(no_value);
744    }
745    Ok(row)
746}
747
748/// Resolves `"id"` or `"id.part"` for a fill, or says why it can't be filled.
749pub fn fill_target(store: &Store, vault: &str, agent: Option<&str>) -> Result<FillTarget, String> {
750    let (id, part) = slots::split(vault);
751    let row = usable_entry(store, id, agent)?;
752    let kind = kinds::kind(&row.kind).ok_or_else(|| format!("entry {id} has an unknown kind"))?;
753    let part = slots::fillable_part(kind, part)?;
754    let slot = slots::slot(kind, part);
755    let what = slots::what(kind, part);
756    Ok(FillTarget { id: row.id, kind: kind.name, typed: false, kind_info: kind, label: row.label, part, slot, what, created_at: row.created_at, version: None })
757}
758
759/// For a value no entry holds yet: the kind's main part, to be typed by the person.
760pub fn request_target(kind: &str, label: &str) -> Result<FillTarget, String> {
761    let kind = kinds::kind(kind).ok_or_else(|| format!("unknown kind {kind:?}"))?;
762    let label = label.trim();
763    if label.is_empty() || label.chars().count() > MAX_LABEL {
764        return Err("request_value needs a label saying what the value is, e.g. \"Alex's SSN\"".into());
765    }
766    let part = slots::fillable_part(kind, None)?;
767    Ok(FillTarget { id: String::new(), kind: kind.name, typed: true, kind_info: kind, label: label.to_string(), part, slot: slots::slot(kind, part), what: slots::what(kind, part), created_at: 0, version: None })
768}
769
770/// What a command's `secrets` entry names (`"id"` or `"id.part"`): the entry and
771/// the part handed to the process, the kind's main part unless another is named.
772/// Unlike a web form, a command may be given any kind of entry; the person is
773/// asked first (spec section 7.3).
774pub fn command_target(store: &Store, vault: &str, agent: Option<&str>) -> Result<FillTarget, String> {
775    // `id@previous` or `id@pending`, then `.part` as usual.
776    let (vault, version) = match vault.trim().split_once('@') {
777        Some((id, rest)) => {
778            let (which, part) = rest.split_once('.').map(|(w, p)| (w, Some(p))).unwrap_or((rest, None));
779            let which = match which {
780                "previous" => "previous",
781                "pending" => "pending",
782                other => return Err(format!("{id}@{other}: a command can name {id}@previous (the value the last change replaced), not @{other}")),
783            };
784            (part.map(|p| format!("{id}.{p}")).unwrap_or_else(|| id.to_string()), Some(which))
785        }
786        None => (vault.to_string(), None),
787    };
788    let mut target = command_target_now(store, &vault, agent)?;
789    target.version = version;
790    if let Some(v) = version {
791        target.what = format!("{} ({v} value)", target.what);
792    }
793    Ok(target)
794}
795
796fn command_target_now(store: &Store, vault: &str, agent: Option<&str>) -> Result<FillTarget, String> {
797    let (id, part) = slots::split(vault);
798    let row = usable_entry(store, id, agent)?;
799    let kind = kinds::kind(&row.kind).ok_or_else(|| format!("entry {id} has an unknown kind"))?;
800    let part = match part {
801        None => kind.parts[0],
802        Some(p) => *kind.parts.iter().find(|x| **x == p).ok_or_else(|| format!("{} has no part {p:?}; its parts are {}", row.label, kind.parts.join(", ")))?,
803    };
804    Ok(FillTarget { id: row.id, kind: kind.name, typed: false, kind_info: kind, label: row.label, part, slot: None, what: slots::what(kind, part), created_at: row.created_at, version: None })
805}
806
807/// A part's value for the host to type; never returned to an agent. The use is
808/// logged by the caller, with the site and the outcome.
809pub fn value_for_fill(store: &Store, id: &str, created_at: i64, part: &str) -> Result<zeroize::Zeroizing<String>, String> {
810    let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
811    if row.created_at != created_at {
812        return Err(format!("{} was replaced while the person was deciding: nothing was typed", row.label));
813    }
814    if linked::is_backed_row(&row) {
815        return backed_part(&row, part);
816    }
817    let key = seal::key(false)?;
818    let parts = seal::open(&key, &row.id, &row.sealed)?;
819    let value = part_of(&row.kind, &parts, part).ok_or_else(|| format!("{} has no {part} saved", row.label))?;
820    Ok(zeroize::Zeroizing::new(value))
821}
822
823/// The value of a backed entry's main part, read from AWS Secrets Manager now; any other part isn't there.
824fn backed_part(row: &VaultRow, part: &str) -> Result<zeroize::Zeroizing<String>, String> {
825    let main = kinds::kind(&row.kind).map(|k| k.parts[0]);
826    if main != Some(part) {
827        return Err(format!("{} has no {part} saved", row.label));
828    }
829    backed::value_of(row)
830}
831
832/// A part's value for a command: the current value, or the version `t` names
833/// (`id@previous`, a rotation's `id@pending`). Never returned to an agent.
834pub fn value_for_command(store: &Store, t: &FillTarget) -> Result<zeroize::Zeroizing<String>, String> {
835    let Some(which) = t.version else { return value_for_fill(store, &t.id, t.created_at, t.part) };
836    let row = store.vault_get(&t.id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {}", t.id))?;
837    if row.created_at != t.created_at {
838        return Err(format!("{} was replaced while the person was deciding: nothing was run", row.label));
839    }
840    if linked::is_backed_row(&row) {
841        return Err(backed::no_versions(&row, which));
842    }
843    let (_, sealed) = versions::sealed_version(store, &row, which)?;
844    let key = seal::key(false)?;
845    let parts = seal::open(&key, &row.id, &sealed)?;
846    let value = part_of(&row.kind, &parts, t.part).ok_or_else(|| format!("{}'s {which} value has no {}", row.label, t.part))?;
847    Ok(zeroize::Zeroizing::new(value))
848}
849
850pub fn delete(store: &Store, id: &str) -> Result<(), String> {
851    let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
852    store.vault_delete(id).map_err(|e| e.to_string())?;
853    // An agent asking again for the entry it was given must not get this id.
854    requests::requests().forget_entry(id);
855    record(store, id, &row.label, PERSON, "deleted", "", "done");
856    Ok(())
857}
858
859/// The prefix of every link id.
860pub const LINK_ID_PREFIX: &str = "e_";
861
862/// A new link id: the prefix and 16 random lowercase letters and digits, so it says nothing about the entry.
863fn new_link_id() -> String {
864    let hex = uuid::Uuid::new_v4().simple().to_string();
865    format!("{LINK_ID_PREFIX}{}", &hex[..16])
866}
867
868/// The link id of each entry in `ids`, given to those that have none yet (an id is assigned once and kept).
869pub fn link_ids(store: &Store, ids: &[&str]) -> Result<std::collections::HashMap<String, String>, String> {
870    let mut known = store.vault_link_ids().map_err(|e| e.to_string())?;
871    for id in ids {
872        if known.contains_key(*id) {
873            continue;
874        }
875        for _ in 0..8 {
876            if let Some(link) = store.vault_link_id_assign(id, &new_link_id()).map_err(|e| e.to_string())? {
877                known.insert(id.to_string(), link);
878                break;
879            }
880        }
881    }
882    Ok(known)
883}
884
885/// The entry a link id names, if it still exists.
886pub fn entry_of_link(store: &Store, link_id: &str) -> Result<Option<String>, String> {
887    store.vault_entry_of_link(link_id).map_err(|e| e.to_string())
888}
889
890/// Every entry for the pane, and why the values couldn't be opened if they
891/// couldn't (the tails are then empty).
892pub fn list_for_pane(store: &Store) -> Result<(Vec<VaultEntryInfo>, Option<String>), String> {
893    let rows = store.vault_list().map_err(|e| e.to_string())?;
894    let mut grants = store.vault_grants().map_err(|e| e.to_string())?;
895    versions::prune(store);
896    let counts = store.vault_version_counts().map_err(|e| e.to_string())?;
897    let mut links = link_ids(store, &rows.iter().map(|r| r.id.as_str()).collect::<Vec<_>>())?;
898    let key = if rows.is_empty() { Ok(None) } else { seal::key(false).map(Some) };
899    let mut problem = key.as_ref().err().cloned();
900    let mut out = Vec::with_capacity(rows.len());
901    for row in rows {
902        let Some(kind) = kinds::kind(&row.kind) else { continue };
903        let (parts_set, tail) = match &key {
904            Ok(Some(key)) => match seal::open(key, &row.id, &row.sealed) {
905                Ok(parts) => (parts.0.keys().cloned().collect(), parts.get(kind.parts[0]).map(|v| kinds::tail(kind, v)).unwrap_or_default()),
906                Err(e) => {
907                    problem.get_or_insert(e);
908                    (Vec::new(), String::new())
909                }
910            },
911            _ => (Vec::new(), String::new()),
912        };
913        let source_checked = source_link::Link::of_row(&row).and_then(|link| source_link::last_check(store, &row, &link));
914        let copies_checked = Some(linked::copy_checks(store, &row)).filter(|copies| !copies.is_empty());
915        out.push(VaultEntryInfo {
916            source_checked,
917            copies_checked,
918            fields: serde_json::from_str(&row.fields).unwrap_or_default(),
919            tags: serde_json::from_str(&row.tags).unwrap_or_default(),
920            section: kind.section,
921            grants: grants.remove(&row.id).unwrap_or_default(),
922            versions: counts.get(&row.id).filter(|(created, _)| *created == row.created_at).map(|(_, n)| *n).unwrap_or(0),
923            link_id: links.remove(&row.id),
924            id: row.id,
925            kind: row.kind,
926            label: row.label,
927            vault_id: row.vault_id,
928            parts_set,
929            tail,
930            created_at: row.created_at,
931            updated_at: row.updated_at,
932            last_used_at: row.last_used_at,
933        });
934    }
935    Ok((out, problem))
936}
937
938/// Every entry `agent` may use, as it may see it. Reads no value, so it never needs the
939/// keychain. An agent that isn't proven (`None`) sees the Vaults open to every agent.
940pub fn list_for_agent(store: &Store, agent: Option<&str>) -> Result<Vec<VaultAgentEntry>, String> {
941    list_for_agent_as(store, agent, None)
942}
943
944/// [`list_for_agent`], telling the agent whose permanent uid is `uid` which logins are shared with it.
945pub fn list_for_agent_as(store: &Store, agent: Option<&str>, uid: Option<&str>) -> Result<Vec<VaultAgentEntry>, String> {
946    let vaults = store.vaults().map_err(|e| e.to_string())?;
947    let rows = store.vault_list().map_err(|e| e.to_string())?;
948    let mut links = link_ids(store, &rows.iter().map(|r| r.id.as_str()).collect::<Vec<_>>())?;
949    Ok(rows
950        .into_iter()
951        .filter_map(|r| {
952            let vault = vaults.iter().find(|v| v.id == r.vault_id);
953            if !vault.is_none_or(|v| vaults::may_use(v, agent)) {
954                return None;
955            }
956            let section = kinds::kind(&r.kind)?.section;
957            let expires = expiry::of(&r).map(|d| d.to_string());
958            let vault = vault.map(|v| v.name.clone()).unwrap_or_default();
959            let source = source_link::for_agent(store, &r);
960            let shared_with_you = uid.is_some_and(|u| shares::names(&signins::fields_of(&r), u));
961            let link_id = links.remove(&r.id).unwrap_or_default();
962            Some(VaultAgentEntry { id: r.id, link_id, label: r.label, kind: r.kind, section, vault, expires, source, shared_with_you })
963        })
964        .collect())
965}
966
967pub fn activity(store: &Store, limit: i64) -> Result<Vec<VaultActivity>, String> {
968    Ok(store
969        .vault_activity_list(limit.clamp(1, 1000))
970        .map_err(|e| e.to_string())?
971        .into_iter()
972        .map(VaultActivity::from)
973        .collect())
974}
975
976#[cfg(test)]
977mod agent_changes_tests;
978#[cfg(test)]
979mod agent_place_tests;
980#[cfg(test)]
981mod card_scan_tests;
982#[cfg(test)]
983mod history_tests;
984#[cfg(test)]
985mod tests;
986#[cfg(test)]
987mod transfer_tests;