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
@@ -1,46 +1,66 @@
@namespace ZB.MOM.WW.Secrets.Ui.Components
@implements IDisposable
@using Microsoft.JSInterop
@using Microsoft.Extensions.Logging
@inject ISecretStore Store
@inject ISecretCipher Cipher
@inject IAuditWriter Audit
@inject IServiceProvider Services
@using Microsoft.Extensions.Logging
@* 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. *@
@inject IJSRuntime JS
@* Values are read only on an authorized request and disclosed only after successful audit.
The stable control/status never contains plaintext; target changes cancel obsolete work. *@
@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>
}
@{ long renderedGeneration = _generation; bool renderedHide = _revealed; }
<div @ref="_root" class="zb-secret-reveal" style="min-width:0;max-width:100%">
<TechButton Variant="@(_revealed ? ButtonVariant.Ghost : ButtonVariant.Secondary)"
Class="@(_revealed ? "hide-secret" : "reveal-secret")" Busy="_busy" BusyText="Revealing…"
id="@ControlId" data-reveal-control="" data-secret-name="@Name.Value"
data-testid="@(_revealed ? "hide-button" : "reveal-button")"
aria-label="@(_revealed ? $"Hide result for {Name.Value}" : $"Reveal {Name.Value}")"
aria-describedby="@ControlDescriptionIds" aria-expanded="@(_revealed ? "true" : "false")"
aria-controls="@(_revealed ? PanelId : null)"
@onclick="() => ActivateAsync(renderedGeneration, renderedHide)">
@(_revealed ? "Hide" : "Reveal")
</TechButton>
<p id="@StatusId" role="status" aria-live="polite" class="muted" style="margin:0" data-testid="reveal-status">@_status</p>
@if (_revealed)
{
<div id="@PanelId" class="reveal-panel" data-testid="reveal-panel">
@if (_value is not null)
{
<div role="region" tabindex="0" aria-label="@($"Revealed value for {Name.Value}")"
style="max-width:100%;max-height:16rem;overflow:auto;white-space:pre-wrap;overflow-wrap:anywhere">
<code class="revealed-value mono" style="color:var(--ink, #1b1d21)" data-testid="revealed-value">@_value</code>
</div>
<p class="muted" style="margin:.5rem 0 0">Visible until Hide or leaving this row or page.</p>
}
else
{
<span id="@ErrorId" class="field-error s-bad" data-testid="reveal-error">@(_error ?? "Unavailable.")</span>
}
</div>
}
</div>
@code {
private readonly CancellationTokenSource _cts = new();
private CancellationTokenSource? _operationCts;
private readonly string _id = $"secret-reveal-{Guid.NewGuid():N}";
private string ControlId => $"{_id}-control";
private string StatusId => $"{_id}-status";
private string ErrorId => $"{_id}-error";
private string ControlDescriptionIds => _revealed && !string.IsNullOrEmpty(_error) ? $"{StatusId} {ErrorId}" : StatusId;
private string PanelId => $"{_id}-panel";
private ElementReference _root;
private SecretName? _identity;
private long _generation;
private bool _disposed;
private bool _revealed;
private string? _value;
private string? _error;
private string _status = "";
private bool _busy;
private bool _focusControl;
/// <summary>The secret whose plaintext this button reveals.</summary>
[Parameter] public SecretName Name { get; set; }
@@ -48,110 +68,157 @@ else
/// <summary>The cascading authentication state, used as the fallback source of the audit actor.</summary>
[CascadingParameter] private Task<AuthenticationState>? AuthState { get; set; }
// Fail CLOSED on audit (Secrets-015): the plaintext is shown only after its secret.reveal
// Success audit has been written. Reveal is the most privileged operation here and the audit is
// the only record that a human saw the value; if the sink is down (or made to fail), nothing is
// shown and the failure is logged (actor + name, never the value). Unlike add/rotate/delete
// (scadaproj#34), nothing has happened yet that a failed audit would misreport — withholding the
// value costs only a retry.
private bool IsCurrent(long generation) => !_disposed && generation == _generation;
/// <inheritdoc />
protected override void OnParametersSet()
{
if (_disposed || _identity == Name) return;
_identity = Name;
++_generation;
_operationCts?.Cancel();
_operationCts?.Dispose();
_operationCts = null;
_value = null;
_error = null;
_status = "";
_busy = false;
_revealed = false;
_focusControl = false;
}
/// <inheritdoc />
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!_focusControl || _busy || _disposed) return;
_focusControl = false;
long generation = _generation;
try
{
// Only a DOM control reference crosses interop, never a value or status payload.
await using IJSObjectReference module = await JS.InvokeAsync<IJSObjectReference>("import", "./_content/ZB.MOM.WW.Secrets.Ui/js/secrets-reveal.js");
if (IsCurrent(generation)) await module.InvokeVoidAsync("focusIfUnclaimed", _root);
}
catch (JSDisconnectedException) { } // The browser no longer has a focus destination.
}
private Task ActivateAsync(long generation, bool hide)
{
// A delayed click from a previous target/mode cannot become a reveal of a new target.
if (!IsCurrent(generation) || _busy) return Task.CompletedTask;
if (hide) { Hide(); return Task.CompletedTask; }
return RevealAsync();
}
private async Task RevealAsync()
{
if (!await SecretsComponentAuthorization.IsAuthorizedAsync(Services, AuthState, SecretsAuthorization.RevealPolicy))
{
_value = null;
_error = "You are not authorized to reveal secrets.";
_revealed = true;
return;
}
if (_disposed || _busy) return;
long generation = _generation;
SecretName name = Name;
Task<AuthenticationState>? authState = AuthState;
ILogger<RevealButton>? logger = Services.GetService<ILogger<RevealButton>>();
var readCts = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token);
_operationCts = readCts;
CancellationToken ct = readCts.Token;
_busy = true;
// Captured now: if the component is disposed mid-reveal, reading _cts.Token later would throw
// ObjectDisposedException; a captured token just reports cancellation, which fails closed.
CancellationToken ct = _cts.Token;
_value = null;
_error = null;
_status = "Revealing value…";
string? plaintext = null;
AuditOutcome outcome;
string? error;
try
{
StoredSecret? row = await Store.GetAsync(Name, ct);
if (row is null)
if (!await SecretsComponentAuthorization.IsAuthorizedAsync(Services, authState, SecretsAuthorization.RevealPolicy))
{
error = "Secret not found.";
outcome = AuditOutcome.Failure;
if (IsCurrent(generation)) SetOutcome(null, "You are not authorized to reveal secrets.");
return;
}
else
if (!IsCurrent(generation) || ct.IsCancellationRequested) return;
// Resolve optional host actor services before waiting on the store, avoiding late
// resolution through a circuit scope disposed while a non-cooperative read finishes.
string actor = await SecretActorResolver.ResolveAsync(Services, authState);
if (!IsCurrent(generation) || ct.IsCancellationRequested) return;
AuditOutcome outcome;
string? error;
try
{
plaintext = Cipher.Decrypt(row);
error = null;
outcome = AuditOutcome.Success;
StoredSecret? row = await Store.GetAsync(name, ct);
if (!IsCurrent(generation) || ct.IsCancellationRequested) return;
if (row is null) { error = "Secret not found."; outcome = AuditOutcome.Failure; }
else { plaintext = Cipher.Decrypt(row); error = null; outcome = AuditOutcome.Success; }
}
}
catch (SecretDecryptionException)
{
error = "Unable to decrypt secret.";
outcome = AuditOutcome.Failure;
}
catch (Exception)
{
// Any other unexpected store/cipher fault (e.g. master key unavailable, timeout) must
// still be audited as a Failure and surfaced to the user, not left to tear down the
// circuit. The value is never shown.
error = "Unable to reveal secret.";
outcome = AuditOutcome.Failure;
}
catch (OperationCanceledException) when (ct.IsCancellationRequested) { return; }
catch (SecretDecryptionException) { error = "Unable to decrypt secret."; outcome = AuditOutcome.Failure; }
catch (Exception) { error = "Unable to reveal secret."; outcome = AuditOutcome.Failure; }
string actor = await SecretActorResolver.ResolveAsync(Services, AuthState);
bool audited;
try
{
await Audit.WriteAsync(
new AuditEvent
bool audited;
try
{
await Audit.WriteAsync(new AuditEvent
{
EventId = Guid.NewGuid(),
OccurredAtUtc = DateTimeOffset.UtcNow,
Actor = actor,
Action = "secret.reveal",
Outcome = outcome,
Category = "Secrets",
Target = Name.Value,
EventId = Guid.NewGuid(), OccurredAtUtc = DateTimeOffset.UtcNow,
Actor = actor, Action = "secret.reveal", Outcome = outcome,
Category = "Secrets", Target = name.Value,
DetailsJson = outcome == AuditOutcome.Failure ? "{\"reason\":\"error\"}" : null,
},
ct);
audited = true;
}, ct);
audited = true;
}
catch (Exception ex)
{
audited = false;
logger?.LogWarning(ex,
"The secret.reveal audit of {SecretName} by {Actor} could not be written; {Disposition}.",
name.Value, actor, outcome == AuditOutcome.Success ? "the value was NOT shown" : "the reveal had already failed");
}
if (!IsCurrent(generation) || ct.IsCancellationRequested) return;
if (outcome == AuditOutcome.Success && !audited)
{
plaintext = null;
error = "Reveal is unavailable: the audit record could not be written.";
}
// Fail CLOSED: only now may plaintext enter rendered component state.
SetOutcome(plaintext, error);
}
catch (Exception ex)
{
audited = false;
Services.GetService<ILogger<RevealButton>>()?.LogWarning(
ex,
"The secret.reveal audit of {SecretName} by {Actor} could not be written; {Disposition}.",
Name.Value,
actor,
outcome == AuditOutcome.Success ? "the value was NOT shown" : "the reveal had already failed");
}
if (outcome == AuditOutcome.Success && !audited)
finally
{
plaintext = null;
error = "Reveal is unavailable: the audit record could not be written.";
if (IsCurrent(generation)) { _busy = false; _focusControl = true; }
if (ReferenceEquals(_operationCts, readCts)) _operationCts = null;
readCts.Dispose();
}
}
_value = plaintext;
private void SetOutcome(string? value, string? error)
{
_value = value;
_error = error;
_busy = false;
_revealed = true;
_status = value is not null ? "Value revealed." : "Reveal failed.";
}
private void Hide()
{
bool hadValue = _value is not null;
++_generation;
_operationCts?.Cancel();
_operationCts?.Dispose();
_operationCts = null;
_revealed = false;
_value = null;
_error = null;
_status = hadValue ? "Value hidden." : "Reveal dismissed.";
_focusControl = true;
}
/// <inheritdoc />
public void Dispose()
{
if (_disposed) return;
_disposed = true;
++_generation;
_operationCts?.Cancel();
_operationCts?.Dispose();
_operationCts = null;
_value = null;
_cts.Cancel();
_cts.Dispose();
}
@@ -5,6 +5,23 @@
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. *@
<style>
.zb-secrets-list { min-width: 0; }
.zb-secrets-list .zb-secret-filter-controls { display: flex; gap: .5rem; align-items: start; }
.zb-secrets-list .zb-secret-filter-controls input { flex: 1; min-width: 0; }
.zb-secrets-list .data-table { table-layout: fixed; min-width: 42rem; }
.zb-secrets-list .data-table tbody tr { cursor: default; }
.zb-secrets-list caption { caption-side: top; text-align: left; color: var(--ink-muted, #626970); }
.zb-secrets-list .zb-secret-name, .zb-secrets-list .zb-secret-description { white-space: normal; overflow-wrap: anywhere; }
.zb-secrets-list .zb-secret-actions { display: flex; gap: .35rem; flex-wrap: wrap; align-items: start; }
.zb-secrets-list .zb-secret-technical { margin-top: .5rem; font-weight: normal; }
.zb-secrets-list .zb-secret-technical summary { cursor: pointer; color: var(--ink-muted, #626970); }
.zb-secrets-list .zb-secret-technical .zb-secret-tech-scroll { max-height: 16rem; overflow: auto; margin-top: .5rem; }
.zb-secrets-list .zb-secret-technical dl { margin: 0; }
.zb-secrets-list .zb-secret-technical dt, .zb-secrets-list .zb-secret-technical dd { margin: 0; }
.zb-secrets-list .zb-secret-technical dt:not(:first-child) { margin-top: .5rem; }
</style>
<div class="zb-secrets-list">
<AuthorizeView Policy="@SecretsAuthorization.ManagePolicy">
<div class="toolbar btn-row">
<TechButton Variant="ButtonVariant.Primary" disabled="@OperationBusy" data-testid="add-secret" @onclick="ShowAdd">
@@ -42,56 +59,68 @@
}
@if (_secrets is not null)
{
<div class="table-wrap" aria-busy="@(_loading ? "true" : "false")">
<table class="data-table">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Content type</th>
<th>KEK</th>
<th class="num">Revision</th>
<th>Updated (UTC)</th>
<th>Updated by</th>
<th></th>
</tr>
</thead>
var visibleSecrets = VisibleSecrets;
<TechField Label="Filter by name" For="@FilterId" Hint="Search loaded names only. Secret values are not searched." HintId="@FilterHintId">
<div class="zb-secret-filter-controls">
<input @ref="_filterInput" id="@FilterId" class="form-control" type="search"
@bind="_filter" @bind:event="oninput" aria-describedby="@FilterHintId" aria-controls="@ResultsId" data-testid="secret-filter" />
<TechButton Variant="ButtonVariant.Secondary" disabled="@(_filter.Length == 0)" data-testid="clear-secret-filter" @onclick="ClearFilter">Clear filter</TechButton>
</div>
</TechField>
<p id="@CountId" role="status" class="muted" data-testid="filter-count">@visibleSecrets.Count of @_secrets.Count names shown</p>
<div class="table-wrap" role="region" aria-label="Secret metadata" tabindex="0" aria-busy="@(_loading ? "true" : "false")">
<table id="@ResultsId" class="data-table" aria-describedby="@CountId">
<caption>Secret metadata. Updated times are UTC.</caption>
<colgroup><col style="width:32%" /><col style="width:24%" /><col style="width:18%" /><col style="width:26%" /></colgroup>
<thead><tr>
<th scope="col">Name</th>
<th scope="col">Description</th>
<th scope="col">Updated (UTC)</th>
<th scope="col">Actions</th>
</tr></thead>
<tbody>
@if (_secrets.Count == 0)
{
<tr>
<td class="empty-row" colspan="8">No secrets.</td>
</tr>
<tr><td class="empty-row" colspan="4">No secrets.</td></tr>
}
else if (visibleSecrets.Count == 0)
{
<tr><td class="empty-row" colspan="4" data-testid="filter-empty">No names match this filter. Clear filter to see the loaded metadata.</td></tr>
}
else
{
@foreach (SecretMetadata secret in _secrets)
@foreach (SecretMetadata secret in visibleSecrets)
{
<tr>
<td class="mono">@secret.Name.Value</td>
<td>@secret.Description</td>
<td>@secret.ContentType</td>
<td class="mono">@secret.KekId</td>
<td class="num">@secret.Revision</td>
<td class="mono">@secret.UpdatedUtc.UtcDateTime.ToString("u")</td>
<td>@secret.UpdatedBy</td>
<td class="row-actions">
<tr @key="secret.Name" data-secret-row="@secret.Name.Value">
<th scope="row" class="mono zb-secret-name">@secret.Name.Value</th>
<td class="zb-secret-description">
@secret.Description
<details class="zb-secret-technical">
<summary aria-label="@($"Technical metadata for {secret.Name.Value}")">Technical metadata</summary>
<div class="zb-secret-tech-scroll" role="region" tabindex="0" aria-label="@($"Technical metadata for {secret.Name.Value}")">
<dl>
<dt>Content type</dt><dd>@secret.ContentType</dd>
<dt>KEK</dt><dd class="mono">@secret.KekId</dd>
<dt>Revision</dt><dd class="mono">@secret.Revision</dd>
<dt>Updated by</dt><dd>@secret.UpdatedBy</dd>
</dl>
</div>
</details>
</td>
<td class="mono"><time datetime="@secret.UpdatedUtc.ToString("O")">@secret.UpdatedUtc.UtcDateTime.ToString("yyyy-MM-dd")<br />@secret.UpdatedUtc.UtcDateTime.ToString("HH:mm:ss'Z'")</time></td>
<td><div class="zb-secret-actions">
<AuthorizeView Policy="@SecretsAuthorization.RevealPolicy">
<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" disabled="@OperationBusy"
@onclick="() => ShowRotate(secret.Name)">
Rotate
</button>
aria-label="@($"Rotate {secret.Name.Value}")" data-secret-name="@secret.Name.Value" disabled="@OperationBusy"
@onclick="() => ShowRotate(secret.Name)">Rotate</button>
<button type="button" class="btn btn-danger delete-secret"
id="@RowActionId(secret.Name)" data-secret-name="@secret.Name.Value" disabled="@OperationBusy"
@onclick="() => ShowDelete(secret.Name)">
Delete
</button>
aria-label="@($"Delete {secret.Name.Value}")" id="@RowActionId(secret.Name)" data-secret-name="@secret.Name.Value" disabled="@OperationBusy"
@onclick="() => ShowDelete(secret.Name)">Delete</button>
</AuthorizeView>
</td>
</div></td>
</tr>
}
}
@@ -108,10 +137,32 @@
OnBusyChanged="busy => OnDeleteBusyChanged(deleteGeneration, busy)"
OnDeleted="() => OnDeleteCommittedAsync(deleteGeneration)"
OnCancelled="() => CloseDelete(deleteGeneration)" />
</div>
@code {
private readonly string _id = $"secrets-list-{Guid.NewGuid():N}";
private string HeadingId => $"{_id}-heading";
private string FilterId => $"{_id}-filter";
private string FilterHintId => $"{_id}-filter-hint";
private string ResultsId => $"{_id}-results";
private string CountId => $"{_id}-count";
private string _filter = "";
private ElementReference _filterInput;
private bool _focusFilter;
private IReadOnlyList<SecretMetadata> VisibleSecrets => _secrets?.Where(row =>
row.Name.Value.Contains(_filter.Trim(), StringComparison.OrdinalIgnoreCase)).ToArray() ?? [];
private void ClearFilter() { _filter = ""; _focusFilter = true; }
/// <inheritdoc />
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (_focusFilter && !_disposed)
{
_focusFilter = false;
await _filterInput.FocusAsync();
}
}
private readonly Dictionary<SecretName, string> _rowIds = new();
private long _deleteGeneration;
private bool _deleteBusy;
@@ -245,7 +296,7 @@
private string DeleteReturnFocusId()
{
if (_secrets is null || _deleteTarget is not { } target) return HeadingId;
var rows = _secrets.ToList();
var rows = VisibleSecrets.ToList();
int index = rows.FindIndex(row => row.Name == target);
if (index < 0) return HeadingId;
if (index + 1 < rows.Count) return RowActionId(rows[index + 1].Name);
@@ -0,0 +1,12 @@
// Completion can re-enable the stable Reveal/Hide control after the browser dropped focus.
// Restore only when no other control has claimed it; never send plaintext through interop.
export function focusIfUnclaimed(root) {
const control = root?.querySelector('button[data-reveal-control]');
if (!control?.isConnected || control.matches(':disabled') || !control.getClientRects().length) return;
for (let node = control; node; node = node.parentElement) {
const style = getComputedStyle(node);
if (node.hidden || node.inert || style.display === 'none' || ['hidden', 'collapse'].includes(style.visibility)) return;
}
if ([control, document.body, document.documentElement].includes(document.activeElement))
control.focus({ preventScroll: true });
}