Bundle: redb-route / demo/As4ConformanceDemo (demo.As4ConformanceDemo.txt), 14 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/demo/As4ConformanceDemo/ConformanceModule/Commands.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/demo/As4ConformanceDemo/ConformanceModule/Commands.cs ---- using redb.Route.Abstractions; // IExchange, IMessage using redb.Route.As4; // As4Headers, As4Payload, exceptions namespace ConformanceModule; /// /// The SUT Controller commands of the eDelivery conformance testing service (user guide v2.90, §5.3.1). A command is /// an ordinary AS4 user message on the command channel; what it says travels in eb:MessageProperties and its /// payloads. /// /// Submit (test driver to us): send this user message — its header values are the properties, its /// payloads are the payloads of the command. /// Deliver (us to the test driver): we received this user message — the same properties and payloads, /// read from what arrived. /// Notify (us to the test driver): this signal answered the message we sent — a receipt or an error. /// /// Each method rewrites the exchange into the message the next To(...) sends: the AS4 sender takes its header /// values and every redbAs4.property.* header from the exchange, so what is left over from the previous message /// is removed first. /// public static class Commands { /// Header: name of the agreement the user message is sent under. public const string PartnerHeader = "as4ct.partner"; /// Header: whether a missing receipt is redelivered (the ONEWAY_RETRY profile). public const string RetryHeader = "as4ct.retry"; // The properties of a command that describe the user message itself; any other one is a property of that message. private static readonly HashSet Described = new(StringComparer.OrdinalIgnoreCase) { "messageId", "conversationId", "refToMessageId", "fromPartyId", "fromPartyIdType", "fromPartyRole", "toPartyId", "toPartyIdType", "toPartyRole", "service", "serviceType", "action", "agreementRef", "mpc", }; /// A Submit command becomes the user message it asks for. public static void SubmitToUserMessage(IExchange exchange, IReadOnlyDictionary<(string Service, string Action), ConformanceLeg> legs, Func partnerName) { var command = Read(exchange.In); var service = command.Value("service") ?? throw new InvalidOperationException("Submit command without a 'service' property."); var action = command.Value("action") ?? throw new InvalidOperationException("Submit command without an 'action' property."); if (!legs.TryGetValue((service, action), out var leg)) throw new InvalidOperationException( $"Submit command for service '{service}', action '{action}': no such leg. Add it with the ExtraLegs setting of the context."); var payloads = Detach(exchange.In.Body); Clear(exchange.In); var h = exchange.In.Headers; if (command.Value("messageId") is { } messageId) h[As4Headers.MessageId] = messageId; if (command.Value("conversationId") is { } conversationId) h[As4Headers.ConversationId] = conversationId; if (command.Value("refToMessageId") is { } refToMessageId) h[As4Headers.RefToMessageId] = refToMessageId; foreach (var (name, value, type) in command.Properties.Where(p => !Described.Contains(p.Name))) { h[As4Headers.PropertyPrefix + name] = value; if (type is not null) h[As4Headers.PropertyTypePrefix + name] = type; } h[PartnerHeader] = partnerName(leg); h[RetryHeader] = leg.Retry; exchange.In.Body = payloads; exchange.In.ContentType = null; } /// A received user message becomes the Deliver command that reports it. public static void UserMessageToDeliver(IExchange exchange) { var message = exchange.In; string? Header(string name) => message.Headers.TryGetValue(name, out var value) ? value?.ToString() : null; var properties = new List<(string Name, string Value, string? Type)>(); void Add(string name, string? value) { if (!string.IsNullOrEmpty(value)) properties.Add((name, value, null)); } Add("messageId", Header(As4Headers.MessageId)); Add("conversationId", Header(As4Headers.ConversationId)); Add("refToMessageId", Header(As4Headers.RefToMessageId)); Add("fromPartyId", Header(As4Headers.FromPartyId)); Add("fromPartyRole", Header(As4Headers.FromRole)); Add("toPartyId", Header(As4Headers.ToPartyId)); Add("toPartyRole", Header(As4Headers.ToRole)); Add("service", Header(As4Headers.Service)); Add("serviceType", Header(As4Headers.ServiceType)); Add("action", Header(As4Headers.Action)); Add("agreementRef", Header(As4Headers.AgreementRef)); // The message's own properties (originalSender, finalRecipient, trackingIdentifier, ...) travel on as they came. properties.AddRange(Read(message).Properties.Where(p => !Described.Contains(p.Name))); var payloads = Detach(message.Body); Clear(message); Write(message, properties); message.Body = payloads; message.ContentType = null; } /// The verified receipt of the user message we sent becomes a Notify command. public static void ReceiptToNotify(IExchange exchange) { var sent = exchange.In.Headers.TryGetValue(As4Headers.MessageId, out var id) ? id?.ToString() : null; Notify(exchange, sent, [("signalType", "receipt", null)]); } /// /// The failure of a send becomes a Notify command: the partner's ebMS error as it came, or EBMS:0301 MissingReceipt /// when no receipt arrived after the redeliveries (AS4_CP_TA15: reported to the producer). /// public static void FailureToNotify(IExchange exchange) { var sent = exchange.In.Headers.TryGetValue(As4Headers.MessageId, out var id) ? id?.ToString() : null; var failure = exchange.Exception ?? (exchange.Properties.TryGetValue("ExceptionCaught", out var caught) ? caught as Exception : null); var properties = new List<(string Name, string Value, string? Type)> { ("signalType", "error", null) }; switch (failure) { case As4ErrorSignalException error: properties.Add(("errorCode", error.ErrorCode, null)); if (!string.IsNullOrEmpty(error.ShortDescription)) properties.Add(("shortDescription", error.ShortDescription, null)); if (!string.IsNullOrEmpty(error.Description)) properties.Add(("description", error.Description, null)); break; // Our own failures are reported by code only, never with the text of our exception (it stays in our log), as // our ebMS errors are. The test driver reads the code (AS4_CP_TA15, TA81); and Notifies that quoted our // exception were refused by the gateway in front of the conformance service (HTTP 403, Azure WAF). case As4ReceiptException receipt: properties.Add(("errorCode", receipt.Code.Code, null)); properties.Add(("shortDescription", receipt.Code.ShortDescription, null)); break; case HttpRequestException: // The partner was not reached on any attempt: no receipt arrived, which is what reception awareness reports. properties.Add(("errorCode", As4ErrorCode.MissingReceipt.Code, null)); properties.Add(("shortDescription", As4ErrorCode.MissingReceipt.ShortDescription, null)); break; default: properties.Add(("errorCode", "EBMS:0004", null)); properties.Add(("shortDescription", "Other", null)); break; } Notify(exchange, sent, properties); } private static void Notify(IExchange exchange, string? sentMessageId, List<(string Name, string Value, string? Type)> properties) { if (!string.IsNullOrEmpty(sentMessageId)) properties.Add(("refToMessageId", sentMessageId, null)); Clear(exchange.In); Write(exchange.In, properties); // A Notify has no payload: an empty list is a message without payloads. exchange.In.Body = Array.Empty(); exchange.In.ContentType = null; } // ── The message properties of the exchange ─────────────────────────────── private sealed record CommandProperties(List<(string Name, string Value, string? Type)> Properties) { public string? Value(string name) => Properties.FirstOrDefault(p => string.Equals(p.Name, name, StringComparison.OrdinalIgnoreCase)).Value; } private static CommandProperties Read(IMessage message) { var properties = new List<(string Name, string Value, string? Type)>(); foreach (var (key, value) in message.Headers) { if (!key.StartsWith(As4Headers.PropertyPrefix, StringComparison.Ordinal) || value is null) continue; var name = key[As4Headers.PropertyPrefix.Length..]; var type = message.Headers.TryGetValue(As4Headers.PropertyTypePrefix + name, out var t) ? t?.ToString() : null; properties.Add((name, value.ToString()!, type)); } return new CommandProperties(properties); } private static void Write(IMessage message, IEnumerable<(string Name, string Value, string? Type)> properties) { foreach (var (name, value, type) in properties) { message.Headers[As4Headers.PropertyPrefix + name] = value; if (type is not null) message.Headers[As4Headers.PropertyTypePrefix + name] = type; } } /// Removes every AS4 header of the previous message, and ours. private static void Clear(IMessage message) { foreach (var key in message.Headers.Keys.Where(k => k.StartsWith(As4Headers.Prefix, StringComparison.Ordinal) || k.StartsWith("as4ct.", StringComparison.Ordinal)).ToList()) message.Headers.Remove(key); } /// /// Copies the payloads out of the receiving exchange, which closes their streams when it ends: the message that /// carries them on is sent from another exchange, after the receipt of this one went out. /// private static List Detach(object? body) { var payloads = new List(); foreach (var payload in body as IEnumerable ?? []) { var copy = new MemoryStream(); if (payload.Content.CanSeek) payload.Content.Position = 0; payload.Content.CopyTo(copy); copy.Position = 0; payloads.Add(payload with { Content = copy }); } return payloads; } } Path: redb-route/demo/As4ConformanceDemo/ConformanceModule/ConformanceModule.config.json 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/demo/As4ConformanceDemo/ConformanceModule/ConformanceModule.config.json ---- { "ContextName": "as4-conformance", "AutoStart": true, "TestDriver": { "PartyId": "test_driver", "ControllerPartyId": "test_driver_sut_controller_domain" }, "Sut": { "PartyId": "system_under_test", "ControllerPartyId": "sut_controller_domain", "HostName": "redb.route" }, "Receive": { "Port": 4090, "SutPath": "/as4/sut", "ControllerPath": "/as4/controller", "DuplicateStore": "memory", "DuplicateWindowDays": 7 }, "Retry": { "Count": 4, "DelaySeconds": 20, "SendTimeoutMs": 60000 } } Path: redb-route/demo/As4ConformanceDemo/ConformanceModule/ConformanceModule.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/demo/As4ConformanceDemo/ConformanceModule/ConformanceModule.csproj ---- net10.0 enable enable ConformanceModule false ConformanceModule <_TpkgStaging>$(IntermediateOutputPath)tpkg <_TpkgFile>$(MSBuildThisFileDirectory)output\$(TsakModuleName).tpkg Path: redb-route/demo/As4ConformanceDemo/ConformanceModule/ConformanceSettings.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/demo/As4ConformanceDemo/ConformanceModule/ConformanceSettings.cs ---- using System.Globalization; using System.Security.Cryptography.X509Certificates; using redb.Route.Abstractions; // IRouteContext using redb.Route.As4; namespace ConformanceModule; /// /// What the eDelivery support team hands over at registration, and where this module listens. The values come from /// the route context (), so nothing of one test account is compiled into the module. /// public sealed class ConformanceSettings { /// eb:PartyId/@type of every party of the conformance tests. public const string UnregisteredPartyIdType = "urn:oasis:names:tc:ebcore:partyid-type:unregistered"; /// Party id of the access point under test, as assigned by the support team. public string SutPartyId { get; init; } = "system_under_test"; /// Party id of the test driver in the message exchanges under test. public string TestDriverPartyId { get; init; } = "test_driver"; /// Our party id on the command channel (Submit, Deliver, Notify). public string ControllerPartyId { get; init; } = "sut_controller_domain"; /// Party id of the test driver on the command channel. public string TestDriverControllerPartyId { get; init; } = "test_driver_sut_controller_domain"; /// MSH address of the test driver for the messages under test. public required string TestDriverUrl { get; init; } /// MSH address of the test driver for Deliver and Notify commands. public required string TestDriverControllerUrl { get; init; } /// Port both receive endpoints listen on (one shared host). public int Port { get; init; } = 4090; /// Path of the access point under test. public string SutPath { get; init; } = "/as4/sut"; /// Path that receives Submit commands. public string ControllerPath { get; init; } = "/as4/controller"; /// Host part of the message ids we generate. public string ExternalHostName { get; init; } = "redb.route"; /// The SUT key: signs our messages and receipts, decrypts what the test driver encrypts for us. public required X509Certificate2 SutKey { get; init; } /// The test driver's certificate: verifies its signatures, and payloads are encrypted for it. public required X509Certificate2 TestDriverCertificate { get; init; } /// /// Certificate of the test driver on the command channel. The conformance testing service signs Submit, Deliver and /// Notify with a certificate of its own (test_driver_sut_controller); null: , /// as a driver with one key has it. /// public X509Certificate2? TestDriverControllerCertificate { get; init; } /// /// Redeliveries of the ONEWAY_RETRY profile. The test driver takes 5 transmissions, the message and 4 /// redeliveries, and then expects the Notify (AS4_CP_TA15); a sixth transmission fails the test. /// public int RetryCount { get; init; } = 4; /// Delay between those redeliveries; the user guide asks for less than 3 minutes. public TimeSpan RetryDelay { get; init; } = TimeSpan.FromSeconds(20); /// /// Where the ids of received messages are remembered: memory, lost with the process, or redb, the /// worker's redb, so that a resend is still recognised after a restart and by every node of a cluster. /// public string DuplicateStore { get; init; } = "memory"; /// How long a received message id is remembered. public TimeSpan DuplicateWindow { get; init; } = TimeSpan.FromDays(7); /// Milliseconds to wait for the test driver's response with the receipt. public int SendTimeout { get; init; } = 60000; /// /// The certification authorities above : sent with it as its certification path on the PKI path /// legs. Empty when the SUT certificate is its own authority. /// public IReadOnlyList SutChain { get; init; } = []; /// /// The authorities the test driver's signing certificate must chain to on the PKI path legs. Empty: the test /// driver's certificate itself, as its own authority. /// public IReadOnlyList TestDriverTrustAnchors { get; init; } = []; /// Certificate policy OID required on the leg bstPkiPathSutC3PolicyFail; that leg is left out when null. public string? PkiPathPolicy { get; init; } /// Service and action pairs added to : service|action;service|action. public string? ExtraLegs { get; init; } /// /// Reads the settings from the route context, the way the Tsak worker provides them: the module's /// ConformanceModule.config.json gives the defaults, and what differs per test account arrives through the /// Override layer, environment variables on the worker such as /// Tsak__Contexts__as4-conformance__Override__TestDriver__Url. Every root key is a context property; a /// section is a dictionary. /// public static ConformanceSettings FromContext(IRouteContext context) { ArgumentNullException.ThrowIfNull(context); IDictionary Section(string name) => context.GetProperty>(name) ?? new Dictionary(); static string? Value(IDictionary section, string key) => section.TryGetValue(key, out var value) && Convert.ToString(value, CultureInfo.InvariantCulture) is { Length: > 0 } text ? text : null; string Need(IDictionary section, string sectionName, string key) => Value(section, key) ?? throw new InvalidOperationException( $"{sectionName}:{key} is not configured for context '{context.ContextId}': set it in ConformanceModule.config.json, " + $"or, for a value of one test account, in Tsak:Contexts:{context.ContextId}:Override (see demos/As4ConformanceDemo/README.md)."); // Certificate files separated by ";". static IReadOnlyList Certificates(string? files) => (files ?? "").Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) .Select(X509CertificateLoader.LoadCertificateFromFile).ToList(); static int Int(string text) => int.Parse(text, CultureInfo.InvariantCulture); var driver = Section("TestDriver"); var sut = Section("Sut"); var receive = Section("Receive"); var retry = Section("Retry"); var pkiPath = Section("PkiPath"); var url = Need(driver, "TestDriver", "Url"); return new ConformanceSettings { TestDriverUrl = url, TestDriverControllerUrl = Value(driver, "ControllerUrl") ?? url, TestDriverPartyId = Need(driver, "TestDriver", "PartyId"), TestDriverControllerPartyId = Need(driver, "TestDriver", "ControllerPartyId"), TestDriverCertificate = X509CertificateLoader.LoadCertificateFromFile(Need(driver, "TestDriver", "Certificate")), TestDriverControllerCertificate = Value(driver, "ControllerCertificate") is { } controllerCertificate ? X509CertificateLoader.LoadCertificateFromFile(controllerCertificate) : null, TestDriverTrustAnchors = Certificates(Value(driver, "TrustAnchors")), SutPartyId = Need(sut, "Sut", "PartyId"), ControllerPartyId = Need(sut, "Sut", "ControllerPartyId"), SutKey = X509CertificateLoader.LoadPkcs12FromFile(Need(sut, "Sut", "Pfx"), Value(sut, "PfxPassword")), SutChain = Certificates(Value(sut, "Chain")), ExternalHostName = Need(sut, "Sut", "HostName"), Port = Int(Need(receive, "Receive", "Port")), SutPath = Need(receive, "Receive", "SutPath"), ControllerPath = Need(receive, "Receive", "ControllerPath"), DuplicateStore = Need(receive, "Receive", "DuplicateStore"), DuplicateWindow = TimeSpan.FromDays(Int(Need(receive, "Receive", "DuplicateWindowDays"))), RetryCount = Int(Need(retry, "Retry", "Count")), RetryDelay = TimeSpan.FromSeconds(Int(Need(retry, "Retry", "DelaySeconds"))), SendTimeout = Int(Need(retry, "Retry", "SendTimeoutMs")), PkiPathPolicy = Value(pkiPath, "Policy"), ExtraLegs = context.GetProperty("ExtraLegs") is { Length: > 0 } extra ? extra : null, }; } } /// /// One service and action pair of the conformance tests, with how our signature references our certificate: /// X509IssuerSerial unless the test asks for another form, as the test suite does. /// public sealed record ConformanceLeg(string Service, string Action, As4KeyReference KeyReference = As4KeyReference.IssuerSerial, bool PkiPath = false, bool WithPolicy = false) { /// Whether a missing receipt is redelivered: the ONEWAY_RETRY profile of the user guide. public bool Retry => Action == "retry"; } /// /// The legs between the test driver and the access point under test: user guide v2.90, annex A (PMode parameters 11 and /// 12) for the common profile and the Four Corner enhancement. The agreements of the node are built from this list, one /// per pair, since a received message is matched on sender, service and action. /// public static class ConformanceLegs { public const string OneWay = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/oneWay"; public const string TwoWay = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/twoWay"; /// ebMS 3.0 test service (Core §5.2.2): its messages get a receipt and reach no business application. public const string TestService = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/service"; public const string TestAction = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/test"; /// Service of the command channel; its actions are Submit, Deliver and Notify. public const string CommandService = "http://www.edelivery.eu/as4/conformancetest"; public static IReadOnlyList Default { get; } = [ new(OneWay, "default"), new(OneWay, "retry"), new(OneWay, "fourCorner"), new(OneWay, "duplicateDetection"), new(OneWay, "emptyBodyNotReferencedInSignature"), new(OneWay, "bstDefault", As4KeyReference.BinarySecurityToken), new(OneWay, "ski", As4KeyReference.KeyIdentifier), new(OneWay, "issuerSerial", As4KeyReference.IssuerSerial), // PKI path: we sign with our certification path, and the test driver's signer must present one that leads to // a trust anchor (AS4_CP_TA47 to TA51). The last leg also requires a certificate policy. new(OneWay, "bstPkiPath", As4KeyReference.PkiPath, PkiPath: true), new(OneWay, "bstPkiPathSutC3Fail", As4KeyReference.PkiPath, PkiPath: true), new(OneWay, "bstPkiPathSutC3PolicyFail", As4KeyReference.PkiPath, PkiPath: true, WithPolicy: true), new(TwoWay, "default"), new(TestService, TestAction), ]; /// plus the pairs of service|action;service|action. public static IReadOnlyList With(string? extra) { var legs = Default.ToList(); foreach (var pair in (extra ?? "").Split(';', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) { var parts = pair.Split('|'); if (parts.Length != 2 || parts[0].Length == 0 || parts[1].Length == 0) throw new InvalidOperationException($"ExtraLegs: '{pair}' is not service|action."); if (!legs.Any(l => l.Service == parts[0] && l.Action == parts[1])) legs.Add(new ConformanceLeg(parts[0], parts[1])); } return legs; } } Path: redb-route/demo/As4ConformanceDemo/ConformanceModule/InitRoute.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/demo/As4ConformanceDemo/ConformanceModule/InitRoute.cs ---- using System.Security.Cryptography.X509Certificates; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; // IRouteContext, IExchange, IIdempotentRepository using redb.Route.As4; // As4Component, As4ConnectionFactory, As4Partner, As4Headers, exceptions using redb.Route.As4.Fluent; // As4.Send / As4.Receive using redb.Route.Components; // AddIdempotentRepository using redb.Route.Core; // RouteContext using redb.Route; // Seda using redb.Route.Processors; // InMemoryIdempotentRepository using redb.Route.RedbCore.Repositories; // RedbIdempotentRepository namespace ConformanceModule; /// /// Tsak module entry point: the System Under Test of the eDelivery AS4 conformance testing service. /// /// The service drives an access point through its own "SUT Controller", which the owner of the access point writes /// (user guide v2.90, §5.1.4). Here both are routes of one module: /// /// /// test driver --Submit--> {ControllerPath} --> the user message it asks for --> test driver /// | receipt, error or no receipt --Notify--> test driver /// test driver --user message--> {SutPath} --> receipt in the response /// | --Deliver--> test driver (not for the ebMS test service) /// /// /// Two nodes, as the service uses two pairs of party ids: sut is the access point under test, controller /// the command channel. A command is answered with its receipt first and acted on afterwards, from a seda: /// queue: the ONEWAY_RETRY profile redelivers for minutes, far longer than a command's HTTP request should stay open. /// /// public static class InitRoute { private const string SendQueue = "as4ct-send"; private const string SendRetryQueue = "as4ct-send-retry"; private const string DeliverQueue = "as4ct-deliver"; /// Entry point the Tsak worker calls: the settings come from the route context. public static IRouteContext main(IRouteContext context) => Configure(context, ConformanceSettings.FromContext(context)); /// Registers the two nodes and the routes for . public static IRouteContext Configure(IRouteContext context, ConformanceSettings settings) { ArgumentNullException.ThrowIfNull(context); ArgumentNullException.ThrowIfNull(settings); // The leg that requires a certificate policy needs one to require. var legs = ConformanceLegs.With(settings.ExtraLegs).Where(l => !l.WithPolicy || settings.PkiPathPolicy is not null).ToList(); var byValues = legs.ToDictionary(l => (l.Service, l.Action)); string PartnerName(ConformanceLeg leg) => "leg-" + legs.IndexOf(leg); var testDriver = X509CertificateLoader.LoadCertificate(settings.TestDriverCertificate.Export(X509ContentType.Cert)); context.AddComponent(new As4Component()); // ── The access point under test: one agreement per service and action of the tests ── var sut = new As4ConnectionFactory { OurPartyId = settings.SutPartyId, OurPartyIdType = ConformanceSettings.UnregisteredPartyIdType, ExternalHostName = settings.ExternalHostName, SigningCertificate = settings.SutKey, DecryptionCertificates = { settings.SutKey }, }; foreach (var authority in settings.SutChain) sut.SigningCertificateChain.Add(authority); foreach (var leg in legs) { var agreement = Agreement(PartnerName(leg), settings.TestDriverPartyId, leg.Service, leg.Action, testDriver, leg.KeyReference); if (leg.PkiPath) { // The test driver's signer is not pinned on these legs: it must present its certification path, and the // path must lead to a trust anchor (and assert the policy, where the leg asks for one). agreement.PartnerSigningCertificates.Clear(); foreach (var anchor in settings.TestDriverTrustAnchors.Count > 0 ? settings.TestDriverTrustAnchors : [testDriver]) agreement.PartnerTrustAnchors.Add(anchor); if (leg.WithPolicy) agreement.PartnerCertificatePolicies.Add(settings.PkiPathPolicy!); } sut.Partners.Add(agreement); } context.AddToRegistry("sut", sut); // ── The command channel: Submit comes in, Deliver and Notify go out ── var controller = new As4ConnectionFactory { OurPartyId = settings.ControllerPartyId, OurPartyIdType = ConformanceSettings.UnregisteredPartyIdType, ExternalHostName = settings.ExternalHostName, SigningCertificate = settings.SutKey, DecryptionCertificates = { settings.SutKey }, }; var testDriverController = settings.TestDriverControllerCertificate is { } controllerCertificate ? X509CertificateLoader.LoadCertificate(controllerCertificate.Export(X509ContentType.Cert)) : testDriver; foreach (var command in new[] { "Submit", "Deliver", "Notify" }) controller.Partners.Add(Agreement(command, settings.TestDriverControllerPartyId, ConformanceLegs.CommandService, command, testDriverController)); context.AddToRegistry("controller", controller); // Reception awareness: a resend gets its receipt again and reaches no route. Receive:DuplicateStore says where // the ids are remembered. context.AddIdempotentRepository("as4ct-sut", Duplicates(context, settings, "as4ct-sut")); context.AddIdempotentRepository("as4ct-controller", Duplicates(context, settings, "as4ct-controller")); var toTestDriver = As4.Send(settings.TestDriverUrl).ConnectionFactory("sut") .Partner("${header." + Commands.PartnerHeader + "}").Timeout(settings.SendTimeout).Build(); var notify = As4.Send(settings.TestDriverControllerUrl).ConnectionFactory("controller").Partner("Notify").Timeout(settings.SendTimeout).Build(); var deliver = As4.Send(settings.TestDriverControllerUrl).ConnectionFactory("controller").Partner("Deliver").Timeout(settings.SendTimeout).Build(); var routes = (RouteContext)context; // ── Receiving ──────────────────────────────────────────────────────── routes.AddRoutes(r => { // A Submit command: answered with its receipt, then acted on from the queue of its profile. r.From(As4.Receive(settings.ControllerPath).Port(settings.Port).ConnectionFactory("controller") .IdempotentRepository("as4ct-controller").PayloadList()) .RouteId("as4ct-submit") .Log("Submit ${header.redbAs4.messageId}: send ${header.redbAs4.property.messageId} " + "(${header.redbAs4.property.service} / ${header.redbAs4.property.action})") .Process(e => Commands.SubmitToUserMessage(e, byValues, PartnerName)) .Choice() .When(e => e.In.GetHeader(Commands.RetryHeader)).To(Seda.Send(SendRetryQueue)) .Otherwise().To(Seda.Send(SendQueue)) .EndChoice(); // A user message from the test driver. The receipt goes out with the response; the Deliver follows from // its queue. A message for the ebMS test service stops here: it reaches no business application // (profile §3.2.4, AS4_CP_TA17). r.From(As4.Receive(settings.SutPath).Port(settings.Port).ConnectionFactory("sut") .IdempotentRepository("as4ct-sut").PayloadList()) .RouteId("as4ct-receive") .Log("Received ${header.redbAs4.messageId} (${header.redbAs4.service} / ${header.redbAs4.action})") .Filter(e => e.In.GetHeader(As4Headers.Service) != ConformanceLegs.TestService) .Process(Commands.UserMessageToDeliver) .To(Seda.Send(DeliverQueue)) .End(); }); // ── Deliver ────────────────────────────────────────────────────────── routes.AddRoutes(r => { r.From(Seda.Consume(DeliverQueue)) .RouteId("as4ct-deliver") .To(deliver) .Log("Deliver sent for ${header.redbAs4.property.messageId}"); }); // ── Sending what a Submit asked for, then the Notify ───────────────── // Two builders, as an OnException belongs to the routes of its own builder: the retry profile redelivers a // missing receipt, every other profile reports it at once. routes.AddRoutes(r => SendRoute(r, SendQueue, "as4ct-send", toTestDriver, notify, redeliveries: 0, settings.RetryDelay)); routes.AddRoutes(r => SendRoute(r, SendRetryQueue, "as4ct-send-retry", toTestDriver, notify, settings.RetryCount, settings.RetryDelay)); return context; } /// /// Where one receive endpoint remembers the message ids it has taken. In memory the memory ends with the process: a /// message resent after a restart is delivered a second time. In the worker's redb it survives a restart and is /// shared by the nodes of a cluster; the entries of one endpoint are kept apart by . /// private static IIdempotentRepository Duplicates(IRouteContext context, ConformanceSettings settings, string scope) { switch (settings.DuplicateStore.ToLowerInvariant()) { case "memory": return new InMemoryIdempotentRepository(settings.DuplicateWindow); case "redb": var scopes = context.GetServiceProvider()?.GetService() ?? throw new InvalidOperationException( "Receive:DuplicateStore is 'redb', but the route context has no service provider with redb: " + "run the module under a worker with a redb store, or set the store to 'memory'."); return new RedbIdempotentRepository(scopes, new RedbIdempotentOptions { ProcessorName = scope, Ttl = settings.DuplicateWindow }); default: throw new InvalidOperationException( $"Receive:DuplicateStore is '{settings.DuplicateStore}'; it is 'memory' or 'redb'."); } } private static void SendRoute(InlineRouteBuilder r, string queue, string routeId, string toTestDriver, string notify, int redeliveries, TimeSpan delay) { // No receipt: redelivered as the same message (same id, same bytes), then EBMS:0301 is reported (AS4_CP_TA09, TA15). // The Notify carries the ebMS code only; what went wrong in our words goes to our log. r.OnException() .MaximumRedeliveries(redeliveries) .RedeliveryDelay(delay) .Handled() .Log("Send of ${header.redbAs4.messageId} failed, Notify follows: ${exception.message}") .Process(Commands.FailureToNotify) .To(notify); // The test driver's access point unreachable: the same policy. r.OnException() .MaximumRedeliveries(redeliveries) .RedeliveryDelay(delay) .Handled() .Log("Send of ${header.redbAs4.messageId} failed, Notify follows: ${exception.message}") .Process(Commands.FailureToNotify) .To(notify); // An ebMS error is the test driver's answer: reported as it came, never redelivered. r.OnException() .Handled() .Log("Send of ${header.redbAs4.messageId} answered with an ebMS error, Notify follows: ${exception.message}") .Process(Commands.FailureToNotify) .To(notify); r.From(Seda.Consume(queue)) .RouteId(routeId) .To(toTestDriver) .Log("Sent ${header.redbAs4.messageId}, receipt ${header.redbAs4.receiptMessageId}") .Process(Commands.ReceiptToNotify) .To(notify); } /// /// One agreement with the test driver. The roles are the ones the tests use; the four-corner properties are not /// required, as the common profile does not ask for them: a message carries them when the test gives them. The /// reply leg has the values of the request leg, since a Two-Way test answers under the same service and action. /// private static As4Partner Agreement(string name, string partyId, string service, string action, X509Certificate2 certificate, As4KeyReference keyReference = As4KeyReference.IssuerSerial) => new() { Name = name, PartyId = partyId, PartyIdType = ConformanceSettings.UnregisteredPartyIdType, OurRole = "http://www.edelivery.eu/as4/conformancetest/sut", PartnerRole = "http://www.edelivery.eu/as4/conformancetest/testdriver", Service = service, Action = action, ReplyLeg = new As4Leg { Service = service, Action = action }, KeyReference = keyReference, RequireFourCornerProperties = false, PartnerSigningCertificates = { certificate }, PartnerEncryptionCertificate = certificate, }; } Path: redb-route/demo/As4ConformanceDemo/ConformanceModule/manifest.json 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/demo/As4ConformanceDemo/ConformanceModule/manifest.json ---- { "Name": "ConformanceModule", "Version": "1.0.0", "EntryPoints": ["ConformanceModule.dll"], "Dependencies": [] } Path: redb-route/demo/As4ConformanceDemo/ConformanceWorker/ConformanceWorker.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/demo/As4ConformanceDemo/ConformanceWorker/ConformanceWorker.csproj ---- Exe net10.0 enable enable ConformanceWorker false Path: redb-route/demo/As4ConformanceDemo/ConformanceWorker/ContextConfiguration.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/demo/As4ConformanceDemo/ConformanceWorker/ContextConfiguration.cs ---- using Microsoft.Extensions.Configuration; using redb.Route.Abstractions; namespace ConformanceWorker; /// /// The context configuration the way the Tsak worker builds it, in miniature. Each layer deep-merges /// over the previous one, later layers win: /// /// Tsak:Contexts:default of the host configuration, /// Tsak:Contexts:{context}, /// the module's {Module}.config.json, /// Tsak:Contexts:{context}:Override, the operator's last word. /// /// Every root key then becomes a property of the route context; a section becomes a dictionary. The /// real worker also reads a module's context.json and per-context Contexts blocks inside /// the module files; this module uses neither. /// public static class ContextConfiguration { /// The context a module asks for, from its ContextName. public static string ContextNameOf(string moduleConfigPath) => new ConfigurationBuilder().AddJsonFile(moduleConfigPath, optional: false).Build()["ContextName"] ?? throw new InvalidOperationException($"{moduleConfigPath} has no ContextName."); public static IDictionary Build(IConfiguration host, string contextName, string moduleConfigPath) { var config = NewDictionary(); Merge(config, Read(host.GetSection("Tsak:Contexts:default"), skipReserved: true)); Merge(config, Read(host.GetSection($"Tsak:Contexts:{contextName}"), skipReserved: true)); Merge(config, Read(new ConfigurationBuilder().AddJsonFile(moduleConfigPath, optional: false).Build(), skipReserved: false)); Merge(config, Read(host.GetSection($"Tsak:Contexts:{contextName}:Override"), skipReserved: false)); return config; } public static void ApplyTo(IRouteContext context, IDictionary config) { foreach (var (key, value) in config) { if (value is not null) context.SetProperty(key, value); } } private static Dictionary Read(IConfiguration section, bool skipReserved) { var result = NewDictionary(); foreach (var child in section.GetChildren()) { // A context section carries the module list and the Override layer next to the settings. if (skipReserved && (child.Key.Equals("Modules", StringComparison.OrdinalIgnoreCase) || child.Key.Equals("Override", StringComparison.OrdinalIgnoreCase))) continue; result[child.Key] = child.GetChildren().Any() ? Read(child, skipReserved: false) : child.Value; } return result; } private static void Merge(IDictionary target, IDictionary layer) { foreach (var (key, value) in layer) { if (value is IDictionary nested && target.TryGetValue(key, out var existing) && existing is IDictionary current) Merge(current, nested); else target[key] = value; } } private static Dictionary NewDictionary() => new(StringComparer.OrdinalIgnoreCase); } Path: redb-route/demo/As4ConformanceDemo/ConformanceWorker/Program.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/demo/As4ConformanceDemo/ConformanceWorker/Program.cs ---- // ============================================================================ // ConformanceWorker — a debug host for the ConformanceModule Tsak module. // // ConformanceWorker run the module for the eDelivery conformance testing service; // settings come from the module's config file and the Override layer in the // environment, as under Tsak (see README.md). // ConformanceWorker selftest run the module against a test driver of its own on loopback and // play the scenarios of the service's sample messages. Exit code 0 // when every check passed. // ============================================================================ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Route.Core; // RouteContext namespace ConformanceWorker; public static class Program { public static async Task Main(string[] args) { var services = new ServiceCollection(); services.AddLogging(b => b .AddSimpleConsole(o => { o.SingleLine = true; o.TimestampFormat = "HH:mm:ss "; }) .SetMinimumLevel(LogLevel.Information)); var sp = services.BuildServiceProvider(); if (args.Length > 0 && args[0] == "selftest") return await SelfTest.RunAsync(sp); // lossyproxy [host]: stands in front of a real test driver and loses its first // responses, to see the retry profile against another MSH. Point the module's TestDriver:Url at it. The host // is the address to listen on: loopback by default, "+" inside a container. if (args.Length is 4 or 5 && args[0] == "lossyproxy") { var swallow = args[3] == "all" ? int.MaxValue : int.Parse(args[3], System.Globalization.CultureInfo.InvariantCulture); await using var proxy = new LossyProxy(int.Parse(args[1], System.Globalization.CultureInfo.InvariantCulture), args[2], args.Length == 5 ? args[4] : "127.0.0.1"); proxy.Reset(swallow); Console.WriteLine($"Lossy proxy on port {args[1]} -> {args[2]}; responses to lose: {args[3]}. Ctrl+C to exit."); var done = new ManualResetEventSlim(); Console.CancelKeyPress += (_, e) => { e.Cancel = true; done.Set(); }; while (!done.Wait(TimeSpan.FromSeconds(2))) Console.WriteLine($"requests {proxy.Requests}, different bodies {proxy.DistinctBodies}"); return 0; } // The context configuration as the Tsak worker builds it: the module's config file, then the Override layer // from the environment (Tsak__Contexts__as4-conformance__Override__...). var host = new ConfigurationBuilder().AddEnvironmentVariables().Build(); var moduleConfig = Path.Combine(AppContext.BaseDirectory, "ConformanceModule.config.json"); var contextName = ContextConfiguration.ContextNameOf(moduleConfig); var ctx = new RouteContext(sp, contextId: contextName); ctx.AddService(typeof(ILoggerFactory), sp.GetRequiredService()); ContextConfiguration.ApplyTo(ctx, ContextConfiguration.Build(host, contextName, moduleConfig)); ConformanceModule.InitRoute.main(ctx); // <- the exact method the Tsak worker calls await ctx.Start(); Console.WriteLine(); Console.WriteLine("ConformanceWorker running. Ctrl+C to exit."); Console.WriteLine(); var stop = new ManualResetEventSlim(); Console.CancelKeyPress += (_, e) => { e.Cancel = true; stop.Set(); }; stop.Wait(); await ctx.DisposeAsync(); return 0; } } Path: redb-route/demo/As4ConformanceDemo/ConformanceWorker/SelfTest.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/demo/As4ConformanceDemo/ConformanceWorker/SelfTest.cs ---- using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Channels; using ConformanceModule; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using redb.Route.Abstractions; // IExchange, IMessage using redb.Route.As4; // As4Component, As4ConnectionFactory, As4Partner, As4Headers, As4Payload using redb.Route.As4.Fluent; // As4.Send / As4.Receive using redb.Route.Components; // AddIdempotentRepository using redb.Route.Core; // RouteContext, Exchange, Message using redb.Route.Processors; // InMemoryIdempotentRepository namespace ConformanceWorker; /// /// The module against a test driver of our own, on loopback: the message flow of the conformance testing service's /// samples ("AS4 Basic Connectivity Two Way SUT C3"), plus the ebMS test service and an ebMS error. The driver is the /// same connector with the parties swapped, so this proves the controller logic, not interoperability: that is what /// the stands (Domibus, Holodeck) and the service itself are for. /// internal static class SelfTest { private const int SutPort = 14190; private const int DriverPort = 14191; private const int ProxyPort = 14192; private const string SutRole = "http://www.edelivery.eu/as4/conformancetest/sut"; private const string DriverRole = "http://www.edelivery.eu/as4/conformancetest/testdriver"; private const string FailMarker = "selftest.fail"; /// What the driver received: the AS4 headers and the payloads, copied out of the exchange. private sealed record Received(Dictionary Headers, List<(string? Id, string Type, string Text, string? CharacterSet)> Payloads) { public string? Header(string name) => Headers.GetValueOrDefault(name); public string? Property(string name) => Headers.GetValueOrDefault(As4Headers.PropertyPrefix + name); } public static async Task RunAsync(IServiceProvider sp) { using var sutKey = SelfSigned("CN=redb AS4 SUT (selftest)"); using var driverKey = SelfSigned("CN=test driver (selftest)"); // The conformance testing service signs the commands with a key of their own, and posts them to a Domibus domain. using var driverControllerKey = SelfSigned("CN=test driver controller (selftest)"); // AS4_CP_TA78: another certificate of the same authority, signing as the test driver. using var secondaryKey = SelfSigned("CN=test driver secondary (selftest)"); // ── The module, exactly as the Tsak worker would configure it ── var settings = new ConformanceSettings { // The messages under test go to the driver through a proxy that can swallow its responses (a lost receipt). TestDriverUrl = $"http://127.0.0.1:{ProxyPort}/driver/msh", TestDriverControllerUrl = $"http://127.0.0.1:{DriverPort}/driver/controller?domain=sut_controller_domain", Port = SutPort, SutKey = sutKey, TestDriverCertificate = PublicOnly(driverKey), TestDriverControllerCertificate = PublicOnly(driverControllerKey), RetryCount = 1, RetryDelay = TimeSpan.FromSeconds(1), SendTimeout = 15000, }; var sut = NewContext(sp, "as4-conformance"); InitRoute.Configure(sut, settings); // ── The test driver ── var userMessages = Channel.CreateUnbounded(); var commands = Channel.CreateUnbounded(); var driver = NewContext(sp, "test-driver"); ConfigureDriver(driver, settings, driverKey, driverControllerKey, secondaryKey, PublicOnly(sutKey), userMessages, commands); await using var proxy = new LossyProxy(ProxyPort, $"http://127.0.0.1:{DriverPort}"); await sut.Start(); await driver.Start(); var failures = 0; void Check(string what, bool ok, string? detail = null) { if (!ok) failures++; Console.WriteLine($" [{(ok ? "PASS" : "FAIL")}] {what}{(ok || detail is null ? "" : ": " + detail)}"); } try { var conversation = Guid.NewGuid().ToString("D"); var requestId = $"selftest-request-{Guid.NewGuid():N}@gitb.eu"; var responseId = "AS4_RESPONSE_" + requestId; var sutUrl = $"http://127.0.0.1:{SutPort}{settings.SutPath}"; var controllerUrl = $"http://127.0.0.1:{SutPort}{settings.ControllerPath}"; // ── 1. Request leg: the driver sends a user message with two payloads; the SUT acknowledges and reports it ── Console.WriteLine("Two-Way, request leg (the SUT receives):"); var request = NewMessage(Payloads()); request.In.Headers[As4Headers.MessageId] = requestId; request.In.Headers[As4Headers.ConversationId] = conversation; await Send(driver, As4.Send(sutUrl).ConnectionFactory("driver").Partner(LegName(ConformanceLegs.TwoWay, "default")), request); Check("the SUT answers with a verified receipt", request.Out?.GetHeader(As4Headers.ReceiptValid) == true); var deliver = await Next(commands); Check("a Deliver command follows", deliver?.Header(As4Headers.Action) == "Deliver", deliver?.Header(As4Headers.Action)); Check("Deliver names the message", deliver?.Property("messageId") == requestId, deliver?.Property("messageId")); Check("Deliver names the conversation", deliver?.Property("conversationId") == conversation); Check("Deliver names service and action", deliver?.Property("service") == ConformanceLegs.TwoWay && deliver?.Property("action") == "default"); Check("Deliver names the parties and roles", deliver?.Property("fromPartyId") == settings.TestDriverPartyId && deliver?.Property("toPartyId") == settings.SutPartyId && deliver?.Property("fromPartyRole") == DriverRole && deliver?.Property("toPartyRole") == SutRole); CheckPayloads("Deliver", deliver, Check); // ── 2. Response leg: a Submit command asks the SUT to answer; the SUT sends, then reports the receipt ── Console.WriteLine("Two-Way, response leg (the SUT sends on a Submit command):"); var submit = NewMessage(Payloads()); Property(submit, "messageId", responseId); Property(submit, "refToMessageId", requestId); Property(submit, "conversationId", conversation); Property(submit, "fromPartyId", settings.SutPartyId); Property(submit, "fromPartyRole", SutRole); Property(submit, "toPartyId", settings.TestDriverPartyId); Property(submit, "toPartyRole", DriverRole); Property(submit, "service", ConformanceLegs.TwoWay); Property(submit, "action", "default"); Property(submit, "originalSender", "C4"); Property(submit, "finalRecipient", "C1"); await Send(driver, As4.Send(controllerUrl).ConnectionFactory("driver-controller").Partner("Submit"), submit); Check("the Submit command is acknowledged", submit.Out?.GetHeader(As4Headers.ReceiptValid) == true); var response = await Next(userMessages); Check("the SUT sends the user message with the commanded id", response?.Header(As4Headers.MessageId) == responseId, response?.Header(As4Headers.MessageId)); Check("it refers to the request", response?.Header(As4Headers.RefToMessageId) == requestId); Check("it keeps the conversation", response?.Header(As4Headers.ConversationId) == conversation); Check("it carries service and action of the leg", response?.Header(As4Headers.Service) == ConformanceLegs.TwoWay && response?.Header(As4Headers.Action) == "default"); Check("it carries the four-corner properties of the command", response?.Property("originalSender") == "C4" && response?.Property("finalRecipient") == "C1"); Check("it carries no command property", response?.Property("messageId") is null && response?.Property("service") is null); Check("its roles are the SUT's and the driver's", response?.Header(As4Headers.FromRole) == SutRole && response?.Header(As4Headers.ToRole) == DriverRole); CheckPayloads("the user message", response, Check); var notify = await Next(commands); Check("a Notify command follows", notify?.Header(As4Headers.Action) == "Notify", notify?.Header(As4Headers.Action)); Check("Notify reports a receipt", notify?.Property("signalType") == "receipt", notify?.Property("signalType")); Check("Notify refers to the message the SUT sent", notify?.Property("refToMessageId") == responseId, notify?.Property("refToMessageId")); Check("Notify has no payload", notify?.Payloads.Count == 0); // ── 3. The ebMS test service: acknowledged, and reported to nobody ── Console.WriteLine("ebMS test service (ping):"); var ping = NewMessage(Payloads()); await Send(driver, As4.Send(sutUrl).ConnectionFactory("driver").Partner(LegName(ConformanceLegs.TestService, ConformanceLegs.TestAction)), ping); Check("the ping is acknowledged", ping.Out?.GetHeader(As4Headers.ReceiptValid) == true); Check("no Deliver follows a ping", await Next(commands, TimeSpan.FromSeconds(2)) is null); // ── 4. The driver refuses the message: the SUT reports the ebMS error ── Console.WriteLine("The test driver answers with an ebMS error:"); var refusedId = $"selftest-refused-{Guid.NewGuid():N}@gitb.eu"; var refused = NewMessage(Payloads()); Property(refused, "messageId", refusedId); Property(refused, "service", ConformanceLegs.OneWay); Property(refused, "action", "default"); Property(refused, FailMarker, "true"); await Send(driver, As4.Send(controllerUrl).ConnectionFactory("driver-controller").Partner("Submit"), refused); var error = await Next(commands); Check("a Notify command follows", error?.Header(As4Headers.Action) == "Notify"); Check("Notify reports an error", error?.Property("signalType") == "error", error?.Property("signalType")); Check("Notify carries the ebMS error code", error?.Property("errorCode")?.StartsWith("EBMS:", StringComparison.Ordinal) == true, error?.Property("errorCode")); Check("Notify refers to the refused message", error?.Property("refToMessageId") == refusedId, error?.Property("refToMessageId")); // ── 5. The receipt is lost once: the SUT resends the same message, the driver delivers it once ── Console.WriteLine("Retry profile, the first receipt is lost (AS4_CP_TA09, TA10):"); var retriedId = $"selftest-retried-{Guid.NewGuid():N}@gitb.eu"; proxy.Reset(swallow: 1); await Send(driver, As4.Send(controllerUrl).ConnectionFactory("driver-controller").Partner("Submit"), RetrySubmit(retriedId)); var retried = await Next(userMessages); var retriedNotify = await Next(commands); Check("the driver gets the message", retried?.Header(As4Headers.MessageId) == retriedId, retried?.Header(As4Headers.MessageId)); Check("the SUT sent it twice", proxy.Requests == 2, proxy.Requests.ToString()); Check("the resend is the same message, byte for byte", proxy.DistinctBodies == 1, proxy.DistinctBodies.ToString()); Check("the driver delivers it once", await Next(userMessages, TimeSpan.FromSeconds(2)) is null); Check("Notify reports the receipt of the resend", retriedNotify?.Property("signalType") == "receipt" && retriedNotify?.Property("refToMessageId") == retriedId, retriedNotify?.Property("signalType")); // ── 6. Every receipt is lost: after the redeliveries the SUT reports EBMS:0301 ── Console.WriteLine("Retry profile, no receipt ever arrives (AS4_CP_TA15):"); var lostId = $"selftest-lost-{Guid.NewGuid():N}@gitb.eu"; proxy.Reset(swallow: int.MaxValue); await Send(driver, As4.Send(controllerUrl).ConnectionFactory("driver-controller").Partner("Submit"), RetrySubmit(lostId)); var lostNotify = await Next(commands); var lostDelivered = await Next(userMessages); Check("the driver did get the message once: only its receipts were lost", lostDelivered?.Header(As4Headers.MessageId) == lostId && await Next(userMessages, TimeSpan.FromSeconds(1)) is null); Check("the SUT sent it once and redelivered it RetryCount times", proxy.Requests == 1 + settings.RetryCount, proxy.Requests.ToString()); Check("every transmission is the same message", proxy.DistinctBodies == 1, proxy.DistinctBodies.ToString()); Check("Notify reports an error", lostNotify?.Property("signalType") == "error", lostNotify?.Property("signalType")); Check("the error is EBMS:0301 MissingReceipt", lostNotify?.Property("errorCode") == "EBMS:0301", lostNotify?.Property("errorCode")); Check("Notify refers to the message without a receipt", lostNotify?.Property("refToMessageId") == lostId, lostNotify?.Property("refToMessageId")); proxy.Reset(swallow: 0); // ── 7. PKI path: a signer that presents its certification path, and one that does not ── Console.WriteLine("PKI path (AS4_CP_TA47 to TA51):"); var withPath = NewMessage(Payloads()); await Send(driver, As4.Send(sutUrl).ConnectionFactory("driver").Partner(LegName(ConformanceLegs.OneWay, "bstPkiPath")), withPath); Check("a message signed with a path is acknowledged", withPath.Out?.GetHeader(As4Headers.ReceiptValid) == true); var pathDeliver = await Next(commands); Check("and reported with a Deliver", pathDeliver?.Property("action") == "bstPkiPath", pathDeliver?.Property("action")); var withoutPath = NewMessage(Payloads()); string? refusal = null; try { await Send(driver, As4.Send(sutUrl).ConnectionFactory("driver").Partner(LegName(ConformanceLegs.OneWay, "bstPkiPathSutC3Fail")), withoutPath); } catch (As4ErrorSignalException e) { refusal = e.ErrorCode; } Check("a signer that presents no path is refused where one is required", refusal == "EBMS:0101", refusal); Check("and no Deliver follows", await Next(commands, TimeSpan.FromSeconds(2)) is null); var pathSubmitId = $"selftest-pkipath-{Guid.NewGuid():N}@gitb.eu"; var pathSubmit = NewMessage(Payloads()); Property(pathSubmit, "messageId", pathSubmitId); Property(pathSubmit, "service", ConformanceLegs.OneWay); Property(pathSubmit, "action", "bstPkiPath"); await Send(driver, As4.Send(controllerUrl).ConnectionFactory("driver-controller").Partner("Submit"), pathSubmit); var pathMessage = await Next(userMessages); var pathNotify = await Next(commands); Check("on a Submit the SUT sends with its own path and the driver receives it", pathMessage?.Header(As4Headers.MessageId) == pathSubmitId, pathMessage?.Header(As4Headers.MessageId)); Check("the driver's receipt, signed with a path, is verified", pathNotify?.Property("signalType") == "receipt", pathNotify?.Property("signalType")); // ── 8. Sender authentication: the test driver's party id, signed with another certificate ── Console.WriteLine("Sender authentication (AS4_CP_TA78):"); var impostor = NewMessage(Payloads()); string? impostorRefusal = null; try { await Send(driver, As4.Send(sutUrl).ConnectionFactory("driver-secondary").Partner("default"), impostor); } catch (As4ErrorSignalException e) { impostorRefusal = e.ErrorCode; } Check("a message signed by a certificate that is not the sender's is refused", impostorRefusal == "EBMS:0101", impostorRefusal); Check("and no Deliver follows", await Next(commands, TimeSpan.FromSeconds(2)) is null); } catch (Exception e) { failures++; Console.WriteLine($" [FAIL] the scenario stopped: {e.GetType().Name}: {e.Message}"); } finally { await driver.DisposeAsync(); await sut.DisposeAsync(); } Console.WriteLine(); Console.WriteLine(failures == 0 ? "Self-test passed." : $"Self-test FAILED: {failures} check(s)."); return failures == 0 ? 0 : 1; } // ── The test driver ────────────────────────────────────────────────────── private static string LegName(string service, string action) => "leg-" + ConformanceLegs.Default.ToList().FindIndex(l => l.Service == service && l.Action == action); private static void ConfigureDriver(RouteContext context, ConformanceSettings settings, X509Certificate2 driverKey, X509Certificate2 driverControllerKey, X509Certificate2 secondaryKey, X509Certificate2 sutCertificate, Channel userMessages, Channel commands) { context.AddComponent(new As4Component()); As4Partner Agreement(string name, string partyId, string service, string action) => new() { Name = name, PartyId = partyId, PartyIdType = ConformanceSettings.UnregisteredPartyIdType, OurRole = DriverRole, PartnerRole = SutRole, Service = service, Action = action, ReplyLeg = new As4Leg { Service = service, Action = action }, RequireFourCornerProperties = false, PartnerSigningCertificates = { sutCertificate }, PartnerEncryptionCertificate = sutCertificate, }; var node = new As4ConnectionFactory { OurPartyId = settings.TestDriverPartyId, OurPartyIdType = ConformanceSettings.UnregisteredPartyIdType, ExternalHostName = "gitb.eu", SigningCertificate = driverKey, DecryptionCertificates = { driverKey }, }; foreach (var leg in ConformanceLegs.Default) { var agreement = Agreement(LegName(leg.Service, leg.Action), settings.SutPartyId, leg.Service, leg.Action); // The driver presents its certification path on the leg that expects one to be accepted, and its bare // certificate on the leg that expects the SUT to refuse it. if (leg.Action == "bstPkiPath") agreement.KeyReference = As4KeyReference.PkiPath; node.Partners.Add(agreement); } context.AddToRegistry("driver", node); // The same party signing with another key: only the message under test goes out from it. var secondary = new As4ConnectionFactory { OurPartyId = settings.TestDriverPartyId, OurPartyIdType = ConformanceSettings.UnregisteredPartyIdType, ExternalHostName = "gitb.eu", SigningCertificate = secondaryKey, DecryptionCertificates = { secondaryKey }, }; secondary.Partners.Add(Agreement("default", settings.SutPartyId, ConformanceLegs.OneWay, "default")); context.AddToRegistry("driver-secondary", secondary); var controller = new As4ConnectionFactory { OurPartyId = settings.TestDriverControllerPartyId, OurPartyIdType = ConformanceSettings.UnregisteredPartyIdType, ExternalHostName = "gitb.eu", SigningCertificate = driverControllerKey, DecryptionCertificates = { driverControllerKey }, }; foreach (var command in new[] { "Submit", "Deliver", "Notify" }) controller.Partners.Add(Agreement(command, settings.ControllerPartyId, ConformanceLegs.CommandService, command)); context.AddToRegistry("driver-controller", controller); context.AddIdempotentRepository("driver-in", new InMemoryIdempotentRepository(TimeSpan.FromHours(1))); context.AddIdempotentRepository("driver-controller-in", new InMemoryIdempotentRepository(TimeSpan.FromHours(1))); context.AddRoutes(r => { r.From(As4.Receive("/driver/msh").Host("127.0.0.1").Port(DriverPort).ConnectionFactory("driver") .IdempotentRepository("driver-in").PayloadList()) .RouteId("driver-msh") .Process(e => { var received = Capture(e.In); if (received.Property(FailMarker) is not null) throw new InvalidOperationException("selftest: the driver refuses this message."); userMessages.Writer.TryWrite(received); }); r.From(As4.Receive("/driver/controller").Host("127.0.0.1").Port(DriverPort).ConnectionFactory("driver-controller") .IdempotentRepository("driver-controller-in").PayloadList()) .RouteId("driver-controller") .Process(e => commands.Writer.TryWrite(Capture(e.In))); }); } private static Received Capture(IMessage message) { var headers = message.Headers .Where(h => h.Key.StartsWith(As4Headers.Prefix, StringComparison.Ordinal) && h.Value is not null) .ToDictionary(h => h.Key, h => h.Value!.ToString()!); var payloads = ((IReadOnlyList)message.Body!) .Select(p => (p.ContentId, p.ContentType, new StreamReader(p.Content, leaveOpen: true).ReadToEnd(), p.Properties.TryGetValue("CharacterSet", out var set) ? set : null)) .ToList(); return new Received(headers, payloads); } // ── Fixtures ───────────────────────────────────────────────────────────── // The payload profile of the user guide (§5.3.3): an XML leading document and a non-XML one. private static List Payloads() => [ new("xmlpayload@gitb", "application/xml", new MemoryStream(Encoding.UTF8.GetBytes("world")), new Dictionary { ["CharacterSet"] = "UTF-8" }), new("custompayload@gitb", "application/octet-stream", new MemoryStream(Encoding.UTF8.GetBytes("custom payload")), new Dictionary { ["CharacterSet"] = "UTF-8" }), ]; private static void CheckPayloads(string of, Received? received, Action check) { var payloads = received?.Payloads ?? []; check($"{of} carries both payloads in order, under their Content-IDs", payloads.Select(p => p.Id).SequenceEqual(["xmlpayload@gitb", "custompayload@gitb"]), string.Join(", ", payloads.Select(p => p.Id))); check($"{of} carries their content and media types", payloads.Select(p => (p.Type, p.Text)).SequenceEqual([("application/xml", "world"), ("application/octet-stream", "custom payload")]), null); check($"{of} carries the CharacterSet part property", payloads.Count == 2 && payloads.All(p => p.CharacterSet == "UTF-8"), null); } private static Exchange NewMessage(List payloads) => new(new Message(payloads)); private static Exchange RetrySubmit(string messageId) { var submit = NewMessage(Payloads()); Property(submit, "messageId", messageId); Property(submit, "service", ConformanceLegs.OneWay); Property(submit, "action", "retry"); return submit; } private static void Property(Exchange exchange, string name, string value) => exchange.In.Headers[As4Headers.PropertyPrefix + name] = value; private static async Task Send(RouteContext context, string uri, IExchange exchange) { var producer = context.GetEndpoint(uri).CreateProducer(); await producer.Start(); try { await producer.Process(exchange); } finally { await producer.Stop(); } } private static async Task Next(Channel channel, TimeSpan? timeout = null) { using var cts = new CancellationTokenSource(timeout ?? TimeSpan.FromSeconds(20)); try { return await channel.Reader.ReadAsync(cts.Token); } catch (OperationCanceledException) { return null; } } private static RouteContext NewContext(IServiceProvider sp, string id) { var context = new RouteContext(sp, contextId: id); context.AddService(typeof(ILoggerFactory), sp.GetRequiredService()); return context; } // SELF-TEST ONLY: a self-signed RSA certificate. The conformance testing service hands out the real ones. private static X509Certificate2 SelfSigned(string subject) { using var rsa = RSA.Create(2048); var request = new CertificateRequest(subject, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509KeyUsageExtension( X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment, critical: false)); using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1)); return X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pfx, "selftest"), "selftest"); } private static X509Certificate2 PublicOnly(X509Certificate2 certificate) => X509CertificateLoader.LoadCertificate(certificate.Export(X509ContentType.Cert)); } /// /// Stands between the SUT and the test driver, as the conformance tests "simulate the RMSH to not send receipts /// (can be done by intercepting the receipts)": every request reaches the driver, and the first responses are /// swallowed, answered to the SUT with an empty 202. /// internal sealed class LossyProxy : IAsyncDisposable { private readonly System.Net.HttpListener _listener = new(); private readonly HttpClient _http = new() { Timeout = TimeSpan.FromSeconds(30) }; private readonly string _target; private readonly Task _loop; private readonly HashSet _bodies = []; private int _swallow; private int _requests; /// Port to listen on. /// Scheme, host and port of the test driver the requests are forwarded to. /// Address to listen on: loopback for the self-test, + inside a container. public LossyProxy(int port, string target, string host = "127.0.0.1") { _target = target; _listener.Prefixes.Add($"http://{host}:{port}/"); _listener.Start(); _loop = Task.Run(ServeAsync); } /// Requests seen since the last . public int Requests => Volatile.Read(ref _requests); /// Different request bodies among them: one when every transmission was the same bytes. public int DistinctBodies { get { lock (_bodies) return _bodies.Count; } } /// Forgets what was seen; the next responses of the driver are lost. public void Reset(int swallow) { Volatile.Write(ref _swallow, swallow); Volatile.Write(ref _requests, 0); lock (_bodies) _bodies.Clear(); } private async Task ServeAsync() { while (_listener.IsListening) { System.Net.HttpListenerContext context; try { context = await _listener.GetContextAsync(); } catch (Exception e) when (e is System.Net.HttpListenerException or ObjectDisposedException or ArgumentException) { return; } try { using var body = new MemoryStream(); await context.Request.InputStream.CopyToAsync(body); var bytes = body.ToArray(); Interlocked.Increment(ref _requests); lock (_bodies) _bodies.Add(Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(bytes))); using var forward = new HttpRequestMessage(HttpMethod.Post, _target + context.Request.RawUrl) { Content = new ByteArrayContent(bytes) }; forward.Content.Headers.TryAddWithoutValidation("Content-Type", context.Request.ContentType); using var answer = await _http.SendAsync(forward); var answerBytes = await answer.Content.ReadAsByteArrayAsync(); var remaining = Volatile.Read(ref _swallow); if (remaining > 0) { if (remaining != int.MaxValue) Volatile.Write(ref _swallow, remaining - 1); context.Response.StatusCode = 202; } else { context.Response.StatusCode = (int)answer.StatusCode; context.Response.ContentType = answer.Content.Headers.ContentType?.ToString(); await context.Response.OutputStream.WriteAsync(answerBytes); } context.Response.Close(); } catch (Exception e) when (e is System.Net.HttpListenerException or ObjectDisposedException or IOException or HttpRequestException) { // The listener is stopping, or the SUT gave up on this request. } } } public async ValueTask DisposeAsync() { _listener.Stop(); _listener.Close(); _http.Dispose(); await _loop; } } Path: redb-route/demo/As4ConformanceDemo/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/demo/As4ConformanceDemo/README.md ---- # As4ConformanceDemo — the System Under Test for the eDelivery AS4 conformance testing service The European Commission's [eDelivery conformance testing service](https://ec.europa.eu/digital-building-blocks/sites/spaces/DIGITAL/pages/467118600/eDelivery+conformance+testing) checks an AS4 access point against the eDelivery AS4 profile. Its test driver cannot press buttons in somebody else's product, so it asks the owner of the access point to write a **SUT Controller**: the piece that obeys the driver's commands and reports back. This demo is that controller, and the access point it drives, as one redb.Route module. Two projects, one entry point: `InitRoute.main` is called by both the Tsak worker and the debug host (the layout of [EchoWorkerDemo](../EchoWorkerDemo)). ``` As4ConformanceDemo/ ├─ ConformanceModule/ <- the module (class library -> ConformanceModule.tpkg) │ ├─ InitRoute.cs <- main(IRouteContext): two nodes, their agreements, the routes │ ├─ Commands.cs <- Submit, Deliver, Notify: a command to a message and back │ ├─ ConformanceSettings.cs <- settings from the route context and the table of service/action legs │ └─ manifest.json ├─ ConformanceWorker/ <- the debug host (exe) │ ├─ Program.cs <- InitRoute.main(ctx) + Start, or "selftest", or "lossyproxy" │ ├─ ContextConfiguration.cs <- the context settings as the Tsak worker builds them │ └─ SelfTest.cs <- a test driver of our own on loopback └─ deploy/ <- the module under Tsak: docker-compose.tsak.yml, docker-compose.mssql.yml, .env.example ``` ## What the service asks for, and where it is A command is an ordinary AS4 user message on a channel of its own (service `http://www.edelivery.eu/as4/conformancetest`); what it says travels in `eb:MessageProperties` and its payloads (user guide v2.90, §5.3). ``` test driver ──Submit──> /as4/controller ──> the user message it asks for ──> test driver │ receipt, ebMS error or no receipt ──Notify──> test driver test driver ──user message──> /as4/sut ──> receipt in the response │ ──Deliver──> test driver (not for the ebMS test service) ``` | Route | What it does | |---|---| | `as4ct-submit` | Receives a **Submit**, turns its properties into the header values of the message to send (`messageId`, `conversationId`, `refToMessageId`, every other property as a message property) and queues it. The command gets its receipt first. | | `as4ct-send`, `as4ct-send-retry` | Send that message to the test driver under the agreement of its service and action, then send a **Notify**: `signalType=receipt`, or `signalType=error` with the ebMS code. The retry route redelivers a missing receipt (the same message, byte for byte) before it reports `EBMS:0301`. | | `as4ct-receive` | The access point under test. The receipt goes out with the response; the message is queued for a **Deliver**. A message for the ebMS test service stops here: acknowledged, reported to nobody. | | `as4ct-deliver` | Sends the **Deliver**: the header values of the received message as properties, its payloads as they came. | Two nodes, because the service uses two pairs of party ids: `sut` is the access point under test, `controller` the command channel. The agreements of `sut` are built from `ConformanceLegs.Default`, one per service and action of the tests (user guide, annex A); a received message is matched on sender, service and action. Add a pair with the `ExtraLegs` setting when a test suite needs one that is not there. Four things of the connector carry the controller: - a partner address with a query: the service takes the commands at a Domibus domain, `/domibus?domain=...`; - a list of `As4Payload` as the body: several payloads in the order given, under the Content-IDs the driver chose, with their part properties, and an empty list for a Notify, which has no payload; - `payloadList` on the receive endpoints: a single payload still arrives with its Content-ID and part properties; - `RequireFourCornerProperties = false`: the common profile does not ask for `originalSender` and `finalRecipient`. ## Check it without the service ``` dotnet run --project ConformanceWorker --framework net10.0 -- selftest ``` A second route context plays the test driver on loopback and walks the message flow of the service's own sample ("AS4 Basic Connectivity Two Way SUT C3"), then a ping, an ebMS error and the retry profile: a proxy between the two swallows the driver's responses, once (the message is resent byte for byte, delivered once, and the receipt of the resend is reported) and for good (`EBMS:0301` is reported after the redeliveries). Every step prints `PASS` or `FAIL`; the exit code is 0 when all 49 passed. Then the PKI path: a signer that presents its certification path is acknowledged, one that does not is refused where a path is required, and on a Submit the SUT sends with its own. The last scenario is sender authentication (TA78): a message from the test driver's party id signed with another certificate is refused with `EBMS:0101`. As the service does, the driver signs its commands with a key of their own and takes them at an address with a query. The driver is the same connector with the parties swapped, so this proves the controller logic and nothing about interoperability. ## Check it against Domibus The Commission's test driver runs on Domibus. The Harmony stand (Harmony AP 2.6.2, whose MSH is Domibus 5.1) plays that driver: its P-Mode has the roles, legs and commands of the tests, and its WS plugin submits what the driver would send. Both directions were run there: Domibus sends a two-payload message to the access point and gets the Deliver with the properties and both payloads; Domibus sends a Submit and gets the user message under the commanded id, then the Notify; a Two-Way exchange, the response referring to the request under the same service and action; and the retry profile through `ConformanceWorker lossyproxy`, which stands in front of Domibus and loses its responses: one lost (resent byte for byte, Domibus answers with its stored receipt) and all lost (`EBMS:0301` reported). The stand, its P-Mode and the script that drives it are described in the stand's own README (`conformance-driver.sh receive|submit|twoway|retry`). ## Settings The module takes its settings from the route context, the way the Tsak worker provides them. Its own `ConformanceModule.config.json`, which travels inside the package, holds the defaults; what differs per test account arrives through the Override layer, environment variables on the worker of the form `Tsak__Contexts__as4-conformance__Override__
__`. | Section and key | Default | Meaning | |---|---|---| | `TestDriver:Url` | (required) | MSH address of the test driver for the messages under test. | | `TestDriver:ControllerUrl` | `TestDriver:Url` | MSH address of the test driver for Deliver and Notify; it may carry a query, such as the Domibus domain of the service (`?domain=sut_controller_domain`). | | `TestDriver:PartyId` | `test_driver` | Party id of the test driver. | | `TestDriver:ControllerPartyId` | `test_driver_sut_controller_domain` | Its party id on the command channel. | | `TestDriver:Certificate` | (required) | File of the test driver's certificate (DER or PEM). | | `TestDriver:ControllerCertificate` | `TestDriver:Certificate` | File of the test driver's certificate on the command channel; the service signs Submit, Deliver and Notify with a certificate of its own (`test_driver_sut_controller`). | | `TestDriver:TrustAnchors` | the test driver's certificate | Certificate files (`;` between them) of the authorities its signer must chain to on the legs `bstPkiPath*`. | | `Sut:PartyId` | `system_under_test` | Party id of the access point under test, as assigned. | | `Sut:ControllerPartyId` | `sut_controller_domain` | Our party id on the command channel. | | `Sut:Pfx`, `Sut:PfxPassword` | (required), none | The SUT key as a PKCS#12 file. | | `Sut:Chain` | none | Certificate files of the authorities above the SUT certificate: sent with it as its certification path on the legs `bstPkiPath*`. | | `Sut:HostName` | `redb.route` | Host part of the message ids we generate. | | `Receive:Port` | `4090` | Port of both receive endpoints. | | `Receive:SutPath`, `Receive:ControllerPath` | `/as4/sut`, `/as4/controller` | Their paths. | | `Receive:DuplicateStore` | `memory` | Where the ids of received messages are remembered: `memory` (lost with the process) or `redb` (the worker's redb: a resend is still a duplicate after a restart, and on every node of a cluster). | | `Receive:DuplicateWindowDays` | `7` | How long an id is remembered. | | `Retry:Count`, `Retry:DelaySeconds` | `4`, `20` | Redeliveries of the retry profile: the test driver takes 5 transmissions (the message and 4 redeliveries), less than 3 minutes apart, then expects the Notify. | | `Retry:SendTimeoutMs` | `60000` | Milliseconds to wait for the test driver's response. | | `PkiPath:Policy` | none | Certificate policy OID required on the leg `bstPkiPathSutC3PolicyFail`; without it that leg is left out. | | `ExtraLegs` | none | More legs: `service\|action;service\|action`. | The party ids above are the ones of the service's sample messages; use the ones you are given. ## Run it under Tsak `deploy/` holds what a deployment needs: `docker-compose.tsak.yml` (the Tsak stack image, in-memory storage, the package in `./modules`, the keys in `./keys`) and `.env.example`. Copy the example to `.env`, fill it in, put `ConformanceModule/output/ConformanceModule.tpkg` into `modules/` and the two key files into `keys/`: ``` docker compose -f docker-compose.tsak.yml up -d ``` The package holds the module's DLL, its config file and the manifest; the AS4 connector comes from the worker's shared layer, so **the worker image must carry the connector this module was built against**. The compose file joins the Docker network of the access point that plays the test driver, and that access point posts to `http://as4ct-tsak:4090/as4/sut` and `/as4/controller`. For the conformance testing service itself the two paths go behind the reverse proxy that terminates TLS: the service needs two public HTTPS addresses from you. ### Persistent storage `deploy/docker-compose.mssql.yml` goes on top of the first file: Tsak's own state and the module's memory of received message ids live in a SQL Server database, and `Receive:DuplicateStore` becomes `redb`. Without it everything ends with the process: a message the partner resends after a restart of the container would be delivered a second time. Give the stand a database and a login of its own; redb creates its tables, not the database. ``` docker compose -f docker-compose.tsak.yml -f docker-compose.mssql.yml up -d ``` Checked against Domibus (2026-10-13): a message is delivered and reported, its receipt is lost on the way back, the container is restarted, Domibus resends the message — the restarted module answers with the receipt again and does not deliver or report it a second time. ### What was run This was run on a Linux host against Domibus (2026-10-13): the scenarios of `conformance-driver.sh` pass from the container — `receive`, `submit`, `twoway`, `retry` through the lossy proxy (one response lost, and all of them), and `receive` and `submit` on the PKI path leg. That run is also what found that the connector wrote MIME line endings by the platform's default: from Linux every message with a payload was refused until 4.3.0 (see the changelog). ## Run it in the debug host The same entry point, outside Tsak: the host reads the module's config file and the same Override variables. ``` dotnet run --project ConformanceWorker --framework net10.0 ``` ## What is not here - **Pull, Dynamic Discovery, SBDH**: optional enhancements of the profile, not implemented by the connector. The Four Corner enhancement needs nothing more than the properties the driver gives. - **Negative tests** (a damaged payload, a hyperlink reference, compression after signing): the driver sends those itself and expects an ebMS error from the access point; no controller logic is involved. - **Keys**: nothing of a test account belongs in a repository; `.gitignore` here refuses the usual file types. Path: redb-route/demo/As4ConformanceDemo/deploy/docker-compose.mssql.yml 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/demo/As4ConformanceDemo/deploy/docker-compose.mssql.yml ---- # Persistent storage for the stand, on top of docker-compose.tsak.yml: Tsak's own state (modules, contexts, audit, # dead letters, the Quartz job store) and the module's memory of received message ids live in a SQL Server database # instead of ending with the process. # # docker compose -f docker-compose.tsak.yml -f docker-compose.mssql.yml up -d # # or once, in .env: COMPOSE_FILE=docker-compose.tsak.yml:docker-compose.mssql.yml # # The database must exist: redb creates its tables, not the database. Give the stand a database and a login of its own. services: tsak: environment: - ConnectionStrings__MSSql=${TSAK_MSSQL_CONNECTION:?TSAK_MSSQL_CONNECTION required} - Tsak__Storage__Type=Redb - Tsak__Redb__Provider=mssql - Tsak__Redb__UsePro=true # The job store is now in a database other nodes can share, so the scheduler is clustered: the image ships # with clustering off, for its default storage, and the worker reports the combination as fatal at startup. - Quartz__quartz.jobStore.clustered=true # With a shared store the dashboard runs in cluster mode: it signs users in against the users of the store # (roles admin / operator / viewer) and finds the worker there, under the address the worker registers. # The Tsak:Web:Nodes entries of docker-compose.tsak.yml are not read in this mode. - Tsak__Web__Mode=cluster - Tsak__Web__ServiceApiKey=${TSAK_WEB_API_KEY:?TSAK_WEB_API_KEY required} - Tsak__Cluster__NodeId=as4ct-1 # The address the worker registers for its management API: the container name on the compose networks, which # the dashboard in the same container and any other node or dashboard on those networks can reach. A loopback # address would reach only the container itself, and the worker warns about it at every start. - Tsak__Cluster__ApiEndpoint=http://as4ct-tsak:9090 # A resend after a restart is still a duplicate: the ids of received messages go to the same database. - Tsak__Contexts__as4-conformance__Override__Receive__DuplicateStore=redb networks: [stand, db] networks: db: name: ${TSAK_DB_NETWORK:?TSAK_DB_NETWORK required} external: true Path: redb-route/demo/As4ConformanceDemo/deploy/docker-compose.postgres.yml 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/demo/As4ConformanceDemo/deploy/docker-compose.postgres.yml ---- # Persistent storage in PostgreSQL, on top of docker-compose.tsak.yml: Tsak's own state (modules, contexts, audit, # dead letters, the Quartz job store) and the module's memory of received message ids live in a database of their own. # # docker compose -f docker-compose.tsak.yml -f docker-compose.postgres.yml up -d # # or once, in .env: COMPOSE_FILE=docker-compose.tsak.yml:docker-compose.postgres.yml # # The database must exist: redb creates its tables, not the database. Give the stand a database and a role of its own, # the owner of that database and nothing more. services: tsak: environment: - ConnectionStrings__Postgres=${TSAK_POSTGRES_CONNECTION:?TSAK_POSTGRES_CONNECTION required} - Tsak__Storage__Type=Redb - Tsak__Redb__Provider=postgres - Tsak__Redb__UsePro=true # The job store is in a database other nodes could share, so the scheduler is clustered: the image ships with # clustering off, for its default storage, and the worker reports the combination as fatal at startup. - Quartz__quartz.jobStore.clustered=true # With a shared store the dashboard runs in cluster mode: it signs users in against the users of the store # (roles admin / operator / viewer) and finds the worker there, under the address the worker registers. # The Tsak:Web:Nodes entries of docker-compose.tsak.yml are not read in this mode. - Tsak__Web__Mode=cluster - Tsak__Web__ServiceApiKey=${TSAK_WEB_API_KEY:?TSAK_WEB_API_KEY required} - Tsak__Cluster__NodeId=${TSAK_NODE_ID:-as4ct-1} # The address the worker registers for its management API: the container name on the compose networks, which # the dashboard in the same container and any other node or dashboard on those networks can reach. A loopback # address would reach only the container itself, and the worker warns about it at every start. - Tsak__Cluster__ApiEndpoint=http://as4ct-tsak:9090 # A resend after a restart is still a duplicate: the ids of received messages go to the same database. - Tsak__Contexts__as4-conformance__Override__Receive__DuplicateStore=redb networks: [stand, db] networks: db: name: ${TSAK_DB_NETWORK:?TSAK_DB_NETWORK required} external: true Path: redb-route/demo/As4ConformanceDemo/deploy/docker-compose.tsak.yml 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/demo/As4ConformanceDemo/deploy/docker-compose.tsak.yml ---- # ConformanceModule under Tsak: the stack image (worker + dashboard), in-memory storage, the module as a .tpkg in # ./modules, the keys in ./keys. Nothing of a test account is in this file: copy .env.example to .env and fill it in. # # docker compose -f docker-compose.tsak.yml up -d # # The container joins the network of the access point that plays the test driver, so the two reach each other by # name: the driver posts to http://as4ct-tsak:4090/as4/sut and .../as4/controller. For the conformance testing # service itself, publish port 4090 behind the reverse proxy that terminates TLS instead. name: as4-conformance services: tsak: image: ${TSAK_IMAGE:-redb-tsak-stack:4.3.0-net10} container_name: as4ct-tsak restart: ${AS4CT_RESTART:-no} # a stand is started by hand; the public access point: unless-stopped ports: - "${TSAK_WEB_BIND:-127.0.0.1}:${TSAK_WEB_PORT:-18085}:8085" # dashboard; TSAK_WEB_BIND opens it to one interface - "127.0.0.1:${TSAK_API_PORT:-19090}:9090" # management API environment: # ── Tsak ── - Tsak__Storage__Type=InMemory - Tsak__Modules__AssemblyPaths__0=/app/modules - Tsak__Auth__Enabled=true - Tsak__Auth__Secret=${TSAK_AUTH_SECRET:?TSAK_AUTH_SECRET required} - Tsak__Auth__Keys__0__Id=svc-tsak-web - Tsak__Auth__Keys__0__KeyHash=${TSAK_WEB_API_KEY_HASH:?TSAK_WEB_API_KEY_HASH required} - Tsak__Auth__Keys__0__Name=tsak-web-dashboard - Tsak__Auth__Keys__0__Roles=admin - Tsak__Web__AdminLogin=admin # The BCrypt hash of the dashboard password, not the password: nothing on the host gives the password back. - Tsak__Web__AdminPasswordHash=${TSAK_WEB_ADMIN_PASSWORD_HASH:?TSAK_WEB_ADMIN_PASSWORD_HASH required} # In-memory storage has no shared store to discover workers from: the dashboard is told its one worker, with # the key it calls the management API with (Tsak:Web:ServiceApiKey is read in cluster mode only). # Behind a reverse proxy that publishes the dashboard: the client address and scheme from X-Forwarded-*, so the # login throttle sees real clients and the auth cookie is Secure. Off when nothing proxies the dashboard. - Tsak__Web__TrustProxyHeaders=${TSAK_WEB_TRUST_PROXY_HEADERS:-false} - Tsak__Web__Mode=standalone - Tsak__Web__Nodes__0__Id=default - Tsak__Web__Nodes__0__Url=http://localhost:9090 - Tsak__Web__Nodes__0__ApiKey=${TSAK_WEB_API_KEY:?TSAK_WEB_API_KEY required} # ── The module: what differs from ConformanceModule.config.json ── - Tsak__Contexts__as4-conformance__Override__TestDriver__Url=${AS4CT_TESTDRIVER_URL:?AS4CT_TESTDRIVER_URL required} - Tsak__Contexts__as4-conformance__Override__TestDriver__ControllerUrl=${AS4CT_TESTDRIVER_CONTROLLER_URL:?AS4CT_TESTDRIVER_CONTROLLER_URL required} - Tsak__Contexts__as4-conformance__Override__TestDriver__PartyId=${AS4CT_TESTDRIVER_PARTY:-test_driver} - Tsak__Contexts__as4-conformance__Override__TestDriver__ControllerPartyId=${AS4CT_TESTDRIVER_CONTROLLER_PARTY:-test_driver_sut_controller_domain} - Tsak__Contexts__as4-conformance__Override__TestDriver__Certificate=/app/keys/${AS4CT_TESTDRIVER_CERT_FILE:?AS4CT_TESTDRIVER_CERT_FILE required} # Optional, full paths in the container (empty = not set): the command channel's certificate, the authorities # a path token must chain to, and the authorities above the SUT certificate (";" between files). - Tsak__Contexts__as4-conformance__Override__TestDriver__ControllerCertificate=${AS4CT_TESTDRIVER_CONTROLLER_CERT:-} - Tsak__Contexts__as4-conformance__Override__TestDriver__TrustAnchors=${AS4CT_TESTDRIVER_TRUST_ANCHORS:-} - Tsak__Contexts__as4-conformance__Override__Sut__Chain=${AS4CT_SUT_CHAIN:-} - Tsak__Contexts__as4-conformance__Override__Sut__PartyId=${AS4CT_SUT_PARTY:-system_under_test} - Tsak__Contexts__as4-conformance__Override__Sut__ControllerPartyId=${AS4CT_CONTROLLER_PARTY:-sut_controller_domain} - Tsak__Contexts__as4-conformance__Override__Sut__Pfx=/app/keys/${AS4CT_SUT_PFX_FILE:?AS4CT_SUT_PFX_FILE required} - Tsak__Contexts__as4-conformance__Override__Sut__PfxPassword=${AS4CT_SUT_PFX_PASSWORD:?AS4CT_SUT_PFX_PASSWORD required} - Tsak__Contexts__as4-conformance__Override__Sut__HostName=${AS4CT_HOST_NAME:-redb.route} - Tsak__Contexts__as4-conformance__Override__Retry__Count=${AS4CT_RETRY_COUNT:-4} - Tsak__Contexts__as4-conformance__Override__Retry__DelaySeconds=${AS4CT_RETRY_DELAY_SECONDS:-20} volumes: - ./modules:/app/modules - ./keys:/app/keys:ro - as4ct-logs:/app/worker/Logs networks: [stand] volumes: as4ct-logs: networks: stand: name: ${AS4CT_NETWORK:?AS4CT_NETWORK required} external: true