using Microsoft.Extensions.Logging.Abstractions; using Opc.Ua; using Opc.Ua.Server; using DataValue = Opc.Ua.DataValue; 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; /// SDK decisions must use the live mapped subject even when legacy local ACLs are off. [Trait("Category", "Unit")] [Trait("Feature", "GrpcData")] [Trait("Phase", "P03")] public sealed class GrpcDataMappedSubjectTests : IDisposable { private static readonly DateTimeOffset Now = new(2026, 11, 15, 12, 0, 0, TimeSpan.Zero); private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-mapped-acl-{Guid.NewGuid():N}"); [Theory] [InlineData(AddressSpaceRealm.Raw, DataRealm.Raw, NodeHierarchyKind.Raw)] [InlineData(AddressSpaceRealm.Uns, DataRealm.Uns, NodeHierarchyKind.Uns)] public async Task A_mapped_read_is_gated_with_acl_off_but_a_local_read_is_unchanged( AddressSpaceRealm realm, DataRealm dataRealm, NodeHierarchyKind kind) { var fixture = new Fixture(dataRealm, kind, NodePermissions.Browse); var (host, server) = await BootAsync(); try { var nm = server.NodeManager!; nm.Authorizer = fixture.Gate; nm.MappedSubjectResolver = (r, id) => r == realm && id == "Plant/Mount/Speed" ? fixture.Resolution() : MappedNodeResolution.Local; nm.EnsureVariable("Plant/Mount/Speed", null, "mapped", "Float", false, realm); nm.EnsureVariable("Plant/Local/Speed", null, "local", "Float", false, realm); var mapped = nm.TryGetVariable("Plant/Mount/Speed", realm)!.NodeId; var local = nm.TryGetVariable("Plant/Local/Speed", realm)!.NodeId; var errors = Read(nm, fixture.Identity, mapped, local); errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadUserAccessDenied.Code); errors[1].StatusCode.Code.ShouldNotBe(StatusCodes.BadUserAccessDenied.Code); } finally { await host.DisposeAsync(); } } [Theory] [InlineData(AddressSpaceRealm.Raw, DataRealm.Raw, NodeHierarchyKind.Raw)] [InlineData(AddressSpaceRealm.Uns, DataRealm.Uns, NodeHierarchyKind.Uns)] public void Cached_allow_never_survives_changed_live_provenance_or_a_removed_mapping( AddressSpaceRealm realm, DataRealm dataRealm, NodeHierarchyKind kind) { var f = new Fixture(dataRealm, kind, NodePermissions.Read); var live = f.Subject; var resolver = f.Resolver; f.Gate.MappedSubjectResolver = (_, _) => MappedNodeResolution.Mapped(live.View, live, resolver, f.Lease); var node = new NodeId("Plant/Mount/Speed", 2); f.Gate.AuthorizeCached(f.Identity, OpcUaOperation.Read, node, realm).ShouldBeNull(); live = live with { LocalAncestry = ["different-parent", "mapping-a"] }; f.Gate.AuthorizeCached(f.Identity, OpcUaOperation.Read, node, realm).ShouldNotBeNull(); live = f.Subject; resolver = new MappedSubjectResolver([], catalogEpoch: 8, new TestCatalogAuthority()); f.Gate.AuthorizeCached(f.Identity, OpcUaOperation.Read, node, realm).ShouldNotBeNull(); f.Gate.MappedSubjectResolver = (_, _) => MappedNodeResolution.Deny; f.Gate.AuthorizeCached(f.Identity, OpcUaOperation.Read, node, realm).ShouldNotBeNull(); } [Theory] [InlineData(OpcUaOperation.Browse)] [InlineData(OpcUaOperation.Read)] [InlineData(OpcUaOperation.WriteOperate)] public void Mapped_permissions_are_evaluated_per_operation_with_acl_off(OpcUaOperation operation) { var f = new Fixture(DataRealm.Raw, NodeHierarchyKind.Raw, NodePermissions.Browse | NodePermissions.Read | NodePermissions.WriteOperate); f.Gate.MappedSubjectResolver = (_, _) => f.Resolution(); var node = new NodeId("Plant/Mount/Speed", 2); f.Gate.AuthorizeIfRequired(f.Identity, operation, node, AddressSpaceRealm.Raw).ShouldBeNull(); f.Gate.AuthorizeIfRequired(null, operation, node, AddressSpaceRealm.Raw).ShouldNotBeNull(); f.Gate.MappedSubjectResolver = (_, _) => MappedNodeResolution.Mapped( f.Subject.View with { Subject = "Plant/Mount" }, f.Subject, f.Resolver, f.Lease); f.Gate.AuthorizeIfRequired(f.Identity, operation, node, AddressSpaceRealm.Raw).ShouldNotBeNull(); } [Fact] public async Task Authorized_mapped_write_never_falls_through_to_the_local_gateway() { var f = new Fixture(DataRealm.Raw, NodeHierarchyKind.Raw, NodePermissions.WriteOperate); var (host, server) = await BootAsync(); try { var nm = server.NodeManager!; var gateway = new RecordingWriteGateway(); nm.NodeWriteGateway = gateway; nm.Authorizer = f.Gate; nm.MappedSubjectResolver = (_, id) => id == "Plant/Mount/Speed" ? f.Resolution() : MappedNodeResolution.Local; nm.EnsureVariable("Plant/Mount/Speed", null, "mapped", "Float", true, AddressSpaceRealm.Raw); var node = nm.TryGetVariable("Plant/Mount/Speed", AddressSpaceRealm.Raw)!.NodeId; f.Gate.AuthorizeIfRequired(f.Identity, OpcUaOperation.WriteOperate, node, AddressSpaceRealm.Raw).ShouldBeNull(); var context = new OperationContext(new RequestHeader(), null, RequestType.Write, RequestLifetime.None, f.Identity); var writes = new List { new() { NodeId = node, AttributeId = Attributes.Value, Value = new DataValue(new Variant(42f), StatusCodes.Good) } }; var errors = new List { null! }; nm.Write(context, writes, errors); errors[0].StatusCode.Code.ShouldBe(StatusCodes.BadNotWritable.Code); gateway.Calls.ShouldBe(0); } finally { await host.DisposeAsync(); } } [Fact] public void Mapped_classifier_uses_the_actual_namespace_not_a_local_identifier_that_looks_opaque() { var f = new Fixture(DataRealm.Raw, NodeHierarchyKind.Raw, NodePermissions.Read); f.Gate.MappedSubjectResolver = (_, _) => MappedNodeResolution.Deny; f.Gate.MappedNamespacePredicate = id => id.NamespaceIndex == 3; var sameIdentifier = "p1.canonical-looking"; f.Gate.AuthorizeIfRequired(f.Identity, OpcUaOperation.Read, new NodeId(sameIdentifier, 2), AddressSpaceRealm.Raw).ShouldBeNull(); f.Gate.AuthorizeIfRequired(f.Identity, OpcUaOperation.Read, new NodeId(sameIdentifier, 3), AddressSpaceRealm.Raw).ShouldNotBeNull(); } [Fact] public void Cached_allow_rechecks_original_key_version_principal_and_expiry() { var f = new Fixture(DataRealm.Raw, NodeHierarchyKind.Raw, NodePermissions.Read); f.Gate.MappedSubjectResolver = (_, _) => f.Resolution(); var node = new NodeId("Plant/Mount/Speed", 2); f.Gate.AuthorizeCached(f.Identity, OpcUaOperation.Read, node, AddressSpaceRealm.Raw).ShouldBeNull(); var otherVersion = f.IdentityFor(new ApiKey { ApiKeyId = f.Key.ApiKeyId, Name = f.Key.Name, Principal = f.Key.Principal, SecretHash = "replacement", Enabled = true }, Now.AddMinutes(2)); f.Gate.AuthorizeCached(otherVersion, OpcUaOperation.Read, node, AddressSpaceRealm.Raw).ShouldNotBeNull(); var otherPrincipal = new RoleCarryingUserIdentity(new UserNameIdentityToken { UserName = "apikey" }, [], "intruder", f.Key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(f.Key), Now.AddMinutes(2)); f.Gate.AuthorizeCached(otherPrincipal, OpcUaOperation.Read, node, AddressSpaceRealm.Raw).ShouldNotBeNull(); f.Clock.Utc = Now.AddMinutes(3); f.Gate.AuthorizeCached(f.Identity, OpcUaOperation.Read, node, AddressSpaceRealm.Raw).ShouldNotBeNull(); } [Fact] public async Task Mapped_subscription_stays_stood_down_without_a_publish_time_lease_gate() { var f = new Fixture(DataRealm.Raw, NodeHierarchyKind.Raw, NodePermissions.Subscribe); var (host, server) = await BootAsync(); try { var nm = server.NodeManager!; nm.Authorizer = f.Gate; nm.MappedSubjectResolver = (_, id) => id == "Plant/Mount/Speed" ? f.Resolution() : MappedNodeResolution.Local; nm.EnsureVariable("Plant/Mount/Speed", null, "mapped", "Float", false, AddressSpaceRealm.Raw); var node = nm.TryGetVariable("Plant/Mount/Speed", AddressSpaceRealm.Raw)!.NodeId; var handle = (NodeHandle)nm.GetManagerHandle(node)!; var item = new StubSampledItem(handle, f.Identity); nm.TrackLiveMonitoredItem(handle, item); nm.RevalidateMonitoredItems(); item.Denials.ShouldBe(1); f.Lease.IsValid = false; nm.RevalidateMonitoredItems(); item.Denials.ShouldBe(1); } finally { await host.DisposeAsync(); } } [Fact] public void Role_augmentation_preserves_original_credential_evidence() { var f = new Fixture(DataRealm.Raw, NodeHierarchyKind.Raw, NodePermissions.Read); var augmented = f.Identity.WithAdditionalRoles([Role.AuthenticatedUser], new NamespaceTable()) .ShouldBeOfType(); augmented.CredentialVersion.ShouldBe(DataCallerIdentity.CredentialVersionFor(f.Key)); augmented.CredentialExpiresUtc.ShouldBe(Now.AddMinutes(2)); } private static List Read(OtOpcUaNodeManager nm, IUserIdentity identity, params NodeId[] ids) { var context = new OperationContext(new RequestHeader(), null, RequestType.Read, RequestLifetime.None, identity); var reads = ids.Select(id => new ReadValueId { NodeId = id, AttributeId = Attributes.Value }).ToList(); var values = ids.Select(_ => new DataValue()).ToList(); var errors = Enumerable.Repeat(null!, ids.Length).ToList(); nm.Read(context, 0, reads, values, errors); return errors; } private async Task<(OpcUaApplicationHost Host, OtOpcUaSdkServer Server)> BootAsync() { var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions { ApplicationName = "MappedAclTest", ApplicationUri = $"urn:MappedAclTest:{Guid.NewGuid():N}", OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pkiRoot, }, NullLogger.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken); return (started.Host, started.Server); } public void Dispose() { if (Directory.Exists(_pkiRoot)) try { Directory.Delete(_pkiRoot, recursive: true); } catch (IOException) { } } private sealed class Fixture { internal readonly TestClock Clock = new(); internal readonly TestLease Lease = new(); internal readonly ApiKey Key = NewKey("hash-a"); internal readonly DataPlaneAuthorizer Gate; internal readonly MappedNamespaceSubject Subject; internal readonly MappedSubjectResolver Resolver; internal RoleCarryingUserIdentity Identity => IdentityFor(Key, Now.AddMinutes(2)); internal Fixture(DataRealm realm, NodeHierarchyKind kind, NodePermissions permissions) { var state = new DataPlaneAuthorityState(); var grant = new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader", ScopeKind = NodeAclScopeKind.RawFolder, ScopeId = "folder", PermissionFlags = permissions }; state.Apply("c1", "rev-a", [Key], [grant], new Dictionary> { [new(NodeAclScopeKind.RawFolder, "folder")] = [new([realm == DataRealm.Raw ? "raw" : "uns", "Plant", "Mount"])], }); Gate = new DataPlaneAuthorizer(state, new TriePermissionEvaluator(state.Tries, Clock), false, NullLogger.Instance, Clock); var serving = new ServingIdentity("node-a", "incarnation-a", "Primary", 7, 1); Subject = new MappedNamespaceSubject( new DataView(new DataAddress("origin", "ns", "string", "source"), realm, "mapping-a", 1, "Plant/Mount/Speed"), new NodeScope { ClusterId = "c1", Kind = kind, Segments = ["Plant", "Mount", "Speed"] }, ["local-parent", "mapping-a"], serving, DataOperations.Browse | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe, WriteThrough: true); Resolver = new MappedSubjectResolver([Subject], catalogEpoch: 7, new TestCatalogAuthority()); } internal MappedNodeResolution Resolution() => MappedNodeResolution.Mapped(Subject.View, Subject, Resolver, Lease); internal RoleCarryingUserIdentity IdentityFor(ApiKey key, DateTimeOffset expiry) => new(new UserNameIdentityToken { UserName = "apikey" }, [], "reader", key.ApiKeyId, DataCallerIdentity.CredentialVersionFor(key), expiry); private static ApiKey NewKey(string hash) => new() { ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = hash, Enabled = true, ExpiresUtc = Now.AddHours(1).UtcDateTime }; } private sealed class RecordingWriteGateway : IOpcUaNodeWriteGateway { public int Calls { get; private set; } public Task WriteAsync(string nodeId, object? value, AddressSpaceRealm realm, CancellationToken ct) { Calls++; return Task.FromResult(new NodeWriteOutcome(true, null)); } } private sealed class TestCatalogAuthority : IDataMappedCatalogAuthority { public long CatalogEpoch => 1; public long AuthorityEpoch => 1; public bool IsActive => true; } private sealed class TestLease : IDataAuthorizationLease { public ServingIdentity Serving { get; } = new("node-a", "incarnation-a", "Primary", 7, 1); public bool IsValid { get; set; } = true; } private sealed class StubSampledItem(NodeHandle handle, IUserIdentity identity) : ISampledDataChangeMonitoredItem { /// How many BadUserAccessDenied values revalidation queued on this item. public int Denials { get; private set; } public IUserIdentity EffectiveIdentity => identity; public object ManagerHandle => handle; public NodeId NodeId => handle.NodeId; public void QueueValue(in DataValue value, ServiceResult? error, bool ignoreFilters) { if (error?.StatusCode.Code == StatusCodes.BadUserAccessDenied) Denials++; } public void QueueValue(in DataValue value, ServiceResult? error) => QueueValue(value, error, false); public void Dispose() { } // ── everything below is untouched by revalidation ── public IAsyncNodeManager NodeManager => throw new NotSupportedException(); public ISession Session => throw new NotSupportedException(); public uint Id => throw new NotSupportedException(); public uint SubscriptionId => throw new NotSupportedException(); public bool IsDurable => throw new NotSupportedException(); public uint ClientHandle => throw new NotSupportedException(); public ISubscription SubscriptionCallback { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public int MonitoredItemType => throw new NotSupportedException(); public bool IsReadyToPublish => throw new NotSupportedException(); public bool IsReadyToTrigger { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public bool IsResendData => throw new NotSupportedException(); public MonitoringMode MonitoringMode => throw new NotSupportedException(); public double SamplingInterval => throw new NotSupportedException(); public DataChangeFilter DataChangeFilter => throw new NotSupportedException(); public uint AttributeId => throw new NotSupportedException(); public NumericRange IndexRange => throw new NotSupportedException(); public QualifiedName DataEncoding => throw new NotSupportedException(); public bool AlwaysReportUpdates { get => throw new NotSupportedException(); set => throw new NotSupportedException(); } public DiagnosticsMasks DiagnosticsMasks => throw new NotSupportedException(); public uint QueueSize => throw new NotSupportedException(); public double MinimumSamplingInterval => throw new NotSupportedException(); public int TimeToNextSample => throw new NotSupportedException(); public void SetupResendDataTrigger() => throw new NotSupportedException(); public ServiceResult GetCreateResult(out MonitoredItemCreateResult result) => throw new NotSupportedException(); public ServiceResult GetModifyResult(out MonitoredItemModifyResult result) => throw new NotSupportedException(); public IStoredMonitoredItem ToStorableMonitoredItem() => throw new NotSupportedException(); public MonitoringMode SetMonitoringMode(MonitoringMode monitoringMode) => throw new NotSupportedException(); public bool Publish( OperationContext context, Queue notifications, Queue diagnostics, uint maxNotificationsPerPublish, Microsoft.Extensions.Logging.ILogger logger) => throw new NotSupportedException(); public void SetSemanticsChanged() => throw new NotSupportedException(); public void SetStructureChanged() => throw new NotSupportedException(); public bool SamplingIntervalExpired() => throw new NotSupportedException(); public ReadValueId GetReadValueId() => throw new NotSupportedException(); public ServiceResult ModifyAttributes( DiagnosticsMasks diagnosticsMasks, TimestampsToReturn timestampsToReturn, uint clientHandle, MonitoringFilter originalFilter, MonitoringFilter filterToUse, Opc.Ua.Range range, double samplingInterval, uint queueSize, bool discardOldest) => throw new NotSupportedException(); public void SetSamplingInterval(double samplingInterval) => throw new NotSupportedException(); } private sealed class TestClock : TimeProvider { internal DateTimeOffset Utc { get; set; } = Now; public override DateTimeOffset GetUtcNow() => Utc; } }