Skip to main content

dig_keystore/backend/
file.rs

1//! Filesystem backend.
2//!
3//! # What this does
4//!
5//! Stores each [`BackendKey`] as a `<root>/<key>.dks` file (`.dks` = "DIG
6//! keystore"). Writes are atomic (tmp file + rename). Deletes best-effort
7//! overwrite the file with zeros before unlinking.
8//!
9//! # Atomicity
10//!
11//! On **POSIX**: `rename(2)` is atomic within a filesystem. We write to
12//! `<key>.dks.tmp.<random>`, `fsync` the file handle, then `rename` onto the
13//! final name. If the process crashes between the open and the rename, the
14//! tmp file is orphaned but the original `<key>.dks` (if any) is intact.
15//!
16//! On **Windows**: Rust's `std::fs::rename` wraps `MoveFileExW` with the
17//! `MOVEFILE_REPLACE_EXISTING` flag, which is atomic enough for our purposes
18//! (Windows does not provide a fully-atomic rename-across-replace on all
19//! filesystems but the behaviour is "either old or new contents — never a
20//! torn write").
21//!
22//! # Permissions
23//!
24//! On Unix, the keystore root directory (on creation) and every written file
25//! are restricted to mode `0700` / `0600` — reachable only by the owning user
26//! — and that restriction is **verified after the fact**, not merely
27//! requested. A path that is still group- or other-accessible fails the write
28//! with [`KeystoreError::InsecurePermissions`] rather than succeeding quietly,
29//! because a `chmod` on a filesystem without POSIX modes reports success and
30//! changes nothing. See [`is_owner_only`].
31//!
32//! **On Windows there is no equivalent floor.** Standard NTFS ACL inheritance
33//! applies and this crate does not narrow it, so a blob inherits whatever its
34//! parent directory grants. Restricting it would mean an explicit owner-only
35//! DACL, which requires Win32 FFI, and this package pins `unsafe_code =
36//! "forbid"` as a spec property (`SPEC.md` §12/§13.2, conformance C-15) — so
37//! that enforcement cannot live here. It belongs beside the platform hardware
38//! providers in a separate workspace member (dig_ecosystem #1693). Until then,
39//! operators on a shared user account should not rely on this crate for access
40//! control on Windows.
41//!
42//! Either way this is defence in depth. The blob is already sealed with
43//! AES-256-GCM under an Argon2id-hardened key (`SPEC.md` §3–§5); permissions
44//! decide who may *attempt* an offline attack on it, not whether one succeeds.
45//!
46//! # Secure delete
47//!
48//! On modern SSDs, a single-pass overwrite cannot guarantee the sectors are
49//! unrecoverable — the SSD's flash translation layer may have copied them
50//! elsewhere. This crate does a single zero pass as a best-effort. For
51//! high-value keys on untrusted hardware, use full-disk encryption (LUKS,
52//! BitLocker) which zero-keys the entire volume on wipe.
53//!
54//! # References
55//!
56//! - [POSIX `rename(2)`](https://pubs.opengroup.org/onlinepubs/9699919799/functions/rename.html)
57//! - [Windows `MoveFileExW`](https://learn.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexw)
58//! - [DJB on secure-delete on SSDs](https://cr.yp.to/bib/2009/coker.pdf)
59
60use std::fs;
61use std::io::{self, Read, Write};
62use std::path::{Path, PathBuf};
63
64use crate::backend::{BackendKey, Exclusivity, KeychainBackend};
65use crate::error::{KeystoreError, Result};
66
67/// File extension for keystore blobs. Stands for "DIG KeyStore".
68const EXT: &str = "dks";
69
70/// Every group and other permission bit — the set that must be clear on any
71/// path holding sealed key material.
72const GROUP_AND_OTHER_BITS: u32 = 0o077;
73
74/// Whether `mode` grants access to nobody but the owner.
75///
76/// This is the property the backend actually promises. It is deliberately
77/// phrased over the *observed* bits rather than over "did `chmod` return
78/// `Ok`", because the two are not the same thing: on a filesystem with no
79/// POSIX mode support a `chmod` succeeds and changes nothing, so a successful
80/// call is no evidence at all that the file is protected.
81///
82/// Only the low nine permission bits are considered; file-type and setuid
83/// bits carried in the same word are irrelevant to who may read the blob.
84///
85/// Compiled on every platform even though only Unix calls it, so that its
86/// behaviour is testable on any build host. A `#[cfg(unix)]` predicate is
87/// unfalsifiable on a Windows developer machine, which is where most of this
88/// crate's consumers are written.
89#[cfg_attr(not(unix), allow(dead_code))]
90fn is_owner_only(mode: u32) -> bool {
91    mode & GROUP_AND_OTHER_BITS == 0
92}
93
94/// Request owner-only permissions on `path`, then verify they took effect.
95///
96/// `requested` is the mode to ask for (`0o700` for the root directory,
97/// `0o600` for a blob). The request's own error is intentionally ignored: it
98/// is the verification below, not the call's return value, that decides
99/// whether the path is safe to hold key material.
100///
101/// On non-Unix hosts this is a no-op — see the module docs for what does and
102/// does not protect a blob on Windows.
103#[allow(unused_variables)]
104fn enforce_owner_only(path: &Path, requested: u32) -> Result<()> {
105    #[cfg(unix)]
106    {
107        use std::os::unix::fs::PermissionsExt;
108
109        let _ = fs::set_permissions(path, fs::Permissions::from_mode(requested));
110
111        let mode = fs::metadata(path)?.permissions().mode() & 0o777;
112        if !is_owner_only(mode) {
113            return Err(KeystoreError::InsecurePermissions {
114                path: path.display().to_string(),
115                mode,
116            });
117        }
118    }
119    Ok(())
120}
121
122/// Create `path` for writing, born owner-only where the platform allows it.
123///
124/// `File::create` opens with `0666 & ~umask`, so on a default umask the tmp
125/// blob exists at `0644` for the window between the open and the narrowing
126/// `chmod`. Requesting the mode in the `open(2)` call itself removes that
127/// window: the file never exists under a permissive mode at all. `create_new`
128/// additionally refuses to follow a symlink planted on the tmp path.
129///
130/// One window is *not* closed by this, and is not closable from user space: a
131/// process holding a directory fd opened before the root was tightened can
132/// still `openat` inside it, and read permission granted at open time survives
133/// any later `chmod`. That is why the root is brought to a verified `0700`
134/// before any tmp file is created, rather than relying on the blob mode alone.
135fn create_owner_only(path: &Path) -> Result<fs::File> {
136    let mut opts = fs::OpenOptions::new();
137    opts.write(true).create_new(true);
138    #[cfg(unix)]
139    {
140        use std::os::unix::fs::OpenOptionsExt;
141        opts.mode(0o600);
142    }
143    Ok(opts.open(path)?)
144}
145
146/// Filesystem-backed keychain.
147///
148/// Thread-safe — `KeychainBackend` is `Send + Sync`, and all operations use
149/// OS-level atomic primitives (rename, unlink). Multiple `FileBackend`
150/// instances pointing at the same root directory coexist without mutual
151/// serialization; the tmp-file names include a random suffix so concurrent
152/// writes to the same `BackendKey` do not step on each other's tmp files.
153///
154/// # Example
155///
156/// ```no_run
157/// use std::sync::Arc;
158/// use dig_keystore::{
159///     backend::{FileBackend, BackendKey, KeychainBackend},
160/// };
161///
162/// let backend: Arc<dyn KeychainBackend> = Arc::new(
163///     FileBackend::new("/var/lib/dig/keys")
164/// );
165/// backend.write(&BackendKey::new("v1"), b"...").unwrap();
166/// # drop(backend);
167/// ```
168pub struct FileBackend {
169    /// Directory that contains all `<key>.dks` files owned by this backend.
170    root: PathBuf,
171}
172
173impl FileBackend {
174    /// Create a new file backend rooted at `root`.
175    ///
176    /// The directory is **not** created immediately — it is lazily created on
177    /// the first `write` call (with mode `0700` on Unix). This lets callers
178    /// construct a `FileBackend` in tests without side effects; no files are
179    /// written until the first `write`.
180    ///
181    /// # Example
182    ///
183    /// ```
184    /// use dig_keystore::backend::FileBackend;
185    /// let be = FileBackend::new("/var/lib/dig/keys");
186    /// let _ = be;  // directory not created yet
187    /// ```
188    pub fn new(root: impl Into<PathBuf>) -> Self {
189        Self { root: root.into() }
190    }
191
192    /// The root directory this backend writes to.
193    pub fn root(&self) -> &Path {
194        &self.root
195    }
196
197    /// Build the full path for a `BackendKey`.
198    fn path_for(&self, key: &BackendKey) -> PathBuf {
199        let mut p = self.root.clone();
200        p.push(format!("{}.{}", key.as_str(), EXT));
201        p
202    }
203
204    /// Create the root directory if it does not already exist, and hold it to
205    /// the owner-only floor whether or not this call created it.
206    ///
207    /// Called from `write` to support the "lazy directory creation" behaviour.
208    /// On Unix the directory is restricted to mode `0700` — so only the owning
209    /// user can list or enter it — and that is verified, not assumed.
210    ///
211    /// **The check runs on every write, not only on the creation path.** An
212    /// earlier shape returned early when the root already existed, which left
213    /// the floor unreachable for exactly the roots that need it most: one
214    /// created by a version that requested `0700` without checking the result,
215    /// on a filesystem where that request does nothing, stays unverified
216    /// forever.
217    ///
218    /// The exposure that closes is the root's **write** bits rather than its
219    /// read bits — blobs carry their own verified `0600`, so a permissive root
220    /// does not expose sealed bytes, but group- or world-writable grants
221    /// `unlink` and `create` inside it. That is blob substitution (rolling a
222    /// victim back to an older sealed seed) and deletion, on the directory
223    /// holding an account master seed.
224    ///
225    /// **A permissive mode is repaired; a symlinked root is refused.** The two
226    /// resolve in opposite directions because they are different kinds of
227    /// claim. A mode is a property of the intended directory: the backend can
228    /// correct it in one syscall and then *verify* that it did, so refusing
229    /// instead would turn any drift — a restore from backup, a `chmod` by the
230    /// user — into a permanent brick on master-seed writes, and hand anyone who
231    /// can merely widen the mode a denial primitive over a condition the crate
232    /// can fix. A symlink is a claim about *which directory the keystore is*,
233    /// and no syscall makes an attacker-chosen directory into the intended one;
234    /// since `set_permissions` and `metadata` both follow links, "repairing" it
235    /// would mean chmodding that directory to `0700` and sealing the seed
236    /// inside it. Fail closed where the invariant cannot be established, repair
237    /// where it can be established and confirmed.
238    fn ensure_root(&self) -> Result<()> {
239        // `symlink_metadata` inspects the root itself; `exists()` and
240        // `metadata()` both follow links, and so do `set_permissions` and the
241        // verification read below. Following a link here would mean chmodding
242        // and then seeding a directory chosen by whoever planted it.
243        match fs::symlink_metadata(&self.root) {
244            Ok(meta) if meta.file_type().is_symlink() => Err(KeystoreError::UnsafeRoot {
245                path: self.root.display().to_string(),
246                reason: "it is a symbolic link; pass the resolved target if that is intended",
247            }),
248            Ok(meta) if !meta.is_dir() => Err(KeystoreError::UnsafeRoot {
249                path: self.root.display().to_string(),
250                reason: "it exists and is not a directory",
251            }),
252            Ok(_) => enforce_owner_only(&self.root, 0o700),
253            Err(e) if e.kind() == io::ErrorKind::NotFound => {
254                fs::create_dir_all(&self.root)?;
255                enforce_owner_only(&self.root, 0o700)
256            }
257            Err(e) => Err(KeystoreError::from(e)),
258        }
259    }
260}
261
262impl KeychainBackend for FileBackend {
263    /// Read the entire file at `<root>/<key>.dks`.
264    ///
265    /// Returns `KeystoreError::Backend` wrapping an `io::Error` with
266    /// `ErrorKind::NotFound` if the file does not exist.
267    fn read(&self, key: &BackendKey) -> Result<Vec<u8>> {
268        let path = self.path_for(key);
269        let mut f = fs::File::open(&path)?;
270        let mut buf = Vec::new();
271        f.read_to_end(&mut buf)?;
272        Ok(buf)
273    }
274
275    /// Atomically write `data` to `<root>/<key>.dks`.
276    ///
277    /// Steps:
278    /// 1. Ensure `root` exists, is a directory rather than a symlink, and is
279    ///    verified owner-only.
280    /// 2. Create sibling `<key>.dks.tmp.<random>` file with mode `0600`
281    ///    requested in the `open(2)` call on Unix, then verify the mode that
282    ///    actually took effect before any bytes are written —
283    ///    so a root that cannot hold key material safely yields
284    ///    [`KeystoreError::InsecurePermissions`] and an empty, removed tmp
285    ///    file rather than an exposed blob.
286    /// 3. Write `data`, `fsync` the file handle.
287    /// 4. `rename` the tmp file onto the final name.
288    /// 5. On Unix, `fsync` the containing directory so the rename is durable.
289    /// 6. On error in step 4, best-effort unlink the tmp file.
290    ///
291    /// The random suffix in step 2 is **not** cryptographic — it exists only
292    /// to disambiguate two concurrent writes to the same key from the same
293    /// process. Uses a hash of `(nanoseconds_since_epoch, pid)`.
294    fn write(&self, key: &BackendKey, data: &[u8]) -> Result<()> {
295        self.ensure_root()?;
296        let final_path = self.path_for(key);
297        let mut tmp_path = final_path.clone();
298        let rand_suffix: u64 = fastrand_suffix();
299        tmp_path.set_extension(format!("{EXT}.tmp.{rand_suffix:016x}"));
300
301        // Stage the bytes into the tmp file. Written as a closure so the file
302        // handle is dropped by leaving scope — and so EVERY failure in here,
303        // not just a rename failure, gets the same cleanup below. An earlier
304        // shape orphaned the tmp file whenever `write_all` or `sync_all`
305        // failed.
306        let staged = (|| -> Result<()> {
307            let mut f = create_owner_only(&tmp_path)?;
308            // Restrict the file BEFORE any ciphertext reaches it. A keystore
309            // that cannot protect its own blobs must write nothing at all,
310            // rather than report success over a world-readable seed.
311            enforce_owner_only(&tmp_path, 0o600)?;
312            f.write_all(data)?;
313            // fsync the file so the bytes hit durable storage before rename.
314            // Without this, a crash between write() and rename() would leave
315            // a zero-length tmp file and no keystore data at all.
316            f.sync_all()?;
317            Ok(())
318        })();
319
320        if let Err(e) = staged {
321            // The handle is already closed, so this also succeeds on Windows,
322            // where an open file cannot be unlinked.
323            let _ = fs::remove_file(&tmp_path);
324            return Err(e);
325        }
326
327        // Atomic rename. On POSIX this is truly atomic within a filesystem;
328        // on Windows it's "effectively atomic" via MoveFileExW.
329        fs::rename(&tmp_path, &final_path).map_err(|e| {
330            // Best-effort cleanup of the tmp file on rename failure.
331            let _ = fs::remove_file(&tmp_path);
332            KeystoreError::from(e)
333        })?;
334
335        // fsync the containing directory on Unix so the rename is durable
336        // across a crash. No-op on Windows (directory fsync isn't a concept).
337        #[cfg(unix)]
338        {
339            if let Ok(dir) = fs::File::open(&self.root) {
340                let _ = dir.sync_all();
341            }
342        }
343
344        Ok(())
345    }
346
347    /// Best-effort secure delete, then unlink.
348    ///
349    /// Steps:
350    /// 1. No-op if the file is **confidently absent** (idempotent); refuses if
351    ///    its presence could not be determined, rather than reporting a
352    ///    completed erase over a blob that may still be there.
353    /// 2. Open the file for writing; overwrite with zeros in 4 KiB chunks.
354    /// 3. `fsync` the overwritten file so zeros hit storage.
355    /// 4. `unlink` the file.
356    ///
357    /// Step 2 is best-effort. On SSDs with flash translation layer or on
358    /// copy-on-write filesystems (btrfs, ZFS), the zero pass may not reach
359    /// the sectors that held the ciphertext. Use full-disk encryption for
360    /// stronger guarantees.
361    fn delete(&self, key: &BackendKey) -> Result<()> {
362        let path = self.path_for(key);
363        // Three-valued, exactly as `exists` — an absent blob is an idempotent
364        // success, but a blob whose presence could not be DETERMINED is a
365        // refusal. `Path::exists()` collapses those, so an unreadable parent
366        // used to report a completed secure-erase over key material still on
367        // disk (`SPEC.md` §10.2).
368        match fs::symlink_metadata(&path) {
369            // Present. A dangling symlink lands here too, and is unlinked
370            // below: something occupies the name, and removing it is what the
371            // caller asked for.
372            Ok(_) => {}
373            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(()),
374            Err(e) => return Err(e.into()),
375        }
376
377        if let Ok(metadata) = fs::metadata(&path) {
378            let len = metadata.len();
379            if let Ok(mut f) = fs::OpenOptions::new().write(true).open(&path) {
380                let zeros = vec![0u8; 4096];
381                let mut remaining = len as usize;
382                while remaining > 0 {
383                    let n = remaining.min(zeros.len());
384                    if f.write_all(&zeros[..n]).is_err() {
385                        break;
386                    }
387                    remaining -= n;
388                }
389                let _ = f.sync_all();
390            }
391        }
392
393        fs::remove_file(&path)?;
394        Ok(())
395    }
396
397    /// Enumerate keys whose names start with `prefix`.
398    ///
399    /// Scans the root directory; skips any file that:
400    /// - does not end in `.dks`
401    /// - has a non-UTF-8 name
402    /// - does not start with `prefix`
403    ///
404    /// Returns an empty vec if the root directory is **confidently absent**, and
405    /// an error if it could not be inspected at all — the same three-valued
406    /// contract [`exists`](Self::exists) keeps, for the same reason.
407    fn list(&self, prefix: &str) -> Result<Vec<BackendKey>> {
408        // An absent root is a legitimate empty result — no keystore has been
409        // created yet. A root that could not be INSPECTED is not: reporting it
410        // as empty tells a caller enumerating identities that the user has no
411        // keys, when the truth is that we could not look (`SPEC.md` §10.2).
412        match fs::symlink_metadata(&self.root) {
413            Ok(_) => {}
414            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()),
415            Err(e) => return Err(e.into()),
416        }
417        let mut out = Vec::new();
418        for entry in fs::read_dir(&self.root)? {
419            let entry = entry?;
420            let name = entry.file_name();
421            let name = match name.to_str() {
422                Some(s) => s,
423                None => continue,
424            };
425            let Some(stem) = name.strip_suffix(&format!(".{EXT}")) else {
426                continue;
427            };
428            if stem.starts_with(prefix) {
429                out.push(BackendKey::new(stem.to_string()));
430            }
431        }
432        Ok(out)
433    }
434
435    /// Stat the path without opening it, preserving the trait's three-valued
436    /// contract: present, confidently absent, or **could not determine**.
437    ///
438    /// Uses `symlink_metadata` rather than `Path::exists()` or `try_exists()`.
439    /// `Path::exists()` maps every error to `false`, which turns an
440    /// inspection failure into a confident negative — and the caller uses that
441    /// answer to decide whether to mint over a `write` that replaces.
442    ///
443    /// `symlink_metadata` is also the stricter of the two honest options: it
444    /// does not follow links, so a **dangling symlink** at the key path counts
445    /// as present. Something occupies that name; refusing to write over it is
446    /// the fail-closed reading, whereas `try_exists()` would report `false` and
447    /// invite exactly the overwrite this method exists to prevent.
448    fn exists(&self, key: &BackendKey) -> Result<bool> {
449        match fs::symlink_metadata(self.path_for(key)) {
450            Ok(_) => Ok(true),
451            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(false),
452            Err(e) => Err(e.into()),
453        }
454    }
455
456    /// Establish `<root>/<key>.dks` **only if it does not already exist**.
457    ///
458    /// Exclusivity comes from the OS: the file is opened with `create_new`, so
459    /// exactly one racer creates it and every other gets
460    /// [`KeystoreError::AlreadyExists`] — a distinguishable error the loser can
461    /// adopt on, rather than a generic I/O failure it can only give up on.
462    ///
463    /// # Why this does not use tmp + rename
464    ///
465    /// `rename` always replaces, so it cannot express "only if absent"; the two
466    /// guarantees are not simultaneously available without a hard link, which
467    /// not every filesystem supports. Exclusivity is the one that matters here,
468    /// and the cost is bounded: a crash mid-write leaves a **short file**, which
469    /// the format's magic, length and CRC all detect on the next read
470    /// (`SPEC.md` §3.2), and which is repaired by deleting it and retrying. The
471    /// state this method exists to prevent — a coupled pair that settled
472    /// mismatched — is neither detectable nor repairable. A best-effort unlink
473    /// removes the partial file on the way out of any failure.
474    fn write_new(&self, key: &BackendKey, data: &[u8]) -> Result<()> {
475        self.ensure_root()?;
476        let path = self.path_for(key);
477
478        // `create_owner_only` is the same exclusive, born-owner-only open the
479        // tmp-file path uses: `create_new(true)` plus the requested mode, so
480        // the file never exists under a permissive mode and a symlink planted
481        // on the path is refused rather than followed.
482        let f = match create_owner_only(&path) {
483            Ok(f) => f,
484            Err(KeystoreError::Backend(e)) if e.kind() == io::ErrorKind::AlreadyExists => {
485                return Err(KeystoreError::AlreadyExists(key.as_str().to_string()))
486            }
487            Err(e) => return Err(e),
488        };
489
490        // Stage the bytes with the handle owned by a closure, so it is closed
491        // by leaving scope. An explicit `drop(f)` would say the same thing on
492        // every native target and trip `clippy::drop_non_drop` on wasm32, where
493        // `std::fs::File` is a stub that does not implement `Drop` — and the
494        // close is load-bearing, because Windows cannot unlink an open file.
495        // Same shape as `write`, for the same reason.
496        let staged = (|mut f: fs::File| -> Result<()> {
497            // The mode is verified, not merely requested: a `chmod` on a
498            // filesystem without POSIX modes reports success and changes
499            // nothing, so the file is removed below rather than filled with key
500            // material it cannot protect. Same floor and reasoning as `write`.
501            enforce_owner_only(&path, 0o600)?;
502            f.write_all(data)?;
503            f.sync_all()?;
504            Ok(())
505        })(f);
506
507        if let Err(e) = staged {
508            // Only reachable once THIS call created the file — an
509            // `AlreadyExists` returned above, so a losing racer never reaches
510            // here and can never unlink the winner's blob.
511            let _ = fs::remove_file(&path);
512            return Err(e);
513        }
514
515        // fsync the containing directory on Unix so the creation is durable
516        // across a crash, matching `write`. Not a concept on Windows.
517        #[cfg(unix)]
518        {
519            if let Ok(dir) = fs::File::open(&self.root) {
520                let _ = dir.sync_all();
521            }
522        }
523
524        Ok(())
525    }
526
527    /// `create_new(true)` is an atomic create-if-absent at the OS level, so two
528    /// concurrent calls cannot both succeed.
529    fn write_new_exclusivity(&self) -> Exclusivity {
530        Exclusivity::Atomic
531    }
532}
533
534/// Quick, non-cryptographic random suffix for tmp filenames.
535///
536/// We do NOT use this for anything security-sensitive — it only disambiguates
537/// concurrent tmp files. Uses `(nanoseconds_since_epoch * golden_ratio_prime) + pid`
538/// for a spread uniform enough to avoid collisions across processes on the same host.
539///
540/// If two tmp files happen to collide, the loser will fail the final
541/// `fs::rename` with `AlreadyExists` (on Windows) or succeed but overwrite
542/// the other tmp (on Unix); either way the actual final `.dks` file is
543/// unaffected.
544fn fastrand_suffix() -> u64 {
545    use std::time::{SystemTime, UNIX_EPOCH};
546    let ns = SystemTime::now()
547        .duration_since(UNIX_EPOCH)
548        .map(|d| d.as_nanos() as u64)
549        .unwrap_or(0);
550    let pid = std::process::id() as u64;
551    // 0x9E37_79B9_7F4A_7C15 = 2^64 / golden ratio — gives uniform spread.
552    ns.wrapping_mul(0x9E37_79B9_7F4A_7C15).wrapping_add(pid)
553}
554
555#[cfg(test)]
556mod tests {
557    use super::*;
558    use crate::error::KeystoreError;
559    use tempfile::TempDir;
560    /// A key whose name carries an interior NUL byte. Every OS path API
561    /// rejects it with `InvalidInput` — never `NotFound` — so it is a
562    /// deterministic, cross-platform way to make a `stat` **fail to answer**
563    /// rather than answer "absent".
564    ///
565    /// It is the vehicle, not the property. The property is that an
566    /// undeterminable read refuses; the realistic vehicles (an unreadable
567    /// parent directory, a failing mount, an I/O fault) are not portably
568    /// constructible in a unit test, and one of them is covered by
569    /// `exists_refuses_when_the_parent_cannot_be_read` below.
570    fn undeterminable_key() -> BackendKey {
571        let mut name = String::from("un");
572        name.push('\u{0}');
573        name.push_str("determinable");
574        BackendKey::new(name)
575    }
576
577    /// **Proves:** `FileBackend::exists` returns `Err` — not `Ok(false)` —
578    /// when the filesystem could not answer whether the blob is there.
579    ///
580    /// **Why it matters:** `exists` is a two-valued answer to a three-valued
581    /// question, and its one production caller (`Keystore::create_with_rng`,
582    /// `src/custody/keystore.rs`) uses it to decide whether to MINT.
583    /// `FileBackend::write` is replace-semantics tmp+rename, so a spurious
584    /// `false` does not merely mint a duplicate beside the original — it
585    /// **overwrites the original**. Once the blob is hardware-wrapped
586    /// (`SPEC.md` §17) that overwrite is unrecoverable, and
587    /// `HardwareUnwrapFailed` structurally cannot name its own cause
588    /// (§17.5b), so the loss is silent as well as permanent.
589    ///
590    /// **Catches:** exactly the implementation this replaced —
591    /// `Ok(self.path_for(key).exists())`. `Path::exists()` maps *every* error
592    /// to `false`, so it returns `Ok(false)` for this fixture and this
593    /// assertion fails. Also catches any future "cheap override" that maps a
594    /// non-`NotFound` error to absent.
595    #[test]
596    fn exists_refuses_rather_than_reporting_absent_when_it_cannot_tell() {
597        let dir = TempDir::new().unwrap();
598        let be = FileBackend::new(dir.path().to_path_buf());
599
600        // Control: the same backend answers a *determinable* absence honestly,
601        // so the test cannot pass by refusing everything.
602        assert!(
603            !be.exists(&BackendKey::new("genuinely-absent")).unwrap(),
604            "a determinable absence must still be reported as absent"
605        );
606
607        let err = be
608            .exists(&undeterminable_key())
609            .expect_err("an unanswerable stat must not be reported as absent");
610        assert!(
611            matches!(err, KeystoreError::Backend(_)),
612            "the refusal must carry the underlying I/O cause"
613        );
614    }
615
616    /// **Proves:** the refusal reaches the mint decision — a write is not
617    /// attempted, and nothing is half-created, when the read could not answer.
618    ///
619    /// **Why it matters:** this is the *placement* half. The assertion above
620    /// pins the backend's contract; a guard added in `Keystore::create`
621    /// instead would leave every other present and future `exists` caller
622    /// minting on a false absence. Both the seam and its effect are observed,
623    /// so the fix cannot be relocated without a test noticing.
624    ///
625    /// **Catches:** an `exists` override that answers `Ok(false)` here, which
626    /// would let the write proceed.
627    #[test]
628    fn an_unanswerable_read_does_not_reach_a_write() {
629        let dir = TempDir::new().unwrap();
630        let be = FileBackend::new(dir.path().to_path_buf());
631        let key = undeterminable_key();
632
633        assert!(be.exists(&key).is_err());
634        // And the write itself refuses too, rather than half-creating anything.
635        assert!(be.write(&key, b"payload").is_err());
636        assert!(
637            be.list("").unwrap().is_empty(),
638            "a refused write must leave no residue"
639        );
640    }
641
642    /// **Proves:** a parent directory the process cannot read makes `exists`
643    /// refuse, rather than report absent.
644    ///
645    /// **Why it matters:** this is the *realistic* vehicle for the same
646    /// property — a keystore root whose permissions changed under a running
647    /// service. The NUL-key test above proves the branch; this one proves the
648    /// branch is reached by a situation that actually happens.
649    ///
650    /// **Unix only.** Windows has no equivalent portable construction: mode
651    /// bits do not apply, and denying access needs an explicit DACL, which
652    /// needs Win32 FFI this crate cannot contain (`unsafe_code = "forbid"`,
653    /// §13.2 C-15). On Windows this test is not compiled in and the property
654    /// rests on the test above. It is exercised by the Linux and macOS CI legs;
655    /// a Windows developer cannot run it locally.
656    #[cfg(unix)]
657    #[test]
658    fn exists_refuses_when_the_parent_cannot_be_read() {
659        use std::os::unix::fs::PermissionsExt;
660
661        let dir = TempDir::new().unwrap();
662        let root = dir.path().join("locked");
663        fs::create_dir(&root).unwrap();
664        let be = FileBackend::new(root.clone());
665        let key = BackendKey::new("sealed");
666        be.write(&key, b"payload").unwrap();
667
668        fs::set_permissions(&root, fs::Permissions::from_mode(0o000)).unwrap();
669        let answer = be.exists(&key);
670        // Restore before asserting so a failure cannot leave an unremovable dir.
671        fs::set_permissions(&root, fs::Permissions::from_mode(0o700)).unwrap();
672
673        // Root defeats permission bits entirely, so the fixture cannot make the
674        // stat fail there. Rather than skip — which would print `ok` while
675        // asserting nothing, and go unfalsifiable on any root CI runner — each
676        // environment asserts the outcome it can actually exhibit. Neither
677        // branch is vacuous, and neither is `Ok(false)`, which is the answer
678        // this method must never give.
679        if running_as_root() {
680            assert!(
681                answer.unwrap(),
682                "root can read the directory, so the blob must be reported present"
683            );
684        } else {
685            assert!(
686                answer.is_err(),
687                "an unreadable parent must refuse, not report the blob absent"
688            );
689        }
690    }
691
692    /// Whether this process can read a `0o000` directory — i.e. is effectively
693    /// root. Probed by observation rather than `libc::geteuid`, because the
694    /// crate forbids `unsafe` and the observable is the thing we actually care
695    /// about.
696    #[cfg(unix)]
697    fn running_as_root() -> bool {
698        use std::os::unix::fs::PermissionsExt;
699        let probe = TempDir::new().unwrap();
700        let d = probe.path().join("probe");
701        fs::create_dir(&d).unwrap();
702        fs::set_permissions(&d, fs::Permissions::from_mode(0o000)).unwrap();
703        let readable = fs::read_dir(&d).is_ok();
704        fs::set_permissions(&d, fs::Permissions::from_mode(0o700)).unwrap();
705        readable
706    }
707
708    /// **Proves:** `write_new` refuses an existing key with a distinguishable
709    /// `AlreadyExists`, and leaves the stored bytes untouched.
710    ///
711    /// **Why it matters:** a consumer storing two COUPLED records — a wrapped
712    /// blob and the device key that opens it — needs to say "I am
713    /// *establishing* this, not updating it" (dig-keystore#16). With only
714    /// replace-semantics `write`, two concurrent starts settle key `D_B`
715    /// beside blob `B_A`, which never self-heals. `create_new` +
716    /// adopt-on-`AlreadyExists` makes that state unreachable rather than
717    /// unlikely.
718    ///
719    /// **Catches:** a `write_new` implemented as `exists()` then `write()`,
720    /// which would replace the bytes; and one that reports the collision as a
721    /// generic I/O error, which a caller cannot adopt on.
722    #[test]
723    fn write_new_refuses_an_existing_key_without_touching_it() {
724        let dir = TempDir::new().unwrap();
725        let be = FileBackend::new(dir.path().to_path_buf());
726        let key = BackendKey::new("coupled");
727
728        be.write_new(&key, b"established").unwrap();
729        let err = be
730            .write_new(&key, b"usurper")
731            .expect_err("write_new must refuse an established key");
732
733        assert!(
734            matches!(err, KeystoreError::AlreadyExists(ref k) if k == "coupled"),
735            "the collision must be adoptable, not a generic I/O error: {err:?}"
736        );
737        assert_eq!(
738            be.read(&key).unwrap(),
739            b"established",
740            "a refused write_new must not replace the established bytes"
741        );
742    }
743
744    /// **Proves:** `write_new` on an absent key stores bytes `read` recovers,
745    /// and the `write` beside it still replaces.
746    ///
747    /// **Why it matters:** the control for the test above. A `write_new` that
748    /// refused unconditionally would satisfy the refusal assertion perfectly
749    /// while being useless, and no other test would notice.
750    ///
751    /// **Catches:** a `write_new` that never writes, writes to a different
752    /// path than `write`/`read` use, or that accidentally makes `write`
753    /// exclusive too.
754    #[test]
755    fn write_new_establishes_an_absent_key() {
756        let dir = TempDir::new().unwrap();
757        let be = FileBackend::new(dir.path().to_path_buf());
758        let key = BackendKey::new("fresh");
759
760        be.write_new(&key, b"payload").unwrap();
761        assert_eq!(be.read(&key).unwrap(), b"payload");
762        be.write(&key, b"replaced").unwrap();
763        assert_eq!(be.read(&key).unwrap(), b"replaced");
764    }
765
766    /// **Proves:** `FileBackend` claims exclusive `write_new`.
767    ///
768    /// **Why it matters:** [`Exclusivity`] is what a consumer reads to decide
769    /// whether `write_new` can be *relied on* to make a coupled mismatch
770    /// unreachable. A backend that overstates it hands back the exact race the
771    /// method exists to remove.
772    ///
773    /// **Catches:** a `FileBackend` that keeps the `Atomic` claim after being
774    /// reimplemented as a check-then-write.
775    #[test]
776    fn file_backend_claims_exclusive_creation() {
777        let dir = TempDir::new().unwrap();
778        let be = FileBackend::new(dir.path().to_path_buf());
779        assert_eq!(be.write_new_exclusivity(), Exclusivity::Atomic);
780    }
781
782    /// **Proves:** under contention, exactly ONE `write_new` establishes the key
783    /// and every other racer gets `AlreadyExists` — the mechanism behind the
784    /// [`Exclusivity::Atomic`] claim, not merely the claim.
785    ///
786    /// **Why it matters:** `write_new_refuses_an_existing_key_without_touching_it`
787    /// above is satisfied identically by a check-then-write, so on its own it
788    /// pins a coincidence. The whole value of `write_new` to a consumer with
789    /// coupled records is that two concurrent *starts* cannot both establish;
790    /// that is a property of concurrency and nothing sequential can observe it.
791    ///
792    /// **Catches:** a `write_new` reimplemented as `exists()` then `write()`.
793    /// Every thread would pass the vacancy check inside the barrier window and
794    /// several would report success.
795    ///
796    /// **One-directional, deliberately.** A correct implementation can *never*
797    /// produce two winners, so this test cannot fail spuriously. A broken one
798    /// is caught probabilistically — the barrier maximises the overlap, but a
799    /// single unlucky scheduling could still serialise the threads. It is a
800    /// sound proof of the negative and a strong-but-not-certain detector of the
801    /// positive, which is the right way round.
802    #[test]
803    fn only_one_concurrent_write_new_can_win() {
804        use std::sync::{Arc, Barrier};
805
806        const RACERS: usize = 16;
807
808        let dir = TempDir::new().unwrap();
809        // Create the root up front so the race is over the blob, not over
810        // `ensure_root`, which would serialise the threads before they reach
811        // the interesting call.
812        let be = Arc::new(FileBackend::new(dir.path().to_path_buf()));
813        be.write(&BackendKey::new("warmup"), b"x").unwrap();
814
815        let key = BackendKey::new("contended");
816        let gate = Arc::new(Barrier::new(RACERS));
817
818        let winners: usize = std::thread::scope(|scope| {
819            let handles: Vec<_> = (0..RACERS)
820                .map(|i| {
821                    let (be, gate, key) = (Arc::clone(&be), Arc::clone(&gate), key.clone());
822                    scope.spawn(move || {
823                        // Each racer writes a distinguishable payload, so the
824                        // survivor identifies which one won.
825                        let payload = [i as u8; 8];
826                        gate.wait();
827                        be.write_new(&key, &payload).is_ok()
828                    })
829                })
830                .collect();
831            // `join` consumes the handle, so map-then-filter rather than
832            // `filter(|h| h.join()..)`. `unwrap` is deliberate: a panicking
833            // racer must fail this test, not be counted as a loser.
834            handles
835                .into_iter()
836                .map(|h| h.join().unwrap())
837                .filter(|won| *won)
838                .count()
839        });
840
841        assert_eq!(
842            winners, 1,
843            "exactly one racer may establish a key; {winners} did"
844        );
845        // The stored bytes are one racer's payload in full — never a blend of
846        // two, which is what a torn concurrent write would leave.
847        let stored = be.read(&key).unwrap();
848        assert_eq!(stored.len(), 8);
849        assert!(
850            stored.iter().all(|b| *b == stored[0]),
851            "the survivor's payload must be intact, not a mix of two writers"
852        );
853    }
854
855    /// **Proves:** `FileBackend::write` followed by `FileBackend::read`
856    /// recovers the same bytes.
857    ///
858    /// **Why it matters:** The basic "file actually persists" check. This
859    /// exercises the full tmp-file + rename path including directory
860    /// creation, mode setting, `fsync`, and `rename`.
861    ///
862    /// **Catches:** a regression where `write` skips the rename step (file
863    /// left in `<name>.tmp.XXX` form) or `read` opens the wrong path.
864    #[test]
865    fn write_then_read_roundtrip() {
866        let dir = TempDir::new().unwrap();
867        let be = FileBackend::new(dir.path().to_path_buf());
868        let key = BackendKey::new("test");
869        be.write(&key, b"hello").unwrap();
870        let out = be.read(&key).unwrap();
871        assert_eq!(out, b"hello");
872    }
873
874    /// **Proves:** two sequential `write` calls to the same key leave no
875    /// `.tmp.` residue in the directory — meaning the tmp-then-rename
876    /// dance successfully cleaned up intermediate files.
877    ///
878    /// **Why it matters:** If tmp files accumulated, `list` would return
879    /// them to callers, disk space would leak, and operators would have to
880    /// manually clean up. The second `write` also asserts that the newer
881    /// content (`"second"`) overwrote the older (`"first"`) — atomicity's
882    /// visible behaviour.
883    ///
884    /// **Catches:** a regression where the rename fails silently and the
885    /// tmp file is not deleted; a regression where the final file is not
886    /// actually renamed on top of the previous one.
887    #[test]
888    fn write_is_atomic_on_rename_failure() {
889        let dir = TempDir::new().unwrap();
890        let be = FileBackend::new(dir.path().to_path_buf());
891        let key = BackendKey::new("atomic");
892        be.write(&key, b"first").unwrap();
893        be.write(&key, b"second").unwrap();
894        assert_eq!(be.read(&key).unwrap(), b"second");
895        // No .tmp files should linger.
896        let entries: Vec<_> = fs::read_dir(dir.path()).unwrap().collect();
897        for e in entries {
898            let name = e.unwrap().file_name();
899            let s = name.to_string_lossy().into_owned();
900            assert!(!s.contains(".tmp."), "leftover tmp file: {s}");
901        }
902    }
903
904    /// **Proves:** after `delete`, the file is gone and `exists` returns `false`.
905    ///
906    /// **Why it matters:** Confirms the delete path actually unlinks the
907    /// file. This is the final action in `Keystore::delete`; a regression
908    /// here would leave keystore files behind after an operator thought
909    /// they had wiped them.
910    ///
911    /// **Catches:** a regression where `delete` only overwrites (secure
912    /// wipe) without unlinking; where `exists` checks a stale cache; or
913    /// where `delete` silently errors on the unlink step.
914    #[test]
915    fn delete_removes_file() {
916        let dir = TempDir::new().unwrap();
917        let be = FileBackend::new(dir.path().to_path_buf());
918        let key = BackendKey::new("delete_me");
919        be.write(&key, b"bye").unwrap();
920        assert!(be.exists(&key).unwrap());
921        be.delete(&key).unwrap();
922        assert!(!be.exists(&key).unwrap());
923    }
924
925    /// **Proves:** deleting a non-existent key is a no-op success — not an
926    /// error.
927    ///
928    /// **Why it matters:** The [`KeychainBackend`] contract requires
929    /// `delete` to be idempotent. Callers (e.g., `dig-validator keys remove`)
930    /// can call `delete` without first checking existence; a double-call
931    /// after a concurrent delete should not fail.
932    ///
933    /// **Catches:** a regression where `delete` returns `NotFound` for
934    /// missing files.
935    #[test]
936    fn delete_is_idempotent() {
937        let dir = TempDir::new().unwrap();
938        let be = FileBackend::new(dir.path().to_path_buf());
939        be.delete(&BackendKey::new("never_existed")).unwrap();
940    }
941
942    /// **Proves:** `delete` returns `Err` — not `Ok(())` — when the filesystem
943    /// could not answer whether the blob is there.
944    ///
945    /// **Why it matters:** `delete` is this crate's secure-erase path, so its
946    /// `Ok(())` is read as *the key material is gone*. `Path::exists()` maps
947    /// every error to `false`, so an unreadable parent or a failing mount made
948    /// `delete` take the early "already absent" return and report success over a
949    /// blob still sitting on disk. That is a false assurance about residual key
950    /// material — a lie about custody rather than a loss of it, which is why
951    /// this is the lower-severity half of the same defect class as `exists`
952    /// (#18/#19), and still not something this crate is willing to say.
953    ///
954    /// **Catches:** exactly the implementation this replaced —
955    /// `if !path.exists() { return Ok(()); }`. Under it this fixture returns
956    /// `Ok(())` and the assertion fails.
957    ///
958    /// **The control is load-bearing:** a `delete` that simply refused
959    /// everything would satisfy the first assertion, and would break the
960    /// documented idempotence the second one pins.
961    #[test]
962    fn delete_refuses_rather_than_reporting_success_when_it_cannot_tell() {
963        let dir = TempDir::new().unwrap();
964        let be = FileBackend::new(dir.path().to_path_buf());
965
966        // Control: a determinable absence is still an idempotent success.
967        be.delete(&BackendKey::new("genuinely-absent"))
968            .expect("a determinable absence must still delete Ok");
969
970        let err = be
971            .delete(&undeterminable_key())
972            .expect_err("an unanswerable stat must not be reported as a completed delete");
973        assert!(
974            matches!(err, KeystoreError::Backend(_)),
975            "the refusal must carry the underlying I/O cause"
976        );
977    }
978
979    /// **Proves:** `list` distinguishes a root that is genuinely absent (a
980    /// legitimate empty result) from a root it could not inspect (an error).
981    ///
982    /// **Why it matters:** a caller enumerating a user's identities acts on an
983    /// empty vec — it offers to create a first keystore, or reports "you have no
984    /// keys". `Path::exists()` collapsed "there is no root yet" and "I could not
985    /// read the root" into the same answer, so a permissions change under a
986    /// running service presented as a user with nothing in it.
987    ///
988    /// **Catches:** exactly the implementation this replaced —
989    /// `if !self.root.exists() { return Ok(Vec::new()); }`. Under it the
990    /// undeterminable root returns `Ok(vec![])` and the third assertion fails.
991    ///
992    /// **Both controls are load-bearing**, and they are different from each
993    /// other: an absent root must stay `Ok(vec![])` (the legitimate empty this
994    /// fix must not turn into an error), and a present, genuinely empty root
995    /// must also stay `Ok(vec![])` (so the fix cannot pass by refusing every
996    /// root that holds no keys).
997    #[test]
998    fn list_separates_an_absent_root_from_an_uninspectable_one() {
999        let dir = TempDir::new().unwrap();
1000
1001        // Control 1: root does not exist yet. A legitimate empty.
1002        let absent_root = FileBackend::new(dir.path().join("not-created-yet"));
1003        assert!(
1004            absent_root.list("").unwrap().is_empty(),
1005            "a root that is genuinely absent must still list as empty"
1006        );
1007
1008        // Control 2: root exists and holds no keys. Also a legitimate empty.
1009        let empty_root = FileBackend::new(dir.path().to_path_buf());
1010        assert!(
1011            empty_root.list("").unwrap().is_empty(),
1012            "an existing empty root must still list as empty"
1013        );
1014
1015        // The property: a root that cannot be inspected is not an empty root.
1016        let unreadable_root = FileBackend::new(PathBuf::from("un\u{0}determinable"));
1017        let err = unreadable_root
1018            .list("")
1019            .expect_err("an uninspectable root must not be reported as holding no keys");
1020        assert!(
1021            matches!(err, KeystoreError::Backend(_)),
1022            "the refusal must carry the underlying I/O cause"
1023        );
1024    }
1025
1026    /// **Proves:** a root whose parent the process cannot read makes both
1027    /// `delete` and `list` refuse, rather than report a completed delete and an
1028    /// empty keystore.
1029    ///
1030    /// **Why it matters:** this is the *realistic* vehicle for the property the
1031    /// two tests above prove with an interior-NUL path — a keystore directory
1032    /// whose permissions changed under a running service. The parent is locked
1033    /// rather than the root itself, because a `0o000` root still *stats*
1034    /// successfully from its readable parent; it is the stat that must be made
1035    /// to fail, not the directory read.
1036    ///
1037    /// **Unix only**, for the same reason as
1038    /// `exists_refuses_when_the_parent_cannot_be_read`: Windows needs an
1039    /// explicit DACL, which needs Win32 FFI this crate cannot contain
1040    /// (`unsafe_code = "forbid"`, §13.2 C-15).
1041    #[cfg(unix)]
1042    #[test]
1043    fn delete_and_list_refuse_when_the_root_cannot_be_stat_ed() {
1044        use std::os::unix::fs::PermissionsExt;
1045
1046        let dir = TempDir::new().unwrap();
1047        let parent = dir.path().join("locked-parent");
1048        fs::create_dir(&parent).unwrap();
1049        let root = parent.join("keys");
1050        let be = FileBackend::new(root.clone());
1051        let key = BackendKey::new("sealed");
1052        be.write(&key, b"payload").unwrap();
1053
1054        fs::set_permissions(&parent, fs::Permissions::from_mode(0o000)).unwrap();
1055        let listed = be.list("");
1056        let deleted = be.delete(&key);
1057        // Restore before asserting so a failure cannot leave an unremovable dir.
1058        fs::set_permissions(&parent, fs::Permissions::from_mode(0o700)).unwrap();
1059
1060        // Root defeats permission bits entirely, so each environment asserts the
1061        // outcome it can actually exhibit — neither branch is vacuous, and in
1062        // neither is the answer the silent success this test exists to forbid.
1063        if running_as_root() {
1064            assert_eq!(
1065                listed.unwrap().len(),
1066                1,
1067                "root can read the parent, so the blob must be enumerated"
1068            );
1069            deleted.expect("root can read the parent, so the delete must complete");
1070        } else {
1071            assert!(
1072                listed.is_err(),
1073                "an uninspectable root must refuse, not report an empty keystore"
1074            );
1075            assert!(
1076                deleted.is_err(),
1077                "an uninspectable blob must refuse, not report a completed delete"
1078            );
1079        }
1080    }
1081
1082    /// **Proves:** `list("alph")` returns exactly `["alpha", "alpha2"]`
1083    /// when the directory contains `alpha.dks`, `alpha2.dks`, and `beta.dks`.
1084    ///
1085    /// **Why it matters:** Prefix-based listing is what enables CLI tools
1086    /// like `dig-validator keys list` to enumerate all keystores of a given
1087    /// operator. Strict prefix matching (not substring, not suffix) must
1088    /// be pinned.
1089    ///
1090    /// **Catches:** `starts_with` → `contains` regression (which would
1091    /// include `beta` if prefix were `"eta"`); failure to strip the `.dks`
1092    /// extension.
1093    #[test]
1094    fn list_with_prefix() {
1095        let dir = TempDir::new().unwrap();
1096        let be = FileBackend::new(dir.path().to_path_buf());
1097        be.write(&BackendKey::new("alpha"), b"a").unwrap();
1098        be.write(&BackendKey::new("alpha2"), b"a").unwrap();
1099        be.write(&BackendKey::new("beta"), b"b").unwrap();
1100        let mut keys = be.list("alph").unwrap();
1101        keys.sort_by_key(|k| k.0.clone());
1102        assert_eq!(
1103            keys,
1104            vec![BackendKey::new("alpha"), BackendKey::new("alpha2")]
1105        );
1106    }
1107
1108    /// **Proves:** reading a non-existent key returns a `KeystoreError::Backend`
1109    /// wrapping an `io::Error` with `ErrorKind::NotFound`.
1110    ///
1111    /// **Why it matters:** The default [`KeychainBackend::exists`] impl
1112    /// relies on this specific error shape to distinguish "not present"
1113    /// from "I/O failed." If `read` returned a generic `InvalidInput` or
1114    /// similar, `exists` would misclassify missing keys.
1115    ///
1116    /// **Catches:** a regression where `read` eats the OS error and
1117    /// returns a custom `KeystoreError` variant, breaking the default
1118    /// `exists` implementation.
1119    #[test]
1120    fn read_nonexistent_returns_error() {
1121        let dir = TempDir::new().unwrap();
1122        let be = FileBackend::new(dir.path().to_path_buf());
1123        let err = be.read(&BackendKey::new("missing")).unwrap_err();
1124        let is_not_found = match &err {
1125            KeystoreError::Backend(io) => io.kind() == std::io::ErrorKind::NotFound,
1126            _ => false,
1127        };
1128        assert!(is_not_found);
1129    }
1130
1131    /// **Proves:** `FileBackend::write` lazily creates the root directory
1132    /// (and intermediate parents) when the first write arrives.
1133    ///
1134    /// **Why it matters:** Operators may point the validator at
1135    /// `~/.dig/keys/` before that directory exists. Requiring them to
1136    /// `mkdir -p` first is poor UX. This test pins the "lazy mkdir" on
1137    /// first write behaviour so `FileBackend::new` can remain side-effect-free.
1138    ///
1139    /// **Catches:** a regression where `write` assumes the dir exists and
1140    /// fails with `NotFound` on first call; or where `new` eagerly creates
1141    /// the dir (unwanted in tests).
1142    #[test]
1143    fn creates_root_dir() {
1144        let dir = TempDir::new().unwrap();
1145        let sub = dir.path().join("nested/keys");
1146        let be = FileBackend::new(sub.clone());
1147        assert!(!sub.exists());
1148        be.write(&BackendKey::new("k"), b"x").unwrap();
1149        assert!(sub.exists());
1150    }
1151
1152    /// `is_owner_only` accepts exactly those modes that grant nobody but the
1153    /// owner any access.
1154    ///
1155    /// **Why it matters:** this predicate is the whole of the permission
1156    /// guarantee. Everything else in `enforce_owner_only` is plumbing around
1157    /// its answer, so a predicate that is merely *nearly* right silently
1158    /// downgrades the at-rest floor for dig-app's account seed and dig-node's
1159    /// seed store, which are this backend's production callers.
1160    ///
1161    /// **Catches:** each of the plausible near-miss implementations. `0o400`
1162    /// and `0o000` rule out an equality test against `0o600`; `0o640` rules
1163    /// out a predicate that only inspects the *other* triad (and any
1164    /// `mode & 0o077 != 0o077` inversion, which would read group-readable as
1165    /// safe); `0o604` rules out one that only inspects the *group* triad.
1166    #[test]
1167    fn owner_only_predicate_rejects_every_non_owner_bit() {
1168        // No access for group or other, at varying owner permissions.
1169        for mode in [0o000, 0o400, 0o600, 0o700] {
1170            assert!(
1171                is_owner_only(mode),
1172                "{mode:04o} grants nobody but the owner"
1173            );
1174        }
1175
1176        // A single group or other bit is enough to fail, in either triad.
1177        for mode in [0o640, 0o604, 0o644, 0o060, 0o006, 0o660, 0o777] {
1178            assert!(!is_owner_only(mode), "{mode:04o} reaches beyond the owner");
1179        }
1180    }
1181
1182    /// A written blob, and the root that holds it, really are owner-only on
1183    /// disk — not merely requested to be.
1184    ///
1185    /// **Why it matters:** `SPEC.md` §10.3 / conformance C-14 state mode
1186    /// `0700` for the root and `0600` for blobs as a normative property. It
1187    /// was previously requested with the result discarded, so nothing
1188    /// observed whether it held.
1189    ///
1190    /// **Catches:** a regression that drops the `enforce_owner_only` call
1191    /// from either `ensure_root` or `write`, or that reorders the blob's
1192    /// restriction after `write_all` so ciphertext lands at the umask default
1193    /// first.
1194    ///
1195    /// Unix-only because Windows has no POSIX mode. That makes it
1196    /// unfalsifiable on a Windows build host, which is why the predicate above
1197    /// is tested separately and unconditionally.
1198    #[cfg(unix)]
1199    #[test]
1200    fn written_blob_and_root_are_owner_only_on_disk() {
1201        use std::os::unix::fs::PermissionsExt;
1202
1203        let dir = TempDir::new().unwrap();
1204        let root = dir.path().join("keys");
1205        let be = FileBackend::new(root.clone());
1206        be.write(&BackendKey::new("seed"), b"sealed").unwrap();
1207
1208        let root_mode = fs::metadata(&root).unwrap().permissions().mode() & 0o777;
1209        assert_eq!(root_mode, 0o700, "root dir mode");
1210
1211        let blob_mode = fs::metadata(root.join("seed.dks"))
1212            .unwrap()
1213            .permissions()
1214            .mode()
1215            & 0o777;
1216        assert_eq!(blob_mode, 0o600, "blob mode");
1217    }
1218
1219    /// An **already-existing** permissive root is brought back to `0700` on the
1220    /// next write, not left alone.
1221    ///
1222    /// **Why it matters:** the floor is worthless if it only applies to roots
1223    /// this version created. A root created by 0.8.x — which requested `0700`
1224    /// and discarded the result — is precisely the one at risk, and it exists
1225    /// before any 0.9.0 write reaches it. The exposure is the root's *write*
1226    /// bits: blobs carry their own verified `0600`, but a group- or
1227    /// world-writable root grants `unlink` and `create`, which is blob
1228    /// substitution (rolling a victim back to an older sealed seed) and
1229    /// deletion, on the directory holding an account master seed.
1230    ///
1231    /// **Catches:** the `if self.root.exists() { return Ok(()); }` early
1232    /// return. Under it this test sees `0o755` and fails, because
1233    /// `enforce_owner_only` never runs on the existing-root path.
1234    /// `written_blob_and_root_are_owner_only_on_disk` above cannot catch it:
1235    /// its root is a fresh non-existent path, so it only ever exercises the
1236    /// creation branch.
1237    ///
1238    /// **Why this asserts tightening rather than `InsecurePermissions`:** on a
1239    /// root the process owns, `chmod` succeeds, so the permissive mode is
1240    /// repaired and there is nothing to refuse. Erroring instead would fail a
1241    /// host the crate can simply fix. `InsecurePermissions` stays reserved for
1242    /// the unrepairable case — a filesystem where the `chmod` does nothing, a
1243    /// foreign-owned root where it returns `EPERM`, an immutable attribute.
1244    /// The *production call sites* therefore cannot reach the refusal on a
1245    /// mode-honouring filesystem the process owns; the refusal itself is not
1246    /// unreachable, and
1247    /// `enforce_owner_only_refuses_a_mode_it_could_not_bring_to_the_floor`
1248    /// drives it directly.
1249    #[cfg(unix)]
1250    #[test]
1251    fn existing_permissive_root_is_tightened_on_write() {
1252        use std::os::unix::fs::PermissionsExt;
1253
1254        let dir = TempDir::new().unwrap();
1255        let root = dir.path().join("keys");
1256        fs::create_dir_all(&root).unwrap();
1257        fs::set_permissions(&root, fs::Permissions::from_mode(0o755)).unwrap();
1258        assert_eq!(
1259            fs::metadata(&root).unwrap().permissions().mode() & 0o777,
1260            0o755,
1261            "fixture must start group/other-accessible, or it proves nothing"
1262        );
1263
1264        let be = FileBackend::new(root.clone());
1265        be.write(&BackendKey::new("seed"), b"sealed").unwrap();
1266
1267        assert_eq!(
1268            fs::metadata(&root).unwrap().permissions().mode() & 0o777,
1269            0o700,
1270            "an existing root must be brought to the floor, not skipped"
1271        );
1272    }
1273
1274    /// The verify half of chmod-then-verify actually refuses.
1275    ///
1276    /// **Property:** when the mode observed after the request is *not*
1277    /// owner-only, `enforce_owner_only` returns `InsecurePermissions` carrying
1278    /// the bits it saw — it does not return `Ok` on the strength of the
1279    /// `chmod` having succeeded.
1280    ///
1281    /// **Why this is the load-bearing assertion of the whole change:** the
1282    /// thesis of 0.9.0 is "verify the outcome, do not trust the request". The
1283    /// request's own `Result` is discarded on purpose in `enforce_owner_only`;
1284    /// the refusal below is the entire reason that is safe. Without this test
1285    /// the fail-closed block can be deleted with a green suite, returning the
1286    /// crate to the 0.8.x shape — `set_permissions` called and its result
1287    /// thrown away with nothing observing the bits.
1288    ///
1289    /// **Fixture design.** The refusal cannot be provoked through `write`,
1290    /// whose call sites always request an owner-only mode on a path the
1291    /// process owns, so a `write`-level fixture would need a mode-ignoring
1292    /// mount or a second uid — neither available in a test, which is what
1293    /// previously left this branch untested. The requested mode is a
1294    /// *parameter*, so asking for a permissive one drives the same verified
1295    /// read the production path performs, hermetically: no root, no second
1296    /// uid, no exotic mount. `0o755` is used rather than `0o777` because it
1297    /// leaves the owner triad at its production value, so the assertion is
1298    /// about the group and other bits and nothing else.
1299    ///
1300    /// **Catches:** deletion of the fail-closed block in `enforce_owner_only`,
1301    /// and any narrowing of `is_owner_only` reached through it. Asserting the
1302    /// observed `mode` — not merely that the call erred — also rules out a
1303    /// refusal that reports the mode it *asked* for instead of the one on
1304    /// disk, which would make the diagnostic useless on exactly the mount
1305    /// classes it exists to diagnose.
1306    #[cfg(unix)]
1307    #[test]
1308    fn enforce_owner_only_refuses_a_mode_it_could_not_bring_to_the_floor() {
1309        use std::os::unix::fs::PermissionsExt;
1310
1311        let dir = TempDir::new().unwrap();
1312        let root = dir.path().join("permissive");
1313        fs::create_dir_all(&root).unwrap();
1314
1315        let err = enforce_owner_only(&root, 0o755)
1316            .expect_err("a mode granting group and other access must be refused, not accepted");
1317
1318        match err {
1319            KeystoreError::InsecurePermissions { path, mode } => {
1320                assert_eq!(mode, 0o755, "the reported mode must be the one on disk");
1321                assert_eq!(path, root.display().to_string(), "reported path");
1322            }
1323            other => panic!("expected InsecurePermissions, got {other:?}"),
1324        }
1325
1326        // The refusal describes the state it found, so the mode really is the
1327        // permissive one — the fixture is not silently owner-only already.
1328        assert_eq!(
1329            fs::metadata(&root).unwrap().permissions().mode() & 0o777,
1330            0o755,
1331            "fixture must remain group/other-accessible, or it proves nothing"
1332        );
1333    }
1334
1335    /// A symlinked root is refused, not followed.
1336    ///
1337    /// **Property:** `write` on a root that is a symbolic link returns
1338    /// `UnsafeRoot` and touches neither the target's mode nor its contents.
1339    ///
1340    /// **Why refuse here when a permissive mode is repaired:** a mode is a
1341    /// property of the intended directory that the backend can correct and
1342    /// then verify. A symlink is a claim about *which* directory the keystore
1343    /// is, and no syscall makes an attacker-chosen directory into the intended
1344    /// one. Both `set_permissions` and `metadata` follow links, so the
1345    /// alternative is chmodding a directory of someone else's choosing to
1346    /// `0700` and sealing an account master seed inside it.
1347    ///
1348    /// **Catches:** reverting `symlink_metadata` to `exists()`/`metadata()`.
1349    ///
1350    /// **The side effects are asserted before the error, deliberately.** Under
1351    /// that revert the write returns `Ok`, so an `expect_err` placed first
1352    /// panics and the two assertions that name the actual damage never run —
1353    /// the proof would fire on "no error" rather than on the primitive. Ordered
1354    /// this way, the failure a reverting change sees is the chmod reaching
1355    /// through the link, which is what is new in this diff. The error
1356    /// assertion still has to be there: a write that failed for some later,
1357    /// unrelated reason would leave the victim equally untouched.
1358    #[cfg(unix)]
1359    #[test]
1360    fn symlinked_root_is_refused_and_its_target_is_untouched() {
1361        use std::os::unix::fs::PermissionsExt;
1362
1363        let dir = TempDir::new().unwrap();
1364        let victim = dir.path().join("victim");
1365        fs::create_dir_all(&victim).unwrap();
1366        fs::set_permissions(&victim, fs::Permissions::from_mode(0o755)).unwrap();
1367
1368        let root = dir.path().join("keys");
1369        std::os::unix::fs::symlink(&victim, &root).unwrap();
1370
1371        let result = FileBackend::new(root.clone()).write(&BackendKey::new("seed"), b"sealed");
1372
1373        assert_eq!(
1374            fs::metadata(&victim).unwrap().permissions().mode() & 0o777,
1375            0o755,
1376            "the link's target must not be chmodded through the link"
1377        );
1378        assert!(
1379            !victim.join("seed.dks").exists(),
1380            "the sealed blob must not land in the link's target"
1381        );
1382        assert!(
1383            matches!(result, Err(KeystoreError::UnsafeRoot { .. })),
1384            "a symlinked root must be refused, got {result:?}"
1385        );
1386    }
1387}