asx-rs 0.14.0

AS2 and AS4 B2B messaging library for Rust — signing, encryption, MDN, and ebMS3/AS4 profile support
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
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
// WS-Security module — thin re-export hub.
//
// Implementation is split across focused sub-modules:
//   canonicalize  — Exclusive XML Canonicalization (Exc-C14N) + DOM serializer
//   sign          — XMLDSig signature generation
//   verify        — Signature + reference verification
//   x509          — X.509 certificate validation + PKIX chain
//   ocsp          — OCSP / CRL revocation
//   xmlenc        — XML Encryption (AES-128/256-GCM + RSA-OAEP)

// These sub-modules depend on roxmltree / quick-xml which are as4-only deps.
#[cfg(feature = "as4")]
pub(crate) mod canonicalize;
#[cfg(feature = "as4")]
pub(crate) use canonicalize::swa_attachment_digest_input;
pub(crate) mod ocsp;
#[cfg(feature = "as4")]
pub(crate) mod sign;
#[cfg(feature = "as4")]
pub(crate) mod verify;
pub(crate) mod x509;

#[cfg(feature = "as4")]
pub mod xmlenc;

// ---------------------------------------------------------------------------
// Namespace URI constants (used across all sub-modules)
// ---------------------------------------------------------------------------

#[cfg(feature = "as4")]
pub(crate) const DS_NS: &str = "http://www.w3.org/2000/09/xmldsig#";
#[cfg(feature = "as4")]
pub(crate) const XML_NS: &str = "http://www.w3.org/XML/1998/namespace";
pub(crate) const XML_EXC_C14N_URI: &str = "http://www.w3.org/2001/10/xml-exc-c14n#";
/// W3C Canonical XML 1.0 (Inclusive C14N) transform algorithm URI.
/// Used by legacy AS4 gateways (IBM DataPower default, older SAP PI/PO,
/// some eDelivery v1.x stacks) that do not support Exclusive C14N.
pub(crate) const XML_INC_C14N_URI: &str = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";
pub(crate) const SHA256_URI: &str = "http://www.w3.org/2001/04/xmlenc#sha256";
pub(crate) const SHA384_URI: &str = "http://www.w3.org/2001/04/xmldsig-more#sha384";
pub(crate) const SHA512_URI: &str = "http://www.w3.org/2001/04/xmlenc#sha512";
pub(crate) const RSA_SHA256_URI: &str = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
pub(crate) const RSA_SHA384_URI: &str = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha384";
pub(crate) const RSA_SHA512_URI: &str = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512";
pub(crate) const ECDSA_SHA256_URI: &str = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256";
pub(crate) const ECDSA_SHA384_URI: &str = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384";
pub(crate) const ECDSA_SHA512_URI: &str = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512";
/// WSS SOAP-with-Attachments profile 1.1: digest covers the attachment
/// **content octets** only. Mandated by the AS4 profile for `cid:` payload
/// references; emitted by asx on sign and accepted on verify.
#[cfg(feature = "as4")]
pub(crate) const SWA_ATTACHMENT_CONTENT_TRANSFORM_URI: &str = "http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Content-Signature-Transform";

// ---------------------------------------------------------------------------
// Public types
// ---------------------------------------------------------------------------

use crate::core::{OcspFailureMode, OcspMode};
use serde::{Deserialize, Serialize};

#[derive(Clone, Default)]
pub struct RevocationPolicy<'a> {
    pub trust_anchor_pems: &'a [String],
    pub revocation_crl_pems: &'a [String],
    pub ocsp_mode: OcspMode,
    pub ocsp_failure_mode: OcspFailureMode,
    pub stapled_ocsp_responses_der: &'a [Vec<u8>],
    pub responder_ocsp_responses_der: &'a [Vec<u8>],
    /// Namespace used to scope OCSP responder cache entries (e.g. tenant,
    /// partner, or session domain) to reduce cross-tenant cache coupling.
    pub ocsp_cache_namespace: &'a str,
    /// When `true`, PKIX chain validation is always performed and fails if
    /// `trust_anchor_pems` is empty (fail-closed).  When `false`, chain
    /// validation is skipped entirely and should only be used in controlled
    /// test harnesses.
    pub require_chain_validation: bool,
    /// Pre-parsed trust-anchor X.509 certificates.  When `Some`, these are
    /// used directly instead of re-parsing `trust_anchor_pems` on every
    /// verification call.  Obtain via `CertHandle::trust_anchors_x509`,
    /// which caches the result via an internal `OnceLock`.
    pub pre_parsed_trust_anchors: Option<Vec<openssl::x509::X509>>,
    /// Pre-built `X509Store` derived from `trust_anchor_pems`.  When `Some`,
    /// the verification pipeline uses this directly instead of constructing a
    /// new store on every call.  Obtain via `CertHandle::trust_anchor_x509_store`,
    /// which caches the result across all clones of the same `CertHandle`.
    pub pre_built_x509_store: Option<std::sync::Arc<openssl::x509::store::X509Store>>,
}

impl std::fmt::Debug for RevocationPolicy<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RevocationPolicy")
            .field("require_chain_validation", &self.require_chain_validation)
            .field("ocsp_mode", &self.ocsp_mode)
            .field("ocsp_failure_mode", &self.ocsp_failure_mode)
            .field(
                "pre_parsed_trust_anchors",
                &self.pre_parsed_trust_anchors.as_ref().map(|v| v.len()),
            )
            .field("pre_built_x509_store", &self.pre_built_x509_store.is_some())
            .finish_non_exhaustive()
    }
}

/// Owned counterpart to [`RevocationPolicy`] for configurations that must
/// outlive a single call scope or be stored in a `struct` without lifetime
/// annotation friction.
///
/// Convert to [`RevocationPolicy`] via the `From<&'_ OwnedRevocationPolicy>`
/// implementation, which borrows all fields from `self`.
///
/// # Example
/// ```rust
/// # use asx_rs::crypto::wssec::{OwnedRevocationPolicy, RevocationPolicy};
/// # use asx_rs::core::{OcspMode, OcspFailureMode};
/// let owned = OwnedRevocationPolicy {
///     trust_anchor_pems: vec![],
///     revocation_crl_pems: vec![],
///     ocsp_mode: OcspMode::Disabled,
///     ocsp_failure_mode: OcspFailureMode::SoftFail,
///     stapled_ocsp_responses_der: vec![],
///     responder_ocsp_responses_der: vec![],
///     ocsp_cache_namespace: "my-tenant".to_string(),
///     require_chain_validation: false,
/// };
/// let policy: RevocationPolicy<'_> = RevocationPolicy::from(&owned);
/// let _ = policy;
/// ```
///
/// # ⚠ Security
/// Setting `require_chain_validation: false` disables PKIX chain building.
/// Any signer certificate will be accepted regardless of its trust chain.
/// This setting is intended **only** for local integration tests with
/// synthetic certificates.  Production deployments **must** supply at least
/// one trust-anchor PEM and set `require_chain_validation: true`.
#[derive(Debug, Clone)]
pub struct OwnedRevocationPolicy {
    pub trust_anchor_pems: Vec<String>,
    pub revocation_crl_pems: Vec<String>,
    pub ocsp_mode: OcspMode,
    pub ocsp_failure_mode: OcspFailureMode,
    pub stapled_ocsp_responses_der: Vec<Vec<u8>>,
    pub responder_ocsp_responses_der: Vec<Vec<u8>>,
    pub ocsp_cache_namespace: String,
    pub require_chain_validation: bool,
}

impl OwnedRevocationPolicy {
    /// Create a production-safe revocation policy with the supplied trust
    /// anchors, OCSP enabled in responder-only mode, and PKIX chain validation
    /// **required** (`require_chain_validation = true`).
    ///
    /// Use this constructor in all production deployments.  Adjust individual
    /// fields via struct-update syntax if needed:
    ///
    /// ```rust,ignore
    /// let policy = OwnedRevocationPolicy::production(vec![ca_pem])
    ///     .with_ocsp_mode(OcspMode::Required);
    /// ```
    pub fn production(trust_anchor_pems: Vec<String>) -> Self {
        Self {
            trust_anchor_pems,
            revocation_crl_pems: Vec::new(),
            ocsp_mode: OcspMode::ResponderOnly,
            ocsp_failure_mode: OcspFailureMode::SoftFail,
            stapled_ocsp_responses_der: Vec::new(),
            responder_ocsp_responses_der: Vec::new(),
            ocsp_cache_namespace: String::new(),
            require_chain_validation: true,
        }
    }

    /// Create a revocation policy with **PKIX chain validation disabled**.
    ///
    /// # ⚠ Security: Testing and local integration only
    ///
    /// With this policy **any** signer certificate is accepted regardless of
    /// its trust chain.  This is intentionally named to be obviously unsafe so
    /// it stands out during code review.
    ///
    /// **Never use this in production binaries.**  Supply at least one trust
    /// anchor PEM and use [`production`](Self::production) instead.
    pub fn test_unsafe_no_chain_validation() -> Self {
        Self {
            trust_anchor_pems: Vec::new(),
            revocation_crl_pems: Vec::new(),
            ocsp_mode: OcspMode::Disabled,
            ocsp_failure_mode: OcspFailureMode::SoftFail,
            stapled_ocsp_responses_der: Vec::new(),
            responder_ocsp_responses_der: Vec::new(),
            ocsp_cache_namespace: String::new(),
            require_chain_validation: false,
        }
    }

    /// Override the OCSP mode, returning `self` for chaining.
    pub fn with_ocsp_mode(mut self, mode: OcspMode) -> Self {
        self.ocsp_mode = mode;
        self
    }

    /// Override the cache namespace (e.g. tenant or partner identifier),
    /// returning `self` for chaining.
    pub fn with_cache_namespace(mut self, namespace: impl Into<String>) -> Self {
        self.ocsp_cache_namespace = namespace.into();
        self
    }
}

impl<'a> From<&'a OwnedRevocationPolicy> for RevocationPolicy<'a> {
    fn from(owned: &'a OwnedRevocationPolicy) -> Self {
        Self {
            trust_anchor_pems: &owned.trust_anchor_pems,
            revocation_crl_pems: &owned.revocation_crl_pems,
            ocsp_mode: owned.ocsp_mode,
            ocsp_failure_mode: owned.ocsp_failure_mode,
            stapled_ocsp_responses_der: &owned.stapled_ocsp_responses_der,
            responder_ocsp_responses_der: &owned.responder_ocsp_responses_der,
            ocsp_cache_namespace: &owned.ocsp_cache_namespace,
            require_chain_validation: owned.require_chain_validation,
            pre_parsed_trust_anchors: None,
            pre_built_x509_store: None,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[non_exhaustive]
pub enum WsSecOutboundKeyInfoProfile {
    /// WS-Security X.509 v3 token (`wsse:BinarySecurityToken` with
    /// `ValueType="...#X509v3"`), referenced from `ds:KeyInfo` via
    /// `wsse:SecurityTokenReference`. **The default**, and the shape WSS 1.1.1
    /// §7.7 requires — `ds:KeyInfo` in a WS-Security header MUST contain a
    /// `SecurityTokenReference`. WSS4J-based receivers (Holodeck B2B, phase4,
    /// Domibus) reject a bare `ds:X509Data` KeyInfo with
    /// `UNSUPPORTED_SECURITY_TOKEN`.
    #[default]
    BinarySecurityTokenX509v3,
    /// Bare `ds:X509Data` + `ds:RSAKeyValue` KeyInfo. Not WSS-conformant —
    /// use only for consumers that verify with plain XMLDSig tooling.
    X509DataAndRsaKeyValue,
    /// Bare `ds:X509Data` KeyInfo. Not WSS-conformant — see
    /// [`Self::X509DataAndRsaKeyValue`].
    X509DataOnly,
    /// WS-Security X.509 PKI path token (`wsse:BinarySecurityToken` with
    /// `ValueType="...#X509PKIPathv1"`).  The `ds:KeyInfo` inside the signature
    /// element contains a `<wsse:SecurityTokenReference>` pointing to the BST
    /// by `wsu:Id` instead of an inline `ds:X509Certificate`.
    ///
    /// Required by BDEW AS4-Profil §2.2.6.2.1 and some German energy market
    /// profiles.  When this profile is selected, the caller must also use
    /// [`WsSecurityHeaderBuilder::with_signing_cert_pkipath_der`](crate::crypto::soap_builder::WsSecurityHeaderBuilder::with_signing_cert_pkipath_der) so that the
    /// BST element and `ds:KeyInfo` reference are consistent.
    X509PKIPathv1,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[non_exhaustive]
pub enum WsSecCanonicalizationKind {
    /// W3C Exclusive XML Canonicalization (Exc-C14N, RFC 3741).
    /// Only visibly-utilized namespace declarations are rendered.
    /// Required by WS-Security 1.0 and all modern AS4 profiles.
    #[default]
    Exclusive,
    /// W3C Canonical XML 1.0 (Inclusive C14N).
    /// ALL in-scope namespace declarations are rendered, regardless of
    /// whether they are visibly utilized at the element.  Used by some
    /// legacy AS4 gateways (IBM DataPower ≤ v7.5, SAP PI/PO ≤ 7.31).
    Inclusive,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WsSecCanonicalizationProfile {
    pub kind: WsSecCanonicalizationKind,
    pub include_comments: bool,
    /// Prefixes from `exc-c14n:InclusiveNamespaces/@PrefixList`.
    ///
    /// Per W3C Exc-C14N §2.1: when a namespace prefix appears in this list and
    /// the binding is in-scope at the element being serialized, the namespace
    /// declaration MUST be rendered even if the prefix is not "visibly utilized"
    /// by the element or its attributes.  This is required for interoperability
    /// with signers that declare visually-unused prefixes in the SignedInfo scope.
    pub inclusive_ns_prefixes: Vec<String>,
}

impl Default for WsSecCanonicalizationProfile {
    fn default() -> Self {
        Self {
            kind: WsSecCanonicalizationKind::Exclusive,
            include_comments: false,
            inclusive_ns_prefixes: Vec::new(),
        }
    }
}

impl WsSecCanonicalizationProfile {
    /// Returns the W3C transform algorithm URI for this profile's C14N kind.
    pub fn algorithm_uri(&self) -> &'static str {
        match self.kind {
            WsSecCanonicalizationKind::Exclusive => XML_EXC_C14N_URI,
            WsSecCanonicalizationKind::Inclusive => XML_INC_C14N_URI,
        }
    }

    /// Construct a profile for Inclusive C14N.
    pub fn inclusive() -> Self {
        Self {
            kind: WsSecCanonicalizationKind::Inclusive,
            include_comments: false,
            inclusive_ns_prefixes: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum WsSecDigestMethod {
    Sha256,
    /// SHA-384 reference digest — rare but accepted by some regulated-sector
    /// gateways (e.g. BDEW, financial-sector AS4 variants).  Not required by
    /// PEPPOL or CEF eDelivery; supported for broad inbound interoperability.
    Sha384,
    /// SHA-512 reference digest — uncommon but present in some IBM DataPower
    /// and Axway configurations.  Supported for inbound decryption/verification.
    Sha512,
}

impl WsSecDigestMethod {
    pub fn from_algorithm_uri(uri: &str) -> crate::core::Result<Self> {
        match uri {
            SHA256_URI => Ok(Self::Sha256),
            SHA384_URI => Ok(Self::Sha384),
            SHA512_URI => Ok(Self::Sha512),
            _ => Err(crate::core::AsxError::new(
                crate::core::ErrorCode::InteropViolation,
                format!(
                    "unsupported digest algorithm URI: {uri} (supported: sha256, sha384, sha512)"
                ),
                crate::core::ErrorContext::new("wssec_digest_method"),
            )),
        }
    }

    /// Returns the canonical algorithm URI for this digest method.
    pub fn algorithm_uri(self) -> &'static str {
        match self {
            Self::Sha256 => SHA256_URI,
            Self::Sha384 => SHA384_URI,
            Self::Sha512 => SHA512_URI,
        }
    }

    /// Output byte length for this digest method.
    #[cfg(feature = "as4")]
    pub(crate) fn output_len(self) -> usize {
        match self {
            Self::Sha256 => 32,
            Self::Sha384 => 48,
            Self::Sha512 => 64,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WsSecSignatureReference {
    pub uri: String,
    pub digest_method: WsSecDigestMethod,
    pub digest_value_base64: String,
    /// C14N algorithm used for this reference's `<ds:Transform>`.
    /// Defaults to `Exclusive`; set to `Inclusive` when the transform URI is
    /// `http://www.w3.org/TR/2001/REC-xml-c14n-20010315`.
    pub c14n_kind: WsSecCanonicalizationKind,
    /// Inclusive namespace prefixes parsed from `exc-c14n:InclusiveNamespaces/@PrefixList`
    /// inside the `<ds:Transforms>` element for this reference.
    /// Only meaningful when `c14n_kind == Exclusive`.
    pub inclusive_ns_prefixes: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WsSecCanonicalizedReference {
    pub uri: String,
    pub canonical_bytes: Vec<u8>,
    pub digest_value_base64: String,
}

/// Internal-only material extracted from a `<ds:Signature>` element.
///
/// Gated to match its only consumer, the `as4` test module below — a `test`
/// build without `as4` would otherwise define it and never construct it.
#[cfg(all(test, feature = "as4"))]
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct WsSecSignatureMaterial {
    pub(crate) signed_info_c14n: Vec<u8>,
    pub(crate) signature_value: Vec<u8>,
    pub(crate) signature_method_algorithm: String,
    pub(crate) rsa_modulus: Option<Vec<u8>>,
    pub(crate) rsa_exponent: Option<Vec<u8>>,
    pub(crate) x509_certificates_der: Vec<Vec<u8>>,
}

// ---------------------------------------------------------------------------
// Public API re-exports
// ---------------------------------------------------------------------------

#[cfg(feature = "as4")]
pub use xmlenc::{
    XmlEncPayloadAlgorithm, decrypt_payload_xmlenc, encrypt_payload_xmlenc,
    encrypt_payload_xmlenc_preparsed, encrypt_soap_header_xmlenc_preparsed,
};

#[cfg(feature = "as4")]
pub use canonicalize::{
    SameDocumentReferenceIndex, canonical_vector_diff, canonicalize_enveloped_document,
    canonicalize_reference, canonicalize_reference_digest_from_doc_with_inclusive_ns_and_index,
    canonicalize_reference_from_doc, canonicalize_reference_from_doc_with_inclusive_ns,
};
pub use ocsp::CertOcspOutcome;
#[cfg(feature = "as4")]
pub use sign::{
    generate_xmlsig_signature, generate_xmlsig_signature_with_external_references,
    generate_xmlsig_signature_with_external_references_preparsed,
};
#[cfg(feature = "as4")]
pub use verify::{
    ENVELOPED_SIGNATURE_URI, VerifiedEnvelopedSignature, WsSecVerifyOptions,
    parse_signature_references, verify_enveloped_document_signature, verify_enveloped_signature,
    verify_signature_references_strict,
};
pub use x509::validate_certificate_chain as validate_certificate_chain_with_revocation_vectors;

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(all(test, feature = "as4"))]
mod tests {
    use super::*;
    use base64::Engine;
    use base64::engine::general_purpose::STANDARD as BASE64_STANDARD;
    use openssl::asn1::Asn1Time;
    use openssl::hash::MessageDigest;
    use openssl::pkey::PKey;
    use openssl::sign::Signer;
    use openssl::x509::X509;
    use verify::parse_signature_material;
    use x509::validate_x509_certificate;

    // Valid DER-encoded self-signed RSA CA certificate generated for tests.
    const TEST_CA_CERT_B64: &str = concat!(
        "MIIDBzCCAe+gAwIBAgIUK+LZMsfX026W1bjcNh7Itso/uIowDQYJKoZIhvcNAQELBQAwEzERMA8GA1UEAwwIYXN4LXRlc3QwHhcNMjYwNTE3MTA0ND",
        "U3WhcNMjcwNTE3MTA0NDU3WjATMREwDwYDVQQDDAhhc3gtdGVzdDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAJ5HIVNm97sqbUIurm2p",
        "fhcvhXyKxRY/eGr8Ohs4h5UvpOtFjlMDoQZEqihyeq8dzFU51FpTuwU+xprCLNwYkBTT7M9J2t6VQZdK2+CobUzk56rRAH1J3io+v3abpYro3bYexU",
        "Zh4aow7Oy5T7rouEdAqes6ozt9v6WouyHcY0LxSIR2WYjaGDZRbJCdySdGWgsznjNOkYjKaRUySvtSHAHXFM544ZR0xIJf94OqnFYjWPx3RYM0ttIi",
        "lcZgem9T+K8MMb6BNWBWM5n+KXSjph+6PlO0txjLMW2GO8xcjeHplM0j/0B7NbtF1NGJpNTXS8XY8OjNpVy6QQj5DAVG1HUCAwEAAaNTMFEwHQYDVR",
        "0OBBYEFAsog+EedA+IQsJhrXUwEP2ltMJHMB8GA1UdIwQYMBaAFAsog+EedA+IQsJhrXUwEP2ltMJHMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcN",
        "AQELBQADggEBACm6hPG6kdwcNEHBMccjW0elgdjhBcygn4FTnMTR3Vfxyr69grzhtiyo7IoSm6KPpx88D33PH3s8w2ZCRg8js7wRRZkugHZUNl1lcI",
        "pjJcelhZim9oKnklpnjgH4YE14mIFlEN5OhOZMuLSjA//iw+fQ3U+Xqnv+TnaSPbop0JqPZGQW4a8tGOfK55wPU9JSRQ5OrBgP+tMM8TYSNDler4Xs",
        "Dk4+exqNprjVO1457CfiDPAYWnkfByAoTgw9ffdSxdiZRKBgJcWrJyp/AWxeqO6rP8x9xo3WRwe0X+GynUet3hSskSfyQX45vXqoGL+uv+9m9pfWAe",
        "Rmb40yqB4UT/g="
    );

    /// Generate a 2048-bit RSA key pair (openssl) and return the PKey,
    /// base64-encoded modulus, and base64-encoded public exponent.
    fn make_test_rsa_key() -> (openssl::pkey::PKey<openssl::pkey::Private>, String, String) {
        let rsa = openssl::rsa::Rsa::generate(2048).expect("rsa key generation");
        let modulus_b64 = BASE64_STANDARD.encode(rsa.n().to_vec());
        let exponent_b64 = BASE64_STANDARD.encode(rsa.e().to_vec());
        let pkey = openssl::pkey::PKey::from_rsa(rsa).expect("pkey from rsa");
        (pkey, modulus_b64, exponent_b64)
    }

    /// An RSA key plus a self-signed certificate that carries it.
    ///
    /// Verification requires an X.509 signer token — a bare `ds:RSAKeyValue`
    /// authenticates nobody — so positive tests need a certificate whose public
    /// key really is the signing key.
    fn make_test_rsa_key_and_cert() -> (
        openssl::pkey::PKey<openssl::pkey::Private>,
        String,
        String,
        String,
    ) {
        let (pkey, modulus_b64, exponent_b64) = make_test_rsa_key();

        let mut name = openssl::x509::X509NameBuilder::new().expect("name builder");
        name.append_entry_by_nid(openssl::nid::Nid::COMMONNAME, "asx-wssec-test")
            .expect("cn");
        let name = name.build();

        let mut builder = openssl::x509::X509::builder().expect("x509 builder");
        builder.set_version(2).expect("version");
        let mut serial = openssl::bn::BigNum::new().expect("serial");
        serial
            .pseudo_rand(64, openssl::bn::MsbOption::MAYBE_ZERO, false)
            .expect("serial rand");
        builder
            .set_serial_number(&serial.to_asn1_integer().expect("serial asn1"))
            .expect("serial");
        builder.set_subject_name(&name).expect("subject");
        builder.set_issuer_name(&name).expect("issuer");
        builder.set_pubkey(&pkey).expect("pubkey");
        builder
            .set_not_before(&openssl::asn1::Asn1Time::days_from_now(0).expect("nb"))
            .expect("nb");
        builder
            .set_not_after(&openssl::asn1::Asn1Time::days_from_now(365).expect("na"))
            .expect("na");
        builder
            .sign(&pkey, openssl::hash::MessageDigest::sha256())
            .expect("sign cert");
        let cert_b64 = BASE64_STANDARD.encode(builder.build().to_der().expect("cert der"));

        (pkey, modulus_b64, exponent_b64, cert_b64)
    }

    /// Sign `data` with the given PKey using RSA-SHA256; return base64 signature.
    fn rsa_sha256_sign(pkey: &openssl::pkey::PKey<openssl::pkey::Private>, data: &[u8]) -> String {
        let mut signer = openssl::sign::Signer::new(openssl::hash::MessageDigest::sha256(), pkey)
            .expect("signer");
        signer.update(data).expect("signer update");
        BASE64_STANDARD.encode(signer.sign_to_vec().expect("sign"))
    }

    /// The `<ds:Transforms>` a real signer writes for this reference.
    ///
    /// A same-document reference must state the exclusive algorithm, because
    /// XMLDSig §4.3.3.2 makes *inclusive* C14N the default for one that states
    /// nothing (D2). A `cid:` reference dereferences to an octet stream and
    /// correctly carries no C14N transform at all.
    fn reference_transforms(reference_uri: &str) -> &'static str {
        if reference_uri.starts_with("cid:") {
            ""
        } else {
            "\n                    <ds:Transforms>\
             \n                        <ds:Transform Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"/>\
             \n                    </ds:Transforms>"
        }
    }

    fn signed_xml_with_rsa_keyvalue(
        reference_uri: &str,
        payload_xml: &str,
        digest_base64: &str,
        signature_value_base64: &str,
        modulus_base64: &str,
        exponent_base64: &str,
    ) -> String {
        let transforms = reference_transforms(reference_uri);
        format!(
            r#"<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
        xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
        xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
        xmlns:eb="urn:example:eb">
    <soap:Header>
        <ds:Signature>
            <ds:SignedInfo>
                <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                <ds:SignatureMethod Algorithm="{RSA_SHA256_URI}"/>
                <ds:Reference URI="{reference_uri}">{transforms}
                    <ds:DigestMethod Algorithm="{SHA256_URI}"/>
                    <ds:DigestValue>{digest_base64}</ds:DigestValue>
                </ds:Reference>
            </ds:SignedInfo>
            <ds:SignatureValue>{signature_value_base64}</ds:SignatureValue>
            <ds:KeyInfo>
                <ds:KeyValue>
                    <ds:RSAKeyValue>
                        <ds:Modulus>{modulus_base64}</ds:Modulus>
                        <ds:Exponent>{exponent_base64}</ds:Exponent>
                    </ds:RSAKeyValue>
                </ds:KeyValue>
            </ds:KeyInfo>
        </ds:Signature>
    </soap:Header>
    <soap:Body>
{payload_xml}
    </soap:Body>
</soap:Envelope>"#
        )
    }

    fn signed_xml_with_rsa_keyvalue_and_x509(
        reference_uri: &str,
        payload_xml: &str,
        digest_base64: &str,
        signature_value_base64: &str,
        modulus_base64: &str,
        exponent_base64: &str,
        x509_certificate_base64: &str,
    ) -> String {
        let transforms = reference_transforms(reference_uri);
        format!(
            r#"<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
        xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
        xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
        xmlns:eb="urn:example:eb">
    <soap:Header>
        <ds:Signature>
            <ds:SignedInfo>
                <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                <ds:SignatureMethod Algorithm="{RSA_SHA256_URI}"/>
                <ds:Reference URI="{reference_uri}">{transforms}
                    <ds:DigestMethod Algorithm="{SHA256_URI}"/>
                    <ds:DigestValue>{digest_base64}</ds:DigestValue>
                </ds:Reference>
            </ds:SignedInfo>
            <ds:SignatureValue>{signature_value_base64}</ds:SignatureValue>
            <ds:KeyInfo>
                <ds:KeyValue>
                    <ds:RSAKeyValue>
                        <ds:Modulus>{modulus_base64}</ds:Modulus>
                        <ds:Exponent>{exponent_base64}</ds:Exponent>
                    </ds:RSAKeyValue>
                </ds:KeyValue>
                <ds:X509Data>
                    <ds:X509Certificate>{x509_certificate_base64}</ds:X509Certificate>
                </ds:X509Data>
            </ds:KeyInfo>
        </ds:Signature>
    </soap:Header>
    <soap:Body>
{payload_xml}
    </soap:Body>
</soap:Envelope>"#
        )
    }

    fn signed_xml_with_x509_only(
        reference_uri: &str,
        payload_xml: &str,
        digest_base64: &str,
        signature_value_base64: &str,
        x509_certificate_base64: &str,
    ) -> String {
        let transforms = reference_transforms(reference_uri);
        format!(
            r#"<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope"
        xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
        xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
        xmlns:eb="urn:example:eb">
    <soap:Header>
        <ds:Signature>
            <ds:SignedInfo>
                <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                <ds:SignatureMethod Algorithm="{RSA_SHA256_URI}"/>
                <ds:Reference URI="{reference_uri}">{transforms}
                    <ds:DigestMethod Algorithm="{SHA256_URI}"/>
                    <ds:DigestValue>{digest_base64}</ds:DigestValue>
                </ds:Reference>
            </ds:SignedInfo>
            <ds:SignatureValue>{signature_value_base64}</ds:SignatureValue>
            <ds:KeyInfo>
                <ds:X509Data>
                    <ds:X509Certificate>{x509_certificate_base64}</ds:X509Certificate>
                </ds:X509Data>
            </ds:KeyInfo>
        </ds:Signature>
    </soap:Header>
    <soap:Body>
{payload_xml}
    </soap:Body>
</soap:Envelope>"#
        )
    }

    /// XMLDSig §4.3.3.2: a same-document reference that declares no transform
    /// is digested over **inclusive** Canonical XML. Defaulting to exclusive
    /// rejects a conformant peer's signature as a forgery whenever an ancestor
    /// declares a namespace the signed subtree does not use — the ordinary
    /// shape of a SOAP envelope.
    #[test]
    fn transformless_same_document_reference_digests_over_inclusive_c14n() {
        let payload = "    <eb:Payload wsu:Id=\"payload-1\">ABC</eb:Payload>";
        let skeleton = signed_xml_with_x509_only("#payload-1", payload, "placeholder", "AA==", "");
        // Strip the transform the fixture writes, leaving a bare reference.
        let bare = skeleton
            .replace(
                "\n                    <ds:Transforms>\
                 \n                        <ds:Transform Algorithm=\"http://www.w3.org/2001/10/xml-exc-c14n#\"/>\
                 \n                    </ds:Transforms>",
                "",
            );
        assert!(!bare.contains("ds:Transforms"), "the fixture must be bare");

        let inclusive = canonicalize_reference(
            &bare,
            "#payload-1",
            WsSecCanonicalizationProfile {
                kind: WsSecCanonicalizationKind::Inclusive,
                include_comments: false,
                inclusive_ns_prefixes: Vec::new(),
            },
        )
        .expect("inclusive digest")
        .digest_value_base64;

        let exclusive =
            canonicalize_reference(&bare, "#payload-1", WsSecCanonicalizationProfile::default())
                .expect("exclusive digest")
                .digest_value_base64;

        assert_ne!(
            inclusive, exclusive,
            "the fixture must be one where the two algorithms disagree, or it \
             proves nothing"
        );

        // What the reference parser resolves the bare reference to is what
        // decides which of the two digests the verifier will compute.
        let references = parse_signature_references(&bare).expect("references parse");
        let reference = references
            .iter()
            .find(|r| r.uri == "#payload-1")
            .expect("the reference is present");
        assert_eq!(
            reference.c14n_kind,
            WsSecCanonicalizationKind::Inclusive,
            "a transform-less same-document reference defaults to inclusive C14N"
        );
    }

    #[test]
    fn parser_rejects_missing_references() {
        let xml = "<Envelope xmlns=\"urn:example\"></Envelope>";
        let err = parse_signature_references(xml).expect_err("missing refs should fail");
        assert_eq!(err.code, crate::core::ErrorCode::ParseFailed);
    }

    #[test]
    fn parser_accepts_digest_value_with_padding_whitespace() {
        let xml = r##"
<d:Envelope xmlns:d="urn:example" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
  <ds:Signature>
    <ds:SignedInfo>
        <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
      <ds:Reference URI="#x">
        <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
        <ds:DigestValue>
          abcd==
        </ds:DigestValue>
      </ds:Reference>
    </ds:SignedInfo>
    <ds:SignatureValue>stub-signature</ds:SignatureValue>
  </ds:Signature>
</d:Envelope>
"##;

        let refs = parse_signature_references(xml).expect("reference parse should pass");
        assert_eq!(refs.len(), 1);
        assert_eq!(refs[0].digest_value_base64, "abcd==");
    }

    #[test]
    fn parser_rejects_missing_signature_value() {
        let xml = r##"
<d:Envelope xmlns:d="urn:example" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
  <ds:Signature>
    <ds:SignedInfo>
        <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
      <ds:Reference URI="#x">
        <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
        <ds:DigestValue>abcd==</ds:DigestValue>
      </ds:Reference>
    </ds:SignedInfo>
  </ds:Signature>
</d:Envelope>
"##;

        let err = parse_signature_references(xml).expect_err("missing signature value should fail");
        assert_eq!(err.code, crate::core::ErrorCode::SecurityVerificationFailed);
    }

    #[test]
    fn parser_rejects_duplicate_reference_uris() {
        let xml = r##"
<d:Envelope xmlns:d="urn:example" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
    <ds:Signature>
        <ds:SignedInfo>
            <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
            <ds:Reference URI="#x">
                <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                <ds:DigestValue>abcd==</ds:DigestValue>
            </ds:Reference>
            <ds:Reference URI="#x">
                <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                <ds:DigestValue>abcd==</ds:DigestValue>
            </ds:Reference>
        </ds:SignedInfo>
        <ds:SignatureValue>stub-signature</ds:SignatureValue>
    </ds:Signature>
</d:Envelope>
"##;

        let err = parse_signature_references(xml).expect_err("duplicate references should fail");
        assert_eq!(err.code, crate::core::ErrorCode::InteropViolation);
    }

    #[test]
    fn parser_rejects_transforms_in_reference() {
        let xml = r##"
<d:Envelope xmlns:d="urn:example" xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
    <ds:Signature>
        <ds:SignedInfo>
            <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
            <ds:Reference URI="#x">
                <ds:Transforms>
                    <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
                </ds:Transforms>
                <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                <ds:DigestValue>abcd==</ds:DigestValue>
            </ds:Reference>
        </ds:SignedInfo>
        <ds:SignatureValue>stub-signature</ds:SignatureValue>
    </ds:Signature>
</d:Envelope>
"##;

        let err = parse_signature_references(xml).expect_err("transforms should fail");
        assert_eq!(err.code, crate::core::ErrorCode::InteropViolation);
    }

    #[test]
    fn verify_enveloped_signature_strict_accepts_valid_rsa_signature_value() {
        let (test_pkey, modulus_base64, exponent_base64, cert_base64) =
            make_test_rsa_key_and_cert();

        let payload = "    <eb:Payload wsu:Id=\"payload-1\">ABC</eb:Payload>";
        let unsigned = signed_xml_with_rsa_keyvalue_and_x509(
            "#payload-1",
            payload,
            "placeholder",
            "AA==",
            &modulus_base64,
            &exponent_base64,
            &cert_base64,
        );

        let digest = canonicalize_reference(
            &unsigned,
            "#payload-1",
            WsSecCanonicalizationProfile::default(),
        )
        .expect("digest")
        .digest_value_base64;

        let material = parse_signature_material(
            &signed_xml_with_rsa_keyvalue_and_x509(
                "#payload-1",
                payload,
                &digest,
                "AA==",
                &modulus_base64,
                &exponent_base64,
                &cert_base64,
            ),
            WsSecCanonicalizationProfile::default(),
        )
        .expect("signature material");

        let mut signer = Signer::new(MessageDigest::sha256(), &test_pkey).expect("signer");
        signer
            .update(&material.signed_info_c14n)
            .expect("signer update");
        let signature_bytes = signer.sign_to_vec().expect("sign");
        let signature_base64 = BASE64_STANDARD.encode(&signature_bytes);

        let signed = signed_xml_with_rsa_keyvalue_and_x509(
            "#payload-1",
            payload,
            &digest,
            &signature_base64,
            &modulus_base64,
            &exponent_base64,
            &cert_base64,
        );

        verify_enveloped_signature(&signed, WsSecVerifyOptions::new())
            .expect("strict verification");
    }

    #[test]
    fn verify_enveloped_signature_accepts_x509data_without_rsa_keyvalue() {
        let rsa = openssl::rsa::Rsa::generate(2048).expect("rsa");
        let pkey = PKey::from_rsa(rsa).expect("pkey");

        let mut name = openssl::x509::X509NameBuilder::new().expect("name builder");
        name.append_entry_by_nid(openssl::nid::Nid::COMMONNAME, "asx-wssec-test")
            .expect("cn");
        let name = name.build();

        let mut serial = openssl::bn::BigNum::new().expect("serial");
        serial
            .pseudo_rand(64, openssl::bn::MsbOption::MAYBE_ZERO, false)
            .expect("serial rand");
        let serial = serial.to_asn1_integer().expect("serial asn1");

        let mut cert_builder = X509::builder().expect("x509 builder");
        cert_builder.set_version(2).expect("version");
        cert_builder.set_serial_number(&serial).expect("serial");
        cert_builder.set_subject_name(&name).expect("subject");
        cert_builder.set_issuer_name(&name).expect("issuer");
        cert_builder.set_pubkey(&pkey).expect("pubkey");
        let not_before = Asn1Time::days_from_now(0).expect("not_before");
        let not_after = Asn1Time::days_from_now(365).expect("not_after");
        cert_builder.set_not_before(&not_before).expect("nb");
        cert_builder.set_not_after(&not_after).expect("na");
        cert_builder
            .sign(&pkey, MessageDigest::sha256())
            .expect("cert sign");
        let cert = cert_builder.build();
        let cert_der_b64 = BASE64_STANDARD.encode(cert.to_der().expect("cert der"));

        let payload = "    <eb:Payload wsu:Id=\"payload-1\">ABC</eb:Payload>";
        let unsigned =
            signed_xml_with_x509_only("#payload-1", payload, "placeholder", "AA==", &cert_der_b64);

        let digest = canonicalize_reference(
            &unsigned,
            "#payload-1",
            WsSecCanonicalizationProfile::default(),
        )
        .expect("digest")
        .digest_value_base64;

        let material = parse_signature_material(
            &signed_xml_with_x509_only("#payload-1", payload, &digest, "AA==", &cert_der_b64),
            WsSecCanonicalizationProfile::default(),
        )
        .expect("signature material");

        let mut signer =
            openssl::sign::Signer::new(MessageDigest::sha256(), &pkey).expect("signer");
        signer
            .update(&material.signed_info_c14n)
            .expect("signer update");
        let signature = signer.sign_to_vec().expect("signature");
        let signature_base64 = BASE64_STANDARD.encode(signature);

        let signed = signed_xml_with_x509_only(
            "#payload-1",
            payload,
            &digest,
            &signature_base64,
            &cert_der_b64,
        );

        verify_enveloped_signature(
            &signed,
            WsSecVerifyOptions::new().with_expected_fingerprint(None),
        )
        .expect("verification should pass");
    }

    #[test]
    fn verify_enveloped_signature_rejects_tampered_external_reference_bytes() {
        let (test_pkey, modulus_base64, exponent_base64, cert_base64) =
            make_test_rsa_key_and_cert();

        let payload = b"payload-attachment";
        let payload_digest = openssl::hash::hash(MessageDigest::sha256(), payload).expect("digest");
        let payload_digest_b64 = BASE64_STANDARD.encode(payload_digest);

        let unsigned = signed_xml_with_rsa_keyvalue_and_x509(
            "cid:payload-1@example.com",
            "    <eb:Payload>Attachment</eb:Payload>",
            &payload_digest_b64,
            "AA==",
            &modulus_base64,
            &exponent_base64,
            &cert_base64,
        );

        let material = parse_signature_material(&unsigned, WsSecCanonicalizationProfile::default())
            .expect("signature material");

        let mut signer = Signer::new(MessageDigest::sha256(), &test_pkey).expect("signer");
        signer
            .update(&material.signed_info_c14n)
            .expect("signer update");
        let signature_base64 = BASE64_STANDARD.encode(signer.sign_to_vec().expect("sign"));

        let signed = signed_xml_with_rsa_keyvalue_and_x509(
            "cid:payload-1@example.com",
            "    <eb:Payload>Attachment</eb:Payload>",
            &payload_digest_b64,
            &signature_base64,
            &modulus_base64,
            &exponent_base64,
            &cert_base64,
        );

        let good_refs: [(&str, &[u8]); 1] = [("cid:payload-1@example.com", payload.as_slice())];
        verify_enveloped_signature(
            &signed,
            WsSecVerifyOptions::new().with_external_references(&good_refs),
        )
        .expect("valid external reference bytes should pass");

        let bad_refs: [(&str, &[u8]); 1] = [("cid:payload-1@example.com", b"payload-tampered")];
        let err = verify_enveloped_signature(
            &signed,
            WsSecVerifyOptions::new().with_external_references(&bad_refs),
        )
        .expect_err("tampered external reference bytes must fail");

        assert_eq!(err.code, crate::core::ErrorCode::SecurityVerificationFailed);
        assert!(
            err.message
                .contains("digest mismatch for reference cid:payload-1@example.com")
        );
    }

    /// A signature that verifies against a key the message itself supplied
    /// proves nothing: an attacker can generate a key pair, sign the envelope,
    /// and inline the public half. Verification must demand an X.509 signer
    /// token regardless of what the caller's policy asks for.
    #[test]
    fn bare_rsa_keyvalue_without_a_certificate_is_rejected() {
        let (test_pkey, modulus_base64, exponent_base64) = make_test_rsa_key();

        let payload = "    <eb:Payload wsu:Id=\"payload-1\">ABC</eb:Payload>";
        let unsigned = signed_xml_with_rsa_keyvalue(
            "#payload-1",
            payload,
            "placeholder",
            "AA==",
            &modulus_base64,
            &exponent_base64,
        );
        let digest = canonicalize_reference(
            &unsigned,
            "#payload-1",
            WsSecCanonicalizationProfile::default(),
        )
        .expect("digest")
        .digest_value_base64;

        let material = parse_signature_material(
            &signed_xml_with_rsa_keyvalue(
                "#payload-1",
                payload,
                &digest,
                "AA==",
                &modulus_base64,
                &exponent_base64,
            ),
            WsSecCanonicalizationProfile::default(),
        )
        .expect("signature material");
        let signature_base64 = rsa_sha256_sign(&test_pkey, &material.signed_info_c14n);

        // Cryptographically this signature is perfectly valid over SignedInfo.
        let signed = signed_xml_with_rsa_keyvalue(
            "#payload-1",
            payload,
            &digest,
            &signature_base64,
            &modulus_base64,
            &exponent_base64,
        );

        let err = verify_enveloped_signature(&signed, WsSecVerifyOptions::new())
            .expect_err("a self-asserted RSAKeyValue must never satisfy verification");
        assert_eq!(err.code, crate::core::ErrorCode::SecurityVerificationFailed);
        assert!(
            err.message.contains("no X.509 certificate"),
            "error must name the cause: {}",
            err.message
        );
    }

    #[test]
    fn xmlenc_encrypt_decrypt_roundtrip() {
        let rsa = openssl::rsa::Rsa::generate(2048).expect("rsa");
        let pkey = PKey::from_rsa(rsa).expect("pkey");

        let mut name = openssl::x509::X509NameBuilder::new().expect("name builder");
        name.append_entry_by_nid(openssl::nid::Nid::COMMONNAME, "asx-xmlenc-test")
            .expect("cn");
        let name = name.build();

        let mut cert_builder = X509::builder().expect("x509 builder");
        cert_builder.set_version(2).expect("version");
        let mut serial = openssl::bn::BigNum::new().expect("serial");
        serial
            .pseudo_rand(64, openssl::bn::MsbOption::MAYBE_ZERO, false)
            .expect("serial rand");
        let serial = serial.to_asn1_integer().expect("serial asn1");
        cert_builder.set_serial_number(&serial).expect("serial");
        cert_builder.set_subject_name(&name).expect("subject");
        cert_builder.set_issuer_name(&name).expect("issuer");
        cert_builder.set_pubkey(&pkey).expect("pubkey");
        let not_before = Asn1Time::days_from_now(0).expect("not_before");
        let not_after = Asn1Time::days_from_now(365).expect("not_after");
        cert_builder.set_not_before(&not_before).expect("nb");
        cert_builder.set_not_after(&not_after).expect("na");
        cert_builder
            .sign(&pkey, MessageDigest::sha256())
            .expect("cert sign");
        let cert_pem = cert_builder.build().to_pem().expect("cert pem");
        let key_pem = pkey.private_key_to_pem_pkcs8().expect("key pem");

        let ciphertext =
            encrypt_payload_xmlenc(b"payload", &cert_pem, XmlEncPayloadAlgorithm::Aes128Gcm)
                .expect("encrypt");
        let plaintext = decrypt_payload_xmlenc(&ciphertext, &key_pem).expect("decrypt");
        assert_eq!(plaintext, b"payload");
    }

    #[test]
    fn verify_enveloped_signature_strict_rejects_tampered_signature_value() {
        let (pkey, modulus_base64, exponent_base64) = make_test_rsa_key();

        let payload = "    <eb:Payload wsu:Id=\"payload-1\">ABC</eb:Payload>";
        let unsigned = signed_xml_with_rsa_keyvalue(
            "#payload-1",
            payload,
            "placeholder",
            "AA==",
            &modulus_base64,
            &exponent_base64,
        );

        let digest = canonicalize_reference(
            &unsigned,
            "#payload-1",
            WsSecCanonicalizationProfile::default(),
        )
        .expect("digest")
        .digest_value_base64;

        let material = parse_signature_material(
            &signed_xml_with_rsa_keyvalue(
                "#payload-1",
                payload,
                &digest,
                "AA==",
                &modulus_base64,
                &exponent_base64,
            ),
            WsSecCanonicalizationProfile::default(),
        )
        .expect("signature material");

        let mut signature = BASE64_STANDARD
            .decode(rsa_sha256_sign(&pkey, &material.signed_info_c14n))
            .expect("decode sig");
        signature[0] ^= 0x01;
        let signature_base64 = BASE64_STANDARD.encode(signature);

        let signed = signed_xml_with_rsa_keyvalue(
            "#payload-1",
            payload,
            &digest,
            &signature_base64,
            &modulus_base64,
            &exponent_base64,
        );

        let err = verify_enveloped_signature(&signed, WsSecVerifyOptions::new())
            .expect_err("tampered signature should fail");
        assert_eq!(err.code, crate::core::ErrorCode::SecurityVerificationFailed);
    }

    #[test]
    fn trust_binding_requires_x509_certificate_when_fingerprint_is_configured() {
        let (pkey, modulus_base64, exponent_base64) = make_test_rsa_key();

        let payload = "    <eb:Payload wsu:Id=\"payload-1\">ABC</eb:Payload>";
        let unsigned = signed_xml_with_rsa_keyvalue(
            "#payload-1",
            payload,
            "placeholder",
            "AA==",
            &modulus_base64,
            &exponent_base64,
        );

        let digest = canonicalize_reference(
            &unsigned,
            "#payload-1",
            WsSecCanonicalizationProfile::default(),
        )
        .expect("digest")
        .digest_value_base64;

        let material = parse_signature_material(
            &signed_xml_with_rsa_keyvalue(
                "#payload-1",
                payload,
                &digest,
                "AA==",
                &modulus_base64,
                &exponent_base64,
            ),
            WsSecCanonicalizationProfile::default(),
        )
        .expect("signature material");

        let signature_base64 = rsa_sha256_sign(&pkey, &material.signed_info_c14n);

        let signed = signed_xml_with_rsa_keyvalue(
            "#payload-1",
            payload,
            &digest,
            &signature_base64,
            &modulus_base64,
            &exponent_base64,
        );

        let err = verify_enveloped_signature(
            &signed,
            WsSecVerifyOptions::new().with_expected_fingerprint(Some("ab:cd")),
        )
        .expect_err("missing x509 certificate should fail trust binding");
        assert_eq!(err.code, crate::core::ErrorCode::SecurityVerificationFailed);
    }

    #[test]
    fn malformed_x509_certificate_is_rejected() {
        let (pkey, modulus_base64, exponent_base64) = make_test_rsa_key();

        let payload = "    <eb:Payload wsu:Id=\"payload-1\">ABC</eb:Payload>";
        let unsigned = signed_xml_with_rsa_keyvalue_and_x509(
            "#payload-1",
            payload,
            "placeholder",
            "AA==",
            &modulus_base64,
            &exponent_base64,
            "AQID",
        );

        let digest = canonicalize_reference(
            &unsigned,
            "#payload-1",
            WsSecCanonicalizationProfile::default(),
        )
        .expect("digest")
        .digest_value_base64;

        let material = parse_signature_material(
            &signed_xml_with_rsa_keyvalue_and_x509(
                "#payload-1",
                payload,
                &digest,
                "AA==",
                &modulus_base64,
                &exponent_base64,
                "AQID",
            ),
            WsSecCanonicalizationProfile::default(),
        )
        .expect("signature material");

        let signature_base64 = rsa_sha256_sign(&pkey, &material.signed_info_c14n);

        let signed = signed_xml_with_rsa_keyvalue_and_x509(
            "#payload-1",
            payload,
            &digest,
            &signature_base64,
            &modulus_base64,
            &exponent_base64,
            "AQID",
        );

        let err = verify_enveloped_signature(
            &signed,
            WsSecVerifyOptions::new().with_expected_fingerprint(None),
        )
        .expect_err("malformed x509 certificate must fail");
        assert_eq!(err.code, crate::core::ErrorCode::SecurityVerificationFailed);
    }

    #[test]
    fn mismatched_x509_and_keyvalue_are_rejected() {
        let (pkey, modulus_base64, exponent_base64) = make_test_rsa_key();

        let payload = "    <eb:Payload wsu:Id=\"payload-1\">ABC</eb:Payload>";
        let unsigned = signed_xml_with_rsa_keyvalue_and_x509(
            "#payload-1",
            payload,
            "placeholder",
            "AA==",
            &modulus_base64,
            &exponent_base64,
            TEST_CA_CERT_B64,
        );

        let digest = canonicalize_reference(
            &unsigned,
            "#payload-1",
            WsSecCanonicalizationProfile::default(),
        )
        .expect("digest")
        .digest_value_base64;

        let material = parse_signature_material(
            &signed_xml_with_rsa_keyvalue_and_x509(
                "#payload-1",
                payload,
                &digest,
                "AA==",
                &modulus_base64,
                &exponent_base64,
                TEST_CA_CERT_B64,
            ),
            WsSecCanonicalizationProfile::default(),
        )
        .expect("signature material");

        let signature_base64 = rsa_sha256_sign(&pkey, &material.signed_info_c14n);

        let signed = signed_xml_with_rsa_keyvalue_and_x509(
            "#payload-1",
            payload,
            &digest,
            &signature_base64,
            &modulus_base64,
            &exponent_base64,
            TEST_CA_CERT_B64,
        );

        let err = verify_enveloped_signature(
            &signed,
            WsSecVerifyOptions::new().with_expected_fingerprint(None),
        )
        .expect_err("key mismatch must fail");
        assert_eq!(err.code, crate::core::ErrorCode::SecurityVerificationFailed);
    }

    #[test]
    fn ca_certificate_is_rejected_for_message_signing() {
        let cert_der = BASE64_STANDARD
            .decode(TEST_CA_CERT_B64)
            .expect("decode test certificate");

        let err = validate_x509_certificate(&cert_der)
            .expect_err("CA certificate must be rejected for end-entity signing");
        assert_eq!(err.code, crate::core::ErrorCode::SecurityVerificationFailed);
    }

    #[test]
    fn signer_policy_rejects_cert_without_compatible_eku() {
        let (pkey, modulus_base64, exponent_base64) = make_test_rsa_key();

        let payload = "    <eb:Payload wsu:Id=\"payload-1\">ABC</eb:Payload>";
        let unsigned = signed_xml_with_rsa_keyvalue_and_x509(
            "#payload-1",
            payload,
            "placeholder",
            "AA==",
            &modulus_base64,
            &exponent_base64,
            TEST_CA_CERT_B64,
        );

        let digest = canonicalize_reference(
            &unsigned,
            "#payload-1",
            WsSecCanonicalizationProfile::default(),
        )
        .expect("digest")
        .digest_value_base64;

        let material = parse_signature_material(
            &signed_xml_with_rsa_keyvalue_and_x509(
                "#payload-1",
                payload,
                &digest,
                "AA==",
                &modulus_base64,
                &exponent_base64,
                TEST_CA_CERT_B64,
            ),
            WsSecCanonicalizationProfile::default(),
        )
        .expect("signature material");

        let signature_base64 = rsa_sha256_sign(&pkey, &material.signed_info_c14n);

        let signed = signed_xml_with_rsa_keyvalue_and_x509(
            "#payload-1",
            payload,
            &digest,
            &signature_base64,
            &modulus_base64,
            &exponent_base64,
            TEST_CA_CERT_B64,
        );

        let err = verify_enveloped_signature(
            &signed,
            WsSecVerifyOptions::new().with_expected_fingerprint(None),
        )
        .expect_err("certificate with incompatible EKU must fail signer policy");
        assert_eq!(err.code, crate::core::ErrorCode::SecurityVerificationFailed);
    }

    // -----------------------------------------------------------------------
    // W3C Exclusive XML Canonicalization 1.0 test vectors
    // -----------------------------------------------------------------------

    fn c14n_element(envelope: &str, id: &str) -> String {
        let result = canonicalize_reference(
            envelope,
            id,
            WsSecCanonicalizationProfile {
                kind: WsSecCanonicalizationKind::Exclusive,
                include_comments: false,
                inclusive_ns_prefixes: Vec::new(),
            },
        )
        .expect("canonicalize_reference");
        String::from_utf8(result.canonical_bytes).expect("valid UTF-8")
    }

    #[test]
    fn w3c_exc_c14n_simple_namespace_propagation() {
        let envelope = r#"<root xmlns:n1="http://www.w3.org">
  <elem wsu:Id="e1"
        xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
        xmlns:n1="http://www.w3.org"
        n1:attr="v">text</elem>
</root>"#;

        let c14n = c14n_element(envelope, "#e1");
        assert!(
            c14n.contains(r#"xmlns:n1="http://www.w3.org""#),
            "n1 ns missing: {c14n}"
        );
        assert!(c14n.contains(r#"n1:attr="v""#), "attr missing: {c14n}");
        assert!(c14n.contains("text"), "text missing: {c14n}");
    }

    #[test]
    fn w3c_exc_c14n_attribute_ordering() {
        let envelope = r#"<r xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
      xmlns:ns="urn:test">
  <e wsu:Id="e1" ns:z="last" ns:a="first" plain="plain"/>
</r>"#;

        let c14n = c14n_element(envelope, "#e1");
        let a_pos = c14n.find(r#"ns:a="first""#).expect("ns:a missing");
        let z_pos = c14n.find(r#"ns:z="last""#).expect("ns:z missing");
        assert!(
            a_pos < z_pos,
            "ns:a must precede ns:z in C14N output:\n{c14n}"
        );
    }

    #[test]
    fn w3c_c14n_text_and_attr_escaping() {
        let envelope = r#"<r xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  <e wsu:Id="e1" a="&quot;&amp;&#x9;&#xA;&#xD;">text &lt;&amp;&gt;</e>
</r>"#;

        let c14n = c14n_element(envelope, "#e1");
        assert!(
            c14n.contains(r#"&quot;&amp;&#x9;&#xA;&#xD;"#),
            "attr escaping wrong: {c14n}"
        );
        assert!(
            c14n.contains("text &lt;&amp;&gt;"),
            "text escaping wrong: {c14n}"
        );
    }

    #[test]
    fn c14n_preserves_processing_instructions() {
        let envelope = r#"<r xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  <e wsu:Id="e1"><?xml-stylesheet type="text/xsl" href="style.xsl"?>body</e>
</r>"#;

        let c14n = c14n_element(envelope, "#e1");
        assert!(
            c14n.contains(r#"<?xml-stylesheet type="text/xsl" href="style.xsl"?>"#),
            "PI missing from C14N output: {c14n}"
        );
    }

    #[test]
    fn c14n_strips_comments_by_default() {
        let envelope = r#"<r xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  <e wsu:Id="e1"><!-- secret -->visible</e>
</r>"#;

        let c14n = c14n_element(envelope, "#e1");
        assert!(!c14n.contains("secret"), "comment not stripped: {c14n}");
        assert!(c14n.contains("visible"), "text missing: {c14n}");
    }

    #[test]
    fn c14n_preserves_comments_when_requested() {
        let envelope = r#"<r xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  <e wsu:Id="e1"><!-- keep-me -->text</e>
</r>"#;

        let result = canonicalize_reference(
            envelope,
            "#e1",
            WsSecCanonicalizationProfile {
                kind: WsSecCanonicalizationKind::Exclusive,
                include_comments: true,
                inclusive_ns_prefixes: Vec::new(),
            },
        )
        .expect("canonicalize");
        let c14n = String::from_utf8(result.canonical_bytes).unwrap();
        assert!(c14n.contains("<!-- keep-me -->"), "comment missing: {c14n}");
    }

    #[test]
    fn c14n_inclusive_ns_prefixes_renders_ancestor_binding() {
        let envelope = r#"<root xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <bar wsu:Id="e1"/>
</root>"#;

        let result = canonicalize_reference(
            envelope,
            "#e1",
            WsSecCanonicalizationProfile {
                kind: WsSecCanonicalizationKind::Exclusive,
                include_comments: false,
                inclusive_ns_prefixes: vec!["xsi".to_string()],
            },
        )
        .expect("canonicalize");
        let c14n = String::from_utf8(result.canonical_bytes).unwrap();
        assert!(
            c14n.contains(r#"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance""#),
            "xsi declaration missing from inclusive-prefix output:\n{c14n}"
        );
    }

    #[test]
    fn c14n_inclusive_ns_prefix_not_in_scope_is_not_emitted() {
        let envelope = r#"<root xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
  <bar wsu:Id="e1"/>
</root>"#;

        let result = canonicalize_reference(
            envelope,
            "#e1",
            WsSecCanonicalizationProfile {
                kind: WsSecCanonicalizationKind::Exclusive,
                include_comments: false,
                inclusive_ns_prefixes: vec!["xsi".to_string()],
            },
        )
        .expect("canonicalize");
        let c14n = String::from_utf8(result.canonical_bytes).unwrap();
        assert!(
            !c14n.contains("xmlns:xsi"),
            "xsi declaration must not appear when prefix is not in scope:\n{c14n}"
        );
    }
}