soap-server 0.1.0

A WSDL-driven, spec-compliant SOAP 1.1/1.2 server library for Rust with WS-Security and ONVIF 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
//! SOAP fault types and serialization for SOAP 1.1 and 1.2.
use crate::xml_escape::escape_text;
use thiserror::Error;

#[derive(Debug, Clone, PartialEq)]
pub enum FaultCode {
    VersionMismatch,
    MustUnderstand,
    DataEncodingUnknown,
    Sender,
    Receiver,
}

impl FaultCode {
    /// Returns the SOAP 1.2 fault code string (e.g. `"env:Sender"`, `"env:Receiver"`).
    /// Use this when serializing SOAP 1.2 responses.
    pub fn as_soap12_str(&self) -> &'static str {
        match self {
            FaultCode::VersionMismatch => "env:VersionMismatch",
            FaultCode::MustUnderstand => "env:MustUnderstand",
            FaultCode::DataEncodingUnknown => "env:DataEncodingUnknown",
            FaultCode::Sender => "env:Sender",
            FaultCode::Receiver => "env:Receiver",
        }
    }

    /// Returns the SOAP 1.1 fault code string (e.g. `"env:Client"`, `"env:Server"`).
    /// Use this when serializing SOAP 1.1 responses.
    pub fn as_soap11_str(&self) -> &'static str {
        match self {
            FaultCode::VersionMismatch => "env:VersionMismatch",
            FaultCode::MustUnderstand => "env:MustUnderstand",
            // DataEncodingUnknown has no SOAP 1.1 equivalent — map to Server per Apache CXF
            FaultCode::DataEncodingUnknown => "env:Server",
            FaultCode::Sender => "env:Client",
            FaultCode::Receiver => "env:Server",
        }
    }
}

#[derive(Debug, Clone, Error)]
#[error("SOAP Fault: {code:?} — {reason}")]
pub struct SoapFault {
    pub code: FaultCode,
    pub reason: String,
    pub detail: Option<String>,
    /// Raw, verbatim XML to emit as the fault detail child element (not escaped).
    /// Takes precedence over `detail` when both are set.
    pub detail_xml: Option<String>,
}

impl SoapFault {
    pub fn new(code: FaultCode, reason: impl Into<String>, detail: Option<String>) -> Self {
        Self {
            code,
            reason: reason.into(),
            detail,
            detail_xml: None,
        }
    }

    /// Attach a raw XML child element as the fault detail. The provided XML is emitted
    /// VERBATIM inside `<env:Detail>` (SOAP 1.2) / `<detail>` (SOAP 1.1) — it is NOT escaped,
    /// so the caller MUST supply well-formed XML. Takes precedence over the text `detail`.
    pub fn with_detail_xml(mut self, xml: impl Into<String>) -> Self {
        self.detail_xml = Some(xml.into());
        self
    }

    pub fn sender(reason: impl Into<String>) -> Self {
        Self::new(FaultCode::Sender, reason, None)
    }

    pub fn receiver(reason: impl Into<String>) -> Self {
        Self::new(FaultCode::Receiver, reason, None)
    }

    pub fn version_mismatch() -> Self {
        Self::new(FaultCode::VersionMismatch, "SOAP version mismatch", None)
    }

    pub fn must_understand(header: &str) -> Self {
        Self::new(
            FaultCode::MustUnderstand,
            format!("Header not understood: {header}"),
            None,
        )
    }

    pub fn action_not_supported(action: &str) -> Self {
        Self::new(
            FaultCode::Sender,
            format!("Action not supported: {action}"),
            None,
        )
    }

    /// Serialize to a complete SOAP envelope. Version determines fault structure and code names.
    /// SOAP 1.2 uses nested Code/Reason (existing to_xml_bytes). SOAP 1.1 uses flat
    /// faultcode/faultstring per W3C SOAP 1.1 spec Section 4.4.
    pub fn to_xml_bytes_versioned(
        &self,
        version: &crate::wsdl::definitions::SoapVersion,
    ) -> Vec<u8> {
        match version {
            crate::wsdl::definitions::SoapVersion::Soap12 => self.to_xml_bytes(),
            crate::wsdl::definitions::SoapVersion::Soap11 => self.to_xml_bytes_v11(),
        }
    }

    fn to_xml_bytes_v11(&self) -> Vec<u8> {
        let ns = "http://schemas.xmlsoap.org/soap/envelope/";
        let faultcode = match &self.code {
            FaultCode::Sender => "SOAP-ENV:Client",
            FaultCode::Receiver => "SOAP-ENV:Server",
            FaultCode::VersionMismatch => "SOAP-ENV:VersionMismatch",
            FaultCode::MustUnderstand => "SOAP-ENV:MustUnderstand",
            // DataEncodingUnknown has no SOAP 1.1 equivalent — map to Server per Apache CXF
            FaultCode::DataEncodingUnknown => "SOAP-ENV:Server",
        };
        let reason = escape_text(&self.reason);
        let detail_xml = if let Some(raw) = &self.detail_xml {
            format!("<detail>{raw}</detail>")
        } else {
            match &self.detail {
                Some(detail) => format!("<detail>{}</detail>", escape_text(detail)),
                None => String::new(),
            }
        };
        format!(
            r#"<SOAP-ENV:Envelope xmlns:SOAP-ENV="{ns}"><SOAP-ENV:Body><SOAP-ENV:Fault><faultcode>{faultcode}</faultcode><faultstring>{reason}</faultstring>{detail_xml}</SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope>"#
        ).into_bytes()
    }

    /// Serialize to a complete SOAP 1.2 envelope XML string.
    /// HTTP status is always 500 per W3C SOAP 1.2 spec Section 7.4.2 (FLT-03).
    pub fn to_xml_bytes(&self) -> Vec<u8> {
        let code = self.code.as_soap12_str();
        let reason = escape_text(&self.reason);

        // SOAP 1.2 env:Detail is element-only (xs:any children; no character data).
        // The human-readable message is already in Reason/Text, so when only a
        // plain-text `detail` is set we emit nothing rather than invalid chardata (F-3).
        let detail_xml = if let Some(raw) = &self.detail_xml {
            format!("<env:Detail>{raw}</env:Detail>")
        } else {
            String::new()
        };

        let xml = format!(
            r#"<env:Envelope xmlns:env="http://www.w3.org/2003/05/soap-envelope"><env:Body><env:Fault><env:Code><env:Value>{code}</env:Value></env:Code><env:Reason><env:Text xml:lang="en">{reason}</env:Text></env:Reason>{detail_xml}</env:Fault></env:Body></env:Envelope>"#
        );

        xml.into_bytes()
    }
}

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

    #[test]
    fn fault_code_sender_as_soap12_str() {
        assert_eq!(FaultCode::Sender.as_soap12_str(), "env:Sender");
    }

    #[test]
    fn fault_code_receiver_as_soap12_str() {
        assert_eq!(FaultCode::Receiver.as_soap12_str(), "env:Receiver");
    }

    #[test]
    fn fault_code_version_mismatch_as_soap12_str() {
        assert_eq!(
            FaultCode::VersionMismatch.as_soap12_str(),
            "env:VersionMismatch"
        );
    }

    #[test]
    fn fault_code_must_understand_as_soap12_str() {
        assert_eq!(
            FaultCode::MustUnderstand.as_soap12_str(),
            "env:MustUnderstand"
        );
    }

    #[test]
    fn fault_code_data_encoding_unknown_as_soap12_str() {
        assert_eq!(
            FaultCode::DataEncodingUnknown.as_soap12_str(),
            "env:DataEncodingUnknown"
        );
    }

    #[test]
    fn fault_code_sender_as_soap11_str() {
        assert_eq!(FaultCode::Sender.as_soap11_str(), "env:Client");
    }

    #[test]
    fn fault_code_receiver_as_soap11_str() {
        assert_eq!(FaultCode::Receiver.as_soap11_str(), "env:Server");
    }

    #[test]
    fn fault_code_version_mismatch_as_soap11_str() {
        assert_eq!(
            FaultCode::VersionMismatch.as_soap11_str(),
            "env:VersionMismatch"
        );
    }

    #[test]
    fn fault_code_must_understand_as_soap11_str() {
        assert_eq!(
            FaultCode::MustUnderstand.as_soap11_str(),
            "env:MustUnderstand"
        );
    }

    #[test]
    fn fault_code_data_encoding_unknown_as_soap11_str() {
        // DataEncodingUnknown has no SOAP 1.1 equivalent — maps to env:Server
        assert_eq!(FaultCode::DataEncodingUnknown.as_soap11_str(), "env:Server");
    }

    #[test]
    fn serialize_sender_fault_contains_env_sender() {
        let fault = SoapFault::sender("Bad request");
        let xml = String::from_utf8(fault.to_xml_bytes()).unwrap();
        assert!(
            xml.contains("<env:Value>env:Sender</env:Value>"),
            "Expected env:Sender in XML, got: {xml}"
        );
    }

    #[test]
    fn serialize_receiver_fault_contains_env_receiver() {
        let fault = SoapFault::receiver("Internal error");
        let xml = String::from_utf8(fault.to_xml_bytes()).unwrap();
        assert!(
            xml.contains("<env:Value>env:Receiver</env:Value>"),
            "Expected env:Receiver in XML, got: {xml}"
        );
    }

    #[test]
    fn serialize_fault_wraps_in_soap12_envelope() {
        let fault = SoapFault::sender("test");
        let xml = String::from_utf8(fault.to_xml_bytes()).unwrap();
        assert!(
            xml.contains(r#"xmlns:env="http://www.w3.org/2003/05/soap-envelope""#),
            "Expected SOAP 1.2 namespace in XML, got: {xml}"
        );
        assert!(xml.starts_with("<env:Envelope"), "Expected envelope root");
        assert!(xml.contains("<env:Body>"), "Expected Body element");
        assert!(xml.contains("<env:Fault>"), "Expected Fault element");
    }

    #[test]
    fn serialize_fault_reason_included() {
        let fault = SoapFault::sender("Custom reason text");
        let xml = String::from_utf8(fault.to_xml_bytes()).unwrap();
        assert!(
            xml.contains("Custom reason text"),
            "Expected reason in XML, got: {xml}"
        );
        assert!(
            xml.contains(r#"<env:Text xml:lang="en">"#),
            "Expected Text element with lang"
        );
    }

    #[test]
    fn serialize_fault_no_detail_when_none() {
        let fault = SoapFault::sender("test");
        let xml = String::from_utf8(fault.to_xml_bytes()).unwrap();
        assert!(
            !xml.contains("<env:Detail>"),
            "Expected no Detail element when detail is None, got: {xml}"
        );
    }

    #[test]
    fn serialize_fault_with_detail() {
        // SOAP 1.2 env:Detail is element-only — a plain-text `detail` has no valid
        // place there (F-3). The reason is already in Reason/Text, so no env:Detail
        // is emitted. The reason string must still appear in the envelope.
        let fault = SoapFault::new(
            FaultCode::Receiver,
            "Internal error",
            Some("extra info".to_string()),
        );
        let xml = String::from_utf8(fault.to_xml_bytes()).unwrap();
        assert!(
            !xml.contains("<env:Detail>extra info</env:Detail>"),
            "SOAP 1.2 must not emit char-data in env:Detail (F-3): {xml}"
        );
        assert!(
            !xml.contains("<env:Detail>"),
            "No env:Detail at all for plain-text detail (F-3): {xml}"
        );
        assert!(
            xml.contains("Internal error"),
            "Reason must still be in Reason/Text: {xml}"
        );
    }

    #[test]
    fn version_mismatch_convenience() {
        let fault = SoapFault::version_mismatch();
        assert_eq!(fault.code, FaultCode::VersionMismatch);
        let xml = String::from_utf8(fault.to_xml_bytes()).unwrap();
        assert!(xml.contains("<env:Value>env:VersionMismatch</env:Value>"));
    }

    #[test]
    fn must_understand_convenience() {
        let fault = SoapFault::must_understand("MyHeader");
        assert_eq!(fault.code, FaultCode::MustUnderstand);
        let xml = String::from_utf8(fault.to_xml_bytes()).unwrap();
        assert!(xml.contains("<env:Value>env:MustUnderstand</env:Value>"));
        assert!(xml.contains("MyHeader"));
    }

    #[test]
    fn action_not_supported_is_sender_fault() {
        let fault = SoapFault::action_not_supported("urn:SomeAction");
        assert_eq!(fault.code, FaultCode::Sender);
        let xml = String::from_utf8(fault.to_xml_bytes()).unwrap();
        assert!(xml.contains("<env:Value>env:Sender</env:Value>"));
        assert!(xml.contains("urn:SomeAction"));
    }

    // ── SOAP 1.1 fault tests (TDD RED) ───────────────────────────────────────

    #[test]
    fn fault_soap11_structure() {
        let fault = SoapFault::sender("bad");
        let xml = String::from_utf8(fault.to_xml_bytes_v11()).unwrap();
        assert!(
            xml.contains("<faultcode>"),
            "Expected <faultcode>, got: {xml}"
        );
        assert!(
            xml.contains("<faultstring>"),
            "Expected <faultstring>, got: {xml}"
        );
        assert!(
            xml.contains("SOAP-ENV:Fault"),
            "Expected SOAP-ENV:Fault, got: {xml}"
        );
        assert!(
            !xml.contains("<env:Code>"),
            "Should NOT contain <env:Code>, got: {xml}"
        );
        assert!(
            !xml.contains("<env:Reason>"),
            "Should NOT contain <env:Reason>, got: {xml}"
        );
    }

    #[test]
    fn fault_soap11_namespace() {
        let fault = SoapFault::sender("bad");
        let xml = String::from_utf8(fault.to_xml_bytes_v11()).unwrap();
        assert!(
            xml.contains(r#"xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/""#),
            "Expected SOAP 1.1 namespace on Envelope, got: {xml}"
        );
    }

    #[test]
    fn fault_soap11_wraps_in_envelope() {
        let fault = SoapFault::sender("bad");
        let xml = String::from_utf8(fault.to_xml_bytes_v11()).unwrap();
        assert!(
            xml.starts_with("<SOAP-ENV:Envelope"),
            "Expected SOAP-ENV:Envelope root, got: {xml}"
        );
        assert!(
            xml.contains("<SOAP-ENV:Body>"),
            "Expected <SOAP-ENV:Body>, got: {xml}"
        );
    }

    #[test]
    fn fault_code_sender_maps_to_client() {
        let fault = SoapFault::sender("bad");
        let xml = String::from_utf8(fault.to_xml_bytes_v11()).unwrap();
        assert!(
            xml.contains("<faultcode>SOAP-ENV:Client</faultcode>"),
            "Expected SOAP-ENV:Client, got: {xml}"
        );
    }

    #[test]
    fn fault_code_receiver_maps_to_server() {
        let fault = SoapFault::receiver("internal");
        let xml = String::from_utf8(fault.to_xml_bytes_v11()).unwrap();
        assert!(
            xml.contains("<faultcode>SOAP-ENV:Server</faultcode>"),
            "Expected SOAP-ENV:Server, got: {xml}"
        );
    }

    #[test]
    fn fault_code_version_mismatch_soap11() {
        let fault = SoapFault::version_mismatch();
        let xml = String::from_utf8(fault.to_xml_bytes_v11()).unwrap();
        assert!(
            xml.contains("<faultcode>SOAP-ENV:VersionMismatch</faultcode>"),
            "Expected SOAP-ENV:VersionMismatch, got: {xml}"
        );
    }

    #[test]
    fn fault_code_must_understand_soap11() {
        let fault = SoapFault::must_understand("MyHeader");
        let xml = String::from_utf8(fault.to_xml_bytes_v11()).unwrap();
        assert!(
            xml.contains("<faultcode>SOAP-ENV:MustUnderstand</faultcode>"),
            "Expected SOAP-ENV:MustUnderstand, got: {xml}"
        );
    }

    #[test]
    fn fault_code_data_encoding_unknown_soap11() {
        let fault = SoapFault::new(FaultCode::DataEncodingUnknown, "enc error", None);
        let xml = String::from_utf8(fault.to_xml_bytes_v11()).unwrap();
        assert!(
            xml.contains("<faultcode>SOAP-ENV:Server</faultcode>"),
            "Expected SOAP-ENV:Server (no 1.1 equivalent for DataEncodingUnknown), got: {xml}"
        );
    }

    #[test]
    fn fault_soap11_with_detail() {
        let fault = SoapFault::new(
            FaultCode::Receiver,
            "Internal error",
            Some("extra info".to_string()),
        );
        let xml = String::from_utf8(fault.to_xml_bytes_v11()).unwrap();
        assert!(
            xml.contains("<detail>extra info</detail>"),
            "Expected <detail> element with content, got: {xml}"
        );
    }

    #[test]
    fn fault_soap11_no_detail_when_none() {
        let fault = SoapFault::sender("test");
        let xml = String::from_utf8(fault.to_xml_bytes_v11()).unwrap();
        assert!(
            !xml.contains("<detail>"),
            "Expected no <detail> when detail is None, got: {xml}"
        );
    }

    #[test]
    fn to_xml_bytes_versioned_soap12_calls_existing() {
        use crate::wsdl::definitions::SoapVersion;
        let fault = SoapFault::sender("test");
        let v12 = fault.to_xml_bytes_versioned(&SoapVersion::Soap12);
        let existing = fault.to_xml_bytes();
        assert_eq!(
            v12, existing,
            "Soap12 path should produce identical output to to_xml_bytes()"
        );
    }

    #[test]
    fn to_xml_bytes_versioned_soap11_calls_v11() {
        use crate::wsdl::definitions::SoapVersion;
        let fault = SoapFault::sender("test");
        let v11_versioned = fault.to_xml_bytes_versioned(&SoapVersion::Soap11);
        let v11_direct = fault.to_xml_bytes_v11();
        assert_eq!(
            v11_versioned, v11_direct,
            "Soap11 path should produce identical output to to_xml_bytes_v11()"
        );
    }

    // ── XML escaping tests (Finding #1) ──────────────────────────────────────

    /// Verify that reason and detail containing all five XML special characters
    /// (`& < > " '`) are properly escaped and the resulting document parses as
    /// well-formed XML.  Uses quick_xml to parse the envelope so any unescaped
    /// entity or unbound prefix would surface as a parse error.
    #[test]
    fn soap12_fault_special_chars_in_reason_and_detail_are_escaped() {
        use quick_xml::events::Event;
        use quick_xml::Reader;

        let special = r#"& < > " '"#;
        let fault = SoapFault::new(FaultCode::Sender, special, Some(special.to_string()));
        let xml_bytes = fault.to_xml_bytes();
        let xml_str = String::from_utf8(xml_bytes.clone()).unwrap();

        // The raw ampersand must NOT appear unescaped in the output.
        // We check that the literal "& " (ampersand-space) is absent — the namespace
        // URI http://... does not contain "& ", so any match is from the dynamic value.
        assert!(
            !xml_str.contains("& "),
            "Unescaped '& ' found in SOAP 1.2 fault XML: {xml_str}"
        );
        // The escaped forms must be present.
        assert!(xml_str.contains("&amp;"), "Expected &amp;: {xml_str}");
        assert!(xml_str.contains("&lt;"), "Expected &lt;: {xml_str}");
        assert!(xml_str.contains("&gt;"), "Expected &gt;: {xml_str}");
        assert!(xml_str.contains("&quot;"), "Expected &quot;: {xml_str}");
        assert!(xml_str.contains("&apos;"), "Expected &apos;: {xml_str}");

        // Parse with quick_xml to confirm the document is well-formed XML.
        // Any unescaped `<` or bare `&` would cause a parse error here (the
        // expect() would panic with an XML error rather than the assertions below).
        // Parse with quick_xml to confirm the document is well-formed XML.
        // A bare `&` or unescaped `<` would cause a parse error on the expect().
        let mut reader = Reader::from_str(&xml_str);
        reader.config_mut().trim_text(true);
        let mut buf = Vec::new();
        let mut event_count = 0usize;
        loop {
            let is_eof = {
                let ev = reader
                    .read_event_into(&mut buf)
                    .expect("XML must parse as well-formed");
                matches!(ev, Event::Eof)
            };
            buf.clear();
            if is_eof {
                break;
            }
            event_count += 1;
        }
        assert!(event_count > 0, "Expected at least one XML event");
    }

    // ── detail_xml (raw XML child) tests ────────────────────────────────────

    #[test]
    fn serialize_fault_with_raw_xml_detail_soap12() {
        let fault = SoapFault::sender("bad")
            .with_detail_xml(r#"<c:Info xmlns:c="urn:x"><c:Code>42</c:Code></c:Info>"#);
        let xml = String::from_utf8(fault.to_xml_bytes()).unwrap();
        // raw child present, NOT escaped:
        assert!(
            xml.contains(
                r#"<env:Detail><c:Info xmlns:c="urn:x"><c:Code>42</c:Code></c:Info></env:Detail>"#
            ),
            "got: {xml}"
        );
        assert!(
            !xml.contains("&lt;c:Info"),
            "detail must not be escaped: {xml}"
        );
    }

    #[test]
    fn serialize_fault_with_raw_xml_detail_soap11() {
        let fault =
            SoapFault::sender("bad").with_detail_xml(r#"<c:Info xmlns:c="urn:x">x</c:Info>"#);
        let xml = String::from_utf8(fault.to_xml_bytes_v11()).unwrap();
        assert!(
            xml.contains(r#"<detail><c:Info xmlns:c="urn:x">x</c:Info></detail>"#),
            "got: {xml}"
        );
        assert!(
            !xml.contains("&lt;c:Info"),
            "detail must not be escaped: {xml}"
        );
    }

    #[test]
    fn detail_xml_takes_precedence_over_text_detail() {
        let fault = SoapFault::new(FaultCode::Sender, "r", Some("plaintext".into()))
            .with_detail_xml("<x:Y xmlns:x=\"urn:z\"/>");
        let xml = String::from_utf8(fault.to_xml_bytes()).unwrap();
        assert!(
            xml.contains("<x:Y xmlns:x=\"urn:z\"/>"),
            "raw xml should win: {xml}"
        );
        assert!(
            !xml.contains("plaintext"),
            "text detail should be suppressed when detail_xml set: {xml}"
        );
    }

    #[test]
    fn existing_text_detail_still_escaped_when_no_xml() {
        // SOAP 1.2: plain-text `detail` has no valid place in element-only env:Detail
        // (F-3). The human-readable message is already in Reason/Text. Assert no
        // env:Detail element is emitted — the text is dropped, not wrapped.
        let fault = SoapFault::new(FaultCode::Sender, "r", Some("a < b & c".into()));
        let xml = String::from_utf8(fault.to_xml_bytes()).unwrap();
        assert!(
            !xml.contains("<env:Detail>"),
            "SOAP 1.2: env:Detail must not be emitted for plain-text detail (F-3): {xml}"
        );
    }

    // ── F-3: SOAP 1.2 env:Detail is element-only ────────────────────────────

    /// SOAP 1.2 env:Detail has element-only content (xs:any children, no text).
    /// When only a plain-text `detail` is set (no `detail_xml`), no env:Detail
    /// element should appear in the output — the reason is already in Reason/Text.
    #[test]
    fn soap12_text_detail_does_not_emit_env_detail_chardata() {
        let fault = SoapFault::new(
            FaultCode::Receiver,
            "Internal error",
            Some("plain text detail".to_string()),
        );
        let xml = String::from_utf8(fault.to_xml_bytes()).unwrap();
        // Must NOT emit <env:Detail> wrapping character data
        assert!(
            !xml.contains("<env:Detail>plain text detail</env:Detail>"),
            "SOAP 1.2 env:Detail must not contain character data (F-3): {xml}"
        );
        // Must NOT emit env:Detail at all when only text detail is present
        assert!(
            !xml.contains("<env:Detail>"),
            "SOAP 1.2 env:Detail must not be emitted for plain-text detail (F-3): {xml}"
        );
        // The reason must still be present in Reason/Text
        assert!(
            xml.contains("Internal error"),
            "Reason must still appear in Reason/Text: {xml}"
        );
    }

    /// SOAP 1.2: when detail_xml (a real element) is set, env:Detail is still emitted
    /// with the raw element child — this path is valid and must remain unchanged.
    #[test]
    fn soap12_detail_xml_element_still_emits_env_detail() {
        let fault = SoapFault::new(
            FaultCode::Receiver,
            "Internal error",
            Some("plain text".to_string()),
        )
        .with_detail_xml("<c:Child xmlns:c=\"urn:x\"/>");
        let xml = String::from_utf8(fault.to_xml_bytes()).unwrap();
        assert!(
            xml.contains("<env:Detail><c:Child xmlns:c=\"urn:x\"/></env:Detail>"),
            "detail_xml element path must still emit env:Detail: {xml}"
        );
    }

    #[test]
    fn soap11_fault_special_chars_in_reason_and_detail_are_escaped() {
        use quick_xml::events::Event;
        use quick_xml::Reader;

        let special = r#"& < > " '"#;
        let fault = SoapFault::new(FaultCode::Sender, special, Some(special.to_string()));
        let xml_bytes = fault.to_xml_bytes_v11();
        let xml_str = String::from_utf8(xml_bytes).unwrap();

        assert!(
            !xml_str.contains("& "),
            "Unescaped '& ' found in SOAP 1.1 fault XML: {xml_str}"
        );
        assert!(xml_str.contains("&amp;"), "Expected &amp;: {xml_str}");
        assert!(xml_str.contains("&lt;"), "Expected &lt;: {xml_str}");

        // Parse to confirm well-formed.
        let mut reader = Reader::from_str(&xml_str);
        reader.config_mut().trim_text(true);
        let mut buf = Vec::new();
        loop {
            let is_eof = {
                let ev = reader.read_event_into(&mut buf).expect("XML must parse");
                matches!(ev, Event::Eof)
            };
            buf.clear();
            if is_eof {
                break;
            }
        }
    }
}