diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Browse/IGalaxyAttributeSecuritySource.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Browse/IGalaxyAttributeSecuritySource.cs new file mode 100644 index 000000000..ebd7331eb --- /dev/null +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Browse/IGalaxyAttributeSecuritySource.cs @@ -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; + +/// +/// Driver-side seam for the per-attribute security_classification of the AUTHORED Galaxy objects +/// (#991 G-1). WriteAsync routes SecuredWrite / VerifiedWrite attributes to WriteSecured; that +/// classification used to come only from DiscoverAsync, 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 InitializeAsync and +/// on every deploy-watcher rediscovery. +/// +public interface IGalaxyAttributeSecuritySource +{ + /// The named objects with their attributes. A name the Galaxy does not hold is simply absent. + /// Object tag_names (the part of an attributeRef before its first dot). + /// Cancellation token for the query. + /// The objects found, each with its attributes. + Task> GetObjectsAsync(IReadOnlyCollection tagNames, CancellationToken cancellationToken); +} + +/// +/// Default : one DiscoverHierarchy per authored object, rooted +/// at its tag_name with max_depth = 0 and attributes included — the cost scales with the authored +/// objects, not the Galaxy (the full-hierarchy dump the /raw picker pulls would be fetched on every driver +/// init). A bounded number run concurrently; an object the gateway reports NotFound is skipped. +/// +public sealed class GatewayGalaxyAttributeSecuritySource : IGalaxyAttributeSecuritySource +{ + /// Concurrent per-object queries. + public const int MaxConcurrency = 4; + + private readonly GalaxyRepositoryClient _client; + + /// Initializes a new instance of the class. + /// The gateway's Galaxy repository client. + public GatewayGalaxyAttributeSecuritySource(GalaxyRepositoryClient client) + => _client = client ?? throw new ArgumentNullException(nameof(client)); + + /// + public Task> GetObjectsAsync( + IReadOnlyCollection tagNames, CancellationToken cancellationToken) + => QueryAsync(_client.DiscoverHierarchyRawAsync, tagNames, MaxConcurrency, cancellationToken); + + /// The per-object queries behind a delegate, so they are unit-testable without a channel. + /// The raw DiscoverHierarchy RPC. + /// The objects to fetch. + /// Concurrent queries. + /// Cancellation token. + /// The objects found (only the requested root of each reply). + internal static async Task> QueryAsync( + Func> discover, + IReadOnlyCollection tagNames, + int maxConcurrency, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(discover); + var found = new ConcurrentBag(); + 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; + } +} + +/// +/// over an injected — the +/// seam-mode fallback, so a driver built around a hierarchy source seeds the same way production does. +/// +internal sealed class HierarchyAttributeSecuritySource(IGalaxyHierarchySource hierarchy) : IGalaxyAttributeSecuritySource +{ + /// + public async Task> GetObjectsAsync( + IReadOnlyCollection tagNames, CancellationToken cancellationToken) + { + var wanted = new HashSet(tagNames, StringComparer.OrdinalIgnoreCase); + var all = await hierarchy.GetHierarchyAsync(cancellationToken).ConfigureAwait(false); + return [.. all.Where(o => wanted.Contains(o.TagName))]; + } +} diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs index 35faeb8a7..aff2f9a6f 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs @@ -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 and . /// /// Optional cached key → Galaxy-identity set (lmxopcua#765). + /// + /// Optional security-classification seam (#991 G-1). Without it, seam mode falls back to + /// ; production builds a . + /// 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 /// 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); } } + /// The security-classification source for the current runtime (#991 G-1), or null. + private IGalaxyAttributeSecuritySource? ResolveSecuritySource() => + _securitySource + ?? _ownedSecuritySource + ?? (!_ownsRuntime && _hierarchySource is { } hierarchy ? new HierarchyAttributeSecuritySource(hierarchy) : null); + /// /// 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 /// 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 } } + /// + /// #991 G-1 — one security seed pass: fetch the authored objects' attributes and record each authored tag's + /// under its RawPath, the key resolves against. + /// Before this the map was filled only by , 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). + /// + 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(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); + } + } + /// Deploy-watcher rediscovery: a redeploy may add or remove platforms / engines. private void ReseedProbePlatformsOnRediscovery() => RequestProbeSeed("rediscovery"); @@ -1157,6 +1270,7 @@ public sealed class GalaxyDriver _hierarchySource = null; _alarmAcknowledger = null; _ownedPlatformSource = null; + _ownedSecuritySource = null; _ownsRuntime = false; } } diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyDataWriter.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyDataWriter.cs index cb84e1f30..854db7a35 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyDataWriter.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GatewayGalaxyDataWriter.cs @@ -361,8 +361,12 @@ public sealed class GatewayGalaxyDataWriter : IGalaxyDataWriter /// directly and route through InvokeAsync. Verifier user is left at zero /// for SecuredWrite; VerifiedWrite uses the same path because the gw's worker /// interprets the underlying MXAccess command kind. + /// #991 G-1: the current user is the configured MxAccess.WriteUserId — 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). /// - private static Task InvokeWriteSecuredAsync( + private Task 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, }, }; diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Browse/GatewayGalaxyAttributeSecuritySourceTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Browse/GatewayGalaxyAttributeSecuritySourceTests.cs new file mode 100644 index 000000000..ab7a45628 --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Browse/GatewayGalaxyAttributeSecuritySourceTests.cs @@ -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; + +/// +/// #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. +/// +public sealed class GatewayGalaxyAttributeSecuritySourceTests +{ + private static GalaxyObject Obj(string tag) => new() { TagName = tag, ContainedName = tag }; + + /// One rooted, depth-0, attribute-bearing request per object; replies reduced to the requested root. + [Fact] + public async Task Each_object_is_fetched_rooted_at_depth_zero_with_attributes() + { + var requests = new ConcurrentBag(); + Task 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); + } + + /// An object the gateway reports NotFound (undeployed) is skipped; the others still load. + [Fact] + public async Task A_not_found_object_is_skipped() + { + Task 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"); + } + + /// Any other failure (gateway down) propagates — the driver keeps the previous map and logs. + [Fact] + public async Task Any_other_failure_propagates() + { + static Task Discover(DiscoverHierarchyRequest r, CancellationToken _) + => throw new MxGatewayException("unavailable", new RpcException(new Status(StatusCode.Unavailable, "down"))); + + await Should.ThrowAsync(() => GatewayGalaxyAttributeSecuritySource.QueryAsync( + Discover, ["Tank1"], maxConcurrency: 1, TestContext.Current.CancellationToken)); + } +} diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverSecurityResolutionTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverSecurityResolutionTests.cs new file mode 100644 index 000000000..861243a4a --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverSecurityResolutionTests.cs @@ -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; + +/// +/// #991 G-1 — WriteAsync picks WriteSecured vs the supervisory raw Write from a per-tag +/// security map that ONLY DiscoverAsync filled — and the runtime never calls DiscoverAsync on the +/// served driver (only the /raw picker's throwaway instance does). Every authored tag resolved +/// FreeAccess, so a SecuredWrite/VerifiedWrite attribute always went down the raw path and was refused +/// (MXAccess 1012/1013 → BadUserAccessDenied, 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. +/// +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 objects) : IGalaxyHierarchySource + { + public Task> GetHierarchyAsync(CancellationToken cancellationToken) + => Task.FromResult(objects); + } + + private sealed class FakeWriter : IGalaxyDataWriter + { + public List<(string FullRef, SecurityClassification Resolved)> Calls { get; } = []; + + public Task> WriteAsync( + IReadOnlyList writes, Func securityResolver, + CancellationToken cancellationToken) + { + foreach (var w in writes) Calls.Add((w.FullReference, securityResolver(w.FullReference))); + return Task.FromResult>([.. writes.Select(_ => new WriteResult(StatusCodeMap.Good))]); + } + + public void InvalidateHandleCaches() { } + } + + private static async Task 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; + } + + /// + /// The production shape: tags authored, the driver initialized, DiscoverAsync never called. The writer + /// must receive the attribute's real classification (positive control: a FreeAccess sibling stays FreeAccess). + /// + [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"); + } + + /// The dedicated seam is preferred, and only the authored objects are asked for. + [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 objects) : IGalaxyAttributeSecuritySource + { + public List> Requested { get; } = []; + + public Task> GetObjectsAsync( + IReadOnlyCollection tagNames, CancellationToken cancellationToken) + { + lock (Requested) Requested.Add([.. tagNames]); + return Task.FromResult(objects); + } + } +} diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GatewayGalaxyDataWriterFailClosedTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GatewayGalaxyDataWriterFailClosedTests.cs index ce0328aac..964de2d20 100644 --- a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GatewayGalaxyDataWriterFailClosedTests.cs +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GatewayGalaxyDataWriterFailClosedTests.cs @@ -37,6 +37,20 @@ public sealed class GatewayGalaxyDataWriterFailClosedTests ops.RawWriteHandles.ShouldBeEmpty(); } + /// #991 G-1: WriteSecured carries the configured WriteUserId as the current user, not a hard-coded 0. + [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 ---------------- /// When AdviseSupervisory fails (non-OK protocol status), the raw Write must NOT be issued and