fix(opcua-acl): #972 revalidation no longer stands down subscriptions while Security:Acl:Enabled=false

IsSubscriptionStillPermitted now asks Permits(identity, CreateMonitoredItems, node) — the creation
gate's own seam and the one place the flag-off bypass lives — instead of the bypass-less
IsAllowedCached. Since 8ad03e9c5 the pass ran with the flag off (SecurityFilteringActive's
'|| NamespaceIndexes.Count >= 4' term was always true: five namespaces are always registered) and
stood every ungranted/Anonymous subscription down within 60 s or on the next deploy (review U-1).

- SecurityFilteringActive deleted: it was a dead toggle, and the gated request paths it guarded are
  also the projected-data routing path; Permits alone decides the flag.
- pass-local verdict memo keyed by namespace index (realm folded projected/imported ids into Raw/UNS).
- _authorizer null-guarded in the pass (no authorizer wired => no NRE).
- AclRevalidationTimer / AclOptions remarks, docs/security.md and the data-plane-auth rule corrected.

Tests: unit flag-off (keyed + Anonymous, empty authority, no authorizer) x5 passes with a flag-on
positive control; wire flag-off data + folder-event subscriptions survive 5 ticks + a no-grant deploy,
with flag-on controls on the same items.
This commit is contained in:
Joseph Doherty
2026-12-03 10:00:02 -05:00
parent 65fd71de7a
commit 85d479e23e
9 changed files with 411 additions and 133 deletions
+12 -4
View File
@@ -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
+5 -1
View File
@@ -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.
@@ -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;
@@ -274,6 +274,83 @@ public sealed class AclEventSubscriptionEnforcementTests
finally { await rig.DisposeAsync(); }
}
/// <summary>
/// Gitea #972 (review U-1): with <c>Security:Acl:Enabled=false</c> 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.
/// </summary>
/// <remarks>
/// The regression silently unsubscribed the item from its notifier on the first tick (an event item is not
/// told). <c>AttachedEventItems</c> is the direct observable; the post-deploy transition is the delivery one.
/// </remarks>
[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(); }
}
/// <summary>
/// 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.
/// </summary>
[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 ───────────────────
/// <summary>
@@ -163,6 +163,80 @@ public sealed class AclSubscriptionEnforcementTests
finally { await rig.DisposeAsync(); }
}
/// <summary>
/// Gitea #972 (review U-1): with <c>Security:Acl:Enabled=false</c> an Anonymous subscription whose session
/// holds no Subscribe grant keeps streaming across repeated revalidation ticks AND a deployment.
/// </summary>
/// <remarks>
/// Subscribe is ungated with the flag off (<c>.claude/rules/data-plane-auth.md</c>), so creation admits the
/// item; the regression stood it down again on the next 60 s tick or deploy with <c>BadUserAccessDenied</c>.
/// The deploy carries NO grants at all, so a pass that consulted the trie would certainly deny.
/// <see cref="Enabling_enforcement_stands_down_the_same_ungranted_subscription"/> is the positive control.
/// </remarks>
[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(); }
}
/// <summary>
/// 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.
/// </summary>
[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(); }
}
/// <summary>A principal with no Subscribe bit cannot create a monitored item at all.</summary>
[Fact]
public async Task Subscribing_without_the_permission_is_refused()
@@ -327,7 +401,8 @@ public sealed class AclSubscriptionEnforcementTests
/// <summary>Switches enforcement on with one grant, returning the state so a test can redeploy.</summary>
public DataPlaneAuthorityState Enforce(
NodeAcl grant, IReadOnlyDictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>? scopes = null)
NodeAcl grant, IReadOnlyDictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>? 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;
}
/// <summary>One clock-axis revalidation pass — what the host's <c>AclRevalidationTimer</c> tick runs.</summary>
public void Revalidate() => Nm.RevalidateMonitoredItems();
public void Materialise()
{
@@ -733,8 +733,119 @@ public sealed class NodeManagerStage6EnforcementTests : IDisposable
finally { await host.DisposeAsync(); }
}
/// <summary>
/// Gitea #972 (review U-1): with <c>Security:Acl:Enabled=false</c> a revalidation pass — the host's
/// 60 s <c>AclRevalidationTimer</c> 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.
/// </summary>
/// <remarks>
/// Regression from <c>8ad03e9c5</c>: the pass asked <c>IsAllowedCached</c>, which evaluates the grant trie
/// with no flag-off bypass, so a principal holding no Subscribe grant (a narrow key, or Anonymous) was
/// queued <c>BadUserAccessDenied</c> 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). <see cref="Revalidation_with_enforcement_on_stands_down_an_ungranted_item"/>
/// is the positive control: the same items, the same grants, only the flag differs.
/// </remarks>
[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(); }
}
/// <summary>
/// #972: the flag-off pass must not consult the authority at all — on a node with no artifact yet (blank
/// <c>ClusterId</c>) the trie walk denies every session outright, so the regression stood down EVERY item.
/// </summary>
[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(); }
}
/// <summary>
/// #972: a pass with no authorizer wired (the node manager's documented "not wired ⇒ not enabled") is a
/// no-op, never a <see cref="NullReferenceException"/> out of the deploy thread or the timer.
/// </summary>
[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(); }
}
/// <summary>
/// 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.
/// </summary>
[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 ─────────────────────────────
/// <summary>An Anonymous session's identity, as the activation handler builds it (reserved principal, no key).</summary>
private static RoleCarryingUserIdentity AnonymousIdentity() =>
new(new AnonymousIdentityToken(), [], OpcUaPrincipals.Anonymous, apiKeyId: null);
/// <summary>The public id of the key the clock-driven expiry cases authenticate with.</summary>
private const string ExpiringKeyId = "k-expiry";