ferrocrypt 0.3.0-rc.5

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
//! Mixing-rule enforcement, native-scheme classification, and the
//! `NativeRecipientType` registry.
//!
//! Native classification and mixing enforcement are kept together because
//! adding a native recipient type requires coordinated updates to both.
//!
//! ## Two layers
//!
//! - `NativeMixingRule` (`pub(crate)`) is the **internal enforcement
//!   representation**. Each native recipient type declares one as a
//!   compile-time constant. The enum has two structurally-distinct
//!   shapes: `SingleEntry` (the type must appear alone, no class) and
//!   `Class { name }` (multiple entries of the same class may coexist).
//!   By construction, a single-entry rule has no class to compare, so
//!   the cardinality and class-equality enforcement modes are mutually
//!   exclusive at the type level.
//! - [`MixingPolicy`] (`pub`) is the **public diagnostic projection** of
//!   the rule, surfaced via [`CryptoError::IncompatibleRecipients`] so
//!   callers can pattern-match on the cause without parsing the message.
//!   New compatibility classes show up as
//!   [`MixingPolicy::Custom { compatibility_class }`](MixingPolicy::Custom)
//!   and do not require a new public enum variant.

use crate::CryptoError;
use crate::error::FormatDefect;
use crate::recipient::entry::RecipientEntry;
use crate::recipient::native::{argon2id, x25519};

/// Registered native recipient types supported by this implementation.
///
/// Each variant's discriminant is that type's `FORMAT.md` §4 registry index,
/// and the derived ordering is that index, which is the tie-break the step-8
/// body-content check uses (see [`classify_recipient_mode`]). Writing the
/// index out means the compiler rejects a new type that reuses one, and a new
/// type takes the next unused index rather than a position in this list.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub(crate) enum NativeRecipientType {
    /// Passphrase recipient. See [`crate::recipient::native::argon2id`].
    Argon2id = 0,
    /// X25519 public-key recipient. See [`crate::recipient::native::x25519`].
    X25519 = 1,
}

impl NativeRecipientType {
    /// Looks up a recipient `type_name` in the native registry.
    ///
    /// Returns `None` for unrecognised names. Per `FORMAT.md` §3.4,
    /// non-critical unknown recipients are skipped by callers; critical
    /// unknown recipients cause file rejection.
    pub(crate) fn from_type_name(name: &str) -> Option<Self> {
        match name {
            argon2id::TYPE_NAME => Some(Self::Argon2id),
            x25519::TYPE_NAME => Some(Self::X25519),
            _ => None,
        }
    }

    /// Wire-format type name for this variant.
    pub(crate) const fn type_name(self) -> &'static str {
        match self {
            Self::Argon2id => argon2id::TYPE_NAME,
            Self::X25519 => x25519::TYPE_NAME,
        }
    }

    /// Recipient body length (in bytes) for this variant.
    pub(crate) const fn body_len(self) -> usize {
        match self {
            Self::Argon2id => argon2id::BODY_LENGTH,
            Self::X25519 => x25519::BODY_LENGTH,
        }
    }

    /// Recipient-specific pre-cryptographic body checks for this
    /// variant (`FORMAT.md` §3.7 step 8). This hook rejects a body
    /// whose content is structurally invalid, with no credential, KDF,
    /// or key agreement. `argon2id` rejects `kdf_params` outside the
    /// `FORMAT.md` §2.2 bounds; `x25519` rejects an all-zero or
    /// non-canonical ephemeral public key.
    ///
    /// Two obligations bind every implementation of this hook, because
    /// [`classify_recipient_mode`] settles a rejected file's diagnostic
    /// class from the recipient type alone:
    ///
    /// - Callers MUST have verified the exact [`Self::body_len`] first.
    ///   Each implementation still handles a short body, but only as a
    ///   backstop; the length rejection is the caller's.
    /// - Given that precondition, the hook MUST report a single
    ///   diagnostic class, so which entry of a type failed cannot
    ///   change the class (`FORMAT.md` §3.7). `argon2id` reports
    ///   `invalid_kdf_parameters` and `x25519` reports
    ///   `malformed_recipient_entry`.
    ///
    /// The work MUST stay bounded by the body length: the caller runs
    /// this over every supported entry without stopping at the first
    /// failure, and it runs before the aggregate header-MAC work cap is
    /// charged.
    pub(crate) fn validate_body(self, body: &[u8]) -> Result<(), CryptoError> {
        match self {
            Self::Argon2id => argon2id::validate_body_preflight(body),
            Self::X25519 => x25519::validate_body_preflight(body),
        }
    }

    /// Recipient-mixing rule for this native type, per `FORMAT.md` §3.5.
    /// Used by [`enforce_recipient_mixing_policy`] before any recipient
    /// unwrap or KDF runs. Adding a new native type means adding one arm
    /// here — the rest of the mixing-enforcement machinery is registry-
    /// driven and does not need editing.
    pub(crate) const fn mixing_rule(self) -> NativeMixingRule {
        match self {
            Self::Argon2id => NativeMixingRule::exclusive(),
            Self::X25519 => NativeMixingRule::public_key_mixable(),
        }
    }

    /// Native [`crate::UnauthenticatedRecipientMode`] for this type. Used by
    /// [`classify_recipient_mode`] to pick the file's mode without a
    /// second closed list of `has_*` booleans. Adding a new native type
    /// means adding one arm here.
    pub(crate) const fn recipient_mode(self) -> crate::UnauthenticatedRecipientMode {
        match self {
            Self::Argon2id => crate::UnauthenticatedRecipientMode::Passphrase,
            Self::X25519 => crate::UnauthenticatedRecipientMode::PublicKey,
        }
    }
}

/// Public diagnostic category for a recipient mixing rule, surfaced
/// through [`CryptoError::IncompatibleRecipients`].
///
/// This is intentionally not the full internal enforcement representation
/// — that is the crate-private `NativeMixingRule` type, which can express
/// new native compatibility classes without adding public enum variants.
/// [`MixingPolicy::Custom`] is the catch-all for compatibility classes
/// that do not match the two fixed shorthand variants below; the
/// associated `compatibility_class` string preserves which class the
/// offending rule declared, so programmatic diagnostics can distinguish
/// (for example) a post-quantum class clash from any future custom class.
///
/// The enum is `#[non_exhaustive]` so future native rules can be added
/// without a breaking API change. New rule information also arrives as
/// a new variant — the fields of the existing variants are frozen.
/// It deliberately does not implement `Copy`: today's class identifiers
/// are `&'static str` only because the registry is compile-time, and
/// `Copy` would restrict every future variant to that same shape.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum MixingPolicy {
    /// This recipient must appear alone — not mixed with any other
    /// entry, including unknown non-critical ones. Currently:
    /// `argon2id`.
    Exclusive,
    /// Standard public-key mixability: multiple recipients of this
    /// type are permitted, alongside other public-key recipients in
    /// the same compatibility class. Currently: `x25519`.
    PublicKeyMixable,
    /// A recipient-specific compatibility class not represented by the
    /// fixed shorthand variants above. The `compatibility_class` field
    /// carries the class identifier the offending rule declared so a
    /// caller can distinguish — for example — a post-quantum class
    /// clash (`"postquantum"`) from a future custom class.
    Custom {
        /// Class identifier as declared by the recipient type's
        /// crate-private mixing rule. Stable per native type within a
        /// release; not part of the wire format and never appears on
        /// disk.
        compatibility_class: &'static str,
    },
}

/// Internal native-recipient mixing rule, per `FORMAT.md` §3.5.
///
/// The enum has two structurally-distinct shapes — a single-entry rule
/// has no compatibility class at all, so a class comparison cannot
/// accidentally treat two single-entry rules as compatible. Cardinality
/// (single-entry) and class equality are mutually exclusive enforcement
/// modes by construction.
///
/// `NativeMixingRule` is `pub(crate)` because it is the enforcement plane;
/// public diagnostics surface as [`MixingPolicy`] (the projection
/// returned by [`Self::diagnostic_policy`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum NativeMixingRule {
    /// The recipient type must be the only entry in the file (counting
    /// unknown non-critical entries too, per `FORMAT.md` §4.1). There
    /// is no compatibility class because a single-entry rule by
    /// definition cannot coexist with anything. Currently: `argon2id`.
    SingleEntry,
    /// The recipient type may coexist with other entries declaring the
    /// same compatibility class. Two `Class` rules are compatible when
    /// their `name` fields are exactly equal. Currently: `x25519`
    /// declares `Class { name: PUBLIC_KEY_CLASS }`; the upcoming
    /// `x25519-mlkem768` would declare
    /// `Class { name: POST_QUANTUM_CLASS }`.
    Class {
        /// Compatibility-class identifier, fixed per native recipient
        /// type and never appearing on the wire.
        name: &'static str,
    },
}

impl NativeMixingRule {
    /// Class for standard public-key recipients that share an
    /// unconstrained compatibility group.
    pub(crate) const PUBLIC_KEY_CLASS: &'static str = "public-key";

    /// Class for native post-quantum or hybrid-PQ recipients (reserved
    /// for the upcoming `x25519-mlkem768` recipient type and any future
    /// native PQ recipient sharing the same compatibility class).
    #[allow(dead_code)] // referenced by the upcoming PQ recipient PR
    pub(crate) const POST_QUANTUM_CLASS: &'static str = "postquantum";

    /// `argon2id`-style rule: the type must be the only entry in the
    /// file. Diagnostic projection is [`MixingPolicy::Exclusive`].
    pub(crate) const fn exclusive() -> Self {
        Self::SingleEntry
    }

    /// `x25519`-style rule: standard public-key compatibility class,
    /// no cardinality constraint. Diagnostic projection is
    /// [`MixingPolicy::PublicKeyMixable`].
    pub(crate) const fn public_key_mixable() -> Self {
        Self::Class {
            name: Self::PUBLIC_KEY_CLASS,
        }
    }

    /// Future native PQ / hybrid-PQ rule: post-quantum compatibility
    /// class, no cardinality constraint. Diagnostic projection is
    /// [`MixingPolicy::Custom { compatibility_class: "postquantum" }`].
    #[allow(dead_code)] // referenced by the upcoming PQ recipient PR
    pub(crate) const fn post_quantum() -> Self {
        Self::Class {
            name: Self::POST_QUANTUM_CLASS,
        }
    }

    /// `true` when this rule requires the recipient to be the only
    /// entry in the file.
    pub(crate) const fn requires_single_entry(self) -> bool {
        matches!(self, Self::SingleEntry)
    }

    /// Public-API diagnostic projection of this rule. Used by
    /// [`CryptoError::IncompatibleRecipients`] so callers can pattern-
    /// match on the cause without inspecting the internal enum.
    pub(crate) fn diagnostic_policy(self) -> MixingPolicy {
        match self {
            Self::SingleEntry => MixingPolicy::Exclusive,
            Self::Class { name } if name == Self::PUBLIC_KEY_CLASS => {
                MixingPolicy::PublicKeyMixable
            }
            Self::Class { name } => MixingPolicy::Custom {
                compatibility_class: name,
            },
        }
    }
}

/// Enforces recipient-mixing rules across a parsed entry list, per
/// `FORMAT.md` §3.5.
///
/// Returns `Ok(())` if the list satisfies every supported native mixing
/// rule; otherwise returns a typed [`CryptoError::IncompatibleRecipients`]
/// carrying the offending `type_name` and the rule's diagnostic
/// [`MixingPolicy`] projection.
///
/// This must run before any recipient unwrap, especially before the
/// Argon2id KDF for `argon2id`, so an invalid mixed-recipient file
/// cannot force work that policy would reject.
///
/// Rules:
///
/// 1. Cardinality. Any entry whose native rule is
///    [`NativeMixingRule::SingleEntry`] (today only `argon2id`) must
///    appear as the only entry in the file — counting unknown
///    non-critical entries too, per `FORMAT.md` §4.1. A second
///    same-type entry, a different native entry, or any unknown
///    non-critical entry alongside it is a violation.
///
/// 2. Compatibility class. Two supported [`NativeMixingRule::Class`]
///    rules are compatible when their `name` fields are exactly equal.
///    Unknown non-critical entries are skipped for the class
///    comparison (they are forward-compatibility filler, not
///    enforcement subjects). Unknown critical entries are rejected
///    upstream by [`classify_recipient_mode`] before this function
///    can matter.
///
/// On a class clash the reported `(type_name, policy)` favours the
/// stricter / non-`PublicKeyMixable` side so the diagnostic identifies
/// the recipient with the more specific compatibility class. The error
/// shape carries one `type_name`, not both sides; the
/// [`MixingPolicy::Custom`] variant additionally carries the offending
/// rule's compatibility-class string so programmatic consumers can
/// distinguish, for example, post-quantum from any future custom class.
pub(crate) fn enforce_recipient_mixing_policy(
    entries: &[RecipientEntry],
) -> Result<(), CryptoError> {
    // The mixing-rule table on `NativeRecipientType::mixing_rule` is the
    // single source of truth. Adding a new native type means adding one
    // arm there; this function does not need to be edited.
    // Unknown non-critical entries are not enforcement subjects and are
    // left out by `supported_entries`. Critical unknowns were rejected by
    // `classify_recipient_mode` before this function ran.
    let mut control: Option<(&RecipientEntry, NativeMixingRule)> = None;
    for (entry, ty) in supported_entries(entries) {
        let rule = ty.mixing_rule();

        if rule.requires_single_entry() && entries.len() != 1 {
            return Err(CryptoError::IncompatibleRecipients {
                type_name: entry.type_name.clone(),
                policy: rule.diagnostic_policy(),
            });
        }

        match control {
            None => control = Some((entry, rule)),
            Some((first_entry, first_rule)) => match (first_rule, rule) {
                // Same compatibility class: compatible. Control stays
                // on the first entry so a third clashing entry is
                // still reported against the original.
                (NativeMixingRule::Class { name: a }, NativeMixingRule::Class { name: b })
                    if a == b => {}
                // Class clash: prefer the stricter / non-PublicKeyMixable
                // side for the diagnostic so the reported `type_name`
                // identifies the recipient with the more specific
                // compatibility class.
                (NativeMixingRule::Class { .. }, NativeMixingRule::Class { .. }) => {
                    let (reported_entry, reported_rule) =
                        if rule.diagnostic_policy() != MixingPolicy::PublicKeyMixable {
                            (entry, rule)
                        } else {
                            (first_entry, first_rule)
                        };
                    return Err(CryptoError::IncompatibleRecipients {
                        type_name: reported_entry.type_name.clone(),
                        policy: reported_rule.diagnostic_policy(),
                    });
                }
                // A `SingleEntry` rule on either side cannot reach this
                // arm: the cardinality check at the start of each
                // iteration rejects any single-entry rule whenever
                // `entries.len() != 1`, and we only enter the
                // class-comparison arm when a previous entry has
                // already been processed (so `entries.len() >= 2`).
                // Fail closed if the invariant ever breaks instead of
                // accepting silently.
                (NativeMixingRule::SingleEntry, _) | (_, NativeMixingRule::SingleEntry) => {
                    return Err(crate::error::internal_invariant!(
                        "single-entry rule reached class check"
                    ));
                }
            },
        }
    }
    Ok(())
}

/// Pairs every entry naming a registered native type with that type.
/// Unknown entries are left out: the critical ones are rejected before
/// any of this runs, and the rest carry no rule a native check applies.
fn supported_entries(
    entries: &[RecipientEntry],
) -> impl Iterator<Item = (&RecipientEntry, NativeRecipientType)> {
    entries.iter().filter_map(|entry| {
        NativeRecipientType::from_type_name(&entry.type_name).map(|native| (entry, native))
    })
}

/// Counts the entries a reader may have to try, per `FORMAT.md` §3.7
/// step 10: those naming a registered native type. Unknown non-critical
/// entries are skipped by the slot loop and so cost no recipient work,
/// but their bytes still sit in the header every candidate
/// authenticates.
///
/// Used to bound aggregate header-MAC work
/// ([`crate::HeaderReadLimits::max_header_mac_work_bytes`]). The count
/// is deliberately the number of entries that *could* unwrap, not the
/// number that will: which slots open depends on the credential, and
/// the cap must hold before any credential work runs.
pub(crate) fn count_supported_recipients(entries: &[RecipientEntry]) -> usize {
    supported_entries(entries).count()
}

/// Classifies a parsed recipient list into the file's
/// [`crate::UnauthenticatedRecipientMode`]. Returns an error for any list
/// that does not yield a unique mode.
///
/// This scans the **entire** list rather than only the first entry —
/// future valid files may place unknown non-critical recipients before
/// a supported native recipient, and a classifier that looked at only
/// the first entry would misclassify those.
///
/// Order of checks:
/// 1. Reject any unknown entry marked critical with
///    [`CryptoError::UnknownCriticalRecipient`] (`FORMAT.md` §3.7
///    step 6). This pass covers every entry before step 8 begins, so
///    the diagnostic class depends on what the file contains rather
///    than on the order its entries happen to appear in.
/// 2. Run the `FORMAT.md` §3.7 step-8 preflight over the supported
///    native entries in two passes, the second of which starts only
///    once the first has covered every entry. Pass one rejects
///    `recipient_flags != 0` (per `FORMAT.md` §3.4: "Native `argon2id`
///    and `x25519` entries MUST have `recipient_flags = 0`") and a
///    body length that is not the exact native length, both with
///    [`CryptoError::InvalidFormat`] /
///    [`FormatDefect::MalformedRecipientEntry`]. Pass two runs
///    [`NativeRecipientType::validate_body`], reporting the failure of
///    the lowest [`NativeRecipientType`] registry index when entries of
///    more than one type fail, so the class a rejected file yields
///    follows its content and not its entry order. Reserved bits 1..=15
///    are already rejected at parse time
///    (`RECIPIENT_FLAGS_RESERVED_MASK`), so only bit 0 (critical) can be
///    set here. Step 8 completes before mixing runs, so a file that is
///    both structurally malformed and illegally mixed reports the
///    structural defect (`FORMAT.md` §3.7 step 8 before step 9).
/// 3. Run [`enforce_recipient_mixing_policy`] (cardinality + class).
/// 4. For each supported native entry, look up
///    [`NativeRecipientType::recipient_mode`]; the file's mode is the
///    common value across all supported entries.
/// 5. If two supported native entries declare different modes the file
///    is rejected (currently unreachable — the cardinality check on
///    `argon2id` already forbids cross-mode mixes — but the branch is
///    kept fail-closed in case a future native type breaks the
///    one-class-implies-one-mode assumption).
/// 6. If no supported native entry is present (only unknown non-critical
///    entries) → [`CryptoError::NoSupportedRecipient`].
///
/// What is pinned is the **diagnostic class**, which is what
/// `FORMAT.md` §12.1 freezes as the cross-language contract. The error
/// value carrying it is not pinned the same way. Where a class admits
/// several payloads — the [`crate::error::InvalidKdfParams`] variant
/// naming the offending field, for one — the payload comes from the
/// entry the class was taken from, which in pass two is the first
/// failing entry of the winning registry index and not necessarily the
/// first failing entry in the file.
///
/// This is structural classification only. The caller still has to
/// run the appropriate per-recipient unwrap and the header MAC verify
/// before accepting any candidate `file_key`.
pub(crate) fn classify_recipient_mode(
    entries: &[RecipientEntry],
) -> Result<crate::UnauthenticatedRecipientMode, CryptoError> {
    // Step 1: a reader must refuse to process a file that declares an
    // unknown entry it cannot skip. This walk covers the whole list
    // before step 2 starts, so a file carrying both defects always
    // reports the unknown-critical one, whichever entry comes first.
    for entry in entries {
        if entry.is_critical() && NativeRecipientType::from_type_name(&entry.type_name).is_none() {
            return Err(CryptoError::UnknownCriticalRecipient {
                type_name: entry.type_name.clone(),
            });
        }
    }

    // Step 2, pass one: the framing rules for supported native types —
    // a non-zero flag and a body of the wrong length. Both report the
    // same defect, so stopping at the first offender cannot change the
    // class; what matters is that no entry reaches pass two until every
    // entry has passed here.
    for (entry, native) in supported_entries(entries) {
        if entry.recipient_flags != 0 || entry.body.len() != native.body_len() {
            return Err(CryptoError::InvalidFormat(
                FormatDefect::MalformedRecipientEntry,
            ));
        }
    }

    // Step 2, pass two: recipient-specific body content, which is the
    // one part of step 8 whose defect class differs by type. Here the
    // first offender is not enough: every supported entry is checked,
    // and the failure kept is the one from the lowest registry index,
    // so two files holding the same entries in a different order report
    // the same class. Each check is bounded by the body length, and the
    // recipient count is capped at parse time, so the whole pass stays
    // within the header the reader has already accepted. All of step 8
    // finishes before mixing and before any KDF or private-key work
    // (`FORMAT.md` §3.7 steps 8-9).
    let mut body_defect: Option<(NativeRecipientType, CryptoError)> = None;
    for (entry, native) in supported_entries(entries) {
        if let Err(defect) = native.validate_body(&entry.body) {
            if body_defect.as_ref().is_none_or(|(kept, _)| native < *kept) {
                body_defect = Some((native, defect));
            }
        }
    }
    if let Some((_, defect)) = body_defect {
        return Err(defect);
    }

    // Step 3: enforce mixing rules before any KDF/unwrap could run.
    enforce_recipient_mixing_policy(entries)?;

    // Step 4 / 5: registry-driven mode classification. Walk the entry
    // list once, look up `recipient_mode()` per supported native type,
    // and confirm every supported entry agrees on a single mode.
    let mut mode: Option<crate::UnauthenticatedRecipientMode> = None;
    for (entry, ty) in supported_entries(entries) {
        let entry_mode = ty.recipient_mode();
        match mode {
            None => mode = Some(entry_mode),
            Some(existing) if existing == entry_mode => {}
            Some(_) => {
                // Cross-mode native mix slipped past
                // `enforce_recipient_mixing_policy`. Currently
                // unreachable (argon2id's cardinality forbids it); kept
                // fail-closed as defense-in-depth for future native
                // types whose class might span modes.
                return Err(CryptoError::IncompatibleRecipients {
                    type_name: entry.type_name.clone(),
                    policy: ty.mixing_rule().diagnostic_policy(),
                });
            }
        }
    }

    // Step 6: no supported native recipient. Unknown non-critical
    // entries cannot decrypt the file on their own.
    mode.ok_or(CryptoError::NoSupportedRecipient)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crypto::kdf::KdfParams;
    use crate::error::{FormatDefect, InvalidKdfParams};
    use crate::recipient::entry::RECIPIENT_FLAG_CRITICAL;

    #[test]
    fn known_recipient_type_round_trips_through_type_name() {
        assert_eq!(
            NativeRecipientType::from_type_name(argon2id::TYPE_NAME),
            Some(NativeRecipientType::Argon2id)
        );
        assert_eq!(
            NativeRecipientType::from_type_name(x25519::TYPE_NAME),
            Some(NativeRecipientType::X25519)
        );
        assert_eq!(
            NativeRecipientType::Argon2id.type_name(),
            argon2id::TYPE_NAME
        );
        assert_eq!(NativeRecipientType::X25519.type_name(), x25519::TYPE_NAME);
    }

    #[test]
    fn known_recipient_type_returns_none_for_unknown_names() {
        assert_eq!(NativeRecipientType::from_type_name("scrypt"), None);
        assert_eq!(NativeRecipientType::from_type_name("foo"), None);
        assert_eq!(NativeRecipientType::from_type_name(""), None);
        assert_eq!(NativeRecipientType::from_type_name("argon2"), None); // close but not exact
    }

    #[test]
    fn body_length_matches_per_type() {
        assert_eq!(
            NativeRecipientType::Argon2id.body_len(),
            argon2id::BODY_LENGTH
        );
        assert_eq!(NativeRecipientType::X25519.body_len(), x25519::BODY_LENGTH);
    }

    /// `FORMAT.md` §3.7 lets the registry index alone decide what a
    /// rejected file reports, which holds only while each native type's
    /// body check reports a single diagnostic class. Driven here over
    /// every body defect the wire can carry, at the exact body length
    /// pass one guarantees before this check runs.
    #[test]
    fn each_native_body_check_reports_one_diagnostic_class() {
        for params in [
            KdfParams {
                lanes: 0,
                ..KdfParams::test_fast_default()
            },
            KdfParams {
                time_cost: 0,
                ..KdfParams::test_fast_default()
            },
            KdfParams {
                mem_cost: 0,
                ..KdfParams::test_fast_default()
            },
        ] {
            let body = argon2id::test_body_with_kdf_params(&params);
            match NativeRecipientType::Argon2id.validate_body(&body) {
                Err(CryptoError::InvalidKdfParams(_)) => {}
                other => panic!("argon2id body check reports one class, got {other:?}"),
            }
        }

        let mut all_zero = vec![0x11u8; x25519::BODY_LENGTH];
        all_zero[..x25519::PUBLIC_KEY_SIZE].fill(0);
        let mut non_canonical = vec![0x11u8; x25519::BODY_LENGTH];
        non_canonical[..x25519::PUBLIC_KEY_SIZE].fill(0xFF);
        for body in [all_zero, non_canonical] {
            match NativeRecipientType::X25519.validate_body(&body) {
                Err(CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry)) => {}
                other => panic!("x25519 body check reports one class, got {other:?}"),
            }
        }
    }

    /// The registry index is the `FORMAT.md` §4 tie-break for step 8,
    /// so it is pinned against the specification rather than left to
    /// the order the variants happen to be declared in.
    #[test]
    fn native_registry_indices_match_the_specification() {
        assert_eq!(NativeRecipientType::Argon2id as u8, 0);
        assert_eq!(NativeRecipientType::X25519 as u8, 1);
        assert!(NativeRecipientType::Argon2id < NativeRecipientType::X25519);
    }

    #[test]
    fn mixing_rule_per_native_type() {
        // argon2id: SingleEntry — diagnostic projection `Exclusive`.
        // The variant carries no class field, so two argon2id rules
        // cannot have a "matching class" by accident.
        let argon = NativeRecipientType::Argon2id.mixing_rule();
        assert_eq!(argon, NativeMixingRule::SingleEntry);
        assert!(argon.requires_single_entry());
        assert_eq!(argon.diagnostic_policy(), MixingPolicy::Exclusive);

        // x25519: Class { name: PUBLIC_KEY_CLASS }, no cardinality,
        // diagnostic projection `PublicKeyMixable`.
        let x = NativeRecipientType::X25519.mixing_rule();
        assert_eq!(
            x,
            NativeMixingRule::Class {
                name: NativeMixingRule::PUBLIC_KEY_CLASS,
            }
        );
        assert!(!x.requires_single_entry());
        assert_eq!(x.diagnostic_policy(), MixingPolicy::PublicKeyMixable);
    }

    /// Confirm the [`NativeMixingRule::post_quantum`] / [`NativeMixingRule::POST_QUANTUM_CLASS`]
    /// constants project to the documented public diagnostic shape.
    /// Locks in the `Custom { compatibility_class: "postquantum" }`
    /// wording so the upcoming `x25519-mlkem768` recipient PR does not
    /// silently drift the class identifier.
    #[test]
    fn post_quantum_rule_projects_to_custom_diagnostic() {
        let rule = NativeMixingRule::post_quantum();
        assert_eq!(
            rule,
            NativeMixingRule::Class {
                name: NativeMixingRule::POST_QUANTUM_CLASS,
            }
        );
        assert!(!rule.requires_single_entry());
        assert_eq!(
            rule.diagnostic_policy(),
            MixingPolicy::Custom {
                compatibility_class: NativeMixingRule::POST_QUANTUM_CLASS,
            }
        );
    }

    /// Native registry's [`NativeRecipientType::recipient_mode`]
    /// must agree with what `classify_recipient_mode` emits for
    /// single-recipient lists. Locks in the registry as the single
    /// source of truth for mode classification (the classifier no
    /// longer hard-codes `argon2id` / `x25519` type-name strings).
    #[test]
    fn recipient_mode_per_native_type() {
        assert_eq!(
            NativeRecipientType::Argon2id.recipient_mode(),
            crate::UnauthenticatedRecipientMode::Passphrase
        );
        assert_eq!(
            NativeRecipientType::X25519.recipient_mode(),
            crate::UnauthenticatedRecipientMode::PublicKey
        );
    }

    fn argon2id_entry() -> RecipientEntry {
        RecipientEntry::native(
            NativeRecipientType::Argon2id,
            argon2id::test_body_with_valid_kdf_params(),
        )
        .unwrap()
    }

    /// Companion of [`argon2id_entry`] carrying a canonical-length body
    /// whose `kdf_params` are outside the `FORMAT.md` §2.2 structural
    /// bounds.
    ///
    /// Exactly one field is out of range, so the reported
    /// [`InvalidKdfParams`] variant identifies the field this fixture
    /// set and does not depend on the order `validate_structural`
    /// happens to check the three fields in.
    fn argon2id_entry_with_invalid_kdf_params() -> RecipientEntry {
        let params = KdfParams {
            lanes: 0,
            ..KdfParams::test_fast_default()
        };
        RecipientEntry::native(
            NativeRecipientType::Argon2id,
            argon2id::test_body_with_kdf_params(&params),
        )
        .unwrap()
    }

    fn x25519_entry() -> RecipientEntry {
        // 0x11 filler keeps the ephemeral-key field non-zero and
        // canonical, so the body passes the structural preflight.
        RecipientEntry::native(
            NativeRecipientType::X25519,
            vec![0x11u8; x25519::BODY_LENGTH],
        )
        .unwrap()
    }

    /// Companion of [`x25519_entry`] whose ephemeral public key is all
    /// zero, so a canonical-length body fails the `FORMAT.md` §4.2
    /// preflight.
    fn x25519_entry_with_all_zero_ephemeral() -> RecipientEntry {
        let mut entry = x25519_entry();
        entry.body[..x25519::PUBLIC_KEY_SIZE].fill(0);
        entry
    }

    fn unknown_entry(name: &str, critical: bool) -> RecipientEntry {
        RecipientEntry {
            type_name: name.to_string(),
            recipient_flags: if critical { RECIPIENT_FLAG_CRITICAL } else { 0 },
            body: vec![0u8; 8],
        }
    }

    #[test]
    fn native_constructor_rejects_wrong_body_length() {
        let err =
            RecipientEntry::native(NativeRecipientType::Argon2id, vec![0u8; 100]).unwrap_err();
        match err {
            CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry) => {}
            other => panic!("expected MalformedRecipientEntry, got {other:?}"),
        }
    }

    #[test]
    fn native_constructor_sets_canonical_type_name_and_zero_flags() {
        let entry = argon2id_entry();
        assert_eq!(entry.type_name, argon2id::TYPE_NAME);
        assert_eq!(entry.recipient_flags, 0);
        assert!(!entry.is_critical());
    }

    #[test]
    fn enforce_mixing_accepts_lone_argon2id() {
        enforce_recipient_mixing_policy(&[argon2id_entry()]).unwrap();
    }

    #[test]
    fn enforce_mixing_accepts_multiple_x25519() {
        enforce_recipient_mixing_policy(&[x25519_entry(), x25519_entry()]).unwrap();
    }

    /// Helper: assert `err` is the `IncompatibleRecipients` variant
    /// naming `argon2id` with the `Exclusive` policy.
    fn assert_argon2id_mixing_violation(err: CryptoError) {
        match err {
            CryptoError::IncompatibleRecipients { type_name, policy } => {
                assert_eq!(type_name, argon2id::TYPE_NAME);
                assert_eq!(policy, MixingPolicy::Exclusive);
            }
            other => panic!("expected IncompatibleRecipients(argon2id, Exclusive), got {other:?}"),
        }
    }

    #[test]
    fn enforce_mixing_rejects_argon2id_plus_x25519() {
        let err = enforce_recipient_mixing_policy(&[argon2id_entry(), x25519_entry()]).unwrap_err();
        assert_argon2id_mixing_violation(err);
    }

    /// Reverse-order companion of
    /// [`enforce_mixing_rejects_argon2id_plus_x25519`]: place the
    /// `x25519` entry first so the cardinality check fires on the
    /// SECOND iteration. The error must still name `argon2id`
    /// (not `x25519`) — the cardinality check on the single-entry
    /// rule is what trips, regardless of iteration position.
    #[test]
    fn enforce_mixing_rejects_x25519_plus_argon2id() {
        let err = enforce_recipient_mixing_policy(&[x25519_entry(), argon2id_entry()]).unwrap_err();
        assert_argon2id_mixing_violation(err);
    }

    #[test]
    fn enforce_mixing_rejects_two_argon2ids() {
        // argon2id is Exclusive — even another argon2id is a violation.
        // Without this case the "exactly one" guarantee is implicit; the
        // test makes it explicit.
        let err =
            enforce_recipient_mixing_policy(&[argon2id_entry(), argon2id_entry()]).unwrap_err();
        assert_argon2id_mixing_violation(err);
    }

    #[test]
    fn classify_rejects_two_argon2ids() {
        let err = classify_recipient_mode(&[argon2id_entry(), argon2id_entry()]).unwrap_err();
        assert_argon2id_mixing_violation(err);
    }

    #[test]
    fn enforce_mixing_rejects_argon2id_plus_unknown_non_critical() {
        // Per FORMAT.md §4.1, even an unknown non-critical entry
        // alongside argon2id is a mixing violation.
        let err = enforce_recipient_mixing_policy(&[
            argon2id_entry(),
            unknown_entry("future-thing", false),
        ])
        .unwrap_err();
        assert_argon2id_mixing_violation(err);
    }

    /// The work bound charges for entries the slot loop can try. Unknown
    /// non-critical entries are skipped there, so they must not be
    /// counted — but they still inflate the header every counted
    /// candidate authenticates.
    #[test]
    fn count_supported_recipients_ignores_unknown_entries() {
        assert_eq!(count_supported_recipients(&[]), 0);
        assert_eq!(
            count_supported_recipients(&[unknown_entry("future-thing", false)]),
            0
        );
        assert_eq!(
            count_supported_recipients(&[
                x25519_entry(),
                unknown_entry("future-thing", false),
                x25519_entry(),
            ]),
            2
        );
        assert_eq!(count_supported_recipients(&[argon2id_entry()]), 1);
    }

    #[test]
    fn classify_returns_passphrase_for_lone_argon2id() {
        let mode = classify_recipient_mode(&[argon2id_entry()]).unwrap();
        assert_eq!(mode, crate::UnauthenticatedRecipientMode::Passphrase);
    }

    #[test]
    fn classify_returns_public_key_for_x25519() {
        let mode = classify_recipient_mode(&[x25519_entry()]).unwrap();
        assert_eq!(mode, crate::UnauthenticatedRecipientMode::PublicKey);
    }

    #[test]
    fn classify_returns_public_key_for_multiple_x25519() {
        let mode = classify_recipient_mode(&[x25519_entry(), x25519_entry()]).unwrap();
        assert_eq!(mode, crate::UnauthenticatedRecipientMode::PublicKey);
    }

    #[test]
    fn classify_skips_unknown_non_critical_in_front_of_x25519() {
        // Forward-compat: a future file may put unknown non-critical
        // entries before a supported native entry. Classification must
        // not look only at the first slot.
        let mode = classify_recipient_mode(&[unknown_entry("future-thing", false), x25519_entry()])
            .unwrap();
        assert_eq!(mode, crate::UnauthenticatedRecipientMode::PublicKey);
    }

    #[test]
    fn classify_rejects_unknown_critical() {
        let err = classify_recipient_mode(&[unknown_entry("must-handle-me", true), x25519_entry()])
            .unwrap_err();
        match err {
            CryptoError::UnknownCriticalRecipient { type_name } => {
                assert_eq!(type_name, "must-handle-me");
            }
            other => panic!("expected UnknownCriticalRecipient, got {other:?}"),
        }
    }

    #[test]
    fn classify_rejects_argon2id_mixed_via_incompatible_recipients() {
        let err = classify_recipient_mode(&[argon2id_entry(), x25519_entry()]).unwrap_err();
        assert_argon2id_mixing_violation(err);
    }

    #[test]
    fn classify_rejects_only_unknown_non_critical_with_no_supported_recipient() {
        let err = classify_recipient_mode(&[unknown_entry("future-thing", false)]).unwrap_err();
        assert!(matches!(err, CryptoError::NoSupportedRecipient));
    }

    #[test]
    fn classify_rejects_empty_entry_list_with_no_supported_recipient() {
        // A zero-recipient header is structurally rejected upstream
        // (HeaderFixed validates recipient_count >= 1), but the
        // classifier must still answer something sensible if called
        // with an empty slice. NoSupportedRecipient is the right class.
        let err = classify_recipient_mode(&[]).unwrap_err();
        assert!(matches!(err, CryptoError::NoSupportedRecipient));
    }

    /// FORMAT.md §3.4 mandates `recipient_flags = 0` on native
    /// `argon2id` and `x25519` entries. A native entry with the
    /// critical bit set is structurally malformed and must be rejected
    /// at classify time — not just inside `protocol::decrypt`'s slot
    /// loop — so `probe_recipient_mode` and the cross-mode mismatch
    /// path both surface the typed `MalformedRecipientEntry` rather
    /// than misroute the file.
    #[test]
    fn classify_rejects_native_argon2id_with_critical_bit() {
        let bad = RecipientEntry {
            type_name: argon2id::TYPE_NAME.to_owned(),
            recipient_flags: RECIPIENT_FLAG_CRITICAL,
            body: vec![0u8; argon2id::BODY_LENGTH],
        };
        let err = classify_recipient_mode(&[bad]).unwrap_err();
        match err {
            CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry) => {}
            other => {
                panic!(
                    "expected MalformedRecipientEntry for native argon2id+critical, got {other:?}"
                )
            }
        }
    }

    /// Companion of [`classify_rejects_native_argon2id_with_critical_bit`]
    /// for the `x25519` native type — same `FORMAT.md` §3.4 rule.
    #[test]
    fn classify_rejects_native_x25519_with_critical_bit() {
        let bad = RecipientEntry {
            type_name: x25519::TYPE_NAME.to_owned(),
            recipient_flags: RECIPIENT_FLAG_CRITICAL,
            body: vec![0u8; x25519::BODY_LENGTH],
        };
        let err = classify_recipient_mode(&[bad]).unwrap_err();
        match err {
            CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry) => {}
            other => {
                panic!("expected MalformedRecipientEntry for native x25519+critical, got {other:?}")
            }
        }
    }

    /// FORMAT.md §3.7 step 8 fixes native body lengths as a
    /// pre-cryptographic check: a native entry whose body is not the
    /// exact registry length must be rejected at classify time, before
    /// any KDF or private-key work can start.
    #[test]
    fn classify_rejects_native_body_with_wrong_length() {
        for (name, good_len) in [
            (argon2id::TYPE_NAME, argon2id::BODY_LENGTH),
            (x25519::TYPE_NAME, x25519::BODY_LENGTH),
        ] {
            for wrong_len in [good_len - 1, good_len + 1] {
                let bad = RecipientEntry {
                    type_name: name.to_owned(),
                    recipient_flags: 0,
                    body: vec![0u8; wrong_len],
                };
                let err = classify_recipient_mode(&[bad]).unwrap_err();
                match err {
                    CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry) => {}
                    other => panic!(
                        "expected MalformedRecipientEntry for {name} body of {wrong_len}, got {other:?}"
                    ),
                }
            }
        }
    }

    /// The per-entry structural pass covers every entry, so a malformed
    /// native body hiding behind a well-shaped entry is still caught at
    /// classify time.
    #[test]
    fn classify_rejects_wrong_length_after_valid_entry() {
        let mut short = x25519_entry();
        short.body.pop();
        let err = classify_recipient_mode(&[x25519_entry(), short]).unwrap_err();
        match err {
            CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry) => {}
            other => panic!("expected MalformedRecipientEntry for second slot, got {other:?}"),
        }
    }

    /// FORMAT.md §4.1 makes `kdf_params` outside the §2.2 bounds a
    /// reader rejection, and §3.7 puts it in the step-8 preflight —
    /// before any credential is supplied, so a caller is never asked
    /// for a passphrase that could not open the file.
    #[test]
    fn classify_rejects_argon2id_with_invalid_kdf_params() {
        let err = classify_recipient_mode(&[argon2id_entry_with_invalid_kdf_params()]).unwrap_err();
        match err {
            CryptoError::InvalidKdfParams(InvalidKdfParams::Parallelism(0)) => {}
            other => panic!("expected InvalidKdfParams(Parallelism(0)), got {other:?}"),
        }
    }

    /// Step 8 outranks step 9 for the Argon2id KDF fields exactly as it
    /// does for body length: a file that is both malformed and
    /// illegally mixed reports the malformed KDF, whichever position
    /// the offending entry holds.
    #[test]
    fn classify_reports_invalid_kdf_params_before_illegal_mixing() {
        for entries in [
            vec![argon2id_entry_with_invalid_kdf_params(), x25519_entry()],
            vec![x25519_entry(), argon2id_entry_with_invalid_kdf_params()],
        ] {
            match classify_recipient_mode(&entries) {
                Err(CryptoError::InvalidKdfParams(InvalidKdfParams::Parallelism(0))) => {}
                other => panic!(
                    "expected the KDF defect to take precedence over mixing regardless of \
                     entry order, got {other:?}"
                ),
            }
        }
    }

    /// FORMAT.md §3.7 orders step 8 before step 9: when a file is both
    /// structurally malformed and illegally mixed, the structural
    /// rejection wins.
    #[test]
    fn classify_reports_structural_defect_before_illegal_mixing() {
        let mut short = argon2id_entry();
        short.body.pop();
        let err = classify_recipient_mode(&[short, x25519_entry()]).unwrap_err();
        match err {
            CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry) => {}
            other => panic!(
                "expected the structural defect to take precedence over mixing, got {other:?}"
            ),
        }
    }

    /// `FORMAT.md` §3.7 requires every step-8 check to complete over
    /// every entry before the next begins. The framing checks come
    /// first, so a wrong body length outranks an invalid `kdf_params`
    /// in the same file whichever entry carries which.
    #[test]
    fn classify_reports_a_wrong_body_length_before_a_body_content_defect() {
        let mut short = argon2id_entry();
        short.body.pop();
        let bad_kdf = argon2id_entry_with_invalid_kdf_params();
        for entries in [
            vec![short.clone(), bad_kdf.clone()],
            vec![bad_kdf.clone(), short.clone()],
        ] {
            match classify_recipient_mode(&entries) {
                Err(CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry)) => {}
                other => panic!(
                    "expected the wrong body length regardless of entry order, got {other:?}"
                ),
            }
        }
    }

    /// Body content is the one step-8 check whose class differs by
    /// recipient type, so a file whose entries both fail it reports the
    /// class of the lowest registry index — `argon2id` before `x25519`
    /// — however the entries are arranged.
    #[test]
    fn classify_reports_one_body_defect_class_whatever_the_entry_order() {
        let bad_kdf = argon2id_entry_with_invalid_kdf_params();
        let bad_ephemeral = x25519_entry_with_all_zero_ephemeral();
        for entries in [
            vec![bad_kdf.clone(), bad_ephemeral.clone()],
            vec![bad_ephemeral.clone(), bad_kdf.clone()],
        ] {
            match classify_recipient_mode(&entries) {
                Err(CryptoError::InvalidKdfParams(InvalidKdfParams::Parallelism(0))) => {}
                other => panic!(
                    "expected the argon2id body defect regardless of entry order, got {other:?}"
                ),
            }
        }
    }

    /// When BOTH a native-flags violation AND an unknown-critical entry
    /// are present, `FORMAT.md` §3.7 step 6 outranks step 8, so the
    /// unknown-critical entry is reported whichever position it holds.
    /// The single-violation cases above pin the precise diagnostic per
    /// case.
    #[test]
    fn classify_rejects_when_native_critical_and_unknown_critical_both_present() {
        let bad_native = RecipientEntry {
            type_name: x25519::TYPE_NAME.to_owned(),
            recipient_flags: RECIPIENT_FLAG_CRITICAL,
            body: vec![0u8; x25519::BODY_LENGTH],
        };
        let unknown_crit = unknown_entry("future-critical", true);
        for entries in [
            vec![bad_native.clone(), unknown_crit.clone()],
            vec![unknown_crit.clone(), bad_native.clone()],
        ] {
            match classify_recipient_mode(&entries) {
                Err(CryptoError::UnknownCriticalRecipient { type_name })
                    if type_name == "future-critical" => {}
                other => panic!(
                    "expected UnknownCriticalRecipient regardless of entry order, got {other:?}"
                ),
            }
        }
    }
}