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
//! MIME multipart/related attachment support for AS4 messages.
//!
//! This module provides utilities for packaging AS4 payloads as MIME multipart/related
//! attachments with Content-ID references, conforming to the **OpenPeppol AS4 Profile v2.0**
//! and **CEF eDelivery AS4 profile**.
//!
//! ## Background
//!
//! AS4 payloads are transmitted as MIME multipart/related parts (SwA
//! packaging): the root part carries the SOAP envelope with an **empty**
//! `<soap:Body>`, and each payload part is referenced from the signed
//! `eb:PartInfo href="cid:…"` entries in the `eb:Messaging` header.
//!
//! ### Example MIME Structure
//!
//! ```text
//! Content-Type: multipart/related; boundary="----boundary123"; type="application/soap+xml"
//!
//! ------boundary123
//! Content-Type: application/soap+xml; charset=UTF-8
//! Content-Transfer-Encoding: 8bit
//! Content-ID: <soap-body@example.com>
//!
//! <?xml version="1.0"?>
//! <soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
//!   <soap:Header>
//!     <!-- eb:Messaging with eb:PartInfo href="cid:payload-001@example.com" -->
//!     <!-- wsse:Security signing eb:Messaging, the Body and the attachment -->
//!   </soap:Header>
//!   <soap:Body/>
//! </soap:Envelope>
//!
//! ------boundary123
//! Content-Type: application/octet-stream
//! Content-Transfer-Encoding: binary
//! Content-ID: <payload-001@example.com>
//! Content-Disposition: attachment; filename="MSCONS_..._260705_1230_REF.txt"
//!
//! [binary payload data]
//! ------boundary123--
//! ```
//!
//! ## Architecture
//!
//! The module provides:
//! - `MimePackage`: A builder for constructing MIME multipart/related messages
//! - `MimeAttachment`: Represents a single attachment within the package
//! - Helpers for generating stable Content-ID values from payloads

use crate::core::{AsxError, ErrorCode, ErrorContext, Result};
use std::fmt;
use std::io::Write;

// ──────────────────────────────────────────────────────────────────────────────
// PayloadFilename newtype
// ──────────────────────────────────────────────────────────────────────────────

/// A validated MIME `Content-Disposition` filename safe for embedding in
/// AS4 payload part headers.
///
/// ## Invariants (enforced once, at construction)
///
/// * 1–255 printable US-ASCII bytes (range `0x20`–`0x7E`)
/// * No double-quote (`"`) or backslash (`\`) — RFC 2183 `quoted-string` specials
/// * No control characters including CR/LF — header-injection hardening
///
/// Using a newtype instead of a raw `String` moves validation to the API
/// boundary ("parse, don't validate"): once a `PayloadFilename` exists, the
/// send pipeline can embed it in a MIME header without any further checks.
///
/// ## Examples
///
/// ```rust
/// use asx_rs::as4::mime_packaging::PayloadFilename;
///
/// let name = PayloadFilename::new("invoice.xml").unwrap();
///
/// // BDEW Allgemeine Festlegungen §AF §2.12 — build the filename string in
/// // your application, then wrap it:
/// let bdew = format!(
///     "MSCONS_4011234000000_4011234000001_{}_{}_{}.txt",
///     "260705", "1230", "REF123"
/// );
/// let name = PayloadFilename::new(&bdew).unwrap();
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PayloadFilename(String);

/// Error returned when a string violates [`PayloadFilename`] invariants.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PayloadFilenameError(String);

impl fmt::Display for PayloadFilenameError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl std::error::Error for PayloadFilenameError {}

impl PayloadFilename {
    const MAX_LEN: usize = 255;

    /// Create a `PayloadFilename` from a string slice.
    ///
    /// Validates first, then allocates — the `&str` is only copied into an
    /// owned `String` when the value is known to be valid.
    ///
    /// For callers that already own a `String`, use `TryFrom<String>` to
    /// avoid a redundant allocation:
    ///
    /// ```rust
    /// use asx_rs::as4::mime_packaging::PayloadFilename;
    /// let s = "invoice.xml".to_owned();
    /// let name: PayloadFilename = s.try_into().unwrap();
    /// ```
    ///
    /// Returns `Err` when the string is empty, exceeds 255 bytes, or contains
    /// any character outside `0x20`–`0x7E` or the forbidden `"` and `\`.
    pub fn new(s: &str) -> std::result::Result<Self, PayloadFilenameError> {
        Self::validate_bytes(s.as_bytes())?;
        Ok(Self(s.to_owned()))
    }

    /// Return the filename as a string slice.
    #[inline]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    fn validate_bytes(bytes: &[u8]) -> std::result::Result<(), PayloadFilenameError> {
        if bytes.is_empty() {
            return Err(PayloadFilenameError(
                "payload filename must not be empty \
                 (use None to omit the Content-Disposition filename parameter)"
                    .into(),
            ));
        }
        if bytes.len() > Self::MAX_LEN {
            return Err(PayloadFilenameError(format!(
                "payload filename exceeds maximum length ({} bytes, limit is {})",
                bytes.len(),
                Self::MAX_LEN,
            )));
        }
        if let Some(bad) = bytes
            .iter()
            .copied()
            .find(|&b| !(0x20..=0x7E).contains(&b) || b == b'"' || b == b'\\')
        {
            return Err(PayloadFilenameError(format!(
                "payload filename contains character 0x{bad:02X} not allowed in a \
                 Content-Disposition header value (must be printable ASCII, \
                 no double-quote or backslash)"
            )));
        }
        Ok(())
    }
}

impl fmt::Display for PayloadFilename {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

impl AsRef<str> for PayloadFilename {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl std::str::FromStr for PayloadFilename {
    type Err = PayloadFilenameError;
    /// Parse a `PayloadFilename` from a string slice. Enables the `.parse()` idiom:
    /// ```rust
    /// use asx_rs::as4::mime_packaging::PayloadFilename;
    /// let name: PayloadFilename = "invoice.xml".parse().unwrap();
    /// ```
    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        Self::new(s)
    }
}

impl TryFrom<String> for PayloadFilename {
    type Error = PayloadFilenameError;
    /// Validate and wrap an owned `String` without re-allocating.
    fn try_from(s: String) -> std::result::Result<Self, Self::Error> {
        Self::validate_bytes(s.as_bytes())?;
        Ok(Self(s))
    }
}

impl TryFrom<&str> for PayloadFilename {
    type Error = PayloadFilenameError;
    fn try_from(s: &str) -> std::result::Result<Self, Self::Error> {
        Self::new(s)
    }
}

/// MIME boundary marker for multipart/related messages.
///
/// Chosen to be unlikely to appear in any embedded payload data.
/// Format: `----boundary-{random hex}`
pub const MIME_BOUNDARY_PREFIX: &str = "----boundary-asx-";

/// MIME attachment representing a single part within a multipart/related message.
#[derive(Debug, Clone)]
pub struct MimeAttachment {
    /// Content-ID for this attachment (e.g., `payload-001@example.com`).
    /// Referenced from `eb:PartInfo href="cid:…"` in the SOAP envelope.
    pub content_id: String,

    /// MIME type of the attachment (e.g., `application/octet-stream`).
    pub content_type: String,

    /// Content-Transfer-Encoding (typically `binary` for payloads, `8bit` for SOAP).
    pub transfer_encoding: String,

    /// Attachment body (binary or XML).
    pub body: Vec<u8>,

    /// Optional Content-Disposition header value.
    pub disposition: Option<String>,
}

impl MimeAttachment {
    /// Create a new MIME attachment.
    ///
    /// # Parameters
    /// - `content_id`: Unique identifier (will be wrapped in `<...>` when serialized)
    /// - `content_type`: RFC 2045 media type
    /// - `body`: Attachment body (binary or text)
    /// - `transfer_encoding`: Encoding scheme (e.g., `binary`, `8bit`)
    pub fn new(
        content_id: impl Into<String>,
        content_type: impl Into<String>,
        body: impl Into<Vec<u8>>,
        transfer_encoding: impl Into<String>,
    ) -> Self {
        Self {
            content_id: content_id.into(),
            content_type: content_type.into(),
            transfer_encoding: transfer_encoding.into(),
            body: body.into(),
            disposition: None,
        }
    }

    /// Add a Content-Disposition header (e.g., `attachment; name="payload"`).
    pub fn with_disposition(mut self, disposition: impl Into<String>) -> Self {
        self.disposition = Some(disposition.into());
        self
    }

    /// Generate a stable Content-ID from payload digest.
    ///
    /// Computes SHA-256 of the payload and formats as `payload-{first 16 hex chars}@example.com`.
    pub fn content_id_from_digest(payload: &[u8]) -> String {
        // Use OpenSSL to compute SHA-256 digest
        use openssl::hash::MessageDigest;

        // Compute SHA-256
        let digest =
            openssl::hash::hash(MessageDigest::sha256(), payload).expect("SHA-256 should not fail");

        // Convert first 8 bytes to hex string (16 hex characters)
        let hex_str = digest
            .iter()
            .take(8)
            .map(|b| format!("{:02x}", b))
            .collect::<String>();

        format!("payload-{}@example.com", hex_str)
    }
}

/// Builder for constructing MIME multipart/related messages.
///
/// Handles serialization of SOAP envelope and attachments into properly-formatted
/// multipart MIME structure with correct boundary markers and headers.
#[derive(Debug)]
pub struct MimePackageBuilder {
    boundary: String,
    root_soap_content_type: String,
    soap_attachment: Option<MimeAttachment>,
    attachments: Vec<MimeAttachment>,
}

impl MimePackageBuilder {
    fn write_crlf_line(body: &mut Vec<u8>, line: &str, stage: &'static str) -> Result<()> {
        body.write_all(line.as_bytes()).map_err(|_| {
            AsxError::new(
                ErrorCode::ReliabilityFailure,
                "Failed to write MIME line",
                ErrorContext::new(stage),
            )
        })?;
        body.write_all(b"\r\n").map_err(|_| {
            AsxError::new(
                ErrorCode::ReliabilityFailure,
                "Failed to write MIME CRLF",
                ErrorContext::new(stage),
            )
        })
    }

    /// Create a new MIME package builder.
    ///
    /// Generates a unique boundary marker automatically.
    pub fn new() -> Self {
        // Generate boundary using current nanosecond timestamp and incrementing counter
        use std::sync::atomic::{AtomicU64, Ordering};
        use std::time::{SystemTime, UNIX_EPOCH};

        static COUNTER: AtomicU64 = AtomicU64::new(0);

        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_nanos() as u64)
            .unwrap_or(0);

        let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
        let combined = nanos.wrapping_add(counter);

        let boundary = format!("{}{:016x}", MIME_BOUNDARY_PREFIX, combined);

        Self {
            boundary,
            root_soap_content_type: "application/soap+xml".to_string(),
            soap_attachment: None,
            attachments: Vec::new(),
        }
    }

    /// Set SOAP media type advertised for the root XOP part.
    ///
    /// Example:
    /// - SOAP 1.2: `application/soap+xml`
    pub fn with_root_soap_content_type(mut self, soap_content_type: impl Into<String>) -> Self {
        self.root_soap_content_type = soap_content_type.into();
        self
    }

    /// Set the SOAP envelope as the root attachment (Content-ID: `<soap-body@example.com>`).
    ///
    /// The root part is `application/soap+xml` — AS4 SwA packaging. (MTOM's
    /// `application/xop+xml` root, emitted by asx through 0.12.0, makes WSS4J-based
    /// receivers fail the security-header DOM conversion.)
    pub fn with_soap_body(mut self, soap_xml: Vec<u8>) -> Self {
        let content_type = format!("{}; charset=UTF-8", self.root_soap_content_type);
        self.soap_attachment = Some(MimeAttachment::new(
            "soap-body@example.com",
            content_type,
            soap_xml,
            "8bit",
        ));
        self
    }

    /// Add a binary attachment (e.g., encrypted payload).
    pub fn add_attachment(mut self, attachment: MimeAttachment) -> Self {
        self.attachments.push(attachment);
        self
    }

    /// Add multiple attachments.
    pub fn add_attachments(mut self, attachments: Vec<MimeAttachment>) -> Self {
        self.attachments.extend(attachments);
        self
    }

    /// Build the final MIME multipart/related message as bytes.
    ///
    /// Returns the complete HTTP message body with proper boundary markers
    /// and headers for each part.
    pub fn build(self) -> Result<Vec<u8>> {
        if self.soap_attachment.is_none() {
            return Err(AsxError::new(
                ErrorCode::PolicyViolation,
                "MIME package requires at least a SOAP body attachment",
                ErrorContext::new("mime_packaging"),
            ));
        }

        let mut body = Vec::new();

        // Write root MIME boundaries and SOAP part
        if let Some(ref soap) = self.soap_attachment {
            Self::write_crlf_line(&mut body, &format!("--{}", self.boundary), "mime_packaging")?;

            Self::write_attachment(&mut body, soap)?;
        }

        // Write additional attachments
        for attachment in &self.attachments {
            Self::write_crlf_line(&mut body, &format!("--{}", self.boundary), "mime_packaging")?;

            Self::write_attachment(&mut body, attachment)?;
        }

        // Write closing boundary
        Self::write_crlf_line(
            &mut body,
            &format!("--{}--", self.boundary),
            "mime_packaging",
        )?;

        Ok(body)
    }

    /// Get the Content-Type header value for this package.
    ///
    /// Returns the multipart/related Content-Type with boundary parameter.
    /// The `type` parameter names the root part's media type per RFC 2387 —
    /// `application/soap+xml` for AS4 SwA packaging.
    pub fn content_type(&self) -> String {
        format!(
            "multipart/related; boundary=\"{}\"; type=\"{}\"",
            self.boundary, self.root_soap_content_type
        )
    }

    /// Get the boundary marker for this package.
    pub fn boundary(&self) -> &str {
        &self.boundary
    }

    fn write_attachment(body: &mut Vec<u8>, attachment: &MimeAttachment) -> Result<()> {
        // Write headers
        Self::write_crlf_line(
            body,
            &format!("Content-Type: {}", attachment.content_type),
            "mime_packaging",
        )?;

        Self::write_crlf_line(
            body,
            &format!(
                "Content-Transfer-Encoding: {}",
                attachment.transfer_encoding
            ),
            "mime_packaging",
        )?;

        Self::write_crlf_line(
            body,
            &format!("Content-ID: <{}>", attachment.content_id),
            "mime_packaging",
        )?;

        if let Some(ref disposition) = attachment.disposition {
            Self::write_crlf_line(
                body,
                &format!("Content-Disposition: {}", disposition),
                "mime_packaging",
            )?;
        }

        // Empty line before body
        body.write_all(b"\r\n").map_err(|_| {
            AsxError::new(
                ErrorCode::ReliabilityFailure,
                "Failed to write empty line before attachment body",
                ErrorContext::new("mime_packaging"),
            )
        })?;

        // Write body
        body.extend_from_slice(&attachment.body);

        // Separate the part body from the next boundary marker.
        body.write_all(b"\r\n").map_err(|_| {
            AsxError::new(
                ErrorCode::ReliabilityFailure,
                "Failed to write CRLF after attachment body",
                ErrorContext::new("mime_packaging"),
            )
        })?;

        Ok(())
    }
}

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

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

    #[test]
    fn mime_attachment_with_digest_generates_stable_content_id() {
        let payload = b"test payload data";
        let cid_1 = MimeAttachment::content_id_from_digest(payload);
        let cid_2 = MimeAttachment::content_id_from_digest(payload);

        // Same payload → same Content-ID
        assert_eq!(cid_1, cid_2);

        // Format check: should be payload-{hex}@example.com
        assert!(cid_1.starts_with("payload-"));
        assert!(cid_1.ends_with("@example.com"));
    }

    #[test]
    fn mime_attachment_different_payloads_different_content_ids() {
        let payload_a = b"payload A";
        let payload_b = b"payload B";

        let cid_a = MimeAttachment::content_id_from_digest(payload_a);
        let cid_b = MimeAttachment::content_id_from_digest(payload_b);

        // Different payloads → different Content-IDs
        assert_ne!(cid_a, cid_b);
    }

    #[test]
    fn mime_package_builder_generates_boundary() {
        let builder_1 = MimePackageBuilder::new();
        let builder_2 = MimePackageBuilder::new();

        let boundary_1 = builder_1.boundary();
        let boundary_2 = builder_2.boundary();

        // Each builder gets a unique boundary
        assert_ne!(boundary_1, boundary_2);

        // Boundary matches prefix pattern
        assert!(boundary_1.starts_with(MIME_BOUNDARY_PREFIX));
        assert!(boundary_2.starts_with(MIME_BOUNDARY_PREFIX));
    }

    #[test]
    fn mime_package_content_type_header() {
        let builder = MimePackageBuilder::new();
        let content_type = builder.content_type();

        assert!(content_type.starts_with("multipart/related"));
        assert!(content_type.contains("boundary="));
        assert!(content_type.contains("type=\"application/soap+xml\""));
    }

    #[test]
    fn mime_package_builder_requires_soap_body() {
        let builder = MimePackageBuilder::new();
        let result = builder.build();

        assert!(result.is_err());
        if let Err(e) = result {
            assert_eq!(e.code, ErrorCode::PolicyViolation);
        }
    }

    #[test]
    fn mime_package_builder_with_soap_and_attachment() {
        let soap_body = b"<soap:Envelope>...</soap:Envelope>".to_vec();
        let payload = b"binary payload".to_vec();

        let attachment = MimeAttachment::new(
            "payload-001@example.com",
            "application/octet-stream",
            payload,
            "binary",
        );

        let builder = MimePackageBuilder::new()
            .with_soap_body(soap_body)
            .add_attachment(attachment);

        let result = builder.build();
        assert!(result.is_ok());

        let mime_body = result.unwrap();
        // Should contain boundary markers
        assert!(String::from_utf8_lossy(&mime_body).contains("--"));
        // Should contain Content-ID headers
        assert!(String::from_utf8_lossy(&mime_body).contains("Content-ID:"));
    }

    // ── PayloadFilename tests ─────────────────────────────────────────────────

    #[test]
    fn payload_filename_accepts_printable_ascii() {
        assert!(PayloadFilename::new("invoice.xml").is_ok());
        assert!(
            PayloadFilename::new("MSCONS_4011234000000_4011234000001_260705_1230_REF.txt").is_ok()
        );
        assert!(PayloadFilename::new("file with spaces.txt").is_ok());
        // full printable range: 0x20 and 0x7E
        assert!(PayloadFilename::new(" ~").is_ok());
    }

    #[test]
    fn payload_filename_rejects_empty() {
        let err = PayloadFilename::new("").unwrap_err();
        assert!(err.to_string().contains("empty"), "{err}");
    }

    #[test]
    fn payload_filename_rejects_over_length() {
        let long = "a".repeat(256);
        let err = PayloadFilename::new(&long).unwrap_err();
        assert!(err.to_string().contains("maximum length"), "{err}");
    }

    #[test]
    fn payload_filename_rejects_control_characters() {
        // Header-injection: CR, LF
        assert!(PayloadFilename::new("evil\r\nX-Injected: hdr").is_err());
        assert!(PayloadFilename::new("evil\n").is_err());
        // Null byte
        assert!(PayloadFilename::new("evil\x00null").is_err());
        // DEL (0x7F is outside the 0x20–0x7E printable range)
        assert!(PayloadFilename::new("evil\x7f").is_err());
        // Non-ASCII: U+00E9 é (UTF-8: 0xC3 0xA9 — both bytes > 0x7E)
        assert!(PayloadFilename::new("caf\u{00e9}").is_err());
    }

    #[test]
    fn payload_filename_rejects_quoted_string_specials() {
        // Double-quote would break `filename="..."` encoding
        assert!(PayloadFilename::new("evil\"quote").is_err());
        // Backslash is the RFC 2183 escape character in quoted-string
        assert!(PayloadFilename::new("evil\\backslash").is_err());
    }

    #[test]
    fn payload_filename_tryfrom_conversions_work() {
        let from_str: PayloadFilename = "invoice.xml".try_into().unwrap();
        let from_string: PayloadFilename = "invoice.xml".to_string().try_into().unwrap();
        let from_parse: PayloadFilename = "invoice.xml".parse().unwrap();
        assert_eq!(from_str, from_string);
        assert_eq!(from_str, from_parse);
        assert_eq!(from_str.as_str(), "invoice.xml");
    }

    #[test]
    fn payload_filename_display_and_asref() {
        let name = PayloadFilename::new("report.pdf").unwrap();
        assert_eq!(name.to_string(), "report.pdf");
        assert_eq!(AsRef::<str>::as_ref(&name), "report.pdf");
    }
}