xml-sec 0.1.8

Pure Rust XML Security: XMLDSig, XMLEnc, C14N. Drop-in replacement for libxmlsec1.
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
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
//! Configuration and key material for XMLDSig key resolution.

use std::{collections::HashMap, time::SystemTime};

use crypto_bigint::BoxedUint;
use p256::pkcs8::EncodePublicKey as P256EncodePublicKey;
use x509_parser::{
    prelude::{FromDer, X509Certificate},
    public_key::PublicKey,
    x509::SubjectPublicKeyInfo,
};

use super::{
    DsigError, KeyInfo, KeyInfoSource, KeyResolver, KeyValueInfo, SignatureAlgorithm, VerifyingKey,
    X509ChainOptions, X509DataInfo,
    parse::{
        EC_P256_OID, EC_P384_OID, ParseError, parse_x509_certificate,
        x509_certificate_matches_any_selector, x509_data_has_lookup_identifiers,
        x509_selector_categories_match_chain,
    },
    verify_ecdsa_signature_spki, verify_rsa_signature_spki, verify_x509_certificate_chain,
};

/// A public verification key available to key resolvers.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VerificationKey {
    /// Signature algorithm this key is configured to verify.
    pub algorithm: SignatureAlgorithm,
    /// DER-encoded SubjectPublicKeyInfo bytes.
    pub public_key_bytes: Vec<u8>,
    /// DER certificate from which the key was extracted, when applicable.
    pub certificate_der: Option<Vec<u8>>,
    /// Name used to register this key for `<KeyName>` resolution.
    pub name: Option<String>,
}

impl VerifyingKey for VerificationKey {
    fn verify(
        &self,
        algorithm: SignatureAlgorithm,
        signed_data: &[u8],
        signature_value: &[u8],
    ) -> Result<bool, DsigError> {
        if algorithm != self.algorithm {
            return Err(KeyResolutionError::AlgorithmMismatch.into());
        }
        let result = match algorithm {
            SignatureAlgorithm::RsaSha1
            | SignatureAlgorithm::RsaSha256
            | SignatureAlgorithm::RsaSha384
            | SignatureAlgorithm::RsaSha512 => verify_rsa_signature_spki(
                algorithm,
                &self.public_key_bytes,
                signed_data,
                signature_value,
            ),
            SignatureAlgorithm::EcdsaP256Sha256 | SignatureAlgorithm::EcdsaP384Sha384 => {
                verify_ecdsa_signature_spki(
                    algorithm,
                    &self.public_key_bytes,
                    signed_data,
                    signature_value,
                )
            }
        };
        result.map_err(DsigError::Crypto)
    }
}

/// Failures while applying [`KeyResolverConfig`] to parsed key material.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum KeyResolutionError {
    /// A configured or embedded key does not match the signature method.
    #[error("verification key does not match the signature algorithm")]
    AlgorithmMismatch,
    /// An embedded certificate could not be parsed completely.
    #[error("invalid embedded certificate DER")]
    InvalidCertificate,
    /// Configured or embedded public key DER could not be parsed completely.
    #[error("invalid public key DER")]
    InvalidPublicKey,
    /// More than one configured certificate satisfies all X.509 selectors.
    #[error("X.509 lookup selectors match multiple configured certificates")]
    AmbiguousCertificate,
    /// An X.509 selector uses a digest algorithm unsupported by this crate.
    #[error("unsupported X.509 digest algorithm: {0}")]
    UnsupportedDigestAlgorithm(String),
    /// Embedded certificate path validation failed.
    #[error("certificate chain validation failed: {0}")]
    Chain(#[from] super::X509ChainError),
    /// System time was unavailable for certificate validation.
    #[error("system time is unavailable")]
    SystemTime,
}

/// Configuration for the default XMLDSig key resolver.
///
/// The configuration owns all key material and has no global registry. Chain
/// verification is opt-in so callers that pin an embedded certificate can use
/// the documented TOFU model without constructing a certificate path.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyResolverConfig {
    /// DER-encoded certificates accepted as trust anchors.
    pub trusted_certs: Vec<Vec<u8>>,
    /// Verification keys addressable by `<KeyName>` content.
    pub named_keys: HashMap<String, VerificationKey>,
    /// Whether embedded X.509 certificate chains must terminate at a trust anchor.
    pub verify_chains: bool,
    /// Certificate verification time override; `None` selects the system clock.
    pub verification_time: Option<SystemTime>,
    /// Maximum certificates in a validated path, including the trust anchor.
    pub max_chain_depth: usize,
}

impl Default for KeyResolverConfig {
    fn default() -> Self {
        Self {
            trusted_certs: Vec::new(),
            named_keys: HashMap::new(),
            verify_chains: false,
            verification_time: None,
            max_chain_depth: 9,
        }
    }
}

/// Configuration-driven resolver for embedded certificates, DER keys, and key names.
#[derive(Debug, Clone, Default)]
pub struct DefaultKeyResolver {
    config: KeyResolverConfig,
}

impl DefaultKeyResolver {
    /// Construct a resolver from explicit caller-owned key policy.
    #[must_use]
    pub fn new(config: KeyResolverConfig) -> Self {
        Self { config }
    }

    /// Borrow the active resolver configuration.
    #[must_use]
    pub fn config(&self) -> &KeyResolverConfig {
        &self.config
    }

    fn resolve_x509(
        &self,
        info: &X509DataInfo,
        algorithm: SignatureAlgorithm,
    ) -> Result<Option<VerificationKey>, KeyResolutionError> {
        let certificate_der = if let Some(&signing_index) = info.certificate_chain.first() {
            let certificate_der = info
                .certificates
                .get(signing_index)
                .ok_or(KeyResolutionError::InvalidCertificate)?;
            if self.config.verify_chains {
                self.verify_x509_policy(info, None)?;
            }
            certificate_der
        } else {
            let Some(certificate) = self.resolve_configured_x509(info)? else {
                return Ok(None);
            };
            if self.config.verify_chains {
                let parsed = parse_x509_certificate(certificate)
                    .map_err(|_| KeyResolutionError::InvalidCertificate)?;
                let selected = X509DataInfo {
                    certificates: vec![certificate.clone()],
                    parsed_certificates: vec![parsed],
                    certificate_chain: vec![0],
                    ..X509DataInfo::default()
                };
                // Validate the selected certificate's own policy before
                // requiring a distinct configured certificate as its anchor.
                self.verify_x509_policy(&selected, None)?;
                self.verify_x509_policy(&selected, Some(certificate))?;
            }
            certificate
        };

        let (rest, certificate) = X509Certificate::from_der(certificate_der)
            .map_err(|_| KeyResolutionError::InvalidCertificate)?;
        if !rest.is_empty() {
            return Err(KeyResolutionError::InvalidCertificate);
        }
        let public_key_bytes = certificate.public_key().raw.to_vec();
        validate_spki_algorithm(&public_key_bytes, algorithm)?;
        Ok(Some(VerificationKey {
            algorithm,
            public_key_bytes,
            certificate_der: Some(certificate_der.clone()),
            name: None,
        }))
    }

    fn verify_x509_policy(
        &self,
        info: &X509DataInfo,
        selected_lookup_certificate: Option<&[u8]>,
    ) -> Result<(), KeyResolutionError> {
        let trusted_certs = self
            .config
            .trusted_certs
            .iter()
            .filter(|certificate| {
                selected_lookup_certificate
                    .is_none_or(|selected| certificate.as_slice() != selected)
            })
            .cloned()
            .collect::<Vec<_>>();
        let options = X509ChainOptions {
            trusted_certs: &trusted_certs,
            verification_time: self
                .config
                .verification_time
                .unwrap_or_else(SystemTime::now),
            max_chain_depth: self.config.max_chain_depth,
            check_crls: false,
        };
        verify_x509_certificate_chain(info, &options)?;
        Ok(())
    }

    fn resolve_configured_x509<'a>(
        &'a self,
        info: &X509DataInfo,
    ) -> Result<Option<&'a Vec<u8>>, KeyResolutionError> {
        if !x509_data_has_lookup_identifiers(info) {
            return Ok(None);
        }

        let mut matches = Vec::new();
        for certificate_der in &self.config.trusted_certs {
            let parsed = parse_x509_certificate(certificate_der)
                .map_err(|_| KeyResolutionError::InvalidCertificate)?;
            let is_match = x509_certificate_matches_any_selector(info, &parsed, certificate_der)
                .map_err(|error| match error {
                    ParseError::UnsupportedAlgorithm { uri } => {
                        KeyResolutionError::UnsupportedDigestAlgorithm(uri)
                    }
                    _ => KeyResolutionError::InvalidCertificate,
                })?;
            if is_match {
                matches.push((certificate_der, parsed));
            }
        }

        let matched_chain = X509DataInfo {
            certificates: matches
                .iter()
                .map(|(certificate, _)| (*certificate).clone())
                .collect(),
            parsed_certificates: matches.iter().map(|(_, parsed)| parsed.clone()).collect(),
            ..X509DataInfo::default()
        };
        if !x509_selector_categories_match_chain(&X509DataInfo {
            subject_names: info.subject_names.clone(),
            issuer_serials: info.issuer_serials.clone(),
            skis: info.skis.clone(),
            digests: info.digests.clone(),
            ..matched_chain
        })
        .map_err(|error| match error {
            ParseError::UnsupportedAlgorithm { uri } => {
                KeyResolutionError::UnsupportedDigestAlgorithm(uri)
            }
            _ => KeyResolutionError::InvalidCertificate,
        })? {
            return Ok(None);
        }

        match matches.as_slice() {
            [] => Ok(None),
            [(certificate, _)] => Ok(Some(certificate)),
            _ => {
                let leaves = matches
                    .iter()
                    .filter(|(_, candidate)| {
                        candidate.subject_dn != candidate.issuer_dn
                            && !matches
                                .iter()
                                .any(|(_, other)| other.issuer_dn == candidate.subject_dn)
                    })
                    .collect::<Vec<_>>();
                match leaves.as_slice() {
                    [(certificate, _)] => Ok(Some(certificate)),
                    _ => Err(KeyResolutionError::AmbiguousCertificate),
                }
            }
        }
    }

    fn resolve_key_value(
        key_value: &KeyValueInfo,
        algorithm: SignatureAlgorithm,
    ) -> Result<Option<VerificationKey>, KeyResolutionError> {
        let public_key_bytes = match key_value {
            KeyValueInfo::Rsa { modulus, exponent } => {
                if !matches!(
                    algorithm,
                    SignatureAlgorithm::RsaSha1
                        | SignatureAlgorithm::RsaSha256
                        | SignatureAlgorithm::RsaSha384
                        | SignatureAlgorithm::RsaSha512
                ) {
                    return Err(KeyResolutionError::AlgorithmMismatch);
                }
                rsa_key_value_to_spki_der(modulus, exponent)?
            }
            KeyValueInfo::Ec {
                curve_oid,
                public_key,
            } => {
                if !matches!(
                    algorithm,
                    SignatureAlgorithm::EcdsaP256Sha256 | SignatureAlgorithm::EcdsaP384Sha384
                ) {
                    return Ok(None);
                }
                ec_key_value_to_spki_der(curve_oid, public_key)?
            }
            KeyValueInfo::InvalidEcKeyValue => return Err(KeyResolutionError::InvalidPublicKey),
            KeyValueInfo::Unsupported { .. } => return Ok(None),
        };
        validate_spki_algorithm(&public_key_bytes, algorithm)?;

        Ok(Some(VerificationKey {
            algorithm,
            public_key_bytes,
            certificate_der: None,
            name: None,
        }))
    }
}

impl KeyResolver for DefaultKeyResolver {
    fn resolve<'a>(
        &'a self,
        key_info: Option<&KeyInfo>,
        algorithm: SignatureAlgorithm,
    ) -> Result<Option<Box<dyn VerifyingKey + 'a>>, DsigError> {
        let Some(key_info) = key_info else {
            return Ok(None);
        };
        let mut deferred_key_value_error = None;
        for source in &key_info.sources {
            let resolved = match source {
                KeyInfoSource::X509Data(info) => self.resolve_x509(info, algorithm)?,
                KeyInfoSource::DerEncodedKeyValue(public_key_bytes) => {
                    validate_spki_algorithm(public_key_bytes, algorithm)?;
                    Some(VerificationKey {
                        algorithm,
                        public_key_bytes: public_key_bytes.clone(),
                        certificate_der: None,
                        name: None,
                    })
                }
                KeyInfoSource::KeyName(name) => self
                    .config
                    .named_keys
                    .get(name)
                    .map(|key| {
                        if key.algorithm != algorithm {
                            return Err(KeyResolutionError::AlgorithmMismatch);
                        }
                        validate_spki_algorithm(&key.public_key_bytes, algorithm)?;
                        Ok(key.clone())
                    })
                    .transpose()?,
                KeyInfoSource::KeyValue(key_value) => {
                    match Self::resolve_key_value(key_value, algorithm) {
                        Ok(resolved) => resolved,
                        Err(error) if ec_key_value_error_allows_fallback(key_value, &error) => {
                            deferred_key_value_error.get_or_insert(error);
                            None
                        }
                        Err(error) => return Err(error.into()),
                    }
                }
            };
            if let Some(key) = resolved {
                return Ok(Some(Box::new(key)));
            }
        }
        if let Some(error) = deferred_key_value_error {
            return Err(error.into());
        }
        Ok(None)
    }

    fn consumes_document_key_info(&self) -> bool {
        true
    }
}

fn rsa_key_value_to_spki_der(
    modulus: &[u8],
    exponent: &[u8],
) -> Result<Vec<u8>, KeyResolutionError> {
    let key = rsa::RsaPublicKey::new(
        BoxedUint::from_be_slice_vartime(modulus),
        BoxedUint::from_be_slice_vartime(exponent),
    )
    .map_err(|_| KeyResolutionError::InvalidPublicKey)?;
    key.to_public_key_der()
        .map_err(|_| KeyResolutionError::InvalidPublicKey)
        .map(|der| der.as_bytes().to_vec())
}

fn ec_key_value_to_spki_der(
    curve_oid: &str,
    public_key: &[u8],
) -> Result<Vec<u8>, KeyResolutionError> {
    match curve_oid {
        EC_P256_OID => p256::PublicKey::from_sec1_bytes(public_key)
            .map_err(|_| KeyResolutionError::InvalidPublicKey)?
            .to_public_key_der()
            .map_err(|_| KeyResolutionError::InvalidPublicKey)
            .map(|der| der.as_bytes().to_vec()),
        EC_P384_OID => p384::PublicKey::from_sec1_bytes(public_key)
            .map_err(|_| KeyResolutionError::InvalidPublicKey)?
            .to_public_key_der()
            .map_err(|_| KeyResolutionError::InvalidPublicKey)
            .map(|der| der.as_bytes().to_vec()),
        _ => Err(KeyResolutionError::InvalidPublicKey),
    }
}

fn ec_key_value_error_allows_fallback(
    key_value: &KeyValueInfo,
    error: &KeyResolutionError,
) -> bool {
    matches!(
        key_value,
        KeyValueInfo::Ec { .. } | KeyValueInfo::InvalidEcKeyValue
    ) && matches!(
        error,
        KeyResolutionError::InvalidPublicKey | KeyResolutionError::AlgorithmMismatch
    )
}

fn validate_spki_algorithm(
    public_key_bytes: &[u8],
    algorithm: SignatureAlgorithm,
) -> Result<(), KeyResolutionError> {
    let (rest, spki) = SubjectPublicKeyInfo::from_der(public_key_bytes)
        .map_err(|_| KeyResolutionError::InvalidPublicKey)?;
    if !rest.is_empty() {
        return Err(KeyResolutionError::InvalidPublicKey);
    }
    let parsed = spki
        .parsed()
        .map_err(|_| KeyResolutionError::InvalidPublicKey)?;
    let curve_oid = spki
        .algorithm
        .parameters
        .as_ref()
        .and_then(|value| value.as_oid().ok())
        .map(|oid| oid.to_id_string());
    match (algorithm, parsed) {
        (
            SignatureAlgorithm::RsaSha1
            | SignatureAlgorithm::RsaSha256
            | SignatureAlgorithm::RsaSha384
            | SignatureAlgorithm::RsaSha512,
            PublicKey::RSA(_),
        ) => Ok(()),
        (SignatureAlgorithm::EcdsaP256Sha256, PublicKey::EC(_))
            if curve_oid.as_deref() == Some("1.2.840.10045.3.1.7") =>
        {
            Ok(())
        }
        // xmlsec's OpenSSL backend maps ecdsa-sha384 to EVP_sha384() plus the
        // generic EC key class, without restricting the curve to P-384. Keep
        // P-521/SHA-384 compatible with that donor contract.
        (SignatureAlgorithm::EcdsaP384Sha384, PublicKey::EC(_))
            if matches!(curve_oid.as_deref(), Some("1.3.132.0.34" | "1.3.132.0.35")) =>
        {
            Ok(())
        }
        _ => Err(KeyResolutionError::AlgorithmMismatch),
    }
}

#[cfg(test)]
mod tests {
    use base64::{Engine, engine::general_purpose::STANDARD};
    use rsa::{pkcs8::DecodePublicKey, traits::PublicKeyParts};

    use super::*;

    const SIGNED_SAML: &str =
        include_str!("../../tests/fixtures/saml/response_signed_by_idp_ecdsa.xml");
    const SAML_PUBLIC_KEY: &str =
        include_str!("../../tests/fixtures/keys/ec/saml-idp-ecdsa-pubkey.pem");
    const RSA_PUBLIC_KEY: &str = include_str!("../../tests/fixtures/keys/rsa/rsa-2048-pubkey.pem");
    const RSA_4096_CERTIFICATE: &str =
        include_str!("../../tests/fixtures/keys/rsa/rsa-4096-cert.pem");
    const X509_DIGEST_SIGNATURE: &str = include_str!(
        "../../tests/fixtures/xmldsig/aleksey-xmldsig-01/enveloped-x509-digest-sha512.xml"
    );
    const RSA_KEY_VALUE_SIGNATURE: &str = include_str!(
        "../../tests/fixtures/xmldsig/aleksey-xmldsig-01/enveloping-sha256-rsa-sha256.xml"
    );
    const LEGACY_RSA_KEY_VALUE_SIGNATURE: &str = include_str!(
        "../../tests/fixtures/xmldsig/merlin-xmldsig-twenty-three/signature-enveloping-rsa.xml"
    );
    const EC_P256_KEY_VALUE_SIGNATURE: &str = include_str!(
        "../../tests/fixtures/xmldsig/xmldsig11-interop-2012/signature-enveloping-p256_sha256.xml"
    );
    const EC_P384_KEY_VALUE_SIGNATURE: &str = include_str!(
        "../../tests/fixtures/xmldsig/xmldsig11-interop-2012/signature-enveloping-p384_sha384.xml"
    );

    fn replace_key_info(xml: &str, replacement: &str) -> String {
        let start = xml.find("<ds:KeyInfo>").expect("fixture has KeyInfo");
        let end = xml
            .find("</ds:KeyInfo>")
            .expect("fixture has closing KeyInfo")
            + "</ds:KeyInfo>".len();
        format!("{}{}{}", &xml[..start], replacement, &xml[end..])
    }

    fn replace_unprefixed_key_info(xml: &str, replacement: &str) -> String {
        let start = xml.find("<KeyInfo>").expect("fixture has KeyInfo");
        let end = xml.find("</KeyInfo>").expect("fixture has closing KeyInfo") + "</KeyInfo>".len();
        format!("{}{}{}", &xml[..start], replacement, &xml[end..])
    }

    fn rsa_key_value_parts(public_key: &rsa::RsaPublicKey) -> (String, String) {
        (
            STANDARD.encode(public_key.n().to_be_bytes_trimmed_vartime()),
            STANDARD.encode(public_key.e().to_be_bytes_trimmed_vartime()),
        )
    }

    fn x509_signature_with_leaf_subject() -> String {
        replace_unprefixed_key_info(
            X509_DIGEST_SIGNATURE,
            "<KeyInfo><X509Data><X509SubjectName>C=US, ST=California, O=XML Security Library (http://www.aleksey.com/xmlsec), CN=Test Key rsa-4096</X509SubjectName></X509Data></KeyInfo>",
        )
    }

    fn fixture_certificate_time() -> SystemTime {
        // 2027-01-15 UTC, inside the donor certificates' 2026-2126 validity window.
        SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_800_000_000)
    }

    fn public_key_der(pem_text: &str) -> Vec<u8> {
        let (rest, pem) = x509_parser::pem::parse_x509_pem(pem_text.as_bytes())
            .expect("fixture public key is PEM");
        assert!(rest.iter().all(|byte| byte.is_ascii_whitespace()));
        assert_eq!(pem.label, "PUBLIC KEY");
        pem.contents
    }

    fn certificate_der(pem_text: &str) -> Vec<u8> {
        let (rest, pem) = x509_parser::pem::parse_x509_pem(pem_text.as_bytes())
            .expect("fixture certificate is PEM");
        assert!(rest.iter().all(|byte| byte.is_ascii_whitespace()));
        assert_eq!(pem.label, "CERTIFICATE");
        pem.contents
    }

    #[test]
    fn defaults_match_key_resolution_policy() {
        // Defaults must remain compatible with xmlsec1's depth and opt-in trust policy.
        let config = KeyResolverConfig::default();

        assert!(config.trusted_certs.is_empty());
        assert!(config.named_keys.is_empty());
        assert!(!config.verify_chains);
        assert_eq!(config.verification_time, None);
        assert_eq!(config.max_chain_depth, 9);
    }

    #[test]
    fn stores_named_verification_key_metadata() {
        // Named resolution must retain every field needed by the later resolver wiring.
        let key = VerificationKey {
            algorithm: SignatureAlgorithm::RsaSha256,
            public_key_bytes: vec![1, 2, 3],
            certificate_der: Some(vec![4, 5, 6]),
            name: Some("idp-signing".into()),
        };
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert("idp-signing".into(), key.clone());

        assert_eq!(config.named_keys.get("idp-signing"), Some(&key));
    }

    #[test]
    fn resolves_embedded_certificate_end_to_end() {
        // The default resolver must make parsed X509Data usable by VerifyContext.
        let resolver = DefaultKeyResolver::default();
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(SIGNED_SAML)
            .expect("embedded certificate should resolve");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn resolves_x509_digest_from_configured_certificates() {
        // Selector-only X509Data must locate the signing certificate without
        // embedding key material or supplying a preset verification key.
        let leaf_certificate_der = certificate_der(RSA_4096_CERTIFICATE);
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            trusted_certs: vec![
                leaf_certificate_der,
                certificate_der(include_str!("../../tests/fixtures/keys/ca2cert.pem")),
                certificate_der(include_str!("../../tests/fixtures/keys/cacert.pem")),
            ],
            ..KeyResolverConfig::default()
        });
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(X509_DIGEST_SIGNATURE)
            .expect("X509Digest should resolve a configured certificate");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn selector_resolved_certificate_obeys_chain_policy() {
        // Enabling chain verification must apply validity policy even when
        // X509Data contains only selectors and the matching cert is configured.
        let certificate_der = certificate_der(RSA_4096_CERTIFICATE);
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            trusted_certs: vec![certificate_der],
            verify_chains: true,
            verification_time: Some(SystemTime::UNIX_EPOCH),
            ..KeyResolverConfig::default()
        });
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&x509_signature_with_leaf_subject())
            .expect_err("selector-resolved certificate must satisfy chain policy");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::Chain(
                super::super::X509ChainError::CertificateNotValid(_)
            ))
        ));
    }

    #[test]
    fn selector_resolved_leaf_does_not_anchor_itself() {
        // A certificate available for selector lookup is not automatically a
        // trust anchor; chain verification still requires a separate issuer.
        let certificate_der = certificate_der(RSA_4096_CERTIFICATE);
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            trusted_certs: vec![certificate_der],
            verify_chains: true,
            verification_time: Some(fixture_certificate_time()),
            ..KeyResolverConfig::default()
        });
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&x509_signature_with_leaf_subject())
            .expect_err("selector-resolved leaf must not trust itself");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::Chain(
                super::super::X509ChainError::UntrustedRoot
            ))
        ));
    }

    #[test]
    fn selector_resolved_leaf_uses_separate_anchor() {
        // Selector lookup may use the leaf from the configured set, but chain
        // verification must terminate at a different configured certificate.
        let leaf = certificate_der(RSA_4096_CERTIFICATE);
        let issuer = certificate_der(include_str!("../../tests/fixtures/keys/ca2cert.pem"));
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            trusted_certs: vec![leaf, issuer],
            verify_chains: true,
            verification_time: Some(fixture_certificate_time()),
            ..KeyResolverConfig::default()
        });
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&x509_signature_with_leaf_subject())
            .expect("selector-resolved leaf should chain to its configured issuer");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn resolves_each_x509_selector_from_configured_certificates() {
        // Every selector form documented by KeyInfo must independently locate
        // the same configured RSA certificate without embedded key material.
        let selectors = [
            "<X509SubjectName>C=US, ST=California, O=XML Security Library (http://www.aleksey.com/xmlsec), CN=Test Key rsa-2048</X509SubjectName>",
            "<X509IssuerSerial><X509IssuerName>C=US, ST=California, O=XML Security Library (http://www.aleksey.com/xmlsec), OU=Second level CA, CN=Aleksey Sanin, Email=xmlsec@aleksey.com</X509IssuerName><X509SerialNumber>680572598617295163017172295025714171905498632019</X509SerialNumber></X509IssuerSerial>",
            "<X509SKI>bcOXN/nsVl8GatRbcKrPbzIbw0Y=</X509SKI>",
        ];
        let configured_certificate = certificate_der(include_str!(
            "../../tests/fixtures/keys/rsa/rsa-2048-cert.pem"
        ));

        for selector in selectors {
            let key_info = format!("<KeyInfo><X509Data>{selector}</X509Data></KeyInfo>");
            let xml = replace_unprefixed_key_info(RSA_KEY_VALUE_SIGNATURE, &key_info);
            let resolver = DefaultKeyResolver::new(KeyResolverConfig {
                trusted_certs: vec![configured_certificate.clone()],
                ..KeyResolverConfig::default()
            });
            let result = super::super::VerifyContext::new()
                .key_resolver(&resolver)
                .verify(&xml)
                .expect("X509 selector should resolve configured certificate");

            assert_eq!(result.status, super::super::DsigStatus::Valid);
        }
    }

    #[test]
    fn resolves_configured_chain_selectors_across_certificates() {
        // Selector categories may identify different members of one configured
        // chain; the unique leaf remains the signing certificate.
        let key_info = r#"<KeyInfo><X509Data><X509SubjectName>C=US, ST=California, O=XML Security Library (http://www.aleksey.com/xmlsec), CN=Test Key rsa-2048</X509SubjectName><X509SKI>0X0XrEVCio75sBcl1TxymJ2IOiU=</X509SKI></X509Data></KeyInfo>"#;
        let xml = replace_unprefixed_key_info(RSA_KEY_VALUE_SIGNATURE, key_info);
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            trusted_certs: vec![
                certificate_der(include_str!(
                    "../../tests/fixtures/keys/rsa/rsa-2048-cert.pem"
                )),
                certificate_der(include_str!("../../tests/fixtures/keys/ca2cert.pem")),
            ],
            ..KeyResolverConfig::default()
        });
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("selectors across one configured chain should resolve its leaf");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn unmatched_x509_selector_does_not_resolve() {
        // A selector mismatch must not fall back to arbitrary configured key material.
        let key_info = "<KeyInfo><X509Data><X509SubjectName>CN=not-the-signer</X509SubjectName></X509Data></KeyInfo>";
        let xml = replace_unprefixed_key_info(RSA_KEY_VALUE_SIGNATURE, key_info);
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            trusted_certs: vec![certificate_der(include_str!(
                "../../tests/fixtures/keys/rsa/rsa-2048-cert.pem"
            ))],
            ..KeyResolverConfig::default()
        });
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("an unmatched selector is a key miss, not a parser failure");

        assert!(matches!(
            result.status,
            super::super::DsigStatus::Invalid(super::super::FailureReason::KeyNotFound)
        ));
    }

    #[test]
    fn ambiguous_x509_selector_fails_closed() {
        // Duplicate configured certificates must not make key selection order-dependent.
        let certificate = certificate_der(RSA_4096_CERTIFICATE);
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            trusted_certs: vec![certificate.clone(), certificate],
            ..KeyResolverConfig::default()
        });
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&x509_signature_with_leaf_subject())
            .expect_err("ambiguous X509 selector lookup must fail closed");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::AmbiguousCertificate)
        ));
    }

    #[test]
    fn unsupported_x509_digest_selector_fails_closed() {
        // Unknown digest URIs must not be treated as a normal key miss because
        // that would silently weaken the caller's explicit selector policy.
        let key_info = "<KeyInfo xmlns:dsig11=\"http://www.w3.org/2009/xmldsig11#\"><X509Data><dsig11:X509Digest Algorithm=\"urn:unsupported\">AQ==</dsig11:X509Digest></X509Data></KeyInfo>";
        let xml = replace_unprefixed_key_info(RSA_KEY_VALUE_SIGNATURE, key_info);
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            trusted_certs: vec![certificate_der(include_str!(
                "../../tests/fixtures/keys/rsa/rsa-2048-cert.pem"
            ))],
            ..KeyResolverConfig::default()
        });
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect_err("unsupported X509Digest algorithm must fail closed");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::UnsupportedDigestAlgorithm(uri))
                if uri == "urn:unsupported"
        ));
    }

    #[test]
    fn resolves_named_key_end_to_end() {
        // KeyName lookup must preserve the same cryptographic result as embedded X509Data.
        let xml = replace_key_info(
            SIGNED_SAML,
            "<ds:KeyInfo><ds:KeyName>idp-signing</ds:KeyName></ds:KeyInfo>",
        );
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "idp-signing".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaP256Sha256,
                public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                certificate_der: None,
                name: Some("idp-signing".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("named key should resolve");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn resolves_der_encoded_key_end_to_end() {
        // DSig 1.1 DEREncodedKeyValue must feed the same SPKI verifier path.
        let encoded = STANDARD.encode(public_key_der(SAML_PUBLIC_KEY));
        let xml = replace_key_info(
            SIGNED_SAML,
            &format!(
                "<ds:KeyInfo><dsig11:DEREncodedKeyValue xmlns:dsig11=\"http://www.w3.org/2009/xmldsig11#\">{encoded}</dsig11:DEREncodedKeyValue></ds:KeyInfo>"
            ),
        );
        let resolver = DefaultKeyResolver::default();
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("DER key should resolve");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn resolves_rsa_key_value_end_to_end() {
        // Embedded CryptoBinary parameters must verify the original RSA-2048 donor signature.
        let public_key = rsa::RsaPublicKey::from_public_key_pem(RSA_PUBLIC_KEY)
            .expect("fixture must contain an RSA public key");
        let (modulus, exponent) = rsa_key_value_parts(&public_key);
        let key_info = format!(
            "<KeyInfo><KeyValue><RSAKeyValue><Modulus>{}</Modulus><Exponent>{}</Exponent></RSAKeyValue></KeyValue></KeyInfo>",
            modulus, exponent,
        );
        let xml = replace_unprefixed_key_info(RSA_KEY_VALUE_SIGNATURE, &key_info);
        let resolver = DefaultKeyResolver::default();
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("RSAKeyValue should resolve");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn rsa_key_value_rejects_legacy_weak_modulus() {
        // Embedded keys must obey the same 2048-bit minimum as certificate and DER keys.
        let resolver = DefaultKeyResolver::default();
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(LEGACY_RSA_KEY_VALUE_SIGNATURE)
            .expect_err("1024-bit RSAKeyValue must fail closed");

        assert!(matches!(
            error,
            DsigError::Crypto(super::super::SignatureVerificationError::InvalidKeyDer)
        ));
    }

    #[test]
    fn rsa_key_value_rejects_ecdsa_signature_method() {
        // Embedded RSA parameters must not be relabeled for an ECDSA SignatureMethod.
        let public_key = rsa::RsaPublicKey::from_public_key_pem(RSA_PUBLIC_KEY)
            .expect("fixture must contain an RSA public key");
        let (modulus, exponent) = rsa_key_value_parts(&public_key);
        let key_info = format!(
            "<ds:KeyInfo><ds:KeyValue><ds:RSAKeyValue><ds:Modulus>{}</ds:Modulus><ds:Exponent>{}</ds:Exponent></ds:RSAKeyValue></ds:KeyValue></ds:KeyInfo>",
            modulus, exponent,
        );
        let xml = replace_key_info(SIGNED_SAML, &key_info);
        let resolver = DefaultKeyResolver::default();
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect_err("RSAKeyValue must not resolve for ECDSA");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::AlgorithmMismatch)
        ));
    }

    #[test]
    fn resolves_ec_p256_key_value_end_to_end() {
        // XMLDSig 1.1 ECKeyValue must verify without a preset key or certificate.
        let resolver = DefaultKeyResolver::default();
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(EC_P256_KEY_VALUE_SIGNATURE)
            .expect("P-256 ECKeyValue should resolve");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn resolves_ec_p384_key_value_end_to_end() {
        // The donor P-384 vector uses NamedCurve + uncompressed PublicKey.
        let resolver = DefaultKeyResolver::default();
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(EC_P384_KEY_VALUE_SIGNATURE)
            .expect("P-384 ECKeyValue should resolve");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn ec_key_value_ignored_for_rsa_signature_method() {
        // Embedded EC key material must not be relabeled for an RSA SignatureMethod.
        let key_info = r#"<KeyInfo xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/><dsig11:PublicKey>BJ/yaXNlq4FRObyJCBhb5jAz8GVzinK3bBGLjSDfjbJwNfydtgjnlS4EsDmxSRhWyJWq6GIqy5wvnaiARK04uB4=</dsig11:PublicKey></dsig11:ECKeyValue></KeyValue></KeyInfo>"#;
        let xml = replace_unprefixed_key_info(RSA_KEY_VALUE_SIGNATURE, key_info);
        let resolver = DefaultKeyResolver::default();
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("single incompatible ECKeyValue should be ignored");

        assert_eq!(
            result.status,
            super::super::DsigStatus::Invalid(super::super::FailureReason::KeyNotFound)
        );
    }

    #[test]
    fn incompatible_ec_key_value_falls_back_to_later_rsa_key_value() {
        // Mixed KeyInfo should keep scanning after an incompatible ECKeyValue source.
        let public_key = rsa::RsaPublicKey::from_public_key_pem(RSA_PUBLIC_KEY)
            .expect("fixture must contain an RSA public key");
        let (modulus, exponent) = rsa_key_value_parts(&public_key);
        let key_info = format!(
            r#"<KeyInfo xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/><dsig11:PublicKey>BJ/yaXNlq4FRObyJCBhb5jAz8GVzinK3bBGLjSDfjbJwNfydtgjnlS4EsDmxSRhWyJWq6GIqy5wvnaiARK04uB4=</dsig11:PublicKey></dsig11:ECKeyValue></KeyValue><KeyValue><RSAKeyValue><Modulus>{}</Modulus><Exponent>{}</Exponent></RSAKeyValue></KeyValue></KeyInfo>"#,
            modulus, exponent,
        );
        let xml = replace_unprefixed_key_info(RSA_KEY_VALUE_SIGNATURE, &key_info);
        let resolver = DefaultKeyResolver::default();
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("later RSAKeyValue should resolve");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn unsupported_ec_key_value_falls_back_to_later_key_name() {
        // Unsupported curves are non-fatal so a later compatible source can verify.
        let key_info = r#"<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><ds:KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve URI="urn:oid:1.3.132.0.35"/><dsig11:PublicKey>BA==</dsig11:PublicKey></dsig11:ECKeyValue></ds:KeyValue><ds:KeyName>idp-signing</ds:KeyName></ds:KeyInfo>"#;
        let xml = replace_key_info(SIGNED_SAML, key_info);
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "idp-signing".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaP256Sha256,
                public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                certificate_der: None,
                name: Some("idp-signing".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("later KeyName should resolve");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn invalid_ec_key_value_falls_back_to_later_key_name() {
        // Off-curve EC points are typed errors only if no later source can verify.
        let key_info = r#"<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><ds:KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/><dsig11:PublicKey>BAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</dsig11:PublicKey></dsig11:ECKeyValue></ds:KeyValue><ds:KeyName>idp-signing</ds:KeyName></ds:KeyInfo>"#;
        let xml = replace_key_info(SIGNED_SAML, key_info);
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "idp-signing".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaP256Sha256,
                public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                certificate_der: None,
                name: Some("idp-signing".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("later KeyName should resolve after invalid ECKeyValue");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn malformed_ec_key_value_falls_back_to_later_key_name() {
        // Parse-level EC point errors remain non-fatal while later sources exist.
        let key_info = r#"<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><ds:KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/><dsig11:PublicKey>AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</dsig11:PublicKey></dsig11:ECKeyValue></ds:KeyValue><ds:KeyName>idp-signing</ds:KeyName></ds:KeyInfo>"#;
        let xml = replace_key_info(SIGNED_SAML, key_info);
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "idp-signing".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaP256Sha256,
                public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                certificate_der: None,
                name: Some("idp-signing".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("later KeyName should resolve after malformed ECKeyValue");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn invalid_base64_ec_key_value_falls_back_to_later_key_name() {
        // A bad ECKeyValue payload is an unusable source, not a reason to skip
        // later ordered KeyInfo sources that can verify the signature.
        let key_info = r#"<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><ds:KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/><dsig11:PublicKey>not base64!</dsig11:PublicKey></dsig11:ECKeyValue></ds:KeyValue><ds:KeyName>idp-signing</ds:KeyName></ds:KeyInfo>"#;
        let xml = replace_key_info(SIGNED_SAML, key_info);
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "idp-signing".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaP256Sha256,
                public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                certificate_der: None,
                name: Some("idp-signing".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("later KeyName should resolve after bad ECKeyValue base64");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn missing_curve_uri_ec_key_value_falls_back_to_later_key_name() {
        // Missing EC curve parameters make only this KeyValue source unusable.
        let key_info = r#"<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><ds:KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve/><dsig11:PublicKey>BA==</dsig11:PublicKey></dsig11:ECKeyValue></ds:KeyValue><ds:KeyName>idp-signing</ds:KeyName></ds:KeyInfo>"#;
        let xml = replace_key_info(SIGNED_SAML, key_info);
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "idp-signing".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaP256Sha256,
                public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                certificate_der: None,
                name: Some("idp-signing".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("later KeyName should resolve after missing EC curve URI");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn malformed_ec_key_value_children_fall_back_to_later_key_name() {
        // An unusable EC source must not prevent later ordered KeyInfo sources
        // from resolving, regardless of which required child-shape check fails.
        let malformed_ec_key_values = [
            r#"<dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/>"#,
            r#"<dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/><dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/>"#,
            r#"<dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/><dsig11:PublicKey>BA==</dsig11:PublicKey><dsig11:PublicKey>BA==</dsig11:PublicKey>"#,
        ];

        for malformed_children in malformed_ec_key_values {
            let key_info = format!(
                r#"<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><ds:KeyValue><dsig11:ECKeyValue>{malformed_children}</dsig11:ECKeyValue></ds:KeyValue><ds:KeyName>idp-signing</ds:KeyName></ds:KeyInfo>"#
            );
            let xml = replace_key_info(SIGNED_SAML, &key_info);
            let mut config = KeyResolverConfig::default();
            config.named_keys.insert(
                "idp-signing".into(),
                VerificationKey {
                    algorithm: SignatureAlgorithm::EcdsaP256Sha256,
                    public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                    certificate_der: None,
                    name: Some("idp-signing".into()),
                },
            );
            let resolver = DefaultKeyResolver::new(config);
            let result = super::super::VerifyContext::new()
                .key_resolver(&resolver)
                .verify(&xml)
                .expect("later KeyName should resolve after malformed EC child shape");

            assert_eq!(result.status, super::super::DsigStatus::Valid);
        }
    }

    #[test]
    fn mismatched_ec_curve_falls_back_to_later_key_name() {
        // A valid P-384 key is unusable for an ECDSA-SHA256 signature but must not
        // prevent a later P-256 KeyName from resolving the same document.
        let key_info = r#"<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><ds:KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve URI="urn:oid:1.3.132.0.34"/><dsig11:PublicKey>BO/yd/OZzDfjX4qivDY/vsUIuh6KWAxoxW5P4ukvwd+T6pVljWsX2UBJNNy5MdhTwB8e2YwB8kUbJwdsAS/XGi/fz8unFrs+lVlAgIs6s/xBYFbfUoRiAacD2SpVDe6XBA==</dsig11:PublicKey></dsig11:ECKeyValue></ds:KeyValue><ds:KeyName>idp-signing</ds:KeyName></ds:KeyInfo>"#;
        let xml = replace_key_info(SIGNED_SAML, key_info);
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "idp-signing".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaP256Sha256,
                public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                certificate_der: None,
                name: Some("idp-signing".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let result = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect("later KeyName should resolve after mismatched ECKeyValue");

        assert_eq!(result.status, super::super::DsigStatus::Valid);
    }

    #[test]
    fn lone_malformed_ec_key_value_reports_invalid_public_key() {
        let key_info = r#"<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><ds:KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve URI="urn:oid:1.2.840.10045.3.1.7"/><dsig11:PublicKey>AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=</dsig11:PublicKey></dsig11:ECKeyValue></ds:KeyValue></ds:KeyInfo>"#;
        let xml = replace_key_info(SIGNED_SAML, key_info);
        let error = super::super::VerifyContext::new()
            .key_resolver(&DefaultKeyResolver::default())
            .verify(&xml)
            .expect_err("lone malformed ECKeyValue should surface typed key error");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::InvalidPublicKey)
        ));
    }

    #[test]
    fn lone_mismatched_ec_curve_reports_algorithm_mismatch() {
        let key_info = r#"<ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns:dsig11="http://www.w3.org/2009/xmldsig11#"><ds:KeyValue><dsig11:ECKeyValue><dsig11:NamedCurve URI="urn:oid:1.3.132.0.34"/><dsig11:PublicKey>BO/yd/OZzDfjX4qivDY/vsUIuh6KWAxoxW5P4ukvwd+T6pVljWsX2UBJNNy5MdhTwB8e2YwB8kUbJwdsAS/XGi/fz8unFrs+lVlAgIs6s/xBYFbfUoRiAacD2SpVDe6XBA==</dsig11:PublicKey></dsig11:ECKeyValue></ds:KeyValue></ds:KeyInfo>"#;
        let xml = replace_key_info(SIGNED_SAML, key_info);
        let error = super::super::VerifyContext::new()
            .key_resolver(&DefaultKeyResolver::default())
            .verify(&xml)
            .expect_err("lone mismatched ECKeyValue should surface typed key error");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::AlgorithmMismatch)
        ));
    }

    #[test]
    fn chain_verification_rejects_untrusted_embedded_certificate() {
        // Enabling chain policy must fail closed when no trust anchor is configured.
        let resolver = DefaultKeyResolver::new(KeyResolverConfig {
            verify_chains: true,
            ..KeyResolverConfig::default()
        });
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(SIGNED_SAML)
            .expect_err("untrusted certificate must fail chain validation");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::Chain(
                super::super::X509ChainError::UntrustedRoot
            ))
        ));
    }

    #[test]
    fn named_key_algorithm_mismatch_fails_closed() {
        // A key registered for RSA must never be attempted for an ECDSA signature.
        let xml = replace_key_info(
            SIGNED_SAML,
            "<ds:KeyInfo><ds:KeyName>wrong-algorithm</ds:KeyName></ds:KeyInfo>",
        );
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "wrong-algorithm".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::RsaSha256,
                public_key_bytes: public_key_der(SAML_PUBLIC_KEY),
                certificate_der: None,
                name: Some("wrong-algorithm".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect_err("algorithm mismatch must fail closed");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::AlgorithmMismatch)
        ));
    }

    #[test]
    fn named_key_spki_type_mismatch_fails_during_resolution() {
        // The configured algorithm label cannot override the actual SPKI key type.
        let xml = replace_key_info(
            SIGNED_SAML,
            "<ds:KeyInfo><ds:KeyName>mislabeled</ds:KeyName></ds:KeyInfo>",
        );
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "mislabeled".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaP256Sha256,
                public_key_bytes: public_key_der(RSA_PUBLIC_KEY),
                certificate_der: None,
                name: Some("mislabeled".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect_err("mislabeled named key must fail during resolution");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::AlgorithmMismatch)
        ));
    }

    #[test]
    fn malformed_named_key_reports_public_key_error() {
        // Non-certificate SPKI failures must not be mislabeled as certificate errors.
        let xml = replace_key_info(
            SIGNED_SAML,
            "<ds:KeyInfo><ds:KeyName>malformed</ds:KeyName></ds:KeyInfo>",
        );
        let mut config = KeyResolverConfig::default();
        config.named_keys.insert(
            "malformed".into(),
            VerificationKey {
                algorithm: SignatureAlgorithm::EcdsaP256Sha256,
                public_key_bytes: vec![1, 2, 3],
                certificate_der: None,
                name: Some("malformed".into()),
            },
        );
        let resolver = DefaultKeyResolver::new(config);
        let error = super::super::VerifyContext::new()
            .key_resolver(&resolver)
            .verify(&xml)
            .expect_err("malformed named key must fail during resolution");

        assert!(matches!(
            error,
            DsigError::KeyResolution(KeyResolutionError::InvalidPublicKey)
        ));
    }
}