Skip to main content

vault_core/
uid_registry.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright the UnENVerse contributors.
3//! The unique-ID registry — Phase 24.4.
4//!
5//! A server-side record of every identifier this deployment has issued, so a
6//! new one can be checked for uniqueness before it is handed out and a
7//! presented one can be checked for provenance. **Keyed hash only, never the
8//! value**: a database of every API key ever minted would be the best single
9//! target an attacker could find, so what is stored is
10//! `HMAC-SHA256(pepper, normalise(value))` truncated to 16 bytes — enough to be
11//! collision-free at any size this will reach, and useless if stolen.
12//!
13//! Lives in its own SQLCipher file, `registry.db`, beside `vault.db`. Its key
14//! and pepper are random 32-byte values held in the **vault's** `vault_meta`
15//! table: the registry only opens while the vault is unlocked, travels with
16//! vault backups, and survives a master-password change without needing its
17//! own KDF.
18//!
19//! Storage shape and pragmas are exactly what was measured on 2026-09-14
20//! (`CLAUDE.md`, Phase 24.4): `WITHOUT ROWID`, a date index, a 32 MB page
21//! cache, and pruning in 10,000-row chunks rather than one statement — the
22//! single-statement prune held the writer lock for 45.7s at 10M rows in that
23//! benchmark, which would stall every mint and register behind it.
24
25use hmac::KeyInit;
26use rusqlite::{params, Connection, OpenFlags, OptionalExtension};
27use serde::Serialize;
28use sha2::Sha256;
29use std::fs;
30use std::path::Path;
31
32/// A value is registered by an `INSERT` that fails on the primary key, never a
33/// `SELECT` then `INSERT` — so two concurrent mints of one value cannot both
34/// succeed. `check` is therefore advisory ("unique right now"); `register` is
35/// authoritative.
36const PRUNE_CHUNK: usize = 10_000;
37
38// ── Registry secrets, held in the vault's own vault_meta ──────────────────────
39
40const META_KEY: &str = "uid_registry_key";
41const META_PEPPER: &str = "uid_registry_pepper";
42
43fn rand32() -> [u8; 32] {
44    use rand::Rng;
45    let mut b = [0u8; 32];
46    rand::rng().fill_bytes(&mut b);
47    b
48}
49
50/// Reads the registry's SQLCipher key and HMAC pepper from `vault_meta`,
51/// generating and persisting both the first time the registry is used. Callers
52/// never see the values live anywhere but here and inside the open registry
53/// connection.
54pub fn ensure_registry_secrets(vault_conn: &Connection) -> Result<([u8; 32], [u8; 32]), String> {
55    Ok((
56        get_or_create_secret(vault_conn, META_KEY, "uid_registry_key")?,
57        get_or_create_secret(vault_conn, META_PEPPER, "uid_registry_pepper")?,
58    ))
59}
60
61/// Reads the 32-byte secret stored under `meta_key`, creating it on first use.
62///
63/// Creation is `INSERT OR IGNORE` followed by a read, so two callers that both find
64/// nothing converge on whichever row landed first. It used to be a read, a random
65/// value and `INSERT OR REPLACE`: the second caller's value replaced the first's, a
66/// registry file already created under the first key became unreadable ("Wrong
67/// registry key"), and a changed pepper made every issued id look unissued, which
68/// silently breaks uniqueness.
69fn get_or_create_secret(
70    vault_conn: &Connection,
71    meta_key: &str,
72    label: &str,
73) -> Result<[u8; 32], String> {
74    let read = || -> Result<Option<String>, String> {
75        vault_conn
76            .query_row(
77                "SELECT value FROM vault_meta WHERE key = ?1",
78                params![meta_key],
79                |r| r.get::<_, String>(0),
80            )
81            .optional()
82            .map_err(|e| e.to_string())
83    };
84    if read()?.is_none() {
85        vault_conn
86            .execute(
87                "INSERT OR IGNORE INTO vault_meta (key, value) VALUES (?1, ?2)",
88                params![meta_key, hex::encode(rand32())],
89            )
90            .map_err(|e| e.to_string())?;
91    }
92    let hex_str = read()?.ok_or_else(|| format!("{label} could not be created"))?;
93    hex::decode(&hex_str)
94        .map_err(|e| e.to_string())?
95        .try_into()
96        .map_err(|_| format!("{label} is corrupt (wrong length)"))
97}
98
99// ── Opening the registry file ──────────────────────────────────────────────────
100
101/// Opens (creating if absent) `registry.db` at `path` with the measured pragmas.
102pub fn open_registry(path: &Path, key: &[u8; 32]) -> Result<Connection, String> {
103    if let Some(p) = path.parent() {
104        fs::create_dir_all(p).map_err(|e| e.to_string())?;
105    }
106    let conn = Connection::open_with_flags(
107        path,
108        OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_CREATE,
109    )
110    .map_err(|e| e.to_string())?;
111    conn.execute_batch(&format!("PRAGMA key = \"x'{}'\";", hex::encode(key)))
112        .map_err(|e| e.to_string())?;
113    conn.execute_batch("SELECT count(*) FROM sqlite_master;")
114        .map_err(|_| "Wrong registry key".to_string())?;
115    conn.execute_batch(
116        "PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL; PRAGMA cache_size=-32000;",
117    )
118    .map_err(|e| e.to_string())?;
119    crate::restrict_to_owner(path)?;
120    for suffix in ["-wal", "-shm"] {
121        let mut side = path.as_os_str().to_owned();
122        side.push(suffix);
123        let side = std::path::PathBuf::from(side);
124        if side.exists() {
125            crate::restrict_to_owner(&side)?;
126        }
127    }
128    init_schema(&conn)?;
129    Ok(conn)
130}
131
132pub fn init_schema(conn: &Connection) -> Result<(), String> {
133    conn.execute_batch(
134        "PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;
135         CREATE TABLE IF NOT EXISTS uid (
136             h BLOB PRIMARY KEY,
137             t INTEGER NOT NULL,
138             m INTEGER
139         ) WITHOUT ROWID;
140         CREATE INDEX IF NOT EXISTS uid_t ON uid(t);
141         CREATE TABLE IF NOT EXISTS uid_meta (
142             id        INTEGER PRIMARY KEY,
143             namespace TEXT,
144             generator TEXT,
145             params    TEXT,
146             normalise TEXT,
147             actor     TEXT,
148             source    TEXT,
149             entry_ck  TEXT,
150             note      TEXT,
151             created_at INTEGER NOT NULL
152         );",
153    )
154    .map_err(|e| e.to_string())
155}
156
157// ── Normalisation ────────────────────────────────────────────────────────────
158
159#[derive(Clone, Copy, PartialEq, Eq, Debug)]
160pub enum Normalise {
161    Uuid,
162    Ulid,
163    Lower,
164    None,
165}
166
167impl Normalise {
168    pub fn parse(s: &str) -> Option<Self> {
169        match s.to_ascii_lowercase().as_str() {
170            "uuid" => Some(Normalise::Uuid),
171            "ulid" => Some(Normalise::Ulid),
172            "lower" => Some(Normalise::Lower),
173            "none" => Some(Normalise::None),
174            _ => None,
175        }
176    }
177
178    pub fn as_str(self) -> &'static str {
179        match self {
180            Normalise::Uuid => "uuid",
181            Normalise::Ulid => "ulid",
182            Normalise::Lower => "lower",
183            Normalise::None => "none",
184        }
185    }
186}
187
188/// Decides what "the same ID" means. Getting this wrong makes two spellings of
189/// one identifier both look unique.
190pub fn normalise(value: &str, mode: Normalise) -> String {
191    match mode {
192        Normalise::Uuid => {
193            let hex_only: String = value
194                .chars()
195                .filter(|c| c.is_ascii_hexdigit())
196                .collect::<String>()
197                .to_ascii_lowercase();
198            if hex_only.len() == 32 {
199                format!(
200                    "{}-{}-{}-{}-{}",
201                    &hex_only[0..8],
202                    &hex_only[8..12],
203                    &hex_only[12..16],
204                    &hex_only[16..20],
205                    &hex_only[20..32]
206                )
207            } else {
208                value.to_ascii_lowercase()
209            }
210        }
211        Normalise::Ulid => value
212            .to_ascii_uppercase()
213            .chars()
214            .map(|c| match c {
215                'I' | 'L' => '1',
216                'O' => '0',
217                other => other,
218            })
219            .collect(),
220        Normalise::Lower => value.to_ascii_lowercase(),
221        Normalise::None => value.to_string(),
222    }
223}
224
225/// `HMAC-SHA256(pepper, normalise(value))`, truncated to 16 bytes. The
226/// namespace is **not** part of the input — that is what "unique across
227/// everything" means: the same string minted under two namespaces is one
228/// collision, not two independent slots.
229pub fn hash_value(pepper: &[u8; 32], value: &str, mode: Normalise) -> [u8; 16] {
230    use hmac::{Hmac, Mac};
231    type HmacSha256 = Hmac<Sha256>;
232    let normalised = normalise(value, mode);
233    let mut mac = HmacSha256::new_from_slice(pepper).expect("HMAC accepts any key length");
234    mac.update(normalised.as_bytes());
235    let full = mac.finalize().into_bytes();
236    let mut out = [0u8; 16];
237    out.copy_from_slice(&full[..16]);
238    out
239}
240
241fn now_ts() -> i64 {
242    std::time::SystemTime::now()
243        .duration_since(std::time::UNIX_EPOCH)
244        .map(|d| d.as_secs() as i64)
245        .unwrap_or(0)
246}
247
248// ── Batch metadata ────────────────────────────────────────────────────────────
249
250#[derive(Default, Clone)]
251pub struct BatchMeta<'a> {
252    pub namespace: Option<&'a str>,
253    pub generator: Option<&'a str>,
254    pub params: Option<&'a str>,
255    pub actor: Option<&'a str>,
256    pub source: Option<&'a str>,
257    pub entry_ck: Option<&'a str>,
258    pub note: Option<&'a str>,
259}
260
261fn insert_meta_row(
262    conn: &Connection,
263    meta: &BatchMeta,
264    normalise_mode: Normalise,
265) -> Result<i64, String> {
266    conn.execute(
267        "INSERT INTO uid_meta (namespace, generator, params, normalise, actor, source, entry_ck, note, created_at) \
268         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
269        params![
270            meta.namespace,
271            meta.generator,
272            meta.params,
273            normalise_mode.as_str(),
274            meta.actor,
275            meta.source,
276            meta.entry_ck,
277            meta.note,
278            now_ts(),
279        ],
280    )
281    .map_err(|e| e.to_string())?;
282    Ok(conn.last_insert_rowid())
283}
284
285// ── Check / register / lookup ─────────────────────────────────────────────────
286
287/// Advisory only — "unique right now". Never authoritative: `register` is the
288/// only operation that actually reserves a value.
289pub fn check(
290    conn: &Connection,
291    pepper: &[u8; 32],
292    values: &[String],
293    mode: Normalise,
294) -> Result<Vec<(String, bool)>, String> {
295    let mut out = Vec::with_capacity(values.len());
296    for v in values {
297        let h = hash_value(pepper, v, mode);
298        let exists: bool = conn
299            .query_row(
300                "SELECT EXISTS(SELECT 1 FROM uid WHERE h = ?1)",
301                params![h.as_slice()],
302                |r| r.get(0),
303            )
304            .map_err(|e| e.to_string())?;
305        out.push((v.clone(), !exists));
306    }
307    Ok(out)
308}
309
310pub struct RegisterOutcome {
311    pub value: String,
312    pub registered: bool,
313}
314
315/// Registers every value as one batch. Each is an `INSERT` that fails on the
316/// primary key — never a read-then-write — so two concurrent registrations of
317/// one value cannot both succeed; the loser is reported as a conflict, not an
318/// error.
319pub fn register(
320    conn: &Connection,
321    pepper: &[u8; 32],
322    values: &[String],
323    mode: Normalise,
324    meta: &BatchMeta,
325) -> Result<Vec<RegisterOutcome>, String> {
326    // One savepoint: the batch's provenance row and its ids stand or fall together, and a
327    // batch that registered nothing leaves no provenance row behind.
328    conn.execute_batch("SAVEPOINT uid_register")
329        .map_err(|e| e.to_string())?;
330    let result = register_in_savepoint(conn, pepper, values, mode, meta);
331    let end = if result.is_ok() {
332        "RELEASE uid_register"
333    } else {
334        "ROLLBACK TO uid_register; RELEASE uid_register"
335    };
336    conn.execute_batch(end).map_err(|e| e.to_string())?;
337    result
338}
339
340fn register_in_savepoint(
341    conn: &Connection,
342    pepper: &[u8; 32],
343    values: &[String],
344    mode: Normalise,
345    meta: &BatchMeta,
346) -> Result<Vec<RegisterOutcome>, String> {
347    let meta_id = insert_meta_row(conn, meta, mode)?;
348    let t = now_ts();
349    let mut out = Vec::with_capacity(values.len());
350    for v in values {
351        let h = hash_value(pepper, v, mode);
352        let registered = match conn.execute(
353            "INSERT INTO uid (h, t, m) VALUES (?1, ?2, ?3)",
354            params![h.as_slice(), t, meta_id],
355        ) {
356            Ok(_) => true,
357            // Only the primary key saying "already issued" is a conflict. Any other
358            // failure (disk full, locked, read-only) used to be reported the same way,
359            // so a mint retried against a broken database and answered "collision".
360            Err(rusqlite::Error::SqliteFailure(e, _))
361                if e.code == rusqlite::ErrorCode::ConstraintViolation =>
362            {
363                false
364            }
365            Err(e) => return Err(e.to_string()),
366        };
367        out.push(RegisterOutcome {
368            value: v.clone(),
369            registered,
370        });
371    }
372    if !out.iter().any(|o| o.registered) {
373        conn.execute("DELETE FROM uid_meta WHERE id = ?1", [meta_id])
374            .map_err(|e| e.to_string())?;
375    }
376    Ok(out)
377}
378
379/// Generate-check-register in one call, retrying up to `max_attempts` times on
380/// collision. `generate` is supplied by the caller (`unv-server`), which owns
381/// the id-shape decision this module has no opinion about.
382pub fn mint(
383    conn: &Connection,
384    pepper: &[u8; 32],
385    mode: Normalise,
386    meta: &BatchMeta,
387    max_attempts: u32,
388    mut generate: impl FnMut() -> String,
389) -> Result<Option<String>, String> {
390    for _ in 0..max_attempts.max(1) {
391        let candidate = generate();
392        let outcome = register(conn, pepper, std::slice::from_ref(&candidate), mode, meta)?;
393        if outcome.first().is_some_and(|o| o.registered) {
394            return Ok(Some(candidate));
395        }
396    }
397    Ok(None)
398}
399
400#[derive(Serialize)]
401pub struct LookupResult {
402    pub issued: bool,
403    pub namespace: Option<String>,
404    pub generator: Option<String>,
405    pub actor: Option<String>,
406    pub source: Option<String>,
407    pub created_at: Option<i64>,
408}
409
410/// One value → provenance the caller may see. `check`/`lookup` are the
411/// enumeration oracle for a low-entropy namespace — the rate limiter is the
412/// control, not this function.
413pub fn lookup(
414    conn: &Connection,
415    pepper: &[u8; 32],
416    value: &str,
417    mode: Normalise,
418) -> Result<LookupResult, String> {
419    let h = hash_value(pepper, value, mode);
420    let row = conn
421        .query_row(
422            "SELECT u.t, m.namespace, m.generator, m.actor, m.source \
423             FROM uid u LEFT JOIN uid_meta m ON u.m = m.id \
424             WHERE u.h = ?1",
425            params![h.as_slice()],
426            |r| {
427                Ok((
428                    r.get::<_, i64>(0)?,
429                    r.get::<_, Option<String>>(1)?,
430                    r.get::<_, Option<String>>(2)?,
431                    r.get::<_, Option<String>>(3)?,
432                    r.get::<_, Option<String>>(4)?,
433                ))
434            },
435        )
436        .optional()
437        .map_err(|e| e.to_string())?;
438    Ok(match row {
439        Some((t, namespace, generator, actor, source)) => LookupResult {
440            issued: true,
441            namespace,
442            generator,
443            actor,
444            source,
445            created_at: Some(t),
446        },
447        None => LookupResult {
448            issued: false,
449            namespace: None,
450            generator: None,
451            actor: None,
452            source: None,
453            created_at: None,
454        },
455    })
456}
457
458/// Registers an ID that was minted **elsewhere** — the provenance-recording
459/// half, distinct from `mint` which generates in-process.
460pub fn register_external(
461    conn: &Connection,
462    pepper: &[u8; 32],
463    values: &[String],
464    mode: Normalise,
465    meta: &BatchMeta,
466) -> Result<Vec<RegisterOutcome>, String> {
467    register(conn, pepper, values, mode, meta)
468}
469
470// ── Prune ──────────────────────────────────────────────────────────────────────
471
472#[derive(Serialize, Default)]
473pub struct PruneReport {
474    pub matched: u64,
475    pub deleted: u64,
476    pub chunks: u64,
477    pub dry_run: bool,
478}
479
480/// Deletes rows older than `before_ts`, optionally narrowed by namespace,
481/// generator or actor (all resolved through `uid_meta`). Runs in chunks of
482/// `PRUNE_CHUNK` rows in **separate transactions**, so registration and
483/// minting are never blocked behind one long-held writer lock — the measured
484/// reason a single `DELETE` was rejected (45.7s at 10M rows vs. a 0.38s worst
485/// chunk).
486///
487/// This deletes the only evidence an ID was issued: a pruned ID can be issued
488/// again without a collision being detected, and `lookup` answers `unknown`
489/// for an ID that was real. Callers must say so before confirming — see
490/// `unv-app/src/uid_cmd.rs` and the `/api/uid/prune` handler.
491pub fn prune(
492    conn: &mut Connection,
493    before_ts: i64,
494    namespace: Option<&str>,
495    generator: Option<&str>,
496    actor: Option<&str>,
497    dry_run: bool,
498) -> Result<PruneReport, String> {
499    // One clause used unconditionally, rather than a fast path for "no meta
500    // filter": with every filter `NULL` the subquery matches every batch, so
501    // correctness does not depend on which branch ran — only the query plan
502    // would differ, and this table is small enough that it does not matter.
503    let where_clause = "u.t < ?1 AND u.m IN (SELECT id FROM uid_meta m WHERE \
504         (?2 IS NULL OR m.namespace = ?2) AND \
505         (?3 IS NULL OR m.generator = ?3) AND \
506         (?4 IS NULL OR m.actor = ?4))";
507
508    // rusqlite 0.40 dropped `FromSql for u64` (SQLite integers are signed).
509    let matched: i64 = conn
510        .query_row(
511            &format!("SELECT COUNT(*) FROM uid u WHERE {where_clause}"),
512            params![before_ts, namespace, generator, actor],
513            |r| r.get(0),
514        )
515        .map_err(|e| e.to_string())?;
516    let matched = matched as u64;
517
518    if dry_run {
519        return Ok(PruneReport {
520            matched,
521            deleted: 0,
522            chunks: 0,
523            dry_run: true,
524        });
525    }
526
527    let mut deleted: u64 = 0;
528    let mut chunks: u64 = 0;
529    loop {
530        let tx = conn.transaction().map_err(|e| e.to_string())?;
531        let n = tx
532            .execute(
533                &format!(
534                    "DELETE FROM uid WHERE h IN (SELECT h FROM uid u WHERE {where_clause} LIMIT {PRUNE_CHUNK})"
535                ),
536                params![before_ts, namespace, generator, actor],
537            )
538            .map_err(|e| e.to_string())?;
539        tx.commit().map_err(|e| e.to_string())?;
540        deleted += n as u64;
541        chunks += 1;
542        if n == 0 {
543            break;
544        }
545    }
546    Ok(PruneReport {
547        matched,
548        deleted,
549        chunks,
550        dry_run: false,
551    })
552}
553
554// ── Stats ──────────────────────────────────────────────────────────────────────
555
556#[derive(Serialize)]
557pub struct RegistryStats {
558    pub count: i64,
559    pub size_bytes: i64,
560    pub oldest_ts: Option<i64>,
561}
562
563pub fn stats(conn: &Connection) -> Result<RegistryStats, String> {
564    let count: i64 = conn
565        .query_row("SELECT COUNT(*) FROM uid", [], |r| r.get(0))
566        .map_err(|e| e.to_string())?;
567    let oldest_ts: Option<i64> = conn
568        .query_row("SELECT MIN(t) FROM uid", [], |r| r.get(0))
569        .map_err(|e| e.to_string())?;
570    let page_count: i64 = conn
571        .query_row("PRAGMA page_count", [], |r| r.get(0))
572        .unwrap_or(0);
573    let page_size: i64 = conn
574        .query_row("PRAGMA page_size", [], |r| r.get(0))
575        .unwrap_or(4096);
576    Ok(RegistryStats {
577        count,
578        size_bytes: page_count * page_size,
579        oldest_ts,
580    })
581}
582
583#[cfg(test)]
584mod tests {
585    use super::*;
586
587    fn mem() -> Connection {
588        let conn = Connection::open_in_memory().unwrap();
589        init_schema(&conn).unwrap();
590        conn
591    }
592
593    #[test]
594    fn uuid_normalisation_folds_case_and_dashes() {
595        let a = normalise("550E8400-E29B-41D4-A716-446655440000", Normalise::Uuid);
596        let b = normalise("550e8400e29b41d4a716446655440000", Normalise::Uuid);
597        assert_eq!(a, b);
598        assert_eq!(a, "550e8400-e29b-41d4-a716-446655440000");
599    }
600
601    #[test]
602    fn ulid_normalisation_maps_ambiguous_letters() {
603        // I/L -> 1, O -> 0, per Crockford base32.
604        assert_eq!(normalise("01ILOabc", Normalise::Ulid), "01110ABC");
605    }
606
607    #[test]
608    fn registering_the_same_value_twice_reports_a_conflict_not_two_rows() {
609        let conn = mem();
610        let pepper = [7u8; 32];
611        let meta = BatchMeta::default();
612        let first = register(&conn, &pepper, &["abc".to_string()], Normalise::None, &meta).unwrap();
613        assert!(first[0].registered);
614        let second =
615            register(&conn, &pepper, &["abc".to_string()], Normalise::None, &meta).unwrap();
616        assert!(!second[0].registered);
617        let count: i64 = conn
618            .query_row("SELECT COUNT(*) FROM uid", [], |r| r.get(0))
619            .unwrap();
620        assert_eq!(count, 1);
621    }
622
623    // S8: every insert failure was reported as "already registered", so a broken
624    // database looked like a run of collisions, and the batch's provenance row stayed.
625    #[test]
626    fn a_failed_insert_is_an_error_and_a_batch_of_conflicts_leaves_no_provenance() {
627        let conn = mem();
628        let pepper = [7u8; 32];
629        let meta = BatchMeta::default();
630        let metas = |c: &Connection| -> i64 {
631            c.query_row("SELECT COUNT(*) FROM uid_meta", [], |r| r.get(0))
632                .unwrap()
633        };
634        register(&conn, &pepper, &["abc".to_string()], Normalise::None, &meta).unwrap();
635        assert_eq!(metas(&conn), 1);
636        register(&conn, &pepper, &["abc".to_string()], Normalise::None, &meta).unwrap();
637        assert_eq!(
638            metas(&conn),
639            1,
640            "an all-conflict batch leaves no provenance row"
641        );
642        conn.execute_batch("ALTER TABLE uid RENAME TO uid_gone")
643            .unwrap();
644        let err = register(&conn, &pepper, &["new".to_string()], Normalise::None, &meta);
645        assert!(err.is_err(), "a failing insert is not a conflict");
646        assert_eq!(
647            metas(&conn),
648            1,
649            "the failed batch's provenance row was rolled back"
650        );
651    }
652
653    #[test]
654    fn check_is_advisory_and_never_reserves() {
655        let conn = mem();
656        let pepper = [1u8; 32];
657        let r1 = check(&conn, &pepper, &["x".to_string()], Normalise::None).unwrap();
658        assert!(r1[0].1, "unique before anything is registered");
659        let r2 = check(&conn, &pepper, &["x".to_string()], Normalise::None).unwrap();
660        assert!(r2[0].1, "check alone must not have reserved it");
661    }
662
663    #[test]
664    fn lookup_reports_provenance_for_a_registered_value() {
665        let conn = mem();
666        let pepper = [3u8; 32];
667        let meta = BatchMeta {
668            namespace: Some("ci"),
669            generator: Some("uuidv4"),
670            actor: Some("runner-1"),
671            ..Default::default()
672        };
673        register(&conn, &pepper, &["v1".to_string()], Normalise::None, &meta).unwrap();
674        let found = lookup(&conn, &pepper, "v1", Normalise::None).unwrap();
675        assert!(found.issued);
676        assert_eq!(found.namespace.as_deref(), Some("ci"));
677        let missing = lookup(&conn, &pepper, "v2", Normalise::None).unwrap();
678        assert!(!missing.issued);
679    }
680
681    #[test]
682    fn prune_deletes_only_rows_older_than_the_cutoff() {
683        let mut conn = mem();
684        let pepper = [9u8; 32];
685        let meta = BatchMeta::default();
686        register(&conn, &pepper, &["old".to_string()], Normalise::None, &meta).unwrap();
687        conn.execute("UPDATE uid SET t = 100", []).unwrap();
688        register(&conn, &pepper, &["new".to_string()], Normalise::None, &meta).unwrap();
689        conn.execute("UPDATE uid SET t = 999999999 WHERE t != 100", [])
690            .unwrap();
691
692        let dry = prune(&mut conn, 500, None, None, None, true).unwrap();
693        assert_eq!(dry.matched, 1);
694        assert_eq!(dry.deleted, 0);
695
696        let real = prune(&mut conn, 500, None, None, None, false).unwrap();
697        assert_eq!(real.deleted, 1);
698        let remaining: i64 = conn
699            .query_row("SELECT COUNT(*) FROM uid", [], |r| r.get(0))
700            .unwrap();
701        assert_eq!(remaining, 1);
702    }
703
704    #[test]
705    fn a_pruned_value_can_be_registered_again() {
706        // Written down as a consequence, not a bug: pruning deletes the only
707        // evidence an ID was issued.
708        let mut conn = mem();
709        let pepper = [4u8; 32];
710        let meta = BatchMeta::default();
711        register(
712            &conn,
713            &pepper,
714            &["gone".to_string()],
715            Normalise::None,
716            &meta,
717        )
718        .unwrap();
719        conn.execute("UPDATE uid SET t = 1", []).unwrap();
720        prune(&mut conn, 1000, None, None, None, false).unwrap();
721        let again = register(
722            &conn,
723            &pepper,
724            &["gone".to_string()],
725            Normalise::None,
726            &meta,
727        )
728        .unwrap();
729        assert!(again[0].registered);
730    }
731}