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
//! AS4 signal generation: Receipt, Error, and PullRequest signals.

use super::stream::{extract_multipart_related_payload_if_present, normalize_mpc};
use super::types::{
    As4ErrorCode, As4ErrorSeverity, As4GeneratePullRequestPolicy, As4NriReference,
    As4ReceiptCredentials, As4ReceivePushOutput,
};
use crate::core::{AsxError, ErrorCode, ErrorContext, Result, SessionContext};
#[cfg(feature = "as4")]
use crate::crypto::soap_builder::WsSecurityHeaderBuilder;
use crate::crypto::wssec::generate_xmlsig_signature;

/// Generate an AS4 `eb:Receipt` SignalMessage per ebMS3 §5.2.2.1 and §5.1.3.
///
/// The returned bytes are a complete SOAP 1.2 envelope containing a
/// `eb:SignalMessage` with an `eb:Receipt` element referencing
/// `ref_to_message_id`. The receipt contains an empty
/// `<ebbpsig:NonRepudiationInformation/>` placeholder.
///
/// For a conformant NRO receipt that echoes the original message's signed
/// references, use [`generate_receipt_with_nri`] instead.
///
/// The receipt is unsigned; if the P-Mode requires a signed receipt (NRR),
/// use [`generate_signed_receipt_with_nri`] instead.
pub fn generate_receipt(
    session: &SessionContext,
    message_id: &str,
    ref_to_message_id: &str,
) -> Result<Vec<u8>> {
    generate_receipt_with_nri(session, message_id, ref_to_message_id, &[])
}

/// Generate an AS4 `eb:Receipt` SignalMessage with Non-Repudiation of Origin
/// (NRO) information per ebMS3 §5.2.2.1 and eDelivery AS4 §5.1.3.
///
/// When `nri_refs` is non-empty each entry becomes a
/// `<ebbpsig:MessagePartNRInformation>/<ds:Reference>` element inside the
/// `<ebbpsig:NonRepudiationInformation>` block, as required by the AS4
/// Non-Repudiation of Origin profile.
///
/// Obtain `nri_refs` by calling
/// [`crate::crypto::wssec::parse_signature_references`] on the raw bytes of
/// the inbound signed message and mapping each
/// [`crate::crypto::wssec::WsSecSignatureReference`] to
/// [`As4NriReference`]:
///
/// ```text
/// let sig_refs = parse_signature_references(xml_str)?;
/// let nri: Vec<As4NriReference> = sig_refs.into_iter().map(As4NriReference::from).collect();
/// let receipt = generate_receipt_with_nri(&session, &id, &ref_id, &nri)?;
/// ```
///
/// The receipt is unsigned; for a receipt carrying a WS-Security XML
/// Signature (Non-Repudiation of Receipt), use
/// [`generate_signed_receipt_with_nri`].
#[cfg_attr(feature = "trace", tracing::instrument(skip_all, fields(message_id = %message_id, partner_id = %session.partner_id())))]
pub fn generate_receipt_with_nri(
    session: &SessionContext,
    message_id: &str,
    ref_to_message_id: &str,
    nri_refs: &[As4NriReference],
) -> Result<Vec<u8>> {
    validate_receipt_signal_ids(
        session,
        "as4_generate_receipt",
        message_id,
        ref_to_message_id,
    )?;

    let timestamp = crate::time_utils::format_rfc3339_secs(std::time::SystemTime::now());
    // SECURITY: Escape caller-supplied values to prevent XML injection.
    let message_id_escaped = crate::wire::escape_xml(message_id);
    let ref_to_message_id_escaped = crate::wire::escape_xml(ref_to_message_id);

    let nri_xml = build_receipt_nri_xml(nri_refs);
    let ds_ns_attr = if nri_refs.is_empty() {
        ""
    } else {
        " xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\""
    };

    let xml = format!(
        "<S12:Envelope \
 xmlns:S12=\"http://www.w3.org/2003/05/soap-envelope\" \
 xmlns:eb=\"http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/\" \
 xmlns:ebbpsig=\"http://docs.oasis-open.org/ebxml-bp/ebbp-signals-2.0\"{ds_ns}>\
<S12:Header>\
<eb:Messaging S12:mustUnderstand=\"true\">\
<eb:SignalMessage>\
<eb:MessageInfo>\
<eb:Timestamp>{timestamp}</eb:Timestamp>\
<eb:MessageId>{message_id_escaped}</eb:MessageId>\
<eb:RefToMessageId>{ref_to_message_id_escaped}</eb:RefToMessageId>\
</eb:MessageInfo>\
<eb:Receipt>{nri_xml}</eb:Receipt>\
</eb:SignalMessage>\
</eb:Messaging>\
</S12:Header>\
<S12:Body/>\
</S12:Envelope>",
        ds_ns = ds_ns_attr,
    );
    Ok(xml.into_bytes())
}

/// Validate the message-ID pair shared by all receipt generators.
fn validate_receipt_signal_ids(
    session: &SessionContext,
    stage: &'static str,
    message_id: &str,
    ref_to_message_id: &str,
) -> Result<()> {
    if message_id.trim().is_empty() {
        return Err(AsxError::new(
            ErrorCode::InvalidInput,
            "message_id must not be empty",
            ErrorContext::for_session(stage, session),
        ));
    }
    if ref_to_message_id.trim().is_empty() {
        return Err(AsxError::new(
            ErrorCode::InvalidInput,
            "ref_to_message_id must not be empty",
            ErrorContext::for_session(stage, session),
        ));
    }
    Ok(())
}

/// Build the `<ebbpsig:NonRepudiationInformation>` block for a receipt.
///
/// When NRI references are provided, each becomes a MessagePartNRInformation
/// entry that echoes the original message's ds:Reference — conformant with
/// eDelivery AS4 §5.1.3 Non-Repudiation of Origin.
fn build_receipt_nri_xml(nri_refs: &[As4NriReference]) -> String {
    if nri_refs.is_empty() {
        return "<ebbpsig:NonRepudiationInformation/>".to_string();
    }
    let mut nri = "<ebbpsig:NonRepudiationInformation>".to_string();
    for r in nri_refs {
        // SECURITY: escape all caller-controlled fields.
        let uri_esc = crate::wire::escape_xml(&r.uri);
        let dig_method_esc = crate::wire::escape_xml(&r.digest_method_uri);
        let dig_value_esc = crate::wire::escape_xml(&r.digest_value_b64);
        nri.push_str(&format!(
            "<ebbpsig:MessagePartNRInformation>\
<ds:Reference URI=\"{uri}\">\
<ds:DigestMethod Algorithm=\"{dig_method}\"\
></ds:DigestMethod\
><ds:DigestValue>{dig_value}</ds:DigestValue>\
</ds:Reference>\
</ebbpsig:MessagePartNRInformation>",
            uri = uri_esc,
            dig_method = dig_method_esc,
            dig_value = dig_value_esc,
        ));
    }
    nri.push_str("</ebbpsig:NonRepudiationInformation>");
    nri
}

/// Validate that a PEM signing key and certificate parse and match each other.
fn validate_signal_signing_credentials(
    session: &SessionContext,
    stage: &'static str,
    signal_name: &str,
    signing_key_pem: &[u8],
    signing_cert_pem: &[u8],
) -> Result<()> {
    let signing_cert = openssl::x509::X509::from_pem(signing_cert_pem).map_err(|_err| {
        AsxError::new(
            ErrorCode::InvalidInput,
            format!("AS4 {signal_name} signing_cert_pem is not a valid PEM X.509 certificate"),
            ErrorContext::for_session(stage, session),
        )
    })?;

    let signing_key =
        openssl::pkey::PKey::private_key_from_pem(signing_key_pem).map_err(|_err| {
            AsxError::new(
                ErrorCode::InvalidInput,
                format!("AS4 {signal_name} signing_key_pem is not a valid PEM private key"),
                ErrorContext::for_session(stage, session),
            )
        })?;

    let signing_cert_public = signing_cert.public_key().map_err(|_err| {
        AsxError::new(
            ErrorCode::InvalidInput,
            format!("AS4 {signal_name} signing_cert_pem does not contain a usable public key"),
            ErrorContext::for_session(stage, session),
        )
    })?;

    if !signing_key.public_eq(&signing_cert_public) {
        return Err(AsxError::new(
            ErrorCode::InvalidInput,
            format!("AS4 {signal_name} signing_cert_pem does not match signing_key_pem"),
            ErrorContext::for_session(stage, session),
        ));
    }
    Ok(())
}

const RECEIPT_MESSAGING_WSU_ID: &str = "as4-receipt-messaging";
const RECEIPT_BODY_WSU_ID: &str = "as4-receipt-body";

/// Generate a **signed** AS4 `eb:Receipt` SignalMessage with Non-Repudiation
/// Information per ebMS3 §5.2.2.1 and eDelivery AS4 §5.1.8.
///
/// The returned SOAP envelope carries a `wsse:Security` header whose XML
/// Signature covers the `eb:Messaging` header (the SignalMessage including
/// the `NonRepudiationInformation` block) and the SOAP Body — providing
/// Non-Repudiation of Receipt (NRR) as required by profiles such as the BDEW
/// AS4-Profil §2.2.4.  The result verifies with
/// [`crate::crypto::wssec::verify_enveloped_signature`] and is accepted by
/// counterparties enforcing `require_signed_receipt = true`.
///
/// Obtain `nri_refs` from the inbound signed message via
/// [`crate::crypto::wssec::parse_signature_references`], or use
/// [`generate_signed_receipt_for_output`] which extracts them for you.
#[cfg_attr(feature = "trace", tracing::instrument(skip_all, fields(message_id = %message_id, partner_id = %session.partner_id())))]
pub fn generate_signed_receipt_with_nri(
    session: &SessionContext,
    message_id: &str,
    ref_to_message_id: &str,
    nri_refs: &[As4NriReference],
    credentials: &As4ReceiptCredentials,
) -> Result<Vec<u8>> {
    let stage = "as4_generate_signed_receipt";
    validate_receipt_signal_ids(session, stage, message_id, ref_to_message_id)?;
    validate_signal_signing_credentials(
        session,
        stage,
        "Receipt",
        &credentials.signing_key_pem,
        &credentials.signing_cert_pem,
    )?;

    let timestamp = crate::time_utils::format_rfc3339_secs(std::time::SystemTime::now());
    // SECURITY: Escape caller-supplied values to prevent XML injection.
    let message_id_escaped = crate::wire::escape_xml(message_id);
    let ref_to_message_id_escaped = crate::wire::escape_xml(ref_to_message_id);
    let nri_xml = build_receipt_nri_xml(nri_refs);

    let envelope = format!(
        "<S12:Envelope \
 xmlns:S12=\"http://www.w3.org/2003/05/soap-envelope\" \
 xmlns:eb=\"http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/\" \
 xmlns:ebbpsig=\"http://docs.oasis-open.org/ebxml-bp/ebbp-signals-2.0\" \
 xmlns:wsse=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\" \
 xmlns:wsu=\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd\" \
 xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\">\
<S12:Header>\
<!-- wsse-placeholder -->\
<eb:Messaging S12:mustUnderstand=\"true\" wsu:Id=\"{RECEIPT_MESSAGING_WSU_ID}\">\
<eb:SignalMessage>\
<eb:MessageInfo>\
<eb:Timestamp>{timestamp}</eb:Timestamp>\
<eb:MessageId>{message_id_escaped}</eb:MessageId>\
<eb:RefToMessageId>{ref_to_message_id_escaped}</eb:RefToMessageId>\
</eb:MessageInfo>\
<eb:Receipt>{nri_xml}</eb:Receipt>\
</eb:SignalMessage>\
</eb:Messaging>\
</S12:Header>\
<S12:Body wsu:Id=\"{RECEIPT_BODY_WSU_ID}\"/>\
</S12:Envelope>",
    );

    let messaging_ref = format!("#{RECEIPT_MESSAGING_WSU_ID}");
    let body_ref = format!("#{RECEIPT_BODY_WSU_ID}");
    let reference_uris = [messaging_ref.as_str(), body_ref.as_str()];
    let signature_xml = generate_xmlsig_signature(
        &envelope,
        &reference_uris,
        &credentials.signing_key_pem,
        &credentials.signing_cert_pem,
        credentials.key_info_profile,
    )?;
    let wsse_header = WsSecurityHeaderBuilder::new()
        .with_signing_cert(credentials.signing_cert_pem.clone())
        .with_signature_xml(signature_xml)
        .build()
        .map_err(|err| {
            AsxError::new(
                ErrorCode::ParseFailed,
                format!("failed to build WS-Security header for receipt: {err:?}"),
                ErrorContext::for_session(stage, session),
            )
        })?;
    let wsse_str = String::from_utf8(wsse_header).map_err(|_| {
        AsxError::new(
            ErrorCode::ParseFailed,
            "WS-Security header for receipt is not valid UTF-8",
            ErrorContext::for_session(stage, session),
        )
    })?;

    let signed_envelope = envelope.replace("<!-- wsse-placeholder -->", &wsse_str);
    Ok(signed_envelope.into_bytes())
}

/// Generate an AS4 `eb:Error` SignalMessage per ebMS3 §6.7.3.
pub fn generate_error_signal(
    session: &SessionContext,
    message_id: &str,
    ref_to_message_id: &str,
    error_code: As4ErrorCode,
    severity: As4ErrorSeverity,
    description: &str,
) -> Result<Vec<u8>> {
    validate_receipt_signal_ids(
        session,
        "as4_generate_error_signal",
        message_id,
        ref_to_message_id,
    )?;
    if description.trim().is_empty() {
        return Err(AsxError::new(
            ErrorCode::InvalidInput,
            "description must not be empty",
            ErrorContext::for_session("as4_generate_error_signal", session),
        ));
    }

    let timestamp = crate::time_utils::format_rfc3339_secs(std::time::SystemTime::now());
    let message_id_escaped = crate::wire::escape_xml(message_id);
    let ref_id_escaped = crate::wire::escape_xml(ref_to_message_id);
    let description_escaped = crate::wire::escape_xml(description);

    let xml = format!(
        "<S12:Envelope \
              xmlns:S12=\"http://www.w3.org/2003/05/soap-envelope\" \
              xmlns:eb=\"http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/\">\
              <S12:Header>\
                <eb:Messaging S12:mustUnderstand=\"true\">\
                  <eb:SignalMessage>\
                    <eb:MessageInfo>\
                      <eb:Timestamp>{timestamp}</eb:Timestamp>\
                      <eb:MessageId>{message_id_escaped}</eb:MessageId>\
                      <eb:RefToMessageId>{ref_id_escaped}</eb:RefToMessageId>\
                    </eb:MessageInfo>\
                    <eb:Error errorCode=\"{error_code}\" severity=\"{severity}\" \
                              category=\"CONTENT\" origin=\"ebMS\">\
                      <eb:Description xml:lang=\"en\">{description_escaped}</eb:Description>\
                    </eb:Error>\
                  </eb:SignalMessage>\
                </eb:Messaging>\
              </S12:Header>\
              <S12:Body/>\
            </S12:Envelope>",
        timestamp = timestamp,
        message_id_escaped = message_id_escaped,
        ref_id_escaped = ref_id_escaped,
        error_code = error_code.ebms_code(),
        severity = severity.as_str(),
        description_escaped = description_escaped,
    );
    Ok(xml.into_bytes())
}

/// Generate an AS4 `eb:PullRequest` signal message, optionally signed.
///
/// Per eDelivery AS4 v1.15 §4.5.5, pull requests sent by the Receiver MSH
/// MUST carry a WS-Security XML Signature when credentials are supplied.
#[cfg_attr(feature = "trace", tracing::instrument(skip_all, fields(message_id = %policy.message_id, partner_id = %session.partner_id())))]
pub fn generate_pull_request(
    session: &SessionContext,
    policy: &As4GeneratePullRequestPolicy,
) -> Result<Vec<u8>> {
    let stage = "as4_generate_pull_request";

    let mpc = normalize_mpc(&policy.mpc);
    if mpc.is_empty() {
        return Err(AsxError::new(
            ErrorCode::InvalidInput,
            "AS4 PullRequest MPC must not be empty",
            ErrorContext::for_session(stage, session),
        ));
    }
    if policy.message_id.trim().is_empty() {
        return Err(AsxError::new(
            ErrorCode::InvalidInput,
            "AS4 PullRequest message_id must not be empty",
            ErrorContext::for_session(stage, session),
        ));
    }

    if let Some(ref auth) = policy.authorization_info
        && auth.trim().is_empty()
    {
        return Err(AsxError::new(
            ErrorCode::InvalidInput,
            "AS4 PullRequest authorization_info must not be empty when set",
            ErrorContext::for_session(stage, session),
        ));
    }

    if let Some(creds) = &policy.credentials {
        validate_signal_signing_credentials(
            session,
            stage,
            "PullRequest",
            &creds.signing_key_pem,
            &creds.signing_cert_pem,
        )?;
    }

    let timestamp = crate::time_utils::format_rfc3339_secs(std::time::SystemTime::now());
    let mpc_escaped = crate::wire::escape_xml(mpc);
    let message_id_escaped = crate::wire::escape_xml(&policy.message_id);

    const PULL_REQUEST_WSU_ID: &str = "as4-pull-request";

    let auth_info_xml = policy
        .authorization_info
        .as_deref()
        .map(|v| {
            format!(
                "\n        <eb:AuthorizationInfo>{}</eb:AuthorizationInfo>",
                crate::wire::escape_xml(v)
            )
        })
        .unwrap_or_default();

    let messaging_header = format!(
        r#"<!-- wsse-placeholder -->
    <eb:Messaging S12:mustUnderstand="true">
      <eb:SignalMessage>
        <eb:MessageInfo>
          <eb:Timestamp>{timestamp}</eb:Timestamp>
          <eb:MessageId>{message_id_escaped}</eb:MessageId>
        </eb:MessageInfo>
        <eb:PullRequest wsu:Id="{PULL_REQUEST_WSU_ID}" eb:mpc="{mpc_escaped}">{auth_info}</eb:PullRequest>
      </eb:SignalMessage>
    </eb:Messaging>"#,
        timestamp = timestamp,
        message_id_escaped = message_id_escaped,
        mpc_escaped = mpc_escaped,
        auth_info = auth_info_xml,
    );

    let envelope = format!(
        r#"<S12:Envelope xmlns:S12="http://www.w3.org/2003/05/soap-envelope"
  xmlns:eb="http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/"
  xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"
  xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"
  xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
  <S12:Header>
    {messaging_header}
  </S12:Header>
  <S12:Body/>
</S12:Envelope>"#,
        messaging_header = messaging_header,
    );

    if let Some(creds) = &policy.credentials {
        let reference_uri = format!("#{PULL_REQUEST_WSU_ID}");
        let reference_uris = [reference_uri.as_str()];
        let signature_xml = generate_xmlsig_signature(
            &envelope,
            &reference_uris,
            &creds.signing_key_pem,
            &creds.signing_cert_pem,
            creds.key_info_profile,
        )?;
        let wsse_header = WsSecurityHeaderBuilder::new()
            .with_signing_cert(creds.signing_cert_pem.clone())
            .with_signature_xml(signature_xml)
            .build()
            .map_err(|err| {
                AsxError::new(
                    ErrorCode::ParseFailed,
                    format!("failed to build WS-Security header for pull request: {err:?}"),
                    ErrorContext::for_session(stage, session),
                )
            })?;
        let wsse_str = String::from_utf8(wsse_header).map_err(|_| {
            AsxError::new(
                ErrorCode::ParseFailed,
                "WS-Security header for pull request is not valid UTF-8",
                ErrorContext::for_session(stage, session),
            )
        })?;

        let signed_envelope = envelope.replace("<!-- wsse-placeholder -->", &wsse_str);
        Ok(signed_envelope.into_bytes())
    } else {
        let unsigned_envelope = envelope.replace("<!-- wsse-placeholder -->\n    ", "");
        Ok(unsigned_envelope.into_bytes())
    }
}

/// Convenience wrapper: generate a receipt for a completed receive output.
///
/// Equivalent to calling [`generate_receipt_with_nri`] with
/// `ref_to_message_id = output.user_message.message_id` and an empty NRI
/// slice.  For NRO-profile receipts (with `<NonRepudiationInformation>`),
/// use [`generate_receipt_with_nri`] directly with refs extracted from the
/// raw inbound bytes.
///
/// The result is **unsigned**; production deployments that must satisfy
/// Non-Repudiation of Receipt (e.g. BDEW AS4-Profil §2.2.4) should use
/// [`generate_signed_receipt_for_output`] instead.
///
/// # Example
/// ```no_run
/// use asx_rs::as4::{generate_receipt_for_output, As4ReceiveOutcome};
/// use asx_rs::core::SessionContext;
///
/// # fn example(
/// #     session: &SessionContext,
/// #     outcome: As4ReceiveOutcome,
/// # ) -> asx_rs::Result<()> {
/// if let As4ReceiveOutcome::FirstSeen(output) = outcome {
///     // A ping is acknowledged but never delivered (ebMS3 §5.2.2).
///     let receipt_id = format!("receipt@{}", uuid::Uuid::new_v4());
///     let receipt_bytes = generate_receipt_for_output(session, &receipt_id, &output)?;
///     let _ = receipt_bytes;
/// }
/// # Ok(())
/// # }
/// ```
pub fn generate_receipt_for_output(
    session: &SessionContext,
    receipt_message_id: &str,
    output: &As4ReceivePushOutput,
) -> Result<Vec<u8>> {
    generate_receipt_with_nri(
        session,
        receipt_message_id,
        &output.user_message.message_id,
        &[],
    )
}

/// Generate a **signed** receipt for a completed receive output, echoing the
/// inbound message's `ds:Reference` digests as Non-Repudiation Information.
///
/// `inbound_http_body` / `inbound_http_content_type` are the raw HTTP request
/// body and `Content-Type` of the inbound push exactly as passed to the
/// receive pipeline (MIME multipart or bare SOAP).  The NRI references are
/// extracted from the inbound WS-Security signature via
/// [`crate::crypto::wssec::parse_signature_references`], then the receipt is
/// built and signed with [`generate_signed_receipt_with_nri`].
///
/// Returns [`ErrorCode::InvalidInput`] when the inbound message carries no
/// `ds:Signature` — an NRR receipt cannot echo digests that do not exist.
/// For unsigned inbound messages (test setups only), fall back to
/// [`generate_receipt_for_output`].
///
/// # Example
/// ```no_run
/// use asx_rs::as4::{
///     generate_signed_receipt_for_output, As4ReceiptCredentials, As4ReceiveOutcome,
/// };
/// use asx_rs::core::SessionContext;
///
/// # fn example(
/// #     session: &SessionContext,
/// #     outcome: As4ReceiveOutcome,
/// #     raw_body: &[u8],
/// #     content_type: &str,
/// #     credentials: &As4ReceiptCredentials,
/// # ) -> asx_rs::Result<()> {
/// if let As4ReceiveOutcome::FirstSeen(output) = outcome {
///     let receipt_id = format!("receipt@{}", uuid::Uuid::new_v4());
///     let receipt_bytes = generate_signed_receipt_for_output(
///         session, &receipt_id, &output, raw_body, content_type, credentials,
///     )?;
///     let _ = receipt_bytes;
/// }
/// # Ok(())
/// # }
/// ```
#[cfg_attr(feature = "trace", tracing::instrument(skip_all, fields(message_id = %receipt_message_id, partner_id = %session.partner_id())))]
pub fn generate_signed_receipt_for_output(
    session: &SessionContext,
    receipt_message_id: &str,
    output: &As4ReceivePushOutput,
    inbound_http_body: &[u8],
    inbound_http_content_type: &str,
    credentials: &As4ReceiptCredentials,
) -> Result<Vec<u8>> {
    let stage = "as4_generate_signed_receipt";
    let soap_bytes = match extract_multipart_related_payload_if_present(
        inbound_http_body,
        inbound_http_content_type,
        session,
        stage,
    )? {
        Some(multipart) => multipart.soap_xml,
        None => inbound_http_body,
    };
    let soap_xml = crate::core::bytes_to_utf8_str(soap_bytes, stage, session)?;
    let sig_refs = crate::crypto::wssec::parse_signature_references(soap_xml).map_err(|err| {
        AsxError::new(
            ErrorCode::InvalidInput,
            format!(
                "cannot build NRR receipt: failed to extract ds:Reference digests \
                 from the inbound message signature ({}); for unsigned inbound \
                 messages use generate_receipt_for_output instead",
                err.message
            ),
            ErrorContext::for_session(stage, session),
        )
    })?;
    let nri_refs: Vec<As4NriReference> = sig_refs.into_iter().map(As4NriReference::from).collect();
    generate_signed_receipt_with_nri(
        session,
        receipt_message_id,
        &output.user_message.message_id,
        &nri_refs,
        credentials,
    )
}