openlatch-client 0.5.2

OpenLatch runtime enforcement node — the capture-and-enforce adapter that evaluates every covered action against a coding agent's Autonomy Zone before it runs
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
//! Owner-only protection for the files that hold secrets.
//!
//! Four call sites wrote a secret and then set mode `0600` under
//! `#[cfg(unix)]` — the credentials file, the HMAC key, the hook state file
//! and the daemon token. Windows got nothing, on the rationale (written at the
//! token site) that `%APPDATA%` is already ACL-restricted to the user.
//!
//! That rationale holds for the default directory and stops holding the moment
//! `OPENLATCH_DIR` points elsewhere — `C:\ProgramData`, a second volume, a
//! mapped share — all of which inherit a DACL that grants `Users` read access.
//! The secret is then world-readable on the machine, silently, and no test
//! could have caught it: every `mode_0600` assertion in the tree is itself
//! `#[cfg(unix)]`.
//!
//! So the platform answer lives here, once, instead of four times at the call
//! sites: `0600` on Unix, an explicit owner-only DACL on Windows.

use std::io;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant, SystemTime};

/// Restrict `path` so that only its owner can read or write it.
///
/// Unix: mode `0600`, propagating failures exactly as `set_permissions` did at
/// the call sites this replaced. Windows: strip inherited ACEs and grant full
/// control to the object's owner alone — **warn-and-continue on failure**.
/// Elsewhere: `Ok(())`; there is no third platform in this crate's target list.
///
/// The asymmetry is deliberate and temporary. Windows previously did nothing
/// here, so a hardening step that cannot complete leaves the status quo, while
/// propagating would turn `openlatch init` into a hard failure on the one
/// platform where this code has never run — trading a gap for an outage. The
/// effect is asserted by `windows_leaves_only_an_owner_ace`, which runs in
/// `.github/workflows/windows-checks.yml`; once that has been green on main,
/// this can propagate like the Unix half.
///
/// Errors that do reach the caller are theirs to weigh: a store that hard-fails
/// when it cannot protect a secret propagates, and a best-effort site (the hook
/// state file) keeps ignoring the result as it always did.
pub fn restrict_to_owner(path: &Path) -> io::Result<()> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
    }
    #[cfg(windows)]
    {
        if let Err(e) = restrict_windows(path) {
            tracing::warn!(
                error = %e,
                path = %path.display(),
                "could not restrict file to its owner; it keeps the directory's inherited ACL"
            );
        }
        Ok(())
    }
    #[cfg(not(any(unix, windows)))]
    {
        let _ = path;
        Ok(())
    }
}

/// Write `body` to `path` atomically and leave it **executable**.
///
/// The sibling of [`restrict_to_owner`], not a replacement for it, and the
/// distinction is load-bearing: `restrict_to_owner` sets `0600` and so strips
/// the execute bit. A hook script written through it is permission-denied every
/// time the agent tries to run it — a silent, total capture failure on a file
/// that looks perfectly correct on disk.
///
/// A named helper rather than a tenth inline `cfg` block, per
/// `.claude/rules/cross-platform.md`: this module and `path_compat` own every
/// platform branch, so the mode lives here once and no call site re-derives it.
///
/// Durability follows `hooks::atomic`: write, `sync_all`, rename over the
/// target, then `sync_all` the parent directory so the rename itself survives a
/// crash. A reader sees the old file or the new one, never a half-written one.
///
/// **The temp name APPENDS, it never replaces an extension.**
/// `Path::with_extension` is wrong for both shapes this writes: given
/// `PreToolUse` it produces a *sibling* named `PreToolUse.tmp` — which is
/// itself a name the agent may discover — and given `PreToolUse.ps1` it
/// *replaces* `.ps1`, so the rename would move a file the agent no longer
/// recognises.
///
/// Errors: any I/O failure, propagated. A hook that cannot be written is not a
/// hook, so unlike the Windows half of `restrict_to_owner` there is nothing to
/// warn-and-continue about.
pub fn write_executable(path: &Path, body: &str) -> io::Result<()> {
    write_atomic(path, body, 0o755)
}

/// Write `body` to `path` atomically and leave it **readable, not executable**.
///
/// The third member of the family, and the mode is the whole point: Cline's
/// enforcement plugin is a JavaScript module Node *imports*. It is never
/// executed, so [`write_executable`]'s `0755` would hand the developer an
/// executable that is not one — a file whose mode says "run me" on a path
/// nothing ever will. `restrict_to_owner`'s `0600` is wrong in the other
/// direction for an artefact an agent process may read under a different
/// umask.
///
/// Every durability and symlink property of [`write_executable`] holds here:
/// the two differ by one octal constant and share the body below, so a fix to
/// one is a fix to both.
pub fn write_readable(path: &Path, body: &str) -> io::Result<()> {
    write_atomic(path, body, 0o644)
}

/// The shared body of [`write_executable`] and [`write_readable`].
///
/// `mode` is applied on Unix only; Windows has no mode to set, which is why the
/// two public wrappers document their modes as the writer's *contract* rather
/// than as something a `stat` will confirm on every platform.
fn write_atomic(path: &Path, body: &str, mode: u32) -> io::Result<()> {
    let (tmp, mut file) = open_temp_exclusive(path)?;
    file.write_all(body.as_bytes())?;
    file.sync_all()?;
    drop(file);

    // Before the rename, not after. `fs::rename` preserves the mode, so the
    // file has its final mode from the instant it appears under its real name;
    // setting it afterwards leaves a window — and, if it fails, a hook in place
    // that the agent cannot execute.
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Err(e) = std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(mode)) {
            let _ = std::fs::remove_file(&tmp);
            return Err(e);
        }
    }
    #[cfg(not(unix))]
    let _ = mode;

    if let Err(e) = std::fs::rename(&tmp, path) {
        let _ = std::fs::remove_file(&tmp);
        return Err(e);
    }
    sync_parent(path);
    Ok(())
}

/// `<path>.openlatch-tmp`, opened exclusively.
///
/// The one place the temp path is named and opened, for every atomic writer in
/// the crate. **The name APPENDS**, see [`write_executable`].
fn open_temp_exclusive(path: &Path) -> io::Result<(PathBuf, std::fs::File)> {
    let file_name = path.file_name().ok_or_else(|| {
        io::Error::new(
            io::ErrorKind::InvalidInput,
            format!("'{}' has no file name to write", path.display()),
        )
    })?;

    let mut tmp_name = file_name.to_os_string();
    tmp_name.push(".openlatch-tmp");
    let tmp = path.with_file_name(tmp_name);

    // `create_new`, never `File::create`, and a symlink-safe retry.
    //
    // `File::create` FOLLOWS a symlink at the temp path. The hook directory is
    // one the developer (and anything running as them) can write to, so a
    // planted `<HookName>.openlatch-tmp` pointing at any file this process can
    // write turns an install into a truncate-and-overwrite of that target. The
    // install path runs with the developer's privileges, which is exactly when
    // an arbitrary-write primitive is worth having.
    //
    // `create_new(true)` refuses to open anything that already exists, symlink
    // included. A leftover temp file from a crashed run is the one legitimate
    // way that path is occupied, so remove it once and retry: `remove_file`
    // does NOT follow a symlink — it unlinks the link itself, never the target.
    // One spelling of the flags. Written twice, a later edit can touch the retry
    // and not the first open — silently re-opening the symlink hole this closes.
    let open_exclusive = || {
        std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(&tmp)
    };
    let file = match open_exclusive() {
        Ok(f) => f,
        Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
            std::fs::remove_file(&tmp)?;
            open_exclusive()?
        }
        Err(e) => return Err(e),
    };
    Ok((tmp, file))
}

/// `sync_all` the parent directory so a rename survives a crash. Unix only:
/// Windows cannot open a directory as a file, and NTFS journals the rename.
fn sync_parent(path: &Path) {
    #[cfg(unix)]
    {
        if let Some(parent) = path.parent() {
            if let Ok(dir) = std::fs::File::open(parent) {
                let _ = dir.sync_all();
            }
        }
    }
    #[cfg(not(unix))]
    let _ = path;
}

/// What a file looked like when it was read — enough to tell, just before
/// replacing it, whether anything else wrote it in between.
///
/// Length, modification time and, on Unix, the inode. The inode is what catches
/// the writer this exists for: an editor that saves by writing a temp file and
/// renaming it over the original produces a new inode even when the length and
/// the mtime second happen to match.
///
/// **Windows has no inode to compare**, and length-and-mtime alone is not
/// enough there: `std` exposes no stable file index (`file_index` is behind the
/// unstable `windows_by_handle`), and the system clock it stamps `modified`
/// from advances in ~15.6 ms ticks, so an editor's save and our read inside one
/// tick carry the same timestamp. A same-length save — `{"a":1}` becoming
/// `{"a":2}` — was then invisible and got silently overwritten, which is the one
/// thing this module exists to prevent.
///
/// So on Windows the fingerprint carries a digest of the contents instead. The
/// files it guards are agent config, a few hundred kilobytes at the outside, and
/// the read happens twice per replace rather than once. Creation time was the
/// cheaper candidate and is wrong: NTFS **file tunneling** restores the original
/// creation time when a name is recreated within 15 seconds, which is exactly
/// the save-by-rename this catches.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FileFingerprint {
    size: u64,
    modified: Option<SystemTime>,
    identity: Option<(u64, u64)>,
    /// Non-Unix only — see the note above. `None` on Unix, where the inode
    /// answers the same question without reading the file.
    digest: Option<[u8; 32]>,
}

impl FileFingerprint {
    /// The file's length in bytes when it was fingerprinted.
    pub fn size(&self) -> u64 {
        self.size
    }
}

/// Fingerprint `path`, following a symlink to the file it names.
pub fn fingerprint(path: &Path) -> io::Result<FileFingerprint> {
    let meta = std::fs::metadata(path)?;
    #[cfg(unix)]
    let identity = {
        use std::os::unix::fs::MetadataExt;
        Some((meta.dev(), meta.ino()))
    };
    #[cfg(not(unix))]
    let identity = None;
    #[cfg(unix)]
    let digest = None;
    #[cfg(not(unix))]
    let digest = {
        use sha2::{Digest, Sha256};
        let mut hasher = Sha256::new();
        hasher.update(std::fs::read(path)?);
        Some(<[u8; 32]>::from(hasher.finalize()))
    };
    Ok(FileFingerprint {
        size: meta.len(),
        modified: meta.modified().ok(),
        identity,
        digest,
    })
}

/// How a compare-before-rename replace ended.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReplaceOutcome {
    /// The file now holds the new body.
    Replaced,
    /// The file changed after it was fingerprinted, so it was left exactly as
    /// the other writer left it.
    Contended,
}

/// Replace the file at `path` with `body` — only if it still looks the way it
/// did when `expected` was taken — keeping its permissions.
///
/// For a file somebody else owns and writes. An agent's settings file is saved
/// by a running editor at moments we do not choose; overwriting a save that
/// landed between our read and our rename would silently discard the
/// developer's change. So the fingerprint is taken again after the new body is
/// durable in the temp file and immediately before the rename, and any
/// difference abandons the write. A window remains between that check and the
/// rename; it is microseconds wide rather than the width of a parse-and-edit.
///
/// **The mode is the original file's**, copied onto the temp file before the
/// rename. A replace that fell back to the umask would turn a `0600` file
/// holding API keys into a world-readable one. On Windows the temp file is
/// created in the same directory and takes that directory's inherited ACL,
/// which is what the original has unless someone set an explicit one.
///
/// `path` must be the real file, not a symlink to it: the rename replaces
/// whatever directory entry `path` names. The temp file is opened with
/// `create_new`, so a planted symlink at the temp path is never followed.
pub fn replace_preserving(
    path: &Path,
    body: &[u8],
    expected: &FileFingerprint,
) -> io::Result<ReplaceOutcome> {
    replace_inner(path, body, Some(expected))
}

/// Write `body` to `path` atomically, creating it when absent and keeping an
/// existing file's permissions.
///
/// [`replace_preserving`] without the compare, for a writer that owns its file
/// outright. The temp file is still opened with `create_new`.
pub fn write_preserving_mode(path: &Path, body: &[u8]) -> io::Result<()> {
    replace_inner(path, body, None).map(|_| ())
}

fn replace_inner(
    path: &Path,
    body: &[u8],
    expected: Option<&FileFingerprint>,
) -> io::Result<ReplaceOutcome> {
    let (tmp, mut file) = open_temp_exclusive(path)?;
    let written = file.write_all(body).and_then(|()| file.sync_all());
    // Closed before the rename: Windows refuses to rename a file with an open
    // handle.
    drop(file);
    let outcome = written.and_then(|()| commit_replace(path, &tmp, expected));
    match outcome {
        Ok(ReplaceOutcome::Replaced) => sync_parent(path),
        _ => {
            let _ = std::fs::remove_file(&tmp);
        }
    }
    outcome
}

/// Copy the target's mode onto the durable temp file, check the fingerprint,
/// rename.
fn commit_replace(
    path: &Path,
    tmp: &Path,
    expected: Option<&FileFingerprint>,
) -> io::Result<ReplaceOutcome> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        match std::fs::metadata(path) {
            Ok(meta) => std::fs::set_permissions(
                tmp,
                std::fs::Permissions::from_mode(meta.permissions().mode() & 0o7777),
            )?,
            Err(e) if e.kind() == io::ErrorKind::NotFound => {}
            Err(e) => return Err(e),
        }
    }
    if let Some(expected) = expected {
        // A file that vanished since the read is a change too.
        match fingerprint(path) {
            Ok(now) if now == *expected => {}
            Ok(_) => return Ok(ReplaceOutcome::Contended),
            Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(ReplaceOutcome::Contended),
            Err(e) => return Err(e),
        }
    }
    std::fs::rename(tmp, path)?;
    Ok(ReplaceOutcome::Replaced)
}

/// How long [`with_lockfile`] waits for another holder before giving up.
const LOCK_WAIT: Duration = Duration::from_secs(2);

/// Run `f` while holding `lock`, a file created exclusively beside the data it
/// guards.
///
/// For a small file several processes rewrite whole — the CLI during `init` or
/// `uninstall`, and a running daemon's wiring pass — where a read-modify-write
/// that interleaves with another loses the other's entry. A file rather than an
/// OS lock because it behaves the same on every platform and needs no handle
/// kept alive across the call.
///
/// A lock older than `stale_after` belongs to a process that died holding it
/// and is removed; the critical sections this guards take milliseconds, so the
/// bound is generous. A live holder is waited on for up to two seconds, then
/// the call fails with `WouldBlock` rather than hanging the caller.
pub fn with_lockfile<T>(
    lock: &Path,
    stale_after: Duration,
    f: impl FnOnce() -> T,
) -> io::Result<T> {
    let started = Instant::now();
    loop {
        match std::fs::OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(lock)
        {
            Ok(mut file) => {
                let _ = write!(file, "{}", std::process::id());
                drop(file);
                let _held = LockGuard(lock);
                return Ok(f());
            }
            Err(e) if e.kind() == io::ErrorKind::AlreadyExists => {
                let stale = std::fs::metadata(lock)
                    .and_then(|m| m.modified())
                    .ok()
                    .and_then(|t| t.elapsed().ok())
                    .is_some_and(|age| age >= stale_after);
                if stale {
                    let _ = std::fs::remove_file(lock);
                } else if started.elapsed() >= LOCK_WAIT {
                    return Err(io::Error::new(
                        io::ErrorKind::WouldBlock,
                        format!("'{}' is held by another process", lock.display()),
                    ));
                } else {
                    std::thread::sleep(Duration::from_millis(10));
                }
            }
            Err(e) => return Err(e),
        }
    }
}

/// Removes the lock file when the critical section ends, panics included.
struct LockGuard<'a>(&'a Path);

impl Drop for LockGuard<'_> {
    fn drop(&mut self) {
        let _ = std::fs::remove_file(self.0);
    }
}

/// `icacls <path> /inheritance:r /grant:r *S-1-3-4:(F)`.
///
/// `/inheritance:r` drops every inherited ACE — the ones that make a file in
/// `C:\ProgramData` readable by `Users` — leaving only what we grant next.
/// Both flags go in one invocation so the file is never left with an empty
/// DACL between two calls.
///
/// The grantee is `S-1-3-4` (OWNER RIGHTS), the well-known SID that resolves to
/// whoever currently owns the object, rather than a `DOMAIN\user` string. The
/// account name would have to come from `%USERNAME%` or `GetUserNameW`, and a
/// bare name is ambiguous on a domain-joined machine (a local account and a
/// domain account can share it); OWNER RIGHTS needs no lookup, cannot resolve
/// to the wrong principal, and survives an account rename. On an elevated
/// process the owner defaults to `BUILTIN\Administrators` — still owner-only,
/// still no `Users` access, which is the invariant being protected.
///
/// Shelling out to `icacls` rather than calling `SetNamedSecurityInfoW`: the
/// API route needs `SetEntriesInAclW`, a hand-built `EXPLICIT_ACCESS` and three
/// `LocalFree`s of unsafe code that no Linux developer here can execute before
/// merging. `icacls` is one auditable line, ships with Windows, and these are
/// cold paths — a credential write, a key generation, a token creation.
#[cfg(windows)]
fn restrict_windows(path: &Path) -> io::Result<()> {
    use std::process::{Command, Stdio};

    /// OWNER RIGHTS. `*` prefixes a SID in icacls' grantee syntax.
    const OWNER_RIGHTS_SID: &str = "*S-1-3-4:(F)";

    let output = Command::new("icacls")
        .arg(path)
        .args(["/inheritance:r", "/grant:r", OWNER_RIGHTS_SID])
        .stdin(Stdio::null())
        .output()?;

    if output.status.success() {
        return Ok(());
    }
    // icacls reports the reason on stdout, not stderr — a volume without ACL
    // support (FAT32 / exFAT on a removable drive) lands here, and the honest
    // answer is that the secret cannot be protected on it.
    let detail = String::from_utf8_lossy(&output.stdout);
    Err(io::Error::other(format!(
        "icacls failed to restrict '{}' to its owner ({}): {}",
        path.display(),
        output.status,
        detail.trim()
    )))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn write_secret(dir: &Path, name: &str) -> std::path::PathBuf {
        let path = dir.join(name);
        std::fs::write(&path, b"secret").unwrap();
        path
    }

    #[test]
    fn restricting_keeps_the_file_readable_by_this_process() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_secret(dir.path(), "token");

        restrict_to_owner(&path).unwrap();

        assert_eq!(std::fs::read(&path).unwrap(), b"secret");
    }

    /// Unix-only: the Windows arm warns instead of propagating, so a missing
    /// file is `Ok(())` there by design (see `restrict_to_owner`).
    #[test]
    #[cfg(unix)]
    fn restricting_a_missing_file_is_an_error() {
        let dir = tempfile::tempdir().unwrap();
        let missing = dir.path().join("nope");

        assert!(restrict_to_owner(&missing).is_err());
    }

    #[test]
    #[cfg(unix)]
    fn unix_sets_mode_0600() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let path = write_secret(dir.path(), "token");
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o644)).unwrap();

        restrict_to_owner(&path).unwrap();

        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "expected 0600, got {mode:o}");
    }

    #[test]
    fn write_executable_writes_the_body() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("PreToolUse");

        write_executable(&path, "#!/bin/sh\nprintf '{}'\n").unwrap();

        assert_eq!(
            std::fs::read_to_string(&path).unwrap(),
            "#!/bin/sh\nprintf '{}'\n"
        );
    }

    /// The whole reason this is not `restrict_to_owner`: `0600` would strip the
    /// execute bit and the agent could never run the script.
    #[test]
    #[cfg(unix)]
    fn write_executable_sets_mode_0755() {
        use std::os::unix::fs::PermissionsExt;

        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("PreToolUse");

        write_executable(&path, "#!/bin/sh\n").unwrap();

        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o755, "expected 0755, got {mode:o}");
    }

    /// Replacing an existing script keeps its name and mode, and the rename is
    /// what makes the swap atomic.
    #[test]
    fn write_executable_replaces_an_existing_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("PreToolUse");
        std::fs::write(&path, "old").unwrap();

        write_executable(&path, "new").unwrap();

        assert_eq!(std::fs::read_to_string(&path).unwrap(), "new");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
            assert_eq!(mode, 0o755);
        }
    }

    /// `with_extension` is wrong for BOTH shapes this writes, so the temp name
    /// appends. Given `PreToolUse` it would make a sibling the agent may itself
    /// discover as a hook; given `PreToolUse.ps1` it would REPLACE `.ps1`, and
    /// the rename would then move a file Windows discovery ignores.
    #[test]
    fn write_executable_leaves_no_temp_file_behind() {
        let dir = tempfile::tempdir().unwrap();

        for name in ["PreToolUse", "PreToolUse.ps1"] {
            let path = dir.path().join(name);
            write_executable(&path, "body").unwrap();
            assert_eq!(std::fs::read_to_string(&path).unwrap(), "body");
        }

        let mut left: Vec<String> = std::fs::read_dir(dir.path())
            .unwrap()
            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
            .collect();
        left.sort();
        assert_eq!(
            left,
            vec!["PreToolUse".to_string(), "PreToolUse.ps1".to_string()],
            "a temp file survived, or an extension was replaced instead of appended"
        );
    }

    /// A planted symlink at the temp path must not be followed.
    ///
    /// The hook directory is one the developer — and anything running as them —
    /// can write to. `File::create` follows a symlink, so a planted
    /// `<HookName>.openlatch-tmp` pointing anywhere this process can write
    /// turned an install into a truncate-and-overwrite of that target. The
    /// install path runs with the developer's privileges, which is exactly when
    /// that matters.
    ///
    /// The victim file must come out BYTE-IDENTICAL. Asserting only that
    /// `write_executable` succeeded would pass while it wrote through the link.
    #[cfg(unix)]
    #[test]
    fn write_executable_never_follows_a_planted_temp_symlink() {
        let dir = tempfile::tempdir().unwrap();
        let victim = dir.path().join("victim-do-not-touch");
        std::fs::write(&victim, "PRECIOUS").unwrap();

        let path = dir.path().join("PreToolUse");
        let tmp = dir.path().join("PreToolUse.openlatch-tmp");
        std::os::unix::fs::symlink(&victim, &tmp).unwrap();

        write_executable(&path, "shim body").expect("the write itself still succeeds");

        assert_eq!(
            std::fs::read_to_string(&victim).unwrap(),
            "PRECIOUS",
            "the planted symlink was followed and the victim file was overwritten"
        );
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "shim body");
        assert!(
            !tmp.exists(),
            "the temp path must not survive the write, symlink or not"
        );
    }

    /// A leftover temp file from a crashed run must not wedge every later install.
    ///
    /// `create_new` refuses an existing path, which is the whole point — so the
    /// one legitimate occupant, our own stale temp file, has to be cleared and
    /// retried rather than turned into a permanent failure.
    #[test]
    fn write_executable_recovers_from_a_stale_temp_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("PreToolUse");
        std::fs::write(dir.path().join("PreToolUse.openlatch-tmp"), "crashed run").unwrap();

        write_executable(&path, "fresh body").expect("a stale temp file is recoverable");
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "fresh body");
    }

    /// A save that lands between our read and our rename is the developer's
    /// change, and it must survive: the replace abandons, the file keeps the
    /// other writer's bytes, and no temp file is left behind.
    #[test]
    fn replace_aborts_when_the_file_changed_under_it() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("globalState.json");
        std::fs::write(&path, "{\"a\":1}").unwrap();
        let seen = fingerprint(&path).unwrap();

        // Another writer saves the way an editor does: temp file, then rename.
        let theirs = dir.path().join("editor-tmp");
        std::fs::write(&theirs, "{\"a\":2}").unwrap();
        std::fs::rename(&theirs, &path).unwrap();

        let outcome = replace_preserving(&path, b"{\"ours\":true}", &seen).unwrap();
        assert_eq!(outcome, ReplaceOutcome::Contended);
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "{\"a\":2}");
        assert!(!dir.path().join("globalState.json.openlatch-tmp").exists());

        // Taken again, the replace goes through.
        let now = fingerprint(&path).unwrap();
        assert_eq!(
            replace_preserving(&path, b"{\"ours\":true}", &now).unwrap(),
            ReplaceOutcome::Replaced
        );
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "{\"ours\":true}");
    }

    /// A file deleted since the read is not ours to recreate.
    #[test]
    fn replace_treats_a_vanished_file_as_contended() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("providers.json");
        std::fs::write(&path, "{}").unwrap();
        let seen = fingerprint(&path).unwrap();
        std::fs::remove_file(&path).unwrap();

        assert_eq!(
            replace_preserving(&path, b"{}", &seen).unwrap(),
            ReplaceOutcome::Contended
        );
        assert!(!path.exists());
    }

    /// The live defect this fixes: `providers.json` holds API keys at `0600`, and a
    /// rewrite through a umask-created temp file made it world-readable.
    #[test]
    #[cfg(unix)]
    fn replace_preserves_mode_0600() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("providers.json");
        std::fs::write(&path, "{}").unwrap();
        std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();

        let seen = fingerprint(&path).unwrap();
        replace_preserving(&path, b"{\"x\":1}", &seen).unwrap();
        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "expected 0600, got {mode:o}");

        write_preserving_mode(&path, b"{\"x\":2}").unwrap();
        let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
        assert_eq!(mode, 0o600, "expected 0600, got {mode:o}");
    }

    #[cfg(unix)]
    #[test]
    fn replace_never_follows_a_planted_temp_symlink() {
        let dir = tempfile::tempdir().unwrap();
        let victim = dir.path().join("victim-do-not-touch");
        std::fs::write(&victim, "PRECIOUS").unwrap();
        let path = dir.path().join("globalState.json");
        std::fs::write(&path, "{}").unwrap();
        std::os::unix::fs::symlink(&victim, dir.path().join("globalState.json.openlatch-tmp"))
            .unwrap();

        let seen = fingerprint(&path).unwrap();
        replace_preserving(&path, b"{\"x\":1}", &seen).unwrap();
        assert_eq!(std::fs::read_to_string(&victim).unwrap(), "PRECIOUS");
        assert_eq!(std::fs::read_to_string(&path).unwrap(), "{\"x\":1}");
    }

    /// Two writers of one small file must not interleave their read-modify-write.
    #[test]
    fn with_lockfile_excludes_a_second_holder() {
        let dir = tempfile::tempdir().unwrap();
        let lock = dir.path().join("records.lock");
        let inner = with_lockfile(&lock, Duration::from_secs(30), || {
            assert!(lock.exists(), "the lock is held inside the section");
            with_lockfile(&lock, Duration::from_secs(30), || ())
        })
        .unwrap();
        let err = inner.expect_err("a second holder waits, then gives up");
        assert_eq!(err.kind(), io::ErrorKind::WouldBlock);
        assert!(!lock.exists(), "the lock is released when the section ends");
    }

    /// A process that died holding the lock does not wedge every later writer.
    #[test]
    fn a_stale_lock_is_recovered() {
        let dir = tempfile::tempdir().unwrap();
        let lock = dir.path().join("records.lock");
        std::fs::write(&lock, "12345").unwrap();
        let ran = with_lockfile(&lock, Duration::ZERO, || true).unwrap();
        assert!(ran);
        assert!(!lock.exists());
    }

    #[test]
    fn write_executable_fails_when_the_directory_is_missing() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("nope").join("PreToolUse");

        assert!(write_executable(&path, "body").is_err());
    }

    /// The Windows half of `unix_sets_mode_0600`, and the reason
    /// `.github/workflows/windows-checks.yml` exists: nothing else in this
    /// repository has ever asserted that a secret file is unreadable by other
    /// accounts on Windows.
    #[test]
    #[cfg(windows)]
    fn windows_leaves_only_an_owner_ace() {
        let dir = tempfile::tempdir().unwrap();
        let path = write_secret(dir.path(), "token");

        restrict_to_owner(&path).unwrap();

        let out = std::process::Command::new("icacls")
            .arg(&path)
            .output()
            .expect("icacls runs");
        let acl = String::from_utf8_lossy(&out.stdout);

        assert!(
            acl.contains("OWNER RIGHTS") || acl.contains("S-1-3-4"),
            "owner ACE missing from DACL: {acl}"
        );
        // `(I)` marks an inherited ACE — `/inheritance:r` must have removed
        // every one of them, including whatever granted `Users` access.
        assert!(
            !acl.contains("(I)"),
            "inherited ACEs survived, secret may be readable by others: {acl}"
        );
        assert!(
            !acl.contains("\\Users:") && !acl.contains("BUILTIN\\Users"),
            "Users group still has access: {acl}"
        );
    }
}