ferrocrypt 0.3.0-rc.1

Recipient-oriented file and directory encryption: passphrase (Argon2id) and X25519 public-key recipients, XChaCha20-Poly1305 STREAM payloads, HKDF-SHA3-256 / HMAC-SHA3-256 key derivation and authentication.
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
//! FCA path grammar — the single shared writer/reader validator.
//!
//! See `ferrocrypt-lib/FORMAT.md` §9.6 (path grammar) and §9.10
//! (writer obligations — same TLV / path canonicality on both sides).
//!
//! The writer/reader symmetry guarantee is satisfied by having a
//! single function — [`validate_fca_path`] — called from both encode
//! and decode paths. There is no separate writer-side and reader-side
//! validator to drift apart.

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

use crate::CryptoError;
use crate::error::sanitize_for_display;
use crate::fs::paths::INCOMPLETE_SUFFIX;

use super::limits::{
    ARCHIVE_PATH_EMPTY, ArchiveLimits, component_count, enforce_path_bytes_cap,
    enforce_path_depth_cap,
};

/// Bytes that cannot appear in any FCA path component on any platform
/// FerroCrypt targets. The Windows-reserved set per FORMAT.md §9.6; rejecting
/// these on every platform makes a valid FCA path representable
/// everywhere FerroCrypt runs.
const WINDOWS_RESERVED_CHARS: &[u8] = b"<>:\"|?*";

/// The 255-byte filename limit shared by the filesystems FerroCrypt
/// targets (ext4, XFS, APFS, NTFS).
const FILESYSTEM_NAME_MAX_BYTES: usize = 255;

/// Maximum UTF-8 byte length of a single FCA path component per
/// FORMAT.md §9.6: the filesystem name limit minus room for the
/// `.incomplete` staging suffix extraction appends to the root
/// component (§9.11 step 10). Without the reserve, a near-limit root
/// name would archive fine and then fail to extract because its
/// working name exceeds what the filesystem can create.
pub const FCA_COMPONENT_MAX_BYTES: usize = FILESYSTEM_NAME_MAX_BYTES - INCOMPLETE_SUFFIX.len();

/// Rejection reason for an over-long component. Kept next to
/// [`FCA_COMPONENT_MAX_BYTES`]; a unit test pins the embedded number
/// to the constant so the two cannot drift.
pub(super) const COMPONENT_TOO_LONG: &str = "component exceeds 244 bytes";

/// Validates an FCA archive path against the FORMAT.md §9.6 grammar.
/// Same function called by encode-side metadata-pass and decode-side
/// manifest-parse — the single shared implementation IS the writer /
/// reader symmetry guarantee.
///
/// Caller has already passed `limits` through
/// `ArchiveLimits::validate`; we don't re-run that check here.
pub fn validate_fca_path(path: &str, limits: ArchiveLimits) -> Result<(), CryptoError> {
    if path.is_empty() {
        return Err(CryptoError::MalformedArchive {
            reason: ARCHIVE_PATH_EMPTY,
        });
    }
    enforce_path_bytes_cap(
        u32::try_from(path.len()).unwrap_or(u32::MAX),
        Some(path),
        &limits,
    )?;
    let bytes = path.as_bytes();
    if bytes[0] == b'/' {
        return Err(unsafe_path(path, "absolute"));
    }
    if bytes[bytes.len() - 1] == b'/' {
        return Err(unsafe_path(path, "trailing slash"));
    }
    if bytes.contains(&0) {
        return Err(unsafe_path(path, "contains NUL byte"));
    }
    if bytes.contains(&b'\\') {
        return Err(unsafe_path(path, "contains backslash"));
    }
    if bytes.windows(2).any(|w| w == b"//") {
        return Err(unsafe_path(path, "repeated slash separators"));
    }

    enforce_path_depth_cap(path, &limits)?;

    for component in path.split('/') {
        validate_fca_component(component, path)?;
    }

    // Defense-in-depth: walk the host `Path::components()` and reject
    // any kind that is not `Normal`. The `/`-split component checks
    // above already cover `.` and `..`, but a future host-`Path`
    // tweak (e.g., a Windows `Prefix` parsed from a path that snuck
    // past the byte-level checks) would still surface here.
    for component in Path::new(path).components() {
        match component {
            Component::Normal(_) => {}
            Component::RootDir
            | Component::Prefix(_)
            | Component::CurDir
            | Component::ParentDir => {
                return Err(unsafe_path(path, "non-normal host path component"));
            }
        }
    }

    Ok(())
}

/// Builds the [`CryptoError::UnsafeArchivePath`] rejection with the
/// offending path sanitized for display. Single construction point so
/// every grammar arm embeds the path the same way.
fn unsafe_path(path: &str, reason: &'static str) -> CryptoError {
    CryptoError::UnsafeArchivePath {
        path: sanitize_for_display(path),
        reason,
    }
}

/// Validates a single `/`-delimited path component per FORMAT.md §9.6.
/// `path` is the full entry path, threaded through for the rejection
/// payload only.
fn validate_fca_component(component: &str, path: &str) -> Result<(), CryptoError> {
    if component.is_empty() || component == "." || component == ".." {
        return Err(unsafe_path(path, "forbidden component"));
    }
    if component.len() > FCA_COMPONENT_MAX_BYTES {
        return Err(unsafe_path(path, COMPONENT_TOO_LONG));
    }

    let b = component.as_bytes();
    if b.iter().any(|&c| c <= 0x1f) {
        return Err(unsafe_path(path, "contains ASCII control byte"));
    }
    if b.iter().any(|c| WINDOWS_RESERVED_CHARS.contains(c)) {
        return Err(unsafe_path(path, "contains a Windows-reserved character"));
    }
    if b.last() == Some(&b' ') {
        return Err(unsafe_path(path, "component ends with space"));
    }
    if b.last() == Some(&b'.') {
        return Err(unsafe_path(path, "component ends with dot"));
    }
    if is_windows_reserved_device_component(component) {
        return Err(unsafe_path(path, "Windows-reserved device name"));
    }
    Ok(())
}

/// ASCII-only lowercase. Multi-byte UTF-8 bytes (anything `>= 0x80`)
/// pass through unchanged, which is intentional per FORMAT.md §9.6: the
/// reserved-device check is ASCII-only, not Unicode-folded.
fn ascii_lower_byte(b: u8) -> u8 {
    if b.is_ascii_uppercase() { b + 32 } else { b }
}

/// Returns `true` if the component's pre-extension stem matches a
/// Windows reserved device name under ASCII-case-insensitive
/// comparison. The stem is the substring before the first `.`; if there
/// is no `.`, the whole component is the stem. This catches both bare
/// names (`CON`) and stems-with-extension (`CON.txt`, `LPT9.bin`).
///
/// The superscript forms (`COM¹`, `LPT²`, …) are matched on their
/// exact UTF-8 bytes: `¹ ² ³` have no ASCII case and pass through
/// [`ascii_lower_byte`] unchanged, so byte comparison is exact per
/// FORMAT.md §9.6.
fn is_windows_reserved_device_component(component: &str) -> bool {
    // Windows resolves a name to a device by taking the text before the
    // first `.` and then stripping trailing spaces, so `AUX .txt` is the
    // AUX device. Match that: cut at the first `.`, then drop trailing
    // spaces before comparing.
    let stem = component
        .split_once('.')
        .map_or(component, |(stem, _)| stem)
        .trim_end_matches(' ');
    let stem_bytes = stem.as_bytes();

    // All reserved device-name stems are 3..=7 bytes (`CONOUT$` is
    // the longest; the superscript forms are 5 bytes as UTF-8);
    // longer stems cannot match. The early return also keeps the
    // stack buffer sizing exact.
    if stem_bytes.is_empty() || stem_bytes.len() > 7 {
        return false;
    }

    // Stack buffer avoids an allocation per component check on the
    // common no-match path. ascii_lower_byte folds the ASCII letters
    // and leaves the superscript UTF-8 bytes unchanged.
    let mut buf = [0u8; 7];
    for (i, &b) in stem_bytes.iter().enumerate() {
        buf[i] = ascii_lower_byte(b);
    }
    let lower = &buf[..stem_bytes.len()];

    matches!(
        lower,
        b"con"
            | b"prn"
            | b"aux"
            | b"nul"
            | b"clock$"
            | b"conin$"
            | b"conout$"
            | b"com0"
            | b"com1"
            | b"com2"
            | b"com3"
            | b"com4"
            | b"com5"
            | b"com6"
            | b"com7"
            | b"com8"
            | b"com9"
            | b"com\xc2\xb9" // COM¹
            | b"com\xc2\xb2" // COM²
            | b"com\xc2\xb3" // COM³
            | b"lpt0"
            | b"lpt1"
            | b"lpt2"
            | b"lpt3"
            | b"lpt4"
            | b"lpt5"
            | b"lpt6"
            | b"lpt7"
            | b"lpt8"
            | b"lpt9"
            | b"lpt\xc2\xb9" // LPT¹
            | b"lpt\xc2\xb2" // LPT²
            | b"lpt\xc2\xb3" // LPT³
    )
}

/// ASCII-case-insensitive collision key per FORMAT.md §9.7. Maps `A..Z` to
/// `a..z`; everything else (digits, punctuation, multi-byte UTF-8)
/// passes through unchanged. Used by tree.rs to detect paths like
/// `Foo.txt` vs `FOO.TXT` that would collide on a case-insensitive
/// filesystem before the platform backend's `create_new(true)` check
/// could surface the conflict.
pub fn ascii_case_collision_key(path: &str) -> Vec<u8> {
    path.bytes().map(ascii_lower_byte).collect()
}

/// FORMAT.md §9.8 canonical sort key: depth ascending, then path
/// bytes ascending. Used by the writer's full-manifest sort and the
/// reader's directory pre-creation pass so the two sites cannot
/// drift on what "canonical order" means.
pub(super) fn canonical_path_order(a: &str, b: &str) -> std::cmp::Ordering {
    component_count(a)
        .cmp(&component_count(b))
        .then_with(|| a.cmp(b))
}

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

    fn limits() -> ArchiveLimits {
        ArchiveLimits::default()
    }

    // -- Positive cases -----------------------------------------------------

    #[test]
    fn accepts_simple_file() {
        assert!(validate_fca_path("file.txt", limits()).is_ok());
    }

    #[test]
    fn accepts_nested_path() {
        assert!(validate_fca_path("dir/sub/file.txt", limits()).is_ok());
    }

    #[test]
    fn accepts_mixed_case() {
        assert!(validate_fca_path("Some/Mixed/Case.TXT", limits()).is_ok());
    }

    #[test]
    fn accepts_non_ascii() {
        assert!(validate_fca_path("naïve.txt", limits()).is_ok());
        assert!(validate_fca_path("résumé/notes.md", limits()).is_ok());
    }

    #[test]
    fn accepts_emoji() {
        assert!(validate_fca_path("🎉.txt", limits()).is_ok());
    }

    /// `.foo` (hidden file on Unix) has empty stem — empty stem is
    /// not a reserved device name, so accepted.
    #[test]
    fn accepts_dotfile() {
        assert!(validate_fca_path(".gitignore", limits()).is_ok());
        assert!(validate_fca_path(".env", limits()).is_ok());
    }

    /// `auxiliary.txt` shares a prefix with `aux` but the stem is
    /// 9 bytes — over the 6-byte fast-path cap, so it cannot match.
    #[test]
    fn accepts_long_stem_that_starts_with_reserved_prefix() {
        assert!(validate_fca_path("auxiliary.txt", limits()).is_ok());
        assert!(validate_fca_path("conditional.md", limits()).is_ok());
    }

    // -- Whole-path rejections (FORMAT.md §9.6) ----------------------------

    #[test]
    fn rejects_empty() {
        let err = validate_fca_path("", limits()).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::MalformedArchive {
                reason: ARCHIVE_PATH_EMPTY
            }
        ));
    }

    #[test]
    fn rejects_leading_slash() {
        let err = validate_fca_path("/etc/passwd", limits()).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::UnsafeArchivePath {
                reason: "absolute",
                ..
            }
        ));
    }

    #[test]
    fn rejects_trailing_slash() {
        let err = validate_fca_path("dir/", limits()).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::UnsafeArchivePath {
                reason: "trailing slash",
                ..
            }
        ));
    }

    #[test]
    fn rejects_double_slash() {
        let err = validate_fca_path("a//b", limits()).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::UnsafeArchivePath {
                reason: "repeated slash separators",
                ..
            }
        ));
    }

    #[test]
    fn rejects_nul_byte() {
        let err = validate_fca_path("a\0b", limits()).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::UnsafeArchivePath {
                reason: "contains NUL byte",
                ..
            }
        ));
    }

    #[test]
    fn rejects_backslash() {
        let err = validate_fca_path("a\\b", limits()).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::UnsafeArchivePath {
                reason: "contains backslash",
                ..
            }
        ));
    }

    /// Rejection payloads carry the offending path sanitized: control
    /// bytes and direction-override characters render as escapes, so
    /// the error text cannot smuggle terminal sequences or visually
    /// reordered names.
    #[test]
    fn rejection_payload_is_sanitized() {
        let err = validate_fca_path("dir/\u{202e}gpj.\u{1b}txt", limits()).unwrap_err();
        match err {
            CryptoError::UnsafeArchivePath { path, .. } => {
                assert!(!path.contains('\u{202e}'), "raw bidi override: {path:?}");
                assert!(!path.contains('\u{1b}'), "raw ESC: {path:?}");
                assert!(path.contains("\\u{202e}"), "got: {path}");
                assert!(path.contains("\\u{1b}"), "got: {path}");
            }
            other => panic!("expected UnsafeArchivePath, got {other:?}"),
        }
    }

    #[test]
    fn rejects_oversize_path() {
        let l = ArchiveLimits::default().with_max_path_bytes(10);
        let err = validate_fca_path("this_is_too_long.txt", l).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::ArchivePathBytesCapExceeded { .. }
        ));
    }

    #[test]
    fn rejects_oversize_depth() {
        let l = ArchiveLimits::default().with_max_path_depth(3);
        let err = validate_fca_path("a/b/c/d", l).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::ArchivePathDepthCapExceeded { .. }
        ));
    }

    /// Boundary check: depth exactly at cap is admissible, cap+1
    /// rejected. Same `>` vs `>=` regression guard as the limits
    /// helpers carry on the encode side.
    #[test]
    fn depth_at_cap_admissible() {
        let l = ArchiveLimits::default().with_max_path_depth(3);
        assert!(validate_fca_path("a/b/c", l).is_ok());
    }

    // -- Component rejections (§9.6) ---------------------------------------

    #[test]
    fn rejects_control_byte_tab() {
        let err = validate_fca_path("a\tb", limits()).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::UnsafeArchivePath {
                reason: "contains ASCII control byte",
                ..
            }
        ));
    }

    #[test]
    fn rejects_control_byte_low() {
        let err = validate_fca_path("a\x01b", limits()).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::UnsafeArchivePath {
                reason: "contains ASCII control byte",
                ..
            }
        ));
    }

    /// Every byte in the spec's Windows-reserved set rejects when
    /// embedded in a component. Loop-over-set keeps the test honest
    /// against accidental drift from the spec literal.
    #[test]
    fn rejects_each_windows_reserved_char() {
        for &c in WINDOWS_RESERVED_CHARS {
            let path = format!("a{}b.txt", c as char);
            let err = validate_fca_path(&path, limits()).unwrap_err();
            assert!(
                matches!(
                    err,
                    CryptoError::UnsafeArchivePath {
                        reason: "contains a Windows-reserved character",
                        ..
                    }
                ),
                "char {:?} should reject",
                c as char,
            );
        }
    }

    /// `:` is in the reserved set — pin separately because it's the
    /// alternate-data-stream attack vector on NTFS, the most
    /// security-relevant case in this set.
    #[test]
    fn rejects_colon_for_alternate_data_stream() {
        let err = validate_fca_path("file:stream", limits()).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::UnsafeArchivePath {
                reason: "contains a Windows-reserved character",
                ..
            }
        ));
    }

    #[test]
    fn rejects_trailing_space_in_component() {
        let err = validate_fca_path("file ", limits()).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::UnsafeArchivePath {
                reason: "component ends with space",
                ..
            }
        ));

        let err = validate_fca_path("dir /file", limits()).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::UnsafeArchivePath {
                reason: "component ends with space",
                ..
            }
        ));
    }

    #[test]
    fn rejects_trailing_dot_in_component() {
        let err = validate_fca_path("file.", limits()).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::UnsafeArchivePath {
                reason: "component ends with dot",
                ..
            }
        ));

        let err = validate_fca_path("dir./file", limits()).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::UnsafeArchivePath {
                reason: "component ends with dot",
                ..
            }
        ));
    }

    #[test]
    fn rejects_dot_components() {
        assert!(validate_fca_path(".", limits()).is_err());
        assert!(validate_fca_path("./file", limits()).is_err());
        assert!(validate_fca_path("a/./b", limits()).is_err());
    }

    #[test]
    fn rejects_double_dot_components() {
        assert!(validate_fca_path("..", limits()).is_err());
        assert!(validate_fca_path("../escape", limits()).is_err());
        assert!(validate_fca_path("a/..", limits()).is_err());
        assert!(validate_fca_path("a/../b", limits()).is_err());
    }

    // -- Reserved device names (§9.6) --------------------------------------

    /// All 33 reserved device names from FORMAT.md §9.6 reject. Loop-over
    /// pin keeps the test honest against future spec changes that
    /// add or remove an entry.
    #[test]
    fn rejects_every_reserved_device_name() {
        let names = [
            "CON",
            "PRN",
            "AUX",
            "NUL",
            "CLOCK$",
            "CONIN$",
            "CONOUT$",
            "COM0",
            "COM1",
            "COM2",
            "COM3",
            "COM4",
            "COM5",
            "COM6",
            "COM7",
            "COM8",
            "COM9",
            "COM\u{b9}",
            "COM\u{b2}",
            "COM\u{b3}",
            "LPT0",
            "LPT1",
            "LPT2",
            "LPT3",
            "LPT4",
            "LPT5",
            "LPT6",
            "LPT7",
            "LPT8",
            "LPT9",
            "LPT\u{b9}",
            "LPT\u{b2}",
            "LPT\u{b3}",
        ];
        assert_eq!(names.len(), 33);
        for name in &names {
            let err = validate_fca_path(name, limits()).unwrap_err();
            assert!(
                matches!(
                    err,
                    CryptoError::UnsafeArchivePath {
                        reason: "Windows-reserved device name",
                        ..
                    }
                ),
                "name {name} should reject",
            );
        }
    }

    /// Reserved-stem-with-extension form per FORMAT.md §9.6. The stem
    /// is checked before the first `.`, so `CON.txt` matches `con`
    /// and rejects.
    #[test]
    fn rejects_reserved_stems_with_extension() {
        for stem in &[
            "CON.txt",
            "PRN.bak",
            "AUX.bin",
            "NUL.log",
            "CLOCK$.dat",
            "CONIN$.txt",
            "CONOUT$.log",
            "COM0.dat",
            "COM1.log",
            "COM\u{b9}.txt",
            "LPT0.bak",
            "LPT9.bin",
            "LPT\u{b3}.log",
        ] {
            let err = validate_fca_path(stem, limits()).unwrap_err();
            assert!(
                matches!(
                    err,
                    CryptoError::UnsafeArchivePath {
                        reason: "Windows-reserved device name",
                        ..
                    }
                ),
                "stem {stem} should reject",
            );
        }
    }

    /// Spec §9.6: "ASCII-case-insensitive only". Same reserved name
    /// in any case combination rejects; locale-sensitive folding is
    /// explicitly NOT used (would be wrong for e.g. Turkish dotted
    /// `İ`/`ı`).
    #[test]
    fn reserved_check_is_ascii_case_insensitive() {
        for name in &[
            "con",
            "Con",
            "CON",
            "cOn",
            "lpt9",
            "Lpt9",
            "LPT9",
            "conin$",
            "CONIN$",
            "conout$",
            "ConOut$",
            "com\u{b9}",
            "Com\u{b9}",
            "lpt\u{b2}",
            "Lpt\u{b2}",
        ] {
            let err = validate_fca_path(name, limits()).unwrap_err();
            assert!(
                matches!(
                    err,
                    CryptoError::UnsafeArchivePath {
                        reason: "Windows-reserved device name",
                        ..
                    }
                ),
                "name {name} should reject",
            );
        }
    }

    /// `.foo` has empty stem (text before the first dot is empty),
    /// so it is NOT a reserved-device collision. Pin this to catch
    /// a future refactor that conflates "no dot" and "empty stem".
    #[test]
    fn empty_stem_is_not_reserved() {
        assert!(validate_fca_path(".foo", limits()).is_ok());
        assert!(!is_windows_reserved_device_component(".foo"));
    }

    /// Windows strips trailing spaces from a name's stem before
    /// resolving it to a device, so `AUX .txt` is the AUX device even
    /// though the stem is not byte-equal to `aux`. The whole-component
    /// trailing-space rule does not fire here (the component ends in
    /// `t`), so the device matcher must do the trimming itself.
    #[test]
    fn rejects_space_padded_reserved_stems() {
        for name in &[
            "aux .txt",
            "con  .log",
            "com1 .bin",
            "CONIN$ .dat",
            "lpt9   .x",
        ] {
            let err = validate_fca_path(name, limits()).unwrap_err();
            assert!(
                matches!(
                    err,
                    CryptoError::UnsafeArchivePath {
                        reason: "Windows-reserved device name",
                        ..
                    }
                ),
                "name {name:?} should reject as a reserved device",
            );
        }

        // A trailing space next to a non-reserved stem stays valid.
        assert!(validate_fca_path("notes .txt", limits()).is_ok());
    }

    // -- Component byte cap (§9.6) ------------------------------------------

    /// Boundary check: a component exactly at [`FCA_COMPONENT_MAX_BYTES`]
    /// is admissible, one byte over rejects. The cap leaves room for
    /// the `.incomplete` staging suffix next to the 255-byte filesystem
    /// name limit, so "encrypt succeeds, decrypt fails" cannot happen
    /// for a near-limit name.
    #[test]
    fn component_at_byte_cap_admissible_one_over_rejects() {
        let at_cap = "a".repeat(FCA_COMPONENT_MAX_BYTES);
        assert!(validate_fca_path(&at_cap, limits()).is_ok());

        let over_cap = "a".repeat(FCA_COMPONENT_MAX_BYTES + 1);
        let err = validate_fca_path(&over_cap, limits()).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::UnsafeArchivePath {
                reason: COMPONENT_TOO_LONG,
                ..
            }
        ));
    }

    /// The component cap applies to every component, not only the
    /// root: an over-long component nested inside an otherwise valid
    /// path rejects even though the whole path is under the path-byte
    /// cap.
    #[test]
    fn rejects_over_long_nested_component() {
        let long = "b".repeat(FCA_COMPONENT_MAX_BYTES + 1);
        let path = format!("root/{long}/leaf.txt");
        let err = validate_fca_path(&path, limits()).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::UnsafeArchivePath {
                reason: COMPONENT_TOO_LONG,
                ..
            }
        ));
    }

    /// The byte count embedded in the rejection text must equal the
    /// constant, and the constant must leave exactly the suffix room
    /// it promises. Locks the human-readable message and the derived
    /// value together so neither can drift alone.
    #[test]
    fn component_cap_reason_matches_constant() {
        assert_eq!(
            COMPONENT_TOO_LONG,
            format!("component exceeds {FCA_COMPONENT_MAX_BYTES} bytes"),
        );
        assert_eq!(
            FCA_COMPONENT_MAX_BYTES + INCOMPLETE_SUFFIX.len(),
            FILESYSTEM_NAME_MAX_BYTES,
        );
    }

    // -- Collision key (§9.7) ----------------------------------------------

    #[test]
    fn collision_key_lowercases_ascii() {
        assert_eq!(ascii_case_collision_key("Foo.TXT"), b"foo.txt");
        assert_eq!(ascii_case_collision_key("ABCdef"), b"abcdef");
        assert_eq!(ascii_case_collision_key(""), Vec::<u8>::new());
    }

    /// Multi-byte UTF-8 bytes pass through unchanged. The check is
    /// intentionally NOT Unicode-aware per FORMAT.md §9.7; filesystem-
    /// specific Unicode collisions fall through to `create_new(true)`
    /// at extraction time.
    #[test]
    fn collision_key_passes_through_non_ascii() {
        let input = "naïve";
        assert_eq!(ascii_case_collision_key(input), input.as_bytes());

        // Capital N gets lowercased; ï (multi-byte) stays.
        let key = ascii_case_collision_key("Naïve");
        assert_eq!(key.first(), Some(&b'n'));
        assert_eq!(&key[1..], "aïve".as_bytes());
    }

    // -- Pin-by-name coverage for platform-specific path attempts ---------

    /// Windows drive-letter paths reject by name. Currently transitive
    /// via the colon-rejection (`<>:"|?*`) and backslash rejection,
    /// but pinning by name keeps coverage explicit so a future split
    /// of the validators doesn't drop the case.
    #[test]
    fn rejects_windows_drive_path_with_backslash() {
        let err = validate_fca_path("C:\\x", limits()).unwrap_err();
        assert!(
            matches!(err, CryptoError::UnsafeArchivePath { .. }),
            "got: {err}",
        );
    }

    #[test]
    fn rejects_windows_drive_path_with_forward_slash() {
        // `C:/x` is an absolute path attempt without backslash. Hits
        // the `:` Windows-reserved-character rejection on the first
        // component.
        let err = validate_fca_path("C:/x", limits()).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::UnsafeArchivePath {
                reason: "contains a Windows-reserved character",
                ..
            }
        ));
    }

    #[test]
    fn rejects_unc_path_attempt() {
        // `\\server\share` UNC attempt. Backslash rejection fires.
        let err = validate_fca_path("\\\\server\\share", limits()).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::UnsafeArchivePath {
                reason: "contains backslash",
                ..
            }
        ));
    }

    #[test]
    fn rejects_double_forward_slash_unc_like() {
        // `//server/share` — POSIX double-slash, would be UNC-equivalent
        // on Windows. Hits the leading-slash rejection.
        let err = validate_fca_path("//server/share", limits()).unwrap_err();
        assert!(matches!(
            err,
            CryptoError::UnsafeArchivePath {
                reason: "absolute",
                ..
            }
        ));
    }

    /// Tar-rs `extracting_malicious_tarball` corpus (CVE-2001-1267
    /// et al. — see `tests/all.rs:768` in tar-rs). Tar's reaction is
    /// to silently strip leading slashes and skip `..` entries; FCA's
    /// posture is fail-closed — every entry MUST reject with a typed
    /// defect (`UnsafeArchivePath` or `MalformedArchive`). Loop-pin
    /// against the full byte set so a future relaxation of the
    /// rejection is caught.
    ///
    /// See `notes/done/tar_rs_crosscheck.md` §5 for the cross-check finding.
    #[test]
    fn rejects_every_tar_rs_malicious_path() {
        let corpus: &[&str] = &[
            "/tmp/abs_evil.txt",
            "//tmp/abs_evil2.txt",
            "///tmp/abs_evil3.txt",
            "/./tmp/abs_evil4.txt",
            "//./tmp/abs_evil5.txt",
            "///./tmp/abs_evil6.txt",
            "/../tmp/rel_evil.txt",
            "../rel_evil2.txt",
            "./../rel_evil3.txt",
            "some/../../rel_evil4.txt",
            "",
            "././//./..",
            "..",
            "/////////..",
            "/////////",
        ];
        for path in corpus {
            let result = validate_fca_path(path, limits());
            assert!(
                result.is_err(),
                "tar-rs malicious path {path:?} MUST reject (FCA fails closed; tar silently strips)",
            );
            // Confirm it's the typed path/archive rejection, not a
            // panic or unrelated error class.
            assert!(
                matches!(
                    result.unwrap_err(),
                    CryptoError::UnsafeArchivePath { .. } | CryptoError::MalformedArchive { .. }
                ),
                "tar-rs malicious path {path:?} must reject as a typed archive defect",
            );
        }
    }
}