ferrocrypt 0.3.0-beta.2

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
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
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
//! Public coverage for the new `Encryptor` / `Decryptor` API.
//!
//! `integration_tests.rs` exercises round-trip behavior through the
//! `passphrase_auto` / `recipient_auto` shims (which now wrap the new API
//! internally). This file targets the new API surface directly so the
//! builder methods, `Decryptor::open` mode classification, multi-
//! recipient encrypt, and `EmptyRecipientList` rejection have explicit
//! coverage independent of the shim implementation.

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

use ferrocrypt::secrecy::SecretString;
use ferrocrypt::{
    CryptoError, Decryptor, Encryptor, FormatDefect, HeaderReadLimits, InvalidKdfParams, KdfLimit,
    KdfParams, KeyPairGenerator, PrivateKey, PublicKey, probe_recipient_mode,
    probe_recipient_mode_with_limits,
};
use ferrocrypt_test_support::{
    TEST_FAST_KDF_MEM_COST, fast_keypair_generator, fast_passphrase_encryptor,
};

/// Test-side keygen helper that mirrors the lib's free `generate_key_pair`
/// signature but routes through the workspace-internal fast-Argon2id
/// builder so each call returns in milliseconds rather than seconds.
fn generate_key_pair(
    output_dir: impl AsRef<Path>,
    passphrase: SecretString,
    on_event: impl Fn(&ferrocrypt::ProgressEvent),
) -> Result<ferrocrypt::KeyGenOutcome, CryptoError> {
    fast_keypair_generator(passphrase).write(output_dir, on_event)
}

const PASSPHRASE: &str = "api-test-passphrase";
const TEST_WORKSPACE: &str = "tests/workspace_api";

#[ctor::dtor]
fn cleanup() {
    if Path::new(TEST_WORKSPACE).exists() {
        let _ = fs::remove_dir_all(TEST_WORKSPACE);
    }
}

fn fresh_workspace(name: &str) -> PathBuf {
    let dir = Path::new(TEST_WORKSPACE).join(name);
    if dir.exists() {
        fs::remove_dir_all(&dir).expect("clean api workspace");
    }
    fs::create_dir_all(&dir).expect("create api workspace");
    dir
}

fn pass() -> SecretString {
    SecretString::from(PASSPHRASE.to_string())
}

#[test]
fn encryptor_passphrase_round_trip() {
    let work = fresh_workspace("passphrase_round_trip");
    let input = work.join("data.txt");
    fs::write(&input, b"hello passphrase api").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    let outcome = fast_passphrase_encryptor(pass())
        .write(&input, &out_dir, |_| {})
        .expect("encrypt");

    let restore = work.join("restored");
    fs::create_dir_all(&restore).unwrap();
    let decrypted = match Decryptor::open(&outcome.output_path).expect("open") {
        Decryptor::Passphrase(d) => d.decrypt(pass(), &restore, |_| {}).expect("decrypt"),
        Decryptor::PrivateKey(_) => panic!("expected passphrase decryptor"),
        _ => unreachable!("Decryptor is non_exhaustive; v1 has only Passphrase + PrivateKey"),
    };
    let restored_bytes = fs::read(decrypted.output_path).unwrap();
    assert_eq!(restored_bytes, b"hello passphrase api");
}

#[test]
fn encryptor_recipient_round_trip() {
    let work = fresh_workspace("recipient_round_trip");
    let keys = work.join("keys");
    fs::create_dir_all(&keys).unwrap();
    let kg = generate_key_pair(&keys, pass(), |_| {}).expect("keygen");
    let input = work.join("data.txt");
    fs::write(&input, b"hello recipient api").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    let outcome = Encryptor::with_public_key(PublicKey::from_key_file(&kg.public_key_path))
        .write(&input, &out_dir, |_| {})
        .expect("encrypt");

    let restore = work.join("restored");
    fs::create_dir_all(&restore).unwrap();
    let decrypted = match Decryptor::open(&outcome.output_path).expect("open") {
        Decryptor::PrivateKey(d) => d
            .decrypt(
                PrivateKey::from_key_file(&kg.private_key_path),
                pass(),
                &restore,
                |_| {},
            )
            .expect("decrypt"),
        Decryptor::Passphrase(_) => panic!("expected private-key decryptor"),
        _ => unreachable!("Decryptor is non_exhaustive; v1 has only Passphrase + PrivateKey"),
    };
    let restored_bytes = fs::read(decrypted.output_path).unwrap();
    assert_eq!(restored_bytes, b"hello recipient api");
}

#[test]
fn encryptor_with_recipients_each_can_decrypt() {
    let work = fresh_workspace("multi_recipients");
    let keys_a = work.join("keys_a");
    let keys_b = work.join("keys_b");
    fs::create_dir_all(&keys_a).unwrap();
    fs::create_dir_all(&keys_b).unwrap();
    let kg_a = generate_key_pair(&keys_a, pass(), |_| {}).expect("keygen alice");
    let kg_b = generate_key_pair(&keys_b, pass(), |_| {}).expect("keygen bob");
    let input = work.join("data.txt");
    fs::write(&input, b"multi recipient payload").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    let outcome = Encryptor::with_public_keys([
        PublicKey::from_key_file(&kg_a.public_key_path),
        PublicKey::from_key_file(&kg_b.public_key_path),
    ])
    .expect("with_public_keys")
    .write(&input, &out_dir, |_| {})
    .expect("encrypt");

    for (label, kg) in [("alice", &kg_a), ("bob", &kg_b)] {
        let restore = work.join(format!("restored-{label}"));
        fs::create_dir_all(&restore).unwrap();
        let decrypted = match Decryptor::open(&outcome.output_path).expect("open") {
            Decryptor::PrivateKey(d) => d
                .decrypt(
                    PrivateKey::from_key_file(&kg.private_key_path),
                    pass(),
                    &restore,
                    |_| {},
                )
                .expect("decrypt"),
            Decryptor::Passphrase(_) => panic!("expected private-key decryptor"),
            _ => unreachable!("Decryptor is non_exhaustive"),
        };
        let restored_bytes = fs::read(decrypted.output_path).unwrap();
        assert_eq!(
            restored_bytes, b"multi recipient payload",
            "{label} restored bytes drifted"
        );
    }
}

#[test]
fn encryptor_with_recipients_rejects_empty() {
    let err = Encryptor::with_public_keys(std::iter::empty::<PublicKey>()).unwrap_err();
    assert!(
        matches!(err, CryptoError::EmptyRecipientList),
        "expected EmptyRecipientList, got {err:?}"
    );
}

#[test]
fn save_as_overrides_default_filename() {
    let work = fresh_workspace("save_as");
    let input = work.join("data.txt");
    fs::write(&input, b"x").unwrap();
    let custom = work.join("custom-name.fcr");

    let outcome = fast_passphrase_encryptor(pass())
        .save_as(&custom)
        .write(&input, &work, |_| {})
        .expect("encrypt");

    assert_eq!(outcome.output_path, custom, "save_as path not honored");
    assert!(custom.exists(), "custom path missing on disk");
}

#[test]
fn decryptor_open_rejects_directory() {
    let work = fresh_workspace("open_dir");
    let err = Decryptor::open(&work).unwrap_err();
    match err {
        CryptoError::InvalidInput(msg) => {
            assert!(msg.contains("directory"), "unexpected message: {msg:?}");
        }
        other => panic!("expected InvalidInput, got {other:?}"),
    }
}

#[test]
fn decryptor_open_rejects_non_fcr_file() {
    let work = fresh_workspace("open_bad_magic");
    let path = work.join("plain.txt");
    fs::write(&path, b"this is not a FerroCrypt file").unwrap();
    let err = Decryptor::open(&path).unwrap_err();
    match err {
        CryptoError::InvalidFormat(FormatDefect::BadMagic) => {}
        other => panic!("expected InvalidFormat(BadMagic), got {other:?}"),
    }
}

#[test]
fn decryptor_open_rejects_missing_input() {
    let err = Decryptor::open("/nonexistent/never/exists.fcr").unwrap_err();
    assert!(
        matches!(err, CryptoError::InputPath),
        "expected InputPath, got {err:?}"
    );
}

/// `fast_passphrase_encryptor("")` must reject the empty passphrase
/// at the top of `write`, before the input-existence check fires. Pins
/// the cheap-caller-input-first ordering matching the deprecated
/// `symmetric_encrypt` path so an empty passphrase against a missing
/// input still surfaces the more actionable "Passphrase must not be
/// empty" diagnostic.
#[test]
fn encryptor_passphrase_rejects_empty_before_input_check() {
    let work = fresh_workspace("empty_pass_before_input");
    let missing = work.join("does-not-exist.txt");
    let err = fast_passphrase_encryptor(SecretString::from(String::new()))
        .write(&missing, &work, |_| {})
        .unwrap_err();
    match err {
        CryptoError::InvalidInput(msg) => assert!(
            msg.contains("Passphrase"),
            "expected Passphrase rejection, got {msg:?}"
        ),
        other => panic!("expected InvalidInput, got {other:?}"),
    }
}

/// Pins the secrecy-redaction invariant on the new API. `Encryptor`
/// embeds a `SecretString` for the passphrase variant; this test fails
/// fast if `SecretString` is ever swapped for a raw `String`.
#[test]
fn encryptor_debug_does_not_leak_passphrase() {
    const SECRET: &str = "totally-secret-passphrase-9F2";
    let encryptor = fast_passphrase_encryptor(SecretString::from(SECRET.to_string()));
    let rendered = format!("{encryptor:?}");
    assert!(
        !rendered.contains(SECRET),
        "Encryptor leaked passphrase into Debug output: {rendered}"
    );
}

#[test]
fn probe_recipient_mode_round_trips_via_encryptor() {
    let work = fresh_workspace("probe_round_trip");
    let input = work.join("data.txt");
    fs::write(&input, b"x").unwrap();
    let outcome = fast_passphrase_encryptor(pass())
        .write(&input, &work, |_| {})
        .expect("encrypt");
    assert!(
        probe_recipient_mode(&outcome.output_path)
            .unwrap()
            .is_some(),
        "encrypt output must classify as a known FerroCrypt mode"
    );
}

/// Regression: verifies that `DecryptOutcome::recipient_mode` is populated
/// with the mode that actually authenticated the file, not the other one.
/// Without this test, swapping the two `AuthenticatedRecipientMode::*()`
/// constructors between `PassphraseDecryptor::decrypt` and
/// `PrivateKeyDecryptor::decrypt` would silently compile and pass every
/// other test — those check `output_path` but not which mode authenticated.
#[test]
fn decrypt_outcome_carries_authenticated_passphrase_mode() {
    let work = fresh_workspace("outcome_mode_passphrase");
    let input = work.join("data.txt");
    fs::write(&input, b"plaintext").unwrap();
    let encrypted = fast_passphrase_encryptor(pass())
        .write(&input, &work, |_| {})
        .expect("encrypt");

    let restore = work.join("restored");
    fs::create_dir_all(&restore).unwrap();
    let outcome = match Decryptor::open(&encrypted.output_path).expect("open") {
        Decryptor::Passphrase(d) => d.decrypt(pass(), &restore, |_| {}).expect("decrypt"),
        other => panic!("expected passphrase decryptor, got {other:?}"),
    };
    assert!(
        outcome.recipient_mode.is_passphrase(),
        "passphrase decrypt must report passphrase mode, got {}",
        outcome.recipient_mode
    );
    assert!(!outcome.recipient_mode.is_public_key());
}

/// Companion regression for the recipient (X25519) decrypt path.
#[test]
fn decrypt_outcome_carries_authenticated_public_key_mode() {
    let work = fresh_workspace("outcome_mode_public_key");
    let keys = work.join("keys");
    fs::create_dir_all(&keys).unwrap();
    let kg = generate_key_pair(&keys, pass(), |_| {}).expect("keygen");
    let input = work.join("data.txt");
    fs::write(&input, b"plaintext").unwrap();
    let encrypted = Encryptor::with_public_key(PublicKey::from_key_file(&kg.public_key_path))
        .write(&input, &work, |_| {})
        .expect("encrypt");

    let restore = work.join("restored");
    fs::create_dir_all(&restore).unwrap();
    let outcome = match Decryptor::open(&encrypted.output_path).expect("open") {
        Decryptor::PrivateKey(d) => d
            .decrypt(
                PrivateKey::from_key_file(&kg.private_key_path),
                pass(),
                &restore,
                |_| {},
            )
            .expect("decrypt"),
        other => panic!("expected private-key decryptor, got {other:?}"),
    };
    assert!(
        outcome.recipient_mode.is_public_key(),
        "public-key decrypt must report public-key mode, got {}",
        outcome.recipient_mode
    );
    assert!(!outcome.recipient_mode.is_passphrase());
}

/// Exercises the new `archive_limits()` builder on
/// [`PassphraseDecryptor`]. The bug being guarded is that callers who
/// raise the encrypt-side cap had no way to lift the decrypt-side cap,
/// so a legitimately-encrypted archive could be un-decryptable under
/// default decrypt limits. Setting a TIGHT decrypt cap proves the
/// value is plumbed through to `unarchive`.
#[test]
fn passphrase_decryptor_archive_limits_constrains_extraction() {
    use ferrocrypt::ArchiveLimits;

    let work = fresh_workspace("passphrase_archive_limits");
    let dir = work.join("input");
    fs::create_dir_all(&dir).unwrap();
    fs::write(dir.join("a.txt"), b"a").unwrap();
    fs::write(dir.join("b.txt"), b"b").unwrap();
    fs::write(dir.join("c.txt"), b"c").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    let outcome = fast_passphrase_encryptor(pass())
        .write(&dir, &out_dir, |_| {})
        .expect("encrypt");

    let restore = work.join("restored");
    fs::create_dir_all(&restore).unwrap();
    let tight = ArchiveLimits::default().with_max_entry_count(1);
    let result = match Decryptor::open(&outcome.output_path).expect("open") {
        Decryptor::Passphrase(d) => d.archive_limits(tight).decrypt(pass(), &restore, |_| {}),
        _ => panic!("expected passphrase decryptor"),
    };
    match result {
        Err(CryptoError::InvalidInput(msg)) => {
            assert!(
                msg.contains("entry-count cap exceeded"),
                "expected entry-count cap error, got: {msg}"
            );
        }
        other => panic!("expected InvalidInput cap error, got {other:?}"),
    }
}

/// Mirrors `passphrase_decryptor_archive_limits_constrains_extraction`
/// for [`PrivateKeyDecryptor`]: the `archive_limits()` builder must
/// reach `unarchive` on the public-key decrypt path too.
#[test]
fn recipient_decryptor_archive_limits_constrains_extraction() {
    use ferrocrypt::ArchiveLimits;

    let work = fresh_workspace("recipient_archive_limits");
    let keys = work.join("keys");
    fs::create_dir_all(&keys).unwrap();
    let kg = generate_key_pair(&keys, pass(), |_| {}).expect("keygen");
    let dir = work.join("input");
    fs::create_dir_all(&dir).unwrap();
    fs::write(dir.join("a.txt"), b"a").unwrap();
    fs::write(dir.join("b.txt"), b"b").unwrap();
    fs::write(dir.join("c.txt"), b"c").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    let outcome = Encryptor::with_public_key(PublicKey::from_key_file(&kg.public_key_path))
        .write(&dir, &out_dir, |_| {})
        .expect("encrypt");

    let restore = work.join("restored");
    fs::create_dir_all(&restore).unwrap();
    let tight = ArchiveLimits::default().with_max_entry_count(1);
    let result = match Decryptor::open(&outcome.output_path).expect("open") {
        Decryptor::PrivateKey(d) => d.archive_limits(tight).decrypt(
            PrivateKey::from_key_file(&kg.private_key_path),
            pass(),
            &restore,
            |_| {},
        ),
        _ => panic!("expected private-key decryptor"),
    };
    match result {
        Err(CryptoError::InvalidInput(msg)) => {
            assert!(
                msg.contains("entry-count cap exceeded"),
                "expected entry-count cap error, got: {msg}"
            );
        }
        other => panic!("expected InvalidInput cap error, got {other:?}"),
    }
}

/// Encrypt-side `archive_limits` raised above the default while the
/// reader uses [`ArchiveLimits::default`]: a file containing a path
/// deeper than the reader's default `max_path_depth` (64) is rejected
/// at extract time with the typed `path depth cap exceeded` message,
/// and the same file decrypts successfully when the reader raises
/// `archive_limits` to match the writer.
///
/// Pins the documented asymmetry on
/// [`PassphraseDecryptor::archive_limits`] / [`PrivateKeyDecryptor::archive_limits`]
/// ("Must match (or exceed) the limits the writer used") as
/// intentional behavior rather than implicit. `max_path_depth` is
/// used because it is the only `ArchiveLimits` axis whose default cap
/// (64) is small enough to exercise asymmetrically with a tractable
/// fixture; `max_entry_count` (250 000) and
/// `max_total_plaintext_bytes` (64 GiB) would each require an
/// impractical fixture.
#[test]
fn archive_limits_writer_raised_default_reader_rejects_path_depth() {
    use ferrocrypt::ArchiveLimits;

    let work = fresh_workspace("archive_limits_asymmetric_path_depth");
    let input = work.join("input");
    // Archive paths are emitted as `<root>/<rel>`: the input directory
    // contributes one component (`input`), each nested `a` adds one,
    // and the leaf file adds one. 64 nested directories therefore
    // produce a leaf entry with 66 components — two over the default
    // reader cap of 64, so the rejection cannot be a fence-post mistake.
    let mut deepest = input.clone();
    for _ in 0..64 {
        deepest = deepest.join("a");
    }
    fs::create_dir_all(&deepest).unwrap();
    fs::write(deepest.join("leaf.txt"), b"deep payload").unwrap();

    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    // Writer raises `max_path_depth` so the encrypt-side preflight
    // accepts the deep tree. Without this raise the writer's own
    // preflight would reject before any payload bytes were written.
    let raised = ArchiveLimits::default().with_max_path_depth(80);
    let outcome = fast_passphrase_encryptor(pass())
        .archive_limits(raised)
        .write(&input, &out_dir, |_| {})
        .expect("encrypt");

    // Default reader: rejects on extract with the typed path-depth
    // diagnostic. Surfaces from `enforce_per_entry_caps` as
    // `CryptoError::InvalidInput(_)`.
    let restore = work.join("restored");
    fs::create_dir_all(&restore).unwrap();
    let default_decrypt = match Decryptor::open(&outcome.output_path).expect("open") {
        Decryptor::Passphrase(d) => d.decrypt(pass(), &restore, |_| {}),
        _ => panic!("expected passphrase decryptor"),
    };
    match default_decrypt {
        Err(CryptoError::InvalidInput(msg)) => assert!(
            msg.contains("path depth cap"),
            "expected path-depth cap rejection from default reader, got: {msg}"
        ),
        other => panic!("expected default reader to reject deep file, got {other:?}"),
    }

    // Reader raises `archive_limits` to match the writer: succeeds.
    let restore2 = work.join("restored2");
    fs::create_dir_all(&restore2).unwrap();
    let raised_decrypt = match Decryptor::open(&outcome.output_path).expect("open") {
        Decryptor::Passphrase(d) => d
            .archive_limits(raised)
            .decrypt(pass(), &restore2, |_| {})
            .expect("raised reader must accept the file the default reader refused"),
        _ => panic!("expected passphrase decryptor"),
    };
    assert!(raised_decrypt.output_path.is_dir());
    let mut leaf = raised_decrypt.output_path.clone();
    for _ in 0..64 {
        leaf = leaf.join("a");
    }
    leaf = leaf.join("leaf.txt");
    assert_eq!(fs::read(&leaf).unwrap(), b"deep payload");
}

/// Round-trip with raised caps on both sides — the writer-and-reader-
/// aligned case the new builder enables. Without `Decryptor::archive_limits`, this
/// pattern was impossible: the encrypt side could exceed defaults but
/// the decrypt side was hardcoded to `ArchiveLimits::default()`.
#[test]
fn archive_limits_raised_on_both_sides_round_trips() {
    use ferrocrypt::ArchiveLimits;

    let work = fresh_workspace("archive_limits_raised");
    let dir = work.join("input");
    fs::create_dir_all(&dir).unwrap();
    fs::write(dir.join("a.txt"), b"alpha").unwrap();
    fs::write(dir.join("b.txt"), b"beta").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    let raised = ArchiveLimits::default()
        .with_max_entry_count(8)
        .with_max_path_depth(8);
    let outcome = fast_passphrase_encryptor(pass())
        .archive_limits(raised)
        .write(&dir, &out_dir, |_| {})
        .expect("encrypt");

    let restore = work.join("restored");
    fs::create_dir_all(&restore).unwrap();
    let outcome_decrypt = match Decryptor::open(&outcome.output_path).expect("open") {
        Decryptor::Passphrase(d) => d
            .archive_limits(raised)
            .decrypt(pass(), &restore, |_| {})
            .expect("decrypt"),
        _ => panic!("expected passphrase decryptor"),
    };
    let extracted = outcome_decrypt.output_path;
    assert!(extracted.is_dir());
    assert_eq!(fs::read(extracted.join("a.txt")).unwrap(), b"alpha");
    assert_eq!(fs::read(extracted.join("b.txt")).unwrap(), b"beta");
}

/// Encrypts to 80 of the same recipient — above the default
/// `RECIPIENT_COUNT_LOCAL_CAP_DEFAULT` (64) but well below the
/// structural ceiling (4096). [`Decryptor::open`] with default limits
/// MUST refuse the file with [`CryptoError::RecipientCountCapExceeded`];
/// the same file MUST decrypt successfully when the caller raises the
/// cap via [`Decryptor::open_with_limits`] /
/// [`HeaderReadLimits::max_recipient_count`]. Pins the audit-flagged
/// Low 2 finding closed at the public-API level (not just the
/// internal parser).
#[test]
fn decryptor_open_with_limits_accepts_recipient_count_above_default() {
    let work = fresh_workspace("recipient_count_above_default");
    let keys = work.join("keys");
    fs::create_dir_all(&keys).unwrap();
    let kg = generate_key_pair(&keys, pass(), |_| {}).expect("keygen");
    let input = work.join("data.txt");
    fs::write(&input, b"raised count payload").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    // 80 copies of the same recipient produce a file with 80 x25519
    // recipient entries. Each entry independently wraps the same
    // file_key, so the holder of `kg`'s private key can decrypt any
    // of them.
    const RECIPIENT_COUNT: usize = 80;
    let recipients: Vec<PublicKey> = (0..RECIPIENT_COUNT)
        .map(|_| PublicKey::from_key_file(&kg.public_key_path))
        .collect();
    // Writer-mirrors-reader contract: the writer refuses lists above the
    // default `RECIPIENT_COUNT_LOCAL_CAP_DEFAULT` (64) unless the caller
    // raises `Encryptor::header_read_limits` explicitly. The decryptor
    // must mirror the raise via `Decryptor::open_with_limits`.
    let writer_limits = HeaderReadLimits::default().max_recipient_count(128);
    let outcome = Encryptor::with_public_keys(recipients)
        .expect("with_public_keys")
        .header_read_limits(writer_limits)
        .write(&input, &out_dir, |_| {})
        .expect("encrypt");

    // Default open: rejected by recipient_count cap.
    match Decryptor::open(&outcome.output_path) {
        Err(CryptoError::RecipientCountCapExceeded { count, local_cap }) => {
            assert_eq!(count, RECIPIENT_COUNT as u16);
            assert!(
                local_cap < count,
                "default local_cap should be below file count"
            );
        }
        other => panic!("expected RecipientCountCapExceeded with default cap, got {other:?}"),
    }

    // Same file via open_with_limits: succeeds.
    let raised = HeaderReadLimits::default().max_recipient_count(128);
    let restore = work.join("restored");
    fs::create_dir_all(&restore).unwrap();
    let decrypted = match Decryptor::open_with_limits(&outcome.output_path, raised)
        .expect("open_with_limits")
    {
        Decryptor::PrivateKey(d) => d
            .decrypt(
                PrivateKey::from_key_file(&kg.private_key_path),
                pass(),
                &restore,
                |_| {},
            )
            .expect("decrypt"),
        _ => panic!("expected private-key decryptor"),
    };
    assert_eq!(
        fs::read(decrypted.output_path).unwrap(),
        b"raised count payload"
    );
}

/// `probe_recipient_mode_with_limits` honors the elevated cap when
/// classifying a file the default-limited variant refuses. Companion
/// to [`decryptor_open_with_limits_accepts_recipient_count_above_default`]
/// for the probe-only path used by callers that want to classify
/// without going through `Decryptor::open`.
#[test]
fn probe_recipient_mode_with_limits_accepts_above_default() {
    use ferrocrypt::UnauthenticatedRecipientMode;

    let work = fresh_workspace("probe_with_limits");
    let keys = work.join("keys");
    fs::create_dir_all(&keys).unwrap();
    let kg = generate_key_pair(&keys, pass(), |_| {}).expect("keygen");
    let input = work.join("data.txt");
    fs::write(&input, b"x").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    let recipients: Vec<PublicKey> = (0..80)
        .map(|_| PublicKey::from_key_file(&kg.public_key_path))
        .collect();
    // Writer must opt into the raised recipient-count cap; the
    // probe-only path below confirms the same opt-in is required
    // on the read side.
    let writer_limits = HeaderReadLimits::default().max_recipient_count(128);
    let outcome = Encryptor::with_public_keys(recipients)
        .expect("with_public_keys")
        .header_read_limits(writer_limits)
        .write(&input, &out_dir, |_| {})
        .expect("encrypt");

    // Default probe: rejected.
    match probe_recipient_mode(&outcome.output_path) {
        Err(CryptoError::RecipientCountCapExceeded { .. }) => {}
        other => panic!("expected RecipientCountCapExceeded with default probe, got {other:?}"),
    }

    // Raised probe: classifies cleanly.
    let raised = HeaderReadLimits::default().max_recipient_count(128);
    match probe_recipient_mode_with_limits(&outcome.output_path, raised) {
        Ok(Some(UnauthenticatedRecipientMode::PublicKey)) => {}
        other => panic!("expected Ok(Some(PublicKey)) under raised cap, got {other:?}"),
    }
}

// ─── Writer caps mirror reader defaults ────────────────────────────────────
//
// Pin the contract that a default-configured `Encryptor` /
// `KeyPairGenerator` produces files a default-configured `Decryptor`
// (or `PrivateKeyDecryptor` `private.key` unlock) can read. Going
// above default requires the caller to opt in on BOTH sides; the
// tests below pin both the rejection (no opt-in) and the acceptance
// (opt-in matches) directions.

/// Default `Encryptor::with_public_keys(N>64)` rejects at write time
/// with [`CryptoError::RecipientCountCapExceeded`] before any X25519
/// ECDH or key wrapping runs. Pins the writer-side half of the
/// recipient-count contract; the matching reader-side rejection /
/// acceptance is pinned by
/// [`decryptor_open_with_limits_accepts_recipient_count_above_default`].
#[test]
fn encryptor_with_recipients_above_default_rejects_without_opt_in() {
    let work = fresh_workspace("recipients_above_default_rejects");
    let keys = work.join("keys");
    fs::create_dir_all(&keys).unwrap();
    let kg = generate_key_pair(&keys, pass(), |_| {}).expect("keygen");
    let input = work.join("data.txt");
    fs::write(&input, b"x").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    let cap = HeaderReadLimits::RECIPIENT_COUNT_DEFAULT;

    // One above the default cap — boundary rejection, not "way over".
    let recipients: Vec<PublicKey> = (0..(cap as usize + 1))
        .map(|_| PublicKey::from_key_file(&kg.public_key_path))
        .collect();
    let result = Encryptor::with_public_keys(recipients)
        .expect("with_public_keys")
        .write(&input, &out_dir, |_| {});
    match result {
        Err(CryptoError::RecipientCountCapExceeded { count, local_cap }) => {
            assert_eq!(count, cap + 1);
            assert_eq!(local_cap, cap);
        }
        other => panic!("expected RecipientCountCapExceeded, got {other:?}"),
    }

    // Boundary: a list at exactly the default cap MUST succeed under
    // default settings. Pins the cap check uses `>`, not `>=`.
    let at_cap: Vec<PublicKey> = (0..cap)
        .map(|_| PublicKey::from_key_file(&kg.public_key_path))
        .collect();
    let at_cap_out = out_dir.join("at_cap");
    fs::create_dir_all(&at_cap_out).unwrap();
    let outcome = Encryptor::with_public_keys(at_cap)
        .expect("with_public_keys at cap")
        .write(&input, &at_cap_out, |_| {})
        .expect("encrypt at exactly the default cap must succeed");
    assert!(outcome.output_path.exists());
}

/// Writer-side `HeaderReadLimits` preflight applies to passphrase files
/// too, not just public-key files. Tightening recipient_count
/// below the one canonical `argon2id` slot rejects before Argon2id runs,
/// preventing a file that the same limits would reject on decrypt.
#[test]
fn encryptor_passphrase_header_limits_reject_tight_recipient_count() {
    let work = fresh_workspace("passphrase_header_count_tight");
    let input = work.join("data.txt");
    fs::write(&input, b"x").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    let tight = HeaderReadLimits::default().max_recipient_count(0);
    let result = fast_passphrase_encryptor(pass())
        .header_read_limits(tight)
        .write(&input, &out_dir, |_| {});
    match result {
        Err(CryptoError::RecipientCountCapExceeded {
            count: 1,
            local_cap: 0,
        }) => {}
        other => panic!("expected RecipientCountCapExceeded(1, 0), got {other:?}"),
    }
}

/// Writer-side `HeaderReadLimits::max_recipient_body_len` is enforced
/// against native body lengths. A caller who tightens below the v1
/// `argon2id` body length gets the same typed cap error during encrypt
/// that a reader would later return.
#[test]
fn encryptor_passphrase_header_limits_reject_tight_body_len() {
    let work = fresh_workspace("passphrase_header_body_tight");
    let input = work.join("data.txt");
    fs::write(&input, b"x").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    let tight = HeaderReadLimits::default().max_recipient_body_len(1);
    let result = fast_passphrase_encryptor(pass())
        .header_read_limits(tight)
        .write(&input, &out_dir, |_| {});
    match result {
        Err(CryptoError::RecipientBodyCapExceeded {
            body_len,
            local_cap,
        }) => {
            assert!(body_len > local_cap);
            assert_eq!(local_cap, 1);
        }
        other => panic!("expected RecipientBodyCapExceeded, got {other:?}"),
    }
}

/// Writer-side `HeaderReadLimits::max_header_len` is enforced against
/// the exact v1 header length the writer will emit. Tightening below
/// that shape rejects before any output is written.
#[test]
fn encryptor_recipient_header_limits_reject_tight_header_len() {
    let work = fresh_workspace("recipient_header_len_tight");
    let keys = work.join("keys");
    fs::create_dir_all(&keys).unwrap();
    let kg = generate_key_pair(&keys, pass(), |_| {}).expect("keygen");
    let input = work.join("data.txt");
    fs::write(&input, b"x").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    let tight = HeaderReadLimits::default().max_header_len(32);
    let result = Encryptor::with_public_key(PublicKey::from_key_file(&kg.public_key_path))
        .header_read_limits(tight)
        .write(&input, &out_dir, |_| {});
    match result {
        Err(CryptoError::HeaderLenCapExceeded {
            header_len,
            local_cap: 32,
        }) => {
            assert!(header_len > 32);
        }
        other => panic!("expected HeaderLenCapExceeded, got {other:?}"),
    }
}

/// Writer-side KDF validation now mirrors reader-side structural rules,
/// not just the local memory cap. A `time_cost` accepted by upstream
/// Argon2 but outside FerroCrypt v1's structural range rejects at write
/// time instead of producing an undecryptable `.fcr`.
#[test]
fn encryptor_kdf_params_rejects_structural_time_cost() {
    let work = fresh_workspace("kdf_structural_time_rejects");
    let input = work.join("data.txt");
    fs::write(&input, b"x").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    let invalid = KdfParams {
        mem_cost: TEST_FAST_KDF_MEM_COST,
        time_cost: 13,
        lanes: 4,
    };
    let result = Encryptor::with_passphrase(pass())
        .kdf_params(invalid)
        .write(&input, &out_dir, |_| {});
    match result {
        Err(CryptoError::InvalidKdfParams(InvalidKdfParams::TimeCost(13))) => {}
        other => panic!("expected InvalidKdfParams::TimeCost(13), got {other:?}"),
    }
}

/// Even with an explicitly raised writer-side `KdfLimit`, structural
/// `mem_cost` above FerroCrypt's v1 maximum must reject before Argon2id
/// runs. This prevents the resource-limit opt-in from bypassing the
/// file-format structural ceiling.
#[test]
fn encryptor_kdf_params_rejects_structural_mem_cost_even_with_raised_limit() {
    let work = fresh_workspace("kdf_structural_mem_rejects");
    let input = work.join("data.txt");
    fs::write(&input, b"x").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    let invalid_mem = 3 * 1024 * 1024;
    let invalid = KdfParams {
        mem_cost: invalid_mem,
        time_cost: 4,
        lanes: 4,
    };
    let result = Encryptor::with_passphrase(pass())
        .kdf_params(invalid)
        .kdf_limit(KdfLimit::new(4 * 1024 * 1024))
        .write(&input, &out_dir, |_| {});
    match result {
        Err(CryptoError::InvalidKdfParams(InvalidKdfParams::MemoryCost(n))) => {
            assert_eq!(n, invalid_mem);
        }
        other => panic!("expected InvalidKdfParams::MemoryCost, got {other:?}"),
    }
}

/// Key-pair generation uses the same writer-side KDF validator as
/// passphrase `.fcr` encryption. Invalid `lanes` rejects before a
/// `private.key` containing reader-rejected KDF params can be written.
#[test]
fn keypair_generator_kdf_params_rejects_structural_lanes() {
    let work = fresh_workspace("keypair_kdf_structural_lanes_rejects");
    let keys = work.join("keys");
    fs::create_dir_all(&keys).unwrap();

    let invalid = KdfParams {
        mem_cost: TEST_FAST_KDF_MEM_COST,
        time_cost: 1,
        lanes: 9,
    };
    let result = KeyPairGenerator::with_passphrase(pass())
        .kdf_params(invalid)
        .write(&keys, |_| {});
    match result {
        Err(CryptoError::InvalidKdfParams(InvalidKdfParams::Parallelism(9))) => {}
        other => panic!("expected InvalidKdfParams::Parallelism(9), got {other:?}"),
    }
}

/// Default `Encryptor::kdf_params(P)` with `P.mem_cost > KdfLimit::default()`
/// rejects at write time before Argon2id runs. The matching opt-in
/// path is pinned by [`encryptor_kdf_params_at_kdf_limit_succeeds`].
#[test]
fn encryptor_kdf_params_above_default_rejects_with_default_kdf_limit() {
    let work = fresh_workspace("kdf_above_default_rejects");
    let input = work.join("data.txt");
    fs::write(&input, b"x").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    // mem_cost = default + 1 KiB — minimal overflow, still well
    // within `KdfParams::MAX_MEM_COST`, so this exercises the
    // writer-side resource cap after structural validation succeeds.
    let default_limit = KdfLimit::default();
    let oversized_params = KdfParams {
        mem_cost: default_limit.max_mem_cost_kib + 1,
        time_cost: 4,
        lanes: 4,
    };
    let result = Encryptor::with_passphrase(pass())
        .kdf_params(oversized_params)
        .write(&input, &out_dir, |_| {});
    match result {
        Err(CryptoError::KdfResourceCapExceeded {
            mem_cost_kib,
            local_cap_kib,
        }) => {
            assert_eq!(mem_cost_kib, oversized_params.mem_cost);
            assert_eq!(local_cap_kib, default_limit.max_mem_cost_kib);
        }
        other => panic!("expected KdfResourceCapExceeded, got {other:?}"),
    }
}

/// `Encryptor::kdf_params(P).kdf_limit(L)` with `P.mem_cost <= L` is
/// accepted by the writer, the resulting `.fcr` round-trips under a
/// matching reader-side `kdf_limit`, and the cap check uses `>`
/// (boundary inclusive) — `mem_cost == max_mem_cost_kib` succeeds.
///
/// The test deliberately uses `TEST_FAST_KDF_MEM_COST` (8 MiB) so the
/// real Argon2id run inside the assertion stays fast; the same
/// boundary semantics apply at any `mem_cost` the writer might
/// configure.
#[test]
fn encryptor_kdf_params_at_kdf_limit_succeeds() {
    let work = fresh_workspace("kdf_at_limit_succeeds");
    let input = work.join("data.txt");
    fs::write(&input, b"hello").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    // Boundary: kdf_limit at exactly fast-KDF mem_cost. Cap check
    // (`mem_cost > max_mem_cost_kib`) is `false`, so the encrypt
    // proceeds into a real (fast) Argon2id run.
    let exact = KdfLimit::new(TEST_FAST_KDF_MEM_COST);
    let outcome = fast_passphrase_encryptor(pass())
        .kdf_limit(exact)
        .write(&input, &out_dir, |_| {})
        .expect("encrypt with kdf_limit at boundary");

    // Round-trip under matching reader settings.
    let restore = work.join("restored");
    fs::create_dir_all(&restore).unwrap();
    let decrypted = match Decryptor::open(&outcome.output_path).expect("open") {
        Decryptor::Passphrase(d) => d
            .kdf_limit(exact)
            .decrypt(pass(), &restore, |_| {})
            .expect("decrypt"),
        _ => panic!("expected passphrase decryptor"),
    };
    assert_eq!(fs::read(decrypted.output_path).unwrap(), b"hello");
}

/// Default `KeyPairGenerator::kdf_params(P)` with
/// `P.mem_cost > KdfLimit::default()` rejects at write time before
/// Argon2id runs.
#[test]
fn keypair_generator_kdf_params_above_default_rejects_with_default_kdf_limit() {
    let work = fresh_workspace("keypair_kdf_above_default_rejects");
    let keys = work.join("keys");
    fs::create_dir_all(&keys).unwrap();

    let default_limit = KdfLimit::default();
    let oversized_params = KdfParams {
        mem_cost: default_limit.max_mem_cost_kib + 1,
        time_cost: 4,
        lanes: 4,
    };
    let result = KeyPairGenerator::with_passphrase(pass())
        .kdf_params(oversized_params)
        .write(&keys, |_| {});
    match result {
        Err(CryptoError::KdfResourceCapExceeded {
            mem_cost_kib,
            local_cap_kib,
        }) => {
            assert_eq!(mem_cost_kib, oversized_params.mem_cost);
            assert_eq!(local_cap_kib, default_limit.max_mem_cost_kib);
        }
        other => panic!("expected KdfResourceCapExceeded, got {other:?}"),
    }
}

/// `KeyPairGenerator::kdf_params(P).kdf_limit(L)` with
/// `P.mem_cost <= L` produces a `private.key` whose unlock under a
/// matching `PrivateKeyDecryptor::kdf_limit(L)` succeeds.
#[test]
fn keypair_generator_kdf_params_at_kdf_limit_succeeds() {
    let work = fresh_workspace("keypair_kdf_at_limit_succeeds");
    let keys = work.join("keys");
    fs::create_dir_all(&keys).unwrap();

    let exact = KdfLimit::new(TEST_FAST_KDF_MEM_COST);
    let kg = fast_keypair_generator(pass())
        .kdf_limit(exact)
        .write(&keys, |_| {})
        .expect("keygen with kdf_limit at boundary");

    // Encrypt to that key with default Encryptor (X25519 path
    // doesn't run Argon2id), then decrypt with the matching
    // PrivateKeyDecryptor::kdf_limit so the private.key unlock
    // accepts the elevated mem_cost authenticated in the cleartext.
    let input = work.join("data.txt");
    fs::write(&input, b"x25519 round-trip via raised kdf").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();
    let outcome = Encryptor::with_public_key(PublicKey::from_key_file(&kg.public_key_path))
        .write(&input, &out_dir, |_| {})
        .expect("encrypt");

    let restore = work.join("restored");
    fs::create_dir_all(&restore).unwrap();
    let decrypted = match Decryptor::open(&outcome.output_path).expect("open") {
        Decryptor::PrivateKey(d) => d
            .kdf_limit(exact)
            .decrypt(
                PrivateKey::from_key_file(&kg.private_key_path),
                pass(),
                &restore,
                |_| {},
            )
            .expect("decrypt"),
        _ => panic!("expected private-key decryptor"),
    };
    assert_eq!(
        fs::read(decrypted.output_path).unwrap(),
        b"x25519 round-trip via raised kdf"
    );
}

/// A second passphrase encrypt to a path already occupied by an `.fcr`
/// file from the first run must reject *before* Argon2id fires. The
/// output-precheck inside `protocol::encrypt` runs ahead of any KDF
/// emission, so a `DerivingPassphraseWrapKey` event count of 0 on
/// the failing run proves the user did not pay for a multi-second KDF
/// just to learn the destination was occupied. Pinned as a regression
/// for BUG_REVIEW #2 — without the preflight, the failure used to
/// surface only after the KDF + recipient wrap + header build.
#[test]
fn encryptor_passphrase_rejects_existing_output_before_kdf() {
    let work = fresh_workspace("rejects_existing_output_before_kdf");
    let input = work.join("data.txt");
    fs::write(&input, b"output-conflict preflight").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    fast_passphrase_encryptor(pass())
        .write(&input, &out_dir, |_| {})
        .expect("first encrypt");

    let kdf_event_count = std::cell::Cell::new(0u32);
    let result = fast_passphrase_encryptor(pass()).write(&input, &out_dir, |evt| {
        if matches!(evt, ferrocrypt::ProgressEvent::DerivingPassphraseWrapKey) {
            kdf_event_count.set(kdf_event_count.get() + 1);
        }
    });

    match result {
        Err(CryptoError::InvalidInput(msg)) => {
            assert!(
                msg.starts_with("Output already exists:"),
                "unexpected message: {msg}"
            );
        }
        other => panic!("expected InvalidInput(Output already exists), got {other:?}"),
    }
    assert_eq!(
        kdf_event_count.get(),
        0,
        "Argon2id ran before the output-conflict preflight"
    );
}

/// Companion to the test above: a dangling symlink at the encrypt
/// output path must reject up front. `Path::exists()` follows the link
/// and would return `false` (target missing), letting Argon2id run
/// before the atomic no-clobber rename finally refuses to overwrite.
/// The fix routes the precheck through `symlink_metadata`, so a
/// `DerivingPassphraseWrapKey` event count of 0 on the failing run
/// proves the user did not pay for a multi-second KDF to learn that a
/// stale symlink occupies the destination. Pinned for BUG_REVIEW #3.
#[cfg(unix)]
#[test]
fn encryptor_passphrase_rejects_dangling_symlink_at_output_before_kdf() {
    use std::os::unix::fs::symlink;

    let work = fresh_workspace("rejects_dangling_symlink_before_kdf");
    let input = work.join("data.txt");
    fs::write(&input, b"dangling-symlink preflight").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    let dangling = out_dir.join("data.fcr");
    symlink(out_dir.join("absent-target"), &dangling).unwrap();
    assert!(!dangling.exists(), "sanity: target really is missing");

    let kdf_event_count = std::cell::Cell::new(0u32);
    let result = fast_passphrase_encryptor(pass()).write(&input, &out_dir, |evt| {
        if matches!(evt, ferrocrypt::ProgressEvent::DerivingPassphraseWrapKey) {
            kdf_event_count.set(kdf_event_count.get() + 1);
        }
    });

    match result {
        Err(CryptoError::InvalidInput(msg)) => {
            assert!(
                msg.starts_with("Output already exists:"),
                "unexpected message: {msg}"
            );
        }
        other => panic!("expected InvalidInput(Output already exists), got {other:?}"),
    }
    assert_eq!(
        kdf_event_count.get(),
        0,
        "Argon2id ran before the dangling-symlink preflight"
    );
}

/// `PrivateKeyDecryptor::decrypt` re-probes the input before the
/// `private.key` unlock. A file replacement between `Decryptor::open`
/// and `.decrypt` must not trigger the Argon2id unlock or its
/// `UnlockingPrivateKey` event.
#[test]
fn private_key_decrypt_re_probes_input_before_unlock() {
    let work = fresh_workspace("private_key_decrypt_re_probe");
    let keys = work.join("keys");
    fs::create_dir_all(&keys).unwrap();
    let kg = generate_key_pair(&keys, pass(), |_| {}).expect("keygen");
    let input = work.join("data.txt");
    fs::write(&input, b"payload").unwrap();
    let out_dir = work.join("out");
    fs::create_dir_all(&out_dir).unwrap();

    let outcome = Encryptor::with_public_key(PublicKey::from_key_file(&kg.public_key_path))
        .write(&input, &out_dir, |_| {})
        .expect("encrypt");

    let decryptor = match Decryptor::open(&outcome.output_path).expect("open") {
        Decryptor::PrivateKey(d) => d,
        other => panic!("expected private-key decryptor, got {other:?}"),
    };

    // Simulate a hostile path swap between `open` and `decrypt`:
    // replace the .fcr bytes with something that fails the magic check.
    fs::write(&outcome.output_path, b"NOT-AN-FCR-FILE").unwrap();

    let unlock_event_count = std::cell::Cell::new(0u32);
    let restore = work.join("restored");
    fs::create_dir_all(&restore).unwrap();
    let err = decryptor
        .decrypt(
            PrivateKey::from_key_file(&kg.private_key_path),
            pass(),
            &restore,
            |evt| {
                if matches!(evt, ferrocrypt::ProgressEvent::UnlockingPrivateKey) {
                    unlock_event_count.set(unlock_event_count.get() + 1);
                }
            },
        )
        .expect_err("expected rejection of swapped .fcr");

    match err {
        CryptoError::InvalidFormat(FormatDefect::BadMagic) => {}
        other => panic!("expected BadMagic from re-probe, got {other:?}"),
    }
    assert_eq!(
        unlock_event_count.get(),
        0,
        "Argon2id unlock ran before the re-probe rejection",
    );
}