Bundle: redb-route / tests/redb.Route.Tests.As4 (tests.redb.Route.Tests.As4.txt), 22 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/tests/redb.Route.Tests.As4/As4CanonicalizationTests.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/tests/redb.Route.Tests.As4/As4CanonicalizationTests.cs ---- using System.Security.Cryptography; using System.Text; using redb.Route.As4.Mime; using redb.Route.As4.Security; namespace redb.Route.Tests.As4; /// /// The digest input of the Attachment-Content-Signature-Transform (SwA 1.1 §5.4.2, the rules of WSS4J): /// Exclusive C14N for XML media types, CRLF line endings for other text, the bytes as they are for the rest. /// Interop with Holodeck over these rules is As4HolodeckLiveTests.UncompressedTextPayload_*. /// public class As4CanonicalizationTests { private static byte[] Digest(string contentType, string content) => AttachmentCanonicalizer.Sha256(new SwaPart("p", contentType, Encoding.UTF8.GetBytes(content))); private static byte[] Sha(string canonical) => SHA256.HashData(Encoding.UTF8.GetBytes(canonical)); [Theory] [InlineData("text/xml")] [InlineData("text/xml; charset=UTF-8")] [InlineData("application/xml")] [InlineData("application/soap+xml")] [InlineData("image/svg+xml")] public void XmlMediaTypes_AreExclusiveC14N(string contentType) { Digest(contentType, "") .Should().Equal(Sha("")); } [Theory] [InlineData("a\nb", "a\r\nb")] [InlineData("a\rb", "a\r\nb")] [InlineData("a\r\nb", "a\r\nb")] [InlineData("a\n\nb\r\r", "a\r\n\r\nb\r\n\r\n")] public void OtherText_HasCrlfLineEndings(string content, string canonical) { Digest("text/plain", content).Should().Equal(Sha(canonical)); } [Fact] public void CrlfSplitAcrossReads_IsOneLineEnding() { // The reader works in 80 KB blocks: a CR that ends one block and the LF that starts the next are one CRLF. var head = new string('x', 81919); Digest("text/csv", head + "\r\n" + "tail").Should().Equal(Sha(head + "\r\n" + "tail")); } [Theory] [InlineData("application/octet-stream")] [InlineData("application/gzip")] [InlineData("application/pdf")] public void OtherMediaTypes_AreTheBytesAsTheyAre(string contentType) { Digest(contentType, "\n").Should().Equal(Sha("\n")); } [Fact] public void XmlAttachmentWithADoctype_IsRefused_AsAFailedSignature() { var act = () => Digest("text/xml", "]>&e;"); act.Should().Throw().WithMessage("*cannot be read as XML*"); } [Fact] public void XmlAttachmentOverTheDefaultLimits_IsRefusedBeforeCanonicalization() { // The payload is the partner's document, read with the generous default limits: 100 000 levels stop at 257. var deep = string.Concat(Enumerable.Repeat("", 100_000)) + string.Concat(Enumerable.Repeat("", 100_000)); var act = () => Digest("application/xml", deep); act.Should().Throw().WithMessage("*MaxDepth*") .WithInnerException(); } [Fact] public void XmlAttachmentWithinTheDefaultLimits_IsCanonicalizedAsBefore() { // A deep but ordinary payload (60 levels, more than any envelope) keeps its digest path. Deeper than about 65 // levels the patched System.Security.Cryptography.Xml (10.0.13) refuses to canonicalize on its own. var deep = string.Concat(Enumerable.Repeat("", 60)) + string.Concat(Enumerable.Repeat("", 60)); Digest("application/xml", deep).Should().HaveCount(32); } } Path: redb-route/tests/redb.Route.Tests.As4/As4ConsumerTests.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/tests/redb.Route.Tests.As4/As4ConsumerTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Xml; using redb.Route.Abstractions; using redb.Route.As4; using redb.Route.As4.Messaging; using redb.Route.As4.Mime; using redb.Route.As4.Security; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; using As4Dsl = redb.Route.As4.Fluent.As4; namespace redb.Route.Tests.As4; /// /// The AS4 receiver on the shared Kestrel host. Loopback (our producer → our consumer) proves the whole /// round trip and the receipt; raw requests prove every refusal answers with its ebMS code, the partner never /// reads the text of one of our exceptions, and a failed unit of work — rollback-only included — is never /// acknowledged with a receipt. /// public class As4ConsumerTests { private static readonly X509Certificate2 NodeA = As4TestMessages.KeyPair("CN=a.as4.test"); private static readonly X509Certificate2 NodeB = As4TestMessages.KeyPair("CN=b.as4.test"); private static readonly X509Certificate2 Stranger = As4TestMessages.KeyPair("CN=stranger.as4.test"); private const string Payload = "42"; // ── Start ──────────────────────────────────────────────────────────────── [Fact] public async Task ListenerThatFailedToStart_LeavesNothingBehind_SoAManualStartRegistersOnce() { var calls = 0; var port = global::redb.Route.Tests.Shared.TestPorts.Next(); // No background retry: the route is started by hand once the port is free. var engine = new redb.Route.Configuration.RouteEngineOptions { ShutdownTimeout = TimeSpan.FromSeconds(2), ConsumerStartRetry = new redb.Route.Configuration.ConsumerStartRetryOptions { Enabled = false }, }; var squatter = new System.Net.Sockets.TcpListener(IPAddress.Loopback, port); squatter.Start(); Stand stand; try { stand = await Stand.StartAsync(_ => { Interlocked.Increment(ref calls); return Task.CompletedTask; }, engine: engine, port: port); stand.Status.Should().Be(RouteStatus.Errored, "the port is taken"); } finally { squatter.Stop(); } await using (stand) { await stand.StartRoute(); stand.Status.Should().Be(RouteStatus.Started); var exchange = NewExchange(); await stand.Send(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); Volatile.Read(ref calls).Should().Be(1, "one registration of the route, not one per start"); await stand.Stop(); var stopped = () => stand.PostBytes("text/plain", [1]); await stopped.Should().ThrowAsync("the stopped receiver gives the port back"); } } // ── Loopback ───────────────────────────────────────────────────────────── [Fact] public async Task Loopback_DeliversThePayloadAndHeaders_AndTheSenderGetsAVerifiedReceipt() { IExchange? received = null; await using var stand = await Stand.StartAsync(e => { received = e; return Task.CompletedTask; }); var exchange = NewExchange(); await stand.Send(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); received.Should().NotBeNull(); Encoding.UTF8.GetString((byte[])received!.In.Body!).Should().Be(Payload); received.In.ContentType.Should().Be("text/xml"); received.In.GetHeader(As4Headers.Partner).Should().Be("a"); received.In.GetHeader(As4Headers.MessageId).Should().Be(exchange.In.GetHeader(As4Headers.MessageId)); received.In.GetHeader(As4Headers.FromPartyId).Should().Be("urn:redb:a"); received.In.GetHeader(As4Headers.Action).Should().Be("Submit"); received.In.GetHeader(As4Headers.OriginalSender).Should().Be("C1"); received.In.GetHeader(As4Headers.SignatureValid).Should().BeTrue(); received.In.GetHeader(As4Headers.SignerThumbprint).Should().Be(NodeA.Thumbprint); } [Fact] public async Task Principal_IsTheEnvelopeSigner_WithTheAgreementItAuthenticated() { // As camel-cxf with WSS4J: the principal comes from the signature. System.Security.Claims.ClaimsPrincipal? principal = null; await using var stand = await Stand.StartAsync(e => { principal = ExchangePrincipal.Get(e); return Task.CompletedTask; }); await stand.Send(NewExchange()); var identity = principal!.Identities.First(); identity.AuthenticationType.Should().Be(As4AuthenticationTypes.Signature); identity.IsAuthenticated.Should().BeTrue(); identity.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)!.Value.Should().Be("a"); identity.FindFirst(System.Security.Claims.ClaimTypes.Thumbprint)!.Value.Should().Be(NodeA.Thumbprint); identity.FindFirst(System.Security.Claims.ClaimTypes.Name)!.Value.Should().Be(NodeA.Subject); principal.Identities.Should().NotContain(i => i.AuthenticationType == As4AuthenticationTypes.ClientCertificate, "no TLS here"); } [Fact] public async Task RouteFailure_IsAnsweredWithOther_WithoutTheExceptionText() { await using var stand = await Stand.StartAsync(_ => throw new InvalidOperationException(@"cannot open C:\secret\ledger.db")); var act = () => stand.Send(NewExchange()); var error = (await act.Should().ThrowAsync()).Which; error.ErrorCode.Should().Be("EBMS:0004"); error.Description.Should().NotContain("secret").And.NotContain("ledger"); error.ErrorDetail.Should().StartWith("ref: "); } [Fact] public async Task RollbackOnly_IsNotAcknowledged() { await using var stand = await Stand.StartAsync(e => { e.MarkRollbackOnly(); return Task.CompletedTask; }); var act = () => stand.Send(NewExchange()); (await act.Should().ThrowAsync()).Which.ErrorCode.Should().Be("EBMS:0004"); } [Fact] public async Task MalformedRequest_IsAnsweredWithValueInconsistent_AndItsOwnText() { await using var stand = await Stand.StartAsync(_ => throw new MalformedRequestException("element 'total' is not a number")); var act = () => stand.Send(NewExchange()); var error = (await act.Should().ThrowAsync()).Which; error.ErrorCode.Should().Be("EBMS:0003"); error.Description.Should().Be("element 'total' is not a number"); } [Fact] public async Task UnknownSender_IsValueNotRecognized() { await using var stand = await Stand.StartAsync(_ => Task.CompletedTask); var act = () => stand.Send(NewExchange(), from: "c"); (await act.Should().ThrowAsync()).Which.ErrorCode.Should().Be("EBMS:0001"); } // ── Duplicate detection ────────────────────────────────────────────────── [Fact] public async Task Resend_OfADeliveredMessage_GetsAReceiptAgain_AndIsNotDeliveredTwice() { var deliveries = 0; var duplicates = new InMemoryIdempotentRepository(); await using var stand = await Stand.StartAsync(_ => { Interlocked.Increment(ref deliveries); return Task.CompletedTask; }, duplicates); var (message, messageId) = SecuredRawMessage(); var first = await stand.PostRaw(message); var second = await stand.PostRaw(message); first.Should().Be((HttpStatusCode.OK, (string?)null, true)); second.Should().Be((HttpStatusCode.OK, (string?)null, true)); deliveries.Should().Be(1); (await duplicates.Contains(messageId)).Should().BeTrue(); } [Theory] [InlineData(false)] [InlineData(true)] public async Task Resend_OfADeliveredMessage_GetsTheVeryReceiptOfTheOriginal(bool payloadList) { // AS4_CP_TA63: the same receipt, not a new one for the same message (its own id, time and signature). await using var stand = await Stand.StartAsync(_ => Task.CompletedTask, payloadList: payloadList); var (message, _) = SecuredRawMessage(); using var first = await stand.PostBytes(message.ContentType, message.Body); using var second = await stand.PostBytes(message.ContentType, message.Body); second.Content.Headers.ContentType!.ToString().Should().Be(first.Content.Headers.ContentType!.ToString()); (await second.Content.ReadAsByteArrayAsync()).Should().Equal(await first.Content.ReadAsByteArrayAsync()); } [Fact] public async Task Resend_UnderAnotherAgreementOfTheSameParty_GetsTheReceiptOfTheOriginal() { // AS4_CP_TA63: the test driver resends the message id under another action, so another agreement with the same // party matches it. It is still the same message of the same sender. await using var stand = await Stand.StartAsync(_ => Task.CompletedTask, receiver: node => { var first = node.Partners.Single(); node.Partners.Add(new As4Partner { Name = first.Name + "-other", PartyId = first.PartyId, Service = first.Service, Action = "Other", PartnerSigningCertificates = { first.PartnerSigningCertificates.Single() }, PartnerEncryptionCertificate = first.PartnerEncryptionCertificate, }); }); var messageId = Guid.NewGuid().ToString("N") + "@a.example"; var (original, _) = SecuredRawMessage(messageId, action: "Submit"); var (resend, _) = SecuredRawMessage(messageId, action: "Other"); original.Body.Should().NotEqual(resend.Body, "the resend is another transmission"); using var first = await stand.PostBytes(original.ContentType, original.Body); using var second = await stand.PostBytes(resend.ContentType, resend.Body); (await second.Content.ReadAsByteArrayAsync()).Should().Equal(await first.Content.ReadAsByteArrayAsync()); } [Fact] public async Task Resend_WhileTheFirstCopyIsStillInTheRoute_IsRefusedAsBusy_AndDeliveredAfterTheFirstFails() { // The first copy fails after the resend arrived: a receipt for the resend would have told the sender the message // arrived, and the release of the first claim would have lost it. Refused with 503 and no ebMS signal, the sender // resends (Domibus does, at its P-Mode retry interval). var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var attempts = 0; var deliveries = 0; await using var stand = await Stand.StartAsync(async _ => { if (Interlocked.Increment(ref attempts) == 1) { entered.TrySetResult(); await release.Task; throw new InvalidOperationException("the route is down"); } Interlocked.Increment(ref deliveries); }); var (message, _) = SecuredRawMessage(); var first = stand.PostRaw(message); await entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); using (var resend = await stand.PostBytes(message.ContentType, message.Body)) { resend.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); resend.Headers.RetryAfter!.Delta.Should().Be(TimeSpan.FromSeconds(1), "retryAfterSeconds, default 1"); (await resend.Content.ReadAsByteArrayAsync()).Should().BeEmpty("no ebMS signal: nothing was decided about the message"); } release.SetResult(); (await first).ErrorCode.Should().Be("EBMS:0004"); (await stand.PostRaw(message)).Receipt.Should().BeTrue("the failed copy released its claim, so the resend is delivered"); deliveries.Should().Be(1); } [Fact] public async Task Resend_WhileTheFirstCopyIsStillInTheRoute_GetsTheReceiptOfTheOriginal_OnceItIsConfirmed() { // AS4_CP_TA63 still holds for the resend that comes after the refusal: the very receipt of the original. var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var deliveries = 0; await using var stand = await Stand.StartAsync(async _ => { Interlocked.Increment(ref deliveries); entered.TrySetResult(); await release.Task; }); var (message, _) = SecuredRawMessage(); var first = stand.PostBytes(message.ContentType, message.Body); await entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); using (var busy = await stand.PostBytes(message.ContentType, message.Body)) busy.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); release.SetResult(); using var original = await first; using var later = await stand.PostBytes(message.ContentType, message.Body); original.StatusCode.Should().Be(HttpStatusCode.OK); (await later.Content.ReadAsByteArrayAsync()).Should().Equal(await original.Content.ReadAsByteArrayAsync()); deliveries.Should().Be(1); } [Fact] public async Task AClaimNeverConfirmed_OlderThanInFlightClaimTimeout_IsTakenOver_AndTheMessageDelivered() { // A node stopped between the claim and its confirmation: the claim stays, unconfirmed. var duplicates = new InMemoryIdempotentRepository(); var (message, messageId) = SecuredRawMessage(); (await duplicates.Add(messageId)).Should().BeTrue(); var deliveries = 0; await using var stand = await Stand.StartAsync(_ => { Interlocked.Increment(ref deliveries); return Task.CompletedTask; }, duplicates, inFlightClaimTimeout: 50); await Task.Delay(200); (await stand.PostRaw(message)).Receipt.Should().BeTrue(); deliveries.Should().Be(1); (await duplicates.Claim(messageId, null)).Should().Be(IdempotentClaim.Confirmed); } [Fact] public async Task AClaimNeverConfirmed_YoungerThanInFlightClaimTimeout_IsRefusedAsBusy() { var duplicates = new InMemoryIdempotentRepository(); var (message, messageId) = SecuredRawMessage(); (await duplicates.Add(messageId)).Should().BeTrue(); var deliveries = 0; await using var stand = await Stand.StartAsync(_ => { Interlocked.Increment(ref deliveries); return Task.CompletedTask; }, duplicates); using var response = await stand.PostBytes(message.ContentType, message.Body); response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); deliveries.Should().Be(0); } [Fact] public async Task Receipts_GoToTheNodesReceiptStore() { var store = new InMemoryClaimCheckRepository(); await using var stand = await Stand.StartAsync(_ => Task.CompletedTask, receiver: node => node.ReceiptStore = store); var (message, _) = SecuredRawMessage(); using var first = await stand.PostBytes(message.ContentType, message.Body); using var second = await stand.PostBytes(message.ContentType, message.Body); store.Count.Should().Be(1); (await second.Content.ReadAsByteArrayAsync()).Should().Equal(await first.Content.ReadAsByteArrayAsync()); } [Fact] public async Task ReceiptStoreFailure_StillAnswersEveryMessageWithAReceipt() { var store = Substitute.For(); store.Store(Arg.Any(), Arg.Any>(), Arg.Any(), Arg.Any()) .Returns(Task.FromException(new InvalidOperationException("store down"))); store.Retrieve(Arg.Any(), Arg.Any()) .Returns(Task.FromException(new InvalidOperationException("store down"))); var deliveries = 0; await using var stand = await Stand.StartAsync(_ => { Interlocked.Increment(ref deliveries); return Task.CompletedTask; }, receiver: node => node.ReceiptStore = store); var (message, _) = SecuredRawMessage(); var first = await stand.PostRaw(message); var second = await stand.PostRaw(message); first.Should().Be((HttpStatusCode.OK, (string?)null, true)); second.Should().Be((HttpStatusCode.OK, (string?)null, true)); deliveries.Should().Be(1); } [Fact] public async Task Resend_AfterARouteFailure_IsDelivered() { var attempts = 0; await using var stand = await Stand.StartAsync(_ => Interlocked.Increment(ref attempts) == 1 ? throw new InvalidOperationException("first attempt fails") : Task.CompletedTask); var (message, _) = SecuredRawMessage(); var first = await stand.PostRaw(message); var second = await stand.PostRaw(message); first.ErrorCode.Should().Be("EBMS:0004"); second.Should().Be((HttpStatusCode.OK, (string?)null, true)); attempts.Should().Be(2); } [Fact] public async Task Resend_AfterTheRequestWasAbortedMidRoute_IsDelivered() { var attempts = 0; await using var stand = await Stand.StartAsync(_ => Interlocked.Increment(ref attempts) == 1 ? throw new OperationCanceledException("request aborted") : Task.CompletedTask); var (message, _) = SecuredRawMessage(); using (await stand.PostBytes(message.ContentType, message.Body)) { } var second = await stand.PostRaw(message); second.Should().Be((HttpStatusCode.OK, (string?)null, true)); attempts.Should().Be(2); } [Fact] public async Task Claim_IsTakenWithoutTheRequestsCancellation() { // A claim cut by the sender's disconnect could be written and then reported as failed, leaving the id marked for // a message the route never saw — its resend would get a receipt. The claim is a short state write, taken // uncancelled, as Confirm and Release are. var duplicates = Substitute.For(); duplicates.Lease(Arg.Any(), Arg.Any(), Arg.Any()).Returns(new IdempotentLease(IdempotentClaim.Claimed, "c1")); duplicates.Confirm(Arg.Any(), Arg.Any(), Arg.Any()).Returns(true); await using var stand = await Stand.StartAsync(_ => Task.CompletedTask, duplicates); (await stand.PostRaw(SecuredRawMessage().Message)).Receipt.Should().BeTrue(); await duplicates.Received(1).Lease(Arg.Any(), Arg.Any(), Arg.Is(t => !t.CanBeCanceled)); } [Fact] public async Task DuplicateStoreFailure_IsOther_AndNeverReachesTheRoute() { var reached = false; var duplicates = Substitute.For(); duplicates.Lease(Arg.Any(), Arg.Any(), Arg.Any()) .Returns(Task.FromException(new InvalidOperationException(@"cannot reach C:\secret\dedup.db"))); await using var stand = await Stand.StartAsync(_ => { reached = true; return Task.CompletedTask; }, duplicates); var (message, _) = SecuredRawMessage(); var (status, errorCode, receipt) = await stand.PostRaw(message); status.Should().Be(HttpStatusCode.OK); errorCode.Should().Be("EBMS:0004"); receipt.Should().BeFalse(); reached.Should().BeFalse(); } // ── Streams ────────────────────────────────────────────────────────────── [Fact] public async Task StreamBody_HandsTheVerifiedPayloadAsAStream_ClosedWhenTheExchangeEnds() { Stream? body = null; string? read = null; await using var stand = await Stand.StartAsync(e => { body = e.In.Body as Stream; read = new StreamReader(body!, leaveOpen: true).ReadToEnd(); return Task.CompletedTask; }, streamBody: true); var (status, errorCode, receipt) = await stand.PostRaw(SecuredRawMessage().Message); (status, errorCode, receipt).Should().Be((HttpStatusCode.OK, (string?)null, true)); read.Should().Be(Payload); body!.CanRead.Should().BeFalse("Exchange.DisposeAsync closes a Stream body"); } [Fact] public async Task LargePayload_IsSpooledToDisk_NotHeldInMemory() { var large = new string('x', 300_000); bool? spooled = null; string? read = null; await using var stand = await Stand.StartAsync(e => { var cache = (StreamCache)e.In.Body!; spooled = cache.IsSpooled; read = new StreamReader(cache, leaveOpen: true).ReadToEnd(); return Task.CompletedTask; }, streamBody: true, spool: new redb.Route.Configuration.StreamCacheOptions { SpoolThreshold = 4096 }); var (_, errorCode, receipt) = await stand.PostRaw(SecuredMessage(Encoding.UTF8.GetBytes(large)).Message); errorCode.Should().BeNull(); receipt.Should().BeTrue(); spooled.Should().BeTrue(); read.Should().Be(large); } [Fact] public async Task SpoolThreshold_OfTheEngineOptions_ReachesTheReceiver() { bool? spooled = null; await using var stand = await Stand.StartAsync(e => { spooled = ((StreamCache)e.In.Body!).IsSpooled; return Task.CompletedTask; }, streamBody: true, engine: new redb.Route.Configuration.RouteEngineOptions { StreamCaching = new redb.Route.Configuration.StreamCacheOptions { SpoolThreshold = 4096 }, }); var (_, errorCode, _) = await stand.PostRaw(SecuredMessage(Encoding.UTF8.GetBytes(new string('y', 50_000))).Message); errorCode.Should().BeNull(); spooled.Should().BeTrue("50 KB is past the engine's 4 KB threshold, below the 128 KB default"); } [Fact] public async Task SeveralPayloads_AreAs4PayloadStreams_ReleasedWithTheExchange() { IReadOnlyList? payloads = null; List? contents = null; await using var stand = await Stand.StartAsync(e => { payloads = (IReadOnlyList)e.In.Body!; contents = payloads.Select(p => new StreamReader(p.Content, leaveOpen: true).ReadToEnd()).ToList(); return Task.CompletedTask; }); var (_, errorCode, receipt) = await stand.PostRaw(SecuredMessage(Encoding.UTF8.GetBytes(""), Encoding.UTF8.GetBytes("")).Message); errorCode.Should().BeNull(); receipt.Should().BeTrue(); contents.Should().Equal("", ""); payloads!.Should().OnlyContain(p => p.ContentType == "text/xml" && !p.Content.CanRead); } [Fact] public async Task Loopback_AListOfPayloads_ArrivesInOrder_WithContentIdsAndPartProperties() { List<(string? Id, string Type, string Text, string? CharacterSet)>? received = null; await using var stand = await Stand.StartAsync(e => { received = ((IReadOnlyList)e.In.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 Task.CompletedTask; }); var exchange = NewExchange(); exchange.In.Body = new List { new("invoice@a.example", "application/xml", new MemoryStream(Encoding.UTF8.GetBytes("")), new Dictionary { ["CharacterSet"] = "utf-8" }), new(null, "application/octet-stream", new MemoryStream(Encoding.UTF8.GetBytes("scan-1")), new Dictionary()), new("scan2@a.example", "application/octet-stream", new MemoryStream(Encoding.UTF8.GetBytes("scan-2")), new Dictionary()), }; await stand.Send(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); received!.Select(p => p.Text).Should().Equal("", "scan-1", "scan-2"); received!.Select(p => p.Type).Should().Equal("application/xml", "application/octet-stream", "application/octet-stream"); received![0].Id.Should().Be("invoice@a.example"); received[0].CharacterSet.Should().Be("utf-8"); received[1].Id.Should().EndWith("@a.example"); received[2].Id.Should().Be("scan2@a.example"); } [Fact] public async Task PayloadList_HandsASinglePayloadAsAList_WithItsContentId() { IReadOnlyList? payloads = null; string? text = null; string? contentType = "unset"; await using var stand = await Stand.StartAsync(e => { payloads = (IReadOnlyList)e.In.Body!; text = new StreamReader(payloads[0].Content, leaveOpen: true).ReadToEnd(); contentType = e.In.ContentType; return Task.CompletedTask; }, payloadList: true); var (_, errorCode, receipt) = await stand.PostRaw(SecuredMessage(Encoding.UTF8.GetBytes(Payload)).Message); errorCode.Should().BeNull(); receipt.Should().BeTrue(); payloads.Should().ContainSingle(); payloads![0].ContentId.Should().Be("p0@a.example"); payloads[0].ContentType.Should().Be("text/xml"); text.Should().Be(Payload); contentType.Should().BeNull(); } [Fact] public async Task Loopback_AnEmptyPayloadList_IsAMessageWithoutPayloads_AndIsAcknowledged() { object? body = "unset"; string? action = null; await using var stand = await Stand.StartAsync(e => { body = e.In.Body; action = e.In.GetHeader(As4Headers.Action); return Task.CompletedTask; }); var exchange = NewExchange(); exchange.In.Body = Array.Empty(); await stand.Send(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); body.Should().BeNull(); action.Should().Be("Submit"); } [Fact] public async Task PayloadList_OfAMessageWithoutPayloads_IsAnEmptyList() { object? body = null; await using var stand = await Stand.StartAsync(e => { body = e.In.Body; return Task.CompletedTask; }, payloadList: true); var exchange = NewExchange(); exchange.In.Body = Array.Empty(); await stand.Send(exchange); body.Should().BeAssignableTo>().Which.Should().BeEmpty(); } [Fact] public async Task WithoutFourCornerProperties_IsDelivered_WhenTheAgreementDoesNotRequireThem() { IExchange? received = null; await using var stand = await Stand.StartAsync(e => { received = e; return Task.CompletedTask; }, agreement: p => p.RequireFourCornerProperties = false); var exchange = new Exchange(new Message(Payload) { ContentType = "text/xml" }); await stand.Send(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); received.Should().NotBeNull(); received!.In.Headers.Should().NotContainKey(As4Headers.OriginalSender); } [Fact] public async Task Loopback_APropertyType_TravelsWithItsProperty() { IExchange? received = null; await using var stand = await Stand.StartAsync(e => { received = e; return Task.CompletedTask; }); var exchange = NewExchange(); exchange.In.Headers[As4Headers.PropertyTypePrefix + "originalSender"] = "urn:oasis:names:tc:ebcore:partyid-type:unregistered"; await stand.Send(exchange); received!.In.GetHeader(As4Headers.OriginalSender).Should().Be("C1"); received.In.GetHeader(As4Headers.PropertyTypePrefix + "originalSender").Should().Be("urn:oasis:names:tc:ebcore:partyid-type:unregistered"); received.In.Headers.Should().NotContainKey(As4Headers.PropertyTypePrefix + "finalRecipient"); } // ── Raw requests ───────────────────────────────────────────────────────── [Fact] public async Task UnsignedMessage_IsProcessingModeMismatch_AndNeverReachesTheRoute() { // EBMS:0010, as the eDelivery conformance test driver expects (AS4_CP_TA80). var reached = false; await using var stand = await Stand.StartAsync(_ => { reached = true; return Task.CompletedTask; }); var message = RawMessage(); var (status, errorCode, _) = await stand.PostRaw(message.Write()); status.Should().Be(HttpStatusCode.OK); errorCode.Should().Be("EBMS:0010"); reached.Should().BeFalse(); } [Fact] public async Task WithoutFourCornerProperties_IsProcessingModeMismatch_AndNeverReachesTheRoute() { var reached = false; await using var stand = await Stand.StartAsync(_ => { reached = true; return Task.CompletedTask; }); var (status, errorCode, receipt) = await stand.PostRaw(SecuredMessage(fourCorner: false, Encoding.UTF8.GetBytes(Payload)).Message); status.Should().Be(HttpStatusCode.OK); errorCode.Should().Be("EBMS:0010"); receipt.Should().BeFalse(); reached.Should().BeFalse(); } [Theory] [InlineData("From")] [InlineData("To")] public async Task MoreThanOnePartyIdOnASide_IsProcessingModeMismatch(string side) { // eDelivery AS4 1.16 REQUIRES one eb:PartyId per side; phase4 and Holodeck refuse more with EBMS:0010. var reached = false; await using var stand = await Stand.StartAsync(_ => { reached = true; return Task.CompletedTask; }); var message = RawMessage(); var party = (XmlElement)message.Envelope.GetElementsByTagName(side, EbmsNamespaces.Eb)[0]!; var extra = message.Envelope.CreateElement("eb", "PartyId", EbmsNamespaces.Eb); extra.InnerText = "urn:redb:second"; party.InsertBefore(extra, party.GetElementsByTagName("Role", EbmsNamespaces.Eb)[0]); As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow); As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken); (await stand.PostRaw(message.Write())).ErrorCode.Should().Be("EBMS:0010"); reached.Should().BeFalse(); } [Fact] public async Task PullRequest_IsProcessingModeMismatch_AsDomibusAnswersWithoutAPullProcess() { // Domibus (PullRequestLegConfigurationExtractor): no pull process for the mpc → EBMS:0010. Pull is out of scope. await using var stand = await Stand.StartAsync(_ => Task.CompletedTask); var pull = new SignalMessage(new MessageInfo(DateTimeOffset.UtcNow, Guid.NewGuid().ToString("N") + "@a.example", null), null, [], EbmsNamespaces.DefaultMpc); var body = Encoding.UTF8.GetBytes(MessagingWriter.CreateEnvelope(pull).OuterXml); var response = await stand.PostBytes("application/soap+xml", body); var answer = SwaMessage.Read(response.Content.Headers.ContentType!.ToString(), await response.Content.ReadAsByteArrayAsync(), 1024 * 1024); MessagingReader.Read(answer.Envelope).SignalMessages.SelectMany(s => s.Errors).Single().ErrorCode.Should().Be("EBMS:0010"); } [Theory] [InlineData("urn:example:other-mpc", "EBMS:0001")] [InlineData(EbmsNamespaces.DefaultMpc, null)] public async Task Mpc_OtherThanTheDefault_IsValueNotRecognized_AsDomibusMatchesItToTheLeg(string mpc, string? errorCode) { // Domibus (CachingPModeProvider.checkMpcMismatch): an mpc the leg does not name → EBMS:0001; the default passes. await using var stand = await Stand.StartAsync(_ => Task.CompletedTask); var message = RawMessage(); ((XmlElement)message.Envelope.GetElementsByTagName("UserMessage", EbmsNamespaces.Eb)[0]!).SetAttribute("mpc", mpc); As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow); As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken); var (_, code, receipt) = await stand.PostRaw(message.Write()); code.Should().Be(errorCode); receipt.Should().Be(errorCode is null); } [Fact] public async Task TamperedAfterSigning_IsFailedAuthentication() { await using var stand = await Stand.StartAsync(_ => Task.CompletedTask); var message = RawMessage(); As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow); As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken); ((XmlElement)message.Envelope.GetElementsByTagName("ConversationId", EbmsNamespaces.Eb)[0]!).InnerText = "someone-else"; (await stand.PostRaw(message.Write())).ErrorCode.Should().Be("EBMS:0101"); } [Fact] public async Task EncryptedForSomeoneElse_IsFailedDecryption() { await using var stand = await Stand.StartAsync(_ => Task.CompletedTask); var message = RawMessage(); As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow); As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(Stranger), As4KeyReference.BinarySecurityToken); (await stand.PostRaw(message.Write())).ErrorCode.Should().Be("EBMS:0102"); } [Fact] public async Task EnvelopeWithADoctype_IsASenderSoapFault() { await using var stand = await Stand.StartAsync(_ => Task.CompletedTask); var body = Encoding.UTF8.GetBytes("]>"); var response = await stand.PostBytes("application/soap+xml", body); response.StatusCode.Should().Be(HttpStatusCode.BadRequest); (await response.Content.ReadAsStringAsync()).Should().Contain("soapenv:Sender"); } [Theory] [InlineData("Body")] [InlineData("Header")] public async Task EnvelopeWithoutBodyOrHeader_IsASenderSoapFault(string missing) { // Not a SOAP 1.2 envelope an AS4 message can be (SOAP 1.2 Part 1 §5): refused as the DTD is, before ebMS. var reached = false; await using var stand = await Stand.StartAsync(_ => { reached = true; return Task.CompletedTask; }); var message = RawMessage(); As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow); As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken); var element = message.Envelope.GetElementsByTagName(missing, EbmsNamespaces.Soap12)[0]!; element.ParentNode!.RemoveChild(element); var (contentType, bytes) = message.Write(); var response = await stand.PostBytes(contentType, bytes); response.StatusCode.Should().Be(HttpStatusCode.BadRequest); (await response.Content.ReadAsStringAsync()).Should().Contain("soapenv:Sender"); reached.Should().BeFalse(); } [Fact] public async Task TwoSecurityHeaders_IsPolicyNoncompliance_NotAServerError() { // WS-Security 1.1 §6.1: no two wsse:Security headers for one role. An ebMS error, not an unhandled 500. await using var stand = await Stand.StartAsync(_ => Task.CompletedTask); var message = RawMessage(); As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow); As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken); var header = (XmlElement)message.Envelope.GetElementsByTagName("Header", EbmsNamespaces.Soap12)[0]!; header.AppendChild(message.Envelope.CreateElement("wsse", "Security", WsSecurityNames.Wsse)); var (status, errorCode, receipt) = await stand.PostRaw(message.Write()); status.Should().Be(HttpStatusCode.OK); errorCode.Should().Be("EBMS:0103"); receipt.Should().BeFalse(); } [Fact] public async Task UnexpectedFailure_IsAnsweredWithOther_AndCountedAsAnError() { // Anything the receiver did not foresee (here the spool directory is gone) is still an ebMS answer with a // reference, logged and counted — never a bare 500 the partner cannot tell from a network failure (BR-4). var spool = new redb.Route.Configuration.StreamCacheOptions { SpoolThreshold = 16, TempDirectory = Path.Combine(Path.GetTempPath(), "redb-as4-" + Guid.NewGuid().ToString("N"), "gone") }; await using var stand = await Stand.StartAsync(_ => Task.CompletedTask, spool: spool); var (status, errorCode, receipt) = await stand.PostRaw(SecuredRawMessage().Message); status.Should().Be(HttpStatusCode.OK); errorCode.Should().Be("EBMS:0004"); receipt.Should().BeFalse(); stand.Errors.Should().Be(1); } [Theory] [InlineData("http://www.w3.org/2003/05/soap-envelope/role/none", false)] [InlineData("urn:example:gateway", false)] [InlineData("http://www.w3.org/2003/05/soap-envelope/role/next", true)] [InlineData("http://www.w3.org/2003/05/soap-envelope/role/ultimateReceiver", true)] public async Task MustUnderstandHeader_IsOursOnlyForTheRolesWePlay(string role, bool fault) { // SOAP 1.2 Part 1 §2.2: every node plays "next", the ultimate receiver also "ultimateReceiver"; a block for "none" // or another role is not addressed to us and must not fault. await using var stand = await Stand.StartAsync(_ => Task.CompletedTask); var message = RawMessage(); var header = (XmlElement)message.Envelope.GetElementsByTagName("Header", EbmsNamespaces.Soap12)[0]!; var block = message.Envelope.CreateElement("x", "Routing", "urn:example:routing"); foreach (var (name, value) in new[] { ("mustUnderstand", "true"), ("role", role) }) { var attribute = message.Envelope.CreateAttribute("soapenv", name, EbmsNamespaces.Soap12); attribute.Value = value; block.Attributes.Append(attribute); } header.AppendChild(block); As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow); As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken); var (contentType, bytes) = message.Write(); var response = await stand.PostBytes(contentType, bytes); if (fault) (await response.Content.ReadAsStringAsync()).Should().Contain("soapenv:MustUnderstand"); else response.StatusCode.Should().Be(HttpStatusCode.OK, "a block for another role is left alone"); } [Fact] public async Task UnknownMustUnderstandHeader_IsAMustUnderstandFault() { await using var stand = await Stand.StartAsync(_ => Task.CompletedTask); var message = RawMessage(); var header = (XmlElement)message.Envelope.GetElementsByTagName("Header", EbmsNamespaces.Soap12)[0]!; var block = message.Envelope.CreateElement("x", "Routing", "urn:example:routing"); var mustUnderstand = message.Envelope.CreateAttribute("soapenv", "mustUnderstand", EbmsNamespaces.Soap12); mustUnderstand.Value = "true"; block.Attributes.Append(mustUnderstand); header.AppendChild(block); var (contentType, bytes) = message.Write(); var response = await stand.PostBytes(contentType, bytes); response.StatusCode.Should().Be(HttpStatusCode.InternalServerError); (await response.Content.ReadAsStringAsync()).Should().Contain("soapenv:MustUnderstand"); } // ── eDelivery conformance assertions, as the test driver's simulated sender sends them ── // (Test Assertions Description v1.5, common profile; the id of the assertion is in each name.) [Fact] public async Task TA04_AnUncompressedPayload_IsAcknowledgedAndDelivered() { string? delivered = null; await using var stand = await Stand.StartAsync(e => { delivered = Encoding.UTF8.GetString((byte[])e.In.Body!); return Task.CompletedTask; }); var message = Conformance(Encoding.UTF8.GetBytes(Payload), uncompressedMimeType: "text/xml"); var (_, errorCode, receipt) = await stand.PostRaw(message); errorCode.Should().BeNull(); receipt.Should().BeTrue("a receiving MSH MUST NOT reject messages with payloads that are not compressed"); delivered.Should().Be(Payload); } [Fact] public async Task TA08_APayloadHyperlinkReference_IsAnsweredWithAnError_AndNotDelivered() { var reached = false; await using var stand = await Stand.StartAsync(_ => { reached = true; return Task.CompletedTask; }); // No attachment: the only eb:PartInfo points outside the message. var message = Conformance(content: null, beforeSigning: envelope => ((XmlElement)envelope.GetElementsByTagName("PartInfo", EbmsNamespaces.Eb)[0]!).SetAttribute("href", "http://example.com/invoice.xml")); var (status, errorCode, receipt) = await stand.PostRaw(message); status.Should().Be(HttpStatusCode.OK); errorCode.Should().Be("EBMS:0011"); receipt.Should().BeFalse(); reached.Should().BeFalse(); } [Fact] public async Task TA20_TA44_MessageAndPartProperties_WithAndWithoutAType_AreAcknowledged() { IExchange? received = null; await using var stand = await Stand.StartAsync(e => { received = e; return Task.CompletedTask; }); var message = Conformance(As4TestMessages.Gzip(Encoding.UTF8.GetBytes(Payload)), beforeSigning: envelope => { // One property with a type and one without, among the message properties and among the part properties. ((XmlElement)envelope.GetElementsByTagName("MessageProperties", EbmsNamespaces.Eb)[0]!.FirstChild!).SetAttribute("type", "urn:example:party-type"); var partProperties = (XmlElement)envelope.GetElementsByTagName("PartProperties", EbmsNamespaces.Eb)[0]!; ((XmlElement)partProperties.FirstChild!).SetAttribute("type", "urn:example:media-type"); }); var (_, errorCode, receipt) = await stand.PostRaw(message); errorCode.Should().BeNull(); receipt.Should().BeTrue(); received!.In.GetHeader(As4Headers.PropertyTypePrefix + "originalSender").Should().Be("urn:example:party-type"); received.In.Headers.Should().NotContainKey(As4Headers.PropertyTypePrefix + "finalRecipient"); } [Theory] [InlineData("!utf*", "EBMS:0003")] [InlineData("8bit", "EBMS:0003")] // an encoding name starts with a letter [InlineData("", "EBMS:0003")] [InlineData("UTF-16", null)] [InlineData("ISO-8859-1", null)] public async Task TA29_ACharacterSetThatIsNotAnEncodingName_IsAnsweredWithAnError(string characterSet, string? expectedError) { var reached = false; await using var stand = await Stand.StartAsync(_ => { reached = true; return Task.CompletedTask; }); var message = Conformance(As4TestMessages.Gzip(Encoding.UTF8.GetBytes(Payload)), beforeSigning: envelope => { var partProperties = (XmlElement)envelope.GetElementsByTagName("PartProperties", EbmsNamespaces.Eb)[0]!; var property = envelope.CreateElement("eb", "Property", EbmsNamespaces.Eb); property.SetAttribute("name", "CharacterSet"); property.InnerText = characterSet; partProperties.AppendChild(property); }); var (_, errorCode, receipt) = await stand.PostRaw(message); errorCode.Should().Be(expectedError); receipt.Should().Be(expectedError is null); reached.Should().Be(expectedError is null); } [Fact] public async Task TA30_ADamagedCompressedPayload_IsDecompressionFailure() { var reached = false; await using var stand = await Stand.StartAsync(_ => { reached = true; return Task.CompletedTask; }); // Declared gzip, correctly signed and encrypted, but the bytes do not inflate. var damaged = As4TestMessages.Gzip(Encoding.UTF8.GetBytes(Payload)); Array.Fill(damaged, 0x5A, 10, damaged.Length - 10); var (status, errorCode, receipt) = await stand.PostRaw(Conformance(damaged)); status.Should().Be(HttpStatusCode.OK); errorCode.Should().Be("EBMS:0303"); receipt.Should().BeFalse(); reached.Should().BeFalse(); } [Fact] public async Task TA35_APayloadSignedBeforeItWasCompressed_IsAnsweredWithAnError() { var reached = false; await using var stand = await Stand.StartAsync(_ => { reached = true; return Task.CompletedTask; }); // Signed over the plain bytes, compressed afterwards: the digest in the signature is not the one of the part. var plain = Encoding.UTF8.GetBytes(Payload); var message = Conformance(plain, afterSigning: part => part.Replace(new MemoryStream(As4TestMessages.Gzip(plain), writable: false))); var (_, errorCode, receipt) = await stand.PostRaw(message); errorCode.Should().Be("EBMS:0101"); receipt.Should().BeFalse(); reached.Should().BeFalse(); } [Fact] public async Task TA37_APayloadEncryptedBeforeItWasCompressed_IsAnsweredWithAnError() { var reached = false; await using var stand = await Stand.StartAsync(_ => { reached = true; return Task.CompletedTask; }); // Compressed after encryption: what arrives under the content id is gzip, not the ciphertext. var message = Conformance(As4TestMessages.Gzip(Encoding.UTF8.GetBytes(Payload)), afterEncryption: part => part.Replace(new MemoryStream(As4TestMessages.Gzip(part.ToArray()), writable: false))); var (_, errorCode, receipt) = await stand.PostRaw(message); errorCode.Should().NotBeNull(); errorCode.Should().BeOneOf("EBMS:0102", "EBMS:0101"); receipt.Should().BeFalse(); reached.Should().BeFalse(); } [Fact] public async Task EmptyBodyNotReferencedInSignature_IsAnsweredWithAnError_AndNotDelivered() { // The conformance test of that name (testing service 2026.06). The AS4 profile has the sender sign the body // (§5.1.4, §5.1.5); answered as Domibus, the reference implementation, answers it: EBMS:0103, its policy lists // sp:Body among the signed parts (As4HarmonyLiveTests). var reached = false; await using var stand = await Stand.StartAsync(_ => { reached = true; return Task.CompletedTask; }); var (_, errorCode, receipt) = await stand.PostRaw(Conformance(As4TestMessages.Gzip(Encoding.UTF8.GetBytes(Payload)), coverBody: false)); errorCode.Should().Be("EBMS:0103"); receipt.Should().BeFalse(); reached.Should().BeFalse(); } [Theory] // Testing service 2026.06, "encryption algorithm" and "signature algorithm": only the profile's own are accepted. [InlineData("payload encryption", "http://www.w3.org/2009/xmlenc11#aes256-gcm", "EBMS:0102")] [InlineData("payload encryption", "http://www.w3.org/2001/04/xmlenc#aes128-cbc", "EBMS:0102")] [InlineData("key transport", "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p", "EBMS:0102")] [InlineData("key transport", "http://www.w3.org/2001/04/xmlenc#rsa-1_5", "EBMS:0102")] [InlineData("signature", "http://www.w3.org/2000/09/xmldsig#rsa-sha1", "EBMS:0101")] [InlineData("signature", "http://www.w3.org/2001/04/xmldsig-more#rsa-sha512", "EBMS:0101")] [InlineData("digest", "http://www.w3.org/2000/09/xmldsig#sha1", "EBMS:0101")] public async Task AnAlgorithmOutsideTheProfile_IsAnsweredWithAnError_AndNotDelivered(string what, string algorithm, string expectedError) { var reached = false; await using var stand = await Stand.StartAsync(_ => { reached = true; return Task.CompletedTask; }); var message = Conformance(As4TestMessages.Gzip(Encoding.UTF8.GetBytes(Payload)), afterSecuring: envelope => { XmlElement First(string localName, string ns, XmlElement? within = null) => (XmlElement)(within ?? envelope.DocumentElement!).GetElementsByTagName(localName, ns)[0]!; var target = what switch { "payload encryption" => First("EncryptionMethod", WsSecurityNames.Xenc, First("EncryptedData", WsSecurityNames.Xenc)), "key transport" => First("EncryptionMethod", WsSecurityNames.Xenc, First("EncryptedKey", WsSecurityNames.Xenc)), "signature" => First("SignatureMethod", WsSecurityNames.Ds), _ => First("DigestMethod", WsSecurityNames.Ds, First("SignedInfo", WsSecurityNames.Ds)), }; target.SetAttribute("Algorithm", algorithm); }); var (_, errorCode, receipt) = await stand.PostRaw(message); errorCode.Should().Be(expectedError); receipt.Should().BeFalse(); reached.Should().BeFalse(); } [Theory] // A base64 value whose last character has non-zero unused bits decodes to the right bytes on .NET 10, so the message // would be accepted there and refused on .NET 11. XML Schema base64Binary forbids that spelling: refused on every // runtime, with the code of any malformed value in that place (a malformed ds:SignatureValue is EBMS:0102, AS4_CP_TA66). [InlineData("SignatureValue", "EBMS:0102")] [InlineData("CipherValue", "EBMS:0102")] public async Task ASecurityValueWithUnusedBitsSet_IsAnsweredWithAnError_OnEveryRuntime(string element, string expectedError) { var reached = false; await using var stand = await Stand.StartAsync(_ => { reached = true; return Task.CompletedTask; }); var message = Conformance(As4TestMessages.Gzip(Encoding.UTF8.GetBytes(Payload)), afterSecuring: envelope => { var ns = element == "CipherValue" ? WsSecurityNames.Xenc : WsSecurityNames.Ds; var value = (XmlElement)envelope.GetElementsByTagName(element, ns)[0]!; value.InnerText = As4TestMessages.WithUnusedBitsSet(value.InnerText); }); var (_, errorCode, receipt) = await stand.PostRaw(message); errorCode.Should().Be(expectedError); receipt.Should().BeFalse(); reached.Should().BeFalse(); } [Fact] public async Task ASoap11Envelope_IsNotAnAs4Message_AndIsAnsweredWithASoapFault() { // Testing service 2026.06, "SOAP 1.2": AS4 is SOAP 1.2; a SOAP 1.1 envelope is not read as one. var reached = false; await using var stand = await Stand.StartAsync(_ => { reached = true; return Task.CompletedTask; }); var body = Encoding.UTF8.GetBytes( ""); var response = await stand.PostBytes("text/xml", body); ((int)response.StatusCode).Should().BeOneOf(400, 415); reached.Should().BeFalse(); } /// /// A user message from A to B as a simulated sender builds it: one attachment with as /// its bytes (none when null), declared gzip unless is given, signed and /// encrypted as A sends it, with a hook at each stage to bend it away from the profile. /// private static (string ContentType, byte[] Body) Conformance(byte[]? content, string? uncompressedMimeType = null, Action? beforeSigning = null, Action? afterSigning = null, Action? afterEncryption = null, bool coverBody = true, Action? afterSecuring = null) { const string contentId = "p1@a.example"; var envelope = As4TestMessages.UserMessage(Guid.NewGuid().ToString("N") + "@a.example", contentId, from: "urn:redb:a", to: "urn:redb:b", service: "urn:example", action: "Submit", uncompressedMimeType: uncompressedMimeType); beforeSigning?.Invoke(envelope); var message = SwaMessage.Create(envelope); var part = content is null ? null : message.AddPart(contentId, uncompressedMimeType ?? "application/gzip", content); As4Signature.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow, coverBody); if (part is not null) afterSigning?.Invoke(part); As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken); if (part is not null) afterEncryption?.Invoke(part); afterSecuring?.Invoke(message.Envelope); return message.Write(); } // ── Fixtures ───────────────────────────────────────────────────────────── private static Exchange NewExchange() { var exchange = new Exchange(new Message(Payload) { ContentType = "text/xml" }); exchange.In.Headers[As4Headers.OriginalSender] = "C1"; exchange.In.Headers[As4Headers.FinalRecipient] = "C4"; return exchange; } /// A user message from A to B, compressed, not yet signed or encrypted. private static SwaMessage RawMessage(string? messageId = null, string action = "Submit") { const string contentId = "p1@a.example"; var message = SwaMessage.Create(As4TestMessages.UserMessage(messageId ?? Guid.NewGuid().ToString("N") + "@a.example", contentId, from: "urn:redb:a", to: "urn:redb:b", service: "urn:example", action: action)); message.AddPart(contentId, "application/gzip", As4TestMessages.Gzip(Encoding.UTF8.GetBytes(Payload))); return message; } /// A user message from A to B with the given payloads (each gzipped), signed and encrypted as A sends it. private static ((string ContentType, byte[] Body) Message, string MessageId) SecuredMessage(params byte[][] payloads) => SecuredMessage(fourCorner: true, payloads); private static ((string ContentType, byte[] Body) Message, string MessageId) SecuredMessage(bool fourCorner, params byte[][] payloads) { var ids = payloads.Select((_, i) => $"p{i}@a.example").ToArray(); var message = SwaMessage.Create(As4TestMessages.UserMessage(Guid.NewGuid().ToString("N") + "@a.example", ids[0], from: "urn:redb:a", to: "urn:redb:b", service: "urn:example", action: "Submit", fourCorner: fourCorner, moreContentIds: ids[1..])); for (var i = 0; i < payloads.Length; i++) message.AddPart(ids[i], "application/gzip", As4TestMessages.Gzip(payloads[i])); var messageId = MessagingReader.Read(message.Envelope).UserMessages.Single().MessageInfo.MessageId; As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow); As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken); return (message.Write(), messageId); } /// A user message from A to B, signed and encrypted as A sends it; the bytes resend unchanged. private static ((string ContentType, byte[] Body) Message, string MessageId) SecuredRawMessage(string? id = null, string action = "Submit") { var message = RawMessage(id, action); var messageId = MessagingReader.Read(message.Envelope).UserMessages.Single().MessageInfo.MessageId; As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow); As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken); return (message.Write(), messageId); } private static As4Partner Partner(string name, X509Certificate2 certificate) => new() { Name = name, PartyId = "urn:redb:" + name, Service = "urn:example", Action = "Submit", PartnerSigningCertificates = { As4TestMessages.PublicOnly(certificate) }, PartnerEncryptionCertificate = As4TestMessages.PublicOnly(certificate), }; private static As4ConnectionFactory Node(string name, X509Certificate2 key, params As4Partner[] partners) { var node = new As4ConnectionFactory { OurPartyId = "urn:redb:" + name, ExternalHostName = name + ".example", SigningCertificate = key, DecryptionCertificates = { key }, }; foreach (var partner in partners) node.Partners.Add(partner); return node; } /// Node B receiving on a loopback port; nodes A and C (C unknown to B) can send to it. // ── Hostile XML (11-XML-HARDENING, layer 1) ────────────────────────────── // Each test checks a property of the receiver, not a package version: the refusal comes with the right protocol // answer and in bounded time, and the test turns red when someone removes the limit behind it. /// A SOAP 1.2 envelope whose header carries . private static byte[] EnvelopeWith(string hostile) => Encoding.UTF8.GetBytes( "" + hostile + ""); public static TheoryData EnvelopesOverTheLimits() => new() { // 100 000 levels: the limit stops the reader at level 33, long before a recursive step would meet them. { "MaxDepth", string.Concat(Enumerable.Repeat("", 100_000)) + string.Concat(Enumerable.Repeat("", 100_000)) }, { "MaxAttributesPerElement", " $"a{i}=\"v\"")) + "/>" }, { "MaxNamespaceDeclarationsPerElement", " $"xmlns:p{i}=\"urn:{i}\"")) + "/>" }, { "MaxNamespaceDeclarations", string.Concat(Enumerable.Range(0, 5_000).Select(i => $"")) }, }; [Theory] [MemberData(nameof(EnvelopesOverTheLimits))] public async Task EnvelopeOverAStructureLimit_IsASenderSoapFaultInBoundedTime(string limit, string hostile) { var reached = false; await using var stand = await Stand.StartAsync(_ => { reached = true; return Task.CompletedTask; }); var watch = System.Diagnostics.Stopwatch.StartNew(); var response = await stand.PostBytes("application/soap+xml", EnvelopeWith(hostile)); watch.Stop(); response.StatusCode.Should().Be(HttpStatusCode.BadRequest); var text = await response.Content.ReadAsStringAsync(); text.Should().Contain("soapenv:Sender").And.Contain(limit); reached.Should().BeFalse(); stand.Refused.Should().Be(1, "a hostile envelope is the partner's fault"); stand.Errors.Should().Be(0); watch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(5)); } [Fact] public async Task EnvelopeWithinTheLimits_StillReachesTheRoute() { // The limits are three to four times what real envelopes use: an ordinary message is untouched by them. var reached = false; await using var stand = await Stand.StartAsync(_ => { reached = true; return Task.CompletedTask; }); var (message, _) = SecuredMessage(Encoding.UTF8.GetBytes(Payload)); (await stand.PostRaw(message)).Receipt.Should().BeTrue(); reached.Should().BeTrue(); } [Fact] public async Task HundredsOfReferences_AreRefusedBeforeAnyIsDigested() { // A 4 MB payload referenced 1000 more times would cost 4 GB of hashing if references were digested before the // signature over them is checked. They are not: the signature fails first. The time is measured against the same // message without the extra references in the same run, so a slow host moves both: digesting them would take // hundreds of times the baseline, refusing takes about as long as it. A refusal over the limit is tried again, up // to three times: a stall of a shared host passes, digesting would make every attempt slow. await using var stand = await Stand.StartAsync(_ => Task.CompletedTask); var payload = System.Security.Cryptography.RandomNumberGenerator.GetBytes(4 * 1024 * 1024); var baseline = System.Diagnostics.Stopwatch.StartNew(); (await stand.PostRaw(Referencing(payload, extraReferences: 0))).Receipt.Should().BeTrue(); baseline.Stop(); var limit = TimeSpan.FromTicks(Math.Max(baseline.Elapsed.Ticks * 3, TimeSpan.FromSeconds(1).Ticks)); var attempts = new List(); do { var hostileMessage = Referencing(payload, extraReferences: 1000); var hostile = System.Diagnostics.Stopwatch.StartNew(); var answer = await stand.PostRaw(hostileMessage); hostile.Stop(); answer.ErrorCode.Should().Be("EBMS:0101"); attempts.Add(hostile.Elapsed); } while (attempts[^1] >= limit && attempts.Count < 3); attempts.Min().Should().BeLessThan(limit, $"the same message without the extra references took {baseline.Elapsed}; the refusals took {string.Join(", ", attempts)}"); static (string ContentType, byte[] Body) Referencing(byte[] payload, int extraReferences) { var message = RawMessage(); message.Parts.Values.Single().Replace(new MemoryStream(As4TestMessages.Gzip(payload))); As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow); var signedInfo = (XmlElement)message.Envelope.GetElementsByTagName("SignedInfo", WsSecurityNames.Ds)[0]!; var attachmentReference = signedInfo.ChildNodes.OfType() .Last(e => e.LocalName == "Reference" && e.GetAttribute("URI").StartsWith("cid:", StringComparison.Ordinal)); for (var i = 0; i < extraReferences; i++) signedInfo.AppendChild(attachmentReference.CloneNode(deep: true)); As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken); return message.Write(); } } [Fact] public async Task MoreThanOneEncryptedKey_IsFailedDecryption() { // Each key costs an RSA private-key operation, and anyone can encrypt for our certificate: one key per message. await using var stand = await Stand.StartAsync(_ => Task.CompletedTask); var message = RawMessage(); As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow); As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken); var encryptedKey = (XmlElement)message.Envelope.GetElementsByTagName("EncryptedKey", WsSecurityNames.Xenc)[0]!; for (var i = 0; i < 50; i++) encryptedKey.ParentNode!.InsertAfter(encryptedKey.CloneNode(deep: true), encryptedKey); (await stand.PostRaw(message.Write())).ErrorCode.Should().Be("EBMS:0102"); } [Fact] public async Task APartReferencedTwiceForDecryption_IsFailedDecryption() { await using var stand = await Stand.StartAsync(_ => Task.CompletedTask); var message = RawMessage(); As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow); As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken); var dataReference = (XmlElement)message.Envelope.GetElementsByTagName("DataReference", WsSecurityNames.Xenc)[0]!; dataReference.ParentNode!.AppendChild(dataReference.CloneNode(deep: true)); (await stand.PostRaw(message.Write())).ErrorCode.Should().Be("EBMS:0102"); } [Fact] public async Task XmlPayloadOverTheDefaultLimits_FailsItsSignatureInBoundedTime() { // An uncompressed XML payload is canonicalized for its digest. Signed as an ordinary document, then swapped // for one 100 000 levels deep: the canonicalizer's reader stops it at the default depth. await using var stand = await Stand.StartAsync(_ => Task.CompletedTask); const string contentId = "p1@a.example"; var message = SwaMessage.Create(As4TestMessages.UserMessage(Guid.NewGuid().ToString("N") + "@a.example", contentId, from: "urn:redb:a", to: "urn:redb:b", service: "urn:example", action: "Submit")); var part = message.AddPart(contentId, "application/xml", Encoding.UTF8.GetBytes(Payload)); As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow); part.Replace(new MemoryStream(Encoding.UTF8.GetBytes( string.Concat(Enumerable.Repeat("", 100_000)) + string.Concat(Enumerable.Repeat("", 100_000))))); As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken); var watch = System.Diagnostics.Stopwatch.StartNew(); var answer = await stand.PostRaw(message.Write()); watch.Stop(); answer.ErrorCode.Should().Be("EBMS:0101"); watch.Elapsed.Should().BeLessThan(TimeSpan.FromSeconds(5)); } private sealed class Stand : IAsyncDisposable { private readonly RouteContext _context; private readonly int _port; private string _receiveUri = ""; private Stand(RouteContext context, int port) { _context = context; _port = port; } /// Errors counted on the receive endpoint. public long Errors => ((IEndpointStatistics)_context.GetEndpoint(_receiveUri)).Errors; /// Requests refused on the receive endpoint as the partner's fault. public long Refused => ((IEndpointStatistics)_context.GetEndpoint(_receiveUri)).Refused; public static async Task StartAsync(Func route, IIdempotentRepository? duplicates = null, bool streamBody = false, redb.Route.Configuration.StreamCacheOptions? spool = null, redb.Route.Configuration.RouteEngineOptions? engine = null, bool payloadList = false, Action? agreement = null, Action? receiver = null, int? port = null, int? inFlightClaimTimeout = null) { var listenPort = port ?? global::redb.Route.Tests.Shared.TestPorts.Next(); var context = new RouteContext(options: engine); context.AddComponent(new As4Component()); context.AddIdempotentRepository("dedup", duplicates ?? new InMemoryIdempotentRepository()); if (spool is not null) context.AddService(typeof(redb.Route.Configuration.StreamCacheOptions), spool); // The agreement between A and B, as each side holds it. var aAtB = Partner("a", NodeA); var bAtA = Partner("b", NodeB); agreement?.Invoke(aAtB); agreement?.Invoke(bAtA); var nodeB = Node("b", NodeB, aAtB); receiver?.Invoke(nodeB); context.AddToRegistry("b", nodeB); context.AddToRegistry("a", Node("a", NodeA, bAtA)); context.AddToRegistry("c", Node("c", Stranger, Partner("b", NodeB))); var receive = As4Dsl.Receive("/as4/in").Host("127.0.0.1").Port(listenPort).ConnectionFactory("b").IdempotentRepository("dedup"); if (streamBody) receive.StreamBody(); if (payloadList) receive.PayloadList(); if (inFlightClaimTimeout is { } claimTimeout) receive.InFlightClaimTimeout(claimTimeout); context.AddRoutes(r => r.From(receive).RouteId(RouteId) .Process((e, _) => route(e))); await context.Start(); return new Stand(context, listenPort) { _receiveUri = receive.Build() }; } /// The id of the receive route. public const string RouteId = "as4-in"; /// The status of the receive route. public RouteStatus Status => _context.GetRoute(RouteId)!.Status; /// Starts the receive route by hand, as the Tsak routes controller does. public Task StartRoute() => _context.StartRoute(RouteId); /// Stops the context. public Task Stop() => _context.Stop(); public async Task Send(IExchange exchange, string from = "a") { var producer = _context.GetEndpoint( As4Dsl.Send($"http://127.0.0.1:{_port}/as4/in").ConnectionFactory(from).Partner("b").Timeout(15000)).CreateProducer(); await producer.Start(); await producer.Process(exchange); } public async Task PostBytes(string contentType, byte[] body) { // 60 s: the 4 MB baseline of HundredsOfReferences_AreRefusedBeforeAnyIsDigested took longer than 15 s on a loaded // host. No test judges time by this timeout; the one that measures compares against its own baseline. using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(60) }; var content = new ByteArrayContent(body); content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType); return await http.PostAsync($"http://127.0.0.1:{_port}/as4/in", content); } public async Task<(HttpStatusCode Status, string? ErrorCode, bool Receipt)> PostRaw((string ContentType, byte[] Body) message) { using var response = await PostBytes(message.ContentType, message.Body); var body = await response.Content.ReadAsByteArrayAsync(); var answer = SwaMessage.Read(response.Content.Headers.ContentType!.ToString(), body, 1024 * 1024); var signals = MessagingReader.Read(answer.Envelope).SignalMessages; var error = signals.SelectMany(s => s.Errors).FirstOrDefault(); return (response.StatusCode, error?.ErrorCode, signals.Any(s => s.IsReceipt)); } public async ValueTask DisposeAsync() => await _context.DisposeAsync(); } } Path: redb-route/tests/redb.Route.Tests.As4/As4EngineIntegrationTests.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/tests/redb.Route.Tests.As4/As4EngineIntegrationTests.cs ---- using System.Diagnostics; using System.Net; using System.Net.Http.Headers; using System.Security.Cryptography.X509Certificates; using System.Text; using Microsoft.Extensions.DependencyInjection; using redb.Route.Abstractions; using redb.Route.As4; using redb.Route.As4.Messaging; using redb.Route.As4.Mime; using redb.Route.As4.Security; using redb.Route.Components; using redb.Route.Core; using redb.Route.Http; using redb.Route.Processors; using As4Dsl = redb.Route.As4.Fluent.As4; namespace redb.Route.Tests.As4; /// /// The AS4 connector in the engine's cross-cutting mechanics, each after the neighbour test it copies — /// admission limits (As2ConcurrencyLimitOptionsTests, HttpConcurrencyLimitTests), the shared host a /// scan-loading module host provides (SoapComponentSharedHostFromDiTests), the drain on stop /// (SoapStopDrainsInflightTests), statistics once per event (As2ReceiveTests, HttpConcurrencyLimitTests), /// one trace across sender and receiver (As2ReceiveTests.Loopback_EmitsLinkedProducerAndConsumerSpans), and the /// answer after a .Transacted() unit of work. /// public class As4EngineIntegrationTests { private static readonly ActivitySource TraceTestSource = new("redb.Route.Tests.As4.Trace"); private static readonly X509Certificate2 NodeA = As4TestMessages.KeyPair("CN=a.as4.test"); private static readonly X509Certificate2 NodeB = As4TestMessages.KeyPair("CN=b.as4.test"); private const string Payload = "42"; // ── Admission limits ───────────────────────────────────────────────────── [Fact] public void Limits_UriAndDsl_CarryTheOptions() { string built = As4Dsl.Receive("/as4/in").Port(4090).ConnectionFactory("b").IdempotentRepository("dedup") .MaxConcurrentRequests(2, queue: 4).RejectStatusCode(503).RetryAfterSeconds(0); built.Should().Contain("maxConcurrentRequests=2").And.Contain("requestQueueLimit=4") .And.Contain("rejectStatusCode=503").And.Contain("retryAfterSeconds=0"); var endpoint = (As4Endpoint)new As4Component().CreateEndpoint(EndpointUriParser.Parse(built)); endpoint.EndpointOptions.MaxConcurrentRequests.Should().Be(2); endpoint.EndpointOptions.RequestQueueLimit.Should().Be(4); endpoint.EndpointOptions.RejectStatusCode.Should().Be(503); endpoint.EndpointOptions.RetryAfterSeconds.Should().Be(0); } [Fact] public void Limits_QueueWithoutLimit_FailsLoud() { var act = () => new As4Component().CreateEndpoint(EndpointUriParser.Parse("as4:/in?connectionFactory=b&requestQueueLimit=3")); act.Should().Throw().WithMessage("*requestQueueLimit*maxConcurrentRequests*"); } [Fact] public async Task Limits_OverTheLimit_IsShedWith503_CountedOnceAsRejected() { var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var port = TestPort(); await using var context = NewContext(); var uri = Receive(port).MaxConcurrentRequests(1).Build(); context.AddRoutes(r => r.From(uri).Process(async (_, _) => { entered.TrySetResult(); await release.Task; })); await context.Start(); var first = Post(port); await entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); using var shed = await PostResponse(port); release.TrySetResult(); (await first).Receipt.Should().BeTrue(); shed.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable, "an AS4 sender retries on 503"); var stats = (IEndpointStatistics)context.GetEndpoint(uri); stats.Rejected.Should().Be(1, "each shed request is counted once"); stats.Errors.Should().Be(0, "shedding is not a processing error"); } // ── The shared host of a module host ───────────────────────────────────── [Fact] public void SharedHost_FromTheContextsContainer_IsUsedWhenNoneWasAssigned() { var shared = new SharedHttpServerManager(); var component = new As4Component(); using var context = new RouteContext(); context.SetServiceProvider(new ServiceCollection().AddSingleton(shared).BuildServiceProvider()); context.AddComponent(component); component.Server.Should().BeSameAs(shared); } [Fact] public void SharedHost_AssignedWinsOverTheContainer() { var assigned = new SharedHttpServerManager(); var component = new As4Component { ServerManager = assigned }; using var context = new RouteContext(); context.SetServiceProvider(new ServiceCollection().AddSingleton(new SharedHttpServerManager()).BuildServiceProvider()); context.AddComponent(component); component.Server.Should().BeSameAs(assigned); } [Fact] public void SharedHost_AsAContextService_IsFound() { var shared = new SharedHttpServerManager(); var component = new As4Component(); using var context = new RouteContext(); context.AddService(typeof(SharedHttpServerManager), shared); context.AddComponent(component); component.Server.Should().BeSameAs(shared); } [Fact] public async Task SharedHost_OneListener_ServesAnHttpRouteAndAnAs4RouteOnOnePort() { // As a scan-loaded module host runs them: both components find the one manager, neither owns a server. var port = TestPort(); await using var shared = new SharedHttpServerManager(); await using var context = NewContext(); context.AddService(typeof(SharedHttpServerManager), shared); context.AddComponent(new HttpComponent()); context.AddRoutes(r => { r.From($"http://127.0.0.1:{port}/ping?inOut=true").SetBody("pong"); r.From(Receive(port)).Process(_ => { }); }); await context.Start(); using var http = new HttpClient(); (await http.GetStringAsync($"http://127.0.0.1:{port}/ping")).Should().Be("pong"); (await Post(port)).Receipt.Should().BeTrue(); } // ── Stop ───────────────────────────────────────────────────────────────── [Fact] public async Task Stop_WaitsForAMessageAlreadyInTheRoute_WhileThePortStaysBusy() { var port = TestPort(); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var finished = false; await using var context = NewContext(); var slow = context.GetEndpoint(Receive(port)).CreateConsumer(new DelegateProcessor(async (_, _) => { entered.TrySetResult(); await release.Task; finished = true; })); // A second route keeps the listener up after the first one stops — the case where nothing used to wait. var other = context.GetEndpoint(As4Dsl.Receive("/as4/other").Host("127.0.0.1").Port(port).ConnectionFactory("b").IdempotentRepository("dedup")) .CreateConsumer(new DelegateProcessor(_ => { })); await slow.Start(); await other.Start(); var call = Post(port); await entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); var stop = slow.Stop(); (await Task.WhenAny(stop, Task.Delay(500)) == stop).Should().BeFalse("Stop must not return while a message of this route is in the pipeline"); release.TrySetResult(); await stop.WaitAsync(TimeSpan.FromSeconds(10)); finished.Should().BeTrue(); (await call).Receipt.Should().BeTrue("the message in flight is answered, not cut"); await other.Stop(); } // ── Statistics ─────────────────────────────────────────────────────────── [Fact] public async Task Statistics_EachEventIsCountedOnce() { var port = TestPort(); var fail = false; await using var context = NewContext(); var uri = Receive(port).Build(); context.AddRoutes(r => r.From(uri).Process(_ => { if (fail) throw new InvalidOperationException("route fails"); })); await context.Start(); var stats = (IEndpointStatistics)context.GetEndpoint(uri); (await Post(port)).Receipt.Should().BeTrue(); stats.MessagesIn.Should().Be(1); stats.Errors.Should().Be(0); fail = true; (await Post(port)).ErrorCode.Should().Be("EBMS:0004"); stats.MessagesIn.Should().Be(2); stats.Errors.Should().Be(1, "a route failure is counted by the engine, not again by the connector"); using var unsigned = await PostResponse(port, sign: false); stats.MessagesIn.Should().Be(2, "a message refused before the route is not a message in"); stats.Errors.Should().Be(1, "the partner's bad message is not a failure of this endpoint"); stats.Refused.Should().Be(1, "the refusal is counted once, as a refusal"); stats.LastRefusalMessage.Should().StartWith("EBMS:0010"); } [Fact] public async Task Statistics_RefusalsLeaveHealthAndErrorsAlone() { // A partner sending what the agreement does not allow, again and again, must not turn the route red: the endpoint // is fine, the partner is not. The refusals are visible on their own counter, with the reason of the last one. var port = TestPort(); await using var context = NewContext(); var uri = Receive(port).Build(); context.AddRoutes(r => r.From(uri).Process(_ => { })); await context.Start(); var stats = (IEndpointStatistics)context.GetEndpoint(uri); for (var i = 0; i < 5; i++) { using var _ = await PostResponse(port, sign: false); } stats.Refused.Should().Be(5); stats.Errors.Should().Be(0); stats.LastErrorTime.Should().BeNull(); stats.LastRefusalTime.Should().NotBeNull(); stats.HealthStatus.Should().Be(EndpointHealthStatus.Healthy); } [Fact] public async Task Statistics_TheSenderCountsOneMessageOut() { var port = TestPort(); await using var context = NewContext(); context.AddRoutes(r => { r.From(Receive(port)).Process(_ => { }); r.From("direct://out").To(Send(port)); }); await context.Start(); var producer = context.GetEndpoint("direct://out").CreateProducer(); await producer.Start(); await producer.Process(NewExchange()); ((IEndpointStatistics)context.GetEndpoint(Send(port))).MessagesOut.Should().Be(1); } // ── Tracing ────────────────────────────────────────────────────────────── [Fact] public async Task Trace_SenderAndReceiverSpans_ShareOneTrace() { var spans = new List(); using var listener = new ActivityListener { ShouldListenTo = s => s.Name == redb.Route.Telemetry.RouteActivitySource.SourceName || s.Name == TraceTestSource.Name, Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllData, ActivityStopped = a => { lock (spans) spans.Add(a); }, }; ActivitySource.AddActivityListener(listener); var port = TestPort(); await using var context = NewContext(); var receive = Receive(port).Build(); context.AddRoutes(r => r.From(receive).Process(_ => { })); await context.Start(); var producer = context.GetEndpoint(Send(port)).CreateProducer(); await producer.Start(); ActivityTraceId traceId; // The listener sees every test's spans in the process: this test's own root tells its trace apart (as SpanCapture does). using (var root = TraceTestSource.StartActivity("test")) { await producer.Process(NewExchange()); traceId = root!.TraceId; } Activity? send, received; lock (spans) { send = spans.LastOrDefault(a => a.OperationName == "b send" && a.TraceId == traceId); received = spans.LastOrDefault(a => a.OperationName == "/as4/in receive" && a.TraceId == send?.TraceId); } send.Should().NotBeNull(); send!.Kind.Should().Be(ActivityKind.Client); received.Should().NotBeNull("the receiver continues the sender's trace from traceparent"); received!.Kind.Should().Be(ActivityKind.Consumer); received.GetTagItem("redb.route.endpoint").Should().NotBeNull("as StartTransportSpan tags every transport span"); } // The core tracing contract (RouteTelemetryExtensions, redb.Route 0b5658f0), as the HTTP transport uses it. private static (ActivityTraceId TraceId, ActivitySpanId SpanId, string Header) Caller() { var traceId = ActivityTraceId.CreateRandom(); var spanId = ActivitySpanId.CreateRandom(); return (traceId, spanId, $"00-{traceId}-{spanId}-01"); } [Fact] public async Task Trace_ReceivedMessage_WithTraceparent_ContinuesTheSendersTrace_OnANamedSpan() { var port = TestPort(); await using var context = NewContext(); context.AddRoutes(r => r.From(Receive(port)).Process(_ => { })); await context.Start(); using var probe = redb.Route.Tests.Telemetry.RouteTelemetryProbe.ForEndpointContaining($"port={port}"); var caller = Caller(); using var response = await PostResponse(port, headers: new Dictionary { ["traceparent"] = caller.Header }); var span = probe.Activities.Single(a => a.Kind == ActivityKind.Consumer); span.TraceId.Should().Be(caller.TraceId); span.ParentSpanId.Should().Be(caller.SpanId); span.DisplayName.Should().Be("/as4/in receive", "the span names its destination, as the messaging conventions do"); } [Fact] public async Task Trace_ReceivedMessage_WithoutTraceparent_IsARootSpan() { var port = TestPort(); await using var context = NewContext(); context.AddRoutes(r => r.From(Receive(port)).Process(_ => { })); await context.Start(); using var probe = redb.Route.Tests.Telemetry.RouteTelemetryProbe.ForEndpointContaining($"port={port}"); using var response = await PostResponse(port); var span = probe.Activities.Single(a => a.Kind == ActivityKind.Consumer); span.ParentSpanId.Should().Be(default(ActivitySpanId)); span.Parent.Should().BeNull(); } [Fact] public async Task Trace_TheSendersBaggage_ReachesTheRoute() { var port = TestPort(); await using var context = NewContext(); var baggage = new System.Collections.Concurrent.ConcurrentQueue(); context.AddRoutes(r => r.From(Receive(port)).Process(_ => baggage.Enqueue(Activity.Current?.GetBaggageItem("tenant")))); await context.Start(); using var probe = redb.Route.Tests.Telemetry.RouteTelemetryProbe.ForEndpointContaining($"port={port}"); // the baggage rides on the span var headers = new Dictionary(); using (var send = new Activity("caller").Start()) { send.AddBaggage("tenant", "t1"); redb.Route.Telemetry.RouteTelemetryExtensions.InjectTraceContext(send, headers, static (h, name, value) => h[name] = value); } using var response = await PostResponse(port, headers: headers); baggage.Should().ContainSingle().Which.Should().Be("t1"); } [Fact] public async Task Trace_ASend_CarriesTheContextOfItsOwnSpan_AndAMissingReceiptMarksItRed() { // A partner that records the traceparent it gets and answers without a receipt. var port = TestPort(); using var partner = new HttpListener(); partner.Prefixes.Add($"http://127.0.0.1:{port}/"); partner.Start(); string? seen = null; var serving = Task.Run(async () => { var ctx = await partner.GetContextAsync(); seen = ctx.Request.Headers["traceparent"]; await ctx.Request.InputStream.CopyToAsync(Stream.Null); ctx.Response.StatusCode = 200; ctx.Response.Close(); }); await using var context = NewContext(); await context.Start(); var producer = context.GetEndpoint(Send(port)).CreateProducer(); await producer.Start(); using var probe = redb.Route.Tests.Telemetry.RouteTelemetryProbe.ForEndpointContaining($":{port}/"); var act = () => producer.Process(NewExchange()); await act.Should().ThrowAsync(); await serving.WaitAsync(TimeSpan.FromSeconds(10)); var send = probe.Activities.Single(a => a.Kind == ActivityKind.Client); send.DisplayName.Should().Be("b send"); seen.Should().Be($"00-{send.TraceId}-{send.SpanId}-{(int)send.ActivityTraceFlags:x2}"); send.Status.Should().Be(ActivityStatusCode.Error, "a response without a receipt is a failed send"); } [Fact] public async Task Trace_TelemetryOff_OpensNoSpan_AndTheCallersContextStillReachesThePartner() { var port = TestPort(); using var partner = new HttpListener(); partner.Prefixes.Add($"http://127.0.0.1:{port}/"); partner.Start(); string? seen = null; var serving = Task.Run(async () => { var ctx = await partner.GetContextAsync(); seen = ctx.Request.Headers["traceparent"]; await ctx.Request.InputStream.CopyToAsync(Stream.Null); ctx.Response.StatusCode = 200; ctx.Response.Close(); }); using var callerListener = new ActivityListener { ShouldListenTo = s => s.Name == TraceTestSource.Name, Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllData, }; ActivitySource.AddActivityListener(callerListener); await using var context = NewContext(new redb.Route.Configuration.RouteEngineOptions { EnableTelemetry = false }); await context.Start(); var producer = context.GetEndpoint(Send(port)).CreateProducer(); await producer.Start(); using var probe = redb.Route.Tests.Telemetry.RouteTelemetryProbe.ForEndpointContaining($":{port}/"); ActivityTraceId traceId; using (var root = TraceTestSource.StartActivity("caller")) { traceId = root!.TraceId; var act = () => producer.Process(NewExchange()); await act.Should().ThrowAsync(); // the partner answers without a receipt } await serving.WaitAsync(TimeSpan.FromSeconds(10)); probe.Activities.Should().BeEmpty(); seen.Should().Contain(traceId.ToString(), "a redb hop with tracing off does not cut the trace around it"); } // ── Transactions ───────────────────────────────────────────────────────── [Fact] public async Task Transacted_Commit_IsAcknowledgedWithAReceipt() { var port = TestPort(); await using var context = NewContext(); context.AddRoutes(r => r.From(Receive(port)).Transacted().Process(_ => { }).End()); await context.Start(); (await Post(port)).Receipt.Should().BeTrue(); } [Fact] public async Task Transacted_Rollback_IsAnsweredWithAnError_NotAReceipt() { var port = TestPort(); await using var context = NewContext(); context.AddRoutes(r => r.From(Receive(port)).Transacted().Process(_ => throw new InvalidOperationException("rolls back")).End()); await context.Start(); var (_, errorCode, receipt) = await Post(port); errorCode.Should().Be("EBMS:0004"); receipt.Should().BeFalse(); } // ── Fixtures ───────────────────────────────────────────────────────────── private static int TestPort() => global::redb.Route.Tests.Shared.TestPorts.Next(); private static redb.Route.As4.Fluent.As4Builder Receive(int port) => As4Dsl.Receive("/as4/in").Host("127.0.0.1").Port(port).ConnectionFactory("b").IdempotentRepository("dedup"); private static string Send(int port) => As4Dsl.Send($"http://127.0.0.1:{port}/as4/in").ConnectionFactory("a").Partner("b").Timeout(15000); private static RouteContext NewContext(redb.Route.Configuration.RouteEngineOptions? options = null) { var context = new RouteContext(options: options ?? new redb.Route.Configuration.RouteEngineOptions()); context.AddComponent(new As4Component()); context.AddIdempotentRepository("dedup", new InMemoryIdempotentRepository()); context.AddToRegistry("b", Node("b", NodeB, Partner("a", NodeA))); context.AddToRegistry("a", Node("a", NodeA, Partner("b", NodeB))); return context; } private static As4Partner Partner(string name, X509Certificate2 certificate) => new() { Name = name, PartyId = "urn:redb:" + name, Service = "urn:example", Action = "Submit", PartnerSigningCertificates = { As4TestMessages.PublicOnly(certificate) }, PartnerEncryptionCertificate = As4TestMessages.PublicOnly(certificate), }; private static As4ConnectionFactory Node(string name, X509Certificate2 key, As4Partner partner) => new() { OurPartyId = "urn:redb:" + name, ExternalHostName = name + ".example", SigningCertificate = key, DecryptionCertificates = { key }, Partners = { partner }, }; private static Exchange NewExchange() { var exchange = new Exchange(new Message(Payload) { ContentType = "text/xml" }); exchange.In.Headers[As4Headers.OriginalSender] = "C1"; exchange.In.Headers[As4Headers.FinalRecipient] = "C4"; return exchange; } private static async Task PostResponse(int port, bool sign = true, IReadOnlyDictionary? headers = null) { const string contentId = "p1@a.example"; using var message = SwaMessage.Create(As4TestMessages.UserMessage(Guid.NewGuid().ToString("N") + "@a.example", contentId, from: "urn:redb:a", to: "urn:redb:b", service: "urn:example", action: "Submit")); message.AddPart(contentId, "application/gzip", As4TestMessages.Gzip(Encoding.UTF8.GetBytes(Payload))); if (sign) { As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow); As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken); } var (contentType, body) = message.Write(); using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) }; var content = new ByteArrayContent(body); content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType); var request = new HttpRequestMessage(System.Net.Http.HttpMethod.Post, $"http://127.0.0.1:{port}/as4/in") { Content = content }; foreach (var (name, value) in headers ?? new Dictionary()) request.Headers.TryAddWithoutValidation(name, value); return await http.SendAsync(request); } private static async Task<(HttpStatusCode Status, string? ErrorCode, bool Receipt)> Post(int port) { using var response = await PostResponse(port); var answer = SwaMessage.Read(response.Content.Headers.ContentType!.ToString(), await response.Content.ReadAsByteArrayAsync(), 1024 * 1024); var signals = MessagingReader.Read(answer.Envelope).SignalMessages; return (response.StatusCode, signals.SelectMany(s => s.Errors).FirstOrDefault()?.ErrorCode, signals.Any(s => s.IsReceipt)); } } Path: redb-route/tests/redb.Route.Tests.As4/As4HarmonyLiveTests.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/tests/redb.Route.Tests.As4/As4HarmonyLiveTests.cs ---- using System.Net; using System.Net.Http.Json; using System.Text; using System.Text.Json; using redb.Route.As4; using redb.Route.Components; using As4Dsl = redb.Route.As4.Fluent.As4; namespace redb.Route.Tests.As4; /// /// Live against a second, independent MSH: Harmony Access Point 2.6.2 (NIIS), whose MSH is Domibus 5.1 — the /// eDelivery reference implementation. The stand runs on the stand server (its README.md next to its compose file) and /// is reached through SSH tunnels: 127.0.0.1:18480 is Harmony (18080 on the server), and Harmony reaches our receiver on 15090 through the /// reverse tunnel. Skipped when the tunnel is down, unless REDB_AS4_INTEROP=1. /// public class As4HarmonyLiveTests { private const int HarmonyPort = 18480; // local end of the tunnel; 18080 here is the Soap agent's soap-echo stand private const int InboundPort = 15090; private const string PartyIdType = "urn:oasis:names:tc:ebcore:partyid-type:unregistered"; [As4LiveTheory(HarmonyPort)] [InlineData(As4KeyReference.BinarySecurityToken)] [InlineData(As4KeyReference.IssuerSerial)] [InlineData(As4KeyReference.KeyIdentifier)] public async Task WeSendToHarmony_ItVerifiesAndReceives_AndWeVerifyItsReceipt(As4KeyReference form) { await using var context = new redb.Route.Core.RouteContext(); context.AddComponent(new As4Component()); context.AddToRegistry("node", Node(partner => { partner.Name = "harmony"; partner.Service = "urn:redb:as4:interop"; partner.ServiceType = "urn:redb:services"; partner.Action = "StoreMessage"; partner.KeyReference = form; })); var producer = context.GetEndpoint(As4Dsl.Send($"http://127.0.0.1:{HarmonyPort}/services/msh") .ConnectionFactory("node").Partner("harmony").Timeout(60000)).CreateProducer(); await producer.Start(); var exchange = new redb.Route.Core.Exchange(new redb.Route.Core.Message( $"{Guid.NewGuid():N}") { ContentType = "text/xml" }); exchange.In.Headers[As4Headers.OriginalSender] = "urn:oasis:names:tc:ebcore:partyid-type:unregistered:C1"; exchange.In.Headers[As4Headers.FinalRecipient] = "urn:oasis:names:tc:ebcore:partyid-type:unregistered:C4"; await producer.Process(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue("Harmony's receipt is signed and names our digests"); var messageId = exchange.In.GetHeader(As4Headers.MessageId)!; using var harmony = await HarmonyClient.LoginAsync(); await harmony.ShouldHaveReceivedAsync(messageId); } [As4LiveFact(HarmonyPort)] public async Task UncompressedXml_IsSignedOverItsCanonicalForm_AndHarmonyVerifiesIt() { // The attachment is signed after Exclusive C14N (SwA 1.1 §5.4.2); raw and canonical bytes differ on purpose. var (context, producer) = await Sender(partner => partner.CompressPayloads = false); await using var _ = context; var exchange = NewExchange("\n\n 42\n\n"); await producer.Process(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); using var harmony = await HarmonyClient.LoginAsync(); await harmony.ShouldHaveReceivedAsync(exchange.In.GetHeader(As4Headers.MessageId)!); } [As4LiveFact(HarmonyPort)] public async Task Redelivery_OfTheSameExchange_IsAcknowledgedAgain_WithTheStoredReceipt() { // A redelivery runs on the same exchange (OnException). Domibus answers the duplicate with the stored receipt of // the first transmission, whose NRR digests only match if the retransmission is the same message. var (context, producer) = await Sender(_ => { }); await using var _ = context; var exchange = NewExchange(""); await producer.Process(exchange); var firstReceipt = exchange.Out!.GetHeader(As4Headers.ReceiptMessageId); await producer.Process(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue("the stored receipt names the digests of the same message"); exchange.Out.GetHeader(As4Headers.ReceiptMessageId).Should().Be(firstReceipt, "Domibus answers a duplicate with the receipt it stored"); } [As4LiveFact(HarmonyPort)] public async Task HarmonySendsToUs_TheDocumentArrives_AndHarmonyAcceptsOurReceipt() { // Harmony calls back one fixed port, shared with the Holodeck inbound test: one test process at a time. await using var exclusive = await As4Stand.ExclusiveAsync("inbound-15090", TimeSpan.FromMinutes(5)); await using var context = new redb.Route.Core.RouteContext(); context.AddComponent(new As4Component()); context.AddIdempotentRepository("dedup", new redb.Route.Processors.InMemoryIdempotentRepository()); context.AddToRegistry("node", Node(partner => { // Domibus' test message is the ebMS 3.0 test service (Ebms3Constants.TEST_SERVICE / TEST_ACTION). partner.Name = "harmony-test"; partner.Service = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/service"; partner.Action = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/test"; })); var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); context.AddRoutes(r => r.From(As4Dsl.Receive("/as4/in").Host("127.0.0.1").Port(InboundPort).ConnectionFactory("node").IdempotentRepository("dedup")) .Process(e => received.TrySetResult(e))); await context.Start(); using var harmony = await HarmonyClient.LoginAsync(); var messageId = await harmony.SendTestMessageAsync(receiver: "redb"); var exchange = await received.Task.WaitAsync(TimeSpan.FromSeconds(90)); exchange.In.GetHeader(As4Headers.MessageId).Should().Be(messageId); exchange.In.GetHeader(As4Headers.Partner).Should().Be("harmony-test"); exchange.In.ContentType.Should().Be("text/xml"); // Domibus marks a sent message ACKNOWLEDGED once it has verified the receipt (signature and NRR). string? status = null; for (var i = 0; i < 60 && status != "ACKNOWLEDGED"; i++) { status = await harmony.StatusAsync(messageId); if (status != "ACKNOWLEDGED") await Task.Delay(TimeSpan.FromSeconds(1)); } status.Should().Be("ACKNOWLEDGED", $"Harmony should accept our receipt for {messageId}"); } [As4LiveTheory(HarmonyPort)] [InlineData(true)] [InlineData(false)] public async Task SeveralPayloads_UnderOurContentIds_AreReceivedByHarmony(bool compress) { // The payload profile of the eDelivery conformance tests: an XML leading document and a non-XML one, each under // the Content-ID the producer chose, with its CharacterSet part property. var (context, producer) = await Sender(partner => partner.CompressPayloads = compress); await using var _ = context; var run = Guid.NewGuid().ToString("N"); var exchange = NewExchange("unused"); exchange.In.Body = new List { new($"xmlpayload-{run}@redb", "application/xml", new MemoryStream(Encoding.UTF8.GetBytes("\n 1\n")), new Dictionary { ["CharacterSet"] = "UTF-8" }), new($"custompayload-{run}@redb", "application/octet-stream", new MemoryStream([0, 1, 2, 3, 250, 251, 252]), new Dictionary()), new(null, "application/octet-stream", new MemoryStream(Encoding.UTF8.GetBytes("third")), new Dictionary()), }; await producer.Process(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue("Harmony's receipt names the digests of every part"); using var harmony = await HarmonyClient.LoginAsync(); await harmony.ShouldHaveReceivedAsync(exchange.In.GetHeader(As4Headers.MessageId)!); } [As4LiveFact(HarmonyPort)] public async Task AMessageWithoutPayloads_IsReceivedByHarmony() { // The Notify command of the conformance tests has no payload: a simple SOAP message, signed, nothing to encrypt. var (context, producer) = await Sender(_ => { }); await using var _ = context; var exchange = NewExchange("unused"); exchange.In.Body = Array.Empty(); await producer.Process(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); using var harmony = await HarmonyClient.LoginAsync(); await harmony.ShouldHaveReceivedAsync(exchange.In.GetHeader(As4Headers.MessageId)!); } [As4LiveFact(HarmonyPort)] public async Task AnEmptyPayload_IsAWholeGzipMember_AndIsReceivedByHarmony() { // From .NET 9 on GZipStream writes nothing for empty content; zero bytes are not gzip to Domibus. var (context, producer) = await Sender(_ => { }); await using var _ = context; var exchange = NewExchange(""); await producer.Process(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); using var harmony = await HarmonyClient.LoginAsync(); await harmony.ShouldHaveReceivedAsync(exchange.In.GetHeader(As4Headers.MessageId)!); } [As4LiveTheory(HarmonyPort)] [InlineData(true, null)] [InlineData(false, "EBMS:0103")] public async Task AnEmptyBodyLeftOutOfTheSignature_IsRefusedByDomibus_AsItsPolicyRequiresTheBodySigned(bool coverBody, string? expectedError) { // What the reference implementation answers to the conformance test "emptyBodyNotReferencedInSignature": its // WS-SecurityPolicy (eDeliveryAS4Policy.xml) lists sp:Body among the signed parts. The same hand-built message // with the body covered is the control: it is received. const string contentId = "p1@redb.test"; var envelope = As4TestMessages.UserMessage(Guid.NewGuid().ToString("N") + "@redb.test", contentId, from: "redb", to: "harmony", agreementRef: "urn:redb:as4:interop", service: "urn:redb:as4:interop", serviceType: "urn:redb:services", action: "StoreMessage"); foreach (System.Xml.XmlElement partyId in envelope.GetElementsByTagName("PartyId", redb.Route.As4.Messaging.EbmsNamespaces.Eb)) partyId.SetAttribute("type", PartyIdType); var message = redb.Route.As4.Mime.SwaMessage.Create(envelope); message.AddPart(contentId, "application/gzip", As4TestMessages.Gzip(Encoding.UTF8.GetBytes(""))); redb.Route.As4.Security.As4Signature.Sign(message, As4Stand.KeyPair("redb"), As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow, coverBody); redb.Route.As4.Security.As4SecurityEngine.Encrypt(message, As4Stand.Certificate("harmony_gw"), As4KeyReference.BinarySecurityToken); var (contentType, body) = message.Write(); using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(60) }; var content = new ByteArrayContent(body); content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(contentType); using var response = await http.PostAsync($"http://127.0.0.1:{HarmonyPort}/services/msh", content); var answerBytes = await response.Content.ReadAsByteArrayAsync(); var answer = redb.Route.As4.Mime.SwaMessage.Read(response.Content.Headers.ContentType!.ToString(), answerBytes, 1024 * 1024); var signals = redb.Route.As4.Messaging.MessagingReader.Read(answer.Envelope).SignalMessages; signals.SelectMany(s => s.Errors).FirstOrDefault()?.ErrorCode.Should().Be(expectedError); signals.Any(s => s.IsReceipt).Should().Be(expectedError is null); } [As4LiveTheory(HarmonyPort)] [InlineData(false)] // Harmony's certificate pinned: its receipt's path token is read for the certificate it is for [InlineData(true)] // Harmony's certificate as the trust anchor: its receipt must come with a path, validated public async Task AMessageSignedWithACertificationPath_IsReceivedByHarmony_UnderItsPkiPathPolicy(bool trustAnAuthority) { // The leg redbPushPkiPath runs under eDeliveryAS4Policy_BST_PKIP.xml: the signing token is an X509PKIPathv1 // BinarySecurityToken in both directions. The stand's certificates are their own authorities: paths of one. var (context, producer) = await Sender(partner => { partner.Action = "StoreMessagePkiPath"; partner.KeyReference = As4KeyReference.PkiPath; if (trustAnAuthority) { partner.PartnerSigningCertificates.Clear(); partner.PartnerTrustAnchors.Add(As4Stand.Certificate("harmony_gw")); } }); await using var _ = context; var exchange = NewExchange($"{Guid.NewGuid():N}"); await producer.Process(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); using var harmony = await HarmonyClient.LoginAsync(); await harmony.ShouldHaveReceivedAsync(exchange.In.GetHeader(As4Headers.MessageId)!); } [As4LiveFact(HarmonyPort)] public async Task APathOfThreeCertificates_RootIssuingAuthoritySigner_IsReadByDomibusInItsOrder() { // The stand's own certificates are their own authorities; this signer is issued under two (keys/pki-root.crt, // pki-issuing.crt), given here out of order. WSS4J takes the signer from the path by its position: a path // written in the wrong order would have Domibus verify the signature with an authority's key. await using var context = new redb.Route.Core.RouteContext(); context.AddComponent(new As4Component()); context.AddToRegistry("node", new As4ConnectionFactory { OurPartyId = "redb_pki", OurPartyIdType = PartyIdType, ExternalHostName = "redb.test", SigningCertificate = As4Stand.KeyPair("redb_pki"), SigningCertificateChain = { As4Stand.Certificate("pki-root"), As4Stand.Certificate("pki-issuing") }, DecryptionCertificates = { As4Stand.KeyPair("redb_pki") }, Partners = { new As4Partner { Name = "harmony", PartyId = "harmony", PartyIdType = PartyIdType, AgreementRef = "urn:redb:as4:interop", Service = "urn:redb:as4:interop", ServiceType = "urn:redb:services", Action = "StoreMessagePkiPath", KeyReference = As4KeyReference.PkiPath, PartnerTrustAnchors = { As4Stand.Certificate("harmony_gw") }, PartnerEncryptionCertificate = As4Stand.Certificate("harmony_gw"), }, }, }); var producer = context.GetEndpoint(As4Dsl.Send($"http://127.0.0.1:{HarmonyPort}/services/msh") .ConnectionFactory("node").Partner("harmony").Timeout(60000)).CreateProducer(); await producer.Start(); var exchange = NewExchange($"{Guid.NewGuid():N}"); await producer.Process(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); using var harmony = await HarmonyClient.LoginAsync(); await harmony.ShouldHaveReceivedAsync(exchange.In.GetHeader(As4Headers.MessageId)!); } // ── Fixtures ───────────────────────────────────────────────────────────── private static async Task<(redb.Route.Core.RouteContext Context, redb.Route.Abstractions.IProducer Producer)> Sender(Action configure) { var context = new redb.Route.Core.RouteContext(); context.AddComponent(new As4Component()); context.AddToRegistry("node", Node(partner => { partner.Name = "harmony"; partner.Service = "urn:redb:as4:interop"; partner.ServiceType = "urn:redb:services"; partner.Action = "StoreMessage"; configure(partner); })); var producer = context.GetEndpoint(As4Dsl.Send($"http://127.0.0.1:{HarmonyPort}/services/msh") .ConnectionFactory("node").Partner("harmony").Timeout(60000)).CreateProducer(); await producer.Start(); return (context, producer); } private static redb.Route.Core.Exchange NewExchange(string xml) { var exchange = new redb.Route.Core.Exchange(new redb.Route.Core.Message(xml) { ContentType = "text/xml" }); exchange.In.Headers[As4Headers.OriginalSender] = "urn:oasis:names:tc:ebcore:partyid-type:unregistered:C1"; exchange.In.Headers[As4Headers.FinalRecipient] = "urn:oasis:names:tc:ebcore:partyid-type:unregistered:C4"; return exchange; } private static As4ConnectionFactory Node(Action configure) { var partner = new As4Partner { PartyId = "harmony", PartyIdType = PartyIdType, AgreementRef = "urn:redb:as4:interop", PartnerSigningCertificates = { As4Stand.Certificate("harmony_gw") }, PartnerEncryptionCertificate = As4Stand.Certificate("harmony_gw"), }; configure(partner); return new As4ConnectionFactory { OurPartyId = "redb", OurPartyIdType = PartyIdType, ExternalHostName = "redb.test", SigningCertificate = As4Stand.KeyPair("redb"), DecryptionCertificates = { As4Stand.KeyPair("redb") }, Partners = { partner }, }; } /// The admin REST API of the Harmony stand (Domibus /rest): session cookie plus the XSRF header. private sealed class HarmonyClient : IDisposable { private readonly CookieContainer _cookies = new(); private readonly HttpClient _http; private HarmonyClient() { _http = new HttpClient(new HttpClientHandler { CookieContainer = _cookies }) { BaseAddress = new Uri($"http://127.0.0.1:{HarmonyPort}/"), Timeout = TimeSpan.FromSeconds(60), }; } public static async Task LoginAsync() { var client = new HarmonyClient(); (await client._http.GetAsync("")).EnsureSuccessStatusCode(); // issues the XSRF cookie using var login = await client.PostJsonAsync("rest/security/authentication", new { username = "harmony", password = "teststand" }); login.EnsureSuccessStatusCode(); return client; } public async Task SendTestMessageAsync(string receiver) { using var response = await PostJsonAsync("rest/testservice", new { sender = "harmony", receiver, receiverType = PartyIdType }); var body = await response.Content.ReadAsStringAsync(); response.IsSuccessStatusCode.Should().BeTrue($"Harmony refused the test message: {body}"); return Json(body).GetString()!; } /// /// The message's status in Domibus' message log, or null when it has no row. Domibus may answer with the receipt /// before the row is visible to its REST API, so an absent row is polled for up to five seconds. /// public async Task StatusAsync(string messageId) { for (var attempt = 0; ; attempt++) { var body = await _http.GetStringAsync($"rest/messagelog?messageId={Uri.EscapeDataString(messageId)}&page=0&pageSize=10&fields=messageId&fields=messageStatus"); var messages = Json(body).GetProperty("messageLogEntries"); if (messages.GetArrayLength() > 0) return messages[0].GetProperty("messageStatus").GetString(); if (attempt == 20) return null; await Task.Delay(TimeSpan.FromMilliseconds(250)); } } /// /// Asserts that Domibus logged as received. The failure names the message id, so the /// message can be looked up in Harmony's log afterwards. /// public async Task ShouldHaveReceivedAsync(string messageId) => (await StatusAsync(messageId)).Should().Be("RECEIVED", $"Harmony's message log should hold {messageId} as received"); private async Task PostJsonAsync(string path, object body) { var request = new HttpRequestMessage(HttpMethod.Post, path) { Content = JsonContent.Create(body) }; var xsrf = _cookies.GetCookies(_http.BaseAddress!)["XSRF-TOKEN"]?.Value; if (xsrf is not null) request.Headers.Add("X-XSRF-TOKEN", xsrf); return await _http.SendAsync(request); } /// Domibus prefixes JSON with the anti-JSON-hijacking line )]}',. private static JsonElement Json(string body) => JsonDocument.Parse(body.StartsWith(")]}'", StringComparison.Ordinal) ? body[(body.IndexOf('\n') + 1)..] : body).RootElement; public void Dispose() => _http.Dispose(); } } Path: redb-route/tests/redb.Route.Tests.As4/As4HolodeckLiveTests.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/tests/redb.Route.Tests.As4/As4HolodeckLiveTests.cs ---- using System.Net.Http.Headers; using System.Text; using System.Xml; using redb.Route.As4; using redb.Route.As4.Mime; using redb.Route.As4.Security; using redb.Route.Components; namespace redb.Route.Tests.As4; /// /// Live: a message signed and encrypted by us is accepted by Holodeck B2B node B (P-Mode /// redb-interop-push, through the recorder on port 14091), which answers with a receipt we verify — /// its signature, and that its non-repudiation references are exactly the ones we signed. /// public class As4HolodeckLiveTests { private const int RecorderPort = 14091; [As4LiveTheory(RecorderPort)] [InlineData(As4KeyReference.BinarySecurityToken)] [InlineData(As4KeyReference.IssuerSerial)] [InlineData(As4KeyReference.KeyIdentifier)] public async Task OurSignedEncryptedMessage_IsAcceptedByHolodeck_WithAVerifiedReceipt(As4KeyReference form) { var messageId = Guid.NewGuid().ToString("N") + "@redb.test"; const string contentId = "payload-1@redb.test"; var payload = Encoding.UTF8.GetBytes($"{messageId}"); var envelope = As4TestMessages.UserMessage(messageId, contentId, from: "urn:redb:as4:test:redb", to: "org:holodeckb2b:example:company:B", agreementRef: "urn:redb:as4:interop", service: "urn:redb:as4:interop", serviceType: "org:holodeckb2b:services", action: "StoreMessage"); var message = SwaMessage.Create(envelope); message.AddPart(contentId, "application/gzip", As4TestMessages.Gzip(payload)); var sent = As4SecurityEngine.Sign(message, As4Stand.KeyPair("redb"), form, TimeSpan.FromMinutes(5), DateTimeOffset.UtcNow); As4SecurityEngine.Encrypt(message, As4Stand.Certificate("holodeck-b"), form); var (contentType, body) = message.Write(); using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(60) }; using var content = new ByteArrayContent(body); content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType); using var response = await http.PostAsync($"http://127.0.0.1:{RecorderPort}/holodeckb2b/as4", content); var responseBody = await response.Content.ReadAsByteArrayAsync(); var responseType = response.Content.Headers.ContentType?.ToString() ?? throw new InvalidOperationException($"Holodeck answered HTTP {(int)response.StatusCode} without a Content-Type."); var answer = SwaMessage.Read(responseType, responseBody, 1024 * 1024); var error = answer.Envelope.GetElementsByTagName("Error", WsSecurityNames.Eb).OfType().FirstOrDefault(); error.Should().BeNull($"Holodeck answered with an ebMS error: {error?.OuterXml}"); var verification = As4SecurityEngine.Verify(answer, [As4Stand.Certificate("holodeck-b")], TimeSpan.FromMinutes(5), DateTimeOffset.UtcNow); verification.Signer.Thumbprint.Should().Be(As4Stand.Certificate("holodeck-b").Thumbprint); answer.Envelope.GetElementsByTagName("RefToMessageId", WsSecurityNames.Eb)[0]!.InnerText.Should().Be(messageId); var echoed = answer.Envelope.GetElementsByTagName("MessagePartNRInformation", "http://docs.oasis-open.org/ebxml-bp/ebbp-signals-2.0") .OfType() .Select(e => (XmlElement)e.GetElementsByTagName("Reference", WsSecurityNames.Ds)[0]!) .Select(Digest) .ToList(); echoed.Should().BeEquivalentTo(sent.Select(Digest)); } /// /// An uncompressed text payload is signed over its MIME canonical form (SwA 1.1 §5.4.2) — Exclusive C14N for /// XML, CRLF line endings for other text. The payloads are chosen so that canonical and raw bytes differ. /// [As4LiveTheory(RecorderPort)] [InlineData("text/xml", "\n\n 42\n\n")] [InlineData("application/xml", "")] [InlineData("text/plain", "line one\nline two\n")] public async Task UncompressedTextPayload_IsSignedOverItsCanonicalForm_AndAcceptedByHolodeck(string mimeType, string text) { var messageId = Guid.NewGuid().ToString("N") + "@redb.test"; const string contentId = "payload-1@redb.test"; var envelope = As4TestMessages.UserMessage(messageId, contentId, from: "urn:redb:as4:test:redb", to: "org:holodeckb2b:example:company:B", agreementRef: "urn:redb:as4:interop", service: "urn:redb:as4:interop", serviceType: "org:holodeckb2b:services", action: "StoreMessage", uncompressedMimeType: mimeType); var message = SwaMessage.Create(envelope); message.AddPart(contentId, mimeType, Encoding.UTF8.GetBytes(text)); As4SecurityEngine.Sign(message, As4Stand.KeyPair("redb"), As4KeyReference.BinarySecurityToken, TimeSpan.FromMinutes(5), DateTimeOffset.UtcNow); As4SecurityEngine.Encrypt(message, As4Stand.Certificate("holodeck-b"), As4KeyReference.BinarySecurityToken); var (contentType, body) = message.Write(); using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(60) }; using var content = new ByteArrayContent(body); content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType); using var response = await http.PostAsync($"http://127.0.0.1:{RecorderPort}/holodeckb2b/as4", content); var answer = SwaMessage.Read(response.Content.Headers.ContentType!.ToString(), await response.Content.ReadAsByteArrayAsync(), 1024 * 1024); var error = answer.Envelope.GetElementsByTagName("Error", WsSecurityNames.Eb).OfType().FirstOrDefault(); error.Should().BeNull($"Holodeck answered with an ebMS error: {error?.OuterXml}"); answer.Envelope.GetElementsByTagName("Receipt", WsSecurityNames.Eb).Count.Should().Be(1); } [As4LiveFact(RecorderPort)] public async Task Producer_SendsToHolodeck_AndVerifiesItsReceipt() { await using var context = new redb.Route.Core.RouteContext(); context.AddComponent(new As4Component()); context.AddIdempotentRepository("dedup", new redb.Route.Processors.InMemoryIdempotentRepository()); context.AddToRegistry("node", new As4ConnectionFactory { OurPartyId = "urn:redb:as4:test:redb", ExternalHostName = "redb.test", SigningCertificate = As4Stand.KeyPair("redb"), DecryptionCertificates = { As4Stand.KeyPair("redb") }, Partners = { new As4Partner { Name = "holodeck-b", PartyId = "org:holodeckb2b:example:company:B", AgreementRef = "urn:redb:as4:interop", Service = "urn:redb:as4:interop", ServiceType = "org:holodeckb2b:services", Action = "StoreMessage", PartnerSigningCertificates = { As4Stand.Certificate("holodeck-b") }, PartnerEncryptionCertificate = As4Stand.Certificate("holodeck-b"), }, }, }); var producer = context.GetEndpoint( redb.Route.As4.Fluent.As4.Send($"http://127.0.0.1:{RecorderPort}/holodeckb2b/as4").ConnectionFactory("node").Partner("holodeck-b")) .CreateProducer(); await producer.Start(); var payload = $"{Guid.NewGuid():N}"; var exchange = new redb.Route.Core.Exchange(new redb.Route.Core.Message(payload) { ContentType = "text/xml" }); exchange.In.Headers[As4Headers.OriginalSender] = "urn:oasis:names:tc:ebcore:partyid-type:unregistered:C1"; exchange.In.Headers[As4Headers.FinalRecipient] = "urn:oasis:names:tc:ebcore:partyid-type:unregistered:C4"; await producer.Process(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); Directory.GetFiles(Path.Combine(As4Stand.Root, "node-b", "data", "msg_in"), "pl-*") .Select(As4Stand.ReadShared) .Should().Contain(payload, "node B delivers the decrypted, decompressed payload"); } private const int HolodeckAPort = 14090; private const int InboundPort = 15090; // node A's P-Mode redb-inbound-push posts to host.docker.internal:15090/as4/in [As4LiveFact(HolodeckAPort)] public async Task HolodeckPushesToOurReceiver_ThePayloadArrives_AndHolodeckAcceptsOurReceipt() { // Node A calls back one fixed port: one test process at a time. await using var exclusive = await As4Stand.ExclusiveAsync("inbound-15090", TimeSpan.FromMinutes(5)); await using var context = new redb.Route.Core.RouteContext(); context.AddComponent(new As4Component()); context.AddIdempotentRepository("dedup", new redb.Route.Processors.InMemoryIdempotentRepository()); context.AddToRegistry("node", new As4ConnectionFactory { OurPartyId = "urn:redb:as4:test:redb", ExternalHostName = "redb.test", SigningCertificate = As4Stand.KeyPair("redb"), DecryptionCertificates = { As4Stand.KeyPair("redb") }, Partners = { new As4Partner { Name = "holodeck-a", PartyId = "org:holodeckb2b:example:company:A", AgreementRef = "urn:redb:as4:inbound", Service = "urn:redb:as4:inbound", ServiceType = "org:holodeckb2b:services", Action = "StoreMessage", PartnerSigningCertificates = { As4Stand.Certificate("holodeck-a") }, PartnerEncryptionCertificate = As4Stand.Certificate("holodeck-a"), }, }, }); var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); context.AddRoutes(r => r.From(redb.Route.As4.Fluent.As4.Receive("/as4/in").Host("0.0.0.0").Port(InboundPort).ConnectionFactory("node").IdempotentRepository("dedup")) .Process(e => received.TrySetResult(e))); await context.Start(); // Submit on node A: a payload file and its message metadata in data/msg_out. var marker = Guid.NewGuid().ToString("N"); var payload = $"{marker}"; var outbox = Path.Combine(As4Stand.Root, "data", "msg_out"); await File.WriteAllTextAsync(Path.Combine(outbox, $"in-{marker}.xml"), payload); await File.WriteAllTextAsync(Path.Combine(outbox, $"in-{marker}.mmd"), $""" urn:redb:as4:inbound:{marker} urn:oasis:names:tc:ebcore:partyid-type:unregistered:C1 urn:oasis:names:tc:ebcore:partyid-type:unregistered:C4 """); var exchange = await received.Task.WaitAsync(TimeSpan.FromSeconds(90)); Encoding.UTF8.GetString((byte[])exchange.In.Body!).Should().Be(payload); exchange.In.GetHeader(As4Headers.Partner).Should().Be("holodeck-a"); var messageId = exchange.In.GetHeader(As4Headers.MessageId)!; // Node A notifies its back end of a receipt only after it verified it (signature and NRR). var inbox = Path.Combine(As4Stand.Root, "data", "msg_in"); var accepted = false; for (var i = 0; i < 60 && !accepted; i++) { accepted = Directory.GetFiles(inbox, "mi-*.xml") .Any(f => As4Stand.ReadShared(f).Contains($"RefToMessageId>{messageId}<", StringComparison.Ordinal)); if (!accepted) await Task.Delay(TimeSpan.FromSeconds(1)); } accepted.Should().BeTrue($"Holodeck A should accept our receipt for {messageId}"); } private static (string Uri, string Digest) Digest(XmlElement reference) => (reference.GetAttribute("URI"), reference.GetElementsByTagName("DigestValue", WsSecurityNames.Ds)[0]!.InnerText); } Path: redb-route/tests/redb.Route.Tests.As4/As4HolodeckReferenceTests.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/tests/redb.Route.Tests.As4/As4HolodeckReferenceTests.cs ---- using System.IO.Compression; using System.Security.Cryptography; using System.Xml; using redb.Route.As4.Mime; using redb.Route.As4.Security; namespace redb.Route.Tests.As4; /// /// A real message from Holodeck B2B 8.1.1 (capture push-signed-encrypted-gzip) decrypts and verifies /// on .NET — the SwA attachment signature, BST references, RSA-OAEP with MGF1-SHA256 and AES-128-GCM, as the /// eDelivery AS4 1.16 common profile has them. Every tampering is refused. /// public class As4HolodeckReferenceTests { private const string Capture = "push-signed-encrypted-gzip"; private const string Needs = "captures/" + Capture; private static readonly TimeSpan Tolerance = TimeSpan.FromMinutes(5); private static SwaMessage Request() => Load("request"); private static SwaMessage Load(string side) { var (body, contentType) = As4Stand.Capture(Capture, side); return SwaMessage.Read(contentType, body, maxEnvelopeCharacters: 1024 * 1024); } [As4StandFact(Needs)] public void Receipt_VerifiesWithTheResponderKey_AndEchoesTheRequestReferences() { var request = Request(); As4SecurityEngine.Decrypt(request, [As4Stand.KeyPair("holodeck-b")]); var sent = As4SecurityEngine.Verify(request, [As4Stand.Certificate("holodeck-a")], Tolerance, DateTimeOffset.UtcNow); var receipt = Load("response"); var verification = As4SecurityEngine.Verify(receipt, [As4Stand.Certificate("holodeck-b")], Tolerance, DateTimeOffset.UtcNow); verification.Signer.Thumbprint.Should().Be(As4Stand.Certificate("holodeck-b").Thumbprint); var echoed = receipt.Envelope.GetElementsByTagName("MessagePartNRInformation", "http://docs.oasis-open.org/ebxml-bp/ebbp-signals-2.0") .OfType() .Select(e => (XmlElement)e.GetElementsByTagName("Reference", WsSecurityNames.Ds)[0]!) .Select(r => (r.GetAttribute("URI"), r.GetElementsByTagName("DigestValue", WsSecurityNames.Ds)[0]!.InnerText)) .ToList(); var original = sent.References .Select(r => (r.GetAttribute("URI"), r.GetElementsByTagName("DigestValue", WsSecurityNames.Ds)[0]!.InnerText)) .ToList(); echoed.Should().BeEquivalentTo(original); } [As4StandFact(Needs)] public void Request_Parses_EnvelopeAndOneAttachment() { var message = Request(); message.Parts.Should().HaveCount(1); message.Parts.Values.Single().ContentType.Should().Be("application/octet-stream"); message.Envelope.GetElementsByTagName("Messaging", WsSecurityNames.Eb).Count.Should().Be(1); } [As4StandFact(Needs)] public void Request_Decrypts_VerifiesAndDecompresses_ToTheOriginalPayload() { var message = Request(); var decrypted = As4SecurityEngine.Decrypt(message, [As4Stand.KeyPair("holodeck-b")]); var verification = As4SecurityEngine.Verify(message, [As4Stand.Certificate("holodeck-a")], Tolerance, DateTimeOffset.UtcNow); decrypted.Should().HaveCount(1); var part = message.Parts[decrypted[0]]; part.ContentType.Should().Be("application/gzip"); verification.Signer.Thumbprint.Should().Be(As4Stand.Certificate("holodeck-a").Thumbprint); verification.References.Should().HaveCount(3); Gunzip(part.ToArray()).Should().Equal(As4Stand.CaptureFile(Capture, "payload.xml")); } [As4StandFact(Needs)] public void Request_Decrypts_AndDecompresses_ToTheOriginalPayload() { var message = Request(); var decrypted = As4SecurityEngine.Decrypt(message, [As4Stand.KeyPair("holodeck-b")]); decrypted.Should().HaveCount(1); var part = message.Parts[decrypted[0]]; part.ContentType.Should().Be("application/gzip"); Gunzip(part.ToArray()).Should().Equal(As4Stand.CaptureFile(Capture, "payload.xml")); } [As4StandFact(Needs)] public void Decrypt_WithSomeoneElsesKey_IsRefused() { var message = Request(); var act = () => As4SecurityEngine.Decrypt(message, [As4Stand.KeyPair("redb")]); act.Should().Throw(); } [As4StandFact(Needs)] public void Decrypt_TamperedCiphertext_IsRefused() { var message = Request(); As4TestMessages.Flip(message.Parts.Values.Single(), 40); var act = () => As4SecurityEngine.Decrypt(message, [As4Stand.KeyPair("holodeck-b")]); act.Should().Throw(); } [As4StandFact(Needs)] public void Verify_TamperedMessagingHeader_IsRefused() { var message = Request(); As4SecurityEngine.Decrypt(message, [As4Stand.KeyPair("holodeck-b")]); var action = (XmlElement)message.Envelope.GetElementsByTagName("Action", WsSecurityNames.Eb)[0]!; action.InnerText = "SomethingElse"; var act = () => As4SecurityEngine.Verify(message, [As4Stand.Certificate("holodeck-a")], Tolerance, DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*digest of*does not match*"); } [As4StandFact(Needs)] public void Verify_TamperedAttachment_IsRefused() { var message = Request(); As4SecurityEngine.Decrypt(message, [As4Stand.KeyPair("holodeck-b")]); As4TestMessages.Flip(message.Parts.Values.Single(), 5); var act = () => As4SecurityEngine.Verify(message, [As4Stand.Certificate("holodeck-a")], Tolerance, DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*digest of 'cid:*does not match*"); } [As4StandFact(Needs)] public void Verify_SignerIsNotThePartner_IsRefused() { var message = Request(); As4SecurityEngine.Decrypt(message, [As4Stand.KeyPair("holodeck-b")]); var act = () => As4SecurityEngine.Verify(message, [As4Stand.Certificate("redb")], Tolerance, DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*not one of the partner's*"); } [As4StandFact(Needs)] public void Verify_DuplicateIdOfTheSignedHeader_IsRefused() { var message = Request(); As4SecurityEngine.Decrypt(message, [As4Stand.KeyPair("holodeck-b")]); // Signature wrapping: a second element with the id of the signed eb:Messaging. var messaging = (XmlElement)message.Envelope.GetElementsByTagName("Messaging", WsSecurityNames.Eb)[0]!; var body = (XmlElement)message.Envelope.GetElementsByTagName("Body", WsSecurityNames.Soap12)[0]!; body.AppendChild(messaging.CloneNode(deep: true)); var act = () => As4SecurityEngine.Verify(message, [As4Stand.Certificate("holodeck-a")], Tolerance, DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*Two elements carry the id*"); } [As4StandFact(Needs)] public void Verify_WithoutDecrypting_IsRefused() { // The attachment signature is over the plaintext: ciphertext must not verify. var message = Request(); var act = () => As4SecurityEngine.Verify(message, [As4Stand.Certificate("holodeck-a")], Tolerance, DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*digest of 'cid:*does not match*"); } private static byte[] Gunzip(byte[] data) { using var input = new GZipStream(new MemoryStream(data), CompressionMode.Decompress); using var output = new MemoryStream(); input.CopyTo(output); return output.ToArray(); } } Path: redb-route/tests/redb.Route.Tests.As4/As4MessagingTests.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/tests/redb.Route.Tests.As4/As4MessagingTests.cs ---- using System.Text; using System.Xml; using redb.Route.As4; using redb.Route.As4.Compression; using redb.Route.As4.Messaging; using redb.Route.As4.Mime; using redb.Route.Core; namespace redb.Route.Tests.As4; /// /// The ebMS header model — written and read back, read from real Holodeck output, and refused with /// EBMS:0009 and a path for every structural violation; AS4 compression; payload/part consistency. /// public class As4MessagingTests { private static readonly redb.Route.Configuration.StreamCacheOptions Spool = new(); private static UserMessage SampleUserMessage(params PartInfo[] parts) => new( new MessageInfo(new DateTimeOffset(2026, 9, 25, 12, 0, 0, TimeSpan.Zero), "m-1@redb.test", null), new Party([new PartyId("urn:redb:sender", "urn:oasis:names:tc:ebcore:partyid-type:unregistered")], As4Partner.InitiatorRole), new Party([new PartyId("urn:redb:receiver", null)], As4Partner.ResponderRole), new CollaborationInfo(new AgreementRef("urn:agreement", null, "pm-1"), new Service("urn:service", "urn:types"), "Submit", "c-1"), [new Property("originalSender", "C1", null), new Property("finalRecipient", "C4", null)], parts, null); // ── Round trip ─────────────────────────────────────────────────────────── [Fact] public void UserMessage_WrittenAndRead_IsTheSame() { var original = SampleUserMessage(new PartInfo("cid:p1@redb.test", [new Property("MimeType", "text/xml", null), new Property("CompressionType", "application/gzip", null)])); var read = MessagingReader.Read(Reparse(MessagingWriter.CreateEnvelope(original))); read.SignalMessages.Should().BeEmpty(); read.UserMessages.Should().ContainSingle().Which.Should().BeEquivalentTo(original); } [Fact] public void ErrorSignal_WrittenAndRead_IsTheSame() { var error = new EbmsError("EBMS:0004", As4ErrorSeverity.Failure, "Content", "ebms", "m-1@redb.test", "Other", "The message could not be processed.", "ref: 42"); var signal = new SignalMessage(new MessageInfo(DateTimeOffset.UtcNow, "s-1@redb.test", "m-1@redb.test"), null, [error], null); var read = MessagingReader.Read(Reparse(MessagingWriter.CreateEnvelope(signal))); var errors = read.SignalMessages.Should().ContainSingle().Which.Errors; errors.Should().ContainSingle().Which.Should().BeEquivalentTo(error); } [Fact] public void Envelope_DeclaresItsNamespaces_OnTheRoot() { var doc = MessagingWriter.CreateEnvelope(SampleUserMessage()); doc.DocumentElement!.GetAttribute("xmlns:soapenv").Should().Be(EbmsNamespaces.Soap12); doc.DocumentElement.GetAttribute("xmlns:eb").Should().Be(EbmsNamespaces.Eb); } [Fact] public void MessageIdFactory_UsesTheGivenHost_AndIsUnique() { var a = MessageIdFactory.New("ap.example"); var b = MessageIdFactory.New("ap.example"); a.Should().EndWith("@ap.example").And.NotBe(b); a.Should().NotContain("<").And.NotContain(">"); } // ── Holodeck output ────────────────────────────────────────────────────── [Fact] public void HolodeckError_WithOddPrefixes_IsRead() { // Holodeck 8.1.1 answer to an unknown agreement (probe 2026-09-23): eb3 prefix, mustUnderstand in a // namespace declared under the prefix "mustUnderstand", the reason in eb:ErrorDetail. const string xml = """ 2026-09-23T20:31:10.574Zd049e8f4@3062a5da4fb4probe-1@redbCan not process message because no P-Mode was found for the message! """; var signal = MessagingReader.Read(Load(xml)).SignalMessages.Single(); signal.MessageInfo.RefToMessageId.Should().Be("probe-1@redb"); var error = signal.Errors.Single(); error.ErrorCode.Should().Be("EBMS:0010"); error.Severity.Should().Be(As4ErrorSeverity.Failure); error.ErrorDetail.Should().StartWith("Can not process message"); As4ErrorCode.Find(error.ErrorCode).Should().Be(As4ErrorCode.ProcessingModeMismatch); } [As4StandFact("captures/push-signed-encrypted-gzip")] public void HolodeckRequestAndReceipt_AreRead() { var (requestBody, requestType) = As4Stand.Capture("push-signed-encrypted-gzip", "request"); var request = MessagingReader.Read(SwaMessage.Read(requestType, requestBody, 1024 * 1024).Envelope); var (responseBody, responseType) = As4Stand.Capture("push-signed-encrypted-gzip", "response"); var response = MessagingReader.Read(SwaMessage.Read(responseType, responseBody, 1024 * 1024).Envelope); var user = request.UserMessages.Single(); user.From.PartyIds.Single().Value.Should().Be("org:holodeckb2b:example:company:A"); user.CollaborationInfo.Action.Should().Be("StoreMessage"); user.PropertyValue("originalSender").Should().NotBeNull(); user.PayloadInfo.Single().PropertyValue("CompressionType").Should().Be("application/gzip"); var receipt = response.SignalMessages.Single(); receipt.IsReceipt.Should().BeTrue(); receipt.MessageInfo.RefToMessageId.Should().Be(user.MessageInfo.MessageId); receipt.ReceiptContent!.Single().LocalName.Should().Be("NonRepudiationInformation"); } // ── Structural violations → EBMS:0009 ──────────────────────────────────── [Theory] [InlineData("Submit", "", "*Action is missing*")] [InlineData("c-1", "c-1c-2", "*ConversationId appears more than once*")] [InlineData("2026-09-25T12:00:00.000Z", "yesterday", "*Timestamp*not an xsd:dateTime*")] [InlineData("m-1@redb.test", " ", "*MessageId*is empty*")] [InlineData("Submit", "Submit", "*unexpected element*Extra*")] [InlineData("C4", "again", "*property 'originalSender' appears more than once*")] public void MalformedHeader_IsInvalidHeader_WithThePath(string find, string replace, string message) { var xml = MessagingWriter.CreateEnvelope(SampleUserMessage()).OuterXml; xml.Should().Contain(find, "the fixture must contain the element the case edits"); var act = () => MessagingReader.Read(Load(xml.Replace(find, replace))); act.Should().Throw() .Where(e => e.Code == As4ErrorCode.InvalidHeader) .WithMessage(message); } [Fact] public void RepeatedPartProperty_IsInvalidHeader() { // A part property named twice reaches no route: the payload list keys part properties by name. var xml = MessagingWriter.CreateEnvelope(SampleUserMessage(new PartInfo("cid:p1@redb.test", [new Property("MimeType", "text/xml", null), new Property("CharacterSet", "UTF-8", null)]))).OuterXml; const string find = "UTF-8"; xml.Should().Contain(find); var act = () => MessagingReader.Read(Load(xml.Replace(find, find + "ISO-8859-1"))); act.Should().Throw() .Where(e => e.Code == As4ErrorCode.InvalidHeader) .WithMessage("*PartProperties*property 'CharacterSet' appears more than once*"); } [Fact] public void TwoUserMessages_AreInvalid() { var xml = MessagingWriter.CreateEnvelope(SampleUserMessage()).OuterXml; var user = xml[xml.IndexOf("", StringComparison.Ordinal) + "".Length)]; var act = () => MessagingReader.Read(Load(xml.Replace(user, user + user))); act.Should().Throw().WithMessage("*more than one user message*"); } [Fact] public void MessagingOutsideTheHeader_IsNotTheHeader() { var xml = MessagingWriter.CreateEnvelope(SampleUserMessage()).OuterXml; var start = xml.IndexOf("", StringComparison.Ordinal) + "".Length; var moved = xml.Remove(start, end - start).Replace("", "" + xml[start..end] + ""); var act = () => MessagingReader.Read(Load(moved)); act.Should().Throw().WithMessage("*Messaging is missing*"); } // ── Compression ────────────────────────────────────────────────────────── [Fact] public void Compression_RoundTrip_RestoresContentAndType() { var payload = Encoding.UTF8.GetBytes(new string('x', 10_000)); var part = new SwaPart("p1", "text/xml", payload); var properties = As4Compression.Compress(part, Spool); part.ContentType.Should().Be("application/gzip"); part.Length.Should().BeLessThan(payload.Length); As4Compression.Decompress(part, new PartInfo("cid:p1", properties), maxDecompressedBytes: 1_000_000, Spool).Should().BeTrue(); part.ToArray().Should().Equal(payload); part.ContentType.Should().Be("text/xml"); } [Fact] public void Decompression_BeyondTheLimit_IsDecompressionFailure() { var part = new SwaPart("p1", "text/plain", new byte[5_000_000]); // zeros compress to almost nothing var properties = As4Compression.Compress(part, Spool); var act = () => As4Compression.Decompress(part, new PartInfo("cid:p1", properties), maxDecompressedBytes: 1_000_000, Spool); act.Should().Throw().Where(e => e.Code == As4ErrorCode.DecompressionFailure); } [Fact] public void Decompression_OfNotGzip_IsDecompressionFailure() { var part = new SwaPart("p1", "application/gzip", [1, 2, 3, 4, 5]); var info = new PartInfo("cid:p1", [new Property("MimeType", "text/xml", null), new Property("CompressionType", "application/gzip", null)]); var act = () => As4Compression.Decompress(part, info, 1_000_000, Spool); act.Should().Throw().Where(e => e.Code == As4ErrorCode.DecompressionFailure); } [Theory] [InlineData("half")] // stops in the middle of the deflate stream [InlineData("no trailer")] // everything but the CRC-32 and the length [InlineData("half a trailer")] [InlineData("header only")] [InlineData("nothing")] [InlineData("garbage after the header")] public void Decompression_OfTruncatedOrDamagedGzip_IsDecompressionFailure(string damage) { // GZipStream inflates each of these without an exception, to a part of the document or to nothing. var whole = As4TestMessages.Gzip(System.Text.Encoding.UTF8.GetBytes(string.Concat(Enumerable.Repeat("42", 40)))); var bytes = damage switch { "half" => whole[..(whole.Length / 2)], "no trailer" => whole[..^8], "half a trailer" => whole[..^4], "header only" => whole[..10], "nothing" => [], _ => [.. whole[..10], .. Enumerable.Repeat((byte)0x5A, whole.Length - 10)], }; var part = new SwaPart("p1", "application/gzip", bytes); var info = new PartInfo("cid:p1", [new Property("MimeType", "text/xml", null), new Property("CompressionType", "application/gzip", null)]); var act = () => As4Compression.Decompress(part, info, 1_000_000, Spool); act.Should().Throw().Where(e => e.Code == As4ErrorCode.DecompressionFailure); } [Theory] [InlineData(0)] [InlineData(1)] [InlineData(200_000)] // more than one read buffer public void Decompression_OfAWholeGzip_ChecksItsTrailer_AndRestoresTheContent(int length) { var content = new byte[length]; new Random(length).NextBytes(content); var part = new SwaPart("p1", "application/octet-stream", content); var info = new PartInfo("cid:p1", As4Compression.Compress(part, Spool)); As4Compression.Decompress(part, info, 1_000_000, Spool).Should().BeTrue(); part.ToArray().Should().Equal(content); } [Theory] [InlineData("whole", true)] [InlineData("an empty member between", true)] [InlineData("a header with name, comment, extra and crc", true)] [InlineData("last member cut", false)] [InlineData("last member without its trailer", false)] [InlineData("first member's crc wrong", false)] [InlineData("bytes after the last member", false)] public void Decompression_OfSeveralGzipMembers_IsWalkedMemberByMember(string shape, bool whole) { // RFC 1952 §2.2: a gzip file is a series of members. GZipStream inflates them all; only a walk over the members // tells a whole stream from one that stops inside its last member. static byte[] Member(string text) => WholeGzip(System.Text.Encoding.UTF8.GetBytes(text)); var first = Member(string.Concat(Enumerable.Repeat("first ", 2000))); var second = Member(string.Concat(Enumerable.Repeat("second ", 3000))); var expected = string.Concat(Enumerable.Repeat("first ", 2000)) + string.Concat(Enumerable.Repeat("second ", 3000)); byte[] bytes = shape switch { "whole" => [.. first, .. second], "an empty member between" => [.. first, .. WholeGzip([]), .. second], "a header with name, comment, extra and crc" => [.. WithOptionalHeaderFields(first), .. second], "last member cut" => [.. first, .. second[..(second.Length / 2)]], "last member without its trailer" => [.. first, .. second[..^8]], "first member's crc wrong" => [.. first[..^8], (byte)(first[^8] ^ 0xFF), .. first[^7..], .. second], _ => [.. first, .. second, 0x00, 0x01, 0x02], }; var part = new SwaPart("p1", "application/gzip", bytes); var info = new PartInfo("cid:p1", [new Property("MimeType", "text/plain", null), new Property("CompressionType", "application/gzip", null)]); if (whole) { As4Compression.Decompress(part, info, 1_000_000, Spool).Should().BeTrue(); System.Text.Encoding.UTF8.GetString(part.ToArray()).Should().Be(expected); } else { var act = () => As4Compression.Decompress(part, info, 1_000_000, Spool); act.Should().Throw().Where(e => e.Code == As4ErrorCode.DecompressionFailure); } } /// A whole gzip member of , also for empty content on every runtime. private static byte[] WholeGzip(byte[] content) { var part = new SwaPart("m", "application/octet-stream", content); As4Compression.Compress(part, Spool); return part.ToArray(); } /// The member with FEXTRA, FNAME, FCOMMENT and FHCRC set in its header (RFC 1952 §2.3.1). private static byte[] WithOptionalHeaderFields(byte[] member) { var header = member[..10]; header[3] = 0x02 | 0x04 | 0x08 | 0x10; byte[] extra = [3, 0, (byte)'a', (byte)'b', (byte)'c']; // XLEN = 3, then three bytes byte[] name = [(byte)'f', (byte)'.', (byte)'x', 0]; byte[] comment = [(byte)'c', 0]; // CRC16: the two least significant bytes of the CRC-32 of the header up to here. byte[] before = [.. header, .. extra, .. name, .. comment]; var crc = ~redb.Route.As4.Compression.Crc32.Append(0xFFFFFFFFu, before); byte[] headerCrc = [(byte)crc, (byte)(crc >> 8)]; return [.. before, .. headerCrc, .. member[10..]]; } [Fact] public void Multipart_IsWrittenWithCrlfLineEndings_OnEveryPlatform() { // MIME lines end in CRLF (RFC 2046). MimeKit's default follows the platform, so on Linux the body was written // with a bare LF before each boundary: Domibus took it for the last byte of the encrypted attachment before it, // and the AES-GCM tag did not match. The content here has no line break of its own, so every LF in the output // belongs to the MIME structure. SwaMessage.WireFormat.NewLineFormat.Should().Be(MimeKit.NewLineFormat.Dos); var message = SwaMessage.Create(As4TestMessages.UserMessage("m1@a.example", "p1@a.example", moreContentIds: "p2@a.example")); message.AddPart("p1@a.example", "application/octet-stream", [1, 2, 3, 250, 251]); message.AddPart("p2@a.example", "application/octet-stream", [4, 5, 6]); var (contentType, body) = message.Write(); var envelopeStart = body.AsSpan().IndexOf(""u8); for (var i = 0; i < body.Length; i++) { if (body[i] != (byte)'\n' || (i > envelopeStart && i < envelopeEnd)) continue; // the envelope's own text aside (i > 0 && body[i - 1] == (byte)'\r').Should().BeTrue($"the line break at offset {i} must be CRLF"); } // And it reads back to the same bytes. var read = SwaMessage.Read(contentType, body, 1024 * 1024); read.Parts["p1@a.example"].ToArray().Should().Equal(1, 2, 3, 250, 251); read.Parts["p2@a.example"].ToArray().Should().Equal(4, 5, 6); } [Fact] public void Compression_OfEmptyContent_IsTheEmptyGzipMember_NotZeroBytes() { // GZipStream of .NET 9 and later writes nothing for empty content; zero bytes are not gzip to any other receiver. var part = new SwaPart("p1", "text/xml", []); As4Compression.Compress(part, Spool); var compressed = part.ToArray(); compressed.Should().HaveCount(20); compressed[..3].Should().Equal(0x1F, 0x8B, 0x08); As4TestMessages.Gunzip(compressed).Should().BeEmpty(); } [Fact] public void Decompression_WithoutOriginalMimeType_IsValueInconsistent() { var part = new SwaPart("p1", "text/xml", [1]); As4Compression.Compress(part, Spool); var act = () => As4Compression.Decompress(part, new PartInfo("cid:p1", [new Property("CompressionType", "application/gzip", null)]), 1_000_000, Spool); act.Should().Throw().Where(e => e.Code == As4ErrorCode.ValueInconsistent); } [Fact] public void UncompressedPart_IsLeftAlone() { var part = new SwaPart("p1", "text/xml", [1, 2]); As4Compression.Decompress(part, new PartInfo("cid:p1", []), 1_000_000, Spool).Should().BeFalse(); part.ToArray().Should().Equal(1, 2); } // ── Payload consistency → EBMS:0007 / 0011 ─────────────────────────────── [Fact] public void Consistency_PairsEveryReferenceWithItsPart() { var swa = SwaMessage.Create(MessagingWriter.CreateEnvelope(SampleUserMessage())); swa.AddPart("p1@redb.test", "application/gzip", [1]); var pairs = PayloadConsistency.Match(SampleUserMessage(new PartInfo("cid:p1@redb.test", [])), swa); pairs.Should().ContainSingle().Which.Part!.ContentId.Should().Be("p1@redb.test"); } [Fact] public void Consistency_ReferenceWithoutPart_IsMimeInconsistency() { var swa = SwaMessage.Create(MessagingWriter.CreateEnvelope(SampleUserMessage())); var act = () => PayloadConsistency.Match(SampleUserMessage(new PartInfo("cid:missing@redb.test", [])), swa); act.Should().Throw().Where(e => e.Code == As4ErrorCode.MimeInconsistency).WithMessage("*missing@redb.test*"); } [Fact] public void Consistency_UnreferencedPart_IsMimeInconsistency() { var swa = SwaMessage.Create(MessagingWriter.CreateEnvelope(SampleUserMessage())); swa.AddPart("stray@redb.test", "application/octet-stream", [1]); var act = () => PayloadConsistency.Match(SampleUserMessage(), swa); act.Should().Throw().Where(e => e.Code == As4ErrorCode.MimeInconsistency).WithMessage("*stray@redb.test*"); } [Fact] public void Consistency_ExternalReference_IsExternalPayloadError() { var swa = SwaMessage.Create(MessagingWriter.CreateEnvelope(SampleUserMessage())); var act = () => PayloadConsistency.Match(SampleUserMessage(new PartInfo("https://example.org/payload", [])), swa); act.Should().Throw().Where(e => e.Code == As4ErrorCode.ExternalPayloadError); } [Fact] public void Consistency_TooManyParts_IsRefused() { var swa = SwaMessage.Create(MessagingWriter.CreateEnvelope(SampleUserMessage())); swa.AddPart("a", "application/octet-stream", [1]); swa.AddPart("b", "application/octet-stream", [1]); var act = () => PayloadConsistency.Match(SampleUserMessage(new PartInfo("cid:a", []), new PartInfo("cid:b", [])), swa, maxParts: 1); act.Should().Throw().WithMessage("*at most 1*"); } // ── Helpers ────────────────────────────────────────────────────────────── private static XmlDocument Reparse(XmlDocument doc) => Load(doc.OuterXml); private static XmlDocument Load(string xml) => SafeXml.LoadDocument(Encoding.UTF8.GetBytes(xml)); } Path: redb-route/tests/redb.Route.Tests.As4/As4PkiPathTests.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/tests/redb.Route.Tests.As4/As4PkiPathTests.cs ---- using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using redb.Route.Abstractions; using redb.Route.As4; using redb.Route.As4.Security; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; using As4Dsl = redb.Route.As4.Fluent.As4; namespace redb.Route.Tests.As4; /// /// The X509PKIPathv1 security token (WS-Security X.509 Token Profile §3.1.2; eDelivery AS4 1.16 §4.3.3): a signer that /// presents its certification path, and a receiver that trusts an authority instead of holding the signer's /// certificate. The loopback tests carry the ids of the conformance assertions they follow (AS4_CP_TA47 to TA51). /// public class As4PkiPathTests { private const string Policy = "1.3.6.1.4.1.99999.1.1"; // root -> intermediate -> signer, each asserting the policy; and a signer of the same root without it. private static readonly X509Certificate2 Root = Authority("CN=Test Root CA"); private static readonly X509Certificate2 Intermediate = Issue(Root, "CN=Test Issuing CA", authority: true, Policy); private static readonly X509Certificate2 Signer = Issue(Intermediate, "CN=a.pkipath.test", authority: false, Policy); private static readonly X509Certificate2 SignerWithoutPolicy = Issue(Intermediate, "CN=nopolicy.pkipath.test", authority: false); private static readonly X509Certificate2 SelfSigned = As4TestMessages.KeyPair("CN=selfsigned.pkipath.test"); private static readonly X509Certificate2 Receiver = As4TestMessages.KeyPair("CN=b.pkipath.test"); private static PkiPathTrust Trust(params X509Certificate2[] anchors) => new(anchors, []); // ── The token ──────────────────────────────────────────────────────────── [Fact] public void Path_IsEncodedFromTheAuthorityDownToTheSigner_AndReadBackInThatOrder() { // The authorities are given in any order; the signer is the last certificate of the path (ITU-T X.509 PkiPath). var path = PkiPath.Order(Signer, [Intermediate, Root]); path.Select(c => c.Subject).Should().Equal(Root.Subject, Intermediate.Subject, Signer.Subject); var decoded = PkiPath.Decode(PkiPath.Encode(path)); decoded.Select(c => c.Thumbprint).Should().Equal(Root.Thumbprint, Intermediate.Thumbprint, Signer.Thumbprint); } [Fact] public void Order_LeavesOutAnAuthorityThatIssuedNothingOfThePath() { var stranger = Authority("CN=Another Root CA"); PkiPath.Order(Signer, [stranger, Intermediate]).Select(c => c.Subject).Should().Equal(Intermediate.Subject, Signer.Subject); PkiPath.Order(SelfSigned, [Root]).Should().ContainSingle(); } [Theory] [InlineData("not asn.1")] [InlineData("empty sequence")] [InlineData("a certificate, not a sequence of them")] public void Decode_OfWhatIsNotAPath_IsRefused(string what) { byte[] der = what switch { "not asn.1" => [1, 2, 3, 4], "empty sequence" => [0x30, 0x00], _ => Signer.RawData, }; var act = () => PkiPath.Decode(der); act.Should().Throw(); } [Fact] public void Signature_WithAPath_CarriesThePathToken_AndNamesItsTypeOnTheReference() { var message = redb.Route.As4.Mime.SwaMessage.Create(As4TestMessages.UserMessage("m1@a.example", "p1@a.example")); message.AddPart("p1@a.example", "application/gzip", As4TestMessages.Gzip(Encoding.UTF8.GetBytes(""))); As4SecurityEngine.Sign(message, Signer, As4KeyReference.PkiPath, null, DateTimeOffset.UtcNow, [Root, Intermediate, Signer]); var token = (System.Xml.XmlElement)message.Envelope.GetElementsByTagName("BinarySecurityToken", WsSecurityNames.Wsse)[0]!; token.GetAttribute("ValueType").Should().Be(PkiPath.ValueType); PkiPath.Decode(Convert.FromBase64String(token.InnerText)).Select(c => c.Subject) .Should().Equal(Root.Subject, Intermediate.Subject, Signer.Subject); // WS-I Basic Security Profile 1.1 R5215: WSS4J (Domibus, Holodeck) refuses the reference without wsse11:TokenType. var reference = (System.Xml.XmlElement)message.Envelope.GetElementsByTagName("SecurityTokenReference", WsSecurityNames.Wsse)[0]!; reference.GetAttribute("TokenType", WsSecurityNames.Wsse11).Should().Be(PkiPath.ValueType); ((System.Xml.XmlElement)reference.FirstChild!).GetAttribute("ValueType").Should().Be(PkiPath.ValueType); As4SecurityEngine.Verify(message, [], TimeSpan.FromMinutes(5), DateTimeOffset.UtcNow, pkiPath: Trust(Root)) .Signer.Thumbprint.Should().Be(Signer.Thumbprint); } // ── Validation of a path ───────────────────────────────────────────────── [Fact] public void Path_ToATrustedRoot_IsTrusted() => PkiPath.EnsureTrusted([Root, Intermediate, Signer], Trust(Root), DateTimeOffset.UtcNow); [Fact] public void Path_ToATrustedIntermediateAuthority_IsTrusted_AsACertificatePathPrefix() => PkiPath.EnsureTrusted([Root, Intermediate, Signer], Trust(Intermediate), DateTimeOffset.UtcNow); [Fact] public void Path_ThatLeavesTheAnchorOut_IsTrusted_WhenTheAnchorIssuedItsFirstCertificate() => PkiPath.EnsureTrusted([Intermediate, Signer], Trust(Root), DateTimeOffset.UtcNow); [Fact] public void Path_OfASelfSignedCertificate_IsNotTrusted_UnlessItIsItselfTheAnchor() { var act = () => PkiPath.EnsureTrusted([SelfSigned], Trust(Root), DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*does not chain to a trust anchor*"); PkiPath.EnsureTrusted([SelfSigned], Trust(SelfSigned), DateTimeOffset.UtcNow); } [Fact] public void Path_ToAnotherAuthority_IsNotTrusted() { var act = () => PkiPath.EnsureTrusted([Root, Intermediate, Signer], Trust(Authority("CN=Another Root CA")), DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*does not chain to a trust anchor*"); } [Fact] public void Certificates_OutOfOrder_AreNotAPath() { var act = () => PkiPath.EnsureTrusted([Signer, Intermediate, Root], Trust(Root), DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*is not a path*"); } [Fact] public void Path_WithACertificateForgedUnderTheNameOfATrustedAuthority_IsNotTrusted() { // Same subject as the trusted root, another key: the names line up, the signatures do not. var impostor = Authority(Root.Subject); var forged = Issue(impostor, "CN=forged.pkipath.test", authority: false); var act = () => PkiPath.EnsureTrusted([forged], Trust(Root), DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*does not chain to a trust anchor*"); } [Fact] public void Path_ThroughACertificateThatIsNotAnAuthority_IsNotTrusted() { // An end-entity certificate used to issue another one. var issuedByAnEndEntity = Issue(Signer, "CN=below.pkipath.test", authority: false); var act = () => PkiPath.EnsureTrusted([Root, Intermediate, Signer, issuedByAnEndEntity], Trust(Root), DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*not a certification authority*"); } [Fact] public void Path_WithAnExpiredAuthority_IsNotTrusted() { var expired = Issue(Root, "CN=Expired Issuing CA", authority: true, notAfter: DateTimeOffset.UtcNow.AddDays(-1)); var signer = Issue(expired, "CN=late.pkipath.test", authority: false, notAfter: DateTimeOffset.UtcNow.AddDays(-1)); var act = () => PkiPath.EnsureTrusted([Root, expired, signer], Trust(Root), DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*has expired*"); } [Fact] public void Policy_MustBeAssertedByTheSignerAndTheAuthoritiesBelowTheAnchor() { PkiPath.EnsureTrusted([Root, Intermediate, Signer], new PkiPathTrust([Root], [Policy]), DateTimeOffset.UtcNow); var act = () => PkiPath.EnsureTrusted([Root, Intermediate, SignerWithoutPolicy], new PkiPathTrust([Root], [Policy]), DateTimeOffset.UtcNow); act.Should().Throw().WithMessage($"*does not assert the certificate policy {Policy}*"); var other = () => PkiPath.EnsureTrusted([Root, Intermediate, Signer], new PkiPathTrust([Root], ["1.3.6.1.4.1.99999.9"]), DateTimeOffset.UtcNow); other.Should().Throw(); } [Fact] public void AnyPolicy_InACertificate_SatisfiesARequiredPolicy() { var anyPolicy = Issue(Intermediate, "CN=anypolicy.pkipath.test", authority: false, "2.5.29.32.0"); PkiPath.EnsureTrusted([Intermediate, anyPolicy], new PkiPathTrust([Intermediate], [Policy]), DateTimeOffset.UtcNow); } [Fact] public void Path_BeyondThePathLengthOfAnAuthority_IsNotTrusted() { // RFC 5280 §4.2.1.9: the issuing authority may have no authority below it; this path puts one there. var bounded = Issue(Root, "CN=Bounded Issuing CA", authority: true, pathLength: 0); var sub = Issue(bounded, "CN=Sub CA", authority: true); var signer = Issue(sub, "CN=deep.pkipath.test", authority: false); var act = () => PkiPath.EnsureTrusted([Root, bounded, sub, signer], Trust(Root), DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*Bounded Issuing CA allows 0 authorities below it; the path has 1*"); PkiPath.EnsureTrusted([Root, bounded, Issue(bounded, "CN=near.pkipath.test", authority: false)], Trust(Root), DateTimeOffset.UtcNow); } [Fact] public void PathLength_OfTheAnchorItself_IsHonoured() { var bounded = Issue(Root, "CN=Bounded Anchor CA", authority: true, pathLength: 0); var sub = Issue(bounded, "CN=Sub Of Anchor CA", authority: true); var signer = Issue(sub, "CN=under.pkipath.test", authority: false); var act = () => PkiPath.EnsureTrusted([bounded, sub, signer], Trust(bounded), DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*allows 0 authorities below it*"); } [Fact] public void Path_ThroughAnAuthorityWhoseKeyMayNotSignCertificates_IsNotTrusted() { // A certification authority by its basic constraints, but its key usage leaves keyCertSign out. var crlOnly = Issue(Root, "CN=CRL Only CA", authority: true, usage: X509KeyUsageFlags.CrlSign); var signer = Issue(crlOnly, "CN=wrongkey.pkipath.test", authority: false); var act = () => PkiPath.EnsureTrusted([Root, crlOnly, signer], Trust(Root), DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*CRL Only CA is not allowed to sign certificates*"); } // ── The agreement ──────────────────────────────────────────────────────── [Fact] public void Agreement_PinsACertificateOrNamesAuthorities_NotBothAndNotNeither() { var both = Partner("x", Receiver); both.PartnerTrustAnchors.Add(Root); ((Action)both.Validate).Should().Throw().WithMessage("*either PartnerSigningCertificates*or PartnerTrustAnchors*"); var neither = Partner("x", Receiver); neither.PartnerSigningCertificates.Clear(); ((Action)neither.Validate).Should().Throw().WithMessage("*either PartnerSigningCertificates*or PartnerTrustAnchors*"); var policiesWithoutAnchors = Partner("x", Receiver); policiesWithoutAnchors.PartnerCertificatePolicies.Add(Policy); ((Action)policiesWithoutAnchors.Validate).Should().Throw().WithMessage("*PartnerCertificatePolicies*PartnerTrustAnchors*"); } // ── Loopback: a sender with a path, a receiver that trusts an authority ── [Fact] public async Task TA47_TA48_AMessageSignedWithAPath_IsReceived_ByANodeThatTrustsOneOfItsAuthorities() { string? signerThumbprint = null; await using var stand = await Stand.StartAsync(e => signerThumbprint = e.In.GetHeader(As4Headers.SignerThumbprint)); var exchange = NewExchange(); await stand.Send(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); signerThumbprint.Should().Be(Signer.Thumbprint, "the signer is the last certificate of the path, not an authority"); } [Fact] public async Task APathOnBothSides_TheReceiptIsSignedWithAPathToo_AndTheSenderTrustsItsAuthority() { // The receiver's certificate is its own authority here: a path of one, which the sender trusts as its anchor. await using var stand = await Stand.StartAsync(_ => { }, receiverAnswersWithAPath: true); var exchange = NewExchange(); await stand.Send(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); } [Fact] public async Task TA49_ASelfSignedSigner_IsNotAuthorized() { var reached = false; await using var stand = await Stand.StartAsync(_ => reached = true, signer: SelfSigned, authorities: []); var act = () => stand.Send(NewExchange()); (await act.Should().ThrowAsync()).Which.ErrorCode.Should().Be("EBMS:0101"); reached.Should().BeFalse(); } [Theory] [InlineData(As4KeyReference.BinarySecurityToken)] // TA50: a token that holds the signing certificate alone [InlineData(As4KeyReference.IssuerSerial)] // TA51: a reference to the certificate [InlineData(As4KeyReference.KeyIdentifier)] public async Task TA50_TA51_ASignerThatDoesNotPresentAPath_IsNotAuthorized_EvenWhenItsCertificateWouldChain(As4KeyReference form) { var reached = false; await using var stand = await Stand.StartAsync(_ => reached = true, senderReference: form); var act = () => stand.Send(NewExchange()); (await act.Should().ThrowAsync()).Which.ErrorCode.Should().Be("EBMS:0101"); reached.Should().BeFalse(); } [Fact] public async Task ASignerWithoutTheRequiredCertificatePolicy_IsNotAuthorized() { var reached = false; await using var stand = await Stand.StartAsync(_ => reached = true, signer: SignerWithoutPolicy, policy: Policy); var act = () => stand.Send(NewExchange()); (await act.Should().ThrowAsync()).Which.ErrorCode.Should().Be("EBMS:0101"); reached.Should().BeFalse(); } [Fact] public async Task APinnedAgreement_AcceptsItsPartnersCertificateInAPathToken_AsInAnyOtherForm() { // The common profile leaves the token form to the sender: a receiver that pins the certificate reads the path // for the certificate it is for and compares it with the pin. var reached = false; await using var stand = await Stand.StartAsync(_ => reached = true, receiverPinsTheSigner: true); var exchange = NewExchange(); await stand.Send(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); reached.Should().BeTrue(); } // ── Fixtures ───────────────────────────────────────────────────────────── private static Exchange NewExchange() { var exchange = new Exchange(new Message("") { ContentType = "text/xml" }); exchange.In.Headers[As4Headers.OriginalSender] = "C1"; exchange.In.Headers[As4Headers.FinalRecipient] = "C4"; return exchange; } private static As4Partner Partner(string name, X509Certificate2 certificate) => new() { Name = name, PartyId = "urn:redb:" + name, Service = "urn:example", Action = "Submit", PartnerSigningCertificates = { As4TestMessages.PublicOnly(certificate) }, PartnerEncryptionCertificate = As4TestMessages.PublicOnly(certificate), }; /// Node B receiving on a loopback port from node A, whose signer B does not hold: B trusts the root. private sealed class Stand : IAsyncDisposable { private readonly RouteContext _context; private readonly int _port; private Stand(RouteContext context, int port) { _context = context; _port = port; } public static async Task StartAsync(Action route, X509Certificate2? signer = null, X509Certificate2[]? authorities = null, As4KeyReference senderReference = As4KeyReference.PkiPath, string? policy = null, bool receiverAnswersWithAPath = false, bool receiverPinsTheSigner = false) { signer ??= Signer; var port = global::redb.Route.Tests.Shared.TestPorts.Next(); var context = new RouteContext(); context.AddComponent(new As4Component()); context.AddIdempotentRepository("dedup", new InMemoryIdempotentRepository()); // B's view of A: no pinned signing certificate, the root as the trust anchor. var aAtB = Partner("a", signer); if (!receiverPinsTheSigner) { aAtB.PartnerSigningCertificates.Clear(); aAtB.PartnerTrustAnchors.Add(As4TestMessages.PublicOnly(Root)); } if (policy is not null) aAtB.PartnerCertificatePolicies.Add(policy); if (receiverAnswersWithAPath) aAtB.KeyReference = As4KeyReference.PkiPath; context.AddToRegistry("b", new As4ConnectionFactory { OurPartyId = "urn:redb:b", ExternalHostName = "b.example", SigningCertificate = Receiver, DecryptionCertificates = { Receiver }, Partners = { aAtB }, }); // A's view of B: signs with a path; B's own certificate is pinned, or trusted as its own authority. var bAtA = Partner("b", Receiver); bAtA.KeyReference = senderReference; if (receiverAnswersWithAPath) { bAtA.PartnerSigningCertificates.Clear(); bAtA.PartnerTrustAnchors.Add(As4TestMessages.PublicOnly(Receiver)); } var a = new As4ConnectionFactory { OurPartyId = "urn:redb:a", ExternalHostName = "a.example", SigningCertificate = signer, DecryptionCertificates = { signer }, Partners = { bAtA }, }; foreach (var authority in authorities ?? [Intermediate, Root]) a.SigningCertificateChain.Add(As4TestMessages.PublicOnly(authority)); context.AddToRegistry("a", a); context.AddRoutes(r => r.From(As4Dsl.Receive("/as4/in").Host("127.0.0.1").Port(port).ConnectionFactory("b").IdempotentRepository("dedup")) .Process(e => route(e))); await context.Start(); return new Stand(context, port); } public async Task Send(IExchange exchange) { var producer = _context.GetEndpoint( As4Dsl.Send($"http://127.0.0.1:{_port}/as4/in").ConnectionFactory("a").Partner("b").Timeout(15000)).CreateProducer(); await producer.Start(); await producer.Process(exchange); } public async ValueTask DisposeAsync() => await _context.DisposeAsync(); } // ── Our path ───────────────────────────────────────────────────────────── [Fact] public void OurPath_IsOrderedOnce_WhenTheNodeIsResolved() { using var context = NodeContext(Intermediate, Root); var node = As4Node.Resolve(context, "node"); node.SigningPath.Select(c => c.Subject).Should().Equal(Root.Subject, Intermediate.Subject, Signer.Subject); } [Fact] public void OurChain_WithACertificateOffThePath_StopsTheNodeFromStarting() { // An authority that issued neither our certificate nor another authority of the chain would be left out of every // token without a word, and the partner would refuse every message (EBMS:0101). using var context = NodeContext(Intermediate, Root, Authority("CN=Unrelated Root CA")); var act = () => As4Node.Resolve(context, "node"); act.Should().Throw().WithMessage("*SigningCertificateChain holds CN=Unrelated Root CA*not on the certification path*"); } private static RouteContext NodeContext(params X509Certificate2[] chain) { var context = new RouteContext(); var factory = new As4ConnectionFactory { OurPartyId = "urn:redb:a", SigningCertificate = Signer, DecryptionCertificates = { Signer }, Partners = { Partner("b", Receiver) }, }; foreach (var authority in chain) factory.SigningCertificateChain.Add(As4TestMessages.PublicOnly(authority)); context.AddToRegistry("node", factory); return context; } // ── A small certification hierarchy ────────────────────────────────────── private static X509Certificate2 Authority(string subject) { using var rsa = RSA.Create(2048); var request = new CertificateRequest(subject, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509BasicConstraintsExtension(certificateAuthority: true, hasPathLengthConstraint: false, 0, critical: true)); request.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, critical: true)); request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, critical: false)); using var created = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-2), DateTimeOffset.UtcNow.AddYears(2)); return Reload(created); } private static X509Certificate2 Issue(X509Certificate2 issuer, string subject, bool authority, string? policy = null, DateTimeOffset? notAfter = null, int? pathLength = null, X509KeyUsageFlags? usage = null) { using var rsa = RSA.Create(2048); var request = new CertificateRequest(subject, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509BasicConstraintsExtension(authority, pathLength.HasValue, pathLength ?? 0, critical: true)); request.CertificateExtensions.Add(new X509KeyUsageExtension( usage ?? (authority ? X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign : X509KeyUsageFlags.DigitalSignature | X509KeyUsageFlags.KeyEncipherment), critical: true)); request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, critical: false)); if (policy is not null) { // certificatePolicies ::= SEQUENCE OF PolicyInformation { policyIdentifier OBJECT IDENTIFIER } var writer = new System.Formats.Asn1.AsnWriter(System.Formats.Asn1.AsnEncodingRules.DER); using (writer.PushSequence()) using (writer.PushSequence()) writer.WriteObjectIdentifier(policy); request.CertificateExtensions.Add(new X509Extension("2.5.29.32", writer.Encode(), critical: false)); } // A certificate lives within the validity period of its issuer. var issuerEnd = new DateTimeOffset(issuer.NotAfter.ToUniversalTime()); var end = notAfter is { } asked && asked < issuerEnd ? asked : issuerEnd; var serial = RandomNumberGenerator.GetBytes(12); // Positive and without a redundant leading byte (DER INTEGER): a first byte of zero followed by one below 0x80 // is refused by CertificateRevocationListBuilder.AddEntry, which a plain "& 0x7F" produced about once in 512. serial[0] = (byte)((serial[0] & 0x7F) | 0x40); // Signed with the issuer's key directly: the overload that takes the issuer's certificate refuses an issuer // that is not an authority, which one of the tests needs. using var issuerKey = issuer.GetRSAPrivateKey()!; using var issued = request.Create(issuer.SubjectName, X509SignatureGenerator.CreateForRSA(issuerKey, RSASignaturePadding.Pkcs1), new DateTimeOffset(issuer.NotBefore.ToUniversalTime()), end, serial); using var withKey = issued.CopyWithPrivateKey(rsa); return Reload(withKey); } private static X509Certificate2 Reload(X509Certificate2 certificate) => X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pfx), null, X509KeyStorageFlags.Exportable); } Path: redb-route/tests/redb.Route.Tests.As4/As4ProducerTests.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/tests/redb.Route.Tests.As4/As4ProducerTests.cs ---- using System.Net; using System.Text; using redb.Route.Abstractions; using redb.Route.As4; using redb.Route.As4.Messaging; using redb.Route.As4.Mime; using redb.Route.As4.Security; using redb.Route.As4.Signals; using redb.Route.Core; using redb.Route.Processors; using As4Dsl = redb.Route.As4.Fluent.As4; namespace redb.Route.Tests.As4; /// /// The AS4 producer against a loopback partner (, as the AS2 producer tests do) /// that decrypts and verifies what it gets and answers with a real signed non-repudiation receipt — or with an /// ebMS error, nothing, a receipt that echoes the wrong digests, or one signed by a stranger. /// public class As4ProducerTests { private static readonly System.Security.Cryptography.X509Certificates.X509Certificate2 Us = As4TestMessages.KeyPair("CN=us.as4.test"); private static readonly System.Security.Cryptography.X509Certificates.X509Certificate2 Partner = As4TestMessages.KeyPair("CN=acme.as4.test"); private static readonly System.Security.Cryptography.X509Certificates.X509Certificate2 Stranger = As4TestMessages.KeyPair("CN=stranger.as4.test"); private const string Payload = "42"; private enum Answer { Receipt, Error, Nothing, WrongDigest, SignedByStranger, Unsigned, Late, Huge, Forbidden, ReceiptTakenOut } [Fact] public async Task Send_GetsAVerifiedReceipt_AndPutsTheOutcomeOnOut() { await using var fake = new FakePartner(Answer.Receipt); var (context, producer) = await Start(fake.Port); await using var _ = context; var exchange = NewExchange(); await producer.Process(exchange); var sentId = exchange.In.GetHeader(As4Headers.MessageId); sentId.Should().EndWith("@us.example"); exchange.Pattern.Should().Be(ExchangePattern.InOut); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); exchange.Out.GetHeader(As4Headers.MessageId).Should().Be(sentId); exchange.Out.GetHeader(As4Headers.Partner).Should().Be("acme"); // What arrived at the partner: our header values and, after decrypt + verify + decompress, the payload. var user = fake.Received!.UserMessages.Single(); user.MessageInfo.MessageId.Should().Be(sentId); user.From.PartyIds.Single().Value.Should().Be("urn:redb:us"); user.To.PartyIds.Single().Value.Should().Be("urn:redb:acme"); user.CollaborationInfo.Action.Should().Be("Submit"); user.PropertyValue("originalSender").Should().Be("C1"); Encoding.UTF8.GetString(fake.Payload!).Should().Be(Payload); } [Fact] public async Task Send_ToAnAddressWithAQuery_PostsToThatQuery() { // Domibus serves its domains as /domibus?domain=name; the EC test driver takes controller messages so. await using var fake = new FakePartner(Answer.Receipt); var context = NewContext(); await using var _ = context; var uri = (string)As4Dsl.Send($"http://127.0.0.1:{fake.Port}/domibus?domain=sut_controller_domain&x=a%20b") .ConnectionFactory("node").Partner("acme").Timeout(15000); var producer = (As4Producer)context.GetEndpoint(uri).CreateProducer(); await producer.Start(); var exchange = NewExchange(); await producer.Process(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); fake.RequestPathAndQuery.Should().Be("/domibus?domain=sut_controller_domain&x=a%20b"); } [Fact] public async Task Send_ToAPartnerChosenPerMessage_PostsToItsOwnAddress() { // The address is part of the agreement (P-Mode Protocol.Address): one endpoint, each partner at its own MSH. await using var acme = new FakePartner(Answer.Receipt); await using var globex = new FakePartner(Answer.Receipt); var context = NewContext( p => p.Address = $"http://127.0.0.1:{acme.Port}/msh", node => node.Partners.Add(new As4Partner { Name = "globex", PartyId = "urn:redb:globex", Service = "urn:example", Action = "Submit", Address = $"http://127.0.0.1:{globex.Port}/domibus?domain=globex", PartnerSigningCertificates = { As4TestMessages.PublicOnly(Partner) }, PartnerEncryptionCertificate = As4TestMessages.PublicOnly(Partner), })); await using var _ = context; var producer = (As4Producer)context.GetEndpoint(As4Dsl.Send().ConnectionFactory("node").Partner("${header.to}").Timeout(15000)).CreateProducer(); await producer.Start(); foreach (var to in new[] { "acme", "globex" }) { var exchange = NewExchange(); exchange.In.Headers["to"] = to; await producer.Process(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(to); } acme.RequestPathAndQuery.Should().Be("/msh"); acme.Received!.UserMessages.Single().To.PartyIds.Single().Value.Should().Be("urn:redb:acme"); globex.RequestPathAndQuery.Should().Be("/domibus?domain=globex"); globex.Received!.UserMessages.Single().To.PartyIds.Single().Value.Should().Be("urn:redb:globex"); } [Fact] public async Task Send_ToAPartnerChosenPerMessage_WithoutAnAddress_FailsThatMessage() { var context = NewContext(node => { }, node => node.Partners.Add(new As4Partner { Name = "globex", PartyId = "urn:redb:globex", Service = "urn:example", Action = "Submit", Address = "http://127.0.0.1:1/msh", PartnerSigningCertificates = { As4TestMessages.PublicOnly(Partner) }, PartnerEncryptionCertificate = As4TestMessages.PublicOnly(Partner), })); await using var _ = context; var producer = (As4Producer)context.GetEndpoint(As4Dsl.Send().ConnectionFactory("node").Partner("${header.to}")).CreateProducer(); await producer.Start(); var exchange = NewExchange(); exchange.In.Headers["to"] = "acme"; var act = () => producer.Process(exchange); await act.Should().ThrowAsync().WithMessage("*no address*acme*"); } [Fact] public async Task Send_ByDefault_CarriesNoTimestamp_AsTheEDeliveryPolicyOfDomibus() { // Domibus' eDeliveryAS4Policy has no IncludeTimestamp and a Strict layout: a wsu:Timestamp fails it. await using var fake = new FakePartner(Answer.Receipt); var (context, producer) = await Start(fake.Port); await using var _ = context; await producer.Process(NewExchange()); fake.Envelope!.GetElementsByTagName("Timestamp", WsSecurityNames.Wsu).Count.Should().Be(0); } [Fact] public async Task Send_WithATimestampTtl_CarriesATimestamp() { await using var fake = new FakePartner(Answer.Receipt); var (context, producer) = await Start(fake.Port, p => p.TimestampTtl = TimeSpan.FromMinutes(5)); await using var _ = context; await producer.Process(NewExchange()); fake.Envelope!.GetElementsByTagName("Timestamp", WsSecurityNames.Wsu).Count.Should().Be(1); } [Fact] public async Task Send_ReusesTheMessageIdOnTheExchange_SoARedeliveryIsTheSameMessage() { await using var fake = new FakePartner(Answer.Receipt); var (context, producer) = await Start(fake.Port); await using var _ = context; var exchange = NewExchange(); exchange.In.Headers[As4Headers.MessageId] = "fixed-1@us.example"; await producer.Process(exchange); fake.Received!.UserMessages.Single().MessageInfo.MessageId.Should().Be("fixed-1@us.example"); } [Fact] public async Task Route_RedeliveryOnMissingReceipt_ResendsTheSameMessage() { await using var fake = new FakePartner(Answer.Nothing, Answer.Receipt); await using var context = NewContext(); context.AddRoutes(r => { r.OnException() .MaximumRedeliveries(1) .RedeliveryDelay(TimeSpan.FromMilliseconds(10)); r.From("direct://out") .To($"as4://127.0.0.1:{fake.Port}/as4?connectionFactory=node&partner=acme&timeout=15000"); }); await context.Start(); var producer = context.GetEndpoint("direct://out").CreateProducer(); await producer.Start(); var exchange = NewExchange(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); fake.ReceivedIds.Should().HaveCount(2); fake.ReceivedIds[1].Should().Be(fake.ReceivedIds[0]); } [Fact] public async Task Send_NoResponseWithinTheTimeout_IsMissingReceipt_AndRedeliverable() { await using var fake = new FakePartner(Answer.Late, Answer.Receipt); await using var context = NewContext(); context.AddRoutes(r => { r.OnException() .MaximumRedeliveries(1) .RedeliveryDelay(TimeSpan.FromMilliseconds(10)); r.From("direct://out") .To($"as4://127.0.0.1:{fake.Port}/as4?connectionFactory=node&partner=acme&timeout=500"); }); await context.Start(); var producer = context.GetEndpoint("direct://out").CreateProducer(); await producer.Start(); var exchange = NewExchange(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); fake.ReceivedIds.Should().HaveCount(2).And.OnlyContain(id => id == fake.ReceivedIds[0]); } [Fact] public async Task Send_AForwardOnlyStreamBody_IsSent_AndNotClosed() { await using var fake = new FakePartner(Answer.Receipt); var (context, producer) = await Start(fake.Port); await using var _ = context; var stream = new ForwardOnlyStream(Encoding.UTF8.GetBytes(Payload)); var exchange = NewExchange(); exchange.In.Body = stream; await producer.Process(exchange); Encoding.UTF8.GetString(fake.Payload!).Should().Be(Payload); stream.Disposed.Should().BeFalse("the exchange owns its body stream, not the producer"); } [Fact] public async Task Route_RedeliveryOfASeekableStreamBody_SendsTheSameBytes() { await using var fake = new FakePartner(Answer.Nothing, Answer.Receipt); await using var context = NewContext(); context.AddRoutes(r => { r.OnException() .MaximumRedeliveries(1) .RedeliveryDelay(TimeSpan.FromMilliseconds(10)); r.From("direct://out") .To($"as4://127.0.0.1:{fake.Port}/as4?connectionFactory=node&partner=acme&timeout=15000"); }); await context.Start(); var producer = context.GetEndpoint("direct://out").CreateProducer(); await producer.Start(); var exchange = NewExchange(); exchange.In.Body = new MemoryStream(Encoding.UTF8.GetBytes(Payload)); await producer.Process(exchange); fake.ReceivedIds.Should().HaveCount(2); Encoding.UTF8.GetString(fake.Payload!).Should().Be(Payload, "the second attempt reads the stream from its start"); } [Fact] public async Task Route_Redelivery_IsTheSameMessage_ByteForByte() { // A retransmission is the same message (AS4 reception awareness): Domibus answers a duplicate with the stored // receipt of the first transmission, whose non-repudiation digests only match the first signature. await using var fake = new FakePartner(Answer.Nothing, Answer.Receipt); await using var context = NewContext(); context.AddRoutes(r => { r.OnException() .MaximumRedeliveries(1) .RedeliveryDelay(TimeSpan.FromMilliseconds(10)); r.From("direct://out") .To($"as4://127.0.0.1:{fake.Port}/as4?connectionFactory=node&partner=acme&timeout=15000"); }); await context.Start(); var producer = context.GetEndpoint("direct://out").CreateProducer(); await producer.Start(); var exchange = NewExchange(); await producer.Process(exchange); exchange.Exception.Should().BeNull(); fake.RequestHashes.Should().HaveCount(2); fake.RequestHashes[1].Should().Be(fake.RequestHashes[0], "the second attempt sends the bytes of the first"); } [Fact] public async Task ANewExchange_WithTheSameMessageId_IsBuiltAfresh() { // The stored transmission belongs to one exchange; nothing is shared between exchanges. await using var fake = new FakePartner(Answer.Receipt); var (context, producer) = await Start(fake.Port); await using var _ = context; foreach (var attempt in new[] { 1, 2 }) { var exchange = NewExchange(); exchange.In.Headers[As4Headers.MessageId] = "fixed-2@us.example"; await producer.Process(exchange); } fake.RequestHashes.Should().HaveCount(2); fake.RequestHashes[1].Should().NotBe(fake.RequestHashes[0]); } [Fact] public async Task Route_RedeliveriesExhausted_GoToTheDeadLetterRoute() { await using var fake = new FakePartner(Answer.Nothing); await using var context = NewContext(); string? deadMessageId = null; context.AddRoutes(r => { r.OnException() .MaximumRedeliveries(2) .RedeliveryDelay(TimeSpan.FromMilliseconds(10)) .Handled() .To("direct://dead"); r.From("direct://out") .To($"as4://127.0.0.1:{fake.Port}/as4?connectionFactory=node&partner=acme&timeout=15000"); r.From("direct://dead") .Process(e => deadMessageId = e.In.GetHeader(As4Headers.MessageId)); }); await context.Start(); var producer = context.GetEndpoint("direct://out").CreateProducer(); await producer.Start(); await producer.Process(NewExchange()); fake.ReceivedIds.Should().HaveCount(3).And.OnlyContain(id => id == fake.ReceivedIds[0]); deadMessageId.Should().Be(fake.ReceivedIds[0]); } [Fact] public async Task Send_PartnerAnswersWithAnError_ThrowsItsCode() { await using var fake = new FakePartner(Answer.Error); var (context, producer) = await Start(fake.Port); await using var _ = context; var act = () => producer.Process(NewExchange()); (await act.Should().ThrowAsync()).Which.ErrorCode.Should().Be("EBMS:0010"); } [Fact] public async Task Send_PartnerAnswersNothing_IsMissingReceipt() { await using var fake = new FakePartner(Answer.Nothing); var (context, producer) = await Start(fake.Port); await using var _ = context; var act = () => producer.Process(NewExchange()); (await act.Should().ThrowAsync()).Which.Code.Should().Be(As4ErrorCode.MissingReceipt); } [Fact] public async Task Send_ResponseOverTheLimit_IsInvalidReceipt_WithoutReadingItAll() { await using var fake = new FakePartner(Answer.Huge); await using var context = NewContext(); var producer = context.GetEndpoint($"as4://127.0.0.1:{fake.Port}/as4?connectionFactory=node&partner=acme&timeout=15000&maxResponseBodySize=1048576").CreateProducer(); await producer.Start(); var act = () => producer.Process(NewExchange()); var error = (await act.Should().ThrowAsync()).Which; error.Code.Should().Be(As4ErrorCode.InvalidReceipt); error.Message.Should().Contain("1048576"); } [Fact] public async Task Send_ASignalWithTheReceiptTakenOut_IsMissingReceipt() { // AS4_CP_TA15: the test driver answers with the signal of its receipt, the eb:Receipt removed. await using var fake = new FakePartner(Answer.ReceiptTakenOut); var (context, producer) = await Start(fake.Port); await using var _ = context; var act = () => producer.Process(NewExchange()); var error = (await act.Should().ThrowAsync()).Which; error.Code.Should().Be(As4ErrorCode.MissingReceipt); error.Message.Should().Contain("a signal without a receipt"); } [Fact] public async Task Send_AGatewaysRefusalPage_IsInvalidReceipt_QuotingTheStartOfThePage() { // Who refused, and the support reference, are on the page: the error text carries its start. await using var fake = new FakePartner(Answer.Forbidden); var (context, producer) = await Start(fake.Port); await using var _ = context; var act = () => producer.Process(NewExchange()); var error = (await act.Should().ThrowAsync()).Which; error.Code.Should().Be(As4ErrorCode.InvalidReceipt); error.Message.Should().Contain("HTTP 403").And.Contain("text/html: \"403 Forbidden

Forbidden

Request rejected, support ID 4711

"); } [Fact] public void Options_Validate_NonPositiveResponseLimit_Throws() { var act = () => new As4EndpointOptions { ConnectionFactory = "node", MaxResponseBodySize = 0 }.Validate(); act.Should().Throw(); } [Fact] public void Options_Validate_NonPositiveInFlightClaimTimeout_Throws() { var act = () => new As4EndpointOptions { ConnectionFactory = "node", InFlightClaimTimeout = 0 }.Validate(); act.Should().Throw().WithMessage("*inFlightClaimTimeout*"); } [Fact] public async Task Send_ReceiptEchoesOtherDigests_IsInvalidReceipt() { await using var fake = new FakePartner(Answer.WrongDigest); var (context, producer) = await Start(fake.Port); await using var _ = context; var act = () => producer.Process(NewExchange()); var thrown = (await act.Should().ThrowAsync()).Which; thrown.Code.Should().Be(As4ErrorCode.InvalidReceipt); thrown.Detail.Should().Contain("non-repudiation"); } [Fact] public async Task Send_AnUnsignedReceipt_IsInvalidReceipt_NotAProofOfReceipt() { // The receipt names the right digests, but nobody signed it: anyone on the path could have written it. await using var fake = new FakePartner(Answer.Unsigned); var (context, producer) = await Start(fake.Port); await using var _ = context; var act = () => producer.Process(NewExchange()); (await act.Should().ThrowAsync()).Which.Code.Should().Be(As4ErrorCode.InvalidReceipt); } [Fact] public async Task Send_ReceiptSignedByAStranger_IsInvalidReceipt() { await using var fake = new FakePartner(Answer.SignedByStranger); var (context, producer) = await Start(fake.Port); await using var _ = context; var act = () => producer.Process(NewExchange()); var thrown = (await act.Should().ThrowAsync()).Which; thrown.Code.Should().Be(As4ErrorCode.InvalidReceipt); thrown.Detail.Should().Contain("signature"); } [Fact] public async Task Send_WithoutFourCornerProperties_IsRefusedBeforeSending() { await using var fake = new FakePartner(Answer.Receipt); var (context, producer) = await Start(fake.Port); await using var _ = context; var exchange = new Exchange(new Message(Payload) { ContentType = "text/xml" }); var act = () => producer.Process(exchange); await act.Should().ThrowAsync().WithMessage("*originalSender*"); fake.Received.Should().BeNull(); } [Fact] public async Task TA16_APing_IsAUserMessageForTheEbmsTestService() { // ebMS 3.0 Core §5.2.2: the test service and action; an agreement for them is all a ping needs. const string testService = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/service"; const string testAction = "http://docs.oasis-open.org/ebxml-msg/ebms/v3.0/ns/core/200704/test"; await using var fake = new FakePartner(Answer.Receipt); var (context, producer) = await Start(fake.Port, p => { p.Service = testService; p.Action = testAction; }); await using var _ = context; var exchange = NewExchange(); await producer.Process(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); var collaboration = fake.Received!.UserMessages.Single().CollaborationInfo; collaboration.Service.Value.Should().Be(testService); collaboration.Action.Should().Be(testAction); } [Fact] public async Task TA18_Send_WithoutAConversationId_GeneratesOne_AndAGivenOneIsKept() { await using var fake = new FakePartner(Answer.Receipt); var (context, producer) = await Start(fake.Port); await using var _ = context; await producer.Process(NewExchange()); fake.Received!.UserMessages.Single().CollaborationInfo.ConversationId.Should().NotBeNullOrWhiteSpace(); var given = NewExchange(); given.In.Headers[As4Headers.ConversationId] = "conversation-42"; await producer.Process(given); fake.Received!.UserMessages.Single().CollaborationInfo.ConversationId.Should().Be("conversation-42"); } [Fact] public async Task Send_WithoutFourCornerProperties_IsSent_WhenTheAgreementDoesNotRequireThem() { await using var fake = new FakePartner(Answer.Receipt); var (context, producer) = await Start(fake.Port, p => p.RequireFourCornerProperties = false); await using var _ = context; var exchange = new Exchange(new Message(Payload) { ContentType = "text/xml" }); await producer.Process(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); fake.Received!.UserMessages.Single().MessageProperties.Should().BeEmpty(); } [Fact] public async Task Send_APropertyTypeHeader_SetsTheTypeOfThatProperty() { await using var fake = new FakePartner(Answer.Receipt); var (context, producer) = await Start(fake.Port); await using var _ = context; var exchange = NewExchange(); exchange.In.Headers[As4Headers.PropertyTypePrefix + "finalRecipient"] = "urn:example:type"; await producer.Process(exchange); var properties = fake.Received!.UserMessages.Single().MessageProperties; properties.Select(p => p.Name).Should().Equal("finalRecipient", "originalSender"); properties.Single(p => p.Name == "finalRecipient").Type.Should().Be("urn:example:type"); properties.Single(p => p.Name == "originalSender").Type.Should().BeNull(); } [Fact] public async Task Send_AListOfPayloads_KeepsTheirOrder_ContentIdsAndPartProperties() { await using var fake = new FakePartner(Answer.Receipt); var (context, producer) = await Start(fake.Port); await using var _ = context; var exchange = NewExchange(); exchange.In.Body = new List { new("xmlpayload@gitb", "application/xml", new MemoryStream(Encoding.UTF8.GetBytes("")), new Dictionary { ["CharacterSet"] = "utf-8", ["MimeType"] = "ignored/ours" }), new("custompayload@gitb", "application/octet-stream", new MemoryStream([1, 2, 3]), new Dictionary()), new(null, "application/octet-stream", new MemoryStream([4, 5]), new Dictionary()), }; await producer.Process(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); fake.Parts.Should().HaveCount(3); fake.Parts[0].ContentId.Should().Be("xmlpayload@gitb"); fake.Parts[1].ContentId.Should().Be("custompayload@gitb"); fake.Parts[2].ContentId.Should().EndWith("@us.example"); Encoding.UTF8.GetString(fake.Parts[0].Content).Should().Be(""); fake.Parts[1].Content.Should().Equal(1, 2, 3); fake.Parts[2].Content.Should().Equal(4, 5); // The leading document: its own media type and character set, next to the compression the connector applied. var leading = fake.Parts[0].Info; leading.PropertyValue("MimeType").Should().Be("application/xml"); leading.PropertyValue("CompressionType").Should().Be("application/gzip"); leading.PropertyValue("CharacterSet").Should().Be("utf-8"); leading.Properties.Count(p => p.Name == "MimeType").Should().Be(1); } [Fact] public async Task Send_AnEmptyPayloadList_IsASimpleSoapMessageWithoutPayloads() { await using var fake = new FakePartner(Answer.Receipt); var (context, producer) = await Start(fake.Port); await using var _ = context; var exchange = NewExchange(); exchange.In.Body = Array.Empty(); await producer.Process(exchange); exchange.Out!.GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); fake.Parts.Should().BeEmpty(); fake.Received!.UserMessages.Single().PayloadInfo.Should().BeEmpty(); fake.WireContentType.Should().StartWith("application/soap+xml"); } [Fact] public async Task Send_ACharacterSetThatIsNotAnEncodingName_IsRefusedBeforeSending() { await using var fake = new FakePartner(Answer.Receipt); var (context, producer) = await Start(fake.Port); await using var _ = context; var exchange = NewExchange(); exchange.In.Body = new List { new(null, "application/xml", new MemoryStream([1]), new Dictionary { ["CharacterSet"] = "!utf*" }), }; var act = () => producer.Process(exchange); await act.Should().ThrowAsync().WithMessage("*CharacterSet*!utf**"); fake.Received.Should().BeNull(); } [Fact] public async Task Send_TwoPayloadsWithTheSameContentId_IsRefusedBeforeSending() { await using var fake = new FakePartner(Answer.Receipt); var (context, producer) = await Start(fake.Port); await using var _ = context; var exchange = NewExchange(); exchange.In.Body = new List { new("same@gitb", "application/xml", new MemoryStream([1]), new Dictionary()), new("same@gitb", "application/xml", new MemoryStream([2]), new Dictionary()), }; var act = () => producer.Process(exchange); await act.Should().ThrowAsync().WithMessage("*same@gitb*"); fake.Received.Should().BeNull(); } [Fact] public async Task Send_WithOurSigningCertificateExpired_IsRefusedBeforeSending() { await using var fake = new FakePartner(Answer.Receipt); var expired = As4TestMessages.KeyPair("CN=us.as4.test", DateTimeOffset.UtcNow.AddYears(-2), DateTimeOffset.UtcNow.AddDays(-1)); var (context, producer) = await Start(fake.Port, node: n => n.SigningCertificate = expired); await using var _ = context; var act = () => producer.Process(NewExchange()); await act.Should().ThrowAsync().WithMessage("*signing certificate*has expired*"); fake.Received.Should().BeNull(); } [Fact] public async Task Send_ToAPartnerWhoseEncryptionCertificateExpired_IsRefusedBeforeSending() { await using var fake = new FakePartner(Answer.Receipt); var expired = As4TestMessages.PublicOnly( As4TestMessages.KeyPair("CN=acme.as4.test", DateTimeOffset.UtcNow.AddYears(-2), DateTimeOffset.UtcNow.AddDays(-1))); var (context, producer) = await Start(fake.Port, p => p.PartnerEncryptionCertificate = expired); await using var _ = context; var act = () => producer.Process(NewExchange()); await act.Should().ThrowAsync().WithMessage("*encryption certificate*has expired*"); fake.Received.Should().BeNull(); } [Fact] public async Task Send_OverridingTheActionWithoutPermission_IsRefused() { await using var fake = new FakePartner(Answer.Receipt); var (context, producer) = await Start(fake.Port); await using var _ = context; var exchange = NewExchange(); exchange.In.Headers[As4Headers.Action] = "Refund"; var act = () => producer.Process(exchange); await act.Should().ThrowAsync().WithMessage("*does not allow overriding the action*"); } [Fact] public async Task Send_WithRefToMessageId_UsesTheReplyLeg() { await using var fake = new FakePartner(Answer.Receipt); var (context, producer) = await Start(fake.Port, p => p.ReplyLeg = new As4Leg { Service = "urn:example:reply", Action = "Confirm" }); await using var _ = context; var exchange = NewExchange(); exchange.In.Headers[As4Headers.RefToMessageId] = "request-1@acme.example"; await producer.Process(exchange); var user = fake.Received!.UserMessages.Single(); user.MessageInfo.RefToMessageId.Should().Be("request-1@acme.example"); user.CollaborationInfo.Service.Value.Should().Be("urn:example:reply"); user.CollaborationInfo.Action.Should().Be("Confirm"); } // ── Fixtures ───────────────────────────────────────────────────────────── private static Exchange NewExchange() { var exchange = new Exchange(new Message(Payload) { ContentType = "text/xml" }); exchange.In.Headers[As4Headers.OriginalSender] = "C1"; exchange.In.Headers[As4Headers.FinalRecipient] = "C4"; return exchange; } private static async Task<(RouteContext Context, As4Producer Producer)> Start(int port, Action? configure = null, Action? node = null) { var context = NewContext(configure, node); var producer = (As4Producer)context.GetEndpoint($"as4://127.0.0.1:{port}/as4?connectionFactory=node&partner=acme&timeout=15000").CreateProducer(); await producer.Start(); return (context, producer); } private static RouteContext NewContext(Action? configure = null, Action? node = null) { var context = new RouteContext(); context.AddComponent(new As4Component()); var partner = new As4Partner { Name = "acme", PartyId = "urn:redb:acme", Service = "urn:example", Action = "Submit", PartnerSigningCertificates = { As4TestMessages.PublicOnly(Partner) }, PartnerEncryptionCertificate = As4TestMessages.PublicOnly(Partner), }; configure?.Invoke(partner); var factory = new As4ConnectionFactory { OurPartyId = "urn:redb:us", ExternalHostName = "us.example", SigningCertificate = Us, DecryptionCertificates = { Us }, Partners = { partner }, }; node?.Invoke(factory); context.AddToRegistry("node", factory); return context; } /// /// A loopback AS4 partner answering one way or another — request by request, the last answer repeating; /// it records what it received. /// private sealed class FakePartner : IAsyncDisposable { private readonly HttpListener _listener = new(); private readonly Answer[] _answers; private readonly Task _loop; public FakePartner(params Answer[] answers) { _answers = answers; Port = global::redb.Route.Tests.Shared.TestPorts.Next(); _listener.Prefixes.Add($"http://127.0.0.1:{Port}/"); _listener.Start(); _loop = Task.Run(ServeAsync); } public int Port { get; } public EbmsMessaging? Received { get; private set; } /// The envelope of the last request, decrypted. public System.Xml.XmlDocument? Envelope { get; private set; } public byte[]? Payload { get; private set; } /// The payloads of the last request in the order of eb:PartInfo, decrypted and decompressed. public List<(string ContentId, PartInfo Info, byte[] Content)> Parts { get; private set; } = []; /// Content-Type of the last request as it came on the wire. public string? WireContentType { get; private set; } /// Path and query of the last request. public string? RequestPathAndQuery { get; private set; } /// MessageId of every user message received, in order. public List ReceivedIds { get; } = []; /// SHA-256 of every raw request body, in order: a retransmission is the same bytes. public List RequestHashes { get; } = []; private async Task ServeAsync() { while (_listener.IsListening) { HttpListenerContext http; try { http = await _listener.GetContextAsync(); } catch (HttpListenerException) { return; } // listener stopped catch (ObjectDisposedException) { return; } // listener disposed catch (ArgumentException) when (!_listener.IsListening) { return; } // stopped before the first wait (net10: invalid handle) using var body = new MemoryStream(); await http.Request.InputStream.CopyToAsync(body); RequestHashes.Add(Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(body.ToArray()))); var request = SwaMessage.Read(http.Request.ContentType!, body.ToArray(), 1024 * 1024); As4SecurityEngine.Decrypt(request, [Partner]); var verification = As4SecurityEngine.Verify(request, [As4TestMessages.PublicOnly(Us)], TimeSpan.FromMinutes(5), DateTimeOffset.UtcNow); Received = MessagingReader.Read(request.Envelope); Envelope = request.Envelope; Parts = Received.UserMessages.Single().PayloadInfo .Select(info => { var id = Uri.UnescapeDataString(info.Href!["cid:".Length..]); return (id, info, As4TestMessages.Gunzip(request.Parts[id].ToArray())); }) .ToList(); WireContentType = http.Request.ContentType; RequestPathAndQuery = http.Request.Url!.PathAndQuery; Payload = Parts.Count == 1 ? Parts[0].Content : null; var messageId = Received.UserMessages.Single().MessageInfo.MessageId; var mode = _answers[Math.Min(ReceivedIds.Count, _answers.Length - 1)]; ReceivedIds.Add(messageId); if (mode == Answer.Huge) { // A proxy error page of no known length: chunked, far over any receipt. http.Response.StatusCode = 200; http.Response.ContentType = "text/html"; http.Response.SendChunked = true; var junk = new byte[1 << 20]; try { for (var i = 0; i < 20; i++) await http.Response.OutputStream.WriteAsync(junk); } catch (Exception e) when (e is HttpListenerException or ObjectDisposedException or IOException) { } // the sender stops reading at its limit; the listener may be stopping // The test may dispose the listener between the check and the call: Abort then throws ObjectDisposedException. try { if (_listener.IsListening) http.Response.Abort(); } catch (ObjectDisposedException) { } // the listener stopped: nothing left to abort continue; } if (mode == Answer.Late) continue; // never answers; the listener aborts it on dispose if (mode == Answer.Nothing) { http.Response.StatusCode = 202; http.Response.Close(); continue; } if (mode == Answer.Forbidden) { // A gateway's refusal page in front of the partner's access point. var page = System.Text.Encoding.UTF8.GetBytes( "403 Forbidden\r\n

Forbidden

\r\n

Request rejected, support ID 4711

\r\n
"); http.Response.StatusCode = 403; http.Response.ContentType = "text/html; charset=utf-8"; await http.Response.OutputStream.WriteAsync(page); http.Response.Close(); continue; } var info = new MessageInfo(DateTimeOffset.UtcNow, MessageIdFactory.New("acme.example"), messageId); SignalMessage signal = mode switch { Answer.Error => new SignalMessage(info, null, [new EbmsError("EBMS:0010", As4ErrorSeverity.Failure, "Processing", "ebms", messageId, "ProcessingModeMismatch", null, "no P-Mode")], null), // The receipt taken out of the signal, as the conformance test driver simulates a lost one. Answer.ReceiptTakenOut => new SignalMessage(info, null, [], null), _ => new SignalMessage(info, Receipts.NonRepudiation(mode == Answer.WrongDigest ? Tampered(verification.References) : verification.References), [], null), }; var answer = SwaMessage.Create(MessagingWriter.CreateEnvelope(signal)); if (mode != Answer.Unsigned) As4SecurityEngine.Sign(answer, mode == Answer.SignedByStranger ? Stranger : Partner, As4KeyReference.BinarySecurityToken, timestampTtl: null, DateTimeOffset.UtcNow); var (contentType, bytes) = answer.Write(); http.Response.StatusCode = 200; http.Response.ContentType = contentType; await http.Response.OutputStream.WriteAsync(bytes); http.Response.Close(); } } private static IReadOnlyList Tampered(IReadOnlyList references) { var copies = references.Select(r => (System.Xml.XmlElement)r.CloneNode(deep: true)).ToList(); copies[0].GetElementsByTagName("DigestValue", WsSecurityNames.Ds)[0]!.InnerText = Convert.ToBase64String(new byte[32]); return copies; } public async ValueTask DisposeAsync() { _listener.Stop(); _listener.Close(); await _loop.ConfigureAwait(false); } } } /// A stream that reads forward only, as a network body does, and records whether it was closed. internal sealed class ForwardOnlyStream(byte[] content) : Stream { private readonly MemoryStream _inner = new(content, writable: false); public bool Disposed { get; private set; } public override bool CanRead => !Disposed; public override bool CanSeek => false; public override bool CanWrite => false; public override long Length => throw new NotSupportedException(); public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public override int Read(byte[] buffer, int offset, int count) => _inner.Read(buffer, offset, count); public override void Flush() { } public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); public override void SetLength(long value) => throw new NotSupportedException(); public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); protected override void Dispose(bool disposing) { Disposed = true; base.Dispose(disposing); } } Path: redb-route/tests/redb.Route.Tests.As4/As4RestartTests.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/tests/redb.Route.Tests.As4/As4RestartTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Security.Cryptography.X509Certificates; using System.Text; using redb.Route.Abstractions; using redb.Route.As4; using redb.Route.As4.Messaging; using redb.Route.As4.Mime; using redb.Route.As4.Security; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; using As4Dsl = redb.Route.As4.Fluent.As4; namespace redb.Route.Tests.As4; /// /// An AS4 consumer and producer keep working after Stop() and Start() of the same route context (issue /// redb-route #12: a component keeps its endpoints for the life of the context, so a stop must not close for good what /// the next start needs). The stop gives the listener path back to the shared server, the start registers it again on /// the cached endpoint; the duplicate store lives in the registry and still knows the messages taken before the stop; /// a spooled body is written and read on both runs. AS4 has no pending-receipt table and no pull queue to outlive a /// stop: the receipt is the HTTP response of the same request, and a pull request is answered EBMS:0010. /// public class As4RestartTests { private const string Payload = "10"; private static readonly X509Certificate2 NodeA = As4TestMessages.KeyPair("CN=a.restart.as4.test"); private static readonly X509Certificate2 NodeB = As4TestMessages.KeyPair("CN=b.restart.as4.test"); [Theory] [InlineData(false)] [InlineData(true)] public async Task Consumer_and_producer_work_after_the_context_is_stopped_and_started_again(bool streamBody) { var port = global::redb.Route.Tests.Shared.TestPorts.Next(); await using var context = new RouteContext(); context.AddComponent(new As4Component()); context.AddIdempotentRepository("dedup", new InMemoryIdempotentRepository()); context.AddToRegistry("b", Node("b", NodeB, Partner("a", NodeA))); context.AddToRegistry("a", Node("a", NodeA, Partner("b", NodeB))); var delivered = new List<(string MessageId, string Body)>(); var receive = As4Dsl.Receive("/as4/in").Host("127.0.0.1").Port(port).ConnectionFactory("b").IdempotentRepository("dedup"); if (streamBody) receive.StreamBody(); var receiveUri = receive.Build(); context.AddRoutes(r => r.From(receiveUri).RouteId("as4-in") .Process(async (e, ct) => { // A streamed body comes from the spool: it is read here, inside the exchange, as a route reads it. var body = e.In.Body is Stream stream ? await new StreamReader(stream, Encoding.UTF8).ReadToEndAsync(ct) : Encoding.UTF8.GetString((byte[])e.In.Body!); lock (delivered) delivered.Add((e.In.GetHeader(As4Headers.MessageId)!, body)); })); context.AddRoutes(r => r.From("direct://send").RouteId("as4-out") .To(As4Dsl.Send($"http://127.0.0.1:{port}/as4/in").ConnectionFactory("a").Partner("b").Timeout(15000))); async Task SendAsync() { var producer = context.GetEndpoint("direct://send").CreateProducer(); await producer.Start(); var exchange = NewExchange(); await producer.Process(exchange); exchange.Exception.Should().BeNull("the message goes out and its receipt comes back on every run"); (exchange.Out ?? exchange.In).GetHeader(As4Headers.ReceiptValid).Should().BeTrue(); return exchange.In.GetHeader(As4Headers.MessageId)!; } // A message as a partner's access point sends it, kept as bytes so that it can be sent again unchanged. var (resend, resendId) = SecuredMessage(); await context.Start(); var first = await SendAsync(); (await PostAsync(port, resend)).Should().Be((HttpStatusCode.OK, (string?)null, true)); await context.Stop(); await context.Start(); context.GetRoute("as4-in")!.Status.Should().Be(RouteStatus.Started); context.GetRoute("as4-out")!.Status.Should().Be(RouteStatus.Started); var second = await SendAsync(); // Sent again after the restart: the duplicate store still knows it, so it gets its receipt and is not delivered. (await PostAsync(port, resend)).Should().Be((HttpStatusCode.OK, (string?)null, true)); lock (delivered) { delivered.Select(d => d.MessageId).Should().Equal([first, resendId, second]); delivered.Should().OnlyContain(d => d.Body == Payload); } ((IEndpointStatistics)context.GetEndpoint(receiveUri)).Errors.Should().Be(0); } private static Exchange NewExchange() { var exchange = new Exchange(new Message(Payload) { ContentType = "text/xml" }); exchange.In.Headers[As4Headers.OriginalSender] = "C1"; exchange.In.Headers[As4Headers.FinalRecipient] = "C4"; return exchange; } /// A user message from A to B, compressed, signed and encrypted as A sends it; the bytes resend unchanged. private static ((string ContentType, byte[] Body) Message, string MessageId) SecuredMessage() { const string contentId = "p1@a.example"; var message = SwaMessage.Create(As4TestMessages.UserMessage(Guid.NewGuid().ToString("N") + "@a.example", contentId, from: "urn:redb:a", to: "urn:redb:b", service: "urn:example", action: "Submit")); message.AddPart(contentId, "application/gzip", As4TestMessages.Gzip(Encoding.UTF8.GetBytes(Payload))); var messageId = MessagingReader.Read(message.Envelope).UserMessages.Single().MessageInfo.MessageId; As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow); As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken); return (message.Write(), messageId); } /// Posts a message as raw bytes and reads the signal that answers it. private static async Task<(HttpStatusCode Status, string? ErrorCode, bool Receipt)> PostAsync(int port, (string ContentType, byte[] Body) message) { using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) }; var content = new ByteArrayContent(message.Body); content.Headers.ContentType = MediaTypeHeaderValue.Parse(message.ContentType); using var response = await http.PostAsync($"http://127.0.0.1:{port}/as4/in", content); var body = await response.Content.ReadAsByteArrayAsync(); var answer = SwaMessage.Read(response.Content.Headers.ContentType!.ToString(), body, 1024 * 1024); var signals = MessagingReader.Read(answer.Envelope).SignalMessages; var error = signals.SelectMany(s => s.Errors).FirstOrDefault(); return (response.StatusCode, error?.ErrorCode, signals.Any(s => s.IsReceipt)); } private static As4Partner Partner(string name, X509Certificate2 certificate) => new() { Name = name, PartyId = "urn:redb:" + name, Service = "urn:example", Action = "Submit", PartnerSigningCertificates = { As4TestMessages.PublicOnly(certificate) }, PartnerEncryptionCertificate = As4TestMessages.PublicOnly(certificate), }; private static As4ConnectionFactory Node(string name, X509Certificate2 key, params As4Partner[] partners) { var node = new As4ConnectionFactory { OurPartyId = "urn:redb:" + name, ExternalHostName = name + ".example", SigningCertificate = key, DecryptionCertificates = { key }, }; foreach (var partner in partners) node.Partners.Add(partner); return node; } } Path: redb-route/tests/redb.Route.Tests.As4/As4RevocationTests.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/tests/redb.Route.Tests.As4/As4RevocationTests.cs ---- using System.Net; using System.Numerics; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using redb.Route.As4.Security; namespace redb.Route.Tests.As4; /// /// Revocation of pinned certificates, against a real CRL a local CA publishes over HTTP (with its certificate at the /// AIA caIssuers address, so the chain to the CRL signer can be built). The policy is phase4's and Domibus': /// hard-fail when the status cannot be determined unless soft-fail is chosen; a certificate that names no CRL /// distribution point and no AIA passes, as in Domibus. Off by default, as in Camel/CXF, Holodeck and phase4. /// public sealed class As4RevocationTests : IAsyncLifetime { private readonly HttpListener _listener = new(); private readonly int _port = global::redb.Route.Tests.Shared.TestPorts.Next(); private readonly string _prefix = "/" + Guid.NewGuid().ToString("N"); // fresh URLs: the OS caches CRLs by URL private readonly Dictionary _files = new(StringComparer.Ordinal); private readonly Task _loop; public As4RevocationTests() { _listener.Prefixes.Add($"http://127.0.0.1:{_port}/"); _listener.Start(); _loop = Task.Run(ServeAsync); } [Fact] public void NotRevoked_Passes() { var (_, leaf) = Pki(revoke: false); CertificateValidity.Problem(leaf, DateTimeOffset.UtcNow, "The partner certificate", Online()).Should().BeNull(); } [Fact] public void Revoked_IsRefused() { var (_, leaf) = Pki(revoke: true); CertificateValidity.Problem(leaf, DateTimeOffset.UtcNow, "The partner certificate", Online()) .Should().Contain("revoked"); } [Fact] public void Revoked_ButNotChecked_Passes() { var (_, leaf) = Pki(revoke: true); CertificateValidity.Problem(leaf, DateTimeOffset.UtcNow, "The partner certificate", RevocationPolicy.None).Should().BeNull(); } [Fact] public void UnreachableCrl_IsRefused_UnlessSoftFail() { var (_, leaf) = Pki(revoke: false, publish: false); CertificateValidity.Problem(leaf, DateTimeOffset.UtcNow, "The partner certificate", Online()) .Should().Contain("could not be determined"); CertificateValidity.Problem(leaf, DateTimeOffset.UtcNow, "The partner certificate", Online() with { SoftFail = true }) .Should().BeNull(); } [Fact] public void CertificateWithoutRevocationPointers_Passes() { var selfSigned = As4TestMessages.KeyPair("CN=no-crl.as4.test"); CertificateValidity.Problem(selfSigned, DateTimeOffset.UtcNow, "The partner certificate", Online()).Should().BeNull(); } [Fact] public void MessageSignedWithARevokedCertificate_FailsVerification() { var (_, leaf) = Pki(revoke: true); var message = redb.Route.As4.Mime.SwaMessage.Create(As4TestMessages.UserMessage("m-1@redb.test", "p1@redb.test")); message.AddPart("p1@redb.test", "application/gzip", As4TestMessages.Gzip("
"u8.ToArray())); As4SecurityEngine.Sign(message, leaf, redb.Route.As4.As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow); var act = () => As4SecurityEngine.Verify(message, [As4TestMessages.PublicOnly(leaf)], TimeSpan.FromMinutes(5), DateTimeOffset.UtcNow, Online()); act.Should().Throw().WithMessage("*revoked*"); } // ── Fixtures ───────────────────────────────────────────────────────────── private static RevocationPolicy Online() => new(X509RevocationMode.Online, SoftFail: false); /// A CA and a leaf it issued whose CDP and AIA point at this test's listener; the CRL lists the leaf when revoked. private (X509Certificate2 Ca, X509Certificate2 Leaf) Pki(bool revoke, bool publish = true) { var crlUrl = $"http://127.0.0.1:{_port}{_prefix}/ca.crl"; var caUrl = $"http://127.0.0.1:{_port}{_prefix}/ca.cer"; using var caKey = RSA.Create(2048); var caRequest = new CertificateRequest("CN=Test CA " + _prefix, caKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); caRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); caRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, true)); caRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(caRequest.PublicKey, false)); var ca = caRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-2), DateTimeOffset.UtcNow.AddYears(1)); using var leafKey = RSA.Create(2048); var leafRequest = new CertificateRequest("CN=partner.as4.test", leafKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); leafRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false)); leafRequest.CertificateExtensions.Add(CertificateRevocationListBuilder.BuildCrlDistributionPointExtension([crlUrl])); leafRequest.CertificateExtensions.Add(new X509AuthorityInformationAccessExtension(null, [caUrl])); var serial = RandomNumberGenerator.GetBytes(16); // Positive and without a redundant leading byte (DER INTEGER): a first byte of zero followed by one below 0x80 // is refused by CertificateRevocationListBuilder.AddEntry, which a plain "& 0x7F" produced about once in 512. serial[0] = (byte)((serial[0] & 0x7F) | 0x40); using var issued = leafRequest.Create(ca, DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddMonths(6), serial); var leaf = issued.CopyWithPrivateKey(leafKey); if (publish) { var crl = new CertificateRevocationListBuilder(); if (revoke) crl.AddEntry(serial, DateTimeOffset.UtcNow.AddHours(-1), X509RevocationReason.KeyCompromise); _files[$"{_prefix}/ca.crl"] = crl.Build(ca, BigInteger.One, DateTimeOffset.UtcNow.AddDays(7), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1, DateTimeOffset.UtcNow.AddMinutes(-5)); _files[$"{_prefix}/ca.cer"] = ca.Export(X509ContentType.Cert); } return (ca, leaf); } // ── A certification path (eDelivery AS4 1.16 §4.3.3) ───────────────────── [Fact] public void Path_NotRevoked_Passes() { var pki = PathPki(); PkiPath.EnsureTrusted([pki.Root, pki.Intermediate, pki.Signer], new PkiPathTrust([pki.Root], []), DateTimeOffset.UtcNow, Online()); } [Fact] public void Path_WithARevokedSigner_IsRefused() { var pki = PathPki(revokeSigner: true); var act = () => PkiPath.EnsureTrusted([pki.Root, pki.Intermediate, pki.Signer], new PkiPathTrust([pki.Root], []), DateTimeOffset.UtcNow, Online()); act.Should().Throw().WithMessage("The signing certificate CN=signer*has been revoked."); } [Fact] public void Path_WithARevokedIntermediateAuthority_IsRefused() { var pki = PathPki(revokeIntermediate: true); var act = () => PkiPath.EnsureTrusted([pki.Root, pki.Intermediate, pki.Signer], new PkiPathTrust([pki.Root], []), DateTimeOffset.UtcNow, Online()); act.Should().Throw().WithMessage("The certification authority CN=Issuing CA*has been revoked."); } [Fact] public void Path_WithARevokedSigner_UnderAnIntermediateAnchor_IsRefused() { // .NET checks no revocation under an intermediate trust anchor (a partial chain, on Windows and on Linux): the // root the token carries above the anchor completes the chain for the check. var pki = PathPki(revokeSigner: true); var act = () => PkiPath.EnsureTrusted([pki.Root, pki.Intermediate, pki.Signer], new PkiPathTrust([pki.Intermediate], []), DateTimeOffset.UtcNow, Online()); act.Should().Throw().WithMessage("*has been revoked."); } [Fact] public void Path_WithARevokedSigner_UnderAnIntermediateAnchor_TokenWithoutTheRoot_IsRefused() { // The token stops at the anchor: the root is found from the anchor's authority information access. var pki = PathPki(revokeSigner: true); var act = () => PkiPath.EnsureTrusted([pki.Intermediate, pki.Signer], new PkiPathTrust([pki.Intermediate], []), DateTimeOffset.UtcNow, Online()); act.Should().Throw().WithMessage("*has been revoked."); } [Fact] public void Path_UnderAnIntermediateAnchor_WithNoRootToBeFound_IsUndetermined_UnlessSoftFail() { var pki = PathPki(intermediateNamesItsIssuer: false); var trust = new PkiPathTrust([pki.Intermediate], []); var act = () => PkiPath.EnsureTrusted([pki.Intermediate, pki.Signer], trust, DateTimeOffset.UtcNow, Online()); act.Should().Throw().WithMessage("*could not be determined (no self-signed root above the trust anchor*"); PkiPath.EnsureTrusted([pki.Intermediate, pki.Signer], trust, DateTimeOffset.UtcNow, Online() with { SoftFail = true }); } [Fact] public void Path_WithAnUnreachableCrl_IsUndetermined_UnlessSoftFail() { var pki = PathPki(publishSignerCrl: false); var trust = new PkiPathTrust([pki.Root], []); var act = () => PkiPath.EnsureTrusted([pki.Root, pki.Intermediate, pki.Signer], trust, DateTimeOffset.UtcNow, Online()); act.Should().Throw().WithMessage("The signing certificate*could not be determined*"); PkiPath.EnsureTrusted([pki.Root, pki.Intermediate, pki.Signer], trust, DateTimeOffset.UtcNow, Online() with { SoftFail = true }); } [Fact] public void Path_WithARevokedSigner_PassesWhenRevocationIsNotChecked() { var pki = PathPki(revokeSigner: true); PkiPath.EnsureTrusted([pki.Root, pki.Intermediate, pki.Signer], new PkiPathTrust([pki.Root], []), DateTimeOffset.UtcNow, RevocationPolicy.None); } [Fact] public void MessageSignedWithAPathToARevokedSigner_FailsVerification() { var pki = PathPki(revokeSigner: true); var message = redb.Route.As4.Mime.SwaMessage.Create(As4TestMessages.UserMessage("m-1@redb.test", "p1@redb.test")); message.AddPart("p1@redb.test", "application/gzip", As4TestMessages.Gzip(""u8.ToArray())); As4SecurityEngine.Sign(message, pki.Signer, redb.Route.As4.As4KeyReference.PkiPath, null, DateTimeOffset.UtcNow, [pki.Root, pki.Intermediate, pki.Signer]); var act = () => As4SecurityEngine.Verify(message, [], TimeSpan.FromMinutes(5), DateTimeOffset.UtcNow, Online(), pkiPath: new PkiPathTrust([pki.Root], [])); act.Should().Throw().WithMessage("*revoked*"); } /// /// root -> issuing CA -> signer, published by this test's listener: each CRL at its issuer's distribution point, each /// issuer's certificate at the caIssuers address of the certificates it issued. /// private (X509Certificate2 Root, X509Certificate2 Intermediate, X509Certificate2 Signer) PathPki(bool revokeSigner = false, bool revokeIntermediate = false, bool publishSignerCrl = true, bool intermediateNamesItsIssuer = true) { string Url(string file) => $"http://127.0.0.1:{_port}{_prefix}/{file}"; using var rootKey = RSA.Create(2048); var rootRequest = new CertificateRequest("CN=Path Root CA " + _prefix, rootKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); rootRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); rootRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, true)); rootRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(rootRequest.PublicKey, false)); var root = rootRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-2), DateTimeOffset.UtcNow.AddYears(1)); using var intermediateKey = RSA.Create(2048); var intermediateRequest = new CertificateRequest("CN=Issuing CA " + _prefix, intermediateKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); intermediateRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); intermediateRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign | X509KeyUsageFlags.CrlSign, true)); intermediateRequest.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(intermediateRequest.PublicKey, false)); if (intermediateNamesItsIssuer) { intermediateRequest.CertificateExtensions.Add(CertificateRevocationListBuilder.BuildCrlDistributionPointExtension([Url("root.crl")])); intermediateRequest.CertificateExtensions.Add(new X509AuthorityInformationAccessExtension(null, [Url("root.cer")])); } var intermediateSerial = Serial(); using var intermediateIssued = intermediateRequest.Create(root, DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddMonths(6), intermediateSerial); var intermediate = intermediateIssued.CopyWithPrivateKey(intermediateKey); using var signerKey = RSA.Create(2048); var signerRequest = new CertificateRequest("CN=signer.as4.test", signerKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); signerRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false)); signerRequest.CertificateExtensions.Add(CertificateRevocationListBuilder.BuildCrlDistributionPointExtension([Url("issuing.crl")])); signerRequest.CertificateExtensions.Add(new X509AuthorityInformationAccessExtension(null, [Url("issuing.cer")])); var signerSerial = Serial(); using var signerIssued = signerRequest.Create(intermediate, DateTimeOffset.UtcNow.AddHours(-12), DateTimeOffset.UtcNow.AddMonths(3), signerSerial); var signer = signerIssued.CopyWithPrivateKey(signerKey); _files[$"{_prefix}/root.cer"] = root.Export(X509ContentType.Cert); _files[$"{_prefix}/issuing.cer"] = intermediate.Export(X509ContentType.Cert); _files[$"{_prefix}/root.crl"] = Crl(root, revokeIntermediate ? intermediateSerial : null); if (publishSignerCrl) _files[$"{_prefix}/issuing.crl"] = Crl(intermediate, revokeSigner ? signerSerial : null); return (As4TestMessages.PublicOnly(root), As4TestMessages.PublicOnly(intermediate), signer); static byte[] Serial() { var serial = RandomNumberGenerator.GetBytes(16); // Positive and without a redundant leading byte (DER INTEGER): a first byte of zero followed by one below 0x80 // is refused by CertificateRevocationListBuilder.AddEntry, which a plain "& 0x7F" produced about once in 512. serial[0] = (byte)((serial[0] & 0x7F) | 0x40); return serial; } static byte[] Crl(X509Certificate2 issuer, byte[]? revoked) { var crl = new CertificateRevocationListBuilder(); if (revoked is not null) crl.AddEntry(revoked, DateTimeOffset.UtcNow.AddHours(-1), X509RevocationReason.KeyCompromise); return crl.Build(issuer, BigInteger.One, DateTimeOffset.UtcNow.AddDays(7), HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1, DateTimeOffset.UtcNow.AddMinutes(-5)); } } private async Task ServeAsync() { while (_listener.IsListening) { HttpListenerContext http; try { http = await _listener.GetContextAsync(); } catch (HttpListenerException) { return; } catch (ObjectDisposedException) { return; } catch (ArgumentException) when (!_listener.IsListening) { return; } if (_files.TryGetValue(http.Request.Url!.AbsolutePath, out var content)) { http.Response.StatusCode = 200; http.Response.ContentType = http.Request.Url.AbsolutePath.EndsWith(".crl") ? "application/pkix-crl" : "application/pkix-cert"; await http.Response.OutputStream.WriteAsync(content); } else { http.Response.StatusCode = 404; } http.Response.Close(); } } public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { _listener.Stop(); _listener.Close(); await _loop.ConfigureAwait(false); } } Path: redb-route/tests/redb.Route.Tests.As4/As4RouteXmlTests.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/tests/redb.Route.Tests.As4/As4RouteXmlTests.cs ---- using System.Net.Http.Headers; using System.Security.Cryptography.X509Certificates; using System.Text; using redb.Route.As4; using redb.Route.As4.Messaging; using redb.Route.As4.Mime; using redb.Route.As4.Security; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; using redb.Route.Xml; namespace redb.Route.Tests.As4; /// /// The AS4 node is written in Route-XML as its README shows — a <bean> whose Partners is a /// <list> of <ref> partners, certificates loaded by nested beans — and an as4: route from /// XML receives a message and answers with a receipt. The Route-XML grammar is the one XmlBeanListAndRefTests covers. /// public sealed class As4RouteXmlTests : IDisposable { private const string Password = "xml-test"; private static readonly X509Certificate2 NodeA = As4TestMessages.KeyPair("CN=a.as4.test"); private static readonly X509Certificate2 NodeB = As4TestMessages.KeyPair("CN=b.as4.test"); private readonly string _dir = Directory.CreateTempSubdirectory("redb-as4-xml-").FullName; public void Dispose() => Directory.Delete(_dir, recursive: true); [Fact] public async Task NodeAndRouteFromXml_ReceiveAMessage_AndAnswerWithAReceipt() { // The PFX through the X509Certificate2 constructor, the overload named by , which the README // shows with X509CertificateLoader; both are calls the markup has to reach. File.WriteAllBytes(Path.Combine(_dir, "b.pfx"), NodeB.Export(X509ContentType.Pfx, Password)); File.WriteAllBytes(Path.Combine(_dir, "a.cer"), NodeA.Export(X509ContentType.Cert)); var port = global::redb.Route.Tests.Shared.TestPorts.Next(); const string certificate = "System.Security.Cryptography.X509Certificates.X509Certificate2, System.Security.Cryptography"; await using var context = new RouteContext(); context.AddComponent(new As4Component()); var delivered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); context.AddRoutes(r => r.From("direct://as4-inbound").Process(e => delivered.TrySetResult(e.In.GetHeader(As4Headers.Partner)!))); context.AddXmlContextFromContent($""" """); context.AddXmlRoutesFromContent($""" """); await context.Start(); var (errorCode, receipt) = await Post(port); errorCode.Should().BeNull(); receipt.Should().BeTrue(); (await delivered.Task.WaitAsync(TimeSpan.FromSeconds(10))).Should().Be("a"); } [Fact] public async Task APartnerWithAnAddressInXml_IsSentToThere_FromAnEndpointWithoutOne() { // The address belongs to the agreement, as Protocol.Address belongs to a P-Mode: the markup sends to as4:?partner=a. File.WriteAllBytes(Path.Combine(_dir, "b.pfx"), NodeB.Export(X509ContentType.Pfx, Password)); File.WriteAllBytes(Path.Combine(_dir, "a.cer"), NodeA.Export(X509ContentType.Cert)); var port = global::redb.Route.Tests.Shared.TestPorts.Next(); const string certificate = "System.Security.Cryptography.X509Certificates.X509Certificate2, System.Security.Cryptography"; await using var context = new RouteContext(); context.AddComponent(new As4Component()); // Node a, in C#: it receives what node b sends. context.AddToRegistry("a", new As4ConnectionFactory { OurPartyId = "urn:redb:a", ExternalHostName = "a.example", SigningCertificate = NodeA, DecryptionCertificates = { NodeA }, Partners = { new As4Partner { Name = "b", PartyId = "urn:redb:b", Service = "urn:example", Action = "Submit", PartnerSigningCertificates = { As4TestMessages.PublicOnly(NodeB) }, PartnerEncryptionCertificate = As4TestMessages.PublicOnly(NodeB), RequireFourCornerProperties = false, }, }, }); context.AddIdempotentRepository("dedup", new InMemoryIdempotentRepository()); var delivered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); context.AddRoutes(r => r.From($"as4:/as4/in?host=127.0.0.1&port={port}&connectionFactory=a&idempotentRepository=dedup") .Process(e => delivered.TrySetResult(e.In.GetHeader(As4Headers.Partner)!))); context.AddXmlContextFromContent($""" """); context.AddXmlRoutesFromContent(""" """); await context.Start(); var template = new ProducerTemplate(context); template.Start(); await template.SendAsync("direct://as4-outbound", ""); (await delivered.Task.WaitAsync(TimeSpan.FromSeconds(10))).Should().Be("b"); } private async Task<(string? ErrorCode, bool Receipt)> Post(int port) { const string contentId = "p1@a.example"; using var message = SwaMessage.Create(As4TestMessages.UserMessage(Guid.NewGuid().ToString("N") + "@a.example", contentId, from: "urn:redb:a", to: "urn:redb:b", service: "urn:example", action: "Submit")); message.AddPart(contentId, "application/gzip", As4TestMessages.Gzip(Encoding.UTF8.GetBytes(""))); As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow); As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken); var (contentType, body) = message.Write(); using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(15) }; var content = new ByteArrayContent(body); content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType); using var response = await http.PostAsync($"http://127.0.0.1:{port}/as4/in", content); var answer = SwaMessage.Read(response.Content.Headers.ContentType!.ToString(), await response.Content.ReadAsByteArrayAsync(), 1024 * 1024); var signals = MessagingReader.Read(answer.Envelope).SignalMessages; return (signals.SelectMany(s => s.Errors).FirstOrDefault()?.ErrorCode, signals.Any(s => s.IsReceipt)); } } Path: redb-route/tests/redb.Route.Tests.As4/As4SecurityRoundTripTests.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/tests/redb.Route.Tests.As4/As4SecurityRoundTripTests.cs ---- using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Xml; using redb.Route.As4; using redb.Route.As4.Mime; using redb.Route.As4.Security; namespace redb.Route.Tests.As4; /// /// What we sign and encrypt, we decrypt and verify — through the wire format (serialized, parsed back), /// for every key reference form, and every tampering is refused for its own reason. Keys are generated /// in memory; no harness needed. /// public class As4SecurityRoundTripTests { private static readonly X509Certificate2 Sender = KeyPair("CN=sender.as4.test"); private static readonly X509Certificate2 Receiver = KeyPair("CN=receiver.as4.test"); private static readonly X509Certificate2 Stranger = KeyPair("CN=stranger.as4.test"); private static readonly TimeSpan Tolerance = TimeSpan.FromMinutes(5); private static readonly byte[] Payload = Encoding.UTF8.GetBytes("42"); [Theory] [InlineData(As4KeyReference.BinarySecurityToken)] [InlineData(As4KeyReference.IssuerSerial)] [InlineData(As4KeyReference.KeyIdentifier)] public void SignEncrypt_ThenDecryptVerify_ReturnsThePayload(As4KeyReference form) { var received = Transfer(Build(form, timestamp: true)); var decrypted = As4SecurityEngine.Decrypt(received, [Receiver]); var verification = As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow); decrypted.Should().ContainSingle(); verification.Signer.Thumbprint.Should().Be(Sender.Thumbprint); verification.References.Should().HaveCount(4); // eb:Messaging, Body, wsu:Timestamp, attachment var part = received.Parts[decrypted[0]]; part.ContentType.Should().Be("application/gzip"); Gunzip(part.ToArray()).Should().Equal(Payload); } [Fact] public void WhatWeSend_NamesExactlyTheAlgorithmsAndTransformsOfTheProfile() { // What a conformance test driver reads off a message the SUT sent (eDelivery AS4 1.16 §3.2.6; testing service // 2026.06: encryption algorithm, signature algorithm, attachment signing and encryption transforms, WSS 1.1). var envelope = Build(As4KeyReference.BinarySecurityToken, timestamp: false).Message.Envelope; string[] Algorithms(string localName, string ns) => envelope.GetElementsByTagName(localName, ns) .Cast().Select(e => e.GetAttribute("Algorithm")).ToArray(); envelope.DocumentElement!.NamespaceURI.Should().Be("http://www.w3.org/2003/05/soap-envelope", "SOAP 1.2"); // Payloads travel as attachments: the SOAP body is empty, and it is signed all the same (AS4_CP_TA05, TA12). var body = (XmlElement)envelope.GetElementsByTagName("Body", "http://www.w3.org/2003/05/soap-envelope")[0]!; body.HasChildNodes.Should().BeFalse(); var bodyId = body.GetAttribute("Id", WsSecurityNames.Wsu); envelope.GetElementsByTagName("Reference", WsSecurityNames.Ds).Cast().Select(r => r.GetAttribute("URI")) .Should().Contain("#" + bodyId); // Signature: RSA-SHA256 over SHA-256 digests, exclusive canonicalization; the attachment by its content. Algorithms("SignatureMethod", WsSecurityNames.Ds).Should().Equal("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"); Algorithms("CanonicalizationMethod", WsSecurityNames.Ds).Should().Equal("http://www.w3.org/2001/10/xml-exc-c14n#"); Algorithms("DigestMethod", WsSecurityNames.Ds).Should().OnlyContain(a => a == "http://www.w3.org/2001/04/xmlenc#sha256"); var references = envelope.GetElementsByTagName("Reference", WsSecurityNames.Ds).Cast().ToList(); references.Select(r => r.GetAttribute("URI")).Should().Contain("cid:payload-1@redb.test"); references.Single(r => r.GetAttribute("URI").StartsWith("cid:", StringComparison.Ordinal)) .GetElementsByTagName("Transform", WsSecurityNames.Ds).Cast().Select(t => t.GetAttribute("Algorithm")) .Should().Equal("http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Content-Signature-Transform"); // Key transport: RSA-OAEP with MGF1-SHA256 and a SHA-256 digest (XML Encryption 1.1). var encryptedKey = (XmlElement)envelope.GetElementsByTagName("EncryptedKey", WsSecurityNames.Xenc)[0]!; var keyMethod = (XmlElement)encryptedKey.GetElementsByTagName("EncryptionMethod", WsSecurityNames.Xenc)[0]!; keyMethod.GetAttribute("Algorithm").Should().Be("http://www.w3.org/2009/xmlenc11#rsa-oaep"); ((XmlElement)keyMethod.GetElementsByTagName("MGF", WsSecurityNames.Xenc11)[0]!).GetAttribute("Algorithm") .Should().Be("http://www.w3.org/2009/xmlenc11#mgf1sha256"); ((XmlElement)keyMethod.GetElementsByTagName("DigestMethod", WsSecurityNames.Ds)[0]!).GetAttribute("Algorithm") .Should().Be("http://www.w3.org/2001/04/xmlenc#sha256"); // Payload: AES-128-GCM, the ciphertext in place of the attachment's content, the attachment content only. var encryptedData = (XmlElement)envelope.GetElementsByTagName("EncryptedData", WsSecurityNames.Xenc)[0]!; encryptedData.GetAttribute("Type").Should().Be("http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Content-Only"); ((XmlElement)encryptedData.GetElementsByTagName("EncryptionMethod", WsSecurityNames.Xenc)[0]!).GetAttribute("Algorithm") .Should().Be("http://www.w3.org/2009/xmlenc11#aes128-gcm"); var cipherReference = (XmlElement)encryptedData.GetElementsByTagName("CipherReference", WsSecurityNames.Xenc)[0]!; cipherReference.GetAttribute("URI").Should().Be("cid:payload-1@redb.test"); cipherReference.GetElementsByTagName("Transform", WsSecurityNames.Ds).Cast().Select(t => t.GetAttribute("Algorithm")) .Should().Equal("http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Ciphertext-Transform"); // Only the payload is encrypted: the ebMS header travels in the clear (profile §3.2.6). envelope.GetElementsByTagName("Messaging", WsSecurityNames.Eb).Count.Should().Be(1); envelope.GetElementsByTagName("EncryptedData", WsSecurityNames.Xenc).Count.Should().Be(1); } [Fact] public void Sign_ReturnsTheReferencesTheReceiverSees() { var sent = Build(As4KeyReference.BinarySecurityToken, timestamp: false); var sentReferences = sent.References.Select(r => r.OuterXml).ToList(); var received = Transfer(sent.Message); As4SecurityEngine.Decrypt(received, [Receiver]); var verification = As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow); verification.References.Select(r => r.OuterXml).Should().Equal(sentReferences); } [Fact] public void Verify_TamperedHeaderAfterSigning_IsRefused() { var received = Transfer(Build(As4KeyReference.BinarySecurityToken, timestamp: false)); As4SecurityEngine.Decrypt(received, [Receiver]); ((XmlElement)received.Envelope.GetElementsByTagName("Action", WsSecurityNames.Eb)[0]!).InnerText = "Refund"; var act = () => As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*digest of*does not match*"); } [Fact] public void Verify_TamperedSignedInfo_IsRefused() { var received = Transfer(Build(As4KeyReference.BinarySecurityToken, timestamp: false)); As4SecurityEngine.Decrypt(received, [Receiver]); // Rewriting a digest value together with the element it covers leaves the references consistent; only // the signature over SignedInfo can notice. var digest = (XmlElement)received.Envelope.GetElementsByTagName("DigestValue", WsSecurityNames.Ds)[0]!; digest.InnerText = Convert.ToBase64String(new byte[32]); var act = () => As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("The signature does not verify."); } [Theory] // The signature over SignedInfo is checked first, and a DigestValue is part of SignedInfo. [InlineData("SignatureValue", "ds:SignatureValue is not valid base64.")] [InlineData("DigestValue", "The signature does not verify.")] public void Verify_ValueThatIsNotBase64_IsRefusedAsASecurityFailure(string element, string reason) { // A security failure (EBMS:0101), not an unexpected failure of the receiver (AS4_CP_TA66). var received = Transfer(Build(As4KeyReference.BinarySecurityToken, timestamp: false)); As4SecurityEngine.Decrypt(received, [Receiver]); ((XmlElement)received.Envelope.GetElementsByTagName(element, WsSecurityNames.Ds)[0]!).InnerText = "not*base64!"; var act = () => As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow); act.Should().Throw().WithMessage(reason); } [Fact] public void Verify_SignatureValueThatIsNotBase64_IsAMalformedSignatureValue() { // AS4_CP_TA66: answered with EBMS:0102; a value that decodes and does not verify stays EBMS:0101. var received = Transfer(Build(As4KeyReference.BinarySecurityToken, timestamp: false)); As4SecurityEngine.Decrypt(received, [Receiver]); ((XmlElement)received.Envelope.GetElementsByTagName("SignatureValue", WsSecurityNames.Ds)[0]!).InnerText = "not*base64!"; var act = () => As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow); act.Should().Throw(); } [Fact] public void Decrypt_CipherValueThatIsNotBase64_IsRefusedAsASecurityFailure() { var received = Transfer(Build(As4KeyReference.BinarySecurityToken, timestamp: false)); ((XmlElement)received.Envelope.GetElementsByTagName("CipherValue", WsSecurityNames.Xenc)[0]!).InnerText = "not*base64!"; var act = () => As4SecurityEngine.Decrypt(received, [Receiver]); act.Should().Throw().WithMessage("xenc:CipherValue is not valid base64."); } // A value whose last character has non-zero unused bits decodes to the right bytes on .NET 10, so without the check the // message below would decrypt and verify there and be refused on .NET 11. XML Schema base64Binary forbids that spelling: // refused on every runtime, for the same reason as any other malformed value. [Fact] public void Verify_SignatureValueWithUnusedBitsSet_IsAMalformedSignatureValue() { var received = Transfer(Build(As4KeyReference.BinarySecurityToken, timestamp: false)); As4SecurityEngine.Decrypt(received, [Receiver]); var value = (XmlElement)received.Envelope.GetElementsByTagName("SignatureValue", WsSecurityNames.Ds)[0]!; value.InnerText = As4TestMessages.WithUnusedBitsSet(value.InnerText); var act = () => As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("ds:SignatureValue is not valid base64."); } [Fact] public void Verify_DigestValueWithUnusedBitsSet_IsRefused() { var received = Transfer(Build(As4KeyReference.BinarySecurityToken, timestamp: false)); As4SecurityEngine.Decrypt(received, [Receiver]); var digest = (XmlElement)received.Envelope.GetElementsByTagName("DigestValue", WsSecurityNames.Ds)[0]!; digest.InnerText = As4TestMessages.WithUnusedBitsSet(digest.InnerText); Resign(received.Envelope, Sender); // SignedInfo itself verifies, only the digest value is judged var act = () => As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("ds:DigestValue is not valid base64."); } [Fact] public void Decrypt_CipherValueWithUnusedBitsSet_IsRefused() { var received = Transfer(Build(As4KeyReference.BinarySecurityToken, timestamp: false)); var value = (XmlElement)received.Envelope.GetElementsByTagName("CipherValue", WsSecurityNames.Xenc)[0]!; value.InnerText = As4TestMessages.WithUnusedBitsSet(value.InnerText); var act = () => As4SecurityEngine.Decrypt(received, [Receiver]); act.Should().Throw().WithMessage("xenc:CipherValue is not valid base64."); } [Fact] public void Verify_SignedByAStranger_IsRefused() { var received = Transfer(Build(As4KeyReference.BinarySecurityToken, timestamp: false)); As4SecurityEngine.Decrypt(received, [Receiver]); var act = () => As4SecurityEngine.Verify(received, [PublicOnly(Stranger)], Tolerance, DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*not one of the partner's*"); } [Theory] [InlineData(As4KeyReference.BinarySecurityToken)] [InlineData(As4KeyReference.IssuerSerial)] public void Verify_SignedWithTheCertificateOfAnotherKnownParty_IsNotAuthorized(As4KeyReference form) { // AS4_CP_TA78: a certificate the node trusts, but not the sender's: EBMS:0004, not 0101. var received = Transfer(Build(form, timestamp: false)); As4SecurityEngine.Decrypt(received, [Receiver]); var act = () => As4SecurityEngine.Verify(received, [PublicOnly(Stranger)], Tolerance, DateTimeOffset.UtcNow, trustedElsewhere: [PublicOnly(Sender)]); act.Should().Throw(); } [Theory] [InlineData(As4KeyReference.BinarySecurityToken)] [InlineData(As4KeyReference.IssuerSerial)] public void Verify_SignedWithACertificateOfATrustedAuthority_IsNotAuthorized(As4KeyReference form) { // The certificate itself is known nowhere; with an issuer-serial reference only its issuer is seen. var (authority, otherParty) = IssuedByAnAuthority(); var received = Transfer(Build(form, timestamp: false, otherParty)); As4SecurityEngine.Decrypt(received, [Receiver]); var act = () => As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow, trustedElsewhere: [authority]); act.Should().Throw(); } [Theory] [InlineData(As4KeyReference.BinarySecurityToken)] [InlineData(As4KeyReference.IssuerSerial)] public void Verify_AStrangerBesideTrustedAuthorities_StaysAnAuthenticationFailure(As4KeyReference form) { // AS4_CP_TA77: issued by an authority the node does not trust; and a self-signed impostor whose issuer name is // the subject of a trusted certificate that is no authority. var (authority, _) = IssuedByAnAuthority(); var impostor = KeyPair(Sender.Subject); var received = Transfer(Build(form, timestamp: false, impostor)); As4SecurityEngine.Decrypt(received, [Receiver]); var act = () => As4SecurityEngine.Verify(received, [PublicOnly(Stranger)], Tolerance, DateTimeOffset.UtcNow, trustedElsewhere: [authority, PublicOnly(Sender)]); act.Should().Throw().WithMessage("*not one of the partner's*") .Which.Should().NotBeOfType(); } [Fact] public void Verify_AttachmentSignedWithAttachmentComplete_IsAnUnsupportedTransform() { // AS4_CP_TA72: a valid signature whose attachment reference uses the transform the profile forbids: EBMS:0102. var received = Transfer(Build(As4KeyReference.BinarySecurityToken, timestamp: false)); As4SecurityEngine.Decrypt(received, [Receiver]); var transform = received.Envelope.GetElementsByTagName("Transform", WsSecurityNames.Ds).Cast() .Single(t => t.GetAttribute("Algorithm") == "http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Content-Signature-Transform"); transform.SetAttribute("Algorithm", "http://docs.oasis-open.org/wss/oasis-wss-SwAProfile-1.1#Attachment-Complete-Signature-Transform"); Resign(received.Envelope, Sender); var act = () => As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*Attachment-Complete*not supported*"); } [Theory] [InlineData(As4KeyReference.BinarySecurityToken)] [InlineData(As4KeyReference.IssuerSerial)] public void Verify_AStrangerWithThePartnersSubject_IsRefused(As4KeyReference form) { // Same subject (and, self-signed, the same issuer name) as the partner, another key and serial number. var impostor = KeyPair(Sender.Subject); var received = Transfer(Build(form, timestamp: false, impostor)); As4SecurityEngine.Decrypt(received, [Receiver]); var act = () => As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*not one of the partner's*"); } [Theory] [InlineData(2 * 365, "*expired*")] // past NotAfter (the certificate lives a year) [InlineData(-2, "*not yet valid*")] // before NotBefore (a day before issue) public void Verify_OutsideTheSignersValidity_IsRefused(int daysFromNow, string reason) { // Domibus default (domibus.sender.certificate.validation.onreceiving=true): a pinned certificate is still // checked for its validity period. The time is the verifier's clock, the same one the timestamp is checked by. var received = Transfer(Build(As4KeyReference.BinarySecurityToken, timestamp: false)); As4SecurityEngine.Decrypt(received, [Receiver]); var act = () => As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow.AddDays(daysFromNow)); act.Should().Throw().WithMessage(reason); } [Fact] public void Verify_ExpiredTimestamp_IsRefused() { var received = Transfer(Build(As4KeyReference.BinarySecurityToken, timestamp: true)); As4SecurityEngine.Decrypt(received, [Receiver]); // Age allowed for two hours, so it is Expires (5 minutes) that refuses it. var act = () => As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow.AddHours(1), timestampTimeToLive: TimeSpan.FromHours(2)); act.Should().Throw().WithMessage("*Timestamp has expired*"); } [Fact] public void Verify_UnsignedAttachmentAddedLater_IsRefused() { var received = Transfer(Build(As4KeyReference.BinarySecurityToken, timestamp: false)); As4SecurityEngine.Decrypt(received, [Receiver]); received.AddPart("smuggled@example", "application/octet-stream", [1, 2, 3]); var act = () => As4SecurityEngine.Verify(received, [PublicOnly(Sender)], Tolerance, DateTimeOffset.UtcNow); act.Should().Throw().WithMessage("*does not cover the attachment 'smuggled@example'*"); } [Fact] public void Decrypt_ForSomeoneElse_IsRefused() { var received = Transfer(Build(As4KeyReference.BinarySecurityToken, timestamp: false)); var act = () => As4SecurityEngine.Decrypt(received, [Stranger]); act.Should().Throw().WithMessage("*not for any of our certificates*"); } [Fact] public void Decrypt_TamperedCiphertext_IsRefused() { var received = Transfer(Build(As4KeyReference.BinarySecurityToken, timestamp: false)); As4TestMessages.Flip(received.Parts.Values.Single(), 20); var act = () => As4SecurityEngine.Decrypt(received, [Receiver]); act.Should().Throw(); } [Fact] public void Envelope_WithADoctype_IsRefusedBeforeAnyProcessing() { var (contentType, body) = Build(As4KeyReference.BinarySecurityToken, timestamp: false).Message.Write(); var text = Encoding.UTF8.GetString(body).Replace("]> SwaMessage.Read(contentType, Encoding.UTF8.GetBytes(text), 1024 * 1024); act.Should().Throw(); } // ── Fixtures ───────────────────────────────────────────────────────────── private sealed record Sent(SwaMessage Message, IReadOnlyList References); private static Sent Build(As4KeyReference form, bool timestamp) => Build(form, timestamp, Sender); private static Sent Build(As4KeyReference form, bool timestamp, X509Certificate2 signer) { const string contentId = "payload-1@redb.test"; var envelope = As4TestMessages.UserMessage("m-1@redb.test", contentId); var message = SwaMessage.Create(envelope); message.AddPart(contentId, "application/gzip", Gzip(Payload)); var references = As4SecurityEngine.Sign(message, signer, form, timestamp ? TimeSpan.FromMinutes(5) : null, DateTimeOffset.UtcNow); As4SecurityEngine.Encrypt(message, PublicOnly(Receiver), form); return new Sent(message, references); } private static SwaMessage Transfer(SwaMessage message) { var (contentType, body) = message.Write(); return SwaMessage.Read(contentType, body, 1024 * 1024); } private static SwaMessage Transfer(Sent sent) => Transfer(sent.Message); private static X509Certificate2 KeyPair(string subject) { using var rsa = RSA.Create(2048); var request = new CertificateRequest(subject, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, critical: false)); using var created = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1)); // Round-trip through PFX so the key is usable for decryption on every platform. return X509CertificateLoader.LoadPkcs12(created.Export(X509ContentType.Pfx), null, X509KeyStorageFlags.Exportable); } private static X509Certificate2 PublicOnly(X509Certificate2 certificate) => X509CertificateLoader.LoadCertificate(certificate.Export(X509ContentType.Cert)); /// An authority (public part only) and a certificate with its key that it issued to another party. private static (X509Certificate2 Authority, X509Certificate2 Issued) IssuedByAnAuthority() { using var authorityKey = RSA.Create(2048); var authorityRequest = new CertificateRequest("CN=Trusted Test CA, O=redb test", authorityKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); authorityRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); authorityRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign, true)); using var authority = authorityRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1)); using var key = RSA.Create(2048); var request = new CertificateRequest("CN=other party, O=redb test", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509SubjectKeyIdentifierExtension(request.PublicKey, critical: false)); using var issued = request.Create(authority, DateTimeOffset.UtcNow.AddHours(-1), DateTimeOffset.UtcNow.AddMonths(6), [1, 2, 3, 4, 5, 6, 7, 8]); using var withKey = issued.CopyWithPrivateKey(key); return (PublicOnly(authority), X509CertificateLoader.LoadPkcs12(withKey.Export(X509ContentType.Pfx), null, X509KeyStorageFlags.Exportable)); } /// Signs SignedInfo again after a test changed it, so that only the change itself is judged. private static void Resign(XmlDocument envelope, X509Certificate2 signer) { var signedInfo = (XmlElement)envelope.GetElementsByTagName("SignedInfo", WsSecurityNames.Ds)[0]!; var c14nMethod = (XmlElement)signedInfo.GetElementsByTagName("CanonicalizationMethod", WsSecurityNames.Ds)[0]!; var canonical = ExclusiveCanonicalizer.Canonicalize(signedInfo, ExclusiveCanonicalizer.PrefixList(c14nMethod)); using var rsa = signer.GetRSAPrivateKey()!; ((XmlElement)envelope.GetElementsByTagName("SignatureValue", WsSecurityNames.Ds)[0]!).InnerText = Convert.ToBase64String(rsa.SignData(canonical, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1)); } private static byte[] Gzip(byte[] data) => As4TestMessages.Gzip(data); private static byte[] Gunzip(byte[] data) => As4TestMessages.Gunzip(data); } Path: redb-route/tests/redb.Route.Tests.As4/As4SkeletonTests.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/tests/redb.Route.Tests.As4/As4SkeletonTests.cs ---- using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using redb.Route.Abstractions; using redb.Route.As4; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; using As4Dsl = redb.Route.As4.Fluent.As4; namespace redb.Route.Tests.As4; /// /// Skeleton tests: DSL URIs, option binding and validation, secret redaction, scheme registration, and /// resolution of the node and its partners from the registry when an endpoint starts. No AS4 traffic yet. /// public class As4SkeletonTests { // ── DSL ────────────────────────────────────────────────────────────────── [Fact] public void Receive_KeepsFullPath() { string uri = As4Dsl.Receive("/as4/in").Host("0.0.0.0").Port(4090).ConnectionFactory("node"); uri.Should().Be("as4:/as4/in?host=0.0.0.0&port=4090&connectionFactory=node"); EndpointUriParser.Parse(uri).Path.Should().Be("/as4/in"); } [Fact] public void Receive_WithTls_UsesAs4sScheme() { ((string)As4Dsl.Receive("as4/in").Tls()).Should().StartWith("as4s:/as4/in"); } [Fact] public void Send_ToAnAddressWithAQuery_CarriesItInAddressQuery() { // The query of an as4: URI holds the endpoint's options (as http:'s does): the address's own query is one value. var builder = As4Dsl.Send("https://ap.partner/domibus?domain=a&tenant=7").ConnectionFactory("node"); string uri = builder; uri.Should().Be("as4s://ap.partner/domibus?addressQuery=" + Uri.EscapeDataString("domain=a&tenant=7") + "&connectionFactory=node"); ((string)builder).Should().Be(uri, "building twice gives the same URI"); using var ctx = new RouteContext(); ctx.AddComponent(new As4Component()); ((As4Endpoint)ctx.GetEndpoint(uri)).PartnerUrl.Should().Be("https://ap.partner/domibus?domain=a&tenant=7"); } [Theory] [InlineData("https://ap.partner/as4#part")] [InlineData("https://ap.partner/as4?a=1#part")] public void Send_ToAnAddressWithAFragment_IsRefused(string address) { var act = () => As4Dsl.Send(address).Build(); act.Should().Throw().WithMessage("*fragment*"); } [Theory] [InlineData("?domain=a")] [InlineData("domain=a#x")] public void Options_Validate_AMalformedAddressQuery_Throws(string query) { var options = new As4EndpointOptions { ConnectionFactory = "node", AddressQuery = query }; options.Invoking(o => o.Validate()).Should().Throw().WithMessage("*addressQuery*"); } [Fact] public void Send_MapsHttpsToAs4s_AndKeepsExpressions() { string uri = As4Dsl.Send("https://ap.acme.example/as4").ConnectionFactory("node").Partner("${header.partner}"); uri.Should().Be("as4s://ap.acme.example/as4?connectionFactory=node&partner=" + Uri.EscapeDataString("${header.partner}")); ((string)As4Dsl.Send("http://ap/as4")).Should().Be("as4://ap/as4"); } [Fact] public void Builder_LastValueOfAnOptionWins() { ((string)As4Dsl.Send("https://ap/as4").Partner("a").Partner("b")).Should().Be("as4s://ap/as4?partner=b"); } // ── Options ────────────────────────────────────────────────────────────── [Fact] public void Options_BindFromUri_MapsTypedAndDynamicValues() { var o = new As4EndpointOptions(); o.BindFromUri(new Dictionary { ["connectionFactory"] = "node", ["partner"] = "acme", ["action"] = "${header.docType}", ["port"] = "5443", ["maxEnvelopeCharacters"] = "2048", ["clientCertificateMode"] = "RequireCertificate", }); o.ConnectionFactory.Should().Be("node"); o.Partner!.Value.IsDynamic.Should().BeFalse(); o.Action!.Value.IsDynamic.Should().BeTrue(); o.Port.Should().Be(5443); o.MaxEnvelopeCharacters.Should().Be(2048); o.ClientCertificateMode.Should().Be(As4ClientCertificateMode.RequireCertificate); } [Fact] public void Options_Validate_RequiresConnectionFactory() { var act = () => new As4EndpointOptions().Validate(); act.Should().Throw().WithMessage("*connectionFactory*"); } [Fact] public void Options_Validate_AcceptsMinimal() { var act = () => new As4EndpointOptions { ConnectionFactory = "node" }.Validate(); act.Should().NotThrow(); } [Theory] [InlineData(0)] [InlineData(70000)] public void Options_Validate_BadPort_Throws(int port) { var act = () => new As4EndpointOptions { ConnectionFactory = "node", Port = port }.Validate(); act.Should().Throw(); } [Fact] public void Options_Validate_ClientCertificateWithoutTls_Throws() { var act = () => new As4EndpointOptions { ConnectionFactory = "node", ClientCertificateMode = As4ClientCertificateMode.RequireCertificate, }.Validate(); act.Should().Throw().WithMessage("*TLS*"); } [Fact] public void Options_Validate_NonPositiveEnvelopeBound_Throws() { var act = () => new As4EndpointOptions { ConnectionFactory = "node", MaxEnvelopeCharacters = 0 }.Validate(); act.Should().Throw(); } [Fact] public void SslCertPassword_IsRedactedInUri() { new As4EndpointOptions().BindFromUri(new Dictionary { ["sslCertPassword"] = "s3cr3t" }); var masked = EndpointUri.Sanitize("as4s:/as4/in?connectionFactory=node&sslCertPassword=s3cr3t"); masked.Should().NotContain("s3cr3t").And.Contain(EndpointUri.Redacted); } // ── Component ──────────────────────────────────────────────────────────── [Fact] public void Component_ResolvesAs4Scheme() { using var ctx = new RouteContext(); ctx.AddComponent(new As4Component()); ctx.GetEndpoint(As4Dsl.Receive("/as4/in").ConnectionFactory("node")).Should().BeOfType(); } [Fact] public void Component_As4s_SetsTls_AndRebuildsPartnerUrl() { using var ctx = new RouteContext(); ctx.AddComponent(new As4Component()); var endpoint = (As4Endpoint)ctx.GetEndpoint(As4Dsl.Send("https://ap.acme.example:8443/as4").ConnectionFactory("node")); endpoint.EndpointOptions.UseTls.Should().BeTrue(); endpoint.PartnerUrl.Should().Be("https://ap.acme.example:8443/as4"); } [Fact] public void Component_ReceiveUri_HasNoPartnerUrl() { using var ctx = new RouteContext(); ctx.AddComponent(new As4Component()); ((As4Endpoint)ctx.GetEndpoint(As4Dsl.Receive("/as4/in").ConnectionFactory("node"))).PartnerUrl.Should().BeNull(); } // ── Node resolution ────────────────────────────────────────────────────── [Fact] public void Node_Resolves_FactoryAndPartners() { using var ctx = NewContext(); var node = As4Node.Resolve(ctx, "node"); node.Partners.Keys.Should().BeEquivalentTo("acme"); } [Fact] public void Node_UnknownFactory_NamesIt() { using var ctx = new RouteContext(); var act = () => As4Node.Resolve(ctx, "missing"); act.Should().Throw().WithMessage("*missing*"); } [Fact] public void Node_SigningCertificateWithoutPrivateKey_Throws() { using var ctx = NewContext(factory: f => f.SigningCertificate = PublicOnly(OurCertificate)); var act = () => As4Node.Resolve(ctx, "node"); act.Should().Throw().WithMessage("*SigningCertificate*private key*"); } [Fact] public void Node_WithoutPartners_Throws() { using var ctx = NewContext(factory: f => f.Partners.Clear()); var act = () => As4Node.Resolve(ctx, "node"); act.Should().Throw().WithMessage("*Partners is empty*"); } [Fact] public void Node_PartnerWithoutName_Throws() { using var ctx = NewContext(partner: p => p.Name = null); var act = () => As4Node.Resolve(ctx, "node"); act.Should().Throw().WithMessage("*no Name*acme*"); } [Fact] public void Node_RepeatedPartnerName_Throws() { using var ctx = NewContext(factory: f => f.Partners.Add(NewPartner(p => p.PartyId = "other"))); var act = () => As4Node.Resolve(ctx, "node"); act.Should().Throw().WithMessage("*names repeat*acme*"); } [Fact] public void Node_DecryptionCertificateWithoutPrivateKey_Throws() { using var ctx = NewContext(factory: f => f.DecryptionCertificates.Add(PartnerCertificate)); var act = () => As4Node.Resolve(ctx, "node"); act.Should().Throw().WithMessage("*DecryptionCertificates*private key*"); } [Fact] public void Node_PartnerWithoutSigningCertificate_Throws() { using var ctx = NewContext(partner: p => p.PartnerSigningCertificates.Clear()); var act = () => As4Node.Resolve(ctx, "node"); act.Should().Throw().WithMessage("*'acme'*PartnerSigningCertificates*"); } [Fact] public void Node_PartnerWithoutEncryptionCertificate_Throws() { using var ctx = NewContext(partner: p => p.PartnerEncryptionCertificate = null); var act = () => As4Node.Resolve(ctx, "node"); act.Should().Throw().WithMessage("*'acme'*PartnerEncryptionCertificate*"); } [Fact] public void Node_UnsupportedAlgorithm_Throws() { using var ctx = NewContext(partner: p => p.DataEncryptionAlgorithm = "http://www.w3.org/2001/04/xmlenc#aes128-cbc"); var act = () => As4Node.Resolve(ctx, "node"); act.Should().Throw().WithMessage("*data encryption*aes128-cbc*"); } [Fact] public void Node_ReplyLegWithoutAction_Throws() { using var ctx = NewContext(partner: p => p.ReplyLeg = new As4Leg { Service = "svc" }); var act = () => As4Node.Resolve(ctx, "node"); act.Should().Throw().WithMessage("*reply leg*Action*"); } [Fact] public void Node_TwoPartnersIndistinguishableOnReceipt_Throws() { using var ctx = NewContext(factory: f => f.Partners.Add(NewPartner(p => p.Name = "acme2"))); var act = () => As4Node.Resolve(ctx, "node"); act.Should().Throw().WithMessage("*'acme'*'acme2'*could not be matched*"); } [Fact] public void Node_OneAgreementForManyPartners_IsFine() { using var ctx = NewContext( factory: f => f.Partners.Add(NewPartner(p => { p.Name = "globex"; p.PartyId = "globex"; p.AgreementRef = "urn:agreement"; })), partner: p => p.AgreementRef = "urn:agreement"); var act = () => As4Node.Resolve(ctx, "node"); act.Should().NotThrow(); } [Fact] public void Node_AReplyLegWithTheValuesOfItsOwnRequestLeg_IsFine() { // A Two-Way exchange answered under the same service and action: either leg is this partner's. using var ctx = NewContext(partner: p => p.ReplyLeg = new As4Leg { Service = p.Service, ServiceType = p.ServiceType, Action = p.Action }); var act = () => As4Node.Resolve(ctx, "node"); act.Should().NotThrow(); } // ── Start-time checks ──────────────────────────────────────────────────── [Fact] public async Task Producer_Start_ResolvesNode() { using var ctx = NewContext(); var producer = SendProducer(ctx, "partner=acme"); await producer.Start(); producer.IsStarted.Should().BeTrue(); producer.Node!.Partners.Should().ContainKey("acme"); } [Fact] public async Task Producer_Start_UnknownStaticPartner_Throws() { using var ctx = NewContext(); var producer = SendProducer(ctx, "partner=globex"); var act = () => producer.Start(); await act.Should().ThrowAsync().WithMessage("*globex*not a partner*"); } [Fact] public async Task Producer_Start_DynamicPartner_IsCheckedPerMessage() { using var ctx = NewContext(); var producer = SendProducer(ctx, "partner=" + Uri.EscapeDataString("${header.partner}")); await producer.Start(); producer.IsStarted.Should().BeTrue(); } // ── Where a message goes: the endpoint's address or the partner's ─────────── [Fact] public void Send_WithoutAnAddress_IsTheAs4FormWithoutAPath() { ((string)As4Dsl.Send().ConnectionFactory("node").Partner("acme")).Should().Be("as4:?connectionFactory=node&partner=acme"); } [Fact] public async Task Producer_Start_WithThePartnersAddress_TakesIt() { using var ctx = NewContext(partner: p => p.Address = "https://ap.acme.example/domibus?domain=x"); var producer = (As4Producer)ctx.GetEndpoint(As4Dsl.Send().ConnectionFactory("node").Partner("acme")).CreateProducer(); await producer.Start(); producer.IsStarted.Should().BeTrue(); } [Fact] public async Task Producer_Start_WithoutAnyAddress_Throws() { using var ctx = NewContext(); var producer = (As4Producer)ctx.GetEndpoint(As4Dsl.Send().ConnectionFactory("node").Partner("acme")).CreateProducer(); var act = () => producer.Start(); await act.Should().ThrowAsync().WithMessage("*no address*acme*no Address*"); } [Fact] public async Task Producer_Start_WithAnAddressInBothPlaces_Throws() { using var ctx = NewContext(partner: p => p.Address = "https://ap.acme.example/as4"); var producer = SendProducer(ctx, "partner=acme"); var act = () => producer.Start(); await act.Should().ThrowAsync().WithMessage("*one place*"); } [Theory] [InlineData("as4s:?connectionFactory=node&partner=acme")] [InlineData("as4:?connectionFactory=node&partner=acme&addressQuery=domain%3Dx")] public void Producer_WithoutAnAddress_RefusesWhatOnlyAnAddressCarries(string uri) { using var ctx = NewContext(partner: p => p.Address = "https://ap.acme.example/as4"); var act = () => ctx.GetEndpoint(uri).CreateProducer(); act.Should().Throw().WithMessage("*as4s and addressQuery*"); } [Fact] public void Producer_OnAReceivePath_Throws() { using var ctx = NewContext(); var act = () => ctx.GetEndpoint("as4:/as4/in?connectionFactory=node&partner=acme").CreateProducer(); act.Should().Throw().WithMessage("*receive path*"); } [Theory] [InlineData("ap.acme.example/as4")] [InlineData("ftp://ap.acme.example/as4")] [InlineData("https://ap.acme.example/as4#part")] public void Node_PartnerWithAMalformedAddress_Throws(string address) { using var ctx = NewContext(partner: p => p.Address = address); var act = () => As4Node.Resolve(ctx, "node"); act.Should().Throw().WithMessage("*Address*"); } [Fact] public async Task Producer_Start_WithoutPartner_Throws() { using var ctx = NewContext(); var producer = SendProducer(ctx, null); var act = () => producer.Start(); await act.Should().ThrowAsync().WithMessage("*partner*"); } [Fact] public void Options_Validate_Transacted_Throws() { var act = () => new As4EndpointOptions { ConnectionFactory = "node", Transacted = true }.Validate(); act.Should().Throw().WithMessage("*transacted*receipt*"); } [Fact] public void Endpoint_WithAMisspeltOption_IsRefused_NamingTheNearestOne() { using var ctx = NewContext(); var act = () => ctx.GetEndpoint("as4:/as4/in?connectionFactory=node&idempotentRepositry=dedup"); act.Should().Throw().WithMessage("*'idempotentRepositry' is not an option*Did you mean 'idempotentRepository'?*"); } [Fact] public void Endpoint_WithAnUnconvertibleValue_IsRefused() { using var ctx = NewContext(); var act = () => ctx.GetEndpoint("as4:/as4/in?connectionFactory=node&port=http"); act.Should().Throw().WithMessage("*port*"); } [Fact] public void Endpoint_WithTransacted_IsRefusedWhenTheUriIsBound() { using var ctx = NewContext(); var act = () => ctx.GetEndpoint("as4://partner.example/as4?connectionFactory=node&partner=acme&transacted=true"); act.Should().Throw().WithMessage("*transacted*"); } [Fact] public void Consumer_WithPartner_IsRefused_WhenCreated() { using var ctx = NewContext(); var act = () => ctx.GetEndpoint("as4:/as4/in?connectionFactory=node&partner=acme&idempotentRepository=dedup").CreateConsumer(Substitute.For()); act.Should().Throw().WithMessage("*partner*"); } [Theory] [InlineData("timeout=5000")] [InlineData("service=urn%3Ax")] [InlineData("maxResponseBodySize=1024")] public void Consumer_WithASendOnlyOption_IsRefused_NamingIt(string option) { // [EndpointRole], as http: declares it: an option the other side reads would bind and do nothing. using var ctx = NewContext(); var act = () => ctx.GetEndpoint($"as4:/as4/in?connectionFactory=node&idempotentRepository=dedup&{option}").CreateConsumer(Substitute.For()); act.Should().Throw().WithMessage($"*{option[..option.IndexOf('=')]}*"); } [Theory] [InlineData("idempotentRepository=dedup")] [InlineData("streamBody=true")] [InlineData("port=4091")] [InlineData("maxConcurrentRequests=2")] public void Producer_WithAReceiveOnlyOption_IsRefused_NamingIt(string option) { using var ctx = NewContext(); var act = () => ctx.GetEndpoint($"as4://partner.example/as4?connectionFactory=node&partner=acme&{option}").CreateProducer(); act.Should().Throw().WithMessage($"*{option[..option.IndexOf('=')]}*"); } [Fact] public async Task Consumer_Start_UnknownIdempotentRepository_Throws() { using var ctx = NewContext(); var consumer = ctx.GetEndpoint("as4:/as4/in?connectionFactory=node&idempotentRepository=missing-store").CreateConsumer(Substitute.For()); var act = () => consumer.Start(); await act.Should().ThrowAsync().WithMessage("*missing-store*"); } [Fact] public async Task Consumer_Start_WithoutIdempotentRepository_Throws() { using var ctx = NewContext(); var consumer = ctx.GetEndpoint("as4:/as4/in?connectionFactory=node").CreateConsumer(Substitute.For()); var act = () => consumer.Start(); await act.Should().ThrowAsync().WithMessage("*idempotentRepository*"); } // ── Fixtures ───────────────────────────────────────────────────────────── private static readonly X509Certificate2 OurCertificate = SelfSigned("CN=redb-as4-test"); private static readonly X509Certificate2 PartnerCertificate = PublicOnly(SelfSigned("CN=acme-as4-test")); private static RouteContext NewContext(Action? factory = null, Action? partner = null) { var ctx = new RouteContext(); ctx.AddComponent(new As4Component()); ctx.AddIdempotentRepository("dedup", new InMemoryIdempotentRepository()); var f = new As4ConnectionFactory { OurPartyId = "redb", SigningCertificate = OurCertificate, DecryptionCertificates = { OurCertificate }, Partners = { NewPartner(partner) }, }; factory?.Invoke(f); ctx.AddToRegistry("node", f); return ctx; } private static As4Partner NewPartner(Action? configure = null) { var p = new As4Partner { Name = "acme", PartyId = "acme", Service = "urn:example:invoice", Action = "Submit", PartnerSigningCertificates = { PartnerCertificate }, PartnerEncryptionCertificate = PartnerCertificate, }; configure?.Invoke(p); return p; } private static As4Producer SendProducer(RouteContext ctx, string? query) { var uri = "as4s://ap.acme.example/as4?connectionFactory=node" + (query is null ? "" : "&" + query); return (As4Producer)ctx.GetEndpoint(uri).CreateProducer(); } private static X509Certificate2 SelfSigned(string subject) { using var rsa = RSA.Create(2048); var request = new CertificateRequest(subject, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); return request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1)); } private static X509Certificate2 PublicOnly(X509Certificate2 certificate) => X509CertificateLoader.LoadCertificate(certificate.Export(X509ContentType.Cert)); } Path: redb-route/tests/redb.Route.Tests.As4/As4Stand.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/tests/redb.Route.Tests.As4/As4Stand.cs ---- using System.Security.Cryptography.X509Certificates; using System.Text.Json; using Xunit.Sdk; namespace redb.Route.Tests.As4; /// /// The AS4 interop harness: test keys, captured reference messages and the message folders shared with the Holodeck /// nodes of tests/stand/docker-compose.private.yml. No key material lives in the repository: the files are /// copied by hand into the git-ignored tests/stand/.generated/as4. /// internal static class As4Stand { /// The command that starts the Holodeck nodes and the recorder, for skip messages. public const string UpCommand = "docker compose -f redb.Route/docker-compose.tests.yml -f tests/stand/docker-compose.private.yml --profile as4 up -d --wait"; /// /// Root of the harness: AS4_STAND when set, otherwise tests/stand/.generated/as4 of the first folder /// above the test binaries that has tests/stand. /// public static string Root { get; } = Environment.GetEnvironmentVariable("AS4_STAND") ?? FindRoot(); private static string FindRoot() { for (var dir = new DirectoryInfo(AppContext.BaseDirectory); dir is not null; dir = dir.Parent) { if (Directory.Exists(Path.Combine(dir.FullName, "tests", "stand"))) return Path.Combine(dir.FullName, "tests", "stand", ".generated", "as4"); } // No tests/stand above the binaries: name the place it was looked for, so the skip message points at it. return Path.Combine(AppContext.BaseDirectory, "tests", "stand", ".generated", "as4"); } /// True when the run must not skip harness tests (REDB_AS4_INTEROP=1). public static bool Required => Environment.GetEnvironmentVariable("REDB_AS4_INTEROP") == "1"; /// A captured exchange: body bytes and the HTTP Content-Type it came with. public static (byte[] Body, string ContentType) Capture(string name, string side) { var dir = Path.Combine(Root, "captures", name); var body = File.ReadAllBytes(Path.Combine(dir, side + ".bin")); using var meta = JsonDocument.Parse(File.ReadAllText(Path.Combine(dir, side + ".json"))); var contentType = meta.RootElement.GetProperty("headers").GetProperty("content-type").GetString()!; return (body, contentType); } /// A file of a capture folder. public static byte[] CaptureFile(string name, string file) => File.ReadAllBytes(Path.Combine(Root, "captures", name, file)); /// A test key pair of the harness (keys/<name>.p12, password testpass). public static X509Certificate2 KeyPair(string name) { var path = Path.Combine(Root, "keys", name + ".p12"); return X509CertificateLoader.LoadPkcs12FromFile(path, "testpass", X509KeyStorageFlags.Exportable); } /// /// A lock shared by every test process on this machine — the three target frameworks run in parallel, and a /// test that Holodeck calls back on a fixed port can run in one of them at a time. A lock file rather than a /// named mutex: it is not bound to the acquiring thread, which an async test does not keep. /// public static async Task ExclusiveAsync(string name, TimeSpan timeout) { var path = Path.Combine(Path.GetTempPath(), $"redb-as4-{name}.lock"); var deadline = DateTime.UtcNow + timeout; while (true) { try { return new FileStream(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None, 1, FileOptions.DeleteOnClose); } catch (IOException) when (DateTime.UtcNow < deadline) { await Task.Delay(TimeSpan.FromMilliseconds(250)); // held by another test process } } } /// /// Reads a file the stand may still be writing: shared with the writer, retried while the writer holds it exclusively /// (Holodeck writes its msg_in files in place). /// public static string ReadShared(string path) { for (var attempt = 1; ; attempt++) { try { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); using var reader = new StreamReader(stream); return reader.ReadToEnd(); } catch (IOException) when (attempt < 20) { Thread.Sleep(100); } } } /// Whether something accepts TCP connections on 127.0.0.1:. public static bool Listening(int port) { using var client = new System.Net.Sockets.TcpClient(); try { return client.ConnectAsync("127.0.0.1", port).Wait(TimeSpan.FromSeconds(1)) && client.Connected; } catch (AggregateException e) when (e.InnerException is System.Net.Sockets.SocketException) { return false; // refused: that is the answer "nothing listens" } } /// A test certificate of the harness without its key (keys/<name>.crt). public static X509Certificate2 Certificate(string name) { var path = Path.Combine(Root, "keys", name + ".crt"); return X509CertificateLoader.LoadCertificateFromFile(path); } } /// /// A fact that needs the AS4 harness files. Without them it is skipped — visibly, not passed — unless /// REDB_AS4_INTEROP=1, which makes a missing harness a failure. /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] [XunitTestCaseDiscoverer("Xunit.Sdk.FactDiscoverer", "xunit.execution.{Platform}")] public sealed class As4StandFactAttribute : FactAttribute { /// Skips when is not present under the harness root. public As4StandFactAttribute(string relativePath) { if (!As4Stand.Required && !Path.Exists(Path.Combine(As4Stand.Root, relativePath))) Skip = $"AS4 harness not found ({Path.Combine(As4Stand.Root, relativePath)}); copy the stand files there (tests/stand/docker-compose.private.yml) or set AS4_STAND; REDB_AS4_INTEROP=1 requires it."; } } /// /// A fact that needs a live harness endpoint on 127.0.0.1:port (a Holodeck node or the recorder). /// Skipped when it does not answer — visibly — unless REDB_AS4_INTEROP=1 makes that a failure. /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] [XunitTestCaseDiscoverer("Xunit.Sdk.FactDiscoverer", "xunit.execution.{Platform}")] public sealed class As4LiveFactAttribute : FactAttribute { /// Skips when nothing listens on . public As4LiveFactAttribute(int port) { if (!As4Stand.Required && !As4Stand.Listening(port)) Skip = $"AS4 harness endpoint 127.0.0.1:{port} is not up ({As4Stand.UpCommand}); REDB_AS4_INTEROP=1 requires it."; } } /// The theory form of . [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] [XunitTestCaseDiscoverer("Xunit.Sdk.TheoryDiscoverer", "xunit.execution.{Platform}")] public sealed class As4LiveTheoryAttribute : TheoryAttribute { /// Skips when nothing listens on . public As4LiveTheoryAttribute(int port) { if (!As4Stand.Required && !As4Stand.Listening(port)) Skip = $"AS4 harness endpoint 127.0.0.1:{port} is not up ({As4Stand.UpCommand}); REDB_AS4_INTEROP=1 requires it."; } } Path: redb-route/tests/redb.Route.Tests.As4/As4TestMessages.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/tests/redb.Route.Tests.As4/As4TestMessages.cs ---- using System.IO.Compression; using System.Text; using System.Xml; using redb.Route.As4; using redb.Route.As4.Security; using redb.Route.Core; namespace redb.Route.Tests.As4; /// /// Hand-built AS4 user messages for the security tests — written before the ebMS model existed. One /// attachment, compressed, with the eDelivery four-corner properties. /// internal static class As4TestMessages { /// A SOAP 1.2 envelope with one eb:UserMessage whose payload is the part . public static XmlDocument UserMessage(string messageId, string contentId, string from = "sender", string to = "receiver", string? agreementRef = null, string service = "urn:example", string? serviceType = null, string action = "Submit", bool fourCorner = true, string? uncompressedMimeType = null, params string[] moreContentIds) { var properties = fourCorner ? "urn:oasis:names:tc:ebcore:partyid-type:unregistered:C1urn:oasis:names:tc:ebcore:partyid-type:unregistered:C4" : ""; var partInfos = string.Concat(new[] { contentId }.Concat(moreContentIds).Select(id => uncompressedMimeType is null ? $"text/xmlapplication/gzip" : $"{uncompressedMimeType}")); var agreement = agreementRef is null ? "" : $"{agreementRef}"; var serviceTypeAttribute = serviceType is null ? "" : $" type=\"{serviceType}\""; var timestamp = DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'", System.Globalization.CultureInfo.InvariantCulture); return SafeXml.LoadDocument(Encoding.UTF8.GetBytes($""" {timestamp}{messageId} {from}{As4Partner.InitiatorRole} {to}{As4Partner.ResponderRole} {agreement}{service}{action}conversation-1 {properties} {partInfos} """)); } /// A self-signed RSA key pair with a Subject Key Identifier, usable for decryption on every platform. public static System.Security.Cryptography.X509Certificates.X509Certificate2 KeyPair(string subject) => KeyPair(subject, DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1)); /// A key pair valid from to (an expired or future one, for validity tests). public static System.Security.Cryptography.X509Certificates.X509Certificate2 KeyPair(string subject, DateTimeOffset notBefore, DateTimeOffset notAfter) { using var rsa = System.Security.Cryptography.RSA.Create(2048); var request = new System.Security.Cryptography.X509Certificates.CertificateRequest(subject, rsa, System.Security.Cryptography.HashAlgorithmName.SHA256, System.Security.Cryptography.RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new System.Security.Cryptography.X509Certificates.X509SubjectKeyIdentifierExtension(request.PublicKey, critical: false)); using var created = request.CreateSelfSigned(notBefore, notAfter); return System.Security.Cryptography.X509Certificates.X509CertificateLoader.LoadPkcs12( created.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Pfx), null, System.Security.Cryptography.X509Certificates.X509KeyStorageFlags.Exportable); } /// The certificate of without its private key. public static System.Security.Cryptography.X509Certificates.X509Certificate2 PublicOnly(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate) => System.Security.Cryptography.X509Certificates.X509CertificateLoader.LoadCertificate( certificate.Export(System.Security.Cryptography.X509Certificates.X509ContentType.Cert)); public static byte[] Gzip(byte[] data) { using var output = new MemoryStream(); using (var gzip = new GZipStream(output, CompressionLevel.Optimal)) gzip.Write(data); return output.ToArray(); } /// Flips one bit of a part's content, as a tampering attacker would. public static void Flip(redb.Route.As4.Mime.SwaPart part, int index) { var bytes = part.ToArray(); bytes[index] ^= 0x01; part.Replace(new MemoryStream(bytes, writable: false)); } /// /// The same base64 value with the lowest unused bit of its last character set (YR== for YQ==): .NET 10 /// decodes it to the same bytes, .NET 11 and XML Schema base64Binary refuse it. The value must end in padding. /// public static string WithUnusedBitsSet(string base64) { const string alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; var value = base64.Trim(); var last = value.TrimEnd('=').Length - 1; if (last == value.Length - 1) throw new ArgumentException("The value has no padding, so no unused bits.", nameof(base64)); var chars = value.ToCharArray(); chars[last] = alphabet[alphabet.IndexOf(chars[last], StringComparison.Ordinal) | 1]; return new string(chars); } public static byte[] Gunzip(byte[] data) { using var input = new GZipStream(new MemoryStream(data), CompressionMode.Decompress); using var output = new MemoryStream(); input.CopyTo(output); return output.ToArray(); } } Path: redb-route/tests/redb.Route.Tests.As4/As4TimestampTests.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/tests/redb.Route.Tests.As4/As4TimestampTests.cs ---- using System.Security.Cryptography; using System.Xml; using redb.Route.As4.Security; namespace redb.Route.Tests.As4; /// /// Review R5: wsu:Timestamp is checked as WSS4J checks it, the library Domibus and Holodeck verify with — /// Created is required (BSP R3203), may not lie in the future beyond the clock tolerance nor be older than the /// time to live (WSS4J timeStampTTL, 300 s); Expires is optional and, when present, must not have passed. /// An Expires far in the future therefore buys nothing: the age is bounded by Created. /// public class As4TimestampTests { private static readonly TimeSpan Tolerance = TimeSpan.FromMinutes(5); private static readonly TimeSpan TimeToLive = TimeSpan.FromMinutes(5); private static readonly DateTimeOffset Now = new(2026, 9, 28, 12, 0, 0, TimeSpan.Zero); private static XmlElement Timestamp(DateTimeOffset? created, DateTimeOffset? expires) { var doc = new XmlDocument(); var timestamp = doc.CreateElement("wsu", "Timestamp", WsSecurityNames.Wsu); if (created is { } c) timestamp.AppendChild(doc.CreateElement("wsu", "Created", WsSecurityNames.Wsu))!.InnerText = c.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'"); if (expires is { } e) timestamp.AppendChild(doc.CreateElement("wsu", "Expires", WsSecurityNames.Wsu))!.InnerText = e.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.fff'Z'"); return timestamp; } private static Action Check(XmlElement timestamp) => () => As4Signature.CheckTimestamp(timestamp, Tolerance, TimeToLive, Now); [Fact] public void Fresh_WithOrWithoutExpires_Passes() { Check(Timestamp(Now.AddSeconds(-30), Now.AddMinutes(5))).Should().NotThrow(); Check(Timestamp(Now.AddSeconds(-30), null)).Should().NotThrow(); } [Fact] public void WithoutCreated_IsRefused() => Check(Timestamp(null, Now.AddMinutes(5))).Should().Throw().WithMessage("*Created*"); [Fact] public void CreatedTooLongAgo_IsRefused_EvenWithExpiresAYearAhead() => Check(Timestamp(Now.AddMinutes(-10), Now.AddYears(1))).Should().Throw().WithMessage("*too long ago*"); [Fact] public void CreatedInTheFuture_BeyondTheTolerance_IsRefused() => Check(Timestamp(Now.AddMinutes(10), null)).Should().Throw().WithMessage("*future*"); [Fact] public void ExpiresPassed_BeyondTheTolerance_IsRefused() => Check(Timestamp(Now.AddSeconds(-30), Now.AddMinutes(-10))).Should().Throw().WithMessage("*expired*"); [Fact] public void NotADate_IsRefused_AsAFailedSignature() { var timestamp = Timestamp(Now, null); timestamp.FirstChild!.InnerText = "yesterday"; Check(timestamp).Should().Throw(); } } Path: redb-route/tests/redb.Route.Tests.As4/As4TransportSecurityTests.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/tests/redb.Route.Tests.As4/As4TransportSecurityTests.cs ---- using System.Net; using System.Net.Http.Headers; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using redb.Route.Abstractions; using redb.Route.As4; using redb.Route.As4.Messaging; using redb.Route.As4.Mime; using redb.Route.As4.Security; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; namespace redb.Route.Tests.As4; /// /// TLS and mutual TLS of the AS4 receiver on real loopback handshakes, after As2TransportSecurityTests and /// SoapTransportSecurityTests: a TLS receiver without a certificate refuses to start (as the SOAP receiver), one /// with a certificate terminates TLS and leaves no plaintext port, the certificate may come from the node, and a /// receiver that requires a client certificate refuses a handshake without one or with one outside its allow-list. /// public sealed class As4TransportSecurityTests : IDisposable { private static readonly X509Certificate2 NodeA = As4TestMessages.KeyPair("CN=a.as4.test"); private static readonly X509Certificate2 NodeB = As4TestMessages.KeyPair("CN=b.as4.test"); private static readonly X509Certificate2 PartnerTls = As4TestMessages.KeyPair("CN=a.tls.as4.test"); private static readonly X509Certificate2 StrangerTls = As4TestMessages.KeyPair("CN=stranger.tls.as4.test"); private const string Payload = "42"; private readonly List _tempFiles = []; public void Dispose() { foreach (var file in _tempFiles) File.Delete(file); } [Fact] public async Task TlsReceiver_WithoutCertificate_RefusesToStart() { using var context = NewContext(out _); var consumer = context.GetEndpoint($"as4s:/as4/in?host=127.0.0.1&port={TestPort()}&connectionFactory=b&idempotentRepository=dedup") .CreateConsumer(Substitute.For()); var act = () => consumer.Start(); await act.Should().ThrowAsync().WithMessage("*TLS but has no certificate*"); } [Fact] public async Task ClientCertificatesFromTheNode_WithoutTls_RefuseToStart() { using var context = NewContext(out var node); node.ClientCertificateMode = As4ClientCertificateMode.RequireCertificate; var consumer = context.GetEndpoint($"as4:/as4/in?host=127.0.0.1&port={TestPort()}&connectionFactory=b&idempotentRepository=dedup") .CreateConsumer(Substitute.For()); var act = () => consumer.Start(); await act.Should().ThrowAsync().WithMessage("*client certificates without TLS*"); } [Fact] public async Task TlsReceiver_TerminatesTls_AndLeavesNoPlaintextPort() { var port = TestPort(); using var context = NewContext(out _); var consumer = await StartConsumer(context, port, $"&sslCertPath={Uri.EscapeDataString(WritePfx())}"); await using var stop = Stop(consumer); var (status, errorCode, receipt) = await Post(Https(), $"https://127.0.0.1:{port}/as4/in"); (status, errorCode, receipt).Should().Be((HttpStatusCode.OK, (string?)null, true)); var plain = () => Post(new HttpClientHandler(), $"http://127.0.0.1:{port}/as4/in"); await plain.Should().ThrowAsync(); } [Fact] public async Task TlsReceiver_TakesTheCertificateFromTheNode() { var port = TestPort(); using var context = NewContext(out var node); node.SslCertPath = WritePfx(); var consumer = await StartConsumer(context, port, extraQuery: ""); await using var stop = Stop(consumer); (await Post(Https(), $"https://127.0.0.1:{port}/as4/in")).Receipt.Should().BeTrue(); } [Fact] public async Task RequiredClientCertificate_OnTheAllowList_IsAccepted_AndReachesTheExchange() { var port = TestPort(); using var context = NewContext(out _); IExchange? received = null; var consumer = await StartConsumer(context, port, $"&sslCertPath={Uri.EscapeDataString(WritePfx())}&clientCertificateMode=RequireCertificate&allowedClientThumbprints={PartnerTls.Thumbprint}", e => received = e); await using var stop = Stop(consumer); var handler = Https(); handler.ClientCertificates.Add(PartnerTls); (await Post(handler, $"https://127.0.0.1:{port}/as4/in")).Receipt.Should().BeTrue(); received!.In.GetHeader(As4Headers.ClientCertThumbprint).Should().Be(PartnerTls.Thumbprint); received.In.GetHeader(As4Headers.ClientCertSubject).Should().Be(PartnerTls.Subject); var identities = ExchangePrincipal.Get(received)!.Identities.ToList(); identities.Select(i => i.AuthenticationType).Should().Equal(As4AuthenticationTypes.Signature, As4AuthenticationTypes.ClientCertificate); identities[1].FindFirst(System.Security.Claims.ClaimTypes.Thumbprint)!.Value.Should().Be(PartnerTls.Thumbprint); } [Fact] public async Task RequiredClientCertificate_Missing_IsRefusedInTheHandshake() { var port = TestPort(); using var context = NewContext(out _); var consumer = await StartConsumer(context, port, $"&sslCertPath={Uri.EscapeDataString(WritePfx())}&clientCertificateMode=RequireCertificate&allowedClientThumbprints={PartnerTls.Thumbprint}"); await using var stop = Stop(consumer); var act = () => Post(Https(), $"https://127.0.0.1:{port}/as4/in"); await act.Should().ThrowAsync(); } [Fact] public async Task RequiredClientCertificate_OffTheAllowList_IsRefusedInTheHandshake() { var port = TestPort(); using var context = NewContext(out var node); node.ClientCertificateMode = As4ClientCertificateMode.RequireCertificate; // from the node, this time node.AllowedClientThumbprints = PartnerTls.Thumbprint; var consumer = await StartConsumer(context, port, $"&sslCertPath={Uri.EscapeDataString(WritePfx())}"); await using var stop = Stop(consumer); var handler = Https(); handler.ClientCertificates.Add(StrangerTls); var act = () => Post(handler, $"https://127.0.0.1:{port}/as4/in"); await act.Should().ThrowAsync(); } [Fact] public async Task RequiredClientCertificate_OnTheAllowListButExpired_IsRefusedInTheHandshake() { // The allow-list replaces Kestrel's check, and a pin is no excuse for an expired key (Holodeck, Domibus). var expired = As4TestMessages.KeyPair("CN=a.tls.as4.test", DateTimeOffset.UtcNow.AddYears(-2), DateTimeOffset.UtcNow.AddDays(-1)); var port = TestPort(); using var context = NewContext(out _); var consumer = await StartConsumer(context, port, $"&sslCertPath={Uri.EscapeDataString(WritePfx())}&clientCertificateMode=RequireCertificate&allowedClientThumbprints={expired.Thumbprint}"); await using var stop = Stop(consumer); var handler = Https(); handler.ClientCertificates.Add(expired); var act = () => Post(handler, $"https://127.0.0.1:{port}/as4/in"); await act.Should().ThrowAsync(); } // ── TLS versions (sending) ─────────────────────────────────────────────── [Fact] public void Sender_OffersTls12And13_ByDefault() { // eDelivery AS4 1.16: TLS 1.2 MUST, 1.3 MAY; Holodeck, phase4 and Domibus (CXF "TLS") default to exactly these. using var handler = As4Producer.CreateHandler(Node()); handler.SslProtocols.Should().Be(System.Security.Authentication.SslProtocols.Tls12 | System.Security.Authentication.SslProtocols.Tls13); } [Fact] public void Sender_OffersWhatTheNodeAllows() { var node = Node(); node.SslProtocols = System.Security.Authentication.SslProtocols.Tls13; using var handler = As4Producer.CreateHandler(node); handler.SslProtocols.Should().Be(System.Security.Authentication.SslProtocols.Tls13); } [Theory] #pragma warning disable SYSLIB0039, CS0618 // the obsolete protocols are what the check must refuse [InlineData(System.Security.Authentication.SslProtocols.Tls11 | System.Security.Authentication.SslProtocols.Tls12)] [InlineData(System.Security.Authentication.SslProtocols.Tls)] [InlineData(System.Security.Authentication.SslProtocols.Ssl3)] #pragma warning restore SYSLIB0039, CS0618 [InlineData(System.Security.Authentication.SslProtocols.None)] public void Node_WithAProtocolTheProfileForbids_IsRefused(System.Security.Authentication.SslProtocols protocols) { var node = Node(); node.SslProtocols = protocols; var act = () => node.Validate("b"); act.Should().Throw().WithMessage("*SslProtocols*"); } // ── Fixtures ───────────────────────────────────────────────────────────── private static As4ConnectionFactory Node() { using var context = NewContext(out var node); return node; } private static int TestPort() => global::redb.Route.Tests.Shared.TestPorts.Next(); private static RouteContext NewContext(out As4ConnectionFactory nodeB) { var context = new RouteContext(); context.AddComponent(new As4Component()); context.AddIdempotentRepository("dedup", new InMemoryIdempotentRepository()); nodeB = new As4ConnectionFactory { OurPartyId = "urn:redb:b", ExternalHostName = "b.example", SigningCertificate = NodeB, DecryptionCertificates = { NodeB }, Partners = { new As4Partner { Name = "a", PartyId = "urn:redb:a", Service = "urn:example", Action = "Submit", PartnerSigningCertificates = { As4TestMessages.PublicOnly(NodeA) }, PartnerEncryptionCertificate = As4TestMessages.PublicOnly(NodeA), }, }, }; context.AddToRegistry("b", nodeB); return context; } private static async Task StartConsumer(RouteContext context, int port, string extraQuery, Action? onExchange = null) { var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { onExchange?.Invoke(ci.Arg()); return Task.CompletedTask; }); var consumer = context.GetEndpoint($"as4s:/as4/in?host=127.0.0.1&port={port}&connectionFactory=b&idempotentRepository=dedup{extraQuery}") .CreateConsumer(processor); await consumer.Start(); return consumer; } private static AsyncStop Stop(IConsumer consumer) => new(consumer); private readonly struct AsyncStop(IConsumer consumer) : IAsyncDisposable { public async ValueTask DisposeAsync() => await consumer.Stop(); } /// A client that trusts the test's self-signed server certificate, as the AS2 TLS tests do. private static HttpClientHandler Https() => new() { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator, }; private static async Task<(HttpStatusCode Status, string? ErrorCode, bool Receipt)> Post(HttpClientHandler handler, string url) { using var http = new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(15) }; var (contentType, body) = SecuredMessage(); var content = new ByteArrayContent(body); content.Headers.ContentType = MediaTypeHeaderValue.Parse(contentType); using var response = await http.PostAsync(url, content); var answer = SwaMessage.Read(response.Content.Headers.ContentType!.ToString(), await response.Content.ReadAsByteArrayAsync(), 1024 * 1024); var signals = MessagingReader.Read(answer.Envelope).SignalMessages; return (response.StatusCode, signals.SelectMany(s => s.Errors).FirstOrDefault()?.ErrorCode, signals.Any(s => s.IsReceipt)); } /// A user message from A to B, gzipped, signed and encrypted as A sends it. private static (string ContentType, byte[] Body) SecuredMessage() { const string contentId = "p1@a.example"; using var message = SwaMessage.Create(As4TestMessages.UserMessage(Guid.NewGuid().ToString("N") + "@a.example", contentId, from: "urn:redb:a", to: "urn:redb:b", service: "urn:example", action: "Submit")); message.AddPart(contentId, "application/gzip", As4TestMessages.Gzip(Encoding.UTF8.GetBytes(Payload))); As4SecurityEngine.Sign(message, NodeA, As4KeyReference.BinarySecurityToken, null, DateTimeOffset.UtcNow); As4SecurityEngine.Encrypt(message, As4TestMessages.PublicOnly(NodeB), As4KeyReference.BinarySecurityToken); return message.Write(); } /// A self-signed localhost server certificate in a temporary PFX, as the AS2 TLS tests write it. private string WritePfx() { using var rsa = RSA.Create(2048); var request = new CertificateRequest("CN=localhost", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509BasicConstraintsExtension(false, false, 0, false)); var san = new SubjectAlternativeNameBuilder(); san.AddDnsName("localhost"); san.AddIpAddress(IPAddress.Loopback); request.CertificateExtensions.Add(san.Build()); using var cert = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); var path = Path.Combine(Path.GetTempPath(), $"redb-as4-tls-{Guid.NewGuid():N}.pfx"); File.WriteAllBytes(path, cert.Export(X509ContentType.Pfx)); _tempFiles.Add(path); return path; } } Path: redb-route/tests/redb.Route.Tests.As4/RecentReceiptsTests.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/tests/redb.Route.Tests.As4/RecentReceiptsTests.cs ---- using redb.Route.As4.Signals; namespace redb.Route.Tests.As4; /// /// The in-memory store of sent receipts empties itself: almost no receipt is read again, so entries leave by age and /// by count when new ones come, not when they are read. /// public class RecentReceiptsTests { [Fact] public async Task BeyondTheCapacity_TheOldestLeave() { var receipts = new RecentReceipts(TimeSpan.FromHours(1), capacity: 2); await receipts.Store("1", new byte[] { 1 }); await receipts.Store("2", new byte[] { 2 }); await receipts.Store("3", new byte[] { 3 }); (await receipts.Retrieve("1")).Should().BeNull(); (await receipts.Retrieve("2")).Should().Equal(2); (await receipts.Retrieve("3")).Should().Equal(3); } [Fact] public async Task Expired_IsNotReturned_AndLeavesWithTheNextStore() { var receipts = new RecentReceipts(TimeSpan.FromHours(1), capacity: 10); await receipts.Store("old", new byte[] { 1 }, ttl: TimeSpan.FromMilliseconds(1)); await Task.Delay(20); (await receipts.Retrieve("old")).Should().BeNull(); await receipts.Store("new", new byte[] { 2 }); (await receipts.Retrieve("new")).Should().Equal(2); } [Fact] public async Task StoredAgain_UnderTheSameKey_KeepsTheNewerAcrossTheOldersRemoval() { var receipts = new RecentReceipts(TimeSpan.FromHours(1), capacity: 2); await receipts.Store("a", new byte[] { 1 }); await receipts.Store("a", new byte[] { 2 }); await receipts.Store("b", new byte[] { 3 }); // the first "a" item leaves the queue, the newer value stays (await receipts.Retrieve("a")).Should().Equal(2); } } Path: redb-route/tests/redb.Route.Tests.As4/SecurityTokenResolverBase64Tests.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/tests/redb.Route.Tests.As4/SecurityTokenResolverBase64Tests.cs ---- using System.Security.Cryptography; using System.Xml; using redb.Route.As4.Security; namespace redb.Route.Tests.As4; /// /// Every base64 value of a received security header (DigestValue, SignatureValue, CipherValue, BinarySecurityToken, /// KeyIdentifier) is read through . A value whose last character has non-zero /// unused bits is refused on every runtime: .NET 10 decodes it, .NET 11 refuses it, XML Schema base64Binary forbids it. /// public class SecurityTokenResolverBase64Tests { [Theory] [InlineData("YQ==", new byte[] { 0x61 })] [InlineData("YWI=", new byte[] { 0x61, 0x62 })] [InlineData("YWJj", new byte[] { 0x61, 0x62, 0x63 })] [InlineData("\n YWJj\nYQ==\n", new byte[] { 0x61, 0x62, 0x63, 0x61 })] // line breaks, as WSS4J wraps long values public void CanonicalValue_IsDecoded(string text, byte[] expected) { SecurityTokenResolver.Base64(Element("DigestValue", text)).Should().Equal(expected); } [Theory] [InlineData("YR==")] // two '=': the low four bits of 'R' are unused, and one is set [InlineData("YWJ=")] // one '=': the low two bits of 'J' are unused, and one is set [InlineData("YWJjYR==\n")] // after a whole group, with trailing whitespace [InlineData("YWJj\nYR = =")] // whitespace inside the padding public void ValueWithUnusedBitsSet_IsRefusedAsASecurityFailure(string text) { var act = () => SecurityTokenResolver.Base64(Element("DigestValue", text)); act.Should().Throw().WithMessage("ds:DigestValue is not valid base64."); } [Fact] public void BinarySecurityTokenWithUnusedBitsSet_IsRefused() { var der = As4TestMessages.KeyPair("CN=bst.as4.test").RawData; if (der.Length % 3 == 0) der = [.. der, 0x00]; // a value with padding; the base64 check comes before the certificate is parsed var doc = new XmlDocument(); var token = doc.CreateElement("wsse", "BinarySecurityToken", WsSecurityNames.Wsse); token.SetAttribute("ValueType", WsSecurityNames.X509V3); token.InnerText = As4TestMessages.WithUnusedBitsSet(Convert.ToBase64String(der)); var act = () => SecurityTokenResolver.FromBinarySecurityToken(token); act.Should().Throw().WithMessage("wsse:BinarySecurityToken is not valid base64."); } private static XmlElement Element(string localName, string text) { var doc = new XmlDocument(); var element = doc.CreateElement("ds", localName, WsSecurityNames.Ds); element.InnerText = text; return element; } } Path: redb-route/tests/redb.Route.Tests.As4/SecurityTokenResolverIssuerSerialTests.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/tests/redb.Route.Tests.As4/SecurityTokenResolverIssuerSerialTests.cs ---- using System.Numerics; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Xml; using redb.Route.As4.Security; namespace redb.Route.Tests.As4; /// /// A ds:X509IssuerSerial reference finds our certificate whatever spacing the sender puts between the parts /// of the issuer name: WSS4J and Domibus write RFC 2253 ("CN=a,OU=b,C=BE"), .NET writes "CN=a, OU=b, C=BE". /// public class SecurityTokenResolverIssuerSerialTests { private const string Subject = "CN=Conformance Testing CA, OU=eDelivery, O=Building Blocks Office, C=BE"; private static readonly X509Certificate2 Ours = SelfSigned(Subject); [Theory] [InlineData("CN=Conformance Testing CA,OU=eDelivery,O=Building Blocks Office,C=BE")] [InlineData("CN=Conformance Testing CA, OU=eDelivery, O=Building Blocks Office, C=BE")] [InlineData("cn=Conformance Testing CA,ou=eDelivery,o=Building Blocks Office,c=BE")] public void IssuerSerial_FindsOurCertificate_WhateverTheSpacingOfTheIssuerName(string issuerName) { var (keyInfo, envelope) = KeyInfo(issuerName, Serial(Ours)); var resolved = SecurityTokenResolver.Resolve(keyInfo, envelope, [Ours]); resolved.Should().NotBeNull(); resolved!.Thumbprint.Should().Be(Ours.Thumbprint); } [Fact] public void IssuerSerial_OfAnotherSerial_FindsNothing() { var (keyInfo, envelope) = KeyInfo("CN=Conformance Testing CA,OU=eDelivery,O=Building Blocks Office,C=BE", Serial(Ours) + 1); SecurityTokenResolver.Resolve(keyInfo, envelope, [Ours]).Should().BeNull(); } [Fact] public void IssuerSerial_OfAnotherIssuer_FindsNothing() { var (keyInfo, envelope) = KeyInfo("CN=Conformance Testing CA,OU=eDelivery,O=Building Blocks Office,C=DE", Serial(Ours)); SecurityTokenResolver.Resolve(keyInfo, envelope, [Ours]).Should().BeNull(); } private static (XmlElement KeyInfo, XmlDocument Envelope) KeyInfo(string issuerName, BigInteger serial) { var doc = new XmlDocument(); doc.LoadXml( $""" {issuerName} {serial} """); return (doc.DocumentElement!, doc); } private static BigInteger Serial(X509Certificate2 certificate) => new(certificate.GetSerialNumber(), isUnsigned: true, isBigEndian: false); private static X509Certificate2 SelfSigned(string subject) { using var rsa = RSA.Create(2048); var request = new CertificateRequest(subject, rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); using var created = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(1)); return X509CertificateLoader.LoadPkcs12(created.Export(X509ContentType.Pfx), null, X509KeyStorageFlags.Exportable); } } Path: redb-route/tests/redb.Route.Tests.As4/redb.Route.Tests.As4.csproj Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/tests/redb.Route.Tests.As4/redb.Route.Tests.As4.csproj ----