fix(galaxy): #991 G-1 authored SecuredWrite/VerifiedWrite tags route to WriteSecured without DiscoverAsync (security map seeded at init and on redeploy)
This commit is contained in:
@@ -0,0 +1,114 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Grpc.Core;
|
||||
using ZB.MOM.WW.MxGateway.Client;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse;
|
||||
|
||||
/// <summary>
|
||||
/// Driver-side seam for the per-attribute <c>security_classification</c> of the AUTHORED Galaxy objects
|
||||
/// (#991 G-1). <c>WriteAsync</c> routes SecuredWrite / VerifiedWrite attributes to <c>WriteSecured</c>; that
|
||||
/// classification used to come only from <c>DiscoverAsync</c>, which the runtime never calls on a served driver,
|
||||
/// so every write took the raw path. The driver seeds its security map from this at <c>InitializeAsync</c> and
|
||||
/// on every deploy-watcher rediscovery.
|
||||
/// </summary>
|
||||
public interface IGalaxyAttributeSecuritySource
|
||||
{
|
||||
/// <summary>The named objects with their attributes. A name the Galaxy does not hold is simply absent.</summary>
|
||||
/// <param name="tagNames">Object <c>tag_name</c>s (the part of an attributeRef before its first dot).</param>
|
||||
/// <param name="cancellationToken">Cancellation token for the query.</param>
|
||||
/// <returns>The objects found, each with its attributes.</returns>
|
||||
Task<IReadOnlyList<GalaxyObject>> GetObjectsAsync(IReadOnlyCollection<string> tagNames, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Default <see cref="IGalaxyAttributeSecuritySource"/>: one <c>DiscoverHierarchy</c> per authored object, rooted
|
||||
/// at its <c>tag_name</c> with <c>max_depth = 0</c> and attributes included — the cost scales with the authored
|
||||
/// objects, not the Galaxy (the full-hierarchy dump the <c>/raw</c> picker pulls would be fetched on every driver
|
||||
/// init). A bounded number run concurrently; an object the gateway reports <c>NotFound</c> is skipped.
|
||||
/// </summary>
|
||||
public sealed class GatewayGalaxyAttributeSecuritySource : IGalaxyAttributeSecuritySource
|
||||
{
|
||||
/// <summary>Concurrent per-object queries.</summary>
|
||||
public const int MaxConcurrency = 4;
|
||||
|
||||
private readonly GalaxyRepositoryClient _client;
|
||||
|
||||
/// <summary>Initializes a new instance of the <see cref="GatewayGalaxyAttributeSecuritySource"/> class.</summary>
|
||||
/// <param name="client">The gateway's Galaxy repository client.</param>
|
||||
public GatewayGalaxyAttributeSecuritySource(GalaxyRepositoryClient client)
|
||||
=> _client = client ?? throw new ArgumentNullException(nameof(client));
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<IReadOnlyList<GalaxyObject>> GetObjectsAsync(
|
||||
IReadOnlyCollection<string> tagNames, CancellationToken cancellationToken)
|
||||
=> QueryAsync(_client.DiscoverHierarchyRawAsync, tagNames, MaxConcurrency, cancellationToken);
|
||||
|
||||
/// <summary>The per-object queries behind a delegate, so they are unit-testable without a channel.</summary>
|
||||
/// <param name="discover">The raw <c>DiscoverHierarchy</c> RPC.</param>
|
||||
/// <param name="tagNames">The objects to fetch.</param>
|
||||
/// <param name="maxConcurrency">Concurrent queries.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>The objects found (only the requested root of each reply).</returns>
|
||||
internal static async Task<IReadOnlyList<GalaxyObject>> QueryAsync(
|
||||
Func<DiscoverHierarchyRequest, CancellationToken, Task<DiscoverHierarchyReply>> discover,
|
||||
IReadOnlyCollection<string> tagNames,
|
||||
int maxConcurrency,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(discover);
|
||||
var found = new ConcurrentBag<GalaxyObject>();
|
||||
await Parallel.ForEachAsync(
|
||||
tagNames,
|
||||
new ParallelOptions { MaxDegreeOfParallelism = Math.Max(1, maxConcurrency), CancellationToken = cancellationToken },
|
||||
async (tagName, token) =>
|
||||
{
|
||||
var request = new DiscoverHierarchyRequest
|
||||
{
|
||||
RootTagName = tagName,
|
||||
MaxDepth = 0,
|
||||
IncludeAttributes = true,
|
||||
PageSize = 1,
|
||||
};
|
||||
DiscoverHierarchyReply reply;
|
||||
try
|
||||
{
|
||||
reply = await discover(request, token).ConfigureAwait(false);
|
||||
}
|
||||
catch (Exception ex) when (IsNotFound(ex))
|
||||
{
|
||||
return; // not deployed (any more) — no classification to learn
|
||||
}
|
||||
foreach (var obj in reply.Objects)
|
||||
{
|
||||
if (string.Equals(obj.TagName, tagName, StringComparison.OrdinalIgnoreCase)) found.Add(obj);
|
||||
}
|
||||
}).ConfigureAwait(false);
|
||||
return [.. found];
|
||||
}
|
||||
|
||||
private static bool IsNotFound(Exception ex)
|
||||
{
|
||||
for (var e = ex; e is not null; e = e.InnerException)
|
||||
{
|
||||
if (e is RpcException { StatusCode: StatusCode.NotFound }) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IGalaxyAttributeSecuritySource"/> over an injected <see cref="IGalaxyHierarchySource"/> — the
|
||||
/// seam-mode fallback, so a driver built around a hierarchy source seeds the same way production does.
|
||||
/// </summary>
|
||||
internal sealed class HierarchyAttributeSecuritySource(IGalaxyHierarchySource hierarchy) : IGalaxyAttributeSecuritySource
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public async Task<IReadOnlyList<GalaxyObject>> GetObjectsAsync(
|
||||
IReadOnlyCollection<string> tagNames, CancellationToken cancellationToken)
|
||||
{
|
||||
var wanted = new HashSet<string>(tagNames, StringComparer.OrdinalIgnoreCase);
|
||||
var all = await hierarchy.GetHierarchyAsync(cancellationToken).ConfigureAwait(false);
|
||||
return [.. all.Where(o => wanted.Contains(o.TagName))];
|
||||
}
|
||||
}
|
||||
@@ -216,6 +216,12 @@ public sealed class GalaxyDriver
|
||||
// from DiscoverAsync alone left the production watcher with no platforms, ever.
|
||||
private readonly IGalaxyPlatformSource? _platformSource;
|
||||
private IGalaxyPlatformSource? _ownedPlatformSource;
|
||||
|
||||
// #991 G-1: the authored tags' security classifications, for WriteAsync's WriteSecured routing. Injected seam
|
||||
// (tests) or, on the production path, per-object DiscoverHierarchy queries over the owned repository client.
|
||||
// Seeded by the same background worker as the platform set (init + every rediscovery).
|
||||
private readonly IGalaxyAttributeSecuritySource? _securitySource;
|
||||
private IGalaxyAttributeSecuritySource? _ownedSecuritySource;
|
||||
// Probe-seed requests (init + every rediscovery) not yet served. The first request starts the
|
||||
// background worker; later ones only bump the count, and the worker loops until it has served
|
||||
// every request it saw — so a request that lands while a pass is mid-fetch (a deploy, or the
|
||||
@@ -388,6 +394,10 @@ public sealed class GalaxyDriver
|
||||
/// over <see cref="GalaxyDriverOptions.AlarmAck"/> and <paramref name="secretResolver"/>.
|
||||
/// </param>
|
||||
/// <param name="ackIdentityDirectory">Optional cached key → Galaxy-identity set (lmxopcua#765).</param>
|
||||
/// <param name="securitySource">
|
||||
/// Optional security-classification seam (#991 G-1). Without it, seam mode falls back to
|
||||
/// <paramref name="hierarchySource"/>; production builds a <see cref="GatewayGalaxyAttributeSecuritySource"/>.
|
||||
/// </param>
|
||||
internal GalaxyDriver(
|
||||
string driverInstanceId,
|
||||
GalaxyDriverOptions options,
|
||||
@@ -402,9 +412,11 @@ public sealed class GalaxyDriver
|
||||
IGalaxyDeployWatchSource? deployWatchSource = null,
|
||||
IGalaxyPlatformSource? platformSource = null,
|
||||
IGalaxyAckCredentialResolver? ackCredentialResolver = null,
|
||||
IGalaxyAckIdentityDirectory? ackIdentityDirectory = null)
|
||||
IGalaxyAckIdentityDirectory? ackIdentityDirectory = null,
|
||||
IGalaxyAttributeSecuritySource? securitySource = null)
|
||||
{
|
||||
_ackIdentityDirectory = ackIdentityDirectory;
|
||||
_securitySource = securitySource;
|
||||
_deployWatchSource = deployWatchSource;
|
||||
_platformSource = platformSource;
|
||||
_driverInstanceId = !string.IsNullOrWhiteSpace(driverInstanceId)
|
||||
@@ -754,24 +766,39 @@ public sealed class GalaxyDriver
|
||||
/// </summary>
|
||||
private async Task PrepareProbeSeedAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
if (_probeWatcher is null) return;
|
||||
var wantsProbe = _probeWatcher is not null;
|
||||
var wantsSecurity = _rawTagByAttributeRef.Count > 0; // #991 G-1: authored tags need their classifications
|
||||
if (!wantsProbe && !wantsSecurity) return;
|
||||
_seedCts ??= new CancellationTokenSource();
|
||||
if (_platformSource is not null || !_ownsRuntime || _ownedPlatformSource is not null) return;
|
||||
if (!_ownsRuntime) return; // seam mode: injected sources only
|
||||
var needPlatform = wantsProbe && _platformSource is null && _ownedPlatformSource is null;
|
||||
var needSecurity = wantsSecurity && _securitySource is null && _ownedSecuritySource is null;
|
||||
if (!needPlatform && !needSecurity) return;
|
||||
try
|
||||
{
|
||||
_ownedRepositoryClient ??= GalaxyRepositoryClient.Create(
|
||||
await BuildClientOptionsAsync(_options.Gateway, cancellationToken).ConfigureAwait(false));
|
||||
_ownedPlatformSource =
|
||||
new GatewayGalaxyPlatformSource(_ownedRepositoryClient, _options.Repository.DiscoverPageSize);
|
||||
if (needPlatform)
|
||||
{
|
||||
_ownedPlatformSource =
|
||||
new GatewayGalaxyPlatformSource(_ownedRepositoryClient, _options.Repository.DiscoverPageSize);
|
||||
}
|
||||
if (needSecurity) _ownedSecuritySource = new GatewayGalaxyAttributeSecuritySource(_ownedRepositoryClient);
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"GalaxyDriver {InstanceId} could not build the platform query — per-platform host status stays unseeded until the next rediscovery.",
|
||||
"GalaxyDriver {InstanceId} could not build the repository queries — per-platform host status and secured-write routing stay unseeded until the next rediscovery.",
|
||||
_driverInstanceId);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>The security-classification source for the current runtime (#991 G-1), or null.</summary>
|
||||
private IGalaxyAttributeSecuritySource? ResolveSecuritySource() =>
|
||||
_securitySource
|
||||
?? _ownedSecuritySource
|
||||
?? (!_ownsRuntime && _hierarchySource is { } hierarchy ? new HierarchyAttributeSecuritySource(hierarchy) : null);
|
||||
|
||||
/// <summary>
|
||||
/// Ask for a background probe seed (init and every deploy-watcher rediscovery). Requests
|
||||
/// coalesce onto one worker; each worker pass serves the runtime that is live when the pass
|
||||
@@ -780,7 +807,8 @@ public sealed class GalaxyDriver
|
||||
/// </summary>
|
||||
private void RequestProbeSeed(string reason)
|
||||
{
|
||||
if (_runtimeStopping || _probeWatcher is null) return;
|
||||
if (_runtimeStopping) return;
|
||||
if (_probeWatcher is null && (_rawTagByAttributeRef.Count == 0 || ResolveSecuritySource() is null)) return;
|
||||
_seedReason = reason;
|
||||
if (Interlocked.Increment(ref _reseedRequests) != 1) return; // the running worker will serve it
|
||||
|
||||
@@ -794,7 +822,9 @@ public sealed class GalaxyDriver
|
||||
var seedCts = Volatile.Read(ref _seedCts);
|
||||
if (!_runtimeStopping && seedCts is not null)
|
||||
{
|
||||
await SeedProbePlatformsAsync(_seedReason, generation, seedCts.Token).ConfigureAwait(false);
|
||||
var reason = _seedReason;
|
||||
await SeedProbePlatformsAsync(reason, generation, seedCts.Token).ConfigureAwait(false);
|
||||
await SeedSecurityClassificationsAsync(reason, generation, seedCts.Token).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
while (Interlocked.Add(ref _reseedRequests, -served) != 0);
|
||||
@@ -843,6 +873,89 @@ 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.
|
||||
/// Before this the map was filled only by <see cref="DiscoverAsync"/>, which the runtime never calls on a
|
||||
/// served driver, so every write — SecuredWrite / VerifiedWrite attributes included — took the raw path and
|
||||
/// was refused. Never throws; a failed or late pass leaves the map as it was (FreeAccess for anything unseen,
|
||||
/// i.e. the raw path, which fails closed).
|
||||
/// </summary>
|
||||
private async Task SeedSecurityClassificationsAsync(string reason, int generation, CancellationToken cancellationToken)
|
||||
{
|
||||
if (_rawTagByAttributeRef.Count == 0) return;
|
||||
var source = ResolveSecuritySource();
|
||||
if (source is null) return;
|
||||
|
||||
// tag_name is the part of the attributeRef before its first dot; a provider-qualified reference
|
||||
// ("Galaxy!Area.tag.Attr") names an alarm, never a writable value.
|
||||
var tagNames = _rawTagByAttributeRef.Keys
|
||||
.Where(r => !r.Contains('!', StringComparison.Ordinal) && r.IndexOf('.', StringComparison.Ordinal) > 0)
|
||||
.Select(r => r[..r.IndexOf('.', StringComparison.Ordinal)])
|
||||
.Distinct(StringComparer.OrdinalIgnoreCase)
|
||||
.ToArray();
|
||||
if (tagNames.Length == 0) return;
|
||||
|
||||
try
|
||||
{
|
||||
var objects = await source.GetObjectsAsync(tagNames, cancellationToken).ConfigureAwait(false);
|
||||
if (Volatile.Read(ref _runtimeGeneration) != generation || _runtimeStopping)
|
||||
{
|
||||
_logger.LogDebug(
|
||||
"GalaxyDriver {InstanceId} discarded a security seed ({Reason}) — its runtime was torn down.",
|
||||
_driverInstanceId, reason);
|
||||
return;
|
||||
}
|
||||
|
||||
var seeded = new Dictionary<string, SecurityClassification>(StringComparer.OrdinalIgnoreCase);
|
||||
foreach (var obj in objects)
|
||||
{
|
||||
foreach (var attr in obj.Attributes)
|
||||
{
|
||||
if (string.IsNullOrEmpty(attr.AttributeName)) continue;
|
||||
// Same attributeRef derivation as GalaxyDiscoverer, so the two paths key identically.
|
||||
var attributeRef = !string.IsNullOrEmpty(attr.FullTagReference)
|
||||
? (attr.FullTagReference.EndsWith("[]", StringComparison.Ordinal)
|
||||
? attr.FullTagReference[..^2]
|
||||
: attr.FullTagReference)
|
||||
: obj.TagName + "." + attr.AttributeName;
|
||||
if (_rawTagByAttributeRef.TryGetValue(attributeRef, out var entry))
|
||||
seeded[entry.RawPath] = SecurityMap.Map(attr.SecurityClassification);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var entry in _rawTagByAttributeRef.Values)
|
||||
{
|
||||
if (seeded.TryGetValue(entry.RawPath, out var classification)) _securityByFullRef[entry.RawPath] = classification;
|
||||
else _securityByFullRef.TryRemove(entry.RawPath, out _); // gone from the Galaxy: back to the default
|
||||
}
|
||||
|
||||
var secured = seeded.Values.Count(c => c is SecurityClassification.SecuredWrite or SecurityClassification.VerifiedWrite);
|
||||
_logger.LogInformation(
|
||||
"GalaxyDriver {InstanceId} security classifications seeded for {Count} authored tag(s), {Secured} secured/verified ({Reason}).",
|
||||
_driverInstanceId, seeded.Count, secured, reason);
|
||||
if (secured > 0 && _options.MxAccess.WriteUserId == 0)
|
||||
{
|
||||
_logger.LogWarning(
|
||||
"GalaxyDriver {InstanceId} has {Secured} SecuredWrite/VerifiedWrite tag(s) but MxAccess.WriteUserId is 0 — " +
|
||||
"WriteSecured carries no ArchestrA user, so MXAccess is expected to refuse those writes.",
|
||||
_driverInstanceId, secured);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (cancellationToken.IsCancellationRequested
|
||||
|| Volatile.Read(ref _runtimeGeneration) != generation)
|
||||
{
|
||||
_logger.LogDebug(ex, "GalaxyDriver {InstanceId} security seed ({Reason}) abandoned by a teardown.",
|
||||
_driverInstanceId, reason);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_logger.LogWarning(ex,
|
||||
"GalaxyDriver {InstanceId} security seed failed ({Reason}) — secured-write routing stays as it was until the next rediscovery.",
|
||||
_driverInstanceId, reason);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Deploy-watcher rediscovery: a redeploy may add or remove platforms / engines.</summary>
|
||||
private void ReseedProbePlatformsOnRediscovery() => RequestProbeSeed("rediscovery");
|
||||
|
||||
@@ -1157,6 +1270,7 @@ public sealed class GalaxyDriver
|
||||
_hierarchySource = null;
|
||||
_alarmAcknowledger = null;
|
||||
_ownedPlatformSource = null;
|
||||
_ownedSecuritySource = null;
|
||||
_ownsRuntime = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -361,8 +361,12 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
/// directly and route through <c>InvokeAsync</c>. Verifier user is left at zero
|
||||
/// for SecuredWrite; VerifiedWrite uses the same path because the gw's worker
|
||||
/// interprets the underlying MXAccess command kind.
|
||||
/// <para>#991 G-1: the current user is the configured <c>MxAccess.WriteUserId</c> — the same identity the
|
||||
/// raw path writes under — instead of a hard-coded 0. With the default 0 a secured write carries no
|
||||
/// ArchestrA user and MXAccess is expected to refuse it; a VerifiedWrite additionally needs a verifier,
|
||||
/// which nothing supplies yet (follow-up: a per-caller Galaxy identity, like the #749 ack credential).</para>
|
||||
/// </summary>
|
||||
private static Task<MxCommandReply> InvokeWriteSecuredAsync(
|
||||
private Task<MxCommandReply> InvokeWriteSecuredAsync(
|
||||
IMxWriteOps ops, int itemHandle, MxValue value, CancellationToken ct)
|
||||
{
|
||||
var command = new MxCommand
|
||||
@@ -373,7 +377,7 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter
|
||||
ServerHandle = ops.ServerHandle,
|
||||
ItemHandle = itemHandle,
|
||||
Value = value,
|
||||
CurrentUserId = 0,
|
||||
CurrentUserId = _writeUserId,
|
||||
VerifierUserId = 0,
|
||||
},
|
||||
};
|
||||
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
using System.Collections.Concurrent;
|
||||
using Grpc.Core;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.MxGateway.Client;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Browse;
|
||||
|
||||
/// <summary>
|
||||
/// #991 G-1 — the production security-classification source asks for each authored object on its own
|
||||
/// (rooted, depth 0, attributes included), so the cost tracks the authored tags rather than the Galaxy.
|
||||
/// </summary>
|
||||
public sealed class GatewayGalaxyAttributeSecuritySourceTests
|
||||
{
|
||||
private static GalaxyObject Obj(string tag) => new() { TagName = tag, ContainedName = tag };
|
||||
|
||||
/// <summary>One rooted, depth-0, attribute-bearing request per object; replies reduced to the requested root.</summary>
|
||||
[Fact]
|
||||
public async Task Each_object_is_fetched_rooted_at_depth_zero_with_attributes()
|
||||
{
|
||||
var requests = new ConcurrentBag<DiscoverHierarchyRequest>();
|
||||
Task<DiscoverHierarchyReply> Discover(DiscoverHierarchyRequest r, CancellationToken _)
|
||||
{
|
||||
requests.Add(r);
|
||||
var reply = new DiscoverHierarchyReply();
|
||||
reply.Objects.Add(Obj(r.RootTagName));
|
||||
reply.Objects.Add(Obj(r.RootTagName + "_Child")); // a gateway ignoring max_depth must not leak children
|
||||
return Task.FromResult(reply);
|
||||
}
|
||||
|
||||
var objects = await GatewayGalaxyAttributeSecuritySource.QueryAsync(
|
||||
Discover, ["Tank1", "Pump7"], maxConcurrency: 2, TestContext.Current.CancellationToken);
|
||||
|
||||
objects.Select(o => o.TagName).OrderBy(n => n).ShouldBe(["Pump7", "Tank1"]);
|
||||
requests.Count.ShouldBe(2);
|
||||
requests.ShouldAllBe(r => r.MaxDepth == 0 && r.IncludeAttributes && r.RootCase == DiscoverHierarchyRequest.RootOneofCase.RootTagName);
|
||||
}
|
||||
|
||||
/// <summary>An object the gateway reports NotFound (undeployed) is skipped; the others still load.</summary>
|
||||
[Fact]
|
||||
public async Task A_not_found_object_is_skipped()
|
||||
{
|
||||
Task<DiscoverHierarchyReply> Discover(DiscoverHierarchyRequest r, CancellationToken _)
|
||||
{
|
||||
if (r.RootTagName == "Gone")
|
||||
{
|
||||
// The client maps an RpcException to MxGatewayException, keeping it as the inner exception.
|
||||
throw new MxGatewayException("not found", new RpcException(new Status(StatusCode.NotFound, "no such object")));
|
||||
}
|
||||
var reply = new DiscoverHierarchyReply();
|
||||
reply.Objects.Add(Obj(r.RootTagName));
|
||||
return Task.FromResult(reply);
|
||||
}
|
||||
|
||||
var objects = await GatewayGalaxyAttributeSecuritySource.QueryAsync(
|
||||
Discover, ["Gone", "Tank1"], maxConcurrency: 1, TestContext.Current.CancellationToken);
|
||||
|
||||
objects.ShouldHaveSingleItem().TagName.ShouldBe("Tank1");
|
||||
}
|
||||
|
||||
/// <summary>Any other failure (gateway down) propagates — the driver keeps the previous map and logs.</summary>
|
||||
[Fact]
|
||||
public async Task Any_other_failure_propagates()
|
||||
{
|
||||
static Task<DiscoverHierarchyReply> Discover(DiscoverHierarchyRequest r, CancellationToken _)
|
||||
=> throw new MxGatewayException("unavailable", new RpcException(new Status(StatusCode.Unavailable, "down")));
|
||||
|
||||
await Should.ThrowAsync<MxGatewayException>(() => GatewayGalaxyAttributeSecuritySource.QueryAsync(
|
||||
Discover, ["Tank1"], maxConcurrency: 1, TestContext.Current.CancellationToken));
|
||||
}
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto.Galaxy;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
|
||||
|
||||
/// <summary>
|
||||
/// #991 G-1 — <c>WriteAsync</c> picks <c>WriteSecured</c> vs the supervisory raw <c>Write</c> from a per-tag
|
||||
/// security map that ONLY <c>DiscoverAsync</c> filled — and the runtime never calls <c>DiscoverAsync</c> on the
|
||||
/// served driver (only the <c>/raw</c> picker's throwaway instance does). Every authored tag resolved
|
||||
/// <c>FreeAccess</c>, so a SecuredWrite/VerifiedWrite attribute always went down the raw path and was refused
|
||||
/// (MXAccess 1012/1013 → <c>BadUserAccessDenied</c>, pointing at permissions rather than the routing). The map is
|
||||
/// now seeded for the authored tags at initialize (and re-seeded on every redeploy) from the Galaxy repository.
|
||||
/// </summary>
|
||||
public sealed class GalaxyDriverSecurityResolutionTests
|
||||
{
|
||||
private static GalaxyDriverOptions Opts(params (string RawPath, string AttributeRef)[] tags) => new(
|
||||
new GalaxyGatewayOptions("https://mxgw.test:5001", "key"),
|
||||
new GalaxyMxAccessOptions("OtOpcUa-A"),
|
||||
new GalaxyRepositoryOptions(WatchDeployEvents: false),
|
||||
new GalaxyReconnectOptions())
|
||||
{
|
||||
RawTags = [.. tags.Select(t => new RawTagEntry(t.RawPath, $$"""{"attributeRef":"{{t.AttributeRef}}"}""", false))],
|
||||
};
|
||||
|
||||
private static GalaxyObject Obj(string tag, params (string Name, int Sec)[] attrs)
|
||||
{
|
||||
var o = new GalaxyObject { TagName = tag, ContainedName = tag };
|
||||
foreach (var (name, sec) in attrs)
|
||||
{
|
||||
o.Attributes.Add(new GalaxyAttribute
|
||||
{
|
||||
AttributeName = name,
|
||||
FullTagReference = $"{tag}.{name}",
|
||||
MxDataType = 2,
|
||||
SecurityClassification = sec,
|
||||
});
|
||||
}
|
||||
return o;
|
||||
}
|
||||
|
||||
private sealed class FakeHierarchySource(IReadOnlyList<GalaxyObject> objects) : IGalaxyHierarchySource
|
||||
{
|
||||
public Task<IReadOnlyList<GalaxyObject>> GetHierarchyAsync(CancellationToken cancellationToken)
|
||||
=> Task.FromResult(objects);
|
||||
}
|
||||
|
||||
private sealed class FakeWriter : IGalaxyDataWriter
|
||||
{
|
||||
public List<(string FullRef, SecurityClassification Resolved)> Calls { get; } = [];
|
||||
|
||||
public Task<IReadOnlyList<WriteResult>> WriteAsync(
|
||||
IReadOnlyList<WriteRequest> writes, Func<string, SecurityClassification> securityResolver,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
foreach (var w in writes) Calls.Add((w.FullReference, securityResolver(w.FullReference)));
|
||||
return Task.FromResult<IReadOnlyList<WriteResult>>([.. writes.Select(_ => new WriteResult(StatusCodeMap.Good))]);
|
||||
}
|
||||
|
||||
public void InvalidateHandleCaches() { }
|
||||
}
|
||||
|
||||
private static async Task<SecurityClassification> ResolvedOnWriteAsync(GalaxyDriver driver, FakeWriter writer, string rawPath)
|
||||
{
|
||||
writer.Calls.Clear();
|
||||
await driver.WriteAsync([new WriteRequest(rawPath, 1.0)], TestContext.Current.CancellationToken);
|
||||
return writer.Calls.ShouldHaveSingleItem().Resolved;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The production shape: tags authored, the driver initialized, <c>DiscoverAsync</c> never called. The writer
|
||||
/// must receive the attribute's real classification (positive control: a FreeAccess sibling stays FreeAccess).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task An_authored_secured_tag_resolves_its_classification_without_DiscoverAsync()
|
||||
{
|
||||
var hierarchy = new FakeHierarchySource([
|
||||
Obj("Tank1", ("SP", 2 /*SecuredWrite*/), ("Mode", 3 /*VerifiedWrite*/), ("Note", 0 /*FreeAccess*/)),
|
||||
]);
|
||||
var writer = new FakeWriter();
|
||||
var driver = new GalaxyDriver("g",
|
||||
Opts(("Plant/Tank1/SP", "Tank1.SP"), ("Plant/Tank1/Mode", "Tank1.Mode"), ("Plant/Tank1/Note", "Tank1.Note")),
|
||||
hierarchySource: hierarchy, dataWriter: writer);
|
||||
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
await TestWait.UntilAsync(
|
||||
() => ResolvedOnWriteAsync(driver, writer, "Plant/Tank1/SP").GetAwaiter().GetResult() == SecurityClassification.SecuredWrite,
|
||||
"a SecuredWrite attribute must route to WriteSecured without anyone calling DiscoverAsync");
|
||||
(await ResolvedOnWriteAsync(driver, writer, "Plant/Tank1/Mode")).ShouldBe(SecurityClassification.VerifiedWrite);
|
||||
(await ResolvedOnWriteAsync(driver, writer, "Plant/Tank1/Note")).ShouldBe(SecurityClassification.FreeAccess);
|
||||
writer.Calls.Single().FullRef.ShouldBe("Tank1.Note", "the writer dials the attributeRef");
|
||||
}
|
||||
|
||||
/// <summary>The dedicated seam is preferred, and only the authored objects are asked for.</summary>
|
||||
[Fact]
|
||||
public async Task The_security_seed_queries_only_the_authored_objects()
|
||||
{
|
||||
var source = new RecordingSecuritySource([Obj("Pump7", ("Speed", 4 /*Tune*/))]);
|
||||
var writer = new FakeWriter();
|
||||
var driver = new GalaxyDriver("g",
|
||||
Opts(("Plant/Pump7/Speed", "Pump7.Speed"), ("Plant/Pump7/Run", "Pump7.Run"), ("Plant/Valve2/Pos", "Valve2.Pos")),
|
||||
hierarchySource: null, dataWriter: writer, securitySource: source);
|
||||
|
||||
await driver.InitializeAsync("{}", TestContext.Current.CancellationToken);
|
||||
|
||||
await TestWait.UntilAsync(
|
||||
() => ResolvedOnWriteAsync(driver, writer, "Plant/Pump7/Speed").GetAwaiter().GetResult() == SecurityClassification.Tune,
|
||||
"the seeded classification must be used");
|
||||
source.Requested.ShouldHaveSingleItem().OrderBy(n => n).ShouldBe(["Pump7", "Valve2"]);
|
||||
(await ResolvedOnWriteAsync(driver, writer, "Plant/Valve2/Pos")).ShouldBe(SecurityClassification.FreeAccess,
|
||||
"an object the repository did not return keeps the FreeAccess default");
|
||||
}
|
||||
|
||||
private sealed class RecordingSecuritySource(IReadOnlyList<GalaxyObject> objects) : IGalaxyAttributeSecuritySource
|
||||
{
|
||||
public List<IReadOnlyCollection<string>> Requested { get; } = [];
|
||||
|
||||
public Task<IReadOnlyList<GalaxyObject>> GetObjectsAsync(
|
||||
IReadOnlyCollection<string> tagNames, CancellationToken cancellationToken)
|
||||
{
|
||||
lock (Requested) Requested.Add([.. tagNames]);
|
||||
return Task.FromResult(objects);
|
||||
}
|
||||
}
|
||||
}
|
||||
+14
@@ -37,6 +37,20 @@ public sealed class GatewayGalaxyDataWriterFailClosedTests
|
||||
ops.RawWriteHandles.ShouldBeEmpty();
|
||||
}
|
||||
|
||||
/// <summary>#991 G-1: WriteSecured carries the configured WriteUserId as the current user, not a hard-coded 0.</summary>
|
||||
[Fact]
|
||||
public async Task WriteOne_SecuredClassification_CarriesTheConfiguredWriteUserId()
|
||||
{
|
||||
var ops = new FakeMxWriteOps();
|
||||
var writer = new GatewayGalaxyDataWriter(
|
||||
new GalaxyMxSession(new Config.GalaxyMxAccessOptions(ClientName: "OtOpcUa-Test")), writeUserId: 42);
|
||||
|
||||
await writer.WriteOneForTestAsync(
|
||||
ops, new WriteRequest("Tag.Sec", true), SecurityClassification.SecuredWrite, CancellationToken.None);
|
||||
|
||||
ops.Invokes.Single(r => r.Command.Kind == MxCommandKind.WriteSecured).Command.WriteSecured.CurrentUserId.ShouldBe(42);
|
||||
}
|
||||
|
||||
// ---------------- T6: fail-closed on advise failure ----------------
|
||||
|
||||
/// <summary>When AdviseSupervisory fails (non-OK protocol status), the raw Write must NOT be issued and
|
||||
|
||||
Reference in New Issue
Block a user