cordance-core 0.1.0

Cordance core types, schemas, and ports. No I/O.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
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
//! Filesystem write helpers that refuse to follow target-controlled symlinks.
//!
//! Round-5 redteam #1: a hostile target plants `<target>/AGENTS.md` as a
//! symlink to `~/.ssh/authorized_keys`. `std::fs::write` follows the link
//! and the operator's own files are overwritten. The helpers in this module
//! refuse to write to any path that exists as a symlink or Windows reparse
//! point. The operator must remove the link manually and re-run.
//!
//! Round-6 redteam #1 / codereview #1 / bughunt #2: the leaf-only check
//! left the **ancestor** class open. A hostile target shipping
//! `<target>/.cordance/` as a Windows directory junction (or POSIX symlink
//! to a directory) silently redirected every `safe_write_with_mkdir` call
//! through that junction — `create_dir_all` succeeded against the existing
//! junction target, and the leaf check on the final path resolved through
//! the junction and saw "no file here yet". The helpers in this module now
//! refuse if ANY existing ancestor of the destination path is a reparse
//! point. The refusal carries the ANCESTOR path, not the original target,
//! so operators can diagnose which directory in the chain is symlinked.
//!
//! The check uses `std::fs::symlink_metadata` (which does NOT follow links)
//! plus a Windows-only `FILE_ATTRIBUTE_REPARSE_POINT` (0x400) probe for
//! junctions that `is_symlink()` returns false for. This mirrors the
//! reparse-point pattern already used by `cordance-cli`'s entry-point
//! `is_reparse_or_symlink` guard.

use std::path::{Path, PathBuf};

/// Error kind returned by [`safe_write`] when the destination is a reparse
/// point. Wrapped inside `std::io::Error::other` so it composes with normal
/// I/O error propagation in the emitters.
#[derive(Debug, thiserror::Error)]
#[error("refusing to write through symlink/reparse-point at {path:?}")]
pub struct SymlinkRefusal {
    pub path: PathBuf,
}

/// Return `true` when `path` exists AND is a POSIX symlink, a Windows
/// symlink-file, a Windows symlink-dir, or a Windows directory junction.
///
/// `std::fs::FileType::is_symlink()` returns `false` for Windows directory
/// junctions even though they short-circuit the filesystem in the same way
/// a symlink does. On Windows we additionally read the file attributes and
/// check for `FILE_ATTRIBUTE_REPARSE_POINT` (0x400) so junctions are caught.
///
/// A non-existent path returns `false` (we'll create it). Any other I/O
/// error while reading the metadata also returns `false` — the subsequent
/// write will surface a proper error.
fn is_reparse_point(path: &Path) -> bool {
    let Ok(meta) = std::fs::symlink_metadata(path) else {
        return false;
    };
    if meta.file_type().is_symlink() {
        return true;
    }
    #[cfg(windows)]
    {
        use std::os::windows::fs::MetadataExt;
        const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
        if meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
            return true;
        }
    }
    false
}

/// Walk every existing ancestor of `path` (starting from `path` itself,
/// popping up to the filesystem root) and return `Some(ancestor)` for the
/// first reparse-point encountered, or `None` if every existing ancestor is
/// a regular file/directory.
///
/// This is the round-6 hardening of [`safe_write`] and
/// [`safe_write_with_mkdir`]: the leaf-only check from round 5 left a
/// hostile target free to plant `<target>/.cordance/` as a Windows
/// directory junction (or POSIX symlink-to-directory). The OS resolves
/// every subsequent `safe_write(.cordance/pack.json, …)` THROUGH the
/// junction into operator-owned storage. Walking the full ancestor chain
/// closes that class.
///
/// Non-existent ancestors are skipped — a path like
/// `<tempdir>/new-dir/AGENTS.md` is fine when `<tempdir>/new-dir` does not
/// yet exist; `safe_write_with_mkdir` will `create_dir_all` it AFTER the
/// ancestor check refuses any reparse-point already in the chain.
///
/// The walk stops at the filesystem root (the point at which
/// `Path::parent` returns `None`).
fn find_reparse_point_ancestor(path: &Path) -> Option<PathBuf> {
    let mut cur: Option<&Path> = Some(path);
    while let Some(p) = cur {
        // Skip non-existent ancestors. `symlink_metadata` returning Err
        // means "no entry here", which is the normal case for the leaf of
        // a fresh write and for any parent dir that mkdir is about to
        // create. `is_reparse_point` already returns false on metadata
        // failure, so we lean on that.
        if is_reparse_point(p) {
            return Some(p.to_path_buf());
        }
        cur = p.parent();
    }
    None
}

/// Write `bytes` to `path`, refusing if `path` OR any existing ancestor of
/// `path` is a symlink or Windows reparse point (junction, symlink-file,
/// symlink-dir).
///
/// On POSIX, a symlink target points anywhere on disk; following it lets a
/// hostile target write to operator-owned files (`~/.ssh/authorized_keys`,
/// `~/.bashrc`, …). On Windows the same threat exists via reparse points
/// (junctions and symlinks). The round-5 helper checked only the leaf,
/// which left the **ancestor** class open — a hostile target shipping
/// `<target>/.cordance/` as a directory junction redirected every helper
/// write into operator-owned storage (round-6 redteam #1). This helper is
/// the *only* `std::fs::write` wrapper Cordance should use for
/// target-relative writes.
///
/// Idempotency: a non-existent path is allowed (we'll create it). An
/// existing regular file is allowed (we'll truncate-overwrite). An existing
/// directory makes `std::fs::write` error naturally — pass through.
///
/// # Errors
///
/// Returns `std::io::Error::other(SymlinkRefusal { path: ancestor })` if
/// any existing ancestor of `path` (including `path` itself) is a reparse
/// point. The carried path is the **ancestor that triggered the refusal**,
/// not the original target — operators reading the error can identify
/// which directory in the chain is symlinked. Otherwise propagates any I/O
/// error from the underlying write.
pub fn safe_write(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
    if let Some(ancestor) = find_reparse_point_ancestor(path) {
        return Err(std::io::Error::other(SymlinkRefusal { path: ancestor }));
    }
    std::fs::write(path, bytes)
}

/// `safe_write` + `create_dir_all` for the parent directory. Convenience
/// for emitter outputs that may target nested paths
/// (e.g. `.cordance/cortex-receipt.json`).
///
/// The ancestor reparse-point check runs **before** `create_dir_all` and
/// **before** the actual write. This is required: `create_dir_all` itself
/// follows symlinks during traversal, so if (say) `<target>/.cordance` is
/// a directory junction, `create_dir_all(<target>/.cordance/sub)` would
/// happily land `sub` inside the junction target. Checking only the leaf
/// after `create_dir_all` does not help — the leaf-check resolves through
/// the junction too and reports "no file yet" because the redirected
/// destination is genuinely empty. Refusing on the ancestor closes the
/// class (round-6 redteam #1 / codereview #1 / bughunt #2).
///
/// # Errors
///
/// Same as [`safe_write`], plus any I/O error from the `create_dir_all`
/// call. The ancestor reparse-point check is performed before either I/O
/// call, so an attacker-planted junction is refused without creating any
/// directories on disk.
pub fn safe_write_with_mkdir(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
    // Ancestor check FIRST, before any filesystem mutation. If any
    // existing ancestor (or `path` itself) is a reparse point, refuse —
    // otherwise `create_dir_all` would silently traverse the junction and
    // materialise the parent inside the symlink target.
    if let Some(ancestor) = find_reparse_point_ancestor(path) {
        return Err(std::io::Error::other(SymlinkRefusal { path: ancestor }));
    }
    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() {
            std::fs::create_dir_all(parent)?;
        }
    }
    // `safe_write` re-checks the ancestor chain. That's intentional belt-
    // and-braces: `create_dir_all` could (in principle) race with a
    // concurrent attacker who plants a symlink between the check above
    // and the write below. The re-check narrows the window to the
    // already-noted leaf-level TOCTOU (R6-bughunt-2) which is out of
    // scope for this fix and tracked separately.
    safe_write(path, bytes)
}

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

    #[test]
    fn safe_write_creates_new_file_ok() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("new.txt");
        assert!(!path.exists(), "precondition: file must not exist");
        safe_write(&path, b"hello").expect("write to new path must succeed");
        let on_disk = std::fs::read(&path).expect("read back");
        assert_eq!(on_disk, b"hello");
    }

    #[test]
    fn safe_write_overwrites_regular_file_ok() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("file.txt");
        std::fs::write(&path, b"old content").expect("seed");
        safe_write(&path, b"new content").expect("overwrite must succeed");
        let on_disk = std::fs::read(&path).expect("read back");
        assert_eq!(on_disk, b"new content");
    }

    #[test]
    fn safe_write_with_mkdir_creates_parent_dirs_ok() {
        let dir = tempfile::tempdir().expect("tempdir");
        let nested = dir.path().join("a").join("b").join("c").join("out.json");
        assert!(!nested.parent().expect("has parent").exists());
        safe_write_with_mkdir(&nested, b"{}").expect("nested mkdir+write");
        assert!(nested.exists(), "destination must be created");
        let on_disk = std::fs::read(&nested).expect("read back");
        assert_eq!(on_disk, b"{}");
    }

    #[test]
    fn safe_write_with_mkdir_overwrites_existing_regular_file_ok() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("nested").join("file.txt");
        std::fs::create_dir_all(path.parent().expect("parent")).expect("mkdir");
        std::fs::write(&path, b"first").expect("seed");
        safe_write_with_mkdir(&path, b"second").expect("overwrite");
        assert_eq!(std::fs::read(&path).expect("read"), b"second");
    }

    #[test]
    fn safe_write_errors_when_destination_is_directory() {
        // Sanity: writing to an existing directory must fail. The helper
        // does not special-case this — it passes through `std::fs::write`'s
        // natural error so the caller sees a kernel-supplied diagnostic.
        let dir = tempfile::tempdir().expect("tempdir");
        let subdir = dir.path().join("subdir");
        std::fs::create_dir(&subdir).expect("mkdir");
        let err = safe_write(&subdir, b"nope").expect_err("must error");
        // We don't pin the exact ErrorKind because OS variation exists, but
        // it must not be a SymlinkRefusal (the path is a real directory).
        assert!(
            err.get_ref()
                .and_then(|e| e.downcast_ref::<SymlinkRefusal>())
                .is_none(),
            "directory must not be reported as symlink refusal"
        );
    }

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

        let dir = tempfile::tempdir().expect("tempdir");
        let dest = dir.path().join("target.txt");
        std::fs::write(&dest, b"operator owned").expect("seed dest");
        let link = dir.path().join("link.txt");
        symlink(&dest, &link).expect("symlink");

        let err = safe_write(&link, b"attacker bytes").expect_err("must refuse symlink");
        // The error must wrap a SymlinkRefusal so callers can detect it.
        let refusal = err
            .get_ref()
            .and_then(|e| e.downcast_ref::<SymlinkRefusal>())
            .expect("error must carry SymlinkRefusal");
        assert_eq!(refusal.path, link, "refusal must name the link path");

        // The dest must be untouched.
        let on_disk = std::fs::read(&dest).expect("read dest");
        assert_eq!(
            on_disk, b"operator owned",
            "symlink target must NOT be overwritten"
        );
    }

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

        let dir = tempfile::tempdir().expect("tempdir");
        let dest = dir.path().join("real.txt");
        std::fs::write(&dest, b"operator owned").expect("seed");
        let link = dir.path().join("nested").join("link.txt");
        std::fs::create_dir_all(link.parent().expect("parent")).expect("mkdir");
        symlink(&dest, &link).expect("symlink");

        let err =
            safe_write_with_mkdir(&link, b"attacker").expect_err("must refuse symlink");
        assert!(
            err.get_ref()
                .and_then(|e| e.downcast_ref::<SymlinkRefusal>())
                .is_some(),
            "with_mkdir must also refuse symlinks"
        );
        // Operator file untouched.
        assert_eq!(
            std::fs::read(&dest).expect("read dest"),
            b"operator owned"
        );
    }

    #[cfg(windows)]
    #[test]
    fn safe_write_refuses_windows_symlink_file() {
        use std::os::windows::fs::symlink_file;

        let dir = tempfile::tempdir().expect("tempdir");
        let dest = dir.path().join("real.txt");
        std::fs::write(&dest, b"operator owned").expect("seed");
        let link = dir.path().join("link.txt");
        // Creating a symlink on Windows requires Developer Mode or
        // SeCreateSymbolicLinkPrivilege. If that isn't available in the
        // test environment, skip — the POSIX test still proves the
        // contract.
        if symlink_file(&dest, &link).is_err() {
            eprintln!(
                "skipping: cannot create windows symlink (missing privilege / Developer Mode)"
            );
            return;
        }

        let err = safe_write(&link, b"attacker").expect_err("must refuse windows symlink");
        let refusal = err
            .get_ref()
            .and_then(|e| e.downcast_ref::<SymlinkRefusal>())
            .expect("error must carry SymlinkRefusal");
        assert_eq!(refusal.path, link);
        // Dest untouched.
        assert_eq!(
            std::fs::read(&dest).expect("read dest"),
            b"operator owned"
        );
    }

    #[cfg(windows)]
    #[test]
    fn safe_write_refuses_directory_junction() {
        // Directory junctions are reparse points but NOT symlinks per Rust's
        // `is_symlink()`. We probe `FILE_ATTRIBUTE_REPARSE_POINT` to catch
        // them. Creating a junction needs `mklink /J` which works without
        // elevated privileges — but only via cmd.exe / the WinAPI. We use
        // `std::process::Command` to invoke `cmd /c mklink /J`.
        use std::process::Command;

        let dir = tempfile::tempdir().expect("tempdir");
        let dest = dir.path().join("real-dir");
        std::fs::create_dir(&dest).expect("mkdir dest");
        let junction = dir.path().join("junction");

        let status = Command::new("cmd")
            .args([
                "/C",
                "mklink",
                "/J",
                junction.to_str().expect("utf8"),
                dest.to_str().expect("utf8"),
            ])
            .status();
        let Ok(status) = status else {
            eprintln!("skipping: cmd.exe unavailable");
            return;
        };
        if !status.success() {
            eprintln!("skipping: mklink /J failed");
            return;
        }

        // Writing to the junction path itself (as a file) will error
        // naturally because it's a directory, but the reparse-point guard
        // should fire first. We assert the guard refuses via SymlinkRefusal.
        let err =
            safe_write(&junction, b"attacker").expect_err("must refuse directory junction");
        assert!(
            err.get_ref()
                .and_then(|e| e.downcast_ref::<SymlinkRefusal>())
                .is_some(),
            "directory junction must be refused as reparse point"
        );
    }

    // -----------------------------------------------------------------
    // Round-6: ANCESTOR reparse-point coverage.
    //
    // The round-5 leaf check left a hostile target free to plant
    // `<target>/.cordance/` as a directory symlink/junction; every
    // subsequent `safe_write(.cordance/pack.json, …)` then resolved
    // through the link into operator-owned storage. The tests below
    // pin the new behaviour: `safe_write` and `safe_write_with_mkdir`
    // refuse any path whose existing ancestor chain contains a
    // reparse point, and the refusal carries the ANCESTOR path so the
    // operator can diagnose which directory is symlinked.
    // -----------------------------------------------------------------

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

        let dir = tempfile::tempdir().expect("tempdir");
        let escape = tempfile::tempdir().expect("escape tempdir");
        // Plant an "operator owned" file inside the escape tree so we can
        // assert it stays unmodified after the refusal.
        std::fs::write(escape.path().join("AGENTS.md"), b"operator owned")
            .expect("seed escape file");

        // <tempdir>/sub -> <escape>/  (directory symlink)
        let sub = dir.path().join("sub");
        symlink(escape.path(), &sub).expect("plant parent symlink");

        // Attempt to write through the symlinked parent. Must refuse.
        let target = sub.join("AGENTS.md");
        let err =
            safe_write(&target, b"attacker bytes").expect_err("must refuse symlinked parent");
        let refusal = err
            .get_ref()
            .and_then(|e| e.downcast_ref::<SymlinkRefusal>())
            .expect("error must carry SymlinkRefusal");
        // The refusal must name the ANCESTOR (the symlink itself), NOT
        // the original target — this is how operators identify which
        // directory is hijacked.
        assert_eq!(
            refusal.path, sub,
            "refusal must name the symlinked ancestor, not the leaf"
        );

        // Operator file untouched.
        assert_eq!(
            std::fs::read(escape.path().join("AGENTS.md")).expect("read escape file"),
            b"operator owned",
            "operator-owned file must NOT be overwritten through the symlink"
        );
    }

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

        let dir = tempfile::tempdir().expect("tempdir");
        let escape = tempfile::tempdir().expect("escape tempdir");
        // Pre-create a subdirectory inside the escape tree — this becomes
        // the *grandparent* of the eventual target once it's reached
        // through the symlink.
        std::fs::create_dir(escape.path().join("inner")).expect("seed escape/inner");

        // <tempdir>/junction -> <escape>/  (directory symlink, two levels
        // above the target)
        let junction = dir.path().join("junction");
        symlink(escape.path(), &junction).expect("plant grandparent symlink");

        // Target lives two levels under the symlinked ancestor.
        let target = junction.join("inner").join("pack.json");
        let err = safe_write(&target, b"attacker")
            .expect_err("must refuse when any ancestor (not just parent) is a symlink");
        let refusal = err
            .get_ref()
            .and_then(|e| e.downcast_ref::<SymlinkRefusal>())
            .expect("error must carry SymlinkRefusal");
        assert_eq!(
            refusal.path, junction,
            "refusal must name the symlinked grandparent"
        );

        // Nothing should have landed inside the escape tree.
        assert!(
            !escape.path().join("inner").join("pack.json").exists(),
            "no file may be written through the symlinked ancestor"
        );
    }

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

        let dir = tempfile::tempdir().expect("tempdir");
        let escape = tempfile::tempdir().expect("escape tempdir");

        // <tempdir>/.cordance -> <escape>/  (the classic R6 attack:
        // attacker plants the helper's intended write directory as a
        // symlink to operator-owned storage).
        let dotcordance = dir.path().join(".cordance");
        symlink(escape.path(), &dotcordance).expect("plant .cordance symlink");

        // Snapshot the contents of `escape` BEFORE the attempted write —
        // we need to prove `create_dir_all` did NOT run through the
        // symlink. (`create_dir_all` of an existing dir is a no-op, but
        // any deeper paths under the symlinked parent would be visible
        // in the escape tree.)
        let target = dotcordance.join("nested").join("pack.json");
        let err = safe_write_with_mkdir(&target, b"attacker")
            .expect_err("must refuse symlinked parent BEFORE create_dir_all");
        let refusal = err
            .get_ref()
            .and_then(|e| e.downcast_ref::<SymlinkRefusal>())
            .expect("error must carry SymlinkRefusal");
        assert_eq!(
            refusal.path, dotcordance,
            "refusal must name the symlinked parent"
        );

        // The symlink target (escape tree) must still be empty — proves
        // `create_dir_all` did not run through the symlink.
        let entries: Vec<_> = std::fs::read_dir(escape.path())
            .expect("read escape")
            .collect();
        assert!(
            entries.is_empty(),
            "create_dir_all MUST NOT have run through the symlinked parent; \
             escape tree must be empty, found: {entries:?}"
        );
    }

    #[cfg(windows)]
    #[test]
    fn safe_write_refuses_when_parent_dir_is_junction() {
        // Windows directory junctions are reparse points but NOT symlinks
        // per `is_symlink()`; they are exactly the surface a hostile
        // target uses to redirect `.cordance/` on Windows. Junctions can
        // be created without Developer Mode via `cmd /c mklink /J` (or
        // `std::os::windows::fs::symlink_dir` if the privilege is held).
        // Try the privileged API first, fall back to mklink.
        use std::os::windows::fs::symlink_dir;
        use std::process::Command;

        let dir = tempfile::tempdir().expect("tempdir");
        let escape = tempfile::tempdir().expect("escape tempdir");
        std::fs::write(escape.path().join("operator.txt"), b"operator owned")
            .expect("seed escape file");

        // Plant <tempdir>/.cordance as a junction to <escape>/.
        let dotcordance = dir.path().join(".cordance");
        if symlink_dir(escape.path(), &dotcordance).is_err() {
            // No privilege — fall back to mklink /J (always available).
            let status = Command::new("cmd")
                .args([
                    "/C",
                    "mklink",
                    "/J",
                    dotcordance.to_str().expect("utf8 junction path"),
                    escape.path().to_str().expect("utf8 escape path"),
                ])
                .status();
            let Ok(status) = status else {
                eprintln!("skipping: cmd.exe unavailable");
                return;
            };
            if !status.success() {
                eprintln!("skipping: mklink /J failed");
                return;
            }
        }

        let target = dotcordance.join("pack.json");
        let err = safe_write_with_mkdir(&target, b"attacker")
            .expect_err("must refuse junction-redirected parent");
        let refusal = err
            .get_ref()
            .and_then(|e| e.downcast_ref::<SymlinkRefusal>())
            .expect("error must carry SymlinkRefusal");
        assert_eq!(
            refusal.path, dotcordance,
            "refusal must name the junction, not the leaf"
        );

        // Operator file untouched.
        assert_eq!(
            std::fs::read(escape.path().join("operator.txt")).expect("read operator file"),
            b"operator owned",
            "operator-owned file must NOT be overwritten through the junction"
        );
        // The leaf must NOT exist in the escape tree.
        assert!(
            !escape.path().join("pack.json").exists(),
            "attacker bytes must NOT have been written through the junction"
        );
    }

    #[test]
    fn safe_write_accepts_clean_ancestors() {
        // Deeply nested path with NO reparse points anywhere in the
        // chain. `safe_write_with_mkdir` must create the parents and
        // write the file — the round-6 ancestor walk must NOT regress
        // the round-5 happy path.
        let dir = tempfile::tempdir().expect("tempdir");
        let deep = dir
            .path()
            .join("a")
            .join("b")
            .join("c")
            .join("d")
            .join("e")
            .join("pack.json");
        assert!(
            !deep.parent().expect("has parent").exists(),
            "precondition: deep parent must not exist"
        );
        safe_write_with_mkdir(&deep, b"{\"ok\":true}")
            .expect("clean ancestor chain must succeed");
        assert_eq!(
            std::fs::read(&deep).expect("read back"),
            b"{\"ok\":true}",
            "bytes must round-trip through clean ancestor chain"
        );
    }

    #[test]
    fn safe_write_accepts_real_directory_overwrite() {
        // Parent pre-exists as a real directory; helper must overwrite
        // the file inside without false-positive reparse-point refusal.
        let dir = tempfile::tempdir().expect("tempdir");
        let parent = dir.path().join(".cordance");
        std::fs::create_dir(&parent).expect("seed real parent dir");
        let target = parent.join("pack.json");
        std::fs::write(&target, b"old").expect("seed existing file");

        safe_write_with_mkdir(&target, b"new").expect("real-dir overwrite must succeed");
        assert_eq!(std::fs::read(&target).expect("read"), b"new");
    }
}