Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/ApiKeys.razor
T
Joseph Doherty 13521354cc feat(galaxy): #1017 SecuredWrite attributes can be written as the calling API key's Galaxy identity (opt-in); VerifiedWrite stays refused
- MxAccess.SecuredWrites = Refuse (default, unchanged #991 local BadUserAccessDenied) |
  ApiKeyIdentity. Opted in, a SecuredWrite runs as the calling key's own /api-keys Galaxy
  identity (ResolveKeyIdentityAsync: no fallback account; anonymous / no identity / broken
  identity refused before the wire): own plain-advised handle (apart from the raw path's
  supervisory handle) -> AuthenticateUser every write -> WriteSecured(userId, 0), the sequence
  mxaccessgw live-captured committing. Auth failure / user id 0 -> BadUserAccessDenied; password
  only in the AuthenticateUser command, scrubbed from every log. Identity resolved once per batch.
- VerifiedWrite is refused in every mode: an OPC UA Write carries no verifier (MXAccess refuses
  no verifier 1008 / self-verifier 8018), and a stored verifier would defeat the two-person rule.
- Caller plumbing: WriteCaller + optional ICallerAwareWritable (Core.Abstractions); node manager
  passes principal + key id -> IOpcUaNodeWriteGateway caller overload (default drops it) ->
  RouteNodeWrite.Caller -> WriteAttribute.Caller -> ICallerAwareWritable. The gRPC data-connection
  write path carries no caller yet (secured writes refused there).
- AdminUI Galaxy form 'Secured writes' select (owned path); enum serialises as its name; factory
  refuses an unknown value. Docs: Galaxy.md design + live-gate checklist. Not live-gated.
2026-12-03 15:29:02 -05:00

400 lines
16 KiB
Plaintext

@page "/apikeys"
@attribute [Authorize(Policy = AdminUiPolicies.FleetAdmin)]
@rendermode RenderMode.InteractiveServer
@using ZB.MOM.WW.OtOpcUa.Configuration.Entities
@using ZB.MOM.WW.OtOpcUa.Core.Authorization
@using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Raw
@using ZB.MOM.WW.OtOpcUa.AdminUI.ApiKeyAck
@inject IApiKeyAdminService Keys
@inject IApiKeyGalaxyAckIdentityService AckIdentities
<PageErrorBoundary>
<PageTitle>OPC UA API keys · OtOpcUa</PageTitle>
<div class="page-head">
<h1>OPC UA API keys</h1>
<span class="spacer"></span>
</div>
@if (_created is not null)
{
<div class="alert alert-success" role="alert">
<strong>Copy this key now — it is not stored and cannot be shown again.</strong>
<pre class="mono mt-2 mb-0" style="white-space:pre-wrap;word-break:break-all">@_created</pre>
<button class="btn btn-sm btn-secondary mt-2" @onclick="() => _created = null">Dismiss</button>
</div>
}
@if (!string.IsNullOrWhiteSpace(_error))
{
<div class="alert alert-danger" role="alert">@_error</div>
}
<section class="panel mb-3">
<h2 class="panel-head">Create a key</h2>
<div style="padding:1rem">
<div class="row g-2">
<div class="col-md-3">
<label class="form-label" for="k-name">Name</label>
<input id="k-name" class="form-control form-control-sm" @bind="_newName"
placeholder="ScadaBridge DCL" />
</div>
<div class="col-md-3">
<label class="form-label" for="k-principal">Principal</label>
<input id="k-principal" class="form-control form-control-sm mono" @bind="_newPrincipal"
placeholder="scadabridge-dcl" />
</div>
<div class="col-md-3">
<label class="form-label" for="k-expires">Expires (optional, UTC)</label>
<input id="k-expires" type="date" class="form-control form-control-sm" @bind="_newExpires" />
</div>
<div class="col-md-3 d-flex align-items-end">
<button class="btn btn-sm btn-primary" @onclick="CreateAsync" disabled="@_busy">Create key</button>
</div>
</div>
</div>
</section>
@if (_ackEditKeyId is not null)
{
<section class="panel mb-3">
<h2 class="panel-head">Galaxy alarm-ack identity — key <span class="mono">@_ackEditKeyId</span></h2>
<div style="padding:1rem">
<div class="form-text mb-2">
Native Galaxy alarm acknowledges from sessions using this key authenticate as this Galaxy account, and
the Historian records it as the operator. Stored encrypted in the Secrets store
(<span class="mono">otopcua/apikeys/@(_ackEditKeyId)/galaxy-ack-*</span>), never in the database. Keys
without an identity use the Galaxy driver's fallback account; with neither, acknowledges are refused.
A Galaxy driver set to <em>Secured writes = API key identity</em> also writes <code>SecuredWrite</code>
attributes as this account (#1017) — with no fallback: a key without an identity cannot make secured writes.
On a split admin/driver topology the two secrets must also exist on the driver nodes.
</div>
<div class="row g-2">
<div class="col-md-3">
<label class="form-label" for="ack-user">Galaxy user</label>
<input id="ack-user" class="form-control form-control-sm" @bind="_ackUser" autocomplete="off" />
</div>
<div class="col-md-3">
<label class="form-label" for="ack-domain">Domain (optional)</label>
<input id="ack-domain" class="form-control form-control-sm" @bind="_ackDomain" autocomplete="off" />
</div>
<div class="col-md-3">
<label class="form-label" for="ack-password">Password</label>
<input id="ack-password" type="password" class="form-control form-control-sm" @bind="_ackPassword"
placeholder="@(_ackEmptyPassword ? "(empty password)" : _ackIdentities.ContainsKey(_ackEditKeyId) ? "leave blank to keep the current password" : null)"
disabled="@_ackEmptyPassword" autocomplete="new-password" />
<div class="form-check mt-1">
<input id="ack-empty-password" type="checkbox" class="form-check-input" @bind="_ackEmptyPassword" @bind:after="OnAckEmptyPasswordChanged" />
<label class="form-check-label" for="ack-empty-password">Empty password</label>
</div>
<div class="form-text">The account's password is genuinely empty (a blank box keeps the stored password).</div>
</div>
<div class="col-md-3 d-flex align-items-end gap-2">
<button class="btn btn-sm btn-primary" @onclick="SaveAckIdentityAsync" disabled="@_busy">Save</button>
@if (_ackIdentities.ContainsKey(_ackEditKeyId))
{
<button class="btn btn-sm btn-outline-danger" @onclick="ClearAckIdentityAsync" disabled="@_busy">Remove</button>
}
<button class="btn btn-sm btn-secondary" @onclick="CloseAckEditor" disabled="@_busy">Cancel</button>
</div>
</div>
</div>
</section>
}
<section class="panel">
<h2 class="panel-head">Keys</h2>
@if (_keys is null)
{
<div style="padding:1rem" class="text-muted">Loading…</div>
}
else if (_keys.Count == 0)
{
<div style="padding:1rem" class="text-muted">
No keys yet. Until one exists, only anonymous sessions can connect.
</div>
}
else
{
<div class="table-wrap" role="region" aria-label="OPC UA API keys" tabindex="0">
<table class="data-table">
<thead>
<tr>
<th scope="col">Name</th>
<th scope="col">Principal</th>
<th scope="col">Key id</th>
<th scope="col">Status</th>
<th scope="col">Galaxy ack identity</th>
<th scope="col">Created (UTC)</th>
<th scope="col">Expires (UTC)</th>
<th scope="col"><span class="visually-hidden">Actions</span></th>
</tr>
</thead>
<tbody>
@foreach (var k in _keys)
{
<tr>
<td>@k.Name</td>
<td><span class="mono">@k.Principal</span></td>
<td><span class="mono">@k.ApiKeyId</span></td>
<td>
@if (!k.Enabled)
{
<span class="badge bg-secondary">revoked</span>
}
else if (k.ExpiresUtc is { } e && e <= DateTime.UtcNow)
{
<span class="badge bg-warning text-dark">expired</span>
}
else
{
<span class="badge bg-success">active</span>
}
</td>
<td>
@if (_ackIdentities.TryGetValue(k.ApiKeyId, out var ackId))
{
<span class="mono">@ackId</span>
}
else
{
<span class="text-muted">driver fallback</span>
}
</td>
<td>@k.CreatedUtc.ToString("yyyy-MM-dd HH:mm")</td>
<td>@(k.ExpiresUtc?.ToString("yyyy-MM-dd") ?? "—")</td>
<td class="text-end">
<div class="btn-group btn-group-sm" role="group">
<button class="btn btn-sm btn-outline-secondary"
@onclick="() => SetEnabledAsync(k.ApiKeyId, !k.Enabled)" disabled="@_busy">
@(k.Enabled ? "Revoke" : "Re-enable")
</button>
<button class="btn btn-sm btn-outline-secondary"
@onclick="() => OpenAckEditor(k.ApiKeyId)" disabled="@_busy">Ack identity</button>
<button class="btn btn-sm btn-outline-danger"
@onclick="() => RequestDelete(k)" disabled="@_busy">Delete</button>
</div>
</td>
</tr>
}
</tbody>
</table>
</div>
}
</section>
<RawConfirmDialog @bind-Visible="_confirmDeleteVisible" Title="Delete API key"
Message="@_confirmDeleteMessage" OnConfirm="ConfirmDeleteAsync" />
</PageErrorBoundary>
@code {
[CascadingParameter] private Task<AuthenticationState>? AuthState { get; set; }
private IReadOnlyList<ApiKey>? _keys;
private IReadOnlyDictionary<string, string> _ackIdentities = new Dictionary<string, string>();
// Galaxy ack identity editor (lmxopcua#749). The password lives in component state only while the
// editor is open and is cleared on save/cancel; it is never rendered back.
private string? _ackEditKeyId;
private string _ackUser = "";
private string _ackDomain = "";
private string _ackPassword = "";
// #1050: explicit "the account's password is empty" — a blank box alone means "keep the stored password".
private bool _ackEmptyPassword;
private string _newName = "";
private string _newPrincipal = "";
private DateTime? _newExpires;
private string? _created;
private string? _error;
private bool _busy;
// Delete is irreversible (the key stops authenticating at once), so it goes through a confirm dialog
// that names the key rather than firing from the row button.
private bool _confirmDeleteVisible;
private string? _confirmDeleteId;
private string _confirmDeleteMessage = "";
protected override async Task OnInitializedAsync() => await ReloadAsync();
private async Task ReloadAsync()
{
try
{
_keys = await Keys.ListAsync(default);
try { _ackIdentities = await AckIdentities.ListAsync(default); }
catch (Exception ex) { _ackIdentities = new Dictionary<string, string>(); _error = $"Galaxy ack identities unavailable: {ex.Message}"; }
// The one-time banner is only meaningful while its key exists; the credential is
// otua_<keyId>_<secret>, so drop it once no listed key matches (deleted here or elsewhere).
if (_created is not null
&& !_keys.Any(k => _created.StartsWith($"otua_{k.ApiKeyId}_", StringComparison.Ordinal)))
{
_created = null;
}
}
catch (Exception ex)
{
_error = ex.Message;
_keys = [];
}
}
private async Task CreateAsync()
{
_busy = true;
_error = null;
_created = null;
try
{
// Shown once, held only in this component's state. There is no way to recover it afterwards
// — the server stores a hash — so it is deliberately not written anywhere else.
_created = await Keys.CreateAsync(
_newName,
_newPrincipal,
// A date-only input means midnight; treat it as UTC rather than local so an operator
// near a timezone boundary does not get a key that expired before it was issued.
_newExpires is { } d ? DateTime.SpecifyKind(d, DateTimeKind.Utc) : null,
notes: null,
default);
_newName = "";
_newPrincipal = "";
_newExpires = null;
await ReloadAsync();
}
catch (Exception ex)
{
_error = ex.Message;
}
finally
{
_busy = false;
}
}
private async Task SetEnabledAsync(string apiKeyId, bool enabled)
{
_busy = true;
_error = null;
try
{
await Keys.SetEnabledAsync(apiKeyId, enabled, default);
await ReloadAsync();
}
catch (Exception ex) { _error = ex.Message; }
finally { _busy = false; }
}
private void RequestDelete(ApiKey key)
{
_confirmDeleteId = key.ApiKeyId;
_confirmDeleteMessage =
$"Permanently delete API key '{key.Name}' ({key.ApiKeyId})? Clients using it will stop authenticating immediately. This cannot be undone.";
_confirmDeleteVisible = true;
}
private async Task ConfirmDeleteAsync()
{
if (_confirmDeleteId is { } id) { await DeleteAsync(id); }
}
private async Task DeleteAsync(string apiKeyId)
{
_busy = true;
_error = null;
string? cleanupError = null;
try
{
await Keys.DeleteAsync(apiKeyId, default);
// A deleted key's ack identity must not linger in the Secrets store. The key row is already gone,
// so a Secrets failure here must neither skip the reload (the page would keep listing a dead key)
// nor stay anonymous: name the leftovers so the operator can remove them by hand (#997 A-9).
try { await AckIdentities.ClearAsync(apiKeyId, await ActorAsync(), default); }
catch (Exception ex)
{
cleanupError =
$"Key {apiKeyId} was deleted, but its Galaxy ack identity could not be cleared ({ex.Message}). "
+ $"Remove the Secrets '{ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config.GalaxyAckIdentitySecrets.UserSecretName(apiKeyId)}' and "
+ $"'{ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config.GalaxyAckIdentitySecrets.PasswordSecretName(apiKeyId)}' manually.";
}
if (_ackEditKeyId == apiKeyId) CloseAckEditor();
}
catch (Exception ex) { _error = ex.Message; }
finally
{
await ReloadAsync();
if (cleanupError is not null) _error = _error is null ? cleanupError : $"{cleanupError} {_error}";
_busy = false;
}
}
private void OpenAckEditor(string apiKeyId)
{
_ackEditKeyId = apiKeyId;
_ackPassword = "";
_ackEmptyPassword = false;
if (_ackIdentities.TryGetValue(apiKeyId, out var current))
{
var slash = current.IndexOf('\\');
_ackDomain = slash < 0 ? "" : current[..slash];
_ackUser = slash < 0 ? current : current[(slash + 1)..];
}
else
{
_ackUser = "";
_ackDomain = "";
}
}
private void CloseAckEditor()
{
_ackEditKeyId = null;
_ackUser = "";
_ackDomain = "";
_ackPassword = "";
_ackEmptyPassword = false;
}
// A typed password and "Empty password" are mutually exclusive: ticking the box discards what was typed.
private void OnAckEmptyPasswordChanged()
{
if (_ackEmptyPassword) _ackPassword = "";
}
private async Task SaveAckIdentityAsync()
{
if (_ackEditKeyId is not { } id) return;
_busy = true;
_error = null;
try
{
if (_ackEmptyPassword)
await AckIdentities.SetWithEmptyPasswordAsync(id, _ackUser, _ackDomain, await ActorAsync(), default);
else
await AckIdentities.SetAsync(id, _ackUser, _ackDomain, _ackPassword, await ActorAsync(), default);
CloseAckEditor();
await ReloadAsync();
}
catch (Exception ex) { _error = ex.Message; }
finally { _busy = false; }
}
private async Task ClearAckIdentityAsync()
{
if (_ackEditKeyId is not { } id) return;
_busy = true;
_error = null;
try
{
await AckIdentities.ClearAsync(id, await ActorAsync(), default);
CloseAckEditor();
await ReloadAsync();
}
catch (Exception ex) { _error = ex.Message; }
finally { _busy = false; }
}
private async Task<string> ActorAsync()
{
var user = AuthState is null ? null : (await AuthState).User;
return user?.Identity?.Name is { Length: > 0 } name ? name : "unknown";
}
}