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