using Opc.Ua; using Opc.Ua.Client; using Opc.Ua.Server; using Shouldly; using Xunit; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Configuration.Enums; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Core.Authorization; using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.ServerEventRig; using static ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests.WarmRedundancyWireTests; namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests; [Trait("Category", "Integration"), Trait("Feature", "GrpcData"), Trait("Phase", "P08")] public sealed class GrpcDataSdkBrowseWireTests { [Theory(Timeout = 90000), Trait("Phase", "P10Wire")] [InlineData(AddressSpaceRealm.Raw, DataRealm.Raw, "raw")] [InlineData(AddressSpaceRealm.Uns, DataRealm.Uns, "uns")] public async Task Parent_browse_and_translate_enforce_each_anchor_grant_with_legacy_acl_disabled( AddressSpaceRealm realm, DataRealm dataRealm, string aclRealm) { var ct = Deadline(); await using var rig = await StartModeAsync("ProjectedAnchorAcl", "None", ct); rig.Nm.EnsureFolder("Plant", null, "Plant", realm); var parent = rig.Nm.TryGetFolder("Plant", realm)!.NodeId; rig.Nm.EnsureFolder("Ordinary", "Plant", "Ordinary", realm); var ordinary = rig.Nm.TryGetFolder("Ordinary", realm)!.NodeId; var scopePaths = new Dictionary> { [new(NodeAclScopeKind.RawFolder, "allowed")] = [new([aclRealm, "Plant", "Allowed"])], }; var grant = new NodeAcl { NodeAclId = "allowed", ClusterId = ServerEventRig.Cluster, Principal = OpcUaPrincipals.Anonymous, ScopeKind = NodeAclScopeKind.RawFolder, ScopeId = "allowed", PermissionFlags = NodePermissions.Browse }; rig.Enforce(false, [Key()], scopePaths, grant); var address = new DataAddress("origin", "urn:source", "string", "root"); var allowedDef = new ProjectedAnchorDefinition(dataRealm, ProjectedDataIds.Identifier("allowed", address), parent, "Allowed", "Plant/Allowed", "allowed", 1, () => true) { LocalScope = new NodeScope { ClusterId = ServerEventRig.Cluster, Kind = realm == AddressSpaceRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns, Segments = ["Plant", "Allowed"] } }; var deniedDef = new ProjectedAnchorDefinition(dataRealm, ProjectedDataIds.Identifier("denied", address), parent, "Denied", "Plant/Denied", "denied", 1, () => true) { LocalScope = new NodeScope { ClusterId = ServerEventRig.Cluster, Kind = realm == AddressSpaceRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns, Segments = ["Plant", "Denied"] } }; rig.Nm.TryEnsureProjectedAnchor(allowedDef, out var allowed).ShouldBeTrue(); rig.Nm.TryEnsureProjectedAnchor(deniedDef, out var denied).ShouldBeTrue(); using var session = await rig.ConnectAsync(anonymous: true, ct); var client = (SessionClient)session; var browse = await client.BrowseAsync(H(), null, 100, [new BrowseDescription { NodeId = parent, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All, }], ct); StatusCode.IsGood(browse.Results[0].StatusCode).ShouldBeTrue(); var targets = browse.Results[0].References.ToArray()!.Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray(); targets.ShouldContain(allowed!.Value); targets.ShouldNotContain(denied!.Value); targets.ShouldContain(ordinary, "legacy local ACL off still permits ordinary local browse"); var translated = await client.TranslateBrowsePathsToNodeIdsAsync(H(), new[] { Path(allowed.Value), Path(denied.Value) }, ct); translated.Results[0].StatusCode.ShouldBe(StatusCodes.Good); translated.Results[0].Targets.ToArray()!.ShouldContain(t => ExpandedNodeId.ToNodeId(t.TargetId, session.NamespaceUris) == allowed.Value); StatusCode.IsBad(translated.Results[1].StatusCode).ShouldBeTrue(); translated.Results[1].Targets.Count.ShouldBe(0); rig.Nm.Authorizer = null; var withoutAuthority = await client.BrowseAsync(H(), null, 100, [new BrowseDescription { NodeId = parent, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All, }], ct); var withoutAuthorityTargets = withoutAuthority.Results[0].References.ToArray()! .Select(r => ExpandedNodeId.ToNodeId(r.NodeId, session.NamespaceUris)).ToArray(); withoutAuthorityTargets.ShouldNotContain(allowed.Value, "an anchor requires an installed local authority"); withoutAuthorityTargets.ShouldContain(ordinary); return; BrowsePath Path(NodeId target) => new() { StartingNode = parent, RelativePath = new RelativePath { Elements = [new RelativePathElement { ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences, IncludeSubtypes = true, TargetName = new QualifiedName(target.IdentifierAsString, target.NamespaceIndex) }] } }; } [Fact(Timeout = 90000)] public async Task BrowseNext_is_session_bound_and_rechecks_page_authority_before_each_child() { var ct = Deadline(); await using var rig = await StartModeAsync("ProjectedBrowseCursor", "None", ct); AllowAnonymousAnchor(rig); rig.Server.SetProjectedBrowseLimits(maxCursors: 1, maxBytes: 8 * 1024 * 1024); rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; var root = new DataAddress("origin", "urn:raw", "string", "root"); var anchorDefinition = WithRawAnchorScope(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", root), parent, "Remote", "Plant/Remote", "mapping", 1, () => true)); rig.Nm.TryEnsureProjectedAnchor(anchorDefinition, out var anchor).ShouldBeTrue(); var children = new List(); foreach (var name in new[] { "First", "Second", "Third" }) { var origin = root with { Identifier = name }; var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Remote/" + name); var metadata = new DataMetadata(view, name, "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Browse | DataOperations.Read, 1, null, null, false); rig.Nm.TryEnsureProjectedVariable(new(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", origin), anchor!.Value, metadata, 1, () => true), out var child).ShouldBeTrue(); children.Add(child!.Value); } var pages = new BrowsePages(children); rig.Nm.ProjectedBrowseAccess = pages; var access = new BrowseOnlyAccess(); rig.Nm.ProjectedDataAccess = access; using var first = await rig.ConnectAsync(anonymous: true, ct); using var second = await rig.ConnectAsync(anonymous: true, ct); var firstClient = (SessionClient)first; var secondClient = (SessionClient)second; var result = await firstClient.BrowseAsync(H(), null, 1, [new BrowseDescription { NodeId = anchor!.Value, BrowseDirection = BrowseDirection.Forward, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All, }], ct); StatusCode.IsGood(result.Results[0].StatusCode).ShouldBeTrue(); result.Results[0].References.Count.ShouldBe(1); var cursor = result.Results[0].ContinuationPoint; cursor.IsEmpty.ShouldBeFalse(); var stolen = await secondClient.BrowseNextAsync(H(), false, [cursor], ct); stolen.Results[0].StatusCode.ShouldBe(StatusCodes.BadContinuationPointInvalid); var next = await firstClient.BrowseNextAsync(H(), false, [cursor], ct); StatusCode.IsGood(next.Results[0].StatusCode).ShouldBeTrue(); next.Results[0].References.Count.ShouldBe(1); var replacement = next.Results[0].ContinuationPoint; replacement.IsEmpty.ShouldBeFalse("the claimed cursor must reuse its reservation at the configured count limit"); var replay = await firstClient.BrowseNextAsync(H(), false, [cursor], ct); replay.Results[0].StatusCode.ShouldBe(StatusCodes.BadContinuationPointInvalid); replay.Results[0].References.Count.ShouldBe(0); access.OnAcquire = () => pages.Valid = false; var resumed = await firstClient.BrowseNextAsync(H(), false, [replacement], ct); StatusCode.IsBad(resumed.Results[0].StatusCode).ShouldBeTrue(); resumed.Results[0].References.Count.ShouldBe(0); } [Fact(Timeout = 90000)] public async Task Mapped_browse_honors_direction_class_mask_and_result_mask() { var ct = Deadline(); await using var rig = await StartModeAsync("ProjectedBrowseFilters", "None", ct); AllowAnonymousAnchor(rig); rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; var origin = new DataAddress("origin", "urn:raw", "string", "root"); var definition = WithRawAnchorScope(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", origin), parent, "Remote", "Plant/Remote", "mapping", 1, () => true)); rig.Nm.TryEnsureProjectedAnchor(definition, out var anchor).ShouldBeTrue(); var childOrigin = origin with { Identifier = "child" }; var childView = new DataView(childOrigin, DataRealm.Raw, "mapping", 1, "Plant/Remote/Child"); var metadata = new DataMetadata(childView, "Child", "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Browse, 1, null, null, false); rig.Nm.TryEnsureProjectedVariable(new(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", childOrigin), anchor!.Value, metadata, 1, () => true), out var child).ShouldBeTrue(); rig.Nm.ProjectedBrowseAccess = new BrowsePages([child!.Value]); rig.Nm.ProjectedDataAccess = new BrowseOnlyAccess(); using var session = await rig.ConnectAsync(anonymous: true, ct); var client = (SessionClient)session; async Task Browse(BrowseDirection direction, NodeId referenceType, uint classMask, uint resultMask) { var reply = await client.BrowseAsync(H(), null, 10, [new BrowseDescription { NodeId = anchor.Value, BrowseDirection = direction, ReferenceTypeId = referenceType, IncludeSubtypes = true, NodeClassMask = classMask, ResultMask = resultMask }], ct); return reply.Results[0]; } var objects = await Browse(BrowseDirection.Forward, ReferenceTypeIds.HierarchicalReferences, (uint)NodeClass.Object, (uint)BrowseResultMask.All); StatusCode.IsGood(objects.StatusCode).ShouldBeTrue(); objects.References.Count.ShouldBe(0); var variables = await Browse(BrowseDirection.Forward, ReferenceTypeIds.HierarchicalReferences, (uint)NodeClass.Variable, 0); StatusCode.IsGood(variables.StatusCode).ShouldBeTrue(); variables.References.Count.ShouldBe(1); variables.References[0].BrowseName.IsNull.ShouldBeTrue(); variables.References[0].NodeClass.ShouldBe(NodeClass.Unspecified); var inverse = await Browse(BrowseDirection.Inverse, ReferenceTypeIds.Organizes, 0, (uint)BrowseResultMask.All); StatusCode.IsGood(inverse.StatusCode).ShouldBeTrue(); inverse.References.ToArray()!.ShouldContain(reference => reference.NodeId == new ExpandedNodeId(parent) && !reference.IsForward); var noMatch = await Browse(BrowseDirection.Forward, ReferenceTypeIds.HasTypeDefinition, 0, (uint)BrowseResultMask.All); StatusCode.IsGood(noMatch.StatusCode).ShouldBeTrue(); noMatch.References.Count.ShouldBe(0); } [Fact(Timeout = 90000)] public async Task Cursor_expiring_during_a_remote_fetch_cannot_publish_or_be_replaced() { var ct = Deadline(); await using var rig = await StartModeAsync("ProjectedCursorExpiry", "None", ct); AllowAnonymousAnchor(rig); rig.Nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); var parent = rig.Nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; var root = new DataAddress("origin", "urn:raw", "string", "root"); var anchorDefinition = WithRawAnchorScope(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", root), parent, "Remote", "Plant/Remote", "mapping", 1, () => true)); rig.Nm.TryEnsureProjectedAnchor(anchorDefinition, out var anchor).ShouldBeTrue(); var children = new List(); foreach (var name in new[] { "First", "Second" }) { var origin = root with { Identifier = name }; var view = new DataView(origin, DataRealm.Raw, "mapping", 1, "Plant/Remote/" + name); var metadata = new DataMetadata(view, name, "Tag", DataValueKind.Int32, -1, [], false, DataOperations.Browse, 1, null, null, false); rig.Nm.TryEnsureProjectedVariable(new(DataRealm.Raw, ProjectedDataIds.Identifier("mapping", origin), anchor!.Value, metadata, 1, () => true), out var child).ShouldBeTrue(); children.Add(child!.Value); } var clock = new TestMonotonicClock(); var pages = new BlockingPages(children); rig.Nm.ProjectedBrowseClock = clock; rig.Nm.ProjectedBrowseAccess = pages; rig.Nm.ProjectedDataAccess = new BrowseOnlyAccess(); using var session = await rig.ConnectAsync(anonymous: true, ct); var client = (SessionClient)session; var first = await client.BrowseAsync(H(), null, 1, [new BrowseDescription { NodeId = anchor!.Value, BrowseDirection = BrowseDirection.Forward, IncludeSubtypes = true, ResultMask = (uint)BrowseResultMask.All }], ct); var token = first.Results[0].ContinuationPoint; token.IsEmpty.ShouldBeFalse(); var next = client.BrowseNextAsync(H(), false, [token], ct).AsTask(); try { await pages.FetchEntered.Task.WaitAsync(TimeSpan.FromSeconds(5), ct); // The simulated remote page remains outstanding while another // thread acquires the real SDK lock. A network wait cannot hold it. var lockAvailable = await Task.Run(() => { if (!Monitor.TryEnter(rig.Nm.Lock, TimeSpan.FromSeconds(1))) return false; try { return true; } finally { Monitor.Exit(rig.Nm.Lock); } }, ct); lockAvailable.ShouldBeTrue(); clock.Advance(TimeSpan.FromSeconds(61)); } finally { pages.Release.TrySetResult(); } var result = await next.WaitAsync(TimeSpan.FromSeconds(10), ct); StatusCode.IsBad(result.Results[0].StatusCode).ShouldBeTrue(); result.Results[0].References.Count.ShouldBe(0); result.Results[0].ContinuationPoint.IsEmpty.ShouldBeTrue(); var retry = await client.BrowseNextAsync(H(), false, [token], ct); retry.Results[0].StatusCode.ShouldBe(StatusCodes.BadContinuationPointInvalid); } private static void AllowAnonymousAnchor(ServerEventRig rig) => rig.Enforce(false, [Key()], ClusterGrant(OpcUaPrincipals.Anonymous, "anchor-browse", NodePermissions.Browse)); private static ProjectedAnchorDefinition WithRawAnchorScope(ProjectedAnchorDefinition definition) => definition with { LocalScope = new NodeScope { ClusterId = ServerEventRig.Cluster, Kind = NodeHierarchyKind.Raw, Segments = definition.LocalSubject.Split('/') } }; private sealed class TestMonotonicClock : TimeProvider { private long _ticks; public override long TimestampFrequency => TimeSpan.TicksPerSecond; public override long GetTimestamp() => Interlocked.Read(ref _ticks); public void Advance(TimeSpan value) => Interlocked.Add(ref _ticks, value.Ticks); } private sealed class BlockingPages(IReadOnlyList children) : IProjectedBrowseAccess { public TaskCompletionSource FetchEntered { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public TaskCompletionSource Release { get; } = new(TaskCreationOptions.RunContinuationsAsynchronously); public ProjectedBrowseReadiness GetOrSchedule(ProjectedBrowseContext context) => ProjectedBrowseReadiness.Ready; public async Task WaitForPageAsync(ProjectedBrowsePageRequest request, CancellationToken cancellationToken) { if (request.Cursor is null) return new(ProjectedBrowseReadiness.Ready, [children[0]], "next", false, () => true); FetchEntered.TrySetResult(); await Release.Task.WaitAsync(cancellationToken); return new(ProjectedBrowseReadiness.Ready, [children[1]], null, true, () => true); } } private sealed class BrowsePages(IReadOnlyList children) : IProjectedBrowseAccess { public bool Valid = true; public ProjectedBrowseReadiness GetOrSchedule(ProjectedBrowseContext context) => ProjectedBrowseReadiness.Ready; public ProjectedBrowsePage GetOrSchedulePage(ProjectedBrowsePageRequest request) => new(ProjectedBrowseReadiness.Ready, children, null, true, () => Valid); } private sealed class BrowseOnlyAccess : IProjectedDataAccess { public Action? OnAcquire; public TimeProvider Clock => TimeProvider.System; public bool TryAcquire(NodeId nodeId, RoleCarryingUserIdentity caller, DataOperations operation, out IProjectedDemandLease? demand) { OnAcquire?.Invoke(); demand = new BrowseDemand(); return operation == DataOperations.Browse; } public bool ScheduleRead(IProjectedDemandLease demand, DataBudget budget, long requestStartedTimestamp) => false; public Task WriteAsync(IProjectedDemandLease demand, object? value, DataBudget budget, long requestStartedTimestamp, CancellationToken cancellationToken) => throw new NotSupportedException(); public bool StartSubscription(IProjectedDemandLease demand, TimeSpan publishingInterval) => false; } private sealed class BrowseDemand : IProjectedDemandLease { public DataView OriginView { get; } = new(new("origin", "urn:raw", "string", "root"), DataRealm.Raw, null, 0, "root"); public DataRealm Realm => DataRealm.Raw; public string LocalIdentifier => "unused"; public long ProjectionGeneration => 1; public TimeSpan MaximumSampleAge => TimeSpan.FromSeconds(5); public ServingIdentity Serving { get; } = new("node", "boot", "Primary", 1, 1, 1); public CancellationToken CancellationToken => CancellationToken.None; public bool IsValid => true; public void Dispose() { } } }