1use crate::config_history;
21use rusqlite::{params, Connection, OptionalExtension};
22use serde::Serialize;
23
24#[derive(Debug, Serialize, PartialEq, Eq)]
25pub struct Report {
26 pub history_versions: usize,
28 pub snapshots: usize,
30 pub pending_values: usize,
32 pub unreachable: Vec<&'static str>,
34}
35
36const UNREACHABLE: [&str; 5] = [
37 "backups and recovery packages made before now (they keep what the vault held then)",
38 "nodes that received a file containing the value",
39 "the source the entry was imported from (Git store, password manager, service)",
40 "a `.v1.bak` left by an old schema migration",
41 "freed disk space: an SSD or copy-on-write filesystem may keep old blocks",
42];
43
44fn rotation_running(conn: &Connection, entry_id: &str, provider: &str) -> Result<bool, String> {
46 crate::rotation::init_schema(conn)?;
47 Ok(crate::rotation::list_runs(conn)?
48 .iter()
49 .any(|r| !r.is_finished() && (r.entry == entry_id || r.entry == provider)))
50}
51
52pub fn forget_entry(
53 conn: &Connection,
54 entry_id: &str,
55 provider: &str,
56 actor: Option<&str>,
57) -> Result<Report, String> {
58 config_history::init_schema(conn)?;
59 if rotation_running(conn, entry_id, provider)? {
60 return Err(format!(
61 "A rotation of {provider} is still running; finish or abandon it before forgetting its history"
62 ));
63 }
64 let key = format!("id\u{1}{entry_id}");
65 let exists: bool = conn
66 .query_row(
67 "SELECT 1 FROM vault_rows WHERE kind = 'entry' AND key = ?1",
68 params![key],
69 |_| Ok(true),
70 )
71 .optional()
72 .map_err(|e| e.to_string())?
73 .unwrap_or(false);
74 if !exists {
75 return Err(format!("No entry with id {entry_id}"));
76 }
77 conn.execute_batch("BEGIN IMMEDIATE")
78 .map_err(|e| e.to_string())?;
79 let done = (|| -> Result<Report, String> {
80 let history_versions = match conn
81 .query_row(
82 "SELECT data FROM vault_history WHERE key = ?1",
83 params![key],
84 |r| r.get::<_, String>(0),
85 )
86 .optional()
87 .map_err(|e| e.to_string())?
88 {
89 Some(text) => {
90 let n = serde_json::from_str::<serde_json::Value>(&text)
91 .ok()
92 .and_then(|v| v.as_array().map(|a| a.len()))
93 .unwrap_or(1);
94 conn.execute("DELETE FROM vault_history WHERE key = ?1", params![key])
95 .map_err(|e| e.to_string())?;
96 n
97 }
98 None => 0,
99 };
100
101 let like = format!("%{}%", entry_id.replace(['%', '_'], ""));
103 let candidates: Vec<(i64, String)> = {
104 let mut st = conn
105 .prepare(
106 "SELECT seq, exposed FROM config_snapshots WHERE forgotten = 0 AND exposed LIKE ?1",
107 )
108 .map_err(|e| e.to_string())?;
109 let rows = st
110 .query_map(params![like], |r| Ok((r.get(0)?, r.get(1)?)))
111 .map_err(|e| e.to_string())?;
112 rows.collect::<Result<_, _>>().map_err(|e| e.to_string())?
113 };
114 let mut snapshots = 0;
115 for (seq, exposed) in candidates {
116 let list: Vec<crate::blast::Exposed> =
117 serde_json::from_str(&exposed).map_err(|e| e.to_string())?;
118 if list.iter().any(|x| x.entry_id == entry_id) {
119 conn.execute(
120 "UPDATE config_snapshots SET content = '', forgotten = 1 WHERE seq = ?1",
121 params![seq],
122 )
123 .map_err(|e| e.to_string())?;
124 snapshots += 1;
125 }
126 }
127
128 let pending_values = conn
129 .execute(
130 "DELETE FROM rotation_pending WHERE run_id IN \
131 (SELECT id FROM rotation_runs WHERE entry = ?1 OR entry = ?2)",
132 params![entry_id, provider],
133 )
134 .map_err(|e| e.to_string())?;
135
136 crate::record_event(
137 conn,
138 "entry.forget",
139 provider,
140 Some(
141 &serde_json::json!({
142 "entry_id": entry_id, "history_versions": history_versions,
143 "snapshots": snapshots, "pending_values": pending_values
144 })
145 .to_string(),
146 ),
147 actor,
148 )?;
149 Ok(Report {
150 history_versions,
151 snapshots,
152 pending_values,
153 unreachable: UNREACHABLE.to_vec(),
154 })
155 })();
156 match done {
157 Ok(r) => {
158 conn.execute_batch("COMMIT").map_err(|e| e.to_string())?;
159 Ok(r)
160 }
161 Err(e) => {
162 let _ = conn.execute_batch("ROLLBACK");
163 Err(e)
164 }
165 }
166}
167
168#[cfg(test)]
169mod tests {
170 use super::*;
171 use crate::config_history::{self, Stream};
172 use serde_json::json;
173
174 const OLD: &str = "OLD-SECRET-VALUE-aaaa";
175
176 fn db() -> Connection {
177 let c = Connection::open_in_memory().unwrap();
178 crate::init_schema(&c).unwrap();
179 crate::save_vault(
180 &c,
181 json!({ "api_keys": [
182 { "id": "a", "provider": "A", "api_key": "live-a",
183 "version_history": [{ "value": OLD, "saved_at": "2026-01-01T00:00:00Z" }] },
184 { "id": "b", "provider": "B", "api_key": "live-b",
185 "version_history": [{ "value": "b-old", "saved_at": "2026-01-01T00:00:00Z" }] }
186 ] }),
187 crate::SaveCtx {
188 actor: None,
189 expect_version: None,
190 },
191 )
192 .unwrap();
193 c
194 }
195
196 fn snap(c: &Connection, exporter: &str, body: &str, entry_id: &str) -> i64 {
197 let exposed = json!([{ "entry_id": entry_id, "provider": "X", "key_id": "",
198 "field": "version_history", "fp": "f", "short": false }])
199 .to_string();
200 let s = Stream {
201 project: "p1",
202 project_name: "edge",
203 exporter,
204 };
205 config_history::record(c, &s, body, "masked", &exposed, "save", None)
206 .unwrap()
207 .unwrap()
208 }
209
210 fn mentions(c: &Connection, needle: &str) -> bool {
212 let tables: Vec<String> = c
213 .prepare(
214 "SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'",
215 )
216 .unwrap()
217 .query_map([], |r| r.get(0))
218 .unwrap()
219 .map(|r| r.unwrap())
220 .collect();
221 for t in tables {
222 let cols: Vec<String> = c
223 .prepare(&format!("PRAGMA table_info(\"{t}\")"))
224 .unwrap()
225 .query_map([], |r| r.get(1))
226 .unwrap()
227 .map(|r| r.unwrap())
228 .collect();
229 for col in cols {
230 let n: i64 = c
231 .query_row(
232 &format!(
233 "SELECT count(*) FROM \"{t}\" WHERE CAST(\"{col}\" AS TEXT) LIKE ?1"
234 ),
235 [format!("%{needle}%")],
236 |r| r.get(0),
237 )
238 .unwrap();
239 if n > 0 {
240 return true;
241 }
242 }
243 }
244 false
245 }
246
247 #[test]
248 fn the_old_value_is_found_before_and_not_after_and_everything_else_survives() {
249 let c = db();
250 let mine = snap(&c, "nginx", &format!("token={OLD}\n"), "a");
251 let other = snap(&c, "compose", "token=b-old\n", "b");
252 assert!(mentions(&c, OLD));
253
254 let r = forget_entry(&c, "a", "A", Some("owner")).unwrap();
255 assert_eq!((r.history_versions, r.snapshots), (1, 1));
256 assert!(!r.unreachable.is_empty());
257 assert!(!mentions(&c, OLD), "the value is gone from every table");
258
259 assert!(config_history::get(&c, other)
261 .unwrap()
262 .unwrap()
263 .content
264 .contains("b-old"));
265 assert_eq!(
266 crate::storage::entry_history(&c, "b").unwrap().unwrap()[0]["value"],
267 "b-old"
268 );
269 assert_eq!(
270 crate::storage::entry_history(&c, "a").unwrap().unwrap(),
271 json!([])
272 );
273 assert!(mentions(&c, "live-a"));
274
275 assert!(config_history::get(&c, mine)
277 .err()
278 .unwrap()
279 .contains("forgotten"));
280 assert_eq!(
281 config_history::list(&c, Some("p1"), None, None, 10)
282 .unwrap()
283 .len(),
284 2
285 );
286
287 let audit = crate::load_audit(&c).unwrap();
289 let row = audit.iter().find(|a| a.action == "entry.forget").unwrap();
290 assert!(!row.details.clone().unwrap().contains(OLD));
291 assert!(crate::verify_audit(&c).unwrap());
292 assert!(config_history::verify(&c).unwrap().problems.is_empty());
293 assert!(crate::storage::verify(&c).unwrap());
294 }
295
296 #[test]
297 fn a_snapshot_that_is_forgotten_but_edited_back_in_is_reported() {
298 let c = db();
299 let s = snap(&c, "nginx", &format!("token={OLD}\n"), "a");
300 forget_entry(&c, "a", "A", None).unwrap();
301 c.execute(
302 "UPDATE config_snapshots SET content = 'x' WHERE seq = ?1",
303 [s],
304 )
305 .unwrap();
306 assert!(!config_history::verify(&c).unwrap().problems.is_empty());
307 c.execute(
309 "UPDATE config_snapshots SET content = '', sha256 = 'beef' WHERE seq = ?1",
310 [s],
311 )
312 .unwrap();
313 assert!(!config_history::verify(&c).unwrap().problems.is_empty());
314 }
315
316 #[test]
317 fn an_unknown_entry_and_a_running_rotation_are_refused_and_change_nothing() {
318 let c = db();
319 snap(&c, "nginx", &format!("token={OLD}\n"), "a");
320 assert!(forget_entry(&c, "nope", "N", None)
321 .unwrap_err()
322 .contains("No entry"));
323
324 crate::rotation::init_schema(&c).unwrap();
325 let run = crate::rotation::Run::plan(
326 "r1",
327 "A",
328 2,
329 crate::rotation::Class::CreateOverlapping,
330 crate::rotation::Policy::default(),
331 "old-id",
332 );
333 let mut store = crate::rotation::SqlStore { conn: &c };
334 crate::rotation::RunStore::save(&mut store, &run).unwrap();
335 let e = forget_entry(&c, "a", "A", None).unwrap_err();
336 assert!(e.contains("rotation"), "{e}");
337 assert!(mentions(&c, OLD), "nothing was purged");
338 }
339}