Bundle: redb-route / redb.Route.As4 (redb.Route.As4.txt), 44 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.As4/As4Algorithms.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.As4/As4Algorithms.cs ---- namespace redb.Route.As4; /// /// Algorithm identifiers used by AS4 message security, and the set this connector supports. The supported /// set is exactly what the eDelivery AS4 1.16 common profile mandates; an agreement naming anything else is /// refused when it is validated, not when the first message arrives. /// public static class As4Algorithms { /// RSA with SHA-256 signature (XML Signature). public const string RsaSha256 = "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"; /// SHA-256 digest (XML Encryption namespace URI, as XML Signature uses it). public const string Sha256 = "http://www.w3.org/2001/04/xmlenc#sha256"; /// AES-128 in GCM mode (XML Encryption 1.1). public const string Aes128Gcm = "http://www.w3.org/2009/xmlenc11#aes128-gcm"; /// RSA-OAEP key transport (XML Encryption 1.1), with explicit MGF and digest. public const string RsaOaep = "http://www.w3.org/2009/xmlenc11#rsa-oaep"; /// MGF1 with SHA-256 mask generation (XML Encryption 1.1). public const string Mgf1Sha256 = "http://www.w3.org/2009/xmlenc11#mgf1sha256"; private static readonly HashSet Signatures = new(StringComparer.Ordinal) { RsaSha256 }; private static readonly HashSet Digests = new(StringComparer.Ordinal) { Sha256 }; private static readonly HashSet DataEncryption = new(StringComparer.Ordinal) { Aes128Gcm }; private static readonly HashSet KeyTransports = new(StringComparer.Ordinal) { RsaOaep }; private static readonly HashSet MaskGenerations = new(StringComparer.Ordinal) { Mgf1Sha256 }; /// Whether is a supported signature algorithm. public static bool IsSupportedSignature(string? uri) => uri is not null && Signatures.Contains(uri); /// Whether is a supported digest algorithm. public static bool IsSupportedDigest(string? uri) => uri is not null && Digests.Contains(uri); /// Whether is a supported payload encryption algorithm. public static bool IsSupportedDataEncryption(string? uri) => uri is not null && DataEncryption.Contains(uri); /// Whether is a supported key transport algorithm. public static bool IsSupportedKeyTransport(string? uri) => uri is not null && KeyTransports.Contains(uri); /// Whether is a supported mask generation function. public static bool IsSupportedMaskGeneration(string? uri) => uri is not null && MaskGenerations.Contains(uri); } Path: redb-route/redb.Route.As4/As4AuthenticationTypes.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.As4/As4AuthenticationTypes.cs ---- namespace redb.Route.As4; /// /// Authentication types of the identities an AS4 receiver puts on the exchange principal (ExchangePrincipal): the /// envelope signer first, then the TLS client certificate when the partner presented one. /// public static class As4AuthenticationTypes { /// /// The identity proven by the envelope signature. Claims: NameIdentifier — the partner (agreement) the message /// was matched to; Name — the signing certificate's subject; Thumbprint — its thumbprint. /// public const string Signature = "AS4-Signature"; /// The identity proven by a TLS client certificate. Claims: Name — its subject; Thumbprint. public const string ClientCertificate = "TLS-ClientCertificate"; } Path: redb-route/redb.Route.As4/As4Component.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.As4/As4Component.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Extensions; using redb.Route.Http; namespace redb.Route.As4; /// /// AS4 (OASIS ebMS 3.0, AS4 profile; eDelivery AS4 1.16 common profile) transport component for redb.Route. /// Schemes: as4 (HTTP) and as4s (HTTPS). /// /// Receive: as4:/as4/in?host=0.0.0.0&port=4090&connectionFactory=node. /// Send: as4s://ap.partner.example/as4?connectionFactory=node&partner=acme. /// /// Consumer or producer is chosen by the DSL side (.From / .To). The node and its trading /// partners are resolved from the registry when the endpoint starts — see . /// public sealed class As4Component : ComponentBase { // Standalone fallback server, used only when no shared instance was injected (tests, or a host without // AddRedbRouteHttpHosting). private readonly Lazy _ownServer = new(() => new SharedHttpServerManager()); /// The shared Kestrel receive server, set by the DI registrar; owned by the container. public SharedHttpServerManager? ServerManager { get; set; } /// /// The server to host receive endpoints on: the DI-injected one; else the shared instance from the route /// context's service provider (the path under Tsak, which loads connectors with /// Activator.CreateInstance and injects nothing); else a private fallback. /// internal SharedHttpServerManager Server => ServerManager ?? Context.Resolve() ?? _ownServer.Value; /// public override string Scheme => "as4"; /// HTTPS variant of the AS4 scheme. public override IReadOnlyList AlternateSchemes => ["as4s"]; /// public override IEndpoint CreateEndpoint(EndpointUri uri) { ArgumentNullException.ThrowIfNull(uri); var options = new As4EndpointOptions(); options.BindFromUri(uri.RawParameters); // The scheme carries the TLS decision: as4s means HTTPS. Applied after binding, before validation. if (string.Equals(uri.Scheme, "as4s", StringComparison.OrdinalIgnoreCase)) options.UseTls = true; options.Validate(); return new As4Endpoint(uri, this, options); } /// public override async ValueTask DisposeAsync() { // Only the private fallback is ours to dispose; a shared server belongs to the container. if (_ownServer.IsValueCreated) await _ownServer.Value.DisposeAsync().ConfigureAwait(false); } } Path: redb-route/redb.Route.As4/As4ConnectionFactory.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.As4/As4ConnectionFactory.cs ---- using System.Security.Authentication; using System.Security.Cryptography.X509Certificates; using redb.Route.Abstractions; using redb.Route.As4.Security; using redb.Route.Core; namespace redb.Route.As4; /// /// Our AS4 node: our party identity, our keys and the trading partners we /// deal with. Registered once by name and referenced from endpoint URIs with connectionFactory=name, /// so certificates and passwords never travel in a URI (which is the route key and ends up in logs, spans /// and the dashboard). /// /// context.AddToRegistry("node", new As4ConnectionFactory /// { /// OurPartyId = "...", /// SigningCertificate = ourPfx, /// DecryptionCertificates = { ourPfx }, /// Partners = { new As4Partner { Name = "acme", PartyId = "...", Service = "...", Action = "...", /// PartnerSigningCertificates = { acmeCer }, PartnerEncryptionCertificate = acmeCer } }, /// }); /// /// In Route-XML the same node is a <bean> whose Partners property is a <list> of /// <ref bean="…"/> or nested <bean> partners. /// public sealed class As4ConnectionFactory { /// Our eb:PartyId. Exactly one, as eDelivery requires. public string? OurPartyId { get; set; } /// Our eb:PartyId/@type; omitted when null. public string? OurPartyIdType { get; set; } /// /// Host part of the message ids we generate (uuid@host). Set it to a public name: the default is a /// fixed placeholder, never the machine name, so internal host names do not leak to partners. /// public string ExternalHostName { get; set; } = "redb.route"; /// Our certificate with its private key: signs our messages and receipts. public X509Certificate2? SigningCertificate { get; set; } /// /// The certification authorities above , in any order, private keys not needed. /// Sent with our certificate as its certification path to a partner whose is /// , the outermost authority first. Empty for a certificate that is its own /// authority, or when no agreement uses a path. Every certificate here must lie on that path: one that issued neither /// our certificate nor another authority of the chain stops the node from starting. /// public IList SigningCertificateChain { get; set; } = new List(); /// /// Our certificates with private keys that decrypt payloads partners encrypt for us. More than one while /// we rotate our key and partners still encrypt for either; the one a message names is used. /// public IList DecryptionCertificates { get; set; } = new List(); /// /// TLS versions our sender offers. Default TLS 1.2 and 1.3: eDelivery AS4 1.16 requires 1.2, allows 1.3 and forbids /// SSL and TLS 1.0 / 1.1, so anything else is refused when the node is validated. The same default as Holodeck /// (AllowedProtocols), phase4 and Domibus; the name is the AMQP connection factory's. The receive side's /// versions are the shared host's. /// public SslProtocols SslProtocols { get; set; } = SslProtocols.Tls12 | SslProtocols.Tls13; /// /// Revocation check of the certificates the node pins: the partners' signing and encryption certificates, our own /// signing certificate before sending, and allow-listed TLS client certificates. /// (default, as Camel/CXF, Holodeck and phase4), (CRL / OCSP the certificate /// points at; the OS caches them) or (the cache only). The name is ASP.NET's /// CertificateAuthenticationOptions.RevocationMode. A certificate that names no CRL distribution point and no /// authority information access passes, as in Domibus. /// public X509RevocationMode RevocationMode { get; set; } = X509RevocationMode.NoCheck; /// /// Accept a certificate whose revocation status cannot be determined (responder unreachable). Default false: refused, /// as phase4 and Domibus refuse it. /// public bool RevocationSoftFail { get; set; } /// The revocation policy of this node. internal Security.RevocationPolicy Revocation => new(RevocationMode, RevocationSoftFail); /// Our TLS client certificate for sending to partners that require mutual TLS; null for none. public X509Certificate2? ClientCertificate { get; set; } /// PFX the receive server presents over TLS, when the endpoint URI does not give one. public string? SslCertPath { get; set; } /// Password for . [Sensitive] public string? SslCertPassword { get; set; } /// /// Whether the receive server asks partners for a TLS client certificate, when the endpoint URI does not say. /// Needs a TLS (as4s) receive endpoint. /// public As4ClientCertificateMode ClientCertificateMode { get; set; } = As4ClientCertificateMode.NoCertificate; /// Thumbprints (comma-separated) an accepted client certificate must match, when the endpoint URI gives none. public string? AllowedClientThumbprints { get; set; } /// The agreements of this node, one per trading partner, told apart by . public IList Partners { get; set; } = new List(); /// /// Where the receipts this node sends are kept, so that a duplicate of a received message is answered with the /// very receipt of the original (AS4 profile, reception awareness; eDelivery conformance AS4_CP_TA63). Null keeps /// them in memory, up to and the newest 100 000; give a shared store (SQL, Redis, /// file) when several workers receive for this node or the receipts must outlive a restart. A duplicate whose /// receipt is no longer kept is answered with a new receipt for the same message. /// public IClaimCheckRepository? ReceiptStore { get; set; } /// How long a sent receipt is kept for answering duplicates. Default one day. public TimeSpan ReceiptRetention { get; set; } = TimeSpan.FromDays(1); private IClaimCheckRepository? _receipts; /// The store of sent receipts: , or this node's own memory. internal IClaimCheckRepository Receipts => ReceiptStore ?? LazyInitializer.EnsureInitialized(ref _receipts, () => new Signals.RecentReceipts(ReceiptRetention, 100_000)); /// Throws when the node cannot be used; called when an endpoint that names it starts. /// The factory's registry name, for the error text. public void Validate(string name) { var owner = $"AS4 connection factory '{name}'"; if (string.IsNullOrWhiteSpace(OurPartyId)) throw new InvalidOperationException($"{owner}: OurPartyId is required."); if (string.IsNullOrWhiteSpace(ExternalHostName)) throw new InvalidOperationException($"{owner}: ExternalHostName must not be empty."); if (ReceiptRetention <= TimeSpan.Zero) throw new InvalidOperationException($"{owner}: ReceiptRetention must be positive."); if (SslProtocols == SslProtocols.None || (SslProtocols & ~(SslProtocols.Tls12 | SslProtocols.Tls13)) != 0) throw new InvalidOperationException($"{owner}: SslProtocols '{SslProtocols}' is not allowed; eDelivery AS4 1.16 permits TLS 1.2 and TLS 1.3 only."); if (SigningCertificate is not { HasPrivateKey: true }) throw new InvalidOperationException($"{owner}: SigningCertificate with a private key is required — every AS4 message and receipt is signed."); if (SigningCertificateChain is null || SigningCertificateChain.Any(c => c is null)) throw new InvalidOperationException($"{owner}: SigningCertificateChain contains an empty entry."); // An authority that does not lie on the path of our certificate would be left out of every PKIPath token // without a word, and the partner would refuse our messages (EBMS:0101): refused here, before the first one. if (SigningCertificateChain.Count > 0) { var path = PkiPath.Order(SigningCertificate, SigningCertificateChain); if (SigningCertificateChain.FirstOrDefault(c => path.All(p => p.Thumbprint != c.Thumbprint)) is { } stray) throw new InvalidOperationException( $"{owner}: SigningCertificateChain holds {stray.Subject} ({stray.Thumbprint}), which is not on the certification " + $"path of the SigningCertificate {SigningCertificate.Subject}: every authority of the chain must have issued " + "the signing certificate or another authority of the chain."); } if (DecryptionCertificates is null || DecryptionCertificates.Count == 0) throw new InvalidOperationException($"{owner}: DecryptionCertificates is empty — every received payload is encrypted."); if (DecryptionCertificates.Any(c => c is not { HasPrivateKey: true })) throw new InvalidOperationException($"{owner}: every DecryptionCertificates entry needs a private key."); if (Partners is null || Partners.Count == 0) throw new InvalidOperationException($"{owner}: Partners is empty."); if (Partners.Any(p => p is null)) throw new InvalidOperationException($"{owner}: Partners contains an empty entry."); if (Partners.FirstOrDefault(p => string.IsNullOrWhiteSpace(p.Name)) is { } unnamed) throw new InvalidOperationException($"{owner}: a partner has no Name (PartyId '{unnamed.PartyId}')."); var duplicates = Partners.GroupBy(p => p.Name!, StringComparer.Ordinal).Where(g => g.Count() > 1).Select(g => g.Key).ToList(); if (duplicates.Count > 0) throw new InvalidOperationException($"{owner}: partner names repeat: {string.Join(", ", duplicates)}."); } } Path: redb-route/redb.Route.As4/As4Consumer.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.As4/As4Consumer.cs ---- using System.Diagnostics; using System.Security.Cryptography; using System.Xml; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Components; using redb.Route.Configuration; using redb.Route.As4.Compression; using redb.Route.As4.Messaging; using redb.Route.As4.Mime; using redb.Route.As4.Security; using redb.Route.As4.Signals; using redb.Route.Core; using redb.Route.Http; using redb.Route.Telemetry; namespace redb.Route.As4; /// /// AS4 receive server (One-Way / Push, eDelivery AS4 1.16) on the shared Kestrel host. For every request: /// read the envelope (no DTD, bounded), match the agreement, decrypt, verify the signature, check the payload /// references, decompress, hand one exchange to the route, and answer in the HTTP response — a signed /// non-repudiation receipt when the unit of work succeeded (EndedInFailure() is false), an ebMS error /// otherwise. The receipt therefore goes out after the route's transaction has committed. /// /// What the partner reads never carries the text of one of our exceptions (BR-4): each ebMS code has a fixed /// text and the answer quotes a reference; the detail goes to the log. Decryption and signature failures all /// get the same answer of their code, so varying the input teaches the sender nothing. /// /// internal sealed class As4Consumer : IConsumer { private readonly As4Endpoint _endpoint; private readonly IProcessor _processor; private readonly As4EndpointOptions _options; private readonly InflightDrainGuard _drain = new(); private RouteRegistration? _registration; private As4Node? _node; private IIdempotentRepository? _duplicates; private StreamCacheOptions _spool = new(); private ILogger? _logger; public As4Consumer(As4Endpoint endpoint, IProcessor processor, As4EndpointOptions options) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _processor = processor ?? throw new ArgumentNullException(nameof(processor)); _options = options ?? throw new ArgumentNullException(nameof(options)); } /// public IEndpoint Endpoint => _endpoint; /// The engine pipeline received messages are handed to. internal IProcessor Processor => _processor; private SharedHttpServerManager Server => ((As4Component)_endpoint.Component).Server; private string Path => _endpoint.Uri.Path; /// public async Task Start(CancellationToken ct = default) { if (_endpoint.PartnerUrl is not null || Path.Length == 0) throw new InvalidOperationException( $"AS4 receive endpoint {_endpoint.Uri} has no receive path; a receive endpoint is as4:/path?host=...&port=...."); _logger ??= _endpoint.Logger; _node = As4Node.Resolve(_endpoint.Context, _options.ConnectionFactory!); // eDelivery AS4 1.16 mandates duplicate detection; the store is named, as the S3 consumer names it. if (string.IsNullOrWhiteSpace(_options.IdempotentRepository)) throw new InvalidOperationException( $"AS4 receive endpoint {_endpoint.Uri} requires 'idempotentRepository': the name of an IIdempotentRepository registered with " + "context.AddIdempotentRepository(name, repository). It remembers received message ids so a resend is not delivered twice."); var context = _endpoint.Context ?? throw new InvalidOperationException($"AS4 receive endpoint {_endpoint.Uri} has no route context to resolve its idempotent repository from."); _duplicates = context.GetIdempotentRepositoryProvider().Get(_options.IdempotentRepository); _spool = As4Spool.Options(context); // TLS material, as the SOAP receiver resolves it: the URI wins where it says something, the node fills the rest // (a password in a URI travels into logs and the dashboard). var certPath = _options.SslCertPath ?? _node.Factory.SslCertPath; var certPassword = _options.SslCertPassword ?? _node.Factory.SslCertPassword; var certMode = _options.ClientCertificateMode != As4ClientCertificateMode.NoCertificate ? _options.ClientCertificateMode : _node.Factory.ClientCertificateMode; var thumbprints = _options.AllowedClientThumbprints ?? _node.Factory.AllowedClientThumbprints; // Fail here rather than inside Kestrel, as the SOAP receiver does: without a certificate the listener would fall // back to a host default (present on a developer's machine, absent in production), and a partner would meet a // certificate nobody agreed on. if (_options.UseTls && string.IsNullOrWhiteSpace(certPath)) throw new InvalidOperationException( $"AS4 receive endpoint on {_options.Host}:{_options.Port}{Path} is set to serve TLS but has no certificate. " + "Set sslCertPath on the endpoint URI, or SslCertPath on the connection factory it names."); if (certMode != As4ClientCertificateMode.NoCertificate && !_options.UseTls) throw new InvalidOperationException( $"AS4 receive endpoint on {_options.Host}:{_options.Port}{Path} asks for client certificates without TLS: a client " + "certificate is presented in the TLS handshake. Use the as4s scheme, or drop clientCertificateMode."); _drain.Start(ct); _registration = Server.RegisterRoute(_options.Host, _options.Port, Path, "POST", HandleRequest, _options.UseTls, certPath, certPassword, corsOptions: null, maxRequestBodySize: _options.MaxRequestBodySize, clientCertificateMode: MapClientCertificateMode(certMode), clientCertificateValidation: ThumbprintValidator(thumbprints, _node.Factory.Revocation), concurrencyLimit: ConcurrencyLimitOptions.FromEndpoint( _options.MaxConcurrentRequests, _options.RequestQueueLimit, _options.RejectStatusCode, _options.RetryAfterSeconds, onRejected: _endpoint.RecordRejected)); try { await Server.EnsureStarted(_options.Host, _options.Port, ct).ConfigureAwait(false); } catch { // The listener did not come up (a port still taken): the route leaves it, so a later Start registers // once and a stopped receiver does not keep the port. await Stop(CancellationToken.None).ConfigureAwait(false); throw; } _logger?.LogInformation("AS4 receiver started: {Host}:{Port}{Path}, node {Node}", _options.Host, _options.Port, Path, _node.Name); } /// public async Task Stop(CancellationToken ct = default) { if (_registration is null) return; // Unregister, drain what is already inside, then release the listener — the order of the HTTP family. Server.UnregisterRoute(_registration); _registration = null; await _drain.DrainAsync(ct, _logger, $"as4://{_options.Host}:{_options.Port}{Path}").ConfigureAwait(false); await Server.StopIfEmpty(_options.Host, _options.Port, ct).ConfigureAwait(false); _logger?.LogInformation("AS4 receiver stopped: {Host}:{Port}{Path}", _options.Host, _options.Port, Path); } private async Task HandleRequest(HttpContext http) { // Counted for the drain: a message already inside the pipeline must be answered before Stop returns. _drain.Increment(); try { await HandleRequestCore(http).ConfigureAwait(false); } catch (Exception e) when (e is not OperationCanceledException) { // What the receiver did not foresee is still an ebMS answer (BR-4): logged with its reference and counted, the // partner gets EBMS:0004 and the reference, never a bare 500 it cannot tell from a network failure. _logger?.LogError(e, "AS4 receiver {Path}: unexpected failure (ref {Reference}).", Path, http.TraceIdentifier); _endpoint.RecordError(e); if (!http.Response.HasStarted) await WriteSignal(http, Responses.Error(As4ErrorCode.Other, null, _node!.Factory.ExternalHostName, http.TraceIdentifier)).ConfigureAwait(false); } finally { _drain.Decrement(); } } private async Task HandleRequestCore(HttpContext http) { var node = _node!; var host = node.Factory.ExternalHostName; var reference = http.TraceIdentifier; // The Consumer span 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. using var span = RouteTelemetryExtensions.StartConsumerSpan( _endpoint.Context, $"{Path} receive", ActivityKind.Consumer, "messaging.system", "as4", _endpoint.Uri.NormalizedKey, http.Request.Headers, static (headers, name) => headers.TryGetValue(name, out var value) ? value.ToString() : null, InboundParent.HostRequest, destination: Path, operation: "receive"); var activity = span.Activity; // The request is spooled, not buffered: past the threshold it goes to a temporary file (Kestrel bounds it by // maxRequestBodySize), and MimeKit reads the parts from there without another copy. var body = new StreamCache(_spool); // ── Not ebMS at all: a SOAP fault ── SwaMessage message; try { await body.CacheFromSourceAsync(http.Request.Body, http.RequestAborted).ConfigureAwait(false); body.CompleteWriting(); message = SwaMessage.Read(http.Request.ContentType ?? string.Empty, body, _options.MaxEnvelopeCharacters, _spool); } catch (XmlException e) { await body.DisposeAsync().ConfigureAwait(false); // A DTD (forbidden in SOAP, SOAP 1.2 Part 1 §5), broken XML or an envelope over its limits: the text describes // the caller's own bytes. A refusal, not an error of this endpoint. _endpoint.RecordRefused($"Malformed SOAP envelope: {e.Message}"); activity.RecordFailure(e); await Write(http, Responses.SoapFault(mustUnderstand: false, $"Malformed SOAP envelope: {e.Message}")).ConfigureAwait(false); return; } catch (Exception e) when (e is FormatException or MimeKit.ParseException or ArgumentException) { await body.DisposeAsync().ConfigureAwait(false); _endpoint.RecordRefused($"{As4ErrorCode.MimeInconsistency.Code}: {e.Message}"); activity.RecordFailure(e); await WriteSignal(http, Responses.Error(As4ErrorCode.MimeInconsistency, null, host, reference)).ConfigureAwait(false); return; } catch { await body.DisposeAsync().ConfigureAwait(false); throw; } using var owned = message; // parts the route did not take, and the spooled request if (EnvelopeProblem(message.Envelope) is { } notSoap) { _endpoint.RecordRefused(notSoap); activity?.SetStatus(ActivityStatusCode.Error); await Write(http, Responses.SoapFault(mustUnderstand: false, notSoap)).ConfigureAwait(false); return; } if (UnderstoodHeaders(message.Envelope) is { } unknownBlock) { _endpoint.RecordRefused($"Header block {unknownBlock} is not understood."); activity?.SetStatus(ActivityStatusCode.Error); await Write(http, Responses.SoapFault(mustUnderstand: true, $"Header block {unknownBlock} is not understood.")).ConfigureAwait(false); return; } // ── ebMS processing up to the route: every failure is an ebMS error ── string? messageId = null; As4Partner? partner = null; Exchange exchange; SignatureVerification verification; try { var messaging = MessagingReader.Read(message.Envelope); if (messaging.SignalMessages.FirstOrDefault(s => s.PullRequestMpc is not null) is { } pull) { // No pull process here (pull is out of scope): EBMS:0010, as Domibus answers a pull request for an mpc // without one (PullRequestLegConfigurationExtractor). messageId = pull.MessageInfo.MessageId; throw new As4ProcessingException(As4ErrorCode.ProcessingModeMismatch, $"a pull request for mpc '{pull.PullRequestMpc}': this receiver supports push only."); } if (messaging.UserMessages.Count == 0) { // A signal on the message endpoint: eDelivery 1.16 forbids asynchronous signals, so nothing waits for it. _logger?.LogWarning("AS4 receiver {Path}: a signal message arrived and no exchange waits for it; ignored.", Path); http.Response.StatusCode = StatusCodes.Status202Accepted; return; } var user = messaging.UserMessages[0]; messageId = user.MessageInfo.MessageId; (partner, _) = node.MatchInbound(user); verification = Secure(message, node, partner); if (partner.RequireFourCornerProperties) RequireFourCornerProperties(user); exchange = CreateExchange(http, user, message, partner, verification); } catch (As4ProcessingException e) { _logger?.LogWarning("AS4 receiver {Path}: message {MessageId} refused with {Code} (ref {Reference}): {Detail}", Path, messageId, e.Code.Code, reference, e.Detail); // The partner's message does not hold (security, agreement, profile): a refusal answered by protocol. EBMS:0004 // stays an error: it names a failure on this side, except the impersonation refused with it. if (e.Code == As4ErrorCode.Other && e.InnerException is not SignerNotAuthorizedException) _endpoint.RecordError(e); else _endpoint.RecordRefused($"{e.Code.Code} for {messageId}: {e.Detail}"); activity.RecordFailure(e); await WriteSignal(http, Responses.Error(e.Code, messageId, host, reference, signer: partner is null ? null : node.Factory.SigningCertificate, keyReference: partner?.KeyReference ?? As4KeyReference.BinarySecurityToken, signingPath: node.SigningPath)).ConfigureAwait(false); return; } try { // ── Duplicate detection: the two-phase claim of the S3 consumer (Lease, then Confirm or Release of that claim) ── // Claimed after the security checks, so a forged message cannot burn the id of a real one. The claim is a short // state write taken uncancelled, as Confirm and Release are: cut by the sender's disconnect it could be written // and reported failed, leaving the id marked for a message the route never saw. A disconnect after it reaches // the route, whose cancellation releases the claim. IdempotentClaim claim; string? claimToken; try { var lease = await _duplicates!.Lease(messageId!, TimeSpan.FromMilliseconds(_options.InFlightClaimTimeout), CancellationToken.None) .ConfigureAwait(false); claim = lease.Outcome; claimToken = lease.Token; } catch (Exception e) { _logger?.LogError(e, "AS4 receiver {Path}: duplicate check for message {MessageId} failed (ref {Reference}).", Path, messageId, reference); _endpoint.RecordError(e); activity.RecordFailure(e); await WriteSignal(http, Responses.Error(As4ErrorCode.Other, messageId, host, reference, signer: node.Factory.SigningCertificate, keyReference: partner!.KeyReference, signingPath: node.SigningPath)).ConfigureAwait(false); return; } if (claim == IdempotentClaim.InFlight) { // The first copy is still in the route: not a duplicate yet. It may fail and release its claim, and a receipt // now would have told the sender the message arrived. Refused as busy with no ebMS signal, as the admission // limit refuses: the sender resends on its reception-awareness schedule (Domibus does, at its P-Mode interval). _endpoint.RecordRejected(); _logger?.LogWarning("AS4 receiver {Path}: message {MessageId} arrived again while its first copy is in the route; " + "refused with {Status} (ref {Reference}).", Path, messageId, _options.RejectStatusCode, reference); http.Response.StatusCode = _options.RejectStatusCode; if (_options.RetryAfterSeconds > 0) http.Response.Headers.RetryAfter = _options.RetryAfterSeconds.ToString(System.Globalization.CultureInfo.InvariantCulture); return; } if (claim == IdempotentClaim.TakenOver) _logger?.LogWarning("AS4 receiver {Path}: message {MessageId} had a claim older than inFlightClaimTimeout {Timeout} ms " + "that was never confirmed; taken over and processed.", Path, messageId, _options.InFlightClaimTimeout); if (claim == IdempotentClaim.Confirmed) { // Received before: answer with the receipt of the original, the very same signal (AS4_CP_TA63), and do // not deliver it twice. The sender stops resending once it has a receipt. A receipt no longer kept is // built again from the same bytes, so with the same non-repudiation information. var kept = await KeptReceiptAsync(node, partner!, messageId!).ConfigureAwait(false); _logger?.LogInformation("AS4 receiver {Path}: message {MessageId} is a duplicate; {Receipt}, not delivered.", Path, messageId, kept is null ? "a new receipt sent (the original is no longer kept)" : "its receipt sent again"); await WriteSignal(http, kept ?? Responses.Receipt(messageId!, verification.References, host, node.Factory.SigningCertificate!, partner!.KeyReference, partner.TimestampTtl, node.SigningPath)).ConfigureAwait(false); return; } // ── The route; the answer follows its unit of work ── try { await _processor.Process(exchange, http.RequestAborted).ConfigureAwait(false); } catch (OperationCanceledException) { // Aborted mid-route (the sender went away, or the host stopped after the drain timeout): the message // was not processed, so its resend must be delivered — released on any failure, as the S3 consumer does. await ReleaseClaimAsync(messageId!, claimToken).ConfigureAwait(false); throw; } catch (Exception e) { exchange.Exception ??= e; } if (exchange.EndedInFailure()) { // No RecordError: the core StatisticsProcessor saw the same exchange.Exception. The span shows it red. if (exchange.Exception is { } routeFailure) activity.RecordFailure(routeFailure); await ReleaseClaimAsync(messageId!, claimToken).ConfigureAwait(false); // the sender resends; that is not a duplicate var callerText = (exchange.Exception as MalformedRequestException)?.Message; var code = callerText is null ? As4ErrorCode.Other : As4ErrorCode.ValueInconsistent; _logger?.LogWarning(exchange.Exception, "AS4 receiver {Path}: route failed for message {MessageId}; answered {Code} (ref {Reference}).", Path, messageId, code.Code, exchange.ExchangeId); await WriteSignal(http, Responses.Error(code, messageId, host, exchange.ExchangeId, callerText, node.Factory.SigningCertificate, partner!.KeyReference, node.SigningPath)).ConfigureAwait(false); return; } await ConfirmClaimAsync(messageId!, claimToken).ConfigureAwait(false); var receipt = Responses.Receipt(messageId!, verification.References, host, node.Factory.SigningCertificate!, partner!.KeyReference, partner.TimestampTtl, node.SigningPath); await KeepReceiptAsync(node, partner, messageId!, receipt).ConfigureAwait(false); await WriteSignal(http, receipt).ConfigureAwait(false); } finally { await exchange.DisposeAsync().ConfigureAwait(false); } } /// /// Confirms the claim of a processed message. The work is done by now, so a failure to confirm is logged and /// the receipt still goes out; the claim itself (from Lease) already keeps a resend from being delivered. Only this /// request's claim is confirmed: a claim another node took over meanwhile is left to its holder. /// private async Task ConfirmClaimAsync(string messageId, string? token) { try { if (!await _duplicates!.Confirm(messageId, token, CancellationToken.None).ConfigureAwait(false)) LogTakenOver(messageId); } catch (Exception e) when (e is not OperationCanceledException) { _logger?.LogWarning(e, "AS4 receiver {Path}: confirming duplicate claim for message {MessageId} failed.", Path, messageId); } } /// /// Keeps the receipt sent for a message, for its duplicates. Under the sending party and the message id, so a /// receipt goes back only to the party it was signed for. The receipt goes out whether or not it was kept. /// private async Task KeepReceiptAsync(As4Node node, As4Partner partner, string messageId, (string ContentType, byte[] Body) receipt) { try { var contentType = System.Text.Encoding.UTF8.GetBytes(receipt.ContentType); var data = new byte[contentType.Length + 1 + receipt.Body.Length]; contentType.CopyTo(data, 0); data[contentType.Length] = (byte)'\n'; receipt.Body.CopyTo(data, contentType.Length + 1); await node.Factory.Receipts.Store(ReceiptKey(partner, messageId), data, node.Factory.ReceiptRetention, CancellationToken.None) .ConfigureAwait(false); } catch (Exception e) when (e is not OperationCanceledException) { _logger?.LogWarning(e, "AS4 receiver {Path}: keeping the receipt of message {MessageId} failed; a duplicate gets a new receipt.", Path, messageId); } } /// The receipt kept for a message of this party, or null when none is kept (or the store fails). private async Task<(string ContentType, byte[] Body)?> KeptReceiptAsync(As4Node node, As4Partner partner, string messageId) { try { var data = await node.Factory.Receipts.Retrieve(ReceiptKey(partner, messageId), CancellationToken.None).ConfigureAwait(false); var split = data is null ? -1 : Array.IndexOf(data, (byte)'\n'); if (split < 0) return null; return (System.Text.Encoding.UTF8.GetString(data!, 0, split), data![(split + 1)..]); } catch (Exception e) when (e is not OperationCanceledException) { _logger?.LogWarning(e, "AS4 receiver {Path}: reading the kept receipt of message {MessageId} failed.", Path, messageId); return null; } } /// /// A key every store takes (a file store makes a file name of it): a hash of the sending party and the message id. /// The party, not the agreement: a resend may match another agreement with the same party (the conformance test /// driver resends AS4_CP_TA63 under another action), and it is still the same message of the same sender. /// private void LogTakenOver(string messageId) => _logger?.LogWarning("AS4 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.", Path, messageId, _options.InFlightClaimTimeout); private static string ReceiptKey(As4Partner partner, string messageId) => "as4-receipt-" + Convert.ToHexString(System.Security.Cryptography.SHA256.HashData( System.Text.Encoding.UTF8.GetBytes(partner.PartyIdType + "\n" + partner.PartyId + "\n" + messageId))).ToLowerInvariant(); /// /// Releases the claim of a message the route did not process, so its resend is delivered (as the S3 consumer does). /// Only this request's claim is released: a claim another node took over meanwhile stays. /// private async Task ReleaseClaimAsync(string messageId, string? token) { try { if (!await _duplicates!.Release(messageId, token, CancellationToken.None).ConfigureAwait(false)) LogTakenOver(messageId); } catch (Exception e) when (e is not OperationCanceledException) { _logger?.LogWarning(e, "AS4 receiver {Path}: releasing duplicate claim for message {MessageId} failed — it stays marked until manual cleanup.", Path, messageId); } } /// /// Decrypts, verifies and checks the policy of the agreement: eDelivery mandates a signed message with /// encrypted payloads, so a message without either is refused before any other check. Throws the ebMS code /// for each failure; decryption and signature failures carry the detail only for our log. /// private SignatureVerification Secure(SwaMessage message, As4Node node, As4Partner partner) { SoapParts parts; try { parts = SoapParts.Of(message.Envelope); } catch (CryptographicException e) { // Two wsse:Security headers for one role (WS-Security 1.1 §6.1): a policy failure, as Domibus reports WSS4J's. throw new As4ProcessingException(As4ErrorCode.PolicyNoncompliance, e.Message, e); } var security = parts.Security; var signed = security is not null && security.ChildNodes.OfType().Any(e => e.LocalName == "Signature" && e.NamespaceURI == WsSecurityNames.Ds); var encrypted = security is not null && security.ChildNodes.OfType().Any(e => e.LocalName == "EncryptedKey" && e.NamespaceURI == WsSecurityNames.Xenc); if (!signed) // Every agreement asks for a signed message, so an unsigned one does not match the processing mode: EBMS:0010, // as the eDelivery conformance test driver expects (AS4_CP_TA80). throw new As4ProcessingException(As4ErrorCode.ProcessingModeMismatch, "the message is not signed."); if (message.Parts.Count > 0 && !encrypted) throw new As4ProcessingException(As4ErrorCode.PolicyNoncompliance, "the payloads are not encrypted."); try { As4SecurityEngine.Decrypt(message, node.Factory.DecryptionCertificates); } catch (CryptographicException e) { throw new As4ProcessingException(As4ErrorCode.FailedDecryption, e.Message, e); } try { return As4SecurityEngine.Verify(message, partner.PartnerSigningCertificates.ToList(), partner.TimestampTolerance, DateTimeOffset.UtcNow, node.Factory.Revocation, partner.TimestampTimeToLive, partner.PkiPathTrust, TrustedElsewhere(node, partner)); } catch (SignatureCoverageException e) { // Signed, and what is signed is intact, but not everything the profile requires: the policy is not met. throw new As4ProcessingException(As4ErrorCode.PolicyNoncompliance, e.Message, e); } catch (Exception e) when (e is UnsupportedAttachmentTransformException or MalformedSignatureValueException) { throw new As4ProcessingException(As4ErrorCode.FailedDecryption, e.Message, e); } catch (SignerNotAuthorizedException e) { throw new As4ProcessingException(As4ErrorCode.Other, e.Message, e); } catch (CryptographicException e) { throw new As4ProcessingException(As4ErrorCode.FailedAuthentication, e.Message, e); } } /// /// The certificates this node trusts apart from the sender's agreement: the signing certificates of its other /// agreements and the trust anchors of all of them. A message signed with one of these, or with a certificate one of /// them issued, is an impersonation of the sender, not a stranger's message. /// private static List TrustedElsewhere(As4Node node, As4Partner partner) { var trusted = new List(); foreach (var other in node.Factory.Partners) { if (!ReferenceEquals(other, partner)) trusted.AddRange(other.PartnerSigningCertificates); trusted.AddRange(other.PartnerTrustAnchors); } return trusted; } private Exchange CreateExchange(HttpContext http, UserMessage user, SwaMessage message, As4Partner partner, SignatureVerification verification) { // Every payload is decompressed before any is handed on: a failure leaves them all with the message. var matched = new List<(PartInfo Info, SwaPart Part)>(); PayloadConsistency.CheckCharacterSets(user); foreach (var (info, part) in PayloadConsistency.Match(user, message)) { if (part is null) throw new As4ProcessingException(As4ErrorCode.FeatureNotSupported, "a payload in the SOAP body is not supported; AS4 carries payloads as attachments."); As4Compression.Decompress(part, info, MaxDecompressedBytes, message.Spool); matched.Add((info, part)); } // One payload is the body itself — byte[], or with streamBody the spooled stream, which the exchange closes // (Exchange.DisposeAsync), as the File and S3 consumers hand theirs. Several are As4Payload streams the // exchange releases (ExchangeResources.ReleaseWithExchange). With payloadList the body is always that list, in // the order of eb:PartInfo, whatever the number of payloads. object? body; List? payloads = null; var single = matched.Count == 1 && !_options.PayloadList; if (matched.Count == 0 && !_options.PayloadList) { body = null; } else if (single) { body = _options.StreamBody ? matched[0].Part.Detach() : matched[0].Part.ToArray(); } else { payloads = matched.Select(m => new As4Payload(m.Part.ContentId, m.Part.ContentType, m.Part.Detach(), m.Info.Properties.ToDictionary(p => p.Name, p => p.Value, StringComparer.Ordinal))).ToList(); body = payloads; } var messageOut = new Message(body) { ContentType = single ? matched[0].Part.ContentType : null }; Headers(messageOut, user, partner, verification); if (http.Connection.RemoteIpAddress is { } remote) messageOut.Headers[As4Headers.RemoteAddress] = remote.ToString(); // mTLS: what the handshake proved about the caller, as the SOAP receiver puts it on the exchange. if (http.Connection.ClientCertificate is { } clientCert) { messageOut.Headers[As4Headers.ClientCertThumbprint] = clientCert.Thumbprint; messageOut.Headers[As4Headers.ClientCertSubject] = clientCert.Subject; messageOut.Headers[As4Headers.ClientCertNotAfter] = clientCert.NotAfter.ToUniversalTime().ToString("O"); } var exchange = Exchange.Create(messageOut, _endpoint.ScopeFactory); foreach (var payload in payloads ?? []) ExchangeResources.ReleaseWithExchange(exchange, payload.Content); exchange.Pattern = ExchangePattern.InOut; ExchangePrincipal.Set(exchange, Principal(http, partner, verification)); return exchange; } /// /// Who sent the message (as camel-cxf with WSS4J takes the principal from the signature): the /// envelope signer first — its subject, thumbprint and the agreement it authenticated — then the TLS client /// certificate when the partner presented one, then whatever the host's principal resolver adds. /// private static System.Security.Claims.ClaimsPrincipal Principal(HttpContext http, As4Partner partner, SignatureVerification verification) { var signer = verification.Signer; var identities = new List { new([ new(System.Security.Claims.ClaimTypes.NameIdentifier, partner.Name!), new(System.Security.Claims.ClaimTypes.Name, signer.Subject), new(System.Security.Claims.ClaimTypes.Thumbprint, signer.Thumbprint), ], As4AuthenticationTypes.Signature), }; if (http.Connection.ClientCertificate is { } clientCert) identities.Add(new([ new(System.Security.Claims.ClaimTypes.Name, clientCert.Subject), new(System.Security.Claims.ClaimTypes.Thumbprint, clientCert.Thumbprint), ], As4AuthenticationTypes.ClientCertificate)); if (SharedHttpServerManager.GetResolvedPrincipal(http) is { } resolved) identities.AddRange(resolved.Identities); return new System.Security.Claims.ClaimsPrincipal(identities); } /// The eb:Messaging plane onto the exchange, under names only. private static void Headers(IMessage message, UserMessage user, As4Partner partner, SignatureVerification verification) { var h = message.Headers; h[As4Headers.MessageId] = user.MessageInfo.MessageId; if (user.MessageInfo.RefToMessageId is { } refTo) h[As4Headers.RefToMessageId] = refTo; h[As4Headers.Timestamp] = user.MessageInfo.Timestamp; h[As4Headers.ConversationId] = user.CollaborationInfo.ConversationId; var from = user.From.PartyIds[0]; h[As4Headers.FromPartyId] = from.Value; if (from.Type is not null) h[As4Headers.FromPartyIdType] = from.Type; h[As4Headers.FromRole] = user.From.Role; var to = user.To.PartyIds[0]; h[As4Headers.ToPartyId] = to.Value; if (to.Type is not null) h[As4Headers.ToPartyIdType] = to.Type; h[As4Headers.ToRole] = user.To.Role; h[As4Headers.Service] = user.CollaborationInfo.Service.Value; if (user.CollaborationInfo.Service.Type is not null) h[As4Headers.ServiceType] = user.CollaborationInfo.Service.Type; h[As4Headers.Action] = user.CollaborationInfo.Action; if (user.CollaborationInfo.AgreementRef is { } agreement) { h[As4Headers.AgreementRef] = agreement.Value; if (agreement.PMode is not null) h[As4Headers.PModeId] = agreement.PMode; } foreach (var property in user.MessageProperties) { h[As4Headers.PropertyPrefix + property.Name] = property.Value; if (property.Type is not null) h[As4Headers.PropertyTypePrefix + property.Name] = property.Type; } h[As4Headers.Partner] = partner.Name; h[As4Headers.SignatureValid] = true; h[As4Headers.SignerThumbprint] = verification.Signer.Thumbprint; } /// /// The first header block with mustUnderstand="true" that is neither eb:Messaging nor /// wsse:Security (SOAP 1.2 Part 1 §5.2.3), or null. /// private static string? EnvelopeProblem(XmlDocument envelope) { // SOAP 1.2 Part 1 §5: an Envelope, at most one Header, exactly one Body — and an AS4 message has its ebMS // header, so both are required. Anything else is not a message this receiver can answer in ebMS terms. var root = envelope.DocumentElement; if (root is null || root.LocalName != "Envelope" || root.NamespaceURI != EbmsNamespaces.Soap12) return "Not a SOAP 1.2 envelope."; foreach (var name in new[] { "Header", "Body" }) { var count = root.ChildNodes.OfType().Count(e => e.LocalName == name && e.NamespaceURI == EbmsNamespaces.Soap12); if (count != 1) return $"The SOAP 1.2 envelope carries {count} {name} elements; an AS4 message has exactly one."; } return null; } private const string SoapNextRole = "http://www.w3.org/2003/05/soap-envelope/role/next"; private const string SoapUltimateReceiverRole = "http://www.w3.org/2003/05/soap-envelope/role/ultimateReceiver"; private static string? UnderstoodHeaders(XmlDocument envelope) { var header = envelope.DocumentElement?.ChildNodes.OfType() .FirstOrDefault(e => e.LocalName == "Header" && e.NamespaceURI == EbmsNamespaces.Soap12); if (header is null) return null; foreach (var block in header.ChildNodes.OfType()) { // SOAP 1.2 Part 1 §2.2: every node plays "next", the ultimate receiver also "ultimateReceiver" (the role of a // block without one); a block for "none" or another role is not addressed to us. var role = block.GetAttribute("role", EbmsNamespaces.Soap12); if (role.Length > 0 && role is not (SoapNextRole or SoapUltimateReceiverRole)) continue; var understood = (block.LocalName == "Messaging" && block.NamespaceURI == EbmsNamespaces.Eb) || (block.LocalName == "Security" && block.NamespaceURI == WsSecurityNames.Wsse); var mustUnderstand = block.GetAttribute("mustUnderstand", EbmsNamespaces.Soap12); if (!understood && mustUnderstand is "true" or "1") return $"{{{block.NamespaceURI}}}{block.LocalName}"; } return null; } /// /// eDelivery AS4 1.16 §4.1.2: originalSender and finalRecipient MUST be on every message of a /// four-corner exchange; asked of an agreement with (the default). /// Missing or empty is , as Domibus answers it (PropertyProfileValidator); /// checked after the security checks, as there. /// private static void RequireFourCornerProperties(UserMessage user) { foreach (var required in new[] { As4Headers.OriginalSender, As4Headers.FinalRecipient }) { var name = required[As4Headers.PropertyPrefix.Length..]; if (string.IsNullOrEmpty(user.PropertyValue(name))) throw new As4ProcessingException(As4ErrorCode.ProcessingModeMismatch, $"the message has no '{name}' property (eDelivery four-corner model)."); } } /// Upper bound on one decompressed payload: ten times the request limit, at most 1 GB, so a compression bomb cannot exhaust memory. private long MaxDecompressedBytes => Math.Min(_options.MaxRequestBodySize * 10, 1L << 30); private static Task WriteSignal(HttpContext http, (string ContentType, byte[] Body) signal) => Write(http, (StatusCodes.Status200OK, signal.ContentType, signal.Body)); private static async Task Write(HttpContext http, (int Status, string ContentType, byte[] Body) response) { http.Response.StatusCode = response.Status; http.Response.ContentType = response.ContentType; await http.Response.Body.WriteAsync(response.Body, http.RequestAborted).ConfigureAwait(false); } private static Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode? MapClientCertificateMode(As4ClientCertificateMode mode) => mode switch { As4ClientCertificateMode.AllowCertificate => Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode.AllowCertificate, As4ClientCertificateMode.RequireCertificate => Microsoft.AspNetCore.Server.Kestrel.Https.ClientCertificateMode.RequireCertificate, _ => null, }; /// /// The allow-list check for client certificates, as the SOAP receiver builds it. It replaces Kestrel's own check, and a /// pin is a constraint on top of validation, not instead of it: the certificate must be within its validity period and /// pass the node's revocation policy, as Holodeck ("directly trusted, check validity") and Domibus check a pinned /// client certificate. Chain building is skipped for the directly pinned certificate, as Holodeck skips it. /// private Func? ThumbprintValidator(string? allowedThumbprints, RevocationPolicy revocation) { if (string.IsNullOrWhiteSpace(allowedThumbprints)) return null; var allowed = allowedThumbprints .Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) .Select(t => t.Replace(" ", string.Empty)) .ToHashSet(StringComparer.OrdinalIgnoreCase); return (certificate, _, _) => { if (!allowed.Contains(certificate.Thumbprint)) return false; if (CertificateValidity.Problem(certificate, DateTimeOffset.UtcNow, "TLS client certificate", revocation) is not { } problem) return true; _logger?.LogWarning("AS4 receiver {Path}: refused an allow-listed client certificate in the TLS handshake: {Problem}", Path, problem); return false; }; } } Path: redb-route/redb.Route.As4/As4Endpoint.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.As4/As4Endpoint.cs ---- using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.Core; namespace redb.Route.As4; /// /// AS4 endpoint. Extends , which gives it statistics, health and Tsak /// visibility. Produces an (send) or an (receive). /// public sealed class As4Endpoint : EndpointBase { /// Logger of the owning component. internal ILogger? Logger { get; } /// Typed options, for the consumer and producer. internal As4EndpointOptions EndpointOptions => Options; /// The owning route context (registry lookups), via the component. internal IRouteContext? Context => (Component as ComponentBase)?.Context; /// /// Partner URL a producer posts to, rebuilt from a host-style URI (as4s://ap.partner/as4 has the /// path ap.partner/as4), with as its query. Null for a /// receive URI (as4:/as4/in). /// internal string? PartnerUrl { get; } /// Creates an AS4 endpoint. public As4Endpoint(EndpointUri uri, As4Component component, As4EndpointOptions options) : base(uri, component, options) { ArgumentNullException.ThrowIfNull(component); Logger = component.Logger; if (uri.Path.Length > 0 && !uri.Path.StartsWith('/')) PartnerUrl = (options.UseTls ? "https://" : "http://") + uri.Path + (options.AddressQuery is null ? "" : "?" + options.AddressQuery); } /// public override IProducer CreateProducer() { RefuseOtherSidesOptions(EndpointRole.Producer); if (PartnerUrl is null) { // as4:?partner=...: the address is the partner's, scheme and query included. if (Uri.Path.Length > 0) throw new InvalidOperationException( $"AS4 send endpoint '{EndpointUri.Sanitize(Uri.NormalizedKey)}' has a receive path; a send endpoint is " + "as4s://host[:port]/path, or as4:?partner=... to use the partner's Address."); if (Options.UseTls || Options.AddressQuery is not null) throw new InvalidOperationException( $"AS4 send endpoint '{EndpointUri.Sanitize(Uri.NormalizedKey)}' has no address, so as4s and addressQuery say nothing: " + "the partner's Address gives scheme and query. Write as4:?partner=...."); } return new As4Producer(this, Options); } /// public override IConsumer CreateConsumer(IProcessor processor) { RefuseOtherSidesOptions(EndpointRole.Consumer); return new As4Consumer(this, processor, Options); } /// /// An option only the other side reads (, as the http: connector declares it) /// would bind and do nothing — idempotentRepository on a send looks like duplicate detection, timeout /// on a receive like a limit. Refused, naming the parameters and never their values. /// private void RefuseOtherSidesOptions(EndpointRole creating) { var written = redb.Route.Core.EndpointOptions.WrittenForOtherRole(Options.GetType(), Uri, creating); if (written.Count == 0) return; var side = creating == EndpointRole.Producer ? "send" : "receive"; var other = creating == EndpointRole.Producer ? "receive" : "send"; throw new InvalidOperationException( $"AS4 {side} endpoint '{EndpointUri.Sanitize(Uri.NormalizedKey)}' sets {string.Join(", ", written)}: " + $"only a {other} endpoint reads {(written.Count == 1 ? "it" : "them")}."); } } Path: redb-route/redb.Route.As4/As4EndpointOptions.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.As4/As4EndpointOptions.cs ---- using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Http; namespace redb.Route.As4; /// /// Options of an AS4 endpoint, bound from URI query parameters. Only what may differ per endpoint or per /// message lives here; the agreement (identities, certificates, algorithms) is the named /// and its objects — there is no inline /// alternative, so one partner has one source of truth. /// /// checks what the URI alone decides. Everything that depends on the factory is /// checked when the consumer or producer starts: the registry may be filled after the routes are defined. /// /// public sealed class As4EndpointOptions : EndpointOptions { /// Default listen port of a receive endpoint. public const int DefaultPort = 4090; /// Default upper bound on a request body: 100 MB. public const long DefaultMaxRequestBodySize = 100L * 1024 * 1024; /// Default upper bound on the partner's response to a send: 4 MB (a receipt or an error is a few KB). public const long DefaultMaxResponseBodySize = 4L * 1024 * 1024; /// Default upper bound on the SOAP envelope (root MIME part), in characters: 1 M. public const long DefaultMaxEnvelopeCharacters = 1024 * 1024; // ── Node and partner ───────────────────────────────────────────────────── /// Registry name of the (our node). Required. [RegistryReference(typeof(As4ConnectionFactory))] public string? ConnectionFactory { get; set; } /// /// of the partner to send to (producer). May be an expression, e.g. /// ${header.partner}. The name must be one of the node's . /// [EndpointRole(EndpointRole.Producer)] public DynamicValue? Partner { get; set; } // ── Per-message business values (producer) ─────────────────────────────── /// Overrides the agreement's eb:Service; allowed only when the agreement permits it. [EndpointRole(EndpointRole.Producer)] public DynamicValue? Service { get; set; } /// Overrides the agreement's eb:Action; allowed only when the agreement permits it. [EndpointRole(EndpointRole.Producer)] public DynamicValue? Action { get; set; } /// eb:ConversationId. Default: a new id per message, or the redbAs4.conversationId header. [EndpointRole(EndpointRole.Producer)] public DynamicValue? ConversationId { get; set; } /// /// eb:RefToMessageId — set on the reply of a Two-Way / Push-and-Push exchange. Default: the /// redbAs4.refToMessageId header, else none. /// [EndpointRole(EndpointRole.Producer)] public DynamicValue? RefToMessageId { get; set; } /// /// Query of the partner's address, without the ?: Domibus serves its domains as /// /domibus?domain=name. The query of an as4 URI holds the endpoint's options, so the address /// query travels in this option, encoded as one value; As4.Send(url) moves it here from the URL. /// [EndpointRole(EndpointRole.Producer)] public string? AddressQuery { get; set; } /// Milliseconds to wait for the partner's HTTP response carrying the receipt. Default 60000. [EndpointRole(EndpointRole.Producer)] public int Timeout { get; set; } = 60000; /// /// Upper bound in bytes on the partner's HTTP response to a send (producer), the counterpart of /// on receipt. The response is read as a bounded stream: a larger one (a proxy's /// error page, a broken partner) is refused as an invalid receipt without being read into memory. /// Default . /// [EndpointRole(EndpointRole.Producer)] public long MaxResponseBodySize { get; set; } = DefaultMaxResponseBodySize; /// /// Defer the send to the enclosing .Transacted() block. eDelivery requires a synchronous receipt, /// so a sender always waits for the response and never defers: true fails when the URI is bound. /// [EndpointRole(EndpointRole.Producer)] public bool? Transacted { get; set; } // ── Receive server (consumer) ──────────────────────────────────────────── /// /// Name of an IIdempotentRepository registered with context.AddIdempotentRepository(name, repo) — /// the contract of the route-level IdempotentConsumer EIP and of the S3 consumer's option of the same name. /// It remembers received message ids: a message received again is answered with a receipt and not delivered /// twice (AS4 duplicate detection). Required on a receive endpoint — eDelivery AS4 1.16 mandates duplicate /// detection, and which store holds the ids (memory, redb, SQL) decides whether it survives a restart and /// works across cluster nodes, so it is named explicitly. /// /// The keys are eb:MessageId as it is, the way Domibus and Holodeck keep them: a message id is globally /// unique by the ebMS contract, whoever sends it. Give the endpoint a repository of its own — one shared with /// another route's business keys, or reused by a partner's colliding id, would answer a new message with the /// receipt of a duplicate and not deliver it. /// /// [EndpointRole(EndpointRole.Consumer)] [RegistryReference(typeof(IIdempotentRepository))] public string? IdempotentRepository { get; set; } /// /// Receive side: 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 and no /// ebMS signal, not answered with a receipt, and the sender resends it. Takes effect with a repository that keeps the /// confirmed state (the redb, SQL and in-memory ones do). Default 600000 (10 minutes). /// [EndpointRole(EndpointRole.Consumer)] public int InFlightClaimTimeout { get; set; } = 600_000; /// /// If true, the consumer sets the exchange body of a single-payload message to a Stream instead of a byte /// array, as streamBody does for the File, SFTP and S3 consumers. The stream is closed by /// Exchange.DisposeAsync(). Either way the connector itself spools a large request and its payloads to a /// temporary file (the core stream cache) instead of memory, and hands a payload to the route only after it is /// decrypted, its signature verified and it is decompressed. (default: false) /// [EndpointRole(EndpointRole.Consumer)] public bool StreamBody { get; set; } /// /// If true, the consumer always sets the exchange body to the list of , in the order of /// eb:PartInfo: one entry for a single payload, none for a message without payloads. Each entry keeps the /// Content-ID and the part properties, which a single payload handed as the body itself does not carry. The same /// list is what a send endpoint takes, so a route can pass a received message on as it came. Takes precedence over /// . (default: false) /// [EndpointRole(EndpointRole.Consumer)] public bool PayloadList { get; set; } /// Bind address of the receive server. Default 0.0.0.0. [EndpointRole(EndpointRole.Consumer)] public string Host { get; set; } = "0.0.0.0"; /// Listen port of the receive server. Default . [EndpointRole(EndpointRole.Consumer)] public int Port { get; set; } = DefaultPort; /// Serve over HTTPS. Set by the as4s scheme. public bool UseTls { get; set; } /// PFX the receive server presents over TLS; else the factory's. A TLS receiver with neither refuses to start. [EndpointRole(EndpointRole.Consumer)] public string? SslCertPath { get; set; } /// Password for . [EndpointRole(EndpointRole.Consumer)] [Sensitive] public string? SslCertPassword { get; set; } /// Whether the receive server asks partners for a TLS client certificate. [EndpointRole(EndpointRole.Consumer)] public As4ClientCertificateMode ClientCertificateMode { get; set; } = As4ClientCertificateMode.NoCertificate; /// Thumbprints (comma-separated) an accepted client certificate must match; null: any valid one. [EndpointRole(EndpointRole.Consumer)] public string? AllowedClientThumbprints { get; set; } /// Upper bound on a request body in bytes. Default . [EndpointRole(EndpointRole.Consumer)] public long MaxRequestBodySize { get; set; } = DefaultMaxRequestBodySize; /// /// Upper bound on the SOAP envelope in characters. Applies to the envelope only — payloads travel as /// attachments and are bounded by . Default . /// public long MaxEnvelopeCharacters { get; set; } = DefaultMaxEnvelopeCharacters; /// Maximum concurrent executions of this receiver's pipeline; 0 (default) = unlimited. [EndpointRole(EndpointRole.Consumer)] public int MaxConcurrentRequests { get; set; } /// Requests over the limit that wait for a permit (FIFO); 0 (default) = reject at once. [EndpointRole(EndpointRole.Consumer)] public int RequestQueueLimit { get; set; } /// Status code of a shed request. Default 503: an AS4 sender retries on it. [EndpointRole(EndpointRole.Consumer)] public int RejectStatusCode { get; set; } = 503; /// Retry-After of a shed request in seconds; 0 = not sent. Default 1. [EndpointRole(EndpointRole.Consumer)] public int RetryAfterSeconds { get; set; } = 1; /// public override void Validate() { if (string.IsNullOrWhiteSpace(ConnectionFactory)) throw new ArgumentException("AS4 endpoint requires 'connectionFactory': the registry name of an As4ConnectionFactory."); if (Port is < 1 or > 65535) throw new ArgumentOutOfRangeException(nameof(Port), Port, "AS4 port must be between 1 and 65535."); if (Timeout < 0) throw new ArgumentOutOfRangeException(nameof(Timeout), Timeout, "AS4 timeout must not be negative."); if (AddressQuery is not null && (AddressQuery.Length == 0 || AddressQuery.StartsWith('?') || AddressQuery.Contains('#'))) throw new ArgumentException("AS4 addressQuery is the query of the partner's address without '?' and without a fragment, " + "such as 'domain=name'."); if (MaxRequestBodySize <= 0) throw new ArgumentOutOfRangeException(nameof(MaxRequestBodySize), MaxRequestBodySize, "AS4 maxRequestBodySize must be positive."); if (MaxResponseBodySize <= 0) throw new ArgumentOutOfRangeException(nameof(MaxResponseBodySize), MaxResponseBodySize, "AS4 maxResponseBodySize must be positive."); if (MaxEnvelopeCharacters <= 0) throw new ArgumentOutOfRangeException(nameof(MaxEnvelopeCharacters), MaxEnvelopeCharacters, "AS4 maxEnvelopeCharacters must be positive."); // eDelivery AS4 1.16 fixes the receipt to the HTTP response of the same request, so a sender always waits for it: // the URI alone decides this, so it fails in Validate as RabbitMQ refuses ackMode=auto with transacted. if (Transacted == true) throw new ArgumentException("AS4 transacted=true is not supported: an AS4 send waits for its receipt in the response " + "and cannot be deferred to the end of a transaction."); if (ClientCertificateMode != As4ClientCertificateMode.NoCertificate && !UseTls) throw new ArgumentException("AS4 clientCertificateMode needs TLS: a client certificate is presented in the TLS handshake. Use the as4s scheme."); if (InFlightClaimTimeout < 1) throw new ArgumentOutOfRangeException(nameof(InFlightClaimTimeout), InFlightClaimTimeout, "AS4 inFlightClaimTimeout must be positive."); ConcurrencyLimitOptions.ValidateShape(MaxConcurrentRequests, RequestQueueLimit, RejectStatusCode, RetryAfterSeconds); } } Path: redb-route/redb.Route.As4/As4Enums.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.As4/As4Enums.cs ---- namespace redb.Route.As4; /// /// How a signature points at the signer's certificate (WS-Security X.509 Token Profile). eDelivery AS4 /// 1.16 asks implementations to support all three; is the most widely /// implemented. A receiver understands all three regardless of this setting: Holodeck B2B, for one, /// defaults to . /// public enum As4KeyReference { /// The certificate travels in a wsse:BinarySecurityToken the signature references. BinarySecurityToken, /// The certificate is named by issuer and serial number; the receiver must already hold it. IssuerSerial, /// The certificate is named by its Subject Key Identifier; the receiver must already hold it. KeyIdentifier, /// /// The certificate travels with its certification path in a wsse:BinarySecurityToken of type /// X509PKIPathv1 (WS-Security X.509 Token Profile §3.1.2), the authorities of /// first and our certificate last. For a receiver that /// trusts an authority instead of holding our certificate (eDelivery AS4 1.16 §4.3.3). /// PkiPath, } /// Whether the receive server asks the trading partner for a TLS client certificate. public enum As4ClientCertificateMode { /// No client certificate is requested (default). NoCertificate, /// A client certificate is requested but not required. AllowCertificate, /// A client certificate is required; the TLS handshake fails without one. RequireCertificate, } Path: redb-route/redb.Route.As4/As4ErrorCode.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.As4/As4ErrorCode.cs ---- namespace redb.Route.As4; /// Severity of an ebMS error (ebMS 3.0 Core §6.3). public enum As4ErrorSeverity { /// The message unit in error is not processed further. Failure, /// Processing continued; the partner is only informed. Warning, } /// /// An ebMS 3.0 error code (Core §6.7, AS4 profile §3) with its short description, category and default /// severity, and the fixed text we send to a partner for it. A received message never gets the text of one of /// our exceptions back (BR-4): that text names our files, connections and services; the partner gets this /// description and a reference to quote. /// public sealed record As4ErrorCode(string Code, string ShortDescription, string Category, As4ErrorSeverity Severity, string PartnerText) { /// EBMS:0001 — a value of the message is not recognized (unknown agreement, party, service, action). public static readonly As4ErrorCode ValueNotRecognized = new("EBMS:0001", "ValueNotRecognized", "Content", As4ErrorSeverity.Failure, "A value of the message header is not recognized for any agreement."); /// EBMS:0002 — a feature the message asks for is not supported. public static readonly As4ErrorCode FeatureNotSupported = new("EBMS:0002", "FeatureNotSupported", "Content", As4ErrorSeverity.Warning, "A feature the message asks for is not supported."); /// EBMS:0003 — values of the message contradict each other or the agreement. public static readonly As4ErrorCode ValueInconsistent = new("EBMS:0003", "ValueInconsistent", "Content", As4ErrorSeverity.Failure, "Values of the message are inconsistent."); /// EBMS:0004 — any other failure; for us, a failure of the receiving route. public static readonly As4ErrorCode Other = new("EBMS:0004", "Other", "Content", As4ErrorSeverity.Failure, "The message could not be processed."); /// EBMS:0005 — the receiving MSH could not be reached (reported locally by a sender). Not raised by this connector: a send that cannot connect is an HttpRequestException the route handles. public static readonly As4ErrorCode ConnectionFailure = new("EBMS:0005", "ConnectionFailure", "Communication", As4ErrorSeverity.Failure, "The receiving MSH could not be reached."); /// EBMS:0006 — a pulled partition channel is empty (pull only). Reserved for pull (phase 10, out of scope). public static readonly As4ErrorCode EmptyMessagePartitionChannel = new("EBMS:0006", "EmptyMessagePartitionChannel", "Communication", As4ErrorSeverity.Warning, "The message partition channel holds no message."); /// EBMS:0007 — the MIME structure does not match the header's payload references. public static readonly As4ErrorCode MimeInconsistency = new("EBMS:0007", "MimeInconsistency", "Unpackaging", As4ErrorSeverity.Failure, "The MIME parts do not match the payload references of the message header."); /// EBMS:0009 — the ebMS header is missing or malformed. public static readonly As4ErrorCode InvalidHeader = new("EBMS:0009", "InvalidHeader", "Unpackaging", As4ErrorSeverity.Failure, "The ebMS header is missing or malformed."); /// EBMS:0010 — the message does not match the processing mode of its agreement. public static readonly As4ErrorCode ProcessingModeMismatch = new("EBMS:0010", "ProcessingModeMismatch", "Processing", As4ErrorSeverity.Failure, "The message does not match the processing mode of its agreement."); /// EBMS:0011 — a payload referenced outside the message could not be used. public static readonly As4ErrorCode ExternalPayloadError = new("EBMS:0011", "ExternalPayloadError", "Content", As4ErrorSeverity.Failure, "Payloads outside the message are not supported."); /// EBMS:0101 — the signature (or anything it protects) did not verify. public static readonly As4ErrorCode FailedAuthentication = new("EBMS:0101", "FailedAuthentication", "Processing", As4ErrorSeverity.Failure, "The security check of the message failed."); /// EBMS:0102 — the message could not be decrypted. public static readonly As4ErrorCode FailedDecryption = new("EBMS:0102", "FailedDecryption", "Processing", As4ErrorSeverity.Failure, "The security check of the message failed."); /// EBMS:0103 — the message is not secured the way the agreement requires. public static readonly As4ErrorCode PolicyNoncompliance = new("EBMS:0103", "PolicyNoncompliance", "Processing", As4ErrorSeverity.Failure, "The message is not secured as the agreement requires."); /// EBMS:0201 — reliability processing failed. Not raised: reliability is the engine's redelivery. public static readonly As4ErrorCode DysfunctionalReliability = new("EBMS:0201", "DysfunctionalReliability", "Processing", As4ErrorSeverity.Failure, "Reliable messaging processing failed."); /// EBMS:0202 — the message could not be delivered to its consumer. Not raised today: a route failure is answered EBMS:0004 (Other). public static readonly As4ErrorCode DeliveryFailure = new("EBMS:0202", "DeliveryFailure", "Communication", As4ErrorSeverity.Failure, "The message could not be delivered."); /// EBMS:0301 — no receipt arrived for a message that required one (sender side). public static readonly As4ErrorCode MissingReceipt = new("EBMS:0301", "MissingReceipt", "Communication", As4ErrorSeverity.Failure, "No receipt was received for the message."); /// EBMS:0302 — a receipt arrived but does not prove receipt of what was sent (sender side). public static readonly As4ErrorCode InvalidReceipt = new("EBMS:0302", "InvalidReceipt", "Communication", As4ErrorSeverity.Failure, "The receipt does not match the message."); /// EBMS:0303 — a compressed payload could not be decompressed. public static readonly As4ErrorCode DecompressionFailure = new("EBMS:0303", "DecompressionFailure", "Communication", As4ErrorSeverity.Failure, "A payload could not be decompressed."); private static readonly IReadOnlyDictionary ByCode = new[] { ValueNotRecognized, FeatureNotSupported, ValueInconsistent, Other, ConnectionFailure, EmptyMessagePartitionChannel, MimeInconsistency, InvalidHeader, ProcessingModeMismatch, ExternalPayloadError, FailedAuthentication, FailedDecryption, PolicyNoncompliance, DysfunctionalReliability, DeliveryFailure, MissingReceipt, InvalidReceipt, DecompressionFailure, }.ToDictionary(c => c.Code, StringComparer.Ordinal); /// The known code named (EBMS:0009), or null for a code we do not know. public static As4ErrorCode? Find(string? code) => code is not null && ByCode.TryGetValue(code, out var known) ? known : null; } Path: redb-route/redb.Route.As4/As4Headers.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.As4/As4Headers.cs ---- namespace redb.Route.As4; /// /// Exchange header names of the AS4 connector. Everything is under : AS4 carries its /// business metadata inside eb:Messaging, not in HTTP headers, so there is no verbatim wire plane to /// mirror. /// /// Canonical planes (one source of truth per value, consumer and producer agree): /// /// HTTP — transport only; not copied onto the exchange, except the caller's /// address () and traceparent (into the span). /// SOAP header — wsse:Security is consumed by the connector; its outcome /// is and . /// eb:Messaging — the main plane: … /// . On send, only these names are read, by an explicit list; nothing else from the /// exchange reaches the partner's archive. /// eb:MessageProperties — + property name, /// both ways. /// MIME part — per-payload properties travel on the payload object; the /// exchange's Message.ContentType is the original (decompressed) MimeType. /// /// /// public static class As4Headers { /// Prefix of every AS4 header on the exchange. public const string Prefix = "redbAs4."; // ── eb:Messaging plane ─────────────────────────────────────────────────── /// eb:MessageInfo/eb:MessageId. Set by the producer before the first attempt, so a redelivery resends the same id. public const string MessageId = Prefix + "messageId"; /// eb:MessageInfo/eb:RefToMessageId. public const string RefToMessageId = Prefix + "refToMessageId"; /// eb:MessageInfo/eb:Timestamp of a received message. public const string Timestamp = Prefix + "timestamp"; /// eb:CollaborationInfo/eb:ConversationId. public const string ConversationId = Prefix + "conversationId"; /// Sender eb:PartyId. public const string FromPartyId = Prefix + "fromPartyId"; /// Sender eb:PartyId/@type. public const string FromPartyIdType = Prefix + "fromPartyIdType"; /// Sender eb:Role. public const string FromRole = Prefix + "fromRole"; /// Recipient eb:PartyId. public const string ToPartyId = Prefix + "toPartyId"; /// Recipient eb:PartyId/@type. public const string ToPartyIdType = Prefix + "toPartyIdType"; /// Recipient eb:Role. public const string ToRole = Prefix + "toRole"; /// eb:CollaborationInfo/eb:Service. public const string Service = Prefix + "service"; /// eb:Service/@type. public const string ServiceType = Prefix + "serviceType"; /// eb:CollaborationInfo/eb:Action. public const string Action = Prefix + "action"; /// eb:CollaborationInfo/eb:AgreementRef. public const string AgreementRef = Prefix + "agreementRef"; /// eb:AgreementRef/@pmode. public const string PModeId = Prefix + "pmode"; // ── eb:MessageProperties plane ─────────────────────────────────────────── /// Prefix of message properties: redbAs4.property.originalSender is eb:Property[@name='originalSender']. public const string PropertyPrefix = Prefix + "property."; /// /// Prefix of the @type of a message property: redbAs4.propertyType.originalSender is the type /// attribute of eb:Property[@name='originalSender']. Absent when the property has no type. /// public const string PropertyTypePrefix = Prefix + "propertyType."; /// The eDelivery four-corner originalSender property (mandatory unless the agreement says otherwise). public const string OriginalSender = PropertyPrefix + "originalSender"; /// The eDelivery four-corner finalRecipient property (mandatory unless the agreement says otherwise). public const string FinalRecipient = PropertyPrefix + "finalRecipient"; // ── Computed by the connector ──────────────────────────────────────────── /// Registry name of the partner the message was matched to (receive) or sent to (send). public const string Partner = Prefix + "partner"; /// True when the signature was present and verified against the partner's certificate. public const string SignatureValid = Prefix + "signatureValid"; /// Thumbprint of the certificate that signed the received message. public const string SignerThumbprint = Prefix + "signerThumbprint"; /// Address of the peer that sent the request. public const string RemoteAddress = Prefix + "remoteAddress"; /// Thumbprint of the TLS client certificate the partner presented (mutual TLS). public const string ClientCertThumbprint = Prefix + "clientCertThumbprint"; /// Subject of the TLS client certificate. public const string ClientCertSubject = Prefix + "clientCertSubject"; /// Expiry of the TLS client certificate, UTC, round-trip format. public const string ClientCertNotAfter = Prefix + "clientCertNotAfter"; /// True when a receipt was received and verified, including its non-repudiation references (send). public const string ReceiptValid = Prefix + "receiptValid"; /// eb:MessageId of the receipt signal (send). public const string ReceiptMessageId = Prefix + "receiptMessageId"; /// True if is an AS4 connector header. public static bool IsRedbHeader(string key) => key.StartsWith(Prefix, StringComparison.OrdinalIgnoreCase); } Path: redb-route/redb.Route.As4/As4Leg.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.As4/As4Leg.cs ---- namespace redb.Route.As4; /// /// The business side of one leg of an agreement: which eb:Service and eb:Action a user /// message on that leg carries. The request leg lives on itself; the reply leg of a /// Two-Way / Push-and-Push exchange (required by eDelivery AS4 1.16) is . /// public sealed class As4Leg { /// eb:CollaborationInfo/eb:Service. public string? Service { get; set; } /// eb:Service/@type; omitted when null. public string? ServiceType { get; set; } /// eb:CollaborationInfo/eb:Action. public string? Action { get; set; } /// Throws when the leg cannot describe a user message. /// Name of the agreement and leg, for the error text. internal void Validate(string owner) { if (string.IsNullOrWhiteSpace(Service)) throw new InvalidOperationException($"{owner}: Service is required."); if (string.IsNullOrWhiteSpace(Action)) throw new InvalidOperationException($"{owner}: Action is required."); } } Path: redb-route/redb.Route.As4/As4Node.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.As4/As4Node.cs ---- using System.Security.Cryptography.X509Certificates; using redb.Route.As4.Security; using redb.Route.Abstractions; using redb.Route.Extensions; namespace redb.Route.As4; /// /// The resolved, validated view of one : the factory and its partners by /// name, looked up in the route context once, when an endpoint starts. Resolving at start rather than at /// endpoint creation is deliberate: the registry may be filled after the routes are defined, and a /// misconfigured node then stops the route from starting instead of failing the first message a partner sends. /// internal sealed class As4Node { private As4Node(string name, As4ConnectionFactory factory, IReadOnlyDictionary partners, IReadOnlyList signingPath) { Name = name; Factory = factory; Partners = partners; SigningPath = signingPath; } /// Registry name of the factory. public string Name { get; } /// The node configuration. public As4ConnectionFactory Factory { get; } /// The node's partners, keyed by (ordinal). public IReadOnlyDictionary Partners { get; } /// /// Our certificate with its authorities from , outermost /// first: the certification path a token carries. Ordered once, when the node is /// resolved; the factory validation has made sure every authority of the chain is on it. /// public IReadOnlyList SigningPath { get; } /// /// Looks up the factory and validates it with its partners together. Throws with the offending name on /// anything missing, of the wrong type, invalid, or ambiguous on receipt. /// public static As4Node Resolve(IRouteContext? context, string factoryName) { ArgumentException.ThrowIfNullOrWhiteSpace(factoryName); var factory = context.GetRequiredFromRegistry(factoryName); factory.Validate(factoryName); var partners = new Dictionary(StringComparer.Ordinal); foreach (var partner in factory.Partners) { partner.Validate(); partners[partner.Name!] = partner; } EnsureUnambiguous(factoryName, partners); return new As4Node(factoryName, factory, partners, PkiPath.Order(factory.SigningCertificate!, factory.SigningCertificateChain)); } /// /// The agreement a received user message belongs to, matched as Domibus and Holodeck match a P-Mode: the /// message must be addressed to our party; the sender, service and action must be those of the partner's /// request leg or reply leg; an agreement reference, when the partner declares one, must be the message's. /// No match is ; more than one — which node validation already /// prevents — . /// public (As4Partner Partner, bool IsReplyLeg) MatchInbound(Messaging.UserMessage message) { ArgumentNullException.ThrowIfNull(message); // eDelivery AS4 1.16 REQUIRES one eb:PartyId per side. Refused as phase4 (CEF profile validator) and Holodeck // (P-Mode match by the whole set) refuse it; picking one of several would pick an arbitrary sender. foreach (var (side, party) in new[] { ("From", message.From), ("To", message.To) }) if (party.PartyIds.Count > 1) throw new As4ProcessingException(As4ErrorCode.ProcessingModeMismatch, $"PartyInfo/{side} carries {party.PartyIds.Count} eb:PartyId elements; eDelivery allows one."); // An agreement here is a push leg on the default MPC. Another mpc names a leg we do not have: EBMS:0001, as Domibus // drops a leg whose defaultMpc does not match (CachingPModeProvider.checkMpcMismatch); no mpc means the default. if (message.Mpc is { } mpc && mpc != Messaging.EbmsNamespaces.DefaultMpc) throw new As4ProcessingException(As4ErrorCode.ValueNotRecognized, $"the message is for mpc '{mpc}'; this node exchanges on the default MPC only."); if (!message.To.PartyIds.Any(p => p.Value == Factory.OurPartyId && p.Type == Factory.OurPartyIdType)) throw new As4ProcessingException(As4ErrorCode.ValueNotRecognized, $"the message is addressed to '{string.Join(", ", message.To.PartyIds.Select(p => p.Value))}', not to this node."); var c = message.CollaborationInfo; var matches = new List<(As4Partner, bool)>(); foreach (var partner in Partners.Values) { if (!message.From.PartyIds.Any(p => p.Value == partner.PartyId && p.Type == partner.PartyIdType)) continue; if (partner.AgreementRef is not null && (c.AgreementRef is null || c.AgreementRef.Value != partner.AgreementRef || c.AgreementRef.Type != partner.AgreementRefType)) continue; if (Leg(partner.Service, partner.ServiceType, partner.Action)) matches.Add((partner, false)); else if (partner.ReplyLeg is { } reply && Leg(reply.Service, reply.ServiceType, reply.Action)) matches.Add((partner, true)); } return matches.Count switch { 1 => matches[0], 0 => throw new As4ProcessingException(As4ErrorCode.ValueNotRecognized, $"no agreement of node '{Name}' matches sender '{string.Join(", ", message.From.PartyIds.Select(p => p.Value))}', " + $"service '{c.Service.Value}', action '{c.Action}', agreement '{c.AgreementRef?.Value}'."), _ => throw new As4ProcessingException(As4ErrorCode.ProcessingModeMismatch, $"agreements {string.Join(", ", matches.Select(m => m.Item1.Name))} of node '{Name}' all match the message."), }; bool Leg(string? service, string? serviceType, string? action) => c.Service.Value == service && c.Service.Type == serviceType && c.Action == action; } /// /// Two partners that an incoming user message could not tell apart would make receipt depend on /// dictionary order. A message is matched on everything its agreement pins — agreement reference, sender, /// service and action, as Domibus and Holodeck match a P-Mode — so that combination must be unique across /// the node, for every leg. One agreement shared by many partners is fine: the sender tells them apart. So is a /// reply leg with the service and action of its own request leg — a Two-Way exchange that answers under the same /// values, as the eDelivery conformance tests run it: either way the message is that partner's. /// private static void EnsureUnambiguous(string factoryName, IReadOnlyDictionary partners) { var byKey = new Dictionary(StringComparer.Ordinal); void Claim(As4Partner p, string partnerName, string? service, string? serviceType, string? action, string leg) { var key = string.Join('\n', p.AgreementRef, p.AgreementRefType, p.PartyId, p.PartyIdType, service, serviceType, action); if (byKey.TryGetValue(key, out var other) && other != partnerName) throw new InvalidOperationException( $"AS4 connection factory '{factoryName}': partners '{other}' and '{partnerName}' ({leg}) share agreement, " + $"sender, service and action ('{p.AgreementRef}', '{p.PartyId}', '{service}', '{action}'); " + "a received message could not be matched to one agreement."); byKey[key] = partnerName; } foreach (var (name, p) in partners) { Claim(p, name, p.Service, p.ServiceType, p.Action, "request leg"); if (p.ReplyLeg is { } reply) Claim(p, name, reply.Service, reply.ServiceType, reply.Action, "reply leg"); } } } Path: redb-route/redb.Route.As4/As4Partner.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.As4/As4Partner.cs ---- using System.Security.Cryptography.X509Certificates; namespace redb.Route.As4; /// /// The agreement with one trading partner: who they are, what we exchange, how it is secured. This is the /// partner half of an ebMS P-Mode; the node half (our identity and keys) is . /// /// A partner lives in and is named by : the /// name a send endpoint gives in partner= and the value of the redbAs4.partner header on /// receipt. In Route-XML it is a nested <bean> or a <ref> in the node's Partners list. /// /// /// Defaults follow the eDelivery AS4 1.16 common profile: every message is signed, its payloads encrypted /// and compressed, and the receiver answers with a signed non-repudiation receipt in the HTTP response. /// Those are not options: the profile mandates them. /// /// public sealed class As4Partner { /// Default eb:Role of the side that sends the first message of an exchange. public const string InitiatorRole = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/initiator"; /// Default eb:Role of the side that receives it. public const string ResponderRole = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/responder"; // ── Identity ───────────────────────────────────────────────────────────── /// Name of the agreement within its node: what partner= refers to. Required, unique per node. public string? Name { get; set; } /// The partner's eb:PartyId. Exactly one per side, as eDelivery requires. public string? PartyId { get; set; } /// /// The partner's MSH address (P-Mode Protocol.Address): http:// or https://, with a query where the /// partner has one, such as a Domibus domain (/domibus?domain=name). A send endpoint without an address of its /// own (as4:?partner=..., As4.Send()) posts here, so a partner chosen per message by an expression gets /// its own address. Null: the send endpoint gives the address; giving it in both places is refused. /// public string? Address { get; set; } /// The partner's eb:PartyId/@type; omitted when null. public string? PartyIdType { get; set; } /// Our eb:Role in exchanges with this partner. Default: initiator. public string OurRole { get; set; } = InitiatorRole; /// The partner's eb:Role. Default: responder. public string PartnerRole { get; set; } = ResponderRole; // ── Agreement ──────────────────────────────────────────────────────────── /// eb:AgreementRef; omitted when null. When present on both sides it selects the agreement on receipt. public string? AgreementRef { get; set; } /// eb:AgreementRef/@type; omitted when null. public string? AgreementRefType { get; set; } /// eb:AgreementRef/@pmode; omitted when null. public string? PModeId { get; set; } /// eb:Service of the request leg. public string? Service { get; set; } /// eb:Service/@type of the request leg; omitted when null. public string? ServiceType { get; set; } /// eb:Action of the request leg. public string? Action { get; set; } /// Whether a route may send a different eb:Service than (option or header). public bool AllowOverrideService { get; set; } /// Whether a route may send a different eb:Action than (option or header). public bool AllowOverrideAction { get; set; } /// /// The reply leg of a Two-Way / Push-and-Push exchange: the user message the responder pushes back with /// eb:RefToMessageId set to the request. Null for one-way agreements. /// public As4Leg? ReplyLeg { get; set; } // ── Security ───────────────────────────────────────────────────────────── /// /// The partner's certificates that verify its signatures. More than one while the partner rotates its /// key; a signature by any of them is the partner's. /// public IList PartnerSigningCertificates { get; set; } = new List(); /// /// Certification authorities the partner's signing certificate must chain to, instead of pinning the certificate /// itself in : roots or intermediate authorities ("certificate path /// prefixes", eDelivery AS4 1.16 §4.3.3). With these set, the partner's messages and receipts must carry the signing /// certificate in an X509PKIPathv1 security token; the path is validated up to one of the anchors — every /// signature, every validity period, every issuer a certification authority. A message that references its /// certificate another way is refused, even when the certificate would chain. Set one or the other, not both. /// public IList PartnerTrustAnchors { get; set; } = new List(); /// /// Certificate policy OIDs (RFC 5280 §4.2.1.4) the partner's signing certificate, and every authority between it /// and the trust anchor, must assert; anyPolicy in a certificate satisfies each. Used with /// . Empty for none. /// public IList PartnerCertificatePolicies { get; set; } = new List(); /// The trust of an agreement that names authorities; null when the signing certificate is pinned. internal Security.PkiPathTrust? PkiPathTrust => PartnerTrustAnchors is { Count: > 0 } ? new Security.PkiPathTrust(PartnerTrustAnchors.ToList(), (PartnerCertificatePolicies ?? []).ToList()) : null; /// The partner's certificate we encrypt payloads for. public X509Certificate2? PartnerEncryptionCertificate { get; set; } /// How our signatures reference our certificate. Default: . public As4KeyReference KeyReference { get; set; } = As4KeyReference.BinarySecurityToken; /// Signature algorithm URI. Default RSA-SHA256. public string SignatureAlgorithm { get; set; } = As4Algorithms.RsaSha256; /// Digest algorithm URI for signature references. Default SHA-256. public string DigestAlgorithm { get; set; } = As4Algorithms.Sha256; /// Payload encryption algorithm URI. Default AES-128-GCM. public string DataEncryptionAlgorithm { get; set; } = As4Algorithms.Aes128Gcm; /// Key transport algorithm URI. Default RSA-OAEP (XML Encryption 1.1). public string KeyTransportAlgorithm { get; set; } = As4Algorithms.RsaOaep; /// Mask generation function URI for key transport. Default MGF1-SHA256. public string MaskGenerationAlgorithm { get; set; } = As4Algorithms.Mgf1Sha256; /// Digest URI for OAEP key transport. Default SHA-256. public string KeyTransportDigestAlgorithm { get; set; } = As4Algorithms.Sha256; /// /// Lifetime of a wsu:Timestamp in the messages and receipts we sign; null (default) signs none. The eDelivery /// AS4 1.16 policy of Domibus, the reference implementation (eDeliveryAS4Policy.xml), has no /// IncludeTimestamp and a Strict layout, so a timestamp fails it; set a lifetime for a partner whose /// policy asks for one. A received timestamp is always checked, whatever this setting. /// public TimeSpan? TimestampTtl { get; set; } /// /// Clock skew accepted when checking the partner's wsu:Timestamp: how far in the future its Created /// may lie and how long past its Expires (WSS4J futureTimeToLive). Default 5 minutes. /// public TimeSpan TimestampTolerance { get; set; } = TimeSpan.FromMinutes(5); /// Default : 5 minutes, WSS4J's timeStampTTL (300 s). public static readonly TimeSpan DefaultTimestampTimeToLive = TimeSpan.FromMinutes(5); /// /// How old the Created of a received wsu:Timestamp may be (WSS4J timeStampTTL, CXF /// ws-security.timestamp.timeToLive). It bounds a replayed message whatever its Expires says. /// Default . /// public TimeSpan TimestampTimeToLive { get; set; } = DefaultTimestampTimeToLive; /// /// Gzip the payloads we send (AS4 compression; eDelivery AS4 1.16 requires support for it). Default true. /// Received payloads are decompressed whenever their part properties say so, whatever this setting. /// public bool CompressPayloads { get; set; } = true; /// /// Whether every message of this agreement must carry the originalSender and finalRecipient message /// properties, on sending and on receipt. They belong to the Four Corner Topology profile enhancement of eDelivery /// AS4 1.16 (§4.1.2); the common profile does not ask for them, so a point-to-point agreement sets this to false. /// Default true. /// public bool RequireFourCornerProperties { get; set; } = true; /// Throws when the agreement cannot be used; called when an endpoint of its node starts. public void Validate() { var owner = $"AS4 partner '{Name}'"; if (string.IsNullOrWhiteSpace(PartyId)) throw new InvalidOperationException($"{owner}: PartyId is required."); if (string.IsNullOrWhiteSpace(OurRole) || string.IsNullOrWhiteSpace(PartnerRole)) throw new InvalidOperationException($"{owner}: OurRole and PartnerRole are required."); if (Address is not null && (!Uri.TryCreate(Address, UriKind.Absolute, out var address) || (address.Scheme != Uri.UriSchemeHttp && address.Scheme != Uri.UriSchemeHttps) || address.Fragment.Length > 0)) throw new InvalidOperationException($"{owner}: Address is an absolute http:// or https:// address without a fragment."); new As4Leg { Service = Service, ServiceType = ServiceType, Action = Action }.Validate($"{owner} request leg"); ReplyLeg?.Validate($"{owner} reply leg"); var pinned = PartnerSigningCertificates is { Count: > 0 }; var anchored = PartnerTrustAnchors is { Count: > 0 }; if (pinned == anchored) throw new InvalidOperationException( $"{owner}: set either PartnerSigningCertificates (the partner's certificate is pinned) or PartnerTrustAnchors " + "(the partner presents a certification path to an authority) — every AS4 message and receipt is signed, and one of the two says by whom."); if ((pinned && PartnerSigningCertificates!.Any(c => c is null)) || (anchored && PartnerTrustAnchors!.Any(c => c is null))) throw new InvalidOperationException($"{owner}: a certificate in PartnerSigningCertificates or PartnerTrustAnchors is null."); if (PartnerCertificatePolicies is { Count: > 0 }) { if (!anchored) throw new InvalidOperationException($"{owner}: PartnerCertificatePolicies applies to a certification path; set PartnerTrustAnchors."); if (PartnerCertificatePolicies.Any(string.IsNullOrWhiteSpace)) throw new InvalidOperationException($"{owner}: a certificate policy OID in PartnerCertificatePolicies is empty."); } if (PartnerEncryptionCertificate is null) throw new InvalidOperationException($"{owner}: PartnerEncryptionCertificate is required — every payload is encrypted."); if (!As4Algorithms.IsSupportedSignature(SignatureAlgorithm)) throw new InvalidOperationException($"{owner}: unsupported signature algorithm '{SignatureAlgorithm}'."); if (!As4Algorithms.IsSupportedDigest(DigestAlgorithm)) throw new InvalidOperationException($"{owner}: unsupported digest algorithm '{DigestAlgorithm}'."); if (!As4Algorithms.IsSupportedDataEncryption(DataEncryptionAlgorithm)) throw new InvalidOperationException($"{owner}: unsupported data encryption algorithm '{DataEncryptionAlgorithm}'."); if (!As4Algorithms.IsSupportedKeyTransport(KeyTransportAlgorithm)) throw new InvalidOperationException($"{owner}: unsupported key transport algorithm '{KeyTransportAlgorithm}'."); if (!As4Algorithms.IsSupportedMaskGeneration(MaskGenerationAlgorithm)) throw new InvalidOperationException($"{owner}: unsupported mask generation function '{MaskGenerationAlgorithm}'."); if (!As4Algorithms.IsSupportedDigest(KeyTransportDigestAlgorithm)) throw new InvalidOperationException($"{owner}: unsupported key transport digest '{KeyTransportDigestAlgorithm}'."); if (TimestampTtl is { } ttl && ttl <= TimeSpan.Zero) throw new InvalidOperationException($"{owner}: TimestampTtl must be positive when set."); if (TimestampTolerance < TimeSpan.Zero) throw new InvalidOperationException($"{owner}: TimestampTolerance must not be negative."); if (TimestampTimeToLive <= TimeSpan.Zero) throw new InvalidOperationException($"{owner}: TimestampTimeToLive must be positive."); } } Path: redb-route/redb.Route.As4/As4Payload.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.As4/As4Payload.cs ---- namespace redb.Route.As4; /// /// One payload of an AS4 message. /// /// On receipt: a message with a single payload — the common case — has it as the exchange body itself /// (byte[], or a with streamBody=true) and its media type as /// Message.ContentType; a message with several has a list of these as the body, for a route to /// .Split(). With payloadList=true the body is always that list. /// /// /// On sending: a body that is a list of these is sent as that many payloads, the eb:PartInfo elements in the /// order of the list (the first is the leading business document); an empty list sends a message without payloads. /// /// /// /// Content-ID of the MIME part, without angle brackets. On receipt null for a payload carried in the SOAP body; on /// sending null lets the connector generate one. /// /// The original (uncompressed) media type: the MimeType part property. /// /// On receipt the decrypted, decompressed content: a readable, seekable stream, in memory or spooled to a temporary /// file when large. The exchange owns it and closes it when it ends (ExchangeResources.ReleaseWithExchange); read it within /// the route, not after. On sending it is copied and left open; a seekable one is read from its start. /// /// /// The eb:PartProperties, by name. On sending they are written next to MimeType and /// CompressionType, which the connector sets itself: CharacterSet for an XML payload, for one. /// public sealed record As4Payload(string? ContentId, string ContentType, Stream Content, IReadOnlyDictionary Properties); Path: redb-route/redb.Route.As4/As4Producer.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.As4/As4Producer.cs ---- using System.Diagnostics; using System.Net.Http.Headers; using System.Security.Cryptography; using System.Text; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; using redb.Route.As4.Compression; using redb.Route.Configuration; using redb.Route.As4.Messaging; using redb.Route.As4.Mime; using redb.Route.As4.Security; using redb.Route.As4.Signals; using redb.Route.Core; using redb.Route.Telemetry; namespace redb.Route.As4; /// /// AS4 sender (One-Way / Push, eDelivery AS4 1.16): builds the user message from the exchange and the agreement, /// compresses, signs and encrypts the payload, posts it, and requires a signed non-repudiation receipt in the /// response that names exactly what was signed. The outcome is on exchange.Out (InOut), as the AS2 /// producer puts its MDN there. /// /// Failures are exceptions the route handles: when the partner refuses /// the message, when no valid receipt proves receipt — the one to redeliver /// on. The message id is written to redbAs4.messageId before the first attempt, so a redelivery of the /// same exchange resends the same message. /// /// internal sealed class As4Producer : ConnectableProducer { private readonly As4Endpoint _endpoint; private readonly As4EndpointOptions _options; private HttpClient? _http; private StreamCacheOptions _spool = new(); public As4Producer(As4Endpoint endpoint, As4EndpointOptions options) { _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); _options = options ?? throw new ArgumentNullException(nameof(options)); } /// The resolved node; set when the producer has started. internal As4Node? Node { get; private set; } /// protected override IEndpoint ProducerEndpoint => _endpoint; // The name reaches the started/stopped logs; a partner URL may carry userinfo no [Sensitive] reaches. /// protected override string ProducerName => _endpoint.PartnerUrl is { } url ? $"as4:{EndpointUri.Sanitize(url)}" : EndpointUri.Sanitize(_endpoint.Uri.NormalizedKey); /// protected override Task ConnectAsync(CancellationToken ct) { var node = As4Node.Resolve(_endpoint.Context, _options.ConnectionFactory!); _spool = As4Spool.Options(_endpoint.Context); if (_options.Partner is not { } partner) throw new InvalidOperationException($"AS4 send endpoint {_endpoint.Uri} requires 'partner': the Name of one of its node's partners."); // A static partner name is checked now; an expression can only be checked per message. if (!partner.IsDynamic) { var name = partner.Resolve(null!); // static: the exchange is not read if (string.IsNullOrWhiteSpace(name) || !node.Partners.TryGetValue(name, out var agreement)) throw new InvalidOperationException( $"AS4 send endpoint {_endpoint.Uri}: partner '{name}' is not a partner of connection factory '{node.Name}'."); AddressOf(agreement); } // One client per producer, as the AS2 and HTTP producers keep. _http = new HttpClient(CreateHandler(node.Factory)) { Timeout = _options.Timeout > 0 ? TimeSpan.FromMilliseconds(_options.Timeout) : Timeout.InfiniteTimeSpan, }; Node = node; return Task.CompletedTask; } /// /// Reads the partner's response within : refused on a declared /// length over it, else read as a stream that stops one byte past it. A receipt or an error is a few KB; anything /// larger (a proxy's error page, a broken partner) is not one, and is not buffered to find out. /// 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 As4ReceiptException(As4ErrorCode.InvalidReceipt, messageId, $"the response declares {declared} bytes, over maxResponseBodySize {limit}."); 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 As4ReceiptException(As4ErrorCode.InvalidReceipt, messageId, $"the response is over maxResponseBodySize {limit} bytes."); buffer.Write(chunk, 0, read); } return buffer.ToArray(); } /// /// Builds the request of : each payload of the body spooled (a large one to a temporary /// file), compressed per the agreement, signed, encrypted and written to a spool the HTTP content streams from. /// private async Task BuildAsync(IExchange exchange, As4Node node, As4Partner partner, string messageId, CancellationToken ct) { var host = node.Factory.ExternalHostName; var refToMessageId = Resolve(_options.RefToMessageId, exchange) ?? exchange.In.GetHeader(As4Headers.RefToMessageId); var (service, serviceType, action) = BusinessValues(exchange, partner, isReply: refToMessageId is not null); var conversationId = Resolve(_options.ConversationId, exchange) ?? exchange.In.GetHeader(As4Headers.ConversationId) ?? Guid.NewGuid().ToString("D"); var properties = MessageProperties(exchange, partner); // One part per payload, eb:PartInfo in the order the route gave them: the first is the leading business // document (eDelivery AS4 1.16 §3.2.3). var parts = new List(); try { var partInfos = new List(); foreach (var payload in Payloads(exchange.In, partner)) { var contentId = payload.ContentId ?? "part-" + Guid.NewGuid().ToString("N") + "@" + host; if (parts.Any(p => p.ContentId == contentId)) throw new InvalidOperationException( $"AS4 message to partner '{partner.Name}' has two payloads with Content-ID '{contentId}'."); var part = new SwaPart(contentId, payload.ContentType, await As4Spool.RunAsync(_spool, (output, token) => WritePayloadAsync(payload.Content, output, token), ct).ConfigureAwait(false)); parts.Add(part); IReadOnlyList described = partner.CompressPayloads ? As4Compression.Compress(part, _spool) : [new Property(As4Compression.MimeTypeProperty, part.ContentType, null)]; partInfos.Add(new PartInfo(WsSecurityNames.CidUri(contentId), [.. described, .. payload.Properties])); } var user = new UserMessage( new MessageInfo(DateTimeOffset.UtcNow, messageId, refToMessageId), new Party([new PartyId(node.Factory.OurPartyId!, node.Factory.OurPartyIdType)], partner.OurRole), new Party([new PartyId(partner.PartyId!, partner.PartyIdType)], partner.PartnerRole), new CollaborationInfo( partner.AgreementRef is null ? null : new AgreementRef(partner.AgreementRef, partner.AgreementRefType, partner.PModeId), new Service(service, serviceType), action, conversationId), properties, partInfos, null); using var message = SwaMessage.Create(MessagingWriter.CreateEnvelope(user), _spool); foreach (var part in parts) message.Parts.Add(part.ContentId, part); var signed = As4SecurityEngine.Sign(message, node.Factory.SigningCertificate!, partner.KeyReference, partner.TimestampTtl, DateTimeOffset.UtcNow, node.SigningPath); As4SecurityEngine.Encrypt(message, partner.PartnerEncryptionCertificate!, partner.KeyReference); string? wireType = null; var body = As4Spool.Run(_spool, output => wireType = message.WriteTo(output)); return new As4Transmission(messageId, partner.Name!, exchange.In.Body, body, wireType!, signed); } finally { foreach (var part in parts) part.Dispose(); } } /// What the route asks to send as one payload: its content as the exchange gave it. private readonly record struct OutboundPayload(string? ContentId, string ContentType, object? Content, IReadOnlyList Properties); /// /// The payloads of the message. A body that is a list of (or one of them) is sent as that /// many payloads in that order, each with its Content-ID and part properties; an empty list is a message without /// payloads. Any other body is one payload with a generated Content-ID and the media type of the message. /// private static IReadOnlyList Payloads(IMessage message, As4Partner partner) { IEnumerable? listed = message.Body switch { As4Payload one => [one], IEnumerable many => many, _ => null, }; if (listed is null) return [new OutboundPayload(null, message.ContentType ?? "application/octet-stream", message.Body, [])]; var payloads = new List(); foreach (var payload in listed) { if (payload is null) throw new InvalidOperationException($"AS4 message to partner '{partner.Name}': a payload in the body list is null."); if (payload.ContentId is { } id && (id.Length == 0 || id.Any(c => char.IsWhiteSpace(c) || c is '<' or '>'))) throw new InvalidOperationException( $"AS4 message to partner '{partner.Name}': Content-ID '{id}' is not usable; give it without angle brackets and spaces, or null."); if (string.IsNullOrWhiteSpace(payload.ContentType)) throw new InvalidOperationException($"AS4 message to partner '{partner.Name}': a payload has no ContentType."); if (payload.Properties is not null && payload.Properties.TryGetValue(PayloadConsistency.CharacterSetProperty, out var characterSet) && !PayloadConsistency.IsCharacterSetName(characterSet)) throw new InvalidOperationException( $"AS4 message to partner '{partner.Name}': CharacterSet '{characterSet}' is not an encoding name of XML 1.0 §4.3.3 (UTF-8, ISO-8859-1, ...)."); // MimeType and CompressionType describe what the connector does to the part; they are its own to write. var properties = (payload.Properties ?? new Dictionary()) .Where(p => p.Key is not (As4Compression.MimeTypeProperty or As4Compression.CompressionTypeProperty) && p.Value is not null) .Select(p => new Property(p.Key, p.Value, null)) .OrderBy(p => p.Name, StringComparer.Ordinal) .ToList(); payloads.Add(new OutboundPayload(payload.ContentId, payload.ContentType, payload.Content, properties)); } return payloads; } /// /// The HTTP handler of a sender: the TLS versions the node allows (TLS 1.2 and 1.3 by default, as Holodeck, phase4 /// and Domibus offer), and our client certificate for partners that require mutual TLS. /// internal static HttpClientHandler CreateHandler(As4ConnectionFactory node) { ArgumentNullException.ThrowIfNull(node); var handler = new HttpClientHandler { SslProtocols = node.SslProtocols }; if (node.ClientCertificate is { } clientCertificate) handler.ClientCertificates.Add(clientCertificate); return handler; } /// 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 node = Node!; var partner = ResolvePartner(exchange, node); var address = AddressOf(partner); var host = node.Factory.ExternalHostName; // The id is fixed on the exchange before the first attempt: a redelivery resends the same message. var messageId = exchange.In.GetHeader(As4Headers.MessageId); if (string.IsNullOrWhiteSpace(messageId)) { messageId = MessageIdFactory.New(host); exchange.In.Headers[As4Headers.MessageId] = messageId; } // Pinned keys are still checked for their validity period before anything is sent, on every attempt (Domibus // sender/receiver certificate validation on sending): a partner would refuse the message, and a receipt could not // be trusted either. var now = DateTimeOffset.UtcNow; if (CertificateValidity.Problem(node.Factory.SigningCertificate!, now, $"AS4 node '{node.Name}': our signing certificate", node.Factory.Revocation) is { } ours) throw new InvalidOperationException(ours); if (CertificateValidity.Problem(partner.PartnerEncryptionCertificate!, now, $"AS4 partner '{partner.Name}': the encryption certificate", node.Factory.Revocation) is { } theirs) throw new InvalidOperationException(theirs); // A redelivery on this exchange resends the message of the first attempt, byte for byte. if (exchange.Properties.TryGetValue(As4Transmission.Property, out var stored) && stored is As4Transmission prior && prior.IsFor(messageId, partner.Name!, exchange.In.Body)) { Logger?.LogDebug("AS4 message {MessageId}: redelivery sends the transmission of the first attempt.", messageId); } else { prior = await BuildAsync(exchange, node, partner, messageId, ct).ConfigureAwait(false); exchange.Properties[As4Transmission.Property] = prior; ExchangeResources.ReleaseWithExchange(exchange, prior); } var transmission = prior; var sent = transmission.Signed; // The send span on the core contract (EnableTelemetry=false opens none); its context is written to the request, // replacing one already there: HttpClient writes none of its own when the header is present. using var activity = RouteTelemetryExtensions.StartTransportSpan( _endpoint.Context, $"{partner.Name} send", ActivityKind.Client, "messaging.system", "as4", _endpoint.Uri.NormalizedKey, destination: EndpointUri.Sanitize(address), operation: "send"); using var request = new HttpRequestMessage(HttpMethod.Post, address) { Content = transmission.Content() }; RouteTelemetryExtensions.InjectTraceContext(activity, request, static (r, name, value) => { r.Headers.Remove(name); r.Headers.TryAddWithoutValidation(name, value); }); _endpoint.RecordBytesOut(transmission.Body.Length); byte[] responseBody; string? responseType; SignalMessage receipt; try { using var response = await ReceiptWithin(_http!.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, ct), messageId, partner, ct).ConfigureAwait(false); responseBody = await ReceiptWithin(ReadBoundedAsync(response, messageId, ct), messageId, partner, ct).ConfigureAwait(false); responseType = response.Content.Headers.ContentType?.ToString(); receipt = ReadReceipt(messageId, response, responseBody, responseType, partner, sent); } catch (Exception e) when (e is not OperationCanceledException) { // Unreachable, no receipt, an ebMS error or a receipt that does not verify: the send failed. activity.RecordFailure(e); throw; } var outMessage = new Message(responseBody) { ContentType = responseType }; outMessage.Headers[As4Headers.MessageId] = messageId; outMessage.Headers[As4Headers.Partner] = partner.Name; outMessage.Headers[As4Headers.ReceiptValid] = true; outMessage.Headers[As4Headers.ReceiptMessageId] = receipt.MessageInfo.MessageId; exchange.Out = outMessage; exchange.Pattern = ExchangePattern.InOut; Logger?.LogDebug("AS4 message {MessageId} sent to partner {Partner}; receipt {ReceiptId} verified.", messageId, partner.Name, receipt.MessageInfo.MessageId); } // ── Receipt ────────────────────────────────────────────────────────────── /// /// Whether the answer is an eb:SignalMessage about (or about no message) with no /// receipt, error or pull request in it: what is left of a receipt when the receipt is taken out. /// private static bool IsSignalWithoutReceipt(System.Xml.XmlDocument envelope, string messageId) { var signals = envelope.GetElementsByTagName("SignalMessage", EbmsNamespaces.Eb).OfType().ToList(); return signals.Count > 0 && signals.All(signal => { var children = signal.ChildNodes.OfType().Where(c => c.NamespaceURI == EbmsNamespaces.Eb).ToList(); if (children.Any(c => c.LocalName is "Receipt" or "Error" or "PullRequest")) return false; var refTo = children.FirstOrDefault(c => c.LocalName == "MessageInfo")?.ChildNodes.OfType() .FirstOrDefault(c => c.LocalName == "RefToMessageId" && c.NamespaceURI == EbmsNamespaces.Eb)?.InnerText.Trim(); return refTo is null || refTo == messageId; }); } /// /// The start of a textual answer that is not an ebMS signal (a proxy's or firewall's page often names who refused /// and a support reference), for the error text: at most 160 characters, whitespace collapsed, control characters /// dropped. Empty for a binary answer. /// private static string AnswerExcerpt(byte[] body, string contentType) { if (!contentType.StartsWith("text/", StringComparison.OrdinalIgnoreCase)) return ""; var text = System.Text.Encoding.UTF8.GetString(body, 0, Math.Min(body.Length, 4096)); var excerpt = new System.Text.StringBuilder(160); var space = false; foreach (var c in text) { if (excerpt.Length >= 160) break; if (char.IsWhiteSpace(c)) { space = excerpt.Length > 0; continue; } if (char.IsControl(c)) continue; if (space) { excerpt.Append(' '); space = false; } excerpt.Append(c); } return excerpt.Length == 0 ? "" : $" ({contentType.Split(';')[0].Trim()}: \"{excerpt}\")"; } /// /// The verified receipt for in the partner's response, or the exception that /// says why there is none: the partner's own error signal, a response without a signal (missing receipt), /// or a receipt that does not verify or does not echo what we signed (invalid receipt). /// private SignalMessage ReadReceipt(string messageId, HttpResponseMessage response, byte[] body, string? contentType, As4Partner partner, IReadOnlyList sent) { // A signal may come with any status (Holodeck answers an ebMS error with 200); only an empty body is "nothing". if (body.Length == 0 || string.IsNullOrWhiteSpace(contentType)) throw new As4ReceiptException(As4ErrorCode.MissingReceipt, messageId, $"the partner answered HTTP {(int)response.StatusCode} without a signal."); SwaMessage? read = null; SwaMessage answer; EbmsMessaging messaging; try { answer = read = SwaMessage.Read(contentType, body, _options.MaxEnvelopeCharacters); messaging = MessagingReader.Read(answer.Envelope); } catch (As4ProcessingException e) when (read is not null && IsSignalWithoutReceipt(read.Envelope, messageId)) { // A signal about our message that holds neither a receipt nor an error: no receipt came (reception awareness, // EBMS:0301), as the conformance test driver simulates a lost receipt (AS4_CP_TA15). throw new As4ReceiptException(As4ErrorCode.MissingReceipt, messageId, $"the partner's HTTP {(int)response.StatusCode} answer is a signal without a receipt.", e); } catch (Exception e) when (e is As4ProcessingException or FormatException or System.Xml.XmlException or MimeKit.ParseException) { throw new As4ReceiptException(As4ErrorCode.InvalidReceipt, messageId, $"the partner's HTTP {(int)response.StatusCode} answer is not an ebMS signal{AnswerExcerpt(body, contentType)}.", e); } // Signals about our message; an error that names no message at all is about it too — a partner that could not // parse our header cannot quote its id. var signals = messaging.SignalMessages .Where(s => s.MessageInfo.RefToMessageId == messageId || s.Errors.Any(e => e.RefToMessageInError == messageId) || (s.MessageInfo.RefToMessageId is null && s.Errors.Count > 0 && s.Errors.All(e => e.RefToMessageInError is null))) .ToList(); var failure = signals.SelectMany(s => s.Errors).FirstOrDefault(e => e.Severity == As4ErrorSeverity.Failure); if (failure is not null) throw new As4ErrorSignalException(messageId, failure.ErrorCode, failure.ShortDescription, failure.Description, failure.ErrorDetail); var receipt = signals.FirstOrDefault(s => s.IsReceipt) ?? throw new As4ReceiptException(As4ErrorCode.MissingReceipt, messageId, $"the partner's HTTP {(int)response.StatusCode} answer carries no receipt for it."); try { As4SecurityEngine.Verify(answer, partner.PartnerSigningCertificates.ToList(), partner.TimestampTolerance, DateTimeOffset.UtcNow, Node!.Factory.Revocation, partner.TimestampTimeToLive, partner.PkiPathTrust); } catch (CryptographicException e) { throw new As4ReceiptException(As4ErrorCode.InvalidReceipt, messageId, "the receipt's signature does not verify.", e); } if (!Receipts.ProvesReceiptOf(receipt, sent)) throw new As4ReceiptException(As4ErrorCode.InvalidReceipt, messageId, "the receipt's non-repudiation information does not name what was signed."); return receipt; } // ── Building the message ───────────────────────────────────────────────── private As4Partner ResolvePartner(IExchange exchange, As4Node node) { var name = _options.Partner!.Value.Resolve(exchange); if (string.IsNullOrWhiteSpace(name) || !node.Partners.TryGetValue(name, out var partner)) throw new InvalidOperationException( $"AS4 send endpoint {_endpoint.Uri}: partner '{name}' is not a partner of connection factory '{node.Name}'."); return partner; } /// /// Where the message goes: the address of the send endpoint, or the partner's . Exactly /// one of them: two would leave the reader of the route to guess which one is used. /// private string AddressOf(As4Partner partner) { if (_endpoint.PartnerUrl is { } url) { if (partner.Address is not null) throw new InvalidOperationException( $"AS4 send endpoint {EndpointUri.Sanitize(_endpoint.Uri.NormalizedKey)} gives an address and partner '{partner.Name}' has " + "one in its Address: give it in one place."); return url; } return partner.Address ?? throw new InvalidOperationException( $"AS4 send endpoint {EndpointUri.Sanitize(_endpoint.Uri.NormalizedKey)} has no address and partner '{partner.Name}' has no Address: " + "set the partner's Address, or send to as4s://host[:port]/path."); } /// /// Service and action: the agreement's request leg, or its reply leg when the message answers another one /// (Two-Way / Push-and-Push). An option or header may override them only where the agreement allows it. /// private (string Service, string? ServiceType, string Action) BusinessValues(IExchange exchange, As4Partner partner, bool isReply) { string service, action; string? serviceType; if (isReply) { var leg = partner.ReplyLeg ?? throw new InvalidOperationException( $"AS4 partner '{partner.Name}': the message answers another one (refToMessageId), but the agreement has no ReplyLeg."); (service, serviceType, action) = (leg.Service!, leg.ServiceType, leg.Action!); } else { (service, serviceType, action) = (partner.Service!, partner.ServiceType, partner.Action!); } var serviceOverride = Resolve(_options.Service, exchange) ?? exchange.In.GetHeader(As4Headers.Service); if (serviceOverride is not null && serviceOverride != service) { if (!partner.AllowOverrideService) throw new InvalidOperationException( $"AS4 partner '{partner.Name}' does not allow overriding the service ('{service}' asked to be '{serviceOverride}')."); service = serviceOverride; } var actionOverride = Resolve(_options.Action, exchange) ?? exchange.In.GetHeader(As4Headers.Action); if (actionOverride is not null && actionOverride != action) { if (!partner.AllowOverrideAction) throw new InvalidOperationException( $"AS4 partner '{partner.Name}' does not allow overriding the action ('{action}' asked to be '{actionOverride}')."); action = actionOverride; } return (service, serviceType, action); } /// /// eb:MessageProperties from the exchange headers under — the only /// exchange headers that reach the partner, each with the type a header under /// gives it. The eDelivery four-corner properties are required unless /// the agreement says otherwise (). /// private static IReadOnlyList MessageProperties(IExchange exchange, As4Partner partner) { var headers = exchange.In.Headers; var properties = headers .Where(h => h.Key.StartsWith(As4Headers.PropertyPrefix, StringComparison.Ordinal) && h.Value is not null) .Select(h => { var name = h.Key[As4Headers.PropertyPrefix.Length..]; var type = headers.TryGetValue(As4Headers.PropertyTypePrefix + name, out var t) && t?.ToString() is { Length: > 0 } text ? text : null; return new Property(name, h.Value!.ToString()!, type); }) .OrderBy(p => p.Name, StringComparer.Ordinal) .ToList(); if (!partner.RequireFourCornerProperties) return properties; foreach (var required in new[] { As4Headers.OriginalSender, As4Headers.FinalRecipient }) { var name = required[As4Headers.PropertyPrefix.Length..]; if (!properties.Any(p => p.Name == name && p.Value.Length > 0)) throw new InvalidOperationException( $"AS4 message to partner '{partner.Name}' has no '{name}' property: set the header '{required}' (eDelivery four-corner model)."); } return properties; } /// /// Writes the body into the payload spool. A is copied, not buffered, and not closed: the /// exchange owns it (the ownsStream rule of the stream connectors). A seekable one is read from its start, /// so a redelivery sends the same bytes (the SttProducer precedent); a forward-only one is read once — to redeliver /// it, the route caches it with .StreamCaching(). /// private static async Task WritePayloadAsync(object? body, Stream output, CancellationToken ct) { switch (body) { case null: return; case byte[] bytes: await output.WriteAsync(bytes, ct).ConfigureAwait(false); return; case string text: await output.WriteAsync(Encoding.UTF8.GetBytes(text), ct).ConfigureAwait(false); return; case Stream stream: if (stream.CanSeek) stream.Position = 0; await stream.CopyToAsync(output, ct).ConfigureAwait(false); return; default: // As the AS2 and HTTP producers do: any other body is sent as its UTF-8 text. await output.WriteAsync(Encoding.UTF8.GetBytes(BodyText.Of(body)), ct).ConfigureAwait(false); return; } } /// /// Awaits one step of the exchange with the partner. A timeout is a missing receipt, not a cancellation: the /// engine's OnException and dead letter channel always rethrow , so an /// unconverted timeout could never be redelivered (the McpProducer precedent). A cancelled /// stays a cancellation. /// private async Task ReceiptWithin(Task step, string messageId, As4Partner partner, CancellationToken ct) { try { return await step.ConfigureAwait(false); } catch (OperationCanceledException e) when (!ct.IsCancellationRequested) { throw new As4ReceiptException(As4ErrorCode.MissingReceipt, messageId, $"no response from partner '{partner.Name}' within {_options.Timeout} ms.", e); } } private static string? Resolve(DynamicValue? value, IExchange exchange) => value is { } v && v.Resolve(exchange) is { Length: > 0 } resolved ? resolved : null; } Path: redb-route/redb.Route.As4/As4Transmission.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.As4/As4Transmission.cs ---- using System.Net; using System.Xml; namespace redb.Route.As4; /// /// One signed, encrypted AS4 request as it went on the wire, kept on its exchange for redelivery. A retransmission is /// the same message (AS4 reception awareness): Domibus answers a duplicate with the stored receipt of the first /// transmission, whose non-repudiation digests match only the first signature, so a rebuilt message — new timestamp, /// new signature — could never have its receipt verified. The exchange owns it and releases it when it ends /// (ExchangeResources.ReleaseWithExchange); another exchange, even with the same message id, builds its own. /// internal sealed class As4Transmission : IAsyncDisposable { /// Exchange property that holds the transmission between attempts. public const string Property = "redbAs4.transmission"; public As4Transmission(string messageId, string partner, object? source, Stream body, string contentType, IReadOnlyList signed) { MessageId = messageId; Partner = partner; Source = source; Body = body; ContentType = contentType; Signed = signed; } /// The eb:MessageId it carries. public string MessageId { get; } /// The agreement it was built for. public string Partner { get; } /// The exchange body it was built from; a route that replaced the body sends a new message. public object? Source { get; } /// The request body, readable and seekable (the core stream cache). public Stream Body { get; } /// The request Content-Type. public string ContentType { get; } /// The ds:Reference elements we signed — what the receipt's non-repudiation information must name. public IReadOnlyList Signed { get; } /// Whether a redelivery of to with is this message. public bool IsFor(string messageId, string partner, object? source) => MessageId == messageId && Partner == partner && ReferenceEquals(Source, source); /// The request content; each attempt reads the body from its start and leaves it open for the next. public HttpContent Content() { var content = new ReplayContent(Body); content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(ContentType); content.Headers.ContentLength = Body.Length; return content; } /// public ValueTask DisposeAsync() => Body.DisposeAsync(); /// Content over a stream it does not own: StreamContent would close it with the request. private sealed class ReplayContent(Stream body) : HttpContent { protected override async Task SerializeToStreamAsync(Stream stream, TransportContext? context) { body.Position = 0; await body.CopyToAsync(stream).ConfigureAwait(false); } protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context, CancellationToken cancellationToken) { body.Position = 0; return body.CopyToAsync(stream, cancellationToken); } protected override bool TryComputeLength(out long length) { length = body.Length; return true; } } } Path: redb-route/redb.Route.As4/Compression/As4Compression.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.As4/Compression/As4Compression.cs ---- using System.IO.Compression; using redb.Route.As4.Messaging; using redb.Route.As4.Mime; using redb.Route.Configuration; namespace redb.Route.As4.Compression; /// /// AS4 compression (profile §3.1, eDelivery AS4 1.16): an attachment is gzipped before it is signed and /// encrypted; eb:PartProperties carry CompressionType=application/gzip and the original /// MimeType. The receiver decompresses after decryption and signature verification. /// internal static class As4Compression { /// The only compression type AS4 defines. public const string Gzip = "application/gzip"; /// Part property naming the compression. public const string CompressionTypeProperty = "CompressionType"; /// Part property naming the original media type. public const string MimeTypeProperty = "MimeType"; /// /// Gzips in place and returns the part properties that describe it: the original /// media type and the compression type. /// public static IReadOnlyList Compress(SwaPart part, StreamCacheOptions spool) { ArgumentNullException.ThrowIfNull(spool); ArgumentNullException.ThrowIfNull(part); var original = part.ContentType; part.Replace(As4Spool.Run(spool, output => { using (var gzip = new GZipStream(output, CompressionLevel.Optimal, leaveOpen: true)) part.OpenRead().CopyTo(gzip); // From .NET 9 on GZipStream writes nothing at all for empty content, and zero bytes are not a gzip stream: // a receiver refuses them (java.util.zip: EOFException). An empty payload is the empty member. if (output.Length == 0) output.Write(EmptyGzip); })); part.ContentType = Gzip; return [new Property(MimeTypeProperty, original, null), new Property(CompressionTypeProperty, Gzip, null)]; } /// /// Decompresses in place when says it is compressed, and /// gives it the original media type. More than of output — the shape of /// a compression bomb — and anything that does not inflate are ; /// a compression type other than gzip, or one without MimeType, is . /// Returns whether the part was compressed. /// public static bool Decompress(SwaPart part, PartInfo partInfo, long maxDecompressedBytes, StreamCacheOptions spool) { ArgumentNullException.ThrowIfNull(spool); ArgumentNullException.ThrowIfNull(part); ArgumentNullException.ThrowIfNull(partInfo); var compression = partInfo.PropertyValue(CompressionTypeProperty); if (compression is null) return false; if (compression != Gzip) throw new As4ProcessingException(As4ErrorCode.ValueInconsistent, $"part '{part.ContentId}' names compression '{compression}'; AS4 defines only {Gzip}."); var mimeType = partInfo.PropertyValue(MimeTypeProperty) ?? throw new As4ProcessingException(As4ErrorCode.ValueInconsistent, $"compressed part '{part.ContentId}' does not name its original MimeType."); Stream inflated; try { inflated = As4Spool.Run(spool, output => { var compressed = part.OpenRead(); using var input = new GZipStream(compressed, CompressionMode.Decompress, leaveOpen: true); var buffer = new byte[81920]; long total = 0; var crc = 0xFFFFFFFFu; int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { total += read; if (total > maxDecompressedBytes) throw new As4ProcessingException(As4ErrorCode.DecompressionFailure, $"part '{part.ContentId}' inflates beyond {maxDecompressedBytes} bytes."); crc = Crc32.Append(crc, buffer.AsSpan(0, read)); output.Write(buffer, 0, read); } // GZipStream ends quietly when its input stops in the middle of the stream: a truncated payload would // inflate to a part of the document and be acknowledged. Whether everything arrived is in the gzip // trailers (RFC 1952 §2.3.1: CRC-32 and length of the content). A stream of one member, which is what // AS4 senders write, is settled by its last eight bytes; anything else is walked member by member. if (!TrailerMatches(compressed, ~crc, total) && !GzipMembers.AreWhole(compressed, total)) throw new As4ProcessingException(As4ErrorCode.DecompressionFailure, $"part '{part.ContentId}' is truncated or damaged: its gzip trailer does not match the inflated content."); }); } catch (InvalidDataException e) { throw new As4ProcessingException(As4ErrorCode.DecompressionFailure, $"part '{part.ContentId}' is not valid gzip.", e); } part.Replace(inflated); part.ContentType = mimeType; return true; } /// /// Whether the last eight bytes of are the gzip trailer of content with this CRC-32 /// and length: both little-endian, the length modulo 2^32. True only for a whole stream of one member: the trailer /// of a stream of several members describes its last one alone, and decides for those. /// private static bool TrailerMatches(Stream compressed, uint crc, long length) { const int headerAndTrailer = 10 + 8; if (compressed.Length < headerAndTrailer) return false; Span trailer = stackalloc byte[8]; compressed.Position = compressed.Length - trailer.Length; compressed.ReadExactly(trailer); return System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(trailer) == crc && System.Buffers.Binary.BinaryPrimitives.ReadUInt32LittleEndian(trailer[4..]) == unchecked((uint)length); } /// /// A gzip stream of no content (RFC 1952): the ten-byte header, an empty final deflate block, CRC-32 and length zero. /// private static ReadOnlySpan EmptyGzip => [0x1F, 0x8B, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]; } Path: redb-route/redb.Route.As4/Compression/GzipMembers.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.As4/Compression/GzipMembers.cs ---- using System.Buffers.Binary; using Org.BouncyCastle.Utilities.Zlib; namespace redb.Route.As4.Compression; /// /// Walks a gzip stream member by member (RFC 1952) and says whether it is whole: every member has a well-formed /// header, a deflate stream that reaches its end, and a trailer whose CRC-32 and length are those of what it inflated; /// nothing follows the last member. /// /// GZipStream inflates a stream of any number of members but ends without an exception when its input stops in /// the middle of one, and it does not say where a member ends. This reader does: it inflates with an inflater that /// reports how much input it consumed, so the trailer of each member is found and checked. /// /// internal static class GzipMembers { private const int FlagHeaderCrc = 0x02; private const int FlagExtra = 0x04; private const int FlagName = 0x08; private const int FlagComment = 0x10; private const int FlagReserved = 0xE0; /// /// Whether , read from its start, is one or more whole gzip members that inflate to /// exactly bytes in total. /// public static bool AreWhole(Stream compressed, long expectedLength) { ArgumentNullException.ThrowIfNull(compressed); compressed.Position = 0; var input = new Input(compressed); var window = new byte[81920]; long total = 0; var members = 0; Span trailer = stackalloc byte[8]; while (input.Fill()) { if (!ReadHeader(input)) return false; var inflater = new ZStream(); if (inflater.inflateInit(true) != JZlib.Z_OK) // nowrap: a raw deflate stream, as gzip carries it return false; var crc = 0xFFFFFFFFu; long length = 0; try { while (true) { if (input.Available == 0 && !input.Fill()) return false; // the input ends inside the deflate stream inflater.next_in = input.Buffer; inflater.next_in_index = input.Position; inflater.avail_in = input.Available; inflater.next_out = window; inflater.next_out_index = 0; inflater.avail_out = window.Length; var result = inflater.inflate(JZlib.Z_NO_FLUSH); var consumed = inflater.next_in_index - input.Position; var produced = inflater.next_out_index; input.Position = inflater.next_in_index; crc = Crc32.Append(crc, window.AsSpan(0, produced)); length += produced; if (total + length > expectedLength) return false; if (result == JZlib.Z_STREAM_END) break; if (result != JZlib.Z_OK || (consumed == 0 && produced == 0)) return false; // not deflate, or no progress with input and room at hand } } finally { inflater.inflateEnd(); } if (!input.Read(trailer) || BinaryPrimitives.ReadUInt32LittleEndian(trailer) != ~crc || BinaryPrimitives.ReadUInt32LittleEndian(trailer[4..]) != unchecked((uint)length)) return false; total += length; members++; } return members > 0 && total == expectedLength; } /// Reads one member header (RFC 1952 §2.3); false when it is not one or the input ends inside it. private static bool ReadHeader(Input input) { Span fixedPart = stackalloc byte[10]; if (!input.Read(fixedPart) || fixedPart[0] != 0x1F || fixedPart[1] != 0x8B || fixedPart[2] != 8) return false; var flags = fixedPart[3]; if ((flags & FlagReserved) != 0) return false; if ((flags & FlagExtra) != 0) { Span size = stackalloc byte[2]; if (!input.Read(size) || !input.Skip(BinaryPrimitives.ReadUInt16LittleEndian(size))) return false; } if ((flags & FlagName) != 0 && !input.SkipPastZero()) return false; if ((flags & FlagComment) != 0 && !input.SkipPastZero()) return false; if ((flags & FlagHeaderCrc) != 0 && !input.Skip(2)) return false; return true; } /// A buffer over the compressed stream that the inflater and the header and trailer readers share. private sealed class Input(Stream source) { public byte[] Buffer { get; } = new byte[81920]; public int Position { get; set; } private int _end; public int Available => _end - Position; /// Makes at least one byte available; false at the end of the stream. public bool Fill() { if (Available > 0) return true; Position = 0; _end = source.Read(Buffer, 0, Buffer.Length); return _end > 0; } public bool Read(Span destination) { for (var i = 0; i < destination.Length; i++) { if (!Fill()) return false; destination[i] = Buffer[Position++]; } return true; } public bool Skip(int count) { while (count > 0) { if (!Fill()) return false; var step = Math.Min(count, Available); Position += step; count -= step; } return true; } public bool SkipPastZero() { while (Fill()) if (Buffer[Position++] == 0) return true; return false; } } } /// CRC-32 of gzip (ISO 3309, reflected polynomial 0xEDB88320). internal static class Crc32 { private static readonly uint[] Table = BuildTable(); private static uint[] BuildTable() { var table = new uint[256]; for (uint i = 0; i < table.Length; i++) { var value = i; for (var bit = 0; bit < 8; bit++) value = (value & 1) != 0 ? 0xEDB88320u ^ (value >> 1) : value >> 1; table[i] = value; } return table; } /// Continues the running value (start with 0xFFFFFFFF, finish with its complement). public static uint Append(uint crc, ReadOnlySpan data) { foreach (var b in data) crc = Table[(crc ^ b) & 0xFF] ^ (crc >> 8); return crc; } } Path: redb-route/redb.Route.As4/Exceptions/As4ProcessingException.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.As4/Exceptions/As4ProcessingException.cs ---- namespace redb.Route.As4; /// /// A received AS4 message cannot be processed for a reason ebMS names with a code. The receiver answers it with /// an eb:Error carrying and its fixed partner text; /// — the detail — is ours and goes to the log only (BR-4). /// public class As4ProcessingException : Exception { /// Creates the exception. /// The ebMS error code to answer with. /// What exactly was wrong, for our log; never sent to the partner. /// The underlying failure, if any. public As4ProcessingException(As4ErrorCode code, string detail, Exception? innerException = null) : base($"{code.Code} {code.ShortDescription}: {detail}", innerException) { Code = code ?? throw new ArgumentNullException(nameof(code)); Detail = detail; } /// The ebMS error code. public As4ErrorCode Code { get; } /// What exactly was wrong, for our log. public string Detail { get; } } Path: redb-route/redb.Route.As4/Exceptions/As4SignalExceptions.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.As4/Exceptions/As4SignalExceptions.cs ---- namespace redb.Route.As4; /// /// The partner answered our message with an ebMS error of severity failure. Carries the partner's /// code and texts as sent; a route handles it with OnException<As4ErrorSignalException>(). /// public sealed class As4ErrorSignalException : Exception { /// Creates the exception from the partner's error. public As4ErrorSignalException(string messageId, string errorCode, string? shortDescription, string? description, string? detail) : base($"The partner refused AS4 message '{messageId}' with {errorCode} {shortDescription}: {description ?? detail}") { MessageId = messageId; ErrorCode = errorCode; ShortDescription = shortDescription; Description = description; ErrorDetail = detail; } /// Our message the error refers to. public string MessageId { get; } /// The ebMS error code, e.g. EBMS:0010. public string ErrorCode { get; } /// eb:Error/@shortDescription. public string? ShortDescription { get; } /// eb:Error/eb:Description. public string? Description { get; } /// eb:Error/eb:ErrorDetail. public string? ErrorDetail { get; } } /// /// No receipt proves that the partner received our message: none arrived (), /// or the one that did is not valid for it (). This is the exception a route /// redelivers on — OnException<As4ReceiptException>().MaximumRedeliveries(n) — and the message id stays /// the same on every attempt, so the partner sees a resend, not a new message. /// public sealed class As4ReceiptException : As4ProcessingException { /// Creates the exception. public As4ReceiptException(As4ErrorCode code, string messageId, string detail, Exception? innerException = null) : base(code, $"message '{messageId}': {detail}", innerException) => MessageId = messageId; /// Our message the receipt was expected for. public string MessageId { get; } } Path: redb-route/redb.Route.As4/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.As4/Extensions/ServiceCollectionExtensions.cs ---- using Microsoft.Extensions.DependencyInjection; using redb.Route.Extensions; using redb.Route.Http; namespace redb.Route.As4; /// Registration of the AS4 transport in a DI container. public static class ServiceCollectionExtensions { /// /// Registers the so that as4: and as4s: URIs resolve, sharing one /// Kestrel host with every other HTTP-based connector of the process. /// /// services.AddRedbRoute(route => /// { /// route.Services.AddRedbRouteAs4(); /// route.AddRouteBuilder<MyRoutes>(); /// }); /// /// public static IServiceCollection AddRedbRouteAs4(this IServiceCollection services) { services.AddRedbRouteHttpHosting(); services.AddSingleton(); services.AddRouteContextConfigurator((sp, context) => { var component = sp.GetRequiredService(); component.ServerManager = sp.GetRequiredService(); context.AddComponent(component); // registers as4 + as4s, sets Context + Logger }); return services; } } Path: redb-route/redb.Route.As4/Fluent/As4.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.As4/Fluent/As4.cs ---- using System.Globalization; using System.Text; namespace redb.Route.As4.Fluent; /// /// Entry point of the AS4 fluent DSL. /// /// // Receive server: accepts every partner of the node and matches each message to one agreement /// From(As4.Receive("/as4/in").Port(4090).Tls().ConnectionFactory("node").IdempotentRepository("as4-in")) /// .To("direct://inbound"); /// /// // Send to a partner: the address is the URI, the agreement is the registry /// From("direct://outbound") /// .To(As4.Send("https://ap.partner.example/as4").ConnectionFactory("node").Partner("acme")); /// /// public static class As4 { /// AS4 receive server on the given HTTP path. public static As4Builder Receive(string path) => new(As4BuilderMode.Receive, path); /// AS4 sender posting to the given partner URL. public static As4Builder Send(string url) { ArgumentException.ThrowIfNullOrWhiteSpace(url); return new(As4BuilderMode.Send, url); } /// /// AS4 sender posting to the of its partner: as4:?partner=.... A partner chosen /// per message by an expression gets its own address. /// public static As4Builder Send() => new(As4BuilderMode.Send, ""); } /// Which side of the exchange a builder produces. internal enum As4BuilderMode { /// Receive server (consumer). Receive, /// Sender (producer). Send, } /// /// Fluent builder of AS4 endpoint URIs. Receive: as4:/path?host=..&port=.., the path kept intact. /// Send: as4[s]://host[:port]/path, with HTTPS mapped onto the as4s scheme. /// public sealed class As4Builder { private readonly As4BuilderMode _mode; private readonly string _target; private readonly List<(string Key, string Value)> _options = []; private bool _useTls; internal As4Builder(As4BuilderMode mode, string target) { _mode = mode; _target = target ?? throw new ArgumentNullException(nameof(target)); } /// Registry name of the node (). Required. public As4Builder ConnectionFactory(string name) => Set("connectionFactory", name); /// Registry name of the partner to send to (send only); may be an expression such as ${header.partner}. public As4Builder Partner(string nameOrExpression) => Set("partner", nameOrExpression); /// Overrides the agreement's eb:Service (send only; the agreement must allow it). public As4Builder Service(string valueOrExpression) => Set("service", valueOrExpression); /// Overrides the agreement's eb:Action (send only; the agreement must allow it). public As4Builder Action(string valueOrExpression) => Set("action", valueOrExpression); /// eb:ConversationId of sent messages (send only). public As4Builder ConversationId(string valueOrExpression) => Set("conversationId", valueOrExpression); /// eb:RefToMessageId — the reply of a Two-Way / Push-and-Push exchange (send only). public As4Builder RefToMessageId(string valueOrExpression) => Set("refToMessageId", valueOrExpression); /// Milliseconds to wait for the partner's response carrying the receipt (send only). public As4Builder Timeout(int milliseconds) => Set("timeout", milliseconds.ToString(CultureInfo.InvariantCulture)); /// Named IIdempotentRepository that remembers received message ids (receive only, required). public As4Builder IdempotentRepository(string name) => Set("idempotentRepository", name); /// /// Receive endpoint: 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 As4Builder InFlightClaimTimeout(int milliseconds) => Set("inFlightClaimTimeout", milliseconds.ToString(CultureInfo.InvariantCulture)); /// Hand a single payload to the route as a Stream instead of byte[] (receive only). public As4Builder StreamBody() => Set("streamBody", "true"); /// Always hand the payloads to the route as a list of As4Payload, with Content-IDs and part properties (receive only). public As4Builder PayloadList() => Set("payloadList", "true"); /// Bind host of the receive server (receive only). public As4Builder Host(string host) => Set("host", host); /// Listen port of the receive server (receive only). public As4Builder Port(int port) => Set("port", port.ToString(CultureInfo.InvariantCulture)); /// /// Serve the receive endpoint over TLS (receive only). Omit the certificate to take it from the node's /// connection factory; a TLS receiver that finds none refuses to start. /// public As4Builder Tls(string? certPath = null, string? certPassword = null) { _useTls = true; if (certPath is not null) Set("sslCertPath", certPath); if (certPassword is not null) Set("sslCertPassword", certPassword); return this; } /// Ask partners for a TLS client certificate (receive only; needs ). public As4Builder ClientCertificate(As4ClientCertificateMode mode, string? allowedThumbprints = null) { Set("clientCertificateMode", mode.ToString()); if (allowedThumbprints is not null) Set("allowedClientThumbprints", allowedThumbprints); return this; } /// /// Admission limit (receive only): at most concurrent pipeline executions; /// overflow beyond the optional FIFO is shed before any MIME or crypto work. /// public As4Builder MaxConcurrentRequests(int max, int queue = 0) { Set("maxConcurrentRequests", max.ToString(CultureInfo.InvariantCulture)); if (queue > 0) Set("requestQueueLimit", queue.ToString(CultureInfo.InvariantCulture)); return this; } /// Status code of a request shed by the admission limit (receive only). Default 503: an AS4 sender retries on it. public As4Builder RejectStatusCode(int statusCode) => Set("rejectStatusCode", statusCode.ToString(CultureInfo.InvariantCulture)); /// Retry-After of a shed request in seconds; 0 = not sent (receive only). public As4Builder RetryAfterSeconds(int seconds) => Set("retryAfterSeconds", seconds.ToString(CultureInfo.InvariantCulture)); /// Upper bound on a request body in bytes (receive only). public As4Builder MaxRequestBodySize(long bytes) => Set("maxRequestBodySize", bytes.ToString(CultureInfo.InvariantCulture)); /// Upper bound on the SOAP envelope in characters (receive only); payloads are not counted. public As4Builder MaxEnvelopeCharacters(long characters) => Set("maxEnvelopeCharacters", characters.ToString(CultureInfo.InvariantCulture)); /// Builds the AS4 URI string. public string Build() => _mode == As4BuilderMode.Receive ? BuildReceive() : BuildSend(); private As4Builder Set(string key, string value) { ArgumentNullException.ThrowIfNull(value); _options.RemoveAll(o => o.Key == key); _options.Add((key, value)); return this; } private string BuildReceive() { var path = _target.StartsWith('/') ? _target : "/" + _target; var sb = new StringBuilder(_useTls ? "as4s:" : "as4:").Append(path); AppendQuery(sb, '?'); return sb.ToString(); } private string BuildSend() { if (_target.Length == 0) { var own = new StringBuilder("as4:"); AppendQuery(own, '?'); return own.ToString(); } var scheme = "as4"; var rest = _target; if (rest.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) { scheme = "as4s"; rest = rest["https://".Length..]; } else if (rest.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) { rest = rest["http://".Length..]; } else if (rest.StartsWith("as4s://", StringComparison.OrdinalIgnoreCase)) { scheme = "as4s"; rest = rest["as4s://".Length..]; } else if (rest.StartsWith("as4://", StringComparison.OrdinalIgnoreCase)) { rest = rest["as4://".Length..]; } // The query of an as4: URI holds the endpoint's options, as http:'s does: the address's own query (Domibus // domains, ?domain=name) travels in the addressQuery option, as one encoded value. if (rest.Contains('#')) throw new ArgumentException($"AS4 partner address '{_target}' has a fragment; a partner address has none.", nameof(_target)); var query = rest.IndexOf('?'); var addressQuery = query >= 0 ? rest[(query + 1)..] : ""; if (query >= 0) rest = rest[..query]; var sb = new StringBuilder(scheme).Append("://").Append(rest); if (addressQuery.Length > 0) sb.Append("?addressQuery=").Append(Uri.EscapeDataString(addressQuery)); AppendQuery(sb, addressQuery.Length > 0 ? '&' : '?'); return sb.ToString(); } private void AppendQuery(StringBuilder sb, char first) { var sep = first; foreach (var (key, value) in _options) { sb.Append(sep).Append(key).Append('=').Append(Uri.EscapeDataString(value)); sep = '&'; } } /// Lets the builder be passed to From()/To() without calling Build(). public static implicit operator string(As4Builder builder) => builder.Build(); /// public override string ToString() => Build(); } Path: redb-route/redb.Route.As4/Messaging/EbmsModel.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.As4/Messaging/EbmsModel.cs ---- using System.Xml; namespace redb.Route.As4.Messaging; /// Namespaces of the ebMS 3.0 header and of the receipt's non-repudiation information. internal static class EbmsNamespaces { /// ebMS 3.0 core header. public const string Eb = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/"; /// ebBP signals: ebbp:NonRepudiationInformation inside an AS4 receipt. public const string Ebbp = "http://docs.oasis-open.org/ebxml-bp/ebbp-signals-2.0"; /// SOAP 1.2 envelope. public const string Soap12 = "http://www.w3.org/2003/05/soap-envelope"; /// Default message partition channel (Core §3.4.1). public const string DefaultMpc = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/defaultMPC"; } /// The content of one eb:Messaging header: user messages and signals. /// At most one in AS4 (profile §2.1); a list because the header allows more. /// Receipts, errors, pull requests; one header may carry several. internal sealed record EbmsMessaging(IReadOnlyList UserMessages, IReadOnlyList SignalMessages); /// eb:MessageInfo. internal sealed record MessageInfo(DateTimeOffset Timestamp, string MessageId, string? RefToMessageId); /// eb:PartyId and its optional @type. internal sealed record PartyId(string Value, string? Type); /// eb:From or eb:To: the party ids and the role. internal sealed record Party(IReadOnlyList PartyIds, string Role); /// eb:AgreementRef. internal sealed record AgreementRef(string Value, string? Type, string? PMode); /// eb:Service. internal sealed record Service(string Value, string? Type); /// eb:CollaborationInfo. internal sealed record CollaborationInfo(AgreementRef? AgreementRef, Service Service, string Action, string ConversationId); /// eb:Property of message or part properties. internal sealed record Property(string Name, string Value, string? Type); /// eb:PartInfo: a payload reference (cid: for an attachment, none for the SOAP body) and its properties. internal sealed record PartInfo(string? Href, IReadOnlyList Properties) { /// The value of the part property , or null. public string? PropertyValue(string name) => Properties.FirstOrDefault(p => p.Name == name)?.Value; } /// eb:UserMessage. internal sealed record UserMessage( MessageInfo MessageInfo, Party From, Party To, CollaborationInfo CollaborationInfo, IReadOnlyList MessageProperties, IReadOnlyList PayloadInfo, string? Mpc) { /// The value of the message property , or null. public string? PropertyValue(string name) => MessageProperties.FirstOrDefault(p => p.Name == name)?.Value; } /// /// eb:SignalMessage. keeps the child elements of eb:Receipt as they /// arrived (the non-repudiation information is compared element by element against what was signed). /// internal sealed record SignalMessage( MessageInfo MessageInfo, IReadOnlyList? ReceiptContent, IReadOnlyList Errors, string? PullRequestMpc) { /// Whether the signal is a receipt. public bool IsReceipt => ReceiptContent is not null; } /// eb:Error. internal sealed record EbmsError( string ErrorCode, As4ErrorSeverity Severity, string? Category, string? Origin, string? RefToMessageInError, string? ShortDescription, string? Description, string? ErrorDetail); Path: redb-route/redb.Route.As4/Messaging/MessagingReader.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.As4/Messaging/MessagingReader.cs ---- using System.Globalization; using System.Xml; namespace redb.Route.As4.Messaging; /// /// Reads eb:Messaging from a SOAP 1.2 envelope into the typed model, enforcing the structure of ebMS 3.0 /// Core §5.2 element by element: a missing required element, a repeated singleton, an element the header does /// not define or an unparsable value is with the path of the offence. /// /// This is the check the OASIS schema would make; the schema itself is not used because it imports the SOAP /// schemas by network location, and nothing here resolves anything over the network (SafeXml, no /// resolver). Elements are matched by namespace and local name, never by prefix. /// /// internal static class MessagingReader { /// /// The eb:Messaging of . The envelope must be SOAP 1.2 and carry exactly one /// eb:Messaging as a direct child of the header. /// public static EbmsMessaging Read(XmlDocument envelope) { ArgumentNullException.ThrowIfNull(envelope); var root = envelope.DocumentElement; if (root is null || root.LocalName != "Envelope" || root.NamespaceURI != EbmsNamespaces.Soap12) throw Invalid("/", "the document is not a SOAP 1.2 envelope"); var header = One(root, "Header", EbmsNamespaces.Soap12, "/Envelope"); var messaging = One(header, "Messaging", EbmsNamespaces.Eb, "/Envelope/Header"); var users = new List(); var signals = new List(); foreach (var child in Elements(messaging)) { if (child.NamespaceURI == EbmsNamespaces.Eb && child.LocalName == "UserMessage") users.Add(ReadUserMessage(child, "/Messaging/UserMessage")); else if (child.NamespaceURI == EbmsNamespaces.Eb && child.LocalName == "SignalMessage") signals.Add(ReadSignalMessage(child, "/Messaging/SignalMessage")); else throw Invalid("/Messaging", $"unexpected element {{{child.NamespaceURI}}}{child.LocalName}"); } if (users.Count == 0 && signals.Count == 0) throw Invalid("/Messaging", "carries neither a user message nor a signal"); if (users.Count > 1) throw Invalid("/Messaging", "carries more than one user message (AS4 profile §2.1)"); return new EbmsMessaging(users, signals); } private static UserMessage ReadUserMessage(XmlElement element, string path) { Only(element, path, "MessageInfo", "PartyInfo", "CollaborationInfo", "MessageProperties", "PayloadInfo"); var info = ReadMessageInfo(One(element, "MessageInfo", EbmsNamespaces.Eb, path), path + "/MessageInfo"); var partyInfoPath = path + "/PartyInfo"; var partyInfo = One(element, "PartyInfo", EbmsNamespaces.Eb, path); Only(partyInfo, partyInfoPath, "From", "To"); var from = ReadParty(One(partyInfo, "From", EbmsNamespaces.Eb, partyInfoPath), partyInfoPath + "/From"); var to = ReadParty(One(partyInfo, "To", EbmsNamespaces.Eb, partyInfoPath), partyInfoPath + "/To"); var collaboration = ReadCollaboration(One(element, "CollaborationInfo", EbmsNamespaces.Eb, path), path + "/CollaborationInfo"); var properties = Optional(element, "MessageProperties", path) is { } props ? ReadProperties(props, path + "/MessageProperties") : []; var parts = new List(); if (Optional(element, "PayloadInfo", path) is { } payloadInfo) { var payloadPath = path + "/PayloadInfo"; Only(payloadInfo, payloadPath, "PartInfo"); foreach (var partInfo in Many(payloadInfo, "PartInfo", payloadPath, atLeastOne: true)) parts.Add(ReadPartInfo(partInfo, payloadPath + "/PartInfo")); } var mpc = element.GetAttributeNode("mpc")?.Value; return new UserMessage(info, from, to, collaboration, properties, parts, mpc); } private static SignalMessage ReadSignalMessage(XmlElement element, string path) { Only(element, path, "MessageInfo", "PullRequest", "Receipt", "Error"); var info = ReadMessageInfo(One(element, "MessageInfo", EbmsNamespaces.Eb, path), path + "/MessageInfo"); var pull = Optional(element, "PullRequest", path); var receipt = Optional(element, "Receipt", path); var errors = Many(element, "Error", path, atLeastOne: false).Select(e => ReadError(e, path + "/Error")).ToList(); var kinds = (pull is null ? 0 : 1) + (receipt is null ? 0 : 1) + (errors.Count == 0 ? 0 : 1); if (kinds != 1) throw Invalid(path, "must carry exactly one of PullRequest, Receipt or Error elements"); IReadOnlyList? receiptContent = null; if (receipt is not null) { receiptContent = Elements(receipt).Select(e => (XmlElement)e.CloneNode(deep: true)).ToList(); if (receiptContent.Count == 0) throw Invalid(path + "/Receipt", "is empty"); } string? pullMpc = null; if (pull is not null) pullMpc = pull.GetAttributeNode("mpc")?.Value ?? EbmsNamespaces.DefaultMpc; if (receipt is not null && info.RefToMessageId is null) throw Invalid(path + "/MessageInfo", "a receipt must carry RefToMessageId"); return new SignalMessage(info, receiptContent, errors, pullMpc); } private static MessageInfo ReadMessageInfo(XmlElement element, string path) { Only(element, path, "Timestamp", "MessageId", "RefToMessageId"); var timestampText = Text(One(element, "Timestamp", EbmsNamespaces.Eb, path), path + "/Timestamp"); if (!DateTimeOffset.TryParse(timestampText, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal | DateTimeStyles.AdjustToUniversal, out var timestamp)) throw Invalid(path + "/Timestamp", $"'{timestampText}' is not an xsd:dateTime"); var messageId = Text(One(element, "MessageId", EbmsNamespaces.Eb, path), path + "/MessageId"); var refTo = Optional(element, "RefToMessageId", path) is { } r ? Text(r, path + "/RefToMessageId") : null; return new MessageInfo(timestamp, messageId, refTo); } private static Party ReadParty(XmlElement element, string path) { Only(element, path, "PartyId", "Role"); var ids = Many(element, "PartyId", path, atLeastOne: true) .Select(p => new PartyId(Text(p, path + "/PartyId"), AttributeOrNull(p, "type"))) .ToList(); var role = Text(One(element, "Role", EbmsNamespaces.Eb, path), path + "/Role"); return new Party(ids, role); } private static CollaborationInfo ReadCollaboration(XmlElement element, string path) { Only(element, path, "AgreementRef", "Service", "Action", "ConversationId"); AgreementRef? agreement = null; if (Optional(element, "AgreementRef", path) is { } a) agreement = new AgreementRef(Text(a, path + "/AgreementRef"), AttributeOrNull(a, "type"), AttributeOrNull(a, "pmode")); var serviceElement = One(element, "Service", EbmsNamespaces.Eb, path); var service = new Service(Text(serviceElement, path + "/Service"), AttributeOrNull(serviceElement, "type")); var action = Text(One(element, "Action", EbmsNamespaces.Eb, path), path + "/Action"); var conversation = Text(One(element, "ConversationId", EbmsNamespaces.Eb, path), path + "/ConversationId"); return new CollaborationInfo(agreement, service, action, conversation); } private static PartInfo ReadPartInfo(XmlElement element, string path) { Only(element, path, "Schema", "Description", "PartProperties"); var href = AttributeOrNull(element, "href"); var properties = Optional(element, "PartProperties", path) is { } p ? ReadProperties(p, path + "/PartProperties") : []; return new PartInfo(href, properties); } private static IReadOnlyList ReadProperties(XmlElement element, string path) { Only(element, path, "Property"); var properties = Many(element, "Property", path, atLeastOne: true) .Select(p => new Property( AttributeOrNull(p, "name") ?? throw Invalid(path + "/Property", "has no name"), p.InnerText, AttributeOrNull(p, "type"))) .ToList(); var repeated = properties.GroupBy(p => p.Name, StringComparer.Ordinal).FirstOrDefault(g => g.Count() > 1); if (repeated is not null) throw Invalid(path, $"property '{repeated.Key}' appears more than once"); return properties; } private static EbmsError ReadError(XmlElement element, string path) { Only(element, path, "Description", "ErrorDetail"); var code = AttributeOrNull(element, "errorCode") ?? throw Invalid(path, "has no errorCode"); var severityText = AttributeOrNull(element, "severity") ?? throw Invalid(path, "has no severity"); var severity = severityText switch { "failure" => As4ErrorSeverity.Failure, "warning" => As4ErrorSeverity.Warning, _ => throw Invalid(path, $"severity '{severityText}' is neither failure nor warning"), }; return new EbmsError(code, severity, AttributeOrNull(element, "category"), AttributeOrNull(element, "origin"), AttributeOrNull(element, "refToMessageInError"), AttributeOrNull(element, "shortDescription"), Optional(element, "Description", path)?.InnerText, Optional(element, "ErrorDetail", path)?.InnerText); } // ── Structure helpers ──────────────────────────────────────────────────── private static IEnumerable Elements(XmlElement parent) => parent.ChildNodes.OfType(); /// Refuses any child element that is not one of in the ebMS namespace. private static void Only(XmlElement element, string path, params string[] allowed) { foreach (var child in Elements(element)) { if (child.NamespaceURI != EbmsNamespaces.Eb || Array.IndexOf(allowed, child.LocalName) < 0) throw Invalid(path, $"unexpected element {{{child.NamespaceURI}}}{child.LocalName}"); } } private static XmlElement One(XmlElement parent, string localName, string ns, string path) => Optional(parent, localName, path, ns) ?? throw Invalid(path, $"{localName} is missing"); private static XmlElement? Optional(XmlElement parent, string localName, string path, string ns = EbmsNamespaces.Eb) { XmlElement? found = null; foreach (var child in Elements(parent)) { if (child.LocalName != localName || child.NamespaceURI != ns) continue; if (found is not null) throw Invalid(path, $"{localName} appears more than once"); found = child; } return found; } private static List Many(XmlElement parent, string localName, string path, bool atLeastOne) { var found = Elements(parent).Where(e => e.LocalName == localName && e.NamespaceURI == EbmsNamespaces.Eb).ToList(); if (atLeastOne && found.Count == 0) throw Invalid(path, $"{localName} is missing"); return found; } private static string Text(XmlElement element, string path) { var text = element.InnerText.Trim(); return text.Length > 0 ? text : throw Invalid(path, "is empty"); } private static string? AttributeOrNull(XmlElement element, string name) => element.GetAttributeNode(name) is { } attribute ? attribute.Value : null; private static As4ProcessingException Invalid(string path, string what) => new(As4ErrorCode.InvalidHeader, $"eb:Messaging {path}: {what}."); } Path: redb-route/redb.Route.As4/Messaging/MessagingWriter.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.As4/Messaging/MessagingWriter.cs ---- using System.Globalization; using System.Xml; namespace redb.Route.As4.Messaging; /// /// Writes the typed model into a SOAP 1.2 envelope: eb:Messaging (with mustUnderstand="true") as the /// only header block and an empty body — AS4 carries payloads as attachments. The namespaces are declared on the /// envelope explicitly, so the document canonicalizes the same before and after serialization (see /// ExclusiveCanonicalizer.DeclareNamespaces). /// internal static class MessagingWriter { private const string SoapPrefix = "soapenv"; private const string EbPrefix = "eb"; /// A new envelope carrying . public static XmlDocument CreateEnvelope(UserMessage message) => CreateEnvelope(messaging => WriteUserMessage(messaging, message)); /// A new envelope carrying . public static XmlDocument CreateEnvelope(SignalMessage signal) => CreateEnvelope(messaging => WriteSignalMessage(messaging, signal)); private static XmlDocument CreateEnvelope(Action fill) { var doc = new XmlDocument { PreserveWhitespace = true, XmlResolver = null }; var envelope = doc.CreateElement(SoapPrefix, "Envelope", EbmsNamespaces.Soap12); envelope.SetAttribute("xmlns:" + SoapPrefix, EbmsNamespaces.Soap12); envelope.SetAttribute("xmlns:" + EbPrefix, EbmsNamespaces.Eb); doc.AppendChild(envelope); var header = Add(envelope, SoapPrefix, "Header", EbmsNamespaces.Soap12); var messaging = Add(header, EbPrefix, "Messaging", EbmsNamespaces.Eb); var mustUnderstand = doc.CreateAttribute(SoapPrefix, "mustUnderstand", EbmsNamespaces.Soap12); mustUnderstand.Value = "true"; messaging.Attributes.Append(mustUnderstand); fill(messaging); Add(envelope, SoapPrefix, "Body", EbmsNamespaces.Soap12); return doc; } private static void WriteUserMessage(XmlElement messaging, UserMessage message) { var user = Add(messaging, EbPrefix, "UserMessage", EbmsNamespaces.Eb); if (message.Mpc is not null) user.SetAttribute("mpc", message.Mpc); WriteMessageInfo(user, message.MessageInfo); var partyInfo = Eb(user, "PartyInfo"); WriteParty(Eb(partyInfo, "From"), message.From); WriteParty(Eb(partyInfo, "To"), message.To); var collaboration = Eb(user, "CollaborationInfo"); if (message.CollaborationInfo.AgreementRef is { } agreement) { var element = Eb(collaboration, "AgreementRef", agreement.Value); if (agreement.Type is not null) element.SetAttribute("type", agreement.Type); if (agreement.PMode is not null) element.SetAttribute("pmode", agreement.PMode); } var service = Eb(collaboration, "Service", message.CollaborationInfo.Service.Value); if (message.CollaborationInfo.Service.Type is not null) service.SetAttribute("type", message.CollaborationInfo.Service.Type); Eb(collaboration, "Action", message.CollaborationInfo.Action); Eb(collaboration, "ConversationId", message.CollaborationInfo.ConversationId); if (message.MessageProperties.Count > 0) WriteProperties(Eb(user, "MessageProperties"), message.MessageProperties); if (message.PayloadInfo.Count > 0) { var payloadInfo = Eb(user, "PayloadInfo"); foreach (var part in message.PayloadInfo) { var partInfo = Eb(payloadInfo, "PartInfo"); if (part.Href is not null) partInfo.SetAttribute("href", part.Href); if (part.Properties.Count > 0) WriteProperties(Eb(partInfo, "PartProperties"), part.Properties); } } } private static void WriteSignalMessage(XmlElement messaging, SignalMessage signal) { var element = Add(messaging, EbPrefix, "SignalMessage", EbmsNamespaces.Eb); WriteMessageInfo(element, signal.MessageInfo); if (signal.ReceiptContent is { } content) { var receipt = Eb(element, "Receipt"); foreach (var child in content) receipt.AppendChild(receipt.OwnerDocument.ImportNode(child, deep: true)); } foreach (var error in signal.Errors) { var e = Eb(element, "Error"); e.SetAttribute("errorCode", error.ErrorCode); e.SetAttribute("severity", error.Severity == As4ErrorSeverity.Failure ? "failure" : "warning"); if (error.Category is not null) e.SetAttribute("category", error.Category); if (error.Origin is not null) e.SetAttribute("origin", error.Origin); if (error.RefToMessageInError is not null) e.SetAttribute("refToMessageInError", error.RefToMessageInError); if (error.ShortDescription is not null) e.SetAttribute("shortDescription", error.ShortDescription); if (error.Description is not null) { var description = Eb(e, "Description", error.Description); var lang = description.OwnerDocument.CreateAttribute("xml", "lang", "http://www.w3.org/XML/1998/namespace"); lang.Value = "en"; description.Attributes.Append(lang); } if (error.ErrorDetail is not null) Eb(e, "ErrorDetail", error.ErrorDetail); } if (signal.PullRequestMpc is not null) Eb(element, "PullRequest").SetAttribute("mpc", signal.PullRequestMpc); } private static void WriteMessageInfo(XmlElement parent, MessageInfo info) { var element = Eb(parent, "MessageInfo"); Eb(element, "Timestamp", info.Timestamp.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture)); Eb(element, "MessageId", info.MessageId); if (info.RefToMessageId is not null) Eb(element, "RefToMessageId", info.RefToMessageId); } private static void WriteParty(XmlElement element, Party party) { foreach (var id in party.PartyIds) { var partyId = Eb(element, "PartyId", id.Value); if (id.Type is not null) partyId.SetAttribute("type", id.Type); } Eb(element, "Role", party.Role); } private static void WriteProperties(XmlElement element, IReadOnlyList properties) { foreach (var property in properties) { var p = Eb(element, "Property", property.Value); p.SetAttribute("name", property.Name); if (property.Type is not null) p.SetAttribute("type", property.Type); } } private static XmlElement Eb(XmlElement parent, string localName, string? text = null) { var element = Add(parent, EbPrefix, localName, EbmsNamespaces.Eb); if (text is not null) element.InnerText = text; return element; } private static XmlElement Add(XmlElement parent, string prefix, string localName, string ns) { var element = parent.OwnerDocument.CreateElement(prefix, localName, ns); parent.AppendChild(element); return element; } } /// Message ids as ebMS requires them: globally unique, RFC 2822 id-left@id-right without brackets. internal static class MessageIdFactory { /// A new id under (the node's public name, never the machine name). public static string New(string host) { ArgumentException.ThrowIfNullOrWhiteSpace(host); return Guid.NewGuid().ToString("D") + "@" + host; } } Path: redb-route/redb.Route.As4/Mime/As4Spool.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.As4/Mime/As4Spool.cs ---- using redb.Route.Abstractions; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Extensions; namespace redb.Route.As4.Mime; /// /// Where the connector spools request bodies and payloads: the engine's stream cache options (threshold, temporary /// directory), as .StreamCaching() resolves them (). /// internal static class As4Spool { /// The stream cache options of . public static StreamCacheOptions Options(IRouteContext? context) => context.GetStreamCacheOptions(); /// The asynchronous form of , for a step that reads a foreign stream (the exchange body). public static async Task RunAsync(StreamCacheOptions options, Func write, CancellationToken ct) { ArgumentNullException.ThrowIfNull(options); ArgumentNullException.ThrowIfNull(write); var spool = new StreamCache(options); try { await write(spool, ct).ConfigureAwait(false); spool.CompleteWriting(); return spool; } catch { await spool.DisposeAsync().ConfigureAwait(false); throw; } } /// /// Runs one processing step, , into a new spool (memory, or a temporary file past the /// threshold). The spool is returned readable and rewound; if the step throws, it is disposed and nothing of its /// output survives. Decryption relies on that, since GCM authenticates only at the end. /// public static Stream Run(StreamCacheOptions options, Action write) { ArgumentNullException.ThrowIfNull(options); ArgumentNullException.ThrowIfNull(write); var spool = new StreamCache(options); try { write(spool); spool.CompleteWriting(); return spool; } catch { spool.Dispose(); throw; } } } Path: redb-route/redb.Route.As4/Mime/EnvelopeLimits.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.As4/Mime/EnvelopeLimits.cs ---- using redb.Route.Core; namespace redb.Route.As4.Mime; /// /// The structure an AS4 envelope may have, received or answered: tighter than , /// because an eDelivery envelope is shallow and narrow whoever builds it. Measured on 3 000 envelopes of Holodeck B2B /// 8.1, Domibus 5 (Harmony 2.6) and this connector, messages and signals alike: at most 10 levels deep, 8 attributes /// and 8 namespace declarations on an element, 24 namespace declarations in the envelope. The limits keep two to four /// times that; namespace declarations count as attributes, so their own limit sits below the attribute limit. The whole /// envelope may declare far more, for messages with many payloads (each adds its references and encryption elements). /// The size is the endpoint's maxEnvelopeCharacters. /// /// They are the profile's shape, not a deployment setting: an envelope over them is not one any eDelivery access point /// sends, and it is refused before canonicalization or a signature check spends anything on it. /// /// internal static class EnvelopeLimits { /// Nesting depth of the envelope's elements. internal const int MaxDepth = 32; /// Attributes on one element, namespace declarations included. internal const int MaxAttributesPerElement = 32; /// Namespace declarations on one element. internal const int MaxNamespaceDeclarationsPerElement = 16; /// Namespace declarations in the whole envelope. internal const int MaxNamespaceDeclarations = 4096; /// The limits of an envelope of at most characters. internal static XmlLimits For(long maxEnvelopeCharacters) => new() { MaxDepth = MaxDepth, MaxAttributesPerElement = MaxAttributesPerElement, MaxNamespaceDeclarationsPerElement = MaxNamespaceDeclarationsPerElement, MaxNamespaceDeclarations = MaxNamespaceDeclarations, MaxCharacters = maxEnvelopeCharacters, }; } Path: redb-route/redb.Route.As4/Mime/PayloadConsistency.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.As4/Mime/PayloadConsistency.cs ---- using redb.Route.As4.Messaging; namespace redb.Route.As4.Mime; /// /// The payload references of a user message and the MIME parts of its message must match one to one /// (ebMS 3.0 Core §5.2.2.13, AS4 profile): every cid: reference names a part, every part is referenced. /// A reference outside the message is not supported. /// internal static class PayloadConsistency { /// Upper bound on attachments per message; beyond it the message is refused before any crypto work. public const int DefaultMaxParts = 100; /// Part property naming the character set of an XML payload before compression. public const string CharacterSetProperty = "CharacterSet"; /// /// Whether is an encoding name of XML 1.0 §4.3.3 (EncName: a Latin letter, then /// Latin letters, digits, ., _ and -), which the profile requires of the /// CharacterSet part property (eDelivery AS4 1.16 §3.2.3). /// public static bool IsCharacterSetName(string? value) { if (string.IsNullOrEmpty(value) || !char.IsAsciiLetter(value[0])) return false; foreach (var c in value) if (!(char.IsAsciiLetterOrDigit(c) || c is '.' or '_' or '-')) return false; return true; } /// /// Throws when a part of names a /// CharacterSet that is not an encoding name. /// public static void CheckCharacterSets(UserMessage message) { ArgumentNullException.ThrowIfNull(message); foreach (var info in message.PayloadInfo) foreach (var property in info.Properties) if (property.Name == CharacterSetProperty && !IsCharacterSetName(property.Value)) throw new As4ProcessingException(As4ErrorCode.ValueInconsistent, $"part '{info.Href}' names CharacterSet '{property.Value}', which is not an encoding name of XML 1.0 §4.3.3."); } /// /// Pairs each eb:PartInfo of with its part, or throws /// / . /// A PartInfo without href stands for the SOAP body and is paired with null. /// public static IReadOnlyList<(PartInfo Info, SwaPart? Part)> Match(UserMessage message, SwaMessage swa, int maxParts = DefaultMaxParts) { ArgumentNullException.ThrowIfNull(message); ArgumentNullException.ThrowIfNull(swa); if (swa.Parts.Count > maxParts) throw new As4ProcessingException(As4ErrorCode.MimeInconsistency, $"the message has {swa.Parts.Count} parts; at most {maxParts} are accepted."); var pairs = new List<(PartInfo, SwaPart?)>(); var referenced = new HashSet(StringComparer.Ordinal); foreach (var info in message.PayloadInfo) { if (info.Href is null) { pairs.Add((info, null)); continue; } if (!info.Href.StartsWith("cid:", StringComparison.OrdinalIgnoreCase)) throw new As4ProcessingException(As4ErrorCode.ExternalPayloadError, $"payload reference '{info.Href}' points outside the message."); var id = Uri.UnescapeDataString(info.Href["cid:".Length..]); if (!referenced.Add(id)) throw new As4ProcessingException(As4ErrorCode.MimeInconsistency, $"part '{id}' is referenced more than once."); if (!swa.Parts.TryGetValue(id, out var part)) throw new As4ProcessingException(As4ErrorCode.MimeInconsistency, $"the header references part '{id}', which the message does not carry."); pairs.Add((info, part)); } var unreferenced = swa.Parts.Keys.FirstOrDefault(id => !referenced.Contains(id)); if (unreferenced is not null) throw new As4ProcessingException(As4ErrorCode.MimeInconsistency, $"part '{unreferenced}' is not referenced by the header."); return pairs; } } Path: redb-route/redb.Route.As4/Mime/SwaMessage.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.As4/Mime/SwaMessage.cs ---- using System.Security.Cryptography; using System.Xml; using MimeKit; using redb.Route.Configuration; using redb.Route.Core; namespace redb.Route.As4.Mime; /// /// An AS4 message as it travels: the SOAP 1.2 envelope and the MIME parts it refers to by Content-ID /// (SOAP with Attachments). A message without attachments may arrive as a bare envelope, not MIME. /// /// Part contents are streams the message owns: small ones in memory, large ones spooled to a temporary file by the /// core (deleted when the part is disposed). Every processing step — decryption, /// decompression, compression, encryption — reads one stream and writes the next, so a large payload is never held /// in a byte[]. Disposing the message disposes every part it still owns; a part handed to the route is /// detached first (). /// /// internal sealed class SwaMessage : IDisposable { private readonly Stream? _source; private SwaMessage(XmlDocument envelope, Dictionary parts, StreamCacheOptions spool, Stream? source) { Envelope = envelope; Parts = parts; Spool = spool; _source = source; } /// The SOAP envelope, loaded with whitespace preserved (signature canonicalization depends on it). public XmlDocument Envelope { get; } /// The attachments, keyed by Content-ID without angle brackets. public Dictionary Parts { get; } /// Where processing steps spool part contents that outgrow memory. public StreamCacheOptions Spool { get; } /// /// Reads a message from an HTTP body and its Content-Type. must be seekable; the message /// takes ownership of it (MimeKit parses it persistently, so parts are read from it without a copy until they are /// decoded). The envelope is parsed with : no DTD, the structure of , at most characters. /// public static SwaMessage Read(string contentType, Stream body, long maxEnvelopeCharacters, StreamCacheOptions spool) { ArgumentException.ThrowIfNullOrWhiteSpace(contentType); ArgumentNullException.ThrowIfNull(body); ArgumentNullException.ThrowIfNull(spool); if (!body.CanSeek) throw new ArgumentException("The message body must be seekable.", nameof(body)); var parts = new Dictionary(StringComparer.Ordinal); try { var type = ContentType.Parse(contentType); if (!type.IsMimeType("multipart", "related")) return new SwaMessage(SafeXml.LoadDocument(ReadAll(body), EnvelopeLimits.For(maxEnvelopeCharacters), preserveWhitespace: true), parts, spool, body); // The HTTP Content-Type stands in for the entity headers; persistent parsing keeps the parts as views of the body. body.Position = 0; using var entity = new MimeKit.IO.ChainedStream(); entity.Add(new MemoryStream(System.Text.Encoding.ASCII.GetBytes("Content-Type: " + contentType + "\r\n\r\n")), leaveOpen: false); entity.Add(body, leaveOpen: true); if (new MimeParser(entity, MimeFormat.Entity, persistent: true).ParseEntity() is not Multipart multipart || multipart.Count == 0) throw new FormatException("The multipart/related body has no parts."); var start = type.Parameters["start"]?.Trim('<', '>'); var root = (start is null ? null : multipart.OfType().FirstOrDefault(p => p.ContentId == start)) ?? multipart[0] as MimePart ?? throw new FormatException("The root part of the multipart/related body is not a leaf part."); byte[] envelopeBytes; using (var envelopeStream = new MemoryStream()) { Content(root).DecodeTo(envelopeStream); envelopeBytes = envelopeStream.ToArray(); } var envelope = SafeXml.LoadDocument(envelopeBytes, EnvelopeLimits.For(maxEnvelopeCharacters), preserveWhitespace: true); foreach (var part in multipart.OfType()) { if (ReferenceEquals(part, root)) continue; if (string.IsNullOrEmpty(part.ContentId)) throw new FormatException("An attachment part has no Content-ID."); if (parts.ContainsKey(part.ContentId)) throw new FormatException($"Two parts carry the Content-ID '{part.ContentId}'."); var decoded = new StreamCache(spool); try { Content(part).DecodeTo(decoded); decoded.CompleteWriting(); } catch { decoded.Dispose(); throw; } parts.Add(part.ContentId, new SwaPart(part.ContentId, part.ContentType.MimeType, decoded)); } return new SwaMessage(envelope, parts, spool, body); } catch { foreach (var part in parts.Values) part.Dispose(); throw; } } /// Reads a message held in memory (signals, tests); see . public static SwaMessage Read(string contentType, byte[] body, long maxEnvelopeCharacters) => Read(contentType, new MemoryStream(body ?? throw new ArgumentNullException(nameof(body)), writable: false), maxEnvelopeCharacters, new StreamCacheOptions()); /// A message to send: and no attachments yet. public static SwaMessage Create(XmlDocument envelope, StreamCacheOptions? spool = null) => new(envelope, new(StringComparer.Ordinal), spool ?? new StreamCacheOptions(), null); /// Adds an attachment the message then owns; throws on a repeated Content-ID. public SwaPart AddPart(string contentId, string contentType, Stream content) { var part = new SwaPart(contentId, contentType, content); if (!Parts.TryAdd(contentId, part)) throw new InvalidOperationException($"The message already has a part with Content-ID '{contentId}'."); return part; } /// Adds an attachment held in memory; throws on a repeated Content-ID. public SwaPart AddPart(string contentId, string contentType, byte[] content) => AddPart(contentId, contentType, new MemoryStream(content ?? throw new ArgumentNullException(nameof(content)), writable: false)); /// /// Serializes the message for HTTP into : multipart/related; type="application/soap+xml" /// with the envelope as the start part and binary parts, or a bare SOAP 1.2 envelope when there are no attachments. /// Returns the Content-Type. Part contents are copied from their streams, not buffered. /// public string WriteTo(Stream output) { ArgumentNullException.ThrowIfNull(output); var envelopeBytes = new System.Text.UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(Envelope.OuterXml); if (Parts.Count == 0) { output.Write(envelopeBytes); return "application/soap+xml; charset=UTF-8"; } var rootId = "root." + Guid.NewGuid().ToString("N") + "@redb.route"; var multipart = new Multipart("related"); multipart.ContentType.Parameters.Add("type", "application/soap+xml"); multipart.ContentType.Parameters.Add("start", "<" + rootId + ">"); var root = new MimePart("application", "soap+xml") { ContentId = rootId, ContentTransferEncoding = ContentEncoding.Binary, Content = new MimeContent(new MemoryStream(envelopeBytes)), }; root.ContentType.Charset = "UTF-8"; multipart.Add(root); foreach (var part in Parts.Values) { multipart.Add(new MimePart(MimeKit.ContentType.Parse(part.ContentType)) { ContentId = part.ContentId, ContentTransferEncoding = ContentEncoding.Binary, Content = new MimeContent(part.OpenRead()), }); } multipart.WriteTo(WireFormat, output, contentOnly: true); // The header value, not ContentType.ToString(), which renders the whole "Content-Type:" line (the AS2 lesson). return multipart.Headers[HeaderId.ContentType] ?? throw new InvalidOperationException("The multipart body has no Content-Type header."); } /// /// How the multipart body is written: lines end in CRLF, as MIME requires (RFC 2046 §4.1.1, §5.1.1), on every /// platform. MimeKit's default follows the platform: on Linux it writes a bare LF before each boundary, which a /// receiver that splits on CRLF takes for the last byte of the part before it — one byte too many in an encrypted /// attachment, and its AES-GCM tag no longer matches (Domibus: "Tag mismatch!"). /// internal static readonly FormatOptions WireFormat = CreateWireFormat(); private static FormatOptions CreateWireFormat() { var options = FormatOptions.Default.Clone(); options.NewLineFormat = NewLineFormat.Dos; return options; } /// Serializes the message into memory (signals, tests); see . public (string ContentType, byte[] Body) Write() { using var output = new MemoryStream(); var contentType = WriteTo(output); return (contentType, output.ToArray()); } /// Runs one processing step into a new spool of this message; see . public Stream Spooled(Action write) => As4Spool.Run(Spool, write); /// Disposes every part the message still owns and the body it was read from. public void Dispose() { foreach (var part in Parts.Values) part.Dispose(); _source?.Dispose(); } private static MimeContent Content(MimePart part) => part.Content as MimeContent ?? throw new FormatException($"The MIME part '{part.ContentId}' has no content."); private static byte[] ReadAll(Stream stream) { stream.Position = 0; using var buffer = new MemoryStream(); stream.CopyTo(buffer); return buffer.ToArray(); } } /// /// One attachment: its Content-ID, media type and content. The content is a readable, seekable stream the part owns /// until swaps it for the output of a processing step or hands it on. /// internal sealed class SwaPart : IDisposable { private Stream? _content; public SwaPart(string contentId, string contentType, Stream content) { ArgumentNullException.ThrowIfNull(content); if (!content.CanRead || !content.CanSeek) throw new ArgumentException("Part content must be readable and seekable.", nameof(content)); ContentId = contentId; ContentType = contentType; _content = content; } /// A part held in memory (signals, tests). public SwaPart(string contentId, string contentType, byte[] content) : this(contentId, contentType, new MemoryStream(content ?? throw new ArgumentNullException(nameof(content)), writable: false)) { } /// Content-ID without angle brackets. public string ContentId { get; } /// Media type of the part as it is now (after decryption: the type the ciphertext stood for). public string ContentType { get; set; } /// Length of the content in bytes. public long Length => Content.Length; private Stream Content => _content ?? throw new ObjectDisposedException(nameof(SwaPart), $"The content of part '{ContentId}' was handed on or released."); /// The content from its start. Reading it moves the shared position; each caller rewinds through this method. public Stream OpenRead() { var content = Content; content.Position = 0; return content; } /// SHA-256 of the content, read as a stream. public byte[] Sha256() => SHA256.HashData(OpenRead()); /// The content as bytes. For small contents and tests: it loads the whole part. public byte[] ToArray() { using var buffer = new MemoryStream(); OpenRead().CopyTo(buffer); return buffer.ToArray(); } /// Makes the content and disposes the one it replaces. public void Replace(Stream next) { ArgumentNullException.ThrowIfNull(next); if (!next.CanRead || !next.CanSeek) throw new ArgumentException("Part content must be readable and seekable.", nameof(next)); var previous = _content; _content = next; previous?.Dispose(); } /// Hands the content, rewound, to a new owner; the part no longer disposes it. public Stream Detach() { var content = OpenRead(); _content = null; return content; } /// public void Dispose() { _content?.Dispose(); _content = null; } } Path: redb-route/redb.Route.As4/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.As4/README.md ---- # redb.Route.As4 **AS4 B2B transport for the [redb.Route](../redb.Route) ESB framework.** OASIS ebMS 3.0 with the AS4 profile, following the **eDelivery AS4 1.16 common profile** (28.01.2026) — the message exchange used by EU eDelivery access points, e-invoicing networks, energy and customs gateways. Business documents travel as SOAP 1.2 messages with attachments; every message is signed, its payloads compressed and encrypted, and the receiver answers in the same HTTP response with a signed **non-repudiation receipt**. Schemes: `as4` (HTTP), `as4s` (HTTPS). - **Send** (`.To(...)`) — gzip → encrypt → sign a payload, POST it to the partner's access point, verify the receipt it answers with (signature and non-repudiation digests). - **Receive** (`.From(...)`) — host an AS4 access point: decrypt, verify, decompress, match the message to an agreement, hand the document to your route, and answer with a receipt or an ebMS error **after** the route's unit of work. - **One-Way/Push** and **Two-Way/Push-and-Push** (the reply leg with `eb:RefToMessageId`), both required by the profile. - **Duplicate detection** on receive and **redelivery with the same message id** on send, built from the engine's `IIdempotentRepository` and `OnException` — no store or timer of the connector's own. [![Certificate of the eDelivery AS4 conformance tests passed by redb.Route.As4 4.6.1](https://raw.githubusercontent.com/redbase-app/redb-route/main/redb.Route.As4/images/as4-ec-conformance-certificate.png)](https://ec.europa.eu/digital-building-blocks/sites/spaces/DIGITAL/pages/721846393/eDelivery+AS4+v1.x+conformant+products) **eDelivery AS4 conformance.** redb.Route.As4 4.6.1 is listed by the European Commission among [eDelivery AS4 v1.x conformant products](https://ec.europa.eu/digital-building-blocks/sites/spaces/DIGITAL/pages/721846393/eDelivery+AS4+v1.x+conformant+products): it passed the eDelivery conformance tests of the eDelivery AS4 Profile 1.16, Common Profile, 76 of 76 required tests, on 2026-11-04 ([certificate, PDF](https://redbase.app/files/as4/redb-route-as4-4.6.1-ec-conformance-certificate.pdf)). The certificate is for version 4.6.1; later versions have not gone through the conformance service again. It attests the eDelivery Common Profile, not Peppol. > **Status:** version 4.6.1 passed the eDelivery conformance tests and is listed by the European Commission among > eDelivery AS4 conformant products (above); interop is also proven live against Holodeck B2B and Domibus in both > directions (see [Status](#status--maturity)). --- ## Install & register ```csharp services.AddRedbRoute(route => { route.Services.AddRedbRouteAs4(); route.AddRouteBuilder(); }); ``` `AddRedbRouteAs4()` registers the `as4` / `as4s` schemes. The receive side runs on the Kestrel host shared with every other HTTP-based connector in the process (`redb.Route.Http.Hosting`), so an HTTP, SOAP, AS2 and AS4 route in one worker never fight over a port. --- ## Concepts | AS4 term | Here | Where it lives | |---|---|---| | Our access point (identity + keys) | **node** — `As4ConnectionFactory` | route context registry, by name | | P-Mode / agreement with one partner | **partner** — `As4Partner` | the node's `Partners` list, by `Name` | | Partner's access point URL (P-Mode `Protocol.Address`) | the partner's **`Address`**, or the **send URI** | `As4Partner.Address` with `As4.Send()`, or `As4.Send("https://...")` | | Our receive URL | the **receive URI** | `As4.Receive("/as4/in")` — one URL for all partners | | Business document | exchange **body** | `byte[]` + `Message.ContentType` | | `eb:Messaging` header values | exchange **headers** `redbAs4.*` | see [Headers](#headers) | Certificates and passwords never appear in a URI: the URI is the route key and ends up in logs, spans and the dashboard. A URI names the node (`connectionFactory=`) and, when sending, the partner (`partner=`). --- ## Node and partners ```csharp context.AddToRegistry("node", new As4ConnectionFactory { OurPartyId = "urn:oasis:names:tc:ebcore:partyid-type:unregistered:us", ExternalHostName = "ap.us.example", // host part of our message ids SigningCertificate = ourPfx, // private key: signs messages and receipts DecryptionCertificates = { ourPfx }, // private keys: decrypt what partners encrypt for us Partners = { new As4Partner { Name = "acme", PartyId = "urn:oasis:names:tc:ebcore:partyid-type:unregistered:acme", Service = "urn:example:services:invoice", Action = "Submit", PartnerSigningCertificates = { acmeCertificate }, // verifies acme's signatures PartnerEncryptionCertificate = acmeCertificate, // we encrypt payloads for acme }, }, }); ``` Certificate lists hold more than one entry while a key rotates. In Route-XML the node is a `` whose `Partners` property is a `` of nested `` or `` partners. A certificate is a nested bean too: ```xml ``` The duplicate store of a receive endpoint is a bean as well: `` of any `IIdempotentRepository`, or `` for the redb-backed one. The node and its partners are resolved and validated **when an endpoint starts**, not when the route is defined — the registry may be filled after the routes. A missing, mistyped or invalid node or partner stops the route from starting, with the offending registry name in the message. ### `As4ConnectionFactory` — our node | Property | Default | Meaning | |---|---|---| | `OurPartyId` | — (required) | Our `eb:PartyId`. Exactly one, as eDelivery requires. | | `OurPartyIdType` | null | Our `eb:PartyId/@type`; omitted when null. | | `ExternalHostName` | `redb.route` | Host part of the message ids we generate (`uuid@host`). Set a public name; the default is a fixed placeholder, never the machine name, so internal host names do not leak. | | `SigningCertificate` | — (required) | Our certificate **with private key**; signs our messages and receipts. | | `SigningCertificateChain` | empty | The certification authorities above `SigningCertificate`, in any order. Sent with it as its certification path to a partner whose `KeyReference` is `PkiPath`; the path is ordered once, when the node starts. A certificate here that issued neither `SigningCertificate` nor another authority of the chain stops the node from starting. | | `DecryptionCertificates` | empty (required) | Our certificates with private keys that decrypt payloads. Several while we rotate; the one a message names is used. | | `ClientCertificate` | null | Our TLS client certificate for partners that require mutual TLS when we send. | | `SslCertPath` / `SslCertPassword` | null | PFX our receive server presents over TLS when the endpoint URI gives none. The password is `[Sensitive]`. | | `ClientCertificateMode` / `AllowedClientThumbprints` | `NoCertificate` / null | Mutual TLS on our receive server when the endpoint URI does not say, as the SOAP factory offers it. | | `SslProtocols` | TLS 1.2 + 1.3 | TLS versions our sender offers; the profile allows only these two, anything else is refused (Holodeck `AllowedProtocols`, phase4, Domibus default the same). | | `RevocationMode` | `NoCheck` | Revocation check of pinned certificates (partner signing and encryption, our signing, allow-listed TLS clients) and of the certificates below the anchor in a partner's certification path: `NoCheck`, `Online` (CRL / OCSP the certificate points at) or `Offline` (OS cache). Off by default, as Camel/CXF, Holodeck and phase4. | | `RevocationSoftFail` | false | Accept a certificate whose revocation status cannot be determined. Default: refused, as phase4 and Domibus refuse it. | | `Partners` | empty | The agreements of this node, one per trading partner. | ### `As4Partner` — the agreement with one partner The partner half of an ebMS P-Mode. Signing, encryption, compression support and a signed receipt in the HTTP response are **not options**: the profile mandates them. | Property | Default | Meaning | |---|---|---| | `Name` | — (required) | Name within the node: what `partner=` refers to and the `redbAs4.partner` header on receipt. | | `PartyId` / `PartyIdType` | — / null | The partner's `eb:PartyId` and its type. | | `Address` | null | The partner's MSH address, `http://` or `https://`, with a query where it has one (a Domibus domain, `/domibus?domain=name`). A send endpoint without an address of its own (`As4.Send()`, `as4:?partner=...`) posts here. Null: the send URI gives the address; both is refused. | | `OurRole` / `PartnerRole` | ebMS `initiator` / `responder` URIs | `eb:Role` of each side. | | `AgreementRef` / `AgreementRefType` / `PModeId` | null | `eb:AgreementRef`, its `@type` and `@pmode`. When set, a received message must carry the same reference. | | `Service` / `ServiceType` / `Action` | — (Service, Action required) | `eb:Service` and `eb:Action` of the request leg. | | `AllowOverrideService` / `AllowOverrideAction` | false | Whether a route may send another service / action (endpoint option or header). | | `ReplyLeg` | null | `As4Leg { Service, ServiceType, Action }` of the reply in a Two-Way / Push-and-Push exchange. | | `PartnerSigningCertificates` | empty | Certificates that verify the partner's signatures (the certificate is pinned); several while the partner rotates. Required unless `PartnerTrustAnchors` is set. | | `PartnerEncryptionCertificate` | — (required) | Certificate we encrypt payloads for. | | `KeyReference` | `BinarySecurityToken` | How our signature references our certificate: `BinarySecurityToken`, `IssuerSerial`, `KeyIdentifier` or `PkiPath` (all are accepted on receipt from a partner whose certificate is pinned). `PkiPath` sends the certificate with the node's `SigningCertificateChain` as an `X509PKIPathv1` token. | | `PartnerTrustAnchors` | empty | Certification authorities the partner's signing certificate must chain to, instead of `PartnerSigningCertificates`: roots or intermediate authorities. With these set the partner must present its certificate in an `X509PKIPathv1` token; any other reference is refused. Set one or the other. See [Certification paths](#certification-paths). | | `PartnerCertificatePolicies` | empty | Certificate policy OIDs the partner's signing certificate, and every authority between it and the anchor, must assert. Used with `PartnerTrustAnchors`. | | `SignatureAlgorithm` | RSA-SHA256 | `http://www.w3.org/2001/04/xmldsig-more#rsa-sha256` | | `DigestAlgorithm` | SHA-256 | `http://www.w3.org/2001/04/xmlenc#sha256` | | `DataEncryptionAlgorithm` | AES-128-GCM | `http://www.w3.org/2009/xmlenc11#aes128-gcm` | | `KeyTransportAlgorithm` | RSA-OAEP | `http://www.w3.org/2009/xmlenc11#rsa-oaep` | | `MaskGenerationAlgorithm` | MGF1-SHA256 | `http://www.w3.org/2009/xmlenc11#mgf1sha256` | | `KeyTransportDigestAlgorithm` | SHA-256 | OAEP digest. | | `TimestampTtl` | null | Lifetime of a `wsu:Timestamp` in what we sign; none by default, since Domibus' eDelivery policy (Strict layout, no IncludeTimestamp) rejects one. A received timestamp is always checked. | | `TimestampTolerance` | 5 min | Clock skew accepted on the partner's `wsu:Timestamp`: how far ahead its `Created` may lie and how long past its `Expires` (WSS4J futureTimeToLive). | | `TimestampTimeToLive` | 5 min | How old a received `Created` may be (WSS4J timeStampTTL). It bounds a replay whatever `Expires` says. | | `CompressPayloads` | true | Gzip what we send. Received payloads are decompressed whenever their part properties say so. | | `RequireFourCornerProperties` | true | Whether every message must carry `originalSender` and `finalRecipient`, on sending and on receipt. False for a point-to-point agreement (common profile without the Four Corner enhancement). | The algorithm properties accept exactly the eDelivery AS4 1.16 set listed above; any other URI stops the endpoint from starting. On receipt a message is matched to one partner the way Domibus and Holodeck match a P-Mode: it must be addressed to our `OurPartyId`; its sender, service and action must be those of a partner's request leg or reply leg; an `AgreementRef`, when the partner declares one, must match. Two partners that a message could not tell apart are rejected when the node is validated. --- ### Certification paths By default an agreement **pins** the partner's signing certificate: the signer of a message must be one of `PartnerSigningCertificates`, whatever form the reference to it takes. The other model trusts an **authority**: the partner presents its certificate together with its certification path in an `X509PKIPathv1` security token (WS-Security X.509 Token Profile §3.1.2), and the path is validated up to one of `PartnerTrustAnchors` (eDelivery AS4 1.16 §4.3.3). ```csharp new As4Partner { Name = "acme", // ... KeyReference = As4KeyReference.PkiPath, // we present our path: SigningCertificate + SigningCertificateChain PartnerTrustAnchors = { acmeIssuingAuthority }, // acme must present its path, leading here PartnerCertificatePolicies = { "1.3.6.1.4.1.99999.1.1" }, PartnerEncryptionCertificate = acmeCertificate, // the recipient of the key is still named by its certificate } ``` A path is validated from the anchor down (RFC 5280 §6.1). The anchor is the certificate of the path nearest to the signer that is one of `PartnerTrustAnchors`, or the anchor that issued the first certificate of the path. An anchor may be an intermediate authority; a certificate that is its own authority is a path of one and is trusted when it is itself the anchor. The path is accepted when the whole token is a path — every certificate issued by the one before it (the name and the signature), every issuer a certification authority whose key may sign certificates (key usage `keyCertSign`, when the certificate restricts the key at all) — and, from the anchor down, every authority's path length constraint allows the authorities below it, everything is within its validity period, and the signer and the authorities below the anchor assert the required policies (`anyPolicy` satisfies each). A signer that does not present a path is refused with `EBMS:0101` even when its certificate would chain: the agreement asks for the path. The two directions are independent: `KeyReference` says how we sign, `PartnerTrustAnchors` how the partner must. With `RevocationMode` set on the node, the signer and the authorities below the anchor are checked for revocation, under the same rules as a pinned certificate: hard-fail when the status cannot be determined unless `RevocationSoftFail`, and a certificate that names no CRL distribution point and no authority information access passes. The CRLs are checked on a chain that ends at a self-signed root, which .NET requires on Windows and on Linux alike; under an intermediate anchor the chain is completed from what the token carries above it, the other `PartnerTrustAnchors` and, as for a pinned certificate, the local certificate stores and the anchor's authority information access. The certificates found there serve the revocation check only: they are not trusted for anything. When no root is found, the status cannot be determined. The reference to a path token carries `wsse11:TokenType` (WS-I Basic Security Profile 1.1, R5215): Domibus and Holodeck refuse it otherwise. --- ## Sending (producer) ```csharp using redb.Route.As4.Fluent; From("direct://outbound") .SetHeader(As4Headers.OriginalSender, "urn:example:c1") .SetHeader(As4Headers.FinalRecipient, "urn:example:c4") .To(As4.Send("https://ap.acme.example/as4").ConnectionFactory("node").Partner("acme")); ``` **Where it goes.** The address is the send URI's, or the partner's `Address` when the URI has none. With the address in the agreement, one endpoint sends to whichever partner a message names, each at its own access point: ```csharp var acme = new As4Partner { Name = "acme", Address = "https://ap.acme.example/as4", /* ... */ }; var globex = new As4Partner { Name = "globex", Address = "https://msh.globex.example/domibus?domain=edelivery", /* ... */ }; From("direct://outbound") .To(As4.Send().ConnectionFactory("node").Partner("${header.partner}")); // as4:?connectionFactory=node&partner=... ``` An address in both places is refused, at start for a fixed partner and per message for one chosen by an expression; so is a send with no address at all. A body that is not a list of `As4Payload` (see below) is sent as one payload: `byte[]` as is, `string` as UTF-8, `Stream` copied (not buffered, and not closed: the exchange owns it), anything else as its UTF-8 `ToString()`. The payload is compressed, encrypted and written to the wire through the core stream cache, so a large one goes through a temporary file, not memory. Its media type is `Message.ContentType` (default `application/octet-stream`). The eDelivery four-corner properties `originalSender` and `finalRecipient` are mandatory by default: without the two headers the message is refused before anything is sent. They belong to the Four Corner Topology enhancement of the profile (§4.1.2), so a point-to-point agreement turns the requirement off with `RequireFourCornerProperties = false`. Any other `redbAs4.property.` header becomes an `eb:Property`; `redbAs4.propertyType.` gives it a `type`. **Several payloads.** A body that is a list of `As4Payload` is sent as that many payloads, `eb:PartInfo` in the order of the list; the first is the leading business document. An entry names its Content-ID (null generates one), its media type and its part properties, written next to `MimeType` and `CompressionType`, which the connector sets itself. An empty list sends a message without payloads, as a simple SOAP message. ```csharp .Process(e => e.In.Body = new List { new("invoice@us.example", "application/xml", invoiceStream, new Dictionary { ["CharacterSet"] = "utf-8" }), new(null, "application/pdf", scanStream, new Dictionary()), }) .To(As4.Send("https://ap.acme.example/as4").ConnectionFactory("node").Partner("acme")); ``` The producer waits for the partner's HTTP response and verifies the receipt: signed by one of the partner's certificates, naming exactly the digests we signed. The outcome is on `exchange.Out` (InOut): `redbAs4.receiptValid = true`, `redbAs4.receiptMessageId`, and the raw signal as the body. | Outcome | Exception | |---|---| | The partner answers with an ebMS error | `As4ErrorSignalException` (`ErrorCode`, `Description`, `ErrorDetail`) | | No receipt in the response, or no response within `timeout` | `As4ReceiptException` (`EBMS:0301` MissingReceipt) | | Receipt with a bad signature or other digests | `As4ReceiptException` (`EBMS:0302` InvalidReceipt) | ### Send options | URI option | DSL | Default | Meaning | |---|---|---|---| | `connectionFactory` | `.ConnectionFactory(name)` | — (required) | Registry name of the node. | | `partner` | `.Partner(nameOrExpression)` | — (required) | Partner name; may be an expression such as `${header.partner}`. | | `service` | `.Service(value)` | agreement | Overrides `eb:Service`; the agreement must allow it. | | `action` | `.Action(value)` | agreement | Overrides `eb:Action`; the agreement must allow it. | | `conversationId` | `.ConversationId(value)` | new id, or `redbAs4.conversationId` | `eb:ConversationId`. | | `refToMessageId` | `.RefToMessageId(value)` | `redbAs4.refToMessageId`, else none | Set on the reply of a Two-Way exchange; the message then uses the partner's `ReplyLeg`. | | `addressQuery` | in the URL of `As4.Send(...)` | none | Query of the partner's address, without `?`, as one encoded value: the query of an `as4` URI holds the options. Domibus serves its domains so: `As4.Send("https://ap/domibus?domain=x")` gives `as4s://ap/domibus?addressQuery=domain%3Dx`. | | `timeout` | `.Timeout(ms)` | 60000 | Milliseconds to wait for the response with the receipt; 0 = no limit. | | `transacted` | — | — | `true` is refused when the URI is bound: eDelivery requires a synchronous receipt, so a send is never deferred to a transaction. | `https://` in `As4.Send(...)` maps to the `as4s` scheme. ### Retries Retries are the route's `OnException`. The producer puts `redbAs4.messageId` on the exchange before the first attempt and keeps the signed request on the exchange: a redelivery sends **the same message, byte for byte** — the same id and signature — so the partner detects the duplicate, and a receipt it stored for the first transmission (Domibus does so) still names what we signed: ```csharp OnException() .MaximumRedeliveries(5) .RedeliveryDelay(TimeSpan.FromSeconds(30)) .UseExponentialBackOff() .Handled() .To("direct://as4-undelivered"); // dead letter after the last attempt ``` A `Stream` body is read from its start on every attempt when it can seek. A forward-only one (a network stream) can be read once: to redeliver it, cache it in the route with `.StreamCaching()` before the send. Redelivery waits in memory, and a restart loses the exchange being retried. For retry schedules of hours, keep the message in your own outbox (a redb object with the `redbAs4.messageId` it was first sent with) and let a `timer:` route resend what has no receipt yet — with the same id, so the partner still detects it. Such a resend runs on a new exchange and is a new transmission (signed again): a partner that answers a duplicate with the receipt it stored for the first transmission, as Domibus does, returns one that names the first signature, and the resend fails with `EBMS:0302`. The partner did receive the message; the outbox can treat that answer to a resend as delivered. --- ## Receiving (consumer / access point) ```csharp context.AddIdempotentRepository("as4-in", new InMemoryIdempotentRepository(TimeSpan.FromDays(7))); From(As4.Receive("/as4/in").Port(4090).ConnectionFactory("node").IdempotentRepository("as4-in")) .Choice() .When(e => e.In.GetHeader(As4Headers.Partner) == "acme").To("direct://acme-invoices") .End(); ``` One URL serves every partner of the node. For each request the receiver, in order: 1. parses the envelope with the core `SafeXml`: no DTD, at most `maxEnvelopeCharacters`, the structure of an eDelivery envelope (see [Security notes](#security-notes)). A malformed envelope, a DOCTYPE or an envelope over a limit is a SOAP Fault `Sender` (400), an unknown header with `mustUnderstand` a `MustUnderstand` fault (500); 2. reads `eb:Messaging` strictly — a signal (receipt / error) without a waiting sender is answered 202 and logged, since the profile forbids asynchronous signals; 3. matches the message to one partner (`EBMS:0001` / `EBMS:0010` when none or more than one); 4. enforces the profile: unsigned → `EBMS:0010`, unencrypted → `EBMS:0103`; decrypts (`EBMS:0102`), verifies the signature and `wsu:Timestamp` (`EBMS:0101`), checks the attachments against `eb:PayloadInfo` (`EBMS:0007` / `EBMS:0011`), decompresses with a size limit (`EBMS:0303`); 5. claims the message id in the idempotent repository — a message received before gets its receipt again and never reaches the route; 6. runs the route, then answers: route failed or marked rollback-only → ebMS error (a `MalformedRequestException` → `EBMS:0003` with its own text, anything else → `EBMS:0004` with a reference to the exchange); otherwise a signed receipt with the non-repudiation digests. The partner never reads the text of our exceptions: errors carry the code's fixed description and a reference that finds the full story in our log. **Body.** One payload is the body itself with its original `Message.ContentType`: `byte[]` by default, a `Stream` with `streamBody=true` (closed by the exchange when it ends, as the File and S3 consumers hand theirs). A message with several payloads has a list of `As4Payload` as the body, ready for `.Split()`; each `Content` is a stream the exchange releases when it ends, so read it inside the route. **Large messages.** The request and every payload are spooled by the core `StreamCache` (memory up to its threshold, 128 KB by default, then a temporary file deleted on close): MimeKit reads the parts from the spooled request, AES-GCM decrypts by stream (BouncyCastle), gzip inflates by stream with its bound. A payload reaches the route only after its GCM tag and the signature are verified; a spool that fails a check is discarded. ### Receive options | URI option | DSL | Default | Meaning | |---|---|---|---| | `connectionFactory` | `.ConnectionFactory(name)` | — (required) | Registry name of the node. | | `idempotentRepository` | `.IdempotentRepository(name)` | — (required) | Name of an `IIdempotentRepository` registered with `context.AddIdempotentRepository`. See [Duplicate detection](#duplicate-detection). | | `inFlightClaimTimeout` | `.InFlightClaimTimeout(ms)` | 600000 ms | Age past which an unconfirmed claim of a message id is taken over; a resend under a younger claim is answered `rejectStatusCode`. See [Duplicate detection](#duplicate-detection). | | `streamBody` | `.StreamBody()` | false | Hand a single payload to the route as a `Stream` instead of `byte[]`. | | `payloadList` | `.PayloadList()` | false | Always hand the payloads as a list of `As4Payload` (one entry for a single payload, none for a message without), with Content-IDs and part properties. Takes precedence over `streamBody`. | | `host` | `.Host(host)` | `0.0.0.0` | Bind address. | | `port` | `.Port(port)` | `4090` | Listen port. | | scheme `as4s` | `.Tls(certPath?, password?)` | HTTP | Serve over HTTPS; the certificate from the URI, else the node. With neither the receiver refuses to start. | | `clientCertificateMode` | `.ClientCertificate(mode, thumbprints?)` | the node's, else `NoCertificate` | `AllowCertificate` / `RequireCertificate` asks partners for a TLS client certificate (needs TLS; without it the receiver refuses to start). | | `allowedClientThumbprints` | same | the node's, else any valid | Comma-separated thumbprints an accepted client certificate must match; any other is refused in the handshake. | | `maxRequestBodySize` | `.MaxRequestBodySize(bytes)` | 100 MB | Upper bound on a request body. | | `maxEnvelopeCharacters` | `.MaxEnvelopeCharacters(n)` | 1 M | Upper bound on the SOAP envelope; payloads are attachments and not counted. | | `maxConcurrentRequests` / `requestQueueLimit` | `.MaxConcurrentRequests(max, queue)` | 0 (unlimited) / 0 | Admission limit per endpoint; overflow is shed before any MIME or crypto work. | | `rejectStatusCode` / `retryAfterSeconds` | — | `503` / `1` | Answer to a shed request and to a resend while the first copy is in the route; an AS4 sender retries on 503. | A receive endpoint takes no `partner`: it accepts every partner of its node. ### Duplicate detection Required by the profile, so `idempotentRepository` is mandatory — it is the same contract the route-level `IdempotentConsumer` and the S3 consumer use. The `eb:MessageId` is claimed only after the security checks, so a forged message cannot take the id of a real one. The claim is confirmed when the route succeeds and released when it fails, so the sender's resend is then delivered. A failure of the repository itself is answered with `EBMS:0004` and the route is not run. - **The store decides what survives.** `InMemoryIdempotentRepository` forgets on restart and does not see a resend that reaches another cluster node: behind a load balancer use the redb or SQL repository. - **The duplicate window is the repository's `Ttl`.** Keep it longer than the sender's whole retry schedule. - **One repository per receive endpoint.** Its keys are `eb:MessageId` as it is, as Domibus and Holodeck keep them: the id is globally unique by the ebMS contract. A repository shared with another route's business keys, or a partner reusing another partner's id, makes a new message look like a duplicate: it gets a receipt and is not delivered. - **A resend that arrives while the first copy is still in the route is not a duplicate yet.** The first copy may still fail and release its claim, and a receipt would have told the sender the message arrived. The resend is answered `rejectStatusCode` (503) with `Retry-After` and no ebMS signal, and the sender resends it; by then the first copy is confirmed (the resend gets its receipt) or released (the resend is delivered). A claim never confirmed and older than `inFlightClaimTimeout` (10 minutes) was left by a stopped node: it is taken over and the message processed. 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 and gets a receipt. - **Keep `inFlightClaimTimeout` far above the longest processing time.** A node that is still processing when its claim is taken over has the message delivered a second time by the new holder. When it finishes it 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. On the redb repository the timeout must also stay above the clock skew between nodes. The default of 10 minutes does both for a route that answers within the sender's HTTP timeout. - **What a sender does with the 503**, measured against Harmony 2.6.2 (Domibus 5.1) with the P-Mode reception awareness `retry="2;1;CONSTANT"` and real user messages: a 503 is retried at the P-Mode interval (two minutes there) and the retry delivered; `Retry-After` is ignored; an ebMS error of severity Failure (`EBMS:0004`) is retried the same way; messages of Domibus' own test service are never retried. The default `retryAfterSeconds` of 1 suits such a sender; for a partner whose gateway honours `Retry-After`, give a larger value (30 to 60 seconds), or a resend arriving every second keeps meeting the first copy in the route. - **A duplicate gets the very receipt of the original** (same receipt id, time and signature), as Domibus answers and as conformance test AS4_CP_TA63 checks. The node keeps the receipts it sends in `ReceiptStore` of the connection factory, any `IClaimCheckRepository` (SQL, Redis, file), for `ReceiptRetention` (default one day). Without a store they are kept in memory, the newest 100 000; give a shared store behind a load balancer, as for the duplicate repository. A duplicate whose receipt is no longer kept gets a new receipt for the same message, with the same non-repudiation information. - **Business duplicates** (the same invoice sent as two messages) are a route concern: `.IdempotentConsumer(...)` on a business key. --- ## Headers All connector headers start with `redbAs4.` (`As4Headers`). | Header | Direction | Value | |---|---|---| | `messageId` | both | `eb:MessageId`. On send, set before the first attempt (or taken from the exchange). | | `refToMessageId` | both | `eb:RefToMessageId`. | | `timestamp` | receive | `eb:Timestamp`. | | `conversationId` | both | `eb:ConversationId`. | | `fromPartyId`, `fromPartyIdType`, `fromRole` | receive | Sender party. | | `toPartyId`, `toPartyIdType`, `toRole` | receive | Recipient party. | | `service`, `serviceType`, `action` | both | Business collaboration; on send they override the agreement when allowed. | | `agreementRef`, `pmode` | receive | `eb:AgreementRef` and its `@pmode`. | | `property.` | both | `eb:MessageProperties`; `property.originalSender` and `property.finalRecipient` are mandatory unless the agreement sets `RequireFourCornerProperties = false`. | | `propertyType.` | both | The `type` attribute of that message property; absent when it has none. | | `partner` | both | Name of the partner the message was matched to or sent to. | | `signatureValid`, `signerThumbprint` | receive | Signature verified; thumbprint of the signing certificate. | | `remoteAddress` | receive | Address of the peer. | | `clientCertThumbprint`, `clientCertSubject`, `clientCertNotAfter` | receive | The TLS client certificate the partner presented (mutual TLS), as the SOAP receiver reports it. | | `receiptValid`, `receiptMessageId` | send (on Out) | Receipt verified; its `eb:MessageId`. | --- ## Security notes - **Own XML Signature processing.** .NET `SignedXml` cannot resolve `cid:` references to attachments, so the connector processes `ds:Reference` and `SignedInfo` itself (Attachment-Content-Signature-Transform, exclusive C14N through the public `XmlDsigExcC14NTransform`, RSA PKCS#1 v1.5). - **Untrusted XML** goes through the core `SafeXml` only: DTDs are refused, and the reader checks the structure while it reads, before anything is built. A received envelope, and the partner's answer to a send, may be at most 32 levels deep, with 32 attributes and 16 namespace declarations on an element, 4096 namespace declarations in all and `maxEnvelopeCharacters` characters: two to four times what Domibus, Holodeck B2B and this connector send. These are the profile's shape and not options. An uncompressed XML payload is canonicalized for its digest with the core's default limits (depth 256, 1024 attributes, 256 namespace declarations on an element); over them its signature fails, `EBMS:0101`. - **Decryption work is bounded**: a message carries exactly one `xenc:EncryptedKey` (each costs an RSA private-key operation, and anyone can encrypt for our certificate), and each payload is decrypted once; anything else is `EBMS:0102`. The signature over `SignedInfo` is checked before any reference is digested, so references a forger adds cost nothing but one canonicalization of a bounded `SignedInfo`. - **Signature wrapping**: duplicate `wsu:Id` values are refused, and every reference must cover what the profile requires (the `eb:Messaging` header, the body, every attachment). - **Replay**: a received `wsu:Timestamp` is checked as WSS4J checks it (Domibus and Holodeck verify with it): `Created` required, not ahead beyond `TimestampTolerance`, not older than `TimestampTimeToLive`; `Expires` optional and not passed. Plus duplicate detection by message id. - **No oracle**: decryption and signature failures carry the detail only in our log. - **Unsigned errors to an unknown sender**: an error answered before the message is matched to a partner (broken MIME, no agreement) is not signed, since there is no agreement saying how; once the partner is known, errors are signed. - **Certificate validity**: a pinned certificate is still checked for its validity period, as Domibus does by default: the partner's signing certificate on every received message and receipt (`EBMS:0101`), our signing certificate and the partner's encryption certificate before anything is sent, and an allow-listed TLS client certificate in the handshake (a pin narrows validation, it never replaces it). With `RevocationMode` set, revocation is checked for all of them; a certificate that names no CRL distribution point and no AIA passes, as in Domibus. - **One `eb:PartyId` per side**: more is refused with `EBMS:0010`, as phase4 and Holodeck refuse it. - **Principal**: the exchange principal is the envelope signer (`As4AuthenticationTypes.Signature`: the partner name, the certificate subject and thumbprint), then the TLS client certificate (`As4AuthenticationTypes.ClientCertificate`), then what the host's principal resolver adds, as camel-cxf with WSS4J takes the principal from the signature. - **Attachment canonicalization**: an uncompressed attachment is signed over its MIME canonical form (SwA 1.1 §5.4.2, the WSS4J rules): Exclusive C14N for XML types, CRLF line endings for other `text/*`. - **Four-corner properties** are required on receipt too, unless the agreement sets `RequireFourCornerProperties = false`: a message without `originalSender` or `finalRecipient` is answered `EBMS:0010`, as Domibus answers it. - Passwords are `[Sensitive]` and redacted in logs and the dashboard. --- ## What we refuse The connector implements the eDelivery AS4 1.16 common profile and nothing wider. Each line below is a wall a partner outside the profile hits; the answer is the one it gets. | What | Accepted | Anything else | |---|---|---| | Signing token | pinned agreement: any reference form; agreement with `PartnerTrustAnchors`: an `X509PKIPathv1` token whose path leads to an anchor | `EBMS:0101`; `EBMS:0004` when the certificate is one the node trusts for another party (another agreement's, or issued by a trust anchor of one of its agreements): an impersonation, as the conformance test driver expects | | Signature | RSA-SHA256 | the partner's configuration is refused at start; a received message: `EBMS:0101`; a `ds:SignatureValue` that is not base64 (non-canonical base64 included): `EBMS:0102`, as the conformance test driver expects | | Digest | SHA-256 | as above | | Payload encryption | AES-128-GCM | refused at start; a received message: `EBMS:0102` (AES-256-GCM, AES-128-CBC) | | Key transport | RSA-OAEP with MGF1-SHA256 and SHA-256 | refused at start; a received message: `EBMS:0102` (`rsa-oaep-mgf1p` of XML Encryption 1.0) | | Canonicalization | Exclusive C14N | `EBMS:0101` | | Reference transforms | exactly one `ds:Transform` per reference; Attachment-Content for an attachment | `EBMS:0101`; an attachment signed with another transform (Attachment-Complete): `EBMS:0102`, as the conformance test driver expects | | Signature coverage | `eb:Messaging`, `soap:Body`, every attachment | `EBMS:0103`, as Domibus answers from its policy (`sp:SignedParts`); a `wsu:Timestamp` that is present and not covered: `EBMS:0101` | | Envelope structure | depth 32, 32 attributes and 16 namespace declarations on an element, 4096 namespace declarations, `maxEnvelopeCharacters` | SOAP Fault `Sender` | | Session keys | exactly one `xenc:EncryptedKey`, each payload decrypted once | `EBMS:0102` | | Unsigned message | never | `EBMS:0010` (the processing mode asks for a signature), as the conformance test driver expects | | Unencrypted payloads | never | `EBMS:0103` | | Payload in the SOAP body | never (payloads are attachments) | `EBMS:0002` | | Compression | gzip, with `MimeType` | `EBMS:0303` / `EBMS:0003` | | `eb:PartyId` per side | exactly one | `EBMS:0010` | | Four-corner properties | `originalSender` and `finalRecipient` present, unless the agreement does not require them | `EBMS:0010` | | MEP | one-way and two-way push, on the default MPC | a pull request: `EBMS:0010` (as Domibus without a pull process); another `mpc`: `EBMS:0001` (as Domibus); an unsolicited receipt or error: 202, logged | --- ## What it was tested with **Automated suite** (`redb.Route/tests/redb.Route.Tests.As4`; last full run 2026-09-28, all green on **net8.0, net9.0 and net10.0**; the live tests below skip when their stand is down unless `REDB_AS4_INTEROP=1`): | Area | What is covered | |---|---| | Endpoint model | URIs and DSL, option validation, node and partner validation, ambiguous agreements, start-time failures. | | Security | Sign / verify and encrypt / decrypt round trips for all three key references; tampering, a stranger's key, an expired timestamp, duplicate `wsu:Id`, an uncovered attachment. | | Messaging | Strict `eb:Messaging` reader and writer, SwA MIME, payload consistency, gzip with a size limit. | | Producer | Against a loopback partner that decrypts, verifies and answers: verified receipt, ebMS error, no receipt, no response within the timeout, receipt with other digests, receipt signed by a stranger, missing four-corner properties, reply leg; route-level redelivery with the same message id and dead letter after the last attempt; a forward-only `Stream` body sent and left open, a seekable one resent from its start. | | Consumer | Loopback (our sender → our receiver) and raw requests: every refusal answered with its ebMS code or SOAP fault, exception text never sent, rollback-only never acknowledged, duplicates acknowledged without a second delivery, a resend after a route failure or an aborted request delivered, repository failure, a claim taken uncancelled; `streamBody`, a large payload spooled to disk, several payloads as released streams; an envelope without `Body` or `Header`, two `wsse:Security` headers, an unexpected failure answered `EBMS:0004`, `mustUnderstand` only for the roles we play. | | Hardening | `wsu:Timestamp` by the WSS4J rules (no `Created`, too old, from the future, expired), a partner response over `maxResponseBodySize`, options of the other side refused (`[EndpointRole]`), a partner address with a query posted to that query and one with a fragment refused. | | Engine | Admission limits (503, counted once as rejected), the shared host of a module host (container, context service, an HTTP and an AS4 route on one port), the drain on stop, statistics once per event (in, error, refusal, out), one trace across sender and receiver, `.Transacted()` commit and rollback, principal from the signer and the TLS client, a node and route from Route-XML. | | Transport security | Real loopback TLS handshakes: a TLS receiver without a certificate refuses to start, one with a certificate leaves no plaintext port, the certificate from the node, mutual TLS accepting an allow-listed client certificate (and reporting it on the exchange), refusing a missing or foreign one in the handshake. | | Profile | MIME canonical form of uncompressed attachments (XML, text, binary, a CRLF split across reads, a DTD refused), four-corner properties required on receipt, signer outside its validity period, a stranger with the partner's subject, expired own or partner certificates refused before sending. | **Live interop with Holodeck B2B 8.1.1** (Docker stand described in the test files, `As4HolodeckLiveTests` and `As4HolodeckReferenceTests`; runs of 2026-09-25 to 2026-09-28): | Direction | Scenario | Result | |---|---|---| | Holodeck → Holodeck | Reference capture of a signed, encrypted, gzipped push | our reader verifies Holodeck's signature and digests and decrypts AES-128-GCM | | redb → Holodeck | Push signed + encrypted + compressed, each of `BinarySecurityToken`, `IssuerSerial`, `KeyIdentifier` | Holodeck delivers the payload and answers with a receipt whose non-repudiation digests match ours | | Holodeck → redb | Holodeck pushes to our receiver | the route gets the document; Holodeck accepts our signed receipt | | redb → Holodeck | Uncompressed `text/xml`, `application/xml`, `text/plain` whose raw and canonical bytes differ | Holodeck verifies our signature over the canonical form and answers with a receipt | **Live interop with Harmony AP 2.6.2** (NIIS; its MSH is **Domibus 5.1**, the eDelivery reference implementation; Docker stand described in the test file `As4HarmonyLiveTests`; runs of 2026-09-26): | Direction | Scenario | Result | |---|---|---| | redb → Domibus | Push signed + encrypted + compressed, each of the three key references | Domibus verifies and receives it (`RECEIVED`); we verify its receipt | | redb → Domibus | Uncompressed XML whose raw and canonical bytes differ | Domibus verifies the signature over the canonical form | | redb → Domibus | A redelivery on the same exchange | the same bytes: Domibus answers with the receipt it stored, which we verify | | Domibus → redb | Domibus' ebMS test message | the route gets it; Domibus accepts our receipt (`ACKNOWLEDGED`) | Not covered live: TLS on the wire with a partner MSH (both stands run plain HTTP; TLS and mutual TLS are tested on loopback handshakes above), and Pull and asynchronous receipts, which are out of scope. --- ## Status & maturity | Phase | Scope | State | |---|---|---| | 0 | Endpoint skeleton, node and partner model | done | | 1 | WS-Security: signature over attachments, AES-128-GCM, three key references | done, proven against Holodeck | | 2 | ebMS model, SwA MIME, compression | done | | 3 | Send push, verify receipt and NRR | done, live | | 4 | Receive push, receipt or error after the unit of work | done, live | | 5 | Duplicate detection, redelivery with the same id | done | | streams | Spooled request and payloads, streamed AES-GCM, `streamBody` | done, live | | 7 | Rest of the profile, TLS / mutual TLS, MIME canonicalization of `text/*`, certificate validity | done | | 8 | Transactions, limits, statistics, telemetry, shared host, Route-XML | done by tests; live Tsak and Jaeger check with the release | | 9 | Interop: Holodeck both ways, Domibus both ways, redelivery | done, live | | review | Findings of 2026-09-28 (`docs/as4/REVIEW-2026-09-28.md`) R1–R10 | done | | 11 | Release: CHANGELOG, connector roadmap, VS Code catalog, packaging | done, released | | conformance | eDelivery conformance tests, AS4 Profile 1.16 Common Profile: 76 of 76 required tests (2026-11-04) | done for 4.6.1, listed by the European Commission 2026-11-19 | Asynchronous receipts (phase 6) and Pull (phase 10) are optional in the profile and out of scope for now. --- ## Cross-cutting Like every redb.Route connector, AS4 endpoints get statistics and health (`IEndpointStatistics`, visible in the Tsak dashboard). A message the receiver refuses as the partner's fault (malformed or oversized envelope, failed signature or decryption, not what the agreement allows) is counted in `Refused`, with the reason of the last one in `LastRefusalMessage`, and not in `Errors` or health: a partner with a broken configuration does not turn the route red. `EBMS:0004`, a failure on our side, and a failed route stay errors. AS4 endpoints also get distributed tracing on the core's transport contract: the receiver opens a `"{path} receive"` Consumer span (parent: 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), the sender a `"{partner} send"` Client span whose context it writes to the request. A refused message, a failed route, an unreachable partner or a missing or invalid receipt marks the span an error; `EnableTelemetry=false` opens neither. The receiver drains in-flight requests on shutdown in the order the HTTP family uses (unregister → drain → release the listener). Part of the redb.Route connector family. Path: redb-route/redb.Route.As4/Security/AesGcmCipher.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.As4/Security/AesGcmCipher.cs ---- using System.Security.Cryptography; using Org.BouncyCastle.Crypto; using Org.BouncyCastle.Crypto.Engines; using Org.BouncyCastle.Crypto.Modes; using Org.BouncyCastle.Crypto.Parameters; namespace redb.Route.As4.Security; /// /// AES-GCM as XML Encryption 1.1 lays it out: a 96-bit IV, then the ciphertext, then the 128-bit /// authentication tag, as one octet sequence (XML Encryption 1.1 §5.2.4). /// /// Streamed with BouncyCastle's : .NET's works on whole buffers /// only, and a payload may be larger than memory. GCM authenticates only at the end, so decrypted output is not /// trustworthy until returns: callers write it to a spool they discard on failure and hand /// it on only afterwards. /// /// internal static class AesGcmCipher { /// IV length in bytes. public const int IvSize = 12; /// Tag length in bytes. public const int TagSize = 16; private const int BufferSize = 81920; /// /// Decrypts IV || ciphertext || tag from into . Throws /// on a wrong key or tampered data — after writing unauthenticated output, /// which the caller must then discard. /// public static void Decrypt(byte[] key, Stream input, Stream output) { ArgumentNullException.ThrowIfNull(key); ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(output); var iv = new byte[IvSize]; if (input.ReadAtLeast(iv, IvSize, throwOnEndOfStream: false) < IvSize) throw new CryptographicException("AES-GCM data is shorter than its IV and tag."); var gcm = Cipher(forEncryption: false, key, iv); try { Pump(gcm, input, output); } catch (InvalidCipherTextException e) { // Too short for a tag, or the tag does not match: one exception for both, no oracle. throw new CryptographicException("AES-GCM authentication failed.", e); } } /// Encrypts with and a fresh IV into IV || ciphertext || tag. public static void Encrypt(byte[] key, Stream input, Stream output) { ArgumentNullException.ThrowIfNull(key); ArgumentNullException.ThrowIfNull(input); ArgumentNullException.ThrowIfNull(output); var iv = RandomNumberGenerator.GetBytes(IvSize); output.Write(iv); Pump(Cipher(forEncryption: true, key, iv), input, output); } private static GcmBlockCipher Cipher(bool forEncryption, byte[] key, byte[] iv) { var gcm = new GcmBlockCipher(new AesEngine()); gcm.Init(forEncryption, new AeadParameters(new KeyParameter(key), TagSize * 8, iv)); return gcm; } private static void Pump(GcmBlockCipher gcm, Stream input, Stream output) { var buffer = new byte[BufferSize]; // Room for what the cipher still holds from the previous call (under a block, plus the tag it withholds when decrypting). var result = new byte[BufferSize + 64]; int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { var written = gcm.ProcessBytes(buffer, 0, read, result, 0); output.Write(result, 0, written); } var final = new byte[gcm.GetOutputSize(0)]; var finalLength = gcm.DoFinal(final, 0); output.Write(final, 0, finalLength); } } Path: redb-route/redb.Route.As4/Security/As4SecurityEngine.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.As4/Security/As4SecurityEngine.cs ---- using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Xml; using redb.Route.As4.Mime; namespace redb.Route.As4.Security; /// /// WS-Security processing of AS4 messages: encrypting and decrypting the payload parts, signing and verifying /// (). Order on receipt is decrypt, then verify, then /// decompress — the reverse of compress, sign, encrypt on the sending side (AS4 profile §3.1). /// internal static class As4SecurityEngine { // ── Decryption ─────────────────────────────────────────────────────────── /// /// Decrypts every attachment the xenc:EncryptedKey elements of the security header list, in place: /// the part content becomes the plaintext and its type the xenc:EncryptedData/@MimeType. Returns /// the Content-IDs that were decrypted. Throws on anything that does /// not decrypt — callers answer every such failure with one code and one text (no decryption oracle). /// public static IReadOnlyList Decrypt(SwaMessage message, IEnumerable ourCertificates) { ArgumentNullException.ThrowIfNull(message); var ours = ourCertificates.Where(c => c.HasPrivateKey).ToList(); var security = SecurityHeader(message.Envelope); var decrypted = new List(); // One session key for all payloads, as eDelivery AS4 1.16 encrypts and as Domibus, Holodeck B2B and this // connector send. Every xenc:EncryptedKey costs an RSA private-key operation and anyone can encrypt for our // certificate, so more of them are refused before the first is opened: a large envelope full of keys would // otherwise buy seconds of CPU per request. var encryptedKeys = Children(security, "EncryptedKey", WsSecurityNames.Xenc).ToList(); if (encryptedKeys.Count > 1) throw new CryptographicException($"The security header carries {encryptedKeys.Count} xenc:EncryptedKey elements, not one."); foreach (var encryptedKey in encryptedKeys) { var keyInfo = SecurityTokenResolver.FirstChild(encryptedKey, "KeyInfo", WsSecurityNames.Ds) ?? throw new CryptographicException("xenc:EncryptedKey has no ds:KeyInfo."); var recipient = SecurityTokenResolver.Resolve(keyInfo, message.Envelope, ours) ?? throw new CryptographicException("xenc:EncryptedKey is not for any of our certificates."); var ourCertificate = ours.FirstOrDefault(c => c.Thumbprint == recipient.Thumbprint) ?? throw new CryptographicException("xenc:EncryptedKey is not for any of our certificates."); var sessionKey = UnwrapKey(encryptedKey, ourCertificate); var referenceList = SecurityTokenResolver.FirstChild(encryptedKey, "ReferenceList", WsSecurityNames.Xenc) ?? throw new CryptographicException("xenc:EncryptedKey has no xenc:ReferenceList."); foreach (var dataReference in Children(referenceList, "DataReference", WsSecurityNames.Xenc)) { var uri = dataReference.GetAttribute("URI"); if (!uri.StartsWith('#')) throw new CryptographicException($"xenc:DataReference '{uri}' does not point into the message."); var encryptedData = SecurityTokenResolver.FindById(message.Envelope, uri[1..], "EncryptedData", WsSecurityNames.Xenc) ?? throw new CryptographicException($"No xenc:EncryptedData carries the id '{uri[1..]}'."); var id = DecryptAttachment(encryptedData, sessionKey, message, decrypted); decrypted.Add(id); } } return decrypted; } private static byte[] UnwrapKey(XmlElement encryptedKey, X509Certificate2 ourCertificate) { var method = SecurityTokenResolver.FirstChild(encryptedKey, "EncryptionMethod", WsSecurityNames.Xenc) ?? throw new CryptographicException("xenc:EncryptedKey has no xenc:EncryptionMethod."); var algorithm = method.GetAttribute("Algorithm"); if (!As4Algorithms.IsSupportedKeyTransport(algorithm)) throw new CryptographicException($"Key transport '{algorithm}' is not supported."); // XML Encryption 1.1 RSA-OAEP names the digest and the mask generation function separately; .NET's // OAEP padding uses one hash for both, so only matching pairs are accepted. var digest = SecurityTokenResolver.FirstChild(method, "DigestMethod", WsSecurityNames.Ds)?.GetAttribute("Algorithm"); var mgf = SecurityTokenResolver.FirstChild(method, "MGF", WsSecurityNames.Xenc11)?.GetAttribute("Algorithm"); if (!As4Algorithms.IsSupportedDigest(digest) || !As4Algorithms.IsSupportedMaskGeneration(mgf)) throw new CryptographicException($"RSA-OAEP with digest '{digest}' and MGF '{mgf}' is not supported."); var cipher = CipherValue(encryptedKey); using var rsa = ourCertificate.GetRSAPrivateKey() ?? throw new CryptographicException("Our decryption certificate has no RSA private key."); return rsa.Decrypt(cipher, RSAEncryptionPadding.OaepSHA256); } private static string DecryptAttachment(XmlElement encryptedData, byte[] sessionKey, SwaMessage message, IReadOnlyList done) { if (encryptedData.GetAttribute("Type") != WsSecurityNames.AttachmentContentOnly) throw new CryptographicException($"xenc:EncryptedData of type '{encryptedData.GetAttribute("Type")}' is not supported."); var method = SecurityTokenResolver.FirstChild(encryptedData, "EncryptionMethod", WsSecurityNames.Xenc)?.GetAttribute("Algorithm"); if (!As4Algorithms.IsSupportedDataEncryption(method)) throw new CryptographicException($"Data encryption '{method}' is not supported."); var cipherData = SecurityTokenResolver.FirstChild(encryptedData, "CipherData", WsSecurityNames.Xenc) ?? throw new CryptographicException("xenc:EncryptedData has no xenc:CipherData."); var cipherReference = SecurityTokenResolver.FirstChild(cipherData, "CipherReference", WsSecurityNames.Xenc) ?? throw new CryptographicException("xenc:EncryptedData of an attachment has no xenc:CipherReference."); var uri = cipherReference.GetAttribute("URI"); if (!uri.StartsWith(WsSecurityNames.CidPrefix, StringComparison.OrdinalIgnoreCase)) throw new CryptographicException($"xenc:CipherReference '{uri}' does not name a MIME part."); var id = WsSecurityNames.ContentId(uri); if (!message.Parts.TryGetValue(id, out var part)) throw new CryptographicException($"The message has no MIME part with Content-ID '{id}'."); // Each part is decrypted once: references that name it again would read the whole part again for each. if (done.Contains(id, StringComparer.Ordinal)) throw new CryptographicException($"The MIME part '{id}' is referenced for decryption more than once."); // GCM authenticates only at the end: the plaintext goes to a spool that is discarded unless the tag verifies. part.Replace(message.Spooled(output => AesGcmCipher.Decrypt(sessionKey, part.OpenRead(), output))); var mimeType = encryptedData.GetAttribute("MimeType"); if (mimeType.Length > 0) part.ContentType = mimeType; return id; } // ── Encryption ─────────────────────────────────────────────────────────── /// /// Encrypts every attachment for with one fresh AES-128-GCM session key, /// transported by RSA-OAEP with SHA-256 and MGF1-SHA256 (eDelivery AS4 1.16). Each part's content becomes /// IV || ciphertext || tag and its type application/octet-stream; the original type is kept in /// xenc:EncryptedData/@MimeType. Call it after signing: signatures are over the plaintext. The key /// transport elements are placed first in the security header, as a WS-Security processor that prepends /// each step would leave them. /// public static void Encrypt(SwaMessage message, X509Certificate2 recipient, As4KeyReference keyReference) { ArgumentNullException.ThrowIfNull(message); ArgumentNullException.ThrowIfNull(recipient); if (message.Parts.Count == 0) return; var doc = message.Envelope; var parts = SoapParts.Of(doc); var security = parts.Security ?? SoapParts.AddSecurityHeader(doc, parts.Header); var sessionKey = RandomNumberGenerator.GetBytes(16); using var rsa = recipient.GetRSAPublicKey() ?? throw new CryptographicException("The recipient certificate has no RSA key."); var encryptedKey = doc.CreateElement("xenc", "EncryptedKey", WsSecurityNames.Xenc); var keyId = "EK-" + Guid.NewGuid().ToString("N"); encryptedKey.SetAttribute("Id", keyId); var keyMethod = As4Signature.Append(encryptedKey, "xenc", "EncryptionMethod", WsSecurityNames.Xenc); keyMethod.SetAttribute("Algorithm", As4Algorithms.RsaOaep); As4Signature.Append(keyMethod, "ds", "DigestMethod", WsSecurityNames.Ds).SetAttribute("Algorithm", As4Algorithms.Sha256); As4Signature.Append(keyMethod, "xenc11", "MGF", WsSecurityNames.Xenc11).SetAttribute("Algorithm", As4Algorithms.Mgf1Sha256); // The key transport block goes first; the recipient's token, if referenced by BST, before it. security.PrependChild(encryptedKey); // A certification path is how a signer presents itself; the recipient of the key is named by its certificate. var recipientReference = keyReference == As4KeyReference.PkiPath ? As4KeyReference.BinarySecurityToken : keyReference; encryptedKey.AppendChild(SecurityTokenResolver.CreateKeyInfo(doc, security, recipient, recipientReference, insertTokenBefore: encryptedKey)); var cipherData = As4Signature.Append(encryptedKey, "xenc", "CipherData", WsSecurityNames.Xenc); As4Signature.Append(cipherData, "xenc", "CipherValue", WsSecurityNames.Xenc).InnerText = Convert.ToBase64String(rsa.Encrypt(sessionKey, RSAEncryptionPadding.OaepSHA256)); var referenceList = As4Signature.Append(encryptedKey, "xenc", "ReferenceList", WsSecurityNames.Xenc); XmlNode after = encryptedKey; foreach (var part in message.Parts.Values) { var dataId = "ED-" + Guid.NewGuid().ToString("N"); As4Signature.Append(referenceList, "xenc", "DataReference", WsSecurityNames.Xenc).SetAttribute("URI", "#" + dataId); var encryptedData = doc.CreateElement("xenc", "EncryptedData", WsSecurityNames.Xenc); encryptedData.SetAttribute("Id", dataId); encryptedData.SetAttribute("MimeType", part.ContentType); encryptedData.SetAttribute("Type", WsSecurityNames.AttachmentContentOnly); As4Signature.Append(encryptedData, "xenc", "EncryptionMethod", WsSecurityNames.Xenc).SetAttribute("Algorithm", As4Algorithms.Aes128Gcm); var dataKeyInfo = As4Signature.Append(encryptedData, "ds", "KeyInfo", WsSecurityNames.Ds); var str = As4Signature.Append(dataKeyInfo, "wsse", "SecurityTokenReference", WsSecurityNames.Wsse); var tokenType = doc.CreateAttribute("wsse11", "TokenType", WsSecurityNames.Wsse11); tokenType.Value = "http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey"; str.Attributes.Append(tokenType); As4Signature.Append(str, "wsse", "Reference", WsSecurityNames.Wsse).SetAttribute("URI", "#" + keyId); var dataCipher = As4Signature.Append(encryptedData, "xenc", "CipherData", WsSecurityNames.Xenc); var cipherReference = As4Signature.Append(dataCipher, "xenc", "CipherReference", WsSecurityNames.Xenc); cipherReference.SetAttribute("URI", WsSecurityNames.CidUri(part.ContentId)); var transforms = As4Signature.Append(cipherReference, "xenc", "Transforms", WsSecurityNames.Xenc); As4Signature.Append(transforms, "ds", "Transform", WsSecurityNames.Ds).SetAttribute("Algorithm", WsSecurityNames.AttachmentCiphertextTransform); security.InsertAfter(encryptedData, after); after = encryptedData; part.Replace(message.Spooled(output => AesGcmCipher.Encrypt(sessionKey, part.OpenRead(), output))); part.ContentType = "application/octet-stream"; } } // ── Signature ──────────────────────────────────────────────────────────── /// Verifies the message signature; see . public static SignatureVerification Verify(SwaMessage message, IReadOnlyCollection partnerCertificates, TimeSpan timestampTolerance, DateTimeOffset now, RevocationPolicy? revocation = null, TimeSpan? timestampTimeToLive = null, PkiPathTrust? pkiPath = null, IReadOnlyCollection? trustedElsewhere = null) => As4Signature.Verify(message, partnerCertificates, timestampTolerance, now, revocation, timestampTimeToLive, pkiPath, trustedElsewhere); /// Signs the message; see . public static IReadOnlyList Sign(SwaMessage message, X509Certificate2 signer, As4KeyReference keyReference, TimeSpan? timestampTtl, DateTimeOffset now, IReadOnlyList? signingPath = null) => As4Signature.Sign(message, signer, keyReference, timestampTtl, now, signingPath); // ── Helpers ────────────────────────────────────────────────────────────── private static XmlElement SecurityHeader(XmlDocument envelope) { var root = envelope.DocumentElement ?? throw new CryptographicException("The envelope is empty."); var header = SecurityTokenResolver.FirstChild(root, "Header", WsSecurityNames.Soap12) ?? throw new CryptographicException("The envelope has no SOAP 1.2 header."); var securities = Children(header, "Security", WsSecurityNames.Wsse).ToList(); return securities.Count == 1 ? securities[0] : throw new CryptographicException($"The SOAP header carries {securities.Count} wsse:Security headers, not one."); } private static IEnumerable Children(XmlElement parent, string localName, string ns) => parent.ChildNodes.OfType().Where(e => e.LocalName == localName && e.NamespaceURI == ns); private static byte[] CipherValue(XmlElement encrypted) { var cipherData = SecurityTokenResolver.FirstChild(encrypted, "CipherData", WsSecurityNames.Xenc) ?? throw new CryptographicException($"xenc:{encrypted.LocalName} has no xenc:CipherData."); var value = SecurityTokenResolver.FirstChild(cipherData, "CipherValue", WsSecurityNames.Xenc) ?? throw new CryptographicException($"xenc:{encrypted.LocalName} has no xenc:CipherValue."); return SecurityTokenResolver.Base64(value); } } Path: redb-route/redb.Route.As4/Security/As4Signature.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.As4/Security/As4Signature.cs ---- using System.Globalization; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Xml; using redb.Route.As4.Mime; namespace redb.Route.As4.Security; /// /// XML Signature as the AS4 profile uses it, without System.Security.Cryptography.Xml.SignedXml: /// SignedXml refuses every reference that is not a same-document #id, so it cannot digest the /// cid: references to attachments (dotnet/runtime, Reference.CalculateHashValue). Canonicalization /// is the .NET exclusive c14n transform (); the rest — reference /// processing and the RSA signature over the canonical ds:SignedInfo — is here, restricted to what the /// eDelivery AS4 1.16 common profile uses: exclusive c14n, SHA-256, RSA-SHA256, the SwA /// Attachment-Content-Signature-Transform. Anything else is refused, not interpreted. /// internal static class As4Signature { // ── Verification ───────────────────────────────────────────────────────── /// /// Verifies the single ds:Signature of the security header over the current message content (after /// decryption), resolves the signer from its key reference, accepts it only if it is one of /// , and checks that the signature covers eb:Messaging, the SOAP /// body, every attachment and the wsu:Timestamp when there is one — whose Expires must not be /// in the past beyond . Throws on /// any failure. /// public static SignatureVerification Verify(SwaMessage message, IReadOnlyCollection trustedSigners, TimeSpan timestampTolerance, DateTimeOffset now, RevocationPolicy? revocation = null, TimeSpan? timestampTimeToLive = null, PkiPathTrust? pkiPath = null, IReadOnlyCollection? trustedElsewhere = null) { ArgumentNullException.ThrowIfNull(message); var envelope = message.Envelope; EnsureUniqueIds(envelope); var parts = SoapParts.Of(envelope); var security = parts.Security ?? throw new CryptographicException("The message carries no wsse:Security header."); var signature = Children(security, "Signature", WsSecurityNames.Ds).ToList() is { Count: 1 } one ? one[0] : throw new CryptographicException("The security header does not carry exactly one ds:Signature."); var signedInfo = Child(signature, "SignedInfo", WsSecurityNames.Ds) ?? throw new CryptographicException("ds:Signature has no ds:SignedInfo."); var c14nMethod = Child(signedInfo, "CanonicalizationMethod", WsSecurityNames.Ds) ?? throw new CryptographicException("ds:SignedInfo has no ds:CanonicalizationMethod."); if (c14nMethod.GetAttribute("Algorithm") != WsSecurityNames.ExcC14N) throw new CryptographicException($"Canonicalization '{c14nMethod.GetAttribute("Algorithm")}' is not supported."); var signatureMethod = Child(signedInfo, "SignatureMethod", WsSecurityNames.Ds)?.GetAttribute("Algorithm"); if (!As4Algorithms.IsSupportedSignature(signatureMethod)) throw new CryptographicException($"Signature method '{signatureMethod}' is not supported."); var keyInfo = Child(signature, "KeyInfo", WsSecurityNames.Ds) ?? throw new CryptographicException("ds:Signature has no ds:KeyInfo."); X509Certificate2? signer; if (pkiPath is not null) { // The agreement trusts authorities, not a pinned certificate: the signer must come with its certification // path (eDelivery AS4 1.16 §4.3.3), and the path must lead to one of them. var path = SecurityTokenResolver.PkiPathOf(keyInfo, envelope) ?? throw new CryptographicException( "The agreement requires the signing certificate in an X509PKIPathv1 security token; the message references it another way."); // Validity and revocation of the signer and its authorities are part of the path check. The signer is kept; // the rest of the path is released once judged, trusted or not. try { PkiPath.EnsureTrusted(path, pkiPath, now, revocation ?? RevocationPolicy.None); } catch { PkiPath.Release(path, keep: null); throw; } signer = path[^1]; PkiPath.Release(path, keep: signer); } else { signer = SecurityTokenResolver.Resolve(keyInfo, envelope, trustedSigners); if (signer is null || !trustedSigners.Any(c => c.Thumbprint == signer.Thumbprint)) { if (trustedElsewhere is { Count: > 0 } && SecurityTokenResolver.IsTrustedElsewhere(keyInfo, envelope, trustedElsewhere)) throw new SignerNotAuthorizedException( "The signing certificate is trusted here but is not the partner's: it belongs to another party."); throw new CryptographicException("The signing certificate is not one of the partner's."); } CertificateValidity.EnsureSigner(signer, now, revocation ?? RevocationPolicy.None); } var signatureValueElement = Child(signature, "SignatureValue", WsSecurityNames.Ds) ?? throw new CryptographicException("ds:Signature has no ds:SignatureValue."); byte[] signatureValue; try { signatureValue = SecurityTokenResolver.Base64(signatureValueElement); } catch (CryptographicException e) { throw new MalformedSignatureValueException(e.Message); } var canonicalSignedInfo = ExclusiveCanonicalizer.Canonicalize(signedInfo, ExclusiveCanonicalizer.PrefixList(c14nMethod)); using (var rsa = signer.GetRSAPublicKey() ?? throw new CryptographicException("The signing certificate has no RSA key.")) { if (!rsa.VerifyData(canonicalSignedInfo, signatureValue, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)) throw new CryptographicException("The signature does not verify."); } var references = Children(signedInfo, "Reference", WsSecurityNames.Ds).ToList(); if (references.Count == 0) throw new CryptographicException("ds:SignedInfo has no ds:Reference."); var covered = new HashSet(StringComparer.Ordinal); foreach (var reference in references) { var uri = reference.GetAttribute("URI"); if (!covered.Add(uri)) throw new CryptographicException($"ds:Reference '{uri}' appears twice."); var digestMethod = Child(reference, "DigestMethod", WsSecurityNames.Ds)?.GetAttribute("Algorithm"); if (!As4Algorithms.IsSupportedDigest(digestMethod)) throw new CryptographicException($"Digest method '{digestMethod}' is not supported."); var expected = SecurityTokenResolver.Base64( Child(reference, "DigestValue", WsSecurityNames.Ds) ?? throw new CryptographicException($"ds:Reference '{uri}' has no ds:DigestValue.")); var actual = ReferenceDigest(reference, uri, message); if (!CryptographicOperations.FixedTimeEquals(actual, expected)) throw new CryptographicException($"The digest of '{uri}' does not match."); } EnsureCoverage(parts, message, covered, timestampTolerance, timestampTimeToLive ?? As4Partner.DefaultTimestampTimeToLive, now); var copies = references.Select(r => (XmlElement)r.CloneNode(deep: true)).ToList(); return new SignatureVerification(signer, copies); } /// SHA-256 of what a reference covers: a canonicalized element, or an attachment read as a stream. private static byte[] ReferenceDigest(XmlElement reference, string uri, SwaMessage message) { var transforms = Child(reference, "Transforms", WsSecurityNames.Ds) is { } list ? Children(list, "Transform", WsSecurityNames.Ds).ToList() : []; if (transforms.Count != 1) throw new CryptographicException($"ds:Reference '{uri}' must carry exactly one transform."); var transform = transforms[0]; var algorithm = transform.GetAttribute("Algorithm"); if (uri.StartsWith('#')) { if (algorithm != WsSecurityNames.ExcC14N) throw new CryptographicException($"Transform '{algorithm}' of '{uri}' is not supported."); var target = FindById(message.Envelope, uri[1..]) ?? throw new CryptographicException($"No element carries the id '{uri[1..]}'."); return SHA256.HashData(ExclusiveCanonicalizer.Canonicalize(target, ExclusiveCanonicalizer.PrefixList(transform))); } if (uri.StartsWith(WsSecurityNames.CidPrefix, StringComparison.OrdinalIgnoreCase)) { if (algorithm != WsSecurityNames.AttachmentContentSignatureTransform) throw new UnsupportedAttachmentTransformException($"Transform '{algorithm}' of '{uri}' is not supported."); var id = WsSecurityNames.ContentId(uri); return message.Parts.TryGetValue(id, out var part) ? AttachmentCanonicalizer.Sha256(part) : throw new CryptographicException($"The message has no MIME part with Content-ID '{id}'."); } throw new CryptographicException($"ds:Reference '{uri}' points outside the message."); } private static void EnsureCoverage(SoapParts parts, SwaMessage message, HashSet covered, TimeSpan timestampTolerance, TimeSpan timestampTimeToLive, DateTimeOffset now) { bool Covers(XmlElement element) => covered.Contains("#" + WsuId(element)); if (parts.Messaging is null || !Covers(parts.Messaging)) throw new SignatureCoverageException("The signature does not cover eb:Messaging."); if (!Covers(parts.Body)) throw new SignatureCoverageException("The signature does not cover the SOAP body."); foreach (var id in message.Parts.Keys) { if (!covered.Contains(WsSecurityNames.CidUri(id))) throw new SignatureCoverageException($"The signature does not cover the attachment '{id}'."); } if (parts.Timestamp is { } timestamp) { if (!Covers(timestamp)) throw new CryptographicException("The signature does not cover wsu:Timestamp."); CheckTimestamp(timestamp, timestampTolerance, timestampTimeToLive, now); } } /// /// A received wsu:Timestamp, checked as WSS4J checks it (the library Domibus and Holodeck verify with): /// Created is required (BSP R3203) and may lie neither in the future beyond /// (WSS4J futureTimeToLive) nor further back than (WSS4J timeStampTTL); /// Expires is optional and, when present, must not have passed beyond . An /// Expires far ahead buys nothing: the age is bounded by Created. /// internal static void CheckTimestamp(XmlElement timestamp, TimeSpan tolerance, TimeSpan timeToLive, DateTimeOffset now) { var created = Instant(timestamp, "Created") ?? throw new CryptographicException("wsu:Timestamp has no wsu:Created."); if (created > now + tolerance) throw new CryptographicException("wsu:Timestamp was created in the future."); if (created < now - timeToLive) throw new CryptographicException("wsu:Timestamp was created too long ago."); if (Instant(timestamp, "Expires") is { } expires && expires + tolerance < now) throw new CryptographicException("wsu:Timestamp has expired."); static DateTimeOffset? Instant(XmlElement timestamp, string name) { if (Child(timestamp, name, WsSecurityNames.Wsu)?.InnerText.Trim() is not { } text) return null; return DateTimeOffset.TryParse(text, CultureInfo.InvariantCulture, DateTimeStyles.AssumeUniversal, out var value) ? value : throw new CryptographicException($"wsu:{name} is not a date and time."); } } // ── Signing ────────────────────────────────────────────────────────────── /// /// Signs eb:Messaging, the SOAP body, every attachment and — when is /// given — a new wsu:Timestamp, adding the signature to the security header (created when absent). /// Call it before encryption: attachment digests are over the plaintext. Returns copies of the /// ds:Reference elements: what a non-repudiation receipt must echo back. /// public static IReadOnlyList Sign(SwaMessage message, X509Certificate2 signer, As4KeyReference keyReference, TimeSpan? timestampTtl, DateTimeOffset now, IReadOnlyList? signingPath = null) => Sign(message, signer, keyReference, timestampTtl, now, coverBody: true, signingPath); /// /// As the signing of a conformant sender, with the SOAP body left /// out of the signature when is false: what a sender outside the profile produces, for /// the tests of the receiver. A conformant sender always covers the body (AS4 profile §5.1.4, §5.1.5). /// internal static IReadOnlyList Sign(SwaMessage message, X509Certificate2 signer, As4KeyReference keyReference, TimeSpan? timestampTtl, DateTimeOffset now, bool coverBody, IReadOnlyList? signingPath = null) { ArgumentNullException.ThrowIfNull(message); ArgumentNullException.ThrowIfNull(signer); if (!signer.HasPrivateKey) throw new CryptographicException("The signing certificate has no private key."); var doc = message.Envelope; var parts = SoapParts.Of(doc); if (parts.Messaging is null) throw new CryptographicException("The SOAP header has no eb:Messaging to sign."); var security = parts.Security ?? SoapParts.AddSecurityHeader(doc, parts.Header); if (Children(security, "Signature", WsSecurityNames.Ds).Any()) throw new CryptographicException("The message is signed already."); var targets = new List { parts.Messaging }; if (coverBody) targets.Add(parts.Body); if (timestampTtl is { } ttl) { if (parts.Timestamp is not null) throw new CryptographicException("The security header carries a wsu:Timestamp already."); targets.Add(AddTimestamp(doc, security, now, ttl)); } foreach (var target in targets) { EnsureWsuId(target); ExclusiveCanonicalizer.DeclareNamespaces(target); } var signature = doc.CreateElement("ds", "Signature", WsSecurityNames.Ds); signature.SetAttribute("Id", "SIG-" + Guid.NewGuid().ToString("N")); var signedInfo = Append(signature, "ds", "SignedInfo", WsSecurityNames.Ds); Append(signedInfo, "ds", "CanonicalizationMethod", WsSecurityNames.Ds).SetAttribute("Algorithm", WsSecurityNames.ExcC14N); Append(signedInfo, "ds", "SignatureMethod", WsSecurityNames.Ds).SetAttribute("Algorithm", As4Algorithms.RsaSha256); foreach (var target in targets) AppendReference(signedInfo, "#" + WsuId(target), WsSecurityNames.ExcC14N, SHA256.HashData(ExclusiveCanonicalizer.Canonicalize(target, null))); foreach (var part in message.Parts.Values) AppendReference(signedInfo, WsSecurityNames.CidUri(part.ContentId), WsSecurityNames.AttachmentContentSignatureTransform, AttachmentCanonicalizer.Sha256(part)); // Token first, signature after it: a receiver meets the token before the reference to it. var keyInfo = SecurityTokenResolver.CreateKeyInfo(doc, security, signer, keyReference, path: signingPath); security.AppendChild(signature); ExclusiveCanonicalizer.DeclareNamespaces(security); // Canonicalize SignedInfo where it now stands, so the namespaces in scope are the final ones. var canonical = ExclusiveCanonicalizer.Canonicalize(signedInfo, null); using var rsa = signer.GetRSAPrivateKey() ?? throw new CryptographicException("The signing certificate has no RSA private key."); var value = rsa.SignData(canonical, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); Append(signature, "ds", "SignatureValue", WsSecurityNames.Ds).InnerText = Convert.ToBase64String(value); signature.AppendChild(keyInfo); return Children(signedInfo, "Reference", WsSecurityNames.Ds).Select(r => (XmlElement)r.CloneNode(deep: true)).ToList(); } private static void AppendReference(XmlElement signedInfo, string uri, string transform, byte[] digest) { var reference = Append(signedInfo, "ds", "Reference", WsSecurityNames.Ds); reference.SetAttribute("URI", uri); var transforms = Append(reference, "ds", "Transforms", WsSecurityNames.Ds); Append(transforms, "ds", "Transform", WsSecurityNames.Ds).SetAttribute("Algorithm", transform); Append(reference, "ds", "DigestMethod", WsSecurityNames.Ds).SetAttribute("Algorithm", As4Algorithms.Sha256); Append(reference, "ds", "DigestValue", WsSecurityNames.Ds).InnerText = Convert.ToBase64String(digest); } private static XmlElement AddTimestamp(XmlDocument doc, XmlElement security, DateTimeOffset now, TimeSpan ttl) { var timestamp = doc.CreateElement("wsu", "Timestamp", WsSecurityNames.Wsu); Append(timestamp, "wsu", "Created", WsSecurityNames.Wsu).InnerText = Format(now); Append(timestamp, "wsu", "Expires", WsSecurityNames.Wsu).InnerText = Format(now + ttl); security.PrependChild(timestamp); return timestamp; static string Format(DateTimeOffset t) => t.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture); } // ── Ids ────────────────────────────────────────────────────────────────── /// /// Refuses a document in which one id names two elements. Checked over the whole envelope before any /// reference is followed: that is the shape of a signature-wrapping attack. /// public static void EnsureUniqueIds(XmlDocument envelope) { var seen = new HashSet(StringComparer.Ordinal); foreach (XmlElement element in envelope.GetElementsByTagName("*")) { foreach (var id in new[] { element.GetAttribute("Id", WsSecurityNames.Wsu), element.GetAttribute("Id") }) { if (id.Length > 0 && !seen.Add(id)) throw new CryptographicException($"Two elements carry the id '{id}'."); } } } /// The element with wsu:Id or Id ; ids are unique (). public static XmlElement? FindById(XmlDocument document, string id) { foreach (XmlElement element in document.GetElementsByTagName("*")) { if (element.GetAttribute("Id", WsSecurityNames.Wsu) == id || element.GetAttribute("Id") == id) return element; } return null; } private static string WsuId(XmlElement element) => element.GetAttribute("Id", WsSecurityNames.Wsu); private static void EnsureWsuId(XmlElement element) { if (WsuId(element).Length > 0) return; var attribute = element.OwnerDocument.CreateAttribute("wsu", "Id", WsSecurityNames.Wsu); attribute.Value = "id-" + Guid.NewGuid().ToString("N"); element.Attributes.Append(attribute); } // ── XML helpers ────────────────────────────────────────────────────────── internal static XmlElement Append(XmlElement parent, string prefix, string localName, string ns) { var element = parent.OwnerDocument.CreateElement(prefix, localName, ns); parent.AppendChild(element); return element; } internal static XmlElement? Child(XmlElement parent, string localName, string ns) => parent.ChildNodes.OfType().FirstOrDefault(e => e.LocalName == localName && e.NamespaceURI == ns); internal static IEnumerable Children(XmlElement parent, string localName, string ns) => parent.ChildNodes.OfType().Where(e => e.LocalName == localName && e.NamespaceURI == ns); } /// Outcome of a successful signature verification. /// The partner certificate that signed the message. /// /// Copies of the ds:Reference elements of the signature — what a non-repudiation receipt returns, and /// what a sender compares a receipt against. /// internal sealed record SignatureVerification(X509Certificate2 Signer, IReadOnlyList References); /// /// The signature verifies, but leaves out a part the profile requires it to cover: eb:Messaging, the SOAP body /// or an attachment (AS4 profile §5.1.4, §5.1.5). On receipt this is a policy failure, EBMS:0103, as Domibus /// reports it from its WS-SecurityPolicy (sp:SignedParts), not a failed authentication: nothing that was /// signed has been altered. /// internal sealed class SignatureCoverageException(string message) : System.Security.Cryptography.CryptographicException(message); /// /// An attachment is signed with a transform the profile does not allow (Attachment-Complete instead of /// Attachment-Content): answered with EBMS:0102, as the eDelivery conformance test driver expects (AS4_CP_TA72). /// internal sealed class UnsupportedAttachmentTransformException(string message) : System.Security.Cryptography.CryptographicException(message); /// /// The ds:SignatureValue is not a value at all (not base64): answered with EBMS:0102, as the eDelivery conformance /// test driver expects for a modified signature value (AS4_CP_TA66). A value that decodes but does not verify stays /// EBMS:0101. /// internal sealed class MalformedSignatureValueException(string message) : System.Security.Cryptography.CryptographicException(message); /// /// The message is signed with a certificate this node trusts (another agreement's, or issued by an authority one of its /// agreements trusts), but not with the sender's: an impersonation, answered as an authorization failure with EBMS:0004 /// (AS4_CP_TA78). A certificate the node does not know at all stays an authentication failure, EBMS:0101. /// internal sealed class SignerNotAuthorizedException(string message) : System.Security.Cryptography.CryptographicException(message); Path: redb-route/redb.Route.As4/Security/AttachmentCanonicalizer.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.As4/Security/AttachmentCanonicalizer.cs ---- using System.Security.Cryptography; using System.Security.Cryptography.Xml; using System.Text.RegularExpressions; using System.Xml; using redb.Route.As4.Mime; using redb.Route.Core; namespace redb.Route.As4.Security; /// /// The digest input of the Attachment-Content-Signature-Transform: the part's content in its MIME canonical form /// (OASIS WSS SwA Profile 1.1 §5.4.2). The rules and the media type patterns are those of Apache WSS4J, which /// Holodeck B2B and Domibus sign and verify with: /// /// XML (text/xml, application/xml, application/*+xml, image/*+xml) — Exclusive XML /// Canonicalization without comments, with no InclusiveNamespaces prefix list; /// any other text/* — line endings normalized to CRLF; /// anything else — the content as it is. /// /// The media type is the part's own: with AS4 compression it is application/gzip, so the rules bite only on /// payloads sent uncompressed. /// internal static class AttachmentCanonicalizer { private static readonly Regex Xml = new(@"^(text/xml|application/xml|(application|image)/[^;]*\+xml)", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); private static readonly Regex Text = new(@"^text/", RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Compiled); /// SHA-256 of the canonical form of . public static byte[] Sha256(SwaPart part) { ArgumentNullException.ThrowIfNull(part); if (Xml.IsMatch(part.ContentType)) return SHA256.HashData(ExclusiveC14N(part)); if (Text.IsMatch(part.ContentType)) return CrlfSha256(part.OpenRead()); return part.Sha256(); } private static Stream ExclusiveC14N(SwaPart part) { // Foreign XML: the core SafeXml reader (no DTD, the default structure limits), whitespace kept, as the transform // reads the content. The payload is the partner's document, not an envelope, so it gets the generous default // limits; its size is bounded by the request. var document = new XmlDocument { PreserveWhitespace = true, XmlResolver = null }; try { using var reader = SafeXml.CreateReader(part.OpenRead(), XmlLimits.Default); document.Load(reader); } catch (XmlException e) { // Its digest cannot be computed, so the signature over it cannot hold. throw new CryptographicException($"Attachment '{part.ContentId}' is declared {part.ContentType} but cannot be read as XML: {e.Message}", e); } var transform = new XmlDsigExcC14NTransform(includeComments: false); transform.LoadInput(document); return (Stream)transform.GetOutput(typeof(Stream)); } /// /// SHA-256 of with every CR, LF and CRLF written as CRLF — the rule of WSS4J's /// CRLFOutputStream. /// private static byte[] CrlfSha256(Stream input) { using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); ReadOnlySpan crlf = "\r\n"u8; var buffer = new byte[81920]; var afterCr = false; int read; while ((read = input.Read(buffer, 0, buffer.Length)) > 0) { var start = 0; for (var i = 0; i < read; i++) { var b = buffer[i]; if (b == (byte)'\r') { hash.AppendData(buffer, start, i - start); hash.AppendData(crlf); start = i + 1; afterCr = true; } else if (b == (byte)'\n') { hash.AppendData(buffer, start, i - start); if (!afterCr) hash.AppendData(crlf); start = i + 1; afterCr = false; } else { afterCr = false; } } hash.AppendData(buffer, start, read - start); } return hash.GetHashAndReset(); } } Path: redb-route/redb.Route.As4/Security/CertificateValidity.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.As4/Security/CertificateValidity.cs ---- using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace redb.Route.As4.Security; /// /// How the revocation of pinned certificates is checked (). /// /// /// (default), (fetch CRLs and OCSP /// responses the certificate points at) or (the OS cache only). /// /// Accept a certificate whose status cannot be determined (the responder is unreachable). Default false. internal sealed record RevocationPolicy(X509RevocationMode Mode, bool SoftFail) { /// No revocation check. public static readonly RevocationPolicy None = new(X509RevocationMode.NoCheck, SoftFail: false); } /// /// Whether a certificate an agreement pins may be used now. Pinning says whose key it is; it does not make an expired /// or revoked key current — Holodeck ("directly trusted, check validity") and Domibus check both on top of the pin /// (domibus.sender.certificate.validation.onreceiving, domibus.sender/receiver.certificate.validation.onsending). /// Revocation follows phase4: off unless asked for, and then hard-fail when the status cannot be determined unless /// soft-fail is chosen; a certificate that names no CRL distribution point and no authority information access passes, /// as in Domibus. Trust in the chain is not asked for: the pin is the trust. /// internal static class CertificateValidity { private const string CrlDistributionPointsOid = "2.5.29.31"; private const string AuthorityInformationAccessOid = "1.3.6.1.5.5.7.1.1"; /// Null when is valid at ; otherwise why not, naming . public static string? Problem(X509Certificate2 certificate, DateTimeOffset now, string role) => Problem(certificate, now, role, RevocationPolicy.None); /// The validity period, then revocation under . public static string? Problem(X509Certificate2 certificate, DateTimeOffset now, string role, RevocationPolicy revocation) { ArgumentNullException.ThrowIfNull(certificate); ArgumentNullException.ThrowIfNull(revocation); 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}."; if (revocation.Mode == X509RevocationMode.NoCheck || !NamesRevocationSources(certificate)) return null; // The pin is the trust, so the issuer path is found first (local stores, AIA caIssuers) and then made the root // of the chain the revocation check runs on: Windows does not fetch a CRL for a chain to an untrusted root, and // the issuer is what signs the CRL. No issuer found leaves the status undetermined. X509Certificate2[] issuers; using (var discovery = new X509Chain()) { discovery.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; discovery.ChainPolicy.VerificationTime = utc; discovery.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; discovery.Build(certificate); issuers = discovery.ChainElements.Skip(1).Select(e => e.Certificate).ToArray(); } var status = X509ChainStatusFlags.RevocationStatusUnknown; if (issuers.Length > 0) { using var chain = new X509Chain(); chain.ChainPolicy.RevocationMode = revocation.Mode; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.EndCertificateOnly; chain.ChainPolicy.VerificationTime = utc; chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; chain.ChainPolicy.CustomTrustStore.Add(issuers[^1]); chain.ChainPolicy.ExtraStore.AddRange(issuers[..^1]); chain.Build(certificate); status = chain.ChainElements[0].ChainElementStatus.Aggregate(X509ChainStatusFlags.NoError, (all, s) => all | s.Status); } if ((status & X509ChainStatusFlags.Revoked) != 0) return $"{who} has been revoked."; if ((status & (X509ChainStatusFlags.RevocationStatusUnknown | X509ChainStatusFlags.OfflineRevocation)) != 0 && !revocation.SoftFail) return $"{who}: its revocation status could not be determined (CRL or OCSP responder unreachable)."; return null; } /// Throws when a received message's signer may not be used now. public static void EnsureSigner(X509Certificate2 signer, DateTimeOffset now, RevocationPolicy revocation) { if (Problem(signer, now, "The signing certificate", revocation) is { } problem) throw new CryptographicException(problem); } /// Whether names a CRL distribution point or an authority information access. internal static bool NamesRevocationSources(X509Certificate2 certificate) => certificate.Extensions.Any(e => e.Oid?.Value is CrlDistributionPointsOid or AuthorityInformationAccessOid); } Path: redb-route/redb.Route.As4/Security/ExclusiveCanonicalizer.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.As4/Security/ExclusiveCanonicalizer.cs ---- using System.Security.Cryptography.Xml; using System.Xml; namespace redb.Route.As4.Security; /// /// Exclusive XML canonicalization (W3C xml-exc-c14n) of one element as it stands in its document, done by the /// public of .NET. The element is copied into a document of its own /// together with the namespace declarations in scope at its position; exclusive canonicalization then emits /// only the ones the subtree visibly uses and the ones named in the inclusive prefix list — which is exactly /// the output a signer computed over the element in place. /// internal static class ExclusiveCanonicalizer { private const string XmlnsNamespace = "http://www.w3.org/2000/xmlns/"; /// The canonical octets of . /// The element, still inside its document. /// The ec:InclusiveNamespaces/@PrefixList, or null. public static byte[] Canonicalize(XmlElement element, string? inclusivePrefixes) { ArgumentNullException.ThrowIfNull(element); var copy = new XmlDocument { PreserveWhitespace = true, XmlResolver = null }; var root = (XmlElement)copy.ImportNode(element, deep: true); copy.AppendChild(root); // Nearest declaration wins: walk outwards and add only prefixes the copy does not declare yet. for (var node = element.ParentNode; node is XmlElement ancestor; node = ancestor.ParentNode) { foreach (XmlAttribute attribute in ancestor.Attributes) { if (attribute.NamespaceURI != XmlnsNamespace) continue; if (root.HasAttribute(attribute.Name)) continue; root.SetAttribute(attribute.Name, attribute.Value); } } var transform = string.IsNullOrWhiteSpace(inclusivePrefixes) ? new XmlDsigExcC14NTransform() : new XmlDsigExcC14NTransform(inclusivePrefixes); transform.LoadInput(copy); using var output = (Stream)transform.GetOutput(typeof(Stream)); using var buffer = new MemoryStream(); output.CopyTo(buffer); return buffer.ToArray(); } /// /// Adds an explicit xmlns:prefix declaration to every element of the subtree that uses a prefix (in its /// name or an attribute's) not yet declared in scope. The DOM lets code create wsu:Id or /// ds:SignedInfo without one; the serializer then adds it on the way out. Canonicalizing before that /// would digest a different document than the receiver gets, so a signer declares first — on the same element /// the serializer would. /// public static void DeclareNamespaces(XmlElement root) { ArgumentNullException.ThrowIfNull(root); foreach (var element in root.SelectNodes("descendant-or-self::*")!.OfType()) { Declare(element, element.Prefix, element.NamespaceURI); foreach (var attribute in element.Attributes.OfType().ToList()) { if (attribute.Prefix.Length == 0 || attribute.Prefix == "xmlns" || attribute.Prefix == "xml") continue; Declare(element, attribute.Prefix, attribute.NamespaceURI); } } } private static void Declare(XmlElement element, string prefix, string ns) { if (ns.Length == 0) return; var name = prefix.Length == 0 ? "xmlns" : "xmlns:" + prefix; // The nearest declaration of the prefix decides: the same URI is already in scope; a different one is // shadowed here, as the serializer would do. for (XmlNode? node = element; node is XmlElement e; node = e.ParentNode) { if (!e.HasAttribute(name)) continue; if (e.GetAttribute(name) == ns) return; break; } element.SetAttribute(name, ns); } /// /// The inclusive prefix list of a ds:CanonicalizationMethod or ds:Transform of the exclusive /// algorithm, or null when it carries none. /// public static string? PrefixList(XmlElement method) => method.ChildNodes.OfType() .FirstOrDefault(e => e.LocalName == "InclusiveNamespaces" && e.NamespaceURI == WsSecurityNames.ExcC14N) ?.GetAttribute("PrefixList"); } Path: redb-route/redb.Route.As4/Security/PkiPath.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.As4/Security/PkiPath.cs ---- using System.Formats.Asn1; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace redb.Route.As4.Security; /// /// What a partner's signature is trusted by when its certificate is not pinned: the trust anchors a certification path /// must lead to, and the certificate policies the certificates of the path must assert (eDelivery AS4 1.16 §4.3.3). /// /// Certification authority certificates, roots or intermediate ones ("certificate path prefixes"). /// Certificate policy OIDs every certificate below the anchor must assert; empty for none. internal sealed record PkiPathTrust(IReadOnlyCollection Anchors, IReadOnlyCollection Policies); /// /// The X509PKIPathv1 security token (WS-Security X.509 Token Profile 1.1 §3.1.2): an ordered list of X.509 /// certificates packaged in a PKIPath, PkiPath ::= SEQUENCE OF Certificate (ITU-T X.509), where each /// certificate is issued by the one before it — the signing certificate is the last. A receiver that does not hold the /// signer's certificate validates the path up to an authority it trusts. /// internal static class PkiPath { /// Token type of a wsse:BinarySecurityToken carrying a PKIPath, and of a wsse:Reference to one. public const string ValueType = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509PKIPathv1"; /// A path is the signer and its authorities; more certificates than this is not one. public const int MaxLength = 10; private const string CertificatePoliciesOid = "2.5.29.32"; private const string AnyPolicyOid = "2.5.29.32.0"; /// The DER encoding of , given from the authority's side to the signer. public static byte[] Encode(IReadOnlyList path) { ArgumentNullException.ThrowIfNull(path); var writer = new AsnWriter(AsnEncodingRules.DER); using (writer.PushSequence()) { foreach (var certificate in path) writer.WriteEncodedValue(certificate.RawData); } return writer.Encode(); } /// /// The certificates of a DER-encoded PKIPath, in its order: the signer is the last. The caller owns them: what it /// keeps of the path it disposes of when done, the rest at once (). /// public static IReadOnlyList Decode(byte[] der) { ArgumentNullException.ThrowIfNull(der); var path = new List(); try { var reader = new AsnReader(der, AsnEncodingRules.DER); var sequence = reader.ReadSequence(); reader.ThrowIfNotEmpty(); while (sequence.HasData) { if (path.Count == MaxLength) throw new CryptographicException($"The PKIPath token holds more than {MaxLength} certificates."); path.Add(Load(sequence.ReadEncodedValue().ToArray())); } if (path.Count == 0) throw new CryptographicException("The PKIPath token holds no certificate."); return path; } catch (Exception e) { Release(path, keep: null); if (e is AsnContentException) throw new CryptographicException("The PKIPath token is not a DER sequence of certificates.", e); throw; } } /// Disposes of the certificates of a decoded path, all but when it is one of them. public static void Release(IReadOnlyList path, X509Certificate2? keep) { foreach (var certificate in path) if (!ReferenceEquals(certificate, keep)) certificate.Dispose(); } /// /// The path of from its outermost known authority down to itself, built from /// given in any order. An authority that issued none of the others is left out. /// public static IReadOnlyList Order(X509Certificate2 signer, IEnumerable authorities) { ArgumentNullException.ThrowIfNull(signer); var remaining = (authorities ?? []).Where(a => a.Thumbprint != signer.Thumbprint).ToList(); var path = new List { signer }; while (path.Count < MaxLength && !IsSelfIssued(path[0])) { var issuer = remaining.FirstOrDefault(a => SameName(a.SubjectName, path[0].IssuerName) && Issued(a, path[0])); if (issuer is null) break; remaining.Remove(issuer); path.Insert(0, issuer); } return path; } /// /// Throws unless is a certification path whose signer chains to one of the trust anchors: each /// certificate is issued by the one before it and every issuer is a certification authority allowed to sign /// certificates, and from the anchor down (RFC 5280 §6.1) every authority allows the authorities below it, the anchor /// and every certificate below it are within their validity period, the certificates below the anchor assert the /// required policies and — when asks for it — none of them is revoked. /// public static void EnsureTrusted(IReadOnlyList path, PkiPathTrust trust, DateTimeOffset now, RevocationPolicy? revocation = null) { ArgumentNullException.ThrowIfNull(path); ArgumentNullException.ThrowIfNull(trust); if (path.Count == 0) throw new CryptographicException("The PKIPath token holds no certificate."); // The token must be a certification path, all of it: a token that is not one is refused, whatever it holds. for (var i = 1; i < path.Count; i++) EnsureIssued(issuer: path[i - 1], subject: path[i]); // The anchor nearest to the signer decides, and the checks of trust start at it. The token may also leave the // anchor out: then it is the issuer of the first certificate. X509Certificate2? anchor = null; var below = 0; // index of the first certificate under the anchor for (var i = path.Count - 1; i >= 0 && anchor is null; i--) { if (trust.Anchors.Any(a => a.Thumbprint == path[i].Thumbprint)) { anchor = path[i]; below = i + 1; } } if (anchor is null) { anchor = trust.Anchors.FirstOrDefault(a => SameName(a.SubjectName, path[0].IssuerName) && Issued(a, path[0])) ?? throw new CryptographicException( $"The signing certificate {path[^1].Subject} does not chain to a trust anchor of the agreement."); EnsureIssued(anchor, path[0]); } EnsurePathLength(anchor, path, below); if (CertificateValidity.Problem(anchor, now, "The trust anchor") is { } anchorProblem) throw new CryptographicException(anchorProblem); for (var i = below; i < path.Count; i++) { if (CertificateValidity.Problem(path[i], now, Role(path, i)) is { } problem) throw new CryptographicException(problem); } // The signer always, and every authority between it and the anchor (§4.3.3: "any policy and issuing // Certification Authorities involved in issuing the presented signing certificate"). foreach (var policy in trust.Policies) { for (var i = Math.Min(below, path.Count - 1); i < path.Count; i++) { if (!AssertsPolicy(path[i], policy)) throw new CryptographicException( $"The certificate {path[i].Subject} does not assert the certificate policy {policy} the agreement requires."); } } if (revocation is { Mode: not X509RevocationMode.NoCheck }) EnsureNotRevoked(path, below, anchor, trust, now, revocation); } /// /// Throws when a certificate below the anchor is revoked, or when its status cannot be determined and soft-fail is /// not chosen. A certificate that names no CRL distribution point and no authority information access passes, as for /// a pinned certificate (). /// /// The CRLs are found and checked by , which does so only on a chain that ends at a /// self-signed root (on Windows and on Linux alike: under an intermediate trust anchor it reports a partial chain /// and checks nothing). So the chain is completed above the anchor from what the token carries there, the /// agreement's anchors and, failing those, the local stores and the anchor's authority information access; the root /// found is made the chain's trust root for this check alone: the trust decision has been taken by then. The anchor /// itself is not judged (RFC 5280 §6.1: validation starts below it). /// /// private static void EnsureNotRevoked(IReadOnlyList path, int below, X509Certificate2 anchor, PkiPathTrust trust, DateTimeOffset now, RevocationPolicy revocation) { var judged = Enumerable.Range(below, path.Count - below).Where(i => CertificateValidity.NamesRevocationSources(path[i])).ToList(); if (judged.Count == 0) return; var aboveAnchor = path.Take(Math.Max(below - 1, 0)).Concat(trust.Anchors).ToList(); var upward = Order(anchor, aboveAnchor); // the root first, the anchor last if (!IsSelfIssued(upward[0])) upward = Discover(upward, aboveAnchor); if (!IsSelfIssued(upward[0])) { Undetermined(path[judged[0]], Role(path, judged[0]), $"no self-signed root above the trust anchor {anchor.Subject} is known, and the status is checked on a chain to a root"); return; } using var chain = new X509Chain(); chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust; chain.ChainPolicy.CustomTrustStore.Add(upward[0]); chain.ChainPolicy.ExtraStore.AddRange(upward.Skip(1).Concat(path.Skip(below).Take(path.Count - below - 1)).ToArray()); chain.ChainPolicy.RevocationMode = revocation.Mode; chain.ChainPolicy.RevocationFlag = X509RevocationFlag.ExcludeRoot; chain.ChainPolicy.VerificationTime = now.UtcDateTime; chain.ChainPolicy.DisableCertificateDownloads = true; // the path is the token's; only CRLs and OCSP are fetched chain.Build(path[^1]); // The chain must be the path that was judged trusted, not another one the builder found. var expected = upward.Concat(path.Skip(below)).Reverse().Select(c => c.Thumbprint).ToList(); var built = chain.ChainElements.Select(e => e.Certificate.Thumbprint).ToList(); if (!built.SequenceEqual(expected, StringComparer.OrdinalIgnoreCase)) throw new CryptographicException( $"The revocation status of {path[^1].Subject} was checked on another certification path than the one the message carries."); foreach (var i in judged) { var status = chain.ChainElements[path.Count - 1 - i].ChainElementStatus .Aggregate(X509ChainStatusFlags.NoError, (all, s) => all | s.Status); if ((status & X509ChainStatusFlags.Revoked) != 0) throw new CryptographicException($"{Role(path, i)} {path[i].Subject} ({path[i].Thumbprint}) has been revoked."); if ((status & (X509ChainStatusFlags.RevocationStatusUnknown | X509ChainStatusFlags.OfflineRevocation)) != 0) Undetermined(path[i], Role(path, i), "CRL or OCSP responder unreachable"); } void Undetermined(X509Certificate2 certificate, string role, string why) { if (!revocation.SoftFail) throw new CryptographicException( $"{role} {certificate.Subject} ({certificate.Thumbprint}): its revocation status could not be determined ({why})."); } } /// /// completed towards a root as for a pinned certificate (): /// from the local certificate stores and the authority information access of its outermost certificate. Only for the /// revocation check; what is found is not trusted for anything else. /// private static IReadOnlyList Discover(IReadOnlyList upward, IReadOnlyList known) { using var discovery = new X509Chain(); discovery.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck; discovery.ChainPolicy.VerificationFlags = X509VerificationFlags.AllowUnknownCertificateAuthority; discovery.ChainPolicy.ExtraStore.AddRange(known.ToArray()); discovery.Build(upward[0]); var found = discovery.ChainElements.Skip(1).Select(e => e.Certificate).Reverse(); // the root first var completed = found.Concat(upward).ToList(); return completed.Count > MaxLength ? upward : completed; } private static string Role(IReadOnlyList path, int index) => index == path.Count - 1 ? "The signing certificate" : "The certification authority"; private static void EnsureIssued(X509Certificate2 issuer, X509Certificate2 subject) { if (!SameName(issuer.SubjectName, subject.IssuerName)) throw new CryptographicException( $"The PKIPath token is not a path: {subject.Subject} is not issued by {issuer.Subject}."); if (!IsAuthority(issuer)) throw new CryptographicException($"The certificate {issuer.Subject} issues {subject.Subject} but is not a certification authority."); // RFC 5280 §4.2.1.3: a key that may sign certificates says so when the certificate restricts its use at all. if (issuer.Extensions.OfType().FirstOrDefault() is { } usage && (usage.KeyUsages & X509KeyUsageFlags.KeyCertSign) == 0) throw new CryptographicException($"The key of {issuer.Subject} is not allowed to sign certificates (key usage keyCertSign)."); if (!Issued(issuer, subject)) throw new CryptographicException($"The signature of {issuer.Subject} on the certificate {subject.Subject} does not verify."); } /// /// RFC 5280 §4.2.1.9, §6.1.4 (l)-(m): an authority with a path length constraint has at most that many certification /// authorities below it, not counting self-issued ones, before the signing certificate. /// private static void EnsurePathLength(X509Certificate2 anchor, IReadOnlyList path, int below) { var authorities = new List { anchor }; authorities.AddRange(path.Skip(below).Take(path.Count - below - 1)); for (var k = 0; k < authorities.Count; k++) { if (authorities[k].Extensions.OfType().FirstOrDefault() is not { HasPathLengthConstraint: true } constraints) continue; var under = authorities.Skip(k + 1).Count(a => !IsSelfIssued(a)); if (under > constraints.PathLengthConstraint) throw new CryptographicException( $"The certification authority {authorities[k].Subject} allows {constraints.PathLengthConstraint} authorities below it; " + $"the path has {under}."); } } private static bool IsSelfIssued(X509Certificate2 certificate) => SameName(certificate.SubjectName, certificate.IssuerName); private static bool SameName(X500DistinguishedName a, X500DistinguishedName b) => a.RawData.AsSpan().SequenceEqual(b.RawData); private static bool IsAuthority(X509Certificate2 certificate) => certificate.Extensions.OfType().FirstOrDefault() is { CertificateAuthority: true }; /// Whether the key of signed . private static bool Issued(X509Certificate2 issuer, X509Certificate2 subject) { try { var parser = new Org.BouncyCastle.X509.X509CertificateParser(); parser.ReadCertificate(subject.RawData).Verify(parser.ReadCertificate(issuer.RawData).GetPublicKey()); return true; } catch (Exception e) when (e is Org.BouncyCastle.Security.GeneralSecurityException or InvalidOperationException or ArgumentException) { return false; } } /// Whether the certificate policies extension (RFC 5280 §4.2.1.4) lists or anyPolicy. private static bool AssertsPolicy(X509Certificate2 certificate, string policy) { var extension = certificate.Extensions.FirstOrDefault(e => e.Oid?.Value == CertificatePoliciesOid); if (extension is null) return false; try { var policies = new AsnReader(extension.RawData, AsnEncodingRules.DER).ReadSequence(); while (policies.HasData) { var information = policies.ReadSequence(); var identifier = information.ReadObjectIdentifier(); if (identifier == policy || identifier == AnyPolicyOid) return true; } return false; } catch (AsnContentException) { return false; } } private static X509Certificate2 Load(byte[] der) { return X509CertificateLoader.LoadCertificate(der); } } Path: redb-route/redb.Route.As4/Security/SecurityTokenResolver.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.As4/Security/SecurityTokenResolver.cs ---- using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Xml; using redb.Route.Serialization; namespace redb.Route.As4.Security; /// /// Finds the certificate a ds:KeyInfo points at, in any of the three WS-Security X.509 token /// references eDelivery asks for: a wsse:Reference to a wsse:BinarySecurityToken in the same /// message, a ds:X509IssuerSerial, or a wsse:KeyIdentifier with the Subject Key Identifier. /// /// A certificate carried in the message is material, not trust: the caller decides whether it is acceptable /// (the partner's certificate from the agreement, or one of ours for decryption). /// /// internal static class SecurityTokenResolver { /// /// The certificate references. A token in the message is returned as is; an /// issuer-serial or key-identifier reference is matched against . Null when /// nothing matches. /// public static X509Certificate2? Resolve(XmlElement keyInfo, XmlDocument envelope, IEnumerable candidates) { ArgumentNullException.ThrowIfNull(keyInfo); var str = FirstChild(keyInfo, "SecurityTokenReference", WsSecurityNames.Wsse) ?? throw new CryptographicException("ds:KeyInfo holds no wsse:SecurityTokenReference."); if (FirstChild(str, "Reference", WsSecurityNames.Wsse) is { } reference) { var uri = reference.GetAttribute("URI"); if (!uri.StartsWith('#')) throw new CryptographicException($"wsse:Reference '{uri}' does not point into the message."); var token = FindById(envelope, uri[1..], "BinarySecurityToken", WsSecurityNames.Wsse) ?? throw new CryptographicException($"No wsse:BinarySecurityToken carries the id '{uri[1..]}'."); return FromBinarySecurityToken(token); } if (FirstChild(str, "X509Data", WsSecurityNames.Ds) is { } x509Data && FirstChild(x509Data, "X509IssuerSerial", WsSecurityNames.Ds) is { } issuerSerial) { var issuer = FirstChild(issuerSerial, "X509IssuerName", WsSecurityNames.Ds)?.InnerText.Trim(); var serial = FirstChild(issuerSerial, "X509SerialNumber", WsSecurityNames.Ds)?.InnerText.Trim(); if (issuer is null || serial is null) throw new CryptographicException("ds:X509IssuerSerial lacks the issuer name or the serial number."); // The serial is decimal in XML Signature; the issuer is compared as a parsed name, because the // same name can be encoded with different ASN.1 string types. Both sides are rendered from their // encoding: X500DistinguishedName.Name of a parsed string returns that string as given, so // "CN=a,O=b" (RFC 2253, as WSS4J and Domibus write it) would never equal "CN=a, O=b". if (!System.Numerics.BigInteger.TryParse(serial, System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var serialNumber)) throw new CryptographicException("ds:X509SerialNumber is not a decimal number."); var issuerName = new X500DistinguishedName(issuer).Decode(X500DistinguishedNameFlags.None); return candidates.FirstOrDefault(c => string.Equals(c.IssuerName.Decode(X500DistinguishedNameFlags.None), issuerName, StringComparison.OrdinalIgnoreCase) && new System.Numerics.BigInteger(c.GetSerialNumber(), isUnsigned: true, isBigEndian: false) == serialNumber); } if (FirstChild(str, "KeyIdentifier", WsSecurityNames.Wsse) is { } keyIdentifier) { if (keyIdentifier.GetAttribute("ValueType") != WsSecurityNames.X509SubjectKeyIdentifier) throw new CryptographicException($"wsse:KeyIdentifier of type '{keyIdentifier.GetAttribute("ValueType")}' is not supported."); var ski = Base64(keyIdentifier); return candidates.FirstOrDefault(c => c.Extensions.OfType().FirstOrDefault() is { } ext && Convert.FromHexString(ext.SubjectKeyIdentifier!).AsSpan().SequenceEqual(ski)); } throw new CryptographicException("wsse:SecurityTokenReference uses no supported reference form."); } /// /// The certification path a ds:KeyInfo references, when it points at a wsse:BinarySecurityToken of /// type X509PKIPathv1 in the same message; null for any other reference form or token type. /// public static IReadOnlyList? PkiPathOf(XmlElement keyInfo, XmlDocument envelope) { ArgumentNullException.ThrowIfNull(keyInfo); if (FirstChild(keyInfo, "SecurityTokenReference", WsSecurityNames.Wsse) is not { } str || FirstChild(str, "Reference", WsSecurityNames.Wsse) is not { } reference) return null; var uri = reference.GetAttribute("URI"); if (!uri.StartsWith('#')) throw new CryptographicException($"wsse:Reference '{uri}' does not point into the message."); var token = FindById(envelope, uri[1..], "BinarySecurityToken", WsSecurityNames.Wsse) ?? throw new CryptographicException($"No wsse:BinarySecurityToken carries the id '{uri[1..]}'."); return token.GetAttribute("ValueType") == PkiPath.ValueType ? PkiPath.Decode(Base64(token)) : null; } /// /// The certificate in a wsse:BinarySecurityToken: the token itself for the X.509 v3 type, the last /// certificate of the path — the one the path is for — for X509PKIPathv1. /// public static X509Certificate2 FromBinarySecurityToken(XmlElement token) { var valueType = token.GetAttribute("ValueType"); if (valueType == PkiPath.ValueType) { var path = PkiPath.Decode(Base64(token)); PkiPath.Release(path, keep: path[^1]); return path[^1]; } if (valueType != WsSecurityNames.X509V3) throw new CryptographicException($"wsse:BinarySecurityToken of type '{valueType}' is not an X.509 v3 certificate."); var der = Base64(token); return X509CertificateLoader.LoadCertificate(der); } /// /// Whether the certificate references is one this node trusts for another reason than /// the sender's agreement: one of itself, or issued by one of them that is a /// certification authority. /// Only chooses the ebMS code of a refusal; nothing is accepted on it, so a reference by issuer and serial number /// is judged by its issuer name. /// public static bool IsTrustedElsewhere(XmlElement keyInfo, XmlDocument envelope, IReadOnlyCollection trusted) { try { if (Resolve(keyInfo, envelope, trusted) is { } found && trusted.Any(c => c.Thumbprint == found.Thumbprint)) return true; var issuer = ReferencedIssuer(keyInfo, envelope); return issuer is not null && trusted.Any(c => c.Extensions.OfType().Any(b => b.CertificateAuthority) && string.Equals(c.SubjectName.Decode(X500DistinguishedNameFlags.None), issuer, StringComparison.OrdinalIgnoreCase)); } catch (CryptographicException) { return false; } } /// The issuer of the referenced certificate, rendered from its encoding; null for a key identifier. private static string? ReferencedIssuer(XmlElement keyInfo, XmlDocument envelope) { if (FirstChild(keyInfo, "SecurityTokenReference", WsSecurityNames.Wsse) is not { } str) return null; if (FirstChild(str, "X509Data", WsSecurityNames.Ds) is { } x509Data && FirstChild(x509Data, "X509IssuerSerial", WsSecurityNames.Ds) is { } issuerSerial && FirstChild(issuerSerial, "X509IssuerName", WsSecurityNames.Ds)?.InnerText.Trim() is { Length: > 0 } issuer) return new X500DistinguishedName(issuer).Decode(X500DistinguishedNameFlags.None); if (FirstChild(str, "Reference", WsSecurityNames.Wsse) is { } reference && reference.GetAttribute("URI") is ['#', .. var id] && FindById(envelope, id, "BinarySecurityToken", WsSecurityNames.Wsse) is { } token) return FromBinarySecurityToken(token).IssuerName.Decode(X500DistinguishedNameFlags.None); return null; } /// /// The base64 content of a security element. Malformed base64 is a security failure of the message, refused /// like any other (), not an unexpected failure of the receiver. /// /// A value whose last character carries non-zero unused bits (YR== where an encoder writes YQ==) is /// malformed too: XML Schema base64Binary forbids that spelling and .NET 11 refuses it, so it is refused on /// every runtime and the receiver answers the same whatever it runs on. /// /// public static byte[] Base64(XmlElement element) { var text = element.InnerText.Trim(); if (Base64Text.HasUnusedBitsSet(text)) throw NotBase64(element); try { return Convert.FromBase64String(text); } catch (FormatException) { throw NotBase64(element); } } private static CryptographicException NotBase64(XmlElement element) => new($"{element.Name} is not valid base64."); /// The element named in with wsu:Id (or Id) . public static XmlElement? FindById(XmlDocument document, string id, string localName, string ns) { XmlElement? found = null; foreach (XmlElement e in document.GetElementsByTagName(localName, ns)) { if (e.GetAttribute("Id", WsSecurityNames.Wsu) != id && e.GetAttribute("Id") != id) continue; if (found is not null) throw new CryptographicException($"Two {localName} elements carry the id '{id}'."); found = e; } return found; } /// /// Builds a ds:KeyInfo that references in the requested form. For /// the token itself is appended to /// — before when given — unless an identical /// one is there already, and referenced by id: a receiver meets the token before the reference to it. /// public static XmlElement CreateKeyInfo(XmlDocument doc, XmlElement security, X509Certificate2 certificate, As4KeyReference form, XmlNode? insertTokenBefore = null, IReadOnlyList? path = null) { var keyInfo = doc.CreateElement("ds", "KeyInfo", WsSecurityNames.Ds); var str = doc.CreateElement("wsse", "SecurityTokenReference", WsSecurityNames.Wsse); keyInfo.AppendChild(str); switch (form) { case As4KeyReference.BinarySecurityToken: { var tokenId = EnsureBinarySecurityToken(doc, security, Convert.ToBase64String(certificate.RawData), WsSecurityNames.X509V3, insertTokenBefore); var reference = doc.CreateElement("wsse", "Reference", WsSecurityNames.Wsse); reference.SetAttribute("URI", "#" + tokenId); reference.SetAttribute("ValueType", WsSecurityNames.X509V3); str.AppendChild(reference); break; } case As4KeyReference.PkiPath: { // The certificate with its authorities, outermost first (ITU-T X.509 PkiPath): ordered and checked once, // when the node is resolved (As4Node.SigningPath). A certificate that is its own authority is a path of one. var signingPath = path ?? [certificate]; if (signingPath.Count == 0 || signingPath[^1].Thumbprint != certificate.Thumbprint) throw new CryptographicException("The certification path does not end with the signing certificate."); var tokenId = EnsureBinarySecurityToken(doc, security, Convert.ToBase64String(PkiPath.Encode(signingPath)), PkiPath.ValueType, insertTokenBefore); var reference = doc.CreateElement("wsse", "Reference", WsSecurityNames.Wsse); reference.SetAttribute("URI", "#" + tokenId); reference.SetAttribute("ValueType", PkiPath.ValueType); str.AppendChild(reference); // WS-I Basic Security Profile 1.1 R5215: a reference to a PKIPath token names its type on the // wsse:SecurityTokenReference itself; WSS4J (Domibus, Holodeck) refuses the message without it. var tokenType = doc.CreateAttribute("wsse11", "TokenType", WsSecurityNames.Wsse11); tokenType.Value = PkiPath.ValueType; str.Attributes.Append(tokenType); break; } case As4KeyReference.IssuerSerial: { var x509Data = doc.CreateElement("ds", "X509Data", WsSecurityNames.Ds); var issuerSerial = doc.CreateElement("ds", "X509IssuerSerial", WsSecurityNames.Ds); var issuer = doc.CreateElement("ds", "X509IssuerName", WsSecurityNames.Ds); issuer.InnerText = certificate.IssuerName.Name; var serial = doc.CreateElement("ds", "X509SerialNumber", WsSecurityNames.Ds); serial.InnerText = new System.Numerics.BigInteger(certificate.GetSerialNumber(), isUnsigned: true, isBigEndian: false) .ToString(System.Globalization.CultureInfo.InvariantCulture); issuerSerial.AppendChild(issuer); issuerSerial.AppendChild(serial); x509Data.AppendChild(issuerSerial); str.AppendChild(x509Data); break; } case As4KeyReference.KeyIdentifier: { var ski = certificate.Extensions.OfType().FirstOrDefault()?.SubjectKeyIdentifier ?? throw new CryptographicException("The certificate has no Subject Key Identifier to reference."); var identifier = doc.CreateElement("wsse", "KeyIdentifier", WsSecurityNames.Wsse); identifier.SetAttribute("EncodingType", WsSecurityNames.Base64Binary); identifier.SetAttribute("ValueType", WsSecurityNames.X509SubjectKeyIdentifier); identifier.InnerText = Convert.ToBase64String(Convert.FromHexString(ski)); str.AppendChild(identifier); break; } default: throw new ArgumentOutOfRangeException(nameof(form), form, "Unknown key reference form."); } return keyInfo; } private static string EnsureBinarySecurityToken(XmlDocument doc, XmlElement security, string der, string valueType, XmlNode? insertBefore) { foreach (var existing in security.ChildNodes.OfType() .Where(e => e.LocalName == "BinarySecurityToken" && e.NamespaceURI == WsSecurityNames.Wsse)) { if (existing.InnerText.Trim() == der && existing.GetAttribute("ValueType") == valueType) return existing.GetAttribute("Id", WsSecurityNames.Wsu); } var token = doc.CreateElement("wsse", "BinarySecurityToken", WsSecurityNames.Wsse); token.SetAttribute("EncodingType", WsSecurityNames.Base64Binary); token.SetAttribute("ValueType", valueType); var id = doc.CreateAttribute("wsu", "Id", WsSecurityNames.Wsu); id.Value = "X509-" + Guid.NewGuid().ToString("N"); token.Attributes.Append(id); token.InnerText = der; if (insertBefore is null) security.AppendChild(token); else security.InsertBefore(token, insertBefore); return id.Value; } /// The first child element with the given name. public static XmlElement? FirstChild(XmlElement parent, string localName, string ns) => parent.ChildNodes.OfType().FirstOrDefault(e => e.LocalName == localName && e.NamespaceURI == ns); } Path: redb-route/redb.Route.As4/Security/SoapParts.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.As4/Security/SoapParts.cs ---- using System.Security.Cryptography; using System.Xml; namespace redb.Route.As4.Security; /// /// The parts of a SOAP 1.2 envelope that AS4 security works on, found by namespace and position — never by /// prefix, which senders choose freely. eb:Messaging counts only as a direct child of the header: a /// copy anywhere else is not the header the message is processed by. /// internal sealed record SoapParts(XmlElement Header, XmlElement Body, XmlElement? Messaging, XmlElement? Security, XmlElement? Timestamp) { /// Finds the parts; throws when the envelope is not SOAP 1.2 or repeats a part. public static SoapParts Of(XmlDocument envelope) { var root = envelope.DocumentElement; if (root is null || root.LocalName != "Envelope" || root.NamespaceURI != WsSecurityNames.Soap12) throw new CryptographicException("The document is not a SOAP 1.2 envelope."); var header = Single(root, "Header", WsSecurityNames.Soap12) ?? throw new CryptographicException("The envelope has no SOAP header."); var body = Single(root, "Body", WsSecurityNames.Soap12) ?? throw new CryptographicException("The envelope has no SOAP body."); var messaging = Single(header, "Messaging", WsSecurityNames.Eb); var security = Single(header, "Security", WsSecurityNames.Wsse); var timestamp = security is null ? null : Single(security, "Timestamp", WsSecurityNames.Wsu); return new SoapParts(header, body, messaging, security, timestamp); } /// Adds an empty wsse:Security header with mustUnderstand="true" as the first header block. public static XmlElement AddSecurityHeader(XmlDocument envelope, XmlElement header) { var security = envelope.CreateElement("wsse", "Security", WsSecurityNames.Wsse); var mustUnderstand = envelope.CreateAttribute("soapenv", "mustUnderstand", WsSecurityNames.Soap12); mustUnderstand.Value = "true"; security.Attributes.Append(mustUnderstand); header.PrependChild(security); return security; } private static XmlElement? Single(XmlElement parent, string localName, string ns) { XmlElement? found = null; foreach (var child in parent.ChildNodes.OfType()) { if (child.LocalName != localName || child.NamespaceURI != ns) continue; if (found is not null) throw new CryptographicException($"{parent.LocalName} carries more than one {localName}."); found = child; } return found; } } Path: redb-route/redb.Route.As4/Security/WsSecurityNames.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.As4/Security/WsSecurityNames.cs ---- namespace redb.Route.As4.Security; /// Namespaces and URIs of WS-Security, the SwA profile and XML Signature / Encryption used by AS4. internal static class WsSecurityNames { public const string Soap12 = "http://www.w3.org/2003/05/soap-envelope"; public const string Wsse = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"; public const string Wsse11 = "http://docs.oasis-open.org/wss/oasis-wss-wssecurity-secext-1.1.xsd"; public const string Wsu = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"; public const string Ds = "http://www.w3.org/2000/09/xmldsig#"; public const string Xenc = "http://www.w3.org/2001/04/xmlenc#"; public const string Xenc11 = "http://www.w3.org/2009/xmlenc11#"; public const string Eb = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/"; /// X.509 v3 token type of a wsse:BinarySecurityToken and of a wsse:Reference to one. public const string X509V3 = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3"; /// Value type of a wsse:KeyIdentifier carrying a Subject Key Identifier. public const string X509SubjectKeyIdentifier = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509SubjectKeyIdentifier"; /// Base64 encoding type of token values. public const string Base64Binary = "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary"; /// SwA profile: signature over the content of a MIME part, headers excluded. public const string AttachmentContentSignatureTransform = "http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Content-Signature-Transform"; /// SwA profile: the ciphertext replaces the content of a MIME part. public const string AttachmentCiphertextTransform = "http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Ciphertext-Transform"; /// SwA profile xenc:EncryptedData/@Type: only the part content is encrypted. public const string AttachmentContentOnly = "http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Content-Only"; /// The cid: URI scheme of references to MIME parts. public const string CidPrefix = "cid:"; /// Exclusive XML canonicalization without comments. public const string ExcC14N = "http://www.w3.org/2001/10/xml-exc-c14n#"; /// The Content-ID a cid: URI names (RFC 2392 allows percent-encoding). public static string ContentId(string cidUri) => Uri.UnescapeDataString(cidUri[CidPrefix.Length..]); /// The cid: URI of a Content-ID. public static string CidUri(string contentId) => CidPrefix + contentId; } Path: redb-route/redb.Route.As4/Signals/Receipts.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.As4/Signals/Receipts.cs ---- using System.Xml; using redb.Route.As4.Messaging; using redb.Route.As4.Security; namespace redb.Route.As4.Signals; /// /// AS4 non-repudiation receipts (AS4 profile §3.4, eDelivery AS4 1.16: NonRepudiation = true): the /// content of eb:Receipt is one ebbp:NonRepudiationInformation holding a copy of every /// ds:Reference of the signature of the received message. Built by the receiver; checked by the sender /// against the references it signed, which proves the receiver got exactly those bytes. /// internal static class Receipts { /// The eb:Receipt content for a message whose signature had . public static IReadOnlyList NonRepudiation(IReadOnlyList receivedReferences) { ArgumentNullException.ThrowIfNull(receivedReferences); if (receivedReferences.Count == 0) throw new ArgumentException("A non-repudiation receipt needs the references of a signed message.", nameof(receivedReferences)); var doc = new XmlDocument { PreserveWhitespace = true, XmlResolver = null }; var information = doc.CreateElement("ebbp", "NonRepudiationInformation", EbmsNamespaces.Ebbp); information.SetAttribute("xmlns:ebbp", EbmsNamespaces.Ebbp); doc.AppendChild(information); foreach (var reference in receivedReferences) { var part = doc.CreateElement("ebbp", "MessagePartNRInformation", EbmsNamespaces.Ebbp); part.AppendChild(doc.ImportNode(reference, deep: true)); information.AppendChild(part); } ExclusiveCanonicalizer.DeclareNamespaces(information); return [information]; } /// /// Whether the receipt's non-repudiation information names exactly the references we signed — same URIs, /// same digest values, none missing, none extra. A receipt without it does not prove receipt. /// public static bool ProvesReceiptOf(SignalMessage receipt, IReadOnlyList sentReferences) { ArgumentNullException.ThrowIfNull(receipt); ArgumentNullException.ThrowIfNull(sentReferences); if (receipt.ReceiptContent is null) return false; var echoed = receipt.ReceiptContent .Where(e => e.LocalName == "NonRepudiationInformation" && e.NamespaceURI == EbmsNamespaces.Ebbp) .SelectMany(e => e.ChildNodes.OfType()) .Where(e => e.LocalName == "MessagePartNRInformation" && e.NamespaceURI == EbmsNamespaces.Ebbp) .SelectMany(e => e.ChildNodes.OfType()) .Where(e => e.LocalName == "Reference" && e.NamespaceURI == WsSecurityNames.Ds) .Select(Key) .ToList(); var sent = sentReferences.Select(Key).ToList(); return echoed.Count == sent.Count && new HashSet(echoed, StringComparer.Ordinal).SetEquals(sent); } private static string Key(XmlElement reference) { var digest = reference.ChildNodes.OfType() .FirstOrDefault(e => e.LocalName == "DigestValue" && e.NamespaceURI == WsSecurityNames.Ds)?.InnerText.Trim() ?? ""; return reference.GetAttribute("URI") + "\n" + digest; } } Path: redb-route/redb.Route.As4/Signals/RecentReceipts.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.As4/Signals/RecentReceipts.cs ---- using System.Collections.Concurrent; using redb.Route.Abstractions; namespace redb.Route.As4.Signals; /// /// The receipts a node sent, kept in memory to answer duplicates with the same receipt. Every receipt is stored /// and almost none is read again, so entries leave by age (retention) and by count (the oldest beyond /// capacity) on every store, not on a read that never comes. /// internal sealed class RecentReceipts(TimeSpan retention, int capacity) : IClaimCheckRepository { private readonly ConcurrentDictionary _entries = new(StringComparer.Ordinal); private readonly ConcurrentQueue<(string Key, Entry Entry)> _order = new(); private readonly object _trim = new(); public Task Store(ReadOnlyMemory data, TimeSpan? ttl = null, CancellationToken ct = default) => throw new NotSupportedException("Receipts are stored under the id of the message they answer."); public Task Store(string key, ReadOnlyMemory data, TimeSpan? ttl = null, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); var entry = new Entry(data.ToArray(), DateTimeOffset.UtcNow + (ttl ?? retention)); _entries[key] = entry; _order.Enqueue((key, entry)); Trim(); return Task.CompletedTask; } public Task Retrieve(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); return Task.FromResult(_entries.TryGetValue(key, out var entry) && entry.ExpiresAt > DateTimeOffset.UtcNow ? entry.Data : null); } public async Task RetrieveAndRemove(string key, CancellationToken ct = default) { var data = await Retrieve(key, ct).ConfigureAwait(false); await Remove(key, ct).ConfigureAwait(false); return data; } public Task Remove(string key, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(key); _entries.TryRemove(key, out _); return Task.CompletedTask; } /// Drops from the oldest end what has expired or is beyond the capacity. private void Trim() { lock (_trim) { var now = DateTimeOffset.UtcNow; while (_order.TryPeek(out var oldest) && (oldest.Entry.ExpiresAt <= now || _order.Count > capacity)) { _order.TryDequeue(out _); // Only the entry this queue item stored: a later Store under the same key has its own item. _entries.TryRemove(new KeyValuePair(oldest.Key, oldest.Entry)); } } } private sealed record Entry(byte[] Data, DateTimeOffset ExpiresAt); } Path: redb-route/redb.Route.As4/Signals/Responses.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.As4/Signals/Responses.cs ---- using System.Security.Cryptography.X509Certificates; using System.Text; using System.Xml; using redb.Route.As4.Messaging; using redb.Route.As4.Mime; using redb.Route.As4.Security; namespace redb.Route.As4.Signals; /// /// What a receiver answers in the HTTP response (eDelivery AS4 1.16: receipts and errors only as responses): /// a signed non-repudiation receipt, an ebMS error, or — for a message that is not ebMS at all — a SOAP fault. /// Statuses follow what Holodeck B2B answers: an ebMS signal with 200; a SOAP fault per the SOAP 1.2 HTTP /// binding, 400 for a Sender fault, 500 for MustUnderstand. /// internal static class Responses { /// The signed receipt for , echoing . public static (string ContentType, byte[] Body) Receipt(string receivedMessageId, IReadOnlyList receivedReferences, string host, X509Certificate2 signer, As4KeyReference keyReference, TimeSpan? timestampTtl, IReadOnlyList? signingPath = null) { var signal = new SignalMessage( new MessageInfo(DateTimeOffset.UtcNow, MessageIdFactory.New(host), receivedMessageId), Receipts.NonRepudiation(receivedReferences), [], null); var message = SwaMessage.Create(MessagingWriter.CreateEnvelope(signal)); As4SecurityEngine.Sign(message, signer, keyReference, timestampTtl, DateTimeOffset.UtcNow, signingPath); return message.Write(); } /// /// An ebMS error signal for (null when the message could not be read far /// enough to know it). The texts are the code's fixed partner text and a reference to quote — never the text of /// one of our exceptions (BR-4); is the one exception: a description of the caller's /// own bytes. Signed when a signer is given (the agreement is known), unsigned otherwise. /// public static (string ContentType, byte[] Body) Error(As4ErrorCode code, string? refToMessageId, string host, string reference, string? callerText = null, X509Certificate2? signer = null, As4KeyReference keyReference = As4KeyReference.BinarySecurityToken, IReadOnlyList? signingPath = null) { var error = new EbmsError(code.Code, code.Severity, code.Category, "ebms", refToMessageId, code.ShortDescription, callerText ?? code.PartnerText, $"ref: {reference}"); var signal = new SignalMessage(new MessageInfo(DateTimeOffset.UtcNow, MessageIdFactory.New(host), refToMessageId), null, [error], null); var message = SwaMessage.Create(MessagingWriter.CreateEnvelope(signal)); if (signer is not null) As4SecurityEngine.Sign(message, signer, keyReference, timestampTtl: null, DateTimeOffset.UtcNow, signingPath); return message.Write(); } /// A SOAP 1.2 fault with code soapenv:Sender or soapenv:MustUnderstand. public static (int Status, string ContentType, byte[] Body) SoapFault(bool mustUnderstand, string reason) { var code = mustUnderstand ? "MustUnderstand" : "Sender"; var xml = $"" + $"soapenv:{code}" + $"{System.Security.SecurityElement.Escape(reason)}" + ""; return (mustUnderstand ? 500 : 400, "application/soap+xml; charset=UTF-8", Encoding.UTF8.GetBytes(xml)); } } Path: redb-route/redb.Route.As4/redb.Route.As4.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.As4/redb.Route.As4.csproj ---- redb.Route.As4 AS4 (OASIS ebMS 3.0 AS4 profile, eDelivery AS4 1.16 common profile) B2B transport for the redb.Route ESB framework: signed and encrypted SOAP with attachments, non-repudiation receipts, duplicate detection. esb;messaging;as4;ebms;edelivery;b2b;soap;redb README.md