Skip to main content

vault_core/
lifecycle.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! Credential generations and lifecycle facts (roadmap R07).
4//!
5//! Entry JSON holds current descriptive state. This module holds generations,
6//! append-only lifecycle facts, pending credentials and deployment state, so
7//! high-churn operational data does not bloat an entry document.
8
9use hmac::{Hmac, KeyInit, Mac};
10use rand::Rng;
11use rusqlite::{params, Connection, OptionalExtension};
12use serde::{Deserialize, Serialize};
13use serde_json::{json, Value};
14use sha2::Sha256;
15use std::collections::BTreeMap;
16
17type HmacSha256 = Hmac<Sha256>;
18
19const FINGERPRINT_ROOT_META: &str = "credential_fingerprint_root_v1";
20const FINGERPRINT_SALT: &[u8] = b"unenverse/credential-generation/v1";
21const FINGERPRINT_INFO: &[u8] = b"fingerprint-key";
22
23/// Stable paths of entry values whose replacement creates a generation.
24pub const HISTORIED_SECRET_FIELDS: [&str; 5] = [
25    "api_key",
26    "api_secret",
27    "totp_secret",
28    "certificate_data",
29    "cert_key_data",
30];
31
32/// Create R07's relational side tables. Entry metadata remains optional JSON so
33/// a prior desktop preserves it during a `formToEntry` round trip.
34pub fn init_schema(conn: &Connection) -> Result<(), String> {
35    conn.execute_batch(
36        "CREATE TABLE IF NOT EXISTS credential_generations (
37             entry_id            TEXT NOT NULL,
38             field               TEXT NOT NULL,
39             generation          INTEGER NOT NULL,
40             fingerprint         TEXT NOT NULL,
41             source              TEXT NOT NULL,
42             issued_at           TEXT,
43             issued_at_precision TEXT NOT NULL DEFAULT 'unknown',
44             activated_at        TEXT,
45             revoked_at          TEXT,
46             state               TEXT NOT NULL DEFAULT 'active',
47             PRIMARY KEY (entry_id, field, generation)
48         );
49         CREATE INDEX IF NOT EXISTS credential_generations_active
50             ON credential_generations (entry_id, field, state, generation DESC);
51         CREATE TABLE IF NOT EXISTS pending_credentials (
52             id         TEXT PRIMARY KEY,
53             entry_id   TEXT NOT NULL,
54             field      TEXT NOT NULL,
55             created_at TEXT NOT NULL,
56             state      TEXT NOT NULL,
57             detail     TEXT NOT NULL DEFAULT '{}'
58         );
59         CREATE INDEX IF NOT EXISTS pending_credentials_entry
60             ON pending_credentials (entry_id, state);
61         CREATE TABLE IF NOT EXISTS lifecycle_events (
62             id           INTEGER PRIMARY KEY AUTOINCREMENT,
63             entry_id     TEXT NOT NULL,
64             kind         TEXT NOT NULL,
65             at           TEXT NOT NULL,
66             at_precision TEXT NOT NULL DEFAULT 'second',
67             source       TEXT NOT NULL,
68             detail       TEXT NOT NULL DEFAULT '{}'
69         );
70         CREATE INDEX IF NOT EXISTS lifecycle_events_entry_at
71             ON lifecycle_events (entry_id, at DESC, id DESC);
72         CREATE TABLE IF NOT EXISTS deployment_state (
73             entry_id       TEXT NOT NULL,
74             field          TEXT NOT NULL,
75             target_id      TEXT NOT NULL,
76             generation     INTEGER NOT NULL,
77             applied_sha256 TEXT,
78             applied_at     TEXT,
79             checked_at     TEXT,
80             result         TEXT NOT NULL,
81             run_id         TEXT,
82             PRIMARY KEY (entry_id, field, target_id)
83         );
84         CREATE INDEX IF NOT EXISTS deployment_state_entry
85             ON deployment_state (entry_id, field, target_id);",
86    )
87    .map_err(|e| e.to_string())
88}
89
90fn entry_id(entry: &Value) -> Option<&str> {
91    entry
92        .get("id")
93        .and_then(Value::as_str)
94        .filter(|id| !id.is_empty())
95}
96
97fn secret_values(entry: &Value) -> BTreeMap<String, String> {
98    let cookie = entry.get("secretType").and_then(Value::as_str) == Some("cookie");
99    let mut values = BTreeMap::new();
100    for field in HISTORIED_SECRET_FIELDS {
101        let public = match field {
102            "api_key" => entry
103                .get("primary_public")
104                .and_then(Value::as_bool)
105                .unwrap_or(false),
106            "api_secret" => entry
107                .get("secret_public")
108                .and_then(Value::as_bool)
109                .unwrap_or(false),
110            _ => false,
111        };
112        if !cookie && public {
113            continue;
114        }
115        if let Some(value) = entry
116            .get(field)
117            .and_then(Value::as_str)
118            .filter(|v| !v.is_empty())
119        {
120            values.insert(field.to_string(), value.to_string());
121        }
122    }
123    if let Some(vars) = entry.get("extra_vars").and_then(Value::as_array) {
124        for var in vars {
125            if !cookie && var.get("public").and_then(Value::as_bool).unwrap_or(false) {
126                continue;
127            }
128            let (Some(name), Some(value)) = (
129                var.get("key")
130                    .and_then(Value::as_str)
131                    .filter(|v| !v.is_empty()),
132                var.get("value")
133                    .and_then(Value::as_str)
134                    .filter(|v| !v.is_empty()),
135            ) else {
136                continue;
137            };
138            values.insert(format!("extra_vars/{name}"), value.to_string());
139        }
140    }
141    values
142}
143
144fn root(conn: &Connection) -> Result<[u8; 32], String> {
145    let have: Option<String> = conn
146        .query_row(
147            "SELECT value FROM vault_meta WHERE key = ?1",
148            [FINGERPRINT_ROOT_META],
149            |row| row.get(0),
150        )
151        .optional()
152        .map_err(|e| e.to_string())?;
153    if have.is_none() {
154        let mut generated = [0_u8; 32];
155        rand::rng().fill_bytes(&mut generated);
156        conn.execute(
157            "INSERT OR IGNORE INTO vault_meta (key, value) VALUES (?1, ?2)",
158            params![FINGERPRINT_ROOT_META, hex::encode(generated)],
159        )
160        .map_err(|e| e.to_string())?;
161    }
162    let encoded: String = conn
163        .query_row(
164            "SELECT value FROM vault_meta WHERE key = ?1",
165            [FINGERPRINT_ROOT_META],
166            |row| row.get(0),
167        )
168        .map_err(|e| e.to_string())?;
169    let decoded =
170        hex::decode(encoded).map_err(|_| "Credential fingerprint root is invalid".to_string())?;
171    decoded
172        .try_into()
173        .map_err(|_| "Credential fingerprint root has the wrong length".to_string())
174}
175
176fn hkdf(root: &[u8; 32]) -> Result<[u8; 32], String> {
177    let mut extract = HmacSha256::new_from_slice(FINGERPRINT_SALT).map_err(|e| e.to_string())?;
178    extract.update(root);
179    let prk = extract.finalize().into_bytes();
180    let mut expand = HmacSha256::new_from_slice(&prk).map_err(|e| e.to_string())?;
181    expand.update(FINGERPRINT_INFO);
182    expand.update(&[1]);
183    Ok(expand.finalize().into_bytes().into())
184}
185
186fn fingerprint(conn: &Connection, field: &str, value: &str) -> Result<String, String> {
187    let key = hkdf(&root(conn)?)?;
188    let mut mac = HmacSha256::new_from_slice(&key).map_err(|e| e.to_string())?;
189    mac.update(field.as_bytes());
190    mac.update(&[0]);
191    mac.update(value.as_bytes());
192    Ok(hex::encode(mac.finalize().into_bytes()))
193}
194
195fn next_generation(conn: &Connection, entry_id: &str, field: &str) -> Result<i64, String> {
196    conn.query_row(
197        "SELECT COALESCE(MAX(generation), 0) + 1 FROM credential_generations WHERE entry_id = ?1 AND field = ?2",
198        params![entry_id, field],
199        |row| row.get(0),
200    )
201    .map_err(|e| e.to_string())
202}
203
204fn insert_generation(
205    conn: &Connection,
206    entry_id: &str,
207    field: &str,
208    value: &str,
209    source: &str,
210    at: Option<&str>,
211    issued_at: Option<&str>,
212    issued_precision: &str,
213) -> Result<i64, String> {
214    let generation = next_generation(conn, entry_id, field)?;
215    conn.execute(
216        "INSERT INTO credential_generations
217         (entry_id, field, generation, fingerprint, source, issued_at, issued_at_precision, activated_at, state)
218         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 'active')",
219        params![
220            entry_id,
221            field,
222            generation,
223            fingerprint(conn, field, value)?,
224            source,
225            issued_at,
226            issued_precision,
227            at,
228        ],
229    )
230    .map_err(|e| e.to_string())?;
231    Ok(generation)
232}
233
234/// Records one lifecycle event for an entry (a cutover, say). Public so the application layer can
235/// write events that no save diff would detect; the detail must carry no secret.
236pub fn record_event(
237    conn: &Connection,
238    entry_id: &str,
239    kind: &str,
240    at: &str,
241    source: &str,
242    detail: Value,
243) -> Result<(), String> {
244    event(conn, entry_id, kind, at, source, detail)
245}
246
247fn event(
248    conn: &Connection,
249    entry_id: &str,
250    kind: &str,
251    at: &str,
252    source: &str,
253    detail: Value,
254) -> Result<(), String> {
255    conn.execute(
256        "INSERT INTO lifecycle_events (entry_id, kind, at, at_precision, source, detail)
257         VALUES (?1, ?2, ?3, 'second', ?4, ?5)",
258        params![entry_id, kind, at, source, detail.to_string()],
259    )
260    .map(|_| ())
261    .map_err(|e| e.to_string())
262}
263
264fn provenance_kind(entry: &Value) -> Option<&str> {
265    entry
266        .get("provenance")
267        .and_then(|v| v.get("source_kind").or_else(|| v.get("kind")))
268        .and_then(Value::as_str)
269}
270
271fn issued(entry: &Value) -> (Option<&str>, &str) {
272    let value = entry
273        .get("issued_at")
274        .and_then(Value::as_str)
275        .filter(|v| !v.is_empty());
276    let precision = entry
277        .get("issued_at_precision")
278        .and_then(Value::as_str)
279        .filter(|v| matches!(*v, "exact" | "date" | "month" | "year" | "unknown"))
280        .unwrap_or("unknown");
281    (value, precision)
282}
283
284/// Seed generation one for entries that predate R07. It runs after row storage
285/// migration because a 0.42.x vault can still have its document in the legacy
286/// blob when migration 0003 installs the relational tables.
287pub fn seed_existing(conn: &Connection, document: &Value) -> Result<(), String> {
288    let work = || -> Result<(), String> {
289        for entry in document
290            .get("api_keys")
291            .and_then(Value::as_array)
292            .into_iter()
293            .flatten()
294        {
295            let Some(id) = entry_id(entry) else { continue };
296            for (field, value) in secret_values(entry) {
297                let exists: Option<i64> = conn
298                    .query_row(
299                        "SELECT generation FROM credential_generations WHERE entry_id = ?1 AND field = ?2 LIMIT 1",
300                        params![id, field],
301                        |row| row.get(0),
302                    )
303                    .optional()
304                    .map_err(|e| e.to_string())?;
305                if exists.is_none() {
306                    insert_generation(
307                        conn,
308                        id,
309                        &field,
310                        &value,
311                        "migration",
312                        None,
313                        None,
314                        "unknown",
315                    )?;
316                }
317            }
318        }
319        Ok(())
320    };
321    if conn.is_autocommit() {
322        conn.execute_batch("BEGIN IMMEDIATE")
323            .map_err(|e| e.to_string())?;
324        match work() {
325            Ok(()) => crate::commit(conn),
326            Err(error) => {
327                let _ = conn.execute_batch("ROLLBACK");
328                Err(error)
329            }
330        }
331    } else {
332        work()
333    }
334}
335
336/// Record lifecycle side effects inside the transaction that writes entry rows.
337pub fn record_save(
338    conn: &Connection,
339    old: &BTreeMap<String, Value>,
340    next: &[Value],
341    at: &str,
342) -> Result<(), String> {
343    for entry in next {
344        let Some(id) = entry_id(entry) else { continue };
345        let before = old.get(id);
346        let current = secret_values(entry);
347        let (issued_at, issued_precision) = issued(entry);
348        match before {
349            None => {
350                let source = if provenance_kind(entry) == Some("import") {
351                    "import"
352                } else {
353                    "manual"
354                };
355                event(conn, id, "created", at, source, json!({}))?;
356                if source == "import" {
357                    event(conn, id, "imported", at, "import", json!({}))?;
358                }
359                for (field, value) in current {
360                    insert_generation(
361                        conn,
362                        id,
363                        &field,
364                        &value,
365                        source,
366                        Some(at),
367                        issued_at,
368                        issued_precision,
369                    )?;
370                }
371            }
372            Some(previous) => {
373                let old_values = secret_values(previous);
374                let source = if entry.get("last_rotated_at") != previous.get("last_rotated_at") {
375                    "manual"
376                } else {
377                    "save"
378                };
379                for (field, value) in &current {
380                    if old_values.get(field) == Some(value) {
381                        continue;
382                    }
383                    conn.execute(
384                        "UPDATE credential_generations SET state = 'superseded' WHERE entry_id = ?1 AND field = ?2 AND state = 'active'",
385                        params![id, field],
386                    )
387                    .map_err(|e| e.to_string())?;
388                    let generation = insert_generation(
389                        conn,
390                        id,
391                        field,
392                        value,
393                        source,
394                        Some(at),
395                        issued_at,
396                        issued_precision,
397                    )?;
398                    event(
399                        conn,
400                        id,
401                        "rotated",
402                        at,
403                        source,
404                        json!({ "field": field, "generation": generation }),
405                    )?;
406                }
407                let verified = entry.get("last_verified_at").and_then(Value::as_str);
408                if verified.is_some()
409                    && verified != previous.get("last_verified_at").and_then(Value::as_str)
410                {
411                    event(
412                        conn,
413                        id,
414                        "verified",
415                        verified.unwrap_or(at),
416                        "probe",
417                        json!({}),
418                    )?;
419                }
420            }
421        }
422    }
423    Ok(())
424}
425
426#[derive(Debug, Clone, Serialize, Deserialize)]
427pub struct TimelineEvent {
428    pub kind: String,
429    pub at: String,
430    pub at_precision: String,
431    pub source: String,
432    pub detail: Value,
433}
434
435/// Public, secret-free timeline records for one stable entry id.
436pub fn timeline(conn: &Connection, entry_id: &str) -> Result<Vec<TimelineEvent>, String> {
437    let mut stmt = conn
438        .prepare(
439            "SELECT kind, at, at_precision, source, detail FROM lifecycle_events
440             WHERE entry_id = ?1 ORDER BY at DESC, id DESC",
441        )
442        .map_err(|e| e.to_string())?;
443    let rows = stmt
444        .query_map([entry_id], |row| {
445            let detail: String = row.get(4)?;
446            Ok(TimelineEvent {
447                kind: row.get(0)?,
448                at: row.get(1)?,
449                at_precision: row.get(2)?,
450                source: row.get(3)?,
451                detail: serde_json::from_str(&detail).unwrap_or_else(|_| json!({})),
452            })
453        })
454        .map_err(|e| e.to_string())?;
455    rows.collect::<Result<Vec<_>, _>>()
456        .map_err(|e| e.to_string())
457}
458
459/// Latest deployment state per target. R12 will write reports through this API.
460pub fn deployment_state(conn: &Connection, entry_id: &str) -> Result<Vec<Value>, String> {
461    let mut stmt = conn
462        .prepare(
463            "SELECT field, target_id, generation, applied_sha256, applied_at, checked_at, result, run_id
464             FROM deployment_state WHERE entry_id = ?1 ORDER BY target_id, field",
465        )
466        .map_err(|e| e.to_string())?;
467    let rows = stmt
468        .query_map([entry_id], |row| {
469        Ok(json!({
470            "field": row.get::<_, String>(0)?, "target_id": row.get::<_, String>(1)?,
471            "generation": row.get::<_, i64>(2)?, "applied_sha256": row.get::<_, Option<String>>(3)?,
472            "applied_at": row.get::<_, Option<String>>(4)?, "checked_at": row.get::<_, Option<String>>(5)?,
473            "result": row.get::<_, String>(6)?, "run_id": row.get::<_, Option<String>>(7)?,
474        }))
475        })
476        .map_err(|e| e.to_string())?;
477    rows.collect::<Result<Vec<_>, _>>()
478        .map_err(|e| e.to_string())
479}
480
481/// Records what a node reported for one secret on one target (R12): the generation that is active
482/// now, the hash that was applied, and the outcome. A success sets `applied_*`; a failure keeps
483/// what an earlier success recorded and changes only the outcome, so "the last good deployment" is
484/// never lost to a failed retry. A secret with no active generation (the vault has not recorded
485/// one) is skipped and `false` returned.
486#[allow(clippy::too_many_arguments)]
487pub fn record_deployment(
488    conn: &Connection,
489    entry_id: &str,
490    field: &str,
491    target_id: &str,
492    applied_sha256: &str,
493    at: &str,
494    ok: bool,
495    result: &str,
496    run_id: Option<&str>,
497) -> Result<bool, String> {
498    let generation: Option<i64> = conn
499        .query_row(
500            "SELECT generation FROM credential_generations
501             WHERE entry_id = ?1 AND field = ?2 AND state = 'active'",
502            rusqlite::params![entry_id, field],
503            |row| row.get(0),
504        )
505        .optional()
506        .map_err(|e| e.to_string())?;
507    let Some(generation) = generation else {
508        return Ok(false);
509    };
510    let written = if ok {
511        conn.execute(
512            "INSERT INTO deployment_state
513                 (entry_id, field, target_id, generation, applied_sha256, applied_at, checked_at, result, run_id)
514             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?6, ?7, ?8)
515             ON CONFLICT (entry_id, field, target_id) DO UPDATE SET
516                 generation = ?4, applied_sha256 = ?5, applied_at = ?6, checked_at = ?6,
517                 result = ?7, run_id = ?8",
518            rusqlite::params![entry_id, field, target_id, generation, applied_sha256, at, result, run_id],
519        )
520    } else {
521        conn.execute(
522            "INSERT INTO deployment_state
523                 (entry_id, field, target_id, generation, checked_at, result, run_id)
524             VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)
525             ON CONFLICT (entry_id, field, target_id) DO UPDATE SET
526                 checked_at = ?5, result = ?6, run_id = ?7",
527            rusqlite::params![entry_id, field, target_id, generation, at, result, run_id],
528        )
529    };
530    written.map_err(|e| e.to_string())?;
531    Ok(true)
532}
533
534/// Every deployment row, newest check first: what each node last reported for each secret.
535pub fn deployment_state_all(conn: &Connection) -> Result<Vec<Value>, String> {
536    let mut stmt = conn
537        .prepare(
538            "SELECT entry_id, field, target_id, generation, applied_sha256, applied_at, checked_at, result
539             FROM deployment_state ORDER BY COALESCE(checked_at, '') DESC, target_id, entry_id, field",
540        )
541        .map_err(|e| e.to_string())?;
542    let rows = stmt
543        .query_map([], |row| {
544            Ok(json!({
545                "entry_id": row.get::<_, String>(0)?, "field": row.get::<_, String>(1)?,
546                "target_id": row.get::<_, String>(2)?, "generation": row.get::<_, i64>(3)?,
547                "applied_sha256": row.get::<_, Option<String>>(4)?,
548                "applied_at": row.get::<_, Option<String>>(5)?,
549                "checked_at": row.get::<_, Option<String>>(6)?,
550                "result": row.get::<_, String>(7)?,
551            }))
552        })
553        .map_err(|e| e.to_string())?;
554    rows.collect::<Result<Vec<_>, _>>()
555        .map_err(|e| e.to_string())
556}
557
558/// Deployment rows whose recorded generation is no longer the active one.
559/// This is the query R12 uses for "rotated but not redeployed" without ever
560/// comparing a secret value or cross-vault fingerprint.
561pub fn deployment_generation_mismatches(conn: &Connection) -> Result<Vec<Value>, String> {
562    let mut stmt = conn
563        .prepare(
564            "SELECT d.entry_id, d.field, d.target_id, d.generation, g.generation
565             FROM deployment_state d
566             JOIN credential_generations g
567               ON g.entry_id = d.entry_id AND g.field = d.field AND g.state = 'active'
568             WHERE d.generation != g.generation
569             ORDER BY d.entry_id, d.field, d.target_id",
570        )
571        .map_err(|error| error.to_string())?;
572    let rows = stmt
573        .query_map([], |row| {
574            Ok(json!({
575                "entry_id": row.get::<_, String>(0)?, "field": row.get::<_, String>(1)?,
576                "target_id": row.get::<_, String>(2)?, "deployed_generation": row.get::<_, i64>(3)?,
577                "active_generation": row.get::<_, i64>(4)?,
578            }))
579        })
580        .map_err(|error| error.to_string())?;
581    rows.collect::<Result<Vec<_>, _>>()
582        .map_err(|error| error.to_string())
583}
584
585#[cfg(test)]
586mod tests {
587    use super::*;
588
589    fn db() -> Connection {
590        let conn = Connection::open_in_memory().unwrap();
591        conn.execute_batch("CREATE TABLE vault_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);")
592            .unwrap();
593        init_schema(&conn).unwrap();
594        conn
595    }
596
597    #[test]
598    fn the_same_value_has_a_different_vault_scoped_fingerprint() {
599        let a = db();
600        let b = db();
601        assert_ne!(
602            fingerprint(&a, "api_key", "fixture-value").unwrap(),
603            fingerprint(&b, "api_key", "fixture-value").unwrap()
604        );
605    }
606
607    #[test]
608    fn migration_generation_is_idempotent_and_does_not_invent_dates() {
609        let conn = db();
610        let document = json!({ "api_keys": [{ "id": "entry-1", "api_key": "fixture-value" }] });
611        seed_existing(&conn, &document).unwrap();
612        seed_existing(&conn, &document).unwrap();
613        let rows: Vec<(i64, String, Option<String>, String)> = conn
614            .prepare("SELECT generation, source, issued_at, issued_at_precision FROM credential_generations")
615            .unwrap()
616            .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?)))
617            .unwrap()
618            .map(Result::unwrap)
619            .collect();
620        assert_eq!(rows, vec![(1, "migration".into(), None, "unknown".into())]);
621    }
622
623    #[test]
624    fn a_secret_change_creates_a_generation_and_manual_event() {
625        let conn = db();
626        let old = json!({ "id": "entry-1", "api_key": "old" });
627        seed_existing(&conn, &json!({ "api_keys": [old.clone()] })).unwrap();
628        let new = json!({ "id": "entry-1", "api_key": "new", "last_rotated_at": "2026-10-14" });
629        let mut previous = BTreeMap::new();
630        previous.insert("entry-1".into(), old);
631        record_save(&conn, &previous, &[new], "2026-10-14T01:02:03Z").unwrap();
632        let generations: Vec<(i64, String)> = conn
633            .prepare("SELECT generation, state FROM credential_generations ORDER BY generation")
634            .unwrap()
635            .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))
636            .unwrap()
637            .map(Result::unwrap)
638            .collect();
639        assert_eq!(
640            generations,
641            vec![(1, "superseded".into()), (2, "active".into())]
642        );
643        assert_eq!(timeline(&conn, "entry-1").unwrap()[0].source, "manual");
644        conn.execute(
645            "INSERT INTO deployment_state (entry_id, field, target_id, generation, result) VALUES ('entry-1', 'api_key', 'web-01', 1, 'ok')",
646            [],
647        )
648        .unwrap();
649        assert_eq!(
650            deployment_generation_mismatches(&conn).unwrap()[0]["active_generation"],
651            2
652        );
653    }
654
655    #[test]
656    fn imported_generation_keeps_the_issuer_date_precision() {
657        let conn = db();
658        let entry = json!({
659            "id": "imported", "api_key": "fixture-value",
660            "provenance": { "source_kind": "import" },
661            "issued_at": "2024-03", "issued_at_precision": "month",
662        });
663        record_save(&conn, &BTreeMap::new(), &[entry], "2026-10-14T01:02:03Z").unwrap();
664        let row: (String, Option<String>, String) = conn
665            .query_row(
666                "SELECT source, issued_at, issued_at_precision FROM credential_generations WHERE entry_id = 'imported'",
667                [],
668                |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),
669            )
670            .unwrap();
671        assert_eq!(
672            row,
673            ("import".into(), Some("2024-03".into()), "month".into())
674        );
675    }
676
677    #[test]
678    fn a_node_report_is_recorded_against_the_active_generation_and_a_failure_keeps_the_last_good_one(
679    ) {
680        let conn = db();
681        let e = json!({ "id": "entry-1", "api_key": "k1" });
682        record_save(&conn, &BTreeMap::new(), &[e], "2026-10-14T01:02:03Z").unwrap();
683        // A secret with no generation recorded is skipped, not guessed at.
684        assert!(!record_deployment(
685            &conn, "ghost", "api_key", "n/t", "aa", "t", true, "applied", None
686        )
687        .unwrap());
688        assert!(record_deployment(
689            &conn,
690            "entry-1",
691            "api_key",
692            "edge/nginx",
693            "sha-good",
694            "2026-10-15T00:00:00Z",
695            true,
696            "applied",
697            Some("run-1")
698        )
699        .unwrap());
700        let row = |c: &Connection| deployment_state(c, "entry-1").unwrap()[0].clone();
701        assert_eq!(row(&conn)["result"], "applied");
702        assert_eq!(row(&conn)["applied_sha256"], "sha-good");
703        assert_eq!(row(&conn)["generation"], 1);
704        // A later failure changes the outcome and the check time, not what was applied.
705        record_deployment(
706            &conn,
707            "entry-1",
708            "api_key",
709            "edge/nginx",
710            "sha-bad",
711            "2026-10-16T00:00:00Z",
712            false,
713            "failed: validate",
714            None,
715        )
716        .unwrap();
717        let r = row(&conn);
718        assert_eq!(r["result"], "failed: validate");
719        assert_eq!(r["applied_sha256"], "sha-good");
720        assert_eq!(r["applied_at"], "2026-10-15T00:00:00Z");
721        assert_eq!(r["checked_at"], "2026-10-16T00:00:00Z");
722        // A failure on a target never seen before still leaves a row, with nothing applied.
723        record_deployment(
724            &conn,
725            "entry-1",
726            "api_key",
727            "edge/other",
728            "sha-x",
729            "t",
730            false,
731            "failed: write",
732            None,
733        )
734        .unwrap();
735        let rows = deployment_state(&conn, "entry-1").unwrap();
736        assert_eq!(rows.len(), 2);
737        assert!(rows[0]["applied_sha256"].is_null() || rows[1]["applied_sha256"].is_null());
738    }
739}