using Bunit; using Bunit.TestDoubles; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Web; using Microsoft.AspNetCore.Components.Authorization; using System.Security.Claims; using Microsoft.Extensions.DependencyInjection; using ZB.MOM.WW.Audit; using ZB.MOM.WW.Secrets.Abstractions; using ZB.MOM.WW.Secrets.Ui.Components; using ZB.MOM.WW.Secrets.Ui.Tests.Fakes; namespace ZB.MOM.WW.Secrets.Ui.Tests; public class SecretEditorTests : BunitContext { private const string EnteredValue = "sup3r-s3cret-value!"; private (RecordingSecretStore Store, CapturingAuditWriter Audit, FakeCipher Cipher) RegisterServices() { var store = new RecordingSecretStore(); var audit = new CapturingAuditWriter(); var cipher = new FakeCipher(); Services.AddSingleton(store); Services.AddSingleton(audit); Services.AddSingleton(cipher); return (store, audit, cipher); } [Fact] public void SecretEditor_Add_EncryptsAndUpserts() { var (store, audit, cipher) = RegisterServices(); var auth = this.AddAuthorization(); auth.SetAuthorized("carol"); auth.SetPolicies(SecretsAuthorization.ManagePolicy); var cut = Render(p => p .Add(c => c.OnSaved, () => { })); // The value control is a masked password input. var valueInput = cut.Find("[data-testid=secret-value]"); Assert.Equal("password", valueInput.GetAttribute("type")); cut.Find("[data-testid=secret-name]").Change("app/thing"); cut.Find("[data-testid=secret-description]").Change("A thing"); cut.Find("[data-testid=secret-content-type]").Change(nameof(SecretContentType.Json)); valueInput.Change(EnteredValue); cut.Find("[data-testid=editor-submit]").Click(); // Exactly one upsert, round-tripping to the entered value under the entered name. Assert.Single(store.Upserts); StoredSecret row = store.Upserts[0]; Assert.Equal("app/thing", row.Name.Value); Assert.Equal(SecretContentType.Json, row.ContentType); Assert.Equal("A thing", row.Description); Assert.Equal("carol", row.UpdatedBy); Assert.Equal("carol", row.CreatedBy); Assert.Equal(EnteredValue, cipher.Decrypt(row)); // A single secret.add audit was written, Success, correct target/actor, and NO value leak. Assert.Single(audit.Events); AuditEvent evt = audit.Events[0]; Assert.Equal("secret.add", evt.Action); Assert.Equal(AuditOutcome.Success, evt.Outcome); Assert.Equal("Secrets", evt.Category); Assert.Equal("app/thing", evt.Target); Assert.Equal("carol", evt.Actor); AssertNoValueLeak(evt); } [Fact] public void SecretEditor_Rotate_PreservesName_Overwrites() { var (store, audit, cipher) = RegisterServices(); var name = new SecretName("db/primary"); var auth = this.AddAuthorization(); auth.SetAuthorized("dave"); auth.SetPolicies(SecretsAuthorization.ManagePolicy); var cut = Render(p => p .Add(c => c.ExistingName, name) .Add(c => c.OnSaved, () => { })); // In rotate mode the name field is read-only and shows the existing name. var nameInput = cut.Find("[data-testid=secret-name]"); Assert.True(nameInput.HasAttribute("readonly")); Assert.Equal("db/primary", nameInput.GetAttribute("value")); cut.Find("[data-testid=secret-value]").Change("rotated-value"); cut.Find("[data-testid=editor-submit]").Click(); Assert.Single(store.Upserts); StoredSecret row = store.Upserts[0]; Assert.Equal("db/primary", row.Name.Value); Assert.Equal("rotated-value", cipher.Decrypt(row)); Assert.Single(audit.Events); Assert.Equal("secret.rotate", audit.Events[0].Action); Assert.Equal("db/primary", audit.Events[0].Target); AssertNoValueLeak(audit.Events[0], "rotated-value"); } [Fact] public void SecretEditor_Rotate_PreservesDescriptionAndContentType() { var (store, _, cipher) = RegisterServices(); var name = new SecretName("db/primary"); // Seed an existing Json secret with a description; rotating must NOT blank either. StoredSecret existing = cipher.Encrypt(name, "old-value", SecretContentType.Json) with { Description = "db creds", Revision = 1, CreatedUtc = DateTimeOffset.UnixEpoch, UpdatedUtc = DateTimeOffset.UnixEpoch, }; store.Seed(existing); var auth = this.AddAuthorization(); auth.SetAuthorized("dave"); auth.SetPolicies(SecretsAuthorization.ManagePolicy); var cut = Render(p => p .Add(c => c.ExistingName, name) .Add(c => c.OnSaved, () => { })); // The editor pre-filled the existing metadata (no plaintext read). Assert.Equal("db creds", cut.Find("[data-testid=secret-description]").GetAttribute("value")); // The operator supplies ONLY a new value. cut.Find("[data-testid=secret-value]").Change("rotated-value"); cut.Find("[data-testid=editor-submit]").Click(); Assert.Single(store.Upserts); StoredSecret row = store.Upserts[0]; Assert.Equal("db/primary", row.Name.Value); Assert.Equal("rotated-value", cipher.Decrypt(row)); // Metadata preserved — content type not reset to Text, description not blanked. Assert.Equal(SecretContentType.Json, row.ContentType); Assert.Equal("db creds", row.Description); } [Fact] public void SecretEditor_Add_StoreFault_AuditsFailure_ShowsError_DoesNotThrow() { var (store, audit, _) = RegisterServices(); store.UpsertFault = new MasterKeyUnavailableException("KEK unavailable."); var auth = this.AddAuthorization(); auth.SetAuthorized("carol"); auth.SetPolicies(SecretsAuthorization.ManagePolicy); var cut = Render(p => p .Add(c => c.OnSaved, () => { })); cut.Find("[data-testid=secret-name]").Change("app/thing"); cut.Find("[data-testid=secret-value]").Change(EnteredValue); // The click must not throw into the Blazor event pipeline. cut.Find("[data-testid=editor-submit]").Click(); // Nothing persisted, a Failure audit recorded, an error surfaced, and no value leak. Assert.Empty(store.Upserts); Assert.Single(audit.Events); AuditEvent evt = audit.Events[0]; Assert.Equal("secret.add", evt.Action); Assert.Equal(AuditOutcome.Failure, evt.Outcome); Assert.Equal("app/thing", evt.Target); Assert.Equal("carol", evt.Actor); AssertNoValueLeak(evt); Assert.NotEmpty(cut.FindAll("[data-testid=editor-error]")); } [Fact] public void ChangingRotateTarget_DoesNotReuseAnotherSecretsDraft() { var (store, _, cipher) = RegisterServices(); var a = new SecretName("app/a"); var b = new SecretName("app/b"); store.Seed(cipher.Encrypt(a, "old-a", SecretContentType.Text) with { Description = "A" }); store.Seed(cipher.Encrypt(b, "old-b", SecretContentType.Json) with { Description = "B" }); AuthorizeManager(); var cut = Render(p => p.Add(x => x.ExistingName, a)); cut.Find("[data-testid=secret-value]").Change("draft-for-a"); cut.Render(p => p.Add(x => x.ExistingName, b)); Assert.Equal("B", cut.Find("[data-testid=secret-description]").GetAttribute("value")); Assert.Equal(nameof(SecretContentType.Json), cut.Find("[data-testid=secret-content-type]").GetAttribute("value")); Assert.Equal("", cut.Find("[data-testid=secret-value]").GetAttribute("value") ?? ""); } [Fact] public void RotateToAdd_ClearsTargetMetadataAndValue() { var (store, _, cipher) = RegisterServices(); var a = new SecretName("app/a"); store.Seed(cipher.Encrypt(a, "old", SecretContentType.Json) with { Description = "A" }); var cut = Render(p => p.Add(x => x.ExistingName, a)); cut.Find("[data-testid=secret-value]").Change("draft-for-a"); cut.Render(p => p.Add(x => x.ExistingName, (SecretName?)null)); Assert.Equal("", cut.Find("[data-testid=secret-name]").GetAttribute("value") ?? ""); Assert.Equal("", cut.Find("[data-testid=secret-description]").GetAttribute("value") ?? ""); Assert.Equal("", cut.Find("[data-testid=secret-value]").GetAttribute("value") ?? ""); Assert.Equal(nameof(SecretContentType.Text), cut.Find("[data-testid=secret-content-type]").GetAttribute("value")); } [Fact] public void SameTargetRerender_PreservesUnsavedDraftAndFailedSaveError() { var (store, _, cipher) = RegisterServices(); var a = new SecretName("app/a"); store.Seed(cipher.Encrypt(a, "old", SecretContentType.Text) with { Description = "A" }); store.UpsertFault = new IOException("synthetic write failure"); AuthorizeManager(); var cut = Render(p => p.Add(x => x.ExistingName, a)); cut.Find("[data-testid=secret-description]").Change("unsaved description"); cut.Find("[data-testid=secret-value]").Change("unsaved value"); cut.Find("[data-testid=editor-submit]").Click(); cut.Render(p => p.Add(x => x.ExistingName, a)); Assert.Equal("unsaved description", cut.Find("[data-testid=secret-description]").GetAttribute("value")); Assert.Equal("unsaved value", cut.Find("[data-testid=secret-value]").GetAttribute("value")); Assert.NotEmpty(cut.FindAll("[data-testid=editor-error]")); Assert.Single(store.Gets); } [Fact] public async Task SupersededMetadataRead_IsCancelledAndCannotOverwriteNewTarget() { var (store, _, cipher) = RegisterServices(); var a = new SecretName("app/a"); var b = new SecretName("app/b"); var oldRead = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); CancellationToken readToken = default; store.GetOverride = (name, ct) => { if (name == a) { readToken = ct; return oldRead.Task; } return Task.FromResult(cipher.Encrypt(b, "old-b", SecretContentType.Json) with { Description = "B" }); }; var cut = Render(p => p.Add(x => x.ExistingName, a)); try { cut.Render(p => p.Add(x => x.ExistingName, b)); Assert.True(readToken.IsCancellationRequested); } finally { var before = cut.RenderCount; await cut.InvokeAsync(() => oldRead.TrySetResult(cipher.Encrypt(a, "old-a", SecretContentType.Text) with { Description = "A" })); cut.WaitForState(() => cut.RenderCount > before); } Assert.Equal("B", cut.Find("[data-testid=secret-description]").GetAttribute("value")); Assert.Equal("app/b", cut.Find("[data-testid=secret-name]").GetAttribute("value")); } [Fact] public async Task ReturningToSameName_StillRejectsAnOlderGenerationRead() { var (store, _, cipher) = RegisterServices(); var a = new SecretName("app/a"); var b = new SecretName("app/b"); var oldRead = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var readsOfA = 0; store.GetOverride = (name, ct) => name == a && ++readsOfA == 1 ? oldRead.Task : Task.FromResult(cipher.Encrypt(name, "old", SecretContentType.Text) with { Description = "fresh metadata" }); var cut = Render(p => p.Add(x => x.ExistingName, a)); cut.Render(p => p.Add(x => x.ExistingName, b)); cut.Render(p => p.Add(x => x.ExistingName, a)); var before = cut.RenderCount; await cut.InvokeAsync(() => oldRead.SetResult(cipher.Encrypt(a, "old", SecretContentType.Text) with { Description = "stale metadata" })); cut.WaitForState(() => cut.RenderCount > before); Assert.Equal("fresh metadata", cut.Find("[data-testid=secret-description]").GetAttribute("value")); } [Fact] public void TargetChange_ResetsTombstoneRestoreConfirmation() { var (store, _, cipher) = RegisterServices(); store.Seed(cipher.Encrypt(new SecretName("app/retired"), "old", SecretContentType.Text) with { IsDeleted = true }); AuthorizeManager(); var cut = Render(); cut.Find("[data-testid=secret-name]").Change("app/retired"); cut.Find("[data-testid=secret-value]").Change("new"); cut.Find("[data-testid=editor-submit]").Click(); Assert.Empty(store.Upserts); cut.Render(p => p.Add(x => x.ExistingName, new SecretName("app/other"))); cut.Render(p => p.Add(x => x.ExistingName, (SecretName?)null)); cut.Find("[data-testid=secret-name]").Change("app/retired"); cut.Find("[data-testid=secret-value]").Change("another new value"); cut.Find("[data-testid=editor-submit]").Click(); Assert.Empty(store.Upserts); Assert.Contains("deleted secret", cut.Find("[data-testid=editor-error]").TextContent); } [Fact] public async Task PendingWrite_CannotBeCancelledOrSubmittedTwice() { var (store, _, _) = RegisterServices(); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); store.UpsertOverride = (_, _) => { entered.TrySetResult(); return release.Task; }; AuthorizeManager(); var cancelled = false; var saved = false; var cut = Render(p => p.Add(x => x.OnCancelled, () => cancelled = true).Add(x => x.OnSaved, () => saved = true)); cut.Find("[data-testid=secret-name]").Change("app/new"); cut.Find("[data-testid=secret-value]").Change("synthetic value"); var pending = cut.Find("[data-testid=editor-submit]").ClickAsync(new MouseEventArgs()); await entered.Task; try { Assert.True(cut.Find("[data-testid=editor-cancel]").HasAttribute("disabled")); cut.Find("[data-testid=editor-cancel]").Click(); cut.Find("[data-testid=editor-submit]").Click(); Assert.False(cancelled); Assert.False(saved); Assert.Empty(store.Upserts); } finally { release.TrySetResult(); await pending; } Assert.Single(store.Upserts); Assert.True(saved); } [Fact] public async Task SupersededPendingWrite_PreservesCapturedTargetAuditAndCacheButNotSavedCallback() { var (store, audit, cipher) = RegisterServices(); var cache = new RecordingCacheInvalidator(); Services.AddSingleton(cache); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); store.UpsertOverride = (_, _) => { entered.TrySetResult(); return release.Task; }; var a = new SecretName("app/a"); AuthorizeManager(); var saved = false; var cut = Render(p => p.Add(x => x.ExistingName, a).Add(x => x.OnSaved, () => saved = true)); cut.Find("[data-testid=secret-value]").Change("new-a"); var pending = cut.Find("[data-testid=editor-submit]").ClickAsync(new MouseEventArgs()); await entered.Task; try { cut.Render(p => p.Add(x => x.ExistingName, (SecretName?)null)); } finally { release.TrySetResult(); await pending; } var row = Assert.Single(store.Upserts); Assert.Equal(a, row.Name); Assert.Equal("new-a", cipher.Decrypt(row)); var evt = Assert.Single(audit.Events); Assert.Equal("secret.rotate", evt.Action); Assert.Equal(a.Value, evt.Target); Assert.Equal(a, Assert.Single(cache.Invalidated)); Assert.False(saved); Assert.Equal("", cut.Find("[data-testid=secret-value]").GetAttribute("value") ?? ""); } [Fact] public async Task TargetChangeDuringAuthorization_DoesNotWriteTheNewTargetWithTheOldDraft() { var (store, _, _) = RegisterServices(); AuthorizeManager(); var authState = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); RenderFragment EditorFor(SecretName name) => builder => { builder.OpenComponent(0); builder.AddAttribute(1, nameof(SecretEditor.ExistingName), (object)name); builder.CloseComponent(); }; var cut = Render>>(p => p .Add(x => x.Value, authState.Task).AddChildContent(EditorFor(new SecretName("app/a")))); cut.Find("[data-testid=secret-value]").Change("draft for a"); var pending = cut.Find("[data-testid=editor-submit]").ClickAsync(new MouseEventArgs()); cut.Render(p => p.Add(x => x.Value, authState.Task).AddChildContent(EditorFor(new SecretName("app/b")))); authState.SetResult(new AuthenticationState(new ClaimsPrincipal( new ClaimsIdentity([new Claim(ClaimTypes.Name, "reviewer")], "fixture")))); await pending; Assert.Empty(store.Upserts); Assert.Equal("app/b", cut.Find("[data-testid=secret-name]").GetAttribute("value")); Assert.Equal("", cut.Find("[data-testid=secret-value]").GetAttribute("value") ?? ""); } [Fact] public async Task DisposalAfterCommit_StillInvalidatesCapturedTargetWithoutCallingSaved() { var (store, _, _) = RegisterServices(); var audit = new DelayedSuccessAuditWriter(); var cache = new RecordingCacheInvalidator(); Services.AddSingleton(audit); Services.AddSingleton(cache); AuthorizeManager(); var saved = false; var a = new SecretName("app/a"); RenderFragment editor = builder => { builder.OpenComponent(0); builder.AddAttribute(1, nameof(SecretEditor.ExistingName), (object)a); builder.AddAttribute(2, nameof(SecretEditor.OnSaved), EventCallback.Factory.Create(this, () => saved = true)); builder.CloseComponent(); }; var cut = Render>(p => p.Add(x => x.Value, true).AddChildContent(editor)); cut.Find("[data-testid=secret-value]").Change("synthetic new value"); var pending = cut.Find("[data-testid=editor-submit]").ClickAsync(new MouseEventArgs()); await audit.Entered.Task; Assert.Single(store.Upserts); // The mutation has already committed. cut.Render(p => p.Add(x => x.Value, true).AddChildContent((RenderFragment)(_ => { }))); // Unmount through the renderer, invoking IDisposable. audit.Release.SetResult(); await pending; Assert.Equal(a, Assert.Single(cache.Invalidated)); Assert.False(saved); Assert.Equal(AuditOutcome.Success, Assert.Single(audit.Events).Outcome); Assert.Equal(a.Value, audit.Events[0].Target); } [Fact] public async Task CommittedWrite_EvictsCapturedCacheWhenProviderRejectsLateResolution() { var (store, audit, _) = RegisterServices(); // Exercise the logging path too: audit failure after commit must not need the dead scope. audit.SuccessFault = new InvalidOperationException("synthetic audit outage"); var cache = new RecordingCacheInvalidator(); Services.AddSingleton(cache); var provider = new LateResolutionGuardProvider(Services); var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); store.UpsertOverride = (_, _) => { entered.TrySetResult(); return release.Task; }; AuthorizeManager(); var a = new SecretName("app/a"); var cut = Render(p => p.Add(x => x.ExistingName, a)); // bUnit's built-in IServiceProvider resolves itself. Replace only this injected seam // after rendering so the fixture can model a circuit scope rejecting late resolution. typeof(SecretEditor).GetProperty("Services", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)! .SetValue(cut.Instance, provider); cut.Find("[data-testid=secret-value]").Change("synthetic new value"); var pending = cut.Find("[data-testid=editor-submit]").ClickAsync(new MouseEventArgs()); await entered.Task; Assert.True(provider.ResolutionCount > 0); provider.RejectResolutions = true; release.SetResult(); await pending; Assert.Single(store.Upserts); Assert.Equal(a, Assert.Single(cache.Invalidated)); Assert.Empty(cut.FindAll("[data-testid=editor-error]")); } [Fact] public void IdleEditor_CanBeCancelledWithoutMutation() { var (store, _, _) = RegisterServices(); bool cancelled = false; var cut = Render(p => p.Add(x => x.OnCancelled, () => cancelled = true)); Assert.False(cut.Find("[data-testid=editor-cancel]").HasAttribute("disabled")); cut.Find("[data-testid=editor-cancel]").Click(); Assert.True(cancelled); Assert.Empty(store.Upserts); } [Fact] public void EveryEditorControl_HasAnAssociatedLabel() { RegisterServices(); var cut = Render(); foreach (var control in cut.FindAll("input:not([type=hidden]),select")) { Assert.False(string.IsNullOrWhiteSpace(control.Id)); Assert.NotNull(cut.Find($"label[for='{control.Id}']")); } } [Fact] public void TwoEditors_UseUniqueStableIdsAndExistingDescriptions() { RegisterServices(); var first = Render(); var second = Render(); var ids = first.FindAll("input,select").Select(x => x.Id).ToArray(); Assert.DoesNotContain(ids, id => string.IsNullOrWhiteSpace(id)); Assert.Empty(ids.Intersect(second.FindAll("input,select").Select(x => x.Id))); first.Render(); Assert.Equal(ids, first.FindAll("input,select").Select(x => x.Id)); foreach (var control in first.FindAll("[aria-describedby]")) foreach (var id in control.GetAttribute("aria-describedby")!.Split(' ', StringSplitOptions.RemoveEmptyEntries)) Assert.NotNull(first.Find($"[id='{id}']")); } [Fact] public void InvalidName_AssociatesFieldErrorAndClearsInvalidStateOnValidSubmit() { var (store, _, _) = RegisterServices(); AuthorizeManager(); JSInterop.SetupVoid("Blazor._internal.domWrapper.focus", _ => true).SetVoidResult(); var cut = Render(); cut.Find("[data-testid=secret-name]").Change("../invalid"); cut.Find("[data-testid=secret-value]").Change("synthetic value"); cut.Find("[data-testid=editor-submit]").Click(); var name = cut.Find("[data-testid=secret-name]"); Assert.Equal("true", name.GetAttribute("aria-invalid")); var described = name.GetAttribute("aria-describedby")!.Split(' ', StringSplitOptions.RemoveEmptyEntries); Assert.Equal(2, described.Length); Assert.Contains(described, id => cut.Find($"[id='{id}']").ClassList.Contains("field-error")); Assert.Empty(store.Upserts); Assert.Equal("password", cut.Find("[data-testid=secret-value]").GetAttribute("type")); Assert.Equal("new-password", cut.Find("[data-testid=secret-value]").GetAttribute("autocomplete")); cut.Find("[data-testid=secret-name]").Change("app/valid"); cut.Find("[data-testid=editor-submit]").Click(); Assert.Null(cut.Find("[data-testid=secret-name]").GetAttribute("aria-invalid")); Assert.Single(store.Upserts); } private sealed class LateResolutionGuardProvider(IServiceProvider inner) : IServiceProvider { public bool RejectResolutions { get; set; } public int ResolutionCount { get; private set; } public object? GetService(Type serviceType) { ++ResolutionCount; if (RejectResolutions) throw new ObjectDisposedException("synthetic circuit provider"); return inner.GetService(serviceType); } } private sealed class DelayedSuccessAuditWriter : IAuditWriter { public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public List Events { get; } = []; public async Task WriteAsync(AuditEvent evt, CancellationToken ct = default) { Entered.TrySetResult(); await Release.Task; // Deliberately ignore cancellation after the captured mutation committed. Events.Add(evt); } } private void AuthorizeManager() { var auth = this.AddAuthorization(); auth.SetAuthorized("reviewer"); auth.SetPolicies(SecretsAuthorization.ManagePolicy); } private static void AssertNoValueLeak(AuditEvent evt, string value = EnteredValue) { foreach (string? field in new[] { evt.Action, evt.Actor, evt.Category, evt.Target, evt.DetailsJson, evt.ToString() }) { if (field is not null) { Assert.DoesNotContain(value, field, StringComparison.Ordinal); } } } }