Bundle: redb-route / redb.Route.As2 (redb.Route.As2.txt), 29 files
Snapshot: development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/redb.Route.As2/As2Component.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/As2Component.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Extensions;
using redb.Route.Http;
namespace redb.Route.As2;
///
/// AS2 (RFC 4130) transport component for redb.Route. Schemes: as2 (HTTP) and as2s (HTTPS).
///
/// Consumer URI (receive server): as2:/inbound/orders?host=0.0.0.0&port=4080&connectionFactory=partner.
/// Producer URI (send to partner): as2s://partner.example.com:443/as2?connectionFactory=partner.
///
/// Consumer vs producer is chosen by the DSL (.From(...) → consumer, .To(...) → producer),
/// not here — see . Partner certificates/IDs/algorithms are resolved from a named
/// in the registry.
///
public sealed class As2Component : ComponentBase
{
// Standalone fallback server, used only when no shared instance was injected from DI (e.g. tests, or an
// AS2-only host that did not call AddRedbRouteHttpHosting).
private readonly Lazy _ownServer = new(() => new SharedHttpServerManager());
///
/// The shared Kestrel receive server, injected from DI so that HTTP-based connectors (redb.Route.Http,
/// redb.Route.As2, …) in the same worker share ONE server — one Kestrel per host:port, routes
/// multiplexed, no port fights. Set by the DI registrar; owned by the container.
///
public SharedHttpServerManager? ServerManager { get; set; }
/// Correlates outgoing async messages with the MDN receipts partners post back later.
internal As2CorrelationStore Correlation { get; } = new();
///
/// The server to host AS2 receive endpoints on. Resolution order:
///
/// - — set by the DI registrar (AddRedbRouteAs2).
/// - the shared instance from the route context's service provider — this is the path that matters
/// under Tsak, where connectors are loaded from the shared folder via Activator.CreateInstance
/// (no DI injection), so the component shares the one the host
/// registered (via AddRedbRouteHttp/AddRedbRouteHttpHosting) instead of spinning its own.
/// - a private fallback — standalone/tests with no DI at all.
///
///
internal SharedHttpServerManager Server =>
ServerManager
?? Context.Resolve()
?? _ownServer.Value;
///
public override string Scheme => "as2";
/// HTTPS variant of the AS2 scheme.
public override IReadOnlyList AlternateSchemes => ["as2s"];
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new As2EndpointOptions();
options.BindFromUri(uri.RawParameters);
// The scheme carries the TLS decision: as2s ⇒ HTTPS. Applied after binding, before validation.
if (string.Equals(uri.Scheme, "as2s", StringComparison.OrdinalIgnoreCase))
options.UseTls = true;
// With a connection factory named, the factory is the agreement: an agreement option on the URI would be ignored
// (or win) without a word, so it is refused, naming the parameters and never their values.
if (!string.IsNullOrEmpty(options.ConnectionFactory))
{
var inline = uri.RawParameters.Keys
.Where(k => As2Profile.AgreementOptions.Contains(k, StringComparer.OrdinalIgnoreCase))
.ToList();
if (inline.Count > 0)
throw new ArgumentException(
$"AS2 endpoint names connection factory '{options.ConnectionFactory}' and also sets {string.Join(", ", inline)}: " +
"the agreement comes from the connection factory alone; set it there.", inline[0]);
}
options.Validate();
return new As2Endpoint(uri, this, options);
}
///
public override async ValueTask DisposeAsync()
{
Correlation.Dispose(); // stop the eviction timer
// Only the private fallback is ours to dispose; a DI-injected shared server is owned by the container.
if (_ownServer.IsValueCreated)
await _ownServer.Value.DisposeAsync().ConfigureAwait(false);
}
}
Path: redb-route/redb.Route.As2/As2ConnectionFactory.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/As2ConnectionFactory.cs
----
using System.Security.Cryptography.X509Certificates;
using redb.Route.Core;
namespace redb.Route.As2;
///
/// Describes an AS2 trading partner: our key material, the partner's certificate, identifiers and the
/// agreed profile (algorithms, MDN mode). Registered by name in the route context registry and referenced
/// from a URI via connectionFactory=name — so certificates never live in the URI. This mirrors the
/// framework-wide ConnectionFactory pattern (RabbitMQ/Telegram/...).
///
public sealed class As2ConnectionFactory
{
// ── Key material ─────────────────────────────────────────────────────────
/// Our certificate incl. private key — signs outgoing messages and decrypts incoming ones.
public X509Certificate2? OurCertificate { get; set; }
/// Partner's public certificate — encrypts outgoing messages and verifies their signature.
public X509Certificate2? PartnerCertificate { get; set; }
// ── Identity ─────────────────────────────────────────────────────────────
/// Our AS2 identifier (AS2-From).
public string As2From { get; set; } = "";
/// Partner AS2 identifier (AS2-To).
public string As2To { get; set; } = "";
/// Partner endpoint URL the producer POSTs to.
public string PartnerUrl { get; set; } = "";
// ── Profile ──────────────────────────────────────────────────────────────
/// Sign outgoing messages. Default true.
public bool Sign { get; set; } = true;
/// Encrypt outgoing messages. Default true.
public bool Encrypt { get; set; } = true;
/// Compress the payload. Default false.
public bool Compress { get; set; }
/// Signature digest algorithm. Default sha-256.
public string SignAlg { get; set; } = "sha-256";
/// Encryption algorithm. Default aes-128-cbc.
public string EncryptAlg { get; set; } = "aes-128-cbc";
/// MDN mode. Default .
public As2MdnMode MdnMode { get; set; } = As2MdnMode.Sync;
/// Require/produce a signed MDN. Default true.
public bool SignedMdn { get; set; } = true;
///
/// When true, a send whose MDN is negative, has a MIC mismatch, or lacks a required valid signature throws
/// (the transfer is treated as not confirmed) instead of only logging. Default false: the outcome is
/// surfaced on redbAs2.mdn* headers for the route to act on.
///
public bool RequireValidMdn { get; set; }
/// URL the partner posts asynchronous MDNs to (our receiver).
public string? AsyncMdnUrl { get; set; }
///
/// Receive side: the hosts (DNS names or IP literals, compared case-insensitively) an asynchronous MDN may be
/// posted to. The address comes from the partner's Receipt-Delivery-Option header; a receipt is posted
/// only when the message authenticated, is , and the
/// address's host is listed here. Required for a receive endpoint whose is async.
///
public IList AsyncMdnAllowedHosts { get; set; } = [];
// ── Transport security ───────────────────────────────────────────────────
///
/// PFX certificate our receive server presents to the partner over TLS. Distinct from
/// , which is the S/MIME key for the payload: one secures the
/// connection, the other the message. Lives here so its password stays out of the route URI.
///
public string? SslCertPath { get; set; }
/// Password for .
[Sensitive]
public string? SslCertPassword { get; set; }
///
/// Permits the legacy algorithms sha-1 (broken collision resistance) and 3des (a 64-bit block,
/// SWEET32) for and . Only for a partner that still requires them;
/// default false, so a new agreement does not inherit weak cryptography by copy and paste.
///
public bool AllowLegacyAlgorithms { get; set; }
///
/// Checks the agreement; throws naming and what is
/// missing or wrong: both identifiers, supported (and, unless allowed, non-legacy) algorithms, our certificate with
/// its private key and the partner's certificate wherever something is signed or encrypted, and absolute http(s)
/// URLs. Every endpoint naming the factory calls it when it starts; what only one side needs (a partner URL on a
/// send, receipt hosts on an async receive) that side checks itself.
///
public void Validate(string name) => As2Profile.From(this).Validate($"AS2 connection factory '{name}'");
}
Path: redb-route/redb.Route.As2/As2Consumer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/As2Consumer.cs
----
using System.Diagnostics;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using MimeKit;
using MimeKit.Cryptography;
using redb.Route.Abstractions;
using redb.Route.As2.Crypto;
using redb.Route.As2.Mdn;
using redb.Route.Components;
using redb.Route.Configuration;
using redb.Route.Core;
using redb.Route.Extensions;
using redb.Route.Http;
using redb.Route.Telemetry;
namespace redb.Route.As2;
///
/// AS2 receive side (server): registers a POST route on the shared Kestrel host; checks the sender's identifiers,
/// decrypts and verifies the inbound S/MIME message against the pinned partner certificate, enforces the agreement,
/// computes the MIC, hands the business payload to the route, and answers with the MDN the request asked for:
/// synchronously, or posted to the receipt URL when the message authenticated and the agreement allows it.
///
internal sealed class As2Consumer : IConsumer
{
// MIME headers that describe the S/MIME wrapper — they belong to the transport plane and must NOT be
// copied into the exchange headers (the business Content-Type lives on Message.ContentType; leaking the
// wrapper into Headers["Content-Type"] would override it on a downstream HTTP produce).
private static readonly HashSet WrapperHeaders = new(StringComparer.OrdinalIgnoreCase)
{
"Content-Type", "Content-Transfer-Encoding", "Content-Disposition", "Content-Length", "Content-Encoding",
"Connection", "Keep-Alive", "Transfer-Encoding", "TE", "Trailer", "Upgrade", "Host",
};
// Credentials of the HTTP hop, dropped as the HTTP consumer drops a checked Authorization: a route that logs, forwards
// or echoes its headers must not carry a caller's token or session on. The principal the host resolved from them is
// on the exchange (ExchangePrincipal).
private static readonly HashSet CredentialHeaders = new(StringComparer.OrdinalIgnoreCase)
{
"Authorization", "Proxy-Authorization", "Cookie",
};
private readonly As2Endpoint _endpoint;
private readonly IProcessor _processor;
private readonly As2EndpointOptions _options;
private readonly IHeaderFilterStrategy _headerFilter;
private readonly IAs2CryptoEngine _engine = new As2CryptoEngine();
private readonly ILogger? _logger;
private RouteRegistration? _registration;
private As2Profile? _profile;
// Delivers asynchronous MDNs; owned by this receiver, bounded by the endpoint's timeout.
private HttpClient? _mdnClient;
// Slots of the asynchronous MDN pool (AsyncMdnPoolSize): taken when a message asking for one is admitted, released
// when its receipt is delivered or given up. Not disposed: a post a forced stop left behind still releases into it.
private SemaphoreSlim? _asyncMdnSlots;
private IIdempotentRepository? _duplicates;
private StreamCacheOptions? _spool;
// Unregistering the route stops new deliveries; a partner message already inside the pipeline
// still has to finish before Stop returns, and the listener stays up for the other routes.
private readonly InflightDrainGuard _drain = new();
public As2Consumer(As2Endpoint endpoint, IProcessor processor, As2EndpointOptions options)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_processor = processor ?? throw new ArgumentNullException(nameof(processor));
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = endpoint.Logger;
_headerFilter = endpoint.HeaderFilterStrategy;
}
///
public IEndpoint Endpoint => _endpoint;
private SharedHttpServerManager Server =>
(_endpoint.Component as As2Component)?.Server
?? throw new InvalidOperationException("AS2 endpoint has no As2Component/server.");
///
/// The TLS certificate of the receive server: the endpoint's own, else the one on the named
/// connection factory (which is where its password belongs). Nothing here means the host
/// default is asked next, inside the shared host.
///
private (string? Path, string? Password) ResolveServerCertificate()
{
if (!string.IsNullOrEmpty(_options.SslCertPath))
return (_options.SslCertPath, _options.SslCertPassword);
if (!string.IsNullOrEmpty(_options.ConnectionFactory))
{
var factory = _endpoint.Context.GetRequiredFromRegistry(_options.ConnectionFactory);
if (!string.IsNullOrEmpty(factory.SslCertPath))
return (factory.SslCertPath, factory.SslCertPassword);
}
return (null, null);
}
///
public async Task Start(CancellationToken ct = default)
{
// The agreement is resolved once, here: a misnamed or incomplete one stops the route from starting instead of
// answering the partner's first message with a negative MDN.
var profile = As2Profile.Resolve(_endpoint.Context, _options, _endpoint.Uri.Path);
if (profile.MdnMode == As2MdnMode.Async && profile.AsyncMdnAllowedHosts.Count == 0)
throw new InvalidOperationException(
$"AS2 receive endpoint {_endpoint.Uri.Path}: MdnMode is async, so AsyncMdnAllowedHosts must name the hosts receipts may be posted to; " +
"the address itself comes from the partner's request.");
_profile = profile;
_spool = _endpoint.Context.GetStreamCacheOptions();
// Optional here (RFC 4130 does not mandate it, unlike eDelivery AS4); named, as the AS4 and S3 receivers name it.
_duplicates = string.IsNullOrWhiteSpace(_options.IdempotentRepository) ? null
: (_endpoint.Context ?? throw new InvalidOperationException($"AS2 receive endpoint {_endpoint.Uri.Path} has no route context to resolve its idempotent repository from."))
.GetIdempotentRepositoryProvider().Get(_options.IdempotentRepository);
_asyncMdnSlots = new SemaphoreSlim(_options.AsyncMdnPoolSize, _options.AsyncMdnPoolSize);
// The pool already bounds the posts in flight (a slot is held during its post); the handler states the same bound
// for the connections, and renews them, so a partner's address change is picked up.
_mdnClient = new HttpClient(new SocketsHttpHandler
{
MaxConnectionsPerServer = _options.AsyncMdnPoolSize,
PooledConnectionLifetime = TimeSpan.FromMinutes(5),
})
{
Timeout = _options.Timeout > 0 ? TimeSpan.FromMilliseconds(_options.Timeout) : Timeout.InfiniteTimeSpan,
};
_drain.Start(ct);
var host = _options.Host;
var port = _options.Port;
var path = _endpoint.Uri.Path; // e.g. "/inbound/orders" — kept intact by the DSL
// The TLS server certificate travels with the registration. Earlier it did not, so an
// as2s:// receiver opened a PLAINTEXT port while PartnerUrl advertised https:// to the
// trading partner.
var (certPath, certPassword) = ResolveServerCertificate();
_registration = Server.RegisterRoute(host, port, path, "POST", HandleRequest,
_options.UseTls, certPath, certPassword,
maxRequestBodySize: _options.MaxRequestBodySize,
concurrencyLimit: ConcurrencyLimitOptions.FromEndpoint(
_options.MaxConcurrentRequests, _options.RequestQueueLimit,
_options.RejectStatusCode, _options.RetryAfterSeconds,
onRejected: _endpoint.RecordRejected));
try
{
await Server.EnsureStarted(host, port, ct).ConfigureAwait(false);
}
catch
{
// The listener did not come up: the route leaves it and the MDN client goes, so a later Start
// registers once and builds one client.
await Stop(CancellationToken.None).ConfigureAwait(false);
throw;
}
_logger?.LogInformation("AS2 consumer started: {Host}:{Port}{Path}", host, port, path);
}
///
public async Task Stop(CancellationToken ct = default)
{
if (_registration is not null)
{
Server.UnregisterRoute(_registration);
_registration = null;
// The drain also waits for asynchronous MDNs still being posted: each is counted like a request.
await _drain.DrainAsync(ct, _logger, $"as2://{_options.Host}:{_options.Port}").ConfigureAwait(false);
await Server.StopIfEmpty(_options.Host, _options.Port, ct).ConfigureAwait(false);
}
_mdnClient?.Dispose();
_mdnClient = null;
_logger?.LogInformation("AS2 consumer stopped: {Host}:{Port}", _options.Host, _options.Port);
}
private async Task HandleRequest(HttpContext http)
{
// Counted for the drain: unregistering the route stops new deliveries, but a partner's
// message already being verified, decrypted and routed must finish before Stop returns.
_drain.Increment();
AsyncMdnSlot? slot = null;
try
{
// A message that asks for an asynchronous MDN takes its slot now, before any work: with every slot taken it
// is refused, as the admission limit refuses, and the partner resends it later. RFC 4130 §7 puts the
// response before the MDN, so the receiver cannot post the receipt in the caller's place instead.
if (_profile!.MdnMode == As2MdnMode.Async && !string.IsNullOrEmpty(http.Request.Headers[As2Headers.ReceiptDeliveryOption].ToString()))
{
slot = AsyncMdnSlot.TryTake(_asyncMdnSlots!);
if (slot is null)
{
RefuseBusy(http, "every asynchronous MDN slot is taken");
As2Metrics.AsyncMdnRejected.Add(1);
return;
}
}
await HandleRequestCore(http, slot).ConfigureAwait(false);
}
finally
{
// Handed over: the post releases it when the receipt is delivered or given up.
if (slot is { HandedOver: false }) slot.Release();
_drain.Decrement();
}
}
///
/// Answers a request the receiver will not take now with and
/// , the answer of the admission limit.
///
private void RefuseBusy(HttpContext http, string reason)
{
_endpoint.RecordRejected();
_logger?.LogWarning("AS2 receiver {Path}: message {MessageId} refused with {Status}, {Reason} (ref {Reference}).",
http.Request.Path, http.Request.Headers[As2Headers.MessageId].ToString(), _options.RejectStatusCode, reason, http.TraceIdentifier);
http.Response.StatusCode = _options.RejectStatusCode;
if (_options.RetryAfterSeconds > 0)
http.Response.Headers.RetryAfter = _options.RetryAfterSeconds.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
///
/// A slot of the asynchronous MDN pool. The request holds it until it answers; when the receipt is posted after the
/// answer, the post takes it over and releases it once the receipt is delivered or given up.
///
private sealed class AsyncMdnSlot
{
private readonly SemaphoreSlim _pool;
private int _released;
private AsyncMdnSlot(SemaphoreSlim pool) => _pool = pool;
public static AsyncMdnSlot? TryTake(SemaphoreSlim pool) => pool.Wait(0) ? new AsyncMdnSlot(pool) : null;
public bool HandedOver { get; set; }
public void Release()
{
if (Interlocked.Exchange(ref _released, 1) == 0) _pool.Release();
}
}
private async Task HandleRequestCore(HttpContext http, AsyncMdnSlot? slot)
{
using var span = StartReceiveSpan(_endpoint, http.Request);
var request = http.Request;
var profile = _profile!;
var reference = http.TraceIdentifier;
var originalMessageId = request.Headers[As2Headers.MessageId].ToString();
var receipt = ReceiptRequest.Of(request, profile);
if (receipt.RequestedMicAlgs is { Count: > 0 } asked && !asked.Contains(receipt.MicAlg, StringComparer.OrdinalIgnoreCase))
_logger?.LogWarning("AS2 receiver {Path}: message {MessageId} asks for micalg {Asked}; none is usable here, the MIC is {Used}.",
request.Path, originalMessageId, string.Join(", ", asked), receipt.MicAlg);
As2Mic? mic = null;
var signatureValid = false;
var wasSigned = false;
var wasEncrypted = false;
var authenticated = false; // the sender is the agreed partner, as far as the agreement can tell
string? failure = null; // RFC 4130 §7.4.3 modifier of a message that was not processed
IExchange? exchange = null;
var claimed = false; // this request holds the duplicate-detection claim of its Message-ID
string? claimToken = null; // the id of that claim, so a takeover's claim is never settled by this request
var duplicate = false; // the Message-ID was received and processed before
var inFlight = false; // an earlier copy of the Message-ID is still being processed
var processed = false; // the route processed the document
// The request and every stage unwrapped from it live in spools (the core stream cache: memory, or a temporary
// file past the threshold), parsed by MimeKit in place; all of them go when the request is answered.
StreamCache? mime = null;
var spools = new List();
try
{
// The MIME headers of the wrapper and the body, in one spool; bounded by maxRequestBodySize.
mime = await As2Http.ReadBodyAsync(http, _options.MaxRequestBodySize, MimeHeaderPrefix(request), _spool!, http.RequestAborted)
.ConfigureAwait(false);
if (mime is null)
{
_logger?.LogWarning("AS2 receiver {Path}: request refused, its body is over maxRequestBodySize {Limit} bytes (ref {Reference}).",
request.Path, _options.MaxRequestBodySize, reference);
_endpoint.RecordError(new InvalidOperationException(
$"AS2 receiver {request.Path}: request refused, its body is over maxRequestBodySize {_options.MaxRequestBodySize} bytes (ref {reference})."));
span.Activity?.SetStatus(ActivityStatusCode.Error, "request body over maxRequestBodySize");
return;
}
// The agreement names both parties (RFC 4130 §6.2): a message from another sender, or for another
// recipient, is not ours to process, whatever it carries.
var from = request.Headers[As2Headers.As2From].ToString();
var to = request.Headers[As2Headers.As2To].ToString();
if (!IsAgreedIdentifier(from, profile.As2To) || !IsAgreedIdentifier(to, profile.As2From))
throw new As2DispositionException(As2Disposition.AuthenticationFailed,
$"AS2-From '{from}' and AS2-To '{to}' are not the agreement's '{profile.As2To}' and '{profile.As2From}'.");
// A receipt option the sender marked required and this receiver cannot honour (RFC 4130 §7.5.3): the MDN is
// failed/Failure and the message is not processed.
if (receipt.Failure is { } receiptFailure)
throw new As2DispositionException(receiptFailure,
$"Disposition-Notification-Options '{request.Headers[As2Headers.DispositionNotificationOptions]}' requires what this receiver cannot honour.");
// Unwrap: decrypt (outer), then the signature and the compression in the order they were applied: compress
// then sign (RFC 5402 §3.2/3.5) or sign then compress (§3.3/3.6), each at most once.
var entity = MimeEntity.Load(mime, persistent: true);
var wasCompressed = false;
if (entity is ApplicationPkcs7Mime { SecureMimeType: SecureMimeType.EnvelopedData } enveloped)
{
if (profile.OurCertificate is null)
throw new As2DispositionException(As2Disposition.DecryptionFailed,
"the message is encrypted and the agreement has no certificate of ours to decrypt it.");
try { entity = Unwrap(spools, s => _engine.DecryptTo(enveloped, profile.OurCertificate, s)); }
catch (Exception e) when (e is not OperationCanceledException)
{
throw new As2DispositionException(As2Disposition.DecryptionFailed, $"decryption failed: {e.Message}", e);
}
wasEncrypted = true;
}
while (true)
{
if (!wasSigned && entity is MultipartSigned signed)
{
if (profile.PartnerCertificate is null)
throw new As2DispositionException(As2Disposition.AuthenticationFailed,
"the message is signed and the agreement has no partner certificate to verify it.");
if (As2CertificateValidity.Problem(profile.PartnerCertificate, DateTimeOffset.UtcNow, "The partner's signing certificate") is { } invalid)
throw new As2DispositionException(As2Disposition.AuthenticationFailed, invalid);
try { signatureValid = _engine.Verify(signed, profile.PartnerCertificate); }
catch (Exception e) when (e is not OperationCanceledException)
{
throw new As2DispositionException(As2Disposition.AuthenticationFailed, $"signature verification failed: {e.Message}", e);
}
// RFC 5402 §4.1: over the data that was signed, compressed or not.
mic = _engine.ComputeReceivedMic(signed[0], receipt.MicAlg);
entity = signed[0];
wasSigned = true;
}
else if (!wasCompressed && entity is ApplicationPkcs7Mime { SecureMimeType: SecureMimeType.CompressedData } compressed)
{
// Bounded while it inflates: a small body can expand to gigabytes.
try { entity = Unwrap(spools, s => _engine.DecompressTo(compressed, new BoundedWriteStream(s, _options.DecompressedLimit, "maxDecompressedSize"))); }
catch (Exception e) when (e is not OperationCanceledException)
{
throw new As2DispositionException(As2Disposition.DecompressionFailed, $"decompression failed: {e.Message}", e);
}
wasCompressed = true;
}
else
break;
}
// Unsigned: over the (uncompressed) part with its MIME headers, as it arrived, when it was encrypted (RFC 4130
// §7.3.1, RFC 5402 §4.2); over its content alone when it was not, compressed or plain (RFC 4130 §7.3.1, and
// what OpenAS2 computes for a compressed unencrypted message).
mic ??= wasEncrypted
? _engine.ComputeReceivedMic(entity, receipt.MicAlg)
: _engine.ComputeMic(entity, receipt.MicAlg, includeHeaders: false);
// ENFORCE the profile before handing the payload to the route: a message that the partnership
// requires to be signed/encrypted but is not, or whose signature did not verify, is rejected with a
// negative MDN — never processed as if trusted.
if (wasSigned && !signatureValid)
throw new As2DispositionException(As2Disposition.AuthenticationFailed,
"the signature does not verify against the partner certificate (another signer, or altered content).");
if (profile.Encrypt && !wasEncrypted)
throw new As2DispositionException(As2Disposition.InsufficientMessageSecurity,
"the message is not encrypted and the agreement requires encryption.");
if (profile.Sign && !wasSigned)
throw new As2DispositionException(As2Disposition.InsufficientMessageSecurity,
"the message is not signed and the agreement requires a signature.");
authenticated = true;
// Duplicate detection, the AS4 receiver's two-phase claim (Lease, then Confirm or Release of that claim): claimed
// only now, so a forged copy cannot burn the id of the real message; taken uncancelled, as Confirm and Release are.
if (_duplicates is not null)
{
if (string.IsNullOrWhiteSpace(originalMessageId))
throw new As2DispositionException(As2Disposition.UnexpectedProcessingError,
"the message has no Message-ID (RFC 4130 requires one), and duplicate detection needs it.");
// A copy whose first one is still in a route is not a duplicate yet: the first may fail and release its
// claim, and a duplicate-document MDN would have told the partner the document arrived. It is refused as
// busy, and the partner resends it. A claim older than inFlightClaimTimeout was left by a stopped node.
var lease = await _duplicates.Lease(originalMessageId, TimeSpan.FromMilliseconds(_options.InFlightClaimTimeout), CancellationToken.None)
.ConfigureAwait(false);
claimToken = lease.Token;
switch (lease.Outcome)
{
case IdempotentClaim.Claimed:
claimed = true;
break;
case IdempotentClaim.TakenOver:
claimed = true;
_logger?.LogWarning("AS2 receiver {Path}: message {MessageId} had a claim older than inFlightClaimTimeout {Timeout} ms " +
"that was never confirmed; taken over and processed.", request.Path, originalMessageId, _options.InFlightClaimTimeout);
break;
case IdempotentClaim.InFlight:
inFlight = true;
break;
default:
duplicate = true;
_logger?.LogInformation("AS2 receiver {Path}: message {MessageId} is a duplicate; answered, not delivered again.",
request.Path, originalMessageId);
break;
}
}
if (!duplicate && !inFlight)
{
// Extract the business payload.
var (payload, payloadContentType) = ExtractPayload(entity, _spool!, _options.StreamBody);
// Build the exchange. Content-Type comes from the INNER part (Message.ContentType); the wrapper
// Content-Type is deliberately NOT copied into the headers.
var message = new Message(payload) { ContentType = payloadContentType };
exchange = Exchange.Create(message, _endpoint.ScopeFactory);
CopyInboundHeaders(request, message, _headerFilter, exchange);
// The header reports a verification: an unsigned message had none.
message.Headers[As2Headers.SignatureValid] = wasSigned && signatureValid;
if (mic is not null)
{
message.Headers[As2Headers.Mic] = mic.Value.Digest;
message.Headers[As2Headers.MicAlg] = mic.Value.Algorithm;
}
if (http.Connection.RemoteIpAddress is not null)
message.Headers[As2Headers.RemoteAddress] = http.Connection.RemoteIpAddress.ToString();
if (!string.IsNullOrEmpty(_options.ConnectionFactory))
message.Headers[As2Headers.PartnerName] = _options.ConnectionFactory;
exchange.Pattern = ExchangePattern.InOut;
ExchangePrincipal.Set(exchange, SharedHttpServerManager.GetResolvedPrincipal(http));
// Cancelled when the sender goes away, and when a stop outlasts the drain timeout.
using (var processing = CancellationTokenSource.CreateLinkedTokenSource(http.RequestAborted, _drain.ProcessingToken))
await _processor.Process(exchange, processing.Token).ConfigureAwait(false);
if (exchange.EndedInFailure())
{
// No RecordError: the core StatisticsProcessor saw the same exchange.Exception.
_logger?.LogWarning(exchange.Exception, "AS2 receiver {Path}: route failed for message {MessageId} (ref {Reference}).",
request.Path, originalMessageId, reference);
if (exchange.Exception is { } routeFailure) span.Activity.RecordFailure(routeFailure);
failure = As2Disposition.UnexpectedProcessingError;
}
else
{
processed = true;
}
}
}
catch (As2DispositionException e)
{
_logger?.LogWarning(e, "AS2 receiver {Path}: message {MessageId} refused with {Disposition} (ref {Reference}): {Detail}",
request.Path, originalMessageId, e.Modifier, reference, e.Message);
_endpoint.RecordError(e);
span.Activity.RecordFailure(e);
failure = e.Modifier;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger?.LogError(ex, "AS2 receiver {Path}: message {MessageId} not processed (ref {Reference}).",
request.Path, originalMessageId, reference);
_endpoint.RecordError(ex);
span.Activity.RecordFailure(ex);
failure = As2Disposition.UnexpectedProcessingError;
}
finally
{
if (exchange is not null)
await exchange.DisposeAsync().ConfigureAwait(false);
foreach (var spool in spools)
await spool.DisposeAsync().ConfigureAwait(false);
if (mime is not null)
await mime.DisposeAsync().ConfigureAwait(false);
// Processed: the id stays. Anything else (the route failed, threw, or was cancelled): released, so the
// partner's resend is delivered and not taken for a duplicate.
if (claimed)
await SettleClaimAsync(originalMessageId, claimToken, processed).ConfigureAwait(false);
}
if (inFlight)
{
RefuseBusy(http, "an earlier copy of it is still being processed");
return;
}
// RFC 4130 §7.3: an MDN only when the sender asked for one (Disposition-Notification-To), and never when the
// agreement says none.
if (profile.MdnMode == As2MdnMode.None || !receipt.Requested)
{
http.Response.StatusCode = StatusCodes.Status200OK;
return;
}
// Signed when the request asks for a signed receipt, with the micalg it asked for. A failure carries its code
// and our reference only. A receipt that cannot be made as required (receipt.Failure) goes unsigned: it reports
// exactly that no MDN as asked could be generated.
var sign = receipt.Signed && receipt.Failure is null && profile.OurCertificate is not null;
if (receipt.Signed && receipt.Failure is null && profile.OurCertificate is null)
_logger?.LogWarning("AS2 receiver {Path}: message {MessageId} asks for a signed MDN and the agreement has no certificate of ours; " +
"the MDN is unsigned (ref {Reference}).", request.Path, originalMessageId, reference);
var (mdnContentType, mdnCte, mdnBody) = MdnBuilder.Build(
originalMessageId, profile.As2From, profile.As2To, mic, failure, reference,
warning: duplicate ? "duplicate-document" : null,
signer: sign ? _engine : null,
signerCert: sign ? profile.OurCertificate : null,
signAlg: receipt.MicAlg);
// Async MDN: posted only for a sender that authenticated, in an agreement that says async, to a host the
// agreement names — the address comes from the request, so anything less lets any caller make us POST (a
// receipt signed by our key) wherever it likes. Otherwise the receipt is the response to this request.
var receiptUrl = http.Request.Headers[As2Headers.ReceiptDeliveryOption].ToString();
if (!string.IsNullOrEmpty(receiptUrl) && AsyncReceiptRefusal(receiptUrl, authenticated, profile) is { } refusal)
{
_logger?.LogWarning("AS2 receiver {Path}: asynchronous MDN for message {MessageId} not posted to '{Url}': {Reason}; " +
"the MDN is returned in the response (ref {Reference}).", request.Path, originalMessageId, receiptUrl, refusal, reference);
receiptUrl = "";
}
if (!string.IsNullOrEmpty(receiptUrl) && slot is not null)
{
http.Response.StatusCode = StatusCodes.Status200OK;
// Answered first, posted after: the sender's wait for 200 must not depend on its own MDN endpoint. The
// post is counted for the drain and cancelled by a forced stop, not by this request's end; it keeps the
// request's slot until the receipt is delivered or given up.
_drain.Increment();
slot.HandedOver = true;
_ = Task.Run(async () =>
{
try { await PostAsyncMdn(receiptUrl, mdnContentType, mdnCte, mdnBody, profile, originalMessageId, _drain.ProcessingToken).ConfigureAwait(false); }
finally
{
slot.Release();
_drain.Decrement();
}
});
}
else
{
var response = http.Response;
response.StatusCode = StatusCodes.Status200OK;
response.ContentType = mdnContentType;
response.Headers[As2Headers.As2Version] = "1.2";
if (!string.IsNullOrEmpty(profile.As2From)) response.Headers[As2Headers.As2From] = As2Headers.FormatName(profile.As2From);
if (!string.IsNullOrEmpty(profile.As2To)) response.Headers[As2Headers.As2To] = As2Headers.FormatName(profile.As2To);
response.Headers[As2Headers.MessageId] = $"<{Guid.NewGuid():N}@redb.route>";
if (!string.IsNullOrEmpty(mdnCte)) response.Headers["Content-Transfer-Encoding"] = mdnCte;
await response.Body.WriteAsync(mdnBody, http.RequestAborted).ConfigureAwait(false);
}
}
///
/// Why an asynchronous MDN is not posted to , or null when it is. The host must be one the
/// agreement lists () — a name is trusted as the operator
/// wrote it; what it resolves to is not checked again.
///
private static string? AsyncReceiptRefusal(string url, bool authenticated, As2Profile profile)
{
if (!authenticated)
return "the message did not authenticate";
if (profile.MdnMode != As2MdnMode.Async)
return $"the agreement's MDN mode is {profile.MdnMode}";
if (!Uri.TryCreate(url, UriKind.Absolute, out var uri) || (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps))
return "it is not an absolute http(s) URL";
if (!string.IsNullOrEmpty(uri.UserInfo))
return "it carries user information";
var host = uri.Host.Trim('[', ']');
if (!profile.AsyncMdnAllowedHosts.Any(h => string.Equals(h.Trim('[', ']'), host, StringComparison.OrdinalIgnoreCase)))
return $"host '{host}' is not in AsyncMdnAllowedHosts";
return null;
}
///
/// Confirms the claim of a processed message, or releases one the route did not process (as the AS4 and S3
/// receivers do). The answer goes out either way, so a failure here is logged: a failed confirm leaves the claim in
/// place; a failed release leaves the id marked until it is cleaned up. Only this request's claim is settled: when
/// processing outlived inFlightClaimTimeout and another node took the claim over, nothing of its claim is touched.
///
private async Task SettleClaimAsync(string messageId, string? token, bool processed)
{
try
{
var settled = processed
? await _duplicates!.Confirm(messageId, token, CancellationToken.None).ConfigureAwait(false)
: await _duplicates!.Release(messageId, token, CancellationToken.None).ConfigureAwait(false);
if (!settled)
_logger?.LogWarning("AS2 receiver {Path}: the claim of message {MessageId} was taken over while it was processed " +
"(longer than inFlightClaimTimeout {Timeout} ms); the new holder's claim is left as it is.",
_endpoint.Uri.Path, messageId, _options.InFlightClaimTimeout);
}
catch (Exception e) when (e is not OperationCanceledException)
{
_logger?.LogWarning(e, "AS2 receiver {Path}: {Action} the duplicate claim of message {MessageId} failed.",
_endpoint.Uri.Path, processed ? "confirming" : "releasing", messageId);
}
}
///
/// Whether a received AS2-From/AS2-To is the agreed identifier: RFC 4130 §6.2 allows a quoted-string
/// and compares case-sensitively.
///
internal static bool IsAgreedIdentifier(string? received, string agreed)
{
if (string.IsNullOrEmpty(agreed) || string.IsNullOrWhiteSpace(received)) return false;
var value = received.Trim();
if (value.Length >= 2 && value[0] == '"' && value[^1] == '"')
value = value[1..^1].Replace("\\\"", "\"", StringComparison.Ordinal).Replace("\\\\", "\\", StringComparison.Ordinal);
return string.Equals(value, agreed, StringComparison.Ordinal);
}
///
/// Posts an asynchronous MDN, at most times: again after a
/// connection failure, a timeout, 408, 429 or a 5xx answer, waiting
/// doubled for each retry; another 4xx is the partner refusing the receipt itself, and sending it again changes
/// nothing. Every attempt carries the same Message-ID, so the partner can tell a resend. A receipt given up is logged
/// and counted (redb.route.as2.mdn.async_failed).
///
private async Task PostAsyncMdn(string url, string contentType, string? transferEncoding, byte[] body, As2Profile profile,
string originalMessageId, CancellationToken ct)
{
var mdnMessageId = $"<{Guid.NewGuid():N}@redb.route>";
var delay = _options.AsyncMdnRetryDelay;
// Runs detached from the request, so nothing above it would see an exception: every outcome is logged here.
for (var attempt = 1; ; attempt++)
{
string outcome;
Exception? failure = null;
try
{
using var content = new ByteArrayContent(body);
content.Headers.TryAddWithoutValidation("Content-Type", contentType);
if (!string.IsNullOrEmpty(transferEncoding))
content.Headers.TryAddWithoutValidation("Content-Transfer-Encoding", transferEncoding);
using var request = new HttpRequestMessage(HttpMethod.Post, url) { Content = content };
if (!string.IsNullOrEmpty(profile.As2From)) request.Headers.TryAddWithoutValidation(As2Headers.As2From, As2Headers.FormatName(profile.As2From));
if (!string.IsNullOrEmpty(profile.As2To)) request.Headers.TryAddWithoutValidation(As2Headers.As2To, As2Headers.FormatName(profile.As2To));
request.Headers.TryAddWithoutValidation(As2Headers.MessageId, mdnMessageId);
var client = _mdnClient ?? throw new OperationCanceledException("the receiver is stopped.");
using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
if (response.IsSuccessStatusCode)
{
if (attempt > 1)
_logger?.LogInformation("AS2 asynchronous MDN for message {MessageId} to {Url} delivered on attempt {Attempt}.",
originalMessageId, url, attempt);
return;
}
var status = (int)response.StatusCode;
outcome = $"answered {status}";
if (status is not (408 or 429) && status < 500)
{
GiveUp(originalMessageId, url, attempt, outcome, null);
return;
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested || _mdnClient is null)
{
_logger?.LogWarning("AS2 asynchronous MDN for message {MessageId} to {Url} not delivered: the receiver stopped.",
originalMessageId, url);
As2Metrics.AsyncMdnFailed.Add(1);
return;
}
catch (Exception ex)
{
// A connection failure, or the endpoint's timeout (HttpClient reports it as a cancellation).
outcome = "not delivered";
failure = ex;
}
if (attempt >= _options.AsyncMdnAttempts)
{
GiveUp(originalMessageId, url, attempt, outcome, failure);
return;
}
_logger?.LogWarning(failure, "AS2 asynchronous MDN for message {MessageId} to {Url} {Outcome} on attempt {Attempt} of {Attempts}; " +
"tried again in {Delay} ms.", originalMessageId, url, outcome, attempt, _options.AsyncMdnAttempts, delay);
try { await Task.Delay(delay, ct).ConfigureAwait(false); }
catch (OperationCanceledException)
{
_logger?.LogWarning("AS2 asynchronous MDN for message {MessageId} to {Url} not delivered: the receiver stopped.",
originalMessageId, url);
As2Metrics.AsyncMdnFailed.Add(1);
return;
}
delay = (int)Math.Min((long)delay * 2, int.MaxValue);
}
}
private void GiveUp(string originalMessageId, string url, int attempts, string outcome, Exception? failure)
{
_logger?.LogError(failure, "AS2 asynchronous MDN for message {MessageId} to {Url} given up: {Outcome} after {Attempts} attempt(s).",
originalMessageId, url, outcome, attempts);
_endpoint.RecordError(failure ?? new InvalidOperationException($"asynchronous MDN to {url} {outcome}."));
As2Metrics.AsyncMdnFailed.Add(1);
}
// ── Helpers ──────────────────────────────────────────────────────────────
///
/// The Consumer span of a received request, on the core contract ():
/// the host's request span when the application traces ASP.NET Core, else the sender's traceparent, else a
/// root; the sender's baggage is put back; EnableTelemetry=false opens nothing. Named after its destination,
/// the receive path.
///
internal static TransportSpan StartReceiveSpan(As2Endpoint endpoint, HttpRequest request) =>
RouteTelemetryExtensions.StartConsumerSpan(
endpoint.Context, $"{endpoint.Uri.Path} receive", ActivityKind.Consumer,
"messaging.system", "as2", endpoint.Uri.NormalizedKey,
request.Headers, static (headers, name) => headers.TryGetValue(name, out var value) ? value.ToString() : null,
InboundParent.HostRequest, destination: endpoint.Uri.Path, operation: "receive");
/// The MIME headers of the inbound entity, rebuilt from the HTTP headers that carry them.
private static byte[] MimeHeaderPrefix(HttpRequest request)
{
var sb = new StringBuilder();
sb.Append("Content-Type: ").Append(request.ContentType ?? "application/octet-stream").Append("\r\n");
if (request.Headers.TryGetValue("Content-Transfer-Encoding", out var cte))
sb.Append("Content-Transfer-Encoding: ").Append(cte.ToString()).Append("\r\n");
if (request.Headers.TryGetValue("Content-Disposition", out var cd))
sb.Append("Content-Disposition: ").Append(cd.ToString()).Append("\r\n");
sb.Append("\r\n");
return Encoding.ASCII.GetBytes(sb.ToString());
}
///
/// Runs one unwrapping step into a new spool and parses its output in place (MimeKit's persistent mode keeps the
/// parts as views of the spool). The spool lives until the request is answered; a failed step leaves nothing behind.
///
private MimeEntity Unwrap(List spools, Action step)
{
var spool = new StreamCache(_spool!);
spools.Add(spool);
step(spool);
spool.CompleteWriting();
spool.Position = 0;
return MimeEntity.Load(spool, persistent: true);
}
///
/// The business payload, decoded into a spool of its own. With the spool is the body
/// (the exchange closes it); otherwise its bytes are, and the spool goes at once.
///
private static (object payload, string? contentType) ExtractPayload(MimeEntity entity, StreamCacheOptions options, bool streamBody)
{
var spool = new StreamCache(options);
var keep = false;
try
{
string? contentType;
if (entity is MimePart { Content: not null } part)
{
part.Content.DecodeTo(spool);
contentType = part.ContentType?.MimeType;
}
else
{
// Non-leaf payload (rare): the whole entity.
entity.WriteTo(spool);
contentType = entity.ContentType?.MimeType;
}
spool.CompleteWriting();
spool.Position = 0;
if (streamBody)
{
keep = true;
return (spool, contentType);
}
var bytes = new byte[spool.Length];
spool.ReadExactly(bytes);
return (bytes, contentType);
}
finally
{
if (!keep) spool.Dispose();
}
}
///
/// Copies AS2/business request headers verbatim, skipping the S/MIME wrapper + hop-by-hop set and the hop's
/// credentials; decides the rest.
///
private static void CopyInboundHeaders(HttpRequest request, IMessage message, IHeaderFilterStrategy headerFilter,
IExchange exchange)
{
foreach (var header in request.Headers)
{
if (header.Key.StartsWith(':')) continue; // pseudo-headers
if (WrapperHeaders.Contains(header.Key)) continue; // wrapper / hop-by-hop
if (CredentialHeaders.Contains(header.Key)) continue; // they authenticated the hop, not the document
var value = header.Value.Count == 1 ? header.Value[0] : header.Value.ToString();
if (headerFilter.FilterIncoming(header.Key, value, exchange)) continue;
message.Headers[header.Key] = value;
}
}
}
Path: redb-route/redb.Route.As2/As2CorrelationStore.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/As2CorrelationStore.cs
----
using System.Collections.Concurrent;
using redb.Route.As2.Crypto;
namespace redb.Route.As2;
///
/// Correlates asynchronous AS2 MDNs with the messages that requested them: a producer sending in async mode records
/// the outgoing Message-ID and the MIC it expects back; when the partner later POSTs the MDN to our receiver, the MIC
/// is looked up by Original-Message-ID and compared. Nothing waits on an entry — the verdict reaches the
/// ReceiveMdn route as its own exchange. In-memory and per-process: after a restart, past the TTL, or on another
/// node an MDN finds no entry and its MIC status is unknown (see ).
///
internal sealed class As2CorrelationStore : IDisposable
{
private sealed record Pending(As2Mic ExpectedMic, DateTimeOffset RegisteredAt);
private readonly ConcurrentDictionary _pending = new(StringComparer.Ordinal);
private readonly Timer _sweepTimer;
private readonly TimeSpan _maxAge;
/// Evict pending entries older than this (default 30 min).
/// How often to run the sweep (default 5 min).
public As2CorrelationStore(TimeSpan? maxAge = null, TimeSpan? sweepInterval = null)
{
_maxAge = maxAge ?? TimeSpan.FromMinutes(30);
var interval = sweepInterval ?? TimeSpan.FromMinutes(5);
// Periodic eviction: a partner that never delivers a promised async MDN would otherwise leave one entry per
// message forever.
_sweepTimer = new Timer(static s => ((As2CorrelationStore)s!).Sweep(((As2CorrelationStore)s!)._maxAge),
this, interval, interval);
}
///
public void Dispose() => _sweepTimer.Dispose();
/// Records an outgoing message awaiting an async MDN, with the MIC the MDN must carry.
public void Register(string messageId, As2Mic expectedMic) =>
_pending[messageId] = new Pending(expectedMic, DateTimeOffset.UtcNow);
/// The MIC expected for a pending message, or null if unknown.
public As2Mic? ExpectedMic(string messageId)
=> _pending.TryGetValue(messageId, out var pending) ? pending.ExpectedMic : null;
/// Removes the entry of a message whose MDN has been accepted. False if there was none.
public bool Complete(string messageId) => _pending.TryRemove(messageId, out _);
/// Evicts pending entries older than ; returns how many.
public int Sweep(TimeSpan maxAge)
{
var cutoff = DateTimeOffset.UtcNow - maxAge;
var removed = 0;
foreach (var (key, pending) in _pending)
if (pending.RegisteredAt < cutoff && _pending.TryRemove(key, out _))
removed++;
return removed;
}
}
Path: redb-route/redb.Route.As2/As2Endpoint.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/As2Endpoint.cs
----
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
namespace redb.Route.As2;
///
/// AS2 endpoint. Extends so it gets statistics, health and Tsak
/// visibility for free. Produces an
/// (send) or an (receive server) depending on the DSL side.
///
public sealed class As2Endpoint : EndpointBase
{
/// Logger inherited from the owning component.
internal ILogger? Logger { get; }
/// Typed options, exposed to the consumer/producer.
internal As2EndpointOptions EndpointOptions => Options;
/// The owning route context (for registry lookups), via the component.
internal IRouteContext? Context => (Component as ComponentBase)?.Context;
/// Creates an AS2 endpoint.
public As2Endpoint(EndpointUri uri, As2Component component, As2EndpointOptions options)
: base(uri, component, options)
{
ArgumentNullException.ThrowIfNull(component);
Logger = component.Logger;
// Producer URIs are host-style (as2s://partner/as2 ⇒ path "partner/as2"); reconstruct the partner
// URL from the scheme + path. Consumer URIs are path-style ("/inbound/orders") and skip this.
if (string.IsNullOrEmpty(options.PartnerUrl) && uri.Path.Length > 0 && !uri.Path.StartsWith('/'))
options.PartnerUrl = (options.UseTls ? "https://" : "http://") + uri.Path;
_headerFilter = new EndpointHeaderFilter(this, options.HeaderFilterStrategy);
}
private readonly EndpointHeaderFilter _headerFilter;
///
/// The header filter strategy of this endpoint: the one headerFilterStrategy=#name names, or
/// . A name the registry does not hold fails when the producer or
/// consumer is built.
///
internal IHeaderFilterStrategy HeaderFilterStrategy => _headerFilter.Or(As2HeaderFilterStrategy.Default);
///
public override IProducer CreateProducer() => new As2Producer(this, Options);
///
public override IConsumer CreateConsumer(IProcessor processor) => Options.Mode == As2ReceiveMode.Mdn
? new As2MdnReceiver(this, processor, Options)
: new As2Consumer(this, processor, Options);
}
Path: redb-route/redb.Route.As2/As2EndpointOptions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/As2EndpointOptions.cs
----
using redb.Route.Abstractions;
using redb.Route.Http;
using redb.Route.Core;
namespace redb.Route.As2;
///
/// Strongly-typed options for an AS2 endpoint, bound from URI query parameters by
/// . Secrets are marked [Sensitive] so they are
/// redacted in logs. A partner profile (certificates, IDs, algorithms) usually comes from a named
/// in the registry via connectionFactory=name. The agreement has one
/// source: with a factory named, the inline agreement options below are refused on the URI; without one, they are the
/// whole agreement (no certificates, so only for an agreement that neither signs nor encrypts).
///
public sealed class As2EndpointOptions : EndpointOptions
{
// ── Transport ────────────────────────────────────────────────────────────
/// Bind address for the AS2 receive server (consumer). Default 0.0.0.0.
public string Host { get; set; } = "0.0.0.0";
/// Listen port for the AS2 receive server (consumer). Default 4080.
public int Port { get; set; } = 4080;
/// Partner endpoint URL the producer POSTs to. Reconstructed from the URI when absent.
public string? PartnerUrl { get; set; }
///
/// A registry reference (#name) to an that
/// decides which headers this endpoint carries between the exchange and the HTTP headers of an AS2 message, in
/// place of .
///
[RegistryReference(typeof(IHeaderFilterStrategy))]
public string? HeaderFilterStrategy { get; set; }
/// Use HTTPS/TLS. Set automatically when the URI scheme is as2s.
public bool UseTls { get; set; }
// ── Admission limit (HTTP_CONCURRENCY_LIMITS_PLAN) ──
/// Default of .
public const int DefaultMaxConcurrentRequests = 32;
/// Default of while limits.
public const int DefaultRequestQueueLimit = 32;
private int? _requestQueueLimit;
///
/// Maximum concurrent executions of this receiver's pipeline. Default 32; 0 = unlimited.
/// Overflow beyond the limit and is shed with
/// before any MIME/crypto work; AS2 partners retry on their
/// own MDN timeouts, which makes early shedding cheaper than a saturated receiver.
///
public int MaxConcurrentRequests { get; set; } = DefaultMaxConcurrentRequests;
///
/// Requests over the limit that WAIT for a permit (FIFO); 0 = reject immediately. When not set: 32 while
/// limits, 0 when it is 0 (unlimited, nothing to wait for).
///
public int RequestQueueLimit
{
get => _requestQueueLimit ?? (MaxConcurrentRequests > 0 ? DefaultRequestQueueLimit : 0);
set => _requestQueueLimit = value;
}
///
/// Status code of a refused request: shed by the admission limit, or finding every asynchronous MDN slot taken
/// (). Default 503 Service Unavailable: the receiver is busy, the partner resends.
///
public int RejectStatusCode { get; set; } = 503;
///
/// Value of the Retry-After header on a refused request; 0 = do not send it. Default 30: an AS2 resend
/// carries the whole message again, so the partner is told to wait long enough for the load to pass.
///
public int RetryAfterSeconds { get; set; } = 30;
///
/// Receive side: how many asynchronous MDNs the receiver handles at once. A message that asks for one takes a slot
/// when it is admitted, before any work, and keeps it until its receipt is posted (retries included); with every
/// slot taken it is refused with and . Default 20.
///
public int AsyncMdnPoolSize { get; set; } = 20;
///
/// Receive side: how many times an asynchronous MDN is posted before the receiver gives up on it (1 = no retry).
/// A post is tried again after a connection failure, a timeout, 408, 429 or a 5xx answer, not after another 4xx.
/// Default 3.
///
public int AsyncMdnAttempts { get; set; } = 3;
///
/// Receive side: milliseconds before the first retry of an asynchronous MDN, doubled for each one after it.
/// Default 5000.
///
public int AsyncMdnRetryDelay { get; set; } = 5000;
///
/// PFX certificate the receive server presents to the trading partner. This is the TLS server
/// certificate, a different thing from , which
/// signs and decrypts the S/MIME payload. May be left unset when the host carries a default
/// (AddRedbRouteHttpHosting(o => o.Tls.DefaultCertificatePath = ...)); a receive
/// endpoint with TLS and no certificate in either place refuses to bind.
///
public string? SslCertPath { get; set; }
/// Password for .
[Sensitive]
public string? SslCertPassword { get; set; }
///
/// Timeout in milliseconds of an outgoing POST: the message on a send, the asynchronous MDN on a receive.
/// Default 30000.
///
public int Timeout { get; set; } = 30000;
/// Default of : 100 MB, as the AS4 receiver.
public const long DefaultMaxRequestBodySize = 100L * 1024 * 1024;
/// Default of : 4 MB, ample for an MDN.
public const long DefaultMaxResponseBodySize = 4L * 1024 * 1024;
///
/// Receive side (messages and MDNs): the largest request body accepted, in bytes; a larger one is answered 413
/// before it is read. The received message is processed in memory (body, decrypted content and payload), so this
/// also bounds the memory one request takes. Default .
///
public long MaxRequestBodySize { get; set; } = DefaultMaxRequestBodySize;
///
/// Receive side: the most bytes a compressed message (RFC 3274) may inflate to. A few kilobytes of compressed data
/// can inflate to gigabytes, and the inflated payload is spooled and, without , held in
/// memory; past this limit the inflating stops and the message is refused with decompression-failed. Unset
/// (default): , so the payload a request hands over is bounded as its body is.
///
public long? MaxDecompressedSize { get; set; }
/// The bound of a decompressed payload: , else .
internal long DecompressedLimit => MaxDecompressedSize ?? MaxRequestBodySize;
///
/// Send side: the largest response body read, in bytes (the synchronous MDN). A larger one (a proxy's error page,
/// say) fails the send without being read. Default .
///
public long MaxResponseBodySize { get; set; } = DefaultMaxResponseBodySize;
// ── Partner binding ──────────────────────────────────────────────────────
/// Name of an registered in the route context.
[RegistryReference(typeof(As2ConnectionFactory))]
public string? ConnectionFactory { get; set; }
///
/// Receive side: name of an IIdempotentRepository registered with context.AddIdempotentRepository(name, repo)
/// (the contract of the IdempotentConsumer EIP and of the AS4 and S3 receivers). It remembers received
/// Message-IDs: a message received again is answered with a positive MDN carrying
/// processed/warning: duplicate-document and not delivered twice. The id is claimed after the message
/// authenticated and released when the route fails, so the partner's resend is then delivered. Unset (default):
/// every copy is delivered. Which store it is (memory, redb, SQL) decides whether it survives a restart and works
/// across nodes; give the endpoint one of its own.
///
[RegistryReference(typeof(IIdempotentRepository))]
public string? IdempotentRepository { get; set; }
///
/// Receive side, with : milliseconds after which a claim of a Message-ID that
/// was never confirmed is taken to be left by a stopped node and taken over, so its message is processed. A younger
/// one means the message is still in a route: a copy that arrives meanwhile is refused with
/// and , not answered as a duplicate. Takes effect with a
/// repository that keeps the confirmed state (the redb, SQL and in-memory ones do). Default 600000 (10 minutes).
///
public int InFlightClaimTimeout { get; set; } = 600_000;
///
/// Receive side: if true, the exchange body is a Stream (the spooled payload) instead of a byte array, as
/// streamBody does for the AS4, File, SFTP and S3 consumers; Exchange.DisposeAsync() closes it. Either way
/// the connector spools the request and each decrypted and decompressed stage to a temporary file past the core
/// stream-cache threshold, instead of holding them in memory, and hands the payload over only after it is decrypted,
/// verified and decompressed. Default false.
///
public bool StreamBody { get; set; }
/// What a receive endpoint accepts: business messages (default) or async MDN receipts.
public As2ReceiveMode Mode { get; set; } = As2ReceiveMode.Message;
// ── Agreement (inline; refused when a connection factory is named) ───────
/// Sign outgoing / expect signed incoming (S/MIME). Default true.
public bool Sign { get; set; } = true;
/// Encrypt outgoing / expect encrypted incoming (S/MIME). Default true.
public bool Encrypt { get; set; } = true;
/// Compress the payload (RFC 3274). Default false.
public bool Compress { get; set; }
/// Signature digest algorithm (sha-256, sha-384, ...). Default sha-256.
public string SignAlg { get; set; } = "sha-256";
/// Encryption algorithm (aes-128-cbc, aes-256-cbc, ...). Default aes-128-cbc.
public string EncryptAlg { get; set; } = "aes-128-cbc";
/// MDN mode: , or .
public As2MdnMode MdnMode { get; set; } = As2MdnMode.Sync;
/// Request/produce a signed MDN. Default true.
public bool SignedMdn { get; set; } = true;
/// Hard-fail a send on an unacceptable MDN (negative / MIC mismatch / missing required signature).
public bool RequireValidMdn { get; set; }
/// URL the partner posts asynchronous MDNs to (our receiver). Required for async MDN.
public string? AsyncMdnUrl { get; set; }
///
/// Receive side: comma-separated hosts an asynchronous MDN may be posted to (see
/// ). Required for a receive endpoint whose MDN mode is async.
///
public string? AsyncMdnAllowedHosts { get; set; }
// ── Identity ─────────────────────────────────────────────────────────────
/// Our AS2 identifier (AS2-From on send, expected AS2-To on receive).
public string? As2From { get; set; }
/// Partner AS2 identifier (AS2-To on send, expected AS2-From on receive).
public string? As2To { get; set; }
/// Permits the legacy algorithms sha-1 and 3des (see ).
public bool AllowLegacyAlgorithms { get; set; }
///
public override void Validate()
{
if (Port is < 1 or > 65535)
throw new ArgumentOutOfRangeException(nameof(Port), Port, "AS2 port must be between 1 and 65535.");
if (Timeout < 0)
throw new ArgumentOutOfRangeException(nameof(Timeout), Timeout, "AS2 timeout must be non-negative.");
if (MaxRequestBodySize <= 0)
throw new ArgumentOutOfRangeException(nameof(MaxRequestBodySize), MaxRequestBodySize, "AS2 maxRequestBodySize must be positive.");
if (InFlightClaimTimeout < 1)
throw new ArgumentOutOfRangeException(nameof(InFlightClaimTimeout), InFlightClaimTimeout, "AS2 inFlightClaimTimeout must be positive.");
if (AsyncMdnPoolSize < 1)
throw new ArgumentOutOfRangeException(nameof(AsyncMdnPoolSize), AsyncMdnPoolSize, "AS2 asyncMdnPoolSize must be at least 1.");
if (AsyncMdnAttempts < 1)
throw new ArgumentOutOfRangeException(nameof(AsyncMdnAttempts), AsyncMdnAttempts, "AS2 asyncMdnAttempts must be at least 1.");
if (AsyncMdnRetryDelay < 0)
throw new ArgumentOutOfRangeException(nameof(AsyncMdnRetryDelay), AsyncMdnRetryDelay, "AS2 asyncMdnRetryDelay must be non-negative.");
if (MaxDecompressedSize is <= 0)
throw new ArgumentOutOfRangeException(nameof(MaxDecompressedSize), MaxDecompressedSize, "AS2 maxDecompressedSize must be positive.");
if (MaxResponseBodySize <= 0)
throw new ArgumentOutOfRangeException(nameof(MaxResponseBodySize), MaxResponseBodySize, "AS2 maxResponseBodySize must be positive.");
ConcurrencyLimitOptions.ValidateShape(MaxConcurrentRequests, RequestQueueLimit, RejectStatusCode, RetryAfterSeconds);
if (MdnMode == As2MdnMode.Async && string.IsNullOrEmpty(AsyncMdnUrl) && string.IsNullOrEmpty(ConnectionFactory))
throw new ArgumentException("Async MDN requires 'asyncMdnUrl' or a 'connectionFactory' that provides it.");
if (Sign && !Crypto.As2CryptoEngine.IsSupportedDigest(SignAlg))
throw new ArgumentException($"Unsupported AS2 signature algorithm '{SignAlg}'. Supported: sha-1, sha-256, sha-384, sha-512.");
if (Encrypt && !Crypto.As2CryptoEngine.IsSupportedEncryption(EncryptAlg))
throw new ArgumentException($"Unsupported AS2 encryption algorithm '{EncryptAlg}'. Supported: aes-128-cbc, aes-192-cbc, aes-256-cbc, 3des.");
if (!AllowLegacyAlgorithms && (As2Profile.IsLegacy(SignAlg) || (Encrypt && As2Profile.IsLegacy(EncryptAlg))))
throw new ArgumentException(
$"AS2 algorithm '{(As2Profile.IsLegacy(SignAlg) ? SignAlg : EncryptAlg)}' is legacy (sha-1, 3des); set allowLegacyAlgorithms=true only if the partner requires it.");
}
///
protected override string? UnknownParameterHint(string name) =>
string.Equals(name, "certPassword", StringComparison.OrdinalIgnoreCase)
? "The S/MIME certificates and their passwords belong on the As2ConnectionFactory the endpoint names (connectionFactory=...), not in the URI; the TLS certificate is sslCertPath/sslCertPassword."
: null;
}
Path: redb-route/redb.Route.As2/As2Enums.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/As2Enums.cs
----
namespace redb.Route.As2;
///
/// How the receiver returns the MDN (Message Disposition Notification) receipt (RFC 4130 §7).
///
public enum As2MdnMode
{
/// No MDN requested.
None,
/// MDN returned synchronously in the HTTP response to the same POST (InOut).
Sync,
/// Receiver answers 200 immediately and POSTs the MDN later to Receipt-Delivery-Option.
Async,
}
/// What an AS2 receive endpoint accepts.
public enum As2ReceiveMode
{
/// Inbound business AS2 messages (default).
Message,
/// Asynchronous MDN receipts posted back by partners.
Mdn,
}
Path: redb-route/redb.Route.As2/As2HeaderFilterStrategy.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/As2HeaderFilterStrategy.cs
----
using redb.Route.Abstractions;
namespace redb.Route.As2;
///
/// The default of the AS2 component. An endpoint's
/// headerFilterStrategy=#name replaces it; derive from it to add to it.
///
/// A producer sends every exchange header but the component's own redbAs2.* and null values as an HTTP header
/// of the message; a consumer brings every request header in.
///
///
/// Whatever the strategy: the producer never bridges the MIME, AS2 and hop-by-hop fields it sets itself, the
/// credentials of another hop (Authorization, Cookie, Set-Cookie) or Host; the consumer
/// never takes the pseudo-headers, the S/MIME wrapper and hop-by-hop fields or the credentials that authenticated the
/// hop; the consumer's redbAs2.* metadata is set by the consumer.
///
///
public class As2HeaderFilterStrategy : IHeaderFilterStrategy
{
/// The default strategy of an AS2 endpoint.
public static As2HeaderFilterStrategy Default { get; } = new();
///
public virtual bool FilterOutgoing(string name, object? value, IExchange exchange)
=> value is null || As2Headers.IsRedbHeader(name);
///
public virtual bool FilterIncoming(string name, object? value, IExchange exchange) => false;
}
Path: redb-route/redb.Route.As2/As2Headers.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/As2Headers.cs
----
namespace redb.Route.As2;
///
/// AS2 header names surfaced on the exchange, and the reserved set that must not be blindly bridged.
///
/// Two planes, deliberately: AS2 wire headers keep their verbatim names (AS2-From, ...),
/// while redb-computed metadata (MIC, signature validity, ...) lives under the .
/// Canonical-plane rule (from the IBM MQ usr-folder decision): each header has ONE source of truth and the
/// consumer and producer never disagree. The load-bearing example is Content-Type — the transport
/// value is the multipart/signed wrapper; the business payload's real content type lives on
/// Message.ContentType.
///
///
public static class As2Headers
{
/// Prefix for redb-computed AS2 metadata headers.
public const string Prefix = "redbAs2.";
// ── AS2 wire headers (verbatim names; constants for explicit set/get) ────
/// Sender AS2 identifier.
public const string As2From = "AS2-From";
/// Recipient AS2 identifier.
public const string As2To = "AS2-To";
/// AS2 protocol version.
public const string As2Version = "AS2-Version";
/// Unique message id; echoed back in the MDN as Original-Message-ID.
public const string MessageId = "Message-ID";
/// Human-readable subject.
public const string Subject = "Subject";
/// Requests an MDN and (for async) where to send it.
public const string DispositionNotificationTo = "Disposition-Notification-To";
/// Requested MDN profile (signed-receipt protocol / micalg).
public const string DispositionNotificationOptions = "Disposition-Notification-Options";
/// URL for an asynchronous MDN (present ⇒ async).
public const string ReceiptDeliveryOption = "Receipt-Delivery-Option";
// ── redb-computed metadata (under Prefix) ────────────────────────────────
/// Computed Message Integrity Check value.
public const string Mic = Prefix + "mic";
/// MIC digest algorithm.
public const string MicAlg = Prefix + "micalg";
/// Resolved partner (connection-factory) name.
public const string PartnerName = Prefix + "partner";
///
/// True only when a signature was present and verified against the partner certificate; false for an
/// unsigned message or MDN, where nothing was verified.
///
public const string SignatureValid = Prefix + "signatureValid";
/// Remote peer address.
public const string RemoteAddress = Prefix + "remoteAddress";
/// MDN disposition outcome.
public const string MdnDisposition = Prefix + "mdnDisposition";
///
/// True only when the MDN's Received-Content-MIC was compared with the MIC we sent and is the same; false when it
/// differs, is absent, or there was nothing to compare it with (see ).
///
public const string MdnMicMatch = Prefix + "mdnMicMatch";
///
/// The outcome of the MIC comparison: matched, mismatch, absent (the MDN carries no
/// Received-Content-MIC) or unknown (the MDN names no message we are waiting for: no Original-Message-ID,
/// or one sent before a restart, evicted after the correlation TTL, or sent by another node).
///
public const string MdnMicStatus = Prefix + "mdnMicStatus";
///
/// True when the MDN confirms the transfer: its disposition is positive, its MIC matched, and its signature is
/// valid where the agreement asks for a signed MDN. The one header to branch on for "delivered and verified".
///
public const string MdnConfirmed = Prefix + "mdnConfirmed";
/// True if the header name is a redb AS2 metadata header (must not be bridged onto the wire).
public static bool IsRedbHeader(string key)
=> key.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase);
///
/// Headers the producer must NOT blindly copy from exchange.In.Headers onto the outgoing message:
/// MIME headers we set explicitly through the content object, AS2 semantics we set from partner config,
/// and HTTP hop-by-hop headers. redb metadata is filtered separately via .
///
internal static readonly HashSet NonBridgedHeaders = new(StringComparer.OrdinalIgnoreCase)
{
// MIME headers set explicitly via the content object
"Content-Type", "Content-Disposition", "Content-Transfer-Encoding", "Content-Length", "Content-Encoding",
// AS2 semantics set from partner config
"AS2-From", "AS2-To", "AS2-Version", "Message-ID",
"Disposition-Notification-To", "Disposition-Notification-Options", "Receipt-Delivery-Option",
// HTTP hop-by-hop
"Connection", "Keep-Alive", "Transfer-Encoding", "TE", "Trailer", "Upgrade",
"Proxy-Authorization", "Proxy-Authenticate",
// Credentials and state of another hop: bridged, an inbound caller's (or an internal service's) token or
// session would reach the trading partner.
"Authorization", "Cookie", "Set-Cookie",
// Belongs to THIS request's target: bridging it from an inbound http consumer turned
// every From(http) -> To(as2) route into an accidental preserve-host proxy.
"Host",
};
///
/// An AS2-name as it goes into AS2-From / AS2-To (RFC 4130 §6.2): as it is when every character is
/// printable ASCII other than space, double quote and backslash (an AS2-atomic-name), else in double quotes with
/// " and \ escaped (an AS2-quoted-name).
///
internal static string FormatName(string name)
{
if (name.Length > 0 && name.All(c => c is > ' ' and <= '~' and not '"' and not '\\'))
return name;
return "\"" + name.Replace("\\", "\\\\", StringComparison.Ordinal).Replace("\"", "\\\"", StringComparison.Ordinal) + "\"";
}
}
Path: redb-route/redb.Route.As2/As2Http.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/As2Http.cs
----
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Features;
using redb.Route.Configuration;
using redb.Route.Core;
namespace redb.Route.As2;
/// Request-body handling shared by the message and the MDN receiver.
internal static class As2Http
{
///
/// Spools the request body after (the core stream cache: memory, or a temporary file past
/// the threshold of ), refusing more than bytes. The limit is set on
/// the request itself (the listener's own limit belongs to whichever route registered the port first) and enforced
/// while reading, so a body that is not declared up front is cut at the limit too. Returns the spool rewound and
/// readable, or null after answering 413 when the body is too large.
///
public static async Task ReadBodyAsync(HttpContext http, long limit, byte[]? prefix, StreamCacheOptions spool, CancellationToken ct)
{
if (http.Features.Get() is { IsReadOnly: false } feature)
feature.MaxRequestBodySize = limit;
if (http.Request.ContentLength is { } declared && declared > limit)
return TooLarge(http);
var buffer = new StreamCache(spool);
var complete = false;
try
{
if (prefix is not null) await buffer.WriteAsync(prefix, ct).ConfigureAwait(false);
long read = 0;
var chunk = new byte[81920];
int n;
while ((n = await http.Request.Body.ReadAsync(chunk, ct).ConfigureAwait(false)) > 0)
{
read += n;
if (read > limit)
return TooLarge(http);
await buffer.WriteAsync(chunk.AsMemory(0, n), ct).ConfigureAwait(false);
}
buffer.CompleteWriting();
buffer.Position = 0;
complete = true;
return buffer;
}
catch (BadHttpRequestException e) when (e.StatusCode == StatusCodes.Status413PayloadTooLarge)
{
return TooLarge(http);
}
finally
{
if (!complete) await buffer.DisposeAsync().ConfigureAwait(false);
}
}
private static StreamCache? TooLarge(HttpContext http)
{
http.Response.StatusCode = StatusCodes.Status413PayloadTooLarge;
return null;
}
}
Path: redb-route/redb.Route.As2/As2MdnReceiver.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/As2MdnReceiver.cs
----
using System.Diagnostics;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.As2.Crypto;
using redb.Route.As2.Mdn;
using redb.Route.Core;
using redb.Route.Extensions;
using redb.Route.Http;
using redb.Route.Telemetry;
namespace redb.Route.As2;
///
/// Receives asynchronous MDN receipts a partner posts back to our Receipt-Delivery-Option URL.
/// Parses the MDN, compares its MIC with the one recorded for Original-Message-ID, applies the agreement's
/// signed-MDN policy, delivers the verdict to the route (), and answers 200. Bound to an
/// As2.ReceiveMdn(path) endpoint.
///
internal sealed class As2MdnReceiver : IConsumer
{
private readonly As2Endpoint _endpoint;
private readonly IProcessor _processor;
private readonly As2EndpointOptions _options;
private readonly IAs2CryptoEngine _engine = new As2CryptoEngine();
private readonly ILogger? _logger;
private RouteRegistration? _registration;
public As2MdnReceiver(As2Endpoint endpoint, IProcessor processor, As2EndpointOptions options)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_processor = processor ?? throw new ArgumentNullException(nameof(processor));
_options = options ?? throw new ArgumentNullException(nameof(options));
_logger = endpoint.Logger;
}
public IEndpoint Endpoint => _endpoint;
private As2Component Component => (_endpoint.Component as As2Component)
?? throw new InvalidOperationException("AS2 endpoint has no As2Component.");
// Unregistering the route stops new receipts; one already in the pipeline finishes before Stop returns.
private readonly InflightDrainGuard _drain = new();
private As2Profile? _profile;
public async Task Start(CancellationToken ct = default)
{
// Resolved once, as the message receiver does: a misnamed agreement stops the route from starting.
_profile = As2Profile.Resolve(_endpoint.Context, _options, _endpoint.Uri.Path);
// Same as the message receiver: TLS without a certificate used to open a plaintext port.
var certPath = _options.SslCertPath;
var certPassword = _options.SslCertPassword;
if (string.IsNullOrEmpty(certPath) && !string.IsNullOrEmpty(_options.ConnectionFactory))
{
var factory = _endpoint.Context.GetRequiredFromRegistry(_options.ConnectionFactory);
certPath = factory.SslCertPath;
certPassword = factory.SslCertPassword;
}
_drain.Start(ct);
_registration = Component.Server.RegisterRoute(
_options.Host, _options.Port, _endpoint.Uri.Path, "POST", HandleRequest,
_options.UseTls, certPath, certPassword,
maxRequestBodySize: _options.MaxRequestBodySize,
concurrencyLimit: ConcurrencyLimitOptions.FromEndpoint(
_options.MaxConcurrentRequests, _options.RequestQueueLimit,
_options.RejectStatusCode, _options.RetryAfterSeconds,
onRejected: _endpoint.RecordRejected));
await Component.Server.EnsureStarted(_options.Host, _options.Port, ct).ConfigureAwait(false);
_logger?.LogInformation("AS2 async-MDN receiver started: {Host}:{Port}{Path}", _options.Host, _options.Port, _endpoint.Uri.Path);
}
public async Task Stop(CancellationToken ct = default)
{
if (_registration is not null)
{
Component.Server.UnregisterRoute(_registration);
_registration = null;
await _drain.DrainAsync(ct, _logger, $"as2://{_options.Host}:{_options.Port}{_endpoint.Uri.Path}").ConfigureAwait(false);
await Component.Server.StopIfEmpty(_options.Host, _options.Port, ct).ConfigureAwait(false);
}
}
private async Task HandleRequest(HttpContext http)
{
_drain.Increment();
try
{
await HandleRequestCore(http).ConfigureAwait(false);
}
finally
{
_drain.Decrement();
}
}
private async Task HandleRequestCore(HttpContext http)
{
using var span = As2Consumer.StartReceiveSpan(_endpoint, http.Request);
var reference = http.TraceIdentifier;
byte[] bodyBytes;
await using (var body = await As2Http.ReadBodyAsync(http, _options.MaxRequestBodySize, null, _endpoint.Context.GetStreamCacheOptions(), http.RequestAborted)
.ConfigureAwait(false))
{
if (body is null)
{
_logger?.LogWarning("AS2 asynchronous MDN refused: its body is over maxRequestBodySize {Limit} bytes (ref {Reference}).",
_options.MaxRequestBodySize, reference);
_endpoint.RecordError(new InvalidOperationException(
$"AS2 asynchronous MDN refused: its body is over maxRequestBodySize {_options.MaxRequestBodySize} bytes (ref {reference})."));
span.Activity?.SetStatus(ActivityStatusCode.Error, "request body over maxRequestBodySize");
return;
}
// An MDN is a few kilobytes: its bytes are the exchange body.
bodyBytes = new byte[body.Length];
body.ReadExactly(bodyBytes);
}
var profile = _profile!;
var cte = http.Request.Headers.TryGetValue("Content-Transfer-Encoding", out var cteValue) ? cteValue.ToString() : null;
MdnParser.MdnResult result;
try
{
result = MdnParser.Parse(http.Request.ContentType, cte, bodyBytes, _engine, profile.PartnerCertificate);
}
catch (Exception e) when (e is not OperationCanceledException)
{
_logger?.LogWarning(e, "AS2 asynchronous MDN refused: it is not a readable MDN (ref {Reference}).", reference);
_endpoint.RecordError(e);
span.Activity.RecordFailure(e);
http.Response.StatusCode = StatusCodes.Status400BadRequest;
return;
}
// The MDN names the message it reports on; without one, or for one nobody waits for, its MIC cannot be compared.
var originalId = string.IsNullOrEmpty(result.OriginalMessageId) ? null : result.OriginalMessageId;
var expected = originalId is null ? null : Component.Correlation.ExpectedMic(originalId);
var verdict = MdnVerdict.Of(result, expected, profile.SignedMdn);
if (!verdict.SignatureAccepted && profile.RequireValidMdn)
{
// A signed MDN is agreed and a valid one required: an unsigned or foreign receipt may be anyone's, so it is
// neither delivered nor allowed to end the wait; the partner's own receipt must still find the message.
_logger?.LogWarning("AS2 asynchronous MDN for message {MessageId} refused: {Problem} (ref {Reference}).",
originalId, verdict.Problem(result), reference);
_endpoint.RecordError(new InvalidOperationException(
$"AS2 asynchronous MDN for message {originalId} refused: {verdict.Problem(result)} (ref {reference})."));
span.Activity?.SetStatus(ActivityStatusCode.Error, "asynchronous MDN refused by the signature policy");
http.Response.StatusCode = StatusCodes.Status400BadRequest;
return;
}
// Only a receipt the signature policy accepts ends the wait: an unsigned one where a signed one is agreed may
// be forged, and must not make the partner's genuine receipt look like an orphan.
if (originalId is not null && expected is not null && verdict.SignatureAccepted)
Component.Correlation.Complete(originalId);
if (verdict.Problem(result) is { } problem)
_logger?.LogWarning("AS2 asynchronous MDN for message {MessageId} does not confirm the transfer: {Problem}.", originalId, problem);
// Deliver the MDN outcome to the route; redbAs2.mdnConfirmed says whether it confirms the transfer. A route
// failure is the route's: the partner delivered its receipt and is answered 200 either way.
var message = new Message(bodyBytes) { ContentType = http.Request.ContentType };
if (originalId is not null) message.Headers[As2Headers.MessageId] = originalId;
message.Headers[As2Headers.MdnDisposition] = result.Disposition ?? string.Empty;
message.Headers[As2Headers.SignatureValid] = result.SignatureValid;
message.Headers[As2Headers.MdnMicMatch] = verdict.MicMatch;
message.Headers[As2Headers.MdnMicStatus] = verdict.MicStatus;
message.Headers[As2Headers.MdnConfirmed] = verdict.Confirmed;
if (http.Connection.RemoteIpAddress is not null)
message.Headers[As2Headers.RemoteAddress] = http.Connection.RemoteIpAddress.ToString();
if (!string.IsNullOrEmpty(_options.ConnectionFactory))
message.Headers[As2Headers.PartnerName] = _options.ConnectionFactory;
var exchange = Exchange.Create(message, _endpoint.ScopeFactory);
exchange.Pattern = ExchangePattern.InOnly;
ExchangePrincipal.Set(exchange, SharedHttpServerManager.GetResolvedPrincipal(http));
try
{
using var processing = CancellationTokenSource.CreateLinkedTokenSource(http.RequestAborted, _drain.ProcessingToken);
try { await _processor.Process(exchange, processing.Token).ConfigureAwait(false); }
catch (Exception e) when (e is not OperationCanceledException) { exchange.Exception ??= e; }
if (exchange.EndedInFailure())
{
_logger?.LogWarning(exchange.Exception, "AS2 asynchronous MDN for message {MessageId}: the route failed (ref {Reference}).",
originalId, reference);
if (exchange.Exception is { } routeFailure) span.Activity.RecordFailure(routeFailure);
}
}
finally
{
await exchange.DisposeAsync().ConfigureAwait(false);
}
http.Response.StatusCode = StatusCodes.Status200OK;
}
}
Path: redb-route/redb.Route.As2/As2Metrics.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/As2Metrics.cs
----
using System.Diagnostics.Metrics;
using redb.Route.Telemetry;
namespace redb.Route.As2;
/// AS2 counters, on the canonical meter .
internal static class As2Metrics
{
private static readonly Meter Meter = new(RouteMetrics.MeterName);
/// Asynchronous MDNs the receiver gave up on after its attempts.
public static readonly Counter AsyncMdnFailed =
Meter.CreateCounter("redb.route.as2.mdn.async_failed", "receipts", "Asynchronous MDNs not delivered after every attempt.");
/// Messages refused because every asynchronous MDN slot was taken.
public static readonly Counter AsyncMdnRejected =
Meter.CreateCounter("redb.route.as2.mdn.async_rejected", "messages", "Messages refused because every asynchronous MDN slot was taken.");
}
Path: redb-route/redb.Route.As2/As2Producer.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/As2Producer.cs
----
using System.Diagnostics;
using System.Text;
using Microsoft.Extensions.Logging;
using MimeKit;
using redb.Route.Abstractions;
using redb.Route.As2.Crypto;
using redb.Route.As2.Mdn;
using redb.Route.Core;
using redb.Route.Telemetry;
namespace redb.Route.As2;
///
/// AS2 send side (client): builds an S/MIME message (compress → sign → encrypt per the partner profile) and
/// POSTs it to the partner over HTTP(S). Extends with an internal
/// ; presents our certificate for mutual TLS. The computed MIC and Message-ID are
/// written back to the exchange; a synchronous MDN is verified here (), an asynchronous
/// one is correlated by the ReceiveMdn endpoint.
///
internal sealed class As2Producer : ConnectableProducer
{
private readonly As2Endpoint _endpoint;
private readonly As2EndpointOptions _options;
private readonly IAs2CryptoEngine _engine = new As2CryptoEngine();
private HttpClient? _http;
private As2Profile? _profile;
public As2Producer(As2Endpoint endpoint, As2EndpointOptions options)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_options = options ?? throw new ArgumentNullException(nameof(options));
_headerFilter = endpoint.HeaderFilterStrategy;
}
private readonly IHeaderFilterStrategy _headerFilter;
protected override IEndpoint ProducerEndpoint => _endpoint;
// Same invariant as HttpProducer: the name reaches started/stopped logs, and a partner URL
// with basic-auth carries a userinfo password no [Sensitive] attribute can reach.
protected override string ProducerName => $"as2:{EndpointUri.Sanitize(_options.PartnerUrl)}";
///
protected override Task ConnectAsync(CancellationToken ct)
{
// The agreement is resolved and checked once, here: a broken one stops the producer from starting instead of
// failing every message.
var profile = As2Profile.Resolve(_endpoint.Context, _options, EndpointUri.Sanitize(_options.PartnerUrl));
if (string.IsNullOrEmpty(profile.PartnerUrl))
throw new InvalidOperationException("AS2 producer has no partner URL (set it on the URI or on the connection factory).");
if (!string.IsNullOrEmpty(_options.ConnectionFactory) && !string.IsNullOrEmpty(_options.PartnerUrl)
&& !string.Equals(profile.PartnerUrl.TrimEnd('/'), _options.PartnerUrl.TrimEnd('/'), StringComparison.OrdinalIgnoreCase))
throw new InvalidOperationException(
$"AS2 producer {EndpointUri.Sanitize(_options.PartnerUrl)}: connection factory '{_options.ConnectionFactory}' names PartnerUrl " +
$"{EndpointUri.Sanitize(profile.PartnerUrl)}; the endpoint URI and the factory must name the same partner.");
if (profile.MdnMode == As2MdnMode.Async && profile.AsyncMdnUrl is null)
throw new InvalidOperationException(
"AS2 producer: MdnMode is async, so AsyncMdnUrl must say where the partner posts the receipt.");
_profile = profile;
var handler = new HttpClientHandler();
// Mutual TLS: present our certificate to the partner on HTTPS connections.
if (profile.OurCertificate is not null)
handler.ClientCertificates.Add(profile.OurCertificate);
_http = new HttpClient(handler)
{
Timeout = _options.Timeout > 0 ? TimeSpan.FromMilliseconds(_options.Timeout) : Timeout.InfiniteTimeSpan,
};
return Task.CompletedTask;
}
///
protected override Task DisconnectAsync(CancellationToken ct)
{
_http?.Dispose();
_http = null;
return Task.CompletedTask;
}
///
public override async Task Process(IExchange exchange, CancellationToken ct = default)
{
EnsureStarted();
ArgumentNullException.ThrowIfNull(exchange);
var profile = _profile!;
// A pinned certificate is used only while valid: the partner would refuse the message anyway, after our retries.
if (profile.Sign) As2CertificateValidity.Ensure(profile.OurCertificate!, "Our signing certificate");
if (profile.Encrypt) As2CertificateValidity.Ensure(profile.PartnerCertificate!, "The partner's encryption certificate");
// 1. Payload MIME entity from the exchange body.
MimeEntity entity = BuildPayload(exchange.In);
// 2. compress → sign (compute MIC over what we sign) → encrypt, per profile.
// Unsigned: over the uncompressed payload with its MIME headers when it is encrypted (RFC 4130 §7.3.1, RFC 5402
// §4.2), over its content alone when it is not, compressed or plain. Computed before compressing: the payload
// prepared for the MIC is the one compressed and encrypted, so the receiver hashes the same bytes.
As2Mic? unsignedMic = profile.Sign
? null
: _engine.ComputeMic(entity, profile.SignAlg, includeHeaders: profile.Encrypt);
if (profile.Compress)
entity = _engine.Compress(entity);
As2Mic mic;
if (profile.Sign)
{
// Signed: the MIC is over the signed content (the compressed part, when compress-then-sign) —
// which is exactly what the receiver hashes from the signed entity (RFC 5402 §4.1).
mic = _engine.ComputeMic(entity, profile.SignAlg, includeHeaders: true);
entity = _engine.Sign(entity, profile.OurCertificate!, profile.SignAlg);
}
else
mic = unsignedMic!.Value;
if (profile.Encrypt)
entity = _engine.Encrypt(entity, profile.PartnerCertificate!, profile.EncryptAlg);
// 3. Serialize; the top-level MIME headers become HTTP headers, the MIME body becomes the HTTP body.
var (contentType, transferEncoding, contentDisposition, body) = SerializeEntity(entity);
// 4. Assemble the AS2 HTTP request.
var messageId = $"<{Guid.NewGuid():N}@redb.route>";
var request = new HttpRequestMessage(HttpMethod.Post, profile.PartnerUrl);
AddHeader(request, As2Headers.As2Version, "1.2");
AddHeader(request, As2Headers.As2From, string.IsNullOrEmpty(profile.As2From) ? null : As2Headers.FormatName(profile.As2From));
AddHeader(request, As2Headers.As2To, string.IsNullOrEmpty(profile.As2To) ? null : As2Headers.FormatName(profile.As2To));
AddHeader(request, As2Headers.MessageId, messageId);
AddHeader(request, As2Headers.Subject, exchange.In.GetHeader(As2Headers.Subject) ?? "AS2 Message");
if (profile.MdnMode != As2MdnMode.None)
{
AddHeader(request, As2Headers.DispositionNotificationTo,
string.IsNullOrEmpty(profile.As2From) ? "as2@redb.route" : profile.As2From);
if (profile.SignedMdn)
AddHeader(request, As2Headers.DispositionNotificationOptions,
// Required, not optional: the agreement does not accept an unsigned receipt (MdnVerdict), so the
// partner must not think it may send one.
$"signed-receipt-protocol=required, pkcs7-signature; signed-receipt-micalg=required, {profile.SignAlg}");
if (profile.MdnMode == As2MdnMode.Async && !string.IsNullOrEmpty(profile.AsyncMdnUrl))
AddHeader(request, As2Headers.ReceiptDeliveryOption, profile.AsyncMdnUrl);
}
// Bridge non-reserved exchange headers (AS2 semantics + MIME headers are set explicitly, not bridged).
BridgeHeaders(exchange, request);
// Content + its MIME headers.
var content = new ByteArrayContent(body);
content.Headers.TryAddWithoutValidation("Content-Type", contentType);
if (!string.IsNullOrEmpty(transferEncoding))
content.Headers.TryAddWithoutValidation("Content-Transfer-Encoding", transferEncoding);
if (!string.IsNullOrEmpty(contentDisposition))
content.Headers.TryAddWithoutValidation("Content-Disposition", contentDisposition);
request.Content = content;
// 5. Telemetry + POST. The span is opened on the core contract (EnableTelemetry=false opens none) and its context
// is written to the request, replacing a traceparent bridged from the exchange: HttpClient writes none of its own
// when the header is already there, and the partner would see the previous hop instead of this send.
using var activity = RouteTelemetryExtensions.StartTransportSpan(
_endpoint.Context, $"{profile.As2To} send", ActivityKind.Client, "messaging.system", "as2",
_endpoint.Uri.NormalizedKey, destination: profile.PartnerUrl, operation: "send");
RouteTelemetryExtensions.InjectTraceContext(activity, request, static (r, name, value) =>
{
r.Headers.Remove(name);
r.Headers.TryAddWithoutValidation(name, value);
});
try
{
await SendAndVerifyAsync(exchange, profile, request, messageId, mic, ct).ConfigureAwait(false);
}
// A cancellation is a failure unless the caller asked for it: HttpClient reports its own timeout (no answer from
// the partner within `timeout`) as TaskCanceledException.
catch (Exception e) when (e is not OperationCanceledException || !ct.IsCancellationRequested)
{
activity.RecordFailure(e);
throw;
}
}
/// POSTs the message and, for a synchronous MDN, verifies the receipt; throws when the send failed.
private async Task SendAndVerifyAsync(IExchange exchange, As2Profile profile, HttpRequestMessage request, string messageId,
As2Mic mic, CancellationToken ct)
{
// Record what we send so the MDN can be correlated and its Received-Content-MIC verified.
exchange.In.Headers[As2Headers.MessageId] = messageId;
exchange.In.Headers[As2Headers.Mic] = mic.Digest;
exchange.In.Headers[As2Headers.MicAlg] = mic.Algorithm;
// Async: the wait exists BEFORE the POST. A partner may post the MDN before it answers this request (OpenAS2
// often does); registered after the answer, that receipt would read as one nobody waits for. Nothing waits on
// the entry: the verdict reaches the ReceiveMdn route as its own exchange.
var correlation = profile.MdnMode == As2MdnMode.Async ? (_endpoint.Component as As2Component)?.Correlation : null;
correlation?.Register(messageId, mic);
HttpResponseMessage response;
try
{
// Headers first: the body is read below, bounded, and only for a synchronous MDN.
response = await _http!.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct).ConfigureAwait(false);
}
catch
{
correlation?.Complete(messageId); // not delivered: nothing is waiting for a receipt
throw;
}
using var _ = response;
if (!response.IsSuccessStatusCode)
{
correlation?.Complete(messageId);
throw new HttpRequestException(
$"AS2 POST to {EndpointUri.Sanitize(profile.PartnerUrl)} failed: {(int)response.StatusCode} {response.ReasonPhrase}");
}
// Synchronous MDN: parse the receipt, verify its signature, and confirm the partner's
// Received-Content-MIC matches what we sent. The MDN lands on exchange.Out (InOut).
if (profile.MdnMode == As2MdnMode.Sync)
{
var mdnContentType = response.Content.Headers.ContentType?.ToString();
var mdnCte = response.Content.Headers.TryGetValues("Content-Transfer-Encoding", out var cteValues)
? string.Join(",", cteValues) : null;
var mdnBytes = await ReadBoundedAsync(response, messageId, ct).ConfigureAwait(false);
var result = MdnParser.Parse(mdnContentType, mdnCte, mdnBytes, _engine, profile.PartnerCertificate);
var verdict = MdnVerdict.Of(result, mic, profile.SignedMdn);
var outMessage = new Message(mdnBytes) { ContentType = mdnContentType };
outMessage.Headers[As2Headers.MdnDisposition] = result.Disposition ?? string.Empty;
outMessage.Headers[As2Headers.SignatureValid] = result.SignatureValid;
outMessage.Headers[As2Headers.MdnMicMatch] = verdict.MicMatch;
outMessage.Headers[As2Headers.MdnMicStatus] = verdict.MicStatus;
outMessage.Headers[As2Headers.MdnConfirmed] = verdict.Confirmed;
exchange.Out = outMessage;
exchange.Pattern = ExchangePattern.InOut;
// Not confirmed: a negative disposition, a MIC that is not the one we sent (or is absent), or a missing or
// invalid signature where a signed MDN is agreed. Always on the redbAs2.mdn* headers; with RequireValidMdn
// also a failure of the send.
if (verdict.Problem(result) is { } problem)
{
Logger?.LogWarning("AS2 MDN for message {MessageId} does not confirm the transfer: {Problem}.", messageId, problem);
if (profile.RequireValidMdn)
throw new InvalidOperationException($"AS2 transfer of '{messageId}' is not confirmed by its MDN: {problem}.");
}
}
Logger?.LogDebug("AS2 message sent: id={MessageId}, partner={Partner}", messageId, profile.As2To);
}
// ── Helpers ──────────────────────────────────────────────────────────────
/// The response body, refused past maxResponseBodySize without reading the rest (as the AS4 producer).
private async Task ReadBoundedAsync(HttpResponseMessage response, string messageId, CancellationToken ct)
{
var limit = _options.MaxResponseBodySize;
if (response.Content.Headers.ContentLength is { } declared && declared > limit)
throw new InvalidOperationException(
$"AS2 response to '{messageId}' declares {declared} bytes, over maxResponseBodySize {limit}; it is not an MDN.");
await using var body = await response.Content.ReadAsStreamAsync(ct).ConfigureAwait(false);
using var buffer = new MemoryStream();
var chunk = new byte[81920];
int read;
while ((read = await body.ReadAsync(chunk, ct).ConfigureAwait(false)) > 0)
{
if (buffer.Length + read > limit)
throw new InvalidOperationException(
$"AS2 response to '{messageId}' is over maxResponseBodySize {limit} bytes; it is not an MDN.");
buffer.Write(chunk, 0, read);
}
return buffer.ToArray();
}
/// Wraps the exchange body (byte[] preserved as-is; string/other UTF-8 encoded) in a MIME part.
private static MimePart BuildPayload(IMessage message)
{
var bytes = message.Body switch
{
byte[] b => b,
null => [],
string s => Encoding.UTF8.GetBytes(s),
_ => Encoding.UTF8.GetBytes(BodyText.Of(message.Body)),
};
var (mediaType, mediaSubtype) = SplitContentType(message.ContentType);
return new MimePart(mediaType, mediaSubtype)
{
Content = new MimeContent(new MemoryStream(bytes, writable: false)),
ContentTransferEncoding = ContentEncoding.Binary,
};
}
private static (string mediaType, string mediaSubtype) SplitContentType(string? contentType)
{
if (!string.IsNullOrWhiteSpace(contentType) && ContentType.TryParse(contentType, out var parsed))
return (parsed.MediaType, parsed.MediaSubtype);
return ("application", "octet-stream");
}
/// Serializes the entity (CRLF-canonical) and splits its top-level MIME headers from the body.
private static (string contentType, string? transferEncoding, string? contentDisposition, byte[] body) SerializeEntity(MimeEntity entity)
{
using var ms = new MemoryStream();
var options = FormatOptions.Default.Clone();
options.NewLineFormat = NewLineFormat.Dos;
entity.WriteTo(options, ms);
var all = ms.ToArray();
var sep = IndexOfDoubleCrlf(all);
var body = sep >= 0 ? all[(sep + 4)..] : all;
// Use the raw header VALUE — MimeKit's ContentType.ToString() renders the whole "Content-Type: ..."
// header line (field name included), which would double the prefix on the wire.
var contentType = entity.Headers[HeaderId.ContentType] ?? "application/octet-stream";
var transferEncoding = entity.Headers[HeaderId.ContentTransferEncoding];
var contentDisposition = entity.Headers[HeaderId.ContentDisposition];
return (contentType, transferEncoding, contentDisposition, body);
}
private static int IndexOfDoubleCrlf(byte[] data)
{
for (var i = 0; i + 3 < data.Length; i++)
if (data[i] == 13 && data[i + 1] == 10 && data[i + 2] == 13 && data[i + 3] == 10)
return i;
return -1;
}
private static void AddHeader(HttpRequestMessage request, string name, string? value)
{
if (!string.IsNullOrEmpty(value))
request.Headers.TryAddWithoutValidation(name, value);
}
///
/// Bridges the exchange's own headers onto the outgoing request, skipping the reserved set (MIME + AS2
/// semantics + hop-by-hop + credentials) that we set explicitly or never forward, so a passthrough can never
/// silently corrupt them; the endpoint's strategy decides the rest (by default, redb metadata stays back).
///
private void BridgeHeaders(IExchange exchange, HttpRequestMessage request)
{
foreach (var (key, value) in exchange.In.Headers)
{
if (value is null) continue;
if (As2Headers.NonBridgedHeaders.Contains(key)) continue;
if (_headerFilter.FilterOutgoing(key, value, exchange)) continue;
request.Headers.TryAddWithoutValidation(key, value.ToString());
}
}
}
Path: redb-route/redb.Route.As2/As2Profile.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/As2Profile.cs
----
using System.Security.Cryptography.X509Certificates;
using redb.Route.Abstractions;
using redb.Route.As2.Crypto;
using redb.Route.Extensions;
namespace redb.Route.As2;
///
/// The effective AS2 trading configuration of an endpoint: certificates, identifiers and the agreed profile. It comes
/// from ONE place: the named when the endpoint names one (its URI may then not set
/// agreement options, see ), else the endpoint's inline options. Consumer, MDN receiver
/// and producer all resolve through here, once, when they start.
///
internal sealed class As2Profile
{
public X509Certificate2? OurCertificate { get; init; }
public X509Certificate2? PartnerCertificate { get; init; }
public string As2From { get; init; } = "";
public string As2To { get; init; } = "";
public string PartnerUrl { get; init; } = "";
public bool Sign { get; init; }
public bool Encrypt { get; init; }
public bool Compress { get; init; }
public string SignAlg { get; init; } = "sha-256";
public string EncryptAlg { get; init; } = "aes-128-cbc";
public As2MdnMode MdnMode { get; init; }
public bool SignedMdn { get; init; }
public bool RequireValidMdn { get; init; }
public string? AsyncMdnUrl { get; init; }
public IReadOnlyList AsyncMdnAllowedHosts { get; init; } = [];
public bool AllowLegacyAlgorithms { get; init; }
///
/// The URI options that describe the agreement. With a connection factory named, the factory is the agreement and
/// these are refused on the URI: a value there would otherwise be silently ignored, or silently win.
///
public static readonly IReadOnlyList AgreementOptions =
[
nameof(As2EndpointOptions.As2From), nameof(As2EndpointOptions.As2To),
nameof(As2EndpointOptions.Sign), nameof(As2EndpointOptions.Encrypt), nameof(As2EndpointOptions.Compress),
nameof(As2EndpointOptions.SignAlg), nameof(As2EndpointOptions.EncryptAlg),
nameof(As2EndpointOptions.MdnMode), nameof(As2EndpointOptions.SignedMdn), nameof(As2EndpointOptions.RequireValidMdn),
nameof(As2EndpointOptions.AsyncMdnUrl), nameof(As2EndpointOptions.AsyncMdnAllowedHosts),
nameof(As2EndpointOptions.AllowLegacyAlgorithms),
];
///
/// The effective, validated profile: the named connection factory, or the inline options. A set-but-unknown name
/// fails loud, never a silent fallback to inline options; an invalid agreement throws naming what is wrong.
///
public static As2Profile Resolve(IRouteContext? context, As2EndpointOptions options, string endpoint)
{
if (!string.IsNullOrEmpty(options.ConnectionFactory))
{
var factory = context.GetRequiredFromRegistry(options.ConnectionFactory);
var profile = From(factory, options.PartnerUrl);
profile.Validate($"AS2 connection factory '{options.ConnectionFactory}'");
return profile;
}
var inline = new As2Profile
{
As2From = options.As2From ?? "",
As2To = options.As2To ?? "",
PartnerUrl = options.PartnerUrl ?? "",
Sign = options.Sign,
Encrypt = options.Encrypt,
Compress = options.Compress,
SignAlg = options.SignAlg,
EncryptAlg = options.EncryptAlg,
MdnMode = options.MdnMode,
SignedMdn = options.SignedMdn,
RequireValidMdn = options.RequireValidMdn,
AsyncMdnUrl = string.IsNullOrEmpty(options.AsyncMdnUrl) ? null : options.AsyncMdnUrl,
AsyncMdnAllowedHosts = (options.AsyncMdnAllowedHosts ?? "").Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries),
AllowLegacyAlgorithms = options.AllowLegacyAlgorithms,
};
inline.Validate($"AS2 endpoint {endpoint}");
return inline;
}
/// The profile of ; the partner URL is the factory's, else .
public static As2Profile From(As2ConnectionFactory factory, string? uriPartnerUrl = null) => new()
{
OurCertificate = factory.OurCertificate,
PartnerCertificate = factory.PartnerCertificate,
As2From = factory.As2From ?? "",
As2To = factory.As2To ?? "",
PartnerUrl = !string.IsNullOrEmpty(factory.PartnerUrl) ? factory.PartnerUrl : uriPartnerUrl ?? "",
Sign = factory.Sign,
Encrypt = factory.Encrypt,
Compress = factory.Compress,
SignAlg = factory.SignAlg,
EncryptAlg = factory.EncryptAlg,
MdnMode = factory.MdnMode,
SignedMdn = factory.SignedMdn,
RequireValidMdn = factory.RequireValidMdn,
AsyncMdnUrl = string.IsNullOrEmpty(factory.AsyncMdnUrl) ? null : factory.AsyncMdnUrl,
AsyncMdnAllowedHosts = [.. factory.AsyncMdnAllowedHosts ?? []],
AllowLegacyAlgorithms = factory.AllowLegacyAlgorithms,
};
/// Whether is sha-1 or 3des under any of its spellings.
public static bool IsLegacy(string alg) => alg.Trim().ToLowerInvariant() is "sha-1" or "sha1" or "3des" or "des-ede3-cbc";
/// Checks what every role needs; throws naming .
public void Validate(string owner)
{
if (string.IsNullOrWhiteSpace(As2From))
throw new InvalidOperationException($"{owner}: As2From (our AS2 identifier) is required.");
if (string.IsNullOrWhiteSpace(As2To))
throw new InvalidOperationException($"{owner}: As2To (the partner's AS2 identifier) is required.");
// RFC 4130 §6.2: an AS2-name is 1 to 128 printable ASCII characters (a space only in its quoted form, which the
// wire format adds where needed).
foreach (var (name, value) in new[] { ("As2From", As2From), ("As2To", As2To) })
if (value.Length > 128 || value.Any(c => c is < ' ' or > '~'))
throw new InvalidOperationException(
$"{owner}: {name} '{value}' is not an AS2 identifier: 1 to 128 printable ASCII characters (RFC 4130 §6.2).");
// The digest is the MIC algorithm even when nothing is signed.
if (!As2CryptoEngine.IsSupportedDigest(SignAlg))
throw new InvalidOperationException($"{owner}: SignAlg '{SignAlg}' is not supported. Supported: sha-256, sha-384, sha-512 (sha-1 as legacy).");
if (Encrypt && !As2CryptoEngine.IsSupportedEncryption(EncryptAlg))
throw new InvalidOperationException($"{owner}: EncryptAlg '{EncryptAlg}' is not supported. Supported: aes-128-cbc, aes-192-cbc, aes-256-cbc (3des as legacy).");
foreach (var (name, alg) in new[] { ("SignAlg", SignAlg), ("EncryptAlg", Encrypt ? EncryptAlg : "") })
if (IsLegacy(alg) && !AllowLegacyAlgorithms)
throw new InvalidOperationException(
$"{owner}: {name} '{alg}' is a legacy algorithm; set AllowLegacyAlgorithms only if the partner requires it.");
// Our key signs messages and MDNs and decrypts what the partner encrypts; the partner's certificate verifies
// its signatures and encrypts for it.
var signsMdn = MdnMode != As2MdnMode.None && SignedMdn;
if (Sign || Encrypt || signsMdn)
{
if (OurCertificate is null)
throw new InvalidOperationException($"{owner}: OurCertificate is required (signing, decryption or signed MDNs are agreed).");
if (!OurCertificate.HasPrivateKey)
throw new InvalidOperationException($"{owner}: OurCertificate has no private key; it signs and decrypts.");
if (PartnerCertificate is null)
throw new InvalidOperationException($"{owner}: PartnerCertificate is required (signatures, encryption or signed MDNs are agreed).");
}
if (AsyncMdnUrl is not null && !IsHttpUrl(AsyncMdnUrl))
throw new InvalidOperationException($"{owner}: AsyncMdnUrl '{AsyncMdnUrl}' is not an absolute http(s) URL.");
if (!string.IsNullOrEmpty(PartnerUrl) && !IsHttpUrl(PartnerUrl))
throw new InvalidOperationException($"{owner}: PartnerUrl '{redb.Route.Abstractions.EndpointUri.Sanitize(PartnerUrl)}' is not an absolute http(s) URL.");
}
private static bool IsHttpUrl(string url) =>
Uri.TryCreate(url, UriKind.Absolute, out var uri) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps);
}
Path: redb-route/redb.Route.As2/Crypto/As2CertificateValidity.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/Crypto/As2CertificateValidity.cs
----
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace redb.Route.As2.Crypto;
///
/// Whether a certificate an agreement pins may be used now. The pin says whose key it is; it does not make an expired
/// key current (the AS4 connector's rule, after Holodeck and Domibus). Revocation (CRL/OCSP) and chain trust are not
/// checked: the pin is the trust, and revocation is a documented gap of this connector.
///
internal static class As2CertificateValidity
{
/// Null when is valid at ; otherwise why not, naming .
public static string? Problem(X509Certificate2 certificate, DateTimeOffset now, string role)
{
ArgumentNullException.ThrowIfNull(certificate);
var who = $"{role} {certificate.Subject} ({certificate.Thumbprint})";
var utc = now.UtcDateTime;
if (utc < certificate.NotBefore.ToUniversalTime())
return $"{who} is not yet valid: valid from {certificate.NotBefore.ToUniversalTime():O}.";
if (utc > certificate.NotAfter.ToUniversalTime())
return $"{who} has expired: valid until {certificate.NotAfter.ToUniversalTime():O}.";
return null;
}
/// Throws when may not be used now.
public static void Ensure(X509Certificate2 certificate, string role)
{
if (Problem(certificate, DateTimeOffset.UtcNow, role) is { } problem)
throw new CryptographicException(problem);
}
}
Path: redb-route/redb.Route.As2/Crypto/As2CryptoEngine.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/Crypto/As2CryptoEngine.cs
----
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using MimeKit;
using MimeKit.Cryptography;
namespace redb.Route.As2.Crypto;
///
/// Default AS2 crypto engine, built on MimeKit's S/MIME support (Bouncy Castle underneath) — the same
/// cryptographic foundation the AS2 industry (camel-as2, OpenAS2, Mendelson) interoperates on.
/// Uses an in-memory per operation with the relevant certificate
/// imported, so no on-disk certificate store is required.
///
internal sealed class As2CryptoEngine : IAs2CryptoEngine
{
///
public MultipartSigned Sign(MimeEntity content, X509Certificate2 signerCert, string micalg)
{
ArgumentNullException.ThrowIfNull(content);
ArgumentNullException.ThrowIfNull(signerCert);
if (!signerCert.HasPrivateKey)
throw new ArgumentException("Signing certificate must have a private key.", nameof(signerCert));
using var ctx = new TemporarySecureMimeContext();
var signer = new CmsSigner(signerCert) { DigestAlgorithm = MapDigest(micalg) };
return MultipartSigned.Create(ctx, signer, content);
}
///
public MimeEntity Encrypt(MimeEntity content, X509Certificate2 recipientCert, string encAlg)
{
ArgumentNullException.ThrowIfNull(content);
ArgumentNullException.ThrowIfNull(recipientCert);
using var ctx = new TemporarySecureMimeContext();
var recipient = new CmsRecipient(recipientCert) { EncryptionAlgorithms = [MapEncryption(encAlg)] };
return ApplicationPkcs7Mime.Encrypt(ctx, new CmsRecipientCollection { recipient }, content);
}
///
public MimeEntity Compress(MimeEntity content)
{
ArgumentNullException.ThrowIfNull(content);
using var ctx = new TemporarySecureMimeContext();
return ApplicationPkcs7Mime.Compress(ctx, content);
}
///
public MimeEntity Decrypt(MimeEntity encrypted, X509Certificate2 ourCert)
{
ArgumentNullException.ThrowIfNull(encrypted);
ArgumentNullException.ThrowIfNull(ourCert);
if (encrypted is not ApplicationPkcs7Mime { SecureMimeType: SecureMimeType.EnvelopedData } pkcs7)
throw new ArgumentException("Entity is not S/MIME enveloped-data.", nameof(encrypted));
using var ctx = new TemporarySecureMimeContext();
ctx.Import(ourCert);
return pkcs7.Decrypt(ctx);
}
///
public void DecryptTo(ApplicationPkcs7Mime encrypted, X509Certificate2 ourCert, Stream output)
{
ArgumentNullException.ThrowIfNull(encrypted);
ArgumentNullException.ThrowIfNull(ourCert);
ArgumentNullException.ThrowIfNull(output);
if (encrypted.SecureMimeType != SecureMimeType.EnvelopedData || encrypted.Content is null)
throw new ArgumentException("Entity is not S/MIME enveloped-data.", nameof(encrypted));
using var ctx = new TemporarySecureMimeContext();
ctx.Import(ourCert);
using var der = encrypted.Content.Open(); // the transfer encoding (base64) removed
ctx.DecryptTo(der, output);
}
///
public void DecompressTo(ApplicationPkcs7Mime compressed, Stream output)
{
ArgumentNullException.ThrowIfNull(compressed);
ArgumentNullException.ThrowIfNull(output);
if (compressed.SecureMimeType != SecureMimeType.CompressedData || compressed.Content is null)
throw new ArgumentException("Entity is not S/MIME compressed-data.", nameof(compressed));
using var ctx = new TemporarySecureMimeContext();
using var der = compressed.Content.Open();
ctx.DecompressTo(der, output);
}
///
public bool Verify(MultipartSigned signed, X509Certificate2 signerCert)
{
ArgumentNullException.ThrowIfNull(signed);
ArgumentNullException.ThrowIfNull(signerCert);
using var ctx = new TemporarySecureMimeContext();
ctx.Import(signerCert);
try
{
var signatures = signed.Verify(ctx);
if (signatures.Count == 0)
return false;
foreach (var signature in signatures)
{
// The signature must be cryptographically valid AND made by the expected partner
// certificate — an S/MIME signature embeds its own signer cert, so crypto validity alone
// does not prove *who* signed. Bind it to signerCert by fingerprint.
if (!signature.Verify(verifySignatureOnly: true))
return false;
var fingerprint = signature.SignerCertificate?.Fingerprint;
if (fingerprint is null || !FingerprintMatches(fingerprint, signerCert))
return false;
}
return true;
}
catch (DigitalSignatureVerifyException)
{
return false;
}
}
///
public MimeEntity Decompress(MimeEntity compressed)
{
ArgumentNullException.ThrowIfNull(compressed);
if (compressed is not ApplicationPkcs7Mime { SecureMimeType: SecureMimeType.CompressedData } pkcs7)
throw new ArgumentException("Entity is not S/MIME compressed-data.", nameof(compressed));
using var ctx = new TemporarySecureMimeContext();
return pkcs7.Decompress(ctx);
}
///
public As2Mic ComputeReceivedMic(MimeEntity part, string micalg)
{
ArgumentNullException.ThrowIfNull(part);
using var hasher = CreateHash(micalg);
using (var stream = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write, leaveOpen: true))
{
// No Prepare: that would re-encode a binary part (as OpenAS2 signs it) to base64 before it is hashed. The
// part was parsed from the wire, so its headers and content are written back as they came, with CRLF line
// ends as on the wire: FormatOptions.Default takes the platform's, LF on Linux, and the MIC would differ.
part.WriteTo(CrlfFormat, stream);
}
return new As2Mic(Convert.ToBase64String(hasher.Hash!), NormalizeAlg(micalg));
}
///
public As2Mic ComputeMic(MimeEntity part, string micalg, bool includeHeaders)
{
ArgumentNullException.ThrowIfNull(part);
// Hashed as it is written: the content is never copied into memory to be hashed (a received one may be spooled).
using var hasher = CreateHash(micalg);
using (var stream = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write, leaveOpen: true))
{
if (includeHeaders)
{
// Signed / encrypted: hash the MIME headers + content, CRLF-canonicalized (RFC 4130 §7.3.1).
part.Prepare(EncodingConstraint.SevenBit);
part.WriteTo(CrlfFormat, stream);
}
else if (part is MimePart { Content: not null } mp)
{
// Plain: hash the decoded content only, without MIME headers.
mp.Content.DecodeTo(stream);
}
else
{
part.WriteTo(CrlfFormat, stream);
}
}
return new As2Mic(Convert.ToBase64String(hasher.Hash!), NormalizeAlg(micalg));
}
/// MIME written with CRLF line ends on every platform, as on the wire (RFC 4130 §7.3.1).
private static readonly FormatOptions CrlfFormat = CreateCrlfFormat();
private static FormatOptions CreateCrlfFormat()
{
var options = FormatOptions.Default.Clone();
options.NewLineFormat = NewLineFormat.Dos;
return options;
}
///
/// True if MimeKit's signer fingerprint matches . MimeKit reports the SHA-1
/// fingerprint as hex; .NET's is the same SHA-1 hash in a
/// different case, so we normalize both to lowercase hex (and fall back to hashing the raw cert).
///
private static bool FingerprintMatches(string mimeKitFingerprint, X509Certificate2 cert)
{
static string Norm(string s) => string.Concat(s.Where(Uri.IsHexDigit)).ToLowerInvariant();
var actual = Norm(mimeKitFingerprint);
if (actual == Norm(cert.Thumbprint))
return true;
var sha1 = Convert.ToHexString(cert.GetCertHash(HashAlgorithmName.SHA1)).ToLowerInvariant();
return actual == sha1;
}
/// Whether is a signature digest this engine supports.
public static bool IsSupportedDigest(string alg)
=> Normalize(alg) is "sha-256" or "sha-1" or "sha-384" or "sha-512";
/// Whether is an encryption algorithm this engine supports.
public static bool IsSupportedEncryption(string alg) => alg.ToLowerInvariant() is
"aes-128-cbc" or "aes128" or "aes-192-cbc" or "aes192" or "aes-256-cbc" or "aes256" or "3des" or "des-ede3-cbc";
// ── Algorithm mapping ────────────────────────────────────────────────────
private static DigestAlgorithm MapDigest(string micalg) => Normalize(micalg) switch
{
"sha-256" => DigestAlgorithm.Sha256,
"sha-1" => DigestAlgorithm.Sha1,
"sha-384" => DigestAlgorithm.Sha384,
"sha-512" => DigestAlgorithm.Sha512,
_ => throw new NotSupportedException($"Unsupported signature digest algorithm '{micalg}'."),
};
private static EncryptionAlgorithm MapEncryption(string alg) => alg.ToLowerInvariant() switch
{
"aes-128-cbc" or "aes128" => EncryptionAlgorithm.Aes128,
"aes-192-cbc" or "aes192" => EncryptionAlgorithm.Aes192,
"aes-256-cbc" or "aes256" => EncryptionAlgorithm.Aes256,
"3des" or "des-ede3-cbc" => EncryptionAlgorithm.TripleDes,
_ => throw new NotSupportedException($"Unsupported encryption algorithm '{alg}'."),
};
private static HashAlgorithm CreateHash(string micalg) => Normalize(micalg) switch
{
"sha-256" => SHA256.Create(),
"sha-1" => SHA1.Create(),
"sha-384" => SHA384.Create(),
"sha-512" => SHA512.Create(),
_ => throw new NotSupportedException($"Unsupported MIC algorithm '{micalg}'."),
};
/// Canonical AS2 micalg spelling (e.g. sha-256).
private static string NormalizeAlg(string micalg) => Normalize(micalg);
private static string Normalize(string alg) => alg.ToLowerInvariant() switch
{
"sha256" or "sha-256" => "sha-256",
"sha1" or "sha-1" => "sha-1",
"sha384" or "sha-384" => "sha-384",
"sha512" or "sha-512" => "sha-512",
_ => alg.ToLowerInvariant(),
};
}
Path: redb-route/redb.Route.As2/Crypto/As2Mic.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/Crypto/As2Mic.cs
----
using redb.Route.Serialization;
namespace redb.Route.As2.Crypto;
///
/// An AS2 Message Integrity Check: a base64 message digest plus the algorithm name, in the wire format
/// AS2 uses for the Received-Content-MIC MDN field — "<base64-digest>, <algorithm>"
/// (RFC 4130 §7.3.1). The sender computes it over the content it signed; the receiver recomputes it and
/// returns it in the MDN so the sender can confirm the partner got exactly what was sent, intact.
///
public readonly record struct As2Mic(string Digest, string Algorithm)
{
/// Renders the MIC in AS2 wire format: "base64digest, algorithm".
public override string ToString() => $"{Digest}, {Algorithm}";
///
/// Parses an AS2 Received-Content-MIC value ("base64digest, algorithm"). The digest is
/// base64 and never contains a comma, so we split on the last comma to be robust.
///
public static As2Mic Parse(string value)
{
ArgumentException.ThrowIfNullOrWhiteSpace(value);
var comma = value.LastIndexOf(',');
if (comma < 0)
throw new FormatException($"Not a valid AS2 MIC (missing ', algorithm'): '{value}'.");
return new As2Mic(value[..comma].Trim(), value[(comma + 1)..].Trim());
}
///
/// Whether this MIC equals : the same digest bytes (base64 compared after decoding, so folded
/// lines, spaces and missing padding do not matter) and the same algorithm (sha-256 and SHA256 are one).
///
public bool Matches(As2Mic other)
{
if (!string.Equals(AlgorithmKey(Algorithm), AlgorithmKey(other.Algorithm), StringComparison.Ordinal))
return false;
var mine = DigestBytes(Digest);
var theirs = DigestBytes(other.Digest);
return mine is not null && theirs is not null && mine.AsSpan().SequenceEqual(theirs);
}
private static string AlgorithmKey(string algorithm) =>
algorithm.Replace("-", "", StringComparison.Ordinal).Trim().ToLowerInvariant();
private static byte[]? DigestBytes(string digest)
{
var compact = string.Concat(digest.Where(c => !char.IsWhiteSpace(c)));
if (compact.Length % 4 != 0)
compact = compact.PadRight(compact.Length + (4 - compact.Length % 4), '=');
var buffer = new byte[compact.Length * 3 / 4];
return Base64Text.TryDecode(compact, buffer, out var written) && written > 0 ? buffer[..written] : null;
}
}
Path: redb-route/redb.Route.As2/Crypto/BoundedWriteStream.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/Crypto/BoundedWriteStream.cs
----
namespace redb.Route.As2.Crypto;
///
/// Writes through to a stream and fails past a limit, so an unwrapping step that inflates its input (decompression)
/// stops at the bound instead of filling the spool.
///
internal sealed class BoundedWriteStream(Stream inner, long limit, string limitName) : Stream
{
private long _written;
public override bool CanRead => false;
public override bool CanSeek => false;
public override bool CanWrite => true;
public override long Length => _written;
public override long Position { get => _written; set => throw new NotSupportedException(); }
public override void Write(byte[] buffer, int offset, int count)
{
Count(count);
inner.Write(buffer, offset, count);
}
public override void Write(ReadOnlySpan buffer)
{
Count(buffer.Length);
inner.Write(buffer);
}
public override void WriteByte(byte value)
{
Count(1);
inner.WriteByte(value);
}
public override async ValueTask WriteAsync(ReadOnlyMemory buffer, CancellationToken ct = default)
{
Count(buffer.Length);
await inner.WriteAsync(buffer, ct).ConfigureAwait(false);
}
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken ct) =>
WriteAsync(buffer.AsMemory(offset, count), ct).AsTask();
private void Count(int count)
{
_written += count;
if (_written > limit)
throw new InvalidDataException($"the content inflates past {limitName} {limit} bytes.");
}
public override void Flush() => inner.Flush();
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
}
Path: redb-route/redb.Route.As2/Crypto/IAs2CryptoEngine.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/Crypto/IAs2CryptoEngine.cs
----
using System.Security.Cryptography.X509Certificates;
using MimeKit;
using MimeKit.Cryptography;
namespace redb.Route.As2.Crypto;
///
/// S/MIME operations an AS2 connector needs: sign, encrypt, compress and their inverses, plus the AS2
/// Message Integrity Check. Kept behind an interface so the crypto backend is swappable (default:
/// on MimeKit / Bouncy Castle — the industry AS2 foundation; escape hatch:
/// Bouncy Castle .NET directly). Works on MimeKit's MIME model.
///
internal interface IAs2CryptoEngine
{
/// Signs into a multipart/signed with our certificate.
MultipartSigned Sign(MimeEntity content, X509Certificate2 signerCert, string micalg);
/// Encrypts to the partner's certificate (S/MIME enveloped-data).
MimeEntity Encrypt(MimeEntity content, X509Certificate2 recipientCert, string encAlg);
/// Compresses (RFC 3274 compressed-data).
MimeEntity Compress(MimeEntity content);
/// Decrypts an S/MIME enveloped-data entity with our private key.
MimeEntity Decrypt(MimeEntity encrypted, X509Certificate2 ourCert);
///
/// Decrypts an S/MIME enveloped-data entity with our private key, writing the decrypted MIME entity to
/// (a spool) instead of building it in memory.
///
void DecryptTo(ApplicationPkcs7Mime encrypted, X509Certificate2 ourCert, Stream output);
/// Decompresses an RFC 3274 compressed-data entity into (a spool).
void DecompressTo(ApplicationPkcs7Mime compressed, Stream output);
/// Verifies a multipart/signed against the partner's certificate.
bool Verify(MultipartSigned signed, X509Certificate2 signerCert);
/// Decompresses an RFC 3274 compressed-data entity.
MimeEntity Decompress(MimeEntity compressed);
///
/// Computes the AS2 MIC over per RFC 4130 §7.3.1. When
/// is true (signed / encrypted messages) the MIME headers and content
/// are hashed together, CRLF-canonicalized; when false (plain messages) only the content is hashed.
///
As2Mic ComputeMic(MimeEntity part, string micalg, bool includeHeaders);
///
/// The MIC of a RECEIVED signed part (RFC 4130 §7.3.1): its MIME headers and content exactly as they arrived, with
/// no re-encoding. The sending side prepares a part before it signs it; the receiving side hashes what was signed.
///
As2Mic ComputeReceivedMic(MimeEntity part, string micalg);
}
Path: redb-route/redb.Route.As2/Extensions/ServiceCollectionExtensions.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/Extensions/ServiceCollectionExtensions.cs
----
using Microsoft.Extensions.DependencyInjection;
using redb.Route.Extensions;
using redb.Route.Http;
namespace redb.Route.As2;
///
/// Extension methods for registering the AS2 transport in a DI container.
///
public static class ServiceCollectionExtensions
{
///
/// Registers the in the route context so that as2:// and
/// as2s:// URIs are resolved.
///
///
/// services.AddRedbRoute(route =>
/// {
/// route.Services.AddRedbRouteAs2();
/// route.AddRouteBuilder<MyRoutes>();
/// });
///
///
///
public static IServiceCollection AddRedbRouteAs2(this IServiceCollection services)
{
// Share ONE Kestrel host with every other HTTP-based connector in this worker (idempotent).
services.AddRedbRouteHttpHosting();
services.AddSingleton();
// IRouteContextConfigurator is applied by RouteHostedService at startup --
// the correct registration hook (a lazy marker singleton never fires).
services.AddRouteContextConfigurator((sp, context) =>
{
var component = sp.GetRequiredService();
component.ServerManager = sp.GetRequiredService();
context.AddComponent(component); // registers as2 + as2s, sets Context + Logger
});
return services;
}
}
Path: redb-route/redb.Route.As2/Fluent/As2.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/Fluent/As2.cs
----
using System.Text;
namespace redb.Route.As2.Fluent;
///
/// Entry point for the AS2 fluent DSL.
///
/// // Receive server (consumer)
/// From(As2.Receive("/inbound/orders").Host("0.0.0.0").Port(4080).ConnectionFactory("walmart"))
/// .To("direct://process-edi");
///
/// // Send to partner (producer)
/// From("direct://outbound")
/// .To(As2.Send("https://partner.example.com/as2").ConnectionFactory("walmart"));
///
///
public static class As2
{
/// AS2 receive server on the given HTTP path.
public static As2Builder Receive(string path) => new(As2Mode.Receive, path);
/// AS2 async-MDN receiver on the given HTTP path (correlates receipts posted back by partners).
public static As2Builder ReceiveMdn(string path) => new(As2Mode.Receive, path) { AsMdnReceiver = true };
/// AS2 producer that POSTs to the given partner URL.
public static As2Builder Send(string url) => new(As2Mode.Send, url);
}
/// Which side of the AS2 exchange a builder produces.
internal enum As2Mode
{
/// Receive server (consumer).
Receive,
/// Send client (producer).
Send,
}
///
/// Fluent builder for AS2 endpoint URIs. Builds a string consumed by .
///
/// Receive: as2:/path?host=..&port=.. — host/port as query, the path kept intact (no first-segment
/// truncation, mirroring the Http listener fix). Send: as2[s]://host[:port]/path — HTTPS maps to the
/// as2s scheme.
///
///
public sealed class As2Builder
{
private readonly As2Mode _mode;
private readonly string _target;
private string? _host;
private int? _port;
private string? _connectionFactory;
private bool _useTls;
private string? _sslCertPath;
private string? _sslCertPassword;
private int? _maxConcurrentRequests;
private int? _requestQueueLimit;
private int? _rejectStatusCode;
private int? _retryAfterSeconds;
private long? _maxRequestBodySize;
private long? _maxDecompressedSize;
private int? _asyncMdnPoolSize;
private int? _inFlightClaimTimeout;
private int? _asyncMdnAttempts;
private int? _asyncMdnRetryDelay;
private string? _idempotentRepository;
private bool _streamBody;
private long? _maxResponseBodySize;
/// When set, this receive endpoint accepts async MDN receipts (mode=mdn).
internal bool AsMdnReceiver { get; init; }
internal As2Builder(As2Mode mode, string target)
{
_mode = mode;
_target = target ?? throw new ArgumentNullException(nameof(target));
}
/// Bind host for the receive server (consumer only).
public As2Builder Host(string host) { _host = host; return this; }
/// Listen port for the receive server (consumer only).
public As2Builder Port(int port) { _port = port; return this; }
/// Reference a named from the registry instead of inline config.
public As2Builder ConnectionFactory(string name) { _connectionFactory = name; return this; }
///
/// Serve the receive endpoint over TLS. The certificate is the one presented to the trading
/// partner on the connection — not the S/MIME key that signs the payload. Omit it here to take
/// the certificate from the named connection factory or from the host default; a TLS receiver
/// that finds none anywhere refuses to bind.
///
public As2Builder Tls(string? certPath = null, string? certPassword = null)
{
_useTls = true;
_sslCertPath = certPath;
_sslCertPassword = certPassword;
return this;
}
///
/// Admission limit (receive endpoint): at most concurrent pipeline
/// executions (default 32, 0 = unlimited); overflow beyond the FIFO (not given: 32 while
/// limits) is shed with 503 + Retry-After before any MIME/crypto work.
///
public As2Builder MaxConcurrentRequests(int max, int? queue = null)
{
_maxConcurrentRequests = max;
_requestQueueLimit = queue;
return this;
}
/// Status code of a refused request: shed, or every asynchronous MDN slot taken (default 503).
public As2Builder RejectStatusCode(int statusCode) { _rejectStatusCode = statusCode; return this; }
/// Retry-After value of a refused request in seconds; 0 = do not send (default 30).
public As2Builder RetryAfterSeconds(int seconds) { _retryAfterSeconds = seconds; return this; }
///
/// Receive endpoint: how many asynchronous MDNs are handled at once (default 20); a message asking for one when
/// every slot is taken is refused before any work.
///
public As2Builder AsyncMdnPoolSize(int size) { _asyncMdnPoolSize = size; return this; }
///
/// Receive endpoint: an asynchronous MDN is posted at most times (default 3), the first
/// retry after milliseconds (default 5000), doubled for each one after it.
///
public As2Builder AsyncMdnRetry(int attempts, int delayMs)
{
_asyncMdnAttempts = attempts;
_asyncMdnRetryDelay = delayMs;
return this;
}
/// Receive endpoint: a named IIdempotentRepository that remembers received Message-IDs, so a resend is not delivered twice.
public As2Builder IdempotentRepository(string name) { _idempotentRepository = name; return this; }
///
/// Receive endpoint, with an idempotent repository: milliseconds after which an unconfirmed claim of a Message-ID is
/// taken over (default 600000); a copy arriving while a younger claim is in flight is refused as busy.
///
public As2Builder InFlightClaimTimeout(int milliseconds) { _inFlightClaimTimeout = milliseconds; return this; }
/// Receive endpoint: hand the payload to the route as a spooled Stream instead of byte[].
public As2Builder StreamBody(bool streamBody = true) { _streamBody = streamBody; return this; }
/// Receive endpoint: the largest request body accepted, in bytes (default 100 MB); larger is answered 413.
public As2Builder MaxRequestBodySize(long bytes) { _maxRequestBodySize = bytes; return this; }
///
/// Receive endpoint: the most bytes a compressed message may inflate to; past it the message is refused with
/// decompression-failed. Unset: .
///
public As2Builder MaxDecompressedSize(long bytes) { _maxDecompressedSize = bytes; return this; }
/// Send endpoint: the largest response (synchronous MDN) read, in bytes (default 4 MB).
public As2Builder MaxResponseBodySize(long bytes) { _maxResponseBodySize = bytes; return this; }
/// Builds the AS2 URI string.
public string Build() => _mode == As2Mode.Receive ? BuildReceive() : BuildSend();
private string BuildReceive()
{
// Keep the path intact incl. its leading slash — the first segment must NOT be dropped
// (see the Http ConsumerPath fix). host/port travel as query parameters.
var path = _target.StartsWith('/') ? _target : "/" + _target;
var sb = new StringBuilder("as2:").Append(path);
var sep = '?';
void Add(string k, string v) { sb.Append(sep).Append(k).Append('=').Append(Uri.EscapeDataString(v)); sep = '&'; }
if (_host is not null) Add("host", _host);
if (_port is not null) Add("port", _port.Value.ToString());
if (_connectionFactory is not null) Add("connectionFactory", _connectionFactory);
if (_useTls) Add("useTls", "true");
if (_sslCertPath is not null) Add("sslCertPath", _sslCertPath);
if (_sslCertPassword is not null) Add("sslCertPassword", _sslCertPassword);
if (_maxConcurrentRequests is { } max) Add("maxConcurrentRequests", max.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_requestQueueLimit is { } queue) Add("requestQueueLimit", queue.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_rejectStatusCode is { } rsc) Add("rejectStatusCode", rsc.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_retryAfterSeconds is { } ras) Add("retryAfterSeconds", ras.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_maxRequestBodySize is { } mrb) Add("maxRequestBodySize", mrb.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_maxDecompressedSize is { } mds) Add("maxDecompressedSize", mds.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_asyncMdnPoolSize is { } amp) Add("asyncMdnPoolSize", amp.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_asyncMdnAttempts is { } ama) Add("asyncMdnAttempts", ama.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_asyncMdnRetryDelay is { } amd) Add("asyncMdnRetryDelay", amd.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (_streamBody) Add("streamBody", "true");
if (_idempotentRepository is not null) Add("idempotentRepository", _idempotentRepository);
if (_inFlightClaimTimeout is { } ict) Add("inFlightClaimTimeout", ict.ToString(System.Globalization.CultureInfo.InvariantCulture));
if (AsMdnReceiver) Add("mode", "mdn");
return sb.ToString();
}
private string BuildSend()
{
// Map the partner URL scheme onto as2/as2s so the component is selected; TLS is carried by the scheme.
var scheme = "as2";
var rest = _target;
if (rest.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) { scheme = "as2s"; rest = rest["https://".Length..]; }
else if (rest.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) { rest = rest["http://".Length..]; }
else if (rest.StartsWith("as2s://", StringComparison.OrdinalIgnoreCase)) { scheme = "as2s"; rest = rest["as2s://".Length..]; }
else if (rest.StartsWith("as2://", StringComparison.OrdinalIgnoreCase)) { rest = rest["as2://".Length..]; }
var sb = new StringBuilder(scheme).Append("://").Append(rest);
var sep = rest.Contains('?') ? '&' : '?';
void Add(string k, string v) { sb.Append(sep).Append(k).Append('=').Append(Uri.EscapeDataString(v)); sep = '&'; }
if (_connectionFactory is not null) Add("connectionFactory", _connectionFactory);
if (_maxResponseBodySize is { } mrs) Add("maxResponseBodySize", mrs.ToString(System.Globalization.CultureInfo.InvariantCulture));
return sb.ToString();
}
/// Allows passing the builder directly to From()/To() without calling Build().
public static implicit operator string(As2Builder builder) => builder.Build();
///
public override string ToString() => Build();
}
Path: redb-route/redb.Route.As2/Mdn/As2Disposition.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/Mdn/As2Disposition.cs
----
namespace redb.Route.As2.Mdn;
///
/// The disposition modifiers of RFC 4130 §7.4.3 a receiver reports when it did not process a message. The MDN carries
/// the code and a fixed text with a reference; what went wrong in detail stays in our log (the partner learns the
/// class of the failure, not our internals).
///
internal static class As2Disposition
{
/// The sender is not the agreed partner: identifiers or signature do not match the agreement.
public const string AuthenticationFailed = "authentication-failed";
/// The message could not be decrypted with our key.
public const string DecryptionFailed = "decryption-failed";
/// The compressed payload could not be decompressed.
public const string DecompressionFailed = "decompression-failed";
/// The message is signed or encrypted less than the agreement requires.
public const string InsufficientMessageSecurity = "insufficient-message-security";
/// Anything else: a malformed message, or the route failed to process it.
public const string UnexpectedProcessingError = "unexpected-processing-error";
///
/// The sender requires a signed-receipt protocol other than pkcs7-signature: a failed/Failure
/// disposition (RFC 4130 §7.5.3), the message is not processed.
///
public const string UnsupportedFormat = "unsupported format";
///
/// The sender requires MIC algorithms of which none is usable here: a failed/Failure disposition
/// (RFC 4130 §7.5.3), the message is not processed.
///
public const string UnsupportedMicAlgorithms = "unsupported MIC-algorithms";
///
/// Whether is reported as failed/Failure: modifier (no MDN as asked could be
/// generated) rather than processed/error: modifier.
///
public static bool IsFailure(string modifier) => modifier is UnsupportedFormat or UnsupportedMicAlgorithms;
/// The text of the MDN's human-readable part for a failure .
public static string Describe(string modifier) => modifier switch
{
AuthenticationFailed => "The AS2 message could not be authenticated as coming from the agreed partner.",
DecryptionFailed => "The AS2 message could not be decrypted.",
DecompressionFailed => "The AS2 message could not be decompressed.",
InsufficientMessageSecurity => "The AS2 message is not signed or encrypted as the agreement requires.",
UnsupportedFormat => "The AS2 message requires a signed-receipt protocol this receiver does not support; it was not processed.",
UnsupportedMicAlgorithms => "The AS2 message requires MIC algorithms this receiver does not support; it was not processed.",
_ => "The AS2 message could not be processed.",
};
}
/// A received message was not processed, for the reason names (RFC 4130 §7.4.3).
internal sealed class As2DispositionException : Exception
{
public As2DispositionException(string modifier, string detail, Exception? inner = null)
: base(detail, inner) => Modifier = modifier;
/// One of the codes.
public string Modifier { get; }
}
Path: redb-route/redb.Route.As2/Mdn/MdnBuilder.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/Mdn/MdnBuilder.cs
----
using System.Security.Cryptography.X509Certificates;
using System.Text;
using MimeKit;
using redb.Route.As2.Crypto;
namespace redb.Route.As2.Mdn;
///
/// Builds an AS2 MDN (Message Disposition Notification) — a multipart/report;
/// report-type=disposition-notification with a human-readable part and a machine
/// message/disposition-notification part carrying Original-Message-ID, Disposition
/// and Received-Content-MIC (RFC 4130 §7), wrapped in multipart/signed when a signer is given.
///
internal static class MdnBuilder
{
///
/// Builds an MDN reporting on a message we received. is the receiver (us —
/// the MDN's AS2-From and Final-Recipient); is the original sender (AS2-To).
/// Returns the MDN as HTTP-ready parts: the top-level Content-Type, the CTE, and the body bytes.
/// is null for a processed message, else an code; the
/// human-readable part then carries the fixed text of the code and , never our exception.
/// qualifies a processed message (RFC 4130 §7.4.3, e.g. duplicate-document).
///
public static (string contentType, string? transferEncoding, byte[] body) Build(
string originalMessageId,
string ourAs2Id,
string partnerAs2Id,
As2Mic? receivedMic,
string? failure = null,
string? reference = null,
IAs2CryptoEngine? signer = null,
X509Certificate2? signerCert = null,
string signAlg = "sha-256",
string? warning = null)
{
var human = new TextPart("plain")
{
Text = failure is null
? "The AS2 message was received and processed successfully."
: As2Disposition.Describe(failure) + (string.IsNullOrEmpty(reference) ? "" : $" Reference: {reference}."),
};
var machine = new SevenBitDispositionNotification();
machine.Fields.Add("Reporting-UA", "redb.Route.As2");
if (!string.IsNullOrEmpty(ourAs2Id)) machine.Fields.Add("Original-Recipient", $"rfc822; {ourAs2Id}");
if (!string.IsNullOrEmpty(ourAs2Id)) machine.Fields.Add("Final-Recipient", $"rfc822; {ourAs2Id}");
if (!string.IsNullOrEmpty(ourAs2Id)) machine.Fields.Add("AS2-From", ourAs2Id);
if (!string.IsNullOrEmpty(partnerAs2Id)) machine.Fields.Add("AS2-To", partnerAs2Id);
if (!string.IsNullOrEmpty(originalMessageId)) machine.Fields.Add("Original-Message-ID", originalMessageId);
machine.Fields.Add("Disposition", failure is null
? "automatic-action/MDN-sent-automatically; processed" + (warning is null ? "" : $"/warning: {warning}")
: As2Disposition.IsFailure(failure)
? $"automatic-action/MDN-sent-automatically; failed/Failure: {failure}"
: $"automatic-action/MDN-sent-automatically; processed/error: {failure}");
if (receivedMic is not null)
machine.Fields.Add("Received-Content-MIC", receivedMic.Value.ToString());
var report = new MultipartReport("disposition-notification") { human, machine };
// A signed MDN wraps the report in multipart/signed (partners commonly require it).
MimeEntity entity = signer is not null && signerCert is not null
? signer.Sign(report, signerCert, signAlg)
: report;
using var ms = new MemoryStream();
var options = FormatOptions.Default.Clone();
options.NewLineFormat = NewLineFormat.Dos;
entity.WriteTo(options, ms);
var all = ms.ToArray();
var sep = IndexOfDoubleCrlf(all);
var body = sep >= 0 ? all[(sep + 4)..] : all;
var contentType = entity.Headers[HeaderId.ContentType] ?? "multipart/report";
var transferEncoding = entity.Headers[HeaderId.ContentTransferEncoding];
return (contentType, transferEncoding, body);
}
private static int IndexOfDoubleCrlf(byte[] data)
{
for (var i = 0; i + 3 < data.Length; i++)
if (data[i] == 13 && data[i + 1] == 10 && data[i + 2] == 13 && data[i + 3] == 10)
return i;
return -1;
}
}
///
/// The machine-readable MDN part, kept 7bit as RFC 3798 §3.1 requires ("MUST be used"). MimeKit's signing prepares
/// every part for a 78-character line and would re-encode a longer field line (an OpenAS2 Message-ID is about 90) as
/// quoted-printable; a partner that reads the fields without decoding them (OpenAS2 does) then cuts the
/// Original-Message-ID at the soft line break and never finds the message an asynchronous MDN reports on. The fields
/// are ASCII and far below the 998-character line limit of 7bit.
///
internal sealed class SevenBitDispositionNotification : MessageDispositionNotification
{
public SevenBitDispositionNotification() => ContentTransferEncoding = ContentEncoding.SevenBit;
///
public override void Prepare(EncodingConstraint constraint, int maxLineLength = 78) =>
ContentTransferEncoding = ContentEncoding.SevenBit;
}
Path: redb-route/redb.Route.As2/Mdn/MdnParser.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/Mdn/MdnParser.cs
----
using System.Security.Cryptography.X509Certificates;
using System.Text;
using MimeKit;
using MimeKit.Cryptography;
using redb.Route.As2.Crypto;
namespace redb.Route.As2.Mdn;
///
/// Parses an inbound AS2 MDN: verifies its signature (if signed), and extracts the disposition and the
/// Received-Content-MIC so the sender can confirm the partner received exactly what was sent.
///
internal static class MdnParser
{
/// Outcome of parsing an MDN.
public sealed record MdnResult(string? OriginalMessageId, string? Disposition, As2Mic? ReceivedMic, bool SignatureValid, bool IsPositive);
public static MdnResult Parse(string? contentType, string? transferEncoding, byte[] body, IAs2CryptoEngine engine, X509Certificate2? partnerCert)
{
var entity = LoadEntity(contentType, transferEncoding, body);
// Default false: an UNSIGNED MDN is not a valid signature. Only a present-and-verified signature sets it
// true, so a sender that requires a signed receipt (SignedMdn) can reject a stripped/forged one.
var signatureValid = false;
if (entity is MultipartSigned signed)
{
// A pinned certificate outside its validity verifies nothing (As2CertificateValidity).
signatureValid = partnerCert is not null
&& As2CertificateValidity.Problem(partnerCert, DateTimeOffset.UtcNow, "The partner's MDN signing certificate") is null
&& engine.Verify(signed, partnerCert);
entity = signed[0]; // the multipart/report inside
}
string? originalMessageId = null;
string? disposition = null;
As2Mic? mic = null;
if (entity is Multipart report)
{
foreach (var part in report)
{
if (part is not MessageDispositionNotification notification)
continue;
originalMessageId = notification.Fields["Original-Message-ID"];
disposition = notification.Fields["Disposition"];
var micField = notification.Fields["Received-Content-MIC"];
if (!string.IsNullOrEmpty(micField))
{
try { mic = As2Mic.Parse(micField); }
catch (FormatException) { /* leave null on a malformed MIC */ }
}
}
}
return new MdnResult(originalMessageId, disposition, mic, signatureValid, IsPositiveDisposition(disposition));
}
///
/// Whether reports the message as processed, read by its fields (RFC 3798 §3.2.6,
/// RFC 4130 §7.4.3): action-mode/sending-mode; disposition-type[/modifier: text]. Positive is the type
/// processed with no modifier or a warning one; an error or failure modifier, any other
/// type, or a value that is not in that form is not. The free text after the modifier is never read.
///
public static bool IsPositiveDisposition(string? disposition)
{
if (string.IsNullOrWhiteSpace(disposition)) return false;
var semicolon = disposition.IndexOf(';');
if (semicolon < 0 || !disposition[..semicolon].Contains('/')) return false;
var rest = disposition[(semicolon + 1)..].Trim();
var slash = rest.IndexOf('/');
var type = (slash < 0 ? rest : rest[..slash]).Trim();
if (!type.Equals("processed", StringComparison.OrdinalIgnoreCase)) return false;
if (slash < 0) return true;
var modifier = rest[(slash + 1)..];
var colon = modifier.IndexOf(':');
return (colon < 0 ? modifier : modifier[..colon]).Trim().Equals("warning", StringComparison.OrdinalIgnoreCase);
}
private static MimeEntity LoadEntity(string? contentType, string? transferEncoding, byte[] body)
{
var sb = new StringBuilder();
sb.Append("Content-Type: ").Append(contentType ?? "multipart/report").Append("\r\n");
if (!string.IsNullOrEmpty(transferEncoding))
sb.Append("Content-Transfer-Encoding: ").Append(transferEncoding).Append("\r\n");
sb.Append("\r\n");
using var stream = new MemoryStream();
stream.Write(Encoding.ASCII.GetBytes(sb.ToString()));
stream.Write(body);
stream.Position = 0;
return MimeEntity.Load(stream);
}
}
Path: redb-route/redb.Route.As2/Mdn/MdnVerdict.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/Mdn/MdnVerdict.cs
----
using redb.Route.As2.Crypto;
namespace redb.Route.As2.Mdn;
///
/// What a parsed MDN proves about one message, the same way on the synchronous and the asynchronous path. Only a
/// comparison that took place counts: a missing Received-Content-MIC, or a MIC nobody can compare because the message
/// is not known, is not a match (RFC 4130 §7.4.3 requires the field in every MDN).
///
internal sealed record MdnVerdict(string MicStatus, bool SignatureAccepted, bool Confirmed)
{
public const string Matched = "matched";
public const string Mismatch = "mismatch";
public const string Absent = "absent";
public const string Unknown = "unknown";
/// True when the MIC was compared and is the one we sent.
public bool MicMatch => MicStatus == Matched;
/// The parsed MDN.
/// The MIC of the message the MDN reports on; null when that message is not known.
/// The agreement asks for a signed MDN.
public static MdnVerdict Of(MdnParser.MdnResult result, As2Mic? sent, bool signedMdn)
{
var status = sent is null ? Unknown
: result.ReceivedMic is not { } received ? Absent
: received.Matches(sent.Value) ? Matched
: Mismatch;
var signatureAccepted = !signedMdn || result.SignatureValid;
return new MdnVerdict(status, signatureAccepted, result.IsPositive && status == Matched && signatureAccepted);
}
/// Why the MDN does not confirm the transfer, for logs and exceptions; null when it does.
public string? Problem(MdnParser.MdnResult result) => Confirmed ? null : string.Join("; ", new[]
{
result.IsPositive ? null : $"disposition '{result.Disposition ?? "(none)"}'",
MicMatch ? null : $"MIC {MicStatus}",
SignatureAccepted ? null : "a signed MDN is agreed and its signature is missing or invalid",
}.Where(p => p is not null));
}
Path: redb-route/redb.Route.As2/Mdn/ReceiptRequest.cs
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/Mdn/ReceiptRequest.cs
----
using Microsoft.AspNetCore.Http;
using redb.Route.As2.Crypto;
namespace redb.Route.As2.Mdn;
///
/// The receipt a received message asks for (RFC 4130 §7.3): whether any (Disposition-Notification-To), whether
/// signed and with which MIC algorithm (Disposition-Notification-Options:
/// signed-receipt-protocol=importance, pkcs7-signature; signed-receipt-micalg=importance, alg[, alg...]).
///
/// The sender asked for an MDN.
/// The sender asked for a signed MDN (pkcs7-signature).
/// The algorithm of the MIC and of the MDN signature: the first requested one usable here, else the agreement's.
/// The algorithms the sender listed, in its order; empty when it listed none.
///
/// A required option this receiver cannot honour, as the failure of the MDN (RFC 4130 §7.5.3):
/// or ; null when
/// every required option is met. An optional one is never a failure.
///
internal sealed record ReceiptRequest(bool Requested, bool Signed, string MicAlg, IReadOnlyList RequestedMicAlgs, string? Failure = null)
{
public static ReceiptRequest Of(HttpRequest request, As2Profile profile)
{
var requested = !string.IsNullOrWhiteSpace(request.Headers[As2Headers.DispositionNotificationTo].ToString());
var options = request.Headers[As2Headers.DispositionNotificationOptions].ToString();
var signed = false;
var protocolRequired = false;
var protocolListed = false;
var micAlgRequired = false;
IReadOnlyList algs = [];
foreach (var parameter in options.Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
var eq = parameter.IndexOf('=');
if (eq < 0) continue;
var name = parameter[..eq].Trim();
// The first value is the importance (required | optional); the rest are the values.
var all = parameter[(eq + 1)..].Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
var required = all.Length > 0 && all[0].Equals("required", StringComparison.OrdinalIgnoreCase);
var values = all.Skip(1).ToList();
if (name.Equals("signed-receipt-protocol", StringComparison.OrdinalIgnoreCase))
{
protocolListed = true;
protocolRequired = required;
signed = values.Any(v => v.Equals("pkcs7-signature", StringComparison.OrdinalIgnoreCase));
}
else if (name.Equals("signed-receipt-micalg", StringComparison.OrdinalIgnoreCase))
{
micAlgRequired = required;
algs = values;
}
}
var usable = algs.FirstOrDefault(a => As2CryptoEngine.IsSupportedDigest(a) && (!As2Profile.IsLegacy(a) || profile.AllowLegacyAlgorithms));
string? failure = null;
// Required and not producible here: a protocol other than pkcs7-signature, or pkcs7-signature while the agreement
// has no certificate of ours to sign with.
if (protocolListed && protocolRequired && (!signed || profile.OurCertificate is null))
failure = As2Disposition.UnsupportedFormat;
else if (micAlgRequired && usable is null)
failure = As2Disposition.UnsupportedMicAlgorithms;
return new ReceiptRequest(requested, signed, usable ?? profile.SignAlg, algs, failure);
}
}
Path: redb-route/redb.Route.As2/README.md
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/README.md
----
# redb.Route.As2
> Documentation and articles:
**AS2 (RFC 4130) B2B/EDI transport for the [redb.Route](../redb.Route) integration framework.** Exchange business
documents with trading partners over HTTP(S) as signed and encrypted S/MIME messages, confirmed by MDN receipts:
the protocol retail, logistics and EDI networks run on.
Schemes: `as2` (HTTP), `as2s` (HTTPS).
- **Send** (`.To(...)`): compress, sign and encrypt a payload, POST it to the partner, verify the MDN.
- **Receive** (`.From(...)`): host an AS2 server that checks who sent the message, decrypts and verifies it, hands the
document to your route and answers with the MDN the sender asked for.
- **Asynchronous MDN** in both roles, **signed MDN**, **duplicate detection**, bounded request and response sizes.
Crypto is **MimeKit** (Bouncy Castle underneath), the foundation Apache camel-as2, OpenAS2 and Mendelson interoperate
on. Interop is tested in both directions against a live **OpenAS2 4.9.0** (see [TESTING.md](TESTING.md)).
---
## Install and register
```csharp
services.AddRedbRoute(route =>
{
route.Services.AddRedbRouteAs2();
route.AddRouteBuilder();
});
```
`AddRedbRouteAs2()` registers the `as2` and `as2s` schemes and shares one Kestrel receive server with every other
HTTP-based connector in the process (`redb.Route.Http.Hosting`): an HTTP route and an AS2 route on one port do not
fight over it.
---
## The agreement: `As2ConnectionFactory`
A trading partnership is certificates, AS2 identifiers and an agreed profile. Register it once by name; endpoints
name it with `.ConnectionFactory("name")`, so no certificate or password lives in a URI.
```csharp
context.AddToRegistry("walmart", new As2ConnectionFactory
{
OurCertificate = ourPfx, // our certificate WITH its private key: signs what we send, decrypts what we receive
PartnerCertificate = theirCer, // the partner's public certificate: encrypts for it, verifies its signatures
As2From = "OUR-AS2-ID", // us: AS2-From on send, the AS2-To we accept on receive
As2To = "WALMART-AS2-ID", // them: AS2-To on send, the AS2-From we accept on receive
PartnerUrl = "https://partner.example.com/as2",
Sign = true, Encrypt = true, Compress = false,
SignAlg = "sha-256", EncryptAlg = "aes-128-cbc",
MdnMode = As2MdnMode.Sync, SignedMdn = true, RequireValidMdn = true,
});
```
| Property | Default | Meaning |
|---|---|---|
| `OurCertificate` | none | Our S/MIME certificate with its private key. Required when anything is signed or encrypted, or a signed MDN is agreed. |
| `PartnerCertificate` | none | The partner's certificate. Required in the same cases. It is **pinned**: a signature is accepted only when made by this certificate, not merely by a valid one. |
| `As2From` / `As2To` | required | Our and the partner's AS2 identifiers (RFC 4130 §6.2): 1 to 128 printable ASCII characters, checked when the endpoint starts. Written as they are, or in double quotes when one is not an atom (a space, `"` or `\`). |
| `PartnerUrl` | from the send URI | Where the producer POSTs. If both the factory and the send URI name one, they must be the same. |
| `Sign` / `Encrypt` / `Compress` | `true` / `true` / `false` | What we do on send, and what we require on receive (an unsigned or unencrypted message where the agreement requires it is refused). |
| `SignAlg` | `sha-256` | Signature digest, and the MIC algorithm. |
| `EncryptAlg` | `aes-128-cbc` | Content encryption. |
| `AllowLegacyAlgorithms` | `false` | Permits `sha-1` and `3des`. Without it they are refused when the endpoint starts. |
| `MdnMode` | `Sync` | Send: which MDN we ask for. Receive: `Async` permits posting receipts to the address the sender names, `None` never sends an MDN. |
| `SignedMdn` | `true` | Send: ask for a signed MDN (as `required`), and do not count an unsigned one as a confirmation. |
| `RequireValidMdn` | `false` | Send: a transfer the MDN does not confirm fails the exchange (sync) or the receipt is refused (async, see below). |
| `AsyncMdnUrl` | none | Send, async: the URL the partner posts our receipt to (your `As2.ReceiveMdn` endpoint). |
| `AsyncMdnAllowedHosts` | empty | Receive, async: the hosts a receipt may be posted to. Required when a receive endpoint's `MdnMode` is `Async`. |
| `SslCertPath` / `SslCertPassword` | none | The TLS certificate of the receive server (not the S/MIME key). The password is `[Sensitive]`. |
**Checked at start.** Every endpoint that names a factory checks it when it starts (`As2ConnectionFactory.Validate`):
identifiers present, algorithms supported and not legacy unless allowed, our certificate present with its private key
and the partner's certificate present wherever something is signed or encrypted, URLs absolute `http(s)`. A send
endpoint also needs a partner URL, and `AsyncMdnUrl` for async; an async receive endpoint needs `AsyncMdnAllowedHosts`.
A broken agreement stops the route from starting; it never answers a partner's first message with an error.
**One source.** When an endpoint names a factory, the factory is the whole agreement: agreement options on the URI
(`sign`, `signAlg`, `mdnMode`, `as2From`, `asyncMdnAllowedHosts`, ...) are refused, naming the parameters. Without a
factory the inline URI options are the agreement; they carry no certificates, so that is only for an agreement that
neither signs nor encrypts.
---
## Sending (producer)
```csharp
From("direct://outbound")
.To(As2.Send("https://partner.example.com/as2").ConnectionFactory("walmart"));
```
The producer compresses (if agreed), signs, encrypts and POSTs the document, with `AS2-From`, `AS2-To`, a fresh
`Message-ID` and, unless `MdnMode` is `None`, `Disposition-Notification-To`. With `SignedMdn` it asks for
`signed-receipt-protocol=required, pkcs7-signature; signed-receipt-micalg=required, `. Our and the partner's
certificates must be within their validity period, or the send fails before anything is posted.
The sent `Message-ID` and MIC are on `exchange.In` (`Message-ID`, `redbAs2.mic`, `redbAs2.micalg`). A synchronous MDN
is read (at most `maxResponseBodySize` bytes), its signature verified against the pinned partner certificate, and its
`Received-Content-MIC` compared with ours. The verdict lands on `exchange.Out`:
| Header on `exchange.Out` | Meaning |
|---|---|
| `redbAs2.mdnConfirmed` | `true` only when the disposition is positive, the MIC matched, and the signature is valid where `SignedMdn` is agreed. **The one to branch on.** |
| `redbAs2.mdnMicStatus` | `matched`, `mismatch`, `absent` (the MDN carries no MIC) or `unknown` (nothing to compare with) |
| `redbAs2.mdnMicMatch` | `true` only for `matched` |
| `redbAs2.signatureValid` | the MDN was signed and the signature verified |
| `redbAs2.mdnDisposition` | the raw `Disposition`, e.g. `automatic-action/MDN-sent-automatically; processed` |
```csharp
From("direct://outbound")
.To(As2.Send("https://partner/as2").ConnectionFactory("walmart"))
.Choice()
.When(e => e.Out!.GetHeader(As2Headers.MdnConfirmed))
.Log("delivered and verified")
.Otherwise()
.To("direct://delivery-alert");
```
Without `RequireValidMdn` an unconfirmed MDN is logged and left to the route; with it, the exchange fails and the
route's error handling takes over. A missing MIC is never a match (RFC 4130 requires one in every MDN).
What the MIC is computed over, on send and on receive (RFC 4130 §7.3.1, RFC 5402 §4):
| Message | MIC over |
|---|---|
| signed (compressed before or after signing, encrypted or not) | the part that was signed, with its MIME headers |
| unsigned, encrypted (compressed or not) | the uncompressed part with its MIME headers |
| unsigned, not encrypted (compressed or plain) | the content alone |
OpenAS2 4.9.0 computes the same, measured on the interop stand: encrypted only, over the decrypted part with its
headers; compressed and encrypted, over the uncompressed part with its headers; compressed only, over the content
alone. RFC 5402 §4.3 would hash a compressed unencrypted message with its headers; neither side does, as RFC 4130
§7.3.1 has it for a message that is neither signed nor encrypted.
Exchange headers are bridged onto the request, except redb metadata (`redbAs2.*`), the AS2 and MIME headers the
connector sets itself, hop-by-hop headers, `Host`, and credentials (`Authorization`, `Proxy-Authorization`,
`Cookie`, `Set-Cookie`): a token from an inbound caller or an internal service never reaches the partner.
---
## Receiving (consumer / AS2 server)
```csharp
From(As2.Receive("/inbound/orders").Host("0.0.0.0").Port(4080).ConnectionFactory("walmart"))
.Unmarshal(...) // your EDI parsing
.To("direct://process-order");
```
What happens to a request, in order:
1. **Size.** A body over `maxRequestBodySize` (100 MB by default) is answered `413` before it is read.
2. **Who.** `AS2-From` must be the partner's identifier and `AS2-To` ours (case-sensitive, a quoted-string is
unquoted, RFC 4130 §6.2). Then **the receipt**: a `Disposition-Notification-Options` parameter marked `required`
that this receiver cannot honour (a protocol other than `pkcs7-signature`, `pkcs7-signature` while the agreement
has no `OurCertificate`, or no MIC algorithm usable here) is
answered with an unsigned `failed/Failure: unsupported format` or `failed/Failure: unsupported MIC-algorithms` MDN,
and the message is not processed (RFC 4130 §7.5.3).
3. **Decrypt** with `OurCertificate`, **verify** the signature against the pinned `PartnerCertificate` (which must be
within its validity period), **decompress** (up to `maxDecompressedSize`, the body limit by default; past it the
message is refused with `decompression-failed`).
4. **Policy.** A message not signed or not encrypted where the agreement requires it is refused.
5. **Duplicates** (with `idempotentRepository`): a `Message-ID` processed before is answered and not delivered.
6. **Route.** The decrypted document is the body; its content type is `Message.ContentType` (e.g. `application/edi-x12`).
7. **MDN**, as the request asked (below).
A refused message never reaches the route. Its MDN carries the RFC 4130 §7.4.3 code (`authentication-failed`,
`decryption-failed`, `decompression-failed`, `insufficient-message-security`, `unexpected-processing-error`) and a
fixed text with a reference (the request's trace identifier); the detail is in our log under that reference, never in
the MDN.
| Header on the received exchange | Meaning |
|---|---|
| `redbAs2.signatureValid` | `true` only when the message was signed and the signature verified; `false` for an unsigned one |
| `redbAs2.mic` / `redbAs2.micalg` | the MIC returned in the MDN, and its algorithm |
| `redbAs2.remoteAddress` | the sender's IP |
| `redbAs2.partner` | the connection-factory name |
The request's own headers (`AS2-From`, `AS2-To`, `Message-ID`, `Subject`, `Disposition-Notification-*`, your partner's
business headers) are copied verbatim, except the S/MIME wrapper's MIME headers, hop-by-hop headers and the hop's
credentials (`Authorization`, `Proxy-Authorization`, `Cookie`). A principal the host resolved is on the exchange
(`ExchangePrincipal`).
### The MDN the receiver returns
- **Only when asked**: no `Disposition-Notification-To`, no MDN (the answer is an empty `200`). `MdnMode = None` never
sends one.
- **Signed when asked**: when `Disposition-Notification-Options` asks for `pkcs7-signature`, signed with
`OurCertificate`.
- **With the requested MIC algorithm**: the first `signed-receipt-micalg` usable here (legacy only when allowed) is the
algorithm of the MIC and of the MDN signature; if none is and the parameter is `optional`, the agreement's
`SignAlg`, with a warning in the log (`required`: see step 2 above).
- **Synchronous** in the response, unless the request names a `Receipt-Delivery-Option` and all of these hold, in
which case it is posted there: the message **authenticated** (identifiers matched and, where signing is agreed, the
signature verified), the agreement's `MdnMode` is `Async`, and the URL is absolute `http(s)`, without user
information, to a host in `AsyncMdnAllowedHosts`. Anything else is logged and the MDN goes in the response: an
unauthenticated caller cannot make us POST, least of all a receipt signed by our key, to an address of its choosing.
The asynchronous MDN is posted after the `200`, outside the request, bounded by `timeout`, counted by the stop drain.
- **Bounded.** A message that asks for an asynchronous MDN takes a slot of the receiver's pool (`asyncMdnPoolSize`, 20)
when it is admitted, before any work, and keeps it until its receipt is posted. With every slot taken it is refused
with `rejectStatusCode` (503) and `Retry-After` (`retryAfterSeconds`, 30), and the partner resends it later: RFC 4130
§7 puts the response before the MDN, so the receiver cannot post the receipt in the caller's place. A post is tried
`asyncMdnAttempts` times (3), again after a connection failure, a timeout, 408, 429 or a 5xx answer, waiting
`asyncMdnRetryDelay` (5000 ms) doubled for each retry, with the same `Message-ID`; another 4xx is not tried again. A
receipt given up is logged as an error and counted in `redb.route.as2.mdn.async_failed`; a refusal in
`redb.route.as2.mdn.async_rejected`.
### Duplicates
A partner that did not see our answer sends the document again with the same `Message-ID`. Name an
`IIdempotentRepository` and the resend is answered with a positive MDN,
`processed/warning: duplicate-document`, and the same MIC, and is not delivered again:
```csharp
context.AddIdempotentRepository("as2-walmart", new InMemoryIdempotentRepository()); // or a durable one
From(As2.Receive("/inbound/orders").Port(4080).ConnectionFactory("walmart").IdempotentRepository("as2-walmart"))
```
The id is claimed only after the message authenticated (a forged copy cannot burn the id of the real one) and released
when the route fails, so the partner's resend is then delivered. A copy that arrives while the first one is still in the
route is not a duplicate yet: it is answered `rejectStatusCode` (503) with `Retry-After`, without an MDN, and the partner
resends it. A claim never confirmed and older than `inFlightClaimTimeout` (10 minutes) was left by a stopped node; it is
taken over and the message processed. A takeover is at-least-once: a holder still working past the timeout may see
the document delivered once more, so set `inFlightClaimTimeout` above the longest time the route takes. That holder
then confirms or releases only its own claim, by the claim id `IIdempotentRepository.Lease` handed it, and logs a
warning; the new holder's claim stays. Telling the two apart needs a repository that keeps the confirmed state and
overrides `IIdempotentRepository.Lease`: the redb, SQL and in-memory ones do; with any other every held id is a
duplicate, as before. The repository decides whether ids survive a restart and are shared across nodes; give the
endpoint one of its own. Without a repository every copy is delivered: the route
can still use `.IdempotentConsumer(e => e.In.GetHeader(As2Headers.MessageId))`.
### Receiving over TLS
Two certificates, not interchangeable: `OurCertificate` is the S/MIME key of the **message**; this one secures the
**connection**.
```csharp
From(As2.Receive("/inbound/orders").Host("0.0.0.0").Port(4443)
.Tls("/certs/as2-server.pfx", "password")
.ConnectionFactory("walmart"))
// or keep the password in the registry
context.AddToRegistry("walmart", new As2ConnectionFactory { /* ... */ SslCertPath = "/certs/as2-server.pfx", SslCertPassword = secret });
From(As2.Receive("/inbound/orders").Port(4443).Tls().ConnectionFactory("walmart"))
```
The certificate may also come from the host (`AddRedbRouteHttpHosting(o => o.Tls.DefaultCertificatePath = ...)`). A
TLS receiver that finds none **refuses to bind**; it never opens a plaintext port behind an `https://` URL.
---
## Asynchronous MDN
```csharp
// Send side of the agreement
MdnMode = As2MdnMode.Async,
AsyncMdnUrl = "https://our-host:4081/as2/mdn",
// Routes
From("direct://outbound")
.To(As2.Send("https://partner/as2").ConnectionFactory("walmart"));
From(As2.ReceiveMdn("/as2/mdn").Host("0.0.0.0").Port(4081).ConnectionFactory("walmart"))
.Process(e =>
{
var original = e.In.GetHeader(As2Headers.MessageId); // Original-Message-ID
var confirmed = e.In.GetHeader(As2Headers.MdnConfirmed);
});
```
The producer records the sent `Message-ID` and MIC and returns; the verdict arrives later as its own exchange on the
`ReceiveMdn` route, with the same headers as a synchronous MDN (`mdnConfirmed`, `mdnMicStatus`, `mdnMicMatch`,
`signatureValid`, `mdnDisposition`) plus `remoteAddress` and `partner`.
- An MDN for a message nobody waits for (no `Original-Message-ID`, sent before a restart, older than the 30-minute
correlation window, or sent from another node: the record is in memory) has `mdnMicStatus = unknown` and is not a
confirmation.
- Where `SignedMdn` is agreed, an unsigned or foreign-signed MDN is not a confirmation and does not end the wait, so
the partner's genuine receipt still finds the message. With `RequireValidMdn` as well, it is refused (`400`) and not
delivered.
- A negative MDN from the partner is delivered, unconfirmed: the route must learn that the transfer failed.
- The receiver has the message receiver's lifecycle: stop drain, `maxConcurrentRequests`, `maxRequestBodySize`, a
`Consumer` span.
---
## Algorithms
| Knob | Values |
|---|---|
| `SignAlg` | `sha-256` (default), `sha-384`, `sha-512`; `sha-1` **legacy**, only with `AllowLegacyAlgorithms` |
| `EncryptAlg` | `aes-128-cbc` (default), `aes-192-cbc`, `aes-256-cbc`; `3des` **legacy** (SWEET32), only with `AllowLegacyAlgorithms` |
| `Compress` | `true` / `false` (RFC 3274) |
AES-GCM is not supported. An unsupported or unallowed algorithm stops the endpoint from starting.
---
## Endpoint options
| Option | Side | Default | Meaning |
|---|---|---|---|
| `connectionFactory` | both | none | The agreement (above). |
| `host` / `port` | receive | `0.0.0.0` / `4080` | Where the receive server listens. |
| `mode` | receive | `message` | `mdn` for an asynchronous-MDN receiver (`As2.ReceiveMdn`). |
| `useTls`, `sslCertPath`, `sslCertPassword` | receive | off | TLS of the receive server; the `as2s` scheme sets `useTls`. |
| `maxRequestBodySize` | receive | 100 MB | Larger requests are answered 413 before they are read. |
| `maxDecompressedSize` | receive | `maxRequestBodySize` | A compressed message inflating past this is refused with `decompression-failed`. |
| `maxConcurrentRequests`, `requestQueueLimit`, `rejectStatusCode`, `retryAfterSeconds` | receive | `32`, `32`, `503`, `30` | Admission limit, below; the status and `Retry-After` also answer a message refused for want of an asynchronous MDN slot. |
| `asyncMdnPoolSize`, `asyncMdnAttempts`, `asyncMdnRetryDelay` | receive | `20`, `3`, `5000` ms | Asynchronous MDNs handled at once, posts per receipt, first retry delay (doubled each time). |
| `idempotentRepository`, `inFlightClaimTimeout` | receive | none, 600000 ms | Duplicate detection and the age of an abandoned claim, above. |
| `streamBody` | receive | `false` | The body is the spooled payload as a `Stream` (closed with the exchange) instead of `byte[]`. |
| `timeout` | both | 30000 ms | The outgoing POST: the message on send, the asynchronous MDN on receive. |
| `maxResponseBodySize` | send | 4 MB | The synchronous MDN is read up to this; larger fails the send without reading it. |
The fluent builder has the same knobs: `.Host()`, `.Port()`, `.Tls()`, `.ConnectionFactory()`,
`.MaxRequestBodySize()`, `.MaxDecompressedSize()`, `.MaxResponseBodySize()`, `.IdempotentRepository()`, `.InFlightClaimTimeout()`, `.StreamBody()`, `.MaxConcurrentRequests()`,
`.RejectStatusCode()`, `.RetryAfterSeconds()`, `.AsyncMdnPoolSize()`, `.AsyncMdnRetry()`. The URI form:
```
as2:/inbound/orders?host=0.0.0.0&port=4080&connectionFactory=walmart # receive server
as2:/as2/mdn?host=0.0.0.0&port=4081&mode=mdn&connectionFactory=walmart # async-MDN receiver
as2s://partner.example.com/as2?connectionFactory=walmart # producer (https => as2s)
```
The receive path is kept whole (its first segment is not taken for a host). Passwords are `[Sensitive]` and redacted
from logs; an unknown parameter is refused with the nearest option name.
### Admission limit
Kestrel runs as many handlers as requests arrive. `maxConcurrentRequests` caps the concurrent pipeline executions of an
endpoint; the overflow beyond `requestQueueLimit` waiting requests is shed with `rejectStatusCode` and `Retry-After`
before any MIME or crypto work (AS2 partners retry on their own). A shed request is counted in `Rejected`, not in
`MessagesIn` or `Errors`. The limit is per endpoint; for "slow down, do not drop" use `.Threads(n)` in the route.
By default the receiver runs 32 requests at once and lets 32 more wait (`maxConcurrentRequests=32`,
`requestQueueLimit=32`); the 65th request of a burst is refused and resent by the partner. Each admitted request may
hold its payload in memory (a `byte[]` up to `maxRequestBodySize` without `streamBody`) besides the S/MIME work, so
the default bounds the payloads held at 32 x `maxRequestBodySize` (3.2 GB at the 100 MB default; lower
`maxRequestBodySize` or use `streamBody` to bring it down). `maxConcurrentRequests=0` admits every request at once,
without limit, as the HTTP consumer does. A `maxConcurrentRequests` without `requestQueueLimit` keeps the queue of 32;
`requestQueueLimit=0` refuses at once instead of waiting.
---
## Cross-cutting
Statistics and health (`IEndpointStatistics`, visible in the Tsak dashboard), and distributed tracing on the core's
transport contract: the producer opens a `"{partner AS2 id} send"` Client span and writes its context to the request
(replacing a `traceparent` bridged from the exchange); the message and MDN receivers open `"{path} receive"` Consumer
spans whose parent is the host's request span when the application traces ASP.NET Core, else the sender's
`traceparent`, else a root, with the sender's baggage put back. A refused message, a failed route or a failed send
marks the span an error; `EnableTelemetry=false` opens none. Stopping a receive route waits for the messages
and asynchronous MDNs already in flight, and cancels them when the drain times out.
---
## Headers
The producer sends the exchange's own headers as HTTP headers of the message, except the MIME, AS2 and hop-by-hop
fields it sets itself, `Host`, and the credentials of another hop (`Authorization`, `Cookie`, `Set-Cookie`). The
receiver takes the request headers, except the pseudo-headers, the S/MIME wrapper and hop-by-hop fields and the
credentials that authenticated the hop.
`headerFilterStrategy=#name` names an `IHeaderFilterStrategy` in the registry that decides, within those limits,
which headers cross, as in Apache Camel. It replaces the default, `As2HeaderFilterStrategy` (keeps `redbAs2.*` back),
entirely; derive from that class to add to it. The excluded fields above stay excluded whatever the strategy says.
```csharp
ctx.AddToRegistry("correlationOnly", new DefaultHeaderFilterStrategy
{
OutFilter = ["Correlation-ID"],
FilterOnMatch = false, // a whitelist: only the listed headers go out
});
// as2://partner.example/as2?connectionFactory=acme&headerFilterStrategy=#correlationOnly
```
---
## Limits and known gaps
- **Revocation** of certificates (CRL/OCSP) is not checked, nor is the chain: the pin is the trust. Validity periods
are checked.
- **Correlation** of asynchronous MDNs is in memory, per process, for 30 minutes.
- **Spooling.** The request, each decrypted and decompressed stage and the payload go through the core stream cache
(`StreamCaching` options: memory up to the threshold, 128 KB by default, then a temporary file), as in the AS4
receiver. What MimeKit and Bouncy Castle buffer inside one decryption step is theirs; `byte[]` bodies (without
`streamBody`) are the payload in memory by definition.
- `AS2-Version` is not negotiated (we speak 1.2). AS2 Restart (resuming a partial transfer) and multiple attachments
(RFC 6362) are not supported.
---
## Tested on
- **141 tests** per target framework: crypto round-trips over the algorithm matrix, loopback over a live
Kestrel (sync, async and signed MDN, spans, statistics, principal), the security checks above (forged signatures,
foreign identifiers, receipt-URL traps, unsigned receipts, expired certificates), limits and drain, duplicates.
- **Interop against OpenAS2 4.9.0** (Docker), both directions, synchronous and asynchronous MDN: our signed and encrypted message accepted by OpenAS2
with a positive signed MDN whose MIC we verify; OpenAS2's message received, decrypted, verified and routed, and our
MDN accepted by OpenAS2, which checks our MIC on the asynchronous path. See [TESTING.md](TESTING.md).
Design notes and the review this version answers are in `../../docs/as2`.
Path: redb-route/redb.Route.As2/TESTING.md
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/TESTING.md
----
# redb.Route.As2 — Testing & Interop Validation
How the AS2 connector is tested, and the proof it interoperates with a real, independent AS2 implementation.
Test project: `redb.Route/tests/redb.Route.Tests.As2`: **141 test cases per target framework, green on net8.0 / net9.0 / net10.0** (2026-09-28, OpenAS2 stand up; without it the four interop cases are reported skipped).
---
## 1. Test layers
The connector is validated at three levels, each catching a different class of bug.
### Unit — crypto, MIC, options, DSL
Pure, fast, no network. Self-signed certificates are generated in-process (no PFX files in the repo).
- **S/MIME round-trips** for every profile — plain, signed, encrypted, signed+encrypted,
compressed+signed+encrypted — asserting the decrypted payload is byte-identical.
- **MIC** (RFC 4130 §7.3.1) — deterministic; the MIC computed before signing equals the MIC recomputed on
the received signed part; headers-included vs content-only differ; `Received-Content-MIC` wire format parses.
- **Negative** — a signature from the wrong certificate fails verification (not throws).
- **Algorithm matrix** — a `[Theory]` over `{sha-1, sha-256, sha-384, sha-512}` × `{aes-128/192/256-cbc, 3des}`
× `{compress on/off}`, each a full round-trip with MIC verification.
- **Options / DSL** — URI binding, fail-fast validation (bad port, async without a target, unsupported
algorithm), `[Sensitive]` redaction, and DSL URI building (the receive path is never truncated).
### Security and protocol (REVIEW-2026-09-28)
Each finding of the review has a test written to fail first: a receipt-URL **trap** (a local listener that must
receive nothing) for a stranger's signature, a sync agreement, and a host not allowed; foreign `AS2-From`/`AS2-To`;
MDNs without MIC, without `Original-Message-ID`, for unknown messages, unsigned where signed is agreed; the MDN only
when asked, signed only when asked, with the requested micalg; credentials not handed on; 413 over the size limits;
the stop drain and span of the MDN receiver; the agreement checked at start; legacy algorithms; expired and
not-yet-valid certificates; duplicates. Files: `As2ReceiveSecurityTests`, `As2MdnVerdictTests`, `As2LimitsTests`,
`As2AgreementTests`, `As2ProtocolTests`, `As2DuplicateTests`.
### End-to-end — loopback over a live Kestrel
The connector's **own producer sends a real signed+encrypted AS2 message over real HTTP** to the connector's
**own consumer** (hosted on the shared Kestrel server on a free localhost port), which decrypts, verifies,
delivers the payload to a route, and returns an MDN. These exercise both sides together:
- **Delivery** — the business payload arrives at the receiving route intact.
- **Synchronous MDN** — the response is a `multipart/report` with `Disposition: processed`,
`Received-Content-MIC` and the echoed `Original-Message-ID`.
- **Signed MDN** — the producer parses the signed MDN, verifies its signature and confirms `mdnMicMatch`.
- **Asynchronous MDN** — producer (async) → consumer acks 200 and POSTs the MDN to a second endpoint
(`As2.ReceiveMdn`), which correlates it by `Original-Message-ID` and delivers the outcome to a route.
- **Cross-cutting** — `IEndpointStatistics.MessagesIn` increments; an `ActivityListener` sees the producer
`Client` span and the consumer `Consumer` span sharing one `TraceId` (distributed trace linked).
These loopback tests have already earned their keep — they caught a real `Content-Type` double-prefix bug
(MimeKit's `ContentType.ToString()` renders the whole header line) that unit tests would not have.
### Interop — against a real external AS2 server
Loopback proves *self-consistency*. Only exchanging with an **independent** implementation proves *interop
correctness* — that our wire format and MIC are accepted by software we didn't write. See §2.
---
## 2. Interop result — validated against OpenAS2 v4.9.0 ✅ (both directions)
Partner: `greicodex/openas2:latest` = OpenAS2 **v4.9.0** (a mature, Bouncy-Castle-based AS2 server) in Docker.
Both messages are **signed (SHA-256) + encrypted (AES-128-CBC)** with a **signed MDN**.
### redb → OpenAS2
Our producer POSTs to OpenAS2. Confirmed from OpenAS2's own logs:
```
AS2ReceiverHandler - received 4344 bytes ... [<...@redb.route>]
MessageFileModule - stored message to .../redb-openas2/inbox/...@redb.route
MDNSenderModule - sent MDN [automatic-action/mdn-sent-automatically; processed] [<...@redb.route>]
```
OpenAS2 **decrypted** our message, **verified our signature**, **stored** the business document, and returned
a **positive signed MDN**. Our `MdnParser` verified that MDN's signature and confirmed the
`Received-Content-MIC` **matched** what we sent.
### OpenAS2 → redb
OpenAS2's directory poller builds a signed+encrypted message and POSTs it to our consumer. Confirmed:
```
AS2SenderModule - Connecting to: http://host.docker.internal:15081/inbound [<...openas2_redb...>]
AS2MDNReceiverHandler - DISPOSITION MIC ALG: sha-256 IMPORTANCE: optional
AS2Util - Pending MDN MSG FILE deleted ... (our MDN correlated OpenAS2's pending message)
```
Our consumer **decrypted** OpenAS2's message with our private key, **verified OpenAS2's signature**, delivered
the EDI payload to the route, and returned a **signed MDN that OpenAS2 accepted** (pending MDN cleared).
**Correction (2026-09-28).** OpenAS2 4.9.0 does **not** compare the MIC of a synchronous MDN (no `MIC check` in its
trace log), so the paragraph above never proved our received-side MIC. The asynchronous path does compare it, and the
first asynchronous run failed with `MIC not matched`: the receiver prepared the received signed part for 7bit before
hashing it, turning OpenAS2's `binary` part into base64. Fixed (`ComputeReceivedMic` hashes the part as received);
the asynchronous interop below is the proof of the MIC in this direction.
### Asynchronous MDN, both directions
- **redb → OpenAS2** (`Redb_To_OpenAs2_AsyncMdn_IsPostedBack_Signed_AndConfirms`): we send with
`Receipt-Delivery-Option` pointing at our `As2.ReceiveMdn` endpoint (`host.docker.internal:`); OpenAS2 answers
200 and logs `sent AsyncMDN ... OK`; our receiver verifies its signature and MIC: `mdnConfirmed = true`.
- **OpenAS2 → redb** (`OpenAs2_To_Redb_AsyncMdn_IsPostedToOpenAs2_AndItClosesThePendingMessage`): partnership
`openas2-to-redb-async` (partner `redb-async`, `as2_receipt_option = http://127.0.0.1:14081`); our receiver answers
200 and posts the signed MDN to OpenAS2's MDN receiver, which logs `MIC check` and deletes its pending message.
The asynchronous runs found three defects, each fixed with a test that failed first:
1. The machine-readable MDN part went out quoted-printable when a field line was long (OpenAS2 Message-IDs are about
90 characters); RFC 3798 §3.1 requires 7bit, and OpenAS2 read the Original-Message-ID undecoded, cut at the soft
line break (`As2MdnEncodingTests`).
2. The received MIC above (`As2ReceivedMicTests` and the interop).
3. The producer registered the wait for an asynchronous MDN after the partner's 200; OpenAS2 often posts the MDN
first, which then read as `unknown` (`As2AsyncMdnOrderTests`).
This closes the "hard part" of AS2 in **both directions and both MDN modes**: MIC, S/MIME structure and MDN
handling are correct against a real, independent partner, not merely self-consistent.
### Running the interop test
The harness is profile `as2` of the test stand `docker-compose.tests.yml` (OpenAS2 with its configuration under
`tests/docker/as2`, certificates from `tests/docker/gen-certs.sh`; see `tests/docker/README.md`). The interop test is `As2InteropTests` (`[Trait("Category", "Interop")]`) and is
**gated** by `[As2InteropFact]`: without OpenAS2 on `127.0.0.1:14080` the cases are reported **skipped**, with the
reason, never passed; `REDB_AS2_INTEROP=1` turns a missing stand into a failure. The reverse case listens on the
fixed port the stand posts to (15081), so the three target frameworks take turns on it through a lock file in the
temp directory, and each waits for its own uniquely named document.
```bash
bash tests/docker/gen-certs.sh # once: the test certificates
docker compose -f docker-compose.tests.yml --profile as2 up -d --wait
dotnet test tests/redb.Route.Tests.As2 --filter Category=Interop
docker compose -f docker-compose.tests.yml --profile as2 down -v
```
Certificate paths come from the `AS2_INTEROP_CERTS` environment variable (default `tests/docker/.generated/as2/certs`).
### Configuration notes learned from OpenAS2 4.9.0
Captured so the harness reproduces cleanly:
- Partnerships live in a **separate `partnerships.xml`** (`XMLPartnershipFactory`) referenced by
`config.xml`'s `partnership_file` property — **not** inline in `config.xml`.
- The whole `config_template/` must be present (`config.xml` references `commands.xml`, `messages.xml`, …).
The harness is seeded from the image's own template, then `partnerships.xml` and `as2_certs.p12` are replaced.
- The AS2 receiver listens on **10080** inside the container (async-MDN on 10081); the default keystore
password is `testas2`. The keystore holds our partner's key (`openas2`) plus our certificate (`redb`) as a
trusted entry.
---
The reverse direction is driven by `As2InteropTests.OpenAs2_To_Redb_ReceivesSignedEncrypted`: it starts a redb
consumer on host port 15081, drops an EDI file into OpenAS2's outbox for partner `redb`, and waits for the
poller to deliver it. The harness's compose maps `host.docker.internal` via `extra_hosts: host-gateway` so the
Linux container can reach the host consumer, and the `openas2-to-redb` partnership carries a `subject`
attribute (required by the OpenAS2 poller).
## 3. Future work
- **Additional real implementations** — the loopback matrix covers the algorithm space; broadening interop
coverage to Mendelson and partner gateways is future work.
- ~~Async MDN against OpenAS2~~ — done 2026-09-28, both directions (above).
Path: redb-route/redb.Route.As2/redb.Route.As2.csproj
Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages.
License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route
Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.As2/redb.Route.As2.csproj
----
redb.Route.As2
AS2 (RFC 4130) B2B/EDI transport for the redb.Route ESB framework: signed/encrypted S/MIME over HTTP with MDN receipts.
esb;messaging;as2;edi;b2b;smime;redb
README.md