diff --git a/.claude/rules/data-plane-auth.md b/.claude/rules/data-plane-auth.md index b70ed4ca3..656476353 100644 --- a/.claude/rules/data-plane-auth.md +++ b/.claude/rules/data-plane-auth.md @@ -139,10 +139,18 @@ Two things to know before relying on any of this: silenced without ever being told why (caught only by the over-the-wire test). Detaching is also reversible, so restoring the grant resumes the feed with no client action. ⚠️ **`Changed` is no longer the only trigger (arch-review 03/S19):** `AclRevalidationTimer`, armed by `OtOpcUaServerHostedService` - at `Security:Acl:RevalidationIntervalSeconds` (default 60 s, `0` disables, inert while - `Security:Acl:Enabled` is false), runs the same pass on the clock — because `ExpiresUtc` passes with - the clock, not with a deployment. The pass's verdict memo is **pass-local and must stay that way**; - hoisting it across ticks would serve an expiry that landed between two ticks the earlier tick's allow. + at `Security:Acl:RevalidationIntervalSeconds` (default 60 s, `0` disables), runs the same pass on the + clock — because `ExpiresUtc` passes with the clock, not with a deployment. The pass's verdict memo is + **pass-local and must stay that way**; hoisting it across ticks would serve an expiry that landed between + two ticks the earlier tick's allow. ⚠️ **The pass runs with the flag OFF too, so its verdict MUST be + `Permits(identity, CreateMonitoredItems, node)` — the creation gate's own seam, the one place the + `Enabled=false` bypass lives (#972).** `8ad03e9c5` made the old `SecurityFilteringActive` toggle always + true (`|| NamespaceIndexes.Count >= 4` — five namespaces are always registered) while the pass still asked + the bypass-less `IsAllowedCached`, so every ungranted/Anonymous subscription was stood down within 60 s of + creation on the DEFAULT config. The toggle is deleted: the request seams always run their gated path (it is + also the projected-data routing path), and `Permits` alone decides the flag. Tests: + `NodeManagerStage6EnforcementTests.Revalidation_*enforcement_is_off*`, `AclSubscriptionEnforcementTests` / + `AclEventSubscriptionEnforcementTests` flag-off survival + flag-on control. **Event/alarm items ride both triggers too (Gitea #562)** — a second map (`_eventItems`), fed by the `SubscribeToEvents` override, holds every *direct* notifier subscription; a denied one is detached via the SDK's own protected `SubscribeToEvents(…, unsubscribe: true)` (what a client delete does) and diff --git a/docs/security.md b/docs/security.md index 5a707880a..2ffc1e381 100644 --- a/docs/security.md +++ b/docs/security.md @@ -842,7 +842,11 @@ Behaviours worth knowing before enabling it: fan-out; restoring its authority re-attaches it. There are **two triggers**: - a **deployment**, which re-authorizes every live monitored item (the deployment axis); - the host's **low-frequency timer**, `Security:Acl:RevalidationIntervalSeconds` (default 60 s, `0` - disables it, inert while `Security:Acl:Enabled` is false). Without it a key that expired by the + disables it). With `Security:Acl:Enabled` false both triggers still run, but every verdict goes through + the creation gate's own seam (`Permits` → `AuthorizeIfRequired`), which bypasses local grants — so an + ungranted (e.g. Anonymous) subscription admitted with the flag off is **never** stood down by a tick or a + deploy; only gRPC-data projected / imported-condition items, gated in both modes, can lapse (#972 — between + `8ad03e9c5` and the fix, the pass enforced grants with the flag off). Without the timer a key that expired by the clock kept streaming until a deployment happened to land — **indefinitely** on a fleet that has been deployed once and left running, which is exactly the shape a production fleet settles into. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/AclOptions.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/AclOptions.cs index 11a57c300..0d3eba3ce 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/AclOptions.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core/Authorization/AclOptions.cs @@ -56,8 +56,10 @@ public sealed class AclOptions /// /// /// 0 or negative disables the timer, leaving revalidation deploy-triggered only (the - /// previous behaviour). The timer is inert while is false: the - /// pass early-returns when ACL enforcement is off. + /// previous behaviour). While is false the pass still runs but stands no + /// locally-gated item down — it asks the creation gate's own seam, which bypasses local grants + /// with the flag off (Gitea #972); only gRPC-data projected / imported-condition items, whose gates + /// apply in both modes, can lapse. /// /// public int RevalidationIntervalSeconds { get; set; } = 60; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs index f682116d1..922af0a3d 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/OpcUa/OtOpcUaServerHostedService.cs @@ -580,9 +580,13 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl /// Arms the clock-driven monitored-item revalidation tick (arch-review 03/S19). /// /// - /// Created unconditionally: the pass it drives early-returns unless the ACL gate is wired AND - /// Security:Acl:Enabled is on, so it stays inert on the default configuration, and - /// RevalidationIntervalSeconds = 0 arms no timer at all. + /// Created unconditionally, and the pass it drives RUNS in every mode: it walks every live item and + /// asks the creation gate's own seam (OtOpcUaNodeManager.Permits). With + /// Security:Acl:Enabled off that seam bypasses local grants, so on the default configuration + /// the pass stands nothing down — only gRPC-data projected / imported-condition items, whose gates + /// apply in both modes, can lapse (Gitea #972: an earlier remark claimed the pass early-returned with + /// the flag off; it did not, and it enforced grants). RevalidationIntervalSeconds = 0 arms no + /// timer at all. /// /// The node manager is resolved per tick rather than captured: is /// replaced across a restart, and a captured reference would go on revalidating a dead diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ProjectedOriginAccess.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ProjectedOriginAccess.cs index 63a2b5fa8..ac92d5d89 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ProjectedOriginAccess.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.ProjectedOriginAccess.cs @@ -34,7 +34,7 @@ public sealed partial class OtOpcUaNodeManager : IReadAsyncNodeManager, ICreateM async ValueTask IReadAsyncNodeManager.ReadAsync(OperationContext context, double maxAge, ArrayOf nodesToRead, IList values, IList errors, CancellationToken cancellationToken) { - if (SecurityFilteringActive && ProjectedDataAccess is { } access && IdentityOf(context) is { } identity) + if (ProjectedDataAccess is { } access && IdentityOf(context) is { } identity) { try { await ReadProjectedFromOriginAsync(context, maxAge, nodesToRead, values, errors, access, identity, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (ex is not OutOfMemoryException) @@ -246,7 +246,7 @@ public sealed partial class OtOpcUaNodeManager : IReadAsyncNodeManager, ICreateM IList errors, IList filterErrors, IList monitoredItems, bool createDurable, MonitoredItemIdFactory monitoredItemIdFactory, CancellationToken cancellationToken) { - if (SecurityFilteringActive && ProjectedDataAccess is { } access && IdentityOf(context) is { } identity) + if (ProjectedDataAccess is { } access && IdentityOf(context) is { } identity) { try { await RenewLapsedProjectedItemsAsync(context, itemsToCreate, access, identity, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (ex is not OutOfMemoryException) diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs index 146b3636d..a5fe47ec7 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/OtOpcUaNodeManager.cs @@ -845,7 +845,16 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage } } - private bool SecurityFilteringActive => AclEnforced || _mappedSubjectResolver is not null || NamespaceIndexes.Count >= 4; + // Gitea #972: there is deliberately NO "is filtering active" switch on the request seams (Read, Browse, + // TranslateBrowsePath, CreateMonitoredItems, SubscribeToEvents, SetMonitoringMode, HistoryRead) or on the + // revalidation pass. The former `SecurityFilteringActive` toggle carried an `|| NamespaceIndexes.Count >= 4` term + // (8ad03e9c5) that was ALWAYS true — the projected Raw/UNS and imported-condition namespaces are registered + // unconditionally — so every seam already ran its gated path, and those paths are load-bearing beyond ACLs: projected + // Value reads/subscriptions route through ProjectedDataAccess there, and projected/imported nodes fail closed there. + // The `Security:Acl:Enabled=false` bypass lives in ONE place, `Permits` → `DataPlaneAuthorizer.AuthorizeIfRequired` + // (localBypass: !Enabled), and every gated decision — including the revalidation pass + // (IsSubscriptionStillPermitted) — must go through it. The toggle hid that: the pass called the bypass-less + // `IsAllowedCached` and so enforced grants with the flag off (review 2026-12-02 U-1). /// /// True when a wired authorizer is switched on — i.e. when ACL grants, rather than the server-wide @@ -6349,73 +6358,70 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage IList values, IList errors) { - if (SecurityFilteringActive) + var identity = IdentityOf(context); + var denied = 0; + + for (var ii = 0; ii < nodesToRead.Count; ii++) { - var identity = IdentityOf(context); - var denied = 0; - - for (var ii = 0; ii < nodesToRead.Count; ii++) + var projected = nodesToRead[ii]; + if (projected.Processed || projected.AttributeId != Attributes.Value || !IsProjectedDescendant(projected.NodeId)) continue; + projected.Processed = true; + var access = ProjectedDataAccess; + IProjectedDemandLease? demand = null; + try { - var projected = nodesToRead[ii]; - if (projected.Processed || projected.AttributeId != Attributes.Value || !IsProjectedDescendant(projected.NodeId)) continue; - projected.Processed = true; - var access = ProjectedDataAccess; - IProjectedDemandLease? demand = null; - try + if (identity is null || access is null || !access.TryAcquire(projected.NodeId, identity, DataOperations.Read, out demand) || + demand is null || !demand.IsValid) { - if (identity is null || access is null || !access.TryAcquire(projected.NodeId, identity, DataOperations.Read, out demand) || - demand is null || !demand.IsValid) + demand?.Dispose(); demand = null; + // #922: a lapsed metadata lease is not an authorization failure. A caller granted the node gets the same + // retryable answer as a cold read while the lease renews on demand (off this thread, no Lock held). + var lapse = identity is null || access is null ? ProjectedLapseOutcome.Denied + : access.RenewLapsed(projected.NodeId, identity, DataOperations.Read, out _); + if (lapse == ProjectedLapseOutcome.Denied) { - demand?.Dispose(); demand = null; - // #922: a lapsed metadata lease is not an authorization failure. A caller granted the node gets the same - // retryable answer as a cold read while the lease renews on demand (off this thread, no Lock held). - var lapse = identity is null || access is null ? ProjectedLapseOutcome.Denied - : access.RenewLapsed(projected.NodeId, identity, DataOperations.Read, out _); - if (lapse == ProjectedLapseOutcome.Denied) - { - errors[ii] = StatusCodes.BadUserAccessDenied; - values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied); - } - else values[ii] = new DataValue(Variant.Null, lapse == ProjectedLapseOutcome.Renewing - ? StatusCodes.BadWaitingForInitialData : StatusCodes.BadResourceUnavailable); - continue; + errors[ii] = StatusCodes.BadUserAccessDenied; + values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied); } - if (TryServeProjectedFromCache(projected.NodeId, demand, maxAge, out var cachedValue)) { values[ii] = cachedValue; continue; } - var started = access.Clock.GetTimestamp(); - var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024); - if (access.ScheduleRead(demand, budget, started)) demand = null; // ownership transfers only on admission - values[ii] = new DataValue(Variant.Null, StatusCodes.BadWaitingForInitialData); - } - catch (Exception) - { - errors[ii] = StatusCodes.BadUserAccessDenied; - values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied); - } - finally { demand?.Dispose(); } - } - - for (var ii = 0; ii < nodesToRead.Count; ii++) - { - var nodeToRead = nodesToRead[ii]; - if (nodeToRead.Processed || !OwnsNamespace(nodeToRead.NodeId)) continue; - if (Permits(identity, OpcUaOperation.Read, nodeToRead.NodeId)) continue; - - nodeToRead.Processed = true; - // #922: an attribute of a projected node whose lease lapsed — retryable while it renews, never access-denied. - if (identity is not null && IsProjectedDescendant(nodeToRead.NodeId) && ProjectedDataAccess is { } lapsedAccess && - ClassifyProjectedLapse(lapsedAccess, nodeToRead.NodeId, identity, DataOperations.Read) != ProjectedLapseOutcome.Denied) - { - values[ii] = new DataValue(Variant.Null, StatusCodes.BadResourceUnavailable); + else values[ii] = new DataValue(Variant.Null, lapse == ProjectedLapseOutcome.Renewing + ? StatusCodes.BadWaitingForInitialData : StatusCodes.BadResourceUnavailable); continue; } + if (TryServeProjectedFromCache(projected.NodeId, demand, maxAge, out var cachedValue)) { values[ii] = cachedValue; continue; } + var started = access.Clock.GetTimestamp(); + var budget = new DataBudget(TimeSpan.FromSeconds(5), 1, 4 * 1024 * 1024); + if (access.ScheduleRead(demand, budget, started)) demand = null; // ownership transfers only on admission + values[ii] = new DataValue(Variant.Null, StatusCodes.BadWaitingForInitialData); + } + catch (Exception) + { errors[ii] = StatusCodes.BadUserAccessDenied; values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied); - denied++; } - - LogAclFiltering("Read", identity, denied, nodesToRead.Count); + finally { demand?.Dispose(); } } + for (var ii = 0; ii < nodesToRead.Count; ii++) + { + var nodeToRead = nodesToRead[ii]; + if (nodeToRead.Processed || !OwnsNamespace(nodeToRead.NodeId)) continue; + if (Permits(identity, OpcUaOperation.Read, nodeToRead.NodeId)) continue; + + nodeToRead.Processed = true; + // #922: an attribute of a projected node whose lease lapsed — retryable while it renews, never access-denied. + if (identity is not null && IsProjectedDescendant(nodeToRead.NodeId) && ProjectedDataAccess is { } lapsedAccess && + ClassifyProjectedLapse(lapsedAccess, nodeToRead.NodeId, identity, DataOperations.Read) != ProjectedLapseOutcome.Denied) + { + values[ii] = new DataValue(Variant.Null, StatusCodes.BadResourceUnavailable); + continue; + } + errors[ii] = StatusCodes.BadUserAccessDenied; + values[ii] = new DataValue(Variant.Null, StatusCodes.BadUserAccessDenied); + denied++; + } + + LogAclFiltering("Read", identity, denied, nodesToRead.Count); + base.Read(context, maxAge, nodesToRead, values, errors); } @@ -6445,7 +6451,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage var projectedParent = (continuationPoint?.NodeToBrowse as NodeHandle)?.NodeId; if (projectedParent is not null && continuationPoint is not null && ProjectedBrowseAccess is { } browseAccess) { - if (SecurityFilteringActive && !Permits(IdentityOf(context), OpcUaOperation.Browse, projectedParent.Value)) + if (!Permits(IdentityOf(context), OpcUaOperation.Browse, projectedParent.Value)) throw new ServiceResultException(StatusCodes.BadUserAccessDenied); var result = browseAccess.GetOrSchedule(new(projectedParent.Value, IdentityOf(context), continuationPoint, ProjectedBrowseClock.GetTimestamp())); if (result == global::ZB.MOM.WW.OtOpcUa.OpcUaServer.ProjectedBrowseReadiness.Pending) @@ -6457,7 +6463,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage } if (projectedParent is not null && ProjectedBrowseReadiness is { } readiness) { - if (SecurityFilteringActive && !Permits(IdentityOf(context), OpcUaOperation.Browse, projectedParent.Value)) + if (!Permits(IdentityOf(context), OpcUaOperation.Browse, projectedParent.Value)) throw new ServiceResultException(StatusCodes.BadUserAccessDenied); var status = readiness(projectedParent.Value); if (status == global::ZB.MOM.WW.OtOpcUa.OpcUaServer.ProjectedBrowseReadiness.Pending) @@ -6467,12 +6473,6 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage if (status == global::ZB.MOM.WW.OtOpcUa.OpcUaServer.ProjectedBrowseReadiness.InvalidContinuation) throw new ServiceResultException(StatusCodes.BadContinuationPointInvalid); } - if (!SecurityFilteringActive) - { - base.Browse(context, ref continuationPoint!, references); - return; - } - var identity = IdentityOf(context); // NodeToBrowse holds the MANAGER HANDLE the master node manager resolved — a NodeHandle for this // manager — not a NodeState. The declared type is `object`, so casting it to the wrong thing @@ -6532,12 +6532,6 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage IList targetIds, IList unresolvedTargetIds) { - if (!SecurityFilteringActive) - { - base.TranslateBrowsePath(context, sourceHandle, relativePath, targetIds, unresolvedTargetIds); - return; - } - var identity = IdentityOf(context); if (sourceHandle is NodeHandle handle @@ -6587,43 +6581,39 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage bool createDurable, MonitoredItemIdFactory monitoredItemIdFactory) { - RoleCarryingUserIdentity? identity = null; List? projectedAdmitted = null; - if (SecurityFilteringActive) + var identity = IdentityOf(context); + var denied = 0; + + for (var ii = 0; ii < itemsToCreate.Count; ii++) { - identity = IdentityOf(context); - var denied = 0; - - for (var ii = 0; ii < itemsToCreate.Count; ii++) + var item = itemsToCreate[ii]; + var target = item.ItemToMonitor?.NodeId; + if (item.Processed || !OwnsNamespace(target)) continue; + if (target is { } projected && IsProjectedDescendant(projected) && identity is not null && ProjectedDataAccess is { } access && + item.ItemToMonitor?.AttributeId == Attributes.Value) { - var item = itemsToCreate[ii]; - var target = item.ItemToMonitor?.NodeId; - if (item.Processed || !OwnsNamespace(target)) continue; - if (target is { } projected && IsProjectedDescendant(projected) && identity is not null && ProjectedDataAccess is { } access && - item.ItemToMonitor?.AttributeId == Attributes.Value) + // #940: a refused projected item is answered PER ITEM here (outside Lock), classified like Read: a lapse the + // caller is granted is retryable (its renewal was awaited by CreateMonitoredItemsAsync, or starts now), only a + // real refusal is BadUserAccessDenied. Thrown from the item manager instead, it faulted the whole request. + if (ProjectedSubscribeRefusal(access, projected, identity) is { } refusal) { - // #940: a refused projected item is answered PER ITEM here (outside Lock), classified like Read: a lapse the - // caller is granted is retryable (its renewal was awaited by CreateMonitoredItemsAsync, or starts now), only a - // real refusal is BadUserAccessDenied. Thrown from the item manager instead, it faulted the whole request. - if (ProjectedSubscribeRefusal(access, projected, identity) is { } refusal) - { - item.Processed = true; - errors[ii] = refusal; - if (refusal.Code == StatusCodes.BadUserAccessDenied.Code) denied++; - } - else (projectedAdmitted ??= []).Add(ii); - continue; + item.Processed = true; + errors[ii] = refusal; + if (refusal.Code == StatusCodes.BadUserAccessDenied.Code) denied++; } - if (Permits(identity, OpcUaOperation.CreateMonitoredItems, target!.Value)) continue; - - item.Processed = true; - errors[ii] = StatusCodes.BadUserAccessDenied; - denied++; + else (projectedAdmitted ??= []).Add(ii); + continue; } + if (Permits(identity, OpcUaOperation.CreateMonitoredItems, target!.Value)) continue; - LogAclFiltering("CreateMonitoredItems", identity, denied, itemsToCreate.Count); + item.Processed = true; + errors[ii] = StatusCodes.BadUserAccessDenied; + denied++; } + LogAclFiltering("CreateMonitoredItems", identity, denied, itemsToCreate.Count); + base.CreateMonitoredItems( context, subscriptionId, publishingInterval, timestampsToReturn, itemsToCreate, errors, filterErrors, monitoredItems, createDurable, monitoredItemIdFactory); @@ -6698,7 +6688,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage if (!ImportedNotifierAdmits(IdentityOf(context), notifierId)) return StatusCodes.BadUserAccessDenied; PromoteProjectedEventFolder(notifierId); // A4 F4: admitted ⇒ a notifier, even if it materialised before its authority } - else if (SecurityFilteringActive && !unsubscribe + else if (!unsubscribe && IsHandleInNamespace(sourceId) is { } source && !Permits(IdentityOf(context), OpcUaOperation.CreateMonitoredItems, source.NodeId)) { @@ -6785,7 +6775,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage MonitoringMode monitoringMode, NodeHandle handle) { - if (SecurityFilteringActive && monitoringMode != MonitoringMode.Disabled + if (monitoringMode != MonitoringMode.Disabled && !(monitoredItem is ProjectedMonitoredItem projected && projected.HasCurrentDemand) && !Permits(IdentityOf(context), OpcUaOperation.CreateMonitoredItems, handle.NodeId)) { @@ -8747,7 +8737,6 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage public void RevalidateMonitoredItems() { - if (!SecurityFilteringActive) return; if (_liveItems.IsEmpty && _eventItems.IsEmpty) return; var now = UtcNow; @@ -8757,7 +8746,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage // Pass-local, so single-threaded by construction. A concurrent deployment can advance the // generation mid-pass and leave later items decided on the earlier one — exactly as the // un-memoized walk already could, and the change that advanced it runs its own pass. - var verdicts = new Dictionary<(string Session, AddressSpaceRealm Realm, string Node), bool>(); + var verdicts = new Dictionary<(string Session, ushort Namespace, string Node), bool>(); foreach (var (item, tracked) in _liveItems) { @@ -8831,7 +8820,8 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage if (stoodDown > 0 || restored > 0) { - _authorizer!.LogFiltered( + // #972: a projected item can stand down with no authorizer wired (its demand lapsed) — never dereference it blind. + _authorizer?.LogFiltered( "RevalidateSubscriptions", principal: null, stoodDown, _liveItems.Count); } @@ -8881,7 +8871,7 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage /// /// private (int StoodDown, int Restored) RevalidateEventItems( - Dictionary<(string Session, AddressSpaceRealm Realm, string Node), bool> verdicts) + Dictionary<(string Session, ushort Namespace, string Node), bool> verdicts) { var stoodDown = 0; var restored = 0; @@ -8936,9 +8926,17 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage /// /// The session key is ApiKeyId ?? Principal — the same derivation /// uses for its own decision cache, so this memo is - /// never coarser than the cache it sits in front of. The realm is part of the key for the same - /// reason it is part of the authorizer's: the raw and UNS namespaces have independent string - /// identifier spaces, so an identifier alone does not name a node. + /// never coarser than the cache it sits in front of. The namespace INDEX is part of the key (not + /// the realm, which folds the projected and imported-condition namespaces into Raw/UNS): the five + /// registered namespaces have independent string identifier spaces, so an identifier alone does + /// not name a node. + /// + /// + /// ⚠️ The verdict is , the creation gate's own seam (Gitea #972). It is + /// the one place the Security:Acl:Enabled=false bypass lives; with the flag off a local + /// node's verdict is therefore always "allowed" and the pass stands nothing down except what the + /// mapped/imported gates (which apply in both modes) refuse. Asking the authorizer directly — as + /// this method did between 8ad03e9c5 and #972 — enforces grants with the flag off. /// /// /// Anything the key cannot be built from — no role-carrying identity, no principal, a node @@ -8959,25 +8957,23 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage private bool IsSubscriptionStillPermitted( RoleCarryingUserIdentity? identity, NodeId nodeId, - Dictionary<(string Session, AddressSpaceRealm Realm, string Node), bool> verdicts) + Dictionary<(string Session, ushort Namespace, string Node), bool> verdicts) { - var realm = RealmOf(nodeId); - if (_mappedSubjectResolver is not null) - return Permits(identity, OpcUaOperation.CreateMonitoredItems, nodeId); - + // #972: the SAME question the creation gate asks, through the SAME seam — `Permits` carries the + // `Security:Acl:Enabled=false` bypass (AuthorizeIfRequired), the mapped/imported classifiers, and the + // no-authorizer case. The bypass-less `IsAllowedCached` used here before enforced grants with the flag off, + // standing every ungranted subscription (Anonymous included) down on the next tick or deploy. if (identity is null || (identity.ApiKeyId ?? identity.Principal) is not { Length: > 0 } sessionKey || !nodeId.TryGetValue(out string identifier) || identifier.Length == 0) { - return _authorizer!.IsAllowedCached( - identity, OpcUaOperation.CreateMonitoredItems, nodeId, realm); + return Permits(identity, OpcUaOperation.CreateMonitoredItems, nodeId); } - var key = (sessionKey, realm, identifier); + var key = (sessionKey, nodeId.NamespaceIndex, identifier); if (verdicts.TryGetValue(key, out var memoized)) return memoized; - var permitted = _authorizer!.IsAllowedCached( - identity, OpcUaOperation.CreateMonitoredItems, nodeId, realm); + var permitted = Permits(identity, OpcUaOperation.CreateMonitoredItems, nodeId); verdicts[key] = permitted; return permitted; } @@ -9045,8 +9041,6 @@ public sealed partial class OtOpcUaNodeManager : CustomNodeManager2, INodeManage IList results, IList errors) { - if (!SecurityFilteringActive) return nodesToProcess; - var identity = (context as ISessionOperationContext)?.UserIdentity as RoleCarryingUserIdentity ?? context.OperationContext?.UserIdentity as RoleCarryingUserIdentity; diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/AclEventSubscriptionEnforcementTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/AclEventSubscriptionEnforcementTests.cs index 79f3be8eb..749632e44 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/AclEventSubscriptionEnforcementTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/AclEventSubscriptionEnforcementTests.cs @@ -274,6 +274,83 @@ public sealed class AclEventSubscriptionEnforcementTests finally { await rig.DisposeAsync(); } } + /// + /// Gitea #972 (review U-1): with Security:Acl:Enabled=false an Anonymous folder event item whose + /// session holds no grant stays attached — and keeps receiving alarms — across repeated revalidation ticks + /// and a deployment that carries no grants at all. + /// + /// + /// The regression silently unsubscribed the item from its notifier on the first tick (an event item is not + /// told). AttachedEventItems is the direct observable; the post-deploy transition is the delivery one. + /// + [Fact] + public async Task With_acl_enforcement_off_an_ungranted_folder_item_survives_revalidation_and_a_deploy() + { + var ct = TestContext.Current.CancellationToken; + var rig = await Rig.StartAsync("AclEventOffSurvive", ct); + try + { + // The only grant names a key principal; the anonymous session holds nothing. + var state = rig.Enforce(enabled: false, [], ClusterGrant(KeyPrincipal, "acl-key")); + rig.Materialise(); + + using var session = await rig.ConnectAsync(anonymous: true, ct); + var events = new EventCollector(); + var subscription = await CreateSubscriptionAsync(session, events, ct); + var item = AddEventItem(subscription, rig.UnsNodeId(session, EqA)); + await subscription.ApplyChangesAsync(ct); + item.Status.Error.ShouldBeNull(); + + rig.Transition("t1", active: true); + await WaitUntilAsync(() => events.Has(item, "t1")); + rig.AttachedEventItems.ShouldBe(1); + + for (var tick = 0; tick < 5; tick++) rig.TickRevalidation(); + state.Apply(Cluster, "rev-2", [], [], ScopePaths(), + ServerEventRig.EquipmentOwnerPaths(), ServerEventRig.ScriptedAlarmOwners(), ServerEventRig.FolderScopes(), ServerEventRig.TagReferences()); + rig.AttachedEventItems.ShouldBe(1); + + rig.Transition("t2", active: false); + await WaitUntilAsync(() => events.Has(item, "t2")); + + await subscription.DeleteAsync(true, ct); + } + finally { await rig.DisposeAsync(); } + } + + /// + /// The positive control for the flag-off folder-item test: the same item, with enforcement switched ON + /// before the next tick, is detached from its notifier — the flag-off survival is the bypass, not a pass + /// that never reaches event items. + /// + [Fact] + public async Task Enabling_enforcement_detaches_the_same_ungranted_folder_item() + { + var ct = TestContext.Current.CancellationToken; + var rig = await Rig.StartAsync("AclEventOnDetach", ct); + try + { + rig.Enforce(enabled: false, [], ClusterGrant(KeyPrincipal, "acl-key")); + rig.Materialise(); + + using var session = await rig.ConnectAsync(anonymous: true, ct); + var events = new EventCollector(); + var subscription = await CreateSubscriptionAsync(session, events, ct); + var item = AddEventItem(subscription, rig.UnsNodeId(session, EqA)); + await subscription.ApplyChangesAsync(ct); + item.Status.Error.ShouldBeNull(); + rig.AttachedEventItems.ShouldBe(1); + + rig.Enforce(enabled: true, [], ClusterGrant(KeyPrincipal, "acl-key")); + rig.TickRevalidation(); + + rig.AttachedEventItems.ShouldBe(0); + + await subscription.DeleteAsync(true, ct); + } + finally { await rig.DisposeAsync(); } + } + // ─────────────────── Server-object (i=2253) subscriptions — Gitea #586 ─────────────────── /// diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/AclSubscriptionEnforcementTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/AclSubscriptionEnforcementTests.cs index d63dc53f8..174f61b30 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/AclSubscriptionEnforcementTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests/AclSubscriptionEnforcementTests.cs @@ -163,6 +163,80 @@ public sealed class AclSubscriptionEnforcementTests finally { await rig.DisposeAsync(); } } + /// + /// Gitea #972 (review U-1): with Security:Acl:Enabled=false an Anonymous subscription whose session + /// holds no Subscribe grant keeps streaming across repeated revalidation ticks AND a deployment. + /// + /// + /// Subscribe is ungated with the flag off (.claude/rules/data-plane-auth.md), so creation admits the + /// item; the regression stood it down again on the next 60 s tick or deploy with BadUserAccessDenied. + /// The deploy carries NO grants at all, so a pass that consulted the trie would certainly deny. + /// is the positive control. + /// + [Fact] + public async Task With_enforcement_off_an_ungranted_subscription_survives_revalidation_and_a_deploy() + { + var ct = TestContext.Current.CancellationToken; + var rig = await Rig.StartAsync("AclOffSurvive", ct); + try + { + // Read only — deliberately NOT Subscribe — and the flag off. + var state = rig.Enforce(Grant(NodePermissions.Read), enabled: false); + rig.Materialise(); + rig.Write(1); + + using var session = await rig.ConnectAsync(ct); + var (subscription, received) = await rig.SubscribeAsync(session, ct); + await WaitUntilAsync(() => received.Any(v => Equals(v.ClrValue()!, 1f)), TimeSpan.FromSeconds(10)); + + // N clock-axis ticks, then the deployment axis (Changed ⇒ RevalidateMonitoredItems) with no grants. + for (var tick = 0; tick < 5; tick++) rig.Revalidate(); + state.Apply(Cluster, "rev-2", [], [], NoScopes); + + rig.Write(2); + await WaitUntilAsync(() => received.Any(v => Equals(v.ClrValue()!, 2f)), TimeSpan.FromSeconds(10)); + rig.Revalidate(); + rig.Write(3); + await WaitUntilAsync(() => received.Any(v => Equals(v.ClrValue()!, 3f)), TimeSpan.FromSeconds(10)); + received.ShouldNotContain(v => v.StatusCode.Code == StatusCodes.BadUserAccessDenied); + + await subscription.DeleteAsync(true, ct); + } + finally { await rig.DisposeAsync(); } + } + + /// + /// The positive control for the flag-off survival test: the same session, grant and subscription, with + /// enforcement switched ON before the next tick, are stood down and told why — so the flag-off silence is + /// the bypass at work, not a pass that never reaches the item. + /// + [Fact] + public async Task Enabling_enforcement_stands_down_the_same_ungranted_subscription() + { + var ct = TestContext.Current.CancellationToken; + var rig = await Rig.StartAsync("AclOnStandDown", ct); + try + { + rig.Enforce(Grant(NodePermissions.Read), enabled: false); + rig.Materialise(); + rig.Write(1); + + using var session = await rig.ConnectAsync(ct); + var (subscription, received) = await rig.SubscribeAsync(session, ct); + await WaitUntilAsync(() => received.Any(v => Equals(v.ClrValue()!, 1f)), TimeSpan.FromSeconds(10)); + + rig.Enforce(Grant(NodePermissions.Read), enabled: true); + rig.Revalidate(); + + await WaitUntilAsync( + () => received.Any(v => v.StatusCode.Code == StatusCodes.BadUserAccessDenied), + TimeSpan.FromSeconds(10)); + + await subscription.DeleteAsync(true, ct); + } + finally { await rig.DisposeAsync(); } + } + /// A principal with no Subscribe bit cannot create a monitored item at all. [Fact] public async Task Subscribing_without_the_permission_is_refused() @@ -327,7 +401,8 @@ public sealed class AclSubscriptionEnforcementTests /// Switches enforcement on with one grant, returning the state so a test can redeploy. public DataPlaneAuthorityState Enforce( - NodeAcl grant, IReadOnlyDictionary>? scopes = null) + NodeAcl grant, IReadOnlyDictionary>? scopes = null, + bool enabled = true) { var state = new DataPlaneAuthorityState(); state.Apply(Cluster, "rev-1", [], [grant], scopes ?? NoScopes); @@ -337,9 +412,12 @@ public sealed class AclSubscriptionEnforcementTests // request and none that revokes. Nm.DataPlaneAuthority = state; Nm.Authorizer = new DataPlaneAuthorizer( - state, new TriePermissionEvaluator(state.Tries), enabled: true, NullLogger.Instance); + state, new TriePermissionEvaluator(state.Tries), enabled, NullLogger.Instance); return state; } + + /// One clock-axis revalidation pass — what the host's AclRevalidationTimer tick runs. + public void Revalidate() => Nm.RevalidateMonitoredItems(); public void Materialise() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerStage6EnforcementTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerStage6EnforcementTests.cs index 490ac7d7f..6ba6452a6 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerStage6EnforcementTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/NodeManagerStage6EnforcementTests.cs @@ -733,8 +733,119 @@ public sealed class NodeManagerStage6EnforcementTests : IDisposable finally { await host.DisposeAsync(); } } + /// + /// Gitea #972 (review U-1): with Security:Acl:Enabled=false a revalidation pass — the host's + /// 60 s AclRevalidationTimer tick, or a deployment — must stand NOTHING down. Subscribe is + /// ungated with the flag off, so an item admitted at creation must stay admitted on every later pass. + /// + /// + /// Regression from 8ad03e9c5: the pass asked IsAllowedCached, which evaluates the grant trie + /// with no flag-off bypass, so a principal holding no Subscribe grant (a narrow key, or Anonymous) was + /// queued BadUserAccessDenied and detached on the first tick. Several passes are run because the + /// stand-down is a one-shot per item — a single pass would also catch it, but N passes pin that nothing + /// accumulates (the memo is pass-local). + /// is the positive control: the same items, the same grants, only the flag differs. + /// + [Fact] + public async Task Revalidation_stands_nothing_down_while_enforcement_is_off() + { + var (host, server) = await BootAsync(); + try + { + var nm = server.NodeManager!; + nm.Authorizer = Authorizer(enabled: false, GrantOn(NodePermissions.None)); + var nodeId = Variable(nm, "Plant/Modbus/dev1/Speed"); + + var items = new[] + { + TrackItem(nm, nodeId, Identity()), // a principal whose grant carries no Subscribe bit + TrackItem(nm, nodeId, AnonymousIdentity()), // Anonymous, holding no grant at all + }; + + for (var pass = 0; pass < 5; pass++) nm.RevalidateMonitoredItems(); + + items.ShouldAllBe(i => i.Denials == 0); + } + finally { await host.DisposeAsync(); } + } + + /// + /// #972: the flag-off pass must not consult the authority at all — on a node with no artifact yet (blank + /// ClusterId) the trie walk denies every session outright, so the regression stood down EVERY item. + /// + [Fact] + public async Task Revalidation_stands_nothing_down_while_enforcement_is_off_even_with_no_authority() + { + var (host, server) = await BootAsync(); + try + { + var nm = server.NodeManager!; + var state = new DataPlaneAuthorityState(); // never applied: no cluster identity, no trie + nm.DataPlaneAuthority = state; + nm.Authorizer = new DataPlaneAuthorizer( + state, new TriePermissionEvaluator(state.Tries), enabled: false, NullLogger.Instance); + + var item = TrackItem(nm, Variable(nm, "Plant/Modbus/dev1/Speed"), AnonymousIdentity()); + + for (var pass = 0; pass < 5; pass++) nm.RevalidateMonitoredItems(); + + item.Denials.ShouldBe(0); + } + finally { await host.DisposeAsync(); } + } + + /// + /// #972: a pass with no authorizer wired (the node manager's documented "not wired ⇒ not enabled") is a + /// no-op, never a out of the deploy thread or the timer. + /// + [Fact] + public async Task Revalidation_with_no_authorizer_wired_stands_nothing_down() + { + var (host, server) = await BootAsync(); + try + { + var nm = server.NodeManager!; + nm.Authorizer.ShouldBeNull(); + + var item = TrackItem(nm, Variable(nm, "Plant/Modbus/dev1/Speed"), Identity()); + + Should.NotThrow(() => nm.RevalidateMonitoredItems()); + item.Denials.ShouldBe(0); + } + finally { await host.DisposeAsync(); } + } + + /// + /// The positive control for the flag-off cases above: the SAME grant (no Subscribe bit) and the same + /// identities with enforcement ON stand both items down on the first pass — so the flag-off silence is the + /// bypass at work, not a pass that never reaches its items. + /// + [Fact] + public async Task Revalidation_with_enforcement_on_stands_down_an_ungranted_item() + { + var (host, server) = await BootAsync(); + try + { + var nm = server.NodeManager!; + nm.Authorizer = Authorizer(enabled: true, GrantOn(NodePermissions.None)); + var nodeId = Variable(nm, "Plant/Modbus/dev1/Speed"); + + var items = new[] { TrackItem(nm, nodeId, Identity()), TrackItem(nm, nodeId, AnonymousIdentity()) }; + + for (var pass = 0; pass < 5; pass++) nm.RevalidateMonitoredItems(); + + // Exactly once each: a stood-down item is skipped by later passes rather than told again. + items.ShouldAllBe(i => i.Denials == 1); + } + finally { await host.DisposeAsync(); } + } + // ───────────────────────────── helpers ───────────────────────────── + /// An Anonymous session's identity, as the activation handler builds it (reserved principal, no key). + private static RoleCarryingUserIdentity AnonymousIdentity() => + new(new AnonymousIdentityToken(), [], OpcUaPrincipals.Anonymous, apiKeyId: null); + /// The public id of the key the clock-driven expiry cases authenticate with. private const string ExpiringKeyId = "k-expiry";