cordance-core 0.1.1

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
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
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
//! 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.
//!
//! # Cross-platform ancestor-walk contract
//!
//! The walk in [`find_reparse_point_ancestor`] is the same shape on every
//! platform — pop via `Path::parent()` until None — but the **stopping
//! conditions** differ:
//!
//! - **POSIX:** the walk pops cleanly to `/` and then to None. Every
//!   ancestor (including `/`) is a real filesystem entry; the leaf check
//!   either fires on a hostile symlink/junction or returns None at the
//!   root.
//! - **Windows verbatim / UNC prefixes:** `Path::parent()` ascends through
//!   non-filesystem prefix shapes — `\\?\C:`, `\\?\`, `\\`, `\\server` —
//!   that `symlink_metadata` cannot resolve. Round-8 redteam #2: a hostile
//!   junction planted at a leaf under `\\?\C:\…` was silently passed by
//!   the round-6 walk because every prefix component returned `Err` from
//!   `symlink_metadata`, and `is_reparse_point` falls through to `false`
//!   on metadata failure. The walk now detects these prefix shapes via
//!   [`is_unc_or_extended_length_prefix`] and stops cleanly — the leaf
//!   checks below the prefix already caught any reparse-point in the
//!   real filesystem portion of the path.
//!
//! Operators relying on the helper as a single point of refusal should
//! still apply `dunce::canonicalize` at the CLI boundary (main.rs)
//! whenever possible: that strips `\\?\` and yields drive-letter form,
//! which gives the walk a fully-resolvable ancestor chain. The
//! prefix-aware stop is defence-in-depth for callers (e.g. MCP tools)
//! that route raw target-supplied paths past the CLI canonicaliser.

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

/// 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.
///
/// The `Display` impl carries the **ancestor path** that triggered the
/// refusal, NOT the original target — operators reading
/// `cordance: emitter '…' failed\n  caused by: …` can identify which
/// directory in the chain is symlinked. Round-8 redteam #4: the previous
/// shape was wrapped by `anyhow::Context` such that the chain printer
/// dropped the `SymlinkRefusal` Display in favour of the kernel
/// `(os error 5)` message; the helper [`extract_symlink_refusal`] walks
/// an `anyhow::Error` chain and surfaces the structured refusal even when
/// `with_context` is layered on top.
#[derive(Debug, thiserror::Error)]
#[error("refusing to write through symlink/reparse-point at {}", path.display())]
pub struct SymlinkRefusal {
    pub path: PathBuf,
}

/// Walk the `source()` chain of an `Error` and return the first refusal.
///
/// Returns the first [`SymlinkRefusal`] found, or `None` if none of the
/// wrapped errors is a symlink refusal. Useful at the CLI / MCP boundary
/// where a generic `anyhow::Context` wrap would otherwise hide the
/// structured payload behind a kernel `(os error 5)` line.
///
/// `cordance-core` stays pure types/schemas/ports — this helper accepts a
/// `&dyn std::error::Error` rather than `&anyhow::Error` so the core has
/// no dependency on the anyhow surface. Callers holding an
/// `anyhow::Error` pass it via `err.as_ref()` (anyhow implements
/// `AsRef<dyn Error + 'static>`) or via `err.deref()`; the resulting
/// `&dyn Error::source()` walk visits the same chain `anyhow::Error::chain()`
/// would.
///
/// Round-8 redteam #4: `dispatch_emitters` uses `.with_context(...)?` on
/// emitter failures; the resulting `anyhow::Error::to_string()` only
/// renders the outermost context, and the default `{err:#}` chain printer
/// walks `Error::source()` — which on `io::Error::other(custom)` returns
/// the custom error's *source* (None), not its `Display`. The refusal's
/// Display, including the ancestor path, is thereby lost. Callers should
/// reach for this helper before printing so the operator sees the
/// junction path that triggered the refusal.
#[must_use]
pub fn extract_symlink_refusal<'a>(
    err: &'a (dyn std::error::Error + 'static),
) -> Option<&'a SymlinkRefusal> {
    let mut current: Option<&(dyn std::error::Error + 'static)> = Some(err);
    while let Some(cause) = current {
        // Direct hit: the cause IS a SymlinkRefusal.
        if let Some(refusal) = cause.downcast_ref::<SymlinkRefusal>() {
            return Some(refusal);
        }
        // Wrapped hit: the cause is an `io::Error` whose inner payload is
        // `SymlinkRefusal` (the shape `safe_write` returns via
        // `io::Error::other(SymlinkRefusal { ... })`).
        if let Some(io_err) = cause.downcast_ref::<std::io::Error>() {
            if let Some(inner) = io_err.get_ref() {
                if let Some(refusal) = inner.downcast_ref::<SymlinkRefusal>() {
                    return Some(refusal);
                }
            }
        }
        current = cause.source();
    }
    None
}

/// Return `true` when the first component of `path` is a Windows
/// verbatim / extended-length / UNC prefix shape that does not denote a
/// real filesystem directory.
///
/// Round-8 redteam #2: `Path::parent()` on a `\\?\C:\…` path ascends
/// through `\\?\C:`, `\\?\`, `\\` — none of which `symlink_metadata` can
/// resolve. The ancestor walk would silently pass any reparse-point
/// ancestor at or below that prefix because `is_reparse_point` falls
/// through to `false` on metadata failure. The walk uses this helper to
/// stop cleanly when it pops into the prefix region (the leaf checks
/// below the prefix already caught any real-filesystem reparse-point).
///
/// On non-Windows the function always returns `false` — POSIX paths do
/// not have these prefix shapes.
fn is_unc_or_extended_length_prefix(p: &Path) -> bool {
    let Some(first) = p.components().next() else {
        return false;
    };
    let std::path::Component::Prefix(prefix) = first else {
        return false;
    };
    // Only the **prefix-only** ancestors are stop-points: the original
    // path `\\?\C:\Users\foo\bar.txt` has a Prefix component as its
    // first component too, but it's followed by RootDir + Normal
    // components, which `Path::parent()` strips off cleanly until only
    // the prefix remains. We stop only when `p` is a *bare* prefix —
    // i.e. has no RootDir/Normal components past the Prefix.
    //
    // We detect "bare prefix" by checking that NO `Normal` (named segment)
    // component appears past the prefix. `Path::components()` yields
    // Prefix → RootDir → Normal+ for a fully-qualified path. The trailing
    // RootDir is a structural sentinel (`\\?\C:\` has Prefix + RootDir but
    // no Normal — it IS the bare prefix), so we only return `false` when
    // a real named segment appears past the prefix/root.
    let has_named_segment = p
        .components()
        .any(|c| matches!(c, std::path::Component::Normal(_)));
    if has_named_segment {
        return false;
    }
    matches!(
        prefix.kind(),
        Prefix::Verbatim(_)
            | Prefix::VerbatimUNC(_, _)
            | Prefix::VerbatimDisk(_)
            | Prefix::UNC(_, _)
            | Prefix::DeviceNS(_)
    )
}

/// 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`) OR at the first Windows verbatim / UNC
/// prefix ancestor — those are not real filesystem directories, so
/// `symlink_metadata` cannot probe them and continuing past them yields
/// only false-negatives (round-8 redteam #2).
fn find_reparse_point_ancestor(path: &Path) -> Option<PathBuf> {
    let mut cur: Option<&Path> = Some(path);
    while let Some(p) = cur {
        // Round-8 redteam #2: stop cleanly at Windows verbatim / UNC
        // prefixes. `Path::parent()` on `\\?\C:\Users\foo\bar.txt`
        // ascends through `\\?\C:`, `\\?\`, `\\` — none of which is a
        // real filesystem directory. `symlink_metadata` errors on those
        // shapes, `is_reparse_point` returns false on metadata error, so
        // continuing past them would only generate false-negative
        // syscalls. The leaf checks below the prefix already caught any
        // reparse-point in the resolvable portion of the path.
        if is_unc_or_extended_length_prefix(p) {
            return None;
        }
        // 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
}

/// Public pre-check helper: scan the ancestor chain of `path` for
/// reparse points and return `Err` carrying a [`SymlinkRefusal`] for the
/// offending ancestor (if any), or `Ok(())` if the chain is clean.
///
/// Round-8 redteam #1: callers that batch-render multiple emitter outputs
/// can pre-check every destination BEFORE any `safe_write` runs, so the
/// "emitter 1 writes, emitter 2 refuses, disk in inconsistent partial
/// state" race is avoided. The CLI dispatcher uses this to fail the whole
/// batch loudly before committing any I/O.
///
/// # Errors
///
/// Returns the same `Err` shape `safe_write` returns when the destination
/// has a reparse-point ancestor: an `std::io::Error` whose inner custom
/// payload is `SymlinkRefusal { path: ancestor }`. Callers can downcast
/// or use [`extract_symlink_refusal`] on the wrapped chain to surface
/// the ancestor path.
pub fn precheck_no_reparse_point_ancestor(path: &Path) -> std::io::Result<()> {
    if let Some(ancestor) = find_reparse_point_ancestor(path) {
        return Err(std::io::Error::other(SymlinkRefusal { path: ancestor }));
    }
    Ok(())
}

/// 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");
    }

    // -----------------------------------------------------------------
    // Round-8 redteam #2: UNC + `\\?\` extended-length prefix walks.
    //
    // `Path::parent()` on `\\?\C:\…` ascends through `\\?\C:`, `\\?\`,
    // `\\` — none of which is a real filesystem directory. Round-6's
    // walk used `symlink_metadata`, which errors on those shapes;
    // `is_reparse_point` returns false on metadata-error and the walk
    // silently passed any reparse-point ancestor at or below those
    // prefixes. The walk now stops cleanly via
    // `is_unc_or_extended_length_prefix`.
    // -----------------------------------------------------------------

    #[cfg(windows)]
    #[test]
    fn ancestor_walk_terminates_on_verbatim_prefix() {
        // Construct a `\\?\C:\<tempdir>\file.txt` path. The walk must
        // terminate cleanly (no infinite loop, no panic) and — since the
        // tempdir itself is a real dir, NOT a reparse point — return
        // None. The historical bug was that the walk would pass through
        // `\\?\C:`, `\\?\`, `\\` without finding a reparse point AND
        // without false-positive-passing a planted reparse-point in the
        // real-path region of the chain.
        let dir = tempfile::tempdir().expect("tempdir");
        let std_path = dir.path();
        // Build a verbatim-prefix shape against the real path. dunce
        // strips verbatim prefixes; we want to keep one, so construct
        // by hand. Most tempdirs are already canonicalised under
        // `C:\Users\<user>\AppData\Local\Temp\<rand>`; prefix with
        // `\\?\`.
        let s = std_path.to_string_lossy();
        let verbatim = if s.starts_with("\\\\?\\") {
            std_path.to_path_buf()
        } else {
            std::path::PathBuf::from(format!("\\\\?\\{s}"))
        };
        let target = verbatim.join("file.txt");

        // Pre-create the file inside the tempdir so there's a real
        // ancestor chain to walk.
        std::fs::write(std_path.join("file.txt"), b"clean").expect("seed");

        // The walk must not panic / infinite-loop and must return None
        // (no reparse point planted anywhere in the chain).
        let result = find_reparse_point_ancestor(&target);
        assert!(
            result.is_none(),
            "clean verbatim-prefix chain must return None; got {result:?}"
        );
    }

    #[cfg(windows)]
    #[test]
    fn ancestor_walk_detects_reparse_under_verbatim_prefix() {
        // Plant `<tempdir>/.cordance` as a junction (reparse point).
        // Walk a `\\?\C:\<tempdir>\.cordance\pack.json` path: the walk
        // must catch the junction (the resolvable portion of the chain
        // contains a real reparse point) and refuse, rather than
        // passing through to the prefix and returning None.
        use std::os::windows::fs::symlink_dir;
        use std::process::Command;

        let dir = tempfile::tempdir().expect("tempdir");
        let escape = tempfile::tempdir().expect("escape tempdir");
        let dotcordance = dir.path().join(".cordance");
        if symlink_dir(escape.path(), &dotcordance).is_err() {
            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 s = dir.path().to_string_lossy();
        let verbatim_root = if s.starts_with("\\\\?\\") {
            dir.path().to_path_buf()
        } else {
            std::path::PathBuf::from(format!("\\\\?\\{s}"))
        };
        let target = verbatim_root.join(".cordance").join("pack.json");

        // The walk must catch the junction in the resolvable region.
        let result = find_reparse_point_ancestor(&target);
        assert!(
            result.is_some(),
            "junction-redirected verbatim-prefix path must be refused; got None"
        );
    }

    #[cfg(windows)]
    #[test]
    fn is_unc_prefix_detects_bare_verbatim_disk() {
        // `\\?\C:` (bare verbatim-disk prefix) must be detected.
        let p = std::path::PathBuf::from("\\\\?\\C:");
        assert!(
            is_unc_or_extended_length_prefix(&p),
            "bare \\\\?\\C: must be detected as a stop-point prefix"
        );
    }

    #[cfg(windows)]
    #[test]
    fn is_unc_prefix_does_not_match_real_paths() {
        // `\\?\C:\Users\foo` (real verbatim path with components past
        // the prefix) MUST NOT match — the walk should proceed normally
        // until it pops off the components and reaches the bare prefix.
        let p = std::path::PathBuf::from("\\\\?\\C:\\Users\\foo");
        assert!(
            !is_unc_or_extended_length_prefix(&p),
            "real \\\\?\\C:\\Users\\foo must NOT be a stop-point (has components past prefix)"
        );
    }

    #[cfg(windows)]
    #[test]
    fn is_unc_prefix_detects_bare_unc_share() {
        // `\\server\share` (bare UNC share) must be detected.
        let p = std::path::PathBuf::from("\\\\server\\share");
        assert!(
            is_unc_or_extended_length_prefix(&p),
            "bare \\\\server\\share must be detected as a stop-point prefix"
        );
    }

    #[cfg(not(windows))]
    #[test]
    fn is_unc_prefix_returns_false_on_posix() {
        // POSIX paths have no Prefix component; the helper must always
        // return false. (We exercise this on non-Windows to confirm the
        // function is not accidentally Windows-only.)
        let p = std::path::PathBuf::from("/tmp/foo/bar");
        assert!(
            !is_unc_or_extended_length_prefix(&p),
            "POSIX paths must never be classified as UNC/verbatim"
        );
        let bare = std::path::PathBuf::from("/");
        assert!(
            !is_unc_or_extended_length_prefix(&bare),
            "POSIX root must never be classified as UNC/verbatim"
        );
    }

    // -----------------------------------------------------------------
    // Round-8 redteam #4: `extract_symlink_refusal` walks an
    // `anyhow::Error` chain (including `.with_context` wraps) and
    // surfaces the structured `SymlinkRefusal` payload that the default
    // chain printer would otherwise drop in favour of the kernel
    // `(os error 5)` line.
    // -----------------------------------------------------------------

    #[test]
    fn extract_symlink_refusal_finds_direct_refusal() {
        // The error is a direct SymlinkRefusal — no wrapping. The helper
        // must surface it.
        let refusal = SymlinkRefusal {
            path: std::path::PathBuf::from("/tmp/junction"),
        };
        let extracted = extract_symlink_refusal(&refusal);
        assert!(extracted.is_some(), "direct refusal must be extractable");
        assert_eq!(
            extracted.expect("some").path,
            std::path::PathBuf::from("/tmp/junction")
        );
    }

    #[test]
    fn extract_symlink_refusal_finds_io_wrapped_refusal() {
        // The error is `io::Error::other(SymlinkRefusal)` — the shape
        // `safe_write` returns. The helper must downcast through the
        // io::Error layer.
        let refusal = SymlinkRefusal {
            path: std::path::PathBuf::from("/tmp/.cordance"),
        };
        let io_err = std::io::Error::other(refusal);
        let extracted =
            extract_symlink_refusal(&io_err).expect("io-wrapped refusal must be extractable");
        assert_eq!(extracted.path, std::path::PathBuf::from("/tmp/.cordance"));
    }

    /// Local error wrapper used to model an `anyhow::Context`-style chain
    /// without taking a hard dep on `anyhow` in `cordance-core`. The CLI
    /// side (which DOES use anyhow) gets its own end-to-end test in
    /// `cordance-cli/src/pack_cmd.rs`.
    #[derive(Debug)]
    struct WithContext<E: std::error::Error + 'static> {
        msg: &'static str,
        source: E,
    }

    impl<E: std::error::Error + 'static> std::fmt::Display for WithContext<E> {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
            f.write_str(self.msg)
        }
    }

    impl<E: std::error::Error + 'static> std::error::Error for WithContext<E> {
        fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
            Some(&self.source)
        }
    }

    #[test]
    fn extract_symlink_refusal_walks_context_chain() {
        // Model the `with_context` shape: a context wrapper around an
        // io::Error wrapping a SymlinkRefusal. The helper must walk the
        // `source()` chain past the context layer.
        let refusal = SymlinkRefusal {
            path: std::path::PathBuf::from("/tmp/.cordance"),
        };
        let io_err = std::io::Error::other(refusal);
        let wrapped = WithContext {
            msg: "emitter 'claude-code:claude-md' failed",
            source: io_err,
        };
        let extracted =
            extract_symlink_refusal(&wrapped).expect("must extract through context chain");
        assert_eq!(extracted.path, std::path::PathBuf::from("/tmp/.cordance"));
    }

    #[test]
    fn extract_symlink_refusal_returns_none_for_unrelated_error() {
        let err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "nope");
        assert!(extract_symlink_refusal(&err).is_none());
    }

    #[test]
    fn symlink_refusal_display_includes_ancestor_path() {
        // The Display impl must contain the ancestor path (operator-
        // diagnosable). Round-7 dropped this via `with_context` wrapping;
        // round-8 ensures the path is visible at the source.
        let refusal = SymlinkRefusal {
            path: std::path::PathBuf::from("/tmp/.cordance"),
        };
        let rendered = format!("{refusal}");
        assert!(
            rendered.contains("/tmp/.cordance") || rendered.contains("\\tmp\\.cordance"),
            "Display must include ancestor path; got: {rendered}"
        );
        assert!(
            rendered.contains("symlink") || rendered.contains("reparse-point"),
            "Display must indicate the refusal class; got: {rendered}"
        );
    }

    #[test]
    fn precheck_returns_ok_for_clean_path() {
        // Public pre-check helper for the round-8 redteam #1 batch
        // dispatch: must return Ok for a path whose ancestor chain has
        // no reparse points. (The same path safe_write would accept.)
        let dir = tempfile::tempdir().expect("tempdir");
        let target = dir.path().join("a").join("b").join("out.json");
        precheck_no_reparse_point_ancestor(&target).expect("clean path must pre-check OK");
    }

    #[cfg(unix)]
    #[test]
    fn precheck_returns_err_for_symlinked_ancestor() {
        use std::os::unix::fs::symlink;
        let dir = tempfile::tempdir().expect("tempdir");
        let escape = tempfile::tempdir().expect("escape");
        let dotcordance = dir.path().join(".cordance");
        symlink(escape.path(), &dotcordance).expect("plant symlink");
        let target = dotcordance.join("pack.json");
        let err = precheck_no_reparse_point_ancestor(&target)
            .expect_err("planted symlink must fail pre-check");
        let refusal = err
            .get_ref()
            .and_then(|e| e.downcast_ref::<SymlinkRefusal>())
            .expect("pre-check err must carry SymlinkRefusal");
        assert_eq!(refusal.path, dotcordance);
    }
}