Bundle: redb-route / tests/redb.Route.Tests.As2 (tests.redb.Route.Tests.As2.txt), 24 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.As2/As2AgreementTests.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.As2/As2AgreementTests.cs ---- using System.Net; using System.Security.Cryptography.X509Certificates; using AwesomeAssertions; using redb.Route.As2; using redb.Route.As2.Crypto; using redb.Route.As2.Mdn; using redb.Route.Core; using As2Dsl = redb.Route.As2.Fluent.As2; using static redb.Route.Tests.As2.As2TestKit; namespace redb.Route.Tests.As2; /// /// The agreement is checked when an endpoint starts, not on the first message, and a /// certificate is used only while it is valid. /// public class As2AgreementTests { private static readonly X509Certificate2 Expired = MakeCert("as2-expired", DateTimeOffset.UtcNow.AddYears(-2), DateTimeOffset.UtcNow.AddDays(-1)); private static readonly X509Certificate2 NotYetValid = MakeCert("as2-future", DateTimeOffset.UtcNow.AddDays(1), DateTimeOffset.UtcNow.AddYears(2)); private static readonly X509Certificate2 PublicOnly = X509CertificateLoader.LoadCertificate(Cert.Export(X509ContentType.Cert)); // ── As2ConnectionFactory.Validate ──────────────────────────────────────── public static TheoryData, string> Broken => new() { { "no our id", f => f.As2From = "", "As2From" }, { "no partner id", f => f.As2To = " ", "As2To" }, { "unknown digest", f => f.SignAlg = "sha2-256", "SignAlg" }, { "unknown cipher", f => f.EncryptAlg = "aes-128-gcm", "EncryptAlg" }, { "no own certificate", f => f.OurCertificate = null, "OurCertificate" }, { "own certificate without key", f => f.OurCertificate = PublicOnly, "private key" }, { "no partner certificate", f => f.PartnerCertificate = null, "PartnerCertificate" }, { "relative receipt url", f => { f.MdnMode = As2MdnMode.Async; f.AsyncMdnUrl = "/mdn"; }, "AsyncMdnUrl" }, { "relative partner url", f => f.PartnerUrl = "partner/as2", "PartnerUrl" }, }; [Theory] [MemberData(nameof(Broken))] public void Validate_RefusesAnIncompleteAgreement(string _, Action breakIt, string named) { var factory = Sender(breakIt); var act = () => factory.Validate("walmart"); act.Should().Throw().Which.Message.Should().Contain("walmart").And.Contain(named); } [Fact] public void Validate_AcceptsAnAgreementWithoutCertificates_WhenNothingIsSignedOrEncrypted() { var factory = Sender(f => { f.OurCertificate = null; f.PartnerCertificate = null; f.Sign = false; f.Encrypt = false; f.SignedMdn = false; }); factory.Invoking(f => f.Validate("plain")).Should().NotThrow(); } [Fact] public async Task Receiver_WithAnInvalidAgreement_DoesNotStart() { var component = new As2Component(); await using var context = new RouteContext(); context.AddComponent(component); context.AddToRegistry("recv", Receiver(f => f.SignAlg = "sha2-256")); var consumer = context.GetEndpoint(As2Dsl.Receive("/in").Host("127.0.0.1").Port(FreePort()).ConnectionFactory("recv")) .CreateConsumer(new redb.Route.Processors.DelegateProcessor(_ => { })); var act = () => consumer.Start(); (await act.Should().ThrowAsync()).Which.Message.Should().Contain("SignAlg"); } [Fact] public async Task MdnReceiver_WithAnInvalidAgreement_DoesNotStart() { await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("them", Sender(f => f.PartnerCertificate = null)); var consumer = context.GetEndpoint(As2Dsl.ReceiveMdn("/mdn").Host("127.0.0.1").Port(FreePort()).ConnectionFactory("them")) .CreateConsumer(new redb.Route.Processors.DelegateProcessor(_ => { })); var act = () => consumer.Start(); (await act.Should().ThrowAsync()).Which.Message.Should().Contain("PartnerCertificate"); } [Fact] public async Task Producer_WithAnInvalidAgreement_DoesNotStart() { await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("them", Sender(f => f.OurCertificate = null)); var producer = context.GetEndpoint(As2Dsl.Send("http://127.0.0.1:1/as2").ConnectionFactory("them")).CreateProducer(); var act = () => producer.Start(); (await act.Should().ThrowAsync()).Which.Message.Should().Contain("OurCertificate"); } // ── one source of the agreement ────────────────────────────────────────── [Theory] [InlineData("sign=false")] [InlineData("signAlg=sha-384")] [InlineData("mdnMode=None")] [InlineData("as2From=OTHER")] [InlineData("asyncMdnAllowedHosts=example.com")] public void Endpoint_NamingAFactory_RefusesInlineAgreementOptions(string inline) { var component = new As2Component(); var act = () => component.CreateEndpoint(EndpointUriParser.Parse($"as2:/in?port=4080&connectionFactory=walmart&{inline}")); act.Should().Throw().Which.Message.Should().Contain(inline.Split('=')[0]).And.Contain("connection factory"); } [Fact] public void CertPassword_IsNotAnOption_AndSaysWhereCertificatesGo() { var component = new As2Component(); var act = () => component.CreateEndpoint(EndpointUriParser.Parse("as2:/in?port=4080&certPassword=secret")); act.Should().Throw().Which.Message.Should().Contain("As2ConnectionFactory").And.NotContain("secret"); } [Fact] public async Task Producer_WhoseFactoryNamesAnotherPartnerUrl_DoesNotStart() { await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("them", Sender(f => f.PartnerUrl = "https://partner.example/as2")); var producer = context.GetEndpoint(As2Dsl.Send("http://127.0.0.1:1/as2").ConnectionFactory("them")).CreateProducer(); var act = () => producer.Start(); (await act.Should().ThrowAsync()).Which.Message.Should().Contain("PartnerUrl"); } // ── legacy algorithms only on request ──────────────────────────────────── [Theory] [InlineData("sha-1", "aes-128-cbc")] [InlineData("sha1", "aes-128-cbc")] [InlineData("sha-256", "3des")] [InlineData("sha-256", "des-ede3-cbc")] public void LegacyAlgorithms_AreRefused_UnlessAllowed(string signAlg, string encryptAlg) { var refused = Sender(f => { f.SignAlg = signAlg; f.EncryptAlg = encryptAlg; }); refused.Invoking(f => f.Validate("old")).Should().Throw().WithMessage("*AllowLegacyAlgorithms*"); var allowed = Sender(f => { f.SignAlg = signAlg; f.EncryptAlg = encryptAlg; f.AllowLegacyAlgorithms = true; }); allowed.Invoking(f => f.Validate("old")).Should().NotThrow(); } [Fact] public void LegacyAlgorithms_Inline_AreRefused_UnlessAllowed() { var component = new As2Component(); var refused = () => component.CreateEndpoint(EndpointUriParser.Parse("as2:/in?port=4080&signAlg=sha-1")); refused.Should().Throw().WithMessage("*allowLegacyAlgorithms*"); var allowed = () => component.CreateEndpoint(EndpointUriParser.Parse("as2:/in?port=4080&signAlg=sha-1&allowLegacyAlgorithms=true")); allowed.Should().NotThrow(); } // ── certificate validity ───────────────────────────────────────────────── [Fact] public async Task Message_SignedWithAnExpiredPartnerCertificate_IsRefused() { var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver(f => f.PartnerCertificate = Expired)); var delivered = 0; context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv")) .Process(_ => Interlocked.Increment(ref delivered))); await context.Start(); var response = await PostAsync(port, "/in", BuildMessage("PO*EXPIRED~", Expired, Cert)); delivered.Should().Be(0); var cte = response.Content.Headers.TryGetValues("Content-Transfer-Encoding", out var v) ? string.Join(",", v) : null; var mdn = MdnParser.Parse(response.Content.Headers.ContentType?.ToString(), cte, await response.Content.ReadAsByteArrayAsync(), new As2CryptoEngine(), Cert); mdn.Disposition.Should().EndWith("processed/error: authentication-failed"); } [Theory] [InlineData("partner")] [InlineData("ours")] [InlineData("future")] public async Task Send_WithACertificateOutsideItsValidity_FailsBeforePosting(string which) { using var trap = new As2Trap(FreePort()); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("them", Sender(f => { if (which == "partner") f.PartnerCertificate = Expired; else if (which == "ours") f.OurCertificate = Expired; else f.PartnerCertificate = NotYetValid; })); var producer = context.GetEndpoint(As2Dsl.Send(trap.Url("/as2")).ConnectionFactory("them")).CreateProducer(); await producer.Start(); var act = () => producer.Process(new Exchange(new Message("PO*VALIDITY~") { ContentType = "application/edi-x12" })); (await act.Should().ThrowAsync()) .Which.Message.Should().MatchRegex("expired|not yet valid"); (await trap.HitAsync(TimeSpan.FromMilliseconds(300))).Should().BeFalse(); } [Fact] public async Task SyncMdn_SignedWithAnExpiredPartnerCertificate_IsNotAValidSignature() { var port = FreePort(); using var listener = new HttpListener(); listener.Prefixes.Add($"http://127.0.0.1:{port}/"); listener.Start(); var partner = Task.Run(async () => { var ctx = await listener.GetContextAsync(); var id = ctx.Request.Headers["Message-ID"]!; await ctx.Request.InputStream.CopyToAsync(Stream.Null); var (ct, cte, body) = MdnBuilder.Build(id, "US", "THEM", null, null, null, new As2CryptoEngine(), Expired); ctx.Response.ContentType = ct; if (cte is not null) ctx.Response.Headers["Content-Transfer-Encoding"] = cte; await ctx.Response.OutputStream.WriteAsync(body); ctx.Response.Close(); }); await using var context = new RouteContext(); context.AddComponent(new As2Component()); // The MDN signer's certificate is pinned, but expired: sending is refused with it, so it signs only the MDN here. context.AddToRegistry("them", Sender(f => { f.Encrypt = false; f.Sign = false; f.PartnerCertificate = Expired; })); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/as2").ConnectionFactory("them")).CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("PO*MDN~") { ContentType = "application/edi-x12" }); await producer.Process(exchange); await partner.WaitAsync(TimeSpan.FromSeconds(10)); exchange.Out!.GetHeader(As2Headers.SignatureValid).Should().BeFalse(); } } Path: redb-route/tests/redb.Route.Tests.As2/As2AsyncMdnPoolTests.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.As2/As2AsyncMdnPoolTests.cs ---- using System.Diagnostics.Metrics; using System.Net; using AwesomeAssertions; using redb.Route.As2; using redb.Route.Core; using As2Dsl = redb.Route.As2.Fluent.As2; using static redb.Route.Tests.As2.As2TestKit; namespace redb.Route.Tests.As2; /// /// Asynchronous MDNs go through a bounded pool: a message that asks for one takes a slot when it is admitted, before /// any work, and keeps it until its receipt is posted (with bounded retries); with every slot taken it is refused with /// the endpoint's reject status and Retry-After, as the admission limit refuses (RFC 4130 §7: the response comes before /// the MDN, so the receiver cannot post it in the caller's place). /// [Collection(nameof(AsyncMdnMetricsCollection))] public class As2AsyncMdnPoolTests { private static As2ConnectionFactory AsyncReceiver() => Receiver(f => { f.MdnMode = As2MdnMode.Async; f.AsyncMdnAllowedHosts = ["127.0.0.1"]; }); private static Dictionary ReceiptTo(As2Trap trap) => new() { ["Receipt-Delivery-Option"] = trap.Url() }; [Fact] public void Defaults_Are503_RetryAfter30_Pool20_ThreeAttempts() { var options = new As2EndpointOptions(); options.RejectStatusCode.Should().Be(503); options.RetryAfterSeconds.Should().Be(30); options.AsyncMdnPoolSize.Should().Be(20); options.AsyncMdnAttempts.Should().Be(3); options.AsyncMdnRetryDelay.Should().Be(5000); } [Theory] [InlineData(0, 3, 5000, "asyncMdnPoolSize")] [InlineData(20, 0, 5000, "asyncMdnAttempts")] [InlineData(20, 3, -1, "asyncMdnRetryDelay")] public void InvalidPoolOptions_AreRefused(int pool, int attempts, int delay, string named) { var act = () => new As2EndpointOptions { AsyncMdnPoolSize = pool, AsyncMdnAttempts = attempts, AsyncMdnRetryDelay = delay }.Validate(); act.Should().Throw().WithMessage($"*{named}*"); } [Fact] public void UriAndDsl_CarryThePoolOptions() { var built = As2Dsl.Receive("/in").Port(4080).AsyncMdnPoolSize(4).AsyncMdnRetry(attempts: 5, delayMs: 250).Build(); var options = ((As2Endpoint)new As2Component().CreateEndpoint(EndpointUriParser.Parse(built))).EndpointOptions; options.AsyncMdnPoolSize.Should().Be(4); options.AsyncMdnAttempts.Should().Be(5); options.AsyncMdnRetryDelay.Should().Be(250); } [Fact] public async Task WithEverySlotTaken_AMessageAskingForAnAsyncMdn_IsRefused503_WithRetryAfter_BeforeAnyWork() { using var trap = new As2Trap(FreePort()); var port = FreePort(); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var routed = 0; await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", AsyncReceiver()); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").AsyncMdnPoolSize(1)) .Process(async (_, _) => { // Only the first message waits: it holds the one slot while it is in the route. if (Interlocked.Increment(ref routed) != 1) return; entered.TrySetResult(); await release.Task; })); await context.Start(); var first = PostAsync(port, "/in", BuildMessage("PO*1~", Cert, Cert), ReceiptTo(trap)); await entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); var refused = await PostAsync(port, "/in", BuildMessage("PO*2~", Cert, Cert), ReceiptTo(trap)); refused.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); refused.Headers.RetryAfter!.Delta.Should().Be(TimeSpan.FromSeconds(30)); routed.Should().Be(1, "the refused message was not processed"); // A synchronous receipt does not need a slot. var sync = await PostAsync(port, "/in", BuildMessage("PO*SYNC~", Cert, Cert)); sync.StatusCode.Should().Be(HttpStatusCode.OK); routed.Should().Be(2); release.SetResult(); (await first).StatusCode.Should().Be(HttpStatusCode.OK); (await trap.HitAsync(TimeSpan.FromSeconds(10))).Should().BeTrue(); // The slot comes back once the receipt is posted. var deadline = DateTime.UtcNow.AddSeconds(10); HttpResponseMessage again; do again = await PostAsync(port, "/in", BuildMessage("PO*3~", Cert, Cert), ReceiptTo(trap)); while (again.StatusCode == HttpStatusCode.ServiceUnavailable && DateTime.UtcNow < deadline && await Delay()); again.StatusCode.Should().Be(HttpStatusCode.OK); } private static async Task Delay() { await Task.Delay(50); return true; } [Fact] public async Task AnAsyncMdnAnsweredWithAServerError_IsPostedAgain_UntilItIsTaken() { using var trap = new As2Trap(FreePort(), hit => hit == 1 ? 503 : 200); var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", AsyncReceiver()); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").AsyncMdnRetry(3, 50)) .Process(_ => { })); await context.Start(); (await PostAsync(port, "/in", BuildMessage("PO*RETRY~", Cert, Cert), ReceiptTo(trap))).StatusCode.Should().Be(HttpStatusCode.OK); var deadline = DateTime.UtcNow.AddSeconds(10); while (trap.Requests.Count < 2 && DateTime.UtcNow < deadline) await Task.Delay(20); await Task.Delay(300); trap.Requests.Should().HaveCount(2, "one failed post, one taken; nothing after it is taken"); } [Fact] public async Task AnAsyncMdnThatIsNeverTaken_GivesUpAfterTheAttempts_AndIsCounted() { using var trap = new As2Trap(FreePort(), _ => 500); var port = FreePort(); long failed = 0; using var listener = new MeterListener(); listener.InstrumentPublished = (instrument, l) => { if (instrument.Name == "redb.route.as2.mdn.async_failed") l.EnableMeasurementEvents(instrument); }; listener.SetMeasurementEventCallback((_, value, _, _) => Interlocked.Add(ref failed, value)); listener.Start(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", AsyncReceiver()); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").AsyncMdnRetry(3, 50)) .Process(_ => { })); await context.Start(); (await PostAsync(port, "/in", BuildMessage("PO*NEVER~", Cert, Cert), ReceiptTo(trap))).StatusCode.Should().Be(HttpStatusCode.OK); var deadline = DateTime.UtcNow.AddSeconds(10); while (Interlocked.Read(ref failed) == 0 && DateTime.UtcNow < deadline) await Task.Delay(20); Interlocked.Read(ref failed).Should().Be(1); trap.Requests.Should().HaveCount(3); } [Fact] public async Task AnAsyncMdnRefusedWithAClientError_IsNotPostedAgain() { using var trap = new As2Trap(FreePort(), _ => 400); var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", AsyncReceiver()); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").AsyncMdnRetry(3, 50)) .Process(_ => { })); await context.Start(); (await PostAsync(port, "/in", BuildMessage("PO*BAD~", Cert, Cert), ReceiptTo(trap))).StatusCode.Should().Be(HttpStatusCode.OK); (await trap.HitAsync(TimeSpan.FromSeconds(10))).Should().BeTrue(); await Task.Delay(500); trap.Requests.Should().HaveCount(1, "the partner refused the receipt itself; sending it again changes nothing"); } } /// The give-up counter is process-wide: its test does not share the meter with a parallel one. [CollectionDefinition(nameof(AsyncMdnMetricsCollection), DisableParallelization = true)] public sealed class AsyncMdnMetricsCollection; Path: redb-route/tests/redb.Route.Tests.As2/As2ConcurrencyLimitOptionsTests.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.As2/As2ConcurrencyLimitOptionsTests.cs ---- using AwesomeAssertions; using redb.Route.As2; using redb.Route.Core; using Xunit; using As2Dsl = redb.Route.As2.Fluent.As2; namespace redb.Route.Tests.As2; /// /// Admission-limit options on the AS2 receiver. /// AS2 partners retry on their own MDN timeouts, so early shedding is cheaper than a saturated /// receiver doing S/MIME work it will never finish. The shed mechanics are e2e-proved on the /// shared host and the HTTP connector; here — that AS2 carries the quartet end to end. /// public sealed class As2ConcurrencyLimitOptionsTests { [Fact] public void UriAndDsl_CarryTheOptions() { var built = As2Dsl.Receive("/as2/in") .Port(4080) .MaxConcurrentRequests(2, queue: 4) .RejectStatusCode(503) .RetryAfterSeconds(0) .Build(); built.Should().Contain("maxConcurrentRequests=2") .And.Contain("requestQueueLimit=4") .And.Contain("rejectStatusCode=503") .And.Contain("retryAfterSeconds=0"); var endpoint = (As2Endpoint)new As2Component().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 QueueWithoutLimit_FailsLoud() { var uri = EndpointUriParser.Parse("as2:/in?port=4082&maxConcurrentRequests=0&requestQueueLimit=3"); var act = () => new As2Component().CreateEndpoint(uri); act.Should().Throw().WithMessage("*requestQueueLimit*maxConcurrentRequests*"); } [Theory] [InlineData("", 32, 32)] [InlineData("&maxConcurrentRequests=0", 0, 0)] [InlineData("&maxConcurrentRequests=8", 8, 32)] [InlineData("&maxConcurrentRequests=8&requestQueueLimit=0", 8, 0)] [InlineData("&requestQueueLimit=5", 32, 5)] public void Defaults_AreBounded_ZeroIsUnlimited(string query, int max, int queue) { var endpoint = (As2Endpoint)new As2Component().CreateEndpoint(EndpointUriParser.Parse("as2:/in?port=4084" + query)); endpoint.EndpointOptions.MaxConcurrentRequests.Should().Be(max); endpoint.EndpointOptions.RequestQueueLimit.Should().Be(queue); } [Fact] public void Dsl_CarriesAnExplicitZero() { As2Dsl.Receive("/as2/in").Port(4080).MaxConcurrentRequests(0).Build() .Should().Contain("maxConcurrentRequests=0").And.NotContain("requestQueueLimit"); As2Dsl.Receive("/as2/in").Port(4080).MaxConcurrentRequests(8, queue: 0).Build() .Should().Contain("maxConcurrentRequests=8").And.Contain("requestQueueLimit=0"); As2Dsl.Receive("/as2/in").Port(4080).Build() .Should().NotContain("maxConcurrentRequests").And.NotContain("requestQueueLimit"); } } Path: redb-route/tests/redb.Route.Tests.As2/As2DuplicateTests.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.As2/As2DuplicateTests.cs ---- using System.Net; using AwesomeAssertions; using redb.Route.As2; using redb.Route.As2.Crypto; using redb.Route.As2.Mdn; using redb.Route.Components; using redb.Route.Core; using redb.Route.Processors; using As2Dsl = redb.Route.As2.Fluent.As2; using static redb.Route.Tests.As2.As2TestKit; namespace redb.Route.Tests.As2; /// /// A partner that did not get our answer sends the document again with the same Message-ID. /// With an idempotent repository named, the resend is answered and not delivered twice, as the AS4 receiver does. /// public class As2DuplicateTests { private static async Task<(RouteContext Context, List Routed, int Port)> StartReceiver( string? repository, Func? failOnAttempt = null) { var port = FreePort(); var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); context.AddIdempotentRepository("dedup", new InMemoryIdempotentRepository()); var routed = new List(); var attempts = 0; var receive = As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv"); if (repository is not null) receive = receive.IdempotentRepository(repository); context.AddRoutes(r => r.From(receive).Process(e => { var attempt = Interlocked.Increment(ref attempts); if (failOnAttempt?.Invoke(attempt) == true) throw new InvalidOperationException("the route is down"); lock (routed) routed.Add(e.In.GetHeader(As2Headers.MessageId)!); })); await context.Start(); return (context, routed, port); } private static MdnParser.MdnResult Mdn(HttpResponseMessage response) => MdnParser.Parse( response.Content.Headers.ContentType?.ToString(), response.Content.Headers.TryGetValues("Content-Transfer-Encoding", out var v) ? string.Join(",", v) : null, response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(), new As2CryptoEngine(), Cert); [Fact] public async Task Resend_OfADeliveredMessage_IsAnswered_AndNotDeliveredAgain() { var (context, routed, port) = await StartReceiver("dedup"); await using var _ = context; var message = BuildMessage("PO*ONCE~", Cert, Cert); var id = new Dictionary { ["Message-ID"] = "" }; var first = Mdn(await PostAsync(port, "/in", message, id)); var again = Mdn(await PostAsync(port, "/in", message, id)); routed.Should().ContainSingle().Which.Should().Be(""); first.Disposition.Should().EndWith("; processed"); again.IsPositive.Should().BeTrue("the document was processed, once"); again.Disposition.Should().EndWith("processed/warning: duplicate-document"); again.ReceivedMic.Should().Be(first.ReceivedMic); } [Fact] public async Task Resend_AfterTheRouteFailed_IsDelivered() { var (context, routed, port) = await StartReceiver("dedup", attempt => attempt == 1); await using var _ = context; var message = BuildMessage("PO*RETRY~", Cert, Cert); var id = new Dictionary { ["Message-ID"] = "" }; Mdn(await PostAsync(port, "/in", message, id)).IsPositive.Should().BeFalse(); Mdn(await PostAsync(port, "/in", message, id)).IsPositive.Should().BeTrue(); routed.Should().ContainSingle("the first attempt did not process the document, so its resend is not a duplicate"); } [Fact] public async Task ForgedCopy_DoesNotBurnTheMessageId() { var (context, routed, port) = await StartReceiver("dedup"); await using var _ = context; var id = new Dictionary { ["Message-ID"] = "" }; // Claimed only after authentication: a stranger's copy with the id must not make the real message a "duplicate". await PostAsync(port, "/in", BuildMessage("PO*FORGED~", Stranger, Cert), id); await PostAsync(port, "/in", BuildMessage("PO*REAL~", Cert, Cert), id); routed.Should().ContainSingle(); } [Fact] public async Task WithoutARepository_EveryCopyIsDelivered() { var (context, routed, port) = await StartReceiver(null); await using var _ = context; var message = BuildMessage("PO*TWICE~", Cert, Cert); var id = new Dictionary { ["Message-ID"] = "" }; await PostAsync(port, "/in", message, id); await PostAsync(port, "/in", message, id); routed.Should().HaveCount(2); } [Fact] public async Task UnknownRepository_StopsTheReceiverFromStarting() { await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); var consumer = context.GetEndpoint(As2Dsl.Receive("/in").Host("127.0.0.1").Port(FreePort()).ConnectionFactory("recv").IdempotentRepository("nope")) .CreateConsumer(new DelegateProcessor(_ => { })); var act = () => consumer.Start(); (await act.Should().ThrowAsync()).Which.Message.Should().Contain("nope"); } [Fact] public async Task Resend_WhileTheFirstCopyIsStillInTheRoute_IsRefusedAsBusy_AndDeliveredAfterTheFirstFails() { // The first copy fails after the resend arrived: answering the resend "duplicate-document" would have told the // partner the document was received, and the release of the first claim would have lost it. var port = FreePort(); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var attempts = 0; var routed = new List(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); context.AddIdempotentRepository("dedup", new InMemoryIdempotentRepository()); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").IdempotentRepository("dedup")) .Process(async (e, _) => { if (Interlocked.Increment(ref attempts) == 1) { entered.TrySetResult(); await release.Task; throw new InvalidOperationException("the route is down"); } lock (routed) routed.Add(e.In.GetHeader(As2Headers.MessageId)!); })); await context.Start(); var message = BuildMessage("PO*INFLIGHT~", Cert, Cert); var id = new Dictionary { ["Message-ID"] = "" }; var first = PostAsync(port, "/in", message, id); await entered.Task.WaitAsync(TimeSpan.FromSeconds(10)); var resend = await PostAsync(port, "/in", message, id); resend.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); resend.Headers.RetryAfter!.Delta.Should().Be(TimeSpan.FromSeconds(30)); resend.Content.Headers.ContentLength.Should().Be(0, "no MDN: nothing was decided about the document"); release.SetResult(); Mdn(await first).Disposition.Should().EndWith("processed/error: unexpected-processing-error"); var later = Mdn(await PostAsync(port, "/in", message, id)); later.Disposition.Should().EndWith("; processed", "the failed copy released its claim, so the resend is delivered"); routed.Should().ContainSingle().Which.Should().Be(""); } [Fact] public async Task AClaimTakenOverWhileTheRouteRuns_IsNotConfirmedByTheFirstHolder() { // The route outlives the timeout and another node takes the claim over meanwhile: the first holder's confirmation // must leave that node's claim alone, unconfirmed, for its holder to settle. var repository = new InMemoryIdempotentRepository(); var port = FreePort(); string? otherToken = null; await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); context.AddIdempotentRepository("dedup", repository); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv") .IdempotentRepository("dedup")) .Process(_ => { Thread.Sleep(50); var other = repository.Lease("", TimeSpan.FromMilliseconds(10)).GetAwaiter().GetResult(); other.Outcome.Should().Be(redb.Route.Abstractions.IdempotentClaim.TakenOver); otherToken = other.Token; })); await context.Start(); var mdn = Mdn(await PostAsync(port, "/in", BuildMessage("PO*SLOW~", Cert, Cert), new Dictionary { ["Message-ID"] = "" })); mdn.Disposition.Should().EndWith("; processed"); (await repository.Claim("", null)).Should().Be(redb.Route.Abstractions.IdempotentClaim.InFlight, "the other node's claim is still its own, unconfirmed"); (await repository.Confirm("", otherToken)).Should().BeTrue(); } [Fact] public async Task AClaimNeverConfirmed_OlderThanInFlightClaimTimeout_IsTakenOver_AndTheMessageDelivered() { // A node stopped between the claim and its confirmation: the claim stays, unconfirmed. var repository = new InMemoryIdempotentRepository(); (await repository.Add("")).Should().BeTrue(); var port = FreePort(); var routed = 0; await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); context.AddIdempotentRepository("dedup", repository); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv") .IdempotentRepository("dedup").InFlightClaimTimeout(50)) .Process(_ => Interlocked.Increment(ref routed))); await context.Start(); await Task.Delay(200); var mdn = Mdn(await PostAsync(port, "/in", BuildMessage("PO*ORPHAN~", Cert, Cert), new Dictionary { ["Message-ID"] = "" })); mdn.Disposition.Should().EndWith("; processed"); routed.Should().Be(1); (await repository.Claim("", null)).Should().Be(redb.Route.Abstractions.IdempotentClaim.Confirmed); } [Fact] public async Task AClaimNeverConfirmed_YoungerThanInFlightClaimTimeout_IsRefusedAsBusy() { var repository = new InMemoryIdempotentRepository(); (await repository.Add("")).Should().BeTrue(); var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); context.AddIdempotentRepository("dedup", repository); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").IdempotentRepository("dedup")) .Process(_ => { })); await context.Start(); var response = await PostAsync(port, "/in", BuildMessage("PO*YOUNG~", Cert, Cert), new Dictionary { ["Message-ID"] = "" }); response.StatusCode.Should().Be(HttpStatusCode.ServiceUnavailable); } } Path: redb-route/tests/redb.Route.Tests.As2/As2HeaderFilterStrategyTests.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.As2/As2HeaderFilterStrategyTests.cs ---- using redb.Route.Abstractions; using redb.Route.As2; using redb.Route.Core; using As2Dsl = redb.Route.As2.Fluent.As2; namespace redb.Route.Tests.As2; /// /// headerFilterStrategy=#name on AS2 endpoints: on a producer it decides which exchange headers go out as HTTP /// headers of the message, on a consumer which request headers come in. The MIME, AS2, hop-by-hop and credential /// fields and the consumer's redbAs2.* metadata stay outside the strategy. /// public sealed class As2HeaderFilterStrategyTests { private static async Task> Send(string producerOptions, string consumerOptions, IHeaderFilterStrategy? everything = null) { var port = As2TestKit.FreePort(); var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("me", As2TestKit.Receiver()); context.AddToRegistry("them", As2TestKit.Sender()); context.AddToRegistry("correlationOnly", new DefaultHeaderFilterStrategy { OutFilter = ["Correlation-ID"], FilterOnMatch = false }); context.AddToRegistry("noSecrets", new DefaultHeaderFilterStrategy { InFilter = ["X-Secret"] }); if (everything is not null) context.AddToRegistry("everything", everything); context.AddRoutes(r => r .From(As2Dsl.Receive("/inbound").Host("127.0.0.1").Port(port).ConnectionFactory("me").Build() + consumerOptions) .Process(e => received.TrySetResult(e))); await context.Start(); var producer = context .GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/inbound").ConnectionFactory("them").Build() + producerOptions) .CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("ISA*00*...EDI~") { ContentType = "application/edi-x12" }); exchange.In.Headers["Correlation-ID"] = "c-42"; exchange.In.Headers["X-Corr"] = "c1"; exchange.In.Headers["X-Secret"] = "s1"; exchange.In.Headers["Authorization"] = "Bearer secret"; await producer.Process(exchange); await producer.Stop(); return new Dictionary((await received.Task.WaitAsync(TimeSpan.FromSeconds(30))).In.Headers, StringComparer.OrdinalIgnoreCase); } [Fact] public async Task OnAProducer_AWhitelistSendsOnlyTheNamedHeader() { var headers = await Send("&headerFilterStrategy=#correlationOnly", ""); headers["Correlation-ID"].Should().Be("c-42"); headers.Should().NotContainKey("X-Corr"); headers.Should().NotContainKey("X-Secret"); headers.Should().ContainKey(As2Headers.SignatureValid, "the consumer's own metadata is set whatever the strategy says"); } [Fact] public async Task OnAConsumer_TheStrategyDecidesWhatComesIn() { var headers = await Send("", "&headerFilterStrategy=#noSecrets"); headers["X-Corr"].Should().Be("c1"); headers.Should().NotContainKey("X-Secret", "the consumer's strategy drops it on the way in"); } [Fact] public async Task ACredentialNeverCrosses_WhateverTheStrategySays() { var headers = await Send("&headerFilterStrategy=#everything", "&headerFilterStrategy=#everything", new DefaultHeaderFilterStrategy { FilterOnMatch = true }); headers["X-Corr"].Should().Be("c1"); headers.Should().NotContainKey("Authorization", "the producer never bridges another hop's credentials, and the consumer never takes the hop's own"); } } Path: redb-route/tests/redb.Route.Tests.As2/As2HeaderMappingCharacterizationTests.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.As2/As2HeaderMappingCharacterizationTests.cs ---- using System.Text; using redb.Route.Abstractions; using redb.Route.As2; using redb.Route.Core; using As2Dsl = redb.Route.As2.Fluent.As2; namespace redb.Route.Tests.As2; /// /// What crosses an AS2 message today, producer to consumer: pinned before the header filter strategy /// takes the rule over, so the transport's default keeps it exactly. /// The producer sends every exchange header but its own redbAs2.*, As2Headers.NonBridgedHeaders (the /// MIME and AS2 fields it sets itself) and null values as HTTP headers; the consumer takes every request header but /// pseudo-headers, the wrapper and hop-by-hop fields and the credentials that authenticated the hop. /// public sealed class As2HeaderMappingCharacterizationTests { [Fact] public async Task ProducerToConsumer_TheHeadersThatCrossTheMessage() { var port = As2TestKit.FreePort(); var received = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("me", As2TestKit.Receiver()); context.AddToRegistry("them", As2TestKit.Sender()); context.AddRoutes(r => r .From(As2Dsl.Receive("/inbound").Host("127.0.0.1").Port(port).ConnectionFactory("me")) .Process(e => received.TrySetResult(e))); await context.Start(); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/inbound").ConnectionFactory("them")) .CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("ISA*00*...EDI~") { ContentType = "application/edi-x12" }); exchange.In.Headers["X-Corr"] = "c1"; exchange.In.Headers["X-Int"] = 42; exchange.In.Headers["X-Null"] = null; exchange.In.Headers["Authorization"] = "Bearer secret"; exchange.In.Headers["redbHttp.Method"] = "DELETE"; exchange.In.Headers[As2Headers.Prefix + "Custom"] = "own"; await producer.Process(exchange); await producer.Stop(); var arrived = await received.Task.WaitAsync(TimeSpan.FromSeconds(30)); var headers = arrived.In.Headers; Encoding.UTF8.GetString((byte[])arrived.In.Body!).Should().Be("ISA*00*...EDI~"); headers["X-Corr"].Should().Be("c1"); headers["X-Int"].Should().Be("42", "a value crosses as its text"); headers.Should().NotContainKey("X-Null", "a null value is skipped"); headers.Should().NotContainKey("Authorization", "the producer sends it, but the consumer drops the credentials that authenticated the hop"); headers["redbHttp.Method"].Should().Be("DELETE", "a control header of another transport crosses (finding 3.1)"); headers.Should().NotContainKey(As2Headers.Prefix + "Custom", "the producer keeps its own redbAs2.* back"); } } Path: redb-route/tests/redb.Route.Tests.As2/As2InteropTests.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.As2/As2InteropTests.cs ---- using System.Net.Sockets; using System.Security.Cryptography.X509Certificates; using System.Text; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.As2; using redb.Route.Core; using Xunit.Sdk; using As2Dsl = redb.Route.As2.Fluent.As2; namespace redb.Route.Tests.As2; /// /// A fact that needs the OpenAS2 interop stand (profile as2 of docker-compose.tests.yml) on 127.0.0.1:14080. Skipped, visibly, /// when nothing listens there, unless REDB_AS2_INTEROP=1 makes that a failure (the AS4 stand gate). /// [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] [XunitTestCaseDiscoverer("Xunit.Sdk.FactDiscoverer", "xunit.execution.{Platform}")] public sealed class As2InteropFactAttribute : FactAttribute { public As2InteropFactAttribute() => Skip = SkipReason(); /// Why a stand test is skipped here, or null when the stand is up or required. internal static string? SkipReason() => Environment.GetEnvironmentVariable("REDB_AS2_INTEROP") != "1" && !As2InteropTests.IsReachable("127.0.0.1", 14080) ? $"OpenAS2 stand is not up on 127.0.0.1:14080 ({(global::redb.Route.Tests.Shared.TestStand.Up("as2"))}); REDB_AS2_INTEROP=1 requires it." : null; } /// The theory form of : skipped, visibly, without the OpenAS2 stand. [AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)] [XunitTestCaseDiscoverer("Xunit.Sdk.TheoryDiscoverer", "xunit.execution.{Platform}")] public sealed class As2InteropTheoryAttribute : TheoryAttribute { public As2InteropTheoryAttribute() => Skip = As2InteropFactAttribute.SkipReason(); } /// /// Interop tests against a real OpenAS2 server (profile as2 of docker-compose.tests.yml). These prove interop /// correctness — that an external AS2 implementation accepts our signed+encrypted wire format and MIC — /// which loopback e2e cannot. Skipped visibly without the stand (). /// Run with --filter Category=Interop once tests/docker/gen-certs.sh has run and the as2 profile is up. /// [Trait("Category", "Interop")] public class As2InteropTests { private const string OpenAs2Host = "127.0.0.1"; private const int OpenAs2Port = 14080; internal static string CertsDir => Environment.GetEnvironmentVariable("AS2_INTEROP_CERTS") ?? global::redb.Route.Tests.Shared.TestStand.Generated(Path.Combine("as2", "certs")); [As2InteropFact] public async Task Redb_To_OpenAs2_AsyncMdn_IsPostedBack_Signed_AndConfirms() { // OpenAS2 answers 200 at once and posts its signed MDN to the Receipt-Delivery-Option we send: our ReceiveMdn // endpoint on the host, reached from the container as host.docker.internal. var ourCert = LoadPkcs12(Path.Combine(CertsDir, "redb.p12"), "testpass"); var partnerCert = LoadCertificate(Path.Combine(CertsDir, "openas2.crt")); var mdnPort = global::redb.Route.Tests.Shared.TestPorts.Next(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("openas2", new As2ConnectionFactory { OurCertificate = ourCert, PartnerCertificate = partnerCert, As2From = "redb", As2To = "openas2", Sign = true, Encrypt = true, SignAlg = "sha-256", EncryptAlg = "aes-128-cbc", SignedMdn = true, RequireValidMdn = true, MdnMode = As2MdnMode.Async, AsyncMdnUrl = $"http://host.docker.internal:{mdnPort}/as2/mdn", }); var receipts = new System.Collections.Concurrent.ConcurrentQueue<(string? Id, bool Confirmed, bool Signed, string? Mic)>(); context.AddRoutes(r => r.From(As2Dsl.ReceiveMdn("/as2/mdn").Host("0.0.0.0").Port(mdnPort).ConnectionFactory("openas2")) .Process(e => receipts.Enqueue(( e.In.GetHeader(As2Headers.MessageId), e.In.GetHeader(As2Headers.MdnConfirmed), e.In.GetHeader(As2Headers.SignatureValid), e.In.GetHeader(As2Headers.MdnMicStatus))))); await context.Start(); var producer = context.GetEndpoint( As2Dsl.Send($"http://{OpenAs2Host}:{OpenAs2Port}/").ConnectionFactory("openas2")).CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message($"ISA*00*ASYNC*{Guid.NewGuid():N}~") { ContentType = "application/edi-x12" }); await producer.Process(exchange); var sentId = exchange.In.GetHeader(As2Headers.MessageId); exchange.HasOut.Should().BeFalse("an asynchronous MDN is not in the response"); var deadline = DateTime.UtcNow.AddSeconds(30); while (!receipts.Any(r => r.Id == sentId) && DateTime.UtcNow < deadline) await Task.Delay(250); receipts.Should().Contain(r => r.Id == sentId, "OpenAS2 posts the MDN to our Receipt-Delivery-Option") .Which.Should().Be((sentId, true, true, "matched")); } [As2InteropFact] public async Task OpenAs2_To_Redb_AsyncMdn_IsPostedToOpenAs2_AndItClosesThePendingMessage() { // Partnership openas2-to-redb-async asks for an asynchronous receipt at http://127.0.0.1:14081 (OpenAS2's MDN // receiver as the host reaches it). Our receiver answers 200 and posts the signed MDN there; OpenAS2 matches it // to its pending message and deletes the pending file. const int consumerPort = 15082; // matches the partnership's as2_url host.docker.internal:15082 var ourCert = LoadPkcs12(Path.Combine(CertsDir, "redb.p12"), "testpass"); var partnerCert = LoadCertificate(Path.Combine(CertsDir, "openas2.crt")); await using var standLock = await LockAsync(consumerPort); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("openas2", new As2ConnectionFactory { OurCertificate = ourCert, PartnerCertificate = partnerCert, As2From = "redb-async", As2To = "openas2", Sign = true, Encrypt = true, SignedMdn = true, MdnMode = As2MdnMode.Async, AsyncMdnAllowedHosts = ["127.0.0.1"], }); var received = new List(); context.AddRoutes(r => r.From(As2Dsl.Receive("/inbound").Host("0.0.0.0").Port(consumerPort).ConnectionFactory("openas2")) .Process(e => { lock (received) received.Add(Encoding.UTF8.GetString((byte[])e.In.Body!)); })); await context.Start(); var harnessDir = Path.GetDirectoryName(CertsDir.TrimEnd('\\', '/'))!; var outbox = Path.Combine(harnessDir, "data", "outbox", "redb-async"); var pending = Path.Combine(harnessDir, "data", "pendinginfoMDN3"); Directory.CreateDirectory(outbox); var name = $"async-{Guid.NewGuid():N}"; var payload = $"ISA*00*OPENAS2*ZZ*REDB*ASYNC*{name}~"; await File.WriteAllTextAsync(Path.Combine(outbox, name + ".edi"), payload); bool Seen() { lock (received) return received.Contains(payload); } bool Pending() => Directory.Exists(pending) && Directory.EnumerateFiles(pending).Any(f => f.Contains(name, StringComparison.Ordinal)); var deadline = DateTime.UtcNow.AddSeconds(40); while (!Seen() && DateTime.UtcNow < deadline) await Task.Delay(250); Seen().Should().BeTrue("OpenAS2 delivers the dropped file to our receiver"); deadline = DateTime.UtcNow.AddSeconds(20); while (Pending() && DateTime.UtcNow < deadline) await Task.Delay(250); Pending().Should().BeFalse("OpenAS2 accepted our asynchronous MDN and closed the pending message"); } /// /// A file opened without sharing is the lock between the three target frameworks' processes on a port the stand /// posts to; released by the process when it ends, whatever thread it is on. /// private static async Task LockAsync(int port) { var lockPath = Path.Combine(Path.GetTempPath(), $"redb-as2-interop-{port}.lock"); var deadline = DateTime.UtcNow.AddMinutes(3); while (true) { try { return new FileStream(lockPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); } catch (IOException) when (DateTime.UtcNow < deadline) { await Task.Delay(250); } } } [As2InteropFact] public async Task Redb_To_OpenAs2_SignedEncrypted_ReturnsPositiveMdn() { var ourCert = LoadPkcs12(Path.Combine(CertsDir, "redb.p12"), "testpass"); var partnerCert = LoadCertificate(Path.Combine(CertsDir, "openas2.crt")); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("openas2", new As2ConnectionFactory { OurCertificate = ourCert, PartnerCertificate = partnerCert, As2From = "redb", As2To = "openas2", Sign = true, Encrypt = true, SignAlg = "sha-256", EncryptAlg = "aes-128-cbc", SignedMdn = true, MdnMode = As2MdnMode.Sync, }); await context.Start(); var producer = context.GetEndpoint( As2Dsl.Send($"http://{OpenAs2Host}:{OpenAs2Port}/").ConnectionFactory("openas2")).CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("ISA*00* *00* *ZZ*REDB~") { ContentType = "application/edi-x12" }); await producer.Process(exchange); // OpenAS2 accepted our signed+encrypted message and returned a positive, verifiable MDN. exchange.HasOut.Should().BeTrue(); exchange.Out!.GetHeader(As2Headers.MdnDisposition).Should().Contain("processed"); exchange.Out!.GetHeader(As2Headers.MdnMicMatch).Should().BeTrue(); } [As2InteropFact] public async Task OpenAs2_To_Redb_ReceivesSignedEncrypted() { // The stand posts to one fixed port, and the three target frameworks run as three processes at once: without // the lock one of them holds the port and receives the others' documents while they time out. // A file opened without sharing is the lock: released by the process when it ends, whatever thread it is on. var lockPath = Path.Combine(Path.GetTempPath(), "redb-as2-interop-15081.lock"); FileStream? standLock = null; var deadline = DateTime.UtcNow.AddMinutes(3); while (standLock is null) { try { standLock = new FileStream(lockPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None); } catch (IOException) when (DateTime.UtcNow < deadline) { await Task.Delay(250); } } await using (standLock) await ReverseAsync(); } private static async Task ReverseAsync() { const int consumerPort = 15081; // matches partnerships.xml as2_url host.docker.internal:15081 var ourCert = LoadPkcs12(Path.Combine(CertsDir, "redb.p12"), "testpass"); // our key: decrypt var partnerCert = LoadCertificate(Path.Combine(CertsDir, "openas2.crt")); // partner cert: verify await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("openas2", new As2ConnectionFactory { OurCertificate = ourCert, PartnerCertificate = partnerCert, As2From = "redb", As2To = "openas2", Sign = true, Encrypt = true, SignedMdn = true, MdnMode = As2MdnMode.Sync, }); var received = new List(); context.AddRoutes(r => r.From(As2Dsl.Receive("/inbound").Host("0.0.0.0").Port(consumerPort).ConnectionFactory("openas2")) .Process(e => { lock (received) received.Add(Encoding.UTF8.GetString((byte[])e.In.Body!)); })); await context.Start(); // Drop a file into OpenAS2's outbox for partner "redb"; its directory poller picks it up, builds a // signed+encrypted AS2 message and POSTs it to our consumer at host.docker.internal:15081/inbound. var harnessDir = Path.GetDirectoryName(CertsDir.TrimEnd('\\', '/'))!; var outbox = Path.Combine(harnessDir, "data", "outbox", "redb"); Directory.CreateDirectory(outbox); var payload = $"ISA*00*OPENAS2*ZZ*REDB*REVERSE*{Guid.NewGuid():N}~"; await File.WriteAllTextAsync(Path.Combine(outbox, $"reverse-{Guid.NewGuid():N}.edi"), payload); // Wait for the poller (5s interval) + delivery. var deadline = DateTime.UtcNow.AddSeconds(40); while (!Seen() && DateTime.UtcNow < deadline) await Task.Delay(500); Seen().Should().BeTrue("OpenAS2 delivers the dropped file to our receiver"); bool Seen() { lock (received) return received.Contains(payload); } } // ── Helpers ────────────────────────────────────────────────────────────── internal static bool IsReachable(string host, int port) { try { using var client = new TcpClient(); var connect = client.ConnectAsync(host, port); return connect.Wait(TimeSpan.FromMilliseconds(500)) && client.Connected; } catch { return false; } } internal static X509Certificate2 LoadPkcs12(string path, string password) { return X509CertificateLoader.LoadPkcs12FromFile(path, password, X509KeyStorageFlags.Exportable); } internal static X509Certificate2 LoadCertificate(string path) => X509Certificate2.CreateFromPem(File.ReadAllText(path)); } Path: redb-route/tests/redb.Route.Tests.As2/As2LimitsTests.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.As2/As2LimitsTests.cs ---- using System.Diagnostics; using System.Net; using AwesomeAssertions; using redb.Route.As2; using redb.Route.As2.Crypto; using redb.Route.As2.Mdn; using redb.Route.Core; using As2Dsl = redb.Route.As2.Fluent.As2; using static redb.Route.Tests.As2.As2TestKit; namespace redb.Route.Tests.As2; /// /// Bounds and lifecycle: a request or response larger than the endpoint allows is /// refused before it is buffered, and the MDN receiver drains, traces and labels its exchanges as the message /// receiver does. /// public class As2LimitsTests { [Fact] public async Task Message_LargerThanMaxRequestBodySize_IsRefusedWith413_AndNotRouted() { var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); var routed = 0; context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").MaxRequestBodySize(4096)) .Process(_ => Interlocked.Increment(ref routed))); await context.Start(); var big = BuildMessage(new string('X', 64 * 1024), Cert, Cert); var response = await PostAsync(port, "/in", big, expectContinue: true); response.StatusCode.Should().Be(HttpStatusCode.RequestEntityTooLarge); routed.Should().Be(0); ((redb.Route.Abstractions.IEndpointStatistics)context.GetEndpoint( As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").MaxRequestBodySize(4096))) .LastErrorMessage.Should().Contain("maxRequestBodySize", "the dashboard shows why the request was refused"); } [Fact] public async Task Message_WithinMaxRequestBodySize_IsRouted() { var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); var routed = 0; context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").MaxRequestBodySize(256 * 1024)) .Process(_ => Interlocked.Increment(ref routed))); await context.Start(); var response = await PostAsync(port, "/in", BuildMessage(new string('X', 64 * 1024), Cert, Cert)); response.StatusCode.Should().Be(HttpStatusCode.OK); routed.Should().Be(1); } [Fact] public void MaxRequestBodySize_DefaultsTo100MB_AndMustBePositive() { new As2EndpointOptions().MaxRequestBodySize.Should().Be(100L * 1024 * 1024); var act = () => new As2EndpointOptions { MaxRequestBodySize = 0 }.Validate(); act.Should().Throw().WithMessage("*maxRequestBodySize*"); } [Fact] public async Task CompressedMessage_ThatInflatesPastMaxDecompressedSize_IsRefusedWithDecompressionFailed_AndNotRouted() { // A few kilobytes on the wire that inflate to 2 MB: the body limit alone lets it through. var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); var routed = 0; context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").MaxDecompressedSize(1024 * 1024)) .Process(_ => Interlocked.Increment(ref routed))); await context.Start(); var bomb = BuildMessage(new string('X', 2 * 1024 * 1024), Cert, Cert, compress: true); bomb.Body.Length.Should().BeLessThan(64 * 1024, "the point is a small body that inflates"); var response = await PostAsync(port, "/in", bomb); response.StatusCode.Should().Be(HttpStatusCode.OK); var mdn = ReadMdn(response); mdn.IsPositive.Should().BeFalse(); mdn.Disposition.Should().EndWith("processed/error: decompression-failed"); routed.Should().Be(0); } [Fact] public async Task CompressedMessage_WithinMaxDecompressedSize_IsRouted() { var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); string? delivered = null; context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").MaxDecompressedSize(1024 * 1024)) .Process(e => delivered = System.Text.Encoding.UTF8.GetString((byte[])e.In.Body!))); await context.Start(); var payload = new string('X', 512 * 1024); var response = await PostAsync(port, "/in", BuildMessage(payload, Cert, Cert, compress: true)); ReadMdn(response).IsPositive.Should().BeTrue(); delivered.Should().Be(payload); } [Fact] public async Task MaxDecompressedSize_Unset_IsMaxRequestBodySize() { // The payload a request hands over is bounded as its body is: a compressed body may not inflate past it. var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); var routed = 0; context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").MaxRequestBodySize(256 * 1024)) .Process(_ => Interlocked.Increment(ref routed))); await context.Start(); var response = await PostAsync(port, "/in", BuildMessage(new string('X', 1024 * 1024), Cert, Cert, compress: true)); ReadMdn(response).Disposition.Should().EndWith("processed/error: decompression-failed"); routed.Should().Be(0); new As2EndpointOptions().MaxDecompressedSize.Should().BeNull(); var act = () => new As2EndpointOptions { MaxDecompressedSize = 0 }.Validate(); act.Should().Throw().WithMessage("*maxDecompressedSize*"); } private static MdnParser.MdnResult ReadMdn(HttpResponseMessage response) { var cte = response.Content.Headers.TryGetValues("Content-Transfer-Encoding", out var v) ? string.Join(",", v) : null; var body = response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(); return MdnParser.Parse(response.Content.Headers.ContentType?.ToString(), cte, body, new As2CryptoEngine(), Cert); } [Fact] public async Task Mdn_LargerThanMaxRequestBodySize_IsRefusedWith413() { var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("them", Sender(f => { f.MdnMode = As2MdnMode.Async; f.AsyncMdnUrl = $"http://127.0.0.1:{port}/mdn"; })); var routed = 0; context.AddRoutes(r => r.From(As2Dsl.ReceiveMdn("/mdn").Host("127.0.0.1").Port(port).ConnectionFactory("them").MaxRequestBodySize(4096)) .Process(_ => Interlocked.Increment(ref routed))); await context.Start(); using var client = new HttpClient(); var content = new ByteArrayContent(new byte[64 * 1024]); content.Headers.TryAddWithoutValidation("Content-Type", "multipart/report; report-type=disposition-notification; boundary=x"); var request = new HttpRequestMessage(HttpMethod.Post, $"http://127.0.0.1:{port}/mdn") { Content = content }; request.Headers.ExpectContinue = true; // refused before the body is sent, not reset mid-upload var response = await client.SendAsync(request); response.StatusCode.Should().Be(HttpStatusCode.RequestEntityTooLarge); routed.Should().Be(0); ((redb.Route.Abstractions.IEndpointStatistics)context.GetEndpoint( As2Dsl.ReceiveMdn("/mdn").Host("127.0.0.1").Port(port).ConnectionFactory("them").MaxRequestBodySize(4096))) .LastErrorMessage.Should().Contain("maxRequestBodySize", "the dashboard shows why the receipt was refused"); } [Fact] public async Task Send_WhoseResponseIsLargerThanMaxResponseBodySize_Fails_WithoutReadingIt() { var port = FreePort(); using var listener = new HttpListener(); listener.Prefixes.Add($"http://127.0.0.1:{port}/"); listener.Start(); var partner = Task.Run(async () => { var ctx = await listener.GetContextAsync(); await ctx.Request.InputStream.CopyToAsync(Stream.Null); ctx.Response.StatusCode = 200; ctx.Response.ContentType = "text/html"; try { await ctx.Response.OutputStream.WriteAsync(new byte[256 * 1024]); ctx.Response.Close(); } catch (HttpListenerException) { /* the producer stopped reading: that is the point */ } }); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("them", Sender()); var producer = context.GetEndpoint( As2Dsl.Send($"http://127.0.0.1:{port}/as2").ConnectionFactory("them").MaxResponseBodySize(1024)).CreateProducer(); await producer.Start(); var act = () => producer.Process(new Exchange(new Message("PO*BIG~") { ContentType = "application/edi-x12" })); (await act.Should().ThrowAsync()).Which.Message.Should().Contain("maxResponseBodySize"); await partner.WaitAsync(TimeSpan.FromSeconds(10)); } // ── MDN receiver lifecycle ─────────────────────────────────────────────── private static (string ContentType, string? Cte, byte[] Body) SignedMdn(string originalId) => MdnBuilder.Build(originalId, "US", "THEM", new As2Mic("AAAA", "sha-256"), null, null, new As2CryptoEngine(), Cert); private static Task PostMdn(HttpClient client, int port, (string ContentType, string? Cte, byte[] Body) mdn) { var content = new ByteArrayContent(mdn.Body); content.Headers.TryAddWithoutValidation("Content-Type", mdn.ContentType); if (mdn.Cte is not null) content.Headers.TryAddWithoutValidation("Content-Transfer-Encoding", mdn.Cte); return client.PostAsync($"http://127.0.0.1:{port}/mdn", content); } [Fact] public async Task MdnReceiver_Stop_WaitsForAReceiptAlreadyInTheRoute() { var port = FreePort(); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var finished = false; await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("them", Sender(f => { f.MdnMode = As2MdnMode.Async; f.AsyncMdnUrl = $"http://127.0.0.1:{port}/mdn"; })); var slow = context.GetEndpoint(As2Dsl.ReceiveMdn("/mdn").Host("127.0.0.1").Port(port).ConnectionFactory("them").Build()) .CreateConsumer(new redb.Route.Processors.DelegateProcessor(async (e, ct) => { entered.TrySetResult(); await release.Task; finished = true; })); // A second route keeps the listener alive after the first is stopped. context.AddToRegistry("recv", Receiver()); var other = context.GetEndpoint(As2Dsl.Receive("/other").Host("127.0.0.1").Port(port).ConnectionFactory("recv").Build()) .CreateConsumer(new redb.Route.Processors.DelegateProcessor(_ => { })); await slow.Start(); await other.Start(); using var client = new HttpClient(); var call = PostMdn(client, port, SignedMdn("")); 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 receipt is still in the route"); release.TrySetResult(); await stop.WaitAsync(TimeSpan.FromSeconds(15)); finished.Should().BeTrue(); (await call).StatusCode.Should().Be(HttpStatusCode.OK); await other.Stop(); } [Fact] public async Task MdnReceiver_LabelsTheExchange_AndTracesTheRequest() { var spans = new List(); using var activityListener = new ActivityListener { ShouldListenTo = s => s.Name == "redb.Route", Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllData, ActivityStopped = a => { lock (spans) spans.Add(a); }, }; ActivitySource.AddActivityListener(activityListener); var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("them", Sender(f => { f.MdnMode = As2MdnMode.Async; f.AsyncMdnUrl = $"http://127.0.0.1:{port}/mdn"; })); var seen = new System.Collections.Concurrent.ConcurrentQueue<(string? Remote, string? Partner)>(); context.AddRoutes(r => r.From(As2Dsl.ReceiveMdn("/mdn").Host("127.0.0.1").Port(port).ConnectionFactory("them")) .Process(e => seen.Enqueue((e.In.GetHeader(As2Headers.RemoteAddress), e.In.GetHeader(As2Headers.PartnerName))))); await context.Start(); using var client = new HttpClient(); (await PostMdn(client, port, SignedMdn(""))).StatusCode.Should().Be(HttpStatusCode.OK); seen.Should().ContainSingle().Which.Should().Be(("127.0.0.1", "them")); // The span ends when the handler returns, just after the 200 the client already has. var deadline = DateTime.UtcNow.AddSeconds(5); bool Traced() { lock (spans) return spans.Any(a => a.OperationName == "/mdn receive" && a.Kind == ActivityKind.Consumer); } while (!Traced() && DateTime.UtcNow < deadline) await Task.Delay(20); Traced().Should().BeTrue(); } } Path: redb-route/tests/redb.Route.Tests.As2/As2MdnVerdictTests.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.As2/As2MdnVerdictTests.cs ---- using System.Net; using AwesomeAssertions; using redb.Route.As2; using redb.Route.As2.Crypto; using redb.Route.As2.Mdn; using redb.Route.Core; using As2Dsl = redb.Route.As2.Fluent.As2; using static redb.Route.Tests.As2.As2TestKit; namespace redb.Route.Tests.As2; /// /// What a receipt proves: a transfer is confirmed only by a positive MDN whose /// Received-Content-MIC is the one we sent and whose signature the agreement's policy accepts. A missing MIC, an /// unknown message, or an unsigned receipt where a signed one is agreed is not a confirmation. /// public class As2MdnVerdictTests { private static (string ContentType, string? Cte, byte[] Body) Mdn(string originalId, As2Mic? mic, bool signed = true, string? failure = null) => MdnBuilder.Build(originalId, "US", "THEM", mic, failure, null, signer: signed ? new As2CryptoEngine() : null, signerCert: signed ? Cert : null); /// A partner that answers every POST with the given MDN, built for the Message-ID it received. private static Task Partner(HttpListener listener, Func mdnFor) => Task.Run(async () => { var ctx = await listener.GetContextAsync(); var messageId = ctx.Request.Headers["Message-ID"]!; await ctx.Request.InputStream.CopyToAsync(Stream.Null); var (contentType, cte, body) = mdnFor(messageId); ctx.Response.StatusCode = 200; ctx.Response.ContentType = contentType; if (cte is not null) ctx.Response.Headers["Content-Transfer-Encoding"] = cte; await ctx.Response.OutputStream.WriteAsync(body); ctx.Response.Close(); }); private static async Task<(Exchange Exchange, Exception? Error)> SendAsync( Func mdnFor, Action? configure = null) { var port = FreePort(); using var listener = new HttpListener(); listener.Prefixes.Add($"http://127.0.0.1:{port}/"); listener.Start(); var partner = Partner(listener, mdnFor); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("them", Sender(configure)); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/as2").ConnectionFactory("them")).CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("PO*MDN~") { ContentType = "application/edi-x12" }); Exception? error = null; try { await producer.Process(exchange); } catch (Exception e) { error = e; } await partner.WaitAsync(TimeSpan.FromSeconds(10)); return (exchange, error); } [Fact] public async Task SyncMdn_WithoutReceivedContentMic_IsNotAMatch() { var (exchange, error) = await SendAsync(id => Mdn(id, mic: null)); error.Should().BeNull(); exchange.Out!.GetHeader(As2Headers.MdnMicMatch).Should().BeFalse("nobody compared a MIC"); exchange.Out!.GetHeader(As2Headers.MdnMicStatus).Should().Be("absent"); exchange.Out!.GetHeader(As2Headers.MdnConfirmed).Should().BeFalse(); } [Fact] public async Task SyncMdn_WithoutReceivedContentMic_FailsTheSend_WhenAValidMdnIsRequired() { var (_, error) = await SendAsync(id => Mdn(id, mic: null), f => f.RequireValidMdn = true); error.Should().BeOfType().Which.Message.Should().Contain("absent"); } [Fact] public async Task SyncMdn_WithAnotherMic_IsAMismatch() { var (exchange, _) = await SendAsync(id => Mdn(id, new As2Mic("AAAA", "sha-256"))); exchange.Out!.GetHeader(As2Headers.MdnMicStatus).Should().Be("mismatch"); exchange.Out!.GetHeader(As2Headers.MdnConfirmed).Should().BeFalse(); } [Fact] public void Mic_ComparesTheDigestBytes_NotItsSpelling() { // A canonical digest: the unused bits of the last base64 character are zero (.NET 11 refuses others). var sent = new As2Mic("q1w2e3r4t5y6u7i8o9p0aQ==", "sha-256"); sent.Matches(new As2Mic(" q1w2e3r4t5y6\r\n u7i8o9p0aQ== ", "SHA-256")).Should().BeTrue(); sent.Matches(new As2Mic("q1w2e3r4t5y6u7i8o9p0aQ", "sha256")).Should().BeTrue("base64 without padding is the same digest"); sent.Matches(new As2Mic("q1w2e3r4t5y6u7i8o9p0aA==", "sha-256")).Should().BeFalse(); sent.Matches(new As2Mic("q1w2e3r4t5y6u7i8o9p0aQ==", "sha-1")).Should().BeFalse(); } [Fact] public void Mic_WithNonZeroUnusedBits_IsTheSameDigest_OnEveryRuntime() { // "aZ==" and "aQ==" differ only in the 4 unused bits of the last character: .NET 10 decodes both to the same // bytes, .NET 11 refuses "aZ==" in Convert; As2Mic reads them as one digest on both. var sent = new As2Mic("q1w2e3r4t5y6u7i8o9p0aQ==", "sha-256"); sent.Matches(new As2Mic("q1w2e3r4t5y6u7i8o9p0aZ==", "sha-256")).Should().BeTrue(); sent.Matches(new As2Mic("q1w2e3r4t5y6u7i8o9p0aZ", "sha-256")).Should().BeTrue(); } // ── Asynchronous MDN receiver ──────────────────────────────────────────── private sealed record Delivered(string? MessageId, bool MicMatch, string? MicStatus, bool Confirmed, bool SignatureValid); private static async Task<(RouteContext Context, As2Component Component, List Delivered, int Port)> StartMdnReceiver( Action? configure = null) { var port = FreePort(); var context = new RouteContext(); var component = new As2Component(); context.AddComponent(component); context.AddToRegistry("them", Sender(f => { f.MdnMode = As2MdnMode.Async; f.AsyncMdnUrl = $"http://127.0.0.1:{port}/mdn"; configure?.Invoke(f); })); var delivered = new List(); context.AddRoutes(r => r.From(As2Dsl.ReceiveMdn("/mdn").Host("127.0.0.1").Port(port).ConnectionFactory("them")) .Process(e => { lock (delivered) delivered.Add(new Delivered( e.In.GetHeader(As2Headers.MessageId), e.In.GetHeader(As2Headers.MdnMicMatch), e.In.GetHeader(As2Headers.MdnMicStatus), e.In.GetHeader(As2Headers.MdnConfirmed), e.In.GetHeader(As2Headers.SignatureValid))); })); await context.Start(); return (context, component, delivered, port); } private static async Task PostMdn(int port, (string ContentType, string? Cte, byte[] Body) mdn) { using var client = new HttpClient(); var content = new ByteArrayContent(mdn.Body); content.Headers.TryAddWithoutValidation("Content-Type", mdn.ContentType); if (mdn.Cte is not null) content.Headers.TryAddWithoutValidation("Content-Transfer-Encoding", mdn.Cte); var request = new HttpRequestMessage(HttpMethod.Post, $"http://127.0.0.1:{port}/mdn") { Content = content }; request.Headers.TryAddWithoutValidation("AS2-From", "US"); request.Headers.TryAddWithoutValidation("AS2-To", "THEM"); request.Headers.TryAddWithoutValidation("Message-ID", $"<{Guid.NewGuid():N}@kit>"); return await client.SendAsync(request); } private static readonly As2Mic SentMic = new("c2VudC1taWMtZGlnZXN0LWJ5dGVzLTAxMjM0NTY3ODk=", "sha-256"); [Fact] public async Task AsyncMdn_ForAPendingMessage_WithItsMic_IsConfirmed() { var (context, component, delivered, port) = await StartMdnReceiver(); await using var _ = context; component.Correlation.Register("", SentMic); (await PostMdn(port, Mdn("", SentMic))).StatusCode.Should().Be(HttpStatusCode.OK); delivered.Should().ContainSingle().Which.Should().Be(new Delivered("", true, "matched", true, true)); component.Correlation.ExpectedMic("").Should().BeNull("the verdict is in; nothing waits any more"); } [Fact] public async Task AsyncMdn_ForAMessageNobodyWaitsFor_IsNotAMatch() { // After a restart, after the correlation TTL, or on another node: the MIC it should carry is not known. var (context, _, delivered, port) = await StartMdnReceiver(); await using var _ = context; await PostMdn(port, Mdn("", SentMic)); delivered.Should().ContainSingle().Which.Should().Be(new Delivered("", false, "unknown", false, true)); } [Fact] public async Task AsyncMdn_WithoutOriginalMessageId_IsNotAMatch() { var (context, _, delivered, port) = await StartMdnReceiver(); await using var _ = context; await PostMdn(port, Mdn("", SentMic)); delivered.Should().ContainSingle().Which.MicStatus.Should().Be("unknown"); delivered[0].MicMatch.Should().BeFalse(); delivered[0].Confirmed.Should().BeFalse(); } [Fact] public async Task AsyncMdn_WithoutMic_ForAPendingMessage_IsAbsent() { var (context, component, delivered, port) = await StartMdnReceiver(); await using var _ = context; component.Correlation.Register("", SentMic); await PostMdn(port, Mdn("", mic: null)); delivered.Should().ContainSingle().Which.Should().Be(new Delivered("", false, "absent", false, true)); } [Fact] public async Task AsyncMdn_Unsigned_WhereASignedOneIsAgreed_IsNotAConfirmation() { var (context, component, delivered, port) = await StartMdnReceiver(); await using var _ = context; component.Correlation.Register("", SentMic); await PostMdn(port, Mdn("", SentMic, signed: false)); delivered.Should().ContainSingle().Which.Should().Be(new Delivered("", true, "matched", false, false)); component.Correlation.ExpectedMic("").Should().Be(SentMic, "an unsigned receipt may be anyone's: the partner's own one must still find the message waiting"); } [Fact] public async Task AsyncMdn_Unsigned_WhereAValidOneIsRequired_IsRefused_AndTheMessageStillWaits() { var (context, component, delivered, port) = await StartMdnReceiver(f => f.RequireValidMdn = true); await using var _ = context; component.Correlation.Register("", SentMic); var forged = await PostMdn(port, Mdn("", SentMic, signed: false)); forged.StatusCode.Should().Be(HttpStatusCode.BadRequest); delivered.Should().BeEmpty("a receipt the agreement does not accept is not delivered as one"); ((redb.Route.Abstractions.IEndpointStatistics)context.GetEndpoint(As2Dsl.ReceiveMdn("/mdn").Host("127.0.0.1").Port(port).ConnectionFactory("them"))) .LastErrorMessage.Should().Contain("", "the dashboard shows which receipt was refused"); // The partner's genuine receipt still confirms the transfer. (await PostMdn(port, Mdn("", SentMic))).StatusCode.Should().Be(HttpStatusCode.OK); delivered.Should().ContainSingle().Which.Confirmed.Should().BeTrue(); } [Fact] public async Task AsyncMdn_Negative_FromThePartner_IsDelivered_Unconfirmed_EvenWhenAValidOneIsRequired() { // A negative receipt is the partner's word that the transfer failed: the route must see it. var (context, component, delivered, port) = await StartMdnReceiver(f => f.RequireValidMdn = true); await using var _ = context; component.Correlation.Register("", SentMic); (await PostMdn(port, Mdn("", SentMic, failure: As2Disposition.DecryptionFailed))).StatusCode.Should().Be(HttpStatusCode.OK); delivered.Should().ContainSingle().Which.Confirmed.Should().BeFalse(); } } /// /// A partner may post the asynchronous MDN before it answers the message's own POST (OpenAS2 does, often): the wait /// must exist before the message is sent, or the receipt of a message we did send reads as one nobody waits for. /// public class As2AsyncMdnOrderTests { [Fact] public async Task AsyncMdn_PostedBeforeThePartnerAnswers_IsStillCorrelated() { var partnerPort = FreePort(); var mdnPort = FreePort(); using var partner = new HttpListener(); partner.Prefixes.Add($"http://127.0.0.1:{partnerPort}/"); partner.Start(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("them", Sender(f => { f.MdnMode = As2MdnMode.Async; f.AsyncMdnUrl = $"http://127.0.0.1:{mdnPort}/mdn"; })); var statuses = new System.Collections.Concurrent.ConcurrentQueue(); context.AddRoutes(r => r.From(As2Dsl.ReceiveMdn("/mdn").Host("127.0.0.1").Port(mdnPort).ConnectionFactory("them")) .Process(e => statuses.Enqueue(e.In.GetHeader(As2Headers.MdnMicStatus)))); await context.Start(); var serving = Task.Run(async () => { var ctx = await partner.GetContextAsync(); var id = ctx.Request.Headers["Message-ID"]!; await ctx.Request.InputStream.CopyToAsync(Stream.Null); // The receipt first (without a MIC, so a correlated one reads "absent" and an orphan "unknown"), then the 200. var (ct, cte, body) = MdnBuilder.Build(id, "US", "THEM", null, signer: new As2CryptoEngine(), signerCert: Cert); using var client = new HttpClient(); var content = new ByteArrayContent(body); content.Headers.TryAddWithoutValidation("Content-Type", ct); if (cte is not null) content.Headers.TryAddWithoutValidation("Content-Transfer-Encoding", cte); (await client.PostAsync($"http://127.0.0.1:{mdnPort}/mdn", content)).EnsureSuccessStatusCode(); ctx.Response.StatusCode = 200; ctx.Response.Close(); }); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{partnerPort}/as2").ConnectionFactory("them")).CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("PO*EARLY~") { ContentType = "application/edi-x12" })); await serving.WaitAsync(TimeSpan.FromSeconds(10)); statuses.Should().ContainSingle().Which.Should().Be("absent", "the message was sent and waited for: its MIC was compared, and is missing"); } [Fact] public async Task FailedSend_LeavesNothingWaiting() { var mdnPort = FreePort(); await using var context = new RouteContext(); var component = new As2Component(); context.AddComponent(component); context.AddToRegistry("them", Sender(f => { f.MdnMode = As2MdnMode.Async; f.AsyncMdnUrl = $"http://127.0.0.1:{mdnPort}/mdn"; })); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{FreePort()}/as2").ConnectionFactory("them")).CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("PO*NOWHERE~") { ContentType = "application/edi-x12" }); var act = () => producer.Process(exchange); await act.Should().ThrowAsync(); component.Correlation.ExpectedMic(exchange.In.GetHeader(As2Headers.MessageId)!).Should().BeNull( "a message that was not delivered is not waiting for a receipt"); } } Path: redb-route/tests/redb.Route.Tests.As2/As2MicInteropTests.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.As2/As2MicInteropTests.cs ---- using System.Text; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.As2; using redb.Route.Core; using As2Dsl = redb.Route.As2.Fluent.As2; namespace redb.Route.Tests.As2; /// /// The Received-Content-MIC of the unsigned and the sign-then-compress profiles against OpenAS2 (profile as2 of /// docker-compose.tests.yml, partnerships redb-enc, redb-zip, redb-zipenc and /// redb-signzip). Both directions: OpenAS2 confirms the MIC redb sent (our producer sees matched), and /// OpenAS2 closes the message it sent once the MIC in our MDN is its own (a mismatch makes it resend). OpenAS2 4.9.0 /// hashes an encrypted unsigned message over the (uncompressed) part with its MIME headers and a compressed unencrypted /// one over the content alone. /// [Trait("Category", "Interop")] public class As2MicInteropTests { [As2InteropTheory] [InlineData("redb-enc", true, false)] [InlineData("redb-zip", false, true)] [InlineData("redb-zipenc", true, true)] public async Task Redb_To_OpenAs2_UnsignedProfile_TheMicIsConfirmed(string ourId, bool encrypt, bool compress) { var ourCert = As2InteropTests.LoadPkcs12(Path.Combine(As2InteropTests.CertsDir, "redb.p12"), "testpass"); var partnerCert = As2InteropTests.LoadCertificate(Path.Combine(As2InteropTests.CertsDir, "openas2.crt")); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("openas2", new As2ConnectionFactory { OurCertificate = ourCert, PartnerCertificate = partnerCert, As2From = ourId, As2To = "openas2", Sign = false, Encrypt = encrypt, Compress = compress, EncryptAlg = "aes-128-cbc", SignedMdn = true, RequireValidMdn = true, MdnMode = As2MdnMode.Sync, }); await context.Start(); var producer = context.GetEndpoint(As2Dsl.Send("http://127.0.0.1:14080/").ConnectionFactory("openas2")).CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message($"ISA*00*REDB*MIC*{ourId}*{Guid.NewGuid():N}~") { ContentType = "application/edi-x12" }); await producer.Process(exchange); exchange.Out!.GetHeader(As2Headers.MdnMicStatus).Should().Be("matched", "OpenAS2 computed the MIC redb sent"); exchange.Out!.GetHeader(As2Headers.MdnConfirmed).Should().BeTrue(); } [As2InteropTheory] [InlineData("redb-enc", 15083, false, true, false)] [InlineData("redb-zip", 15084, false, false, true)] [InlineData("redb-zipenc", 15085, false, true, true)] [InlineData("redb-signzip", 15086, true, true, true)] public async Task OpenAs2_To_Redb_Profile_IsReceived_AndOpenAs2MatchesOurMic(string ourId, int port, bool sign, bool encrypt, bool compress) { var ourCert = As2InteropTests.LoadPkcs12(Path.Combine(As2InteropTests.CertsDir, "redb.p12"), "testpass"); var partnerCert = As2InteropTests.LoadCertificate(Path.Combine(As2InteropTests.CertsDir, "openas2.crt")); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry(ourId, new As2ConnectionFactory { OurCertificate = ourCert, PartnerCertificate = partnerCert, As2From = ourId, As2To = "openas2", Sign = sign, Encrypt = encrypt, Compress = compress, SignedMdn = true, MdnMode = As2MdnMode.Sync, }); var received = new List<(string Body, bool SignatureValid)>(); context.AddRoutes(r => r.From(As2Dsl.Receive("/inbound").Host("0.0.0.0").Port(port).ConnectionFactory(ourId)) .Process(e => { lock (received) received.Add((Encoding.UTF8.GetString((byte[])e.In.Body!), e.In.GetHeader(As2Headers.SignatureValid))); })); await context.Start(); // Dropped into OpenAS2's outbox for this partner (tests/docker/gen-certs.sh creates it writable); the poller // sends it with the partnership's profile and keeps the message pending until our MDN is accepted. var data = Path.Combine(Path.GetDirectoryName(As2InteropTests.CertsDir.TrimEnd('\\', '/'))!, "data"); var name = $"mic-{Guid.NewGuid():N}"; var payload = $"ISA*00*OPENAS2*MIC*{ourId}*{name}~"; await File.WriteAllTextAsync(Path.Combine(data, "outbox", ourId, name + ".edi"), payload); var deadline = DateTime.UtcNow.AddSeconds(45); while (Arrived() is null && DateTime.UtcNow < deadline) await Task.Delay(250); var arrived = Arrived(); arrived.Should().NotBeNull("OpenAS2 delivers the dropped file to our receiver"); if (sign) arrived!.Value.SignatureValid.Should().BeTrue("the signature over the part that was then compressed verifies"); // A MIC in our MDN other than OpenAS2's own makes it keep the message for a resend: it is closed only when they // are the same. while (Mentioned("pendinginfoMDN3") && DateTime.UtcNow < deadline) await Task.Delay(250); Mentioned("pendinginfoMDN3").Should().BeFalse("OpenAS2 accepted our MDN and closed the message"); await Task.Delay(TimeSpan.FromSeconds(2)); Mentioned("resend").Should().BeFalse("a MIC mismatch would have queued the message for a resend"); lock (received) received.Count(m => m.Body == payload).Should().Be(1); (string Body, bool SignatureValid)? Arrived() { lock (received) return received.Where(m => m.Body == payload).Select(m => ((string, bool)?)m).FirstOrDefault(); } bool Mentioned(string folder) { var dir = Path.Combine(data, folder); if (!Directory.Exists(dir)) return false; foreach (var file in Directory.EnumerateFiles(dir, "*", SearchOption.AllDirectories)) { if (file.Contains(name, StringComparison.Ordinal)) return true; try { if (Encoding.Latin1.GetString(File.ReadAllBytes(file)).Contains(name, StringComparison.Ordinal)) return true; } catch (IOException) { } catch (UnauthorizedAccessException) { } } return false; } } } Path: redb-route/tests/redb.Route.Tests.As2/As2MicRulesTests.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.As2/As2MicRulesTests.cs ---- using System.Security.Cryptography; using System.Text; using AwesomeAssertions; using MimeKit; using MimeKit.Cryptography; using redb.Route.Abstractions; using redb.Route.As2; using redb.Route.As2.Crypto; using redb.Route.As2.Mdn; using redb.Route.Core; using As2Dsl = redb.Route.As2.Fluent.As2; using static redb.Route.Tests.As2.As2TestKit; namespace redb.Route.Tests.As2; /// /// The Received-Content-MIC of each profile (RFC 4130 §7.3.1, RFC 5402 §4): signed, over the data that was signed; /// unsigned and encrypted (compressed or not), over the uncompressed part with its MIME headers; unsigned and not /// encrypted (compressed or plain), over the content alone. And a message signed before it was compressed (RFC 5402 /// §3.3/3.6) is verified like one compressed first. /// public class As2MicRulesTests { private const string Payload = "ISA*00*MIC*RULES~"; private static async Task<(RouteContext Context, List<(string Body, bool SignatureValid)> Delivered, int Port)> StartReceiver( Action configure) { var port = FreePort(); var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver(configure)); var delivered = new List<(string, bool)>(); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv")) .Process(e => { lock (delivered) delivered.Add((Encoding.UTF8.GetString((byte[])e.In.Body!), e.In.GetHeader(As2Headers.SignatureValid))); })); await context.Start(); return (context, delivered, port); } private static MdnParser.MdnResult ReadMdn(HttpResponseMessage response) => MdnParser.Parse( response.Content.Headers.ContentType?.ToString(), response.Content.Headers.TryGetValues("Content-Transfer-Encoding", out var v) ? string.Join(",", v) : null, response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(), new As2CryptoEngine(), Cert); /// The top-level entity of a built message, as the receiver parses it. private static MimeEntity Parse((string ContentType, string? TransferEncoding, byte[] Body) message) { var head = $"Content-Type: {message.ContentType}\r\n" + (message.TransferEncoding is null ? "" : $"Content-Transfer-Encoding: {message.TransferEncoding}\r\n") + "\r\n"; var stream = new MemoryStream(); stream.Write(Encoding.ASCII.GetBytes(head)); stream.Write(message.Body); stream.Position = 0; return MimeEntity.Load(stream); } /// SHA-256 over a MIME part's headers and content as written, with CRLF line ends. private static string HeadersAndContent(MimeEntity part) { var options = FormatOptions.Default.Clone(); options.NewLineFormat = NewLineFormat.Dos; using var ms = new MemoryStream(); part.WriteTo(options, ms); return Convert.ToBase64String(SHA256.HashData(ms.ToArray())); } [Fact] public async Task EncryptedUnsigned_TheMicIsOverTheDecryptedPart_WithItsHeaders() { var (context, delivered, port) = await StartReceiver(f => f.Sign = false); await using var _ = context; var message = BuildMessage(Payload, signer: null, recipient: Cert); var mdn = ReadMdn(await PostAsync(port, "/in", message)); delivered.Should().ContainSingle().Which.Body.Should().Be(Payload); using var ctx = new TemporarySecureMimeContext(); ctx.Import(Cert); var decrypted = ((ApplicationPkcs7Mime)Parse(message)).Decrypt(ctx); mdn.ReceivedMic!.Value.Digest.Should().Be(HeadersAndContent(decrypted)); mdn.ReceivedMic!.Value.Digest.Should().NotBe(Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(Payload))), "an encrypted message is not hashed over its content alone"); } [Fact] public async Task CompressedEncryptedUnsigned_TheMicIsOverTheDecompressedPart_WithItsHeaders() { var (context, delivered, port) = await StartReceiver(f => f.Sign = false); await using var _ = context; var message = BuildMessage(Payload, signer: null, recipient: Cert, compress: true); var mdn = ReadMdn(await PostAsync(port, "/in", message)); delivered.Should().ContainSingle().Which.Body.Should().Be(Payload); using var ctx = new TemporarySecureMimeContext(); ctx.Import(Cert); var decrypted = ((ApplicationPkcs7Mime)Parse(message)).Decrypt(ctx); var decompressed = ((ApplicationPkcs7Mime)decrypted).Decompress(ctx); mdn.ReceivedMic!.Value.Digest.Should().Be(HeadersAndContent(decompressed)); } [Fact] public async Task CompressedUnsigned_TheMicIsOverTheContentAlone() { var (context, delivered, port) = await StartReceiver(f => { f.Sign = false; f.Encrypt = false; }); await using var _ = context; var message = BuildMessage(Payload, signer: null, recipient: null, compress: true); var mdn = ReadMdn(await PostAsync(port, "/in", message)); delivered.Should().ContainSingle().Which.Body.Should().Be(Payload); // Not encrypted: RFC 4130 §7.3.1, and what OpenAS2 4.9.0 computes (RFC 5402 §4.3 would add the headers). mdn.ReceivedMic!.Value.Digest.Should().Be(Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(Payload)))); } [Fact] public async Task Plain_TheMicIsOverTheContentAlone() { var (context, delivered, port) = await StartReceiver(f => { f.Sign = false; f.Encrypt = false; }); await using var _ = context; var mdn = ReadMdn(await PostAsync(port, "/in", BuildMessage(Payload, signer: null, recipient: null))); delivered.Should().ContainSingle(); mdn.ReceivedMic!.Value.Digest.Should().Be(Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(Payload)))); } [Theory] [InlineData(true)] [InlineData(false)] public async Task SignedThenCompressed_IsVerified_AndItsMicIsOverTheSignedPayload(bool encrypt) { var (context, delivered, port) = await StartReceiver(f => f.Encrypt = encrypt); await using var _ = context; var response = await PostAsync(port, "/in", BuildMessage(Payload, signer: Cert, recipient: encrypt ? Cert : null, compress: true, compressAfterSign: true)); var routed = delivered.Should().ContainSingle().Subject; routed.Body.Should().Be(Payload, "the payload, not the multipart/signed around it"); routed.SignatureValid.Should().BeTrue(); var mdn = ReadMdn(response); mdn.IsPositive.Should().BeTrue(); // What was signed is the payload part itself, prepared for signing as the sender prepared it. var signedPart = new MimePart("application", "edi-x12") { Content = new MimeContent(new MemoryStream(Encoding.UTF8.GetBytes(Payload))), ContentTransferEncoding = ContentEncoding.Binary, }; mdn.ReceivedMic!.Value.Digest.Should().Be(new As2CryptoEngine().ComputeMic(signedPart, "sha-256", includeHeaders: true).Digest); } [Theory] [InlineData(true, false)] [InlineData(false, true)] [InlineData(true, true)] public async Task UnsignedProfiles_SentByRedb_AreConfirmedByRedb(bool encrypt, bool compress) { var (context, delivered, port) = await StartReceiver(f => { f.Sign = false; f.Encrypt = encrypt; }); await using var _ = context; context.AddToRegistry("send", Sender(f => { f.Sign = false; f.Encrypt = encrypt; f.Compress = compress; })); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/in").ConnectionFactory("send")).CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message(Payload) { ContentType = "application/edi-x12" }); await producer.Process(exchange); delivered.Should().ContainSingle().Which.Body.Should().Be(Payload); exchange.Out!.GetHeader(As2Headers.MdnMicStatus).Should().Be("matched"); exchange.Out!.GetHeader(As2Headers.MdnConfirmed).Should().BeTrue(); } } Path: redb-route/tests/redb.Route.Tests.As2/As2ProducerTests.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.As2/As2ProducerTests.cs ---- using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using AwesomeAssertions; using MimeKit; using MimeKit.Cryptography; using redb.Route.Abstractions; using redb.Route.As2; using redb.Route.As2.Crypto; using redb.Route.Core; using As2Dsl = redb.Route.As2.Fluent.As2; namespace redb.Route.Tests.As2; /// /// Producer tests: the AS2 send side POSTs a well-formed, signed+encrypted S/MIME message with the /// required AS2 headers. A loopback captures the request; the body is /// reconstructed and run back through the crypto engine (decrypt → verify → extract) to prove it is a /// valid AS2 message on the wire. Interop against real AS2 servers is in As2InteropTests. /// public class As2ProducerTests { private static readonly X509Certificate2 OurCert = MakeCert("as2-us"); private static readonly X509Certificate2 PartnerCert = MakeCert("as2-partner"); [Fact] public async Task Send_PostsSignedEncrypted_WithAs2Headers_AndValidBody() { var port = FreePort(); using var listener = new HttpListener(); listener.Prefixes.Add($"http://127.0.0.1:{port}/"); listener.Start(); var headers = new Dictionary(StringComparer.OrdinalIgnoreCase); string? contentType = null; byte[] bodyBytes = []; var capture = Task.Run(async () => { var ctx = await listener.GetContextAsync(); foreach (string key in ctx.Request.Headers) headers[key] = ctx.Request.Headers[key]!; contentType = ctx.Request.ContentType; using var ms = new MemoryStream(); await ctx.Request.InputStream.CopyToAsync(ms); bodyBytes = ms.ToArray(); ctx.Response.StatusCode = 200; ctx.Response.Close(); }); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("partner", new As2ConnectionFactory { OurCertificate = OurCert, PartnerCertificate = PartnerCert, As2From = "US", As2To = "THEM", Sign = true, Encrypt = true, SignedMdn = true, MdnMode = As2MdnMode.Sync, }); var endpoint = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/as2").ConnectionFactory("partner")); var producer = endpoint.CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("ISA*00*...EDI~") { ContentType = "application/edi-x12" }); await producer.Process(exchange); await capture.WaitAsync(TimeSpan.FromSeconds(5)); // AS2 headers present and correct. headers.Should().ContainKey("AS2-Version").WhoseValue.Should().Be("1.2"); headers.Should().ContainKey("AS2-From").WhoseValue.Should().Be("US"); headers.Should().ContainKey("AS2-To").WhoseValue.Should().Be("THEM"); headers.Should().ContainKey("Message-ID"); headers.Should().ContainKey("Disposition-Notification-To"); // sync MDN requested contentType.Should().Contain("application/pkcs7-mime"); // encrypted (enveloped-data) // The producer recorded the outgoing Message-ID + MIC for later MDN correlation. exchange.In.Headers.Should().ContainKey(As2Headers.Mic); exchange.In.GetHeader(As2Headers.MessageId).Should().StartWith("<"); // Reconstruct the MIME message from the captured MIME headers + body, then decrypt + verify. var engine = new As2CryptoEngine(); var entity = LoadEntity(headers, bodyBytes); var decrypted = engine.Decrypt(entity, PartnerCert); decrypted.Should().BeAssignableTo(); engine.Verify((MultipartSigned)decrypted, OurCert).Should().BeTrue(); var payload = (MimePart)((MultipartSigned)decrypted)[0]; using var decoded = new MemoryStream(); payload.Content.DecodeTo(decoded); Encoding.UTF8.GetString(decoded.ToArray()).Should().Be("ISA*00*...EDI~"); } // ── Helpers ────────────────────────────────────────────────────────────── private static MimeEntity LoadEntity(Dictionary headers, byte[] body) { // Rebuild the MIME entity from the top-level MIME headers the producer promoted to HTTP headers. var sb = new StringBuilder(); sb.Append("Content-Type: ").Append(headers["Content-Type"]).Append("\r\n"); if (headers.TryGetValue("Content-Transfer-Encoding", out var cte)) sb.Append("Content-Transfer-Encoding: ").Append(cte).Append("\r\n"); if (headers.TryGetValue("Content-Disposition", out var cd)) sb.Append("Content-Disposition: ").Append(cd).Append("\r\n"); sb.Append("\r\n"); using var stream = new MemoryStream(); stream.Write(Encoding.ASCII.GetBytes(sb.ToString())); stream.Write(body); stream.Position = 0; return MimeEntity.Load(stream); } [Fact] public void ProducerName_MasksUserInfoPassword() { // Same invariant as HttpProducer: the name is logged as "producer started"; a userinfo // password lives in the authority, where no [Sensitive] attribute can reach it, so the // name must go through EndpointUri.Sanitize. var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("partner", new As2ConnectionFactory { As2From = "US", As2To = "THEM", Sign = false, Encrypt = false, }); var endpoint = context.GetEndpoint( As2Dsl.Send("http://edi:s3cr3t@partner.example/as2").ConnectionFactory("partner")); var producer = endpoint.CreateProducer(); var name = (string?)typeof(ConnectableProducer) .GetProperty("ProducerName", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)! .GetValue(producer); name.Should().NotContain("s3cr3t", "the userinfo password must not reach the started/stopped logs"); } [Fact] public async Task Send_DoesNotBridgeTheHostHeader() { // From(http) -> To(as2) used to be an accidental preserve-host proxy: the inbound Host // rode the header bridge onto the outgoing POST. The partner must see its own host. var port = FreePort(); using var listener = new HttpListener(); listener.Prefixes.Add($"http://127.0.0.1:{port}/"); listener.Start(); string? seenHost = null; var capture = Task.Run(async () => { var ctx = await listener.GetContextAsync(); seenHost = ctx.Request.Headers["Host"]; ctx.Response.StatusCode = 200; ctx.Response.Close(); }); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("partner", new As2ConnectionFactory { As2From = "US", As2To = "THEM", Sign = false, Encrypt = false, MdnMode = As2MdnMode.None, }); var endpoint = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/as2").ConnectionFactory("partner")); var producer = endpoint.CreateProducer(); await producer.Start(); var msg = new Message("ISA*00*...EDI~") { ContentType = "application/edi-x12" }; msg.Headers["Host"] = "upstream.example.com"; await producer.Process(new Exchange(msg)); await capture.WaitAsync(TimeSpan.FromSeconds(5)); await producer.Stop(); seenHost.Should().Be($"127.0.0.1:{port}", "Host is a hop-by-hop header of the HTTP transport, not a payload of the AS2 bridge"); } private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); private static X509Certificate2 MakeCert(string cn) { var rsa = RSA.Create(2048); var req = new CertificateRequest($"CN={cn}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); using var certWithKey = req.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(10)); using var publicOnly = X509CertificateLoader.LoadCertificate(certWithKey.Export(X509ContentType.Cert)); return publicOnly.CopyWithPrivateKey(rsa); } } Path: redb-route/tests/redb.Route.Tests.As2/As2ProtocolTests.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.As2/As2ProtocolTests.cs ---- using System.Net; using System.Text; using AwesomeAssertions; using MimeKit; using MimeKit.Cryptography; using redb.Route.As2; using redb.Route.As2.Crypto; using redb.Route.As2.Mdn; using redb.Route.Core; using As2Dsl = redb.Route.As2.Fluent.As2; using static redb.Route.Tests.As2.As2TestKit; namespace redb.Route.Tests.As2; /// /// The MDN a receiver returns is the one the request asked for (RFC 4130 §7.3), credentials of /// the transport hop do not travel with the document, and a disposition is read by its fields. /// public class As2ProtocolTests { private static async Task<(RouteContext Context, System.Collections.Concurrent.ConcurrentQueue> Routed, int Port)> StartReceiver( Action? configure = null) { var port = FreePort(); var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver(configure)); var routed = new System.Collections.Concurrent.ConcurrentQueue>(); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv")) .Process(e => routed.Enqueue(new Dictionary(e.In.Headers, StringComparer.OrdinalIgnoreCase)))); await context.Start(); return (context, routed, port); } private static MimeEntity Entity(HttpResponseMessage response) { var sb = new StringBuilder(); sb.Append("Content-Type: ").Append(response.Content.Headers.ContentType).Append("\r\n"); if (response.Content.Headers.TryGetValues("Content-Transfer-Encoding", out var cte)) sb.Append("Content-Transfer-Encoding: ").Append(string.Join(",", cte)).Append("\r\n"); sb.Append("\r\n"); var stream = new MemoryStream(); stream.Write(Encoding.ASCII.GetBytes(sb.ToString())); stream.Write(response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult()); stream.Position = 0; return MimeEntity.Load(stream); } // ── the MDN the request asked for ──────────────────────────────────────── [Fact] public async Task Message_ThatAsksForNoMdn_IsAnsweredWithoutOne() { var (context, routed, port) = await StartReceiver(); await using var _ = context; var response = await PostAsync(port, "/in", BuildMessage("PO*NOMDN~", Cert, Cert), new Dictionary { ["Disposition-Notification-To"] = null, ["Disposition-Notification-Options"] = null }); response.StatusCode.Should().Be(HttpStatusCode.OK); (await response.Content.ReadAsByteArrayAsync()).Should().BeEmpty("RFC 4130 §7.3: no Disposition-Notification-To, no MDN"); routed.Should().ContainSingle(); } [Fact] public async Task Mdn_IsSigned_OnlyWhenTheRequestAsksForASignedReceipt() { var (context, _, port) = await StartReceiver(); await using var _ = context; var unsigned = await PostAsync(port, "/in", BuildMessage("PO*PLAINMDN~", Cert, Cert), new Dictionary { ["Disposition-Notification-Options"] = null }); var signed = await PostAsync(port, "/in", BuildMessage("PO*SIGNEDMDN~", Cert, Cert)); unsigned.Content.Headers.ContentType!.MediaType.Should().Be("multipart/report"); signed.Content.Headers.ContentType!.MediaType.Should().Be("multipart/signed"); } [Fact] public async Task Mdn_UsesTheRequestedMicAlgorithm_ForTheMicAndItsSignature() { var (context, _, port) = await StartReceiver(); await using var _ = context; var response = await PostAsync(port, "/in", BuildMessage("PO*384~", Cert, Cert, "sha-384"), new Dictionary { ["Disposition-Notification-Options"] = "signed-receipt-protocol=required, pkcs7-signature; signed-receipt-micalg=required, sha-384, sha-256", }); var signed = Entity(response).Should().BeOfType().Subject; signed.ContentType.Parameters["micalg"].Should().Be("sha-384"); var mdn = MdnParser.Parse(response.Content.Headers.ContentType!.ToString(), response.Content.Headers.TryGetValues("Content-Transfer-Encoding", out var v) ? string.Join(",", v) : null, await response.Content.ReadAsByteArrayAsync(), new As2CryptoEngine(), Cert); mdn.ReceivedMic!.Value.Algorithm.Should().Be("sha-384"); mdn.SignatureValid.Should().BeTrue(); } private static MdnParser.MdnResult ParseMdn(HttpResponseMessage response) => MdnParser.Parse( response.Content.Headers.ContentType!.ToString(), response.Content.Headers.TryGetValues("Content-Transfer-Encoding", out var v) ? string.Join(",", v) : null, response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(), new As2CryptoEngine(), Cert); [Theory] [InlineData("signed-receipt-protocol=required, pkcs7-signature; signed-receipt-micalg=required, sha-0, gost", "unsupported MIC-algorithms")] [InlineData("signed-receipt-protocol=required, pgp-signature; signed-receipt-micalg=optional, sha-256", "unsupported format")] public async Task Message_RequiringAReceiptOptionThisReceiverLacks_GetsAFailedMdn_AndIsNotProcessed(string options, string failure) { // RFC 4130 §7.5.3: a required option that cannot be honoured is answered failed/Failure, the content not processed. var (context, routed, port) = await StartReceiver(); await using var _ = context; var response = await PostAsync(port, "/in", BuildMessage("PO*REQUIRED~", Cert, Cert), new Dictionary { ["Disposition-Notification-Options"] = options }); routed.Should().BeEmpty(); response.Content.Headers.ContentType!.MediaType.Should().Be("multipart/report", "no receipt as asked can be made, so it is not signed"); var mdn = ParseMdn(response); mdn.Disposition.Should().Be($"automatic-action/MDN-sent-automatically; failed/Failure: {failure}"); mdn.IsPositive.Should().BeFalse(); mdn.ReceivedMic.Should().BeNull(); } [Fact] public async Task Message_WithAnOptionalMicAlgorithmThisReceiverLacks_IsProcessed_WithTheAgreementsAlgorithm() { var (context, routed, port) = await StartReceiver(); await using var _ = context; var response = await PostAsync(port, "/in", BuildMessage("PO*OPTIONAL~", Cert, Cert), new Dictionary { ["Disposition-Notification-Options"] = "signed-receipt-protocol=optional, pkcs7-signature; signed-receipt-micalg=optional, sha-0", }); routed.Should().ContainSingle(); var mdn = ParseMdn(response); mdn.IsPositive.Should().BeTrue(); mdn.SignatureValid.Should().BeTrue(); mdn.ReceivedMic!.Value.Algorithm.Should().Be("sha-256"); } [Theory] [InlineData("required", false)] [InlineData("optional", true)] public async Task SignedReceipt_WithoutACertificateOfOurs_FailsWhenRequired_AndGoesUnsignedWhenOptional(string importance, bool processed) { // An agreement without signing, encryption or signed MDNs needs no certificate of ours; a signed receipt then // cannot be made. Required: failed/Failure: unsupported format (RFC 4130 §7.5.3). Optional: processed, unsigned. var (context, routed, port) = await StartReceiver(f => { f.OurCertificate = null; f.PartnerCertificate = null; f.Sign = false; f.Encrypt = false; f.SignedMdn = false; }); await using var _ = context; var response = await PostAsync(port, "/in", BuildMessage("PO*NOCERT~", null, null), new Dictionary { ["Disposition-Notification-Options"] = $"signed-receipt-protocol={importance}, pkcs7-signature; signed-receipt-micalg={importance}, sha-256", }); routed.Should().HaveCount(processed ? 1 : 0); response.Content.Headers.ContentType!.MediaType.Should().Be("multipart/report"); var mdn = ParseMdn(response); mdn.Disposition.Should().Be(processed ? "automatic-action/MDN-sent-automatically; processed" : "automatic-action/MDN-sent-automatically; failed/Failure: unsupported format"); } [Fact] public async Task Producer_AsksForASignedReceipt_AsRequired_WhenTheAgreementWantsOne() { using var trap = new As2Trap(FreePort()); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("them", Sender(f => f.MdnMode = As2MdnMode.None)); context.AddToRegistry("them-mdn", Sender(f => f.SignAlg = "sha-384")); var none = context.GetEndpoint(As2Dsl.Send(trap.Url("/as2")).ConnectionFactory("them")).CreateProducer(); var signed = context.GetEndpoint(As2Dsl.Send(trap.Url("/as2b")).ConnectionFactory("them-mdn")).CreateProducer(); await none.Start(); await signed.Start(); await none.Process(new Exchange(new Message("PO*1~"))); try { await signed.Process(new Exchange(new Message("PO*2~"))); } catch (Exception) { /* the trap answers 200 with no MDN; only the request matters here */ } var requests = trap.Requests.ToArray(); requests.Single(r => r.Path == "/as2").Headers.Should().NotContainKey("Disposition-Notification-To"); requests.Single(r => r.Path == "/as2b").Headers["Disposition-Notification-Options"].Should() .Be("signed-receipt-protocol=required, pkcs7-signature; signed-receipt-micalg=required, sha-384"); } // ── the hop's credentials stay with the hop ────────────────────────────── [Fact] public async Task Receiver_DoesNotHandTheHopsCredentialsToTheRoute() { var (context, routed, port) = await StartReceiver(); await using var _ = context; await PostAsync(port, "/in", BuildMessage("PO*CREDS~", Cert, Cert), new Dictionary { ["Authorization"] = "Basic ZWRpOnMzY3IzdA==", ["Proxy-Authorization"] = "Basic cHJveHk6cHc=", ["Cookie"] = "session=abc", ["X-Business"] = "kept", }); var headers = routed.Should().ContainSingle().Subject; headers.Should().NotContainKeys("Authorization", "Proxy-Authorization", "Cookie"); headers["X-Business"].Should().Be("kept"); } [Fact] public async Task Producer_DoesNotBridgeCredentials() { using var trap = new As2Trap(FreePort()); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("them", Sender(f => f.MdnMode = As2MdnMode.None)); var producer = context.GetEndpoint(As2Dsl.Send(trap.Url("/as2")).ConnectionFactory("them")).CreateProducer(); await producer.Start(); var message = new Message("PO*BRIDGE~"); message.Headers["Authorization"] = "Bearer internal-token"; message.Headers["Cookie"] = "session=abc"; message.Headers["Set-Cookie"] = "a=b"; message.Headers["X-Business"] = "kept"; await producer.Process(new Exchange(message)); (await trap.HitAsync(TimeSpan.FromSeconds(5))).Should().BeTrue(); trap.Requests.TryPeek(out var hit); hit.Headers.Should().NotContainKeys("Authorization", "Cookie", "Set-Cookie"); hit.Headers["X-Business"].Should().Be("kept"); } // ── the disposition by its fields ──────────────────────────────────────── [Theory] [InlineData("automatic-action/MDN-sent-automatically; processed", true)] [InlineData("automatic-action/MDN-sent-automatically; processed/warning: duplicate-document", true)] [InlineData("automatic-action/MDN-sent-automatically; processed/warning: error-free after retry", true)] [InlineData("automatic-action/MDN-sent-automatically; processed/error: decryption-failed", false)] [InlineData("automatic-action/MDN-sent-automatically; processed/Error: authentication-failed", false)] [InlineData("automatic-action/MDN-sent-automatically; failed/Failure: unsupported format", false)] [InlineData("automatic-action/MDN-sent-automatically; processed/failure: sender-equals-receiver", false)] [InlineData("automatic-action/MDN-sent-automatically; denied", false)] [InlineData("processed", false)] public void Disposition_IsPositive_ByItsTypeAndModifier(string disposition, bool positive) { MdnParser.IsPositiveDisposition(disposition).Should().Be(positive); } } /// /// RFC 3798 §3.1: message/disposition-notification is 7bit, "MUST be used". A long Original-Message-ID (OpenAS2's /// are ~90 characters) must not push the machine part into quoted-printable: OpenAS2 reads the field undecoded, cuts the /// id at the soft line break, and never finds the message an asynchronous MDN reports on. /// public class As2MdnEncodingTests { [Theory] [InlineData(true)] [InlineData(false)] public void MachinePart_Stays7bit_AndCarriesALongMessageIdWhole(bool signed) { var id = "<20260928195636+0000-992-openas2_redb-async_async-40c2a6adcca248639558cf38a4c0e4c2abcdef.edi>"; var (_, _, body) = MdnBuilder.Build(id, "redb-async", "openas2", new As2Mic("u2OyNRM8PK2R8YJqYxwovz/9lrGpcFKb+vghhpoABMo=", "sha-256"), signer: signed ? new As2CryptoEngine() : null, signerCert: signed ? As2TestKit.Cert : null); var text = Encoding.ASCII.GetString(body); text.Should().NotContain("quoted-printable"); text.Should().Contain("Original-Message-ID: " + id + "\r\n"); text.Should().Contain("Received-Content-MIC: u2OyNRM8PK2R8YJqYxwovz/9lrGpcFKb+vghhpoABMo=, sha-256\r\n"); } } /// /// RFC 4130 §7.3.1: the receiver's MIC is over the signed part as it was signed (its MIME headers and content, as /// received). OpenAS2 signs a binary part; re-preparing it for 7bit before hashing turned it into base64 and gave /// a MIC OpenAS2 rejects ("MIC not matched", seen on its asynchronous MDN check, which the synchronous path skips). /// public class As2ReceivedMicTests { [Fact] public void Mic_OfAReceivedBinaryPart_IsOverItsBytesAsReceived() { const string part = "Content-Type: application/edi-x12\r\nContent-Transfer-Encoding: binary\r\n\r\nISA*00*BINARY~\r\nLINEé~"; var raw = "Content-Type: multipart/signed; protocol=\"application/pkcs7-signature\"; micalg=sha-256; boundary=\"b\"\r\n\r\n" + "--b\r\n" + part + "\r\n--b\r\nContent-Type: application/pkcs7-signature\r\nContent-Transfer-Encoding: base64\r\n\r\nAAAA\r\n--b--\r\n"; using var stream = new MemoryStream(Encoding.Latin1.GetBytes(raw)); var signed = (MultipartSigned)MimeEntity.Load(stream, persistent: true); var mic = new As2CryptoEngine().ComputeReceivedMic(signed[0], "sha-256"); var expected = Convert.ToBase64String(System.Security.Cryptography.SHA256.HashData(Encoding.Latin1.GetBytes(part))); mic.Should().Be(new As2Mic(expected, "sha-256")); } [Fact] public void Mic_OfAReceivedTextPart_IsOverItsCrlfBytes_OnEveryPlatform() { // A 7bit part is written through MimeKit's line-end filter; with the platform's line ends it would be hashed with // LF on Linux and differ from the sender's MIC, which is over the CRLF bytes on the wire. const string part = "Content-Type: application/edi-x12\r\nContent-Transfer-Encoding: 7bit\r\n\r\nISA*00*TEXT~\r\nGS*IN~\r\n"; var raw = "Content-Type: multipart/signed; protocol=\"application/pkcs7-signature\"; micalg=sha-256; boundary=\"b\"\r\n\r\n" + "--b\r\n" + part + "\r\n--b\r\nContent-Type: application/pkcs7-signature\r\nContent-Transfer-Encoding: base64\r\n\r\nAAAA\r\n--b--\r\n"; using var stream = new MemoryStream(Encoding.ASCII.GetBytes(raw)); var signed = (MultipartSigned)MimeEntity.Load(stream, persistent: true); var mic = new As2CryptoEngine().ComputeReceivedMic(signed[0], "sha-256"); var expected = Convert.ToBase64String(System.Security.Cryptography.SHA256.HashData(Encoding.ASCII.GetBytes(part))); mic.Should().Be(new As2Mic(expected, "sha-256")); } } Path: redb-route/tests/redb.Route.Tests.As2/As2ReceiveSecurityTests.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.As2/As2ReceiveSecurityTests.cs ---- using System.Net; using System.Text; using AwesomeAssertions; using redb.Route.As2; using redb.Route.As2.Crypto; using redb.Route.As2.Mdn; using redb.Route.Core; using As2Dsl = redb.Route.As2.Fluent.As2; using static redb.Route.Tests.As2.As2TestKit; namespace redb.Route.Tests.As2; /// /// What the receiver does for a request it cannot authenticate: the partner is who /// the agreement names, by its AS2 identifiers and its signature; until then its receipt URL is not called and /// its document does not reach the route. /// public class As2ReceiveSecurityTests { private static async Task<(RouteContext Context, List Delivered, int Port)> StartReceiver(As2ConnectionFactory factory) { var port = FreePort(); var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", factory); var delivered = new List(); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv")) .Process(e => { lock (delivered) delivered.Add(Encoding.UTF8.GetString((byte[])e.In.Body!)); })); await context.Start(); return (context, delivered, port); } private static MdnParser.MdnResult ReadMdn(HttpResponseMessage response) { var cte = response.Content.Headers.TryGetValues("Content-Transfer-Encoding", out var v) ? string.Join(",", v) : null; var body = response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(); return MdnParser.Parse(response.Content.Headers.ContentType?.ToString(), cte, body, new As2CryptoEngine(), Cert); } [Fact] public async Task AsyncReceipt_ForAMessageSignedByAStranger_IsNotPosted() { using var trap = new As2Trap(FreePort()); var (context, delivered, port) = await StartReceiver(Receiver(f => { f.MdnMode = As2MdnMode.Async; f.AsyncMdnAllowedHosts = ["127.0.0.1"]; })); await using var _ = context; var response = await PostAsync(port, "/in", BuildMessage("PO*FORGED~", Stranger, Cert), new Dictionary { ["Receipt-Delivery-Option"] = trap.Url() }); (await trap.HitAsync(TimeSpan.FromSeconds(2))).Should().BeFalse( "the sender did not authenticate, so the address it named is not one we post to"); delivered.Should().BeEmpty(); response.StatusCode.Should().Be(HttpStatusCode.OK); var mdn = ReadMdn(response); mdn.IsPositive.Should().BeFalse(); mdn.Disposition.Should().EndWith("processed/error: authentication-failed"); } [Fact] public async Task AsyncReceipt_InASyncPartnership_IsNotPosted_TheReceiptIsInTheResponse() { using var trap = new As2Trap(FreePort()); var (context, delivered, port) = await StartReceiver(Receiver(f => f.AsyncMdnAllowedHosts = ["127.0.0.1"])); await using var _ = context; var response = await PostAsync(port, "/in", BuildMessage("PO*SYNC~", Cert, Cert), new Dictionary { ["Receipt-Delivery-Option"] = trap.Url() }); (await trap.HitAsync(TimeSpan.FromSeconds(2))).Should().BeFalse("the agreement says the receipt is synchronous"); delivered.Should().ContainSingle().Which.Should().Be("PO*SYNC~"); ReadMdn(response).IsPositive.Should().BeTrue(); } [Fact] public async Task AsyncReceipt_ToAHostTheAgreementDoesNotName_IsNotPosted() { using var trap = new As2Trap(FreePort()); var (context, delivered, port) = await StartReceiver(Receiver(f => { f.MdnMode = As2MdnMode.Async; f.AsyncMdnAllowedHosts = ["mdn.partner.example"]; })); await using var _ = context; var response = await PostAsync(port, "/in", BuildMessage("PO*ELSEWHERE~", Cert, Cert), new Dictionary { ["Receipt-Delivery-Option"] = trap.Url() }); (await trap.HitAsync(TimeSpan.FromSeconds(2))).Should().BeFalse("127.0.0.1 is not among asyncMdnAllowedHosts"); delivered.Should().ContainSingle(); response.StatusCode.Should().Be(HttpStatusCode.OK); } [Fact] public async Task AsyncReceipt_OfAnAuthenticatedMessage_ToAnAllowedHost_IsPosted() { using var trap = new As2Trap(FreePort()); var (context, delivered, port) = await StartReceiver(Receiver(f => { f.MdnMode = As2MdnMode.Async; f.AsyncMdnAllowedHosts = ["127.0.0.1"]; })); await using var _ = context; var response = await PostAsync(port, "/in", BuildMessage("PO*ASYNC~", Cert, Cert), new Dictionary { ["Receipt-Delivery-Option"] = trap.Url() }); response.StatusCode.Should().Be(HttpStatusCode.OK); (await trap.HitAsync(TimeSpan.FromSeconds(10))).Should().BeTrue(); delivered.Should().ContainSingle(); trap.Requests.TryPeek(out var hit).Should().BeTrue(); hit.Headers["AS2-From"].Should().Be("US"); hit.Headers["AS2-To"].Should().Be("THEM"); } [Theory] [InlineData("INTRUDER", "US")] [InlineData("THEM", "SOMEONE-ELSE")] [InlineData(null, "US")] [InlineData("THEM", null)] public async Task Message_WhoseAs2IdentifiersAreNotTheAgreements_IsRefused(string? from, string? to) { var (context, delivered, port) = await StartReceiver(Receiver()); await using var _ = context; var response = await PostAsync(port, "/in", BuildMessage("PO*WHO~", Cert, Cert), new Dictionary { ["AS2-From"] = from, ["AS2-To"] = to }); delivered.Should().BeEmpty("a document from, or to, a party the agreement does not name is not ours to process"); var mdn = ReadMdn(response); mdn.IsPositive.Should().BeFalse(); mdn.Disposition.Should().EndWith("processed/error: authentication-failed"); } [Fact] public async Task Message_WithQuotedAs2Identifiers_IsTheAgreements() { // RFC 4130 §6.2: an identifier may be a quoted-string; the quotes are not part of it. var (context, delivered, port) = await StartReceiver(Receiver()); await using var _ = context; var response = await PostAsync(port, "/in", BuildMessage("PO*QUOTED~", Cert, Cert), new Dictionary { ["AS2-From"] = "\"THEM\"", ["AS2-To"] = "\"US\"" }); delivered.Should().ContainSingle(); ReadMdn(response).IsPositive.Should().BeTrue(); } [Theory] [InlineData("КОМПАНИЯ", false)] [InlineData("US\tEAST", false)] [InlineData("café", false)] [InlineData("US EAST", true)] [InlineData("a\"b\\c", true)] public void As2Identifier_IsCheckedWhenTheAgreementIsValidated(string name, bool valid) { // RFC 4130 §6.2: 1 to 128 printable ASCII characters; refused when the endpoint starts, not at send time. var validate = () => Receiver(f => f.As2From = name).Validate("recv"); if (valid) validate.Should().NotThrow(); else validate.Should().Throw().WithMessage("*As2From*not an AS2 identifier*"); } [Theory] [InlineData(128, true)] [InlineData(129, false)] public void As2Identifier_IsAtMost128Characters(int length, bool valid) { var validate = () => Receiver(f => f.As2To = new string('A', length)).Validate("recv"); if (valid) validate.Should().NotThrow(); else validate.Should().Throw().WithMessage("*As2To*not an AS2 identifier*"); } [Theory] [InlineData("US", "US")] [InlineData("0123456780000", "0123456780000")] [InlineData("as2_company!#~", "as2_company!#~")] [InlineData("AS2 Test", "\"AS2 Test\"")] [InlineData("a\"b", "\"a\\\"b\"")] [InlineData("a\\b", "\"a\\\\b\"")] public void As2Name_IsWrittenAtomic_OrQuotedWhenItIsNotAnAtom(string name, string wire) { // RFC 4130 §6.2: the quoted form only when the name is not an AS2-atomic-name. As2Headers.FormatName(name).Should().Be(wire); As2Consumer.IsAgreedIdentifier(wire, name).Should().BeTrue("what we write reads back as the same name"); } [Fact] public async Task Producer_QuotesAnAs2IdentifierThatIsNotAnAtom() { using var trap = new As2Trap(FreePort()); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("them", Sender(f => { f.As2From = "THEM CORP"; f.MdnMode = As2MdnMode.None; })); var producer = context.GetEndpoint(As2Dsl.Send(trap.Url("/as2")).ConnectionFactory("them")).CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("PO*QUOTE~"))); var headers = trap.Requests.Single().Headers; headers["AS2-From"].Should().Be("\"THEM CORP\""); headers["AS2-To"].Should().Be("US"); } [Fact] public async Task Receiver_AnswersWithItsAs2IdentifierQuoted_WhenItIsNotAnAtom() { var (context, delivered, port) = await StartReceiver(Receiver(f => f.As2From = "US EAST")); await using var _ = context; var response = await PostAsync(port, "/in", BuildMessage("PO*QUOTED-US~", Cert, Cert), new Dictionary { ["AS2-To"] = "\"US EAST\"" }); delivered.Should().ContainSingle(); response.Headers.GetValues("AS2-From").Single().Should().Be("\"US EAST\""); response.Headers.GetValues("AS2-To").Single().Should().Be("THEM"); } [Fact] public async Task Message_WithAs2IdentifiersInAnotherCase_IsRefused() { // RFC 4130 §6.2: AS2-From and AS2-To are compared case-sensitively. var (context, delivered, port) = await StartReceiver(Receiver()); await using var _ = context; await PostAsync(port, "/in", BuildMessage("PO*CASE~", Cert, Cert), new Dictionary { ["AS2-From"] = "them" }); delivered.Should().BeEmpty(); } } Path: redb-route/tests/redb.Route.Tests.As2/As2ReceiveTests.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.As2/As2ReceiveTests.cs ---- using System.Diagnostics; using System.Net.Sockets; using System.Net; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using AwesomeAssertions; using MimeKit; using redb.Route.Abstractions; using redb.Route.As2; using redb.Route.As2.Crypto; using redb.Route.Core; using As2Dsl = redb.Route.As2.Fluent.As2; namespace redb.Route.Tests.As2; /// /// End-to-end tests: a real AS2 message travels over real HTTP (shared Kestrel) into the consumer, /// which decrypts + verifies + delivers the payload to a route and returns a synchronous MDN. One test /// drives the full producer→consumer loop; the other asserts the MDN structure. Loopback uses one /// certificate for both sides (distinct certs is the real scenario, validated in As2InteropTests). /// public class As2ReceiveTests { private static readonly X509Certificate2 Cert = As2TestKit.Cert; [Fact] public async Task Loopback_ProducerToConsumer_DeliversPayload() { var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("me", Factory()); context.AddToRegistry("them", As2TestKit.Sender()); var received = new List(); context.AddRoutes(r => r.From(As2Dsl.Receive("/inbound").Host("127.0.0.1").Port(port).ConnectionFactory("me")) .Process(e => received.Add(Encoding.UTF8.GetString((byte[])e.In.Body!)))); await context.Start(); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/inbound").ConnectionFactory("them")).CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("ISA*00*...EDI~") { ContentType = "application/edi-x12" })); // The consumer decrypted + verified + delivered the original business payload to the route. received.Should().ContainSingle().Which.Should().Be("ISA*00*...EDI~"); } [Fact] public async Task Receive_ReturnsSyncMdn_WithDispositionAndMic() { var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("me", Factory()); context.AddToRegistry("them", As2TestKit.Sender()); context.AddRoutes(r => r.From(As2Dsl.Receive("/inbound").Host("127.0.0.1").Port(port).ConnectionFactory("me")).Process(_ => { })); await context.Start(); // Build a signed+encrypted AS2 message with the real engine and POST it directly to capture the MDN. var (contentType, transferEncoding, body) = BuildAs2Message("PO*4200~"); var messageId = ""; using var client = new HttpClient(); using var content = new ByteArrayContent(body); content.Headers.TryAddWithoutValidation("Content-Type", contentType); content.Headers.TryAddWithoutValidation("Content-Transfer-Encoding", transferEncoding); using var request = new HttpRequestMessage(HttpMethod.Post, $"http://127.0.0.1:{port}/inbound") { Content = content }; request.Headers.TryAddWithoutValidation("AS2-From", "THEM"); request.Headers.TryAddWithoutValidation("AS2-To", "US"); request.Headers.TryAddWithoutValidation("Message-ID", messageId); // RFC 4130 §7.3: the sender asks for the receipt, and for it to be signed. request.Headers.TryAddWithoutValidation("Disposition-Notification-To", "them@example.com"); request.Headers.TryAddWithoutValidation("Disposition-Notification-Options", "signed-receipt-protocol=optional, pkcs7-signature; signed-receipt-micalg=optional, sha-256"); var response = await client.SendAsync(request); response.StatusCode.Should().Be(HttpStatusCode.OK); // SignedMdn is on, so the MDN is a multipart/signed wrapping the multipart/report. response.Content.Headers.ContentType!.MediaType.Should().Be("multipart/signed"); // The report is a readable (signed, not encrypted) part inside — its fields are in the body. var mdn = await response.Content.ReadAsStringAsync(); mdn.Should().Contain("processed"); mdn.Should().Contain("Received-Content-MIC"); mdn.Should().Contain(messageId); // Original-Message-ID echoed back } // ── Helpers ────────────────────────────────────────────────────────────── [Fact] public async Task Loopback_ProducerReceivesSignedMdn_SignatureAndMicVerified() { var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("me", Factory()); context.AddToRegistry("them", As2TestKit.Sender()); context.AddRoutes(r => r.From(As2Dsl.Receive("/inbound").Host("127.0.0.1").Port(port).ConnectionFactory("me")).Process(_ => { })); await context.Start(); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/inbound").ConnectionFactory("them")).CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("PO*4200~") { ContentType = "application/edi-x12" }); await producer.Process(exchange); // The producer parsed the signed MDN: signature verified and the returned MIC matched what we sent. exchange.HasOut.Should().BeTrue(); exchange.Out!.GetHeader(As2Headers.MdnDisposition).Should().Contain("processed"); exchange.Out!.GetHeader(As2Headers.SignatureValid).Should().BeTrue(); exchange.Out!.GetHeader(As2Headers.MdnMicMatch).Should().BeTrue(); exchange.Out!.GetHeader(As2Headers.MdnMicStatus).Should().Be("matched"); exchange.Out!.GetHeader(As2Headers.MdnConfirmed).Should().BeTrue(); } [Fact] public async Task AsyncMdn_Loopback_CorrelatesAndDeliversReceipt() { var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("me", As2TestKit.Receiver(f => { f.MdnMode = As2MdnMode.Async; f.AsyncMdnAllowedHosts = ["127.0.0.1"]; })); context.AddToRegistry("them", As2TestKit.Sender(f => { f.MdnMode = As2MdnMode.Async; f.AsyncMdnUrl = $"http://127.0.0.1:{port}/mdn"; })); var received = new List(); var mdns = new List<(string? original, string? disposition, bool micMatch, bool confirmed)>(); context.AddRoutes(r => { r.From(As2Dsl.Receive("/inbound").Host("127.0.0.1").Port(port).ConnectionFactory("me")) .Process(e => received.Add(Encoding.UTF8.GetString((byte[])e.In.Body!))); r.From(As2Dsl.ReceiveMdn("/mdn").Host("127.0.0.1").Port(port).ConnectionFactory("them")) .Process(e => mdns.Add(( e.In.GetHeader(As2Headers.MessageId), e.In.GetHeader(As2Headers.MdnDisposition), e.In.GetHeader(As2Headers.MdnMicMatch), e.In.GetHeader(As2Headers.MdnConfirmed)))); }); await context.Start(); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/inbound").ConnectionFactory("them")).CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message("PO*ASYNC~") { ContentType = "application/edi-x12" }); await producer.Process(exchange); var sentId = exchange.In.GetHeader(As2Headers.MessageId); // The receipt is posted after the partner answered 200, so it arrives a moment after Process returns. var deadline = DateTime.UtcNow.AddSeconds(10); while (mdns.Count == 0 && DateTime.UtcNow < deadline) await Task.Delay(20); // Payload delivered to the business route; the async MDN came back, correlated by Original-Message-ID. received.Should().ContainSingle().Which.Should().Be("PO*ASYNC~"); mdns.Should().ContainSingle(); mdns[0].original.Should().Be(sentId); mdns[0].disposition.Should().Contain("processed"); mdns[0].micMatch.Should().BeTrue(); mdns[0].confirmed.Should().BeTrue(); } [Fact] public async Task Unsigned_Message_Rejected_When_Signature_Required() { var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); // The receiver requires a signature; the sender does not sign. context.AddToRegistry("recv", new As2ConnectionFactory { OurCertificate = Cert, PartnerCertificate = Cert, As2From = "THEM", As2To = "US", Sign = true, Encrypt = false, MdnMode = As2MdnMode.Sync, SignedMdn = false, }); context.AddToRegistry("send", new As2ConnectionFactory { OurCertificate = Cert, PartnerCertificate = Cert, As2From = "US", As2To = "THEM", Sign = false, Encrypt = false, MdnMode = As2MdnMode.Sync, SignedMdn = false, }); var delivered = new List(); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv")) .Process(e => delivered.Add(Encoding.UTF8.GetString((byte[])e.In.Body!)))); await context.Start(); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/in").ConnectionFactory("send")).CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("PO*UNSIGNED~") { ContentType = "application/edi-x12" })); // The unsigned message must NOT reach the business route (rejected with a negative MDN). delivered.Should().BeEmpty(); } [Fact] public async Task Loopback_RecordsConsumerStatistics() { var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("me", Factory()); context.AddToRegistry("them", As2TestKit.Sender()); context.AddRoutes(r => r.From(As2Dsl.Receive("/inbound").Host("127.0.0.1").Port(port).ConnectionFactory("me")).Process(_ => { })); await context.Start(); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/inbound").ConnectionFactory("them")).CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("stats~") { ContentType = "application/edi-x12" })); var stats = (IEndpointStatistics)context.GetEndpoint( As2Dsl.Receive("/inbound").Host("127.0.0.1").Port(port).ConnectionFactory("me")); stats.MessagesIn.Should().BeGreaterThan(0); } [Fact] public async Task Loopback_EmitsLinkedProducerAndConsumerSpans() { var spans = new List(); using var listener = new ActivityListener { ShouldListenTo = s => s.Name == "redb.Route", Sample = (ref ActivityCreationOptions _) => ActivitySamplingResult.AllData, ActivityStopped = a => { lock (spans) spans.Add(a); }, }; ActivitySource.AddActivityListener(listener); var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("me", Factory()); context.AddToRegistry("them", As2TestKit.Sender()); context.AddRoutes(r => r.From(As2Dsl.Receive("/inbound").Host("127.0.0.1").Port(port).ConnectionFactory("me")).Process(_ => { })); await context.Start(); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/inbound").ConnectionFactory("them")).CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("trace~") { ContentType = "application/edi-x12" })); // The receive span ends when the handler returns, just after the response the send has already read. var spanDeadline = DateTime.UtcNow.AddSeconds(5); while (DateTime.UtcNow < spanDeadline) { lock (spans) if (spans.Any(a => a.OperationName == "/inbound receive" && a.Kind == ActivityKind.Consumer && spans.Any(p => p.OperationName == "US send" && p.TraceId == a.TraceId && (p.GetTagItem("messaging.destination.name") as string)?.Contains($":{port}/") == true))) break; await Task.Delay(20); } // The listener is process-wide and other tests run alongside: this test's send is the one to its own port. Activity? producerSpan, consumerSpan; lock (spans) { producerSpan = spans.FirstOrDefault(a => a.OperationName == "US send" && (a.GetTagItem("messaging.destination.name") as string)?.Contains($":{port}/") == true); // Linked: the receive span of this send is in its trace. consumerSpan = producerSpan is null ? null : spans.FirstOrDefault(a => a.OperationName == "/inbound receive" && a.TraceId == producerSpan.TraceId); } producerSpan.Should().NotBeNull(); consumerSpan.Should().NotBeNull(); producerSpan!.Kind.Should().Be(ActivityKind.Client); consumerSpan!.Kind.Should().Be(ActivityKind.Consumer); // Distributed trace: the receive span links to the send span's trace via the injected traceparent. consumerSpan.TraceId.Should().Be(producerSpan.TraceId); } [Fact] public async Task Loopback_HostResolvedCaller_ReachesTheRoute() { var port = FreePort(); await using var manager = new redb.Route.Http.SharedHttpServerManager(new redb.Route.Http.HttpHostingOptions { // Every request is the one partner here: the resolver's own logic is not what this test is about. ResolvePrincipal = _ => Task.FromResult( new System.Security.Claims.ClaimsPrincipal(new System.Security.Claims.ClaimsIdentity( [new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.NameIdentifier, "partner-7")], "test"))), }); await using var context = new RouteContext(); context.AddComponent(new As2Component { ServerManager = manager }); context.AddToRegistry("me", Factory()); context.AddToRegistry("them", As2TestKit.Sender()); var callers = new List(); context.AddRoutes(r => r.From(As2Dsl.Receive("/inbound").Host("127.0.0.1").Port(port).ConnectionFactory("me")) .Process(e => callers.Add( ExchangePrincipal.Get(e)?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value))); await context.Start(); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/inbound").ConnectionFactory("them")).CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("PO*WHO~") { ContentType = "application/edi-x12" })); callers.Should().ContainSingle().Which.Should().Be("partner-7"); } [Fact] public async Task AsyncMdn_HostResolvedCaller_ReachesTheReceiptRoute() { var port = FreePort(); await using var manager = new redb.Route.Http.SharedHttpServerManager(new redb.Route.Http.HttpHostingOptions { // Only the receipt request is identified, so a pass proves the MDN receiver's own line rather // than the message consumer's (that one is Loopback_HostResolvedCaller_ReachesTheRoute). ResolvePrincipal = http => Task.FromResult(http.Request.Path.StartsWithSegments("/mdn") ? new System.Security.Claims.ClaimsPrincipal(new System.Security.Claims.ClaimsIdentity( [new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.NameIdentifier, "mdn-sender")], "test")) : null), }); await using var context = new RouteContext(); context.AddComponent(new As2Component { ServerManager = manager }); context.AddToRegistry("me", As2TestKit.Receiver(f => { f.MdnMode = As2MdnMode.Async; f.AsyncMdnAllowedHosts = ["127.0.0.1"]; })); context.AddToRegistry("them", As2TestKit.Sender(f => { f.MdnMode = As2MdnMode.Async; f.AsyncMdnUrl = $"http://127.0.0.1:{port}/mdn"; })); var messageCallers = new System.Collections.Concurrent.ConcurrentQueue(); var receiptCallers = new System.Collections.Concurrent.ConcurrentQueue(); context.AddRoutes(r => { r.From(As2Dsl.Receive("/inbound").Host("127.0.0.1").Port(port).ConnectionFactory("me")) .Process(e => messageCallers.Enqueue(CallerId(e))); r.From(As2Dsl.ReceiveMdn("/mdn").Host("127.0.0.1").Port(port).ConnectionFactory("them")) .Process(e => receiptCallers.Enqueue(CallerId(e))); }); await context.Start(); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/inbound").ConnectionFactory("them")).CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("PO*RECEIPT~") { ContentType = "application/edi-x12" })); // The receiver completes the producer's wait before it hands the receipt to the route, so the // route may run a moment after Process returns. var deadline = DateTime.UtcNow.AddSeconds(5); while (receiptCallers.IsEmpty && DateTime.UtcNow < deadline) await Task.Delay(20); messageCallers.Should().ContainSingle().Which.Should().BeNull("only the receipt request is identified here"); receiptCallers.Should().ContainSingle().Which.Should().Be("mdn-sender"); } [Fact] public async Task UnsignedMessage_InPartnershipWithoutRequiredSignature_IsNotReportedAsVerified() { // The README promises redbAs2.signatureValid means "the inbound signature verified against the // partner cert". An unsigned message was not verified at all; reporting true lets a route that // gates on the header accept it as authenticated. var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("plain", new As2ConnectionFactory { OurCertificate = Cert, PartnerCertificate = Cert, As2From = "US", As2To = "THEM", Sign = false, Encrypt = false, MdnMode = As2MdnMode.Sync, SignedMdn = false, }); context.AddToRegistry("plain-send", new As2ConnectionFactory { OurCertificate = Cert, PartnerCertificate = Cert, As2From = "THEM", As2To = "US", Sign = false, Encrypt = false, MdnMode = As2MdnMode.Sync, SignedMdn = false, }); var reported = new System.Collections.Concurrent.ConcurrentQueue(); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("plain")) .Process(e => reported.Enqueue(e.In.GetHeader(As2Headers.SignatureValid)))); await context.Start(); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/in").ConnectionFactory("plain-send")).CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("PO*PLAIN~") { ContentType = "application/edi-x12" })); reported.Should().ContainSingle().Which.Should().BeFalse("nothing was verified: the message carried no signature"); } [Fact] public async Task SignedMessage_WithVerifiedSignature_IsReportedAsVerified() { var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("me", Factory()); context.AddToRegistry("them", As2TestKit.Sender()); var reported = new System.Collections.Concurrent.ConcurrentQueue(); context.AddRoutes(r => r.From(As2Dsl.Receive("/inbound").Host("127.0.0.1").Port(port).ConnectionFactory("me")) .Process(e => reported.Enqueue(e.In.GetHeader(As2Headers.SignatureValid)))); await context.Start(); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/inbound").ConnectionFactory("them")).CreateProducer(); await producer.Start(); await producer.Process(new Exchange(new Message("PO*SIGNED~") { ContentType = "application/edi-x12" })); reported.Should().ContainSingle().Which.Should().BeTrue("the signature was present and verified against the partner certificate"); } private static string? CallerId(IExchange e) => ExchangePrincipal.Get(e)?.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)?.Value; private static As2ConnectionFactory Factory() => new() { OurCertificate = Cert, PartnerCertificate = Cert, As2From = "US", As2To = "THEM", Sign = true, Encrypt = true, SignedMdn = true, MdnMode = As2MdnMode.Sync, }; private static (string contentType, string transferEncoding, byte[] body) BuildAs2Message(string payload) { var engine = new As2CryptoEngine(); var part = new MimePart("application", "edi-x12") { Content = new MimeContent(new MemoryStream(Encoding.UTF8.GetBytes(payload))), ContentTransferEncoding = ContentEncoding.Binary, }; var signed = engine.Sign(part, Cert, "sha-256"); var encrypted = engine.Encrypt(signed, Cert, "aes-128-cbc"); using var ms = new MemoryStream(); var options = FormatOptions.Default.Clone(); options.NewLineFormat = NewLineFormat.Dos; encrypted.WriteTo(options, ms); var all = ms.ToArray(); var sep = -1; for (var i = 0; i + 3 < all.Length; i++) if (all[i] == 13 && all[i + 1] == 10 && all[i + 2] == 13 && all[i + 3] == 10) { sep = i; break; } var body = sep >= 0 ? all[(sep + 4)..] : all; return (encrypted.Headers[HeaderId.ContentType]!, encrypted.Headers[HeaderId.ContentTransferEncoding]!, body); } private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); private static X509Certificate2 MakeCert(string cn) { var rsa = RSA.Create(2048); var req = new CertificateRequest($"CN={cn}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); using var certWithKey = req.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(10)); using var publicOnly = X509CertificateLoader.LoadCertificate(certWithKey.Export(X509ContentType.Cert)); return publicOnly.CopyWithPrivateKey(rsa); } } Path: redb-route/tests/redb.Route.Tests.As2/As2RestartTests.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.As2/As2RestartTests.cs ---- using System.Text; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.As2; using redb.Route.Core; using As2Dsl = redb.Route.As2.Fluent.As2; namespace redb.Route.Tests.As2; /// /// An AS2 consumer and producer keep working after Stop() and Start() of the same route context: the stop /// gives the listener path back, the start registers it again on the cached endpoint, and a message is signed, /// encrypted, received and acknowledged with an MDN on both runs. /// public class As2RestartTests { [Fact] public async Task Consumer_and_producer_work_after_the_context_is_stopped_and_started_again() { var port = As2TestKit.FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("me", As2TestKit.Receiver()); context.AddToRegistry("them", As2TestKit.Sender()); var received = new List(); context.AddRoutes(r => r.From(As2Dsl.Receive("/inbound").Host("127.0.0.1").Port(port).ConnectionFactory("me")) .Process(e => { lock (received) received.Add(Encoding.UTF8.GetString((byte[])e.In.Body!)); })); context.AddRoutes(r => r.From("direct://send").To(As2Dsl.Send($"http://127.0.0.1:{port}/inbound").ConnectionFactory("them"))); async Task SendAsync(string payload) { var producer = context.GetEndpoint("direct://send").CreateProducer(); await producer.Start(); var exchange = new Exchange(new Message(payload) { ContentType = "application/edi-x12" }); await producer.Process(exchange); exchange.Exception.Should().BeNull("an AS2 send after a restart arrives and gets an MDN"); } await context.Start(); await SendAsync("ISA*first~"); await context.Stop(); await context.Start(); await SendAsync("ISA*second~"); lock (received) received.Should().Equal(["ISA*first~", "ISA*second~"], "the AS2 receiver accepts after a restart"); } } Path: redb-route/tests/redb.Route.Tests.As2/As2SkeletonTests.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.As2/As2SkeletonTests.cs ---- using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.As2; using redb.Route.Core; using As2Dsl = redb.Route.As2.Fluent.As2; namespace redb.Route.Tests.As2; /// /// Skeleton tests: DSL URI building (no path truncation), scheme/TLS resolution, option binding and /// validation, secret redaction, and component registration through a real RouteContext. No AS2 traffic — /// send/receive arrive in later phases. /// public class As2SkeletonTests { // ── DSL ────────────────────────────────────────────────────────────────── [Fact] public void Receive_KeepsFullPath_NoFirstSegmentTruncation() { string uri = As2Dsl.Receive("/inbound/orders").Host("0.0.0.0").Port(4080).ConnectionFactory("walmart"); uri.Should().Be("as2:/inbound/orders?host=0.0.0.0&port=4080&connectionFactory=walmart"); // The path must survive parsing intact — the Http first-segment-drop bug must not recur. EndpointUriParser.Parse(uri).Path.Should().Be("/inbound/orders"); } [Fact] public void Receive_AddsLeadingSlashWhenMissing() { string uri = As2Dsl.Receive("inbound").Port(4080); uri.Should().StartWith("as2:/inbound?"); } [Fact] public void Send_MapsHttpsToAs2sScheme() { ((string)As2Dsl.Send("https://partner.example.com/as2")).Should().Be("as2s://partner.example.com/as2"); ((string)As2Dsl.Send("http://partner.example.com/as2")).Should().Be("as2://partner.example.com/as2"); } [Fact] public void Send_AppendsConnectionFactory() { ((string)As2Dsl.Send("https://p/as2").ConnectionFactory("walmart")) .Should().Be("as2s://p/as2?connectionFactory=walmart"); } // ── Options: binding & validation ──────────────────────────────────────── [Fact] public void Options_BindFromUri_MapsTypedValues() { var o = new As2EndpointOptions(); o.BindFromUri(new Dictionary { ["port"] = "5443", ["sign"] = "false", ["mdnMode"] = "Async", ["asyncMdnUrl"] = "http://us/mdn", }); o.Port.Should().Be(5443); o.Sign.Should().BeFalse(); o.MdnMode.Should().Be(As2MdnMode.Async); } [Fact] public void Options_Validate_AcceptsDefaults() { var act = () => new As2EndpointOptions().Validate(); act.Should().NotThrow(); } [Fact] public void Options_Validate_AsyncWithoutTarget_Throws() { var act = () => new As2EndpointOptions { MdnMode = As2MdnMode.Async }.Validate(); act.Should().Throw(); } [Fact] public void Options_Validate_BadPort_Throws() { var act = () => new As2EndpointOptions { Port = 70000 }.Validate(); act.Should().Throw(); } [Fact] public void Options_Validate_UnsupportedSignAlg_Throws() { var act = () => new As2EndpointOptions { SignAlg = "md5" }.Validate(); act.Should().Throw(); } [Fact] public void Options_Validate_UnsupportedEncryptionAlg_Throws() { var act = () => new As2EndpointOptions { EncryptAlg = "rc4" }.Validate(); act.Should().Throw(); } [Fact] public void Options_Validate_SupportedMatrix_Ok() { var act = () => new As2EndpointOptions { SignAlg = "sha-512", EncryptAlg = "3des", AllowLegacyAlgorithms = true }.Validate(); act.Should().NotThrow(); } // ── Secret redaction ───────────────────────────────────────────────────── [Fact] public void SslCertPassword_IsSensitive_RedactedInUri() { // Binding harvests [Sensitive] props → registers the key for URI sanitization. var o = new As2EndpointOptions(); o.BindFromUri(new Dictionary { ["sslCertPassword"] = "s3cr3t" }); o.SslCertPassword.Should().Be("s3cr3t"); var masked = EndpointUri.Sanitize("as2s://p/as2?sslCertPassword=s3cr3t"); masked.Should().NotContain("s3cr3t"); masked.Should().Contain(EndpointUri.Redacted); } // ── Component registration through RouteContext ────────────────────────── [Fact] public void Component_ResolvesAs2Scheme_ToAs2Endpoint() { using var ctx = new RouteContext(); ctx.AddComponent(new As2Component()); var endpoint = ctx.GetEndpoint(As2Dsl.Receive("/in").Host("127.0.0.1").Port(4080)); endpoint.Should().BeOfType(); } [Fact] public void Component_ResolvesAs2sScheme_AndSetsTls() { using var ctx = new RouteContext(); ctx.AddComponent(new As2Component()); var endpoint = (As2Endpoint)ctx.GetEndpoint(As2Dsl.Send("https://partner/as2")); endpoint.EndpointOptions.UseTls.Should().BeTrue(); } } Path: redb-route/tests/redb.Route.Tests.As2/As2SpoolTests.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.As2/As2SpoolTests.cs ---- using System.Text; using AwesomeAssertions; using redb.Route.As2; using redb.Route.As2.Crypto; using redb.Route.As2.Mdn; using redb.Route.Configuration; using redb.Route.Core; using As2Dsl = redb.Route.As2.Fluent.As2; using static redb.Route.Tests.As2.As2TestKit; namespace redb.Route.Tests.As2; /// /// A received message goes through the core stream cache, as the AS4 receiver's does: the request, each decrypted and /// decompressed stage, and the payload are spooled to a temporary file past the threshold instead of held in memory. /// streamBody hands the spooled payload to the route as a Stream. /// public class As2SpoolTests { private sealed class Receiver_ { public required RouteContext Context { get; init; } public required int Port { get; init; } public required As2Endpoint Endpoint { get; init; } } private static async Task Start(Func route, bool streamBody, StreamCacheOptions? spool, bool compress = false) { var port = FreePort(); var context = new RouteContext(); if (spool is not null) context.AddService(typeof(StreamCacheOptions), spool); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver(f => f.Compress = compress)); var receive = As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv"); if (streamBody) receive = receive.StreamBody(); context.AddRoutes(r => r.From(receive).Process(e => route(e).GetAwaiter().GetResult())); await context.Start(); return new Receiver_ { Context = context, Port = port, Endpoint = (As2Endpoint)context.GetEndpoint(receive) }; } private static MdnParser.MdnResult Mdn(HttpResponseMessage response) => MdnParser.Parse( response.Content.Headers.ContentType?.ToString(), response.Content.Headers.TryGetValues("Content-Transfer-Encoding", out var v) ? string.Join(",", v) : null, response.Content.ReadAsByteArrayAsync().GetAwaiter().GetResult(), new As2CryptoEngine(), Cert); [Fact] public async Task LargePayload_WithStreamBody_IsSpooledToDisk_AndReadIntact() { var large = new string('x', 300_000); bool? spooled = null; string? read = null; var receiver = await Start(e => { var cache = (StreamCache)e.In.Body!; spooled = cache.IsSpooled; read = new StreamReader(cache, leaveOpen: true).ReadToEnd(); return Task.CompletedTask; }, streamBody: true, new StreamCacheOptions { SpoolThreshold = 4096 }); await using var _ = receiver.Context; var mdn = Mdn(await PostAsync(receiver.Port, "/in", BuildMessage(large, Cert, Cert))); mdn.IsPositive.Should().BeTrue(); spooled.Should().BeTrue(); read.Should().Be(large); } [Fact] public async Task CompressedLargePayload_IsSpooled_AndItsMicStillMatches() { // Through the producer, so the MIC of compress-sign-encrypt is checked end to end against the spooled stages. var port = FreePort(); await using var context = new RouteContext(); context.AddService(typeof(StreamCacheOptions), new StreamCacheOptions { SpoolThreshold = 4096 }); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver(f => f.Compress = true)); context.AddToRegistry("them", Sender(f => f.Compress = true)); bool? spooled = null; string? read = null; context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").StreamBody()) .Process(e => { var cache = (StreamCache)e.In.Body!; spooled = cache.IsSpooled; read = new StreamReader(cache, leaveOpen: true).ReadToEnd(); })); await context.Start(); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{port}/in").ConnectionFactory("them")).CreateProducer(); await producer.Start(); var payload = string.Concat(Enumerable.Range(0, 20_000).Select(i => $"LIN*{i}~")); var exchange = new Exchange(new Message(payload) { ContentType = "application/edi-x12" }); await producer.Process(exchange); spooled.Should().BeTrue(); read.Should().Be(payload); exchange.Out!.GetHeader(As2Headers.MdnConfirmed).Should().BeTrue("the MIC over the spooled content is the one the sender computed"); } [Fact] public async Task StreamBody_IsReleasedWithTheExchange() { Stream? body = null; var receiver = await Start(e => { body = (Stream)e.In.Body!; return Task.CompletedTask; }, streamBody: true, spool: null); await using var _ = receiver.Context; Mdn(await PostAsync(receiver.Port, "/in", BuildMessage("PO*STREAM~", Cert, Cert))).IsPositive.Should().BeTrue(); body.Should().NotBeNull(); body!.CanRead.Should().BeFalse("Exchange.DisposeAsync closes a Stream body"); } [Fact] public async Task WithoutStreamBody_TheBodyIsBytes_EvenWhenSpooled() { var large = new string('y', 200_000); object? body = null; var receiver = await Start(e => { body = e.In.Body; return Task.CompletedTask; }, streamBody: false, new StreamCacheOptions { SpoolThreshold = 4096 }); await using var _ = receiver.Context; await PostAsync(receiver.Port, "/in", BuildMessage(large, Cert, Cert)); body.Should().BeOfType().Which.Should().Equal(Encoding.UTF8.GetBytes(large)); } [Fact] public async Task TheRequestItself_GoesThroughTheSpool() { // The spool directory is gone and the threshold is tiny: a request that is spooled cannot be read, and the // partner gets unexpected-processing-error with a reference, counted as an error. Held in memory, it would pass. var spool = new StreamCacheOptions { SpoolThreshold = 16, TempDirectory = Path.Combine(Path.GetTempPath(), "redb-as2-" + Guid.NewGuid().ToString("N"), "gone"), }; var routed = 0; var receiver = await Start(_ => { Interlocked.Increment(ref routed); return Task.CompletedTask; }, streamBody: false, spool); await using var _ = receiver.Context; var mdn = Mdn(await PostAsync(receiver.Port, "/in", BuildMessage("PO*SPOOL~", Cert, Cert))); routed.Should().Be(0); mdn.Disposition.Should().EndWith("processed/error: unexpected-processing-error"); ((redb.Route.Abstractions.IEndpointStatistics)receiver.Endpoint).Errors.Should().Be(1); } } Path: redb-route/tests/redb.Route.Tests.As2/As2StopDrainsInflightTests.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.As2/As2StopDrainsInflightTests.cs ---- using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using AwesomeAssertions; using MimeKit; using redb.Route.Abstractions; using redb.Route.As2; using redb.Route.As2.Crypto; using redb.Route.Core; using As2Dsl = redb.Route.As2.Fluent.As2; namespace redb.Route.Tests.As2; /// /// Stopping one route on a shared listener must wait for the deliveries it is already processing. It /// used to unregister the route and ask the listener to stop when empty — and when another route /// still holds the port, the listener stays up, so a partner's message could be cut between decrypt /// and route. Reported by the AS4 agent 2026-09-25. /// public class As2StopDrainsInflightTests { private static readonly X509Certificate2 Cert = MakeCert("as2-drain"); private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); private static X509Certificate2 MakeCert(string cn) { var rsa = RSA.Create(2048); var req = new CertificateRequest($"CN={cn}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); using var certWithKey = req.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(10)); using var publicOnly = X509CertificateLoader.LoadCertificate(certWithKey.Export(X509ContentType.Cert)); return publicOnly.CopyWithPrivateKey(rsa); } private static As2ConnectionFactory Factory() => new() { OurCertificate = Cert, PartnerCertificate = Cert, As2From = "US", As2To = "THEM", Sign = true, Encrypt = true, SignedMdn = true, MdnMode = As2MdnMode.Sync, }; private static (string contentType, string transferEncoding, byte[] body) BuildAs2Message(string payload) { var engine = new As2CryptoEngine(); var part = new MimePart("application", "edi-x12") { Content = new MimeContent(new MemoryStream(Encoding.UTF8.GetBytes(payload))), ContentTransferEncoding = ContentEncoding.Binary, }; var signed = engine.Sign(part, Cert, "sha-256"); var encrypted = engine.Encrypt(signed, Cert, "aes-128-cbc"); using var ms = new MemoryStream(); var options = FormatOptions.Default.Clone(); options.NewLineFormat = NewLineFormat.Dos; encrypted.WriteTo(options, ms); var all = ms.ToArray(); var sep = -1; for (var i = 0; i + 3 < all.Length; i++) if (all[i] == 13 && all[i + 1] == 10 && all[i + 2] == 13 && all[i + 3] == 10) { sep = i; break; } var body = sep >= 0 ? all[(sep + 4)..] : all; return (encrypted.Headers[HeaderId.ContentType]!, encrypted.Headers[HeaderId.ContentTransferEncoding]!, body); } [Fact] public async Task Stop_waits_for_a_delivery_already_in_the_pipeline_while_the_port_stays_busy() { var port = FreePort(); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var finished = false; await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("me", Factory()); var slow = context.GetEndpoint( As2Dsl.Receive("/inbound").Host("127.0.0.1").Port(port).ConnectionFactory("me").Build()) .CreateConsumer(new redb.Route.Processors.DelegateProcessor(async (e, ct) => { entered.TrySetResult(); await release.Task; finished = true; })); // A second route keeps the listener alive after the first is stopped. var other = context.GetEndpoint( As2Dsl.Receive("/other").Host("127.0.0.1").Port(port).ConnectionFactory("me").Build()) .CreateConsumer(new redb.Route.Processors.DelegateProcessor(_ => { })); await slow.Start(); await other.Start(); var (contentType, transferEncoding, body) = BuildAs2Message("PO*4200~"); using var client = new HttpClient(); using var content = new ByteArrayContent(body); content.Headers.TryAddWithoutValidation("Content-Type", contentType); content.Headers.TryAddWithoutValidation("Content-Transfer-Encoding", transferEncoding); using var request = new HttpRequestMessage(HttpMethod.Post, $"http://127.0.0.1:{port}/inbound") { Content = content }; request.Headers.TryAddWithoutValidation("AS2-From", "THEM"); request.Headers.TryAddWithoutValidation("AS2-To", "US"); request.Headers.TryAddWithoutValidation("Message-ID", ""); var call = client.SendAsync(request); 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 delivery of this route is still running"); release.TrySetResult(); await stop.WaitAsync(TimeSpan.FromSeconds(15)); finished.Should().BeTrue(); (await call).StatusCode.Should().Be(HttpStatusCode.OK); await other.Stop(); } } Path: redb-route/tests/redb.Route.Tests.As2/As2TestKit.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.As2/As2TestKit.cs ---- using System.Net; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using MimeKit; using redb.Route.As2; using redb.Route.As2.Crypto; namespace redb.Route.Tests.As2; /// /// Shared test material: certificates, mirrored partnerships, raw AS2 messages built with the real engine, and a /// listener that records whatever is posted to it (the "trap" for receipt URLs that must not be called). /// internal static class As2TestKit { /// The certificate of the loopback partnerships: both sides use it, as the loopback tests always did. public static readonly X509Certificate2 Cert = MakeCert("as2-kit"); /// A certificate no partnership pins: a message signed with it did not come from the partner. public static readonly X509Certificate2 Stranger = MakeCert("as2-stranger"); /// The receiving side: we are US, the partner is THEM. public static As2ConnectionFactory Receiver(Action? configure = null) { var f = new As2ConnectionFactory { OurCertificate = Cert, PartnerCertificate = Cert, As2From = "US", As2To = "THEM", Sign = true, Encrypt = true, SignedMdn = true, MdnMode = As2MdnMode.Sync, }; configure?.Invoke(f); return f; } /// The sending side of the same partnership: we are THEM, the partner is US. public static As2ConnectionFactory Sender(Action? configure = null) { var f = new As2ConnectionFactory { OurCertificate = Cert, PartnerCertificate = Cert, As2From = "THEM", As2To = "US", Sign = true, Encrypt = true, SignedMdn = true, MdnMode = As2MdnMode.Sync, }; configure?.Invoke(f); return f; } public static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); public static X509Certificate2 MakeCert(string cn, DateTimeOffset? notBefore = null, DateTimeOffset? notAfter = null) { var rsa = RSA.Create(2048); var req = new CertificateRequest($"CN={cn}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); using var certWithKey = req.CreateSelfSigned(notBefore ?? DateTimeOffset.UtcNow.AddDays(-1), notAfter ?? DateTimeOffset.UtcNow.AddYears(10)); using var publicOnly = X509CertificateLoader.LoadCertificate(certWithKey.Export(X509ContentType.Cert)); return publicOnly.CopyWithPrivateKey(rsa); } /// /// A raw AS2 body: the payload compressed when says so, signed with /// (none: unsigned) and encrypted for (none: not encrypted). /// With the signed part is compressed (RFC 5402 §3.3/3.6) instead of the payload. /// Returns the top-level MIME headers and the body. /// public static (string ContentType, string? TransferEncoding, byte[] Body) BuildMessage( string payload, X509Certificate2? signer, X509Certificate2? recipient, string signAlg = "sha-256", bool compress = false, bool compressAfterSign = false) { var engine = new As2CryptoEngine(); MimeEntity entity = new MimePart("application", "edi-x12") { Content = new MimeContent(new MemoryStream(Encoding.UTF8.GetBytes(payload))), ContentTransferEncoding = ContentEncoding.Binary, }; if (compress && !compressAfterSign) entity = engine.Compress(entity); if (signer is not null) entity = engine.Sign(entity, signer, signAlg); if (compress && compressAfterSign) entity = engine.Compress(entity); if (recipient is not null) entity = engine.Encrypt(entity, recipient, "aes-128-cbc"); using var ms = new MemoryStream(); var options = FormatOptions.Default.Clone(); options.NewLineFormat = NewLineFormat.Dos; entity.WriteTo(options, ms); var all = ms.ToArray(); var sep = -1; for (var i = 0; i + 3 < all.Length; i++) if (all[i] == 13 && all[i + 1] == 10 && all[i + 2] == 13 && all[i + 3] == 10) { sep = i; break; } var body = sep >= 0 ? all[(sep + 4)..] : all; return (entity.Headers[HeaderId.ContentType]!, entity.Headers[HeaderId.ContentTransferEncoding], body); } /// /// POSTs a raw AS2 message from THEM to US that asks for a signed synchronous receipt. /// overrides or adds headers; a null value removes one. /// public static async Task PostAsync( int port, string path, (string ContentType, string? TransferEncoding, byte[] Body) message, IReadOnlyDictionary? headers = null, TimeSpan? timeout = null, bool expectContinue = false) { var all = new Dictionary(StringComparer.OrdinalIgnoreCase) { ["AS2-Version"] = "1.2", ["AS2-From"] = "THEM", ["AS2-To"] = "US", ["Message-ID"] = $"<{Guid.NewGuid():N}@kit>", ["Disposition-Notification-To"] = "them@example.com", ["Disposition-Notification-Options"] = "signed-receipt-protocol=optional, pkcs7-signature; signed-receipt-micalg=optional, sha-256", }; if (headers is not null) foreach (var (k, v) in headers) all[k] = v; using var client = new HttpClient { Timeout = timeout ?? TimeSpan.FromSeconds(30) }; var content = new ByteArrayContent(message.Body); content.Headers.TryAddWithoutValidation("Content-Type", message.ContentType); if (message.TransferEncoding is not null) content.Headers.TryAddWithoutValidation("Content-Transfer-Encoding", message.TransferEncoding); var request = new HttpRequestMessage(HttpMethod.Post, $"http://127.0.0.1:{port}{path}") { Content = content }; // A server that refuses the body answers before it is sent, instead of resetting the connection mid-upload. if (expectContinue) request.Headers.ExpectContinue = true; foreach (var (k, v) in all) if (v is not null) request.Headers.TryAddWithoutValidation(k, v); var response = await client.SendAsync(request); await response.Content.LoadIntoBufferAsync(); return response; } } /// /// An HTTP listener that records every request posted to it and answers 200, or what status gives for the /// request's number (1 for the first). /// internal sealed class As2Trap : IDisposable { private readonly HttpListener _listener = new(); private readonly Task _loop; public As2Trap(int port, Func? status = null) { var hits = 0; Port = port; _listener.Prefixes.Add($"http://127.0.0.1:{port}/"); _listener.Start(); _loop = Task.Run(async () => { while (_listener.IsListening) { HttpListenerContext ctx; try { ctx = await _listener.GetContextAsync(); } catch (HttpListenerException) { return; } catch (ObjectDisposedException) { return; } using var ms = new MemoryStream(); await ctx.Request.InputStream.CopyToAsync(ms); var headers = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (string key in ctx.Request.Headers) headers[key] = ctx.Request.Headers[key]!; Requests.Enqueue((ctx.Request.Url!.AbsolutePath, headers, ms.ToArray())); ctx.Response.StatusCode = status?.Invoke(++hits) ?? 200; ctx.Response.Close(); } }); } public int Port { get; } public string Url(string path = "/mdn") => $"http://127.0.0.1:{Port}{path}"; public System.Collections.Concurrent.ConcurrentQueue<(string Path, Dictionary Headers, byte[] Body)> Requests { get; } = new(); /// Waits up to for a request; true when one arrived. public async Task HitAsync(TimeSpan within) { var deadline = DateTime.UtcNow + within; while (Requests.IsEmpty && DateTime.UtcNow < deadline) await Task.Delay(20); return !Requests.IsEmpty; } public void Dispose() { _listener.Stop(); _listener.Close(); } } Path: redb-route/tests/redb.Route.Tests.As2/As2TracingTests.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.As2/As2TracingTests.cs ---- using System.Diagnostics; using System.Net; using AwesomeAssertions; using redb.Route.As2; using redb.Route.Configuration; using redb.Route.Core; using redb.Route.Telemetry; using redb.Route.Tests.Telemetry; using As2Dsl = redb.Route.As2.Fluent.As2; using static redb.Route.Tests.As2.As2TestKit; namespace redb.Route.Tests.As2; /// /// The AS2 transports on the core tracing contract (, redb.Route 0b5658f0), as /// the HTTP transport uses it: a received message opens a Consumer span continuing the sender's trace, or a root; the /// sender's baggage reaches the route; a send writes the context of its own span to the request, replacing a copied /// header; a failed send is red; EnableTelemetry=false opens none of these spans. /// public class As2TracingTests { private static (ActivityTraceId TraceId, ActivitySpanId SpanId, string Header) Caller() { var traceId = ActivityTraceId.CreateRandom(); var spanId = ActivitySpanId.CreateRandom(); return (traceId, spanId, $"00-{traceId}-{spanId}-01"); } private static async Task<(RouteContext Context, int Port, List Baggage)> StartReceiver(RouteEngineOptions? options = null) { var port = FreePort(); var context = new RouteContext(options: options ?? new RouteEngineOptions()); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); var baggage = new List(); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv")) .Process(_ => { lock (baggage) baggage.Add(Activity.Current?.GetBaggageItem("tenant")); })); await context.Start(); return (context, port, baggage); } private static Activity ReceiveSpan(RouteTelemetryProbe probe) => probe.Activities.Single(a => a.Kind == ActivityKind.Consumer); [Fact] public async Task Received_message_with_traceparent_continues_the_senders_trace_on_a_named_span() { var (context, port, _) = await StartReceiver(); await using var _ = context; using var probe = RouteTelemetryProbe.ForEndpointContaining($"port={port}"); var caller = Caller(); (await PostAsync(port, "/in", BuildMessage("PO*TRACE~", Cert, Cert), new Dictionary { ["traceparent"] = caller.Header })).StatusCode.Should().Be(HttpStatusCode.OK); var span = ReceiveSpan(probe); span.TraceId.Should().Be(caller.TraceId); span.ParentSpanId.Should().Be(caller.SpanId); span.DisplayName.Should().Be("/in receive", "the span names its destination, as the messaging conventions do"); RouteTelemetryProbe.Tag(span, RouteTelemetryProbe.EndpointTag).Should().Contain($"port={port}"); } [Fact] public async Task Received_message_without_traceparent_is_a_root_span() { var (context, port, _) = await StartReceiver(); await using var _ = context; using var probe = RouteTelemetryProbe.ForEndpointContaining($"port={port}"); await PostAsync(port, "/in", BuildMessage("PO*ROOT~", Cert, Cert)); var span = ReceiveSpan(probe); span.ParentSpanId.Should().Be(default(ActivitySpanId)); span.Parent.Should().BeNull(); } [Fact] public async Task The_senders_baggage_reaches_the_route() { var (context, port, baggage) = await StartReceiver(); await using var _ = context; using var probe = RouteTelemetryProbe.ForEndpointContaining($"port={port}"); // the baggage rides on the span, which needs a listener var headers = new Dictionary(); using (var send = new Activity("caller").Start()) { send.AddBaggage("tenant", "t1"); RouteTelemetryExtensions.InjectTraceContext(send, headers, static (h, name, value) => h[name] = value); } await PostAsync(port, "/in", BuildMessage("PO*BAGGAGE~", Cert, Cert), headers); baggage.Should().ContainSingle().Which.Should().Be("t1"); } [Fact] public async Task A_send_writes_the_context_of_its_own_span_replacing_a_copied_traceparent() { // From(http) -> To(as2): the caller's traceparent is an exchange header and was bridged onto the request, so // HttpClient did not write its own and the partner saw the previous hop. using var trap = new As2Trap(FreePort()); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("them", Sender(f => f.MdnMode = As2MdnMode.None)); var producer = context.GetEndpoint(As2Dsl.Send(trap.Url("/as2")).ConnectionFactory("them")).CreateProducer(); await producer.Start(); using var probe = RouteTelemetryProbe.ForEndpointContaining($":{trap.Port}/"); var caller = Caller(); var message = new Message("PO*HOP~") { ContentType = "application/edi-x12" }; message.Headers["traceparent"] = caller.Header; await producer.Process(new Exchange(message)); (await trap.HitAsync(TimeSpan.FromSeconds(5))).Should().BeTrue(); trap.Requests.TryPeek(out var hit); var send = probe.Activities.Single(a => a.Kind == ActivityKind.Client); hit.Headers["traceparent"].Should().Be($"00-{send.TraceId}-{send.SpanId}-{(int)send.ActivityTraceFlags:x2}"); } [Fact] public async Task A_send_the_partner_does_not_answer_within_the_timeout_marks_its_span_red() { // HttpClient reports its own timeout as TaskCanceledException: a failure of the send, not a cancellation by the caller. var port = FreePort(); using var silent = new HttpListener(); silent.Prefixes.Add($"http://127.0.0.1:{port}/"); silent.Start(); var accepted = silent.GetContextAsync(); // takes the request and never answers await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("them", Sender(f => f.MdnMode = As2MdnMode.None)); var producer = context.GetEndpoint($"as2://127.0.0.1:{port}/as2?connectionFactory=them&timeout=300").CreateProducer(); await producer.Start(); using var probe = RouteTelemetryProbe.ForEndpointContaining($":{port}/"); var act = () => producer.Process(new Exchange(new Message("PO*SLOW~"))); await act.Should().ThrowAsync(); probe.Activities.Single(a => a.Kind == ActivityKind.Client).Status.Should().Be(ActivityStatusCode.Error); // On a slow host the 300 ms run out before the request reaches the listener: awaiting it would hang the test. // Disposing the listener ends a pending GetContextAsync. if (accepted.IsCompletedSuccessfully) accepted.Result.Response.Abort(); } [Fact] public async Task A_send_cancelled_by_the_caller_is_not_marked_as_a_failure() { var port = FreePort(); using var silent = new HttpListener(); silent.Prefixes.Add($"http://127.0.0.1:{port}/"); silent.Start(); var accepted = silent.GetContextAsync(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("them", Sender(f => f.MdnMode = As2MdnMode.None)); var producer = context.GetEndpoint($"as2://127.0.0.1:{port}/as2?connectionFactory=them&timeout=30000").CreateProducer(); await producer.Start(); using var probe = RouteTelemetryProbe.ForEndpointContaining($":{port}/"); using var cts = new CancellationTokenSource(); var sending = producer.Process(new Exchange(new Message("PO*STOP~")), cts.Token); var request = await accepted; // the request reached the partner, which does not answer; now the caller gives up cts.Cancel(); var act = () => sending; await act.Should().ThrowAsync(); probe.Activities.Single(a => a.Kind == ActivityKind.Client).Status.Should().NotBe(ActivityStatusCode.Error, "the caller stopped the send; nothing failed"); request.Response.Abort(); } [Fact] public async Task A_failed_send_marks_its_span_red() { await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("them", Sender(f => f.MdnMode = As2MdnMode.None)); var closed = FreePort(); var producer = context.GetEndpoint(As2Dsl.Send($"http://127.0.0.1:{closed}/as2").ConnectionFactory("them")).CreateProducer(); await producer.Start(); using var probe = RouteTelemetryProbe.ForEndpointContaining($":{closed}/"); var act = () => producer.Process(new Exchange(new Message("PO*DOWN~"))); await act.Should().ThrowAsync(); probe.Activities.Single(a => a.Kind == ActivityKind.Client).Status.Should().Be(ActivityStatusCode.Error); } [Fact] public async Task Tracing_off_opens_no_span_and_still_passes_the_senders_context_on() { using var trap = new As2Trap(FreePort()); var port = FreePort(); await using var context = new RouteContext(options: new RouteEngineOptions { EnableTelemetry = false }); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); context.AddToRegistry("next", Sender(f => { f.As2From = "US"; f.As2To = "NEXT"; f.MdnMode = As2MdnMode.None; })); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv")) .To(As2Dsl.Send(trap.Url("/next")).ConnectionFactory("next"))); await context.Start(); using var probe = RouteTelemetryProbe.ForEndpointContaining($"{port}"); using var sendProbe = RouteTelemetryProbe.ForEndpointContaining($":{trap.Port}/"); var caller = Caller(); await PostAsync(port, "/in", BuildMessage("PO*OFF~", Cert, Cert), new Dictionary { ["traceparent"] = caller.Header }); (await trap.HitAsync(TimeSpan.FromSeconds(5))).Should().BeTrue(); trap.Requests.TryPeek(out var hit); hit.Headers["traceparent"].Should().Contain(caller.TraceId.ToString(), "a redb hop with tracing off does not cut the trace around it"); probe.Activities.Should().BeEmpty(); sendProbe.Activities.Should().BeEmpty(); } // ── Failures on the receive span (review of 838764a3) ──────────────────── private static async Task<(RouteContext Context, int Port)> StartMdnReceiver(Action? configure = null, bool routeFails = false, long? maxBody = null) { var port = FreePort(); var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("them", Sender(f => { f.MdnMode = As2MdnMode.Async; f.AsyncMdnUrl = $"http://127.0.0.1:{port}/mdn"; configure?.Invoke(f); })); var receive = As2Dsl.ReceiveMdn("/mdn").Host("127.0.0.1").Port(port).ConnectionFactory("them"); if (maxBody is { } limit) receive = receive.MaxRequestBodySize(limit); context.AddRoutes(r => r.From(receive).Process(_ => { if (routeFails) throw new InvalidOperationException("route failed"); })); await context.Start(); return (context, port); } private static async Task PostMdn(int port, (string ContentType, string? Cte, byte[] Body) mdn, bool expectContinue = false) { using var client = new HttpClient(); var content = new ByteArrayContent(mdn.Body); content.Headers.TryAddWithoutValidation("Content-Type", mdn.ContentType); if (mdn.Cte is not null) content.Headers.TryAddWithoutValidation("Content-Transfer-Encoding", mdn.Cte); var request = new HttpRequestMessage(HttpMethod.Post, $"http://127.0.0.1:{port}/mdn") { Content = content }; if (expectContinue) request.Headers.ExpectContinue = true; return (await client.SendAsync(request)).StatusCode; } private static (string ContentType, string? Cte, byte[] Body) SignedMdn(bool signed = true) => redb.Route.As2.Mdn.MdnBuilder.Build("", "US", "THEM", new redb.Route.As2.Crypto.As2Mic("AAAA", "sha-256"), signer: signed ? new redb.Route.As2.Crypto.As2CryptoEngine() : null, signerCert: signed ? Cert : null); private static Activity MdnSpan(RouteTelemetryProbe probe) => probe.Activities.Single(a => a.Kind == ActivityKind.Consumer); [Fact] public async Task MdnReceiver_AnUnreadableMdn_IsRefused_AndMarksTheSpanRed() { var (context, port) = await StartMdnReceiver(); await using var _ = context; using var probe = RouteTelemetryProbe.ForEndpointContaining($"port={port}"); // A multipart/signed without its signature part: verifying it throws, the MDN cannot be read. var broken = "--b\r\nContent-Type: text/plain\r\n\r\nno signature follows\r\n--b--\r\n"u8.ToArray(); (await PostMdn(port, ("multipart/signed; boundary=b; protocol=\"application/pkcs7-signature\"; micalg=sha-256", null, broken))) .Should().Be(HttpStatusCode.BadRequest); MdnSpan(probe).Status.Should().Be(ActivityStatusCode.Error); } [Fact] public async Task MdnReceiver_AReceiptThePolicyRefuses_MarksTheSpanRed() { var (context, port) = await StartMdnReceiver(f => f.RequireValidMdn = true); await using var _ = context; using var probe = RouteTelemetryProbe.ForEndpointContaining($"port={port}"); (await PostMdn(port, SignedMdn(signed: false))).Should().Be(HttpStatusCode.BadRequest); MdnSpan(probe).Status.Should().Be(ActivityStatusCode.Error); } [Fact] public async Task MdnReceiver_AFailedRoute_MarksTheSpanRed() { var (context, port) = await StartMdnReceiver(routeFails: true); await using var _ = context; using var probe = RouteTelemetryProbe.ForEndpointContaining($"port={port}"); (await PostMdn(port, SignedMdn())).Should().Be(HttpStatusCode.OK, "the partner delivered its receipt; the route's failure is the route's"); MdnSpan(probe).Status.Should().Be(ActivityStatusCode.Error); } [Fact] public async Task MdnReceiver_ABodyOverTheLimit_MarksTheSpanRed() { var (context, port) = await StartMdnReceiver(maxBody: 1024); await using var _ = context; using var probe = RouteTelemetryProbe.ForEndpointContaining($"port={port}"); (await PostMdn(port, ("multipart/report; boundary=x", null, new byte[64 * 1024]), expectContinue: true)) .Should().Be(HttpStatusCode.RequestEntityTooLarge); MdnSpan(probe).Status.Should().Be(ActivityStatusCode.Error); } [Fact] public async Task Receiver_ABodyOverTheLimit_MarksTheSpanRed() { var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddToRegistry("recv", Receiver()); context.AddRoutes(r => r.From(As2Dsl.Receive("/in").Host("127.0.0.1").Port(port).ConnectionFactory("recv").MaxRequestBodySize(1024)) .Process(_ => { })); await context.Start(); using var probe = RouteTelemetryProbe.ForEndpointContaining($"port={port}"); (await PostAsync(port, "/in", BuildMessage(new string('X', 64 * 1024), Cert, Cert), expectContinue: true)) .StatusCode.Should().Be(HttpStatusCode.RequestEntityTooLarge); ReceiveSpan(probe).Status.Should().Be(ActivityStatusCode.Error); } } Path: redb-route/tests/redb.Route.Tests.As2/As2TransportSecurityTests.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.As2/As2TransportSecurityTests.cs ---- using System.Net; using System.Net.Sockets; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using AwesomeAssertions; using redb.Route.Abstractions; using redb.Route.As2; using redb.Route.Core; using redb.Route.Http; using As2Dsl = redb.Route.As2.Fluent.As2; namespace redb.Route.Tests.As2; /// /// The AS2 receiver's transport security. Earlier the connector passed useTls to the /// shared host and no certificate with it — there was no server-certificate option at all — so an /// as2s:// receiver opened a PLAINTEXT port while advertised /// https:// to the trading partner as its PartnerUrl. /// public sealed class As2TransportSecurityTests : IDisposable { private readonly List _tempFiles = []; public void Dispose() { foreach (var f in _tempFiles) if (File.Exists(f)) File.Delete(f); } private static int FreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); // A receiver needs an agreement to start; these tests are about its TLS, so the agreement is the smallest one. private static string Agreed(string receiveUri) => receiveUri + "&as2From=us&as2To=them&sign=false&encrypt=false&signedMdn=false"; [Fact] public async Task TlsReceiver_WithoutCertificate_RefusesToStart() { var port = FreePort(); var component = new As2Component(); var endpoint = component.CreateEndpoint( EndpointUriParser.Parse(Agreed(As2Dsl.Receive("/inbound").Host("127.0.0.1").Port(port).Tls()))); var consumer = endpoint.CreateConsumer(Substitute.For()); var act = () => consumer.Start(); (await act.Should().ThrowAsync( "as2s opened a plain socket while PartnerUrl promised https:// to the partner")) .WithMessage("*certificate*"); } [Fact] public async Task TlsReceiver_WithoutCertificate_LeavesNoPlaintextPortOpen() { var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddRoutes(r => r.From(Agreed(As2Dsl.Receive("/inbound").Host("127.0.0.1").Port(port).Tls())).Process(_ => { })); // The context does not propagate a consumer's start failure — one bad route must not stop // the rest — so the observable security property is the one that matters: the port that a // partner would have taken for a TLS endpoint is simply not there. await context.Start(); using var client = new HttpClient(); var plain = () => client.PostAsync($"http://127.0.0.1:{port}/inbound", new StringContent("x")); await plain.Should().ThrowAsync( "this very plain port is what the partner took for a TLS endpoint"); } [Fact] public async Task TlsReceiver_WithCertificate_ActuallyTerminatesTls() { var port = FreePort(); var certPath = WritePfx(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); context.AddRoutes(r => r.From(Agreed(As2Dsl.Receive("/inbound").Host("127.0.0.1").Port(port).Tls(certPath))).Process(_ => { })); await context.Start(); using var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator, }; using var client = new HttpClient(handler); // The AS2 handler will reject the body; what matters here is that the TLS handshake // completed at all, which it could not before there was a certificate to present. var response = await client.PostAsync($"https://127.0.0.1:{port}/inbound", new StringContent("not-as2")); response.Should().NotBeNull(); } [Fact] public async Task TlsReceiver_TakesCertificateFromTheConnectionFactory() { var port = FreePort(); await using var context = new RouteContext(); context.AddComponent(new As2Component()); // The password belongs in the registry, not the route URI — the framework-wide pattern. context.AddToRegistry("partner", new As2ConnectionFactory { As2From = "us", As2To = "them", Sign = false, Encrypt = false, SignedMdn = false, SslCertPath = WritePfx(), }); context.AddRoutes(r => r.From(As2Dsl.Receive("/inbound").Host("127.0.0.1").Port(port) .ConnectionFactory("partner").Tls()) .Process(_ => { })); await context.Start(); using var handler = new HttpClientHandler { ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator, }; using var client = new HttpClient(handler); var response = await client.PostAsync($"https://127.0.0.1:{port}/inbound", new StringContent("not-as2")); response.Should().NotBeNull(); } 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-as2-tls-{Guid.NewGuid():N}.pfx"); File.WriteAllBytes(path, cert.Export(X509ContentType.Pfx)); _tempFiles.Add(path); return path; } } Path: redb-route/tests/redb.Route.Tests.As2/Crypto/As2CryptoEngineTests.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.As2/Crypto/As2CryptoEngineTests.cs ---- using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using AwesomeAssertions; using MimeKit; using MimeKit.Cryptography; using redb.Route.As2.Crypto; namespace redb.Route.Tests.As2.Crypto; /// /// Crypto tests: S/MIME sign/encrypt/compress round-trips across every AS2 profile, MIC determinism /// (RFC 4130 §7.3.1), and negative cases. Certificates are generated in-process — no PFX files in the repo. /// These prove self-consistency; interop against real AS2 implementations is in As2InteropTests. /// public class As2CryptoEngineTests { private static readonly X509Certificate2 OurCert = MakeCert("redb-as2-us"); private static readonly X509Certificate2 PartnerCert = MakeCert("redb-as2-partner"); private readonly As2CryptoEngine _engine = new(); private static MimeEntity Doc(string text = "ISA*00* *00* *ZZ*US~") => new TextPart("plain") { Text = text }; private static string TextOf(MimeEntity e) => ((TextPart)e).Text!; // ── Sign / Verify ──────────────────────────────────────────────────────── [Fact] public void Sign_ThenVerify_SameCert_True() { var signed = _engine.Sign(Doc(), OurCert, "sha-256"); _engine.Verify(signed, OurCert).Should().BeTrue(); } [Fact] public void Sign_ThenVerify_WrongSigner_False() { // Signed by us, but verified as if it should come from the partner → signer fingerprint mismatch. var signed = _engine.Sign(Doc(), OurCert, "sha-256"); _engine.Verify(signed, PartnerCert).Should().BeFalse(); } // ── Encrypt / Decrypt ──────────────────────────────────────────────────── [Fact] public void Encrypt_ThenDecrypt_RestoresContent() { var encrypted = _engine.Encrypt(Doc("secret-edi"), PartnerCert, "aes-128-cbc"); var decrypted = _engine.Decrypt(encrypted, PartnerCert); TextOf(decrypted).Should().Be("secret-edi"); } // ── Compress / Decompress ──────────────────────────────────────────────── [Fact] public void Compress_ThenDecompress_RestoresContent() { var compressed = _engine.Compress(Doc("compress-me")); var restored = _engine.Decompress(compressed); TextOf(restored).Should().Be("compress-me"); } // ── Full profiles ──────────────────────────────────────────────────────── [Fact] public void SignAndEncrypt_ThenDecryptAndVerify() { var signed = _engine.Sign(Doc("po-9001"), OurCert, "sha-256"); var encrypted = _engine.Encrypt(signed, PartnerCert, "aes-256-cbc"); var decrypted = _engine.Decrypt(encrypted, PartnerCert); decrypted.Should().BeAssignableTo(); _engine.Verify((MultipartSigned)decrypted, OurCert).Should().BeTrue(); } [Fact] public void CompressSignEncrypt_FullRoundTrip() { var compressed = _engine.Compress(Doc("full-profile")); var signed = _engine.Sign(compressed, OurCert, "sha-256"); var encrypted = _engine.Encrypt(signed, PartnerCert, "aes-128-cbc"); var decrypted = _engine.Decrypt(encrypted, PartnerCert); decrypted.Should().BeAssignableTo(); _engine.Verify((MultipartSigned)decrypted, OurCert).Should().BeTrue(); // Extract the signed payload (first part of multipart/signed) and decompress it. var inner = ((MultipartSigned)decrypted)[0]; var restored = _engine.Decompress(inner); TextOf(restored).Should().Be("full-profile"); } // ── MIC (RFC 4130 §7.3.1) ──────────────────────────────────────────────── [Fact] public void ComputeMic_IsDeterministic() { var a = _engine.ComputeMic(Doc("same"), "sha-256", includeHeaders: true); var b = _engine.ComputeMic(Doc("same"), "sha-256", includeHeaders: true); a.Matches(b).Should().BeTrue(); a.Algorithm.Should().Be("sha-256"); } [Fact] public void ComputeMic_DifferentContent_DiffersAndParses() { var a = _engine.ComputeMic(Doc("one"), "sha-256", includeHeaders: true); var b = _engine.ComputeMic(Doc("two"), "sha-256", includeHeaders: true); a.Matches(b).Should().BeFalse(); As2Mic.Parse(a.ToString()).Matches(a).Should().BeTrue(); } [Fact] public void ComputeMic_IncludeHeaders_DiffersFromContentOnly() { var withHeaders = _engine.ComputeMic(Doc("body"), "sha-256", includeHeaders: true); var contentOnly = _engine.ComputeMic(Doc("body"), "sha-256", includeHeaders: false); withHeaders.Matches(contentOnly).Should().BeFalse(); } // ── Algorithm matrix ───────────────────────────────────────────────────── [Theory] [InlineData("sha-1", "3des", false)] [InlineData("sha-256", "aes-128-cbc", false)] [InlineData("sha-256", "aes-256-cbc", true)] [InlineData("sha-384", "aes-192-cbc", true)] [InlineData("sha-512", "aes-256-cbc", false)] public void Matrix_CompressSignEncrypt_RoundTripsWithMic(string signAlg, string encAlg, bool compress) { MimeEntity entity = Doc("matrix-payload"); if (compress) entity = _engine.Compress(entity); var micSent = _engine.ComputeMic(entity, signAlg, includeHeaders: true); var signed = _engine.Sign(entity, OurCert, signAlg); var encrypted = _engine.Encrypt(signed, PartnerCert, encAlg); var decrypted = _engine.Decrypt(encrypted, PartnerCert); _engine.Verify((MultipartSigned)decrypted, OurCert).Should().BeTrue(); var inner = ((MultipartSigned)decrypted)[0]; _engine.ComputeMic(inner, signAlg, includeHeaders: true).Matches(micSent).Should().BeTrue(); if (compress) inner = _engine.Decompress(inner); TextOf(inner).Should().Be("matrix-payload"); } // ── Cert generation ────────────────────────────────────────────────────── private static X509Certificate2 MakeCert(string cn) { // The RSA from RSA.Create() is an exportable, in-memory software key. Keep THIS key on the cert via // CopyWithPrivateKey so the Bouncy Castle backend can export its parameters for signing/decryption. // A PKCS#12 round-trip would leave a non-exportable CNG key on .NET 8 (CngKey.Export throws). var rsa = RSA.Create(2048); var req = new CertificateRequest($"CN={cn}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); using var certWithKey = req.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(10)); using var publicOnly = X509CertificateLoader.LoadCertificate(certWithKey.Export(X509ContentType.Cert)); return publicOnly.CopyWithPrivateKey(rsa); } } Path: redb-route/tests/redb.Route.Tests.As2/redb.Route.Tests.As2.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.As2/redb.Route.Tests.As2.csproj ----