Files
scadaproj/ZB.MOM.WW.Secrets/tests/ZB.MOM.WW.Secrets.Ui.Tests/SecretsListTests.cs
T

486 lines
22 KiB
C#

using Microsoft.AspNetCore.Components;
using Bunit;
using Bunit.TestDoubles;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Components.Web;
using ZB.MOM.WW.Secrets.Ui.Components;
using ZB.MOM.WW.Audit;
using ZB.MOM.WW.Secrets.Abstractions;
using ZB.MOM.WW.Secrets.Ui;
using ZB.MOM.WW.Secrets.Ui.Tests.Fakes;
namespace ZB.MOM.WW.Secrets.Ui.Tests;
public class SecretsListTests : BunitContext
{
public SecretsListTests()
{
DialogInterop.Setup(JSInterop);
RevealInterop.Setup(JSInterop);
JSInterop.SetupVoid("Blazor._internal.domWrapper.focus", _ => true).SetVoidResult();
}
private static readonly SecretMetadata SecretOne = new()
{
Name = new SecretName("db/primary"),
Description = "Primary database connection",
ContentType = SecretContentType.ConnectionString,
KekId = "kek-a",
Revision = 3,
CreatedUtc = new DateTimeOffset(2026, 7, 1, 0, 0, 0, TimeSpan.Zero),
UpdatedUtc = new DateTimeOffset(2026, 7, 10, 12, 0, 0, TimeSpan.Zero),
UpdatedBy = "alice",
};
private static readonly SecretMetadata SecretTwo = new()
{
Name = new SecretName("api/token"),
Description = "External API token",
ContentType = SecretContentType.Text,
KekId = "kek-b",
Revision = 1,
CreatedUtc = new DateTimeOffset(2026, 7, 2, 0, 0, 0, TimeSpan.Zero),
UpdatedUtc = new DateTimeOffset(2026, 7, 11, 8, 30, 0, TimeSpan.Zero),
UpdatedBy = "bob",
};
private void RegisterStore(params SecretMetadata[] rows)
{
// SecretsList now embeds RevealButton / ConfirmDeleteModal / SecretEditor, which inject the
// cipher and audit writer, so those seams must be registered even for list-only assertions.
Services.AddSingleton<ISecretStore>(new FakeSecretStore(rows));
Services.AddSingleton<ISecretCipher>(new FakeCipher());
Services.AddSingleton<IAuditWriter>(new CapturingAuditWriter());
}
[Fact]
public void Renders_Metadata_ForEachSecret()
{
RegisterStore(SecretOne, SecretTwo);
var auth = this.AddAuthorization();
auth.SetAuthorized("alice");
auth.SetPolicies(SecretsAuthorization.ManagePolicy);
var cut = Render<SecretsList>();
var markup = cut.Markup;
Assert.Contains("db/primary", markup);
Assert.Contains("Primary database connection", markup);
Assert.Contains(nameof(SecretContentType.ConnectionString), markup);
Assert.Contains("api/token", markup);
Assert.Contains("External API token", markup);
Assert.Contains(nameof(SecretContentType.Text), markup);
}
[Fact]
public void RevealButton_Hidden_WithoutRevealPolicy()
{
RegisterStore(SecretOne, SecretTwo);
var auth = this.AddAuthorization();
auth.SetAuthorized("alice");
auth.SetPolicies(SecretsAuthorization.ManagePolicy);
var cut = Render<SecretsList>();
Assert.Empty(cut.FindAll("button.reveal-secret"));
Assert.DoesNotContain("Reveal", cut.Markup);
}
[Fact]
public void RevealButton_Shown_WithRevealPolicy()
{
RegisterStore(SecretOne, SecretTwo);
var auth = this.AddAuthorization();
auth.SetAuthorized("carol");
auth.SetPolicies(SecretsAuthorization.ManagePolicy, SecretsAuthorization.RevealPolicy);
var cut = Render<SecretsList>();
// One reveal affordance per secret row.
Assert.Equal(2, cut.FindAll("button.reveal-secret").Count);
}
[Fact]
public void EmptyList_ShowsEmptyState()
{
RegisterStore();
var auth = this.AddAuthorization();
auth.SetAuthorized("alice");
auth.SetPolicies(SecretsAuthorization.ManagePolicy);
var cut = Render<SecretsList>();
Assert.Contains("No secrets", cut.Markup);
}
[Fact]
public void ChangingRows_ReplacesTheEditorAndClearsAnotherRowsDraft()
{
RegisterEditableStore();
var cut = Render<SecretsList>();
cut.Find(".rotate-secret[data-secret-name='db/primary']").Click();
var original = cut.FindComponent<SecretEditor>().Instance;
cut.Find("[data-testid=secret-value]").Change("draft for primary");
cut.Find(".rotate-secret[data-secret-name='api/token']").Click();
Assert.NotSame(original, cut.FindComponent<SecretEditor>().Instance);
Assert.Equal("api/token", cut.Find("[data-testid=secret-name]").GetAttribute("value"));
Assert.Equal("External API token", cut.Find("[data-testid=secret-description]").GetAttribute("value"));
Assert.Equal("", cut.Find("[data-testid=secret-value]").GetAttribute("value") ?? "");
}
[Fact]
public void SelectingSameRow_PreservesItsEditorAndDraft()
{
RegisterEditableStore();
var cut = Render<SecretsList>();
cut.Find(".rotate-secret[data-secret-name='db/primary']").Click();
var original = cut.FindComponent<SecretEditor>().Instance;
cut.Find("[data-testid=secret-value]").Change("same target draft");
cut.Find(".rotate-secret[data-secret-name='db/primary']").Click();
Assert.Same(original, cut.FindComponent<SecretEditor>().Instance);
Assert.Equal("same target draft", cut.Find("[data-testid=secret-value]").GetAttribute("value"));
}
[Fact]
public async Task SupersededSavedCallback_DoesNotCloseANewerEditor()
{
RegisterEditableStore();
var cut = Render<SecretsList>();
cut.Find(".rotate-secret[data-secret-name='db/primary']").Click();
var oldSaved = cut.FindComponent<SecretEditor>().Instance.OnSaved;
cut.Find("[data-testid=add-secret]").Click();
cut.Find("[data-testid=secret-name]").Change("app/new-draft");
await cut.InvokeAsync(() => oldSaved.InvokeAsync());
Assert.Single(cut.FindComponents<SecretEditor>());
Assert.Equal("app/new-draft", cut.Find("[data-testid=secret-name]").GetAttribute("value"));
}
[Fact]
public async Task PendingMutation_DisablesParentTargetSwitchingUntilCompletion()
{
var store = RegisterEditableStore();
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
store.UpsertOverride = (_, _) => { entered.TrySetResult(); return release.Task; };
var cut = Render<SecretsList>();
cut.Find(".rotate-secret[data-secret-name='db/primary']").Click();
cut.Find("[data-testid=secret-value]").Change("new synthetic value");
var pending = cut.Find("[data-testid=editor-submit]").ClickAsync(new MouseEventArgs());
await entered.Task;
try
{
Assert.True(cut.Find("[data-testid=add-secret]").HasAttribute("disabled"));
Assert.All(cut.FindAll(".rotate-secret, .delete-secret"), button => Assert.True(button.HasAttribute("disabled")));
cut.Find("[data-testid=add-secret]").Click();
cut.Find(".rotate-secret[data-secret-name='api/token']").Click();
cut.Find("[data-testid=editor-cancel]").Click();
Assert.Equal("db/primary", cut.Find("[data-testid=secret-name]").GetAttribute("value"));
Assert.Empty(store.Upserts);
}
finally { release.TrySetResult(); await pending; }
cut.WaitForAssertion(() => Assert.Empty(cut.FindComponents<SecretEditor>()));
Assert.Equal("db/primary", Assert.Single(store.Upserts).Name.Value);
Assert.False(cut.Find("[data-testid=add-secret]").HasAttribute("disabled"));
}
[Fact]
public async Task OldBusyCallback_CannotUnlockANewerPendingEditor()
{
var store = RegisterEditableStore();
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
store.UpsertOverride = (_, _) => { entered.TrySetResult(); return release.Task; };
var cut = Render<SecretsList>();
cut.Find(".rotate-secret[data-secret-name='db/primary']").Click();
var oldBusy = cut.FindComponent<SecretEditor>().Instance.OnBusyChanged;
cut.Find(".rotate-secret[data-secret-name='api/token']").Click();
cut.Find("[data-testid=secret-value]").Change("synthetic replacement");
var pending = cut.Find("[data-testid=editor-submit]").ClickAsync(new MouseEventArgs());
await entered.Task;
try
{
await cut.InvokeAsync(() => oldBusy.InvokeAsync(false));
Assert.True(cut.Find("[data-testid=add-secret]").HasAttribute("disabled"));
Assert.Equal("api/token", cut.Find("[data-testid=secret-name]").GetAttribute("value"));
}
finally { release.TrySetResult(); await pending; }
Assert.Single(store.Upserts);
}
[Fact]
public void DeletionFocusFallback_SelectsAdjacentRowThenStableHeadingForOneRow()
{
RegisterEditableStore();
var cut = Render<SecretsList>();
var actions = cut.FindAll(".delete-secret");
var firstName = actions[0].GetAttribute("data-secret-name");
var nextId = actions[1].Id;
actions[0].Click();
Assert.Equal(nextId, cut.FindComponent<ConfirmDeleteModal>().Instance.ReturnFocusId);
cut.Find("[data-testid=confirm-delete]").Click();
Assert.Single(cut.FindAll(".delete-secret"));
Assert.DoesNotContain(cut.FindAll(".delete-secret"), action => action.GetAttribute("data-secret-name") == firstName);
cut.Find(".delete-secret").Click();
Assert.Equal(cut.Find("h2").Id, cut.FindComponent<ConfirmDeleteModal>().Instance.ReturnFocusId);
}
[Fact]
public void InitialListFailure_IsRetryableAndIsNotAnEmptyInventory()
{
var store = RegisterEditableStore();
store.ListFault = new IOException("synthetic outage");
var cut = Render<SecretsList>();
Assert.NotNull(cut.Find("[data-testid=list-error]"));
Assert.DoesNotContain("No secrets.", cut.Markup);
store.ListFault = null;
cut.Find("[data-testid=list-retry]").Click();
Assert.Equal(2, store.ListCalls);
Assert.Empty(cut.FindAll("[data-testid=list-error]"));
Assert.NotEmpty(cut.FindAll("tbody tr"));
Assert.Empty(store.Upserts);
Assert.Empty(store.Deletes);
}
[Fact]
public void DelayedInitialMetadata_IsLoadingUntilTheReadCompletes()
{
var store = RegisterEditableStore();
var result = new TaskCompletionSource<IReadOnlyList<SecretMetadata>>(TaskCreationOptions.RunContinuationsAsynchronously);
store.ListOverride = (_, _) => result.Task;
var cut = Render<SecretsList>();
Assert.NotNull(cut.Find("[data-testid=list-loading]"));
Assert.DoesNotContain("No secrets.", cut.Markup);
result.SetResult([SecretOne]);
cut.WaitForAssertion(() => Assert.Single(cut.FindAll("tbody tr")));
Assert.Empty(cut.FindAll("[data-testid=list-loading]"));
}
[Fact]
public void CommittedSaveAndFailedRefresh_ClosesEditorAndRetriesOnlyMetadata()
{
var store = RegisterEditableStore();
var cut = Render<SecretsList>();
cut.Find(".rotate-secret[data-secret-name='db/primary']").Click();
cut.Find("[data-testid=secret-value]").Change("synthetic replacement");
store.ListFault = new IOException("synthetic refresh outage");
cut.Find("[data-testid=editor-submit]").Click();
Assert.Single(store.Upserts);
Assert.Empty(cut.FindComponents<SecretEditor>());
Assert.Contains("Change saved; list refresh failed", cut.Find("[data-testid=list-error]").TextContent);
Assert.Equal(2, cut.FindAll("tbody tr").Count); // Keep previously visible metadata.
store.ListFault = null;
cut.Find("[data-testid=list-retry]").Click();
Assert.Empty(cut.FindAll("[data-testid=list-error]"));
Assert.Single(store.Upserts); // Retrying a read cannot replay the committed write.
Assert.Empty(store.Deletes);
}
[Fact]
public void CommittedDeleteAndFailedRefresh_RetryDoesNotDeleteTwice()
{
var store = RegisterEditableStore();
var cut = Render<SecretsList>();
cut.Find(".delete-secret[data-secret-name='db/primary']").Click();
store.ListFault = new IOException("synthetic refresh outage");
cut.Find("[data-testid=confirm-delete]").Click();
Assert.Single(store.Deletes);
Assert.Empty(cut.FindAll("[role=dialog]"));
Assert.Contains("Change saved; list refresh failed", cut.Find("[data-testid=list-error]").TextContent);
store.ListFault = null;
cut.Find("[data-testid=list-retry]").Click();
Assert.Single(store.Deletes);
Assert.Empty(store.Upserts);
Assert.Single(cut.FindAll("tbody tr"));
Assert.Empty(cut.FindAll("[data-testid=list-error]"));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void NewFailedMutation_DoesNotRetainThePreviousSavesSuccess(bool delete)
{
var store = RegisterEditableStore();
var cut = Render<SecretsList>();
cut.Find(".rotate-secret[data-secret-name='db/primary']").Click();
cut.Find("[data-testid=secret-value]").Change("synthetic first value");
cut.Find("[data-testid=editor-submit]").Click();
Assert.Contains("Change saved.", cut.Find("[data-testid=list-outcome]").TextContent);
int reads = store.ListCalls;
if (delete)
{
store.DeleteFault = new IOException("synthetic second mutation failure");
cut.Find(".delete-secret[data-secret-name='api/token']").Click();
cut.Find("[data-testid=confirm-delete]").Click();
Assert.NotNull(cut.Find("[data-testid=delete-error]"));
}
else
{
store.UpsertFault = new IOException("synthetic second mutation failure");
cut.Find(".rotate-secret[data-secret-name='api/token']").Click();
cut.Find("[data-testid=secret-value]").Change("synthetic second value");
cut.Find("[data-testid=editor-submit]").Click();
Assert.NotNull(cut.Find("[data-testid=editor-error]"));
}
Assert.Empty(cut.FindAll("[data-testid=list-outcome]"));
Assert.Single(store.Upserts);
Assert.Empty(store.Deletes);
Assert.Equal(reads, store.ListCalls);
Assert.Equal(2, cut.FindAll("tbody tr").Count);
}
[Fact]
public void RemovingList_CancelsReadAndIgnoresItsLateCompletion()
{
var store = RegisterEditableStore();
var result = new TaskCompletionSource<IReadOnlyList<SecretMetadata>>(TaskCreationOptions.RunContinuationsAsynchronously);
CancellationToken token = default;
store.ListOverride = (_, ct) => { token = ct; return result.Task; };
RenderFragment list = builder => { builder.OpenComponent<SecretsList>(0); builder.CloseComponent(); };
var cut = Render<CascadingValue<bool>>(p => p.Add(x => x.Value, true).AddChildContent(list));
cut.Render(p => p.Add(x => x.Value, true).AddChildContent((RenderFragment)(_ => { })));
Assert.True(token.IsCancellationRequested);
result.SetResult([SecretOne]); // A non-cooperative read must not recreate the removed UI.
Assert.Empty(cut.FindAll("table"));
}
[Fact]
public void NameFilter_CanBeClearedWithoutHidingMetadataPermanently()
{
RegisterStore(SecretOne, SecretTwo);
var auth = this.AddAuthorization();
auth.SetAuthorized("reviewer");
auth.SetPolicies(SecretsAuthorization.ManagePolicy);
var cut = Render<SecretsList>();
cut.Find("input[data-testid=secret-filter]").Input("db/primary");
Assert.Single(cut.FindAll("tbody tr[data-secret-row]"));
cut.Find("[data-testid=clear-secret-filter]").Click();
Assert.Equal(2, cut.FindAll("tbody tr[data-secret-row]").Count);
}
[Fact]
public void NameFilter_UsesCaseInsensitiveLoadedNamesWithoutReadingValues()
{
var store = RegisterEditableStore();
var cut = Render<SecretsList>();
cut.Find("[data-testid=secret-filter]").Input(" DB/PRIMARY ");
Assert.Equal("db/primary", Assert.Single(cut.FindAll("tbody tr[data-secret-row]")).GetAttribute("data-secret-row"));
cut.Find("[data-testid=secret-filter]").Input("External API token");
Assert.Empty(cut.FindAll("tbody tr[data-secret-row]")); // Description is not the name filter.
cut.Find("[data-testid=secret-filter]").Input("synthetic fixture");
Assert.Empty(cut.FindAll("tbody tr[data-secret-row]"));
Assert.Empty(store.Gets);
Assert.Equal(1, store.ListCalls);
}
[Fact]
public void NameFilter_NoMatchesHasClearRecoveryAndPreservesManageActions()
{
RegisterEditableStore();
var cut = Render<SecretsList>();
cut.Find("[data-testid=secret-filter]").Input("no-such-name");
Assert.Contains("No names match", cut.Find("[data-testid=filter-empty]").TextContent);
Assert.NotNull(cut.Find("[data-testid=add-secret]"));
Assert.Empty(cut.FindAll("tbody tr[data-secret-row]"));
cut.Find("[data-testid=clear-secret-filter]").Click();
Assert.Equal(2, cut.FindAll("tbody tr[data-secret-row]").Count);
Assert.Equal("", cut.Find("[data-testid=secret-filter]").GetAttribute("value") ?? "");
}
[Fact]
public void RowActionsAndTechnicalMetadata_StayAssociatedWithLongExactNames()
{
var longRow = SecretOne with { Name = new SecretName("app/" + new string('x', 400)) };
RegisterStore(longRow, SecretTwo);
var auth = this.AddAuthorization();
auth.SetAuthorized("reviewer");
auth.SetPolicies(SecretsAuthorization.ManagePolicy, SecretsAuthorization.RevealPolicy);
var cut = Render<SecretsList>();
Assert.Contains(cut.FindAll("thead th[scope=col]"), header => header.TextContent == "Actions");
foreach (var row in cut.FindAll("tr[data-secret-row]"))
{
string name = row.GetAttribute("data-secret-row")!;
Assert.Equal(name, row.QuerySelector("th[scope=row]")!.TextContent.Trim());
foreach (string action in new[] { "Reveal", "Rotate", "Delete" })
Assert.NotNull(row.QuerySelector($"button[aria-label='{action} {name}']"));
Assert.Contains(name, row.QuerySelector("summary")!.GetAttribute("aria-label"));
Assert.NotNull(row.QuerySelector("time[datetime]"));
}
var first = cut.Find($"tr[data-secret-row='{longRow.Name.Value}']");
Assert.Contains("kek-a", first.TextContent);
Assert.Contains("alice", first.TextContent);
Assert.Contains("ConnectionString", first.TextContent);
Assert.Equal(longRow.UpdatedUtc.ToString("O"), first.QuerySelector("time")!.GetAttribute("datetime"));
}
[Fact]
public void FilteringRows_CannotReuseAnotherRowsRevealedValue()
{
var store = RegisterEditableStore(reveal: true);
var cipher = new FakeCipher();
store.Seed(cipher.Encrypt(SecretOne.Name, "synthetic-only-db-value", SecretContentType.Text));
store.Seed(cipher.Encrypt(SecretTwo.Name, "synthetic-only-api-value", SecretContentType.Text));
var cut = Render<SecretsList>();
cut.Find(".reveal-secret[data-secret-name='db/primary']").Click();
Assert.Contains("synthetic-only-db-value", cut.Markup);
cut.Find("[data-testid=secret-filter]").Input("api/token");
Assert.DoesNotContain("synthetic-only-db-value", cut.Markup);
Assert.Empty(cut.FindAll("[data-testid=revealed-value]"));
Assert.Equal("api/token", cut.Find("[data-testid=reveal-button]").GetAttribute("data-secret-name"));
cut.Find("[data-testid=clear-secret-filter]").Click();
Assert.Empty(cut.FindAll("[data-testid=revealed-value]"));
}
[Fact]
public void DeletionFocusFallback_UsesOnlyVisibleMatchingRows()
{
RegisterEditableStore();
var cut = Render<SecretsList>();
cut.Find("[data-testid=secret-filter]").Input("db/primary");
cut.Find(".delete-secret").Click();
Assert.Equal(cut.Find("h2").Id, cut.FindComponent<ConfirmDeleteModal>().Instance.ReturnFocusId);
}
private RecordingSecretStore RegisterEditableStore(bool reveal = false)
{
var store = new RecordingSecretStore();
var cipher = new FakeCipher();
foreach (var metadata in new[] { SecretOne, SecretTwo })
store.Seed(cipher.Encrypt(metadata.Name, "synthetic fixture", metadata.ContentType) with { Description = metadata.Description });
Services.AddSingleton<ISecretStore>(store);
Services.AddSingleton<ISecretCipher>(cipher);
Services.AddSingleton<IAuditWriter>(new CapturingAuditWriter());
var auth = this.AddAuthorization();
auth.SetAuthorized("reviewer");
if (reveal) auth.SetPolicies(SecretsAuthorization.ManagePolicy, SecretsAuthorization.RevealPolicy);
else auth.SetPolicies(SecretsAuthorization.ManagePolicy);
return store;
}
/// <summary>Minimal hand-written <see cref="ISecretStore"/> whose only real behavior is <see cref="ListAsync"/>.</summary>
private sealed class FakeSecretStore(IReadOnlyList<SecretMetadata> rows) : ISecretStore
{
public Task<IReadOnlyList<SecretMetadata>> ListAsync(bool includeDeleted, CancellationToken ct)
=> Task.FromResult(rows);
public Task<StoredSecret?> GetAsync(SecretName name, CancellationToken ct)
=> throw new NotSupportedException();
public Task UpsertAsync(StoredSecret row, CancellationToken ct)
=> throw new NotSupportedException();
public Task<bool> DeleteAsync(SecretName name, string? actor, CancellationToken ct)
=> throw new NotSupportedException();
public Task<IReadOnlyList<SecretManifestEntry>> GetManifestAsync(CancellationToken ct)
=> throw new NotSupportedException();
public Task ApplyReplicatedAsync(StoredSecret row, CancellationToken ct)
=> throw new NotSupportedException();
public Task<bool> ApplyRewrapAsync(
StoredSecret rewrappedRow, byte[] expectedCurrentWrappedDek, CancellationToken ct)
=> throw new NotSupportedException();
}
}