Skip to main content

agentmux_srv_core/backend/vault/
inspect.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! What an agent can ask the Vault about an entry and about the Vault itself: `show`, `update` (details only),
5//! `verify` and `health` (docs/specs/SPEC_VAULT_PARITY_ENTRY_HISTORY_REASONS_AND_IMPORT_2026_11_06.md ยง8). Every
6//! answer is ids, names, states and counts: no sealed value, tail or hash of one. A problem line says what is wrong
7//! in fixed words and never quotes a field's value.
8
9use std::collections::BTreeMap;
10
11use agentmux_common::time::now_ms;
12use serde::{Deserialize, Serialize};
13use zeroize::Zeroize;
14
15use super::source_link::{self, Link};
16use super::{agent_set, expiry, history, kinds, linked, record_line, seal, shares, signins, signups, validate, vaults, Line, Parts};
17use crate::backend::storage::store::Store;
18use crate::backend::storage::vault_changes::DetailsKept;
19use crate::backend::storage::vault::{VaultActivityRow, VaultRow, VALUE_SETTING};
20
21/// The Activity action of a change to an entry's label, plain fields or tags.
22pub const CHANGED_DETAILS: &str = "changed details";
23/// An entry expiring within this many days counts as expiring soon.
24const SOON_DAYS: i64 = 14;
25/// An entry nobody has used for this long counts as unused.
26const UNUSED_DAYS: i64 = 90;
27const DAY_MS: i64 = 24 * 60 * 60 * 1000;
28
29/// The Vault key, or why it couldn't be read: what `verify` and `health` open the sealed rows with.
30pub type KeyResult = Result<seal::Key, String>;
31
32/// Every entry in a Vault `agent` may use (`None`: one that isn't proven, which sees the Vaults open to every agent).
33fn usable(store: &Store, agent: Option<&str>) -> Result<Vec<VaultRow>, String> {
34    let vaults = store.vaults().map_err(|e| e.to_string())?;
35    let rows = store.vault_list().map_err(|e| e.to_string())?;
36    Ok(rows.into_iter().filter(|r| vaults.iter().find(|v| v.id == r.vault_id).is_none_or(|v| vaults::may_use(v, agent))).collect())
37}
38
39/// `id`'s entry if `agent` may use it; anything else is "no entry", as for an id that isn't there.
40pub(super) fn entry_for(store: &Store, id: &str, agent: Option<&str>) -> Result<VaultRow, String> {
41    let no_entry = || format!("no entry {id}");
42    let row = store.vault_get(id.trim()).map_err(|e| e.to_string())?.ok_or_else(no_entry)?;
43    if !vaults::entry_row_usable(store, &row.vault_id, agent)? {
44        return Err(no_entry());
45    }
46    Ok(row)
47}
48
49fn fields_of(row: &VaultRow) -> BTreeMap<String, String> {
50    serde_json::from_str(&row.fields).unwrap_or_default()
51}
52
53/// An entry as `show` gives it.
54#[derive(Debug, Serialize, PartialEq)]
55pub struct Shown {
56    pub id: String,
57    pub kind: String,
58    pub label: String,
59    pub vault: String,
60    pub fields: BTreeMap<String, String>,
61    pub tags: Vec<String>,
62    /// Which secret parts hold a value: names only. Empty when the Vault key can't open the entry (`readable` false).
63    pub parts_set: Vec<String>,
64    pub readable: bool,
65    /// The date its value stops working, when it has one.
66    pub expires: Option<String>,
67    /// `none`, `ok`, `soon` (within 14 days) or `expired`.
68    pub expiry: &'static str,
69    pub days_left: Option<i64>,
70    /// How many times its value was set (the version it is on now). 0 for an entry a file import made: its history
71    /// has one summary line for the whole file, not one of its own.
72    pub value_version: i64,
73    /// Earlier values kept for 7 days.
74    pub kept_versions: usize,
75    pub created_at: i64,
76    pub updated_at: i64,
77    /// 0 when it was never used.
78    pub last_used_at: i64,
79    /// The entry is a link: it holds no value, and its fields say where the key lives and who reads it. A use of it is
80    /// refused.
81    #[serde(skip_serializing_if = "std::ops::Not::not")]
82    pub link_only: bool,
83    /// The entry is backed by AWS Secrets Manager: the Vault keeps no value, and each use reads it there.
84    #[serde(skip_serializing_if = "std::ops::Not::not")]
85    pub backed: bool,
86    /// The newest check of the place its fields name, when there is one of the entry as it is now.
87    #[serde(skip_serializing_if = "Option::is_none")]
88    pub checked: Option<source_link::VaultSourceCheck>,
89    /// A login the person shared with this agent's own browser profile (never with whom else, A8).
90    #[serde(skip_serializing_if = "std::ops::Not::not")]
91    pub shared_with_you: bool,
92}
93
94fn expiry_state(row: &VaultRow, today: chrono::NaiveDate) -> (&'static str, Option<i64>) {
95    let Some(date) = expiry::of(row) else { return ("none", None) };
96    let left = (date - today).num_days();
97    let state = if expiry::expired(row, today) { "expired" } else if left <= SOON_DAYS { "soon" } else { "ok" };
98    (state, Some(left))
99}
100
101/// `show`: the entry's kind, label, plain fields, tags, which parts are set, expiry state, Vault, version counts and
102/// last use, for an entry in a Vault `agent` may use. It is what an agent is given, so the login the entry's machine
103/// copy is read under is not among the fields, as in `list`.
104pub fn show(store: &Store, id: &str, agent: Option<&str>, key: &KeyResult, today: chrono::NaiveDate) -> Result<Shown, String> {
105    show_as(store, id, (agent, None), key, today)
106}
107
108/// [`show`], telling the agent `(name, permanent uid)` whether the login is shared with it.
109pub fn show_as(store: &Store, id: &str, (agent, uid): (Option<&str>, Option<&str>), key: &KeyResult, today: chrono::NaiveDate) -> Result<Shown, String> {
110    let row = entry_for(store, id, agent)?;
111    let shared_with_you = uid.is_some_and(|u| shares::names(&fields_of(&row), u));
112    let kind = kinds::kind(&row.kind).ok_or_else(|| format!("entry {} has an unknown kind", row.id))?;
113    let (parts_set, readable) = match key.as_ref().ok().and_then(|k| seal::open(k, &row.id, &row.sealed).ok()) {
114        Some(mut parts) => {
115            let set = kind.parts.iter().filter(|p| parts.get(p).is_some_and(|v| !v.is_empty())).map(|p| p.to_string()).collect();
116            parts.0.values_mut().for_each(|v| v.zeroize());
117            (set, true)
118        }
119        None => (Vec::new(), false),
120    };
121    let (expiry, days_left) = expiry_state(&row, today);
122    let value_version = store.vault_activity_for_entry(&row.id, &VALUE_SETTING, row.created_at, 1).map_err(|e| e.to_string())?.first().map_or(0, |r| r.version);
123    let kept_versions = store.vault_versions(&row.id, row.created_at).map_err(|e| e.to_string())?.len();
124    let vault = store.vault_info(&row.vault_id).map_err(|e| e.to_string())?.map(|v| v.name).unwrap_or_default();
125    Ok(Shown {
126        link_only: linked::is_linked_row(&row) && !linked::is_backed_row(&row),
127        backed: linked::is_backed_row(&row),
128        checked: Link::of_row(&row).and_then(|link| source_link::last_check(store, &row, &link)),
129        fields: source_link::fields_for_agent(fields_of(&row)),
130        tags: serde_json::from_str(&row.tags).unwrap_or_default(),
131        expires: expiry::of(&row).map(|d| d.to_string()),
132        id: row.id,
133        kind: row.kind,
134        label: row.label,
135        vault,
136        parts_set,
137        readable,
138        expiry,
139        days_left,
140        value_version,
141        kept_versions,
142        created_at: row.created_at,
143        updated_at: row.updated_at,
144        last_used_at: row.last_used_at,
145        shared_with_you,
146    })
147}
148
149/// What an agent asks `update` for: a new label, plain fields (an empty value removes one) and a new set of tags.
150/// Never a value: that is `rotate`, `generate`, `import` with `id` or `capture`.
151#[derive(Debug, Clone, Deserialize)]
152pub struct UpdateRequest {
153    pub id: String,
154    #[serde(default)]
155    pub label: Option<String>,
156    #[serde(default)]
157    pub fields: BTreeMap<String, String>,
158    #[serde(default)]
159    pub tags: Option<Vec<String>>,
160    #[serde(default)]
161    pub reason: Option<String>,
162}
163
164#[derive(Debug, Serialize, PartialEq)]
165pub struct Updated {
166    pub id: String,
167    pub label: String,
168    /// What changed, as the history line says it: `label`, `field notes`, `expires 2027-01-31`, `tags`.
169    pub changed: Vec<String>,
170    /// Where the login is offered (`field site`, `field realm`, `field proxy`) changes the agent asked for on a login it did
171    /// not make: recorded for the person, not made.
172    #[serde(skip_serializing_if = "Vec::is_empty")]
173    pub proposed: Vec<String>,
174    /// Says what a proposal is, when there is one.
175    #[serde(skip_serializing_if = "Option::is_none")]
176    pub note: Option<String>,
177}
178
179/// What an agent is told about a change it proposed.
180pub const PROPOSED_NOTE: &str = "recorded as a proposal; it takes effect when the person accepts it. The login keeps its old site, realm and proxy until then.";
181
182/// Fields that say where a saved sign-in is offered (the site, the realm, which browser profile, a proxy): the
183/// person's to set, like choosing a sign-in Vault. An agent that could change them could point a login's password at
184/// a site of its own.
185/// What an agent is told when it names a field only the person sets.
186pub(super) fn person_only_refusal(name: &str) -> String {
187    if name == signins::PROFILE {
188        return format!("{name} is your own browser profile, which AgentMux sets for a login you make with a site: leave it out");
189    }
190    if name == shares::SHARED {
191        return format!("{name} decides where a saved sign-in is offered, and to whom: the person sets it in the Vault pane (an agent asks to be given a login with Vault share)");
192    }
193    format!("{name} decides where a saved sign-in is offered: the person sets it in the Vault pane")
194}
195
196/// Who may use a login is a grant of use, and a use asks: not an edit (R10).
197fn person_only(field: &str) -> bool {
198    field == shares::SHARED
199}
200
201/// Fields that say where a login is offered. An agent changes them on a login it made, and proposes the change on any other.
202fn is_place(field: &str) -> bool {
203    [signins::SITE, signins::REALM, signins::PROXY, signins::PROFILE].contains(&field)
204}
205
206/// A site an agent gives: an exact origin (scheme, host, optional port; no path, query, user information or wildcard),
207/// kept in its canonical form. Empty is allowed for a field that can be removed (`allow_empty`).
208pub(super) fn agent_origin(site: &str) -> Result<String, String> {
209    let site = site.trim();
210    if site.contains('*') {
211        return Err(format!("a site is one exact origin, like https://example.com: {site:?} has a wildcard"));
212    }
213    agentmux_common::allowed_origins::bare_origin(site).ok_or_else(|| format!("a site is one exact origin, like https://example.com (scheme, host and optional port; no path, query or user information): {site:?} is not"))
214}
215
216/// Tags AgentMux itself sets to keep a sign-in from being offered (the site refused it, or it was made on a sign-up
217/// and not yet sent): an agent can neither add nor clear them.
218const RESERVED_TAGS: [&str; 2] = [signins::REFUSED, signups::UNCONFIRMED];
219
220/// The tags after `asked` replaces `now`: the reserved ones the entry has stay, and asking for one it lacks is refused.
221fn apply_tags(now: &[String], asked: &[String]) -> Result<Vec<String>, String> {
222    if let Some(tag) = asked.iter().find(|t| RESERVED_TAGS.contains(&t.as_str()) && !now.contains(t)) {
223        return Err(format!("the tag {tag:?} is set by AgentMux, not by an agent"));
224    }
225    let mut tags: Vec<String> = asked.iter().filter(|t| !RESERVED_TAGS.contains(&t.as_str())).cloned().collect();
226    tags.extend(now.iter().filter(|t| RESERVED_TAGS.contains(&t.as_str())).cloned());
227    Ok(tags)
228}
229
230/// The fields after `asked` is applied to `now`: a value is trimmed, an empty one removes the field.
231fn apply_fields(kind: &kinds::Kind, now: &BTreeMap<String, String>, asked: &BTreeMap<String, String>) -> Result<BTreeMap<String, String>, String> {
232    let mut fields = now.clone();
233    for (name, value) in asked {
234        if person_only(name) {
235            return Err(person_only_refusal(name));
236        }
237        if !kind.fields.contains(&name.as_str()) && !source_link::is_field(name) && !linked::is_field(name) {
238            return Err(format!("a {} entry has no field {name:?}", kind.name));
239        }
240        match value.trim() {
241            "" => fields.remove(name),
242            v => fields.insert(name.clone(), v.to_string()),
243        };
244    }
245    source_link::settle_kind(&mut fields, asked);
246    if linked::mark(&fields) != linked::mark(now) {
247        return Err(linked::SET_WHEN_MADE.into());
248    }
249    Ok(fields)
250}
251
252/// What differs between an entry's details before and after, named the way its history line names it. A field's value
253/// is never in it, except an expiry date (no secret, and the person is told of it anyway).
254fn what_changed(row: &VaultRow, label: &str, fields: &BTreeMap<String, String>, tags: &[String]) -> Vec<String> {
255    let before = fields_of(row);
256    let mut out = Vec::new();
257    if label != row.label {
258        out.push("label".to_string());
259    }
260    for name in before.keys().chain(fields.keys()).collect::<std::collections::BTreeSet<_>>() {
261        if before.get(name) == fields.get(name) {
262            continue;
263        }
264        out.push(match (name.as_str(), fields.get(name)) {
265            (expiry::FIELD, Some(date)) => format!("expires {date}"),
266            (expiry::FIELD, None) => "no expiry date".to_string(),
267            _ => format!("field {name}"),
268        });
269    }
270    let old_tags: Vec<String> = serde_json::from_str(&row.tags).unwrap_or_default();
271    if old_tags != tags {
272        out.push("tags".to_string());
273    }
274    out
275}
276
277/// An `update` that has been checked: the entry as read, and what it would become.
278struct Planned {
279    row: VaultRow,
280    reason: String,
281    label: String,
282    fields: BTreeMap<String, String>,
283    tags: Vec<String>,
284    changed: Vec<String>,
285    /// Where-the-login-is-offered changes asked for on a login the agent did not make: (field, value).
286    proposals: Vec<(String, String)>,
287    /// A site, realm or proxy the agent changes on its own login in this call.
288    place_changed: bool,
289}
290
291/// The actions an agent's creation of an entry leaves as its first line.
292const CREATING: [&str; 3] = ["generated", "imported", "captured"];
293/// How long after an entry's creation its creation line is written: the two are made in one call.
294const CREATION_LINE_MS: i64 = 10_000;
295
296/// Whether the entry's first history line is `agent`'s creation of it: the login is one it made. The line must be a creation
297/// (an entry with no local creation line, one taken from another machine or imported in bulk, is nobody's here: an agent's
298/// later `import` over it, or a proposal, is not its making) and written when the entry was.
299fn made_by(store: &Store, row: &VaultRow, agent: &str) -> bool {
300    let first = store.vault_activity_first(&row.id, row.created_at).ok().flatten();
301    first.is_some_and(|line| line.actor_kind == "agent" && history::actor_label(&line.actor) == history::actor_label(agent) && is_creation(&line, row))
302}
303
304/// Whether `line`, the first local line of `row`, is the creation of it: a creating action written when the entry was. An
305/// entry with no local creation line (taken from another machine, imported in bulk) has none, and its first line is an edit.
306pub(super) fn is_creation(line: &VaultActivityRow, row: &VaultRow) -> bool {
307    CREATING.contains(&line.action.as_str()) && (0..=CREATION_LINE_MS).contains(&(line.at - row.created_at))
308}
309
310/// Splits the place fields out of what an agent asked for and settles each: on a login the agent made, a site, realm or proxy
311/// is set (a profile only to the agent's own, and only where there is none); on any other login it becomes a proposal.
312/// Returns the proposals; the rest of the asked fields come back in `rest`.
313fn settle_place(
314    store: &Store,
315    row: &VaultRow,
316    asked: &BTreeMap<String, String>,
317    agent: &str,
318    own_profile: Option<&str>,
319) -> Result<(BTreeMap<String, String>, Vec<(String, String)>), String> {
320    let mut rest: BTreeMap<String, String> = asked.iter().filter(|(k, _)| !is_place(k)).map(|(k, v)| (k.clone(), v.clone())).collect();
321    let place: Vec<(&String, &String)> = asked.iter().filter(|(k, _)| is_place(k)).collect();
322    if place.is_empty() {
323        return Ok((rest, Vec::new()));
324    }
325    if row.kind != "login" {
326        return Err(format!("a {} entry has no field {:?}", row.kind, place[0].0));
327    }
328    let mine = made_by(store, row, agent);
329    let have = fields_of(row);
330    let mut proposals = Vec::new();
331    for (field, value) in place {
332        let value = value.trim();
333        if field == signins::PROFILE {
334            let current = have.get(signins::PROFILE).map(String::as_str).filter(|p| !p.is_empty());
335            let fits = mine && (current == Some(value) || (current.is_none() && own_profile == Some(value)));
336            if !fits {
337                return Err(format!("{field} says whose browser may use a saved sign-in, which is a share: ask for it with Vault share (a login you made for your own profile already has it)"));
338            }
339            rest.insert(field.clone(), value.to_string());
340            continue;
341        }
342        let settled = if value.is_empty() && field != signins::SITE {
343            String::new()
344        } else if field == signins::SITE {
345            agent_origin(value)?
346        } else {
347            value.to_string()
348        };
349        if mine {
350            rest.insert(field.clone(), settled);
351        } else if have.get(field.as_str()).map(String::as_str).unwrap_or("") != settled {
352            proposals.push((field.clone(), settled));
353        }
354    }
355    Ok((rest, proposals))
356}
357
358/// Every check of an `update`, with nothing written: the reason, that the agent may use the entry, and that the new
359/// details are ones the entry can have and differ from what it has.
360fn planned(store: &Store, req: &UpdateRequest, agent: &str, own_profile: Option<&str>) -> Result<Planned, String> {
361    let reason = history::require_reason(req.reason.as_deref())?;
362    let row = entry_for(store, &req.id, Some(agent))?;
363    let kind = kinds::kind(&row.kind).ok_or_else(|| format!("entry {} has an unknown kind", row.id))?;
364    let label = req.label.as_deref().map(str::trim).filter(|l| !l.is_empty()).unwrap_or(&row.label).to_string();
365    let (asked, proposals) = settle_place(store, &row, &req.fields, agent, own_profile)?;
366    let fields = apply_fields(kind, &fields_of(&row), &asked)?;
367    let had: Vec<String> = serde_json::from_str(&row.tags).unwrap_or_default();
368    let tags = match &req.tags {
369        Some(tags) => apply_tags(&had, &tags.iter().map(|t| t.trim().to_string()).filter(|t| !t.is_empty()).collect::<Vec<_>>())?,
370        None => had,
371    };
372    validate(kind, &label, &fields, &tags, &Parts::default())?;
373    // A proposal is held to the same rules as the change it asks for: it is never queued if it could not be applied.
374    if !proposals.is_empty() {
375        let mut proposed = fields.clone();
376        for (field, value) in &proposals {
377            match value.as_str() {
378                "" => proposed.remove(field),
379                v => proposed.insert(field.clone(), v.to_string()),
380            };
381        }
382        validate(kind, &label, &proposed, &tags, &Parts::default())?;
383    }
384    let changed = what_changed(&row, &label, &fields, &tags);
385    let place_changed = changed.iter().any(|c| matches!(c.as_str(), "field site" | "field realm" | "field proxy"));
386    if changed.is_empty() && proposals.is_empty() {
387        return Err("nothing to change: give a new label, a field's new value or tags that differ from what the entry has".into());
388    }
389    Ok(Planned { row, reason, label, fields, tags, changed, proposals, place_changed })
390}
391
392/// What an `update` that passed every check is about, for the line a refusal of it leaves.
393pub struct Checked {
394    pub id: String,
395    pub label: String,
396    pub reason: String,
397}
398
399/// Every check of an `update` with nothing written, so a refusal that follows (the pace) is only ever written for a call
400/// that was valid: a reason, an entry the agent may use, and a change.
401pub fn check_update(store: &Store, req: &UpdateRequest, agent: &str, own_profile: Option<&str>) -> Result<Checked, String> {
402    let planned = planned(store, req, agent, own_profile)?;
403    Ok(Checked { id: planned.row.id, label: planned.row.label, reason: planned.reason })
404}
405
406/// `update`: changes an entry's label, plain fields and tags, with the agent's reason, for an entry in a Vault it may
407/// use. The sealed value is not opened or touched. Nobody is asked, a change to where the entry's machine copy is
408/// included: it records one `changed details` line, which is the record
409/// (docs/specs/SPEC_VAULT_AGENT_ADDS_AND_EDITS_WITHOUT_ASKING_2026_11_25.md).
410pub fn update_details(store: &Store, req: &UpdateRequest, agent: &str) -> Result<Updated, String> {
411    update_details_for(store, req, agent, None)
412}
413
414/// [`update_details`] for an agent whose own browser profile is `own_profile` (`profile:<id>`): on a login it made, it may
415/// set that profile where the login has none. On a login it made, a site, realm or proxy is set at once and left unseen
416/// (`agent_set`); on any other login each is recorded as a proposal and the login is unchanged ([`proposals`]). The
417/// details a change replaces are kept 7 days, in the same transaction.
418pub fn update_details_for(store: &Store, req: &UpdateRequest, agent: &str, own_profile: Option<&str>) -> Result<Updated, String> {
419    let plan = planned(store, req, agent, own_profile)?;
420    let Planned { row, reason, label, fields, tags, changed, proposals, place_changed } = plan;
421    let id = row.id.clone();
422    if !changed.is_empty() {
423        let (was, was_fields) = (row.sealed.clone(), row.fields.clone());
424        let kept = DetailsKept {
425            entry_id: row.id.clone(),
426            entry_created_at: row.created_at,
427            label: row.label.clone(),
428            fields: row.fields.clone(),
429            tags: row.tags.clone(),
430            changed_at: now_ms(),
431            changed_by: history::actor_label(agent),
432            what: changed.join(", "),
433        };
434        let new = VaultRow {
435            label: label.clone(),
436            fields: serde_json::to_string(&fields).map_err(|e| e.to_string())?,
437            tags: serde_json::to_string(&tags).map_err(|e| e.to_string())?,
438            // Always later than what was read, so two changes in one millisecond are not taken for one revision.
439            updated_at: now_ms().max(row.updated_at + 1),
440            ..row
441        };
442        // A place the person never saw is marked in the same transaction: a use there never goes ahead on silence (R9).
443        let mark = place_changed.then_some(agent);
444        if !store.vault_update_details_kept(&new, &was, &was_fields, &kept, mark).map_err(|e| e.to_string())? {
445            return Err(format!("{label} changed while this was being saved, so nothing was changed: look at it again"));
446        }
447        let target = changed.join(", ");
448        record_line(store, Line { entry_id: &new.id, label: &label, actor: agent, action: CHANGED_DETAILS, target: &target, outcome: "done", reason: &reason });
449    }
450    let mut proposed = Vec::new();
451    let mut failed = Vec::new();
452    for (field, value) in &proposals {
453        match super::proposals::propose(store, &id, field, value, agent, &reason) {
454            Ok(()) => proposed.push(format!("field {field}")),
455            Err(e) => failed.push(format!("{field}: {e}")),
456        }
457    }
458    if changed.is_empty() && proposed.is_empty() && !failed.is_empty() {
459        return Err(failed.join("; "));
460    }
461    let mut notes = Vec::new();
462    if !proposed.is_empty() {
463        notes.push(PROPOSED_NOTE.to_string());
464    }
465    if !failed.is_empty() {
466        // What was changed stays changed: the agent is told, not given an error for a change that was made.
467        notes.push(format!("the change was made, but a proposal was not recorded ({}): ask again", failed.join("; ")));
468    }
469    let note = (!notes.is_empty()).then(|| notes.join(" "));
470    Ok(Updated { id, label, changed, proposed, note })
471}
472
473/// One thing `verify` found wrong. `id` is empty for the history as a whole.
474#[derive(Debug, Serialize, PartialEq)]
475pub struct Problem {
476    pub id: String,
477    pub problem: String,
478}
479
480#[derive(Debug, Serialize, PartialEq)]
481pub struct Verified {
482    /// How many entries were looked at.
483    pub checked: usize,
484    pub ok: bool,
485    pub problems: Vec<Problem>,
486}
487
488/// What is wrong with an entry's structure and its sealed row, in fixed words: its kind, its plain fields, its main
489/// part, and that the Vault key opens it. Never a value. A removed history line is found by the chain, not here.
490fn entry_problems(row: &VaultRow, key: &KeyResult, today: chrono::NaiveDate) -> Vec<String> {
491    let Some(kind) = kinds::kind(&row.kind) else { return vec![format!("its kind {:?} isn't one this AgentMux knows", row.kind)] };
492    let mut out = Vec::new();
493    if row.label.trim().is_empty() {
494        out.push("it has no label".to_string());
495    }
496    for (name, value) in fields_of(row) {
497        if !kind.fields.contains(&name.as_str()) && !source_link::is_field(&name) && !linked::is_field(&name) && !shares::is_field(kind.name, &name) {
498            out.push(format!("it has a field a {} entry doesn't have: {name}", kind.name));
499        } else if name == expiry::FIELD && expiry::parse(&value).is_err() {
500            out.push("its expiry date isn't a date (YYYY-MM-DD)".to_string());
501        } else if name == signins::PROFILE && !signins::is_profile(&value) {
502            out.push("its profile field isn't a browser profile".to_string());
503        }
504    }
505    if let Some(date) = expiry::of(row).filter(|_| expiry::expired(row, today)) {
506        out.push(format!("its value expired on {date}: rotate or replace it"));
507    }
508    if source_link::validate(&fields_of(row)).is_err() {
509        out.push("where its machine copy is isn't written the way that kind of place is".to_string());
510    }
511    if linked::validate(&fields_of(row), false).is_err() {
512        out.push("what it records about its key (link, readers, rotated, copies) isn't written the way those are".to_string());
513    }
514    out.extend(sealed_problems(row, kind, key));
515    out
516}
517
518fn sealed_problems(row: &VaultRow, kind: &kinds::Kind, key: &KeyResult) -> Option<String> {
519    let key = match key {
520        Ok(key) => key,
521        Err(_) => return Some("its sealed value can't be checked: the Vault key can't be read".to_string()),
522    };
523    let Ok(mut parts) = seal::open(key, &row.id, &row.sealed) else {
524        return Some("its sealed value doesn't open with this computer's Vault key (it was sealed by another key, or it is damaged)".to_string());
525    };
526    let main = kind.parts[0];
527    let missing = !parts.get(main).is_some_and(|v| !v.is_empty());
528    let extra: Vec<String> = parts.0.keys().filter(|p| !kind.parts.contains(&p.as_str())).cloned().collect();
529    parts.0.values_mut().for_each(|v| v.zeroize());
530    // A link is the one entry with no value: having one is what is wrong with it.
531    if linked::is_linked_row(row) {
532        return (!missing).then(|| "it is a link, which holds no value, and it has one".to_string());
533    }
534    if missing {
535        return Some(format!("its {main} isn't set"));
536    }
537    (!extra.is_empty()).then(|| format!("it has a part a {} entry doesn't have: {}", kind.name, extra.join(", ")))
538}
539
540/// `verify`: each entry (the one named, else every entry `agent` may use) and, without an id, the whole history's
541/// chain. `key` is the Vault key as read (or why it couldn't be). An expired entry is a problem.
542pub fn verify(store: &Store, id: Option<&str>, agent: Option<&str>, key: &KeyResult, today: chrono::NaiveDate) -> Result<Verified, String> {
543    let rows = match id.map(str::trim).filter(|i| !i.is_empty()) {
544        Some(id) => vec![entry_for(store, id, agent)?],
545        None => usable(store, agent)?,
546    };
547    let mut problems = Vec::new();
548    for row in &rows {
549        for problem in entry_problems(row, key, today) {
550            problems.push(Problem { id: row.id.clone(), problem });
551        }
552    }
553    if id.is_none_or(|i| i.trim().is_empty()) {
554        let chain = history::check(store)?;
555        if !chain.intact {
556            let at = chain.broken_at.map(|s| format!(" at line {s}")).unwrap_or_default();
557            problems.push(Problem { id: String::new(), problem: format!("the history's chain doesn't hold{at}: {}", chain.problem) });
558        }
559    }
560    Ok(Verified { checked: rows.len(), ok: problems.is_empty(), problems })
561}
562
563#[derive(Debug, Serialize, PartialEq)]
564pub struct KeyStore {
565    pub readable: bool,
566    pub backend: String,
567    pub problem: String,
568}
569
570#[derive(Debug, Serialize, PartialEq)]
571pub struct HistoryState {
572    pub intact: bool,
573    pub checked: usize,
574    pub before_chain: usize,
575    pub unchained_after: usize,
576    pub head_checked: bool,
577    pub problem: String,
578}
579
580#[derive(Debug, Serialize, PartialEq)]
581pub struct Health {
582    pub key_store: KeyStore,
583    /// Over the Vaults `agent` may use.
584    pub entries: usize,
585    pub vaults: usize,
586    pub expiring_within_14_days: usize,
587    pub expired: usize,
588    pub unused_for_90_days: usize,
589    /// Linked entries (they hold no value, and say where a key lives), and how their newest checks stand: the place
590    /// changed since the date recorded or is missing; never checked, or not for 30 days.
591    pub linked: usize,
592    pub linked_changed_or_missing: usize,
593    pub linked_unchecked_for_30_days: usize,
594    pub history: HistoryState,
595    /// This agent's own, still waiting for the person.
596    pub pending_requests: usize,
597    pub pending_uses: usize,
598    pub schema_revision: usize,
599}
600
601/// `health`: the key store, counts over the Vaults `agent` may use, the history chain, this agent's pending asks and
602/// the schema revision. No value.
603pub fn health(store: &Store, agent: Option<&str>, key: &KeyResult, backend: &str, today: chrono::NaiveDate) -> Result<Health, String> {
604    let rows = usable(store, agent)?;
605    let vaults = store.vaults().map_err(|e| e.to_string())?.iter().filter(|v| vaults::may_use(v, agent)).count();
606    let (mut soon, mut expired, mut unused) = (0, 0, 0);
607    let (mut links, mut links_off, mut links_unchecked) = (0, 0, 0);
608    let stale_before = now_ms() - UNUSED_DAYS * DAY_MS;
609    for row in &rows {
610        // A link is never used through the Vault, so it is not counted as unused: its check says how it stands.
611        if let Some((standing, unchecked)) = linked::standing(store, row) {
612            links += 1;
613            links_off += usize::from(standing == linked::Standing::NeedsALook);
614            links_unchecked += usize::from(unchecked);
615        } else if row.last_used_at.max(row.created_at) < stale_before {
616            unused += 1;
617        }
618        match expiry_state(row, today).0 {
619            "expired" => expired += 1,
620            "soon" => soon += 1,
621            _ => {}
622        }
623    }
624    let chain = history::check(store)?;
625    let me = |a: &str| agent.is_some_and(|me| me == a);
626    Ok(Health {
627        key_store: KeyStore { readable: key.is_ok(), backend: backend.to_string(), problem: key.as_ref().err().cloned().unwrap_or_default() },
628        entries: rows.len(),
629        vaults,
630        expiring_within_14_days: soon,
631        expired,
632        unused_for_90_days: unused,
633        linked: links,
634        linked_changed_or_missing: links_off,
635        linked_unchecked_for_30_days: links_unchecked,
636        history: HistoryState {
637            intact: chain.intact,
638            checked: chain.checked,
639            before_chain: chain.before_chain,
640            unchained_after: chain.unchained_after,
641            head_checked: chain.head_checked,
642            problem: chain.problem,
643        },
644        pending_requests: super::requests::requests().list().iter().filter(|r| me(&r.agent)).count(),
645        pending_uses: super::uses::uses().list().iter().filter(|u| me(&u.agent)).count(),
646        schema_revision: crate::backend::storage::vault::schema_revision(),
647    })
648}
649
650#[cfg(test)]
651#[path = "inspect_tests.rs"]
652mod tests;