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); } } }