@namespace ZB.MOM.WW.Secrets.Ui.Components
@implements IDisposable
@inject ISecretCipher Cipher
@inject ISecretStore Store
@inject IAuditWriter Audit
@inject IServiceProvider Services
@using Microsoft.Extensions.Logging
@* 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. *@
@if (IsRotate)
{
}
else
{
}
@if (_error is not null)
{
@_error
}
@(IsRotate ? "Rotate" : "Add")
Cancel
@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;
///
/// The secret being rotated. When null the editor is in add mode (name is
/// editable); when set, the editor is in rotate mode (name is read-only and fixed).
///
[Parameter] public SecretName? ExistingName { get; set; }
/// Raised after a successful add or rotate, so a parent can refresh its listing.
[Parameter] public EventCallback OnSaved { get; set; }
/// Raised when the user cancels the editor without saving.
[Parameter] public EventCallback OnCancelled { get; set; }
/// The cascading authentication state, used as the fallback source of the audit actor.
[CascadingParameter] private Task? AuthState { get; set; }
private bool IsRotate => ExistingName is not null;
private bool _metadataLoaded;
///
protected override async Task OnParametersSetAsync()
{
if (IsRotate)
{
_name = ExistingName!.Value.Value;
// 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)
{
_metadataLoaded = true;
StoredSecret? row = await Store.GetAsync(ExistingName.Value, _cts.Token);
_description = row?.Description ?? string.Empty;
_contentType = row?.ContentType ?? SecretContentType.Text;
}
}
}
private async Task SubmitAsync()
{
_error = null;
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);
try
{
if (!IsRotate)
{
// 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);
string? refusal = AddRefusal(name, existing);
if (refusal is not null)
{
_error = refusal;
return;
}
}
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);
// The write is committed (and, on a replicated host, already published) from here on.
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 (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);
}
}
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()?.Invalidate(name);
await OnSaved.InvokeAsync();
}
}
// The name whose tombstone the operator has been warned about; a second submit of the SAME
// name restores it. Any other name starts over.
private string? _restoreConfirmedFor;
private string? AddRefusal(SecretName name, StoredSecret? existing)
{
if (existing is null)
{
return null;
}
if (!existing.IsDeleted)
{
return $"A secret named '{name.Value}' already exists. Use Rotate to change its value.";
}
if (string.Equals(_restoreConfirmedFor, name.Value, StringComparison.Ordinal))
{
return null;
}
_restoreConfirmedFor = name.Value;
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)
{
try
{
await Audit.WriteAsync(
new AuditEvent
{
EventId = Guid.NewGuid(),
OccurredAtUtc = DateTimeOffset.UtcNow,
Actor = actor,
Action = action,
Outcome = AuditOutcome.Success,
Category = "Secrets",
Target = target,
},
_cts.Token);
}
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>()?.LogWarning(
ex,
"Secret {Action} of {SecretName} by {Actor} succeeded, but its audit event could not be written.",
action,
target,
actor);
}
}
private async Task WriteFailureAuditAsync(string actor, string action, string target)
{
try
{
await Audit.WriteAsync(
new AuditEvent
{
EventId = Guid.NewGuid(),
OccurredAtUtc = DateTimeOffset.UtcNow,
Actor = actor,
Action = action,
Outcome = AuditOutcome.Failure,
Category = "Secrets",
Target = target,
DetailsJson = "{\"reason\":\"error\"}",
},
_cts.Token);
}
catch
{
// Best-effort audit of a failure; never let audit itself surface into the event pipeline.
}
}
private Task CancelAsync() => OnCancelled.InvokeAsync();
///
public void Dispose()
{
_cts.Cancel();
_cts.Dispose();
}
}