Path: redb-route/tests/redb.Route.Tests.Tcp/TcpTransportSecurityTests.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.Tcp/TcpTransportSecurityTests.cs ---- using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using redb.Route.Abstractions; using redb.Route.Core; using redb.Route.Tcp; namespace redb.Route.Tests.Tcp; /// /// The TCP server's TLS setup. It used to bind and accept happily with ssl=true and no /// certificate, then kill every accepted connection deep in the accept loop with an /// ArgumentNullException on SslCertPath! — a type not in its catch list. No plaintext /// ever flowed (the stream becomes an SslStream only after a successful handshake), but the failure /// belongs at the bind, with a message about the certificate, the way the shared HTTP host does it. /// The certificate is also loaded once at start now, not re-read from disk per connection. /// public sealed class TcpTransportSecurityTests : IAsyncLifetime { private readonly List _consumers = []; private readonly List _producers = []; private readonly List _tempFiles = []; public Task InitializeAsync() => Task.CompletedTask; public async Task DisposeAsync() { foreach (var p in _producers) await p.Stop(); foreach (var c in _consumers) await c.Stop(); foreach (var f in _tempFiles) if (File.Exists(f)) File.Delete(f); } private static int GetFreePort() => global::redb.Route.Tests.Shared.TestPorts.Next(); private TcpConsumer CreateConsumer(int port, Dictionary parameters, IProcessor? processor = null, string host = "127.0.0.1") { var component = new TcpComponent(); var uri = new EndpointUri("tcp", $"/{host}:{port}", $"tcp:{host}:{port}", parameters); var endpoint = (TcpEndpoint)component.CreateEndpoint(uri); var consumer = new TcpConsumer(endpoint, processor ?? Substitute.For(), endpoint.EndpointOptions); _consumers.Add(consumer); return consumer; } private TcpProducer CreateProducer(int port, Dictionary parameters, string host = "127.0.0.1") { var component = new TcpComponent(); var uri = new EndpointUri("tcp", $"/{host}:{port}", $"tcp:{host}:{port}", parameters); var endpoint = (TcpEndpoint)component.CreateEndpoint(uri); var producer = (TcpProducer)endpoint.CreateProducer(); _producers.Add(producer); return producer; } [Fact] public async Task TlsConsumer_WithoutCertificate_RefusesToStart() { var port = GetFreePort(); var consumer = CreateConsumer(port, new Dictionary { ["ssl"] = "true" }); var act = () => consumer.Start(); (await act.Should().ThrowAsync( "failing every connection with an ArgumentNullException is not the way to report a missing certificate")) .WithMessage("*certificate*"); } [Fact] public async Task TlsConsumer_WithoutCertificate_LeavesNoListeningPort() { var port = GetFreePort(); var consumer = CreateConsumer(port, new Dictionary { ["ssl"] = "true" }); var start = () => consumer.Start(); await start.Should().ThrowAsync(); using var client = new TcpClient(); var connect = () => client.ConnectAsync(IPAddress.Loopback, port); await connect.Should().ThrowAsync( "the listener accepted connections only to kill them at once - from outside the port looked alive"); } [Fact] public async Task TlsConsumer_WithCertificate_CompletesTheHandshakeAndReceives() { var port = GetFreePort(); var received = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.TrySetResult(ci.Arg().In.Body?.ToString() ?? ""); return Task.CompletedTask; }); var consumer = CreateConsumer(port, new Dictionary { ["ssl"] = "true", ["sslCertPath"] = WritePfx(), ["framing"] = "TextLine", }, processor); await consumer.Start(); using var client = new TcpClient(); await client.ConnectAsync(IPAddress.Loopback, port); await using var ssl = new SslStream(client.GetStream(), leaveInnerStreamOpen: false, (_, _, _, _) => true); await ssl.AuthenticateAsClientAsync("localhost"); var payload = Encoding.UTF8.GetBytes("over-tls\n"); await ssl.WriteAsync(payload); await ssl.FlushAsync(); (await received.Task.WaitAsync(TimeSpan.FromSeconds(10))).Should().Be("over-tls"); } [Fact] public async Task TlsConsumer_ServesManyConnections_FromOneLoadOfTheCertificate() { var port = GetFreePort(); var certPath = WritePfx(); var consumer = CreateConsumer(port, new Dictionary { ["ssl"] = "true", ["sslCertPath"] = certPath, ["framing"] = "TextLine", }); await consumer.Start(); // The PFX is gone from disk after the start. Every connection used to re-read it, so the // second client could never have completed a handshake. File.Delete(certPath); for (var i = 0; i < 2; i++) { using var client = new TcpClient(); await client.ConnectAsync(IPAddress.Loopback, port); await using var ssl = new SslStream(client.GetStream(), leaveInnerStreamOpen: false, (_, _, _, _) => true); var handshake = () => ssl.AuthenticateAsClientAsync("localhost"); await handshake.Should().NotThrowAsync( "the certificate is read once at start, not for every accepted connection"); } } // ── Bind address: the consumer parsed the host, the producer resolved it ── [Fact] public async Task Consumer_OnLocalhost_Starts() { var port = GetFreePort(); var consumer = CreateConsumer(port, new Dictionary { ["framing"] = "TextLine" }, host: "localhost"); await consumer.Start(); using var client = new TcpClient(); await client.ConnectAsync("localhost", port); client.Connected.Should().BeTrue( "IPAddress.Parse(\"localhost\") brought the consumer down with a FormatException, though the producer resolves the same name"); } [Fact] public async Task Consumer_OnUnresolvableHost_FailsWithANamedError() { var port = GetFreePort(); var consumer = CreateConsumer(port, [], host: "no-such-host.invalid"); var act = () => consumer.Start(); (await act.Should().ThrowAsync()).WithMessage("*no-such-host.invalid*"); } // ── Producer: reaching a server with a self-signed certificate ── [Fact] public async Task Producer_TrustAllCertificates_ReachesASelfSignedServer() { var port = GetFreePort(); var received = new TaskCompletionSource(); var processor = Substitute.For(); processor.Process(Arg.Any(), Arg.Any()) .Returns(ci => { received.TrySetResult(ci.Arg().In.Body?.ToString() ?? ""); return Task.CompletedTask; }); var consumer = CreateConsumer(port, new Dictionary { ["ssl"] = "true", ["sslCertPath"] = WritePfx(), ["framing"] = "TextLine", }, processor); await consumer.Start(); var producer = CreateProducer(port, new Dictionary { ["ssl"] = "true", ["trustAllCertificates"] = "true", ["sslTargetHost"] = "localhost", ["framing"] = "TextLine", }); await producer.Start(); await producer.Process(new Exchange(new Message("self-signed"))); (await received.Task.WaitAsync(TimeSpan.FromSeconds(10))).Should().Be("self-signed", "the producer had no way at all to accept a self-signed certificate: staging is unreachable"); } [Fact] public async Task Producer_WithoutTrustAll_RefusesASelfSignedServer() { var port = GetFreePort(); var consumer = CreateConsumer(port, new Dictionary { ["ssl"] = "true", ["sslCertPath"] = WritePfx(), ["framing"] = "TextLine", }); await consumer.Start(); var producer = CreateProducer(port, new Dictionary { ["ssl"] = "true", ["sslTargetHost"] = "localhost", ["framing"] = "TextLine", }); var act = () => producer.Start(); // The specific type matters: ThrowAsync passed on ANY failure (a dead consumer, // a socket error) and could not tell "refused the certificate" from "never connected". await act.Should().ThrowAsync( "turning off the certificate check must be an explicit decision, not the default behaviour"); } // ── Producer mTLS: presenting a client certificate ── [Fact] public async Task Producer_PresentsClientCertificate_WhenTheServerAsksForOne() { var port = GetFreePort(); var serverCert = LoadPfx(WritePfx()); var clientCertPath = WritePfx("tcp-client"); // A raw mTLS server: this connector's own consumer does not request client certificates // (AuthenticateAsServerAsync(cert) alone), so the counterpart here is a plain SslStream. using var listener = new TcpListener(IPAddress.Loopback, port); listener.Start(); var presented = new TaskCompletionSource(); var accept = Task.Run(async () => { using var server = await listener.AcceptTcpClientAsync(); await using var ssl = new SslStream(server.GetStream(), leaveInnerStreamOpen: false, (_, _, _, _) => true); try { await ssl.AuthenticateAsServerAsync(serverCert, clientCertificateRequired: true, checkCertificateRevocation: false); presented.TrySetResult(ssl.RemoteCertificate?.Subject); } catch (Exception ex) { presented.TrySetException(ex); } }); var producer = CreateProducer(port, new Dictionary { ["ssl"] = "true", ["trustAllCertificates"] = "true", ["sslTargetHost"] = "localhost", ["clientCertPath"] = clientCertPath, ["framing"] = "TextLine", }); await producer.Start(); (await presented.Task.WaitAsync(TimeSpan.FromSeconds(10))) .Should().Contain("tcp-client", "the producer could not present a client certificate at all - an mTLS server was unreachable"); await accept; listener.Stop(); serverCert.Dispose(); } private static X509Certificate2 LoadPfx(string path) => X509CertificateLoader.LoadPkcs12FromFile(path, null); private string WritePfx(string cn = "localhost") { using var rsa = RSA.Create(2048); var request = new CertificateRequest($"CN={cn}", 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-tcp-tls-{Guid.NewGuid():N}.pfx"); File.WriteAllBytes(path, cert.Export(X509ContentType.Pfx)); _tempFiles.Add(path); return path; } }