saml 0.0.1-alpha.1

Stateless, async-native SAML 2.0 toolkit with no libxml2/xmlsec C build chain
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
//! XML-Encryption decryption per W3C XML-Encryption (TR/2002/REC-xmlenc-core-).
//! See `docs/rfcs/RFC-002-xml-crypto-core.md` ยง7.
//!
//! The entry point `decrypt_encrypted_assertion` unwraps a
//! `<saml:EncryptedAssertion>` element into the cleartext `<saml:Assertion>`,
//! returning the freshly-parsed element root. Algorithm acceptance is gated
//! by caller-supplied allow-lists (sourced from the peer's
//! `PeerCryptoPolicy`); compile-time `weak-algos` only controls which
//! variants exist โ€” never which are accepted at runtime.

use aes::cipher::{BlockDecryptMut, KeyIvInit, block_padding::Pkcs7};
use aes_gcm::aead::{Aead, KeyInit, Payload};
use aes_gcm::{Aes128Gcm, Aes256Gcm};
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;

use crate::crypto::keypair::{KeyPair, OaepDigest};
use crate::error::Error;
use crate::xml::parse::{Document, Element};
use crate::xmlenc::algorithms::{DataEncryptionAlgorithm, KeyTransportAlgorithm};

// =============================================================================
// XML namespace URIs we look up by.
// =============================================================================

const XENC_NS: &str = "http://www.w3.org/2001/04/xmlenc#";
const DS_NS: &str = "http://www.w3.org/2000/09/xmldsig#";

// XML-Enc digest method URIs we recognize when reading the OAEP digest.
const SHA1_DIGEST_URI: &str = "http://www.w3.org/2000/09/xmldsig#sha1";
const SHA256_DIGEST_URI: &str = "http://www.w3.org/2001/04/xmlenc#sha256";
const SHA384_DIGEST_URI: &str = "http://www.w3.org/2001/04/xmldsig-more#sha384";
const SHA512_DIGEST_URI: &str = "http://www.w3.org/2001/04/xmlenc#sha512";

// =============================================================================
// Public entry point
// =============================================================================

/// Decrypt a `<saml:EncryptedAssertion>` (or any element that contains an
/// `<xenc:EncryptedData>` payload) and return the cleartext element. The
/// returned element is freshly parsed from the decrypted XML bytes.
///
/// The algorithm allow-lists are sourced from the peer's effective
/// `PeerCryptoPolicy`; calling this function with a permissive list defeats
/// the policy. Roles MUST thread their per-peer allow-lists through unchanged.
///
/// Decryption-key rotation: `decryption_keys` is tried in order; the first
/// key whose `RSA` key-transport unwrap succeeds wins. Failures from earlier
/// keys are discarded (Bleichenbacher-safe per `KeyPair::decrypt_rsa_pkcs1v15`).
pub(crate) fn decrypt_encrypted_assertion(
    encrypted_assertion: &Element,
    decryption_keys: &[&KeyPair],
    allowed_data_algorithms: &[DataEncryptionAlgorithm],
    allowed_key_transport_algorithms: &[KeyTransportAlgorithm],
) -> Result<Element, Error> {
    // -- 1. Locate <xenc:EncryptedData>. --
    let encrypted_data = encrypted_assertion
        .child_element(Some(XENC_NS), "EncryptedData")
        .ok_or(Error::DecryptFailed {
            reason: "missing EncryptedData",
        })?;

    // -- 2. Read the data-encryption algorithm and policy-check it. --
    let data_em = encrypted_data
        .child_element(Some(XENC_NS), "EncryptionMethod")
        .ok_or(Error::DecryptFailed {
            reason: "missing EncryptedData/EncryptionMethod",
        })?;
    let data_alg_uri = data_em
        .attribute(None, "Algorithm")
        .ok_or(Error::DecryptFailed {
            reason: "missing EncryptionMethod/@Algorithm",
        })?;
    let data_algorithm = DataEncryptionAlgorithm::from_uri(data_alg_uri)?;
    if !allowed_data_algorithms.contains(&data_algorithm) {
        return Err(Error::DisallowedAlgorithm {
            alg: data_alg_uri.to_owned(),
        });
    }

    // -- 3. Locate <ds:KeyInfo>/<xenc:EncryptedKey>. --
    let key_info =
        encrypted_data
            .child_element(Some(DS_NS), "KeyInfo")
            .ok_or(Error::DecryptFailed {
                reason: "missing KeyInfo",
            })?;
    let encrypted_key = key_info
        .child_element(Some(XENC_NS), "EncryptedKey")
        .ok_or(Error::DecryptFailed {
            reason: "missing EncryptedKey",
        })?;
    let key_em = encrypted_key
        .child_element(Some(XENC_NS), "EncryptionMethod")
        .ok_or(Error::DecryptFailed {
            reason: "missing EncryptedKey/EncryptionMethod",
        })?;
    let key_alg_uri = key_em
        .attribute(None, "Algorithm")
        .ok_or(Error::DecryptFailed {
            reason: "missing EncryptedKey/EncryptionMethod/@Algorithm",
        })?;
    let key_transport_algorithm = KeyTransportAlgorithm::from_uri(key_alg_uri)?;
    if !allowed_key_transport_algorithms.contains(&key_transport_algorithm) {
        return Err(Error::DisallowedAlgorithm {
            alg: key_alg_uri.to_owned(),
        });
    }

    // -- 4. Choose the OAEP digest from <ds:DigestMethod> when applicable. --
    let oaep_digest = match key_transport_algorithm {
        KeyTransportAlgorithm::RsaOaep => oaep_digest_from_method(key_em)?,
        KeyTransportAlgorithm::RsaOaepMgf1Sha1 => OaepDigest::Sha1,
        #[cfg(feature = "weak-algos")]
        KeyTransportAlgorithm::RsaPkcs1V15 => OaepDigest::Sha1, // unused
    };

    // -- 5. Base64-decode the wrapped session key. --
    let wrapped_key_bytes = extract_cipher_value(encrypted_key)?;

    // -- 6. Try each decryption key; first success wins. --
    let session_key = unwrap_session_key(
        &wrapped_key_bytes,
        decryption_keys,
        key_transport_algorithm,
        oaep_digest,
    )?;

    // -- 7. Verify key length matches the data algorithm. --
    if session_key.len() != data_algorithm.key_size() {
        return Err(Error::DecryptFailed {
            reason: "key size mismatch",
        });
    }

    // -- 8. Base64-decode the payload ciphertext (iv/nonce || ct [|| tag]). --
    let ciphertext = extract_cipher_value(encrypted_data)?;

    // -- 9. Decrypt the payload. --
    let plaintext = decrypt_data(data_algorithm, &session_key, &ciphertext)?;

    // -- 10. Re-parse the decrypted XML and return the root element. --
    let doc = Document::parse(&plaintext)?;
    Ok(doc.root().clone())
}

// =============================================================================
// Internal helpers
// =============================================================================

/// Read the OAEP digest from `<EncryptionMethod>/<ds:DigestMethod>`. Per the
/// project hint, when the algorithm URI is the modern `xmlenc11#rsa-oaep`
/// and no `<ds:DigestMethod>` is present we default to SHA-256 (the modern
/// profile default). Legacy `rsa-oaep-mgf1p` would default to SHA-1 โ€” but
/// that path doesn't call this function (it pins SHA-1 directly).
fn oaep_digest_from_method(encryption_method: &Element) -> Result<OaepDigest, Error> {
    let Some(digest_method) = encryption_method.child_element(Some(DS_NS), "DigestMethod") else {
        return Ok(OaepDigest::Sha256);
    };
    let uri = digest_method
        .attribute(None, "Algorithm")
        .ok_or(Error::DecryptFailed {
            reason: "missing DigestMethod/@Algorithm",
        })?;
    match uri {
        SHA1_DIGEST_URI => Ok(OaepDigest::Sha1),
        SHA256_DIGEST_URI => Ok(OaepDigest::Sha256),
        SHA384_DIGEST_URI => Ok(OaepDigest::Sha384),
        SHA512_DIGEST_URI => Ok(OaepDigest::Sha512),
        other => Err(Error::DisallowedAlgorithm {
            alg: other.to_owned(),
        }),
    }
}

/// Extract and base64-decode the text content of
/// `<.../xenc:CipherData/xenc:CipherValue>`.
fn extract_cipher_value(parent: &Element) -> Result<Vec<u8>, Error> {
    let cipher_data =
        parent
            .child_element(Some(XENC_NS), "CipherData")
            .ok_or(Error::DecryptFailed {
                reason: "missing CipherData",
            })?;
    let cipher_value = cipher_data
        .child_element(Some(XENC_NS), "CipherValue")
        .ok_or(Error::DecryptFailed {
            reason: "missing CipherValue",
        })?;
    decode_base64_ws_tolerant(&cipher_value.text_content())
}

/// Base64-decode, tolerating any internal whitespace. `<xenc:CipherValue>`
/// payloads are commonly line-wrapped by XML serializers.
fn decode_base64_ws_tolerant(text: &str) -> Result<Vec<u8>, Error> {
    let cleaned: String = text.chars().filter(|c| !c.is_whitespace()).collect();
    BASE64_STANDARD
        .decode(cleaned.as_bytes())
        // Discarded intentionally: the underlying base64 decode error message
        // would echo per-byte details. Surface the generic variant.
        .map_err(|_err| Error::Base64Decode)
}

/// Try each candidate `KeyPair` against the wrapped session key until one
/// succeeds. Per RFC-002 ยง7.3, all per-key failure modes collapse into a
/// single generic `Error::DecryptFailed { reason: "key transport" }` so that
/// the failure does not leak chosen-ciphertext-distinguishable information.
fn unwrap_session_key(
    wrapped: &[u8],
    keys: &[&KeyPair],
    algorithm: KeyTransportAlgorithm,
    oaep_digest: OaepDigest,
) -> Result<Vec<u8>, Error> {
    for key in keys {
        let attempt = match algorithm {
            KeyTransportAlgorithm::RsaOaep | KeyTransportAlgorithm::RsaOaepMgf1Sha1 => {
                key.decrypt_rsa_oaep(wrapped, oaep_digest)
            }
            #[cfg(feature = "weak-algos")]
            KeyTransportAlgorithm::RsaPkcs1V15 => key.decrypt_rsa_pkcs1v15(wrapped),
        };
        if let Ok(session_key) = attempt {
            return Ok(session_key);
        }
        // Discard the error; try the next key. Bleichenbacher safety: do not
        // surface the per-key failure reason โ€” `decrypt_rsa_pkcs1v15` already
        // folds its internal padding/length errors into a single
        // `DecryptFailed { reason: "key transport" }`, and we do the same here
        // for OAEP. Surfacing per-key reasons would let an attacker tell
        // "this key didn't match" apart from "padding parse failed", which is
        // the exact side-channel we are eliminating.
    }
    Err(Error::DecryptFailed {
        reason: "key transport",
    })
}

/// Decrypt `ciphertext` (formatted as `iv/nonce || ct [|| tag]`) under
/// `session_key`. Failure surfaces as `Error::DecryptFailed { reason: "data" }`
/// regardless of where in the AEAD/CBC pipeline it occurred.
fn decrypt_data(
    algorithm: DataEncryptionAlgorithm,
    session_key: &[u8],
    ciphertext: &[u8],
) -> Result<Vec<u8>, Error> {
    match algorithm {
        DataEncryptionAlgorithm::Aes128Cbc => decrypt_cbc::<aes::Aes128>(session_key, ciphertext),
        DataEncryptionAlgorithm::Aes256Cbc => decrypt_cbc::<aes::Aes256>(session_key, ciphertext),
        DataEncryptionAlgorithm::Aes128Gcm => decrypt_gcm::<Aes128Gcm>(session_key, ciphertext),
        DataEncryptionAlgorithm::Aes256Gcm => decrypt_gcm::<Aes256Gcm>(session_key, ciphertext),
    }
}

fn decrypt_cbc<C>(session_key: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, Error>
where
    C: aes::cipher::BlockCipher + aes::cipher::BlockDecrypt + aes::cipher::KeyInit,
{
    if ciphertext.len() < 16 {
        return Err(Error::DecryptFailed { reason: "data" });
    }
    let (iv, ct) = ciphertext.split_at(16);
    // Discarded intentionally: surfacing the cipher-init reason would leak
    // session-key shape; collapse into a generic mismatch error.
    let decryptor = cbc::Decryptor::<C>::new_from_slices(session_key, iv).map_err(|_err| {
        Error::DecryptFailed {
            reason: "key size mismatch",
        }
    })?;
    // Use the buffer-to-buffer form so we don't require `cipher/alloc` โ€”
    // the destination buffer is sized to the ciphertext length (PKCS#7
    // padding can only shrink, never grow, the unpadded output).
    let mut out = vec![0u8; ct.len()];
    // Discarded intentionally: padding-failure detail is a known side-channel
    // (cf. Vaudenay padding-oracle attacks); collapse to a generic reason.
    let written = decryptor
        .decrypt_padded_b2b_mut::<Pkcs7>(ct, &mut out)
        .map_err(|_err| Error::DecryptFailed { reason: "data" })?
        .len();
    out.truncate(written);
    Ok(out)
}

fn decrypt_gcm<C>(session_key: &[u8], ciphertext: &[u8]) -> Result<Vec<u8>, Error>
where
    C: KeyInit + Aead,
{
    if ciphertext.len() < 12 + 16 {
        return Err(Error::DecryptFailed { reason: "data" });
    }
    let (nonce_bytes, ct_with_tag) = ciphertext.split_at(12);
    // Discarded intentionally: see the CBC path; key-init detail is omitted.
    let cipher = C::new_from_slice(session_key).map_err(|_err| Error::DecryptFailed {
        reason: "key size mismatch",
    })?;
    cipher
        .decrypt(
            aes_gcm::Nonce::from_slice(nonce_bytes),
            Payload {
                msg: ct_with_tag,
                aad: &[],
            },
        )
        // Discarded intentionally: AEAD tag-failure detail must not be
        // surfaced; collapse to a single generic reason.
        .map_err(|_err| Error::DecryptFailed { reason: "data" })
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::crypto::cert::X509Certificate;
    use crate::crypto::cert::test_vectors::{RSA_CERT_PEM, RSA_KEY_PKCS8_PEM};
    use crate::xml::emit::emit_element;
    use crate::xml::parse::{Document, Node, QName};
    use crate::xmlenc::encrypt::encrypt_assertion;

    const SAML_NS: &str = "urn:oasis:names:tc:SAML:2.0:assertion";

    /// Build a small `<saml:Assertion>` carrying its own xmlns declaration so
    /// `emit_element` can serialize it standalone.
    fn sample_assertion() -> Element {
        let subject = Element::build(QName::new(Some(SAML_NS.to_owned()), "Subject"))
            .with_text("alice@example.org")
            .finish();
        Element::build(QName::new(Some(SAML_NS.to_owned()), "Assertion"))
            .with_namespace(Some("saml".to_owned()), SAML_NS)
            .with_attribute(QName::new(None, "ID"), "_a1")
            .with_child(Node::Element(subject))
            .finish()
    }

    fn rsa_keypair() -> KeyPair {
        KeyPair::from_pkcs8_pem(RSA_KEY_PKCS8_PEM).unwrap()
    }

    fn rsa_cert() -> X509Certificate {
        X509Certificate::from_pem(RSA_CERT_PEM).unwrap()
    }

    /// Helper: encrypt with `data`/`kt`, then decrypt with default allow-lists
    /// covering those two algorithms.
    fn roundtrip(
        data: DataEncryptionAlgorithm,
        kt: KeyTransportAlgorithm,
    ) -> Result<Element, Error> {
        let assertion = sample_assertion();
        let encrypted = encrypt_assertion(&assertion, &rsa_cert(), data, kt)?;
        let kp = rsa_keypair();
        decrypt_encrypted_assertion(&encrypted, &[&kp], &[data], &[kt])
    }

    #[test]
    fn round_trip_aes256_gcm_rsa_oaep_sha256() {
        let assertion = sample_assertion();
        let encrypted = encrypt_assertion(
            &assertion,
            &rsa_cert(),
            DataEncryptionAlgorithm::Aes256Gcm,
            KeyTransportAlgorithm::RsaOaep,
        )
        .expect("encrypt");
        let kp = rsa_keypair();
        let decrypted = decrypt_encrypted_assertion(
            &encrypted,
            &[&kp],
            &[DataEncryptionAlgorithm::Aes256Gcm],
            &[KeyTransportAlgorithm::RsaOaep],
        )
        .expect("decrypt");

        assert_eq!(decrypted.qname().local(), "Assertion");
        assert_eq!(decrypted.qname().namespace(), Some(SAML_NS));
        let subject = decrypted
            .child_element(Some(SAML_NS), "Subject")
            .expect("Subject");
        assert_eq!(subject.text_content(), "alice@example.org");
    }

    #[test]
    fn round_trip_aes128_gcm_rsa_oaep() {
        let decrypted = roundtrip(
            DataEncryptionAlgorithm::Aes128Gcm,
            KeyTransportAlgorithm::RsaOaep,
        )
        .expect("round-trip");
        assert_eq!(decrypted.qname().local(), "Assertion");
    }

    #[test]
    fn round_trip_aes256_cbc_rsa_oaep() {
        let decrypted = roundtrip(
            DataEncryptionAlgorithm::Aes256Cbc,
            KeyTransportAlgorithm::RsaOaep,
        )
        .expect("CBC round-trip");
        let subject = decrypted
            .child_element(Some(SAML_NS), "Subject")
            .expect("Subject");
        assert_eq!(subject.text_content(), "alice@example.org");
    }

    /// AES-128-CBC + RSA-OAEP-MGF1-SHA1 is the legacy combination. SHA-1 OAEP
    /// requires `weak-algos`; we only assert the round-trip when that's on.
    #[cfg(feature = "weak-algos")]
    #[test]
    fn round_trip_aes128_cbc_rsa_oaep_mgf1_sha1() {
        let decrypted = roundtrip(
            DataEncryptionAlgorithm::Aes128Cbc,
            KeyTransportAlgorithm::RsaOaepMgf1Sha1,
        )
        .expect("legacy round-trip");
        assert_eq!(decrypted.qname().local(), "Assertion");
    }

    #[test]
    fn disallowed_data_algorithm_rejected() {
        let assertion = sample_assertion();
        let encrypted = encrypt_assertion(
            &assertion,
            &rsa_cert(),
            DataEncryptionAlgorithm::Aes128Cbc,
            KeyTransportAlgorithm::RsaOaep,
        )
        .expect("encrypt");
        let kp = rsa_keypair();
        let err = decrypt_encrypted_assertion(
            &encrypted,
            &[&kp],
            // Only GCM is allowed.
            &[DataEncryptionAlgorithm::Aes256Gcm],
            &[KeyTransportAlgorithm::RsaOaep],
        )
        .expect_err("CBC not in allow-list");
        match err {
            Error::DisallowedAlgorithm { alg } => {
                assert_eq!(alg, DataEncryptionAlgorithm::Aes128Cbc.uri());
            }
            other => panic!("expected DisallowedAlgorithm, got {other:?}"),
        }
    }

    #[test]
    fn disallowed_key_transport_algorithm_rejected() {
        let assertion = sample_assertion();
        let encrypted = encrypt_assertion(
            &assertion,
            &rsa_cert(),
            DataEncryptionAlgorithm::Aes256Gcm,
            KeyTransportAlgorithm::RsaOaep,
        )
        .expect("encrypt");
        let kp = rsa_keypair();
        // Force an allow-list that *doesn't* include RsaOaep.
        let err = decrypt_encrypted_assertion(
            &encrypted,
            &[&kp],
            &[DataEncryptionAlgorithm::Aes256Gcm],
            &[KeyTransportAlgorithm::RsaOaepMgf1Sha1],
        )
        .expect_err("RsaOaep not in allow-list");
        match err {
            Error::DisallowedAlgorithm { alg } => {
                assert_eq!(alg, KeyTransportAlgorithm::RsaOaep.uri());
            }
            other => panic!("expected DisallowedAlgorithm, got {other:?}"),
        }
    }

    /// Forge an EncryptedAssertion whose data algorithm is GCM but whose
    /// wrapped session key is the wrong size for GCM. The decrypter must
    /// reject this *after* successfully unwrapping, with
    /// `DecryptFailed { reason: "key size mismatch" }`.
    #[test]
    fn key_size_mismatch_rejected() {
        // Build a GCM-128 ciphertext but advertise it as GCM-256.
        let assertion = sample_assertion();
        let mut encrypted = encrypt_assertion(
            &assertion,
            &rsa_cert(),
            DataEncryptionAlgorithm::Aes128Gcm,
            KeyTransportAlgorithm::RsaOaep,
        )
        .expect("encrypt 128");
        // Walk into the tree and change the data EncryptionMethod's Algorithm
        // attribute to advertise AES-256-GCM.
        let new_uri = DataEncryptionAlgorithm::Aes256Gcm.uri().to_owned();
        mutate_data_em_algorithm(&mut encrypted, new_uri);

        let kp = rsa_keypair();
        let err = decrypt_encrypted_assertion(
            &encrypted,
            &[&kp],
            &[
                DataEncryptionAlgorithm::Aes128Gcm,
                DataEncryptionAlgorithm::Aes256Gcm,
            ],
            &[KeyTransportAlgorithm::RsaOaep],
        )
        .expect_err("key size mismatch should be caught");
        match err {
            Error::DecryptFailed { reason } => assert_eq!(reason, "key size mismatch"),
            other => panic!("expected DecryptFailed, got {other:?}"),
        }
    }

    /// Tamper with the GCM auth tag (last 16 bytes of CipherValue) โ€” decrypt
    /// must fail.
    #[test]
    fn gcm_tag_tamper_rejected() {
        let assertion = sample_assertion();
        let mut encrypted = encrypt_assertion(
            &assertion,
            &rsa_cert(),
            DataEncryptionAlgorithm::Aes256Gcm,
            KeyTransportAlgorithm::RsaOaep,
        )
        .expect("encrypt");
        // Flip a bit in the last byte of the payload CipherValue.
        flip_last_byte_in_data_cipher_value(&mut encrypted);

        let kp = rsa_keypair();
        let err = decrypt_encrypted_assertion(
            &encrypted,
            &[&kp],
            &[DataEncryptionAlgorithm::Aes256Gcm],
            &[KeyTransportAlgorithm::RsaOaep],
        )
        .expect_err("tag tamper");
        match err {
            Error::DecryptFailed { reason } => assert_eq!(reason, "data"),
            other => panic!("expected DecryptFailed, got {other:?}"),
        }
    }

    /// Tamper with a CBC payload byte โ€” PKCS#7 unpad should fail (or decrypt
    /// to non-XML, which would also be rejected at re-parse). Either way the
    /// decrypter must not silently accept.
    #[test]
    fn cbc_payload_tamper_rejected() {
        let assertion = sample_assertion();
        let mut encrypted = encrypt_assertion(
            &assertion,
            &rsa_cert(),
            DataEncryptionAlgorithm::Aes256Cbc,
            KeyTransportAlgorithm::RsaOaep,
        )
        .expect("encrypt CBC");
        flip_last_byte_in_data_cipher_value(&mut encrypted);

        let kp = rsa_keypair();
        let err = decrypt_encrypted_assertion(
            &encrypted,
            &[&kp],
            &[DataEncryptionAlgorithm::Aes256Cbc],
            &[KeyTransportAlgorithm::RsaOaep],
        )
        .expect_err("CBC tamper");
        // Tampering with the *last* CBC block invalidates PKCS#7 padding,
        // which our decoder surfaces as DecryptFailed { reason: "data" }. If
        // the byte happens to fall on a non-padding region, the unpadded
        // plaintext may still be non-XML and surface as Error::XmlParse.
        match err {
            Error::DecryptFailed { reason } => assert_eq!(reason, "data"),
            Error::XmlParse(_) => {}
            other => panic!("unexpected error: {other:?}"),
        }
    }

    /// Key rotation: the first key in the slice doesn't match, the second
    /// does. Decrypt must succeed by trying both in order.
    #[test]
    fn rotation_first_key_fails_second_succeeds() {
        let assertion = sample_assertion();
        let encrypted = encrypt_assertion(
            &assertion,
            &rsa_cert(),
            DataEncryptionAlgorithm::Aes256Gcm,
            KeyTransportAlgorithm::RsaOaep,
        )
        .expect("encrypt");

        // First key: P-256 (will fail at the RSA-OAEP unwrap because it's not
        // an RSA key โ€” KeyPair::decrypt_rsa_oaep returns DecryptFailed). The
        // second is the real RSA decryption key. Both must be tried.
        use crate::crypto::cert::test_vectors::EC_P256_KEY_PKCS8_PEM;
        let wrong = KeyPair::from_pkcs8_pem(EC_P256_KEY_PKCS8_PEM).unwrap();
        let right = rsa_keypair();
        let decrypted = decrypt_encrypted_assertion(
            &encrypted,
            &[&wrong, &right],
            &[DataEncryptionAlgorithm::Aes256Gcm],
            &[KeyTransportAlgorithm::RsaOaep],
        )
        .expect("rotation must find the matching key");
        assert_eq!(decrypted.qname().local(), "Assertion");
    }

    #[test]
    fn missing_encrypted_data_rejected() {
        // Build a wrapper that has *no* EncryptedData child.
        let wrapper = Element::build(QName::new(Some(SAML_NS.to_owned()), "EncryptedAssertion"))
            .with_namespace(Some("saml".to_owned()), SAML_NS)
            .finish();
        let kp = rsa_keypair();
        let err = decrypt_encrypted_assertion(
            &wrapper,
            &[&kp],
            &[DataEncryptionAlgorithm::Aes256Gcm],
            &[KeyTransportAlgorithm::RsaOaep],
        )
        .expect_err("no EncryptedData");
        match err {
            Error::DecryptFailed { reason } => assert_eq!(reason, "missing EncryptedData"),
            other => panic!("expected DecryptFailed, got {other:?}"),
        }
    }

    /// Confirm we don't accidentally surface per-key reasons during rotation:
    /// when *every* key in the slice fails, the error must be the generic
    /// `key transport` variant.
    #[test]
    fn all_keys_fail_collapses_to_generic_error() {
        let assertion = sample_assertion();
        let encrypted = encrypt_assertion(
            &assertion,
            &rsa_cert(),
            DataEncryptionAlgorithm::Aes256Gcm,
            KeyTransportAlgorithm::RsaOaep,
        )
        .expect("encrypt");

        // Both candidates are wrong (EC key + a freshly-generated *different*
        // RSA key). The first fails fast at the key-family check; the second
        // fails at OAEP unwrap.
        use crate::crypto::cert::test_vectors::EC_P256_KEY_PKCS8_PEM;
        let wrong_ec = KeyPair::from_pkcs8_pem(EC_P256_KEY_PKCS8_PEM).unwrap();
        // Use the same EC key twice โ€” both attempts must collapse into the
        // single generic "key transport" error.
        let wrong_again = KeyPair::from_pkcs8_pem(EC_P256_KEY_PKCS8_PEM).unwrap();
        let err = decrypt_encrypted_assertion(
            &encrypted,
            &[&wrong_ec, &wrong_again],
            &[DataEncryptionAlgorithm::Aes256Gcm],
            &[KeyTransportAlgorithm::RsaOaep],
        )
        .expect_err("no key works");
        match err {
            Error::DecryptFailed { reason } => assert_eq!(reason, "key transport"),
            other => panic!("expected DecryptFailed, got {other:?}"),
        }
    }

    /// Re-emit + re-parse round-trips the encrypted assertion shape โ€” proves
    /// the `Element` returned by `encrypt_assertion` is serializable XML.
    #[test]
    fn emit_then_parse_then_decrypt_round_trip() {
        let assertion = sample_assertion();
        let encrypted = encrypt_assertion(
            &assertion,
            &rsa_cert(),
            DataEncryptionAlgorithm::Aes256Gcm,
            KeyTransportAlgorithm::RsaOaep,
        )
        .expect("encrypt");
        // Serialize and re-parse via Document::parse to get an Element with
        // its namespace context as a top-level document.
        let xml = emit_element(&encrypted).expect("emit");
        let doc = Document::parse(xml.as_bytes()).expect("re-parse");
        let kp = rsa_keypair();
        let decrypted = decrypt_encrypted_assertion(
            doc.root(),
            &[&kp],
            &[DataEncryptionAlgorithm::Aes256Gcm],
            &[KeyTransportAlgorithm::RsaOaep],
        )
        .expect("decrypt");
        assert_eq!(decrypted.qname().local(), "Assertion");
    }

    // ---------------------------------------------------------------------
    // Tree-mutation helpers used by the tamper tests. Tests for
    // tree-internal mutation aren't part of the production API; they live
    // here because `Element` fields are crate-private.
    // ---------------------------------------------------------------------

    /// Set the `Algorithm` attribute of the inner `<EncryptedData>`'s
    /// `<EncryptionMethod>` to a new value.
    fn mutate_data_em_algorithm(encrypted_assertion: &mut Element, new_uri: String) {
        for child in &mut encrypted_assertion.children {
            if let Node::Element(enc_data) = child
                && enc_data.qname.local == "EncryptedData"
            {
                for grandchild in &mut enc_data.children {
                    if let Node::Element(em) = grandchild
                        && em.qname.local == "EncryptionMethod"
                    {
                        for attr in &mut em.attributes {
                            if attr.qname.local == "Algorithm" {
                                attr.value = new_uri.clone();
                                return;
                            }
                        }
                    }
                }
            }
        }
        panic!("EncryptedData/EncryptionMethod/@Algorithm not found");
    }

    /// Flip the last byte of the *payload* `<xenc:CipherValue>` (i.e. the
    /// data ciphertext, not the wrapped key). Used to simulate auth-tag /
    /// CBC-block tampering.
    fn flip_last_byte_in_data_cipher_value(encrypted_assertion: &mut Element) {
        for child in &mut encrypted_assertion.children {
            if let Node::Element(enc_data) = child
                && enc_data.qname.local == "EncryptedData"
            {
                // Find <CipherData> at the EncryptedData level (skipping
                // EncryptionMethod and KeyInfo).
                for grandchild in &mut enc_data.children {
                    if let Node::Element(cipher_data) = grandchild
                        && cipher_data.qname.local == "CipherData"
                    {
                        for ggc in &mut cipher_data.children {
                            if let Node::Element(cipher_value) = ggc
                                && cipher_value.qname.local == "CipherValue"
                            {
                                // Decode, flip, re-encode in-place.
                                let mut bytes =
                                    decode_base64_ws_tolerant(&cipher_value.text_content())
                                        .expect("base64");
                                let last = bytes
                                    .len()
                                    .checked_sub(1)
                                    .expect("CipherValue must be non-empty");
                                bytes[last] ^= 0x01;
                                let re_encoded = BASE64_STANDARD.encode(&bytes);
                                cipher_value.children.clear();
                                cipher_value.children.push(Node::Text(re_encoded));
                                return;
                            }
                        }
                    }
                }
            }
        }
        panic!("EncryptedData/CipherData/CipherValue not found");
    }
}