asx-rs 0.11.1

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
//! AS2 trust-verification traits and implementations.
//!
//! Defines the sealed [`As2TrustVerifier`] / [`AsyncAs2TrustVerifier`] trait
//! pair, the production [`CmsSmimeTrustVerifier`] backed by OpenSSL CMS /
//! S/MIME, and the [`SyncToAsyncTrustVerifier`] adapter.

use std::sync::Arc;
use zeroize::Zeroize;

use crate::core::{AsxError, ErrorCode, ErrorContext, ReceivedBodyHandle, Result, SessionContext};
#[cfg(feature = "as2")]
use crate::crypto::as2_smime::{
    As2SmimeVerificationOptions, SmimeFormat, decrypt_smime_enveloped_payload, detect_smime_format,
    verify_smime_signed_payload,
};
#[cfg(test)]
use crate::lifecycle::TrustEvidence;
use crate::lifecycle::{DecryptionMaterial, SignatureVerification};

/// Sealing module — prevents external crates from implementing the trust
/// verifier traits outside the `testing` feature escape hatch.
pub(crate) mod private {
    pub trait Sealed {}
}

/// Re-export the sealing marker under the `testing` feature so that
/// integration tests can implement [`As2TrustVerifier`] on their own stubs.
///
/// **Never use this in production code.**
#[cfg(feature = "testing")]
pub use private::Sealed as TrustVerifierSeal;

/// Result returned by [`As2TrustVerifier::verify_and_decrypt`].
///
/// Separates the cryptographic verdict from optional decrypted bytes so that
/// `EnvelopedData` payloads can carry their plaintext through the lifecycle
/// state machine without requiring a second pass over the encrypted buffer.
pub struct TrustResult {
    /// Whether S/MIME signature verification succeeded.
    pub signature: SignatureVerification,
    /// Whether decryption material was present and (if needed) applied.
    pub decryption: DecryptionMaterial,
    /// Decrypted plaintext bytes when the verifier performed S/MIME
    /// `EnvelopedData` unwrapping.  `None` for sign-only payloads — in that
    /// case the original payload bytes are used as the domain payload.
    pub decrypted_payload: Option<Arc<[u8]>>,
}

impl TrustResult {
    /// Convenience constructor: verified signature, no decryption needed.
    pub fn signed_only() -> Self {
        Self {
            signature: SignatureVerification::Verified,
            decryption: DecryptionMaterial::Available,
            decrypted_payload: None,
        }
    }

    /// Convenience constructor: verification passed and decryption was applied.
    pub fn decrypted(plaintext: Arc<[u8]>) -> Self {
        Self {
            signature: SignatureVerification::Verified,
            decryption: DecryptionMaterial::Available,
            decrypted_payload: Some(plaintext),
        }
    }
}

/// Sealed trust-verification contract for AS2 inbound messages.
///
/// ## Security note
///
/// This trait is **sealed**: it cannot be implemented outside this crate
/// except when the `testing` Cargo feature is enabled.  In production builds
/// the only valid implementation is [`CmsSmimeTrustVerifier`].
///
/// Enabling `testing` unlocks [`InsecureBypassTrustVerifier`] for use in
/// integration tests.  Never enable the `testing` feature in production
/// binaries.
pub trait As2TrustVerifier: private::Sealed {
    fn verify_and_decrypt(
        &self,
        session: &SessionContext,
        body: &ReceivedBodyHandle,
    ) -> Result<TrustResult>;
}

/// Async counterpart of [`As2TrustVerifier`].
///
/// Implement this trait when your verification backend requires async I/O —
/// for example, an HSM accessed over a network socket, or an OCSP responder
/// that is checked inline during signature verification.
///
/// For synchronous verifiers, use [`SyncToAsyncTrustVerifier`] to adapt an
/// existing [`As2TrustVerifier`] to this interface with blocking-pool
/// offloading.
///
/// ## Security note
///
/// This trait is **sealed**: see [`As2TrustVerifier`] for details.
pub trait AsyncAs2TrustVerifier: Send + Sync + private::Sealed {
    fn verify_and_decrypt<'a>(
        &'a self,
        session: &'a SessionContext,
        body: &'a ReceivedBodyHandle,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<TrustResult>> + Send + 'a>>;
}

/// Adapts any synchronous [`As2TrustVerifier`] to the async
/// [`AsyncAs2TrustVerifier`] interface.
///
/// Verification runs on Tokio's blocking pool via `spawn_blocking`, so
/// CPU-heavy crypto and chain validation do not execute on async workers.
///
/// The inner verifier is stored behind an `Arc`, so `SyncToAsyncTrustVerifier`
/// itself is `Clone` regardless of whether `V` is `Clone`.  This avoids
/// cloning non-trivial verifier state (parsed cert chains, OCSP caches) on
/// every call, reducing memory pressure under concurrent receive load.
///
/// # Migration from the old API
///
/// The previous signature required `V: Clone`.  Existing callsites that
/// already had `SyncToAsyncTrustVerifier(my_verifier)` now need:
///
/// ```rust,ignore
/// SyncToAsyncTrustVerifier::new(my_verifier)
/// // or equivalently
/// SyncToAsyncTrustVerifier(Arc::new(my_verifier))
/// ```
pub struct SyncToAsyncTrustVerifier<V: As2TrustVerifier + Send + Sync + 'static>(pub Arc<V>);

impl<V: As2TrustVerifier + Send + Sync + 'static> SyncToAsyncTrustVerifier<V> {
    /// Wrap `verifier` in an `Arc` and return an adapter.
    pub fn new(verifier: V) -> Self {
        Self(Arc::new(verifier))
    }
}

impl<V: As2TrustVerifier + Send + Sync + 'static> Clone for SyncToAsyncTrustVerifier<V> {
    fn clone(&self) -> Self {
        Self(Arc::clone(&self.0))
    }
}

impl<V: As2TrustVerifier + Send + Sync + 'static> private::Sealed for SyncToAsyncTrustVerifier<V> {}

impl<V: As2TrustVerifier + Send + Sync + 'static> AsyncAs2TrustVerifier
    for SyncToAsyncTrustVerifier<V>
{
    fn verify_and_decrypt<'a>(
        &'a self,
        session: &'a SessionContext,
        body: &'a ReceivedBodyHandle,
    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<TrustResult>> + Send + 'a>> {
        let verifier = Arc::clone(&self.0);
        let blocking_session = session.clone();
        let blocking_body = body.clone();
        let error_session = session.clone();
        Box::pin(async move {
            let permit = crate::core::CryptoAdmissionControl::process_global()
                .acquire("as2_trust_verify_async_admission", &blocking_session)
                .await?;
            tokio::task::spawn_blocking(move || {
                let _permit = permit;
                verifier.verify_and_decrypt(&blocking_session, &blocking_body)
            })
            .await
            .map_err(|err| {
                AsxError::new(
                    ErrorCode::TransportFailure,
                    format!("AS2 trust verification blocking task failed: {err}"),
                    ErrorContext::for_session("as2_trust_verify_async_join", &error_session),
                )
            })?
        })
    }
}

/// Test-only bypass verifier — skips all cryptographic checks.
///
/// Only available in `#[cfg(test)]` builds.  Never use in production.
#[cfg(test)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InsecureBypassTrustVerifier {
    trust: TrustEvidence,
}

#[cfg(test)]
impl InsecureBypassTrustVerifier {
    pub fn new(trust: TrustEvidence) -> Self {
        Self { trust }
    }
}

#[cfg(test)]
impl private::Sealed for InsecureBypassTrustVerifier {}

#[cfg(test)]
impl As2TrustVerifier for InsecureBypassTrustVerifier {
    fn verify_and_decrypt(
        &self,
        _session: &SessionContext,
        _body: &ReceivedBodyHandle,
    ) -> Result<TrustResult> {
        Ok(TrustResult {
            signature: self.trust.signature,
            decryption: self.trust.decryption,
            decrypted_payload: None,
        })
    }
}

/// Production AS2 trust verifier using OpenSSL CMS / S/MIME.
///
/// Handles three inbound AS2 content layouts:
///
/// 1. **Signed-only** (`multipart/signed` or `smime-type=signed-data`) —
///    the signature is verified with the configured trust anchors.
/// 2. **Encrypted-only** (`smime-type=enveloped-data`) — the `EnvelopedData`
///    layer is decrypted using [`Self::decryption_key_pem`] /
///    [`Self::decryption_cert_pem`].  No signature is required *unless*
///    [`Self::require_signed`] is set, in which case unsigned messages are
///    rejected.
/// 3. **Signed-then-encrypted** (the AS2 interop recommendation per
///    RFC 4130 §7.5) — the outer `EnvelopedData` is decrypted first, then
///    the inner signed structure is verified.
///
/// If `decryption_key_pem` is `None` and an encrypted payload arrives, the
/// call returns [`crate::core::ErrorCode::DecryptionFailed`].
#[derive(Debug, Clone, Default)]
pub struct CmsSmimeTrustVerifier {
    /// PEM-encoded recipient private key for `EnvelopedData` decryption.
    /// Required when inbound AS2 messages are encrypted.
    pub decryption_key_pem: Option<Vec<u8>>,
    /// PEM-encoded X.509 recipient certificate matching `decryption_key_pem`.
    /// Required when inbound AS2 messages are encrypted.
    pub decryption_cert_pem: Option<Vec<u8>>,
    /// Reject inbound messages that carry no verifiable S/MIME signature.
    ///
    /// AS2 recipient encryption certificates are exchanged with partners and
    /// are effectively semi-public, so an *encrypted-only, unsigned* message
    /// authenticates nothing about the sender. With `require_signed = true`, a
    /// payload that is encrypted (or plain) but not signed is rejected with
    /// [`ErrorCode::SecurityVerificationFailed`] instead of being surfaced as
    /// verified — giving sender authentication / non-repudiation an
    /// enforceable policy switch.
    ///
    /// Default: `false` (encrypted-only messages are accepted), preserving the
    /// RFC 4130 §7.5 "encryption without signing is legal" behaviour. Set to
    /// `true` for deployments that require every message to be signed.
    pub require_signed: bool,
}

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

impl CmsSmimeTrustVerifier {
    /// Create a new verifier with decryption credentials.
    pub fn with_decryption_credentials(key_pem: Vec<u8>, cert_pem: Vec<u8>) -> Self {
        Self {
            decryption_key_pem: Some(key_pem),
            decryption_cert_pem: Some(cert_pem),
            require_signed: false,
        }
    }

    /// Require every inbound message to carry a verifiable S/MIME signature.
    ///
    /// See [`Self::require_signed`]. Chainable:
    ///
    /// ```rust,ignore
    /// let verifier = CmsSmimeTrustVerifier::with_decryption_credentials(key, cert)
    ///     .requiring_signature();
    /// ```
    #[must_use]
    pub fn requiring_signature(mut self) -> Self {
        self.require_signed = true;
        self
    }

    fn build_revocation_policy<'a>(
        session: &'a SessionContext,
    ) -> Result<crate::crypto::wssec::RevocationPolicy<'a>> {
        if session.cert_handle().trust_anchor_pems.is_empty() {
            return Err(AsxError::new(
                ErrorCode::SecurityVerificationFailed,
                "PKIX chain validation requires at least one trust anchor PEM; \
                 call with_cert_handle() and provide trust_anchor_pems before verifying signed AS2 messages",
                ErrorContext::for_session("as2_smime_build_revocation_policy", session),
            ));
        }
        Ok(crate::crypto::wssec::RevocationPolicy {
            trust_anchor_pems: &session.cert_handle().trust_anchor_pems,
            revocation_crl_pems: &session.cert_handle().revocation_crl_pems,
            ocsp_mode: session.cert_handle().ocsp_mode,
            ocsp_failure_mode: session.cert_handle().ocsp_failure_mode,
            stapled_ocsp_responses_der: &session.cert_handle().stapled_ocsp_responses_der,
            responder_ocsp_responses_der: &session.cert_handle().responder_ocsp_responses_der,
            ocsp_cache_namespace: session.partner_id(),
            require_chain_validation: true,
            pre_parsed_trust_anchors: Some(session.trust_anchors_x509()?),
            pre_built_x509_store: Some(session.trust_anchor_x509_store()?),
        })
    }
}

impl private::Sealed for CmsSmimeTrustVerifier {}

impl As2TrustVerifier for CmsSmimeTrustVerifier {
    fn verify_and_decrypt(
        &self,
        session: &SessionContext,
        body: &ReceivedBodyHandle,
    ) -> Result<TrustResult> {
        #[cfg(feature = "as2")]
        {
            let payload = body.materialize_contiguous("as2_smime_verify", session)?;
            let expected_fingerprint = match session.cert_handle().fingerprint_sha256.trim() {
                "" => None,
                value => Some(value),
            };
            let build_options = || -> Result<As2SmimeVerificationOptions<'_>> {
                Ok(As2SmimeVerificationOptions {
                    expected_signer_fingerprint_sha256: expected_fingerprint,
                    revocation_policy: Self::build_revocation_policy(session)?,
                    intermediate_ca_pems: &session.cert_handle().intermediate_ca_pems,
                })
            };

            match detect_smime_format(payload.as_ref()) {
                SmimeFormat::Enveloped => {
                    // ── Decrypt outer EnvelopedData ───────────────────────────────
                    let (key, cert) = match (&self.decryption_key_pem, &self.decryption_cert_pem) {
                        (Some(k), Some(c)) => (k.as_slice(), c.as_slice()),
                        _ => {
                            return Err(AsxError::new(
                                ErrorCode::DecryptionFailed,
                                "AS2 message is encrypted but no decryption key is configured \
                                 on CmsSmimeTrustVerifier; supply decryption_key_pem and \
                                 decryption_cert_pem",
                                ErrorContext::for_session("as2_smime_decrypt", session),
                            ));
                        }
                    };
                    let decrypted = decrypt_smime_enveloped_payload(payload.as_ref(), cert, key)?;
                    // ── Optionally verify inner signature (signed-then-encrypted) ─
                    match detect_smime_format(&decrypted) {
                        SmimeFormat::OpaqueSignedData | SmimeFormat::MultipartSigned => {
                            verify_smime_signed_payload(&decrypted, build_options()?).map_err(|err| {
                                AsxError::new(
                                    ErrorCode::SecurityVerificationFailed,
                                    format!(
                                        "AS2 inner signed message verification failed after decryption: {err}"
                                    ),
                                    ErrorContext::for_session("as2_smime_verify_inner", session),
                                )
                            })?;
                        }
                        _ => {
                            // Unsigned encrypted payload — no inner signature to
                            // verify. The recipient encryption cert is semi-public,
                            // so this authenticates nothing about the sender.
                            if self.require_signed {
                                return Err(AsxError::new(
                                    ErrorCode::SecurityVerificationFailed,
                                    "AS2 message is encrypted but not signed, and \
                                     require_signed is set on CmsSmimeTrustVerifier",
                                    ErrorContext::for_session("as2_smime_require_signed", session),
                                ));
                            }
                        }
                    }
                    let plaintext: Arc<[u8]> = decrypted.into();
                    Ok(TrustResult::decrypted(plaintext))
                }
                // ── Signed-only path: opaque or detached signature ───────────────
                SmimeFormat::OpaqueSignedData | SmimeFormat::MultipartSigned => {
                    verify_smime_signed_payload(payload.as_ref(), build_options()?)?;
                    Ok(TrustResult::signed_only())
                }
                SmimeFormat::Unknown => {
                    // Fall through and attempt verification anyway; OpenSSL will
                    // reject malformed payloads with a clear error.
                    verify_smime_signed_payload(payload.as_ref(), build_options()?)?;
                    Ok(TrustResult::signed_only())
                }
                SmimeFormat::AuthenticatedData => Err(AsxError::new(
                    ErrorCode::InteropViolation,
                    "CMS AuthenticatedData (smime-type=authenticated-data) is not supported \
                         for AS2 message delivery; partner must use SignedData or EnvelopedData",
                    ErrorContext::for_session("as2_smime_verify", session),
                )),
                SmimeFormat::DigestedData => Err(AsxError::new(
                    ErrorCode::InteropViolation,
                    "CMS DigestedData (smime-type=digested-data) is not supported \
                         for AS2 message delivery; partner must use SignedData or EnvelopedData",
                    ErrorContext::for_session("as2_smime_verify", session),
                )),
            }
        }
        #[cfg(not(feature = "as2"))]
        {
            let _ = (session, body);
            Err(AsxError::new(
                ErrorCode::PolicyViolation,
                "CmsSmimeTrustVerifier requires the 'as2' feature",
                ErrorContext::new("as2_smime_feature_disabled"),
            ))
        }
    }
}