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