diff --git a/tests/NATS.Client.Core.Tests/TlsFirstTest.cs b/tests/NATS.Client.Core.Tests/TlsFirstTest.cs index 605c30d84..35f48921b 100644 --- a/tests/NATS.Client.Core.Tests/TlsFirstTest.cs +++ b/tests/NATS.Client.Core.Tests/TlsFirstTest.cs @@ -6,17 +6,9 @@ public class TlsFirstTest public TlsFirstTest(ITestOutputHelper output) => _output = output; - [Fact] - public async Task Tls_first_connection() + [SkipIfNatsServer(doesNotSupportTlsFirst: true)] + public async Task Implicit_TLS_connection() { - if (!NatsServer.SupportsTlsFirst()) - { - _output.WriteLine($"TLS first is NOT supported by the server"); - return; - } - - _output.WriteLine($"TLS first is supported by the server"); - await using var server = NatsServer.Start( new NullOutputHelper(), new NatsServerOptsBuilder() @@ -47,4 +39,40 @@ public async Task Tls_first_connection() _output.WriteLine($"Auto TLS connection rejected"); } } + + [Fact] + public async Task Implicit_TLS_fails_when_disabled() + { + await using var server = NatsServer.Start( + new NullOutputHelper(), + new NatsServerOptsBuilder() + .UseTransport(TransportType.Tls, tlsFirst: false) + .Build()); + + var clientOpts = server.ClientOpts(NatsOpts.Default); + + Assert.True(clientOpts.TlsOpts.Mode == TlsMode.Auto); + + // TLS first connection should fail + { + await using var nats = new NatsConnection(clientOpts with { TlsOpts = clientOpts.TlsOpts with { Mode = TlsMode.Implicit } }); + + var exception = await Assert.ThrowsAsync(async () => await nats.ConnectAsync()); + + Assert.Matches(@"can not start to connect nats server", exception.Message); + + _output.WriteLine($"Implicit TLS connection rejected"); + + } + + // Normal TLS connection should work + { + await using var nats = new NatsConnection(clientOpts); + await nats.ConnectAsync(); + var rtt = await nats.PingAsync(); + Assert.True(rtt > TimeSpan.Zero); + Assert.True(nats.ServerInfo!.TlsRequired); + _output.WriteLine($"Explicit TLS connection (RTT: {rtt})"); + } + } } diff --git a/tests/NATS.Client.TestUtilities/NatsServer.cs b/tests/NATS.Client.TestUtilities/NatsServer.cs index dff9f1115..de55600f5 100644 --- a/tests/NATS.Client.TestUtilities/NatsServer.cs +++ b/tests/NATS.Client.TestUtilities/NatsServer.cs @@ -529,3 +529,18 @@ public void WriteLine(string format, params object[] args) { } } + +public sealed class SkipIfNatsServer : FactAttribute +{ + private static readonly bool SupportsTlsFirst; + + static SkipIfNatsServer() => SupportsTlsFirst = NatsServer.SupportsTlsFirst(); + + public SkipIfNatsServer(bool doesNotSupportTlsFirst = false) + { + if (doesNotSupportTlsFirst && !SupportsTlsFirst) + { + Skip = "NATS server doesn't support TLS first"; + } + } +}