Files
lmxopcua/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverSecurityResolutionTests.cs
T

131 lines
6.4 KiB
C#

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