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
/// SOAP envelope and ebMS3 message builder for AS4
///
/// Implements RFC 5751 (S/MIME) with OASIS ebMS 3.0 messaging format and WS-Security
/// for AS4 push/pull message construction.
use crate::core::Result;

/// Splice a finished `wsse:Security` header into the slot
/// [`WSSE_HEADER_PLACEHOLDER`] reserved, replacing it exactly once.
///
/// Fails if the placeholder is absent or appears more than once, so the
/// "brittle string-marker insertion" this replaces cannot fail silently — which
/// is the property the rebuild it replaces was chosen for, without the race the
/// rebuild introduced (D42).
///
/// # Errors
///
/// [`ErrorCode::InvalidInput`](crate::ErrorCode::InvalidInput) when the
/// envelope does not contain exactly one placeholder.
pub fn splice_ws_security_header(envelope: &str, header_xml: &str) -> Result<String> {
    let occurrences = envelope.matches(WSSE_HEADER_PLACEHOLDER).count();
    if occurrences != 1 {
        return Err(crate::core::AsxError::new(
            crate::core::ErrorCode::InvalidInput,
            format!(
                "SOAP envelope must contain exactly one wsse:Security placeholder to splice \
                 into, found {occurrences}; build it with \
                 SoapEnvelopeBuilder::with_ws_security_placeholder()"
            ),
            crate::core::ErrorContext::new("as4_soap_builder"),
        ));
    }
    Ok(envelope.replacen(WSSE_HEADER_PLACEHOLDER, header_xml, 1))
}

/// Marker reserving the position of the `wsse:Security` header inside
/// `soap:Header`, emitted by
/// [`SoapEnvelopeBuilder::with_ws_security_placeholder`].
///
/// It exists so the envelope is built **once**. Building it a second time to
/// add the security header is what let `eb:Timestamp` change between the bytes
/// that were digested and the bytes that shipped (D42) — a defect that only
/// appeared when the two builds straddled a whole second.
pub const WSSE_HEADER_PLACEHOLDER: &str = "<!--asx:wsse-security-header-->";
use base64::{Engine as _, engine::general_purpose::STANDARD};

const SOAP12_NAMESPACE: &str = "http://www.w3.org/2003/05/soap-envelope";
const EBMS_NAMESPACE: &str = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/";
const WSSE_NAMESPACE: &str =
    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd";
const WSSEC_UTILITY_NAMESPACE: &str =
    "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd";
const WSA_NAMESPACE: &str = "http://www.w3.org/2005/08/addressing";

// ── WS-Addressing ────────────────────────────────────────────────────────────

/// WS-Addressing headers to include in the outbound SOAP envelope.
///
/// Per the WS-Addressing 1.0 — Core specification (W3C), AS4 deployments
/// using WS-Addressing must include `wsa:MessageID` and `wsa:Action` at
/// minimum.  `wsa:To` is strongly recommended.
///
/// Set on the builder via [`SoapEnvelopeBuilder::with_ws_addressing`].
///
/// If no WS-Addressing configuration is supplied, **no** `wsa:*` headers are
/// emitted (the default for backward-compatible deployments).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WsAddressingHeaders {
    /// Absolute URI uniquely identifying this message instance.
    /// Conventionally a UUID URN: `urn:uuid:<v4-uuid>`.
    pub message_id: String,
    /// WS-Addressing action URI.  Should match the ebMS3 `<eb:Action>` value
    /// so that SOAP intermediaries can route on it.
    pub action: String,
    /// Endpoint reference for the intended recipient.  Typically the partner's
    /// AS4 endpoint URL.  Pass `http://www.w3.org/2005/08/addressing/anonymous`
    /// for reply-to scenarios.
    pub to: String,
    /// Optional reply-to endpoint.  When `None`, the anonymous EPR is implied.
    pub reply_to: Option<String>,
}

impl WsAddressingHeaders {
    /// Minimal WS-Addressing block: `MessageID`, `Action`, and `To`.
    pub fn new(
        message_id: impl Into<String>,
        action: impl Into<String>,
        to: impl Into<String>,
    ) -> Self {
        Self {
            message_id: message_id.into(),
            action: action.into(),
            to: to.into(),
            reply_to: None,
        }
    }

    /// Add an explicit `ReplyTo` endpoint reference.
    pub fn with_reply_to(mut self, reply_to: impl Into<String>) -> Self {
        self.reply_to = Some(reply_to.into());
        self
    }
}

#[derive(Debug, Clone)]
pub struct SoapEnvelopeBuilder {
    message_id: String,
    /// `eb:Timestamp` for `eb:MessageInfo`. **Required** — see
    /// [`with_message_timestamp`](SoapEnvelopeBuilder::with_message_timestamp).
    message_timestamp: Option<String>,
    from_party_id: String,
    to_party_id: String,
    /// `type` attribute on the From `<eb:PartyId>`; `None` omits the attribute.
    from_party_id_type: Option<String>,
    /// `type` attribute on the To `<eb:PartyId>`; `None` omits the attribute.
    to_party_id_type: Option<String>,
    /// `<eb:From>/<eb:Role>` — REQUIRED by the ebMS3 schema.
    from_role: String,
    /// `<eb:To>/<eb:Role>` — REQUIRED by the ebMS3 schema.
    to_role: String,
    /// Optional `<eb:AgreementRef>` (first child of `CollaborationInfo`).
    agreement_ref: Option<String>,
    /// `type` attribute on `<eb:AgreementRef>`.
    agreement_ref_type: Option<String>,
    action: String,
    service: String,
    service_type: String,
    mpc: Option<String>,
    conversation_id: Option<String>,
    /// Two-Way MEP correlation: emits `<eb:RefToMessageId>` in MessageInfo.
    ref_to_message_id: Option<String>,
    original_sender: String,
    final_recipient: String,
    tracking_identifier: String,
    payload: Vec<u8>,
    /// AS4 SwA packaging: reference the payload as a detached MIME attachment
    /// (`eb:PartInfo href="cid:…"`) and leave the SOAP Body **empty**, as the
    /// AS4 profile requires. When false, payload bytes are embedded base64 in
    /// the Body (asx's non-MIME test mode).
    detached_payload_reference: bool,
    payload_mime_type: String,
    /// `CompressionType` part property, set when the payload attachment is a
    /// compressed stream (AS4 profile §3.1).
    payload_compression_type: Option<String>,
    payload_content_id: String,
    /// Additional `eb:PartInfo` entries for a multi-payload UserMessage:
    /// `(content_id, mime_type, compression_type)`.
    extra_part_infos: Vec<(String, String, Option<String>)>,
    ws_security_header: Option<String>,
    /// Emit [`WSSE_HEADER_PLACEHOLDER`] where the security header will go.
    ws_security_placeholder: bool,
    /// Optional WS-Addressing headers to include in the SOAP Header.
    ws_addressing: Option<WsAddressingHeaders>,
}

pub(crate) const MESSAGE_ID_WSU_ID: &str = "as4-message-id";
pub(crate) const SOAP_BODY_WSU_ID: &str = "as4-body";
/// `wsu:Id` placed on the `<ebms:Messaging>` header block so the **entire**
/// ebMS3 UserMessage (party info, service/action, message properties, payload
/// info) is covered by the WS-Security signature — not just the MessageId.
/// Signing only MessageId leaves the routing/authorization metadata tamperable.
pub(crate) const MESSAGING_WSU_ID: &str = "as4-messaging";

/// ebMS3 Core §5.2.2.3/§5.2.2.9: the default party role when a business
/// process defines no specific roles. `eb:Role` itself is REQUIRED — an
/// envelope without it violates the ebMS3 schema and strict receivers
/// (Holodeck B2B, Domibus in strict-validation mode) reject it.
pub const EBMS_DEFAULT_ROLE: &str =
    "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/defaultRole";
/// The ebCore "unregistered" party-id scheme — the `type` value eDelivery/CEF
/// conformance setups use for party identifiers outside a registered scheme.
pub const EBCORE_PARTY_ID_TYPE_UNREGISTERED: &str =
    "urn:oasis:names:tc:ebcore:partyid-type:unregistered";

impl SoapEnvelopeBuilder {
    /// Create a new builder.
    ///
    /// * `from_party_id` — the sender's own party identifier (ebMS3 `From/PartyId`).
    /// * `to_party_id`   — the recipient's party identifier (ebMS3 `To/PartyId`).
    pub fn new(
        message_id: impl Into<String>,
        from_party_id: impl Into<String>,
        to_party_id: impl Into<String>,
    ) -> Self {
        Self {
            message_id: message_id.into(),
            message_timestamp: None,
            from_party_id: from_party_id.into(),
            to_party_id: to_party_id.into(),
            from_party_id_type: Some(EBCORE_PARTY_ID_TYPE_UNREGISTERED.into()),
            to_party_id_type: Some(EBCORE_PARTY_ID_TYPE_UNREGISTERED.into()),
            from_role: EBMS_DEFAULT_ROLE.into(),
            to_role: EBMS_DEFAULT_ROLE.into(),
            agreement_ref: None,
            agreement_ref_type: None,
            action: "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/action".into(),
            service: "http://example.org/example".into(),
            service_type: "example".into(),
            mpc: None,
            conversation_id: None,
            ref_to_message_id: None,
            original_sender: String::new(),
            final_recipient: String::new(),
            tracking_identifier: String::new(),
            payload: Vec::new(),
            detached_payload_reference: false,
            payload_mime_type: "application/octet-stream".into(),
            payload_compression_type: None,
            payload_content_id: "payload@example.org".into(),
            extra_part_infos: Vec::new(),
            ws_security_header: None,
            ws_security_placeholder: false,
            ws_addressing: None,
        }
        .with_default_four_corner_properties()
    }

    fn with_default_four_corner_properties(mut self) -> Self {
        self.original_sender = self.from_party_id.clone();
        self.final_recipient = self.to_party_id.clone();
        self.tracking_identifier = self.message_id.clone();
        self
    }

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

    /// Set the ebMS3 `<eb:Service>` value and `type` attribute.
    ///
    /// Both `service` (the element text) and `service_type` (the `type` attribute)
    /// must be agreed with the trading partner.  Pass an empty string for
    /// `service_type` to omit the attribute.
    pub fn with_service(
        mut self,
        service: impl Into<String>,
        service_type: impl Into<String>,
    ) -> Self {
        self.service = service.into();
        self.service_type = service_type.into();
        self
    }

    /// Set `<eb:RefToMessageId>` for the **Two-Way/Push-and-Push MEP**.
    ///
    /// When set, the outbound `<eb:MessageInfo>` includes
    /// `<eb:RefToMessageId>id</eb:RefToMessageId>` which correlates this
    /// response UserMessage to the original request per ebMS3 §5.2.2.5.
    pub fn with_ref_to_message_id(mut self, id: impl Into<String>) -> Self {
        self.ref_to_message_id = Some(id.into());
        self
    }

    /// Set Four Corner topology MessageProperties.
    ///
    /// Emits `originalSender`, `finalRecipient`, and `trackingIdentifier`
    /// under `<ebms:MessageProperties>`.
    pub fn with_four_corner_properties(
        mut self,
        original_sender: impl Into<String>,
        final_recipient: impl Into<String>,
        tracking_identifier: impl Into<String>,
    ) -> Self {
        self.original_sender = original_sender.into();
        self.final_recipient = final_recipient.into();
        self.tracking_identifier = tracking_identifier.into();
        self
    }

    /// AS4 SwA packaging: emit `eb:PayloadInfo/eb:PartInfo` referencing the
    /// detached MIME attachment and leave the SOAP Body empty. Combine with
    /// [`Self::with_payload_content_id`] and [`Self::with_payload_mime_type`].
    pub fn with_detached_payload_reference(mut self) -> Self {
        self.detached_payload_reference = true;
        self
    }

    /// Additional `eb:PartInfo` entries after the primary:
    /// `(content_id, mime_type, compression_type)` per part.
    pub fn with_extra_part_infos(mut self, parts: Vec<(String, String, Option<String>)>) -> Self {
        self.extra_part_infos = parts;
        self
    }

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

    /// Set the `type` attribute of the From/To `<eb:PartyId>` elements.
    ///
    /// `None` omits the attribute entirely (an *untyped* party identifier —
    /// what Holodeck B2B's example P-Modes use). The default is the ebCore
    /// "unregistered" scheme, which eDelivery/CEF setups expect. The value
    /// must match the counterparty's P-Mode exactly: a typed and an untyped
    /// identifier with the same text do **not** match.
    pub fn with_party_id_types(
        mut self,
        from_type: Option<String>,
        to_type: Option<String>,
    ) -> Self {
        self.from_party_id_type = from_type;
        self.to_party_id_type = to_type;
        self
    }

    /// Set the mandatory `<eb:Role>` values for From and To.
    ///
    /// Defaults to the ebMS3 default role URI for both parties. Business
    /// processes with named roles (e.g. Holodeck's example "Sender"/"Receiver")
    /// must set the values their counterparty's P-Mode declares.
    pub fn with_roles(mut self, from_role: impl Into<String>, to_role: impl Into<String>) -> Self {
        self.from_role = from_role.into();
        self.to_role = to_role.into();
        self
    }

    /// Emit an `<eb:AgreementRef>` (with optional `type` attribute) as the
    /// first child of `<eb:CollaborationInfo>`, per the ebMS3 schema order.
    pub fn with_agreement_ref(
        mut self,
        agreement: impl Into<String>,
        agreement_type: Option<String>,
    ) -> Self {
        self.agreement_ref = Some(agreement.into());
        self.agreement_ref_type = agreement_type;
        self
    }

    /// Pin `eb:MessageInfo/eb:Timestamp`. **Required** — [`build`](Self::build)
    /// fails without it.
    ///
    /// `eb:Timestamp` is inside the signed `eb:Messaging` block, and the AS4
    /// send path builds the envelope twice for one message: once unsigned, to
    /// digest that block, and once with the `wsse:Security` header. If each
    /// build read the clock, the two would disagree whenever they straddled a
    /// second — roughly one send in a thousand — and the envelope that shipped
    /// would not be the one that was signed. Nobody could verify it, and it
    /// would look like a flaky partner.
    ///
    /// Making this an input rather than an ambient read is what turns that from
    /// unlikely into impossible.
    #[must_use]
    pub fn with_message_timestamp(mut self, timestamp: impl Into<String>) -> Self {
        self.message_timestamp = Some(timestamp.into());
        self
    }

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

    pub fn with_payload(mut self, payload: Vec<u8>) -> Self {
        self.payload = payload;
        self
    }

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

    /// Declare that the payload attachment is compressed.
    ///
    /// `compression_type` is the media type of the compression applied
    /// (`application/gzip` for AS4). Per the AS4 profile the `MimeType`
    /// property must continue to describe the *uncompressed* payload, so set
    /// [`with_payload_mime_type`](Self::with_payload_mime_type) to the original
    /// business media type.
    pub fn with_payload_compression_type(mut self, compression_type: impl Into<String>) -> Self {
        self.payload_compression_type = Some(compression_type.into());
        self
    }

    /// Set MIME Content-ID used by `<ebms:PartInfo href="cid:...">`.
    pub fn with_payload_content_id(mut self, payload_content_id: impl Into<String>) -> Self {
        self.payload_content_id = payload_content_id.into();
        self
    }

    /// Reserve the `wsse:Security` slot with [`WSSE_HEADER_PLACEHOLDER`] instead
    /// of supplying the header now.
    ///
    /// Sign the resulting envelope, then splice the finished header in with
    /// [`splice_ws_security_header`]. The signature covers the `eb:Messaging`
    /// and `soap:Body` subtrees, and the placeholder sits in neither, so the
    /// splice cannot change a digest — whereas rebuilding the envelope can, and
    /// did.
    #[must_use]
    pub fn with_ws_security_placeholder(mut self) -> Self {
        self.ws_security_placeholder = true;
        self
    }

    pub fn with_ws_security_header(mut self, header_xml: impl Into<String>) -> Self {
        self.ws_security_header = Some(header_xml.into());
        self
    }

    /// Attach WS-Addressing 1.0 headers to the SOAP envelope.
    ///
    /// When set, the SOAP Header will include `<wsa:MessageID>`,
    /// `<wsa:Action>`, `<wsa:To>`, and (if provided) `<wsa:ReplyTo>` using
    /// the WS-Addressing 1.0 namespace
    /// `http://www.w3.org/2005/08/addressing`.
    ///
    /// Required for deployments that use WS-Addressing for message correlation
    /// or routing via SOAP intermediaries.
    pub fn with_ws_addressing(mut self, headers: WsAddressingHeaders) -> Self {
        self.ws_addressing = Some(headers);
        self
    }

    /// Build a SOAP envelope with ebMS3 UserMessage
    pub fn build(self) -> Result<Vec<u8>> {
        let mut xml = String::new();

        // XML declaration
        xml.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");

        // SOAP Envelope — conditionally include WSA namespace declaration.
        if self.ws_addressing.is_some() {
            xml.push_str(&format!(
                "<soap:Envelope xmlns:soap=\"{}\" xmlns:ebms=\"{}\" xmlns:wsse=\"{}\" xmlns:wsu=\"{}\" xmlns:wsa=\"{}\">\n",
                SOAP12_NAMESPACE, EBMS_NAMESPACE, WSSE_NAMESPACE, WSSEC_UTILITY_NAMESPACE, WSA_NAMESPACE
            ));
        } else {
            xml.push_str(&format!(
                "<soap:Envelope xmlns:soap=\"{}\" xmlns:ebms=\"{}\" xmlns:wsse=\"{}\" xmlns:wsu=\"{}\">\n",
                SOAP12_NAMESPACE, EBMS_NAMESPACE, WSSE_NAMESPACE, WSSEC_UTILITY_NAMESPACE
            ));
        }

        // SOAP Header
        xml.push_str("  <soap:Header>\n");

        // WS-Addressing headers (optional, must appear before ebMS3 Messaging).
        if let Some(wsa) = &self.ws_addressing {
            xml.push_str(&format!(
                "    <wsa:MessageID>{}</wsa:MessageID>\n",
                escape_xml(&wsa.message_id)
            ));
            xml.push_str(&format!(
                "    <wsa:Action soap:mustUnderstand=\"{}\">{}</wsa:Action>\n",
                "true",
                escape_xml(&wsa.action)
            ));
            xml.push_str(&format!("    <wsa:To>{}</wsa:To>\n", escape_xml(&wsa.to)));
            if let Some(reply_to) = &wsa.reply_to {
                xml.push_str(&format!(
                    "    <wsa:ReplyTo><wsa:Address>{}</wsa:Address></wsa:ReplyTo>\n",
                    escape_xml(reply_to)
                ));
            }
        }

        // ebMS3 Messaging/UserMessage is expected under SOAP Header.
        // The wsu:Id makes the whole block referenceable so the signature covers
        // all UserMessage routing/authorization metadata (eDelivery AS4 profile).
        xml.push_str(&format!(
            "    <ebms:Messaging soap:mustUnderstand=\"true\" wsu:Id=\"{MESSAGING_WSU_ID}\">\n"
        ));
        if let Some(mpc) = &self.mpc {
            xml.push_str(&format!(
                "      <ebms:UserMessage mpc=\"{}\">\n",
                escape_xml(mpc)
            ));
        } else {
            xml.push_str("      <ebms:UserMessage>\n");
        }

        // MessageInfo
        xml.push_str("        <ebms:MessageInfo>\n");
        // Required, not defaulted. `eb:Timestamp` sits inside the signed
        // `eb:Messaging` block and the AS4 send path builds the envelope twice
        // — reading the clock here made the two builds disagree whenever they
        // straddled a second, shipping an envelope its own signature did not
        // cover. Refusing is the only way to keep that unrepresentable rather
        // than merely unlikely.
        let Some(message_timestamp) = self.message_timestamp.as_deref() else {
            return Err(crate::core::AsxError::new(
                crate::core::ErrorCode::InvalidInput,
                "SoapEnvelopeBuilder requires an eb:Timestamp pinned with \
                 with_message_timestamp(..); reading the clock inside build() lets two \
                 builds of the same message disagree and ship an envelope its own \
                 signature does not cover",
                crate::core::ErrorContext::new("as4_soap_builder"),
            ));
        };
        xml.push_str(&format!(
            "          <ebms:Timestamp>{message_timestamp}</ebms:Timestamp>\n"
        ));
        xml.push_str(&format!(
            "          <ebms:MessageId wsu:Id=\"{}\">{}</ebms:MessageId>\n",
            MESSAGE_ID_WSU_ID,
            escape_xml(&self.message_id)
        ));
        // Two-Way MEP: emit RefToMessageId when correlating a response to a request.
        if let Some(ref_id) = &self.ref_to_message_id {
            xml.push_str(&format!(
                "          <ebms:RefToMessageId>{}</ebms:RefToMessageId>\n",
                escape_xml(ref_id)
            ));
        }
        xml.push_str("        </ebms:MessageInfo>\n");

        // PartyInfo — From and To use independent party identifiers. Each
        // party carries the schema-mandatory eb:Role (ebMS3 Core §5.2.2.3).
        let party_id_xml = |id: &str, id_type: &Option<String>| -> String {
            match id_type {
                Some(t) => format!(
                    "            <ebms:PartyId type=\"{}\">{}</ebms:PartyId>\n",
                    escape_xml(t),
                    escape_xml(id)
                ),
                None => format!(
                    "            <ebms:PartyId>{}</ebms:PartyId>\n",
                    escape_xml(id)
                ),
            }
        };
        xml.push_str("        <ebms:PartyInfo>\n");
        xml.push_str("          <ebms:From>\n");
        xml.push_str(&party_id_xml(&self.from_party_id, &self.from_party_id_type));
        xml.push_str(&format!(
            "            <ebms:Role>{}</ebms:Role>\n",
            escape_xml(&self.from_role)
        ));
        xml.push_str("          </ebms:From>\n");
        xml.push_str("          <ebms:To>\n");
        xml.push_str(&party_id_xml(&self.to_party_id, &self.to_party_id_type));
        xml.push_str(&format!(
            "            <ebms:Role>{}</ebms:Role>\n",
            escape_xml(&self.to_role)
        ));
        xml.push_str("          </ebms:To>\n");
        xml.push_str("        </ebms:PartyInfo>\n");

        // CollaborationInfo — schema order: AgreementRef?, Service, Action,
        // ConversationId (ebMS3 Core §5.2.2.6).
        xml.push_str("        <ebms:CollaborationInfo>\n");
        if let Some(agreement) = &self.agreement_ref {
            match &self.agreement_ref_type {
                Some(t) => xml.push_str(&format!(
                    "          <ebms:AgreementRef type=\"{}\">{}</ebms:AgreementRef>\n",
                    escape_xml(t),
                    escape_xml(agreement)
                )),
                None => xml.push_str(&format!(
                    "          <ebms:AgreementRef>{}</ebms:AgreementRef>\n",
                    escape_xml(agreement)
                )),
            }
        }
        if self.service_type.is_empty() {
            xml.push_str(&format!(
                "          <ebms:Service>{}</ebms:Service>\n",
                escape_xml(&self.service)
            ));
        } else {
            xml.push_str(&format!(
                "          <ebms:Service type=\"{}\">{}</ebms:Service>\n",
                escape_xml(&self.service_type),
                escape_xml(&self.service)
            ));
        }
        xml.push_str(&format!(
            "          <ebms:Action>{}</ebms:Action>\n",
            escape_xml(&self.action)
        ));
        // ConversationId is REQUIRED by the ebMS3 schema (minOccurs=1).
        // Previously it was omitted when unset, producing a schema-invalid
        // envelope. The Peppol AS4 profile's convention for "no conversation
        // semantics" is the literal "1", which also avoids leaking a
        // correlatable identifier.
        let conversation_id = self.conversation_id.as_deref().unwrap_or("1");
        xml.push_str(&format!(
            "          <ebms:ConversationId>{}</ebms:ConversationId>\n",
            escape_xml(conversation_id)
        ));
        xml.push_str("        </ebms:CollaborationInfo>\n");

        // MessageProperties — Four Corner topology routing metadata.
        xml.push_str("        <ebms:MessageProperties>\n");
        xml.push_str(&format!(
            "          <ebms:Property name=\"originalSender\" value=\"{}\"/>\n",
            escape_xml(&self.original_sender)
        ));
        xml.push_str(&format!(
            "          <ebms:Property name=\"finalRecipient\" value=\"{}\"/>\n",
            escape_xml(&self.final_recipient)
        ));
        xml.push_str(&format!(
            "          <ebms:Property name=\"trackingIdentifier\" value=\"{}\"/>\n",
            escape_xml(&self.tracking_identifier)
        ));
        xml.push_str("        </ebms:MessageProperties>\n");

        if !self.payload.is_empty() || self.detached_payload_reference {
            xml.push_str("        <ebms:PayloadInfo>\n");
            xml.push_str(&format!(
                "          <ebms:PartInfo href=\"cid:{}\">\n",
                escape_xml(&self.payload_content_id)
            ));
            xml.push_str("            <ebms:Properties>\n");
            xml.push_str(&format!(
                "              <ebms:Property name=\"MimeType\" value=\"{}\"/>\n",
                escape_xml(&self.payload_mime_type)
            ));
            // AS4 profile §3.1 (Compression): a compressed payload MUST be
            // advertised with a `CompressionType` part property, and `MimeType`
            // MUST describe the payload *before* compression. Without this the
            // receiver has no conformant way to know it should decompress, and
            // the original media type is lost entirely.
            if let Some(compression_type) = &self.payload_compression_type {
                xml.push_str(&format!(
                    "              <ebms:Property name=\"CompressionType\" value=\"{}\"/>\n",
                    escape_xml(compression_type)
                ));
            }
            xml.push_str("            </ebms:Properties>\n");
            xml.push_str("          </ebms:PartInfo>\n");
            for (content_id, mime_type, compression_type) in &self.extra_part_infos {
                xml.push_str(&format!(
                    "          <ebms:PartInfo href=\"cid:{}\">\n",
                    escape_xml(content_id)
                ));
                xml.push_str("            <ebms:Properties>\n");
                xml.push_str(&format!(
                    "              <ebms:Property name=\"MimeType\" value=\"{}\"/>\n",
                    escape_xml(mime_type)
                ));
                if let Some(compression_type) = compression_type {
                    xml.push_str(&format!(
                        "              <ebms:Property name=\"CompressionType\" value=\"{}\"/>\n",
                        escape_xml(compression_type)
                    ));
                }
                xml.push_str("            </ebms:Properties>\n");
                xml.push_str("          </ebms:PartInfo>\n");
            }
            xml.push_str("        </ebms:PayloadInfo>\n");
        }

        xml.push_str("      </ebms:UserMessage>\n");
        xml.push_str("    </ebms:Messaging>\n");

        if let Some(wsse) = &self.ws_security_header {
            xml.push_str(wsse);
        } else if self.ws_security_placeholder {
            xml.push_str(WSSE_HEADER_PLACEHOLDER);
            xml.push('\n');
        }

        xml.push_str("  </soap:Header>\n");

        // SOAP Body. With SwA packaging (`detached_payload_reference`) the Body
        // is EMPTY per the AS4 profile — payloads travel as MIME parts
        // referenced from the signed `eb:PartInfo` header. An MTOM-style
        // `xop:Include` in the Body is exactly what makes WSS4J-based
        // receivers (Holodeck B2B, phase4, Domibus) fail DOM conversion.
        xml.push_str(&format!("  <soap:Body wsu:Id=\"{}\">\n", SOAP_BODY_WSU_ID));

        // Payload bytes are carried in SOAP body as base64 to keep XML valid
        // (non-MIME test mode only).
        if !self.payload.is_empty() && !self.detached_payload_reference {
            xml.push_str("    <asx:Payload xmlns:asx=\"urn:asx:payload\">\n");
            xml.push_str(&format!(
                "      <asx:MimeType>{}</asx:MimeType>\n",
                escape_xml(&self.payload_mime_type)
            ));
            xml.push_str(&format!(
                "      <asx:Base64>{}</asx:Base64>\n",
                STANDARD.encode(&self.payload)
            ));
            xml.push_str("    </asx:Payload>\n");
        }
        xml.push_str("  </soap:Body>\n");
        xml.push_str("</soap:Envelope>\n");

        Ok(xml.into_bytes())
    }
}

fn escape_xml(s: &str) -> String {
    s.chars()
        .map(|c| match c {
            '<' => "&lt;".to_string(),
            '>' => "&gt;".to_string(),
            '&' => "&amp;".to_string(),
            '"' => "&quot;".to_string(),
            '\'' => "&apos;".to_string(),
            c => c.to_string(),
        })
        .collect()
}

/// Encode `cert_der` as a minimal DER `SEQUENCE { Certificate }` suitable for
/// embedding in a `wsse:BinarySecurityToken` with `ValueType="...#X509PKIPathv1"`.
///
/// RFC 3820 defines PKIPath as `SEQUENCE SIZE (1..MAX) OF Certificate`.  For
/// single-certificate chains — the typical case for asx-rs — this is a SEQUENCE
/// wrapping exactly one DER-encoded certificate.
pub fn build_pkipath_der(cert_der: &[u8]) -> Vec<u8> {
    let len = cert_der.len();
    let mut result = vec![0x30u8]; // SEQUENCE tag
    if len < 128 {
        result.push(len as u8);
    } else if len < 0x100 {
        result.extend_from_slice(&[0x81, len as u8]);
    } else if len < 0x1_0000 {
        result.extend_from_slice(&[0x82, (len >> 8) as u8, len as u8]);
    } else {
        result.extend_from_slice(&[0x83, (len >> 16) as u8, (len >> 8) as u8, len as u8]);
    }
    result.extend_from_slice(cert_der);
    result
}

/// WS-Security header builder for X.509 certificate-based signing
#[derive(Debug, Clone)]
pub struct WsSecurityHeaderBuilder {
    signing_cert_pem: Option<Vec<u8>>,
    /// When `Some`, emits a `wsse:BinarySecurityToken` with
    /// `ValueType="...#X509PKIPathv1"` instead of `#X509v3`.
    /// The value is the base64-encoded DER-encoded PKIPath (SEQUENCE OF Certificate).
    signing_cert_pkipath_der: Option<Vec<u8>>,
    include_signature_placeholder: bool,
    signature_xml: Option<String>,
}

impl Default for WsSecurityHeaderBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl WsSecurityHeaderBuilder {
    pub fn new() -> Self {
        Self {
            signing_cert_pem: None,
            signing_cert_pkipath_der: None,
            include_signature_placeholder: false,
            signature_xml: None,
        }
    }

    pub fn with_signing_cert(mut self, cert_pem: Vec<u8>) -> Self {
        self.signing_cert_pem = Some(cert_pem);
        self
    }

    /// Emit a `wsse:BinarySecurityToken` with
    /// `ValueType="...#X509PKIPathv1"` carrying a DER-encoded PKIPath
    /// (`SEQUENCE { Certificate }`).
    ///
    /// Used together with [`WsSecOutboundKeyInfoProfile::X509PKIPathv1`](crate::crypto::wssec::WsSecOutboundKeyInfoProfile::X509PKIPathv1) so
    /// that the `ds:KeyInfo` `<wsse:SecurityTokenReference>` in the signature
    /// references this BST by `wsu:Id="X509PKIPathToken"`.
    ///
    /// Build the PKIPath bytes from a single DER certificate:
    /// ```ignore
    /// let cert_der = signing_cert_ref.to_der()?;
    /// let pkipath = build_pkipath_der(&cert_der);
    /// builder = builder.with_signing_cert_pkipath_der(pkipath);
    /// ```
    pub fn with_signing_cert_pkipath_der(mut self, pkipath_der: Vec<u8>) -> Self {
        self.signing_cert_pkipath_der = Some(pkipath_der);
        self
    }

    pub fn with_signature_placeholder(mut self, enabled: bool) -> Self {
        self.include_signature_placeholder = enabled;
        self
    }

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

    /// Build WS-Security header XML.
    /// Includes a `wsu:Timestamp` (5-minute window) as required by WS-Security 1.1.1 and
    /// the eDelivery AS4 profile.
    pub fn build(self) -> Result<Vec<u8>> {
        let now = std::time::SystemTime::now();
        let created = crate::time_utils::format_rfc3339_secs(now);
        let expires =
            crate::time_utils::format_rfc3339_secs(now + std::time::Duration::from_secs(300));

        let mut xml = String::new();

        xml.push_str("    <wsse:Security soap:mustUnderstand=\"true\" xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\">\n");

        // wsu:Timestamp is REQUIRED by WS-Security 1.1.1 and eDelivery AS4 v1.15 §5.1.7
        xml.push_str(&format!(
            "      <wsu:Timestamp wsu:Id=\"Timestamp\">\n        <wsu:Created>{created}</wsu:Created>\n        <wsu:Expires>{expires}</wsu:Expires>\n      </wsu:Timestamp>\n"
        ));

        if let Some(cert_pem) = self.signing_cert_pem {
            // The BST carries base64(DER). Encoding the PEM text instead
            // produces a token no consumer can parse — invisible while KeyInfo
            // embedded the certificate inline, and an immediate
            // UNSUPPORTED_SECURITY_TOKEN once KeyInfo references the BST.
            let cert_der = openssl::x509::X509::from_pem(&cert_pem)
                .and_then(|cert| cert.to_der())
                .map_err(|err| {
                    crate::core::AsxError::new(
                        crate::core::ErrorCode::ParseFailed,
                        format!("signing certificate PEM could not be converted to DER: {err}"),
                        crate::core::ErrorContext::new("wssec_header_builder"),
                    )
                })?;
            xml.push_str("      <wsse:BinarySecurityToken wsu:Id=\"X509Token\" EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\" ValueType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3\">\n");
            xml.push_str("        ");
            xml.push_str(&STANDARD.encode(cert_der));
            xml.push('\n');
            xml.push_str("      </wsse:BinarySecurityToken>\n");
        }

        if let Some(pkipath_der) = self.signing_cert_pkipath_der {
            xml.push_str("      <wsse:BinarySecurityToken wsu:Id=\"X509PKIPathToken\" \
                EncodingType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary\" \
                ValueType=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509PKIPathv1\">\n");
            xml.push_str("        ");
            xml.push_str(&STANDARD.encode(pkipath_der));
            xml.push('\n');
            xml.push_str("      </wsse:BinarySecurityToken>\n");
        }

        if let Some(signature_xml) = self.signature_xml {
            xml.push_str(&signature_xml);
            if !signature_xml.ends_with('\n') {
                xml.push('\n');
            }
        } else if self.include_signature_placeholder {
            xml.push_str("      <ds:Signature xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\n");
            xml.push_str("        <!-- XMLDSig signature will be inserted here -->\n");
            xml.push_str("      </ds:Signature>\n");
        }

        xml.push_str("    </wsse:Security>\n");

        Ok(xml.into_bytes())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn soap_envelope_builder_generates_valid_xml() {
        let builder =
            SoapEnvelopeBuilder::new("msg-123", "sender@example.org", "receiver@example.com")
                .with_message_timestamp("2026-09-06T12:00:00Z")
                .with_action("urn:example:action")
                .with_conversation_id("conv-456");

        let envelope = builder.build().expect("build");
        let envelope_str = String::from_utf8(envelope).expect("utf8");

        assert!(envelope_str.contains("<?xml version"));
        assert!(envelope_str.contains("soap:Envelope"));
        assert!(envelope_str.contains("<ebms:Messaging"));
        assert!(envelope_str.contains("ebms:UserMessage"));
        assert!(envelope_str.contains("msg-123"));
        assert!(envelope_str.contains("sender@example.org"));
        assert!(envelope_str.contains("receiver@example.com"));
        assert!(envelope_str.contains("conv-456"));
        assert!(envelope_str.contains("name=\"trackingIdentifier\" value=\"msg-123\""));
        // From and To must differ
        assert_ne!(
            envelope_str.find("sender@example.org"),
            envelope_str
                .rfind("sender@example.org")
                .filter(|_| envelope_str.contains("receiver@example.com")),
        );
    }

    /// ebMS3 schema conformance of PartyInfo/CollaborationInfo:
    /// mandatory eb:Role on both parties, optional PartyId type attribute,
    /// AgreementRef ordered before Service, and an always-present
    /// ConversationId (defaulting to "1", the Peppol convention).
    #[test]
    fn soap_envelope_emits_schema_mandatory_party_and_collaboration_elements() {
        // Defaults: unregistered party-id type, ebMS3 default role, conv "1".
        let default_envelope = String::from_utf8(
            SoapEnvelopeBuilder::new("m-1", "pa", "pb")
                .with_message_timestamp("2026-09-06T12:00:00Z")
                .build()
                .expect("build"),
        )
        .expect("utf8");
        assert!(default_envelope.contains(
            "<ebms:PartyId type=\"urn:oasis:names:tc:ebcore:partyid-type:unregistered\">pa</ebms:PartyId>"
        ));
        assert_eq!(
            default_envelope
                .matches(&format!("<ebms:Role>{EBMS_DEFAULT_ROLE}</ebms:Role>"))
                .count(),
            2,
            "both From and To must carry the mandatory eb:Role: {default_envelope}"
        );
        assert!(
            default_envelope.contains("<ebms:ConversationId>1</ebms:ConversationId>"),
            "ConversationId is schema-mandatory and must default to \"1\": {default_envelope}"
        );

        // Explicit overrides: untyped party ids, named roles, agreement ref.
        let envelope = String::from_utf8(
            SoapEnvelopeBuilder::new("m-2", "org:example:company:A", "org:example:company:B")
                .with_message_timestamp("2026-09-06T12:00:00Z")
                .with_party_id_types(None, None)
                .with_roles("Sender", "Receiver")
                .with_agreement_ref("http://agreements.example.org/a0", None)
                .build()
                .expect("build"),
        )
        .expect("utf8");
        assert!(envelope.contains("<ebms:PartyId>org:example:company:A</ebms:PartyId>"));
        assert!(envelope.contains("<ebms:Role>Sender</ebms:Role>"));
        assert!(envelope.contains("<ebms:Role>Receiver</ebms:Role>"));
        let agreement_pos = envelope
            .find("<ebms:AgreementRef>http://agreements.example.org/a0</ebms:AgreementRef>")
            .expect("AgreementRef present");
        let service_pos = envelope.find("<ebms:Service").expect("Service present");
        assert!(
            agreement_pos < service_pos,
            "schema order: AgreementRef must precede Service"
        );
    }

    #[test]
    fn soap_envelope_builder_allows_overriding_four_corner_properties() {
        let builder = SoapEnvelopeBuilder::new("msg-abc", "ap-sender", "ap-receiver")
            .with_message_timestamp("2026-09-06T12:00:00Z")
            .with_four_corner_properties("participant-a", "participant-b", "track-789");

        let envelope = builder.build().expect("build");
        let envelope_str = String::from_utf8(envelope).expect("utf8");

        assert!(envelope_str.contains("name=\"originalSender\" value=\"participant-a\""));
        assert!(envelope_str.contains("name=\"finalRecipient\" value=\"participant-b\""));
        assert!(envelope_str.contains("name=\"trackingIdentifier\" value=\"track-789\""));
    }

    #[test]
    fn soap_envelope_escapes_xml_characters() {
        let builder =
            SoapEnvelopeBuilder::new("msg-<test>", "sender@example.org", "receiver@example.com")
                .with_message_timestamp("2026-09-06T12:00:00Z");
        let envelope = builder.build().expect("build");
        let envelope_str = String::from_utf8(envelope).expect("utf8");

        assert!(envelope_str.contains("msg-&lt;test&gt;"));
        assert!(!envelope_str.contains("msg-<test>"));
    }

    #[test]
    fn wssecurity_header_builds_valid_structure() {
        let builder = WsSecurityHeaderBuilder::new();
        let header = builder.build().expect("build");
        let header_str = String::from_utf8(header).expect("utf8");

        assert!(header_str.contains("wsse:Security"));
        assert!(header_str.contains("</wsse:Security>"));
        // wsu:Timestamp is required by WS-Security 1.1.1
        assert!(header_str.contains("wsu:Timestamp"));
        assert!(header_str.contains("wsu:Created"));
        assert!(header_str.contains("wsu:Expires"));
    }

    #[test]
    fn wssecurity_header_includes_certificate_structure_when_provided() {
        // A real certificate is required: the BST carries base64(DER), so the
        // builder converts the PEM — garbage input is now a build error
        // instead of a silently unparseable token.
        let rsa = openssl::rsa::Rsa::generate(2048).expect("rsa");
        let pkey = openssl::pkey::PKey::from_rsa(rsa).expect("pkey");
        let mut name = openssl::x509::X509NameBuilder::new().expect("name");
        name.append_entry_by_nid(openssl::nid::Nid::COMMONNAME, "bst-test")
            .expect("cn");
        let name = name.build();
        let mut cert = openssl::x509::X509::builder().expect("builder");
        cert.set_subject_name(&name).expect("subject");
        cert.set_issuer_name(&name).expect("issuer");
        cert.set_pubkey(&pkey).expect("pubkey");
        let not_before = openssl::asn1::Asn1Time::days_from_now(0).expect("nb");
        let not_after = openssl::asn1::Asn1Time::days_from_now(1).expect("na");
        cert.set_not_before(&not_before).expect("nb");
        cert.set_not_after(&not_after).expect("na");
        cert.sign(&pkey, openssl::hash::MessageDigest::sha256())
            .expect("sign");
        let cert = cert.build();
        let cert_pem = cert.to_pem().expect("pem");

        let builder = WsSecurityHeaderBuilder::new()
            .with_signing_cert(cert_pem)
            .with_signature_placeholder(true);
        let header = builder.build().expect("build");
        let header_str = String::from_utf8(header).expect("utf8");

        assert!(header_str.contains("wsse:BinarySecurityToken"));
        assert!(header_str.contains("ds:Signature"));
        // The token content must be base64(DER), not base64(PEM).
        let der_b64 = base64::Engine::encode(
            &base64::engine::general_purpose::STANDARD,
            cert.to_der().expect("der"),
        );
        assert!(
            header_str.contains(&der_b64),
            "BinarySecurityToken must carry base64(DER)"
        );
    }
}

#[cfg(test)]
mod timestamp_pinning_tests {
    use super::*;

    /// `eb:Timestamp` sits inside the signed `eb:Messaging` block, and the AS4
    /// A `build()` that read the clock itself would disagree with an earlier
    /// build of the same message whenever the two straddled a second, shipping
    /// an envelope that is not the one that was signed. Making the timestamp a
    /// *required input* turns that race into an error at the first build.
    #[test]
    fn build_refuses_without_a_pinned_timestamp() {
        let err = SoapEnvelopeBuilder::new("msg-1", "from", "to")
            .with_action("urn:example:action")
            .build()
            .expect_err("an unpinned timestamp must be an error, not a clock read");

        assert_eq!(err.code, crate::core::ErrorCode::InvalidInput);
        assert!(
            err.message.contains("with_message_timestamp"),
            "the error names the fix: {}",
            err.message
        );
    }

    /// Two builds of the same message must be byte-identical, because the
    /// second is what ships and the first is what was digested.
    #[test]
    fn two_builds_with_a_pinned_timestamp_agree() {
        let make = || {
            SoapEnvelopeBuilder::new("msg-1", "from", "to")
                .with_action("urn:example:action")
                .with_message_timestamp("2026-09-06T12:00:00Z")
                .build()
                .expect("build")
        };

        assert_eq!(
            make(),
            make(),
            "a pinned timestamp must make the build deterministic"
        );
    }

    /// The placeholder must sit outside both signed subtrees, so splicing the
    /// security header into it cannot change `eb:Messaging` or `soap:Body` —
    /// which is what makes one build plus a splice safe where two builds were
    /// not.
    #[test]
    fn splicing_the_security_header_leaves_the_signed_subtrees_untouched() {
        let envelope = SoapEnvelopeBuilder::new("msg-1", "from", "to")
            .with_action("urn:example:action")
            .with_message_timestamp("2026-09-06T12:00:00Z")
            .with_ws_security_placeholder()
            .build()
            .expect("build");
        let envelope = String::from_utf8(envelope).expect("utf8");

        let spliced = splice_ws_security_header(&envelope, "<wsse:Security/>").expect("splice");

        let messaging = |xml: &str| {
            let start = xml.find("<ebms:Messaging").expect("messaging");
            let end = xml.find("</ebms:Messaging>").expect("messaging end");
            xml[start..end].to_string()
        };
        let body = |xml: &str| {
            let start = xml.find("<soap:Body").expect("body");
            let end = xml.find("</soap:Body>").expect("body end");
            xml[start..end].to_string()
        };

        assert_eq!(messaging(&envelope), messaging(&spliced));
        assert_eq!(body(&envelope), body(&spliced));
        assert!(spliced.contains("<wsse:Security/>"));
        assert!(!spliced.contains(WSSE_HEADER_PLACEHOLDER));
    }

    /// The splice replaces a marker in generated XML, which is only safe if a
    /// miss is loud. Zero placeholders and two placeholders are both errors.
    #[test]
    fn splicing_requires_exactly_one_placeholder() {
        let without = SoapEnvelopeBuilder::new("msg-1", "from", "to")
            .with_action("urn:example:action")
            .with_message_timestamp("2026-09-06T12:00:00Z")
            .build()
            .expect("build");
        let without = String::from_utf8(without).expect("utf8");

        let err = splice_ws_security_header(&without, "<wsse:Security/>")
            .expect_err("no placeholder must be an error, not a no-op");
        assert_eq!(err.code, crate::core::ErrorCode::InvalidInput);

        let doubled = format!("{WSSE_HEADER_PLACEHOLDER}{WSSE_HEADER_PLACEHOLDER}");
        splice_ws_security_header(&doubled, "<wsse:Security/>")
            .expect_err("two placeholders are ambiguous");
    }

    /// The negative half: one second's difference changes the signed bytes,
    /// which is precisely why the pin has to exist — and proves the test above
    /// is testing something.
    #[test]
    fn a_timestamp_one_second_apart_changes_the_signed_bytes() {
        let make = |ts: &str| {
            SoapEnvelopeBuilder::new("msg-1", "from", "to")
                .with_action("urn:example:action")
                .with_message_timestamp(ts)
                .build()
                .expect("build")
        };

        assert_ne!(
            make("2026-09-06T12:00:00Z"),
            make("2026-09-06T12:00:01Z"),
            "eb:Timestamp is inside the signed eb:Messaging block"
        );
    }
}