kovra-core 0.9.0

Core of kovra — local secrets manager for development: vault, sensitivity policy, providers, and the security invariants.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
//! Per-secret sealed-file store: the source of truth (ADR-0001 §A.1–3).
//!
//! Each secret is one independently AEAD-sealed record, filed as a single file
//! named `BLAKE3(coordinate).sec` under a vault directory. This is the
//! durability boundary: one corrupt file loses **one** secret, never the whole
//! vault.
//!
//! On-disk frame: a fixed header (magic [`FRAME_MAGIC`] + little-endian
//! [`FRAME_VERSION`]) followed by the JSON-serialized
//! [`SealedRecord`](crate::crypto::SealedRecord). The header lets the loader
//! reject foreign/garbage files cleanly and version the frame independently of
//! the sealed payload.
//!
//! Writes are atomic (temp → `fsync` → rotate previous to `.bak` → `rename`)
//! and files are `0600`. The loader is **tolerant**: a record that fails its
//! frame or its AEAD tag is quarantined and skipped, never aborting the scan.

use std::fs::{self, File};
use std::io::Write;
use std::path::{Path, PathBuf};

use crate::coordinate::Coordinate;
use crate::crypto::{KEY_LEN, SealedRecord, open};
use crate::error::CoreError;
use crate::record::SecretRecord;

/// Frame magic: marks a file as a kovra sealed record.
pub const FRAME_MAGIC: &[u8; 4] = b"KOVR";
/// On-disk frame version (independent of the vault schema version).
pub const FRAME_VERSION: u32 = 1;
/// Extension for a sealed record file.
pub const RECORD_EXT: &str = "sec";

const HEADER_LEN: usize = 4 + 4; // magic + u32 version

/// A record that could not be loaded, surfaced rather than aborting the scan.
/// The reason is a coordinate-free description (I12) — never a value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Quarantined {
    /// The record id (file stem) that failed to load.
    pub id: String,
    /// Why it was quarantined (frame mismatch, AEAD failure, I/O error).
    pub reason: String,
}

/// Outcome of [`load_all`]: every decryptable record plus the quarantined ones.
#[derive(Debug, Default)]
pub struct LoadOutcome {
    /// Successfully opened records, keyed by record id (file stem).
    pub records: Vec<(String, SecretRecord)>,
    /// Records skipped because they failed to load (ADR-0001 §A.3).
    pub quarantined: Vec<Quarantined>,
}

/// The on-disk path of a record within `dir`, given its storage id (the
/// `<id>.sec` naming convention, owned here so callers never re-derive it).
pub fn record_path_for_id(dir: &Path, id: &str) -> PathBuf {
    dir.join(format!("{id}.{RECORD_EXT}"))
}

/// The on-disk path of a coordinate's record within `dir`.
pub fn record_path(dir: &Path, coord: &Coordinate) -> Result<PathBuf, CoreError> {
    Ok(record_path_for_id(dir, &coord.storage_id()?))
}

/// Frame a sealed record for storage: header + JSON payload.
fn frame(sealed: &SealedRecord) -> Result<Vec<u8>, CoreError> {
    let payload =
        serde_json::to_vec(sealed).map_err(|e| CoreError::Serialization(e.to_string()))?;
    let mut out = Vec::with_capacity(HEADER_LEN + payload.len());
    out.extend_from_slice(FRAME_MAGIC);
    out.extend_from_slice(&FRAME_VERSION.to_le_bytes());
    out.extend_from_slice(&payload);
    Ok(out)
}

/// Parse a framed record back into a sealed record, validating the header.
fn unframe(bytes: &[u8]) -> Result<SealedRecord, CoreError> {
    if bytes.len() < HEADER_LEN || &bytes[..4] != FRAME_MAGIC {
        return Err(CoreError::Serialization(
            "not a kovra record frame".to_string(),
        ));
    }
    let version = u32::from_le_bytes(bytes[4..8].try_into().expect("checked length"));
    if version != FRAME_VERSION {
        return Err(CoreError::Serialization(format!(
            "unsupported record frame version {version}"
        )));
    }
    serde_json::from_slice(&bytes[HEADER_LEN..])
        .map_err(|e| CoreError::Serialization(e.to_string()))
}

/// Set restrictive permissions on a freshly created path: owner-only. On Unix
/// `0600` for files / `0700` for directories. On Windows the equivalent — a
/// **protected** DACL granting only the current user, `SYSTEM`, and
/// `Administrators` (inheritance stripped, so `Users`/`Everyone` are removed) —
/// mirroring how a Unix `0600` still lets root in (KOV-58, I7). No-op on other
/// targets. The single owner of kovra's on-disk permission policy — the index
/// reuses it for `index.redb`.
#[cfg(unix)]
pub(crate) fn restrict(path: &Path, mode: u32) -> Result<(), CoreError> {
    use std::os::unix::fs::PermissionsExt;
    fs::set_permissions(path, fs::Permissions::from_mode(mode))
        .map_err(|e| CoreError::Io(format!("chmod {mode:o}: {e}")))
}

#[cfg(windows)]
pub(crate) fn restrict(path: &Path, _mode: u32) -> Result<(), CoreError> {
    // Files and dirs both become owner-only; the Unix mode is not meaningful here.
    windows_acl::restrict_owner_only(path)
}

#[cfg(not(any(unix, windows)))]
pub(crate) fn restrict(_path: &Path, _mode: u32) -> Result<(), CoreError> {
    Ok(())
}

/// Windows owner-only ACLs — the analog of `chmod 0600/0700` (I7, KOV-58).
///
/// Builds a **protected** DACL with exactly three full-control ACEs — the current
/// user, `SYSTEM`, and `Administrators` — and applies it with
/// `PROTECTED_DACL_SECURITY_INFORMATION` so inherited ACEs (which on a lax parent
/// would grant `Users`/`Everyone`) are dropped. SYSTEM/Administrators are kept on
/// purpose: that matches Unix semantics, where a `0600` file is still readable by
/// root. Validated on real hardware (Windows validation tracker row 3); the test
/// below asserts the resulting DACL is protected (inheritance removed).
#[cfg(windows)]
mod windows_acl {
    use std::os::windows::ffi::OsStrExt;
    use std::path::Path;

    use windows::Win32::Foundation::{CloseHandle, HANDLE, HLOCAL, LocalFree};
    use windows::Win32::Security::Authorization::{
        EXPLICIT_ACCESS_W, MULTIPLE_TRUSTEE_OPERATION, SE_FILE_OBJECT, SET_ACCESS,
        SetEntriesInAclW, SetNamedSecurityInfoW, TRUSTEE_IS_SID, TRUSTEE_IS_UNKNOWN, TRUSTEE_W,
    };
    use windows::Win32::Security::{
        ACE_FLAGS, ACL, CreateWellKnownSid, DACL_SECURITY_INFORMATION, GetTokenInformation,
        PROTECTED_DACL_SECURITY_INFORMATION, PSID, SECURITY_MAX_SID_SIZE, TOKEN_QUERY, TOKEN_USER,
        TokenUser, WinBuiltinAdministratorsSid, WinLocalSystemSid,
    };
    use windows::Win32::System::Threading::{GetCurrentProcess, OpenProcessToken};
    use windows::core::{PCWSTR, PWSTR};

    use crate::error::CoreError;

    /// `GENERIC_ALL` — full control, the access mask granted to each trustee.
    const GENERIC_ALL: u32 = 0x1000_0000;

    pub(crate) fn restrict_owner_only(path: &Path) -> Result<(), CoreError> {
        // SAFETY: the body is a sequence of FFI calls whose pointer arguments all
        // refer to locals that outlive the call; see the per-call notes.
        unsafe { apply(path) }.map_err(|e| CoreError::Io(format!("set ACL on {path:?}: {e}")))
    }

    /// One full-control, non-inheritable ACE for `sid`.
    fn explicit_access(sid: PSID) -> EXPLICIT_ACCESS_W {
        EXPLICIT_ACCESS_W {
            grfAccessPermissions: GENERIC_ALL,
            grfAccessMode: SET_ACCESS,
            grfInheritance: ACE_FLAGS(0), // NO_INHERITANCE
            Trustee: TRUSTEE_W {
                pMultipleTrustee: core::ptr::null_mut(),
                MultipleTrusteeOperation: MULTIPLE_TRUSTEE_OPERATION(0),
                TrusteeForm: TRUSTEE_IS_SID,
                TrusteeType: TRUSTEE_IS_UNKNOWN,
                // For TRUSTEE_IS_SID the SID pointer is carried in ptstrName.
                ptstrName: PWSTR(sid.0 as *mut u16),
            },
        }
    }

    unsafe fn apply(path: &Path) -> windows::core::Result<()> {
        // 1. Current user's SID, from this process's token.
        let mut token = HANDLE::default();
        unsafe { OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &mut token)? };
        let mut len = 0u32;
        // First call sizes the buffer (it returns ERROR_INSUFFICIENT_BUFFER).
        let _ = unsafe { GetTokenInformation(token, TokenUser, None, 0, &mut len) };
        let mut buf = vec![0u8; len as usize];
        let info = unsafe {
            GetTokenInformation(
                token,
                TokenUser,
                Some(buf.as_mut_ptr().cast()),
                len,
                &mut len,
            )
        };
        unsafe { CloseHandle(token).ok() };
        info?;
        // SAFETY: `buf` holds a TOKEN_USER written by the OS; valid for this scope.
        let token_user = unsafe { &*(buf.as_ptr() as *const TOKEN_USER) };
        let user_sid = token_user.User.Sid;

        // 2. Well-known SYSTEM and Administrators SIDs (fixed-size local buffers).
        let mut system_buf = [0u8; SECURITY_MAX_SID_SIZE as usize];
        let mut admins_buf = [0u8; SECURITY_MAX_SID_SIZE as usize];
        let mut n = SECURITY_MAX_SID_SIZE;
        unsafe {
            CreateWellKnownSid(
                WinLocalSystemSid,
                None,
                Some(PSID(system_buf.as_mut_ptr().cast())),
                &mut n,
            )?
        };
        let mut n2 = SECURITY_MAX_SID_SIZE;
        unsafe {
            CreateWellKnownSid(
                WinBuiltinAdministratorsSid,
                None,
                Some(PSID(admins_buf.as_mut_ptr().cast())),
                &mut n2,
            )?
        };
        let system_sid = PSID(system_buf.as_mut_ptr().cast());
        let admins_sid = PSID(admins_buf.as_mut_ptr().cast());

        // 3. Build the DACL: full control for {user, SYSTEM, Administrators}.
        let entries = [
            explicit_access(user_sid),
            explicit_access(system_sid),
            explicit_access(admins_sid),
        ];
        let mut new_acl: *mut ACL = core::ptr::null_mut();
        let rc = unsafe { SetEntriesInAclW(Some(&entries), None, &mut new_acl) };
        if rc.0 != 0 {
            return Err(windows::core::Error::from_hresult(
                windows::core::HRESULT::from_win32(rc.0),
            ));
        }

        // 4. Apply as a PROTECTED DACL so inherited ACEs (Users/Everyone) are
        //    stripped. Owner/group/SACL are left unchanged.
        let wide: Vec<u16> = path
            .as_os_str()
            .encode_wide()
            .chain(core::iter::once(0))
            .collect();
        let rc = unsafe {
            SetNamedSecurityInfoW(
                PCWSTR(wide.as_ptr()),
                SE_FILE_OBJECT,
                DACL_SECURITY_INFORMATION | PROTECTED_DACL_SECURITY_INFORMATION,
                None,
                None,
                Some(new_acl as *const ACL),
                None,
            )
        };
        // The ACL SetEntriesInAclW allocated is freed regardless of the outcome.
        unsafe { LocalFree(Some(HLOCAL(new_acl.cast()))) };
        if rc.0 != 0 {
            return Err(windows::core::Error::from_hresult(
                windows::core::HRESULT::from_win32(rc.0),
            ));
        }
        Ok(())
    }
}

/// Create a vault directory (and parents) at `0700` if missing.
pub fn ensure_dir(dir: &Path) -> Result<(), CoreError> {
    if !dir.exists() {
        fs::create_dir_all(dir).map_err(|e| CoreError::Io(format!("create {dir:?}: {e}")))?;
        restrict(dir, 0o700)?;
    }
    Ok(())
}

/// Write a sealed record atomically: temp file → `fsync` → rotate any existing
/// record to `.bak` → `rename` into place. The result is `0600`.
pub fn write_record(
    dir: &Path,
    coord: &Coordinate,
    sealed: &SealedRecord,
) -> Result<(), CoreError> {
    ensure_dir(dir)?;
    let path = record_path(dir, coord)?;
    let tmp = path.with_extension(format!("{RECORD_EXT}.tmp"));
    let bytes = frame(sealed)?;

    {
        let mut f = File::create(&tmp).map_err(|e| CoreError::Io(format!("create tmp: {e}")))?;
        f.write_all(&bytes)
            .map_err(|e| CoreError::Io(format!("write tmp: {e}")))?;
        f.sync_all()
            .map_err(|e| CoreError::Io(format!("fsync tmp: {e}")))?;
    }
    restrict(&tmp, 0o600)?;

    if path.exists() {
        let bak = path.with_extension(format!("{RECORD_EXT}.bak"));
        fs::rename(&path, &bak).map_err(|e| CoreError::Io(format!("rotate .bak: {e}")))?;
    }
    fs::rename(&tmp, &path).map_err(|e| CoreError::Io(format!("rename into place: {e}")))?;
    Ok(())
}

/// Read and decrypt a single record by coordinate — the O(1) point-lookup path
/// used by resolution (it never touches the index, ADR-0001 §A.5). Returns
/// `Ok(None)` when the record does not exist.
pub fn read_record(
    dir: &Path,
    coord: &Coordinate,
    key: &[u8; KEY_LEN],
) -> Result<Option<SecretRecord>, CoreError> {
    let path = record_path(dir, coord)?;
    if !path.exists() {
        return Ok(None);
    }
    let bytes = fs::read(&path).map_err(|e| CoreError::Io(format!("read record: {e}")))?;
    let sealed = unframe(&bytes)?;
    Ok(Some(open(&sealed, key)?))
}

/// Load every record in a vault directory, tolerantly (ADR-0001 §A.3). A file
/// that fails its frame or its AEAD tag is quarantined and skipped; the scan
/// never aborts, so one corrupt record cannot hide the rest.
pub fn load_all(dir: &Path, key: &[u8; KEY_LEN]) -> Result<LoadOutcome, CoreError> {
    let mut outcome = LoadOutcome::default();
    if !dir.exists() {
        return Ok(outcome);
    }
    let entries = fs::read_dir(dir).map_err(|e| CoreError::Io(format!("read_dir: {e}")))?;
    for entry in entries {
        let entry = entry.map_err(|e| CoreError::Io(format!("dir entry: {e}")))?;
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some(RECORD_EXT) {
            continue; // skip .bak, .tmp, index, anything not a record
        }
        let id = path
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or_default()
            .to_string();

        let opened = fs::read(&path)
            .map_err(|e| CoreError::Io(format!("read: {e}")))
            .and_then(|bytes| unframe(&bytes))
            .and_then(|sealed| open(&sealed, key));

        match opened {
            Ok(record) => outcome.records.push((id, record)),
            Err(e) => outcome.quarantined.push(Quarantined {
                id,
                reason: e.to_string(),
            }),
        }
    }
    Ok(outcome)
}

/// Remove a record (its `.sec` file). The `.bak` rotation, if any, is left in
/// place. No-op if the record does not exist.
pub fn delete_record(dir: &Path, coord: &Coordinate) -> Result<(), CoreError> {
    let path = record_path(dir, coord)?;
    if path.exists() {
        fs::remove_file(&path).map_err(|e| CoreError::Io(format!("remove record: {e}")))?;
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crypto::seal;
    use crate::secret::SecretValue;
    use crate::sensitivity::Sensitivity;

    fn key() -> [u8; KEY_LEN] {
        [0x11; KEY_LEN]
    }

    fn coord(s: &str) -> Coordinate {
        s.parse().unwrap()
    }

    fn literal(value: &str) -> SecretRecord {
        SecretRecord::Literal {
            value: SecretValue::from(value),
            sensitivity: Sensitivity::Medium,
            revealable: false,
            environment: "prod".to_string(),
            component: "db".to_string(),
            key: "password".to_string(),
            description: None,
            created: "2026-05-30T00:00:00Z".to_string(),
            updated: "2026-05-30T00:00:00Z".to_string(),
        }
    }

    #[test]
    fn write_then_read_round_trips() {
        let dir = tempfile::tempdir().unwrap();
        let c = coord("secret:prod/db/password");
        let sealed = seal(&literal("hunter2"), &key()).unwrap();
        write_record(dir.path(), &c, &sealed).unwrap();

        let got = read_record(dir.path(), &c, &key()).unwrap().unwrap();
        match got {
            SecretRecord::Literal { value, .. } => assert_eq!(value.expose(), b"hunter2"),
            other => panic!("expected literal, got {other:?}"),
        }
    }

    #[test]
    fn read_missing_is_none() {
        let dir = tempfile::tempdir().unwrap();
        let c = coord("secret:prod/db/absent");
        assert!(read_record(dir.path(), &c, &key()).unwrap().is_none());
    }

    #[test]
    fn record_file_has_extension_and_hashed_name() {
        let dir = tempfile::tempdir().unwrap();
        let c = coord("secret:prod/db/password");
        write_record(dir.path(), &c, &seal(&literal("x"), &key()).unwrap()).unwrap();
        let path = record_path(dir.path(), &c).unwrap();
        assert!(path.exists());
        // filename is the blake3 hex id, never the cleartext coordinate
        let name = path.file_name().unwrap().to_str().unwrap();
        assert!(name.ends_with(".sec"));
        assert!(!name.contains("password"));
    }

    #[cfg(unix)]
    #[test]
    fn written_record_is_0600() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let c = coord("secret:prod/db/password");
        write_record(dir.path(), &c, &seal(&literal("x"), &key()).unwrap()).unwrap();
        let mode = fs::metadata(record_path(dir.path(), &c).unwrap())
            .unwrap()
            .permissions()
            .mode();
        assert_eq!(mode & 0o777, 0o600);
    }

    // I7 (Windows analog of `0600`): `restrict` makes the file's DACL **protected**
    // — inheritance is removed, so a lax parent can no longer leak `Users`/`Everyone`
    // access to the secret at rest (KOV-58). We assert the SE_DACL_PROTECTED control
    // bit; the impl only ever adds {current user, SYSTEM, Administrators}.
    #[cfg(windows)]
    #[test]
    fn windows_restrict_makes_dacl_protected() {
        use std::os::windows::ffi::OsStrExt;

        use windows::Win32::Foundation::{HLOCAL, LocalFree};
        use windows::Win32::Security::Authorization::{GetNamedSecurityInfoW, SE_FILE_OBJECT};
        use windows::Win32::Security::{
            DACL_SECURITY_INFORMATION, GetSecurityDescriptorControl, PSECURITY_DESCRIPTOR,
            SE_DACL_PROTECTED,
        };
        use windows::core::PCWSTR;

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("secret.bin");
        fs::write(&path, b"x").unwrap();
        restrict(&path, 0o600).unwrap();

        let wide: Vec<u16> = path
            .as_os_str()
            .encode_wide()
            .chain(core::iter::once(0))
            .collect();
        let mut psd = PSECURITY_DESCRIPTOR::default();
        // SAFETY: FFI; `psd` receives an owned descriptor we LocalFree below.
        let rc = unsafe {
            GetNamedSecurityInfoW(
                PCWSTR(wide.as_ptr()),
                SE_FILE_OBJECT,
                DACL_SECURITY_INFORMATION,
                None,
                None,
                None,
                None,
                &mut psd,
            )
        };
        assert_eq!(rc.0, 0, "GetNamedSecurityInfoW failed: {}", rc.0);
        let mut control = 0u16;
        let mut revision = 0u32;
        // SAFETY: FFI; `psd` is a valid descriptor until we free it.
        unsafe { GetSecurityDescriptorControl(psd, &mut control, &mut revision).unwrap() };
        // SAFETY: FFI; free the descriptor GetNamedSecurityInfoW allocated.
        unsafe { LocalFree(Some(HLOCAL(psd.0.cast()))) };

        assert!(
            control & SE_DACL_PROTECTED.0 != 0,
            "DACL must be protected (inheritance stripped); control={control:#x}"
        );
    }

    #[test]
    fn overwrite_rotates_previous_to_bak() {
        let dir = tempfile::tempdir().unwrap();
        let c = coord("secret:prod/db/password");
        write_record(dir.path(), &c, &seal(&literal("v1"), &key()).unwrap()).unwrap();
        write_record(dir.path(), &c, &seal(&literal("v2"), &key()).unwrap()).unwrap();

        // current holds v2
        let current = read_record(dir.path(), &c, &key()).unwrap().unwrap();
        match current {
            SecretRecord::Literal { value, .. } => assert_eq!(value.expose(), b"v2"),
            other => panic!("expected literal, got {other:?}"),
        }
        // a .bak sibling exists
        let bak = record_path(dir.path(), &c)
            .unwrap()
            .with_extension(format!("{RECORD_EXT}.bak"));
        assert!(bak.exists());
    }

    #[test]
    fn load_all_quarantines_corrupt_and_loads_siblings() {
        let dir = tempfile::tempdir().unwrap();
        let good = coord("secret:prod/db/good");
        let bad = coord("secret:prod/db/bad");
        write_record(
            dir.path(),
            &good,
            &seal(&literal("good-val"), &key()).unwrap(),
        )
        .unwrap();
        write_record(
            dir.path(),
            &bad,
            &seal(&literal("bad-val"), &key()).unwrap(),
        )
        .unwrap();

        // Corrupt the ciphertext of the "bad" record (flip a byte past the frame
        // header, so the frame parses but the AEAD tag fails).
        let bad_path = record_path(dir.path(), &bad).unwrap();
        let mut bytes = fs::read(&bad_path).unwrap();
        let last = bytes.len() - 1;
        bytes[last] ^= 0xff;
        fs::write(&bad_path, &bytes).unwrap();

        let outcome = load_all(dir.path(), &key()).unwrap();
        assert_eq!(outcome.records.len(), 1, "the good record still loads");
        assert_eq!(
            outcome.quarantined.len(),
            1,
            "the bad record is quarantined"
        );
        assert_eq!(outcome.quarantined[0].id, bad.storage_id().unwrap());
        // quarantine reason carries no value
        assert!(!outcome.quarantined[0].reason.contains("bad-val"));
    }

    #[test]
    fn load_all_quarantines_garbage_file() {
        let dir = tempfile::tempdir().unwrap();
        ensure_dir(dir.path()).unwrap();
        fs::write(dir.path().join("deadbeef.sec"), b"not a frame").unwrap();
        let outcome = load_all(dir.path(), &key()).unwrap();
        assert!(outcome.records.is_empty());
        assert_eq!(outcome.quarantined.len(), 1);
    }

    #[test]
    fn delete_removes_record() {
        let dir = tempfile::tempdir().unwrap();
        let c = coord("secret:prod/db/password");
        write_record(dir.path(), &c, &seal(&literal("x"), &key()).unwrap()).unwrap();
        delete_record(dir.path(), &c).unwrap();
        assert!(read_record(dir.path(), &c, &key()).unwrap().is_none());
    }

    #[test]
    fn placeholder_coordinate_is_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let c = coord("secret:${ENV}/db/password");
        assert!(matches!(
            write_record(dir.path(), &c, &seal(&literal("x"), &key()).unwrap()),
            Err(CoreError::NotStorable(_))
        ));
    }
}