fix(secrets-ui): isolate drafts and pending operations by editor target

This commit is contained in:
Joseph Doherty
2026-11-13 16:21:37 -05:00
parent be1ce9ef3a
commit f07bd3c776
15 changed files with 2006 additions and 93 deletions
@@ -13,21 +13,21 @@
@if (IsRotate)
{
<input class="form-control mono" type="text" readonly
value="@_name" data-testid="secret-name" />
value="@_name" disabled="@_busy" data-testid="secret-name" />
}
else
{
<input class="form-control mono" type="text"
@bind="_name" data-testid="secret-name" />
@bind="_name" disabled="@_busy" data-testid="secret-name" />
}
</TechField>
<TechField Label="Description">
<input class="form-control" type="text" @bind="_description" data-testid="secret-description" />
<input class="form-control" type="text" @bind="_description" disabled="@(_busy || _metadataLoading)" data-testid="secret-description" />
</TechField>
<TechField Label="Content type">
<select class="form-select" @bind="_contentType" data-testid="secret-content-type">
<select class="form-select" @bind="_contentType" disabled="@(_busy || _metadataLoading)" data-testid="secret-content-type">
@foreach (SecretContentType ct in Enum.GetValues<SecretContentType>())
{
<option value="@ct">@ct</option>
@@ -37,7 +37,7 @@
<TechField Label="Value">
<input class="form-control mono" type="password" autocomplete="new-password"
@bind="_value" data-testid="secret-value" />
@bind="_value" disabled="@(_busy || _metadataLoading)" data-testid="secret-value" />
</TechField>
@if (_error is not null)
@@ -45,12 +45,17 @@
<p class="field-error s-bad" data-testid="editor-error">@_error</p>
}
@if (_busy)
{
<p role="status" data-testid="editor-pending">Saving this change. Wait for completion before changing targets.</p>
}
<div class="btn-row">
<TechButton Variant="ButtonVariant.Primary" Busy="_busy"
<TechButton Variant="ButtonVariant.Primary" Busy="@(_busy || _metadataLoading || !_metadataReady)"
data-testid="editor-submit" @onclick="SubmitAsync">
@(IsRotate ? "Rotate" : "Add")
</TechButton>
<TechButton Variant="ButtonVariant.Secondary"
<TechButton Variant="ButtonVariant.Secondary" Busy="_busy"
data-testid="editor-cancel" @onclick="CancelAsync">
Cancel
</TechButton>
@@ -59,6 +64,13 @@
@code {
private readonly CancellationTokenSource _cts = new();
private CancellationTokenSource? _metadataCts;
private SecretName? _identityName;
private long _generation;
private bool _identityInitialized;
private bool _metadataLoading;
private bool _metadataReady;
private bool _disposed;
private string _name = string.Empty;
private string _description = string.Empty;
@@ -76,73 +88,156 @@
/// <summary>Raised after a successful add or rotate, so a parent can refresh its listing.</summary>
[Parameter] public EventCallback OnSaved { get; set; }
/// <summary>Notifies the parent while a submission is pending so target switching can be disabled.</summary>
[Parameter] public EventCallback<bool> OnBusyChanged { 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;
private bool _metadataLoaded;
private bool IsRotate => _identityName is not null;
private bool IsCurrent(long generation) => !_disposed && generation == _generation;
/// <inheritdoc />
protected override async Task OnParametersSetAsync()
{
if (IsRotate)
if (_disposed || (_identityInitialized && ExistingName == _identityName))
{
_name = ExistingName!.Value.Value;
return;
}
// Rotate must preserve the existing row's metadata: the store's upsert overwrites the
// description and content type from the incoming row, so pre-fill both from the current
// row (metadata only — no plaintext is read or decrypted). Load once so a re-render does
// not clobber operator edits. The operator still supplies the NEW value.
if (!_metadataLoaded)
_identityInitialized = true;
_identityName = ExistingName;
long generation = ++_generation;
_metadataCts?.Cancel();
_metadataCts?.Dispose();
_metadataCts = null;
_name = ExistingName?.Value ?? string.Empty;
_description = string.Empty;
_contentType = SecretContentType.Text;
_value = string.Empty;
_error = null;
_restoreConfirmedFor = null;
_metadataLoading = false;
_metadataReady = !IsRotate;
if (_identityName is not { } name)
{
return;
}
_metadataLoading = true;
var readCts = CancellationTokenSource.CreateLinkedTokenSource(_cts.Token);
_metadataCts = readCts;
CancellationToken ct = readCts.Token;
try
{
// Metadata only; a new identity gets a fresh read while same-target rerenders
// preserve unsaved edits. Some stores can finish after cancellation, so the
// generation check is required even when the old token has been cancelled.
StoredSecret? row = await Store.GetAsync(name, ct);
if (IsCurrent(generation))
{
_metadataLoaded = true;
StoredSecret? row = await Store.GetAsync(ExistingName.Value, _cts.Token);
_description = row?.Description ?? string.Empty;
_contentType = row?.ContentType ?? SecretContentType.Text;
_metadataReady = true;
}
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
// Superseded/disposed metadata has no current UI outcome.
}
catch (Exception)
{
if (IsCurrent(generation))
{
_error = "Unable to load secret metadata. Close and reopen the editor to retry.";
}
}
finally
{
if (IsCurrent(generation))
{
_metadataLoading = false;
}
if (ReferenceEquals(_metadataCts, readCts))
{
_metadataCts = null;
}
readCts.Dispose();
}
}
private async Task SubmitAsync()
{
if (_disposed || _busy || _metadataLoading || !_metadataReady)
{
return;
}
// Snapshot the operation before the first await. A host can still change parameters
// programmatically while a write is pending; its target, mode and draft must not drift.
long generation = _generation;
SecretName? existingName = _identityName;
bool rotate = existingName is not null;
string enteredName = _name;
string description = _description;
SecretContentType contentType = _contentType;
string value = _value;
string action = rotate ? "secret.rotate" : "secret.add";
Task<AuthenticationState>? authState = AuthState;
CancellationToken ct = _cts.Token;
EventCallback savedCallback = OnSaved;
EventCallback<bool> busyCallback = OnBusyChanged;
_error = null;
if (!await SecretsComponentAuthorization.IsAuthorizedAsync(Services, AuthState, SecretsAuthorization.ManagePolicy))
{
_error = "You are not authorized to manage secrets.";
return;
}
SecretName name;
try
{
name = ExistingName ?? new SecretName(_name);
}
catch (ArgumentException ex)
{
_error = ex.Message;
return;
}
_busy = true;
bool saved = false;
try
{
string actor = await SecretActorResolver.ResolveAsync(Services, AuthState);
await busyCallback.InvokeAsync(true);
if (!await SecretsComponentAuthorization.IsAuthorizedAsync(Services, authState, SecretsAuthorization.ManagePolicy))
{
if (IsCurrent(generation)) _error = "You are not authorized to manage secrets.";
return;
}
if (!IsCurrent(generation) || ct.IsCancellationRequested)
{
return;
}
SecretName name;
try
{
if (!IsRotate)
name = existingName ?? new SecretName(enteredName);
}
catch (ArgumentException ex)
{
if (IsCurrent(generation)) _error = ex.Message;
return;
}
string actor = await SecretActorResolver.ResolveAsync(Services, authState);
if (!IsCurrent(generation) || ct.IsCancellationRequested)
{
return;
}
// Resolve optional host services before mutation awaits. A circuit provider may
// be disposed while a committed write/audit finishes; the captured singleton can
// still evict the captured target without resolving through that dead scope.
ISecretCacheInvalidator? cache = Services.GetService<ISecretCacheInvalidator>();
ILogger<SecretEditor>? logger = Services.GetService<ILogger<SecretEditor>>();
bool saved = false;
try
{
if (!rotate)
{
// Add must never silently overwrite (Secrets-014): the store's upsert replaces the
// value, clears a tombstone and resets description/content type, and it would be
// audited as "add". A live row is refused; a tombstone needs a second, deliberate
// submit of the same name. (Check-then-write is not atomic; a concurrent add of the
// same name in another session can still race — the window is the round trip.)
StoredSecret? existing = await Store.GetAsync(name, _cts.Token);
// Preserve the live-row refusal and deliberate same-name tombstone restore.
// Check-then-write remains the existing store contract, not an atomic insert.
StoredSecret? existing = await Store.GetAsync(name, ct);
if (!IsCurrent(generation) || ct.IsCancellationRequested) return;
string? refusal = AddRefusal(name, existing);
if (refusal is not null)
{
@@ -151,51 +246,38 @@
}
}
StoredSecret row = Cipher.Encrypt(name, _value, _contentType);
row = row with
StoredSecret row = Cipher.Encrypt(name, value, contentType) with
{
Description = string.IsNullOrWhiteSpace(_description) ? null : _description,
Description = string.IsNullOrWhiteSpace(description) ? null : description,
CreatedBy = actor,
UpdatedBy = actor,
};
await Store.UpsertAsync(row, _cts.Token);
// The write is committed (and, on a replicated host, already published) from here on.
await Store.UpsertAsync(row, ct);
// From here on a cancellation/target change cannot claim rollback.
saved = true;
}
catch (Exception)
{
// An unexpected store/cipher fault (e.g. master key unavailable, timeout) must still
// be audited as a Failure and surfaced to the operator — never the value — instead of
// tearing down the circuit. The detail carries no plaintext.
_error = IsRotate ? "Unable to rotate the secret." : "Unable to add the secret.";
await WriteFailureAuditAsync(
actor, IsRotate ? "secret.rotate" : "secret.add", name.Value);
if (IsCurrent(generation)) _error = rotate ? "Unable to rotate the secret." : "Unable to add the secret.";
await WriteFailureAuditAsync(actor, action, name.Value, ct);
}
if (saved)
{
// Outside the mutation try (scadaproj#34): an audit sink that throws AFTER the store
// committed must not report the change as failed, audit it as a Failure, or skip the
// cache eviction below — the operator would retry, or believe the leaked credential
// was still live while the resolver kept serving the old plaintext.
await WriteSuccessAuditAsync(
actor, IsRotate ? "secret.rotate" : "secret.add", name.Value);
// Keep committed success separate from best-effort audit. Cache eviction must
// still address the captured target even if this editor was superseded/disposed.
await WriteSuccessAuditAsync(actor, action, name.Value, ct, logger);
cache?.Invalidate(name);
if (IsCurrent(generation))
{
await savedCallback.InvokeAsync();
}
}
}
finally
{
_busy = false;
}
if (saved)
{
// Evict any cached plaintext so the ${secret:} / ISecretResolver path does not serve a
// stale value after this rotate/add for the remainder of its TTL. Optional seam — a no-op
// when the host has not registered an invalidator.
Services.GetService<ISecretCacheInvalidator>()?.Invalidate(name);
await OnSaved.InvokeAsync();
await busyCallback.InvokeAsync(false);
}
}
@@ -224,7 +306,7 @@
return $"A deleted secret named '{name.Value}' exists. Select Add again to restore it with this value.";
}
private async Task WriteSuccessAuditAsync(string actor, string action, string target)
private async Task WriteSuccessAuditAsync(string actor, string action, string target, CancellationToken ct, ILogger<SecretEditor>? logger)
{
try
{
@@ -239,13 +321,13 @@
Category = "Secrets",
Target = target,
},
_cts.Token);
ct);
}
catch (Exception ex)
{
// Best-effort: the change itself succeeded. Logged (name + action only, never the value)
// so the gap in the audit trail is visible to whoever runs the host.
Services.GetService<ILogger<SecretEditor>>()?.LogWarning(
logger?.LogWarning(
ex,
"Secret {Action} of {SecretName} by {Actor} succeeded, but its audit event could not be written.",
action,
@@ -254,7 +336,7 @@
}
}
private async Task WriteFailureAuditAsync(string actor, string action, string target)
private async Task WriteFailureAuditAsync(string actor, string action, string target, CancellationToken ct)
{
try
{
@@ -270,7 +352,7 @@
Target = target,
DetailsJson = "{\"reason\":\"error\"}",
},
_cts.Token);
ct);
}
catch
{
@@ -278,11 +360,18 @@
}
}
private Task CancelAsync() => OnCancelled.InvokeAsync();
private Task CancelAsync() => _busy || _disposed ? Task.CompletedTask : OnCancelled.InvokeAsync();
/// <inheritdoc />
public void Dispose()
{
if (_disposed) return;
_disposed = true;
++_generation;
_metadataCts?.Cancel();
_metadataCts?.Dispose();
_metadataCts = null;
_value = string.Empty;
_cts.Cancel();
_cts.Dispose();
}
@@ -7,7 +7,7 @@
<AuthorizeView Policy="@SecretsAuthorization.ManagePolicy">
<div class="toolbar btn-row">
<TechButton Variant="ButtonVariant.Primary" data-testid="add-secret" @onclick="ShowAdd">
<TechButton Variant="ButtonVariant.Primary" Busy="_editorBusy" data-testid="add-secret" @onclick="ShowAdd">
Add secret
</TechButton>
</div>
@@ -15,9 +15,11 @@
@if (_editorMode != EditorMode.None)
{
<SecretEditor ExistingName="_rotateName"
OnSaved="OnMutatedAsync"
OnCancelled="CloseEditor" />
var editorGeneration = _editorGeneration;
<SecretEditor @key="(_editorMode, _rotateName)" ExistingName="_rotateName"
OnSaved="() => OnEditorSavedAsync(editorGeneration)"
OnBusyChanged="busy => OnEditorBusyChanged(editorGeneration, busy)"
OnCancelled="() => CloseEditor(editorGeneration)" />
}
<TechCard Title="Secrets">
@@ -66,12 +68,12 @@
</AuthorizeView>
<AuthorizeView Policy="@SecretsAuthorization.ManagePolicy">
<button type="button" class="btn btn-outline-secondary rotate-secret"
data-secret-name="@secret.Name.Value"
data-secret-name="@secret.Name.Value" disabled="@_editorBusy"
@onclick="() => ShowRotate(secret.Name)">
Rotate
</button>
<button type="button" class="btn btn-danger delete-secret"
data-secret-name="@secret.Name.Value"
data-secret-name="@secret.Name.Value" disabled="@_editorBusy"
@onclick="() => ShowDelete(secret.Name)">
Delete
</button>
@@ -98,6 +100,9 @@
private EditorMode _editorMode = EditorMode.None;
private SecretName? _rotateName;
private SecretName? _deleteTarget;
private long _editorGeneration;
private bool _editorBusy;
private bool _disposed;
private enum EditorMode
{
@@ -114,29 +119,63 @@
private void ShowAdd()
{
if (_editorBusy || _disposed || _editorMode == EditorMode.Add) return;
++_editorGeneration;
_rotateName = null;
_editorMode = EditorMode.Add;
}
private void ShowRotate(SecretName name)
{
if (_editorBusy || _disposed || (_editorMode == EditorMode.Rotate && _rotateName == name)) return;
++_editorGeneration;
_rotateName = name;
_editorMode = EditorMode.Rotate;
}
private void CloseEditor()
private void CloseEditor(long generation)
{
_editorMode = EditorMode.None;
_rotateName = null;
if (_editorBusy || _disposed || generation != _editorGeneration) return;
ClearEditor();
}
private void ShowDelete(SecretName name) => _deleteTarget = name;
private void ClearEditor()
{
++_editorGeneration;
_editorMode = EditorMode.None;
_rotateName = null;
_editorBusy = false;
}
private void OnEditorBusyChanged(long generation, bool busy)
{
if (!_disposed && generation == _editorGeneration)
{
_editorBusy = busy;
}
}
private async Task OnEditorSavedAsync(long generation)
{
if (_disposed || generation != _editorGeneration) return;
await ReloadAsync();
if (!_disposed && generation == _editorGeneration)
{
ClearEditor();
CloseDelete();
}
}
private void ShowDelete(SecretName name)
{
if (!_editorBusy && !_disposed) _deleteTarget = name;
}
private void CloseDelete() => _deleteTarget = null;
private async Task OnMutatedAsync()
{
CloseEditor();
CloseEditor(_editorGeneration);
CloseDelete();
await ReloadAsync();
}
@@ -144,6 +183,8 @@
/// <inheritdoc />
public void Dispose()
{
_disposed = true;
++_editorGeneration;
_cts.Cancel();
_cts.Dispose();
}
@@ -12,8 +12,18 @@ public sealed class RecordingSecretStore : ISecretStore
{
private readonly ConcurrentDictionary<string, StoredSecret> _rows = new();
private readonly ConcurrentQueue<StoredSecret> _upserts = new();
private readonly ConcurrentQueue<SecretName> _gets = new();
private readonly ConcurrentQueue<(SecretName Name, string? Actor)> _deletes = new();
/// <summary>Names read, in call order; never plaintext.</summary>
public IReadOnlyList<SecretName> Gets => _gets.ToArray();
/// <summary>Optional controlled read, including fixtures that deliberately ignore cancellation.</summary>
public Func<SecretName, CancellationToken, Task<StoredSecret?>>? GetOverride { get; set; }
/// <summary>Optional hook awaited before the normal recorded upsert commits.</summary>
public Func<StoredSecret, CancellationToken, Task>? UpsertOverride { get; set; }
/// <summary>Rows upserted, in call order.</summary>
public IReadOnlyList<StoredSecret> Upserts => _upserts.ToArray();
@@ -32,11 +42,20 @@ public sealed class RecordingSecretStore : ISecretStore
/// <inheritdoc />
public Task<StoredSecret?> GetAsync(SecretName name, CancellationToken ct)
=> Task.FromResult(_rows.TryGetValue(name.Value, out StoredSecret? row) ? row : null);
{
_gets.Enqueue(name);
return GetOverride is null
? Task.FromResult(_rows.TryGetValue(name.Value, out StoredSecret? row) ? row : null)
: GetOverride(name, ct);
}
/// <inheritdoc />
public Task UpsertAsync(StoredSecret row, CancellationToken ct)
public async Task UpsertAsync(StoredSecret row, CancellationToken ct)
{
if (UpsertOverride is not null)
{
await UpsertOverride(row, ct);
}
if (UpsertFault is not null)
{
throw UpsertFault;
@@ -44,7 +63,6 @@ public sealed class RecordingSecretStore : ISecretStore
_rows[row.Name.Value] = row;
_upserts.Enqueue(row);
return Task.CompletedTask;
}
/// <inheritdoc />
@@ -1,6 +1,9 @@
using Bunit;
using Bunit.TestDoubles;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.Authorization;
using System.Security.Claims;
using Microsoft.Extensions.DependencyInjection;
using ZB.MOM.WW.Audit;
using ZB.MOM.WW.Secrets.Abstractions;
@@ -171,6 +174,303 @@ public class SecretEditorTests : BunitContext
Assert.NotEmpty(cut.FindAll("[data-testid=editor-error]"));
}
[Fact]
public void ChangingRotateTarget_DoesNotReuseAnotherSecretsDraft()
{
var (store, _, cipher) = RegisterServices();
var a = new SecretName("app/a");
var b = new SecretName("app/b");
store.Seed(cipher.Encrypt(a, "old-a", SecretContentType.Text) with { Description = "A" });
store.Seed(cipher.Encrypt(b, "old-b", SecretContentType.Json) with { Description = "B" });
AuthorizeManager();
var cut = Render<SecretEditor>(p => p.Add(x => x.ExistingName, a));
cut.Find("[data-testid=secret-value]").Change("draft-for-a");
cut.Render(p => p.Add(x => x.ExistingName, b));
Assert.Equal("B", cut.Find("[data-testid=secret-description]").GetAttribute("value"));
Assert.Equal(nameof(SecretContentType.Json), cut.Find("[data-testid=secret-content-type]").GetAttribute("value"));
Assert.Equal("", cut.Find("[data-testid=secret-value]").GetAttribute("value") ?? "");
}
[Fact]
public void RotateToAdd_ClearsTargetMetadataAndValue()
{
var (store, _, cipher) = RegisterServices();
var a = new SecretName("app/a");
store.Seed(cipher.Encrypt(a, "old", SecretContentType.Json) with { Description = "A" });
var cut = Render<SecretEditor>(p => p.Add(x => x.ExistingName, a));
cut.Find("[data-testid=secret-value]").Change("draft-for-a");
cut.Render(p => p.Add(x => x.ExistingName, (SecretName?)null));
Assert.Equal("", cut.Find("[data-testid=secret-name]").GetAttribute("value") ?? "");
Assert.Equal("", cut.Find("[data-testid=secret-description]").GetAttribute("value") ?? "");
Assert.Equal("", cut.Find("[data-testid=secret-value]").GetAttribute("value") ?? "");
Assert.Equal(nameof(SecretContentType.Text), cut.Find("[data-testid=secret-content-type]").GetAttribute("value"));
}
[Fact]
public void SameTargetRerender_PreservesUnsavedDraftAndFailedSaveError()
{
var (store, _, cipher) = RegisterServices();
var a = new SecretName("app/a");
store.Seed(cipher.Encrypt(a, "old", SecretContentType.Text) with { Description = "A" });
store.UpsertFault = new IOException("synthetic write failure");
AuthorizeManager();
var cut = Render<SecretEditor>(p => p.Add(x => x.ExistingName, a));
cut.Find("[data-testid=secret-description]").Change("unsaved description");
cut.Find("[data-testid=secret-value]").Change("unsaved value");
cut.Find("[data-testid=editor-submit]").Click();
cut.Render(p => p.Add(x => x.ExistingName, a));
Assert.Equal("unsaved description", cut.Find("[data-testid=secret-description]").GetAttribute("value"));
Assert.Equal("unsaved value", cut.Find("[data-testid=secret-value]").GetAttribute("value"));
Assert.NotEmpty(cut.FindAll("[data-testid=editor-error]"));
Assert.Single(store.Gets);
}
[Fact]
public async Task SupersededMetadataRead_IsCancelledAndCannotOverwriteNewTarget()
{
var (store, _, cipher) = RegisterServices();
var a = new SecretName("app/a");
var b = new SecretName("app/b");
var oldRead = new TaskCompletionSource<StoredSecret?>(TaskCreationOptions.RunContinuationsAsynchronously);
CancellationToken readToken = default;
store.GetOverride = (name, ct) =>
{
if (name == a) { readToken = ct; return oldRead.Task; }
return Task.FromResult<StoredSecret?>(cipher.Encrypt(b, "old-b", SecretContentType.Json) with { Description = "B" });
};
var cut = Render<SecretEditor>(p => p.Add(x => x.ExistingName, a));
try
{
cut.Render(p => p.Add(x => x.ExistingName, b));
Assert.True(readToken.IsCancellationRequested);
}
finally
{
var before = cut.RenderCount;
await cut.InvokeAsync(() => oldRead.TrySetResult(cipher.Encrypt(a, "old-a", SecretContentType.Text) with { Description = "A" }));
cut.WaitForState(() => cut.RenderCount > before);
}
Assert.Equal("B", cut.Find("[data-testid=secret-description]").GetAttribute("value"));
Assert.Equal("app/b", cut.Find("[data-testid=secret-name]").GetAttribute("value"));
}
[Fact]
public async Task ReturningToSameName_StillRejectsAnOlderGenerationRead()
{
var (store, _, cipher) = RegisterServices();
var a = new SecretName("app/a");
var b = new SecretName("app/b");
var oldRead = new TaskCompletionSource<StoredSecret?>(TaskCreationOptions.RunContinuationsAsynchronously);
var readsOfA = 0;
store.GetOverride = (name, ct) => name == a && ++readsOfA == 1 ? oldRead.Task
: Task.FromResult<StoredSecret?>(cipher.Encrypt(name, "old", SecretContentType.Text) with { Description = "fresh metadata" });
var cut = Render<SecretEditor>(p => p.Add(x => x.ExistingName, a));
cut.Render(p => p.Add(x => x.ExistingName, b));
cut.Render(p => p.Add(x => x.ExistingName, a));
var before = cut.RenderCount;
await cut.InvokeAsync(() => oldRead.SetResult(cipher.Encrypt(a, "old", SecretContentType.Text) with { Description = "stale metadata" }));
cut.WaitForState(() => cut.RenderCount > before);
Assert.Equal("fresh metadata", cut.Find("[data-testid=secret-description]").GetAttribute("value"));
}
[Fact]
public void TargetChange_ResetsTombstoneRestoreConfirmation()
{
var (store, _, cipher) = RegisterServices();
store.Seed(cipher.Encrypt(new SecretName("app/retired"), "old", SecretContentType.Text) with { IsDeleted = true });
AuthorizeManager();
var cut = Render<SecretEditor>();
cut.Find("[data-testid=secret-name]").Change("app/retired");
cut.Find("[data-testid=secret-value]").Change("new");
cut.Find("[data-testid=editor-submit]").Click();
Assert.Empty(store.Upserts);
cut.Render(p => p.Add(x => x.ExistingName, new SecretName("app/other")));
cut.Render(p => p.Add(x => x.ExistingName, (SecretName?)null));
cut.Find("[data-testid=secret-name]").Change("app/retired");
cut.Find("[data-testid=secret-value]").Change("another new value");
cut.Find("[data-testid=editor-submit]").Click();
Assert.Empty(store.Upserts);
Assert.Contains("deleted secret", cut.Find("[data-testid=editor-error]").TextContent);
}
[Fact]
public async Task PendingWrite_CannotBeCancelledOrSubmittedTwice()
{
var (store, _, _) = RegisterServices();
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
store.UpsertOverride = (_, _) => { entered.TrySetResult(); return release.Task; };
AuthorizeManager();
var cancelled = false;
var saved = false;
var cut = Render<SecretEditor>(p => p.Add(x => x.OnCancelled, () => cancelled = true).Add(x => x.OnSaved, () => saved = true));
cut.Find("[data-testid=secret-name]").Change("app/new");
cut.Find("[data-testid=secret-value]").Change("synthetic value");
var pending = cut.Find("[data-testid=editor-submit]").ClickAsync(new MouseEventArgs());
await entered.Task;
try
{
Assert.True(cut.Find("[data-testid=editor-cancel]").HasAttribute("disabled"));
cut.Find("[data-testid=editor-cancel]").Click();
cut.Find("[data-testid=editor-submit]").Click();
Assert.False(cancelled);
Assert.False(saved);
Assert.Empty(store.Upserts);
}
finally { release.TrySetResult(); await pending; }
Assert.Single(store.Upserts);
Assert.True(saved);
}
[Fact]
public async Task SupersededPendingWrite_PreservesCapturedTargetAuditAndCacheButNotSavedCallback()
{
var (store, audit, cipher) = RegisterServices();
var cache = new RecordingCacheInvalidator();
Services.AddSingleton<ISecretCacheInvalidator>(cache);
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
store.UpsertOverride = (_, _) => { entered.TrySetResult(); return release.Task; };
var a = new SecretName("app/a");
AuthorizeManager();
var saved = false;
var cut = Render<SecretEditor>(p => p.Add(x => x.ExistingName, a).Add(x => x.OnSaved, () => saved = true));
cut.Find("[data-testid=secret-value]").Change("new-a");
var pending = cut.Find("[data-testid=editor-submit]").ClickAsync(new MouseEventArgs());
await entered.Task;
try { cut.Render(p => p.Add(x => x.ExistingName, (SecretName?)null)); }
finally { release.TrySetResult(); await pending; }
var row = Assert.Single(store.Upserts);
Assert.Equal(a, row.Name);
Assert.Equal("new-a", cipher.Decrypt(row));
var evt = Assert.Single(audit.Events);
Assert.Equal("secret.rotate", evt.Action);
Assert.Equal(a.Value, evt.Target);
Assert.Equal(a, Assert.Single(cache.Invalidated));
Assert.False(saved);
Assert.Equal("", cut.Find("[data-testid=secret-value]").GetAttribute("value") ?? "");
}
[Fact]
public async Task TargetChangeDuringAuthorization_DoesNotWriteTheNewTargetWithTheOldDraft()
{
var (store, _, _) = RegisterServices();
AuthorizeManager();
var authState = new TaskCompletionSource<AuthenticationState>(TaskCreationOptions.RunContinuationsAsynchronously);
RenderFragment EditorFor(SecretName name) => builder =>
{
builder.OpenComponent<SecretEditor>(0);
builder.AddAttribute(1, nameof(SecretEditor.ExistingName), (object)name);
builder.CloseComponent();
};
var cut = Render<CascadingValue<Task<AuthenticationState>>>(p => p
.Add(x => x.Value, authState.Task).AddChildContent(EditorFor(new SecretName("app/a"))));
cut.Find("[data-testid=secret-value]").Change("draft for a");
var pending = cut.Find("[data-testid=editor-submit]").ClickAsync(new MouseEventArgs());
cut.Render(p => p.Add(x => x.Value, authState.Task).AddChildContent(EditorFor(new SecretName("app/b"))));
authState.SetResult(new AuthenticationState(new ClaimsPrincipal(
new ClaimsIdentity([new Claim(ClaimTypes.Name, "reviewer")], "fixture"))));
await pending;
Assert.Empty(store.Upserts);
Assert.Equal("app/b", cut.Find("[data-testid=secret-name]").GetAttribute("value"));
Assert.Equal("", cut.Find("[data-testid=secret-value]").GetAttribute("value") ?? "");
}
[Fact]
public async Task DisposalAfterCommit_StillInvalidatesCapturedTargetWithoutCallingSaved()
{
var (store, _, _) = RegisterServices();
var audit = new DelayedSuccessAuditWriter();
var cache = new RecordingCacheInvalidator();
Services.AddSingleton<IAuditWriter>(audit);
Services.AddSingleton<ISecretCacheInvalidator>(cache);
AuthorizeManager();
var saved = false;
var a = new SecretName("app/a");
RenderFragment editor = builder =>
{
builder.OpenComponent<SecretEditor>(0);
builder.AddAttribute(1, nameof(SecretEditor.ExistingName), (object)a);
builder.AddAttribute(2, nameof(SecretEditor.OnSaved), EventCallback.Factory.Create(this, () => saved = true));
builder.CloseComponent();
};
var cut = Render<CascadingValue<bool>>(p => p.Add(x => x.Value, true).AddChildContent(editor));
cut.Find("[data-testid=secret-value]").Change("synthetic new value");
var pending = cut.Find("[data-testid=editor-submit]").ClickAsync(new MouseEventArgs());
await audit.Entered.Task;
Assert.Single(store.Upserts); // The mutation has already committed.
cut.Render(p => p.Add(x => x.Value, true).AddChildContent((RenderFragment)(_ => { }))); // Unmount through the renderer, invoking IDisposable.
audit.Release.SetResult();
await pending;
Assert.Equal(a, Assert.Single(cache.Invalidated));
Assert.False(saved);
Assert.Equal(AuditOutcome.Success, Assert.Single(audit.Events).Outcome);
Assert.Equal(a.Value, audit.Events[0].Target);
}
[Fact]
public async Task CommittedWrite_EvictsCapturedCacheWhenProviderRejectsLateResolution()
{
var (store, audit, _) = RegisterServices();
// Exercise the logging path too: audit failure after commit must not need the dead scope.
audit.SuccessFault = new InvalidOperationException("synthetic audit outage");
var cache = new RecordingCacheInvalidator();
Services.AddSingleton<ISecretCacheInvalidator>(cache);
var provider = new LateResolutionGuardProvider(Services);
var entered = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var release = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
store.UpsertOverride = (_, _) => { entered.TrySetResult(); return release.Task; };
AuthorizeManager();
var a = new SecretName("app/a");
var cut = Render<SecretEditor>(p => p.Add(x => x.ExistingName, a));
// bUnit's built-in IServiceProvider resolves itself. Replace only this injected seam
// after rendering so the fixture can model a circuit scope rejecting late resolution.
typeof(SecretEditor).GetProperty("Services", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic)!
.SetValue(cut.Instance, provider);
cut.Find("[data-testid=secret-value]").Change("synthetic new value");
var pending = cut.Find("[data-testid=editor-submit]").ClickAsync(new MouseEventArgs());
await entered.Task;
Assert.True(provider.ResolutionCount > 0);
provider.RejectResolutions = true;
release.SetResult();
await pending;
Assert.Single(store.Upserts);
Assert.Equal(a, Assert.Single(cache.Invalidated));
Assert.Empty(cut.FindAll("[data-testid=editor-error]"));
}
private sealed class LateResolutionGuardProvider(IServiceProvider inner) : IServiceProvider
{
public bool RejectResolutions { get; set; }
public int ResolutionCount { get; private set; }
public object? GetService(Type serviceType)
{
++ResolutionCount;
if (RejectResolutions) throw new ObjectDisposedException("synthetic circuit provider");
return inner.GetService(serviceType);
}
}
private sealed class DelayedSuccessAuditWriter : 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; // Deliberately ignore cancellation after the captured mutation committed.
Events.Add(evt);
}
}
private void AuthorizeManager()
{
var auth = this.AddAuthorization();
auth.SetAuthorized("reviewer");
auth.SetPolicies(SecretsAuthorization.ManagePolicy);
}
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() })
@@ -1,6 +1,8 @@
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;
@@ -104,6 +106,115 @@ public class SecretsListTests : BunitContext
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);
}
private RecordingSecretStore RegisterEditableStore()
{
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");
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
{