fix(secrets-ui): isolate drafts and pending operations by editor target
This commit is contained in:
@@ -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();
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user