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:
@@ -22,6 +22,23 @@ public interface IOpcUaNodeWriteGateway
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>A task resolving to the device-write outcome.</returns>
|
||||
Task<NodeWriteOutcome> WriteAsync(string nodeId, object? value, AddressSpaceRealm realm, CancellationToken ct);
|
||||
|
||||
/// <summary>
|
||||
/// #1017 — <see cref="WriteAsync(string, object?, AddressSpaceRealm, CancellationToken)"/> carrying WHO wrote
|
||||
/// (the session's principal + API key id), so a driver whose device enforces per-user write permission
|
||||
/// (<see cref="ZB.MOM.WW.OtOpcUa.Core.Abstractions.ICallerAwareWritable"/>) can act on it. The default
|
||||
/// implementation drops the caller — a gateway that cannot carry it behaves exactly as before.
|
||||
/// </summary>
|
||||
/// <param name="nodeId">The full ns-qualified node id being written.</param>
|
||||
/// <param name="value">The value the client wrote.</param>
|
||||
/// <param name="realm">The namespace realm of <paramref name="nodeId"/>.</param>
|
||||
/// <param name="caller">Who issued the write; null when unknown.</param>
|
||||
/// <param name="ct">Cancellation token.</param>
|
||||
/// <returns>A task resolving to the device-write outcome.</returns>
|
||||
Task<NodeWriteOutcome> WriteAsync(
|
||||
string nodeId, object? value, AddressSpaceRealm realm,
|
||||
ZB.MOM.WW.OtOpcUa.Core.Abstractions.WriteCaller? caller, CancellationToken ct)
|
||||
=> WriteAsync(nodeId, value, realm, ct);
|
||||
}
|
||||
|
||||
/// <summary>Outcome of routing an inbound node write to the backing driver.</summary>
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
|
||||
/// <summary>
|
||||
/// Who issued a write (#1017): the authenticated data-plane principal and, for a key-bearing session, the
|
||||
/// public id of the API key it authenticated with. Carries no secret. <see cref="ApiKeyId" /> null = an
|
||||
/// anonymous session (or a write with no client session behind it).
|
||||
/// </summary>
|
||||
/// <param name="Principal">The ACL principal (e.g. the key's principal, or <c>anonymous</c>); null when unknown.</param>
|
||||
/// <param name="ApiKeyId">The authenticating API key's public id; null for anonymous.</param>
|
||||
public sealed record WriteCaller(string? Principal, string? ApiKeyId);
|
||||
|
||||
/// <summary>
|
||||
/// Optional companion to <see cref="IWritable" /> for a driver whose device enforces a per-USER write
|
||||
/// permission and can therefore act on the caller's identity (#1017 — the Galaxy driver's SecuredWrite
|
||||
/// attributes, written under the calling API key's Galaxy account). The runtime calls this overload instead
|
||||
/// of <see cref="IWritable.WriteAsync" /> whenever the write carries a <see cref="WriteCaller" />. It must keep
|
||||
/// every other behaviour of <see cref="IWritable.WriteAsync" />; a caller the driver cannot map is refused
|
||||
/// per write (e.g. <c>BadUserAccessDenied</c>), never silently written under another identity.
|
||||
/// </summary>
|
||||
public interface ICallerAwareWritable : IWritable
|
||||
{
|
||||
/// <summary>Write a batch on behalf of <paramref name="caller" />; one result per request, in order.</summary>
|
||||
/// <param name="writes">Pairs of full reference + value to write.</param>
|
||||
/// <param name="caller">Who issued the write.</param>
|
||||
/// <param name="cancellationToken">Cancellation token; the driver should abort the batch if cancelled.</param>
|
||||
/// <returns>One <see cref="WriteResult" /> per requested write, in the same order.</returns>
|
||||
Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes,
|
||||
WriteCaller caller,
|
||||
CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -176,7 +176,34 @@ public sealed record GalaxyMxAccessOptions(
|
||||
string ClientName,
|
||||
int PublishingIntervalMs = 1000,
|
||||
int WriteUserId = 0,
|
||||
[Range(1, int.MaxValue)] int EventPumpChannelCapacity = 50_000);
|
||||
[Range(1, int.MaxValue)] int EventPumpChannelCapacity = 50_000)
|
||||
{
|
||||
/// <summary>
|
||||
/// How a write to a <c>SecuredWrite</c> attribute is handled (#1017). Default
|
||||
/// <see cref="GalaxySecuredWriteMode.Refuse"/> — refused <c>BadUserAccessDenied</c> locally (#991). A
|
||||
/// <c>VerifiedWrite</c> attribute is refused in every mode.
|
||||
/// </summary>
|
||||
public GalaxySecuredWriteMode SecuredWrites { get; init; } = GalaxySecuredWriteMode.Refuse;
|
||||
}
|
||||
|
||||
/// <summary>How the Galaxy driver handles a write to a <c>SecuredWrite</c> attribute (#1017).</summary>
|
||||
/// <remarks>Always (de)serialised as its NAME, whatever the caller's serializer options: the driver factory parses
|
||||
/// the string, and the browser/probe deserialise the options with options that may lack an enum converter.</remarks>
|
||||
[System.Text.Json.Serialization.JsonConverter(typeof(System.Text.Json.Serialization.JsonStringEnumConverter<GalaxySecuredWriteMode>))]
|
||||
public enum GalaxySecuredWriteMode
|
||||
{
|
||||
/// <summary>Refuse it <c>BadUserAccessDenied</c> before anything reaches the gateway (the #991 behaviour).</summary>
|
||||
Refuse,
|
||||
|
||||
/// <summary>
|
||||
/// Write it as the CALLING session's API key's Galaxy identity — the account mapped to the key on AdminUI
|
||||
/// <c>/api-keys</c> (the same identity a native alarm acknowledge from that key uses,
|
||||
/// <see cref="GalaxyAckIdentitySecrets"/>): <c>AuthenticateUser</c> then <c>WriteSecured</c>. Anonymous
|
||||
/// sessions and keys with no (or a broken) identity are refused; there is NO driver fallback account for
|
||||
/// writes. Needs the driver's gateway API key to hold the <c>invoke:secure</c> scope.
|
||||
/// </summary>
|
||||
ApiKeyIdentity,
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Galaxy Repository browse-side knobs consumed by PR 4.1's <c>GalaxyDiscoverer</c>.
|
||||
|
||||
@@ -38,7 +38,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy;
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class GalaxyDriver
|
||||
: IDriver, ITagDiscovery, IReadable, IWritable, ISubscribable, IRediscoverable, IHostConnectivityProbe, IAlarmSource, IAlarmInitialStateSignal, IAlarmAcknowledgePreflight, IAlarmAcknowledgeConfirmation, ISkippedTagReporter, IDisposable, IAsyncDisposable
|
||||
: IDriver, ITagDiscovery, IReadable, IWritable, ICallerAwareWritable, ISubscribable, IRediscoverable, IHostConnectivityProbe, IAlarmSource, IAlarmInitialStateSignal, IAlarmAcknowledgePreflight, IAlarmAcknowledgeConfirmation, ISkippedTagReporter, IDisposable, IAsyncDisposable
|
||||
{
|
||||
/// <summary>Authored tags this driver could not dial — a TagConfig with no usable
|
||||
/// <c>attributeRef</c> has no MXAccess address to bind.</summary>
|
||||
@@ -396,7 +396,7 @@ public sealed class GalaxyDriver
|
||||
|
||||
/// <summary>
|
||||
/// Test-visible ctor — inject custom seams so <see cref="DiscoverAsync"/>,
|
||||
/// <see cref="ReadAsync"/>, <see cref="WriteAsync"/>, and
|
||||
/// <see cref="ReadAsync"/>, <see cref="WriteAsync(IReadOnlyList{WriteRequest}, CancellationToken)"/>, and
|
||||
/// <see cref="SubscribeAsync"/> can be exercised against canned data without
|
||||
/// building real gRPC channels.
|
||||
/// </summary>
|
||||
@@ -908,7 +908,7 @@ public sealed class GalaxyDriver
|
||||
|
||||
/// <summary>
|
||||
/// #991 G-1 — one security seed pass: fetch the authored objects' attributes and record each authored tag's
|
||||
/// <see cref="SecurityClassification"/> under its RawPath, the key <see cref="WriteAsync"/> resolves against.
|
||||
/// <see cref="SecurityClassification"/> under its RawPath, the key <see cref="WriteAsync(IReadOnlyList{WriteRequest}, CancellationToken)"/> resolves against.
|
||||
/// Before this the map was filled only by <see cref="DiscoverAsync"/>, which the runtime never calls on a
|
||||
/// served driver. Never throws; a failed or late pass leaves the map as it was (FreeAccess for anything
|
||||
/// unseen, i.e. the raw path).
|
||||
@@ -2380,6 +2380,25 @@ public sealed class GalaxyDriver
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes, CancellationToken cancellationToken)
|
||||
=> WriteCoreAsync(writes, caller: null, cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// #1017 — <see cref="WriteAsync(IReadOnlyList{WriteRequest}, CancellationToken)"/> on behalf of
|
||||
/// <paramref name="caller"/>. With <c>MxAccess.SecuredWrites = ApiKeyIdentity</c> a SecuredWrite attribute is
|
||||
/// written as the caller's API key's own Galaxy identity (no fallback account); otherwise — and for every
|
||||
/// VerifiedWrite attribute — it is refused <c>BadUserAccessDenied</c> as before. Non-secured tags are
|
||||
/// unaffected by the caller.
|
||||
/// </summary>
|
||||
/// <param name="writes">Pairs of full reference (RawPath) + value.</param>
|
||||
/// <param name="caller">Who issued the write.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>One result per request, in order.</returns>
|
||||
public Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes, WriteCaller caller, CancellationToken cancellationToken)
|
||||
=> WriteCoreAsync(writes, caller ?? throw new ArgumentNullException(nameof(caller)), cancellationToken);
|
||||
|
||||
private Task<IReadOnlyList<WriteResult>> WriteCoreAsync(
|
||||
IReadOnlyList<WriteRequest> writes, WriteCaller? caller, CancellationToken cancellationToken)
|
||||
{
|
||||
ObjectDisposedException.ThrowIf(_disposed, this);
|
||||
ArgumentNullException.ThrowIfNull(writes);
|
||||
@@ -2403,8 +2422,17 @@ public sealed class GalaxyDriver
|
||||
var dialledWrites = new List<WriteRequest>(writes.Count);
|
||||
foreach (var w in writes) dialledWrites.Add(w with { FullReference = ToAttributeRef(w.FullReference) });
|
||||
|
||||
// #1017: only an opted-in driver with a known caller carries an identity source; the writer resolves it
|
||||
// lazily (at most once per batch, only for a SecuredWrite tag). Key-only — never the ack fallback account.
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential = null;
|
||||
if (caller is not null && _options.MxAccess.SecuredWrites == GalaxySecuredWriteMode.ApiKeyIdentity)
|
||||
{
|
||||
var apiKeyId = caller.ApiKeyId;
|
||||
securedCredential = ct => _ackCredentialResolver.ResolveKeyIdentityAsync(apiKeyId, ct);
|
||||
}
|
||||
|
||||
return _dataWriter.WriteAsync(
|
||||
dialledWrites, attributeRef => ResolveSecurity(ToRawPath(attributeRef)), cancellationToken);
|
||||
dialledWrites, attributeRef => ResolveSecurity(ToRawPath(attributeRef)), securedCredential, cancellationToken);
|
||||
}
|
||||
|
||||
// ===== ISubscribable (PR 4.4) =====
|
||||
|
||||
@@ -115,7 +115,10 @@ public static class GalaxyDriverFactoryExtensions
|
||||
$"Galaxy driver '{driverInstanceId}' missing required MxAccess.ClientName"),
|
||||
PublishingIntervalMs: dto.MxAccess.PublishingIntervalMs ?? 1000,
|
||||
WriteUserId: dto.MxAccess.WriteUserId ?? 0,
|
||||
EventPumpChannelCapacity: dto.MxAccess.EventPumpChannelCapacity ?? 50_000),
|
||||
EventPumpChannelCapacity: dto.MxAccess.EventPumpChannelCapacity ?? 50_000)
|
||||
{
|
||||
SecuredWrites = ParseSecuredWrites(dto.MxAccess.SecuredWrites, driverInstanceId),
|
||||
},
|
||||
Repository: new GalaxyRepositoryOptions(
|
||||
DiscoverPageSize: dto.Repository?.DiscoverPageSize ?? 5000,
|
||||
WatchDeployEvents: dto.Repository?.WatchDeployEvents ?? true),
|
||||
@@ -143,6 +146,24 @@ public static class GalaxyDriverFactoryExtensions
|
||||
|
||||
private static string? NullIfBlank(string? value) => string.IsNullOrWhiteSpace(value) ? null : value.Trim();
|
||||
|
||||
/// <summary>
|
||||
/// #1017: <c>MxAccess.SecuredWrites</c> — absent/blank = <see cref="GalaxySecuredWriteMode.Refuse"/>. An
|
||||
/// unknown value fails the driver config loudly rather than silently refusing (a misspelt opt-in would
|
||||
/// otherwise look like a Galaxy permission problem).
|
||||
/// </summary>
|
||||
internal static GalaxySecuredWriteMode ParseSecuredWrites(string? value, string driverInstanceId)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(value)) return GalaxySecuredWriteMode.Refuse;
|
||||
var text = value.Trim();
|
||||
if (!int.TryParse(text, out _)
|
||||
&& Enum.TryParse<GalaxySecuredWriteMode>(text, ignoreCase: true, out var mode)
|
||||
&& Enum.IsDefined(mode))
|
||||
return mode;
|
||||
throw new InvalidOperationException(
|
||||
$"Galaxy driver '{driverInstanceId}' has an unknown MxAccess.SecuredWrites value '{text}' " +
|
||||
$"(expected {string.Join(" | ", Enum.GetNames<GalaxySecuredWriteMode>())}).");
|
||||
}
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
PropertyNameCaseInsensitive = true,
|
||||
@@ -218,6 +239,8 @@ public static class GalaxyDriverFactoryExtensions
|
||||
public int? WriteUserId { get; init; }
|
||||
/// <summary>Gets or sets the event pump channel capacity.</summary>
|
||||
public int? EventPumpChannelCapacity { get; init; }
|
||||
/// <summary>Gets or sets the SecuredWrite handling (#1017): <c>Refuse</c> (default) or <c>ApiKeyIdentity</c>.</summary>
|
||||
public string? SecuredWrites { get; init; }
|
||||
}
|
||||
|
||||
/// <summary>Repository configuration section.</summary>
|
||||
|
||||
@@ -46,7 +46,7 @@ internal sealed class GalaxyAckCredentialResolver : IGalaxyAckCredentialResolver
|
||||
string? keyNote = null;
|
||||
if (!string.IsNullOrWhiteSpace(apiKeyId))
|
||||
{
|
||||
var keyResult = await ResolveKeyIdentityAsync(apiKeyId, cancellationToken).ConfigureAwait(false);
|
||||
var keyResult = await ResolveMappedKeyIdentityAsync(apiKeyId, cancellationToken).ConfigureAwait(false);
|
||||
if (keyResult.Credential is not null) return keyResult;
|
||||
// A key whose identity is half-configured (user without password, unreadable secret) is
|
||||
// refused outright — silently acknowledging as the fallback account would record the wrong
|
||||
@@ -66,8 +66,30 @@ internal sealed class GalaxyAckCredentialResolver : IGalaxyAckCredentialResolver
|
||||
"in AdminUI /api-keys or configure the driver's fallback ack account.");
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<GalaxyAckCredentialResolution> ResolveKeyIdentityAsync(string? apiKeyId, CancellationToken cancellationToken)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(apiKeyId))
|
||||
{
|
||||
return GalaxyAckCredentialResolution.Refused(
|
||||
"the session is anonymous (no API key), and a secured write runs only as the calling key's own Galaxy identity");
|
||||
}
|
||||
|
||||
var keyResult = await ResolveMappedKeyIdentityAsync(apiKeyId, cancellationToken).ConfigureAwait(false);
|
||||
if (keyResult.Credential is not null || keyResult.RefusalReason is not null)
|
||||
{
|
||||
return keyResult.RefusalReason is null
|
||||
? keyResult
|
||||
: GalaxyAckCredentialResolution.Refused(keyResult.RefusalReason.Replace(
|
||||
"the acknowledge was not sent", "the write was not sent", StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
return GalaxyAckCredentialResolution.Refused(
|
||||
$"API key '{apiKeyId}' has no Galaxy identity (AdminUI /api-keys); a secured write has no fallback account.");
|
||||
}
|
||||
|
||||
// Returns Resolved, Refused (mapped but broken), or (null, null) = "no identity mapped".
|
||||
private async Task<GalaxyAckCredentialResolution> ResolveKeyIdentityAsync(string apiKeyId, CancellationToken ct)
|
||||
private async Task<GalaxyAckCredentialResolution> ResolveMappedKeyIdentityAsync(string apiKeyId, CancellationToken ct)
|
||||
{
|
||||
string userName, passwordName;
|
||||
try
|
||||
|
||||
@@ -13,10 +13,11 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
||||
/// Production <see cref="IGalaxyDataWriter"/> over <see cref="GalaxyMxSession"/>.
|
||||
/// For each batch entry: lazy-AddItem to obtain the MXAccess item handle, encode
|
||||
/// the value via <see cref="MxValueEncoder"/>, supervisory-advise + Write, and translate the
|
||||
/// reply's <c>MxStatusProxy</c> into an OPC UA <see cref="WriteResult"/>. A SecuredWrite /
|
||||
/// VerifiedWrite attribute (per-tag <see cref="SecurityClassification"/>) is refused
|
||||
/// <c>BadUserAccessDenied</c> without a round trip — the driver has no ArchestrA identity to
|
||||
/// write it under (#991 review G-1).
|
||||
/// reply's <c>MxStatusProxy</c> into an OPC UA <see cref="WriteResult"/>. A SecuredWrite attribute
|
||||
/// (per-tag <see cref="SecurityClassification"/>) is written as the caller's Galaxy identity when the
|
||||
/// driver supplies one (#1017: own plain-advised handle → <c>AuthenticateUser</c> → <c>WriteSecured</c>),
|
||||
/// and refused <c>BadUserAccessDenied</c> without a round trip otherwise (#991 review G-1); a
|
||||
/// VerifiedWrite attribute is always refused that way (no verifying user).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Item handle cache survives across writes — repeated writes to the same tag avoid
|
||||
@@ -41,6 +42,11 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
private readonly ConcurrentDictionary<int, byte> _supervisedHandles = new();
|
||||
// Attributes whose secured/verified-write refusal has been logged (once per attribute, #991 review G-1).
|
||||
private readonly ConcurrentDictionary<string, byte> _securedRefusalWarned = new(StringComparer.OrdinalIgnoreCase);
|
||||
// #1017: the secured path's OWN item handles, PLAIN-advised (AuthenticateUser + WriteSecured commits through a
|
||||
// plain advise — live-captured, mxaccessgw docs/LiveCaptures-2026-11-13.md §4). Kept apart from _itemHandles,
|
||||
// whose handles are supervisory-advised for the raw path: MXAccess allows one advise mode per handle.
|
||||
private readonly ConcurrentDictionary<string, int> _securedItemHandles = new(StringComparer.OrdinalIgnoreCase);
|
||||
private readonly ConcurrentDictionary<int, byte> _securedAdvisedHandles = new();
|
||||
private int _addItemCallCount;
|
||||
|
||||
// Write failure-visibility meters (archreview 06/S-1). Reuse the pump's meter name so the single host
|
||||
@@ -73,6 +79,8 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
{
|
||||
_itemHandles.Clear();
|
||||
_supervisedHandles.Clear();
|
||||
_securedItemHandles.Clear();
|
||||
_securedAdvisedHandles.Clear();
|
||||
}
|
||||
|
||||
// ===== Test seams (internal — not part of the public contract) =====
|
||||
@@ -109,10 +117,25 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
public Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes,
|
||||
Func<string, SecurityClassification> securityResolver,
|
||||
CancellationToken cancellationToken)
|
||||
=> WriteCoreAsync(writes, securityResolver, securedCredential: null, cancellationToken);
|
||||
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyList<WriteResult>> IGalaxyDataWriter.WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes,
|
||||
Func<string, SecurityClassification> securityResolver,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential,
|
||||
CancellationToken cancellationToken)
|
||||
=> WriteCoreAsync(writes, securityResolver, securedCredential, cancellationToken);
|
||||
|
||||
private async Task<IReadOnlyList<WriteResult>> WriteCoreAsync(
|
||||
IReadOnlyList<WriteRequest> writes,
|
||||
Func<string, SecurityClassification> securityResolver,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(writes);
|
||||
ArgumentNullException.ThrowIfNull(securityResolver);
|
||||
@@ -125,7 +148,7 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
// Bind the per-batch MX write operations behind the internal IMxWriteOps seam (see below) so the
|
||||
// whole write pipeline is unit-testable without the sealed SDK session (archreview 06/S-1).
|
||||
var ops = new SessionMxWriteOps(session, serverHandle);
|
||||
return await WriteBatchAsync(ops, writes, securityResolver, cancellationToken).ConfigureAwait(false);
|
||||
return await WriteBatchAsync(ops, writes, securityResolver, cancellationToken, securedCredential).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -142,10 +165,12 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
/// <param name="securityResolver">Per-tag classification resolver.</param>
|
||||
/// <param name="ct">The cancellation token.</param>
|
||||
/// <returns>One result per request, in input order.</returns>
|
||||
/// <param name="securedCredential">The caller's Galaxy identity source for secured writes (#1017); null = none.</param>
|
||||
internal Task<IReadOnlyList<WriteResult>> WriteBatchForTestAsync(
|
||||
IMxWriteOps ops, IReadOnlyList<WriteRequest> writes,
|
||||
Func<string, SecurityClassification> securityResolver, CancellationToken ct)
|
||||
=> WriteBatchAsync(ops, writes, securityResolver, ct);
|
||||
Func<string, SecurityClassification> securityResolver, CancellationToken ct,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential = null)
|
||||
=> WriteBatchAsync(ops, writes, securityResolver, ct, securedCredential);
|
||||
|
||||
/// <summary>
|
||||
/// Run a batch as one lane per distinct tag (OrdinalIgnoreCase): writes to the SAME tag
|
||||
@@ -155,11 +180,21 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
/// </summary>
|
||||
private async Task<IReadOnlyList<WriteResult>> WriteBatchAsync(
|
||||
IMxWriteOps ops, IReadOnlyList<WriteRequest> writes,
|
||||
Func<string, SecurityClassification> securityResolver, CancellationToken ct)
|
||||
Func<string, SecurityClassification> securityResolver, CancellationToken ct,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential = null)
|
||||
{
|
||||
var results = new WriteResult[writes.Count];
|
||||
if (writes.Count == 0) return results;
|
||||
|
||||
// #1017: the caller's identity is resolved at most ONCE per batch, and only when a secured tag needs it.
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? batchCredential = null;
|
||||
if (securedCredential is not null)
|
||||
{
|
||||
var once = new Lazy<Task<GalaxyAckCredentialResolution>>(
|
||||
() => securedCredential(ct), LazyThreadSafetyMode.ExecutionAndPublication);
|
||||
batchCredential = _ => once.Value;
|
||||
}
|
||||
|
||||
// Group request indices by tag, first-seen order preserved so the lane start order is
|
||||
// deterministic and a same-tag sequence keeps its authored order.
|
||||
var lanes = new Dictionary<string, List<int>>(StringComparer.OrdinalIgnoreCase);
|
||||
@@ -203,7 +238,7 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
foreach (var i in lane)
|
||||
{
|
||||
results[i] = await WriteOneAsync(ops, writes[i],
|
||||
securityResolver(writes[i].FullReference), ct).ConfigureAwait(false);
|
||||
securityResolver(writes[i].FullReference), ct, batchCredential).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -216,29 +251,38 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
/// <param name="classification">The tag's security classification.</param>
|
||||
/// <param name="ct">The cancellation token.</param>
|
||||
/// <returns>The translated write result.</returns>
|
||||
/// <param name="securedCredential">The caller's Galaxy identity source for a SecuredWrite (#1017); null = none.</param>
|
||||
internal Task<WriteResult> WriteOneForTestAsync(
|
||||
IMxWriteOps ops, WriteRequest request, SecurityClassification classification, CancellationToken ct)
|
||||
=> WriteOneAsync(ops, request, classification, ct);
|
||||
IMxWriteOps ops, WriteRequest request, SecurityClassification classification, CancellationToken ct,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential = null)
|
||||
=> WriteOneAsync(ops, request, classification, ct, securedCredential);
|
||||
|
||||
private async Task<WriteResult> WriteOneAsync(
|
||||
IMxWriteOps ops, WriteRequest request,
|
||||
SecurityClassification classification, CancellationToken ct)
|
||||
SecurityClassification classification, CancellationToken ct,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential = null)
|
||||
{
|
||||
if (NeedsSecuredWrite(classification))
|
||||
if (classification is SecurityClassification.VerifiedWrite)
|
||||
{
|
||||
// #991 review (G-1): REFUSED, before anything reaches the wire. A SecuredWrite/VerifiedWrite attribute
|
||||
// needs a real ArchestrA identity — AuthenticateUser (+ a verifier for VerifiedWrite), the item advised
|
||||
// for that user, and a gateway key holding invoke:secure — none of which this driver has. Routing it to
|
||||
// WriteSecured could only fail, and the gateway's refusal surfaced as BadCommunicationError (a comms
|
||||
// fault). Until a per-caller identity flow exists this is an access refusal: no health impact.
|
||||
if (_securedRefusalWarned.TryAdd(request.FullReference, 0))
|
||||
// #991 review (G-1) / #1017: ALWAYS refused, before anything reaches the wire. A VerifiedWrite needs a
|
||||
// SECOND, verifying user (MXAccess refuses one with no verifier — 1008 — and one whose verifier is the
|
||||
// writer — 8018, both live-captured). An OPC UA Write carries one caller, never a verifier; a stored
|
||||
// verifier credential would let one client satisfy the two-person rule alone.
|
||||
return RefuseSecured(request.FullReference, classification,
|
||||
"a VerifiedWrite needs a second, verifying user, which an OPC UA write cannot carry");
|
||||
}
|
||||
|
||||
if (classification is SecurityClassification.SecuredWrite)
|
||||
{
|
||||
if (securedCredential is null)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver write to {FullRef} refused BadUserAccessDenied — the attribute is {Classification} and the " +
|
||||
"driver has no ArchestrA user identity to write it under (logged once per attribute).",
|
||||
request.FullReference, classification);
|
||||
// #991 review (G-1): no caller identity is in play (the driver's MxAccess.SecuredWrites is Refuse,
|
||||
// or the write carries no caller) — an access refusal, no health impact.
|
||||
return RefuseSecured(request.FullReference, classification,
|
||||
"the driver has no ArchestrA user identity to write it under (MxAccess.SecuredWrites = Refuse, or no caller)");
|
||||
}
|
||||
return new WriteResult(StatusCodeMap.BadUserAccessDenied);
|
||||
|
||||
return await WriteSecuredOneAsync(ops, request, securedCredential, ct).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
try
|
||||
@@ -289,8 +333,183 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
}
|
||||
}
|
||||
|
||||
private static bool NeedsSecuredWrite(SecurityClassification classification) =>
|
||||
classification is SecurityClassification.SecuredWrite or SecurityClassification.VerifiedWrite;
|
||||
private WriteResult RefuseSecured(string fullRef, SecurityClassification classification, string why)
|
||||
{
|
||||
if (_securedRefusalWarned.TryAdd(fullRef, 0))
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver write to {FullRef} refused BadUserAccessDenied — the attribute is {Classification} and {Why} " +
|
||||
"(logged once per attribute).",
|
||||
fullRef, classification, why);
|
||||
}
|
||||
return new WriteResult(StatusCodeMap.BadUserAccessDenied);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// #1017 — a SecuredWrite under the CALLER's Galaxy identity: the writer's own plain-advised handle →
|
||||
/// <c>AuthenticateUser(DOMAIN\user, password)</c> → <c>WriteSecured(current = that user, verifier = 0)</c>, the
|
||||
/// sequence mxaccessgw live-captured committing (docs/LiveCaptures-2026-11-13.md §4). The password goes only
|
||||
/// into the <c>AuthenticateUser</c> command; nothing here logs it, and gateway text is scrubbed of it.
|
||||
/// Authenticates on EVERY write (no cached user id): MXAccess's user-id lifetime is unverified, and a rotated
|
||||
/// or revoked identity must take effect on the next write.
|
||||
/// </summary>
|
||||
private async Task<WriteResult> WriteSecuredOneAsync(
|
||||
IMxWriteOps ops, WriteRequest request,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>> securedCredential, CancellationToken ct)
|
||||
{
|
||||
GalaxyAckCredentialResolution resolution;
|
||||
try
|
||||
{
|
||||
resolution = await securedCredential(ct).ConfigureAwait(false);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver secured write to {FullRef} refused BadUserAccessDenied — resolving the caller's Galaxy identity failed ({ExceptionType}).",
|
||||
request.FullReference, ex.GetType().Name);
|
||||
return new WriteResult(StatusCodeMap.BadUserAccessDenied);
|
||||
}
|
||||
|
||||
if (resolution.Credential is not { } credential)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver secured write to {FullRef} refused BadUserAccessDenied — {Reason}",
|
||||
request.FullReference, resolution.RefusalReason ?? "no Galaxy identity for the caller");
|
||||
return new WriteResult(StatusCodeMap.BadUserAccessDenied);
|
||||
}
|
||||
|
||||
var password = credential.Password;
|
||||
try
|
||||
{
|
||||
var mxValue = MxValueEncoder.Encode(request.Value);
|
||||
var itemHandle = await EnsureSecuredItemHandleAsync(ops, request.FullReference, ct).ConfigureAwait(false);
|
||||
if (!await EnsurePlainAdvisedAsync(ops, itemHandle, ct).ConfigureAwait(false))
|
||||
{
|
||||
WriteAdviseFailed.Add(1);
|
||||
return new WriteResult(StatusCodeMap.BadCommunicationError);
|
||||
}
|
||||
|
||||
var authReply = await ops.InvokeAsync(new MxCommandRequest
|
||||
{
|
||||
SessionId = ops.SessionId,
|
||||
ClientCorrelationId = Guid.NewGuid().ToString("N"),
|
||||
Command = new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.AuthenticateUser,
|
||||
AuthenticateUser = new AuthenticateUserCommand
|
||||
{
|
||||
ServerHandle = ops.ServerHandle,
|
||||
VerifyUser = credential.DisplayName,
|
||||
VerifyUserPassword = password,
|
||||
},
|
||||
},
|
||||
}, ct).ConfigureAwait(false);
|
||||
|
||||
var userId = authReply.AuthenticateUser?.UserId ?? 0;
|
||||
if (authReply.ProtocolStatus is { } authProto && authProto.Code != ProtocolStatusCode.Ok || userId == 0)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver secured write to {FullRef} refused BadUserAccessDenied — MXAccess did not authenticate " +
|
||||
"Galaxy user {GalaxyUser} ({Code}, native 0x{Hresult:X8}: {Message})",
|
||||
request.FullReference, credential.DisplayName, authReply.ProtocolStatus?.Code, authReply.Hresult,
|
||||
GatewayGalaxyAlarmAcknowledger.Scrub(authReply.ProtocolStatus?.Message ?? authReply.DiagnosticMessage, password));
|
||||
return new WriteResult(StatusCodeMap.BadUserAccessDenied);
|
||||
}
|
||||
|
||||
var writeReply = await ops.InvokeAsync(new MxCommandRequest
|
||||
{
|
||||
SessionId = ops.SessionId,
|
||||
ClientCorrelationId = Guid.NewGuid().ToString("N"),
|
||||
Command = new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.WriteSecured,
|
||||
WriteSecured = new WriteSecuredCommand
|
||||
{
|
||||
ServerHandle = ops.ServerHandle,
|
||||
ItemHandle = itemHandle,
|
||||
CurrentUserId = userId,
|
||||
VerifierUserId = 0,
|
||||
Value = mxValue,
|
||||
},
|
||||
},
|
||||
}, ct).ConfigureAwait(false);
|
||||
|
||||
return TranslateReply(writeReply, request.FullReference);
|
||||
}
|
||||
catch (ArgumentException ex)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver secured write rejected — unsupported value type for {FullRef} ({ExceptionType})",
|
||||
request.FullReference, ex.GetType().Name);
|
||||
return new WriteResult(StatusCodeMap.BadInternalError);
|
||||
}
|
||||
catch (OperationCanceledException) when (ct.IsCancellationRequested) { throw; }
|
||||
catch (Exception ex) when (IsCallerRefused(ex))
|
||||
{
|
||||
// The gateway refused the CALLER — typically the driver's API key lacks invoke:secure.
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver secured write to {FullRef} refused by the gateway ({Reason}) — BadUserAccessDenied. " +
|
||||
"Secured writes need the gateway key to hold the invoke:secure scope.",
|
||||
request.FullReference, ((RpcException)UnwrapRpc(ex)!).StatusCode);
|
||||
return new WriteResult(StatusCodeMap.BadUserAccessDenied);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
// Type + scrubbed message only: an exception on this path could carry the AuthenticateUser request.
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver secured write failed for {FullRef} ({ExceptionType}: {Message})",
|
||||
request.FullReference, ex.GetType().Name, GatewayGalaxyAlarmAcknowledger.Scrub(ex.Message, password));
|
||||
return new WriteResult(StatusCodeMap.BadCommunicationError);
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<int> EnsureSecuredItemHandleAsync(IMxWriteOps ops, string fullRef, CancellationToken ct)
|
||||
{
|
||||
if (_securedItemHandles.TryGetValue(fullRef, out var existing)) return existing;
|
||||
var handle = await ops.AddItemAsync(fullRef, ct).ConfigureAwait(false);
|
||||
Interlocked.Increment(ref _addItemCallCount);
|
||||
_securedItemHandles[fullRef] = handle;
|
||||
return handle;
|
||||
}
|
||||
|
||||
/// <summary>Plain-advise the secured path's handle once per session (MXAccess refuses writes to an unadvised
|
||||
/// item). <c>false</c> = the advise failed and the write must fail closed.</summary>
|
||||
private async Task<bool> EnsurePlainAdvisedAsync(IMxWriteOps ops, int itemHandle, CancellationToken ct)
|
||||
{
|
||||
if (!_securedAdvisedHandles.TryAdd(itemHandle, 0)) return true;
|
||||
|
||||
MxCommandReply reply;
|
||||
try
|
||||
{
|
||||
reply = await ops.InvokeAsync(new MxCommandRequest
|
||||
{
|
||||
SessionId = ops.SessionId,
|
||||
ClientCorrelationId = Guid.NewGuid().ToString("N"),
|
||||
Command = new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.Advise,
|
||||
Advise = new AdviseCommand { ServerHandle = ops.ServerHandle, ItemHandle = itemHandle },
|
||||
},
|
||||
}, ct).ConfigureAwait(false);
|
||||
}
|
||||
catch
|
||||
{
|
||||
_securedAdvisedHandles.TryRemove(itemHandle, out _);
|
||||
throw;
|
||||
}
|
||||
|
||||
if (reply.ProtocolStatus is { } proto && proto.Code != ProtocolStatusCode.Ok)
|
||||
{
|
||||
_securedAdvisedHandles.TryRemove(itemHandle, out _);
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver advise for a secured write failed for item {ItemHandle}: {Code} {Message}",
|
||||
itemHandle, proto.Code, proto.Message);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Whether <paramref name="ex"/> (or an inner exception) is the gateway refusing the caller.</summary>
|
||||
internal static bool IsCallerRefused(Exception ex) =>
|
||||
|
||||
@@ -15,4 +15,15 @@ internal interface IGalaxyAckCredentialResolver
|
||||
/// <param name="cancellationToken">Cancels secret resolution.</param>
|
||||
/// <returns>The resolved credential or the refusal reason.</returns>
|
||||
Task<GalaxyAckCredentialResolution> ResolveAsync(string? apiKeyId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// #1017 — the identity a SECURED WRITE from <paramref name="apiKeyId"/> runs as: the key's own Galaxy
|
||||
/// identity only. Unlike <see cref="ResolveAsync"/> there is NO fallback account — an anonymous session or a
|
||||
/// key without (or with a broken) identity is refused, so a secured write is never attributed to a shared
|
||||
/// account. Never throws for a missing or unreadable credential.
|
||||
/// </summary>
|
||||
/// <param name="apiKeyId">The authenticating API key id, or null (anonymous).</param>
|
||||
/// <param name="cancellationToken">Cancels secret resolution.</param>
|
||||
/// <returns>The resolved credential or the refusal reason.</returns>
|
||||
Task<GalaxyAckCredentialResolution> ResolveKeyIdentityAsync(string? apiKeyId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
||||
|
||||
/// <summary>
|
||||
/// Driver-side seam for batched writes. Production implementation decides by
|
||||
/// <see cref="SecurityClassification"/>: SecuredWrite / VerifiedWrite are refused
|
||||
/// <c>BadUserAccessDenied</c> (no ArchestrA identity to write them under — #991 review G-1),
|
||||
/// everything else goes supervisory-advise + raw <c>Write</c>. Tests substitute a fake to record routing
|
||||
/// <see cref="SecurityClassification"/>: SecuredWrite goes <c>AuthenticateUser</c> + <c>WriteSecured</c> under the
|
||||
/// caller's Galaxy identity when one is supplied (#1017) and is otherwise refused <c>BadUserAccessDenied</c>
|
||||
/// (#991 review G-1); VerifiedWrite is always refused; everything else goes supervisory-advise + raw <c>Write</c>. Tests substitute a fake to record routing
|
||||
/// decisions without touching real gw infrastructure.
|
||||
/// </summary>
|
||||
public interface IGalaxyDataWriter
|
||||
@@ -31,6 +31,24 @@ public interface IGalaxyDataWriter
|
||||
Func<string, SecurityClassification> securityResolver,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// #1017 — <see cref="WriteAsync(IReadOnlyList{WriteRequest}, Func{string, SecurityClassification}, CancellationToken)"/>
|
||||
/// with the CALLER's Galaxy identity for SecuredWrite tags: <paramref name="securedCredential"/> resolves it
|
||||
/// (at most once per batch, only when a SecuredWrite tag is present); null = no identity (secured writes refused).
|
||||
/// VerifiedWrite is refused either way. The default implementation ignores the identity (refuses).
|
||||
/// </summary>
|
||||
/// <param name="writes">Pairs of full reference + value to write.</param>
|
||||
/// <param name="securityResolver">Per-tag classification resolver.</param>
|
||||
/// <param name="securedCredential">The caller's Galaxy identity source, or null.</param>
|
||||
/// <param name="cancellationToken">Aborts the in-flight batch.</param>
|
||||
/// <returns>One <see cref="WriteResult"/> per request entry, in input order.</returns>
|
||||
internal Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes,
|
||||
Func<string, SecurityClassification> securityResolver,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential,
|
||||
CancellationToken cancellationToken)
|
||||
=> WriteAsync(writes, securityResolver, cancellationToken);
|
||||
|
||||
/// <summary>Drop cached gateway item handles + supervisory-advise state. Call after a session
|
||||
/// reconnect — the prior handles are dead, so the next write must re-AddItem + re-AdviseSupervisory.</summary>
|
||||
void InvalidateHandleCaches();
|
||||
|
||||
@@ -14,10 +14,25 @@ internal sealed class TracedGalaxyDataWriter(IGalaxyDataWriter inner, string cli
|
||||
public void InvalidateHandleCaches() => inner.InvalidateHandleCaches();
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
public Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes,
|
||||
Func<string, SecurityClassification> securityResolver,
|
||||
CancellationToken cancellationToken)
|
||||
=> TraceAsync(writes, securityResolver, () => inner.WriteAsync(writes, securityResolver, cancellationToken));
|
||||
|
||||
/// <inheritdoc />
|
||||
Task<IReadOnlyList<WriteResult>> IGalaxyDataWriter.WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes,
|
||||
Func<string, SecurityClassification> securityResolver,
|
||||
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential,
|
||||
CancellationToken cancellationToken)
|
||||
=> TraceAsync(writes, securityResolver,
|
||||
() => inner.WriteAsync(writes, securityResolver, securedCredential, cancellationToken));
|
||||
|
||||
private async Task<IReadOnlyList<WriteResult>> TraceAsync(
|
||||
IReadOnlyList<WriteRequest> writes,
|
||||
Func<string, SecurityClassification> securityResolver,
|
||||
Func<Task<IReadOnlyList<WriteResult>>> write)
|
||||
{
|
||||
using var activity = GalaxyTelemetry.ActivitySource.StartActivity("galaxy.write");
|
||||
activity?.SetTag("galaxy.client", clientName);
|
||||
@@ -44,8 +59,7 @@ internal sealed class TracedGalaxyDataWriter(IGalaxyDataWriter inner, string cli
|
||||
|
||||
try
|
||||
{
|
||||
var results = await inner.WriteAsync(writes, securityResolver, cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
var results = await write().ConfigureAwait(false);
|
||||
activity?.SetTag("galaxy.success_count", results.Count(r => r.StatusCode < 0x80000000u));
|
||||
return results;
|
||||
}
|
||||
|
||||
@@ -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">
|
||||
|
||||
+21
-1
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user