using System.IO; using System.Net; using System.Net.Security; using System.Net.Sockets; using System.Security.Authentication; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; namespace Chronos.App.Tests.Library; /// /// A TLS endpoint on loopback with a self-signed certificate no client trusted (a server whose certificate changed since /// sign-in): the client's pinning refuses every handshake, so nothing is ever sent. /// internal sealed class UntrustedTlsEndpoint : IDisposable { private readonly TcpListener _listener = new(IPAddress.Loopback, 0); private readonly X509Certificate2 _certificate; private readonly CancellationTokenSource _stop = new(); private readonly Task _accepting; public UntrustedTlsEndpoint() { using var key = RSA.Create(2048); var request = new CertificateRequest("CN=127.0.0.1", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); using var created = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); // Schannel serves only a certificate whose key it can open: a PKCS #12 round trip gives it one. _certificate = X509CertificateLoader.LoadPkcs12(created.Export(X509ContentType.Pkcs12), null); _listener.Start(); _accepting = Task.Run(AcceptAsync); } public Uri Address => new($"https://127.0.0.1:{((IPEndPoint)_listener.LocalEndpoint).Port}/"); public void Dispose() { _stop.Cancel(); _listener.Stop(); try { _accepting.Wait(TimeSpan.FromSeconds(5)); } catch (AggregateException) { // The loop ends with the listener; how it ended does not matter. } _certificate.Dispose(); _stop.Dispose(); } private async Task AcceptAsync() { while (!_stop.IsCancellationRequested) { TcpClient client; try { client = await _listener.AcceptTcpClientAsync(_stop.Token); } catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException) { return; } using (client) { try { await using var tls = new SslStream(client.GetStream()); await tls.AuthenticateAsServerAsync(new SslServerAuthenticationOptions { ServerCertificate = _certificate }, _stop.Token); } catch (Exception ex) when (ex is AuthenticationException or IOException or OperationCanceledException or SocketException) { // The client refused the certificate: the handshake ends here, as intended. } } } } }