Merge #972: ACL revalidation honours Security:Acl:Enabled=false (no flag-off stand-downs); dead SecurityFilteringActive removed

This commit is contained in:
Joseph Doherty
2026-12-03 10:01:19 -05:00
9 changed files with 411 additions and 133 deletions
@@ -56,8 +56,10 @@ public sealed class AclOptions
/// </para>
/// <para>
/// <c>0</c> or negative disables the timer, leaving revalidation deploy-triggered only (the
/// previous behaviour). The timer is <b>inert while <see cref="Enabled"/> is false</b>: the
/// pass early-returns when ACL enforcement is off.
/// previous behaviour). While <see cref="Enabled"/> is false the pass still runs but <b>stands no
/// locally-gated item down</b> — 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.
/// </para>
/// </remarks>
public int RevalidationIntervalSeconds { get; set; } = 60;
@@ -580,9 +580,13 @@ public sealed class OtOpcUaServerHostedService : IHostedService, IAsyncDisposabl
/// Arms the clock-driven monitored-item revalidation tick (arch-review 03/S19).
/// </summary>
/// <remarks>
/// Created unconditionally: the pass it drives early-returns unless the ACL gate is wired AND
/// <c>Security:Acl:Enabled</c> is on, so it stays inert on the default configuration, and
/// <c>RevalidationIntervalSeconds = 0</c> 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 (<c>OtOpcUaNodeManager.Permits</c>). With
/// <c>Security:Acl:Enabled</c> 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). <c>RevalidationIntervalSeconds = 0</c> arms no
/// timer at all.
/// <para>
/// The node manager is resolved <b>per tick</b> rather than captured: <see cref="_server"/> is
/// replaced across a restart, and a captured reference would go on revalidating a dead
@@ -34,7 +34,7 @@ public sealed partial class OtOpcUaNodeManager : IReadAsyncNodeManager, ICreateM
async ValueTask IReadAsyncNodeManager.ReadAsync(OperationContext context, double maxAge, ArrayOf<ReadValueId> nodesToRead,
IList<DataValue> values, IList<ServiceResult> 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<ServiceResult> errors, IList<MonitoringFilterResult> filterErrors, IList<IMonitoredItem> 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)
@@ -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).
/// <summary>
/// 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<DataValue> values,
IList<ServiceResult> 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<ExpandedNodeId> targetIds,
IList<NodeId> 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<int>? 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
/// </para>
/// </remarks>
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
/// <para>
/// The session key is <c>ApiKeyId ?? Principal</c> — the same derivation
/// <see cref="Security.DataPlaneAuthorizer"/> 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.
/// </para>
/// <para>
/// ⚠️ <b>The verdict is <see cref="Permits"/>, the creation gate's own seam (Gitea #972).</b> It is
/// the one place the <c>Security:Acl:Enabled=false</c> 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 <c>8ad03e9c5</c> and #972 — enforces grants with the flag off.
/// </para>
/// <para>
/// 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<SdkHistoryReadResult> results,
IList<ServiceResult> errors)
{
if (!SecurityFilteringActive) return nodesToProcess;
var identity = (context as ISessionOperationContext)?.UserIdentity as RoleCarryingUserIdentity
?? context.OperationContext?.UserIdentity as RoleCarryingUserIdentity;