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

385 lines
17 KiB
C#

using Bunit;
using Bunit.TestDoubles;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.JSInterop;
using System.Collections.Concurrent;
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 ConfirmDeleteModalTests : BunitContext
{
public ConfirmDeleteModalTests() => DialogInterop.Setup(JSInterop);
[Fact]
public void DeleteDialog_HasANameLinkedToTheExactTarget()
{
Services.AddSingleton<ISecretStore>(new RecordingSecretStore());
Services.AddSingleton<IAuditWriter>(new CapturingAuditWriter());
var cut = Render<ConfirmDeleteModal>(p => p
.Add(x => x.Visible, true).Add(x => x.Name, new SecretName("app/a")));
var dialog = cut.Find("[role=dialog]");
var titleId = dialog.GetAttribute("aria-labelledby");
Assert.False(string.IsNullOrWhiteSpace(titleId));
Assert.Contains("app/a", cut.Find($"[id='{titleId}']").TextContent);
Assert.Equal("true", dialog.GetAttribute("aria-modal"));
var descriptionId = dialog.GetAttribute("aria-describedby");
Assert.False(string.IsNullOrWhiteSpace(descriptionId));
Assert.Contains("tombstones", cut.Find($"[id='{descriptionId}']").TextContent);
}
[Fact]
public void ConfirmDeleteModal_IsInPageModal_NoJsDialog()
{
// Strict interop permits only the exact DOM-enhancement module configured by the fixture.
// Any browser confirm/alert call remains unhandled and fails the test.
JSInterop.Mode = JSRuntimeMode.Strict;
var store = new RecordingSecretStore();
var audit = new CapturingAuditWriter();
Services.AddSingleton<ISecretStore>(store);
Services.AddSingleton<IAuditWriter>(audit);
var name = new SecretName("db/primary");
var auth = this.AddAuthorization();
auth.SetAuthorized("carol");
auth.SetPolicies(SecretsAuthorization.ManagePolicy);
bool deleted = false;
var cut = Render<ConfirmDeleteModal>(p => p
.Add(c => c.Visible, true)
.Add(c => c.Name, name)
.Add(c => c.OnDeleted, () => deleted = true));
// The confirmation is a rendered in-page modal element.
Assert.NotEmpty(cut.FindAll(".zb-secrets-modal"));
Assert.Contains("db/primary", cut.Markup);
cut.Find("[data-testid=confirm-delete]").Click();
// Confirm tombstoned the row (with the resolved actor) and wrote a secret.delete audit.
Assert.Single(store.Deletes);
Assert.Equal("db/primary", store.Deletes[0].Name.Value);
Assert.Equal("carol", store.Deletes[0].Actor);
Assert.True(deleted);
Assert.Single(audit.Events);
AuditEvent evt = audit.Events[0];
Assert.Equal("secret.delete", evt.Action);
Assert.Equal(AuditOutcome.Success, evt.Outcome);
Assert.Equal("Secrets", evt.Category);
Assert.Equal("db/primary", evt.Target);
Assert.Equal("carol", evt.Actor);
}
[Fact]
public void ConfirmDeleteModal_Cancel_DoesNotDelete()
{
var store = new RecordingSecretStore();
var audit = new CapturingAuditWriter();
Services.AddSingleton<ISecretStore>(store);
Services.AddSingleton<IAuditWriter>(audit);
var name = new SecretName("db/primary");
var auth = this.AddAuthorization();
auth.SetAuthorized("carol");
auth.SetPolicies(SecretsAuthorization.ManagePolicy);
bool cancelled = false;
var cut = Render<ConfirmDeleteModal>(p => p
.Add(c => c.Visible, true)
.Add(c => c.Name, name)
.Add(c => c.OnCancelled, () => cancelled = true));
cut.Find("[data-testid=cancel-delete]").Click();
Assert.True(cancelled);
Assert.Empty(store.Deletes);
Assert.Empty(audit.Events);
}
[Fact]
public void ConfirmDeleteModal_StoreFault_AuditsFailure_ShowsError_DoesNotThrow()
{
var store = new RecordingSecretStore
{
DeleteFault = new MasterKeyUnavailableException("KEK unavailable."),
};
var audit = new CapturingAuditWriter();
Services.AddSingleton<ISecretStore>(store);
Services.AddSingleton<IAuditWriter>(audit);
var name = new SecretName("db/primary");
var auth = this.AddAuthorization();
auth.SetAuthorized("carol");
auth.SetPolicies(SecretsAuthorization.ManagePolicy);
bool deleted = false;
var cut = Render<ConfirmDeleteModal>(p => p
.Add(c => c.Visible, true)
.Add(c => c.Name, name)
.Add(c => c.OnDeleted, () => deleted = true));
// The click must not throw into the Blazor event pipeline.
cut.Find("[data-testid=confirm-delete]").Click();
// OnDeleted not raised; a Failure audit recorded; an error surfaced.
Assert.False(deleted);
Assert.Single(audit.Events);
AuditEvent evt = audit.Events[0];
Assert.Equal("secret.delete", evt.Action);
Assert.Equal(AuditOutcome.Failure, evt.Outcome);
Assert.Equal("Secrets", evt.Category);
Assert.Equal("db/primary", evt.Target);
Assert.Equal("carol", evt.Actor);
Assert.NotEmpty(cut.FindAll("[data-testid=delete-error]"));
}
[Fact]
public void ConfirmDeleteModal_NotVisible_RendersNothing()
{
var store = new RecordingSecretStore();
var audit = new CapturingAuditWriter();
Services.AddSingleton<ISecretStore>(store);
Services.AddSingleton<IAuditWriter>(audit);
var name = new SecretName("db/primary");
this.AddAuthorization().SetAuthorized("carol");
var cut = Render<ConfirmDeleteModal>(p => p
.Add(c => c.Visible, false)
.Add(c => c.Name, name));
Assert.Empty(cut.FindAll(".zb-secrets-modal"));
}
/// <summary>
/// scadaproj#2 regression pins. The modal previously used the bare <c>modal</c> class and
/// shipped no CSS, silently depending on the host having no opinion about it — Bootstrap 5's
/// <c>.modal { display: none }</c> made the overlay permanently invisible on every
/// Bootstrap host (ScadaBridge, OtOpcUa, HistorianGateway) while every handler kept working.
/// </summary>
[Fact]
public void ConfirmDeleteModal_UsesNoFrameworkReservedClassNames()
{
var cut = RenderVisibleModal();
// Bootstrap owns these selectors; any element carrying one is again at the mercy of
// whatever stylesheet the host happens to link.
string[] reserved = ["modal", "modal-title", "modal-backdrop", "modal-dialog", "modal-content"];
foreach (string cls in reserved)
{
Assert.Empty(cut.FindAll($".{cls}"));
}
// The elements themselves still render, under the component-scoped vocabulary.
Assert.NotEmpty(cut.FindAll(".zb-secrets-modal"));
Assert.NotEmpty(cut.FindAll(".zb-secrets-modal-backdrop"));
Assert.NotEmpty(cut.FindAll(".zb-secrets-modal-card"));
}
[Fact]
public void ConfirmDeleteModal_ShipsItsOwnStyles()
{
var cut = RenderVisibleModal();
// The RCL must carry the modal's CSS itself: no family host links a Secrets.Ui
// stylesheet, and three of the four never link a scoped-CSS bundle at all — so any
// styling delivered outside the component silently fails to load exactly like the
// original defect. The inline block must both position the overlay and give it a
// display mode, or a host reset/framework rule can hide it again.
var style = cut.FindAll("style").SingleOrDefault();
Assert.NotNull(style);
Assert.Contains(".zb-secrets-modal", style.TextContent);
Assert.Contains("position: fixed", style.TextContent);
Assert.Contains("display: flex", style.TextContent);
}
[Fact]
public async Task PendingDelete_BlocksCancelEscapeAndDuplicateActivation()
{
var store = new RecordingSecretStore();
Services.AddSingleton<ISecretStore>(store);
Services.AddSingleton<IAuditWriter>(new CapturingAuditWriter());
var auth = this.AddAuthorization();
auth.SetAuthorized("reviewer");
auth.SetPolicies(SecretsAuthorization.ManagePolicy);
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
store.DeleteOverride = (_, _, _) => { entered.TrySetResult(); return release.Task; };
bool cancelled = false;
var cut = Render<ConfirmDeleteModal>(p => p.Add(x => x.Visible, true)
.Add(x => x.Name, new SecretName("app/a")).Add(x => x.OnCancelled, () => cancelled = true));
var pending = cut.Find("[data-testid=confirm-delete]").ClickAsync(new MouseEventArgs());
await entered.Task;
try
{
Assert.True(cut.Find("[data-testid=cancel-delete]").HasAttribute("disabled"));
Assert.Equal("true", cut.Find("[role=dialog]").GetAttribute("aria-busy"));
cut.Find("[data-testid=cancel-delete]").Click();
await cut.InvokeAsync(() => cut.Instance.RequestCancelAsync());
cut.Find("[data-testid=confirm-delete]").Click();
Assert.False(cancelled);
Assert.Empty(store.Deletes);
}
finally { release.TrySetResult(); await pending; }
Assert.Single(store.Deletes);
}
[Fact]
public async Task ForcedTargetChangeAfterDeleteStarts_KeepsCommittedAuditAndCacheOnCapturedTarget()
{
var store = new RecordingSecretStore();
var audit = new CapturingAuditWriter();
var cache = new RecordingCacheInvalidator();
Services.AddSingleton<ISecretStore>(store);
Services.AddSingleton<IAuditWriter>(audit);
Services.AddSingleton<ISecretCacheInvalidator>(cache);
var auth = this.AddAuthorization();
auth.SetAuthorized("reviewer");
auth.SetPolicies(SecretsAuthorization.ManagePolicy);
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
store.DeleteOverride = (_, _, _) => { entered.TrySetResult(); return release.Task; };
bool deleted = false;
var a = new SecretName("app/a");
var cut = Render<ConfirmDeleteModal>(p => p.Add(x => x.Visible, true)
.Add(x => x.Name, a).Add(x => x.OnDeleted, () => deleted = true));
var pending = cut.Find("[data-testid=confirm-delete]").ClickAsync(new MouseEventArgs());
await entered.Task;
try { cut.Render(p => p.Add(x => x.Visible, true).Add(x => x.Name, new SecretName("app/b"))); }
finally { release.TrySetResult(); await pending; }
Assert.Equal(a, Assert.Single(store.Deletes).Name);
Assert.Equal(a.Value, Assert.Single(audit.Events).Target);
Assert.Equal(a, Assert.Single(cache.Invalidated));
Assert.False(deleted);
Assert.Contains("app/b", cut.Find("[role=dialog]").TextContent);
}
[Fact]
public async Task DisposalDuringDeferredOpen_ClosesBeforeDisposingTheModule()
{
RegisterDialogServices();
var module = RegisterDeferredModule();
var cut = Render<ConfirmDeleteModal>(p => p.Add(x => x.Visible, true).Add(x => x.Name, new SecretName("app/a")));
await module.OpenEntered.Task;
var disposal = cut.InvokeAsync(() => cut.Instance.DisposeAsync().AsTask());
var repeatedDisposal = cut.InvokeAsync(() => cut.Instance.DisposeAsync().AsTask());
await cut.InvokeAsync(() => Task.CompletedTask); // Let disposal reach the in-flight activation gate.
try
{
Assert.False(disposal.IsCompleted);
Assert.False(repeatedDisposal.IsCompleted);
Assert.DoesNotContain("dispose", module.Events);
}
finally { module.OpenRelease.TrySetResult(); }
await Task.WhenAll(disposal, repeatedDisposal);
Assert.Equal(new[] { "open:start", "open:end", "close", "dispose" }, module.Events);
Assert.False(module.Active);
}
[Theory]
[InlineData(0)] // target changes while opening
[InlineData(1)] // visibility becomes false while opening
[InlineData(2)] // false then a newer visible identity while opening
public async Task SupersededOpening_CannotCloseANewerVisibleIdentity(int transition)
{
RegisterDialogServices();
var module = RegisterDeferredModule();
var cut = Render<ConfirmDeleteModal>(p => p.Add(x => x.Visible, true).Add(x => x.Name, new SecretName("app/a")));
await module.OpenEntered.Task;
if (transition != 0) cut.Render(p => p.Add(x => x.Visible, false).Add(x => x.Name, new SecretName("app/a")));
if (transition != 1) cut.Render(p => p.Add(x => x.Visible, true).Add(x => x.Name, new SecretName("app/b")));
module.OpenRelease.SetResult();
await module.Closed.Task.WaitAsync(TimeSpan.FromSeconds(5));
if (transition != 1) await module.SecondOpenCompleted.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.Equal(1, module.Events.Count(x => x == "close"));
Assert.Equal(transition == 1 ? 1 : 2, module.Events.Count(x => x == "open:end"));
Assert.Equal(transition != 1, module.Active);
if (transition != 1) Assert.Contains("app/b", cut.Find("[role=dialog]").TextContent);
else Assert.Empty(cut.FindAll("[role=dialog]"));
}
private void RegisterDialogServices()
{
Services.AddSingleton<ISecretStore>(new RecordingSecretStore());
Services.AddSingleton<IAuditWriter>(new CapturingAuditWriter());
}
private DeferredDialogModule RegisterDeferredModule()
{
var module = new DeferredDialogModule();
// Exact import only; all other runtime calls remain strict and unhandled.
Services.AddSingleton<IJSRuntime>(new StrictDialogRuntime(module));
return module;
}
private sealed class StrictDialogRuntime(DeferredDialogModule module) : IJSRuntime
{
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, object?[]? args)
=> InvokeAsync<TValue>(identifier, CancellationToken.None, args);
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, CancellationToken ct, object?[]? args)
{
if (identifier != "import" || args is not ["./_content/ZB.MOM.WW.Secrets.Ui/js/secrets-dialog.js"] || typeof(TValue) != typeof(IJSObjectReference))
throw new JSException($"Unexpected runtime interop: {identifier}");
return ValueTask.FromResult((TValue)(object)module);
}
}
private sealed class DeferredDialogModule : IJSObjectReference
{
private readonly ConcurrentQueue<string> _events = new();
private bool _disposed;
private int _opens;
public TaskCompletionSource Closed { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource SecondOpenCompleted { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource OpenEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource OpenRelease { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public IReadOnlyList<string> Events => _events.ToArray();
public bool Active { get; private set; }
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, object?[]? args)
=> InvokeAsync<TValue>(identifier, CancellationToken.None, args);
public async ValueTask<TValue> InvokeAsync<TValue>(string identifier, CancellationToken ct, object?[]? args)
{
if (_disposed) throw new ObjectDisposedException(nameof(DeferredDialogModule));
switch (identifier)
{
case "open":
_events.Enqueue("open:start");
OpenEntered.TrySetResult();
await OpenRelease.Task;
Active = true;
_events.Enqueue("open:end");
if (++_opens == 2) SecondOpenCompleted.TrySetResult();
break;
case "close": Active = false; _events.Enqueue("close"); Closed.TrySetResult(); break;
case "setBusy": _events.Enqueue("setBusy"); break;
default: throw new JSException($"Unexpected dialog interop: {identifier}");
}
return default!;
}
public ValueTask DisposeAsync()
{
_events.Enqueue("dispose");
_disposed = true;
return ValueTask.CompletedTask;
}
}
private IRenderedComponent<ConfirmDeleteModal> RenderVisibleModal()
{
Services.AddSingleton<ISecretStore>(new RecordingSecretStore());
Services.AddSingleton<IAuditWriter>(new CapturingAuditWriter());
this.AddAuthorization().SetAuthorized("carol");
return Render<ConfirmDeleteModal>(p => p
.Add(c => c.Visible, true)
.Add(c => c.Name, new SecretName("db/primary")));
}
}