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("