using System.Security.Cryptography; 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.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; namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections; /// /// A3a (plan §5.2 N4, §5.4): an imported-condition id is classified BEFORE RealmOf on every authorizer entry point /// (read, history, call, subscribe), whatever realm the caller computed; and the publish-time rewriter drops a marked /// imported event whose re-check fails, and re-gates an unmarked one for the publishing session. /// [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A3")] public sealed class ImportedConditionClassifierTests : IAsyncDisposable { private readonly string _pki = Path.Combine(Path.GetTempPath(), $"otopcua-imported-classifier-{Guid.NewGuid():N}"); private OpcUaApplicationHost? _host; [Theory] [InlineData(true)] [InlineData(false)] public void A_condition_namespace_id_is_never_decided_by_the_realm_walk_on_any_authorizer_entry_point(bool aclEnabled) { var f = new Fixture(aclEnabled); // a Cluster-wide grant: the Raw/Uns walk would ALLOW everything var conditionId = new NodeId("c1.anything", 9); var calls = new List<(OpcUaOperation, NodeId)>(); f.Gate.ImportedConditionClassifier = (_, op, id) => { if (id.NamespaceIndex != 9) return null; calls.Add((op, id)); return false; }; foreach (var realm in new[] { AddressSpaceRealm.Raw, AddressSpaceRealm.Uns }) { foreach (var op in new[] { OpcUaOperation.Read, OpcUaOperation.Browse, OpcUaOperation.HistoryRead, OpcUaOperation.Call, OpcUaOperation.CreateMonitoredItems, OpcUaOperation.AlarmAcknowledge }) { f.Gate.Authorize(f.Identity, op, conditionId, realm).ShouldNotBeNull($"Authorize {op} {realm}"); f.Gate.AuthorizeIfRequired(f.Identity, op, conditionId, realm).ShouldNotBeNull($"AuthorizeIfRequired {op} {realm}"); f.Gate.IsAllowedCached(f.Identity, op, conditionId, realm).ShouldBeFalse($"IsAllowedCached {op} {realm}"); f.Gate.TryAuthorizeMapped(f.Identity, op, conditionId, realm, out var veto).ShouldBeTrue(); veto.ShouldNotBeNull(); } } calls.Count.ShouldBe(2 * 6 * 4, "every entry point asked the condition classifier, never the realm"); // Positive control: the same identity on an ordinary Raw id is decided by the grant walk (allowed). f.Gate.Authorize(f.Identity, OpcUaOperation.Read, new NodeId("Plant/x", 2), AddressSpaceRealm.Raw).ShouldBeNull(); } [Fact] public async Task The_node_manager_classifier_allows_Read_and_Subscribe_through_the_condition_and_refuses_history_and_calls() { var nm = await BootAsync(); var f = new Fixture(aclEnabled: true); nm.Authorizer = f.Gate; var access = new Access(); nm.ProjectedConditionAccess = access; var key = Convert.ToBase64String(SHA256.HashData("k"u8.ToArray())).TrimEnd('=').Replace('+', '-').Replace('/', '_'); var view = new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR"), DataRealm.Raw, null, 0, "Plant/dev1/HR"); var placement = new ImportedConditionPlacement("map-a", DataRealm.Raw, view, "Plant/remote-a/dev1", "dev1/HR"); var state = new DataConditionState(key, 1, false, true, new DataConditionInfo("AlarmConditionType", "HR", DataConditionSourceKind.Native, [view], 3), true, false, true, true, 0, 500, "m", 0, null, 0, DateTimeOffset.UtcNow, true, new DataActivationMarker("i", 1)); nm.ApplyConditions([new ImportedConditionUpdate("conn-a", state, state.Info, [placement], "Plant/remote-a/dev1/HR")]); var alarm = nm.FindImportedCondition("conn-a", key).ShouldNotBeNull(); nm.IsImportedConditionId(alarm.NodeId).ShouldBeTrue(); var child = alarm.ActiveState!.Id!.NodeId; nm.IsImportedConditionId(child).ShouldBeTrue("children live in the condition's namespace (#629)"); foreach (var realm in new[] { AddressSpaceRealm.Raw, AddressSpaceRealm.Uns }) { access.Visible = true; f.Gate.Authorize(f.Identity, OpcUaOperation.Read, child, realm).ShouldBeNull(); f.Gate.Authorize(f.Identity, OpcUaOperation.CreateMonitoredItems, alarm.NodeId, realm).ShouldBeNull(); f.Gate.Authorize(f.Identity, OpcUaOperation.HistoryRead, alarm.NodeId, realm).ShouldNotBeNull("no imported condition history"); f.Gate.Authorize(f.Identity, OpcUaOperation.Call, alarm.NodeId, realm).ShouldNotBeNull("remote methods are A3b"); f.Gate.Authorize(f.Identity, OpcUaOperation.AlarmAcknowledge, alarm.NodeId, realm).ShouldNotBeNull(); access.Visible = false; access.Generation++; f.Gate.Authorize(f.Identity, OpcUaOperation.Read, child, realm).ShouldNotBeNull("not visible ⇒ denied despite the Cluster grant"); } } [Fact] public void The_rewriter_drops_a_failed_marked_event_and_regates_an_unmarked_imported_one() { var keep = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => true)) { ClientHandle = 1 }; var drop = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => false)) { ClientHandle = 2 }; var unmarkedDenied = new EventFieldList { ClientHandle = 3 }; var unmarkedOther = new EventFieldList { ClientHandle = 4 }; var throwing = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => throw new InvalidOperationException())) { ClientHandle = 5 }; var message = new NotificationMessage { SequenceNumber = 7, NotificationData = [new ExtensionObject(new EventNotificationList { Events = [keep, drop, unmarkedDenied, unmarkedOther, throwing] })], }; var projected = ProjectedNotificationRewriter.Project(message, republish: false, list => list.ClientHandle == 3 ? false : null); var events = projected.NotificationData[0].TryGetValue(out var list) ? list! : throw new InvalidOperationException(); projected.NotificationData.Count.ShouldBe(1); events.Events.ToArray()!.Select(e => e.ClientHandle).ShouldBe([1u, 4u]); // Every denied event emptied ⇒ the payload is left out entirely (events have no Bad-value form). var allDenied = new NotificationMessage { SequenceNumber = 8, NotificationData = [new ExtensionObject(new EventNotificationList { Events = [drop] })] }; ProjectedNotificationRewriter.Project(allDenied, republish: true, null).NotificationData.Count.ShouldBe(0); // No imported gate and no marker: v1 messages pass through as the same instance. var plain = new NotificationMessage { SequenceNumber = 9, NotificationData = [new ExtensionObject(new EventNotificationList { Events = [unmarkedOther] })] }; ReferenceEquals(ProjectedNotificationRewriter.Project(plain, republish: false, null), plain).ShouldBeTrue(); } /// /// A3 review round 2 (root cause of the intermittent OI ConditionRefresh failures): SDK 2.0.1 pools EventFieldList /// process-wide, and SentMessageQueue calls Reuse() on every list of an acknowledged message. A marked /// list that went back to the stock pool was rented by an unrelated server/session's GetEventFields (its /// RefreshStart/RefreshEnd), carrying a revoked marker, and the rewriter dropped it. A released marked list must never /// be rentable, and must not keep its marker (closure over condition + identity) alive. /// [Fact] public void A_released_marked_event_list_never_returns_to_the_SDK_pool_so_no_other_session_rents_its_marker() { var marked = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => false)) { ClientHandle = 77 }; ((IPooledEncodeable)marked).Reuse(); // exactly what SentMessageQueue.ReuseNotificationPayloads does on ACK / eviction marked.Marker.ShouldBeNull("a released list holds no authority (and keeps no closure alive)"); // Drain more than the pool can hold: had the marked instance been returned, it would come out here. var rented = new List(); try { for (var i = 0; i < PooledEncodeableType.DefaultMaximumRetained + 64; i++) rented.Add((EventFieldList)EventFieldListActivator.Instance.CreateInstance()); rented.ShouldNotContain(l => l is ProjectedEventFieldList, "a stock list rented for any event is never a marked one"); } finally { foreach (var l in rented) ((IPooledEncodeable)l).Reuse(); } // A released marked list that somehow reached the rewriter fails closed (never judged by a stale marker). var message = new NotificationMessage { SequenceNumber = 10, NotificationData = [new ExtensionObject(new EventNotificationList { Events = [marked] })] }; ProjectedNotificationRewriter.Project(message, republish: false, null).NotificationData.Count.ShouldBe(0); } /// /// Verification review r2: the rewriter never sees the queued instance — SDK 2.0.1 SentMessageQueue hands Publish /// and Republish a CoreUtils.Clone of the stored message. The gate holds only because /// is MemberwiseClone, which keeps the subclass, the marker and the handle. Pins /// that dependency: an SDK that cloned through the activator (a stock list) would turn this red. /// [Fact] public void Cloning_a_marked_event_list_the_way_the_SDK_does_keeps_the_subclass_and_the_marker() { var marker = new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => false); var marked = new ProjectedEventFieldList(marker) { ClientHandle = 42 }; var direct = marked.Clone().ShouldBeOfType(); direct.Marker.ShouldBeSameAs(marker); direct.ClientHandle.ShouldBe(42u); var message = new NotificationMessage { SequenceNumber = 11, NotificationData = [new ExtensionObject(new EventNotificationList { Events = [marked] })] }; var delivered = CoreUtils.Clone(message)!; // exactly what SentMessageQueue returns for Publish / Republish delivered.NotificationData[0].TryGetValue(out var list).ShouldBeTrue(); var events = list!.Events; var cloned = events[0].ShouldBeOfType(); cloned.ShouldNotBeSameAs(marked, "the SDK delivers a copy, not the queued instance"); cloned.Marker.ShouldBeSameAs(marker); ProjectedNotificationRewriter.Project(delivered, republish: false, null).NotificationData.Count .ShouldBe(0, "the copy is still judged by its marker (and dropped when the re-check fails)"); } [Fact] public void S2_a_cached_positive_verdict_is_re_proved_past_the_credential_expiry_and_past_the_positive_TTL() { var registry = new ProjectedConditionRegistry(); var condition = new ImportedCondition(new AlarmConditionState(null) { NodeId = new NodeId("c", 9) }, "conn", "k"); var computes = 0; bool Allow() { computes++; return true; } var now = DateTimeOffset.UtcNow; var expiringKey = new object(); registry.Verdict(expiringKey, condition, 1, now, now.AddSeconds(2), Allow).ShouldBeTrue(); registry.Verdict(expiringKey, condition, 1, now.AddSeconds(1), now.AddSeconds(2), Allow).ShouldBeTrue(); computes.ShouldBe(1, "served from cache inside both bounds"); registry.Verdict(expiringKey, condition, 1, now.AddSeconds(3), now.AddSeconds(2), () => { computes++; return false; }) .ShouldBeFalse("past the key's expiry the verdict is re-proved (and the policy now denies)"); var longLived = new object(); registry.Verdict(longLived, condition, 1, now, null, Allow).ShouldBeTrue(); registry.Verdict(longLived, condition, 1, now + ProjectedConditionRegistry.PositiveVerdictTtl + TimeSpan.FromSeconds(1), null, Allow); computes.ShouldBe(4, "a positive verdict lives at most the TTL"); } private async Task BootAsync() { var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions { ApplicationName = "ImportedClassifier", ApplicationUri = $"urn:ImportedClassifier:{Guid.NewGuid():N}", OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki, }, NullLogger.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken); _host = started.Host; return started.Server.NodeManager!; } public async ValueTask DisposeAsync() { if (_host is not null) await _host.DisposeAsync(); if (Directory.Exists(_pki)) try { Directory.Delete(_pki, recursive: true); } catch (IOException) { } } private sealed class Access : IProjectedConditionAccess { public bool Visible { get; set; } public long Generation { get; set; } = 1; public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList placements) => caller is not null && Visible; public long AuthorityGeneration => Generation; public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller) => null; public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject) => caller is not null && Visible; public bool IsConditionBearingMapping(string mappingId) => true; } private sealed class Fixture { private readonly DataPlaneAuthorityState _state = new(); private readonly ApiKey _key = new() { ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = "hash", Enabled = true, ExpiresUtc = DateTime.UtcNow.AddHours(1) }; public DataPlaneAuthorizer Gate { get; } public Fixture(bool aclEnabled) { _state.Apply("c1", "rev", [_key], [new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader", ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = (NodePermissions)~0 }], new Dictionary>()); Gate = new DataPlaneAuthorizer(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), aclEnabled, NullLogger.Instance, TimeProvider.System); } public RoleCarryingUserIdentity Identity => new(new UserNameIdentityToken { UserName = "apikey" }, [], "reader", _key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(_key), DateTimeOffset.UtcNow.AddMinutes(5)); } }