using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
///
/// lmxopcua#1053 (review 02 U-8): a WARM cached ACL decision on a UNS node used to allocate ahead of the decision
/// cache on every call — the live id-chain list, an identifier split, LINQ enumerators, the resolved segment array
/// and a string.Join cache key — about 8–12 short-lived objects per node per decision (≈10k per 1,000-node
/// UNS Read). The resolver still runs per call (it reads live topology); its products are now cached on the folder
/// instance / generation, so a warm hit allocates nothing.
///
public sealed class NodeManagerUnsDecisionAllocationTests : IDisposable
{
private const string Cluster = "SITE-A";
private const string Principal = "scadabridge";
private const string KeyId = "k-1053";
private const string AreaId = "UA-0000000001";
private const string LineId = "UL-0000000001";
private const string Pump = "EQ-00000000a1b2";
private const string Fan = "EQ-00000000c3d4";
private const string VirtualTag = Pump + "/Temp";
private const string Reference = "Area1/Line1/Pump/Speed";
private const string RawTag = "Plant/Modbus/dev1/Speed";
private const string Alarm = "scripted-pump-hi";
private const int Calls = 2_000;
private static readonly DateTime Start = new(2026, 12, 3, 12, 0, 0, DateTimeKind.Utc);
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-1053-{Guid.NewGuid():N}");
///
/// Each UNS shape the resolver places — the equipment folder itself, a node it owns (a virtual tag), and a UNS
/// reference variable — answers a warm cached Read with zero bytes allocated on the calling thread. Positive
/// control: every verdict is an ALLOW from a narrow Equipment grant (so the placement did run), and the sibling
/// equipment the grant does not cover is a DENY.
///
[Fact]
public async Task A_warm_cached_decision_on_a_uns_node_allocates_nothing()
{
var (host, server) = await BootAsync();
try
{
var nm = server.NodeManager!;
Topology(nm);
var authorizer = Wire(nm);
var ns = nm.NamespaceIndexForRealm(AddressSpaceRealm.Uns);
var identity = new RoleCarryingUserIdentity(
new UserNameIdentityToken { UserName = "apikey" }, [], Principal, KeyId);
nm.ResolveUnsAclSubject(Pump).Kind.ShouldBe(UnsAclSubjectKind.Folder);
nm.ResolveUnsAclSubject(VirtualTag).Kind.ShouldBe(UnsAclSubjectKind.Folder);
nm.ResolveUnsAclSubject(Reference).Kind.ShouldBe(UnsAclSubjectKind.ReferenceVariable);
nm.ResolveUnsAclSubject(Alarm).Kind.ShouldBe(UnsAclSubjectKind.ScriptedCondition);
authorizer.IsAllowedCached(identity, OpcUaOperation.Read, new NodeId(Fan, ns), AddressSpaceRealm.Uns)
.ShouldBeFalse("a sibling equipment the grant does not cover is denied (negative control)");
var measured = new List<(string Id, double PerCall)>();
foreach (var id in new[] { Pump, VirtualTag, Reference, Alarm })
{
var nodeId = new NodeId(id, ns);
authorizer.IsAllowedCached(identity, OpcUaOperation.Read, nodeId, AddressSpaceRealm.Uns)
.ShouldBeTrue($"{id} is covered by the Equipment grant");
var before = GC.GetAllocatedBytesForCurrentThread();
var allowed = 0;
for (var i = 0; i < Calls; i++)
if (authorizer.IsAllowedCached(identity, OpcUaOperation.Read, nodeId, AddressSpaceRealm.Uns)) allowed++;
var perCall = (GC.GetAllocatedBytesForCurrentThread() - before) / (double)Calls;
allowed.ShouldBe(Calls);
TestContext.Current.TestOutputHelper?.WriteLine($"{id}: {perCall:F3} bytes per warm decision");
measured.Add((id, perCall));
}
measured.ShouldAllBe(m => m.PerCall < 1d,
"a warm cached decision must not allocate: " + string.Join(", ", measured.Select(m => $"{m.Id}={m.PerCall:F3} B/call")));
}
finally { await host.DisposeAsync(); }
}
///
/// The cached chain is never trusted blindly: moving the equipment to another line (a rebuild that re-mints the
/// folder under a new parent) is re-checked against the LIVE ancestry on the next decision, and is denied until
/// the generation agrees — exactly as before the cache.
///
[Fact]
public async Task A_cached_chain_follows_a_live_reparent()
{
var (host, server) = await BootAsync();
try
{
var nm = server.NodeManager!;
Topology(nm);
var authorizer = Wire(nm);
var ns = nm.NamespaceIndexForRealm(AddressSpaceRealm.Uns);
var identity = new RoleCarryingUserIdentity(
new UserNameIdentityToken { UserName = "apikey" }, [], Principal, KeyId);
var pump = new NodeId(Pump, ns);
var vtag = new NodeId(VirtualTag, ns);
authorizer.IsAllowedCached(identity, OpcUaOperation.Read, pump, AddressSpaceRealm.Uns).ShouldBeTrue();
authorizer.IsAllowedCached(identity, OpcUaOperation.Read, vtag, AddressSpaceRealm.Uns).ShouldBeTrue();
// Re-parent Pump under a second line the generation does not know about: the live chain changes.
nm.RebuildAddressSpace();
nm.EnsureFolder(AreaId, parentNodeId: null, displayName: "Area1", realm: AddressSpaceRealm.Uns);
nm.EnsureFolder(LineId, parentNodeId: AreaId, displayName: "Line1", realm: AddressSpaceRealm.Uns);
nm.EnsureFolder("UL-0000000002", parentNodeId: AreaId, displayName: "Line2", realm: AddressSpaceRealm.Uns);
nm.EnsureFolder(Pump, parentNodeId: "UL-0000000002", displayName: "Pump", realm: AddressSpaceRealm.Uns);
nm.EnsureVariable(VirtualTag, Pump, "Temp", "Double", writable: false, AddressSpaceRealm.Uns);
nm.CompleteAddressSpaceApply();
((IReadOnlyList)nm.ResolveUnsAclSubject(Pump).FolderChain!).ShouldBe([AreaId, "UL-0000000002", Pump]);
authorizer.IsAllowedCached(identity, OpcUaOperation.Read, pump, AddressSpaceRealm.Uns)
.ShouldBeFalse("the live chain no longer matches the generation's placement");
authorizer.IsAllowedCached(identity, OpcUaOperation.Read, vtag, AddressSpaceRealm.Uns).ShouldBeFalse();
}
finally { await host.DisposeAsync(); }
}
private static void Topology(OtOpcUaNodeManager nm)
{
nm.EnsureFolder(AreaId, parentNodeId: null, displayName: "Area1", realm: AddressSpaceRealm.Uns);
nm.EnsureFolder(LineId, parentNodeId: AreaId, displayName: "Line1", realm: AddressSpaceRealm.Uns);
nm.EnsureFolder(Pump, parentNodeId: LineId, displayName: "Pump", realm: AddressSpaceRealm.Uns);
nm.EnsureFolder(Fan, parentNodeId: LineId, displayName: "Fan", realm: AddressSpaceRealm.Uns);
nm.EnsureVariable(VirtualTag, Pump, "Temp", "Double", writable: false, AddressSpaceRealm.Uns);
nm.EnsureFolder("Plant/Modbus/dev1", parentNodeId: null, displayName: "dev1", realm: AddressSpaceRealm.Raw);
nm.EnsureVariable(RawTag, "Plant/Modbus/dev1", "Speed", "Double", writable: false, AddressSpaceRealm.Raw);
nm.EnsureVariable(Reference, Pump, "Speed", "Double", writable: false, AddressSpaceRealm.Uns);
nm.AddReference(Reference, AddressSpaceRealm.Uns, RawTag, AddressSpaceRealm.Raw, "Organizes");
nm.MaterialiseAlarmCondition(Alarm, Pump, "hi", "AlarmCondition", 500, AddressSpaceRealm.Uns);
}
private static AclScopePathResolver Resolver() => new(
new Dictionary(),
new Dictionary(),
new Dictionary(),
new Dictionary(),
new Dictionary(),
new Dictionary { [AreaId] = "Area1" },
new Dictionary { [LineId] = (AreaId, "Line1") },
new Dictionary { [Pump] = (LineId, "Pump"), [Fan] = (LineId, "Fan") },
[]);
private static DataPlaneAuthorizer Wire(OtOpcUaNodeManager nm)
{
var resolver = Resolver();
NodeAclPath One(NodeAclScopeKind kind, string id) => resolver.ResolveOne(kind, id).ShouldHaveSingleItem();
var folders = new Dictionary
{
[AreaId] = new(One(NodeAclScopeKind.UnsArea, AreaId), [AreaId]),
[LineId] = new(One(NodeAclScopeKind.UnsLine, LineId), [AreaId, LineId]),
[Pump] = new(One(NodeAclScopeKind.Equipment, Pump), [AreaId, LineId, Pump]),
[Fan] = new(One(NodeAclScopeKind.Equipment, Fan), [AreaId, LineId, Fan]),
};
var owners = new Dictionary
{
[Pump] = One(NodeAclScopeKind.Equipment, Pump),
[Fan] = One(NodeAclScopeKind.Equipment, Fan),
};
NodeAcl[] grants =
[
new()
{
NodeAclId = "acl-pump", ClusterId = Cluster, Principal = Principal,
ScopeKind = NodeAclScopeKind.Equipment, ScopeId = Pump, PermissionFlags = NodePermissions.ReadOnly,
},
];
ApiKey[] keys =
[
new()
{
ApiKeyId = KeyId, Name = KeyId, SecretHash = "hash", Principal = Principal, Enabled = true,
CreatedUtc = Start.AddDays(-1),
},
];
var state = new DataPlaneAuthorityState();
state.Apply(Cluster, "rev-1", keys, grants, resolver.Resolve(grants), owners,
new Dictionary { [Alarm] = Pump }, folders);
var authorizer = new DataPlaneAuthorizer(
state, new TriePermissionEvaluator(state.Tries), enabled: true, NullLogger.Instance, new FixedClock(Start));
nm.DataPlaneAuthority = state;
nm.Authorizer = authorizer;
return authorizer;
}
private sealed class FixedClock(DateTime utcNow) : TimeProvider
{
public override DateTimeOffset GetUtcNow() => new(utcNow, TimeSpan.Zero);
}
private async Task<(OpcUaApplicationHost Host, OtOpcUaSdkServer Server)> BootAsync()
{
var started = await OpcUaHostStart.StartAsync(
port => new OpcUaApplicationHost(
new OpcUaApplicationHostOptions
{
ApplicationName = "OtOpcUa.UnsDecisionAllocationTest",
ApplicationUri = $"urn:OtOpcUa.UnsDecisionAllocationTest:{Guid.NewGuid():N}",
OpcUaPort = port,
PublicHostname = "localhost",
PkiStoreRoot = _pkiRoot,
},
NullLogger.Instance),
() => new OtOpcUaSdkServer(), Ct);
return (started.Host, started.Server);
}
///
public void Dispose()
{
if (Directory.Exists(_pkiRoot))
{
try { Directory.Delete(_pkiRoot, recursive: true); }
catch (IOException) { /* best effort */ }
}
}
}