using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using ZB.MOM.WW.Secrets.DependencyInjection; using ZB.MOM.WW.Secrets.Sqlite; using Xunit; using System.Text; using Shouldly; using ZB.MOM.WW.OtOpcUa.Host.Configuration; using ZB.MOM.WW.Secrets.Abstractions; namespace ZB.MOM.WW.OtOpcUa.Host.Tests.DataConnections; [Trait("Feature", "GrpcData")] [Trait("Phase", "P07")] public class GrpcDataSecretProvisioningTests { [Fact] public async Task Scoped_bundle_is_encrypted_and_survives_restart_without_bundle() { var store = new MemoryStore(); var cipher = new TestCipher(); var changed = new DataConnectionSecretChangeHandler(); var provisioner = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changed, "consumer-cluster", "node-a"); await provisioner.SetScopeAsync(1, new Dictionary { ["connection"] = "secret:data/key" }, TestContext.Current.CancellationToken); await provisioner.ApplyAsync(new DataConnectionCredentialBundle("consumer-cluster", "node-a", 1, [new DataConnectionCredentialEntry("connection", "secret:data/key", "bearer-value", false)], ScopeVersion: 1), TestContext.Current.CancellationToken); var row = await store.GetAsync(new SecretName("data/key"), TestContext.Current.CancellationToken); row.ShouldNotBeNull(); Encoding.UTF8.GetString(row.Ciphertext).ShouldNotContain("bearer-value"); var restarted = new DataConnectionCredentialResolver(store, cipher, "consumer-cluster", "node-a"); var resolved = await restarted.ResolveAsync("connection", TestContext.Current.CancellationToken); resolved.ShouldNotBeNull(); resolved.Value.ShouldBe("bearer-value"); resolved.Version.ShouldBe(1); } [Fact] public async Task Replica_and_pair_scopes_are_independent() { var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); var a = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair-a", "a1"); var b = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair-a", "a2"); await a.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key-a" }, ct); await b.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key-b" }, ct); await a.ApplyAsync(new("pair-a", "a1", 1, [new("c", "secret:data/key-a", "a", false)], ScopeVersion: 1), ct); (await new DataConnectionCredentialResolver(store, cipher, "pair-a", "a2").ResolveAsync("c", ct)).ShouldBeNull(); (await new DataConnectionCredentialResolver(store, cipher, "pair-b", "a1").ResolveAsync("c", ct)).ShouldBeNull(); await b.ApplyAsync(new("pair-a", "a2", 1, [new("c", "secret:data/key-b", "b", false)], ScopeVersion: 1), ct); (await new DataConnectionCredentialResolver(store, cipher, "pair-a", "a2").ResolveAsync("c", ct))!.Value.ShouldBe("b"); } [Fact] public async Task Failed_store_write_leaves_pending_credential_unavailable() { 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", "old", false)], ScopeVersion: 1), ct); store.FailUpsertName = "data/key"; await Should.ThrowAsync(() => p.ApplyAsync(new("pair", "node", 2, [new("c", "secret:data/key", "new", false)], ScopeVersion: 1), ct)); (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct)).ShouldBeNull(); } [Fact] public async Task Real_sqlite_store_keeps_ciphertext_and_recovers_after_provider_restart() { var ct = TestContext.Current.CancellationToken; var directory = Directory.CreateTempSubdirectory("data-credentials-"); try { var keyFile = Path.Combine(directory.FullName, "master-key"); var db = Path.Combine(directory.FullName, "secrets.db"); await File.WriteAllTextAsync(keyFile, Convert.ToBase64String(System.Security.Cryptography.RandomNumberGenerator.GetBytes(32)), ct); var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary { ["Secrets:SqlitePath"] = db, ["Secrets:MasterKey:Source"] = "File", ["Secrets:MasterKey:FilePath"] = keyFile, ["Secrets:RunMigrationsOnStartup"] = "false", }).Build(); await using (var first = new ServiceCollection().AddLogging().AddZbSecrets(config, "Secrets").BuildServiceProvider()) { await first.GetRequiredService().MigrateAsync(ct); var provisioner = new DataConnectionSecretProvisioner(first.GetRequiredService(), first.GetRequiredService(), new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "cluster", "node"); await provisioner.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); await provisioner.ApplyAsync(new("cluster", "node", 1, [new("c", "secret:data/key", "private-bearer-value", false)], ScopeVersion: 1), ct); } var database = await File.ReadAllBytesAsync(db, ct); Encoding.UTF8.GetString(database).ShouldNotContain("private-bearer-value"); await using var second = new ServiceCollection().AddLogging().AddZbSecrets(config, "Secrets").BuildServiceProvider(); var resolver = new DataConnectionCredentialResolver(second.GetRequiredService(), second.GetRequiredService(), "cluster", "node"); (await resolver.ResolveAsync("c", ct))!.Value.ShouldBe("private-bearer-value"); } finally { directory.Delete(true); } } [Fact] public async Task Interrupted_version_can_resume_only_with_the_same_payload() { 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 bundle = new DataConnectionCredentialBundle("pair", "node", 1, [new("c", "secret:data/key", "intended", false)], ScopeVersion: 1); store.FailUpsertName = "data/key"; await Should.ThrowAsync(() => p.ApplyAsync(bundle, ct)); store.FailUpsertName = null; var restarted = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); await Should.ThrowAsync(() => restarted.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "different", false)], ScopeVersion: 1), ct)); await restarted.ApplyAsync(bundle, ct); (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct))!.Value.ShouldBe("intended"); } [Fact] public async Task Scope_and_historical_reference_capacity_fail_closed() { 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 tooMany = Enumerable.Range(0, DataConnectionSecretProvisioner.MaximumReferences + 1).ToDictionary(i => "c" + i, i => "secret:data/key" + i); await Should.ThrowAsync(() => p.SetScopeAsync(1, tooMany, ct)); } [Fact] public async Task Replaced_secret_cannot_be_resolved_under_a_committed_version() { 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"); await p.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); await p.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "original", false)], ScopeVersion: 1), ct); store.Rows["data/key"] = cipher.Encrypt(new SecretName("data/key"), "replacement", SecretContentType.Text); (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct)).ShouldBeNull(); await Should.ThrowAsync(() => p.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "original", false)], ScopeVersion: 1), ct)); } [Fact] public async Task Completed_bundle_replay_after_restart_is_idempotent_but_changed_payload_is_rejected() { var ct = TestContext.Current.CancellationToken; var store = new MemoryStore(); var cipher = new TestCipher(); var changes = new DataConnectionSecretChangeHandler(); var notices = 0; changes.ConnectionChanged += _ => notices++; var p = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); await p.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); var bundle = new DataConnectionCredentialBundle("pair", "node", 1, [new("c", "secret:data/key", "original", false)], ScopeVersion: 1); await p.ApplyAsync(bundle, ct); var restarted = new DataConnectionSecretProvisioner(store, cipher, new NoopInvalidator(), changes, "pair", "node"); await restarted.ApplyAsync(bundle, ct); notices.ShouldBe(1); (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct))!.Value.ShouldBe("original"); await Should.ThrowAsync(() => restarted.ApplyAsync(bundle with { Entries = [new("c", "secret:data/key", "different", false)] }, ct)); } [Fact] public async Task Canonical_reference_uses_physical_secret_name_for_store_and_resolution() { 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"); await p.SetScopeAsync(1, new Dictionary { ["c"] = "secret:data/key" }, ct); await p.ApplyAsync(new("pair", "node", 1, [new("c", "secret:data/key", "bearer", false)], 1), ct); (await store.GetAsync(new SecretName("data/key"), ct)).ShouldNotBeNull(); (await new DataConnectionCredentialResolver(store, cipher, "pair", "node").ResolveAsync("c", ct))!.Value.ShouldBe("bearer"); } [Fact] public void Pinned_secret_name_normalizes_case_so_wire_aliases_must_not_share_a_row() { new SecretName("data/Key").Value.ShouldBe(new SecretName("data/key").Value); } [Fact] public async Task Canonical_scope_rejects_uppercase_physical_secret_aliases() { var ct = TestContext.Current.CancellationToken; var p = new DataConnectionSecretProvisioner(new MemoryStore(), new TestCipher(), new NoopInvalidator(), new DataConnectionSecretChangeHandler(), "pair", "node"); await Should.ThrowAsync(() => p.SetScopeAsync(1, new Dictionary { ["a"] = "secret:data/Key", ["b"] = "secret:data/key" }, ct)); } internal sealed class NoopInvalidator : ISecretCacheInvalidator { public void Invalidate(SecretName name) { } } internal sealed class TestCipher : ISecretCipher { public StoredSecret Encrypt(SecretName name, string plaintext, SecretContentType contentType) => new() { Name = name, ContentType = contentType, Ciphertext = Encoding.UTF8.GetBytes(plaintext).Select(b => (byte)(b ^ 0x5a)).ToArray(), Nonce = [], Tag = [], WrappedDek = [], WrapNonce = [], WrapTag = [], KekId = "test", Revision = 0, CreatedUtc = DateTimeOffset.UtcNow, UpdatedUtc = DateTimeOffset.UtcNow, }; public string Decrypt(StoredSecret secret) => Encoding.UTF8.GetString(secret.Ciphertext.Select(b => (byte)(b ^ 0x5a)).ToArray()); public StoredSecret Rewrap(StoredSecret secret, IMasterKeyProvider oldKek, IMasterKeyProvider newKek) => throw new NotSupportedException(); } internal sealed class MemoryStore : ISecretStore { public Dictionary Rows { get; } = new(); public string? FailUpsertName { get; set; } public bool FailDelete { get; set; } public Task GetAsync(SecretName name, CancellationToken ct) => Task.FromResult(Rows.GetValueOrDefault(name.Value)); public Task UpsertAsync(StoredSecret row, CancellationToken ct) { if (row.Name.Value == FailUpsertName) throw new InvalidOperationException("store unavailable"); Rows[row.Name.Value] = row; return Task.CompletedTask; } public Task DeleteAsync(SecretName name, string? actor, CancellationToken ct) => FailDelete ? throw new InvalidOperationException("delete unavailable") : Task.FromResult(Rows.Remove(name.Value)); public Task> ListAsync(bool includeDeleted, CancellationToken ct) => Task.FromResult>([]); public Task> GetManifestAsync(CancellationToken ct) => throw new NotSupportedException(); public Task ApplyReplicatedAsync(StoredSecret row, CancellationToken ct) => throw new NotSupportedException(); public Task ApplyRewrapAsync(StoredSecret row, byte[] expectedCurrentWrappedDek, CancellationToken ct) => throw new NotSupportedException(); } }