feat(secrets-ui): add metadata filtering and private reveal outcomes

This commit is contained in:
Joseph Doherty
2026-11-13 17:50:56 -05:00
parent 37cf0ff444
commit 46556dbb56
57 changed files with 5680 additions and 160 deletions
@@ -19,7 +19,7 @@ namespace ZB.MOM.WW.Secrets.Ui.Tests;
/// </summary>
public class ComponentAuthorizationTests : BunitContext
{
public ComponentAuthorizationTests() => DialogInterop.Setup(JSInterop);
public ComponentAuthorizationTests() { DialogInterop.Setup(JSInterop); RevealInterop.Setup(JSInterop); }
private const string PlainValue = "the-plaintext-value-42";
@@ -21,6 +21,9 @@ public sealed class RecordingSecretStore : ISecretStore
/// <summary>Optional controlled read, including fixtures that deliberately ignore cancellation.</summary>
public Func<SecretName, CancellationToken, Task<StoredSecret?>>? GetOverride { get; set; }
/// <summary>Optional delay before a read, without replacing the store's normal row behavior.</summary>
public Func<SecretName, CancellationToken, Task>? BeforeGetAsync { get; set; }
/// <summary>Optional hook awaited before the normal recorded upsert commits.</summary>
public Func<StoredSecret, CancellationToken, Task>? UpsertOverride { get; set; }
@@ -55,12 +58,13 @@ public sealed class RecordingSecretStore : ISecretStore
public void Seed(StoredSecret row) => _rows[row.Name.Value] = row;
/// <inheritdoc />
public Task<StoredSecret?> GetAsync(SecretName name, CancellationToken ct)
public async Task<StoredSecret?> GetAsync(SecretName name, CancellationToken ct)
{
_gets.Enqueue(name);
if (BeforeGetAsync is not null) await BeforeGetAsync(name, ct);
return GetOverride is null
? Task.FromResult(_rows.TryGetValue(name.Value, out StoredSecret? row) ? row : null)
: GetOverride(name, ct);
? (_rows.TryGetValue(name.Value, out StoredSecret? row) ? row : null)
: await GetOverride(name, ct);
}
/// <inheritdoc />
@@ -0,0 +1,10 @@
using Bunit;
namespace ZB.MOM.WW.Secrets.Ui.Tests.Fakes;
internal static class RevealInterop
{
internal static void Setup(BunitJSInterop js)
{
var module = js.SetupModule("./_content/ZB.MOM.WW.Secrets.Ui/js/secrets-reveal.js");
module.SetupVoid("focusIfUnclaimed", _ => true).SetVoidResult();
}
}
@@ -15,6 +15,8 @@ namespace ZB.MOM.WW.Secrets.Ui.Tests;
/// </summary>
public class RevealAuditFailureTests : BunitContext
{
public RevealAuditFailureTests() => RevealInterop.Setup(JSInterop);
private const string PlainValue = "the-plaintext-value-42";
private sealed class CapturingLogger<T> : ILogger<T>
@@ -57,6 +59,12 @@ public class RevealAuditFailureTests : BunitContext
Assert.DoesNotContain(PlainValue, cut.Markup);
Assert.Empty(cut.FindAll("[data-testid=revealed-value]"));
Assert.Contains("audit", cut.Find("[data-testid=reveal-error]").TextContent);
var status = cut.Find("[data-testid=reveal-status][role=status]");
Assert.Contains("Reveal failed", status.TextContent);
Assert.DoesNotContain(PlainValue, status.TextContent);
var described = cut.Find("[data-testid=hide-button]").GetAttribute("aria-describedby")!.Split(' ');
Assert.Contains(cut.Find("[data-testid=reveal-error]").Id, described);
Assert.All(described, id => Assert.NotNull(cut.Find($"[id='{id}']")));
(LogLevel level, string message) = Assert.Single(logger.Entries);
Assert.Equal(LogLevel.Warning, level);
@@ -1,5 +1,9 @@
using Bunit;
using Bunit.TestDoubles;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Web;
using System.Security.Claims;
using Microsoft.Extensions.DependencyInjection;
using ZB.MOM.WW.Audit;
using ZB.MOM.WW.Secrets.Abstractions;
@@ -10,6 +14,8 @@ namespace ZB.MOM.WW.Secrets.Ui.Tests;
public class RevealButtonTests : BunitContext
{
public RevealButtonTests() => RevealInterop.Setup(JSInterop);
private const string PlainValue = "the-plaintext-value-42";
private (RecordingSecretStore Store, CapturingAuditWriter Audit, FakeCipher Cipher) RegisterServices()
@@ -114,6 +120,180 @@ public class RevealButtonTests : BunitContext
AssertNoValueLeak(evt);
}
[Fact]
public void RevealOutcome_IsNonSensitiveAndHideClearsTheValueWithStableControlIdentity()
{
var (store, _, _) = RegisterServices();
AuthorizeReveal();
var name = new SecretName("app/a");
store.Seed(Row(name, PlainValue));
var cut = Render<RevealButton>(p => p.Add(x => x.Name, name));
string? controlId = cut.Find("[data-testid=reveal-button]").Id;
Assert.False(string.IsNullOrWhiteSpace(controlId));
Assert.Equal("", cut.Find("[data-testid=reveal-status][role=status]").TextContent);
cut.Find("[data-testid=reveal-button]").Click();
Assert.Equal(PlainValue, cut.Find("[data-testid=revealed-value]").TextContent);
var status = cut.Find("[data-testid=reveal-status][role=status]");
Assert.Contains("Value revealed", status.TextContent);
Assert.DoesNotContain(PlainValue, status.TextContent);
Assert.DoesNotContain(PlainValue, cut.Find("[data-testid=hide-button]").GetAttribute("aria-label"));
Assert.Equal(controlId, cut.Find("[data-testid=hide-button]").Id);
cut.Find("[data-testid=hide-button]").Click();
Assert.Empty(cut.FindAll("[data-testid=revealed-value]"));
Assert.DoesNotContain(PlainValue, cut.Markup);
Assert.Contains("hidden", cut.Find("[data-testid=reveal-status]").TextContent);
Assert.Equal(controlId, cut.Find("[data-testid=reveal-button]").Id);
}
[Fact]
public void ChangingRevealTarget_ClearsEarlierPlaintextAndOutcome()
{
var (store, audit, _) = RegisterServices();
AuthorizeReveal();
var a = new SecretName("app/a"); var b = new SecretName("app/b");
store.Seed(Row(a, "synthetic-a-value")); store.Seed(Row(b, "synthetic-b-value"));
var cut = Render<RevealButton>(p => p.Add(x => x.Name, a));
cut.Find("[data-testid=reveal-button]").Click();
Assert.Contains("synthetic-a-value", cut.Markup);
cut.Render(p => p.Add(x => x.Name, b));
Assert.DoesNotContain("synthetic-a-value", cut.Markup);
Assert.Equal("", cut.Find("[data-testid=reveal-status]").TextContent);
Assert.Equal("Reveal app/b", cut.Find("[data-testid=reveal-button]").GetAttribute("aria-label"));
cut.Find("[data-testid=reveal-button]").Click();
Assert.Equal("synthetic-b-value", cut.Find("[data-testid=revealed-value]").TextContent);
Assert.Equal(new[] { a.Value, b.Value }, audit.Events.Select(x => x.Target));
}
[Fact]
public async Task SupersededRevealRead_IsCancelledAndCannotDiscloseUnderTheNewTarget()
{
var (store, audit, _) = RegisterServices(); AuthorizeReveal();
var a = new SecretName("app/a"); var b = new SecretName("app/b");
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource<StoredSecret?>(TaskCreationOptions.RunContinuationsAsynchronously);
CancellationToken aToken = default;
store.GetOverride = (name, ct) =>
{
if (name == b) return Task.FromResult<StoredSecret?>(Row(b, "synthetic-b-value"));
aToken = ct; entered.TrySetResult(); return release.Task;
};
var cut = Render<RevealButton>(p => p.Add(x => x.Name, a));
var pending = cut.Find("[data-testid=reveal-button]").ClickAsync(new MouseEventArgs());
await entered.Task;
try
{
cut.Render(p => p.Add(x => x.Name, b));
Assert.True(aToken.IsCancellationRequested);
cut.Find("[data-testid=reveal-button]").Click();
}
finally { release.TrySetResult(Row(a, "synthetic-a-value")); await pending; }
Assert.DoesNotContain("synthetic-a-value", cut.Markup);
Assert.Equal("synthetic-b-value", cut.Find("[data-testid=revealed-value]").TextContent);
Assert.Equal(b.Value, Assert.Single(audit.Events).Target);
}
[Fact]
public async Task PendingAuthorization_DisablesDuplicateRevealBeforeTheRead()
{
var (store, audit, _) = RegisterServices(); AuthorizeReveal();
var name = new SecretName("app/a"); store.Seed(Row(name, PlainValue));
var auth = new TaskCompletionSource<AuthenticationState>(TaskCreationOptions.RunContinuationsAsynchronously);
RenderFragment child = builder =>
{
builder.OpenComponent<RevealButton>(0);
builder.AddAttribute(1, nameof(RevealButton.Name), (object)name);
builder.CloseComponent();
};
var cut = Render<CascadingValue<Task<AuthenticationState>>>(p => p.Add(x => x.Value, auth.Task).AddChildContent(child));
var first = cut.Find("[data-testid=reveal-button]").ClickAsync(new MouseEventArgs());
var second = cut.Find("[data-testid=reveal-button]").ClickAsync(new MouseEventArgs());
try
{
Assert.True(cut.Find("[data-testid=reveal-button]").HasAttribute("disabled"));
Assert.Empty(store.Gets);
}
finally
{
auth.TrySetResult(new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity([new Claim(ClaimTypes.Name, "reviewer")], "fixture"))));
await Task.WhenAll(first, second);
}
Assert.Single(store.Gets);
Assert.Single(audit.Events);
}
[Fact]
public async Task AuditCompletesAfterTargetChange_NeverPublishesOldPlaintext()
{
var (store, _, _) = RegisterServices(); AuthorizeReveal();
var audit = new DeferredRevealAudit(); Services.AddSingleton<IAuditWriter>(audit);
var a = new SecretName("app/a"); var b = new SecretName("app/b");
store.Seed(Row(a, "synthetic-a-value"));
var cut = Render<RevealButton>(p => p.Add(x => x.Name, a));
var pending = cut.Find("[data-testid=reveal-button]").ClickAsync(new MouseEventArgs());
await audit.Entered.Task;
try { cut.Render(p => p.Add(x => x.Name, b)); }
finally { audit.Release.TrySetResult(); await pending; }
Assert.Equal(a.Value, Assert.Single(audit.Events).Target);
Assert.DoesNotContain("synthetic-a-value", cut.Markup);
Assert.Empty(cut.FindAll("[data-testid=revealed-value]"));
Assert.Equal("", cut.Find("[data-testid=reveal-status]").TextContent);
}
[Fact]
public async Task RemovedReveal_CancelsAndDoesNotResolveDisposedScopeAfterRead()
{
var (store, audit, _) = RegisterServices(); AuthorizeReveal();
var provider = new RevealScopeGuard(Services);
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource<StoredSecret?>(TaskCreationOptions.RunContinuationsAsynchronously);
CancellationToken token = default;
store.GetOverride = (_, ct) => { token = ct; entered.TrySetResult(); return release.Task; };
var name = new SecretName("app/a");
RenderFragment child = builder => { builder.OpenComponent<RevealButton>(0); builder.AddAttribute(1, nameof(RevealButton.Name), (object)name); builder.CloseComponent(); };
var cut = Render<CascadingValue<bool>>(p => p.Add(x => x.Value, true).AddChildContent(child));
typeof(RevealButton).GetProperty("Services", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
.SetValue(cut.FindComponent<RevealButton>().Instance, provider);
var pending = cut.Find("[data-testid=reveal-button]").ClickAsync(new MouseEventArgs());
await entered.Task;
Assert.True(provider.Resolutions > 0);
int resolutions = provider.Resolutions;
cut.Render(p => p.Add(x => x.Value, true).AddChildContent((RenderFragment)(_ => { })));
Assert.True(token.IsCancellationRequested);
provider.Reject = true;
release.SetResult(Row(name, PlainValue));
await pending;
Assert.Equal(resolutions, provider.Resolutions);
Assert.Empty(audit.Events);
Assert.DoesNotContain(PlainValue, cut.Markup);
}
private void AuthorizeReveal()
{
var auth = this.AddAuthorization(); auth.SetAuthorized("reviewer");
auth.SetPolicies(SecretsAuthorization.RevealPolicy);
}
private sealed class DeferredRevealAudit : IAuditWriter
{
public TaskCompletionSource Entered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously);
public List<AuditEvent> Events { get; } = [];
public async Task WriteAsync(AuditEvent evt, CancellationToken ct = default)
{ Entered.TrySetResult(); await Release.Task; Events.Add(evt); }
}
private sealed class RevealScopeGuard(IServiceProvider inner) : IServiceProvider
{
public bool Reject { get; set; }
public int Resolutions { get; private set; }
public object? GetService(Type type)
{
++Resolutions;
if (Reject) throw new ObjectDisposedException("synthetic circuit scope");
return inner.GetService(type);
}
}
private static void AssertNoValueLeak(AuditEvent evt)
{
foreach (string? field in new[] { evt.Action, evt.Actor, evt.Category, evt.Target, evt.DetailsJson, evt.ToString() })
@@ -13,7 +13,12 @@ namespace ZB.MOM.WW.Secrets.Ui.Tests;
public class SecretsListTests : BunitContext
{
public SecretsListTests() => DialogInterop.Setup(JSInterop);
public SecretsListTests()
{
DialogInterop.Setup(JSInterop);
RevealInterop.Setup(JSInterop);
JSInterop.SetupVoid("Blazor._internal.domWrapper.focus", _ => true).SetVoidResult();
}
private static readonly SecretMetadata SecretOne = new()
{
@@ -339,7 +344,104 @@ public class SecretsListTests : BunitContext
Assert.Empty(cut.FindAll("table"));
}
private RecordingSecretStore RegisterEditableStore()
[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();
@@ -350,7 +452,8 @@ public class SecretsListTests : BunitContext
Services.AddSingleton<IAuditWriter>(new CapturingAuditWriter());
var auth = this.AddAuthorization();
auth.SetAuthorized("reviewer");
auth.SetPolicies(SecretsAuthorization.ManagePolicy);
if (reveal) auth.SetPolicies(SecretsAuthorization.ManagePolicy, SecretsAuthorization.RevealPolicy);
else auth.SetPolicies(SecretsAuthorization.ManagePolicy);
return store;
}