using System.Net.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Host.Configuration; namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; [Trait("Feature", "GrpcData")] [Trait("Phase", "P07")] public class GrpcDataTrustRotationTests { [Fact] public void Trust_changes_fingerprint_and_name_mismatch_never_falls_back() { using var key = RSA.Create(2048); var request = new CertificateRequest("CN=localhost", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); using var certificate = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); var policy = new DataConnectionTrustPolicy(1, [certificate]); using var message = new HttpRequestMessage(HttpMethod.Get, "https://localhost"); policy.Validate(message, certificate, null, SslPolicyErrors.RemoteCertificateNameMismatch).ShouldBeFalse(); policy.Validate(message, certificate, null, SslPolicyErrors.None).ShouldBeFalse(); // CN alone is insufficient Should.Throw(() => new DataConnectionTrustPolicy(2, [])); } [Fact] public async Task Trust_version_rotation_and_removal_survive_restart() { var ct = TestContext.Current.CancellationToken; var store = new GrpcDataSecretProvisioningTests.MemoryStore(); var cipher = new GrpcDataSecretProvisioningTests.TestCipher(); var changes = new DataConnectionSecretChangeHandler(); var retired = new List(); changes.ConnectionChanged += retired.Add; using var key = RSA.Create(2048); var request = new CertificateRequest("CN=root", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); using var oldRoot = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); using var newKey = RSA.Create(2048); var newRequest = new CertificateRequest("CN=new", newKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); newRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); using var newRoot = newRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); var policies = new DataConnectionTrustPolicyStore(store, cipher, changes, "pair", "node"); await policies.ApplyScopeAsync(1, ["c"], ct); await policies.SetAsync("c", 1, [oldRoot], 1, ct); var old = await policies.ResolveAsync("c", ct); old.ShouldNotBeNull(); await policies.SetAsync("c", 2, [oldRoot, newRoot], 1, ct); var rotated = await policies.ResolveAsync("c", ct); rotated.ShouldNotBeNull(); rotated.Fingerprint.ShouldNotBe(old.Fingerprint); var restarted = new DataConnectionTrustPolicyStore(store, cipher, changes, "pair", "node"); await restarted.SetAsync("c", 3, [newRoot], 1, ct); using var message = new HttpRequestMessage(HttpMethod.Get, "https://localhost"); var current = await restarted.ResolveAsync("c", ct); current.ShouldNotBeNull(); current.Validate(message, oldRoot, null, SslPolicyErrors.RemoteCertificateChainErrors).ShouldBeFalse(); await restarted.SetAsync("c", 4, [], 1, ct); (await restarted.ResolveAsync("c", ct)).ShouldBeNull(); await Should.ThrowAsync(() => restarted.SetAsync("c", 2, [oldRoot], 1, ct)); retired.Count.ShouldBe(4); } [Fact] public async Task Trust_tombstone_capacity_does_not_evict_prior_versions() { var ct = TestContext.Current.CancellationToken; var store = new GrpcDataSecretProvisioningTests.MemoryStore(); var policies = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), new DataConnectionSecretChangeHandler(), "pair", "node"); await policies.ApplyScopeAsync(1, Enumerable.Range(0, DataConnectionTrustPolicyStore.MaximumConnections).Select(i => "c" + i), ct); for (var i = 0; i < DataConnectionTrustPolicyStore.MaximumConnections; i++) await policies.SetAsync("c" + i, 1, [], 1, ct); await Should.ThrowAsync(() => policies.SetAsync("overflow", 1, [], 1, ct)); await Should.ThrowAsync(() => policies.SetAsync("c0", 1, [], 1, ct)); } [Fact] public void Validation_requires_matching_san_and_trusted_issuer() { using var caKey = RSA.Create(2048); var caRequest = new CertificateRequest("CN=ca", caKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); caRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); caRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign, true)); using var ca = caRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); using var leafKey = RSA.Create(2048); var leafRequest = new CertificateRequest("CN=ignored", leafKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); var san = new SubjectAlternativeNameBuilder(); san.AddDnsName("service.example"); leafRequest.CertificateExtensions.Add(san.Build()); using var leaf = leafRequest.Create(ca, DateTimeOffset.UtcNow.AddHours(-1), DateTimeOffset.UtcNow.AddHours(1), [1, 2, 3]); var policy = new DataConnectionTrustPolicy(1, [ca]); using var good = new HttpRequestMessage(HttpMethod.Get, "https://service.example"); using var bad = new HttpRequestMessage(HttpMethod.Get, "https://wrong.example"); policy.Validate(good, leaf, null, SslPolicyErrors.RemoteCertificateChainErrors).ShouldBeTrue(); policy.Validate(bad, leaf, null, SslPolicyErrors.None).ShouldBeFalse(); } [Fact] public async Task Failed_trust_notification_can_resume_same_version() { var ct = TestContext.Current.CancellationToken; var store = new GrpcDataSecretProvisioningTests.MemoryStore(); var changes = new DataConnectionSecretChangeHandler(); var calls = 0; changes.ConnectionChanged += _ => { calls++; if (calls == 1) throw new InvalidOperationException(); }; var trust = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), changes, "pair", "node"); await trust.ApplyScopeAsync(1, ["c"], ct); await Should.ThrowAsync(() => trust.SetAsync("c", 1, [], 1, ct)); await trust.SetAsync("c", 1, [], 1, ct); calls.ShouldBe(2); } [Fact] public async Task Scoped_trust_churn_reclaims_retired_ids_and_rejects_stale_scope() { var ct = TestContext.Current.CancellationToken; var store = new GrpcDataSecretProvisioningTests.MemoryStore(); var trust = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), new DataConnectionSecretChangeHandler(), "pair", "node"); await trust.ApplyScopeAsync(1, ["first"], ct); await trust.SetAsync("first", 1, [], 1, ct); for (var i = 0; i < DataConnectionTrustPolicyStore.MaximumConnections + 1; i++) { var generation = 2L + i; var id = "c" + i; await trust.ApplyScopeAsync(generation, [id], ct); await trust.SetAsync(id, 1, [], generation, ct); } var latest = 3L + DataConnectionTrustPolicyStore.MaximumConnections; await trust.ApplyScopeAsync(latest, ["first"], ct); trust = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), new DataConnectionSecretChangeHandler(), "pair", "node"); await Should.ThrowAsync(() => trust.SetAsync("first", 999, [], 1, ct)); await trust.SetAsync("first", 1, [], latest, ct); } [Fact] public async Task Failed_retirement_followed_by_reintroduction_cannot_restore_old_ca() { var ct = TestContext.Current.CancellationToken; var store = new GrpcDataSecretProvisioningTests.MemoryStore(); var changes = new DataConnectionSecretChangeHandler(); var trust = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), changes, "pair", "node"); using var key = RSA.Create(2048); var request = new CertificateRequest("CN=ca", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); using var ca = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); await trust.ApplyScopeAsync(1, ["c"], ct); await trust.SetAsync("c", 1, [ca], 1, ct); Action broken = _ => throw new InvalidOperationException("retirement failed"); changes.ConnectionChanged += broken; await Should.ThrowAsync(() => trust.ApplyScopeAsync(2, [], ct)); changes.ConnectionChanged -= broken; trust = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), changes, "pair", "node"); await trust.ApplyScopeAsync(3, ["c"], ct); (await trust.ResolveAsync("c", ct)).ShouldBeNull(); await Should.ThrowAsync(() => trust.SetAsync("c", 999, [ca], 1, ct)); await trust.SetAsync("c", 1, [ca], 3, ct); (await trust.ResolveAsync("c", ct)).ShouldNotBeNull(); } [Fact] public async Task Trust_scope_identifiers_and_owner_node_are_case_insensitive_across_restart() { var ct = TestContext.Current.CancellationToken; var store = new GrpcDataSecretProvisioningTests.MemoryStore(); var cipher = new GrpcDataSecretProvisioningTests.TestCipher(); var changes = new DataConnectionSecretChangeHandler(); var trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "Cluster", "Node"); await trust.ApplyScopeAsync(1, ["Link"], ct); await trust.SetAsync("link", 1, [], 1, ct); trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "cluster", "NODE"); await trust.ApplyScopeAsync(1, ["LINK"], ct); await Should.ThrowAsync(() => trust.SetAsync("LINK", 1, [], 1, ct)); await trust.ApplyScopeAsync(2, [], ct); await Should.ThrowAsync(() => trust.SetAsync("link", 999, [], 1, ct)); await Should.ThrowAsync(() => trust.ApplyScopeAsync(3, ["Link", "link"], ct)); } [Fact] public void A_trusted_server_name_with_client_auth_only_certificate_is_rejected() { using var caKey = RSA.Create(2048); var caRequest = new CertificateRequest("CN=ca", caKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); caRequest.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); caRequest.CertificateExtensions.Add(new X509KeyUsageExtension(X509KeyUsageFlags.KeyCertSign, true)); using var ca = caRequest.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); using var leafKey = RSA.Create(2048); var request = new CertificateRequest("CN=ignored", leafKey, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); var san = new SubjectAlternativeNameBuilder(); san.AddDnsName("service.example"); request.CertificateExtensions.Add(san.Build()); var usages = new OidCollection { new Oid("1.3.6.1.5.5.7.3.2") }; request.CertificateExtensions.Add(new X509EnhancedKeyUsageExtension(usages, true)); using var leaf = request.Create(ca, DateTimeOffset.UtcNow.AddHours(-1), DateTimeOffset.UtcNow.AddHours(1), [4, 5, 6]); using var message = new HttpRequestMessage(HttpMethod.Get, "https://service.example"); new DataConnectionTrustPolicy(1, [ca]).Validate(message, leaf, null, SslPolicyErrors.None).ShouldBeFalse(); } [Fact] public async Task Public_trust_batch_rejects_excess_certificate_count_and_bytes_before_writing() { var ct = TestContext.Current.CancellationToken; var store = new GrpcDataSecretProvisioningTests.MemoryStore(); var policy = new DataConnectionTrustPolicyStore(store, new GrpcDataSecretProvisioningTests.TestCipher(), new DataConnectionSecretChangeHandler(), "pair", "node"); await policy.ApplyScopeAsync(1, ["c"], ct); using var key = RSA.Create(2048); var request = new CertificateRequest("CN=ca", key, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1); request.CertificateExtensions.Add(new X509BasicConstraintsExtension(true, false, 0, true)); request.CertificateExtensions.Add(new X509Extension("1.2.3.4", new byte[16384], false)); using var cert = request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddDays(1)); await Should.ThrowAsync(() => policy.SetBundleAsync([("c", 1, Enumerable.Repeat(cert, DataConnectionTrustPolicyStore.MaximumRootCertificates + 1).ToArray())], 1, ct)); var byteLimitCount = checked((int)(DataConnectionTrustPolicyStore.MaximumTrustBytes / cert.RawData.Length) + 1); byteLimitCount.ShouldBeLessThanOrEqualTo(DataConnectionTrustPolicyStore.MaximumRootCertificates); await Should.ThrowAsync(() => policy.SetBundleAsync([("c", 1, Enumerable.Repeat(cert, byteLimitCount).ToArray())], 1, ct)); await policy.SetAsync("c", 1, [], 1, ct); // rejected batches wrote nothing } }