fastmcp-client 0.11.0

MCP client implementation for FastMCP
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
//! Linux descriptor-relative atomic storage for protected credential blobs.
//!
//! The caller supplies an already-open, owner-private directory. No ambient
//! home directory, pathname traversal, runtime, key, or plaintext fallback is
//! introduced. All namespace operations are relative to that retained handle.
//! The fixed lock file is never removed: replacing a lock inode would let two
//! independent writers both believe they own the same slot.
//!
//! This is the filesystem portion of FND-07/AUTH-05, **not encryption**. Callers
//! must protect secrets with their admitted credential-envelope provider before
//! passing bytes here. The SHA-256 revision is a compare-and-swap identity, not
//! authentication or an anti-rollback anchor. No OAuth token is automatically
//! serialized or persisted by this module.
//!
//! These are synchronous, bounded-size filesystem operations. The caller must
//! run them in its owned blocking-I/O lane. Checkpoints prevent starting another
//! operation after cancellation, but cannot preempt a syscall already executing.
//! After rename, directory synchronization is completed even if cancellation
//! arrives: reporting a retryable cancellation then would conceal a commit.
//! Local filesystem rename/fsync/locking semantics are required; distributed
//! filesystems, hostile same-UID processes, inherited handles after fork, and
//! macOS ACLs and Windows DACL/reparse behavior are outside this implementation's
//! boundary. The API is absent on those platforms rather than inferring private
//! access from Unix mode bits where extended ACLs can independently grant it.

use std::fmt;
use std::fs::{File, Metadata, Permissions};
use std::io::{Read, Write};
use std::os::unix::fs::{MetadataExt, PermissionsExt};

use asupersync::Cx;
use fastmcp_core::crypto::{draw_security_identifier, sha256_bounded};
use rustix::fs::{
    AtFlags, FlockOperation, Mode, OFlags, flock, openat, renameat, statat, unlinkat,
};
use rustix::io::Errno;

/// Generation-preserving custody and recovery of caller-protected blobs.
pub mod slot;

/// Hard allocation and on-disk payload ceiling. A store can choose a lower one.
pub const MAX_ATOMIC_FILE_BYTES: usize = 1024 * 1024;
const MAX_LEAF_BYTES: usize = 96;

/// Opaque identity of the complete bytes observed in one slot.
///
/// Equality detects a stale snapshot, not malicious replacement or ABA. A
/// higher-level credential record must bind its own authenticated generation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct AtomicFileVersion([u8; 32]);

/// A bounded read of one complete file. Diagnostic output never includes bytes.
pub struct AtomicFileSnapshot {
    version: AtomicFileVersion,
    bytes: Vec<u8>,
}

impl AtomicFileSnapshot {
    pub fn version(&self) -> AtomicFileVersion {
        self.version
    }

    pub fn bytes(&self) -> &[u8] {
        &self.bytes
    }

    pub fn into_bytes(self) -> Vec<u8> {
        self.bytes
    }
}

impl fmt::Debug for AtomicFileSnapshot {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AtomicFileSnapshot")
            .field("version", &self.version)
            .field("byte_len", &self.bytes.len())
            .finish()
    }
}

/// Sanitized storage refusals. No path, blob, credential, or OS error text is
/// retained. `CommitUncertain` is deliberately different from a precommit error.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum AtomicFileError {
    InvalidName,
    InvalidLimit,
    UnsafeDirectory,
    UnsafeFile,
    LockReplaced,
    Busy,
    TooLarge,
    Conflict,
    RandomUnavailable,
    EntropyUnavailable,
    Cancelled,
    TimedOut,
    Io,
    RecoveryRequired,
    /// Rename happened, but directory durability could not be established.
    /// Do not repeat the operation blindly. Use `reconcile` under the same lock.
    CommitUncertain {
        attempted: AtomicFileVersion,
    },
}

impl fmt::Display for AtomicFileError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::InvalidName => "atomic file requires one bounded ASCII leaf name",
            Self::InvalidLimit => "atomic file byte limit is invalid",
            Self::UnsafeDirectory => "atomic file directory is not owner-private",
            Self::UnsafeFile => "atomic file is not an owner-private single-link regular file",
            Self::LockReplaced => "atomic file lock identity changed",
            Self::Busy => "atomic file is owned by another writer",
            Self::TooLarge => "atomic file exceeds its configured byte limit",
            Self::Conflict => "atomic file changed since the supplied snapshot",
            Self::RandomUnavailable => "atomic file temporary-name randomness unavailable",
            Self::EntropyUnavailable => "atomic file caller lacks entropy authority",
            Self::Cancelled => "atomic file operation cancelled before commit",
            Self::TimedOut => "atomic file operation deadline exceeded before commit",
            Self::Io => "atomic file filesystem operation failed",
            Self::RecoveryRequired => "atomic file requires explicit commit reconciliation",
            Self::CommitUncertain { .. } => {
                "atomic file rename completed but durability is uncertain"
            }
        })
    }
}

impl std::error::Error for AtomicFileError {}

/// Exclusive, owner-private storage of a single bounded opaque blob.
///
/// The directory and advisory writer lock are retained for this handle's
/// lifetime. Another independently opened handle receives `Busy`, without
/// blocking an executor thread. Dropping the handle releases the lock but never
/// unlinks its inode. Access is confined to `leaf` and this slot's private
/// lock/temporary names; callers cannot supply absolute or relative paths.
pub struct SecureAtomicFile {
    directory: File,
    lock: File,
    leaf: String,
    lock_leaf: String,
    maximum_bytes: usize,
    recovery_required: bool,
    /// The directory durability step, `File::sync_all` in every handle `open`
    /// returns. It is a field so crate tests can make it fail after `open`:
    /// `CommitUncertain` needs a directory that synced at open and fails later
    /// (ENOSPC, EIO, a filesystem going read-only), which no unprivileged
    /// fixture can produce.
    directory_sync: fn(&File) -> std::io::Result<()>,
}

impl SecureAtomicFile {
    /// Opens a slot relative to a caller-owned directory handle. The directory
    /// must belong to the effective user and have exactly mode 0700. Existing
    /// files must have mode 0600, one link, and that same owner. Symlinks and
    /// special files are refused; a FIFO cannot block the type check.
    pub fn open(
        cx: &Cx,
        directory: File,
        leaf: &str,
        maximum_bytes: usize,
    ) -> Result<Self, AtomicFileError> {
        checkpoint(cx)?;
        validate_name(leaf)?;
        if maximum_bytes == 0 || maximum_bytes > MAX_ATOMIC_FILE_BYTES {
            return Err(AtomicFileError::InvalidLimit);
        }
        validate_directory(&directory)?;
        let lock_leaf = format!(".{leaf}.lock");
        let (lock, created) = match openat(
            &directory,
            lock_leaf.as_str(),
            private_open_flags() | OFlags::RDWR | OFlags::CREATE | OFlags::EXCL,
            Mode::RUSR | Mode::WUSR,
        ) {
            Ok(fd) => (File::from(fd), true),
            Err(Errno::EXIST) => (
                File::from(
                    openat(
                        &directory,
                        lock_leaf.as_str(),
                        private_open_flags() | OFlags::RDWR,
                        Mode::empty(),
                    )
                    .map_err(|_| AtomicFileError::UnsafeFile)?,
                ),
                false,
            ),
            Err(_) => return Err(AtomicFileError::Io),
        };
        if created {
            // Defeat an unusually restrictive umask only on our new inode.
            // Existing permissions are inspected, never silently repaired.
            lock.set_permissions(Permissions::from_mode(0o600))
                .map_err(|_| AtomicFileError::Io)?;
        }
        validate_regular(&lock.metadata().map_err(|_| AtomicFileError::Io)?)?;
        checkpoint(cx)?;
        match flock(&lock, FlockOperation::NonBlockingLockExclusive) {
            Ok(()) => {}
            Err(Errno::WOULDBLOCK) => return Err(AtomicFileError::Busy),
            Err(_) => return Err(AtomicFileError::Io),
        }
        let store = Self {
            directory,
            lock,
            leaf: leaf.to_owned(),
            lock_leaf,
            maximum_bytes,
            recovery_required: false,
            directory_sync: File::sync_all,
        };
        store.validate_authority()?;
        // Persist creation of the stable lock inode before a payload can commit.
        // A pre-existing lock may have been left by an interrupted first opener.
        checkpoint(cx)?;
        store.lock.sync_all().map_err(|_| AtomicFileError::Io)?;
        checkpoint(cx)?;
        store.sync_directory().map_err(|_| AtomicFileError::Io)?;
        store.read_current(cx)?;
        Ok(store)
    }

    pub fn maximum_bytes(&self) -> usize {
        self.maximum_bytes
    }

    /// Reads the entire bounded file through a no-follow descriptor. Absence is
    /// distinct from an empty file, an unsafe file, or an I/O error.
    pub fn load(&self, cx: &Cx) -> Result<Option<AtomicFileSnapshot>, AtomicFileError> {
        self.admit(cx)?;
        self.read_current(cx)
    }

    /// Atomically replaces exactly the supplied version. `None` requires an
    /// absent target. Every ordinary error occurs before rename and leaves the
    /// previous target unchanged. A successfully synchronized rename is returned
    /// as success even if the caller cancels during final synchronization.
    pub fn replace(
        &mut self,
        cx: &Cx,
        expected: Option<AtomicFileVersion>,
        bytes: &[u8],
    ) -> Result<AtomicFileVersion, AtomicFileError> {
        self.admit(cx)?;
        if bytes.len() > self.maximum_bytes {
            return Err(AtomicFileError::TooLarge);
        }
        self.check_expected(cx, expected)?;
        let version = version(bytes)?;
        if !cx.capabilities().entropy {
            return Err(AtomicFileError::EntropyUnavailable);
        }
        let mut temporary = self.create_temporary(cx)?;
        write_bounded(cx, &mut temporary.file, bytes)?;
        checkpoint(cx)?;
        temporary.file.sync_all().map_err(|_| AtomicFileError::Io)?;
        // Recheck both namespace authority and target identity at the commit
        // boundary. A caller must not silently adopt a replaced lock or target.
        self.validate_authority()?;
        self.check_expected(cx, expected)?;
        checkpoint(cx)?;
        renameat(
            &self.directory,
            temporary.leaf.as_str(),
            &self.directory,
            self.leaf.as_str(),
        )
        .map_err(|_| AtomicFileError::Io)?;
        temporary.renamed = true;
        drop(temporary);
        // No cancellation checkpoint is legal between rename and this durability
        // result: the visible mutation has already happened.
        if self.sync_directory().is_err() {
            self.recovery_required = true;
            return Err(AtomicFileError::CommitUncertain { attempted: version });
        }
        Ok(version)
    }

    fn sync_directory(&self) -> std::io::Result<()> {
        (self.directory_sync)(&self.directory)
    }

    /// Resolves an uncertain commit by rereading the actual target and syncing
    /// its directory while retaining the writer lock. It does not guess whether
    /// the attempted or previous value won. The caller must compare the returned
    /// version to its retained intent before deciding what to do next.
    pub fn reconcile(&mut self, cx: &Cx) -> Result<Option<AtomicFileSnapshot>, AtomicFileError> {
        checkpoint(cx)?;
        self.validate_authority()?;
        let current = self.read_current(cx)?;
        checkpoint(cx)?;
        self.sync_directory()
            .map_err(|_| AtomicFileError::RecoveryRequired)?;
        self.recovery_required = false;
        Ok(current)
    }

    fn admit(&self, cx: &Cx) -> Result<(), AtomicFileError> {
        checkpoint(cx)?;
        if self.recovery_required {
            return Err(AtomicFileError::RecoveryRequired);
        }
        self.validate_authority()
    }

    fn validate_authority(&self) -> Result<(), AtomicFileError> {
        validate_directory(&self.directory)?;
        let held = self.lock.metadata().map_err(|_| AtomicFileError::Io)?;
        validate_regular(&held)?;
        let named = statat(
            &self.directory,
            self.lock_leaf.as_str(),
            AtFlags::SYMLINK_NOFOLLOW,
        )
        .map_err(|_| AtomicFileError::LockReplaced)?;
        if named.st_dev != held.dev() || named.st_ino != held.ino() {
            return Err(AtomicFileError::LockReplaced);
        }
        Ok(())
    }

    fn check_expected(
        &self,
        cx: &Cx,
        expected: Option<AtomicFileVersion>,
    ) -> Result<(), AtomicFileError> {
        let observed = self.read_current(cx)?.map(|snapshot| snapshot.version);
        if observed != expected {
            return Err(AtomicFileError::Conflict);
        }
        Ok(())
    }

    fn read_current(&self, cx: &Cx) -> Result<Option<AtomicFileSnapshot>, AtomicFileError> {
        checkpoint(cx)?;
        let mut file = match openat(
            &self.directory,
            self.leaf.as_str(),
            private_open_flags() | OFlags::RDONLY,
            Mode::empty(),
        ) {
            Ok(fd) => File::from(fd),
            Err(Errno::NOENT) => return Ok(None),
            Err(Errno::LOOP) => return Err(AtomicFileError::UnsafeFile),
            Err(_) => return Err(AtomicFileError::Io),
        };
        let metadata = file.metadata().map_err(|_| AtomicFileError::Io)?;
        validate_regular(&metadata)?;
        if metadata.len() > self.maximum_bytes as u64 {
            return Err(AtomicFileError::TooLarge);
        }
        let mut bytes = Vec::with_capacity(metadata.len() as usize);
        let mut buffer = [0_u8; 8192];
        loop {
            checkpoint(cx)?;
            // One extra byte detects growth without allowing an unbounded read.
            let remaining = self.maximum_bytes - bytes.len();
            let read_limit = buffer.len().min(remaining.saturating_add(1));
            let count = match file.read(&mut buffer[..read_limit]) {
                Ok(0) => break,
                Ok(count) => count,
                Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
                Err(_) => return Err(AtomicFileError::Io),
            };
            if count > remaining {
                return Err(AtomicFileError::TooLarge);
            }
            bytes.extend_from_slice(&buffer[..count]);
        }
        checkpoint(cx)?;
        let after = file.metadata().map_err(|_| AtomicFileError::Io)?;
        validate_regular(&after)?;
        if after.len() != bytes.len() as u64 || metadata.len() != after.len() {
            return Err(AtomicFileError::Conflict);
        }
        Ok(Some(AtomicFileSnapshot {
            version: version(&bytes)?,
            bytes,
        }))
    }

    fn create_temporary<'a>(&'a self, cx: &Cx) -> Result<Temporary<'a>, AtomicFileError> {
        for _ in 0..4 {
            checkpoint(cx)?;
            let random =
                draw_security_identifier().map_err(|_| AtomicFileError::RandomUnavailable)?;
            let mut leaf = format!(".{}.tmp-", self.leaf);
            for byte in random.as_bytes() {
                use std::fmt::Write as _;
                write!(&mut leaf, "{byte:02x}").map_err(|_| AtomicFileError::Io)?;
            }
            match openat(
                &self.directory,
                leaf.as_str(),
                private_open_flags() | OFlags::WRONLY | OFlags::CREATE | OFlags::EXCL,
                Mode::RUSR | Mode::WUSR,
            ) {
                Ok(fd) => {
                    let temporary = Temporary {
                        directory: &self.directory,
                        file: File::from(fd),
                        leaf,
                        renamed: false,
                    };
                    temporary
                        .file
                        .set_permissions(Permissions::from_mode(0o600))
                        .map_err(|_| AtomicFileError::Io)?;
                    validate_regular(&temporary.file.metadata().map_err(|_| AtomicFileError::Io)?)?;
                    return Ok(temporary);
                }
                Err(Errno::EXIST) => continue,
                Err(_) => return Err(AtomicFileError::Io),
            }
        }
        Err(AtomicFileError::RandomUnavailable)
    }
}

struct Temporary<'a> {
    directory: &'a File,
    file: File,
    leaf: String,
    renamed: bool,
}

impl Drop for SecureAtomicFile {
    /// Releases the writer lock explicitly, not by closing the descriptor. A
    /// `flock` belongs to the open file description, and a child that another
    /// thread is spawning holds a duplicate of every descriptor until its exec
    /// closes it: close-on-exec acts at exec, not at fork. Relying on close
    /// would leave the slot locked, and a prompt reopen `Busy`, for as long as
    /// such a child sits between fork and exec. An unlock through any
    /// duplicate releases the description's lock.
    fn drop(&mut self) {
        let _ = flock(&self.lock, FlockOperation::Unlock);
    }
}

impl Drop for Temporary<'_> {
    fn drop(&mut self) {
        if !self.renamed {
            // Only our exact temporary inode may be removed. Never clean up by
            // prefix, and never delete a recovered or another writer's file.
            if let (Ok(held), Ok(named)) = (
                self.file.metadata(),
                statat(
                    self.directory,
                    self.leaf.as_str(),
                    AtFlags::SYMLINK_NOFOLLOW,
                ),
            ) {
                if named.st_dev == held.dev() && named.st_ino == held.ino() {
                    let _ = unlinkat(self.directory, self.leaf.as_str(), AtFlags::empty());
                }
            }
        }
    }
}

fn private_open_flags() -> OFlags {
    OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::NONBLOCK
}

fn validate_name(name: &str) -> Result<(), AtomicFileError> {
    if name.is_empty()
        || name.len() > MAX_LEAF_BYTES
        || !name
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
    {
        return Err(AtomicFileError::InvalidName);
    }
    Ok(())
}

fn validate_directory(directory: &File) -> Result<(), AtomicFileError> {
    let metadata = directory.metadata().map_err(|_| AtomicFileError::Io)?;
    if !metadata.is_dir()
        || metadata.uid() != rustix::process::geteuid().as_raw()
        || metadata.mode() & 0o7777 != 0o700
    {
        return Err(AtomicFileError::UnsafeDirectory);
    }
    Ok(())
}

fn validate_regular(metadata: &Metadata) -> Result<(), AtomicFileError> {
    if !metadata.is_file()
        || metadata.uid() != rustix::process::geteuid().as_raw()
        || metadata.mode() & 0o7777 != 0o600
        || metadata.nlink() != 1
    {
        return Err(AtomicFileError::UnsafeFile);
    }
    Ok(())
}

fn version(bytes: &[u8]) -> Result<AtomicFileVersion, AtomicFileError> {
    sha256_bounded(bytes, MAX_ATOMIC_FILE_BYTES)
        .map(|digest| AtomicFileVersion(digest.into_bytes()))
        .map_err(|_| AtomicFileError::TooLarge)
}

fn write_bounded(cx: &Cx, file: &mut File, mut bytes: &[u8]) -> Result<(), AtomicFileError> {
    while !bytes.is_empty() {
        checkpoint(cx)?;
        match file.write(bytes) {
            Ok(0) => return Err(AtomicFileError::Io),
            Ok(count) => bytes = &bytes[count..],
            Err(error) if error.kind() == std::io::ErrorKind::Interrupted => {}
            Err(_) => return Err(AtomicFileError::Io),
        }
    }
    Ok(())
}

fn checkpoint(cx: &Cx) -> Result<(), AtomicFileError> {
    cx.checkpoint().map_err(|error| {
        use asupersync::{CancelKind, error::ErrorKind};
        match cx.cancel_reason().map(|reason| reason.kind) {
            Some(CancelKind::Deadline | CancelKind::Timeout) => AtomicFileError::TimedOut,
            Some(_) => AtomicFileError::Cancelled,
            None => match error.kind() {
                ErrorKind::DeadlineExceeded | ErrorKind::CancelTimeout => AtomicFileError::TimedOut,
                _ => AtomicFileError::Cancelled,
            },
        }
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::os::unix::fs::DirBuilderExt;
    use std::sync::atomic::{AtomicU64, Ordering};

    static NEXT_DIRECTORY: AtomicU64 = AtomicU64::new(0);

    /// An owner-private 0700 directory, removed on drop. Only the directory this
    /// fixture created is removed.
    pub(super) struct PrivateDirectory(std::path::PathBuf);

    impl PrivateDirectory {
        pub(super) fn new() -> Self {
            let id = NEXT_DIRECTORY.fetch_add(1, Ordering::Relaxed);
            let path = std::env::temp_dir().join(format!(
                "fastmcp-commit-uncertain-{}-{id}",
                std::process::id()
            ));
            std::fs::DirBuilder::new()
                .mode(0o700)
                .create(&path)
                .unwrap();
            Self(path)
        }

        pub(super) fn open(&self, cx: &Cx) -> SecureAtomicFile {
            SecureAtomicFile::open(cx, File::open(&self.0).unwrap(), "credential", 4096).unwrap()
        }
    }

    impl Drop for PrivateDirectory {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    /// `inherited` stands in for the copy a concurrently spawned child holds
    /// between fork and exec: a duplicate of the same open file description.
    #[test]
    fn a_dropped_handle_releases_its_lock_despite_an_inherited_duplicate() {
        let cx = Cx::for_testing();
        let directory = PrivateDirectory::new();
        let store = directory.open(&cx);
        let inherited = store.lock.try_clone().unwrap();
        drop(store);
        let reopened =
            SecureAtomicFile::open(&cx, File::open(&directory.0).unwrap(), "credential", 4096);
        assert!(
            reopened.is_ok(),
            "a dropped handle's slot must reopen while a duplicate lives"
        );
        drop(inherited);
    }

    /// The same duplicate beside a live handle: the lock is still enforced.
    #[test]
    fn a_live_handle_still_refuses_a_second_opener_beside_an_inherited_duplicate() {
        let cx = Cx::for_testing();
        let directory = PrivateDirectory::new();
        let store = directory.open(&cx);
        let inherited = store.lock.try_clone().unwrap();
        let second =
            SecureAtomicFile::open(&cx, File::open(&directory.0).unwrap(), "credential", 4096);
        assert!(matches!(second, Err(AtomicFileError::Busy)));
        drop(store);
        drop(inherited);
    }

    /// A directory fsync that fails after the store has validated the directory.
    pub(super) fn failing_directory_sync(_: &File) -> std::io::Result<()> {
        Err(std::io::Error::other("injected directory fsync failure"))
    }

    #[test]
    fn a_failed_post_rename_directory_sync_is_commit_uncertain() {
        let cx = Cx::for_testing();
        let directory = PrivateDirectory::new();
        let mut store = directory.open(&cx);
        let previous = store.replace(&cx, None, b"previous").unwrap();
        store.directory_sync = failing_directory_sync;
        let attempted = version(b"attempted").unwrap();

        assert_eq!(
            store.replace(&cx, Some(previous), b"attempted"),
            Err(AtomicFileError::CommitUncertain { attempted }),
        );
        // The post-state, not only the error: load and replace stay refused
        // until reconciliation establishes which value is durable.
        assert!(store.recovery_required);
        assert!(matches!(
            store.load(&cx),
            Err(AtomicFileError::RecoveryRequired)
        ));
        assert_eq!(
            store.replace(&cx, Some(attempted), b"again"),
            Err(AtomicFileError::RecoveryRequired),
        );

        store.directory_sync = File::sync_all;
        let reconciled = store.reconcile(&cx).unwrap().expect("the rename happened");
        assert_eq!(reconciled.version(), attempted);
        assert!(!store.recovery_required);
        assert_eq!(store.load(&cx).unwrap().unwrap().bytes(), b"attempted");
    }

    /// Planted negative: identical except the post-rename directory sync
    /// succeeds, so neither the error nor the recovery state may appear.
    #[test]
    fn a_successful_post_rename_directory_sync_commits() {
        let cx = Cx::for_testing();
        let directory = PrivateDirectory::new();
        let mut store = directory.open(&cx);
        let previous = store.replace(&cx, None, b"previous").unwrap();
        let attempted = version(b"attempted").unwrap();

        assert_eq!(
            store.replace(&cx, Some(previous), b"attempted"),
            Ok(attempted)
        );
        assert!(!store.recovery_required);
        assert_eq!(store.load(&cx).unwrap().unwrap().version(), attempted);
    }

    /// A process whose stdin shares `store`'s lock open file description, as
    /// a child forked by any other thread does until it execs.
    fn process_sharing_the_lock_description(store: &SecureAtomicFile) -> std::process::Child {
        std::process::Command::new("sleep")
            .arg("60")
            .stdin(std::process::Stdio::from(store.lock.try_clone().unwrap()))
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .spawn()
            .unwrap()
    }

    fn open_contender(
        cx: &Cx,
        directory: &PrivateDirectory,
    ) -> Result<SecureAtomicFile, AtomicFileError> {
        SecureAtomicFile::open(cx, File::open(&directory.0).unwrap(), "credential", 4096)
    }

    #[test]
    fn a_dropped_handle_is_not_kept_busy_by_another_process_sharing_its_lock() {
        let cx = Cx::for_testing();
        let directory = PrivateDirectory::new();
        let mut store = directory.open(&cx);
        let committed = store.replace(&cx, None, b"committed").unwrap();
        let mut sharer = process_sharing_the_lock_description(&store);
        drop(store);

        let reopened = open_contender(&cx, &directory);
        let _ = sharer.kill();
        let _ = sharer.wait();
        let reopened = reopened.expect("dropping the only handle must release its lock");
        assert_eq!(reopened.load(&cx).unwrap().unwrap().version(), committed);
    }

    /// Planted negative: identical except the owning handle is still live, so
    /// the contender is refused and the owner's state is untouched.
    #[test]
    fn a_live_handle_keeps_a_contender_busy_while_another_process_shares_its_lock() {
        let cx = Cx::for_testing();
        let directory = PrivateDirectory::new();
        let mut store = directory.open(&cx);
        let committed = store.replace(&cx, None, b"committed").unwrap();
        let mut sharer = process_sharing_the_lock_description(&store);

        let contender = open_contender(&cx, &directory);
        let _ = sharer.kill();
        let _ = sharer.wait();
        assert!(matches!(contender, Err(AtomicFileError::Busy)));
        assert!(!store.recovery_required);
        assert_eq!(store.load(&cx).unwrap().unwrap().version(), committed);
        let next = version(b"next").unwrap();
        assert_eq!(store.replace(&cx, Some(committed), b"next"), Ok(next));
    }
}