feat(secrets-ui): add/rotate/delete modal + audited gated reveal
This commit is contained in:
@@ -0,0 +1,95 @@
|
||||
@namespace ZB.MOM.WW.Secrets.Ui.Components
|
||||
@implements IDisposable
|
||||
@inject ISecretStore Store
|
||||
@inject IAuditWriter Audit
|
||||
@inject IServiceProvider Services
|
||||
@* Components/ConfirmDeleteModal.razor — an in-page Blazor overlay (NOT a JS confirm/alert dialog).
|
||||
Shown while Visible is true; Confirm tombstones + audits the delete, Cancel dismisses. *@
|
||||
|
||||
@if (Visible)
|
||||
{
|
||||
<div class="modal-backdrop-inpage" data-testid="delete-modal-backdrop"></div>
|
||||
<div class="modal" role="dialog" aria-modal="true" data-testid="delete-modal">
|
||||
<div class="modal-card">
|
||||
<h3 class="modal-title">Delete secret '@Name.Value'?</h3>
|
||||
<p>This tombstones the secret so the removal can propagate. The action is audited.</p>
|
||||
|
||||
@if (_error is not null)
|
||||
{
|
||||
<p class="field-error s-bad" data-testid="delete-error">@_error</p>
|
||||
}
|
||||
|
||||
<div class="btn-row">
|
||||
<TechButton Variant="ButtonVariant.Danger" Busy="_busy"
|
||||
data-testid="confirm-delete" @onclick="ConfirmAsync">
|
||||
Delete
|
||||
</TechButton>
|
||||
<TechButton Variant="ButtonVariant.Secondary"
|
||||
data-testid="cancel-delete" @onclick="CancelAsync">
|
||||
Cancel
|
||||
</TechButton>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
|
||||
@code {
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private string? _error;
|
||||
private bool _busy;
|
||||
|
||||
/// <summary>Whether the modal overlay is rendered.</summary>
|
||||
[Parameter] public bool Visible { get; set; }
|
||||
|
||||
/// <summary>The secret the modal offers to delete.</summary>
|
||||
[Parameter] public SecretName Name { get; set; }
|
||||
|
||||
/// <summary>Raised after the secret has been tombstoned and audited.</summary>
|
||||
[Parameter] public EventCallback OnDeleted { get; set; }
|
||||
|
||||
/// <summary>Raised when the user cancels the deletion.</summary>
|
||||
[Parameter] public EventCallback OnCancelled { get; set; }
|
||||
|
||||
/// <summary>The cascading authentication state, used as the fallback source of the audit actor.</summary>
|
||||
[CascadingParameter] private Task<AuthenticationState>? AuthState { get; set; }
|
||||
|
||||
private async Task ConfirmAsync()
|
||||
{
|
||||
_error = null;
|
||||
_busy = true;
|
||||
try
|
||||
{
|
||||
string actor = await SecretActorResolver.ResolveAsync(Services, AuthState);
|
||||
|
||||
await Store.DeleteAsync(Name, actor, _cts.Token);
|
||||
|
||||
await Audit.WriteAsync(
|
||||
new AuditEvent
|
||||
{
|
||||
EventId = Guid.NewGuid(),
|
||||
OccurredAtUtc = DateTimeOffset.UtcNow,
|
||||
Actor = actor,
|
||||
Action = "secret.delete",
|
||||
Outcome = AuditOutcome.Success,
|
||||
Category = "Secrets",
|
||||
Target = Name.Value,
|
||||
},
|
||||
_cts.Token);
|
||||
|
||||
await OnDeleted.InvokeAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private Task CancelAsync() => OnCancelled.InvokeAsync();
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
_cts.Cancel();
|
||||
_cts.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
@namespace ZB.MOM.WW.Secrets.Ui.Components
|
||||
@implements IDisposable
|
||||
@inject ISecretStore Store
|
||||
@inject ISecretCipher Cipher
|
||||
@inject IAuditWriter Audit
|
||||
@inject IServiceProvider Services
|
||||
@* Components/RevealButton.razor — a policy-gated, audited reveal. The plaintext is loaded and
|
||||
shown only AFTER the click, straight from the store+cipher (a human reveal shows the CURRENT
|
||||
value, distinct from any cached machine resolve). The value never enters an audit field. *@
|
||||
|
||||
@if (!_revealed)
|
||||
{
|
||||
<button type="button" class="btn btn-outline-secondary reveal-secret"
|
||||
disabled="@_busy" data-secret-name="@Name.Value"
|
||||
data-testid="reveal-button" @onclick="RevealAsync">
|
||||
Reveal
|
||||
</button>
|
||||
}
|
||||
else
|
||||
{
|
||||
<div class="reveal-panel" data-testid="reveal-panel">
|
||||
@if (_value is not null)
|
||||
{
|
||||
<code class="revealed-value" data-testid="revealed-value">@_value</code>
|
||||
}
|
||||
else
|
||||
{
|
||||
<span class="field-error s-bad" data-testid="reveal-error">@(_error ?? "Unavailable.")</span>
|
||||
}
|
||||
<button type="button" class="btn btn-link hide-secret"
|
||||
data-testid="hide-button" @onclick="Hide">
|
||||
Hide
|
||||
</button>
|
||||
</div>
|
||||
}
|
||||
|
||||
@code {
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private bool _revealed;
|
||||
private string? _value;
|
||||
private string? _error;
|
||||
private bool _busy;
|
||||
|
||||
/// <summary>The secret whose plaintext this button reveals.</summary>
|
||||
[Parameter] public SecretName Name { get; set; }
|
||||
|
||||
/// <summary>The cascading authentication state, used as the fallback source of the audit actor.</summary>
|
||||
[CascadingParameter] private Task<AuthenticationState>? AuthState { get; set; }
|
||||
|
||||
private async Task RevealAsync()
|
||||
{
|
||||
_busy = true;
|
||||
AuditOutcome outcome;
|
||||
try
|
||||
{
|
||||
StoredSecret? row = await Store.GetAsync(Name, _cts.Token);
|
||||
if (row is null)
|
||||
{
|
||||
_value = null;
|
||||
_error = "Secret not found.";
|
||||
outcome = AuditOutcome.Failure;
|
||||
}
|
||||
else
|
||||
{
|
||||
_value = Cipher.Decrypt(row);
|
||||
_error = null;
|
||||
outcome = AuditOutcome.Success;
|
||||
}
|
||||
}
|
||||
catch (SecretDecryptionException)
|
||||
{
|
||||
_value = null;
|
||||
_error = "Unable to decrypt secret.";
|
||||
outcome = AuditOutcome.Failure;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
_revealed = true;
|
||||
}
|
||||
|
||||
string actor = await SecretActorResolver.ResolveAsync(Services, AuthState);
|
||||
await Audit.WriteAsync(
|
||||
new AuditEvent
|
||||
{
|
||||
EventId = Guid.NewGuid(),
|
||||
OccurredAtUtc = DateTimeOffset.UtcNow,
|
||||
Actor = actor,
|
||||
Action = "secret.reveal",
|
||||
Outcome = outcome,
|
||||
Category = "Secrets",
|
||||
Target = Name.Value,
|
||||
},
|
||||
_cts.Token);
|
||||
}
|
||||
|
||||
private void Hide()
|
||||
{
|
||||
_revealed = false;
|
||||
_value = null;
|
||||
_error = null;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
_cts.Cancel();
|
||||
_cts.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
@namespace ZB.MOM.WW.Secrets.Ui.Components
|
||||
@implements IDisposable
|
||||
@inject ISecretCipher Cipher
|
||||
@inject ISecretStore Store
|
||||
@inject IAuditWriter Audit
|
||||
@inject IServiceProvider Services
|
||||
@* Components/SecretEditor.razor — add (ExistingName == null) or rotate (ExistingName set) a secret.
|
||||
The value is entered through a masked input and never rendered back or placed in any audit field. *@
|
||||
|
||||
<TechCard Title="@(IsRotate ? "Rotate secret" : "Add secret")">
|
||||
<TechField Label="Name">
|
||||
@if (IsRotate)
|
||||
{
|
||||
<input class="form-control mono" type="text" readonly
|
||||
value="@_name" data-testid="secret-name" />
|
||||
}
|
||||
else
|
||||
{
|
||||
<input class="form-control mono" type="text"
|
||||
@bind="_name" data-testid="secret-name" />
|
||||
}
|
||||
</TechField>
|
||||
|
||||
<TechField Label="Description">
|
||||
<input class="form-control" type="text" @bind="_description" data-testid="secret-description" />
|
||||
</TechField>
|
||||
|
||||
<TechField Label="Content type">
|
||||
<select class="form-select" @bind="_contentType" data-testid="secret-content-type">
|
||||
@foreach (SecretContentType ct in Enum.GetValues<SecretContentType>())
|
||||
{
|
||||
<option value="@ct">@ct</option>
|
||||
}
|
||||
</select>
|
||||
</TechField>
|
||||
|
||||
<TechField Label="Value">
|
||||
<input class="form-control mono" type="password" autocomplete="new-password"
|
||||
@bind="_value" data-testid="secret-value" />
|
||||
</TechField>
|
||||
|
||||
@if (_error is not null)
|
||||
{
|
||||
<p class="field-error s-bad" data-testid="editor-error">@_error</p>
|
||||
}
|
||||
|
||||
<div class="btn-row">
|
||||
<TechButton Variant="ButtonVariant.Primary" Busy="_busy"
|
||||
data-testid="editor-submit" @onclick="SubmitAsync">
|
||||
@(IsRotate ? "Rotate" : "Add")
|
||||
</TechButton>
|
||||
<TechButton Variant="ButtonVariant.Secondary"
|
||||
data-testid="editor-cancel" @onclick="CancelAsync">
|
||||
Cancel
|
||||
</TechButton>
|
||||
</div>
|
||||
</TechCard>
|
||||
|
||||
@code {
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
|
||||
private string _name = string.Empty;
|
||||
private string _description = string.Empty;
|
||||
private SecretContentType _contentType = SecretContentType.Text;
|
||||
private string _value = string.Empty;
|
||||
private string? _error;
|
||||
private bool _busy;
|
||||
|
||||
/// <summary>
|
||||
/// The secret being rotated. When <c>null</c> the editor is in <em>add</em> mode (name is
|
||||
/// editable); when set, the editor is in <em>rotate</em> mode (name is read-only and fixed).
|
||||
/// </summary>
|
||||
[Parameter] public SecretName? ExistingName { get; set; }
|
||||
|
||||
/// <summary>Raised after a successful add or rotate, so a parent can refresh its listing.</summary>
|
||||
[Parameter] public EventCallback OnSaved { get; set; }
|
||||
|
||||
/// <summary>Raised when the user cancels the editor without saving.</summary>
|
||||
[Parameter] public EventCallback OnCancelled { get; set; }
|
||||
|
||||
/// <summary>The cascading authentication state, used as the fallback source of the audit actor.</summary>
|
||||
[CascadingParameter] private Task<AuthenticationState>? AuthState { get; set; }
|
||||
|
||||
private bool IsRotate => ExistingName is not null;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override void OnParametersSet()
|
||||
{
|
||||
if (IsRotate)
|
||||
{
|
||||
_name = ExistingName!.Value.Value;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task SubmitAsync()
|
||||
{
|
||||
_error = null;
|
||||
|
||||
SecretName name;
|
||||
try
|
||||
{
|
||||
name = ExistingName ?? new SecretName(_name);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
_error = ex.Message;
|
||||
return;
|
||||
}
|
||||
|
||||
_busy = true;
|
||||
try
|
||||
{
|
||||
string actor = await SecretActorResolver.ResolveAsync(Services, AuthState);
|
||||
|
||||
StoredSecret row = Cipher.Encrypt(name, _value, _contentType);
|
||||
row = row with
|
||||
{
|
||||
Description = string.IsNullOrWhiteSpace(_description) ? null : _description,
|
||||
CreatedBy = actor,
|
||||
UpdatedBy = actor,
|
||||
};
|
||||
await Store.UpsertAsync(row, _cts.Token);
|
||||
|
||||
await Audit.WriteAsync(
|
||||
new AuditEvent
|
||||
{
|
||||
EventId = Guid.NewGuid(),
|
||||
OccurredAtUtc = DateTimeOffset.UtcNow,
|
||||
Actor = actor,
|
||||
Action = IsRotate ? "secret.rotate" : "secret.add",
|
||||
Outcome = AuditOutcome.Success,
|
||||
Category = "Secrets",
|
||||
Target = name.Value,
|
||||
},
|
||||
_cts.Token);
|
||||
|
||||
await OnSaved.InvokeAsync();
|
||||
}
|
||||
finally
|
||||
{
|
||||
_busy = false;
|
||||
}
|
||||
}
|
||||
|
||||
private Task CancelAsync() => OnCancelled.InvokeAsync();
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Dispose()
|
||||
{
|
||||
_cts.Cancel();
|
||||
_cts.Dispose();
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,24 @@
|
||||
@namespace ZB.MOM.WW.Secrets.Ui
|
||||
@implements IDisposable
|
||||
@inject ISecretStore Store
|
||||
@* Components/SecretsList.razor — metadata-only listing of secrets. Never renders a value or ciphertext. *@
|
||||
@* Components/SecretsList.razor — metadata-only listing of secrets. Never renders a value or
|
||||
ciphertext. Add/rotate use the in-page SecretEditor; delete uses the in-page ConfirmDeleteModal;
|
||||
reveal is the policy-gated, audited RevealButton. The list reloads after any mutation. *@
|
||||
|
||||
<AuthorizeView Policy="@SecretsAuthorization.ManagePolicy">
|
||||
<div class="toolbar btn-row">
|
||||
<TechButton Variant="ButtonVariant.Primary" data-testid="add-secret" @onclick="ShowAdd">
|
||||
Add secret
|
||||
</TechButton>
|
||||
</div>
|
||||
</AuthorizeView>
|
||||
|
||||
@if (_editorMode != EditorMode.None)
|
||||
{
|
||||
<SecretEditor ExistingName="_rotateName"
|
||||
OnSaved="OnMutatedAsync"
|
||||
OnCancelled="CloseEditor" />
|
||||
}
|
||||
|
||||
<TechCard Title="Secrets">
|
||||
@if (_secrets is null)
|
||||
@@ -43,16 +60,20 @@
|
||||
<td class="num">@secret.Revision</td>
|
||||
<td class="mono">@secret.UpdatedUtc.UtcDateTime.ToString("u")</td>
|
||||
<td>@secret.UpdatedBy</td>
|
||||
<td>
|
||||
<td class="row-actions">
|
||||
<AuthorizeView Policy="@SecretsAuthorization.RevealPolicy">
|
||||
@* Placeholder — actual reveal wiring is a later task. Gated so it
|
||||
renders only for principals holding the reveal policy. *@
|
||||
<button type="button"
|
||||
class="btn btn-outline-secondary reveal-secret"
|
||||
disabled
|
||||
title="Reveal (coming soon)"
|
||||
data-secret-name="@secret.Name.Value">
|
||||
Reveal
|
||||
<RevealButton Name="secret.Name" />
|
||||
</AuthorizeView>
|
||||
<AuthorizeView Policy="@SecretsAuthorization.ManagePolicy">
|
||||
<button type="button" class="btn btn-outline-secondary rotate-secret"
|
||||
data-secret-name="@secret.Name.Value"
|
||||
@onclick="() => ShowRotate(secret.Name)">
|
||||
Rotate
|
||||
</button>
|
||||
<button type="button" class="btn btn-danger delete-secret"
|
||||
data-secret-name="@secret.Name.Value"
|
||||
@onclick="() => ShowDelete(secret.Name)">
|
||||
Delete
|
||||
</button>
|
||||
</AuthorizeView>
|
||||
</td>
|
||||
@@ -65,14 +86,59 @@
|
||||
}
|
||||
</TechCard>
|
||||
|
||||
<ConfirmDeleteModal Visible="_deleteTarget.HasValue"
|
||||
Name="_deleteTarget.GetValueOrDefault()"
|
||||
OnDeleted="OnMutatedAsync"
|
||||
OnCancelled="CloseDelete" />
|
||||
|
||||
@code {
|
||||
private readonly CancellationTokenSource _cts = new();
|
||||
private IReadOnlyList<SecretMetadata>? _secrets;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnInitializedAsync()
|
||||
private EditorMode _editorMode = EditorMode.None;
|
||||
private SecretName? _rotateName;
|
||||
private SecretName? _deleteTarget;
|
||||
|
||||
private enum EditorMode
|
||||
{
|
||||
_secrets = await Store.ListAsync(includeDeleted: false, _cts.Token);
|
||||
None,
|
||||
Add,
|
||||
Rotate,
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override async Task OnInitializedAsync() => await ReloadAsync();
|
||||
|
||||
private async Task ReloadAsync()
|
||||
=> _secrets = await Store.ListAsync(includeDeleted: false, _cts.Token);
|
||||
|
||||
private void ShowAdd()
|
||||
{
|
||||
_rotateName = null;
|
||||
_editorMode = EditorMode.Add;
|
||||
}
|
||||
|
||||
private void ShowRotate(SecretName name)
|
||||
{
|
||||
_rotateName = name;
|
||||
_editorMode = EditorMode.Rotate;
|
||||
}
|
||||
|
||||
private void CloseEditor()
|
||||
{
|
||||
_editorMode = EditorMode.None;
|
||||
_rotateName = null;
|
||||
}
|
||||
|
||||
private void ShowDelete(SecretName name) => _deleteTarget = name;
|
||||
|
||||
private void CloseDelete() => _deleteTarget = null;
|
||||
|
||||
private async Task OnMutatedAsync()
|
||||
{
|
||||
CloseEditor();
|
||||
CloseDelete();
|
||||
await ReloadAsync();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ZB.MOM.WW.Secrets.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.Secrets.Ui;
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the principal to record as the audit <c>Actor</c> for a UI-driven secret mutation or
|
||||
/// reveal. The resolution order is: an explicitly wired <see cref="ISecretActorAccessor"/> (if the
|
||||
/// host registered one and it reports a non-blank actor); otherwise the authenticated user's
|
||||
/// <see cref="System.Security.Principal.IIdentity.Name"/> from the cascading authentication state;
|
||||
/// otherwise the literal <c>"unknown"</c> so an action is never attributed to a blank actor.
|
||||
/// </summary>
|
||||
internal static class SecretActorResolver
|
||||
{
|
||||
/// <summary>The fallback actor used when no accessor and no authenticated identity name is available.</summary>
|
||||
public const string Unknown = "unknown";
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the audit actor. Never returns <c>null</c> or blank.
|
||||
/// </summary>
|
||||
/// <param name="services">The component's service provider, used to optionally resolve an <see cref="ISecretActorAccessor"/>.</param>
|
||||
/// <param name="authState">The cascading authentication-state task, or <c>null</c> if unavailable.</param>
|
||||
/// <returns>The resolved actor identity string.</returns>
|
||||
public static async Task<string> ResolveAsync(IServiceProvider services, Task<AuthenticationState>? authState)
|
||||
{
|
||||
string? fromAccessor = services.GetService<ISecretActorAccessor>()?.CurrentActor;
|
||||
if (!string.IsNullOrWhiteSpace(fromAccessor))
|
||||
{
|
||||
return fromAccessor;
|
||||
}
|
||||
|
||||
if (authState is not null)
|
||||
{
|
||||
AuthenticationState state = await authState.ConfigureAwait(false);
|
||||
string? name = state.User.Identity?.Name;
|
||||
if (!string.IsNullOrWhiteSpace(name))
|
||||
{
|
||||
return name;
|
||||
}
|
||||
}
|
||||
|
||||
return Unknown;
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,7 @@
|
||||
<ItemGroup>
|
||||
<PackageReference Include="ZB.MOM.WW.Theme" />
|
||||
<PackageReference Include="ZB.MOM.WW.Auth.AspNetCore" />
|
||||
<PackageReference Include="ZB.MOM.WW.Audit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
@@ -2,6 +2,9 @@
|
||||
@using Microsoft.AspNetCore.Components.Authorization
|
||||
@using Microsoft.AspNetCore.Components.Web
|
||||
@using Microsoft.AspNetCore.Authorization
|
||||
@using Microsoft.Extensions.DependencyInjection
|
||||
@using ZB.MOM.WW.Theme
|
||||
@using ZB.MOM.WW.Audit
|
||||
@using ZB.MOM.WW.Secrets.Abstractions
|
||||
@using ZB.MOM.WW.Secrets.Ui
|
||||
@using ZB.MOM.WW.Secrets.Ui.Components
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
using Bunit;
|
||||
using Bunit.TestDoubles;
|
||||
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 : TestContext
|
||||
{
|
||||
[Fact]
|
||||
public void ConfirmDeleteModal_IsInPageModal_NoJsDialog()
|
||||
{
|
||||
// Strict JS interop mode: any IJSRuntime call (a JS confirm/alert dialog) would throw,
|
||||
// proving the confirmation is a rendered in-page modal, not a browser dialog.
|
||||
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.AddTestAuthorization();
|
||||
auth.SetAuthorized("carol");
|
||||
auth.SetPolicies(SecretsAuthorization.ManagePolicy);
|
||||
|
||||
bool deleted = false;
|
||||
var cut = RenderComponent<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(".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.AddTestAuthorization();
|
||||
auth.SetAuthorized("carol");
|
||||
auth.SetPolicies(SecretsAuthorization.ManagePolicy);
|
||||
|
||||
bool cancelled = false;
|
||||
var cut = RenderComponent<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_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.AddTestAuthorization().SetAuthorized("carol");
|
||||
|
||||
var cut = RenderComponent<ConfirmDeleteModal>(p => p
|
||||
.Add(c => c.Visible, false)
|
||||
.Add(c => c.Name, name));
|
||||
|
||||
Assert.Empty(cut.FindAll(".modal"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
using System.Collections.Concurrent;
|
||||
using ZB.MOM.WW.Audit;
|
||||
|
||||
namespace ZB.MOM.WW.Secrets.Ui.Tests.Fakes;
|
||||
|
||||
/// <summary>
|
||||
/// An <see cref="IAuditWriter"/> test double that collects every <see cref="AuditEvent"/> written,
|
||||
/// so a test can assert on the audit trail (action, outcome, target, actor) and — critically — that
|
||||
/// no plaintext ever appears in any audit field.
|
||||
/// </summary>
|
||||
public sealed class CapturingAuditWriter : IAuditWriter
|
||||
{
|
||||
private readonly ConcurrentQueue<AuditEvent> _events = new();
|
||||
|
||||
/// <summary>The events captured so far, in write order.</summary>
|
||||
public IReadOnlyList<AuditEvent> Events => _events.ToArray();
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task WriteAsync(AuditEvent evt, CancellationToken ct = default)
|
||||
{
|
||||
_events.Enqueue(evt);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
using System.Text;
|
||||
using ZB.MOM.WW.Secrets.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.Secrets.Ui.Tests.Fakes;
|
||||
|
||||
/// <summary>
|
||||
/// A trivial, reversible <see cref="ISecretCipher"/> stand-in for UI tests. It does not perform real
|
||||
/// cryptography — it simply carries the UTF-8 plaintext in <see cref="StoredSecret.Ciphertext"/> so a
|
||||
/// test can prove the editor's encrypt→upsert round-trips back to the entered value. Never used in
|
||||
/// production. A <see cref="FailDecrypt"/> flag lets a test drive the decrypt-failure reveal path.
|
||||
/// </summary>
|
||||
public sealed class FakeCipher : ISecretCipher
|
||||
{
|
||||
/// <summary>When <c>true</c>, <see cref="Decrypt"/> throws to exercise the failure path.</summary>
|
||||
public bool FailDecrypt { get; set; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public StoredSecret Encrypt(SecretName name, string plaintext, SecretContentType contentType)
|
||||
=> new()
|
||||
{
|
||||
Name = name,
|
||||
ContentType = contentType,
|
||||
Ciphertext = Encoding.UTF8.GetBytes(plaintext),
|
||||
Nonce = [1, 2, 3],
|
||||
Tag = [4, 5, 6],
|
||||
WrappedDek = [7, 8, 9],
|
||||
WrapNonce = [10, 11, 12],
|
||||
WrapTag = [13, 14, 15],
|
||||
KekId = "fake-kek",
|
||||
Revision = 0,
|
||||
CreatedUtc = default,
|
||||
UpdatedUtc = default,
|
||||
};
|
||||
|
||||
/// <inheritdoc />
|
||||
public string Decrypt(StoredSecret secret)
|
||||
{
|
||||
if (FailDecrypt)
|
||||
{
|
||||
throw new SecretDecryptionException("Fake decrypt failure.");
|
||||
}
|
||||
|
||||
return Encoding.UTF8.GetString(secret.Ciphertext);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
using System.Collections.Concurrent;
|
||||
using ZB.MOM.WW.Secrets.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.Secrets.Ui.Tests.Fakes;
|
||||
|
||||
/// <summary>
|
||||
/// A hand-written <see cref="ISecretStore"/> test double (the family does not use Moq) that keeps
|
||||
/// an in-memory table of rows and records every <see cref="UpsertAsync"/> and
|
||||
/// <see cref="DeleteAsync"/> call so a test can assert on the mutation trail.
|
||||
/// </summary>
|
||||
public sealed class RecordingSecretStore : ISecretStore
|
||||
{
|
||||
private readonly ConcurrentDictionary<string, StoredSecret> _rows = new();
|
||||
private readonly ConcurrentQueue<StoredSecret> _upserts = new();
|
||||
private readonly ConcurrentQueue<(SecretName Name, string? Actor)> _deletes = new();
|
||||
|
||||
/// <summary>Rows upserted, in call order.</summary>
|
||||
public IReadOnlyList<StoredSecret> Upserts => _upserts.ToArray();
|
||||
|
||||
/// <summary>Delete calls (name + recorded actor), in call order.</summary>
|
||||
public IReadOnlyList<(SecretName Name, string? Actor)> Deletes => _deletes.ToArray();
|
||||
|
||||
/// <summary>Seeds a row so <see cref="GetAsync"/> and <see cref="ListAsync"/> can return it.</summary>
|
||||
/// <param name="row">The row to seed.</param>
|
||||
public void Seed(StoredSecret row) => _rows[row.Name.Value] = row;
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<StoredSecret?> GetAsync(SecretName name, CancellationToken ct)
|
||||
=> Task.FromResult(_rows.TryGetValue(name.Value, out StoredSecret? row) ? row : null);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task UpsertAsync(StoredSecret row, CancellationToken ct)
|
||||
{
|
||||
_rows[row.Name.Value] = row;
|
||||
_upserts.Enqueue(row);
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<bool> DeleteAsync(SecretName name, string? actor, CancellationToken ct)
|
||||
{
|
||||
_deletes.Enqueue((name, actor));
|
||||
return Task.FromResult(_rows.TryRemove(name.Value, out _));
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<SecretMetadata>> ListAsync(bool includeDeleted, CancellationToken ct)
|
||||
{
|
||||
IReadOnlyList<SecretMetadata> projection = _rows.Values
|
||||
.Where(r => includeDeleted || !r.IsDeleted)
|
||||
.Select(r => new SecretMetadata
|
||||
{
|
||||
Name = r.Name,
|
||||
Description = r.Description,
|
||||
ContentType = r.ContentType,
|
||||
KekId = r.KekId,
|
||||
Revision = r.Revision,
|
||||
IsDeleted = r.IsDeleted,
|
||||
CreatedUtc = r.CreatedUtc,
|
||||
UpdatedUtc = r.UpdatedUtc,
|
||||
CreatedBy = r.CreatedBy,
|
||||
UpdatedBy = r.UpdatedBy,
|
||||
})
|
||||
.ToArray();
|
||||
return Task.FromResult(projection);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<SecretManifestEntry>> GetManifestAsync(CancellationToken ct)
|
||||
=> throw new NotSupportedException();
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task ApplyReplicatedAsync(StoredSecret row, CancellationToken ct)
|
||||
=> throw new NotSupportedException();
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
using Bunit;
|
||||
using Bunit.TestDoubles;
|
||||
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 RevealButtonTests : TestContext
|
||||
{
|
||||
private const string PlainValue = "the-plaintext-value-42";
|
||||
|
||||
private (RecordingSecretStore Store, CapturingAuditWriter Audit, FakeCipher Cipher) RegisterServices()
|
||||
{
|
||||
var store = new RecordingSecretStore();
|
||||
var audit = new CapturingAuditWriter();
|
||||
var cipher = new FakeCipher();
|
||||
Services.AddSingleton<ISecretStore>(store);
|
||||
Services.AddSingleton<IAuditWriter>(audit);
|
||||
Services.AddSingleton<ISecretCipher>(cipher);
|
||||
return (store, audit, cipher);
|
||||
}
|
||||
|
||||
private static StoredSecret Row(SecretName name, string plaintext)
|
||||
=> new FakeCipher().Encrypt(name, plaintext, SecretContentType.Text) with
|
||||
{
|
||||
Revision = 1,
|
||||
CreatedUtc = DateTimeOffset.UnixEpoch,
|
||||
UpdatedUtc = DateTimeOffset.UnixEpoch,
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void RevealButton_ShowsValueOnClick_AndAudits()
|
||||
{
|
||||
var (store, audit, _) = RegisterServices();
|
||||
var name = new SecretName("api/token");
|
||||
store.Seed(Row(name, PlainValue));
|
||||
|
||||
var auth = this.AddTestAuthorization();
|
||||
auth.SetAuthorized("carol");
|
||||
auth.SetPolicies(SecretsAuthorization.RevealPolicy);
|
||||
|
||||
var cut = RenderComponent<RevealButton>(p => p.Add(c => c.Name, name));
|
||||
|
||||
// The value is NOT present before the reveal click.
|
||||
Assert.DoesNotContain(PlainValue, cut.Markup);
|
||||
Assert.Empty(audit.Events);
|
||||
|
||||
cut.Find("button.reveal-secret").Click();
|
||||
|
||||
// After the click the plaintext is shown and a Success reveal audit is recorded.
|
||||
Assert.Contains(PlainValue, cut.Markup);
|
||||
Assert.Single(audit.Events);
|
||||
AuditEvent evt = audit.Events[0];
|
||||
Assert.Equal("secret.reveal", evt.Action);
|
||||
Assert.Equal(AuditOutcome.Success, evt.Outcome);
|
||||
Assert.Equal("Secrets", evt.Category);
|
||||
Assert.Equal("api/token", evt.Target);
|
||||
Assert.Equal("carol", evt.Actor);
|
||||
AssertNoValueLeak(evt);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void RevealButton_MissingSecret_AuditsFailure()
|
||||
{
|
||||
var (_, audit, _) = RegisterServices();
|
||||
var name = new SecretName("api/missing");
|
||||
|
||||
var auth = this.AddTestAuthorization();
|
||||
auth.SetAuthorized("carol");
|
||||
auth.SetPolicies(SecretsAuthorization.RevealPolicy);
|
||||
|
||||
var cut = RenderComponent<RevealButton>(p => p.Add(c => c.Name, name));
|
||||
|
||||
cut.Find("button.reveal-secret").Click();
|
||||
|
||||
// No value shown; a Failure reveal audit recorded.
|
||||
Assert.DoesNotContain(PlainValue, cut.Markup);
|
||||
Assert.Single(audit.Events);
|
||||
AuditEvent evt = audit.Events[0];
|
||||
Assert.Equal("secret.reveal", evt.Action);
|
||||
Assert.Equal(AuditOutcome.Failure, evt.Outcome);
|
||||
Assert.Equal("api/missing", evt.Target);
|
||||
}
|
||||
|
||||
private static void AssertNoValueLeak(AuditEvent evt)
|
||||
{
|
||||
foreach (string? field in new[] { evt.Action, evt.Actor, evt.Category, evt.Target, evt.DetailsJson, evt.ToString() })
|
||||
{
|
||||
if (field is not null)
|
||||
{
|
||||
Assert.DoesNotContain(PlainValue, field, StringComparison.Ordinal);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
using Bunit;
|
||||
using Bunit.TestDoubles;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
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 : TestContext
|
||||
{
|
||||
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<ISecretStore>(store);
|
||||
Services.AddSingleton<IAuditWriter>(audit);
|
||||
Services.AddSingleton<ISecretCipher>(cipher);
|
||||
return (store, audit, cipher);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void SecretEditor_Add_EncryptsAndUpserts()
|
||||
{
|
||||
var (store, audit, cipher) = RegisterServices();
|
||||
var auth = this.AddTestAuthorization();
|
||||
auth.SetAuthorized("carol");
|
||||
auth.SetPolicies(SecretsAuthorization.ManagePolicy);
|
||||
|
||||
var cut = RenderComponent<SecretEditor>(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.AddTestAuthorization();
|
||||
auth.SetAuthorized("dave");
|
||||
auth.SetPolicies(SecretsAuthorization.ManagePolicy);
|
||||
|
||||
var cut = RenderComponent<SecretEditor>(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");
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
using Bunit;
|
||||
using Bunit.TestDoubles;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
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;
|
||||
|
||||
@@ -33,7 +35,13 @@ public class SecretsListTests : TestContext
|
||||
};
|
||||
|
||||
private void RegisterStore(params SecretMetadata[] rows)
|
||||
=> Services.AddSingleton<ISecretStore>(new FakeSecretStore(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()
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
<PackageReference Include="xunit" />
|
||||
<PackageReference Include="xunit.runner.visualstudio" />
|
||||
<PackageReference Include="coverlet.collector" />
|
||||
<PackageReference Include="ZB.MOM.WW.Audit" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
|
||||
Reference in New Issue
Block a user