Skip to main content

agentmux_srv_core/backend/vault/
versions.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! An entry's earlier values
5//! (docs/specs/SPEC_VAULT_GENERATE_CAPTURE_AND_BROWSER_SIGNINS_2026_10_28.md §4.4).
6//!
7//! A new value (an edit, a capture, later a rotation or a browser save) becomes
8//! the current one; the value it replaces is kept for 7 days, marked when and by
9//! whom it was replaced, and the person can put it back from the Vault pane. Only
10//! the current value is ever filled or delivered, except a version a command names
11//! (`id@previous`, a rotation's `id@pending`). A version is the entry's sealed blob
12//! as it was: nothing here opens one except to show its last characters or to
13//! hand it to such a command.
14//!
15//! A rotation (`Vault` `rotate`) keeps its new value as a **pending** version until
16//! its commands succeed, then makes it current; if they fail, the pending version
17//! stays for 7 days, marked with the step that failed, and the person can put it
18//! in from the pane (the service may already hold it).
19
20use agentmux_common::time::now_ms;
21use serde::Serialize;
22
23use super::{kinds, record, seal};
24use crate::backend::storage::store::Store;
25use crate::backend::storage::vault::VaultRow;
26use crate::backend::storage::vault_versions::VaultVersionRow;
27
28/// How long a replaced value is kept (§12, decision 8).
29pub const KEEP_MS: i64 = 7 * 24 * 60 * 60 * 1000;
30pub const PREVIOUS: &str = "previous";
31/// A rotation's new value, not yet the entry's.
32pub const PENDING: &str = "pending";
33/// A pending value whose rotation never finished (srv stopped during it).
34pub const INTERRUPTED: &str = "rotation interrupted";
35/// A pending value that wasn't made current because the entry changed meanwhile.
36pub const OVERTAKEN: &str = "rotation failed: the entry changed meanwhile";
37/// What the state of a version that a sync conflict kept starts with, then why it was kept ("changed on <machine> at the
38/// same time", `sync_merge::Kept::label`). Unlike the others it is not pruned after 7 days: the person settles it. A
39/// version kept for a delete holds no value (an empty blob): it is only shown.
40pub const KEPT_PREFIX: &str = "kept: ";
41/// How long a rotation may run before its pending value counts as interrupted.
42const ROTATION_MS: i64 = 30 * 60 * 1000;
43
44/// A pending value whose rotation failed at `step` (2: `set`, 3: `verify`).
45pub fn failed_at(step: u8) -> String {
46    format!("rotation failed at step {step}")
47}
48
49/// A version the person may put back: an earlier value, or a rotation's value
50/// that didn't become current (the service may hold it).
51fn restorable(v: &VaultVersionRow) -> bool {
52    let state = v.state.as_str();
53    state == PREVIOUS || state == INTERRUPTED || state.starts_with("rotation failed") || (state.starts_with(KEPT_PREFIX) && !v.sealed.is_empty())
54}
55
56/// A version that a sync conflict kept, which is not past any 7 days.
57fn is_kept(state: &str) -> bool {
58    state.starts_with(KEPT_PREFIX)
59}
60
61/// An earlier value as the pane shows it: when it was replaced and by whom, and
62/// its last characters as the entry's own value shows them. No value.
63#[derive(Debug, Clone, Serialize, ts_rs::TS)]
64#[ts(export, export_to = "../../../frontend/types/rpc/")]
65pub struct VaultVersionInfo {
66    #[ts(type = "number")]
67    pub seq: i64,
68    #[ts(type = "number")]
69    pub replaced_at: i64,
70    pub replaced_by: String,
71    pub how: String,
72    pub tail: String,
73    /// "previous", "pending", "rotation failed at step 2", "rotation interrupted".
74    pub state: String,
75}
76
77/// `row`'s current value as the version `by` replaces it with (`how`:
78/// "replaced", "captured", …).
79pub(super) fn of(row: &VaultRow, by: &str, how: &str) -> VaultVersionRow {
80    VaultVersionRow {
81        seq: 0,
82        entry_id: row.id.clone(),
83        entry_created_at: row.created_at,
84        sealed: row.sealed.clone(),
85        replaced_at: now_ms(),
86        replaced_by: by.to_string(),
87        how: how.to_string(),
88        state: PREVIOUS.to_string(),
89    }
90}
91
92/// Deletes what is past its 7 days, and marks a rotation's pending value that
93/// has waited longer than any rotation runs as interrupted (its request was
94/// dropped, or srv stopped): the person can then put it in. A failure is
95/// logged, not raised.
96pub fn prune(store: &Store) {
97    if let Err(e) = store.vault_versions_restate_before(PENDING, now_ms() - ROTATION_MS, INTERRUPTED) {
98        tracing::warn!(error = %e, "vault: couldn't mark interrupted rotations");
99    }
100    if let Err(e) = store.vault_versions_prune(now_ms() - KEEP_MS, KEPT_PREFIX) {
101        tracing::warn!(error = %e, "vault: couldn't delete old versions");
102    }
103    if let Err(e) = store.vault_details_prune(now_ms() - KEEP_MS) {
104        tracing::warn!(error = %e, "vault: couldn't delete old details");
105    }
106}
107
108/// The entry's earlier values, newest first.
109pub fn list(store: &Store, id: &str) -> Result<Vec<VaultVersionInfo>, String> {
110    prune(store);
111    let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
112    let kind = kinds::kind(&row.kind).ok_or_else(|| format!("entry {id} has an unknown kind"))?;
113    let versions = store.vault_versions(&row.id, row.created_at).map_err(|e| e.to_string())?;
114    let key = if versions.is_empty() { None } else { Some(seal::key(false)?) };
115    Ok(versions
116        .into_iter()
117        .map(|v| {
118            let tail = key
119                .as_ref()
120                .and_then(|k| seal::open(k, &row.id, &v.sealed).ok())
121                .and_then(|parts| parts.get(kind.parts[0]).map(|main| kinds::tail(kind, main)))
122                .unwrap_or_default();
123            VaultVersionInfo { seq: v.seq, replaced_at: v.replaced_at, replaced_by: v.replaced_by, how: v.how, tail, state: v.state }
124        })
125        .collect())
126}
127
128/// Puts version `seq` back as the entry's value, for the person; the value it
129/// replaces is kept like any other.
130pub fn restore(store: &Store, id: &str, seq: i64) -> Result<(), String> {
131    let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
132    let chosen = store.vault_version_get(seq).map_err(|e| e.to_string())?;
133    let kept_since = now_ms() - KEEP_MS;
134    let Some(chosen) = chosen.filter(|v| v.entry_id == row.id && v.entry_created_at == row.created_at && restorable(v) && (v.replaced_at >= kept_since || is_kept(&v.state))) else {
135        return Err(format!("{} has no earlier value {seq}: it may be past its 7 days", row.label));
136    };
137    let now = now_ms();
138    let current = VaultVersionRow {
139        seq: 0,
140        entry_id: row.id.clone(),
141        entry_created_at: row.created_at,
142        sealed: row.sealed.clone(),
143        replaced_at: now,
144        replaced_by: super::PERSON.to_string(),
145        how: "restored".to_string(),
146        state: PREVIOUS.to_string(),
147    };
148    // A kept version is not past its time whenever it was kept.
149    let since = if is_kept(&chosen.state) { 0 } else { kept_since };
150    if !store.vault_version_swap(&row.id, chosen.seq, &current, now, since).map_err(|e| e.to_string())? {
151        return Err(format!("{} changed while restoring: nothing was changed", row.label));
152    }
153    if let Err(e) = super::resettle_card(store, &row.id) {
154        tracing::warn!(entry = %row.id, error = %e, "vault: a restored card's brand and expiry date could not be worked out again");
155    }
156    let when = chrono::DateTime::from_timestamp_millis(chosen.replaced_at)
157        .map(|t| t.with_timezone(&chrono::Local).format("%Y-%m-%d %H:%M").to_string())
158        .unwrap_or_default();
159    record(store, &row.id, &row.label, super::PERSON, "restored", &format!("the value replaced {when}"), "done");
160    Ok(())
161}
162
163/// A rotation under way: its pending version, and the entry as it was read.
164#[derive(Debug)]
165pub struct Rotation {
166    pub seq: i64,
167    pub label: String,
168    /// Who started it, and what it is called in the entry's history ("rotated", "password change").
169    pub by: String,
170    how: String,
171    created_at: i64,
172    /// The entry's value when the rotation started: if anything else writes it
173    /// meanwhile, the rotation doesn't overwrite that.
174    was: Vec<u8>,
175}
176
177/// Starts a rotation of entry `id`: `value` goes into its main part as a pending
178/// version that nothing is given yet. Refused while another rotation of it runs.
179pub fn start_rotation(store: &Store, id: &str, value: &str, agent: &str) -> Result<Rotation, String> {
180    start_pending(store, id, value, agent, "rotated")
181}
182
183/// [`start_rotation`] for a value that is called `how` in the entry's history: a password change on a site
184/// (`changes.rs`) keeps its new password the same way, pending until the site was sent it.
185pub(super) fn start_pending(store: &Store, id: &str, value: &str, agent: &str, how: &str) -> Result<Rotation, String> {
186    let row = store.vault_get(id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {id}"))?;
187    let kind = kinds::kind(&row.kind).ok_or_else(|| format!("entry {id} has an unknown kind"))?;
188    let key = seal::key(false)?;
189    let mut parts = seal::open(&key, &row.id, &row.sealed)?;
190    if let Some(mut old) = parts.0.insert(kind.parts[0].to_string(), value.to_string()) {
191        zeroize::Zeroize::zeroize(&mut old);
192    }
193    let now = now_ms();
194    let pending = VaultVersionRow {
195        seq: 0,
196        entry_id: row.id.clone(),
197        entry_created_at: row.created_at,
198        sealed: seal::seal(&key, &row.id, &parts)?,
199        replaced_at: now,
200        replaced_by: agent.to_string(),
201        how: how.to_string(),
202        state: PENDING.to_string(),
203    };
204    prune(store);
205    match store.vault_version_pending(&pending, now - ROTATION_MS, INTERRUPTED).map_err(|e| e.to_string())? {
206        Some(seq) => Ok(Rotation { seq, label: row.label, by: agent.to_string(), how: how.to_string(), created_at: row.created_at, was: row.sealed }),
207        None => Err(format!("{} is being rotated already: wait for that rotation to finish", row.label)),
208    }
209}
210
211/// Ends a rotation: `Ok` makes its pending value the entry's, the value it
212/// replaces kept like any other; `Err(step)` keeps it, marked with the step that
213/// failed. An entry changed meanwhile is never overwritten: the pending value is
214/// kept, marked, and the rotation fails.
215pub fn finish_rotation(store: &Store, id: &str, r: &Rotation, outcome: Result<(), u8>, agent: &str) -> Result<(), String> {
216    if let Err(step) = outcome {
217        store.vault_version_mark(r.seq, &failed_at(step)).map_err(|e| e.to_string())?;
218        return Ok(());
219    }
220    let changed = || format!("{} changed while it was rotated: the new value is kept as a version", r.label);
221    let row = store.vault_get(id).map_err(|e| e.to_string())?.filter(|row| row.created_at == r.created_at).ok_or_else(changed)?;
222    let now = now_ms();
223    // Swapped only if the entry still holds the value the rotation started from.
224    let previous = VaultVersionRow { sealed: r.was.clone(), ..of(&row, agent, &r.how) };
225    if !store.vault_version_swap(&row.id, r.seq, &previous, now, now - KEEP_MS).map_err(|e| e.to_string())? {
226        let _ = store.vault_version_mark(r.seq, OVERTAKEN);
227        return Err(changed());
228    }
229    if let Err(e) = super::resettle_card(store, &row.id) {
230        tracing::warn!(entry = %row.id, error = %e, "vault: a rotated card's brand and expiry date could not be worked out again");
231    }
232    Ok(())
233}
234
235/// A pending value of entry `row` that is exactly `value`, started as `how`: the change a site was just sent.
236/// Found in the Vault, not in memory, so it counts across an srv restart. The pending value is never given back.
237pub(super) fn pending_is(store: &Store, row: &VaultRow, value: &str, how: &str) -> Result<Option<Rotation>, String> {
238    let kind = kinds::kind(&row.kind).ok_or_else(|| format!("entry {} has an unknown kind", row.id))?;
239    let versions = store.vault_versions(&row.id, row.created_at).map_err(|e| e.to_string())?;
240    let Some(pending) = versions.into_iter().find(|v| v.state == PENDING && v.how == how) else { return Ok(None) };
241    let parts = seal::open(&seal::key(false)?, &row.id, &pending.sealed)?;
242    if parts.get(kind.parts[0]) != Some(value) {
243        return Ok(None);
244    }
245    Ok(Some(Rotation { seq: pending.seq, label: row.label.clone(), by: pending.replaced_by, how: pending.how, created_at: row.created_at, was: row.sealed.clone() }))
246}
247
248/// Entry `row`'s earlier pending values started as `how` that no site is known to hold any longer: kept 7 days
249/// for the person to put in, as an interrupted rotation's is, so a new one can start.
250pub(super) fn set_aside_pending(store: &Store, row: &VaultRow, how: &str) -> Result<(), String> {
251    for v in store.vault_versions(&row.id, row.created_at).map_err(|e| e.to_string())? {
252        if v.state == PENDING && v.how == how {
253            store.vault_version_mark(v.seq, INTERRUPTED).map_err(|e| e.to_string())?;
254        }
255    }
256    Ok(())
257}
258
259/// Drops a rotation whose `set` never started: no service saw its value, so
260/// there is nothing to keep or put back.
261pub fn abandon_rotation(store: &Store, r: &Rotation) -> Result<(), String> {
262    store.vault_version_delete(r.seq).map_err(|e| e.to_string())
263}
264
265/// Version `seq` of entry `id` (this incarnation), for a command that names it:
266/// its sealed blob, or why it can't be had.
267pub fn sealed_version(store: &Store, row: &VaultRow, which: &str) -> Result<(i64, Vec<u8>), String> {
268    let versions = store.vault_versions(&row.id, row.created_at).map_err(|e| e.to_string())?;
269    let kept_since = now_ms() - KEEP_MS;
270    let found = match which {
271        "previous" => versions.into_iter().find(|v| v.state == PREVIOUS && v.replaced_at >= kept_since),
272        "pending" => versions.into_iter().find(|v| v.state == PENDING),
273        other => return Err(format!("{}@{other}: name @previous or @pending", row.id)),
274    };
275    found.map(|v| (v.seq, v.sealed)).ok_or_else(|| format!("{} has no {which} value", row.label))
276}
277
278#[cfg(test)]
279#[path = "versions_tests.rs"]
280mod tests;