diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index c1271a36a..973446e88 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -6051,7 +6051,10 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage private bool OwnsNamespace(NodeId? nodeId) => nodeId is { } id && (id.NamespaceIndex == NamespaceIndexes[0] || id.NamespaceIndex == NamespaceIndexes[1] || - id.NamespaceIndex == NamespaceIndexes[2] || id.NamespaceIndex == NamespaceIndexes[3]); + id.NamespaceIndex == NamespaceIndexes[2] || id.NamespaceIndex == NamespaceIndexes[3] || + // A3: the imported-condition namespace is ours too — without it a condition's children keep their type ids and + // every Permits() would pass an imported id as "not ours to gate". + (NamespaceIndexes.Count > 4 && id.NamespaceIndex == NamespaceIndexes[4])); /// Pulls the ACL identity off an SDK operation context. /// The SDK context carrying the session identity. @@ -6556,13 +6559,13 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage // Only creation is gated. Refusing an UNSUBSCRIBE would strand the item on a node the session can // no longer reach — the client could never detach it, and the server would keep delivering. // A3 (§5.4): an event item on a projected notifier (a folder wired for imported conditions) is admitted through the - // verified path — Browse on the folder at subscribe time, the mapping gate per event at delivery and again at - // publish — instead of the mapped blanket deny that still applies to data items. + // verified path — the mapping gate of some condition wired there at subscribe time, per event at delivery and again + // at publish — instead of the mapped blanket deny that still applies to data items. var projectedNotifier = !unsubscribe && IsHandleInNamespace(sourceId) is { } candidate && IsProjectedEventNotifier(candidate.NodeId) ? candidate.NodeId : (NodeId?)null; if (projectedNotifier is { } notifierId) { - if (!Permits(IdentityOf(context), OpcUaOperation.Browse, notifierId)) return StatusCodes.BadUserAccessDenied; + if (!ImportedNotifierAdmits(IdentityOf(context), notifierId)) return StatusCodes.BadUserAccessDenied; } else if (SecurityFilteringActive && !unsubscribe && IsHandleInNamespace(sourceId) is { } source diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs index 56d13ddce..31236feca 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/ProjectedConditionRegistry.cs @@ -510,6 +510,18 @@ public sealed partial class OtOpcUaNodeManager : IProjectedConditionSink lock (Lock) return _importedConditions.WiredByFolder.ContainsKey(nodeId); } + /// §5.4 admission of an event item on a projected notifier: the caller sees at least one condition wired there. + private bool ImportedNotifierAdmits(RoleCarryingUserIdentity? identity, NodeId notifierId) + { + List wired; + lock (Lock) + { + if (!_importedConditions.WiredByFolder.TryGetValue(notifierId, out var ids)) return false; + wired = ids.Select(_importedConditions.Find).OfType().ToList(); + } + return wired.Any(c => ImportedVisibleTo(identity, c)); + } + /// /// The authorizer's pre-realm classifier (§5.2): null for any id outside the imported-condition namespace, otherwise /// the imported verdict. diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs new file mode 100644 index 000000000..e53f52577 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/ImportedConditionEventWireTests.cs @@ -0,0 +1,380 @@ +using System.Security.Cryptography; +using Opc.Ua; +using Opc.Ua.Client; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security; +using SdkMonitoredItem = Opc.Ua.Client.MonitoredItem; + +namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests; + +/// +/// A3a over the wire (plan §5.2–§5.5): imported conditions materialised by the consumer's registry in the +/// mapped/conditions namespace reach a projected placement folder and the Server object (i=2253) as exactly +/// one event per origin transition, carry the §5.2 identity fields, are gated by the mapping gate with ACLs OFF (A3-SEC), +/// keep their ConditionId when placements change (N4), wire/unwire notifiers lazily and symmetrically (N7), and never +/// tell a client "known inactive" on staleness (T2). Every absence assertion follows a must-arrive sentinel. +/// +[Trait("Feature", "GrpcData"), Trait("Phase", "A3")] +public sealed class ImportedConditionEventWireTests +{ + private const string Connection = "conn-a"; + private const string MappingA = "map-a"; + private const string MappingB = "map-b"; + private const string Granted = ServerEventRig.KeyPrincipal; + private static readonly string Key1 = KeyOf("cond-1"); + private static readonly string Key2 = KeyOf("cond-2"); + + // Select clauses: EventId, SourceNode, SourceName, Message, Severity, ConditionName, ActiveState/Id, AckedState/Id, + // Quality, ConditionId (ConditionType NodeId attribute), EventType. + private const int EventIdF = 0, SourceNodeF = 1, SourceNameF = 2, MessageF = 3, SeverityF = 4, ConditionNameF = 5, + ActiveF = 6, AckedF = 7, QualityF = 8, ConditionIdF = 9, EventTypeF = 10; + + [Fact] + public async Task Exactly_one_event_per_origin_transition_at_both_placement_folders_and_the_Server_object_with_identity_fields() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-once", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + using var session = await rig.ConnectAsync(anonymous: false, ct); + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + var events = new Events(); + var subscription = await SubscribeAsync(session, events, ct); + var server = AddItem(subscription, ObjectIds.Server); + var device = AddItem(subscription, f.DeviceFolder); + var anchor = AddItem(subscription, f.Anchor); + await subscription.ApplyChangesAsync(ct); + new[] { server, device, anchor }.ShouldAllBe(i => StatusCode.IsGood(i.Status.Error == null ? StatusCodes.Good : i.Status.Error.StatusCode)); + + f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "acked")); + f.Apply(Update(Key1, version: 5, active: false, acked: true, f.TwoPlacements(), message: "sentinel")); + await Events.WaitUntilAsync(() => events.Of(server).Any(e => Message(e) == "sentinel") && events.Of(device).Any(e => Message(e) == "sentinel") + && events.Of(anchor).Any(e => Message(e) == "sentinel")); + + foreach (var item in new[] { server, device, anchor }) + { + events.Of(item).Count(e => Message(e) == "acked").ShouldBe(1, $"exactly one event per transition at {item.StartNodeId}"); + events.Of(item).Count(e => Message(e) == "sentinel").ShouldBe(1); + } + + // §5.2 identity: ConditionId = SourceNode = the opaque (connection, key) id in mapped/conditions; SourceName = the + // primary placement's local display path; Severity verbatim; ConditionName from the origin. + var e0 = events.Of(server).First(e => Message(e) == "acked"); + var expectedId = new NodeId(ImportedConditionIds.Identifier(Connection, Key1), + (ushort)session.NamespaceUris.GetIndex(ImportedConditionIds.NamespaceUri)); + e0[SourceNodeF].GetNodeId().ShouldBe(expectedId); + e0[ConditionIdF].GetNodeId().ShouldBe(expectedId); + e0[SourceNameF].GetString().ShouldBe("Plant/remote-a/dev1/HR200"); + e0[SeverityF].GetUInt16().ShouldBe((ushort)777); + e0[ConditionNameF].GetString().ShouldBe("HR200"); + e0[AckedF].GetBoolean().ShouldBeTrue(); + e0[ActiveF].GetBoolean().ShouldBeTrue(); + rig.Nm.ImportedConditionCount.ShouldBe(1); + } + + [Fact] + public async Task A3_SEC_with_ACLs_off_a_session_without_the_mapping_grant_receives_nothing_at_i2253_on_a_folder_or_on_refresh() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-sec", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); // the anonymous principal holds no grant; ACL enforcement is OFF in this rig + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + using var allowed = await rig.ConnectAsync(anonymous: false, ct); + using var denied = await rig.ConnectAsync(anonymous: true, ct); + var allowedEvents = new Events(); + var deniedEvents = new Events(); + var allowedSub = await SubscribeAsync(allowed, allowedEvents, ct); + var deniedSub = await SubscribeAsync(denied, deniedEvents, ct); + var allowedServer = AddItem(allowedSub, ObjectIds.Server); + var deniedServer = AddItem(deniedSub, ObjectIds.Server); + var deniedFolder = AddItem(deniedSub, f.DeviceFolder); + await allowedSub.ApplyChangesAsync(ct); + await deniedSub.ApplyChangesAsync(ct); + deniedFolder.Status.Error?.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code, + "a projected notifier admits only a caller who sees a condition wired there"); + + await allowedSub.ConditionRefreshAsync(ct); + await deniedSub.ConditionRefreshAsync(ct); + f.Apply(Update(Key1, version: 4, active: true, acked: true, f.TwoPlacements(), message: "sentinel")); + await Events.WaitUntilAsync(() => allowedEvents.Of(allowedServer).Any(e => Message(e) == "sentinel")); + // Positive control: the granted session got the refresh replay AND the transition. + allowedEvents.Of(allowedServer).Count(e => e[AckedF].TryGetValue(out bool _)).ShouldBe(2); + // Must-arrive sentinel on the denied session's own subscription (a non-condition event every session receives): + // RefreshStart/End of its own refresh arrived, so its queue was published after the transition. + await Events.WaitUntilAsync(() => deniedEvents.Of(deniedServer).Any(e => e[EventTypeF].GetNodeId() == ObjectTypeIds.RefreshEndEventType)); + deniedEvents.Of(deniedServer).Count(e => e[AckedF].TryGetValue(out bool _)).ShouldBe(0, "no imported condition event, live or refreshed"); + + // Revocation reaches a queued event at publish time: the marker re-checks the gate. + f.Access.Allowed.Clear(); + Interlocked.Increment(ref f.Access.Generation); // a revocation moves the authority generation (verdict caches key on it) + f.Apply(Update(Key1, version: 5, active: false, acked: true, f.TwoPlacements(), message: "after-revoke")); + await Task.Delay(500, ct); + allowedEvents.Of(allowedServer).Count(e => Message(e) == "after-revoke").ShouldBe(0); + } + + [Fact] + public async Task A_condition_child_Read_is_authorized_through_the_condition_and_methods_are_refused_unapplied() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-child", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + using var allowed = await rig.ConnectAsync(anonymous: false, ct); + using var denied = await rig.ConnectAsync(anonymous: true, ct); + var ns = (ushort)allowed.NamespaceUris.GetIndex(ImportedConditionIds.NamespaceUri); + var id = ImportedConditionIds.Identifier(Connection, Key1); + var child = new NodeId(ImportedConditionIds.ChildIdentifier(id, "ActiveState/Id"), ns); + + rig.Nm.FindImportedCondition(Connection, Key1)!.ActiveState!.Id!.NodeId.ShouldBe(child, "children are instance-scoped (#629) in mapped/conditions"); + var good = await allowed.ReadValueAsync(child, ct); + StatusCode.IsGood(good.StatusCode).ShouldBeTrue(); + good.WrappedValue.GetBoolean().ShouldBeTrue(); + var refused = await Should.ThrowAsync(() => denied.ReadValueAsync(child, ct)); + refused.StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code); + + // A3a: no local apply of a remote method — the condition stays unacknowledged (A3b dispatches to the origin). + var eventId = rig.Nm.FindImportedCondition(Connection, Key1)!.EventId!.Value; + await Should.ThrowAsync(() => allowed.CallAsync(new NodeId(id, ns), MethodIds.AcknowledgeableConditionType_Acknowledge, + ct, eventId, new LocalizedText("x"))); + rig.Nm.FindImportedCondition(Connection, Key1)!.AckedState!.Id!.Value.ShouldBeFalse(); + } + + [Fact] + public async Task Disabling_the_primary_placement_mapping_moves_only_notifiers_and_SourceName_and_a_later_mapping_changes_no_NodeId() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-n4", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + var before = rig.Nm.FindImportedCondition(Connection, Key1)!; + var id = before.NodeId; + rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeTrue(); + + // The primary (dev1, map-a) disappears; only the mapping-B anchor placement remains. + f.Apply(Update(Key1, version: 4, active: true, acked: true, [f.BPlacement()], message: "moved")); + var after = rig.Nm.FindImportedCondition(Connection, Key1)!; + after.NodeId.ShouldBe(id, "ConditionId is keyed on (connection, condition_key) only"); + ReferenceEquals(after, before).ShouldBeTrue("the same condition instance"); + rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeFalse("the old placement folder is unwired symmetrically"); + rig.Nm.IsImportedNotifierWired(f.AnchorB).ShouldBeTrue(); + after.SourceName!.Value.ShouldBe("Plant/remote-b/HR200"); + + // A second mapping opened later (adds placements back): no NodeId changes. + f.Apply(Update(Key1, version: 5, active: true, acked: true, [.. f.TwoPlacements(), f.BPlacement()], message: "added")); + rig.Nm.FindImportedCondition(Connection, Key1)!.NodeId.ShouldBe(id); + rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeTrue(); + } + + [Fact] + public async Task A_retired_placement_folder_is_unwired_and_a_folder_holding_an_event_item_is_not_retired() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-n7", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var events = new Events(); + var subscription = await SubscribeAsync(session, events, ct); + var item = AddItem(subscription, f.DeviceFolder); + await subscription.ApplyChangesAsync(ct); + + var sink = (IProjectedNamespacePageSink)rig.Nm; + sink.TryRemove(f.DeviceFolder, f.DeviceDefinition).ShouldBeFalse("pinned by the admitted event item"); + rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeTrue(); + + subscription.RemoveItem(item); + await subscription.ApplyChangesAsync(ct); + sink.TryRemove(f.DeviceFolder, f.DeviceDefinition).ShouldBeTrue(); + rig.Nm.IsImportedNotifierWired(f.DeviceFolder).ShouldBeFalse("retirement unwires the notifier"); + } + + [Fact] + public async Task A_resync_of_unchanged_state_reports_nothing_and_the_next_real_transition_arrives_exactly_once() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-resync", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var events = new Events(); + var subscription = await SubscribeAsync(session, events, ct); + var server = AddItem(subscription, ObjectIds.Server); + await subscription.ApplyChangesAsync(ct); + var reported = rig.Nm.ImportedEventsReported; + + // A re-snapshot after a stream end re-states the same state under new versions (a new epoch): the shared delta gate + // suppresses it. + f.Apply(Update(Key1, version: 10, active: true, acked: false, f.TwoPlacements())); + f.Apply(Update(Key1, version: 11, active: true, acked: false, f.TwoPlacements())); + rig.Nm.ImportedEventsReported.ShouldBe(reported); + // Positive control: a real transition after it must arrive, once. + f.Apply(Update(Key1, version: 12, active: true, acked: true, f.TwoPlacements(), message: "real")); + await Events.WaitUntilAsync(() => events.Of(server).Any(e => Message(e) == "real")); + events.Of(server).Count(e => e[AckedF].TryGetValue(out bool _)).ShouldBe(1); + } + + [Fact] + public async Task Staleness_is_BadNoCommunication_once_per_condition_and_never_known_inactive_and_unknown_records_change_nothing() + { + var ct = TestContext.Current.CancellationToken; + await using var rig = await ServerEventRig.StartAsync("a3-stale", encrypted: false, ct); + var f = Fixture.Install(rig, Granted); + f.Apply(Update(Key1, version: 3, active: true, acked: false, f.TwoPlacements())); + f.Apply(Update(Key2, version: 3, active: false, acked: true, f.TwoPlacements(), known: false)); + using var session = await rig.ConnectAsync(anonymous: false, ct); + var events = new Events(); + var subscription = await SubscribeAsync(session, events, ct); + var server = AddItem(subscription, ObjectIds.Server); + await subscription.ApplyChangesAsync(ct); + + // T2: a state-unknown record never states "inactive" — the never-known condition is Uncertain, not Good. + rig.Nm.FindImportedCondition(Connection, Key2)!.Quality!.Value.Code.ShouldBe(StatusCodes.UncertainInitialValue.Code); + f.Apply(Update(Key1, version: 4, active: false, acked: true, f.TwoPlacements(), known: false)); + rig.Nm.FindImportedCondition(Connection, Key1)!.ActiveState!.Id!.Value.ShouldBeTrue("an unknown record never changes the last state"); + + rig.Nm.MarkConnectionStale(Connection); + rig.Nm.MarkConnectionStale(Connection); // idempotent: the delta gate reports the Quality change once + f.Apply(Update(Key1, version: 5, active: true, acked: true, f.TwoPlacements(), message: "sentinel")); + await Events.WaitUntilAsync(() => events.Of(server).Any(e => Message(e) == "sentinel")); + var stale = events.Of(server).Where(e => e[QualityF].TryGetValue(out StatusCode q) && q.Code == StatusCodes.BadNoCommunication.Code).ToList(); + stale.Count.ShouldBe(2, "one BadNoCommunication event per condition"); + stale.ShouldContain(e => e[ActiveF].GetBoolean(), "the active condition stays active while stale"); + } + + // --------------------------------------------------------------------------------------------------------------------- + + private static string KeyOf(string seed) => + Convert.ToBase64String(SHA256.HashData(System.Text.Encoding.UTF8.GetBytes(seed))).TrimEnd('=').Replace('+', '-').Replace('/', '_'); + + private static ImportedConditionUpdate Update(string key, long version, bool active, bool acked, + IReadOnlyList placements, string message = "HR200 high", bool known = true) + { + var info = new DataConditionInfo("http://opcfoundation.org/UA/:AlarmConditionType", "HR200", DataConditionSourceKind.Native, + placements.Select(p => p.Placement).ToArray(), (uint)DataConditionMethodSets.Native); + var state = new DataConditionState(key, version, false, known, info, active, acked, true, true, 0, 777, message, + StatusCodes.Good.Code, null, 0, DateTimeOffset.UtcNow, active || !acked, new DataActivationMarker("inc", 1)); + var sourceName = (placements[0].MappingId == MappingA ? "Plant/remote-a/" : "Plant/remote-b/") + placements[0].RelativePath; + return new ImportedConditionUpdate(Connection, state, info, placements, sourceName); + } + + private static string? Message(ArrayOf e) => e[MessageF].GetLocalizedText().Text; + + private static async Task SubscribeAsync(ISession session, Events events, CancellationToken ct) + { + var subscription = new Subscription(session.DefaultSubscription) { PublishingInterval = 100 }; + subscription.FastEventCallback = events.OnEvents; + session.AddSubscription(subscription); + await subscription.CreateAsync(ct); + return subscription; + } + + private static SdkMonitoredItem AddItem(Subscription subscription, NodeId source) + { + var filter = new EventFilter(); + filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.EventId)); + filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.SourceNode)); + filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.SourceName)); + filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.Message)); + filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.Severity)); + filter.AddSelectClause(ObjectTypeIds.ConditionType, QualifiedName.From(BrowseNames.ConditionName)); + filter.SelectClauses += new SimpleAttributeOperand(ObjectTypeIds.AlarmConditionType, + [QualifiedName.From(BrowseNames.ActiveState), QualifiedName.From(BrowseNames.Id)]); + filter.SelectClauses += new SimpleAttributeOperand(ObjectTypeIds.AcknowledgeableConditionType, + [QualifiedName.From(BrowseNames.AckedState), QualifiedName.From(BrowseNames.Id)]); + filter.AddSelectClause(ObjectTypeIds.ConditionType, QualifiedName.From(BrowseNames.Quality)); + filter.SelectClauses += new SimpleAttributeOperand { TypeDefinitionId = ObjectTypeIds.ConditionType, AttributeId = Attributes.NodeId }; + filter.AddSelectClause(ObjectTypeIds.BaseEventType, QualifiedName.From(BrowseNames.EventType)); + var item = new SdkMonitoredItem(subscription.DefaultItem) + { + StartNodeId = source, AttributeId = Attributes.EventNotifier, Filter = filter, QueueSize = 1000, SamplingInterval = 0, + }; + subscription.AddItem(item); + return item; + } + + private sealed class Events + { + private readonly object _gate = new(); + private readonly List<(uint Handle, ArrayOf Fields)> _events = []; + + public void OnEvents(Subscription subscription, EventNotificationList notification, ArrayOf stringTable) + { + lock (_gate) foreach (var e in notification.Events) _events.Add((e.ClientHandle, e.EventFields)); + } + + public IReadOnlyList> Of(SdkMonitoredItem item) + { + lock (_gate) return _events.Where(e => e.Handle == item.ClientHandle).Select(e => e.Fields).ToList(); + } + + public static Task WaitUntilAsync(Func condition) => RecordedEvents.WaitUntilAsync(condition); + } + + /// The fake §5.4 gate: a principal set (ACL enforcement stays OFF in the rig). + internal sealed class FakeConditionAccess : IProjectedConditionAccess + { + public HashSet Allowed { get; } = new(StringComparer.Ordinal); + public int Demands; + public long Generation = 1; + public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList placements) => + caller is not null && Allowed.Contains(caller.Principal); + public long AuthorityGeneration => Interlocked.Read(ref Generation); + public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller) + { + Interlocked.Increment(ref Demands); + return null; + } + } + + /// A local parent, two mapping anchors (map-a, map-b) and one projected device folder under map-a. + private sealed class Fixture + { + public required ServerEventRig Rig { get; init; } + public required FakeConditionAccess Access { get; init; } + public required NodeId Anchor { get; init; } + public required NodeId AnchorB { get; init; } + public required NodeId DeviceFolder { get; init; } + public required ProjectedVariableDefinition DeviceDefinition { get; init; } + + public static Fixture Install(ServerEventRig rig, string grantedPrincipal) + { + var nm = rig.Nm; + nm.EnsureFolder("Plant", null, "Plant", AddressSpaceRealm.Raw); + var parent = nm.TryGetFolder("Plant", AddressSpaceRealm.Raw)!.NodeId; + var rootA = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant"); + var rootB = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Other"); + nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingA, rootA), parent, + "remote-a", "Plant/remote-a", MappingA, 1, () => true), out var anchor).ShouldBeTrue(); + nm.TryEnsureProjectedAnchor(new ProjectedAnchorDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingB, rootB), parent, + "remote-b", "Plant/remote-b", MappingB, 1, () => true), out var anchorB).ShouldBeTrue(); + var devAddress = new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1"); + var metadata = new DataMetadata(new DataView(devAddress, DataRealm.Raw, MappingA, 1, "Plant/remote-a/dev1"), "dev1", "Folder", + DataValueKind.Null, -1, [], false, DataOperations.Browse, 1, null, null, false); + var definition = new ProjectedVariableDefinition(DataRealm.Raw, ProjectedDataIds.Identifier(MappingA, devAddress), anchor!.Value, + metadata, 1, () => true); + nm.TryEnsureProjectedVariable(definition, out var device).ShouldBeTrue(); + var access = new FakeConditionAccess(); + access.Allowed.Add(grantedPrincipal); + nm.ProjectedConditionAccess = access; + return new Fixture { Rig = rig, Access = access, Anchor = anchor.Value, AnchorB = anchorB!.Value, DeviceFolder = device!.Value, + DeviceDefinition = definition }; + } + + /// Primary: the raw tag under dev1 (map-a); second: the same condition listed directly under the map-a root. + public IReadOnlyList TwoPlacements() => + [ + new(MappingA, DataRealm.Raw, View("Plant/dev1/HR200"), "Plant/remote-a/dev1", "dev1/HR200"), + new(MappingA, DataRealm.Raw, View("Plant/HR200"), "Plant/remote-a", "HR200"), + ]; + + public ImportedConditionPlacement BPlacement() => + new(MappingB, DataRealm.Raw, View("Other/HR200"), "Plant/remote-b", "HR200"); + + private static DataView View(string path) => + new(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", path), DataRealm.Raw, null, 0, path); + + public void Apply(ImportedConditionUpdate update) => Rig.Nm.ApplyConditions([update]); + } +}