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)}.");
}
}