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
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
use super::pmode::PayloadPackagingMode;
use crate::core::InteropMode;
use crate::core::{AsxError, ErrorCode, ErrorContext, Result};
use crate::crypto::soap_builder::WsAddressingHeaders;
use crate::crypto::wssec::{
    WsSecOutboundKeyInfoProfile, WsSecSignatureReference, XmlEncPayloadAlgorithm,
};
use crate::interop::InteropExceptionPolicy;
use crate::lifecycle::DomainReady;
use crate::reliability::{DeliveryOutcome, RetryDecision};
use crate::sbdh::SbdhHeader;
use std::sync::Arc;
use zeroize::Zeroize;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SoapEnvelope {
    pub action: String,
    pub body: Arc<[u8]>,
}

impl SoapEnvelope {
    /// Return the body as a [`bytes::Bytes`] without copying the data.
    ///
    /// Useful for passing the serialized SOAP envelope body to `reqwest`,
    /// `axum`, or any other bytes-oriented Tokio ecosystem crate.
    ///
    /// # Performance
    ///
    /// O(1) — wraps the `Arc<[u8]>` via a copy-from-slice.  Use
    /// [`into_body_bytes`](Self::into_body_bytes) when the envelope will not
    /// be reused after conversion.
    #[inline]
    pub fn body_bytes(&self) -> bytes::Bytes {
        bytes::Bytes::copy_from_slice(&self.body)
    }

    /// Consume `self` and return the body as a [`bytes::Bytes`].
    #[inline]
    pub fn into_body_bytes(self) -> bytes::Bytes {
        bytes::Bytes::from(self.body.to_vec())
    }
}

/// Controls how fragment groups are scoped to prevent cross-sender injection.
///
/// ebMS3 Part 2 security guidance requires that fragment group correlation keys
/// incorporate an **authenticated** sender identity so that a malicious actor
/// cannot forge `<eb:From>` to inject data into another sender's fragment group.
///
/// # Scope: fragmented messages only
///
/// This policy is consulted **only** for inbound messages that carry an
/// `mf:MessageFragment` element.  A non-fragmented single `eb:UserMessage` is
/// never affected by it, so
/// [`As4ReceivePushRequest::authenticated_sender_scope`] may always be `None`
/// for profiles that do not use fragmentation (BDEW MaKo, for example).
///
/// Do **not** switch to [`UseSoapSenderId`](Self::UseSoapSenderId) merely to
/// make a `None` scope safe — it already is.  Doing so only weakens the policy
/// on the day a fragment does arrive.
///
/// # ⚠ Security
///
/// The default (`RequireAuthenticatedScope`) is the safe choice for production.
/// `UseSoapSenderId` is provided only for controlled environments where all
/// senders are fully trusted and mTLS-based authentication is infeasible.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[non_exhaustive]
pub enum FragmentScopePolicy {
    /// **Secure default.** Fragment groups are scoped by the transport-layer
    /// authenticated sender identity supplied via
    /// [`As4ReceivePushRequest::authenticated_sender_scope`].
    ///
    /// When this policy is active, `ingest_fragment` returns
    /// [`ErrorCode::PolicyViolation`] if `authenticated_sender_scope` is `None`.
    /// Typical scope values: mTLS client certificate CN, peer IP, or AP identifier
    /// verified at the transport layer before the request was admitted.
    #[default]
    RequireAuthenticatedScope,
    /// **Insecure — legacy compatibility only.**
    ///
    /// Fragment groups are scoped by the `<eb:From/eb:PartyId>` value parsed
    /// from the unauthenticated SOAP envelope.  Any sender can forge this value
    /// to target another sender's fragment group.
    ///
    /// Only acceptable when:
    /// * all senders are on the same trusted internal network, **and**
    /// * upgrading to authenticated scope is not feasible in the short term.
    UseSoapSenderId,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct As4PushPolicy {
    pub interop: InteropMode,
    pub interop_exceptions: InteropExceptionPolicy,
    pub require_signed_receipt: bool,
    /// Whether inbound push messages must carry a valid WS-Security signature.
    ///
    /// Defaults to `true`.  Setting to `false` disables signature enforcement
    /// and should only be used in controlled test environments.
    pub require_signed_push: bool,
    /// When `true` (the default), protocol event emission failures fail the
    /// receive operation (fail-closed audit semantics).
    pub fail_closed_audit_events: bool,
    pub inbound_decryption_key_pem: Option<Arc<[u8]>>,
    /// When `true`, inbound push messages that are **not** XML-encrypted are
    /// rejected with [`ErrorCode::PolicyViolation`].
    ///
    /// Requires `inbound_decryption_key_pem` to be set — the builder returns an
    /// error if `require_encrypted_inbound` is `true` but no decryption key is
    /// configured.
    ///
    /// Defaults to `false` for backward compatibility; set to `true` in any
    /// deployment where encryption is mandatory (e.g. BDEW AS4-Profil §2.2.6.2.2).
    pub require_encrypted_inbound: bool,
    /// Replay-window enforcement for inbound `<eb:Timestamp>`.
    ///
    /// When `Some(window)`, inbound messages whose `<eb:Timestamp>` is more than
    /// `window` in the past (or future) are rejected with
    /// `SecurityVerificationFailed`.  This closes the replay window that exists
    /// when dedup storage alone is used as the replay defence.
    ///
    /// Per eDelivery AS4 v1.15 §5.1.3 the recommended window is **5 minutes**.
    /// Set to `None` to disable freshness enforcement (development / testing only).
    ///
    /// Defaults to `Some(Duration::from_secs(300))` (5 minutes) in production builds.
    pub timestamp_freshness_window: Option<std::time::Duration>,
    /// Policy for fragment group sender-scope determination.
    ///
    /// Controls whether fragment groups are keyed by the **authenticated**
    /// transport-layer sender identity (secure default) or the unauthenticated
    /// SOAP `<eb:From>` party ID (legacy fallback).
    ///
    /// Applies to **fragmented messages only** — non-fragmented single
    /// `eb:UserMessage` pushes are accepted with
    /// `authenticated_sender_scope: None` regardless of this setting.  See
    /// [`FragmentScopePolicy`] for the security implications of each variant.
    /// Defaults to [`FragmentScopePolicy::RequireAuthenticatedScope`].
    pub fragment_scope_policy: FragmentScopePolicy,
}

impl Default for As4PushPolicy {
    fn default() -> Self {
        Self {
            interop: InteropMode::Strict,
            interop_exceptions: InteropExceptionPolicy::default(),
            require_signed_receipt: true,
            require_signed_push: true,
            fail_closed_audit_events: true,
            inbound_decryption_key_pem: None,
            require_encrypted_inbound: false,
            timestamp_freshness_window: Some(std::time::Duration::from_secs(300)),
            fragment_scope_policy: FragmentScopePolicy::RequireAuthenticatedScope,
        }
    }
}

impl As4PushPolicy {
    /// Return the recommended production-safe policy preset.
    ///
    /// Equivalent to `Default::default()` but named explicitly so that
    /// code-review and audit tooling can easily locate all call sites that
    /// are using hardened defaults vs. those that customise a field.
    ///
    /// Use [`As4PushPolicyBuilder`] to adjust individual fields.  Any field
    /// that weakens security — particularly
    /// `allow_unsigned_push` — is
    /// documented with an explicit security warning.
    pub fn strict() -> Self {
        Self::default()
    }

    /// Return the regulated deployment preset for inbound push receive.
    ///
    /// This preset is intentionally fail-closed:
    /// - strict interop mode
    /// - signed push required
    /// - signed receipt required
    /// - fail-closed audit emission
    /// - timestamp freshness enforcement enabled (5 minutes)
    ///
    /// Inbound encryption is **not** required, because requiring it without a
    /// decryption key is an unsatisfiable configuration.  Use
    /// [`regulated_with_decryption_key`](Self::regulated_with_decryption_key)
    /// when the profile mandates encryption.
    ///
    /// `fragment_scope_policy` stays at
    /// [`FragmentScopePolicy::RequireAuthenticatedScope`]; this affects
    /// fragmented messages only, so non-fragmenting profiles need no override
    /// and may pass `authenticated_sender_scope: None`.
    pub fn regulated() -> Self {
        Self {
            interop: InteropMode::Strict,
            interop_exceptions: InteropExceptionPolicy::default(),
            require_signed_receipt: true,
            require_signed_push: true,
            fail_closed_audit_events: true,
            inbound_decryption_key_pem: None,
            require_encrypted_inbound: false,
            timestamp_freshness_window: Some(std::time::Duration::from_secs(300)),
            fragment_scope_policy: FragmentScopePolicy::RequireAuthenticatedScope,
        }
    }

    /// [`regulated`](Self::regulated) with mandatory inbound XML encryption.
    ///
    /// Sets `inbound_decryption_key_pem` and `require_encrypted_inbound = true`
    /// together, so the pair cannot be split: there is no ordering to get wrong
    /// and no way to demand encryption without a key to satisfy the demand.
    ///
    /// This is the preset for profiles that mandate payload encryption, such as
    /// BDEW AS4-Profil §2.2.6.2.2.
    ///
    /// `pem` accepts an RSA or EC private key; the EC path engages ECDH-ES +
    /// ConcatKDF + AES key wrap per BSI TR-03116-3 §9.2.  The key is validated
    /// by [`As4PushPolicyBuilder::build`], so route the result through the
    /// builder to discover a bad key at startup:
    ///
    /// ```rust,ignore
    /// let policy = As4PushPolicy::regulated_with_decryption_key(my_key_pem);
    /// ```
    pub fn regulated_with_decryption_key(pem: impl Into<Vec<u8>>) -> Self {
        Self {
            inbound_decryption_key_pem: Some(Arc::from(pem.into())),
            require_encrypted_inbound: true,
            ..Self::regulated()
        }
    }

    /// Return a relaxed push receive policy for use in integration tests.
    ///
    /// Relaxed mode; does not require signed push or signed receipt; audit
    /// events are best-effort.  Timestamp freshness enforcement is disabled.
    ///
    /// **Never use this in production code.**
    #[cfg(all(feature = "testing", feature = "interop-relaxed"))]
    pub fn test_relaxed() -> Self {
        Self {
            interop: InteropMode::Relaxed,
            require_signed_push: false,
            require_signed_receipt: false,
            fail_closed_audit_events: false,
            timestamp_freshness_window: None,
            fragment_scope_policy: FragmentScopePolicy::UseSoapSenderId,
            ..Self::default()
        }
    }
}

fn validate_strict_as4_policy_consistency(
    stage: &'static str,
    interop: InteropMode,
    interop_exceptions: &InteropExceptionPolicy,
) -> Result<()> {
    if interop == InteropMode::Strict
        && (interop_exceptions.scoped_profile_name.is_some()
            || !interop_exceptions.allowed.is_empty())
    {
        return Err(AsxError::new(
            ErrorCode::InvalidInput,
            "strict AS4 policy forbids configured interop exception overrides",
            ErrorContext::new(stage),
        ));
    }

    Ok(())
}

fn validate_strict_as4_send_policy_consistency(
    stage: &'static str,
    interop: InteropMode,
    sign: bool,
    fail_closed_audit_events: bool,
    payload_packaging_mode: PayloadPackagingMode,
) -> Result<()> {
    if interop == InteropMode::Strict {
        if !sign {
            return Err(AsxError::new(
                ErrorCode::InvalidInput,
                "strict AS4 send policy forbids sign=false",
                ErrorContext::new(stage),
            ));
        }
        if payload_packaging_mode != PayloadPackagingMode::MimeAttachment {
            return Err(AsxError::new(
                ErrorCode::InvalidInput,
                "strict AS4 send policy requires MIME attachment payload packaging",
                ErrorContext::new(stage),
            ));
        }
    }

    #[cfg(not(feature = "testing"))]
    if interop == InteropMode::Strict && !fail_closed_audit_events {
        return Err(AsxError::new(
            ErrorCode::InvalidInput,
            "strict AS4 send policy requires fail_closed_audit_events=true in non-testing builds",
            ErrorContext::new(stage),
        ));
    }
    #[cfg(feature = "testing")]
    let _ = fail_closed_audit_events;

    Ok(())
}

pub(crate) fn validate_as4_send_policy_and_credentials_consistency(
    stage: &'static str,
    policy: &As4SendPolicy,
    credentials: &As4SendCredentials,
    error_code: ErrorCode,
) -> Result<()> {
    let ctx = || ErrorContext::new(stage);

    if policy.action.trim().is_empty() {
        return Err(AsxError::new(
            error_code,
            "As4SendPolicy.action must not be empty",
            ctx(),
        ));
    }

    if policy.service.trim().is_empty() {
        return Err(AsxError::new(
            error_code,
            "As4SendPolicy.service must not be empty",
            ctx(),
        ));
    }

    if let Some(ref id) = policy.ref_to_message_id
        && id.trim().is_empty()
    {
        return Err(AsxError::new(
            error_code,
            "As4SendPolicy.ref_to_message_id must not be empty when set",
            ctx(),
        ));
    }

    if let Some(ref conversation_id) = policy.conversation_id
        && conversation_id.trim().is_empty()
    {
        return Err(AsxError::new(
            error_code,
            "As4SendPolicy.conversation_id must not be empty when set",
            ctx(),
        ));
    }

    if policy.sign {
        if credentials.signing_cert_pem.is_none() {
            return Err(AsxError::new(
                error_code,
                "sign = true requires signing_cert_pem",
                ctx(),
            ));
        }
        if credentials.signing_key_pem.is_none() {
            return Err(AsxError::new(
                error_code,
                "sign = true requires signing_key_pem",
                ctx(),
            ));
        }
    }

    if (policy.encrypt || policy.encrypt_soap_headers) && credentials.recipient_cert_pem.is_none() {
        return Err(AsxError::new(
            error_code,
            "encrypt = true or encrypt_soap_headers = true requires recipient_cert_pem",
            ctx(),
        ));
    }

    Ok(())
}

#[cfg(feature = "as4")]
#[derive(Debug, Clone)]
pub struct As4PreparedSendCredentials {
    pub signing_cert: Option<openssl::x509::X509>,
    pub signing_key: Option<openssl::pkey::PKey<openssl::pkey::Private>>,
    pub recipient_cert: Option<openssl::x509::X509>,
}

impl As4SendCredentials {
    /// Parse and validate all configured PEM material once so callers can reuse
    /// crypto-ready credentials across many sends.
    #[cfg(feature = "as4")]
    pub fn prepare_for_policy(
        &self,
        policy: &As4SendPolicy,
        stage: &'static str,
        error_code: ErrorCode,
    ) -> Result<As4PreparedSendCredentials> {
        let ctx = || ErrorContext::new(stage);

        let mut prepared = As4PreparedSendCredentials {
            signing_cert: None,
            signing_key: None,
            recipient_cert: None,
        };

        if policy.sign {
            let cert_pem = self.signing_cert_pem.as_ref().ok_or_else(|| {
                AsxError::new(error_code, "sign = true requires signing_cert_pem", ctx())
            })?;
            let key_pem = self.signing_key_pem.as_ref().ok_or_else(|| {
                AsxError::new(error_code, "sign = true requires signing_key_pem", ctx())
            })?;

            let signing_cert = openssl::x509::X509::from_pem(cert_pem).map_err(|_err| {
                AsxError::new(
                    error_code,
                    "signing_cert_pem is not a valid PEM X.509 certificate",
                    ctx(),
                )
            })?;

            let signing_key = openssl::pkey::PKey::private_key_from_pem(key_pem).map_err(|_err| {
                AsxError::new(
                    error_code,
                    "signing_key_pem is not a valid PEM private key (check PEM format and key type)",
                    ctx(),
                )
            })?;

            let signing_cert_public = signing_cert.public_key().map_err(|_err| {
                AsxError::new(
                    error_code,
                    "signing_cert_pem does not contain a usable public key",
                    ctx(),
                )
            })?;

            if !signing_key.public_eq(&signing_cert_public) {
                return Err(AsxError::new(
                    error_code,
                    "signing_cert_pem does not match signing_key_pem",
                    ctx(),
                ));
            }

            prepared.signing_cert = Some(signing_cert);
            prepared.signing_key = Some(signing_key);
        }

        if policy.encrypt {
            let cert_pem = self.recipient_cert_pem.as_ref().ok_or_else(|| {
                AsxError::new(
                    error_code,
                    "encrypt = true requires recipient_cert_pem",
                    ctx(),
                )
            })?;
            let recipient_cert = openssl::x509::X509::from_pem(cert_pem).map_err(|_err| {
                AsxError::new(
                    error_code,
                    "recipient_cert_pem is not a valid PEM X.509 certificate",
                    ctx(),
                )
            })?;
            prepared.recipient_cert = Some(recipient_cert);
        } else if let Some(cert_pem) = &self.recipient_cert_pem {
            let recipient_cert = openssl::x509::X509::from_pem(cert_pem).map_err(|_err| {
                AsxError::new(
                    error_code,
                    "recipient_cert_pem is not a valid PEM X.509 certificate",
                    ctx(),
                )
            })?;
            prepared.recipient_cert = Some(recipient_cert);
        }

        Ok(prepared)
    }
}

fn validate_strict_as4_receive_policy_consistency(
    stage: &'static str,
    interop: InteropMode,
    require_signed_receipt: bool,
    fail_closed_audit_events: bool,
) -> Result<()> {
    if interop == InteropMode::Strict && !require_signed_receipt {
        return Err(AsxError::new(
            ErrorCode::InvalidInput,
            "strict AS4 receive policy requires require_signed_receipt=true",
            ErrorContext::new(stage),
        ));
    }

    #[cfg(not(feature = "testing"))]
    if interop == InteropMode::Strict && !fail_closed_audit_events {
        return Err(AsxError::new(
            ErrorCode::InvalidInput,
            "strict AS4 receive policy requires fail_closed_audit_events=true in non-testing builds",
            ErrorContext::new(stage),
        ));
    }
    #[cfg(feature = "testing")]
    let _ = fail_closed_audit_events;

    Ok(())
}

/// Fluent builder for [`As4PushPolicy`] with eager validation.
///
/// Call [`build`](Self::build) when done; it validates PEM material if provided
/// and returns an error rather than letting the failure surface deep in crypto code.
#[derive(Debug, Default)]
pub struct As4PushPolicyBuilder(As4PushPolicy);

impl As4PushPolicyBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Start from the fail-closed [`As4PushPolicy::regulated`] preset.
    ///
    /// Pair with
    /// [`with_mandatory_inbound_encryption`](Self::with_mandatory_inbound_encryption)
    /// for profiles that also mandate payload encryption.
    pub fn regulated() -> Self {
        Self(As4PushPolicy::regulated())
    }

    pub fn interop(mut self, mode: InteropMode) -> Self {
        self.0.interop = mode;
        self
    }

    pub fn interop_exceptions(mut self, exc: InteropExceptionPolicy) -> Self {
        self.0.interop_exceptions = exc;
        self
    }

    pub fn require_signed_receipt(mut self, v: bool) -> Self {
        self.0.require_signed_receipt = v;
        self
    }

    /// Override the default WS-Security signature requirement for inbound push messages.
    ///
    /// # Security
    ///
    /// **Expert use only.** Passing `false` disables WS-Security signature verification
    /// for inbound AS4 push messages, meaning unsigned payloads from any sender will be
    /// accepted without authentication.  This violates the non-repudiation requirement
    /// of ebMS3 / AS4 and **must not be used in production** unless you have an
    /// alternative authentication mechanism at the transport layer.
    ///
    /// Only use this when integrating with a specific legacy partner that is explicitly
    /// known not to sign messages and cannot be upgraded.
    #[cfg(feature = "testing")]
    pub fn allow_unsigned_push(mut self, allow: bool) -> Self {
        self.0.require_signed_push = !allow;
        self
    }

    pub fn fail_closed_audit_events(mut self, v: bool) -> Self {
        self.0.fail_closed_audit_events = v;
        self
    }

    /// Set the PEM-encoded private key used to decrypt inbound XML-Enc payloads.
    ///
    /// Accepts both RSA and EC private keys.  The EC path uses ECDH-ES + ConcatKDF
    /// + AES-128 Key Wrap as required by BSI TR-03116-3 §9.2; the RSA path uses
    ///   RSA-OAEP (SHA-256/MGF1-SHA-256) as required by PEPPOL/CEF AS4 profiles.
    ///
    /// The key is validated immediately so that callers discover misconfiguration
    /// at startup rather than on the first decryption attempt.
    pub fn inbound_decryption_key_pem(mut self, pem: Vec<u8>) -> Self {
        self.0.inbound_decryption_key_pem = Some(Arc::from(pem));
        self
    }

    /// Require that every inbound push message is XML-encrypted.
    ///
    /// When `true`, unencrypted inbound messages are rejected with
    /// [`ErrorCode::PolicyViolation`] before their payload reaches
    /// application handlers.
    ///
    /// [`build`](Self::build) returns an error if this is set to `true` but
    /// `inbound_decryption_key_pem` is not configured — an operator cannot
    /// meaningfully require encryption while providing no key to decrypt it.
    ///
    /// Prefer [`with_mandatory_inbound_encryption`](Self::with_mandatory_inbound_encryption),
    /// which sets the key and the flag together so the invariant cannot be split.
    pub fn require_encrypted_inbound(mut self, require: bool) -> Self {
        self.0.require_encrypted_inbound = require;
        self
    }

    /// Require inbound encryption **and** supply the key that makes it
    /// satisfiable, in one call.
    ///
    /// Equivalent to
    /// [`inbound_decryption_key_pem(pem)`](Self::inbound_decryption_key_pem)
    /// followed by
    /// [`require_encrypted_inbound(true)`](Self::require_encrypted_inbound),
    /// but the two settings cannot drift apart: there is no ordering to get
    /// wrong and no way to enable the requirement without a key.
    ///
    /// This is the shape mandated by profiles such as BDEW AS4-Profil
    /// §2.2.6.2.2 and PEPPOL AS4 §Encryption.
    ///
    /// ```rust,ignore
    /// let policy = As4PushPolicyBuilder::regulated()
    ///     .with_mandatory_inbound_encryption(my_decryption_key_pem)
    ///     .build()?;
    /// ```
    pub fn with_mandatory_inbound_encryption(mut self, pem: Vec<u8>) -> Self {
        self.0.inbound_decryption_key_pem = Some(Arc::from(pem));
        self.0.require_encrypted_inbound = true;
        self
    }

    /// Configure the `<eb:Timestamp>` freshness window for inbound messages.
    ///
    /// Set to `Some(window)` to reject messages whose `<eb:Timestamp>` is older
    /// than `window` (or more than `window` in the future).  Set to `None` to
    /// disable freshness enforcement — **not recommended for production** as this
    /// opens a 24-hour replay window bounded only by the dedup store TTL.
    ///
    /// The default is `Some(Duration::from_secs(300))` (5 minutes per eDelivery
    /// AS4 v1.15 §5.1.3).
    pub fn timestamp_freshness_window(mut self, window: Option<std::time::Duration>) -> Self {
        self.0.timestamp_freshness_window = window;
        self
    }

    /// Set the fragment group scope policy.
    ///
    /// Defaults to [`FragmentScopePolicy::RequireAuthenticatedScope`], which
    /// requires the caller to supply [`As4ReceivePushRequest::authenticated_sender_scope`]
    /// for every fragment message.
    ///
    /// # ⚠ Security
    ///
    /// Only set to `UseSoapSenderId` when ALL senders are on a trusted network
    /// and you cannot provide a transport-layer identity.  This setting allows
    /// cross-sender fragment injection.
    pub fn fragment_scope_policy(mut self, policy: FragmentScopePolicy) -> Self {
        self.0.fragment_scope_policy = policy;
        self
    }

    /// Validate and produce the final [`As4PushPolicy`].
    ///
    /// Fails if a decryption key is present but its PEM encoding is invalid.
    pub fn build(self) -> Result<As4PushPolicy> {
        let stage = "as4_push_policy_build";

        validate_strict_as4_policy_consistency(stage, self.0.interop, &self.0.interop_exceptions)?;

        validate_strict_as4_receive_policy_consistency(
            stage,
            self.0.interop,
            self.0.require_signed_receipt,
            self.0.fail_closed_audit_events,
        )?;

        if self.0.require_encrypted_inbound && self.0.inbound_decryption_key_pem.is_none() {
            return Err(AsxError::new(
                ErrorCode::InvalidInput,
                "require_encrypted_inbound = true requires inbound_decryption_key_pem to be set",
                ErrorContext::new(stage),
            ));
        }

        if let Some(ref pem) = self.0.inbound_decryption_key_pem {
            openssl::pkey::PKey::private_key_from_pem(pem.as_ref()).map_err(|_err| {
                AsxError::new(
                    ErrorCode::InvalidInput,
                    "inbound_decryption_key_pem is not a valid PEM private key (check PEM format and key type)",
                    ErrorContext::new(stage),
                )
            })?;
        }
        Ok(self.0)
    }
}

/// Policy for AS4 message sending (push or pull).
///
/// ## Two-Way / Push-and-Push MEP (eDelivery AS4 v1.15 §3.2.1)
///
/// To send a **response** UserMessage that correlates to a previously received push,
/// set [`ref_to_message_id`](Self::ref_to_message_id) to the `message_id` of the
/// original inbound message.  The builder emits `<eb:RefToMessageId>` in the SOAP
/// `<eb:MessageInfo>` block, which is the correlation mechanism defined by ebMS3
/// for the Two-Way/Push-and-Push MEP.
///
/// On the **receive** side, the correlation value is available via
/// [`ParsedAs4UserMessage::ref_to_message_id`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct As4SendPolicy {
    pub interop: InteropMode,
    pub outbound_key_info_profile: WsSecOutboundKeyInfoProfile,
    /// When true, protocol lifecycle event emission failures fail the send path.
    pub fail_closed_audit_events: bool,
    pub sign: bool,
    pub encrypt: bool,
    /// XML Encryption payload algorithm used when `encrypt = true`.
    ///
    /// Defaults to `Aes128Gcm` for eDelivery AS4 v1.15 Common Profile
    /// conformance. Set to `Aes256Gcm` only for partner-specific agreements.
    pub outbound_xmlenc_payload_algorithm: XmlEncPayloadAlgorithm,
    /// When true, the outbound `eb:Messaging` SOAP header is wrapped in
    /// `xenc:EncryptedHeader` using the configured recipient certificate.
    pub encrypt_soap_headers: bool,
    pub compress: bool,
    /// ebMS3 `<eb:Action>` value for this message.
    ///
    /// Per ebMS3 Core Specification §5.2.2.7, the action identifies the
    /// business process step within the service agreement.  Must be agreed
    /// with the trading partner.  Defaults to a placeholder; always override
    /// for production deployments.
    pub action: String,
    /// ebMS3 `<eb:Service>` value (URI or name).
    ///
    /// Identifies the service or business process.  Must match the trading
    /// partner P-Mode agreement.  Defaults to a placeholder.
    pub service: String,
    /// ebMS3 `<eb:Service type="…">` attribute value.
    ///
    /// Typically `"urn:oasis:names:tc:ebcore:partyid-type:unregistered"` for
    /// unregistered services or a specific scheme URI for Peppol/CEF networks.
    /// Defaults to `"example"`.
    pub service_type: String,
    /// Explicit `<eb:From>/<eb:PartyId>` value.
    ///
    /// When `None`, the session id is used — acceptable for closed loops where
    /// both ends are asx, but a real counterparty resolves its P-Mode against
    /// this value, so production sends should always set it to the party
    /// identifier from the trading-partner agreement.
    pub from_party_id: Option<String>,
    /// Explicit `<eb:To>/<eb:PartyId>` value. Defaults to the session's
    /// partner id when `None`; same caveat as [`Self::from_party_id`].
    pub to_party_id: Option<String>,
    /// `type` attribute of the From `<eb:PartyId>`. `None` omits the
    /// attribute (an *untyped* identifier). Defaults to the ebCore
    /// "unregistered" scheme. Typed and untyped identifiers with identical
    /// text do **not** match during P-Mode resolution — this must mirror the
    /// counterparty's P-Mode exactly.
    pub from_party_id_type: Option<String>,
    /// `type` attribute of the To `<eb:PartyId>`; see [`Self::from_party_id_type`].
    pub to_party_id_type: Option<String>,
    /// `<eb:From>/<eb:Role>` — REQUIRED by the ebMS3 schema. Defaults to the
    /// ebMS3 default-role URI.
    pub from_role: String,
    /// `<eb:To>/<eb:Role>` — REQUIRED by the ebMS3 schema. Defaults to the
    /// ebMS3 default-role URI.
    pub to_role: String,
    /// Optional `<eb:AgreementRef>` naming the trading-partner agreement this
    /// exchange runs under (first child of `CollaborationInfo`).
    pub agreement_ref: Option<String>,
    /// `type` attribute of `<eb:AgreementRef>`.
    pub agreement_ref_type: Option<String>,
    /// Optional `<eb:RefToMessageId>` for **Two-Way/Push-and-Push MEP**.
    ///
    /// When `Some(id)`, the outbound SOAP envelope includes
    /// `<eb:RefToMessageId>id</eb:RefToMessageId>` in `<eb:MessageInfo>`,
    /// correlating this message to the original inbound message with that ID.
    pub ref_to_message_id: Option<String>,
    /// Four Corner topology `originalSender` MessageProperty override.
    ///
    /// When `None`, outbound generation defaults to the primary `From/PartyId`.
    pub original_sender: Option<String>,
    /// Four Corner topology `finalRecipient` MessageProperty override.
    ///
    /// When `None`, outbound generation defaults to the primary `To/PartyId`.
    pub final_recipient: Option<String>,
    /// Four Corner topology `trackingIdentifier` MessageProperty override.
    ///
    /// When `None`, outbound generation defaults to the ebMS `MessageId`.
    pub tracking_identifier: Option<String>,
    /// Optional ebMS3 `<eb:ConversationId>` override.
    pub conversation_id: Option<String>,
    /// Optional WS-Addressing headers to include in outbound SOAP messages.
    ///
    /// When `Some`, the SOAP Header block will include `wsa:MessageID`,
    /// `wsa:Action`, `wsa:To`, and (optionally) `wsa:ReplyTo`.
    ///
    /// Required for CEF strict conformance testing and SOAP intermediary routing.
    /// Set `wsa:Action` to match the ebMS3 `<eb:Action>` value.
    pub ws_addressing: Option<WsAddressingHeaders>,
    /// Optional SBDH header used to wrap outbound business payloads.
    ///
    /// When set, AS4 send paths wrap the supplied business payload bytes in a
    /// `StandardBusinessDocument` envelope before compression/encryption/signing.
    pub sbdh_header: Option<SbdhHeader>,
    /// Payload packaging mode.
    ///
    /// ASX enforces MIME multipart/related payload attachments with Content-ID
    /// references for strict profile (PEPPOL/CEF) conformance.
    pub payload_packaging_mode: PayloadPackagingMode,
}

impl Default for As4SendPolicy {
    fn default() -> Self {
        Self {
            interop: InteropMode::Strict,
            outbound_key_info_profile: WsSecOutboundKeyInfoProfile::BinarySecurityTokenX509v3,
            fail_closed_audit_events: true,
            sign: true,
            encrypt: false,
            outbound_xmlenc_payload_algorithm: XmlEncPayloadAlgorithm::Aes128Gcm,
            encrypt_soap_headers: false,
            compress: false,
            action: "urn:example:action".into(),
            service: "http://example.org/example".into(),
            service_type: "example".into(),
            from_party_id: None,
            to_party_id: None,
            from_party_id_type: Some(
                crate::crypto::soap_builder::EBCORE_PARTY_ID_TYPE_UNREGISTERED.into(),
            ),
            to_party_id_type: Some(
                crate::crypto::soap_builder::EBCORE_PARTY_ID_TYPE_UNREGISTERED.into(),
            ),
            from_role: crate::crypto::soap_builder::EBMS_DEFAULT_ROLE.into(),
            to_role: crate::crypto::soap_builder::EBMS_DEFAULT_ROLE.into(),
            agreement_ref: None,
            agreement_ref_type: None,
            ref_to_message_id: None,
            original_sender: None,
            final_recipient: None,
            tracking_identifier: None,
            conversation_id: None,
            ws_addressing: None,
            sbdh_header: None,
            payload_packaging_mode: PayloadPackagingMode::default(),
        }
    }
}

impl As4SendPolicy {
    /// Return the recommended production-safe send policy preset.
    ///
    /// Signing is enabled by default.  Use [`As4SendPolicyBuilder`] to
    /// configure action/service values and attach credentials before calling
    /// [`send`](crate::as4::send_sync).
    pub fn strict() -> Self {
        Self::default()
    }

    /// Return the regulated deployment preset for AS4 send.
    ///
    /// This preset is intentionally explicit (not an alias to strict preset
    /// wiring) so production bundles can pin audited defaults in one place.
    pub fn regulated() -> Self {
        Self {
            interop: InteropMode::Strict,
            outbound_key_info_profile: WsSecOutboundKeyInfoProfile::BinarySecurityTokenX509v3,
            fail_closed_audit_events: true,
            sign: true,
            encrypt: false,
            outbound_xmlenc_payload_algorithm: XmlEncPayloadAlgorithm::Aes128Gcm,
            encrypt_soap_headers: false,
            compress: false,
            action: "urn:example:action".into(),
            service: "http://example.org/example".into(),
            service_type: "example".into(),
            from_party_id: None,
            to_party_id: None,
            from_party_id_type: Some(
                crate::crypto::soap_builder::EBCORE_PARTY_ID_TYPE_UNREGISTERED.into(),
            ),
            to_party_id_type: Some(
                crate::crypto::soap_builder::EBCORE_PARTY_ID_TYPE_UNREGISTERED.into(),
            ),
            from_role: crate::crypto::soap_builder::EBMS_DEFAULT_ROLE.into(),
            to_role: crate::crypto::soap_builder::EBMS_DEFAULT_ROLE.into(),
            agreement_ref: None,
            agreement_ref_type: None,
            ref_to_message_id: None,
            original_sender: None,
            final_recipient: None,
            tracking_identifier: None,
            conversation_id: None,
            ws_addressing: None,
            sbdh_header: None,
            payload_packaging_mode: PayloadPackagingMode::default(),
        }
    }

    /// Return a relaxed send policy for use in integration tests.
    ///
    /// This preset disables signing and strict audit enforcement so that
    /// test harnesses can exercise the send path without full PKI setup.
    ///
    /// **Never use this in production code.** It bypasses non-repudiation
    /// requirements of ebMS3 / AS4.
    #[cfg(all(feature = "testing", feature = "interop-relaxed"))]
    pub fn test_relaxed() -> Self {
        Self {
            interop: InteropMode::Relaxed,
            fail_closed_audit_events: false,
            sign: false,
            ..Self::default()
        }
    }
}

/// Fluent builder for [`As4SendPolicy`] + [`As4SendCredentials`] with combined validation.
///
/// [`build`](Self::build) enforces that credentials match the requested operations:
/// signing requires both a certificate and a private key; encryption requires a
/// recipient certificate.  Invalid PEM material is caught immediately.
#[derive(Debug, Default)]
pub struct As4SendPolicyBuilder {
    policy: As4SendPolicy,
    credentials: As4SendCredentials,
}

impl As4SendPolicyBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn interop(mut self, mode: InteropMode) -> Self {
        self.policy.interop = mode;
        self
    }

    pub fn outbound_key_info_profile(mut self, profile: WsSecOutboundKeyInfoProfile) -> Self {
        self.policy.outbound_key_info_profile = profile;
        self
    }

    pub fn fail_closed_audit_events(mut self, v: bool) -> Self {
        self.policy.fail_closed_audit_events = v;
        self
    }

    pub fn payload_packaging_mode(mut self, mode: PayloadPackagingMode) -> Self {
        self.policy.payload_packaging_mode = mode;
        self
    }

    pub fn sign(mut self, v: bool) -> Self {
        self.policy.sign = v;
        self
    }

    pub fn encrypt(mut self, v: bool) -> Self {
        self.policy.encrypt = v;
        self
    }

    pub fn outbound_xmlenc_payload_algorithm(mut self, v: XmlEncPayloadAlgorithm) -> Self {
        self.policy.outbound_xmlenc_payload_algorithm = v;
        self
    }

    /// Wrap the outbound `eb:Messaging` SOAP header in `xenc:EncryptedHeader`.
    pub fn encrypt_soap_headers(mut self, v: bool) -> Self {
        self.policy.encrypt_soap_headers = v;
        self
    }

    pub fn compress(mut self, v: bool) -> Self {
        self.policy.compress = v;
        self
    }

    /// Set the ebMS3 `<eb:Action>` value (default: `"urn:example:action"`).
    pub fn action(mut self, action: impl Into<String>) -> Self {
        self.policy.action = action.into();
        self
    }

    /// Set the ebMS3 `<eb:Service>` value and optional `type` attribute.
    ///
    /// `service_type` is the `type="…"` attribute value.  Pass an empty
    /// string to omit the attribute.
    pub fn service(mut self, service: impl Into<String>, service_type: impl Into<String>) -> Self {
        self.policy.service = service.into();
        self.policy.service_type = service_type.into();
        self
    }

    /// Set the `<eb:From>/<eb:PartyId>` value explicitly.
    ///
    /// A real counterparty resolves its P-Mode against this identifier, so
    /// production sends should always set it (the fallback — the session id —
    /// only works when both ends are asx).
    pub fn from_party(mut self, id: impl Into<String>) -> Self {
        self.policy.from_party_id = Some(id.into());
        self
    }

    /// Set the `<eb:To>/<eb:PartyId>` value explicitly.
    pub fn to_party(mut self, id: impl Into<String>) -> Self {
        self.policy.to_party_id = Some(id.into());
        self
    }

    /// Set the `type` attribute of both `<eb:PartyId>` elements.
    ///
    /// `None` omits the attribute (an *untyped* identifier, e.g. for Holodeck
    /// B2B's example P-Modes). The default is the ebCore "unregistered"
    /// scheme. Must mirror the counterparty's P-Mode exactly — typed and
    /// untyped identifiers with the same text do not match.
    pub fn party_id_types(mut self, from_type: Option<String>, to_type: Option<String>) -> Self {
        self.policy.from_party_id_type = from_type;
        self.policy.to_party_id_type = to_type;
        self
    }

    /// Set the mandatory `<eb:Role>` values (default: ebMS3 default-role URI).
    pub fn roles(mut self, from_role: impl Into<String>, to_role: impl Into<String>) -> Self {
        self.policy.from_role = from_role.into();
        self.policy.to_role = to_role.into();
        self
    }

    /// Emit `<eb:AgreementRef>` naming the trading-partner agreement.
    pub fn agreement_ref(
        mut self,
        agreement: impl Into<String>,
        agreement_type: Option<String>,
    ) -> Self {
        self.policy.agreement_ref = Some(agreement.into());
        self.policy.agreement_ref_type = agreement_type;
        self
    }

    /// Set `<eb:RefToMessageId>` for the **Two-Way/Push-and-Push MEP**.
    ///
    /// Pass the `message_id` from the inbound [`ParsedAs4UserMessage`] to
    /// correlate this response with the original request.
    pub fn ref_to_message_id(mut self, id: impl Into<String>) -> Self {
        self.policy.ref_to_message_id = Some(id.into());
        self
    }

    /// Set Four Corner topology `originalSender` MessageProperty override.
    pub fn original_sender(mut self, value: impl Into<String>) -> Self {
        self.policy.original_sender = Some(value.into());
        self
    }

    /// Set Four Corner topology `finalRecipient` MessageProperty override.
    pub fn final_recipient(mut self, value: impl Into<String>) -> Self {
        self.policy.final_recipient = Some(value.into());
        self
    }

    /// Set Four Corner topology `trackingIdentifier` MessageProperty override.
    pub fn tracking_identifier(mut self, value: impl Into<String>) -> Self {
        self.policy.tracking_identifier = Some(value.into());
        self
    }

    /// Set ebMS3 `<eb:ConversationId>` override.
    pub fn conversation_id(mut self, value: impl Into<String>) -> Self {
        self.policy.conversation_id = Some(value.into());
        self
    }

    /// Wrap outbound business payloads in an SBDH envelope.
    pub fn sbdh_header(mut self, header: SbdhHeader) -> Self {
        self.policy.sbdh_header = Some(header);
        self
    }

    /// Attach WS-Addressing 1.0 headers to outbound SOAP envelopes.
    ///
    /// When set, the SOAP Header block includes `wsa:MessageID`, `wsa:Action`,
    /// `wsa:To`, and (optionally) `wsa:ReplyTo`.
    ///
    /// Required for CEF strict conformance testing and deployments that route
    /// messages via SOAP intermediaries that dispatch on `wsa:Action`.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use asx_rs::crypto::soap_builder::WsAddressingHeaders;
    ///
    /// let wsa = WsAddressingHeaders::new(
    ///     format!("urn:uuid:{}", uuid::Uuid::new_v4()),
    ///     "http://docs.oasis-open.org/ebxml-msg/as4/200902/action",
    ///     "https://partner-ap.example.com/as4",
    /// );
    /// let builder = As4SendPolicyBuilder::new().ws_addressing(wsa);
    /// ```
    pub fn ws_addressing(mut self, headers: WsAddressingHeaders) -> Self {
        self.policy.ws_addressing = Some(headers);
        self
    }

    pub fn signing_cert_pem(mut self, pem: impl Into<Arc<[u8]>>) -> Self {
        self.credentials.signing_cert_pem = Some(pem.into());
        self
    }

    pub fn signing_key_pem(mut self, pem: Vec<u8>) -> Self {
        self.credentials.signing_key_pem = Some(pem);
        self
    }

    pub fn recipient_cert_pem(mut self, pem: impl Into<Arc<[u8]>>) -> Self {
        self.credentials.recipient_cert_pem = Some(pem.into());
        self
    }

    /// Validate the policy–credentials combination and return both structs.
    ///
    /// # Errors
    /// - `sign = true` but `signing_cert_pem` or `signing_key_pem` is absent.
    /// - `encrypt = true` but `recipient_cert_pem` is absent.
    /// - Any supplied PEM material fails to parse.
    pub fn build(self) -> Result<(As4SendPolicy, As4SendCredentials)> {
        let stage = "as4_send_policy_build";

        validate_strict_as4_send_policy_consistency(
            stage,
            self.policy.interop,
            self.policy.sign,
            self.policy.fail_closed_audit_events,
            self.policy.payload_packaging_mode,
        )?;

        validate_as4_send_policy_and_credentials_consistency(
            stage,
            &self.policy,
            &self.credentials,
            ErrorCode::InvalidInput,
        )?;

        #[cfg(feature = "as4")]
        self.credentials
            .prepare_for_policy(&self.policy, stage, ErrorCode::InvalidInput)?;

        Ok((self.policy, self.credentials))
    }
}

/// Protocol-specific credentials for AS4 message sending (signing and encryption).
///
/// # Preferred API
///
/// For new integrations and multi-protocol deployments, prefer
/// [`PartnerCredentials`](crate::credentials::PartnerCredentials) as the primary
/// credential holder.  `PartnerCredentials` zeroizes the signing key on drop,
/// supports both AS2 and AS4 from one bundle, and provides
/// [`prepare_as4_for_policy`](crate::credentials::PartnerCredentials::prepare_as4_for_policy)
/// for single-pass parse-and-validate.
///
/// Use `As4SendCredentials` directly only when you are already in AS4-only
/// code that does not need the unified API.
#[derive(Clone, Default)]
pub struct As4SendCredentials {
    /// PEM-encoded signing certificate
    pub signing_cert_pem: Option<Arc<[u8]>>,
    /// PEM-encoded signing private key
    pub signing_key_pem: Option<Vec<u8>>,
    /// PEM-encoded recipient certificate for encryption
    pub recipient_cert_pem: Option<Arc<[u8]>>,
}

impl std::fmt::Debug for As4SendCredentials {
    /// Never prints `signing_key_pem`.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("As4SendCredentials")
            .field("signing_cert_pem", &self.signing_cert_pem)
            .field(
                "signing_key_pem",
                &crate::core::redact_present(self.signing_key_pem.is_some()),
            )
            .field("recipient_cert_pem", &self.recipient_cert_pem)
            .finish()
    }
}

impl Drop for As4SendCredentials {
    fn drop(&mut self) {
        if let Some(key) = self.signing_key_pem.as_mut() {
            key.zeroize();
        }
    }
}

/// Output from AS4 message sending
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct As4SendOutput {
    pub message_id: String,
    pub action: String,
    /// W3C Trace Context `traceparent` header to forward on HTTP egress.
    pub traceparent: Option<String>,
    /// HTTP `Content-Type` to use for transport send.
    ///
    /// `multipart/related` for MIME attachment mode.
    pub http_content_type: String,
    pub soap_envelope: SoapEnvelope,
    /// The `<eb:RefToMessageId>` value emitted in the outbound envelope, if any.
    ///
    /// Mirrors [`As4SendPolicy::ref_to_message_id`].  Callers can use this to
    /// confirm which correlation ID was embedded in the sent message.
    pub ref_to_message_id: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct As4ReceivePushRequest {
    /// HTTP Content-Type associated with `payload`.
    pub http_content_type: String,
    pub payload: Arc<[u8]>,
    pub receipt_payload: Option<Vec<u8>>,
    pub policy: As4PushPolicy,
    /// Authenticated transport-layer sender identity for fragment group scoping.
    ///
    /// When [`FragmentScopePolicy::RequireAuthenticatedScope`] is active (the
    /// default), this field **must** be `Some` for fragment messages.  Typical
    /// values: mTLS client certificate CN, TLS peer IP, or an AP identifier
    /// verified at the transport layer **before** this request was admitted.
    ///
    /// For non-fragment (normal push) messages this field is ignored and may be
    /// `None`.
    pub authenticated_sender_scope: Option<Arc<str>>,
}

// ---------------------------------------------------------------------------
// WS-Addressing receive-path types
// ---------------------------------------------------------------------------

/// WS-Addressing headers extracted from an inbound AS4 SOAP envelope.
///
/// These are read from the `http://www.w3.org/2005/08/addressing` namespace
/// elements in the SOAP Header.  Fields are `None` when the corresponding
/// element was absent.
///
/// # Conformance note
///
/// For CEF eDelivery AS4 v1.15 strict mode, `message_id` and `action` are
/// mandatory.  `to` is strongly recommended.  Missing `message_id` or `action`
/// in strict mode triggers an `InteropPolicyViolation` error.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedWsAddressingHeaders {
    /// `wsa:MessageID` — unique URI identifying this message instance.
    pub message_id: Option<String>,
    /// `wsa:Action` — SOAP action URI; should match `<eb:Action>`.
    pub action: Option<String>,
    /// `wsa:To` — intended recipient endpoint URI.
    pub to: Option<String>,
    /// `wsa:ReplyTo/wsa:Address` — reply-to endpoint, if present.
    pub reply_to: Option<String>,
}

impl ParsedWsAddressingHeaders {
    /// Returns `true` if all CEF mandatory WS-Addressing fields are present
    /// (`wsa:MessageID` and `wsa:Action`).
    #[inline]
    pub fn is_cef_conformant(&self) -> bool {
        self.message_id.is_some() && self.action.is_some()
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedAs4UserMessage {
    pub message_id: String,
    pub action: String,
    /// All `<eb:From>/<eb:PartyId>` values from the inbound UserMessage.
    ///
    /// ebMS3 §5.2.2.4 permits multiple `<eb:PartyId>` per party for
    /// multi-scheme identifiers (e.g., GLN + DUNS).  This `Vec` is always
    /// non-empty; the **first element** is the primary routing identifier,
    /// accessible via [`from_party_id()`][Self::from_party_id].
    pub from_party_ids: Vec<String>,
    /// All `<eb:To>/<eb:PartyId>` values from the inbound UserMessage.
    ///
    /// Always non-empty; primary routing identifier accessible via
    /// [`to_party_id()`][Self::to_party_id].
    pub to_party_ids: Vec<String>,
    pub mpc: Option<String>,
    pub conversation_id: Option<String>,
    pub has_ws_security_header: bool,
    /// `<eb:Service>` value from the inbound UserMessage's `<eb:CollaborationInfo>`.
    ///
    /// Required for P-Mode resolution and Test Service detection.
    pub service: Option<String>,
    /// Present when the inbound UserMessage carries `<eb:RefToMessageId>`.
    ///
    /// Non-`None` indicates the sender is using the **Two-Way/Push-and-Push MEP**
    /// and this message is a response correlated to the original request message.
    pub ref_to_message_id: Option<String>,
    /// Four Corner topology `originalSender` MessageProperty value.
    pub original_sender: Option<String>,
    /// Four Corner topology `finalRecipient` MessageProperty value.
    pub final_recipient: Option<String>,
    /// Four Corner topology `trackingIdentifier` MessageProperty value.
    pub tracking_identifier: Option<String>,
    /// `<eb:Timestamp>` from `<eb:MessageInfo>` in RFC 3339 / ISO 8601 format.
    ///
    /// Present on virtually all conformant AS4 messages.  When `Some`, callers
    /// should validate freshness via [`ParsedAs4UserMessage::check_timestamp_freshness`]
    /// before processing the payload.  A missing timestamp is allowed (the field is
    /// optional in ebMS3) but signals an older or non-conformant sender implementation.
    pub timestamp: Option<String>,
    /// WS-Addressing headers extracted from the inbound SOAP envelope, if present.
    ///
    /// `None` when the inbound message carries no `wsa:*` elements in the SOAP
    /// Header.  Non-`None` when at least one WS-Addressing element was present;
    /// individual fields may still be `None` if omitted by the sender.
    ///
    /// CEF strict conformance requires `wsa:MessageID` and `wsa:Action`.
    pub wsa_headers: Option<ParsedWsAddressingHeaders>,
}

impl ParsedAs4UserMessage {
    /// Returns the primary sender party identifier (first `<eb:From>/<eb:PartyId>`).
    ///
    /// For peers that advertise only a single `<eb:PartyId>` this is equivalent
    /// to the sole identifier.  When multiple scheme-specific identifiers are
    /// present (ebMS3 §5.2.2.4), this returns the first one as encountered in
    /// the XML, which is the primary routing identifier by convention.
    #[inline]
    pub fn from_party_id(&self) -> &str {
        &self.from_party_ids[0]
    }

    /// Returns the primary recipient party identifier (first `<eb:To>/<eb:PartyId>`).
    #[inline]
    pub fn to_party_id(&self) -> &str {
        &self.to_party_ids[0]
    }

    /// Validate that the `<eb:Timestamp>` is within the allowed freshness window.
    ///
    /// Per eDelivery AS4 v1.15 §5.1.3 and ebMS3 Core §6.3, the timestamp is
    /// expected to be within ±`window` of `now`.  The default recommended window
    /// is 5 minutes (300 seconds).
    ///
    /// Returns `Ok(())` when:
    /// - The timestamp is absent (lenient — a missing timestamp is warned elsewhere).
    /// - The parsed timestamp is within `[now - window, now + window]`.
    ///
    /// Returns `Err` when the timestamp is present but outside the freshness window,
    /// or when it cannot be parsed as RFC 3339.
    pub fn check_timestamp_freshness(
        &self,
        window: std::time::Duration,
    ) -> crate::core::Result<()> {
        use crate::core::{AsxError, ErrorCode, ErrorContext};

        let ts_str = match &self.timestamp {
            Some(s) => s,
            None => return Ok(()),
        };

        let ts_secs = crate::time_utils::parse_rfc3339_to_unix_secs(ts_str).ok_or_else(|| {
            AsxError::new(
                ErrorCode::ParseFailed,
                format!("eb:Timestamp value '{ts_str}' is not a valid RFC 3339 timestamp"),
                ErrorContext::new("as4_timestamp_freshness"),
            )
        })?;

        let now_secs = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap_or(std::time::Duration::ZERO)
            .as_secs() as i64;
        let delta_secs = (now_secs - ts_secs).unsigned_abs();
        let window_secs = window.as_secs();

        if delta_secs > window_secs {
            return Err(AsxError::new(
                ErrorCode::SecurityVerificationFailed,
                format!(
                    "eb:Timestamp is outside the freshness window (delta={}s, allowed={}s); \
                     message rejected to prevent replay",
                    delta_secs, window_secs,
                ),
                ErrorContext::new("as4_timestamp_freshness")
                    .with_message_id(self.message_id.clone()),
            ));
        }

        Ok(())
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedAs4Receipt {
    pub ref_to_message_id: String,
    pub is_signed: bool,
    pub has_non_repudiation_info: bool,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct As4ReceivePushOutput {
    /// Primary payload — the first `eb:PartInfo` attachment.
    ///
    /// The overwhelmingly common case is a single payload, so this stays a
    /// direct field rather than an index into a collection. Messages carrying
    /// more than one attachment expose the remainder in
    /// [`Self::additional_payloads`]; use [`Self::payloads`] to iterate all of
    /// them uniformly.
    pub payload: DomainReady<Arc<[u8]>>,
    /// Content-ID the primary payload arrived under (no `cid:` prefix).
    pub payload_content_id: String,
    /// Attachments beyond the first, in `xop:Include` document order.
    ///
    /// Empty for a single-payload message. ebMS3 permits several `eb:PartInfo`
    /// entries per `UserMessage`, and the eDelivery conformance payload
    /// profiles exercise up to four; every one of them is signature-verified
    /// and decrypted on the same terms as the primary.
    pub additional_payloads: Vec<As4ReceivedPayload>,
    /// Parsed SBDH header when inbound business payload was SBDH-wrapped.
    pub sbdh_header: Option<SbdhHeader>,
    pub user_message: ParsedAs4UserMessage,
    pub receipt: Option<ParsedAs4Receipt>,
}

impl As4ReceivePushOutput {
    /// Whether this is an **ebMS3 Test Service message** (Core §5.2.2) — a
    /// connectivity ping, not a business document.
    ///
    /// A conformant MSH acknowledges a test message with a receipt and **does
    /// not deliver it to the application**. The payload of a ping is empty or a
    /// loopback of what the sender sent; handing it to a business pipeline
    /// creates a document out of a health check.
    ///
    /// ```
    /// # #[cfg(feature = "as4")]
    /// # fn handle(out: &asx_rs::as4::As4ReceivePushOutput) {
    /// if out.is_test_service_ping() {
    ///     // Receipt already generated by the receive path; stop here.
    ///     return;
    /// }
    /// // …deliver out.payload to the application
    /// # }
    /// ```
    ///
    /// Derived from the parsed `eb:Service` and `eb:Action`, so it cannot drift
    /// from what was actually on the wire.
    #[must_use]
    pub fn is_test_service_ping(&self) -> bool {
        crate::as4::test_service::is_test_service_message(&self.user_message)
    }

    /// Every payload in `eb:PartInfo` order, primary first.
    pub fn payloads(&self) -> impl Iterator<Item = (&str, &DomainReady<Arc<[u8]>>)> {
        std::iter::once((self.payload_content_id.as_str(), &self.payload)).chain(
            self.additional_payloads
                .iter()
                .map(|p| (p.content_id.as_str(), &p.payload)),
        )
    }

    /// Total attachment count, always at least 1.
    pub fn payload_count(&self) -> usize {
        1 + self.additional_payloads.len()
    }

    /// Look up a payload by Content-ID (`cid:` prefix optional).
    pub fn payload_by_content_id(&self, content_id: &str) -> Option<&DomainReady<Arc<[u8]>>> {
        let wanted = content_id
            .strip_prefix("cid:")
            .or_else(|| content_id.strip_prefix("CID:"))
            .unwrap_or(content_id);
        self.payloads()
            .find(|(cid, _)| *cid == wanted)
            .map(|(_, payload)| payload)
    }
}

/// A non-primary payload attachment from a multi-payload AS4 message.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct As4ReceivedPayload {
    /// Content-ID the attachment arrived under (no `cid:` prefix).
    pub content_id: String,
    pub payload: DomainReady<Arc<[u8]>>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum As4ReceivePushProgress {
    PendingFragment {
        group_id: String,
        received_fragments: usize,
        expected_fragments: Option<usize>,
    },
    Complete(Box<As4ReceivePushOutput>),
    /// The message was already processed — idempotent replay detected by the
    /// dedup store.  Return an acknowledgement without re-dispatching to
    /// business logic.
    Duplicate {
        message_id: String,
    },
}

/// Outcome of a non-fragment-aware AS4 push receive call.
///
/// Unlike `Result<As4ReceivePushOutput, AsxError>`, this enum lets callers
/// distinguish a **first-seen** message (process normally) from a **replay**
/// (return an idempotent acknowledgement without re-dispatching) at the call
/// site — no `EventBus` subscription required.
///
/// # Example
/// ```rust,ignore
/// match receive_push_with_dedup_async(&session, &bus, req, dedup).await? {
///     As4ReceiveOutcome::FirstSeen(output) => dispatch_to_workflow(output),
///     As4ReceiveOutcome::Duplicate { message_id } => {
///         tracing::info!(%message_id, "replay ignored");
///         // still send an AS4 receipt — the sender may not have received the first one
///     }
/// }
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum As4ReceiveOutcome {
    /// First occurrence: message verified and ready for business processing.
    FirstSeen(Box<As4ReceivePushOutput>),
    /// Replay: already processed.  Use `message_id` to correlate and return
    /// an idempotent acknowledgement without re-dispatching.
    Duplicate { message_id: String },
}

impl As4ReceiveOutcome {
    /// Returns `true` if this is a first-seen message.
    #[inline]
    pub fn is_first_seen(&self) -> bool {
        matches!(self, Self::FirstSeen(_))
    }

    /// Returns `true` if this is a duplicate replay.
    #[inline]
    pub fn is_duplicate(&self) -> bool {
        matches!(self, Self::Duplicate { .. })
    }

    /// Consume the outcome and return the output if first-seen, `None` for duplicates.
    #[inline]
    pub fn into_output(self) -> Option<As4ReceivePushOutput> {
        match self {
            Self::FirstSeen(output) => Some(*output),
            Self::Duplicate { .. } => None,
        }
    }

    /// Unwrap the output, panicking on duplicates.  Only use after `is_duplicate()` check.
    ///
    /// # Panics
    /// Panics if called on a `Duplicate` variant.
    #[inline]
    pub fn unwrap_output(self) -> As4ReceivePushOutput {
        match self {
            Self::FirstSeen(output) => *output,
            Self::Duplicate { ref message_id } => {
                panic!("called unwrap_output on a Duplicate (message_id={message_id})")
            }
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct As4QueuedPullMessage {
    /// Message identifier used for overflow auditing and reconciliation.
    pub message_id: Arc<str>,
    /// Original HTTP Content-Type of the queued push payload.
    pub http_content_type: Arc<str>,
    pub payload: Arc<[u8]>,
}

/// A single `<ds:Reference>` extracted from an inbound message's XMLDSig
/// `<ds:SignedInfo>`.  Pass a slice of these to
/// [`crate::as4::generate_receipt_with_nri`] to build a conformant
/// Non-Repudiation of Origin (NRO) receipt per ebMS3 §5.2.2.1.
///
/// Obtain these values from [`crate::crypto::wssec::parse_signature_references`]
/// after verifying the inbound message signature.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct As4NriReference {
    /// The `URI` attribute of the `<ds:Reference>` element (e.g., `"#body"`).
    pub uri: String,
    /// The `Algorithm` attribute of `<ds:DigestMethod>`.
    pub digest_method_uri: String,
    /// The base64-encoded digest value from `<ds:DigestValue>`.
    pub digest_value_b64: String,
}

impl From<&WsSecSignatureReference> for As4NriReference {
    /// Convert a [`WsSecSignatureReference`] (from `parse_signature_references`)
    /// directly into an [`As4NriReference`] suitable for
    /// [`crate::as4::generate_receipt_with_nri`].
    fn from(r: &WsSecSignatureReference) -> Self {
        Self {
            uri: r.uri.clone(),
            digest_method_uri: r.digest_method.algorithm_uri().to_string(),
            digest_value_b64: r.digest_value_base64.clone(),
        }
    }
}

impl From<WsSecSignatureReference> for As4NriReference {
    /// Convert an owned [`WsSecSignatureReference`] into an [`As4NriReference`]
    /// while reusing owned string buffers where possible.
    fn from(r: WsSecSignatureReference) -> Self {
        Self {
            uri: r.uri,
            digest_method_uri: r.digest_method.algorithm_uri().to_string(),
            digest_value_b64: r.digest_value_base64,
        }
    }
}

/// A single `<eb:Error>` entry parsed from a counterparty `eb:SignalMessage`.
///
/// ebMS3 §6.2 defines `eb:Error` with the attributes reproduced here plus the
/// optional `eb:Description` / `eb:ErrorDetail` child elements.  All fields
/// except [`error_code`](Self::error_code) are optional in the schema and are
/// reported exactly as received — no normalization, no defaulting.
///
/// Use [`As4ErrorCode::from_ebms_code`] to map [`error_code`](Self::error_code)
/// onto the subset of codes this crate models, and
/// [`As4ErrorSeverity::from_ebms_severity`] for
/// [`severity`](Self::severity).  Codes outside that subset are still fully
/// available as the raw string — an unrecognised code is never dropped.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct As4ReceivedError {
    /// The `errorCode` attribute, e.g. `"EBMS:0302"`.  `"unknown"` when the
    /// counterparty omitted the attribute (schema-invalid but observed in the
    /// wild).
    pub error_code: String,
    /// The `severity` attribute, e.g. `"failure"` / `"warning"`.
    pub severity: Option<String>,
    /// The `category` attribute, e.g. `"Content"`, `"Processing"`.
    pub category: Option<String>,
    /// The `origin` attribute, e.g. `"ebMS"`, `"security"`, `"reliability"`.
    pub origin: Option<String>,
    /// The `refToMessageId` attribute — the message this error refers to.
    ///
    /// Note that ebMS3 also allows the correlation to be carried only by the
    /// enclosing `eb:MessageInfo/eb:RefToMessageId`; see
    /// [`As4ErrorSignal::ref_to_message_id`].
    pub ref_to_message_id: Option<String>,
    /// The `shortDescription` attribute, e.g. `"InvalidReceipt"`.
    pub short_description: Option<String>,
    /// Text of the `eb:Description` child element.
    pub description: Option<String>,
    /// Text of the `eb:ErrorDetail` child element.
    pub error_detail: Option<String>,
}

impl As4ReceivedError {
    /// The modelled [`As4ErrorCode`] for [`error_code`](Self::error_code), when
    /// this crate recognises it.
    pub fn code(&self) -> Option<As4ErrorCode> {
        As4ErrorCode::from_ebms_code(&self.error_code)
    }

    /// The modelled [`As4ErrorSeverity`], when the counterparty supplied a
    /// recognised `severity` attribute.
    pub fn parsed_severity(&self) -> Option<As4ErrorSeverity> {
        self.severity
            .as_deref()
            .and_then(As4ErrorSeverity::from_ebms_severity)
    }

    /// Whether this entry is a hard failure.
    ///
    /// `true` when `severity` is absent — ebMS3 §6.2 makes the attribute
    /// mandatory, so an omission is treated as the fail-closed reading rather
    /// than silently downgraded to a warning.
    pub fn is_failure(&self) -> bool {
        !matches!(self.parsed_severity(), Some(As4ErrorSeverity::Warning))
    }

    /// Single-line human summary for logs and dead-letter records.
    pub fn summary(&self) -> String {
        let mut summary = self.error_code.clone();
        if let Some(short) = &self.short_description {
            summary.push_str(" (");
            summary.push_str(short);
            summary.push(')');
        }
        if let Some(description) = self.description.as_ref().or(self.error_detail.as_ref()) {
            summary.push_str(": ");
            summary.push_str(description);
        }
        summary
    }
}

/// A counterparty `eb:SignalMessage` carrying one or more `eb:Error` entries.
///
/// Returned by [`crate::as4::verify_sync_response`] as
/// [`As4SyncSignal::Error`](crate::as4::As4SyncSignal::Error) when the remote MSH rejected the message instead
/// of acknowledging it.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct As4ErrorSignal {
    /// `eb:MessageInfo/eb:MessageId` of the error signal itself.
    pub message_id: Option<String>,
    /// `eb:MessageInfo/eb:RefToMessageId` — the message being rejected.
    pub ref_to_message_id: Option<String>,
    /// `eb:MessageInfo/eb:Timestamp` as received (RFC 3339).
    pub timestamp: Option<String>,
    /// Every `eb:Error` entry in the signal, in document order.
    pub errors: Vec<As4ReceivedError>,
}

impl As4ErrorSignal {
    /// Whether any entry has `severity` other than `warning`.
    ///
    /// A signal with no entries at all counts as a failure: an `eb:Error`
    /// SignalMessage that carries no diagnosable entry is still a rejection.
    pub fn is_failure(&self) -> bool {
        self.errors.is_empty() || self.errors.iter().any(As4ReceivedError::is_failure)
    }

    /// Single-line summary of all entries, for logs and dead-letter records.
    pub fn summary(&self) -> String {
        if self.errors.is_empty() {
            return "eb:Error signal with no eb:Error entries".to_string();
        }
        self.errors
            .iter()
            .map(As4ReceivedError::summary)
            .collect::<Vec<_>>()
            .join("; ")
    }
}

/// A counterparty `eb:Receipt` that passed every check demanded by an
/// [`As4ReceiptPolicy`](crate::as4::As4ReceiptPolicy).
///
/// Produced by [`crate::as4::verify_sync_response`].  Holding one of these is
/// the evidence that the message was delivered: when
/// [`non_repudiation`](Self::non_repudiation) is
/// [`Verified`](crate::as4::As4NonRepudiation::Verified) the counterparty
/// signed a statement about the exact digests the sent message was signed over.
///
/// Persist it alongside the sent envelope to satisfy audit requirements such as
/// BDEW AS4-Profil §2.2.4.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct As4VerifiedReceipt {
    /// `eb:MessageId` of the receipt SignalMessage itself, when present.
    pub message_id: Option<String>,
    /// `eb:RefToMessageId` — verified equal to the sent message id.
    pub ref_to_message_id: String,
    /// `eb:Timestamp` as received (RFC 3339), when present.
    pub timestamp: Option<String>,
    /// Whether the receipt carried a WS-Security XML Signature.  When `true`
    /// the signature was verified — an unverifiable signature is an error, never
    /// a `true` here.
    pub signed: bool,
    /// SHA-256 fingerprint the signer certificate was pinned against, when the
    /// receipt was signed.
    pub signer_fingerprint_sha256: Option<String>,
    /// Outcome of the Non-Repudiation of Receipt digest check.
    pub non_repudiation: crate::as4::As4NonRepudiation,
}

impl As4VerifiedReceipt {
    /// Whether this receipt is full Non-Repudiation of Receipt evidence — both
    /// signed by the counterparty and echoing the sent message's digests.
    pub fn is_non_repudiation_evidence(&self) -> bool {
        self.signed && self.non_repudiation.is_verified()
    }
}

/// Credentials required to generate a signed AS4 `PullRequest` signal.
///
/// Per eDelivery AS4 v1.15 §4.5.5, pull requests MUST be signed using the
/// signing certificate of the Receiver Party.
#[derive(Clone)]
pub struct As4PullRequestCredentials {
    /// PEM-encoded RSA private key used to sign the pull request signal.
    pub signing_key_pem: Vec<u8>,
    /// PEM-encoded X.509 certificate corresponding to `signing_key_pem`.
    pub signing_cert_pem: Vec<u8>,
    /// Key-info profile controlling how the signing certificate appears in
    /// the `<ds:KeyInfo>` element of the generated XML signature.
    pub key_info_profile: WsSecOutboundKeyInfoProfile,
}

impl std::fmt::Debug for As4PullRequestCredentials {
    /// Never prints `signing_key_pem`.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("As4PullRequestCredentials")
            .field(
                "signing_key_pem",
                &crate::core::redact_present(!self.signing_key_pem.is_empty()),
            )
            .field("signing_cert_pem", &self.signing_cert_pem)
            .field("key_info_profile", &self.key_info_profile)
            .finish()
    }
}

impl Drop for As4PullRequestCredentials {
    fn drop(&mut self) {
        self.signing_key_pem.zeroize();
    }
}

/// Credentials required to generate a signed AS4 `eb:Receipt` signal.
///
/// Per eDelivery AS4 v1.15 §5.1.8 and profile derivatives (e.g. BDEW
/// AS4-Profil §2.2.4), receipts must carry a WS-Security XML Signature so
/// that Non-Repudiation of Receipt (NRR) holds.  Pass these credentials to
/// [`crate::as4::generate_signed_receipt_with_nri`] or
/// [`crate::as4::generate_signed_receipt_for_output`].
#[derive(Clone)]
pub struct As4ReceiptCredentials {
    /// PEM-encoded private key used to sign the receipt signal.
    pub signing_key_pem: Vec<u8>,
    /// PEM-encoded X.509 certificate corresponding to `signing_key_pem`.
    pub signing_cert_pem: Vec<u8>,
    /// Key-info profile controlling how the signing certificate appears in
    /// the `<ds:KeyInfo>` element of the generated XML signature.
    pub key_info_profile: WsSecOutboundKeyInfoProfile,
}

impl std::fmt::Debug for As4ReceiptCredentials {
    /// Never prints `signing_key_pem`.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("As4ReceiptCredentials")
            .field(
                "signing_key_pem",
                &crate::core::redact_present(!self.signing_key_pem.is_empty()),
            )
            .field("signing_cert_pem", &self.signing_cert_pem)
            .field("key_info_profile", &self.key_info_profile)
            .finish()
    }
}

impl Drop for As4ReceiptCredentials {
    fn drop(&mut self) {
        self.signing_key_pem.zeroize();
    }
}

/// Parameters for [`crate::as4::generate_pull_request`].
#[derive(Debug, Clone)]
pub struct As4GeneratePullRequestPolicy {
    /// The Message Partition Channel to pull from.
    pub mpc: String,
    /// A unique message ID for this pull request signal.  Must conform to
    /// the ebMS3 message-ID format (typically a UUID or RFC 2822 msg-id).
    pub message_id: String,
    /// Optional signing credentials.  When `Some`, a WS-Security XML Signature
    /// is added per eDelivery AS4 v1.15 §4.5.5.  When `None`, the pull request
    /// is unsigned (permitted only when the trading-partner agreement explicitly
    /// opts out of pull-request signing).
    pub credentials: Option<As4PullRequestCredentials>,
    /// Optional `<eb:AuthorizationInfo>` token per ebMS3 §5.2.3.1.  Required
    /// by pull sub-profiles (e.g., CEF eDelivery pull profile) that mandate pull
    /// authorization via a shared secret or token.
    pub authorization_info: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct As4PullPolicy {
    pub interop: InteropMode,
    pub mpc: String,
    pub interop_exceptions: InteropExceptionPolicy,
    pub require_signed_receipt: bool,
    #[doc(hidden)]
    pub(crate) require_signed_push: bool,
    /// When `true` (the default), protocol event emission failures fail the
    /// pull receive operation (fail-closed audit semantics).
    pub fail_closed_audit_events: bool,
    /// How a `PullRequest` proves it may drain this MPC.
    ///
    /// Defaults to [`As4PullAuthorization::Deny`] — see that type for why there
    /// is no "unauthenticated" default.
    pub authorization: As4PullAuthorization,
}

/// How the pull receive path authorizes a `PullRequest` for an MPC.
///
/// Pull inverts the usual trust direction. In push, the sender proves who it is
/// by signing a message it hands you. In pull, a peer asks you to *hand over*
/// queued messages, and the ebMS3 `PullRequest` signal carries no signature —
/// so the only thing standing between a caller and another party's business
/// documents is this check. An MPC URI is not a secret: it appears in P-Mode
/// configuration, agreements, and log lines.
///
/// ebMS3 §5.2.3.1 makes `eb:AuthorizationInfo` optional *at the protocol
/// level*, which is why this is a policy decision rather than a wire
/// requirement. It is not an invitation to skip it: the flexibility exists for
/// deployments where the transport layer owns the boundary, and that is
/// [`EnforcedByTransport`](Self::EnforcedByTransport) — a choice you make
/// explicitly, not one you fall into.
#[derive(Clone, PartialEq, Eq, Default)]
pub enum As4PullAuthorization {
    /// Reject every `PullRequest`. **The default.**
    ///
    /// An MPC with no configured authorization must not serve messages. This
    /// makes the insecure configuration unreachable by omission: you cannot
    /// leave pull open by forgetting to set a field, only by choosing one of
    /// the variants below.
    #[default]
    Deny,

    /// Compare `eb:AuthorizationInfo` against a shared secret in constant time.
    ///
    /// Use a random, high-entropy value agreed with the pulling party — this is
    /// a bearer credential travelling in the SOAP body, so treat it like a
    /// password, not like an identifier.
    SharedSecret(String),

    /// Authorization happens before the request reaches this library.
    ///
    /// Select this only when something upstream — mutually-authenticated TLS
    /// terminating at a reverse proxy, an API gateway mapping client
    /// certificates to MPCs — has already established that this caller may
    /// drain this MPC. The library then performs no check of its own.
    ///
    /// Choosing this without such a control in place makes the endpoint open to
    /// anyone who knows the MPC URI.
    EnforcedByTransport,
}

impl std::fmt::Debug for As4PullAuthorization {
    /// Never prints the shared secret.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Deny => f.write_str("Deny"),
            Self::SharedSecret(secret) => f
                .debug_tuple("SharedSecret")
                .field(&crate::core::redact_present(!secret.is_empty()))
                .finish(),
            Self::EnforcedByTransport => f.write_str("EnforcedByTransport"),
        }
    }
}

const DEFAULT_MPC: &str =
    "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/defaultMPC";

impl Default for As4PullPolicy {
    fn default() -> Self {
        Self {
            interop: InteropMode::Strict,
            mpc: String::from(DEFAULT_MPC),
            interop_exceptions: InteropExceptionPolicy::default(),
            require_signed_receipt: true,
            require_signed_push: true,
            fail_closed_audit_events: true,
            authorization: As4PullAuthorization::Deny,
        }
    }
}

impl As4PullPolicy {
    /// Return the recommended production-safe pull policy preset.
    pub fn strict() -> Self {
        Self::default()
    }

    /// Return the regulated deployment preset for pull receive.
    ///
    /// This preset is fail-closed and requires signed pulled messages and
    /// signed receipts in strict interop mode.
    pub fn regulated() -> Self {
        Self {
            interop: InteropMode::Strict,
            mpc: String::from(DEFAULT_MPC),
            interop_exceptions: InteropExceptionPolicy::default(),
            require_signed_receipt: true,
            require_signed_push: true,
            fail_closed_audit_events: true,
            authorization: As4PullAuthorization::Deny,
        }
    }

    /// Return whether pulled user messages must carry a valid signature.
    pub fn require_signed_push(&self) -> bool {
        self.require_signed_push
    }
}

/// Fluent builder for [`As4PullPolicy`].
#[derive(Debug, Default)]
pub struct As4PullPolicyBuilder(As4PullPolicy);

impl As4PullPolicyBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn interop(mut self, mode: InteropMode) -> Self {
        self.0.interop = mode;
        self
    }

    pub fn mpc(mut self, mpc: impl Into<String>) -> Self {
        self.0.mpc = mpc.into();
        self
    }

    pub fn interop_exceptions(mut self, exc: InteropExceptionPolicy) -> Self {
        self.0.interop_exceptions = exc;
        self
    }

    pub fn require_signed_receipt(mut self, v: bool) -> Self {
        self.0.require_signed_receipt = v;
        self
    }

    /// Override the default signature requirement for pulled user messages.
    ///
    /// # Security
    ///
    /// **Testing-only escape hatch.** Disabling this in production weakens
    /// trust guarantees for received AS4 user messages.
    #[cfg(feature = "testing")]
    pub fn allow_unsigned_push(mut self, allow: bool) -> Self {
        self.0.require_signed_push = !allow;
        self
    }

    pub fn fail_closed_audit_events(mut self, v: bool) -> Self {
        self.0.fail_closed_audit_events = v;
        self
    }

    /// Set how `PullRequest`s are authorized for this MPC.
    ///
    /// Without this call the policy denies every pull — see
    /// [`As4PullAuthorization`].
    pub fn authorization(mut self, authorization: As4PullAuthorization) -> Self {
        self.0.authorization = authorization;
        self
    }

    pub fn build(self) -> Result<As4PullPolicy> {
        let stage = "as4_pull_policy_build";

        validate_strict_as4_policy_consistency(stage, self.0.interop, &self.0.interop_exceptions)?;

        validate_strict_as4_receive_policy_consistency(
            stage,
            self.0.interop,
            self.0.require_signed_receipt,
            self.0.fail_closed_audit_events,
        )?;

        if self.0.mpc.trim().is_empty() {
            return Err(AsxError::new(
                ErrorCode::InvalidInput,
                "As4PullPolicy.mpc must not be empty",
                ErrorContext::new(stage),
            ));
        }

        // An empty shared secret would compare equal to an absent
        // AuthorizationInfo, silently degrading SharedSecret into "allow all".
        if let As4PullAuthorization::SharedSecret(ref secret) = self.0.authorization
            && secret.trim().is_empty()
        {
            return Err(AsxError::new(
                ErrorCode::InvalidInput,
                "As4PullAuthorization::SharedSecret must not be empty — an empty secret \
                 matches an absent eb:AuthorizationInfo and would authorize every caller",
                ErrorContext::new(stage),
            ));
        }

        Ok(self.0)
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct As4ReceivePullRequest {
    pub pull_message_id: String,
    pub policy: As4PullPolicy,
    pub receipt_payload: Option<Vec<u8>>,
    /// The `<eb:AuthorizationInfo>` value extracted from the incoming
    /// `<eb:PullRequest>` element, if present. Checked according to
    /// [`As4PullPolicy::authorization`].
    pub authorization_info: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct As4ReceivePullOutput {
    pub pull_message_id: Arc<str>,
    pub correlation_message_id: Option<Arc<str>>,
    pub mpc: Arc<str>,
    pub duplicate_retrieval: bool,
    pub pulled: Option<Arc<As4ReceivePushOutput>>,
    pub outcome: DeliveryOutcome,
    pub retry: RetryDecision,
}

// ── Signal types ─────────────────────────────────────────────────────────────

/// AS4 error signal error codes per ebMS3 specification §6.7.3.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum As4ErrorCode {
    /// EBMS:0001 — Value not recognised.
    ValueNotRecognized,
    /// EBMS:0002 — Feature not supported.
    FeatureNotSupported,
    /// EBMS:0003 — Value inconsistent.
    ValueInconsistent,
    /// EBMS:0004 — Other.
    Other,
    /// EBMS:0301 — Missing receipt.
    MissingReceipt,
    /// EBMS:0302 — Invalid receipt.
    InvalidReceipt,
    /// EBMS:0303 — Decompression failure.
    DecompressionFailure,
}

impl As4ErrorCode {
    /// Returns the OASIS-defined `errorCode` attribute string, e.g. `"EBMS:0001"`.
    pub fn ebms_code(self) -> &'static str {
        match self {
            As4ErrorCode::ValueNotRecognized => "EBMS:0001",
            As4ErrorCode::FeatureNotSupported => "EBMS:0002",
            As4ErrorCode::ValueInconsistent => "EBMS:0003",
            As4ErrorCode::Other => "EBMS:0004",
            As4ErrorCode::MissingReceipt => "EBMS:0301",
            As4ErrorCode::InvalidReceipt => "EBMS:0302",
            As4ErrorCode::DecompressionFailure => "EBMS:0303",
        }
    }

    /// Map an `errorCode` attribute received from a counterparty back onto the
    /// modelled variants, or `None` for any code outside this subset.
    ///
    /// The ebMS3 registry is larger than what this crate generates; callers
    /// receiving an unmodelled code should keep the raw
    /// [`As4ReceivedError::error_code`] string rather than discarding it.
    /// Matching is ASCII case-insensitive on the `EBMS:` prefix.
    pub fn from_ebms_code(code: &str) -> Option<Self> {
        let code = code.trim();
        let (prefix, digits) = code.split_at_checked(5)?;
        if !prefix.eq_ignore_ascii_case("EBMS:") {
            return None;
        }
        match digits {
            "0001" => Some(As4ErrorCode::ValueNotRecognized),
            "0002" => Some(As4ErrorCode::FeatureNotSupported),
            "0003" => Some(As4ErrorCode::ValueInconsistent),
            "0004" => Some(As4ErrorCode::Other),
            "0301" => Some(As4ErrorCode::MissingReceipt),
            "0302" => Some(As4ErrorCode::InvalidReceipt),
            "0303" => Some(As4ErrorCode::DecompressionFailure),
            _ => None,
        }
    }
}

/// Error severity for AS4 Error signal messages.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum As4ErrorSeverity {
    /// Processing must stop; the message cannot be delivered.
    Failure,
    /// Processing may continue but the sender should be aware.
    Warning,
}

impl As4ErrorSeverity {
    /// The `severity` attribute value written on outbound `eb:Error` signals.
    pub fn as_str(self) -> &'static str {
        match self {
            As4ErrorSeverity::Failure => "Failure",
            As4ErrorSeverity::Warning => "Warning",
        }
    }

    /// Parse a received `severity` attribute, ASCII case-insensitively.
    ///
    /// Returns `None` for any value outside the ebMS3 vocabulary; callers
    /// should treat an unrecognised severity as a failure rather than assuming
    /// it is benign.
    pub fn from_ebms_severity(severity: &str) -> Option<Self> {
        let severity = severity.trim();
        if severity.eq_ignore_ascii_case("failure") {
            Some(As4ErrorSeverity::Failure)
        } else if severity.eq_ignore_ascii_case("warning") {
            Some(As4ErrorSeverity::Warning)
        } else {
            None
        }
    }
}