using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; using Microsoft.Extensions.DependencyInjection; using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime; using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config; using ZB.MOM.WW.Secrets.Abstractions; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Host.Configuration; using static ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections.GrpcDataSecretProvisioningTests; namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; [Trait("Feature", "GrpcData")] [Trait("Phase", "P07")] public class GrpcDataCredentialRetirementTests { [Fact] public async Task Removal_persists_scope_and_stale_bundle_cannot_resurrect_after_restart() { var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); var provisioner = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "cluster", "node"); await provisioner.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); var bundle = new DataConnectionCredentialBundle("cluster", "node", 1, [new("c", "secret:data/key", "value", false)], ScopeVersion: 1); await provisioner.ApplyAsync(bundle, ct); await provisioner.SetScopeAsync(2, new Dictionary(), ct); var restarted = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "cluster", "node"); await Should.ThrowAsync(() => restarted.ApplyAsync(bundle, ct)); (await new DataConnectionCredentialResolver(store, cipher, "cluster", "node").ResolveAsync("c", ct)).ShouldBeNull(); } [Fact] public async Task Shared_reference_is_retained_until_last_scope_is_removed() { var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); await p.SetScopeAsync(1, new Dictionary { ["a"] = "secret:data/key", ["b"] = "secret:data/key" }, ct); await p.ApplyAsync(new("pair", "node", 1, [new("a", "secret:data/key", "secret", false)], ScopeVersion: 1), ct); await p.SetScopeAsync(2, new Dictionary { ["b"] = "secret:data/key" }, ct); (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("b", ct))!.Value.ShouldBe("secret"); await p.SetScopeAsync(3, new Dictionary(), ct); store.Rows.ContainsKey("data/key").ShouldBeFalse(); await Should.ThrowAsync(() => p.SetScopeAsync(2, new Dictionary(), ct)); } [Fact] public async Task Reintroducing_scope_does_not_reactivate_a_previously_retired_reference() { var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); var scope = new Dictionary { ["c"] = "secret:data/key" }; await p.SetScopeAsync(1, scope, ct); var old = new DataConnectionCredentialBundle("pair", "node", 1, [new("c", "secret:data/key", "old", false)], ScopeVersion: 1); await p.ApplyAsync(old, ct); var staleRow = store.Rows["data/key"]; await p.SetScopeAsync(2, new Dictionary(), ct); // A stale replicated row or failed external deletion must not bypass the tombstone. store.Rows["data/key"] = staleRow; await p.SetScopeAsync(3, scope, ct); await p.SetScopeAsync(3, scope, ct); // unchanged applied artifact can be replayed on restart await Should.ThrowAsync(() => p.SetScopeAsync(3, new Dictionary(), ct)); (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct)).ShouldBeNull(); await Should.ThrowAsync(() => p.ApplyAsync(old, ct)); await p.ApplyAsync(new("pair", "node", 2, [new("c", "secret:data/key", "new", false)], ScopeVersion: 3), ct); (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct))!.Value.ShouldBe("new"); } [Fact] public async Task Failed_deletion_is_retried_after_restart_with_same_scope_version() { var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); await p.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); await p.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "secret", false)], ScopeVersion: 1), ct); store.FailDelete = true; await Should.ThrowAsync(() => p.SetScopeAsync(2, new Dictionary(), ct)); (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct)).ShouldBeNull(); store.FailDelete = false; var restarted = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); await restarted.SetScopeAsync(2, new Dictionary(), ct); store.Rows.ContainsKey("data/key").ShouldBeFalse(); } [Fact] public void A_throwing_retirement_observer_does_not_prevent_other_observers_from_draining() { var changes = new DataConnectionSecretChangeHandler(); var observed = new List(); changes.ConnectionChanged += _ => throw new InvalidOperationException("broken observer"); changes.ConnectionChanged += observed.Add; Should.Throw(() => changes.NotifyConnectionChanged("c")); observed.ShouldBe(["c"]); } [Fact] public async Task Failed_scope_notification_is_retried_on_same_version() { var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); await p.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); var calls = 0; Action observer = _ => { calls++; if (calls == 1) throw new InvalidOperationException(); }; changes.ConnectionChanged += observer; await Should.ThrowAsync(() => p.SetScopeAsync(2, new Dictionary(), ct)); await p.SetScopeAsync(2, new Dictionary(), ct); calls.ShouldBe(2); } [Fact] public async Task Scope_generation_allows_reference_churn_without_stale_bundle_resurrection() { var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "pair", "node"); var old = new DataConnectionCredentialBundle("pair", "node", 1, [new("c", "secret:data/key", "old", false)], ScopeVersion: 1); await p.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); await p.ApplyAsync(old, ct); for (var i = 0; i < DataConnectionSecretProvisioner.MaximumReferences + 1; i++) { var generation = 2L + i; var reference = "secret:data/churn" + i; await p.SetScopeAsync(generation, new Dictionary { ["c"] = reference }, ct); await p.ApplyAsync(new("pair", "node", 1, [new("c", reference, "value", false)], ScopeVersion: generation), ct); } var latest = 3L + DataConnectionSecretProvisioner.MaximumReferences; await p.SetScopeAsync(latest, new Dictionary { ["c"] = "secret:data/key" }, ct); p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "pair", "node"); await Should.ThrowAsync(() => p.ApplyAsync(old with { Version = 999 }, ct)); await p.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "new", false)], ScopeVersion: latest), ct); (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct))!.Value.ShouldBe("new"); } [Fact] public async Task Scope_removal_between_eligibility_and_observation_does_not_leak_id() { var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); await p.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); var trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "pair", "node"); await trust.ApplyScopeAsync(1, ["c"], ct); using var provider = new DataConnectionSecurityProvider(new DataConnectionCredentialResolver(store, cipher, "pair", "node"), trust, changes); var eligible = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var resume = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); provider.AfterEligibilityForTest = async () => { eligible.SetResult(); await resume.Task; }; var resolving = provider.ResolveAsync("c", new Uri("https://example.test"), ct).AsTask(); await eligible.Task.WaitAsync(ct); await p.SetScopeAsync(2, new Dictionary(), ct); resume.SetResult(); (await resolving).ShouldBeNull(); provider.ObservedCountForTest.ShouldBe(0); } [Fact] public async Task Mixed_case_scope_and_bundle_reuse_one_durable_generation_floor_after_restart() { var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "Cluster", "Node"); var central = ZB.MOM.WW.OtOpcUa.Configuration.Validation.DataConnectionScopeRevision.Advance(0, null, [new ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection { Enabled = true, ClusterId = "Cluster", DataConnectionId = "Link", ConsumerNodeIds = ["Node"], SecretReference = "secret:data/key" }]); var same = ZB.MOM.WW.OtOpcUa.Configuration.Validation.DataConnectionScopeRevision.Advance(central.Version, central.Fingerprint, [new ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection { Enabled = true, ClusterId = "cluster", DataConnectionId = "link", ConsumerNodeIds = ["node"], SecretReference = "secret:data/key" }]); same.Version.ShouldBe(central.Version); await p.SetScopeAsync(central.Version, new Dictionary { ["Link"] = "secret:data/key" }, ct); await p.ApplyAsync(new("cluster", "node", 1, [new("LINK", "secret:data/key", "token", false)], ScopeVersion: 1), ct); var restarted = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "CLUSTER", "NODE"); await restarted.SetScopeAsync(1, new Dictionary { ["link"] = "secret:data/key" }, ct); (await new DataConnectionCredentialResolver(store, cipher, "cluster", "NODE").ResolveAsync("lInK", ct))!.Value.ShouldBe("token"); await restarted.SetScopeAsync(2, new Dictionary(), ct); await Should.ThrowAsync(() => p.SetScopeAsync(1, new Dictionary { ["Link"] = "secret:data/key" }, ct)); await Should.ThrowAsync(() => restarted.ApplyAsync(new("cluster", "node", 999, [new("LINK", "secret:data/other", "token", false)], ScopeVersion: 1), ct)); } [Fact] public async Task Scope_rejects_duplicate_connection_ids_that_differ_only_by_case() { var ct = TestContext.Current.CancellationToken; var p = new DataConnectionSecretProvisioner(new MemoryStore(), new TestCipher(), new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "cluster", "node"); await Should.ThrowAsync(() => p.SetScopeAsync(1, new Dictionary { ["Link"] = "secret:data/a", ["link"] = "secret:data/b" }, ct)); } [Fact] public async Task Invalidator_attempts_galaxy_and_data_even_when_inner_throws() { var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var directory = new GalaxyAckIdentityDirectory(store, TimeSpan.FromSeconds(30), TimeSpan.FromMinutes(2)); (await directory.RefreshAsync(ct)).ShouldBeTrue(); const string key = "0a1b2c3d4e5f6071"; directory.GetPresence(key).ShouldBe(GalaxyAckIdentityPresence.Absent); var changes = new DataConnectionSecretChangeHandler(); var called = 0; changes.SecretChanged += _ => called++; var invalidator = new SecretChangeSignallingInvalidator(new ThrowingInvalidator(), directory, changes); Should.Throw(() => invalidator.Invalidate(new SecretName(GalaxyAckIdentitySecrets.UserSecretName(key)))); called.ShouldBe(1); directory.GetPresence(key).ShouldBe(GalaxyAckIdentityPresence.Unknown); } [Fact] public void Registration_composes_the_lightweight_handler_without_replacing_inner() { var services = new ServiceCollection(); var inner = new CountingInvalidator(); services.AddSingleton(inner); services.AddSingleton(); SecretsRegistration.DecorateCacheInvalidator(services); using var provider = services.BuildServiceProvider(); var changed = 0; provider.GetRequiredService().SecretChanged += _ => changed++; provider.GetRequiredService().Invalidate(new SecretName("data/key")); inner.Count.ShouldBe(1); changed.ShouldBe(1); } [Fact] public async Task Composed_invalidation_retires_only_connections_that_reference_the_changed_secret() { var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); var trust = new DataConnectionTrustPolicyStore(store, cipher, changes, "pair", "node"); using var security = new DataConnectionSecurityProvider(new DataConnectionCredentialResolver(store, cipher, "pair", "node"), trust, changes); await using var runtime = new DataConnectionDeploymentRuntime("node", "pair", security, new DataConnectionScopeActivator(p, trust), 4); DataConnection Definition(string id, string reference) => new() { DataConnectionId = id, ClusterId = "pair", Revision = 1, Enabled = true, ConsumerNodeIds = ["node"], TargetMode = DataTargetMode.Node, ExpectedClusterId = "target", ExpectedNodeId = "remote", Endpoints = ["https://remote.example:8443"], SecretReference = reference, SecretScopeClusterId = "pair", AllowedOperations = DataOperations.Read }; runtime.Apply(new DataConnectionDeploymentSnapshot(1, "rev", [Definition("a", "secret:data/a"), Definition("shared", "secret:data/a"), Definition("b", "secret:data/b")])); using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct); deadline.CancelAfter(TimeSpan.FromSeconds(5)); while (!runtime.CurrentScopeReady) await Task.Delay(10, deadline.Token); await p.ApplyAsync(new("pair", "node", 1, [new("a", "secret:data/a", "first", false), new("b", "secret:data/b", "second", false)], 1), ct); store.Rows.ContainsKey("data/a").ShouldBeTrue(); store.Rows.ContainsKey("data/b").ShouldBeTrue(); 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.SetBundleAsync([("a", 1, [ca]), ("shared", 1, [ca]), ("b", 1, [ca])], 1, ct); DataConnectionDeploymentLease? a = null, shared = null, b = null; while (!(runtime.TryAcquire("a", out a) && runtime.TryAcquire("shared", out shared) && runtime.TryAcquire("b", out b))) { a?.Dispose(); shared?.Dispose(); b?.Dispose(); a = null; shared = null; b = null; await Task.Delay(10, deadline.Token); } using (a!) using (shared!) using (b!) { var invalidator = new SecretChangeSignallingInvalidator(new NoopInvalidator(), null, changes); invalidator.Invalidate(new SecretName("otopcua/apikeys/unrelated")); a!.CancellationToken.IsCancellationRequested.ShouldBeFalse(); shared!.CancellationToken.IsCancellationRequested.ShouldBeFalse(); b!.CancellationToken.IsCancellationRequested.ShouldBeFalse(); invalidator.Invalidate(new SecretName("data/a")); a.CancellationToken.IsCancellationRequested.ShouldBeTrue(); shared.CancellationToken.IsCancellationRequested.ShouldBeTrue(); b.CancellationToken.IsCancellationRequested.ShouldBeFalse(); } } private sealed class ThrowingInvalidator : ISecretCacheInvalidator { public void Invalidate(SecretName name) => throw new InvalidOperationException("failed"); } private sealed class CountingInvalidator : ISecretCacheInvalidator { public int Count; public void Invalidate(SecretName name) => Count++; } }