Skip to main content

vault_core/
blast.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Phase 36 — blast radius (ADR-0142).
4//!
5//! After a compromise the question is always *which credentials were on that
6//! machine, and when?* It is never answerable, so the honest answer becomes
7//! "rotate everything", so nobody does. This module answers it from three things
8//! the vault already keeps:
9//!
10//! - the hub's audit chain says which files a node **applied** and when
11//!   (`node.apply` rows, Phase 34);
12//! - the config history says what each of those files **contained**, as the list
13//!   of vault secrets whose exact value appears in it (`exposed`, Phase 36), kept
14//!   per snapshot because by the time of a compromise the entry may have been
15//!   rotated, edited or deleted;
16//! - the vault says which of those values are **still current**, by fingerprint.
17//!
18//! The pure logic lives here so it is testable without a database; callers
19//! supply the three lookups.
20//!
21//! # What it cannot know, and says so
22//!
23//! A file applied before the history existed, or whose snapshot was pruned, has
24//! no recorded contents: it is reported as *unaccounted* rather than silently
25//! dropped, because "nothing was exposed" would be a lie. A pull target's file
26//! was never rendered by the hub, so it is not covered at all.
27
28use serde::{Deserialize, Serialize};
29use std::collections::BTreeMap;
30
31/// A secret whose exact value appeared in a rendered file or an environment.
32/// Stored with the snapshot (or the local log) at the moment it was written.
33#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
34pub struct Exposed {
35    pub entry_id: String,
36    pub provider: String,
37    #[serde(default)]
38    pub key_id: String,
39    /// Which part of the entry matched: `api_key`, `api_secret`,
40    /// `extra_vars/NAME`, `version_history`, …
41    pub field: String,
42    /// Fingerprint of the value that matched (`out::fingerprint`), so "is it
43    /// still the live value" is a comparison and not a guess from timestamps.
44    pub fp: String,
45    /// Under 8 characters: it may be a coincidence of text rather than a leak.
46    /// Still reported, because a missed exposure is the failure that matters.
47    #[serde(default)]
48    pub short: bool,
49}
50
51/// One thing a host received.
52#[derive(Debug, Clone, PartialEq, Serialize)]
53pub struct Deployment {
54    pub at: String,
55    /// A node target id, or `exec` / `file` / … for a local materialisation.
56    pub via: String,
57    /// SHA-256 of the file, for a node deployment.
58    pub sha256: String,
59    pub ok: bool,
60    pub error: Option<String>,
61}
62
63/// What the vault holds for an entry now.
64#[derive(Debug, Clone, Default)]
65pub struct CurrentEntry {
66    pub provider: String,
67    pub key_id: String,
68    /// Fingerprints of every present (not historical) secret value.
69    pub fps: Vec<String>,
70    pub console_url: Option<String>,
71}
72
73#[derive(Debug, Clone, PartialEq, Serialize)]
74pub struct EntryExposure {
75    pub entry_id: String,
76    pub provider: String,
77    pub key_id: String,
78    pub fields: Vec<String>,
79    pub first_seen: String,
80    pub last_seen: String,
81    pub times: usize,
82    /// The value that was on the host is still the entry's value, so it still
83    /// opens whatever it opened: rotate it.
84    pub still_current: bool,
85    /// The entry no longer exists in the vault.
86    pub removed: bool,
87    pub short: bool,
88    pub console_url: Option<String>,
89    pub via: Vec<String>,
90}
91
92#[derive(Debug, Clone, PartialEq, Serialize)]
93pub struct Report {
94    pub host: String,
95    pub since: Option<String>,
96    pub deployments: usize,
97    /// Deployments with no recorded contents.
98    pub unaccounted: Vec<Deployment>,
99    pub entries: Vec<EntryExposure>,
100    /// Entries to rotate: still current, in the order listed.
101    pub rotate: Vec<String>,
102    /// One command that rotates exactly those and nothing else.
103    pub command: String,
104}
105
106/// True when a failed apply still put the new file on disk for a moment (it
107/// was written, then restored). A refused or hash-mismatched one never was.
108pub fn failed_apply_touched_disk(error: &str) -> bool {
109    error.contains("validate failed") || error.contains("reload failed")
110}
111
112fn entry_label(provider: &str, key_id: &str) -> String {
113    if key_id.is_empty() {
114        provider.to_string()
115    } else {
116        format!("{provider}:{key_id}")
117    }
118}
119
120/// A shell-safe single-quoted word, or `None` when the name has a quote in it
121/// (quoting differs between shells, and a wrong guess runs the wrong command).
122fn quote(s: &str) -> Option<String> {
123    if s.contains(['\'', '"', '\n', '\r', '\0']) {
124        None
125    } else {
126        Some(format!("'{s}'"))
127    }
128}
129
130/// Builds the report. `deployments` are what the host received, `lookup` maps a
131/// file hash to what it contained (`None` = not recorded), `current` maps an
132/// entry id to what the vault holds now (`None` = deleted).
133pub fn report(
134    host: &str,
135    since: Option<&str>,
136    deployments: &[Deployment],
137    lookup: &dyn Fn(&Deployment) -> Option<Vec<Exposed>>,
138    current: &dyn Fn(&str) -> Option<CurrentEntry>,
139) -> Report {
140    let mut unaccounted = Vec::new();
141    let mut by_entry: BTreeMap<String, EntryExposure> = BTreeMap::new();
142    let mut counted = 0usize;
143
144    for d in deployments {
145        if since.is_some_and(|s| d.at.as_str() < s) {
146            continue;
147        }
148        if !d.ok && !d.error.as_deref().is_some_and(failed_apply_touched_disk) {
149            continue;
150        }
151        counted += 1;
152        let Some(exposed) = lookup(d) else {
153            unaccounted.push(d.clone());
154            continue;
155        };
156        for e in exposed {
157            let cur = current(&e.entry_id);
158            let still = cur.as_ref().is_some_and(|c| c.fps.contains(&e.fp));
159            let slot = by_entry
160                .entry(e.entry_id.clone())
161                .or_insert_with(|| EntryExposure {
162                    entry_id: e.entry_id.clone(),
163                    provider: e.provider.clone(),
164                    key_id: e.key_id.clone(),
165                    fields: Vec::new(),
166                    first_seen: d.at.clone(),
167                    last_seen: d.at.clone(),
168                    times: 0,
169                    still_current: false,
170                    removed: cur.is_none(),
171                    short: true,
172                    console_url: cur.as_ref().and_then(|c| c.console_url.clone()),
173                    via: Vec::new(),
174                });
175            if !slot.fields.contains(&e.field) {
176                slot.fields.push(e.field.clone());
177            }
178            if d.at < slot.first_seen {
179                slot.first_seen = d.at.clone();
180            }
181            if d.at > slot.last_seen {
182                slot.last_seen = d.at.clone();
183            }
184            slot.times += 1;
185            // One exposed value that is still live is enough to need a rotation.
186            slot.still_current |= still;
187            slot.short &= e.short;
188            if !slot.via.contains(&d.via) {
189                slot.via.push(d.via.clone());
190            }
191            // Use the live name where there is one: the entry may have been renamed.
192            if let Some(c) = &cur {
193                slot.provider.clone_from(&c.provider);
194                slot.key_id.clone_from(&c.key_id);
195            }
196        }
197    }
198
199    let mut entries: Vec<EntryExposure> = by_entry.into_values().collect();
200    entries.sort_by(|a, b| {
201        b.still_current
202            .cmp(&a.still_current)
203            .then_with(|| a.provider.to_lowercase().cmp(&b.provider.to_lowercase()))
204            .then_with(|| a.key_id.cmp(&b.key_id))
205    });
206    let rotate: Vec<String> = entries
207        .iter()
208        .filter(|e| e.still_current)
209        .map(|e| entry_label(&e.provider, &e.key_id))
210        .collect();
211    let mut parts = Vec::new();
212    for label in &rotate {
213        match quote(label) {
214            Some(q) => parts.push(format!("unv entry rotate {q} --generate")),
215            None => parts.push(format!(
216                "# cannot quote this name safely, rotate it by hand: {label}"
217            )),
218        }
219    }
220    Report {
221        host: host.to_string(),
222        since: since.map(String::from),
223        deployments: counted,
224        unaccounted,
225        entries,
226        rotate,
227        command: parts.join("; "),
228    }
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234
235    fn exp(id: &str, provider: &str, field: &str, fp: &str) -> Exposed {
236        Exposed {
237            entry_id: id.into(),
238            provider: provider.into(),
239            key_id: String::new(),
240            field: field.into(),
241            fp: fp.into(),
242            short: false,
243        }
244    }
245
246    fn dep(at: &str, via: &str, sha: &str) -> Deployment {
247        Deployment {
248            at: at.into(),
249            via: via.into(),
250            sha256: sha.into(),
251            ok: true,
252            error: None,
253        }
254    }
255
256    fn cur(provider: &str, fps: &[&str]) -> Option<CurrentEntry> {
257        Some(CurrentEntry {
258            provider: provider.into(),
259            key_id: String::new(),
260            fps: fps.iter().map(|s| s.to_string()).collect(),
261            console_url: Some("https://console.example/keys".into()),
262        })
263    }
264
265    #[test]
266    fn a_still_live_secret_is_rotated_and_a_rotated_away_one_is_not() {
267        let deps = [dep("2026-10-01T00:00:00Z", "nginx", "h1")];
268        let lookup = |_: &Deployment| {
269            Some(vec![
270                exp("e1", "Stripe", "api_key", "fp-live"),
271                exp("e2", "GitHub", "api_key", "fp-old"),
272            ])
273        };
274        let current = |id: &str| match id {
275            "e1" => cur("Stripe", &["fp-live"]),
276            "e2" => cur("GitHub", &["fp-new"]), // rotated since the file was written
277            _ => None,
278        };
279        let r = report("vps-01", None, &deps, &lookup, &current);
280        assert_eq!(r.rotate, vec!["Stripe"]);
281        assert_eq!(r.command, "unv entry rotate 'Stripe' --generate");
282        let github = r.entries.iter().find(|e| e.provider == "GitHub").unwrap();
283        assert!(
284            !github.still_current,
285            "a value rotated away needs no rotation"
286        );
287        assert!(
288            r.entries[0].still_current,
289            "still-current entries sort first"
290        );
291    }
292
293    #[test]
294    fn a_deleted_entry_is_reported_but_never_in_the_rotate_command() {
295        let deps = [dep("2026-10-01T00:00:00Z", "nginx", "h1")];
296        let lookup = |_: &Deployment| Some(vec![exp("gone", "Old", "api_key", "fp")]);
297        let r = report("h", None, &deps, &lookup, &|_| None);
298        assert_eq!(r.entries.len(), 1);
299        assert!(r.entries[0].removed);
300        assert!(r.rotate.is_empty());
301        assert_eq!(r.command, "");
302    }
303
304    #[test]
305    fn a_deployment_with_no_recorded_contents_is_unaccounted_not_silently_clean() {
306        let deps = [dep("2026-10-01T00:00:00Z", "nginx", "unknown-hash")];
307        let r = report("h", None, &deps, &|_| None, &|_| None);
308        assert_eq!(r.unaccounted.len(), 1);
309        assert_eq!(r.deployments, 1);
310        assert!(r.entries.is_empty());
311    }
312
313    #[test]
314    fn since_filters_by_time_and_the_window_is_inclusive() {
315        let deps = [
316            dep("2026-09-01T00:00:00Z", "a", "h1"),
317            dep("2026-10-01T00:00:00Z", "b", "h2"),
318        ];
319        let lookup = |d: &Deployment| {
320            Some(vec![exp(
321                if d.sha256 == "h1" { "old" } else { "new" },
322                "P",
323                "api_key",
324                "fp",
325            )])
326        };
327        let r = report("h", Some("2026-10-01T00:00:00Z"), &deps, &lookup, &|id| {
328            cur(id, &["fp"])
329        });
330        assert_eq!(r.entries.len(), 1);
331        assert_eq!(r.entries[0].entry_id, "new");
332    }
333
334    #[test]
335    fn repeated_exposures_collapse_into_one_row_with_a_count_and_a_range() {
336        let deps = [
337            dep("2026-10-03T00:00:00Z", "nginx", "h2"),
338            dep("2026-10-01T00:00:00Z", "nginx", "h1"),
339            dep("2026-10-02T00:00:00Z", "env", "h3"),
340        ];
341        let lookup = |_: &Deployment| Some(vec![exp("e1", "Stripe", "api_key", "fp")]);
342        let r = report("h", None, &deps, &lookup, &|_| cur("Stripe", &["fp"]));
343        assert_eq!(r.entries.len(), 1);
344        let e = &r.entries[0];
345        assert_eq!(
346            (e.times, e.first_seen.as_str(), e.last_seen.as_str()),
347            (3, "2026-10-01T00:00:00Z", "2026-10-03T00:00:00Z")
348        );
349        assert_eq!(e.via, vec!["nginx", "env"]);
350    }
351
352    #[test]
353    fn a_failed_apply_counts_only_when_the_file_reached_the_disk() {
354        let mut validate = dep("2026-10-01T00:00:00Z", "t", "h1");
355        validate.ok = false;
356        validate.error = Some("validate failed, previous file restored: x".into());
357        let mut refused = dep("2026-10-01T00:00:00Z", "t", "h2");
358        refused.ok = false;
359        refused.error =
360            Some("content does not match the hash the hub announced; nothing was written".into());
361        let lookup = |_: &Deployment| Some(vec![exp("e1", "Stripe", "api_key", "fp")]);
362        let r = report("h", None, &[validate, refused], &lookup, &|_| {
363            cur("Stripe", &["fp"])
364        });
365        assert_eq!(r.deployments, 1, "the refused one never touched the disk");
366        assert_eq!(r.entries[0].times, 1);
367    }
368
369    #[test]
370    fn a_name_that_cannot_be_quoted_is_left_for_a_human_not_guessed() {
371        let deps = [dep("2026-10-01T00:00:00Z", "t", "h")];
372        let lookup = |_: &Deployment| Some(vec![exp("e1", "O'Brien", "api_key", "fp")]);
373        let r = report("h", None, &deps, &lookup, &|_| cur("O'Brien", &["fp"]));
374        assert!(r.command.starts_with("# cannot quote"), "{}", r.command);
375        assert!(!r.command.contains("unv entry rotate"));
376    }
377
378    #[test]
379    fn a_renamed_entry_is_listed_under_its_current_name() {
380        let deps = [dep("2026-10-01T00:00:00Z", "t", "h")];
381        let lookup = |_: &Deployment| Some(vec![exp("e1", "OldName", "api_key", "fp")]);
382        let r = report("h", None, &deps, &lookup, &|_| cur("NewName", &["fp"]));
383        assert_eq!(r.rotate, vec!["NewName"]);
384    }
385
386    #[test]
387    fn short_only_matches_are_marked_short() {
388        let deps = [dep("2026-10-01T00:00:00Z", "t", "h")];
389        let mut e = exp("e1", "P", "api_key", "fp");
390        e.short = true;
391        let lookup = move |_: &Deployment| Some(vec![e.clone()]);
392        let r = report("h", None, &deps, &lookup, &|_| cur("P", &["fp"]));
393        assert!(r.entries[0].short);
394    }
395}