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.
This commit is contained in:
Joseph Doherty
2026-12-03 15:29:02 -05:00
parent 9496db9357
commit 13521354cc
26 changed files with 1120 additions and 65 deletions
@@ -64,6 +64,8 @@
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">
@@ -98,6 +98,20 @@
<div id="@FieldId("field-11-error")" class="field-error">@if (_fieldEditContext is not null) { <ValidationMessage For="@(() => _form.Galaxy.MxEventPumpChannelCapacity)" /> }</div>
<div id="@FieldId("field-11-hint")" class="form-text">Default 50000. Raise if events.dropped appears.</div>
</div>
<div class="col-md-6">
<label for="@FieldId("field-11a")" class="form-label">Secured writes</label>
<InputSelect aria-describedby="@FieldIds("field-11a-hint")" id="@FieldId("field-11a")" @bind-Value="_form.Galaxy.MxSecuredWrites" @bind-Value:after="EmitAsync" class="form-select form-select-sm">
<option value="@GalaxySecuredWriteMode.Refuse">Refuse (default)</option>
<option value="@GalaxySecuredWriteMode.ApiKeyIdentity">Write as the calling API key's Galaxy identity</option>
</InputSelect>
<div id="@FieldId("field-11a-hint")" class="form-text">
How a write to a <code>SecuredWrite</code> attribute is handled (#1017). <em>Refuse</em> answers
<code>BadUserAccessDenied</code>. <em>API key identity</em> authenticates as the Galaxy account mapped to the
session's key on <a href="/apikeys">API keys</a> and issues <code>WriteSecured</code>; anonymous sessions and keys
without an identity are refused (no fallback account). The gateway key needs <code>invoke:secure</code>.
<code>VerifiedWrite</code> attributes are always refused.
</div>
</div>
</div>
</div>
</section>
@@ -239,6 +253,7 @@
"gateway.connectTimeoutSeconds", "gateway.defaultCallTimeoutSeconds", "gateway.streamTimeoutSeconds",
"gateway.keepAlivePingDelaySeconds", "gateway.keepAlivePingTimeoutSeconds",
"mxAccess.clientName", "mxAccess.publishingIntervalMs", "mxAccess.writeUserId", "mxAccess.eventPumpChannelCapacity",
"mxAccess.securedWrites",
"repository.discoverPageSize", "repository.watchDeployEvents",
"reconnect.initialBackoffMs", "reconnect.maxBackoffMs", "reconnect.replayOnSessionLost",
"probeTimeoutSeconds",
@@ -318,6 +333,7 @@
public int MxPublishingIntervalMs { get; set; } = 1000;
public int MxWriteUserId { get; set; } = 0;
public int MxEventPumpChannelCapacity { get; set; } = 50_000;
public GalaxySecuredWriteMode MxSecuredWrites { get; set; } = GalaxySecuredWriteMode.Refuse;
// GalaxyRepositoryOptions
public int RepositoryDiscoverPageSize { get; set; } = 5000;
@@ -359,6 +375,7 @@
MxPublishingIntervalMs = mx.PublishingIntervalMs,
MxWriteUserId = mx.WriteUserId,
MxEventPumpChannelCapacity = mx.EventPumpChannelCapacity,
MxSecuredWrites = mx.SecuredWrites,
RepositoryDiscoverPageSize = repo.DiscoverPageSize,
RepositoryWatchDeployEvents = repo.WatchDeployEvents,
ReconnectInitialBackoffMs = rc.InitialBackoffMs,
@@ -387,7 +404,10 @@
ClientName: MxClientName,
PublishingIntervalMs: MxPublishingIntervalMs,
WriteUserId: MxWriteUserId,
EventPumpChannelCapacity: MxEventPumpChannelCapacity),
EventPumpChannelCapacity: MxEventPumpChannelCapacity)
{
SecuredWrites = MxSecuredWrites,
},
Repository: new GalaxyRepositoryOptions(
DiscoverPageSize: RepositoryDiscoverPageSize,
WatchDeployEvents: RepositoryWatchDeployEvents),
@@ -3557,7 +3557,9 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
var clientUserId = identity is { Principal.Length: > 0 } ? identity.Principal : identity?.DisplayName;
return DispatchDeviceWrite(gateway, nodeKey, nodeBareId, nodeRealm, optimisticValue, priorValue, priorStatus, clientUserId,
(node as EquipmentVariableState)?.ActiveWriteStamp);
(node as EquipmentVariableState)?.ActiveWriteStamp,
// #1017: WHO wrote rides to the driver, so a per-user device permission (Galaxy SecuredWrite) can act on it.
identity is null ? null : new WriteCaller(identity.Principal.Length > 0 ? identity.Principal : null, identity.ApiKeyId));
}
/// <summary>
@@ -3578,12 +3580,14 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage
internal ServiceResult DispatchDeviceWrite(
IOpcUaNodeWriteGateway gateway, string nodeKey, string nodeBareId, AddressSpaceRealm nodeRealm,
object? optimisticValue, object? priorValue, StatusCode priorStatus, string? clientUserId,
EquipmentVariableState.WriteStamp? writeStamp = null)
EquipmentVariableState.WriteStamp? writeStamp = null, WriteCaller? caller = null)
{
Task<NodeWriteOutcome> dispatch;
try
{
dispatch = gateway.WriteAsync(nodeKey, optimisticValue, nodeRealm, CancellationToken.None);
dispatch = caller is null
? gateway.WriteAsync(nodeKey, optimisticValue, nodeRealm, CancellationToken.None)
: gateway.WriteAsync(nodeKey, optimisticValue, nodeRealm, caller, CancellationToken.None);
}
catch (Exception ex)
{
@@ -1,6 +1,7 @@
using Akka.Actor;
using Microsoft.Extensions.Logging;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
@@ -44,7 +45,12 @@ public sealed class ActorNodeWriteGateway : IOpcUaNodeWriteGateway
}
/// <inheritdoc />
public async Task<NodeWriteOutcome> WriteAsync(string nodeId, object? value, AddressSpaceRealm realm, CancellationToken ct)
public Task<NodeWriteOutcome> WriteAsync(string nodeId, object? value, AddressSpaceRealm realm, CancellationToken ct)
=> WriteAsync(nodeId, value, realm, caller: null, ct);
/// <inheritdoc />
public async Task<NodeWriteOutcome> WriteAsync(
string nodeId, object? value, AddressSpaceRealm realm, WriteCaller? caller, CancellationToken ct)
{
var driverHost = _resolveDriverHost();
if (driverHost is null)
@@ -56,7 +62,7 @@ public sealed class ActorNodeWriteGateway : IOpcUaNodeWriteGateway
try
{
var result = await driverHost.Ask<DriverHostActor.NodeWriteResult>(
new DriverHostActor.RouteNodeWrite(nodeId, value, realm), _askTimeout, ct).ConfigureAwait(false);
new DriverHostActor.RouteNodeWrite(nodeId, value, realm, caller), _askTimeout, ct).ConfigureAwait(false);
if (!result.Success)
_logger.LogWarning("Operator write to {NodeId} rejected: {Reason}", nodeId, result.Reason);
return new NodeWriteOutcome(result.Success, result.Reason);
@@ -695,7 +695,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
/// </summary>
/// <param name="NodeId">The folder-scoped equipment-variable NodeId the operator wrote to.</param>
/// <param name="Value">The value to write (the driver coerces it to the attribute's data type).</param>
public sealed record RouteNodeWrite(string NodeId, object? Value, AddressSpaceRealm Realm);
public sealed record RouteNodeWrite(string NodeId, object? Value, AddressSpaceRealm Realm, WriteCaller? Caller = null);
/// <summary>Reply to <see cref="RouteNodeWrite"/>: the outcome of forwarding the write to the driver
/// (or a gate/lookup failure that never reached the driver).</summary>
@@ -2613,7 +2613,7 @@ public sealed partial class DriverHostActor : ReceiveActor, IWithTimers, IWithUn
var replyTo = Sender;
var askDeadline = new CancellationTokenSource(_writeBounds.HostAsk, _writeClock);
entry.Actor.Ask<DriverInstanceActor.WriteAttributeResult>(
new DriverInstanceActor.WriteAttribute(target.RawPath, msg.Value!, _writeClock.GetTimestamp()),
new DriverInstanceActor.WriteAttribute(target.RawPath, msg.Value!, _writeClock.GetTimestamp(), msg.Caller),
System.Threading.Timeout.InfiniteTimeSpan,
askDeadline.Token)
.ContinueWith(
@@ -136,7 +136,7 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
/// stamps it so the time the write spends in this actor's MAILBOX counts against the queue budget too: a write
/// delayed there (behind a hanging alarm subscribe, say) and then started could otherwise still be running
/// when the host's Ask fires (lmxopcua#777).</param>
public sealed record WriteAttribute(string TagId, object Value, long? IssuedAt = null);
public sealed record WriteAttribute(string TagId, object Value, long? IssuedAt = null, WriteCaller? Caller = null);
public sealed record WriteAttributeResult(bool Success, string? Reason);
internal sealed record WriteAttributeWithOutcome(WriteAdmissionTicket Ticket, WriteClaim Claim);
/// <summary>
@@ -1669,7 +1669,11 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers
var attempt = invoker.ExecuteWriteAsync(
hostKey,
isIdempotent: false,
async ct => await writable.WriteAsync(request, ct),
// #1017: a write that carries its caller reaches a driver that can act on it (the Galaxy driver's
// SecuredWrite attributes) through ICallerAwareWritable; every other driver/write is unchanged.
async ct => msg.Caller is { } caller && writable is ICallerAwareWritable callerAware
? await callerAware.WriteAsync(request, caller, ct)
: await writable.WriteAsync(request, ct),
cts.Token).AsTask();
IReadOnlyList<WriteResult> results;
try