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
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
//! High-level FerroCrypt operation flow.
//!
//! This is the only module that may coordinate all of:
//!
//! 1. generating a file key,
//! 2. generating the stream nonce,
//! 3. calling recipient schemes to wrap the file key,
//! 4. building the authenticated header,
//! 5. calling archive encoding/decoding,
//! 6. constructing payload stream encryptors/decryptors,
//! 7. finalising staged output,
//! 8. emitting progress events.
//!
//! Algorithm-specific logic plugs in via the [`RecipientScheme`] /
//! [`DecryptionCredential`] traits — both `pub(crate)`. Recipient modules
//! produce / consume opaque [`RecipientBody`] bytes; only this module
//! constructs full headers or verifies the header MAC.
//!
//! ## Decrypt acceptance order (`FORMAT.md` §3.7)
//!
//! 1. Read prefix.
//! 2. Reject bad magic / version / kind / flags / header length.
//! 3. Read header and header MAC.
//! 4. Structurally parse header and recipient entries.
//! 5. Reject malformed flags, unknown critical recipients, illegal
//!    mixing.
//! 6. Apply local resource caps.
//! 7. Iterate supported recipient slots in declared order.
//! 8. Verify header MAC with the candidate `FileKey` — final
//!    acceptance gate per slot.
//! 9. Validate authenticated TLV bytes only after MAC success.
//! 10. Derive payload key.
//! 11. STREAM-decrypt the payload.
//! 12. Decode the archive with path / resource checks before writes.
//! 13. Promote staged output only on success.
//!
//! No refactor may move TLV interpretation, archive writes, or payload
//! plaintext release before the relevant authentication step.

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

use crate::archive::{ArchiveLimits, IncompleteOutputPolicy, unarchive};
use crate::container::{
    HeaderReadLimits, build_encrypted_header, read_encrypted_header, resolve_encrypted_output_path,
    write_encrypted_file,
};
use crate::crypto::keys::{DerivedSubkeys, FileKey, derive_subkeys, random_bytes};
use crate::crypto::stream::{STREAM_NONCE_SIZE, payload_decryptor};
use crate::crypto::tlv::validate_tlv;
use crate::error::CryptoError;
use crate::format;
use crate::fs::paths::{encryption_base_name, reject_occupied};
use crate::recipient::entry::{RecipientBody, RecipientEntry};
#[cfg(test)]
use crate::recipient::policy::MixingPolicy;
use crate::recipient::policy::{NativeMixingRule, NativeRecipientType, classify_recipient_mode};
use crate::{ProgressEvent, UnauthenticatedRecipientMode};

/// Encrypt-side scheme: turn a [`FileKey`] into a recipient body of
/// scheme-specific bytes.
///
/// `TYPE_NAME` and `MIXING_RULE` are associated constants so the
/// multi-recipient `encrypt` orchestrator can enforce the mixing rule
/// before any KDF runs. Implementations must NOT build full
/// [`RecipientEntry`] framing or compute the header MAC — those
/// concerns live in this module.
///
/// `on_event` lets schemes whose wrap step is expensive (today only
/// `argon2id`) emit [`ProgressEvent::DerivingPassphraseWrapKey`] at the
/// actual KDF call site. Schemes whose wrap is cheap (X25519: one
/// scalar mult + one HKDF, sub-millisecond) MUST ignore the parameter
/// — emitting from them would lie about a long pause that never
/// happens.
pub(crate) trait RecipientScheme {
    const TYPE_NAME: &'static str;
    const MIXING_RULE: NativeMixingRule;

    fn wrap_file_key(
        &self,
        file_key: &FileKey,
        on_event: &dyn Fn(&ProgressEvent),
    ) -> Result<RecipientBody, CryptoError>;
}

/// Decrypt-side scheme: try to unwrap a candidate [`FileKey`] from a
/// recipient body whose `type_name` already matched
/// `DecryptionCredential::TYPE_NAME` — the orchestrator pre-filters slots
/// before calling this.
///
/// Return shape:
///
/// - `Ok(Some(file_key))` — AEAD authentication succeeded; the caller
///   now MUST verify the header MAC under the derived `header_key`
///   before accepting the candidate (`FORMAT.md` §3.7 step 8).
/// - `Ok(None)` — AEAD authentication failed on a structurally-valid
///   body. Caller skips this slot and tries the next supported one.
///   This is the ONLY meaning of `Ok(None)`; hard failures (KDF cap
///   exceeded, malformed embedded KDF params, structural defects in
///   the body shape) are `Err(CryptoError::*)`.
///
/// `on_event` lets schemes whose unwrap step is expensive (today only
/// `argon2id`) emit [`ProgressEvent::DerivingPassphraseWrapKey`] at the
/// actual KDF call site. Schemes whose unwrap is cheap (X25519: one
/// scalar mult + one HKDF, sub-millisecond) MUST ignore the parameter.
pub(crate) trait DecryptionCredential {
    const TYPE_NAME: &'static str;
    /// File mode this credential scheme can decrypt. Used by the
    /// orchestrator to surface a typed
    /// [`CryptoError::DecryptorModeMismatch`] when a caller drives
    /// `decrypt` with the wrong credential for the file's recipient list.
    const EXPECTED_MODE: UnauthenticatedRecipientMode;

    fn unwrap_file_key(
        &self,
        body: &[u8],
        on_event: &dyn Fn(&ProgressEvent),
    ) -> Result<Option<FileKey>, CryptoError>;
}

// ─── Encrypt ───────────────────────────────────────────────────────────────

/// Encrypts `input_path` under one or more recipients of a single
/// scheme. Wire format is the v1 `.fcr` container with `recipients.len()`
/// entries whose type matches `R::TYPE_NAME`. Every entry seals the same
/// per-file `file_key` for its respective recipient.
///
/// Defense-in-depth checks (run by this function regardless of caller):
///
/// - `recipients` MUST be non-empty (the public API enforces this at
///   construction time; the orchestrator double-checks).
/// - If `R::MIXING_RULE.requires_single_entry()` then `recipients.len()`
///   MUST be exactly 1. The public API can only reach this code with a
///   single passphrase, but the assertion stops a future caller bypass
///   from emitting an `argon2id` file with two bodies (`FORMAT.md` §4.1
///   forbids it).
///
/// # Caller obligations
///
/// This function is `pub(crate)` and **does not** enforce
/// [`crate::HeaderReadLimits`] caps (`max_recipient_count`,
/// `max_recipient_body_len`, `max_header_len`) or run
/// [`crate::KdfParams`] structural / resource-cap validation against
/// caller-supplied passphrase parameters. Those checks are the
/// **api-layer's** responsibility and live in
/// [`crate::api::Encryptor::write`] via
/// `api::preflight_header_write_limits` and
/// [`crate::KdfParams::validate_for_write`]. The same applies to the
/// non-empty-passphrase check in [`crate::api::validate_passphrase`].
///
/// Any new in-crate caller of `protocol::encrypt` MUST run those
/// preflight steps first (or accept the resulting symmetry break with
/// the default reader). Tests in `protocol.rs::tests` deliberately
/// bypass them to construct forward-compat fixtures; production
/// callers must not.
pub(crate) fn encrypt<R: RecipientScheme>(
    recipients: &[R],
    archive_limits: ArchiveLimits,
    input_path: &Path,
    output_dir: &Path,
    output_file: Option<&Path>,
    on_event: &dyn Fn(&ProgressEvent),
) -> Result<PathBuf, CryptoError> {
    if recipients.is_empty() {
        return Err(CryptoError::EmptyRecipientList);
    }
    if R::MIXING_RULE.requires_single_entry() && recipients.len() > 1 {
        return Err(CryptoError::IncompatibleRecipients {
            type_name: R::TYPE_NAME.to_string(),
            policy: R::MIXING_RULE.diagnostic_policy(),
        });
    }

    // Resolve the destination path and reject a pre-existing output
    // BEFORE any expensive key work runs. In passphrase mode this saves
    // a multi-second Argon2id derivation when the user re-runs encrypt
    // against a populated directory. The atomic no-clobber rename in
    // `write_encrypted_file` is still the load-bearing guarantee that
    // we never overwrite an unrelated file; this preflight is a
    // user-experience win that also defends against dangling-symlink
    // outputs (via `reject_occupied` → `symlink_metadata`).
    let base_name = encryption_base_name(input_path)?;
    let output_path = resolve_encrypted_output_path(output_dir, output_file, &base_name);
    reject_occupied(&output_path, "Output")?;

    // No early progress event here. Each recipient scheme emits its
    // own work-boundary event from inside `wrap_file_key`. For the
    // passphrase-only case, that's exactly one
    // `DerivingPassphraseWrapKey` immediately before Argon2id; for
    // pure X25519 wrapping (sub-millisecond), no event fires until
    // `Encrypting` below — which is what the orchestrator wants:
    // signal what the user can perceive, stay silent for what they
    // can't.

    // Generate per-file random material first so the rest of the build
    // is a pure function of (file_key, recipient input, stream_nonce,
    // input bytes). file_key is held in `Zeroizing` inside the typed
    // newtype, so an early return wipes it.
    let file_key = FileKey::generate()?;
    let stream_nonce = random_bytes::<STREAM_NONCE_SIZE>()?;
    let DerivedSubkeys {
        payload_key,
        header_key,
    } = derive_subkeys(&file_key, &stream_nonce)?;

    // Wrap the file_key for each recipient under the same scheme. After
    // the bodies are built, the raw file_key is no longer needed; drop
    // it immediately so the plaintext window in memory is minimal.
    let mut entries = Vec::with_capacity(recipients.len());
    for recipient in recipients {
        let body = recipient.wrap_file_key(&file_key, on_event)?;
        entries.push(build_native_entry(R::TYPE_NAME, body)?);
    }
    drop(file_key);

    // Assemble prefix + header + MAC. `build_encrypted_header` owns the
    // single byte-arithmetic implementation; encrypt and decrypt share
    // its MAC scope.
    let built = build_encrypted_header(
        &entries,
        b"", // v1.0 writers emit ext_len = 0
        stream_nonce,
        payload_key,
        &header_key,
    )?;
    drop(header_key);

    on_event(&ProgressEvent::Encrypting);

    write_encrypted_file(
        input_path,
        output_dir,
        output_file,
        &base_name,
        &built,
        archive_limits,
    )
}

/// Builds a `RecipientEntry` from a scheme-produced body, validating
/// that the declared scheme is one of the recognised native types.
/// `RecipientEntry::native` enforces the canonical body length for the
/// type, so a scheme that returns the wrong number of bytes fails here.
fn build_native_entry(
    type_name: &'static str,
    body: RecipientBody,
) -> Result<RecipientEntry, CryptoError> {
    debug_assert_eq!(body.type_name, type_name);
    let ty = NativeRecipientType::from_type_name(type_name)
        .ok_or(CryptoError::InternalInvariant("Unknown native scheme"))?;
    RecipientEntry::native(ty, body.bytes)
}

// ─── Decrypt ───────────────────────────────────────────────────────────────

/// Decrypts `input_path` using the supplied credential scheme.
///
/// Iterates every supported recipient slot in declared order before
/// emitting a final verdict. The slot loop is identical for the
/// single-candidate (passphrase) and multi-candidate (X25519) cases —
/// the passphrase path is just a slot loop of length 1. Visiting every
/// supported slot, rather than short-circuiting on the first MAC
/// match, makes wall-clock cost a function of `recipient_count`
/// (capped by `HeaderReadLimits`) rather than of which slot matched,
/// per the `FORMAT.md` §3.7 SHOULD-level mitigation.
pub(crate) fn decrypt<I: DecryptionCredential>(
    credential: &I,
    input_path: &Path,
    output_dir: &Path,
    archive_limits: ArchiveLimits,
    header_read_limits: HeaderReadLimits,
    incomplete_output_policy: IncompleteOutputPolicy,
    on_event: &dyn Fn(&ProgressEvent),
) -> Result<PathBuf, CryptoError> {
    let mut encrypted_file = fs::File::open(input_path)?;

    // 1-4. Structural read + parse. Performs zero crypto; enforces
    //      local caps before any allocation.
    let parsed = read_encrypted_header(&mut encrypted_file, header_read_limits)?;

    // 5. Reject illegal mixing and unknown critical recipients before
    //    any expensive recipient work. `classify_recipient_mode`
    //    runs `enforce_recipient_mixing_policy` internally, so the
    //    mixing-policy check happens here even though it isn't called
    //    by name.
    let mode = classify_recipient_mode(&parsed.recipient_entries)?;

    // Cross-mode mismatch: caller invoked the passphrase decrypt path
    // on a recipient-only file (or vice versa). The classified mode
    // does not match the credential's scheme. Surfaces as a typed
    // `DecryptorModeMismatch` rather than `NoSupportedRecipient`, which
    // would imply "the loop iterated and found nothing" — misleading
    // when the real cause is "wrong tool for this file." The public
    // API can't reach this branch (Decryptor::open routes by mode);
    // it exists for internal callers and any future plugin-style API.
    check_mode_matches_scheme::<I>(mode)?;

    // No early progress event here. Progress events fire at the actual
    // KDF call boundary inside each scheme's `unwrap_file_key`. For the
    // passphrase mode, that means the slot-loop Argon2id emission lives
    // inside `recipient::native::argon2id::unwrap`, which fires
    // `DerivingPassphraseWrapKey` only after the per-slot structural /
    // resource-cap checks have passed. For the recipient (X25519) mode,
    // the heaviest KDF (the `private.key` Argon2id unlock) already ran
    // *before* this function was entered — `PrivateKeyDecryptor::decrypt`
    // calls `open_x25519_private_key` first, and that call emits
    // `UnlockingPrivateKey` at its own work boundary inside
    // `key::private::open_private_key`.

    // 7-8. Iterate supported recipient slots. Per FORMAT.md §3.7 the
    //      candidate `file_key` is not final until the header MAC also
    //      verifies under the derived `header_key`.
    let stream_nonce = parsed.fixed.stream_nonce;
    let mut had_successful_unwrap = false;
    let mut selected_payload_key: Option<crate::crypto::keys::PayloadKey> = None;

    for entry in parsed.recipient_entries.iter() {
        if entry.type_name != I::TYPE_NAME {
            // Unknown non-critical entries: skipped. Critical unknowns
            // were rejected in step 5.
            continue;
        }
        // Native v1 recipients do not use the critical bit — the
        // reader handles them natively. A native entry with the bit
        // set is structurally malformed and aborts the whole file.
        if entry.recipient_flags != 0 {
            return Err(CryptoError::InvalidFormat(
                crate::error::FormatDefect::MalformedRecipientEntry,
            ));
        }
        let file_key = match credential.unwrap_file_key(&entry.body, on_event)? {
            Some(k) => k,
            None => continue,
        };
        had_successful_unwrap = true;

        let DerivedSubkeys {
            payload_key,
            header_key,
        } = derive_subkeys(&file_key, &stream_nonce)?;
        drop(file_key);

        // Header MAC is the final acceptance gate. The first slot
        // whose MAC verifies wins; the loop does NOT short-circuit
        // there — every supported slot still attempts unwrap, so wall
        // time does not betray which MAC-verified slot matched
        // (FORMAT.md §3.7 SHOULD-level mitigation). Slots whose AEAD
        // unwrap fails (`Ok(None)`) skip the `derive_subkeys` and the
        // `verify_header_mac` below, so a residual delta of
        // ~one HKDF + one HMAC remains between AEAD-pass and AEAD-fail
        // slots. That delta is informationally redundant with the
        // overall decrypt success/failure signal — under one private
        // key, at most one slot AEAD-passes, so the delta only reveals
        // "some slot matched", which the success outcome already
        // tells the observer. Crucially, the delta does NOT depend on
        // the matching slot's position in the list, so §3.7's
        // recipient-anonymity goal is preserved without requiring
        // unconditional derive_subkeys + verify_header_mac on every
        // AEAD-fail slot.
        if format::verify_header_mac(
            &parsed.prefix_bytes,
            &parsed.header_bytes,
            &header_key,
            &parsed.header_mac,
        )
        .is_ok()
            && selected_payload_key.is_none()
        {
            selected_payload_key = Some(payload_key);
        }
        drop(header_key);
    }

    let Some(payload_key) = selected_payload_key else {
        // No slot MAC-verified. [`failure_for`]'s `(mode × had_unwrap)`
        // matrix picks the surfaced variant.
        return Err(failure_for(mode, I::TYPE_NAME, had_successful_unwrap));
    };

    // 9. TLV validation runs AFTER MAC verify, so the validator is
    //    operating on authenticated bytes.
    validate_tlv(&parsed.ext_bytes)?;

    // 10-12. STREAM payload decrypt + unarchive. Path / resource caps
    //        are enforced inside `unarchive` before any write.
    on_event(&ProgressEvent::Decrypting);
    let decrypt_reader = payload_decryptor(&payload_key, &stream_nonce, encrypted_file);
    unarchive(
        decrypt_reader,
        output_dir,
        archive_limits,
        incomplete_output_policy,
    )
}

/// Verifies that the classified file mode matches the credential scheme's
/// declared [`DecryptionCredential::EXPECTED_MODE`]. On mismatch, returns a
/// typed [`CryptoError::DecryptorModeMismatch`] carrying both modes so
/// the caller can pattern-match without comparing strings.
fn check_mode_matches_scheme<I: DecryptionCredential>(
    mode: UnauthenticatedRecipientMode,
) -> Result<(), CryptoError> {
    if mode == I::EXPECTED_MODE {
        return Ok(());
    }
    Err(CryptoError::DecryptorModeMismatch {
        expected: I::EXPECTED_MODE,
        found: mode,
    })
}

/// Decrypt-time error wording when no slot MAC-verified. Indexed by
/// `(mode × had_unwrap)`:
///
/// | mode       | had_unwrap | error                                       |
/// |------------|-----------:|---------------------------------------------|
/// | Passphrase | false      | `RecipientUnwrapFailed { type_name }`       |
/// | Passphrase | true       | `HeaderTampered`                            |
/// | PublicKey  | false      | `NoSupportedRecipient` (list-exhaustion)    |
/// | PublicKey  | true       | `HeaderMacFailedAfterUnwrap { type_name }`  |
///
/// `(Passphrase, false)` keeps the per-candidate variant because a
/// passphrase file has exactly one supported candidate and the
/// wrong-passphrase / tampered-body ambiguity is the more accurate
/// diagnostic.
fn failure_for(
    mode: UnauthenticatedRecipientMode,
    type_name: &'static str,
    had_unwrap: bool,
) -> CryptoError {
    match (mode, had_unwrap) {
        (UnauthenticatedRecipientMode::Passphrase, false) => CryptoError::RecipientUnwrapFailed {
            type_name: type_name.to_string(),
        },
        (UnauthenticatedRecipientMode::Passphrase, true) => CryptoError::HeaderTampered,
        (UnauthenticatedRecipientMode::PublicKey, false) => CryptoError::NoSupportedRecipient,
        (UnauthenticatedRecipientMode::PublicKey, true) => {
            CryptoError::HeaderMacFailedAfterUnwrap {
                type_name: type_name.to_string(),
            }
        }
    }
}

// ─── Key-pair generation ───────────────────────────────────────────────────

/// Generates an X25519 key pair and writes both files to `output_dir`.
/// Returns `(private_key_path, public_key_path)`.
///
/// - `private.key` is the v1 passphrase-wrapped binary keyfile.
///   `key::private::seal_private_key` owns the byte layout (cleartext
///   header → AEAD-AAD-bound → wrapped secret). Permissions: `0o600`
///   on Unix.
/// - `public.key` is a UTF-8 text file containing the canonical
///   `fcr1…` Bech32 recipient string. Permissions: `0o644` on Unix
///   (public keys are not secret).
///
/// # Caller obligations
///
/// This function is `pub(crate)` and **does not** validate the
/// caller-supplied [`crate::KdfParams`] against v1 structural bounds
/// or against a [`crate::KdfLimit`] resource cap. Those checks are
/// the **api-layer's** responsibility and live in
/// [`crate::api::KeyPairGenerator::write`] via
/// [`crate::KdfParams::validate_for_write`]. The same applies to the
/// non-empty-passphrase check in [`crate::api::validate_passphrase`].
///
/// Any new in-crate caller MUST run those preflight steps first
/// (or accept the resulting symmetry break with the default reader's
/// `PrivateKeyDecryptor::decrypt`).
pub(crate) fn generate_key_pair(
    passphrase: &secrecy::SecretString,
    kdf_params: &crate::crypto::kdf::KdfParams,
    output_dir: &Path,
    on_event: &dyn Fn(&ProgressEvent),
) -> Result<(PathBuf, PathBuf, String), CryptoError> {
    use std::io::Write as _;

    use crate::fs::atomic;
    use crate::key::files::{PRIVATE_KEY_FILENAME, PUBLIC_KEY_FILENAME};
    use crate::key::private::seal_private_key;
    use crate::key::public::{encode_recipient_string, fingerprint_hex};
    use crate::recipient::native::x25519;

    fs::create_dir_all(output_dir)?;

    // Existence pre-check BEFORE Argon2id so re-running `keygen` against
    // a populated directory returns a helpful error in milliseconds
    // instead of after ~1 GiB / multi-second KDF work. Uses
    // `symlink_metadata` (via `reject_occupied`) so a dangling
    // `private.key` / `public.key` symlink also rejects up front
    // rather than slipping past `Path::exists()` and surviving until
    // the atomic no-clobber rename at `finalize_file` below — which is
    // still the load-bearing guarantee that we never overwrite an
    // existing key.
    let private_key_path = output_dir.join(PRIVATE_KEY_FILENAME);
    let public_key_path = output_dir.join(PUBLIC_KEY_FILENAME);
    reject_occupied(&private_key_path, "Key file")?;
    reject_occupied(&public_key_path, "Key file")?;

    on_event(&ProgressEvent::GeneratingKeyPair);

    // Generate the X25519 keypair via the recipient module. The secret
    // material is returned in `Zeroizing` so it's wiped from memory
    // when this stack frame unwinds, regardless of whether the
    // subsequent seal/write succeeds.
    let (secret_material, public_material) = x25519::generate_keypair()?;

    // Hand off all `private.key` byte-layout, AEAD, and AAD scope to
    // `key/private.rs` — the single source of truth.
    let private_key_bytes = seal_private_key(
        secret_material.as_ref(),
        x25519::TYPE_NAME,
        &public_material,
        &[], // no v1 ext_bytes for the X25519 case
        passphrase,
        kdf_params,
    )?;
    drop(secret_material);

    // Encode the canonical `fcr1…` recipient string via `key/public.rs`
    // (validates type-name grammar, computes the internal SHA3-256
    // checksum, emits BIP 173 lowercase Bech32).
    let recipient_string = encode_recipient_string(x25519::TYPE_NAME, &public_material)?;

    // Write public.key (text file, `fcr1…\n`). Public key isn't secret
    // so permissions relax to 0o644 on Unix.
    let mut public_builder = tempfile::Builder::new();
    public_builder
        .prefix(".ferrocrypt-public_key-")
        .suffix(".tmp");
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        public_builder.permissions(fs::Permissions::from_mode(0o644));
    }
    let mut public_tmp = public_builder.tempfile_in(output_dir)?;
    public_tmp
        .as_file_mut()
        .write_all(recipient_string.as_bytes())?;
    public_tmp.as_file_mut().write_all(b"\n")?;
    public_tmp.as_file().sync_all()?;
    atomic::finalize_file(public_tmp, &public_key_path)?;

    // Write private.key. If this fails, clean up the public.key we
    // just wrote (public keys are not secret, but leaving orphaned
    // output is unfriendly).
    let private_write: Result<(), CryptoError> = (|| {
        let mut private_builder = tempfile::Builder::new();
        private_builder
            .prefix(".ferrocrypt-private_key-")
            .suffix(".tmp");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            private_builder.permissions(fs::Permissions::from_mode(0o600));
        }
        let mut private_tmp = private_builder.tempfile_in(output_dir)?;
        private_tmp.as_file_mut().write_all(&private_key_bytes)?;
        private_tmp.as_file().sync_all()?;
        atomic::finalize_file(private_tmp, &private_key_path)?;
        Ok(())
    })();

    if let Err(e) = private_write {
        let _ = fs::remove_file(&public_key_path);
        return Err(e);
    }

    // Compute the fingerprint from the in-memory `public_material`
    // rather than re-reading and re-decoding `public.key` from disk.
    // The bytes here are the same ones the recipient string just
    // encoded, so the fingerprint matches what
    // `PublicKey::from_key_file(...).fingerprint()` would produce —
    // without paying the extra disk read + Bech32 decode + SHA3 in
    // the API layer.
    let fingerprint = fingerprint_hex(x25519::TYPE_NAME, &public_material);

    Ok((private_key_path, public_key_path, fingerprint))
}

#[cfg(test)]
mod tests {
    //! Forward-compat multi-recipient tests (FORMAT.md §3.4 / §3.5).
    //!
    //! The single-recipient public encrypt API can't produce
    //! multi-recipient files, so these tests build the on-disk bytes
    //! by hand using `container::build_encrypted_header` and exercise
    //! the decrypt path against the resulting fixtures. They lock in:
    //! list iteration on `x25519`, skip unknown non-critical, reject
    //! unknown critical, reject argon2id mixing before any KDF runs,
    //! enforce the local body cap on unknown entries, and the
    //! attempt-all-slots timing-leak mitigation.
    //!
    //! Round-trip and basic tampering coverage lives in the
    //! integration test suite (`tests/integration_tests.rs`) plus the
    //! fixture-stability suite (`tests/fixture_stability.rs`).
    use super::*;
    use crate::container::build_encrypted_header;
    use crate::crypto::stream::payload_encryptor;
    use crate::error::FormatDefect;
    use crate::format;
    use crate::key::public::read_public_key;
    use crate::recipient::entry::RECIPIENT_FLAG_CRITICAL;
    use crate::recipient::native::{argon2id, x25519};
    use crate::recipient::policy::NativeRecipientType;
    use secrecy::SecretString;

    /// Build a complete `.fcr` byte sequence with the given recipient
    /// entries and plaintext. The caller has already wrapped `file_key`
    /// for each entry that actually needs to unwrap; entries with
    /// arbitrary bodies (synthetic unknown types, hostile mixes) are
    /// kept verbatim.
    fn build_multi_recipient_fcr(
        entries: &[RecipientEntry],
        file_key: &FileKey,
        plaintext: &[u8],
        path: &Path,
    ) -> Result<(), CryptoError> {
        let stream_nonce = random_bytes::<STREAM_NONCE_SIZE>()?;
        let DerivedSubkeys {
            payload_key,
            header_key,
        } = derive_subkeys(file_key, &stream_nonce)?;

        let built = build_encrypted_header(entries, b"", stream_nonce, payload_key, &header_key)?;

        // Encrypt a single-file FCA payload into a buffer. Constructs
        // the FCA header + manifest + content for one entry named
        // "data.txt"; matches what `archive::archive` would emit
        // for that input.
        let mut payload_buf: Vec<u8> = Vec::new();
        {
            use crate::archive::ArchiveLimits;
            use crate::archive::format::{serialize_manifest, write_fca_header};
            use crate::archive::model::{ArchiveEntryKind, Manifest, make_entry};
            use std::ffi::OsString;
            use std::io::Write;

            let manifest = Manifest {
                entries: vec![make_entry(
                    "data.txt",
                    ArchiveEntryKind::File,
                    plaintext.len() as u64,
                    0o644,
                )],
                total_file_bytes: plaintext.len() as u64,
                root_name: OsString::from("data.txt"),
                root_is_file: true,
                root_mode: 0o644,
            };
            let manifest_bytes = serialize_manifest(&manifest, ArchiveLimits::default())?;

            let mut writer =
                payload_encryptor(&built.payload_key, &built.stream_nonce, &mut payload_buf);
            writer = write_fca_header(
                writer,
                1,
                0,
                manifest_bytes.len() as u32,
                plaintext.len() as u64,
            )?;
            writer.write_all(&manifest_bytes).map_err(CryptoError::Io)?;
            writer.write_all(plaintext).map_err(CryptoError::Io)?;
            let _ = writer.finish()?;
        }

        let mut buf: Vec<u8> = Vec::new();
        buf.extend_from_slice(&built.prefix_bytes);
        buf.extend_from_slice(&built.header_bytes);
        buf.extend_from_slice(&built.header_mac);
        buf.extend_from_slice(&payload_buf);
        fs::write(path, &buf)?;
        Ok(())
    }

    /// Generates an X25519 keypair, persists a v1 `private.key` for it,
    /// and returns `(public_bytes, private_key_path, passphrase)`.
    fn keypair_fixture(
        keys_dir: &Path,
        label: &str,
        pass: &str,
    ) -> Result<([u8; 32], PathBuf, SecretString), CryptoError> {
        let pass = SecretString::from(pass.to_string());
        let dir = keys_dir.join(label);
        fs::create_dir_all(&dir)?;
        let (private_key_path, public_key_path, _fingerprint) = generate_key_pair(
            &pass,
            &crate::crypto::kdf::KdfParams::test_fast_default(),
            &dir,
            &|_| {},
        )?;
        let pub_bytes = read_public_key(&public_key_path)?.bytes;
        Ok((pub_bytes, private_key_path, pass))
    }

    /// Decrypt helper: opens the X25519 `private.key`, builds an
    /// `X25519Credential`, and runs the orchestrator's slot loop directly
    /// (mirrors what `PrivateKeyDecryptor::decrypt` does in `api.rs` but
    /// preserves raw error variants for assertion).
    fn recipient_decrypt(
        fcr: &Path,
        dec_dir: &Path,
        private_key_path: &Path,
        pass: &SecretString,
    ) -> Result<PathBuf, CryptoError> {
        let private_key_bytes =
            x25519::open_x25519_private_key(private_key_path, pass, None, &|_| {})?;
        let credential = x25519::X25519Credential { private_key_bytes };
        decrypt(
            &credential,
            fcr,
            dec_dir,
            ArchiveLimits::default(),
            HeaderReadLimits::default(),
            IncompleteOutputPolicy::default(),
            &|_| {},
        )
    }

    /// Two `x25519` recipients in one file: the decrypt loop must
    /// iterate the list and accept whichever slot the caller's
    /// private key matches.
    #[test]
    fn multi_x25519_decrypts_via_either_recipient() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;
        let (pub_b, priv_b, pass_b) = keypair_fixture(&keys_dir, "bob", "bob-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let body_b = x25519::wrap(&file_key, &pub_b)?;
        let entries = [
            RecipientEntry::native(NativeRecipientType::X25519, body_a.to_vec())?,
            RecipientEntry::native(NativeRecipientType::X25519, body_b.to_vec())?,
        ];

        let payload = b"two-x25519 round trip";
        let fcr = tmp.path().join("multi.fcr");
        build_multi_recipient_fcr(&entries, &file_key, payload, &fcr)?;

        for (label, private_key, pass) in [("alice", &priv_a, &pass_a), ("bob", &priv_b, &pass_b)] {
            let dec_dir = tmp.path().join(format!("decrypted-{label}"));
            fs::create_dir_all(&dec_dir)?;
            recipient_decrypt(&fcr, &dec_dir, private_key, pass)?;
            let restored = fs::read(dec_dir.join("data.txt"))?;
            assert_eq!(
                restored, payload,
                "{label} should decrypt the same plaintext"
            );
        }
        Ok(())
    }

    /// FORMAT.md §3.7 SHOULD-level mitigation: the decrypt loop must
    /// visit every supported `x25519` slot before deciding, not
    /// short-circuit on the first MAC-verified one.
    #[test]
    fn multi_x25519_attempt_all_visits_every_slot() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let valid_slot = RecipientEntry::native(NativeRecipientType::X25519, body_a.to_vec())?;
        // Bypass `RecipientEntry::native`'s body-length validation —
        // the parser accepts any body_len within the local cap, so an
        // attacker-forged file can carry a wrong-length `x25519` slot
        // that we must reject.
        let malformed_slot = RecipientEntry {
            type_name: x25519::TYPE_NAME.to_string(),
            recipient_flags: 0,
            body: vec![0u8; x25519::BODY_LENGTH - 4],
        };
        let entries = [valid_slot, malformed_slot];

        let fcr = tmp.path().join("multi-attempt-all.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"x", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        let err = recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a).unwrap_err();
        match err {
            CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry) => Ok(()),
            other => panic!(
                "expected MalformedRecipientEntry from slot-2 inspection (proves attempt-all); got {other:?}"
            ),
        }
    }

    /// FORMAT.md §2.4 / §4.2: an `x25519` recipient slot whose ECDH
    /// shared secret is all-zero MUST cause file-fatal rejection, not
    /// slot-skip — the all-zero shared is credential-independent
    /// (every decryptor observes the same value), so it cannot be
    /// confused with "this slot was for someone else." The decrypt
    /// loop must reject the whole file even when an earlier valid
    /// slot has already MAC-verified.
    #[test]
    fn multi_x25519_all_zero_ephemeral_after_valid_is_file_fatal() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let valid_slot = RecipientEntry::native(NativeRecipientType::X25519, body_a.to_vec())?;

        // Hand-craft a malformed `x25519` body: literal all-zero
        // ephemeral public_key forces an all-zero ECDH shared secret per
        // RFC 7748 regardless of the recipient's private key. The rest
        // of the body is filler — the rejection fires before AEAD.
        let mut malformed_body = vec![0u8; x25519::BODY_LENGTH];
        malformed_body[x25519::BODY_LENGTH - 1] = 0xAB;
        let malformed_slot = RecipientEntry::native(NativeRecipientType::X25519, malformed_body)?;

        let entries = [valid_slot, malformed_slot];
        let fcr = tmp.path().join("zero-ephemeral-after.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"x", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        match recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a) {
            Err(CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry)) => Ok(()),
            other => panic!("all-zero shared secret in slot 2 must be file-fatal, got {other:?}"),
        }
    }

    /// Same property as
    /// [`multi_x25519_all_zero_ephemeral_after_valid_is_file_fatal`] but
    /// with the malformed slot first. The decrypt loop encounters the
    /// structural defect before reaching the valid slot; it must still
    /// reject the whole file rather than continuing past the malformed
    /// entry.
    #[test]
    fn multi_x25519_all_zero_ephemeral_before_valid_is_file_fatal() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let valid_slot = RecipientEntry::native(NativeRecipientType::X25519, body_a.to_vec())?;

        let mut malformed_body = vec![0u8; x25519::BODY_LENGTH];
        malformed_body[x25519::BODY_LENGTH - 1] = 0xAB;
        let malformed_slot = RecipientEntry::native(NativeRecipientType::X25519, malformed_body)?;

        let entries = [malformed_slot, valid_slot];
        let fcr = tmp.path().join("zero-ephemeral-before.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"x", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        match recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a) {
            Err(CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry)) => Ok(()),
            other => panic!("all-zero shared secret in slot 1 must be file-fatal, got {other:?}"),
        }
    }

    /// Single-recipient case: an `x25519` file with a single
    /// all-zero-ephemeral slot must also be file-fatal. Confirms the
    /// rejection path is independent of recipient cardinality.
    #[test]
    fn single_x25519_all_zero_ephemeral_is_file_fatal() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (_pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let mut malformed_body = vec![0u8; x25519::BODY_LENGTH];
        malformed_body[x25519::BODY_LENGTH - 1] = 0xAB;
        let entries = [RecipientEntry::native(
            NativeRecipientType::X25519,
            malformed_body,
        )?];

        let fcr = tmp.path().join("single-zero-ephemeral.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"x", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        match recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a) {
            Err(CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry)) => Ok(()),
            other => panic!("single all-zero-ephemeral file must be file-fatal, got {other:?}"),
        }
    }

    /// One supported `x25519` recipient plus one unknown non-critical
    /// recipient: the decrypt loop must skip the unknown entry and
    /// decrypt via the supported one. Entry order matters here — we
    /// place the unknown FIRST.
    #[test]
    fn multi_x25519_plus_unknown_non_critical_skips_unknown() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let unknown_entry = RecipientEntry {
            type_name: "example.com/unknown".to_string(),
            recipient_flags: 0,
            body: vec![0xCDu8; 64],
        };
        let entries = [
            unknown_entry,
            RecipientEntry::native(NativeRecipientType::X25519, body_a.to_vec())?,
        ];

        let payload = b"skip unknown non-critical";
        let fcr = tmp.path().join("skip.fcr");
        build_multi_recipient_fcr(&entries, &file_key, payload, &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a)?;
        let restored = fs::read(dec_dir.join("data.txt"))?;
        assert_eq!(restored, payload);
        Ok(())
    }

    /// One supported `x25519` recipient plus one unknown CRITICAL
    /// recipient: the file MUST be rejected as
    /// `UnknownCriticalRecipient` before any recipient unwrap or KDF
    /// runs.
    #[test]
    fn multi_unknown_critical_rejected_before_any_unwrap() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let unknown_critical = RecipientEntry {
            type_name: "example.com/critical".to_string(),
            recipient_flags: RECIPIENT_FLAG_CRITICAL,
            body: vec![0u8; 32],
        };
        let entries = [
            RecipientEntry::native(NativeRecipientType::X25519, body_a.to_vec())?,
            unknown_critical,
        ];

        let fcr = tmp.path().join("critical.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"x", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        match recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a) {
            Err(CryptoError::UnknownCriticalRecipient { ref type_name })
                if type_name == "example.com/critical" =>
            {
                Ok(())
            }
            other => {
                panic!("expected UnknownCriticalRecipient(example.com/critical), got {other:?}")
            }
        }
    }

    /// Mixing `argon2id` with any other recipient (here `x25519`) MUST
    /// be rejected as `IncompatibleRecipients { type_name: "argon2id", .. }`
    /// BEFORE Argon2id runs.
    #[test]
    fn multi_argon2id_plus_x25519_rejected_as_mixed() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_x = x25519::wrap(&file_key, &pub_a)?;
        let synthetic_argon2id = RecipientEntry {
            type_name: argon2id::TYPE_NAME.to_string(),
            recipient_flags: 0,
            body: vec![0u8; argon2id::BODY_LENGTH],
        };
        let entries = [
            synthetic_argon2id,
            RecipientEntry::native(NativeRecipientType::X25519, body_x.to_vec())?,
        ];

        let fcr = tmp.path().join("mixed.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"x", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        match recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a) {
            Err(CryptoError::IncompatibleRecipients { type_name, policy })
                if type_name == argon2id::TYPE_NAME && policy == MixingPolicy::Exclusive =>
            {
                Ok(())
            }
            other => panic!("expected IncompatibleRecipients(argon2id, Exclusive), got {other:?}"),
        }
    }

    /// An unknown non-critical recipient whose body sits at the local
    /// cap must be accepted (and skipped); above the cap must be
    /// rejected as a resource-cap violation.
    #[test]
    fn multi_unknown_body_at_local_cap_decrypts() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let unknown_at_cap = RecipientEntry {
            type_name: "example.com/at-cap".to_string(),
            recipient_flags: 0,
            body: vec![0xAB; format::BODY_LEN_LOCAL_CAP_DEFAULT as usize],
        };
        let entries = [
            unknown_at_cap,
            RecipientEntry::native(NativeRecipientType::X25519, body_a.to_vec())?,
        ];

        let fcr = tmp.path().join("at-cap.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"at-cap payload", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a)?;
        Ok(())
    }

    /// A public-key `.fcr` with no slot the caller's private key can
    /// AEAD-unwrap surfaces as `NoSupportedRecipient`, not
    /// per-candidate `RecipientUnwrapFailed`. File targets alice;
    /// decrypt with bob.
    #[test]
    fn multi_x25519_no_matching_recipient_surfaces_no_supported_recipient()
    -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, _priv_a, _pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;
        let (_pub_b, priv_b, pass_b) = keypair_fixture(&keys_dir, "bob", "bob-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let entries = [RecipientEntry::native(
            NativeRecipientType::X25519,
            body_a.to_vec(),
        )?];

        let fcr = tmp.path().join("alice-only.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"payload", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        match recipient_decrypt(&fcr, &dec_dir, &priv_b, &pass_b) {
            Err(CryptoError::NoSupportedRecipient) => Ok(()),
            other => panic!("expected NoSupportedRecipient, got {other:?}"),
        }
    }

    /// Decoy-unwrap test: slot A wraps a *decoy* `file_key`; the file's
    /// MAC and payload are keyed off a *different* real `file_key`.
    /// Alice's private key unwraps slot A successfully (yielding the
    /// decoy), but the resulting `header_key` does not verify the MAC.
    /// Slot B targets bob, so alice's private_key fails to unwrap it. The
    /// decrypt loop must surface `HeaderMacFailedAfterUnwrap`.
    #[test]
    fn multi_x25519_decoy_unwrap_returns_mac_failed_after_unwrap() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;
        let (pub_b, _priv_b, _pass_b) = keypair_fixture(&keys_dir, "bob", "bob-pass")?;

        let real_file_key = FileKey::generate().unwrap();
        let decoy_file_key = FileKey::generate().unwrap();

        let body_a = x25519::wrap(&decoy_file_key, &pub_a)?;
        let body_b = x25519::wrap(&decoy_file_key, &pub_b)?;
        let entries = [
            RecipientEntry::native(NativeRecipientType::X25519, body_a.to_vec())?,
            RecipientEntry::native(NativeRecipientType::X25519, body_b.to_vec())?,
        ];

        let fcr = tmp.path().join("decoy-unwrap.fcr");
        build_multi_recipient_fcr(&entries, &real_file_key, b"payload", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        match recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a) {
            Err(CryptoError::HeaderMacFailedAfterUnwrap { ref type_name })
                if type_name == x25519::TYPE_NAME =>
            {
                Ok(())
            }
            other => panic!("expected HeaderMacFailedAfterUnwrap(x25519), got {other:?}"),
        }
    }

    /// Defense-in-depth: an exclusive scheme (`argon2id`) MUST not be
    /// emitted with more than one recipient. The public API has no path
    /// to construct that, but a future caller bypass would break the
    /// `FORMAT.md` §4.1 mixing rule before any output bytes are
    /// written. The orchestrator catches this before any KDF runs.
    #[test]
    fn encrypt_rejects_multi_passphrase_recipient_list() -> Result<(), CryptoError> {
        let pass = SecretString::from("pass".to_string());
        let kdf_params = crate::crypto::kdf::KdfParams::test_fast_default();
        let r1 = argon2id::PassphraseRecipient {
            passphrase: &pass,
            kdf_params,
        };
        let r2 = argon2id::PassphraseRecipient {
            passphrase: &pass,
            kdf_params,
        };
        let recipients = [r1, r2];

        let tmp = tempfile::TempDir::new().unwrap();
        let input = tmp.path().join("data.txt");
        fs::write(&input, b"x")?;
        let out_dir = tmp.path().join("out");
        fs::create_dir_all(&out_dir)?;

        let err = encrypt(
            &recipients,
            ArchiveLimits::default(),
            &input,
            &out_dir,
            None,
            &|_| {},
        )
        .unwrap_err();
        match err {
            CryptoError::IncompatibleRecipients {
                ref type_name,
                policy: MixingPolicy::Exclusive,
            } if type_name == argon2id::TYPE_NAME => Ok(()),
            other => panic!("expected IncompatibleRecipients(argon2id, Exclusive), got {other:?}"),
        }
    }

    /// Cross-mode mismatch: a passphrase-only file is opened with an
    /// `X25519Credential`. The orchestrator must surface
    /// `DecryptorModeMismatch { expected: PublicKey, found: Passphrase }`
    /// before any slot loop runs — never the legacy
    /// `NoSupportedRecipient`, which would imply "the loop iterated and
    /// found nothing." The public Decryptor::open routes by mode and so
    /// can't reach this branch; the test invokes `protocol::decrypt`
    /// directly to lock in the wording for internal/plugin callers.
    #[test]
    fn decrypt_rejects_passphrase_file_with_x25519_credential() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (_pub_a, priv_a, pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        // Single argon2id recipient with a synthetic body. The
        // cross-mode check fires before any AEAD/KDF runs, so the body
        // contents are irrelevant — `classify_recipient_mode` only
        // looks at type_name.
        let synthetic = RecipientEntry::native(
            NativeRecipientType::Argon2id,
            vec![0u8; argon2id::BODY_LENGTH],
        )?;
        let file_key = FileKey::generate().unwrap();
        let fcr = tmp.path().join("passphrase.fcr");
        build_multi_recipient_fcr(&[synthetic], &file_key, b"x", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        match recipient_decrypt(&fcr, &dec_dir, &priv_a, &pass_a) {
            Err(CryptoError::DecryptorModeMismatch { expected, found })
                if expected == UnauthenticatedRecipientMode::PublicKey
                    && found == UnauthenticatedRecipientMode::Passphrase =>
            {
                Ok(())
            }
            other => panic!(
                "expected DecryptorModeMismatch(expected=PublicKey, found=Passphrase), got {other:?}"
            ),
        }
    }

    /// Cross-mode mismatch in the reverse direction: a recipient-sealed
    /// file opened with a `PassphraseCredential`. Symmetric assertion to
    /// [`decrypt_rejects_passphrase_file_with_x25519_credential`].
    #[test]
    fn decrypt_rejects_recipient_file_with_passphrase_credential() -> Result<(), CryptoError> {
        let tmp = tempfile::TempDir::new().unwrap();
        let keys_dir = tmp.path().join("keys");
        let (pub_a, _priv_a, _pass_a) = keypair_fixture(&keys_dir, "alice", "alice-pass")?;

        let file_key = FileKey::generate().unwrap();
        let body_a = x25519::wrap(&file_key, &pub_a)?;
        let entries = [RecipientEntry::native(
            NativeRecipientType::X25519,
            body_a.to_vec(),
        )?];
        let fcr = tmp.path().join("recipient.fcr");
        build_multi_recipient_fcr(&entries, &file_key, b"x", &fcr)?;

        let dec_dir = tmp.path().join("decrypted");
        fs::create_dir_all(&dec_dir)?;
        let pass = SecretString::from("doesn't-matter".to_string());
        let credential = argon2id::PassphraseCredential {
            passphrase: &pass,
            kdf_limit: None,
        };
        let err = decrypt(
            &credential,
            &fcr,
            &dec_dir,
            ArchiveLimits::default(),
            HeaderReadLimits::default(),
            IncompleteOutputPolicy::default(),
            &|_| {},
        )
        .unwrap_err();
        match err {
            CryptoError::DecryptorModeMismatch { expected, found }
                if expected == UnauthenticatedRecipientMode::Passphrase
                    && found == UnauthenticatedRecipientMode::PublicKey =>
            {
                Ok(())
            }
            other => panic!(
                "expected DecryptorModeMismatch(expected=Passphrase, found=PublicKey), got {other:?}"
            ),
        }
    }

    /// Defense-in-depth: empty recipient list rejected before any
    /// allocation or KDF. The public API gates this at construction
    /// time (`with_public_keys` returns `EmptyRecipientList`), but the
    /// orchestrator re-checks so a callable internal short-circuit
    /// can't bypass the contract.
    #[test]
    fn encrypt_rejects_empty_recipient_list() -> Result<(), CryptoError> {
        let recipients: [argon2id::PassphraseRecipient; 0] = [];
        let tmp = tempfile::TempDir::new().unwrap();
        let input = tmp.path().join("data.txt");
        fs::write(&input, b"x")?;
        let out_dir = tmp.path().join("out");
        fs::create_dir_all(&out_dir)?;

        let err = encrypt(
            &recipients,
            ArchiveLimits::default(),
            &input,
            &out_dir,
            None,
            &|_| {},
        )
        .unwrap_err();
        match err {
            CryptoError::EmptyRecipientList => Ok(()),
            other => panic!("expected EmptyRecipientList, got {other:?}"),
        }
    }
}