agentmux_srv_core/backend/vault/
history.rs1use std::sync::atomic::{AtomicBool, Ordering};
14use std::sync::{Mutex, OnceLock};
15use std::time::{Duration, Instant};
16
17use serde::Serialize;
18
19use super::{expiry, vaults, VaultActivity, PERSON};
20use crate::backend::storage::store::Store;
21use crate::backend::storage::vault::{activity_hash, VaultActivityRow};
22use crate::identity::secret_store;
23
24pub const MIN_REASON: usize = 8;
26pub const MAX_REASON: usize = 300;
27pub const MAX_REFS: usize = 3;
29pub const MAX_REF: usize = 120;
30pub const MAX_ROWS: i64 = 1000;
32
33const HEAD_ID: &str = "vault-history-head";
35const HEAD_EVERY: Duration = Duration::from_secs(30);
37
38#[derive(Debug, Clone, Default)]
40pub struct Why {
41 pub reason: String,
42 pub refs: Vec<String>,
43}
44
45pub fn require_reason(raw: Option<&str>) -> Result<String, String> {
48 let line = one_line(raw.unwrap_or(""), usize::MAX);
49 let n = line.chars().count();
50 if n < MIN_REASON {
51 return Err(format!(
52 "a reason is required: say in one line what you need this for and why, for which task ({MIN_REASON} to {MAX_REASON} characters). The person sees it in the approval, and it is kept in the entry's history"
53 ));
54 }
55 if n > MAX_REASON {
56 return Err(format!("a reason is at most {MAX_REASON} characters, one line: yours is {n}"));
57 }
58 Ok(line)
59}
60
61pub fn actor_kind(actor: &str) -> &'static str {
63 if actor == PERSON {
64 "person"
65 } else if actor == expiry::ACTOR {
66 "srv"
67 } else {
68 "agent"
69 }
70}
71
72pub fn actor_label(actor: &str) -> String {
77 let own_part = actor == super::setting_key::AGENTMUX || actor.contains(char::is_whitespace);
78 if actor == PERSON || actor == expiry::ACTOR || own_part || actor.contains(':') {
79 actor.to_string()
80 } else {
81 format!("agent:{actor}")
82 }
83}
84
85pub fn agent_of(actor: &str) -> &str {
87 actor.strip_prefix("agent:").unwrap_or(actor)
88}
89
90pub fn one_line(text: &str, max: usize) -> String {
92 let flat = text.split_whitespace().collect::<Vec<_>>().join(" ");
93 flat.chars().take(max).collect()
94}
95
96pub fn refs_text(refs: &[String]) -> String {
98 let kept: Vec<String> = refs.iter().map(|r| one_line(r, MAX_REF)).filter(|r| !r.is_empty()).take(MAX_REFS).collect();
99 if kept.is_empty() {
100 String::new()
101 } else {
102 serde_json::to_string(&kept).unwrap_or_default()
103 }
104}
105
106pub fn refs_of(text: &str) -> Vec<String> {
108 serde_json::from_str(text).unwrap_or_default()
109}
110
111fn host() -> &'static str {
113 static HOST: OnceLock<String> = OnceLock::new();
114 HOST.get_or_init(|| {
115 let found = ["HOSTNAME", "COMPUTERNAME", "HOST"]
116 .iter()
117 .filter_map(|k| std::env::var(k).ok())
118 .chain(std::fs::read_to_string("/etc/hostname").ok())
119 .map(|h| h.trim().split('.').next().unwrap_or("").to_string())
120 .find(|h| !h.is_empty());
121 found.unwrap_or_default()
122 })
123}
124
125pub fn append(store: &Store, mut row: VaultActivityRow) {
129 row.actor_kind = actor_kind(&row.actor).into();
130 row.actor = actor_label(&row.actor);
131 row.host = host().into();
132 row.reason = one_line(&row.reason, MAX_REASON);
133 match store.vault_activity_add(&row) {
134 Ok(stored) => note_head(&stored),
135 Err(e) => tracing::warn!(error = %e, action = row.action, "vault: couldn't record activity"),
136 }
137}
138
139pub fn history_for(store: &Store, entry_id: &str, agent: Asker<'_>, limit: i64) -> Result<Vec<VaultActivity>, String> {
142 let row = store.vault_get(entry_id).map_err(|e| e.to_string())?.ok_or_else(|| format!("no entry {entry_id}"))?;
143 if let Asker::Agent(agent) = agent {
144 let allowed = store.vaults().map_err(|e| e.to_string())?.iter().find(|v| v.id == row.vault_id).is_none_or(|v| vaults::may_use(v, agent));
145 if !allowed {
146 return Err(format!("no entry {entry_id}"));
148 }
149 }
150 let rows = store.vault_activity_history(entry_id, row.created_at, limit.clamp(1, MAX_ROWS)).map_err(|e| e.to_string())?;
151 Ok(rows.into_iter().map(VaultActivity::from).collect())
152}
153
154#[derive(Debug, Clone, Copy)]
156pub enum Asker<'a> {
157 Person,
159 Agent(Option<&'a str>),
161}
162
163#[derive(Debug, Clone, Serialize, PartialEq, ts_rs::TS)]
165#[ts(export, export_to = "../../../frontend/types/rpc/")]
166pub struct VaultChain {
167 pub intact: bool,
169 pub checked: usize,
171 pub before_chain: usize,
173 pub unchained_after: usize,
176 #[ts(type = "number | null")]
178 pub broken_at: Option<i64>,
179 pub head_checked: bool,
182 pub problem: String,
184}
185
186#[derive(Debug, Clone, PartialEq)]
188pub struct Head {
189 pub seq: i64,
190 pub hash: String,
191}
192
193fn looks_unchained(r: &VaultActivityRow) -> bool {
196 r.version == 0 && r.actor_kind.is_empty() && r.host.is_empty() && r.reason.is_empty() && r.refs.is_empty() && r.prev_hash.is_empty()
197}
198
199pub fn verify_chain(rows: &[VaultActivityRow], head: Option<&Head>) -> VaultChain {
201 let mut out = VaultChain { intact: true, checked: 0, before_chain: 0, unchained_after: 0, broken_at: None, head_checked: head.is_some(), problem: String::new() };
202 let mut prev = String::new();
203 let mut broke = |out: &mut VaultChain, seq: i64, problem: &str| {
204 out.intact = false;
205 out.broken_at = Some(seq);
206 out.problem = problem.into();
207 };
208 for row in rows {
209 if row.hash.is_empty() {
210 if !looks_unchained(row) {
213 broke(&mut out, row.seq, "this line was taken out of the chain");
214 return out;
215 }
216 if out.checked > 0 {
217 out.unchained_after += 1;
218 } else {
219 out.before_chain += 1;
220 }
221 continue;
222 }
223 if row.prev_hash != prev {
224 broke(&mut out, row.seq, "the line before this one was removed or changed");
225 return out;
226 }
227 if activity_hash(&prev, row) != row.hash {
228 broke(&mut out, row.seq, "this line was changed");
229 return out;
230 }
231 prev = row.hash.clone();
232 out.checked += 1;
233 }
234 if let Some(head) = head {
235 match rows.iter().find(|r| r.seq == head.seq) {
236 None => broke(&mut out, head.seq, "the newest lines were removed"),
237 Some(r) if r.hash != head.hash => broke(&mut out, head.seq, "this line is not the one the keychain recorded"),
238 Some(_) => {}
239 }
240 }
241 out
242}
243
244pub fn check(store: &Store) -> Result<VaultChain, String> {
246 let rows = store.vault_activity_all().map_err(|e| e.to_string())?;
247 Ok(verify_chain(&rows, read_head().as_ref()))
248}
249
250fn read_head() -> Option<Head> {
251 if cfg!(any(test, feature = "test-support")) {
252 return None;
253 }
254 let stored = secret_store::get_optional(HEAD_ID).ok()??;
255 let (seq, hash) = stored.split_once(':')?;
256 Some(Head { seq: seq.parse().ok()?, hash: hash.to_string() })
257}
258
259struct HeadWrites {
260 last: Option<Instant>,
261 pending: Option<String>,
262 trailing: bool,
263}
264
265static HEAD_WRITES: Mutex<HeadWrites> = Mutex::new(HeadWrites { last: None, pending: None, trailing: false });
266static HEAD_FAILED_BEFORE: AtomicBool = AtomicBool::new(false);
267
268fn write_head(value: &str) {
269 if let Err(e) = secret_store::put(HEAD_ID, value) {
270 if !HEAD_FAILED_BEFORE.swap(true, Ordering::Relaxed) {
272 tracing::warn!(error = %e, "vault: couldn't keep the history's head in the keychain");
273 }
274 }
275}
276
277fn note_head(row: &VaultActivityRow) {
280 if cfg!(any(test, feature = "test-support")) {
281 return;
282 }
283 let value = format!("{}:{}", row.seq, row.hash);
284 let mut st = HEAD_WRITES.lock().unwrap();
285 if st.last.is_none_or(|t| t.elapsed() >= HEAD_EVERY) {
286 st.last = Some(Instant::now());
287 st.pending = None;
288 drop(st);
289 write_head(&value);
290 return;
291 }
292 st.pending = Some(value);
293 if st.trailing {
294 return;
295 }
296 st.trailing = true;
297 let wait = HEAD_EVERY.saturating_sub(st.last.map_or(Duration::ZERO, |t| t.elapsed()));
298 drop(st);
299 std::thread::spawn(move || {
300 std::thread::sleep(wait);
301 let value = {
302 let mut st = HEAD_WRITES.lock().unwrap();
303 st.trailing = false;
304 st.last = Some(Instant::now());
305 st.pending.take()
306 };
307 if let Some(value) = value {
308 write_head(&value);
309 }
310 });
311}
312
313#[cfg(test)]
314mod actor_label_tests {
315 use super::*;
316
317 #[test]
318 fn an_agent_is_written_with_its_kind_and_the_rest_stay() {
319 assert_eq!(actor_label("lolly"), "agent:lolly");
320 assert_eq!(actor_label(PERSON), PERSON);
321 assert_eq!(actor_label(expiry::ACTOR), expiry::ACTOR);
322 assert_eq!(actor_label("drone:d1"), "drone:d1");
323 assert_eq!(actor_label("agent:lolly"), "agent:lolly");
324 assert_eq!(actor_label("AgentMux voice input"), "AgentMux voice input");
325 assert_eq!(actor_label(super::super::setting_key::AGENTMUX), super::super::setting_key::AGENTMUX);
326 }
327
328 #[test]
329 fn an_agent_named_like_the_person_is_not_read_as_the_person() {
330 assert_eq!(actor_kind(&actor_label("lolly")), "agent");
332 assert_eq!(actor_kind(PERSON), "person");
333 assert_eq!(agent_of("agent:lolly"), "lolly");
334 assert_eq!(agent_of("lolly"), "lolly");
335 }
336}