Files
lmxopcua/src/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer/Security/DataPlaneAuthorizer.cs
T
Joseph Doherty dc6cc7779d feat(grpc-data): H3 SDK side of projected history
Projected variables advertise Historizing + the HistoryRead access bit (never
HistoryWrite) only when the definition says so. The Raw/Processed/AtTime
overrides split authorized handles: local ones go to the H1 port unchanged,
projected ones to IProjectedHistoryAccess, each written back to its own slot;
nothing waits under Lock. HistoryCursorKind.Remote stores the projection's
cursor in the SDK session store; disposing the point (session close, eviction,
releaseContinuationPoints, faulted request) releases it at the origin. Mapped
HistoryRead is opened deliberately in DataPlaneAuthorizer; other mapped
operations outside the allowlist stay closed.
2026-11-24 00:27:51 -05:00

931 lines
54 KiB
C#

using Microsoft.Extensions.Logging;
using Opc.Ua;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
/// <summary>
/// Turns an inbound OPC UA request into a node-scoped ACL decision. The one place
/// the address space's <see cref="NodeId"/> meets <see cref="IPermissionEvaluator"/>.
/// </summary>
/// <remarks>
/// <para>
/// <b>Dormant unless <see cref="Enabled"/>.</b> With <c>Security:Acl:Enabled</c> false —
/// the default — <see cref="Authorize"/> is never consulted and the node manager keeps its
/// server-wide role gates. See <see cref="AclOptions"/> for why the two are alternatives rather
/// than a chain.
/// </para>
/// <para>
/// <b>Every failure path denies.</b> No identity, no principal, no cluster identity, a NodeId
/// whose identifier is not a string, a trie that was never installed — each returns
/// <c>BadUserAccessDenied</c>. That is the only safe direction for a gate, but it also means a
/// wiring mistake presents as "everything is denied" rather than "everything is allowed", which
/// is loud. The install log at <c>OpcUaPublish</c> is where an operator confirms a trie exists at
/// all.
/// </para>
/// <para>
/// <b>Authorization state is built per call, not per session.</b> <see cref="UserAuthorizationState"/>
/// was designed for LDAP, where a directory can change group membership out of band and a
/// long-lived session must re-resolve on a timer. Under the API-key model nothing can change a
/// session's principals out of band — the principal comes from the key, and keys and grants both
/// ride the deployment artifact — so the only real invalidation signal is the generation stamp,
/// which a per-call construction picks up for free. The cost is one small record per write, alarm
/// command or HistoryRead, none of which are hot.
/// </para>
/// <para>
/// Stage 6's request-rate seams — Read, Browse, subscription creation — go through
/// <see cref="AuthorizeCached"/> instead, which memoizes the grant walk in
/// <see cref="Decisions"/>. That is a cache of the walk, <b>not</b> of the decision: the key's
/// revocation and expiry are re-checked on every call regardless, because expiry moves with the
/// clock rather than with a generation.
/// </para>
/// <para>
/// <see cref="UserAuthorizationState.IsStale"/> and
/// <see cref="UserAuthorizationState.NeedsRefresh"/> are vestigial here rather than load-bearing,
/// and a reader should not conclude from their presence that a freshness timer is doing anything.
/// They are switched off <b>explicitly</b> (<c>AuthCacheMaxStaleness = TimeSpan.MaxValue</c>) rather
/// than left to never be reached — see the comment at that line. Relying on "the stamp is always
/// fresh" was not safe: the stamp comes from this class's clock and the ceiling is checked against
/// the evaluator's, so any divergence between the two denied every request with a verdict that
/// looks exactly like "no grant matched".
/// </para>
/// </remarks>
public sealed class DataPlaneAuthorizer
{
/// <summary>
/// The single veto every denial returns. Logged, never explained to the client: the client gets an
/// undifferentiated <c>BadUserAccessDenied</c> so the server cannot be used to probe which nodes
/// exist or which grants a principal holds, and the operator debugging a denial reads the reason in
/// the log. Same posture as the authenticator's <c>DenyMessage</c>.
/// </summary>
/// <remarks>
/// <b>Shared rather than per-call, because <see cref="ServiceResult"/> is immutable to us.</b>
/// Verified by reflection against the pinned Opc.Ua.Core 1.5.378.106: every one of its properties
/// (<c>StatusCode</c>, <c>SymbolicId</c>, <c>NamespaceUri</c>, <c>LocalizedText</c>,
/// <c>AdditionalInfo</c>, <c>InnerResult</c>) has a <b>private</b> setter, and its only non-getter
/// method — <c>Append(StringBuilder)</c> — formats rather than mutates, so no code outside the type
/// can change an instance. The SDK itself publishes <c>ServiceResult.Good</c> and
/// <c>ServiceResult.Bad</c> as shared <c>static readonly</c> singletons, which is its own
/// endorsement of the pattern. Every call site here treats the result as an opaque value — it is
/// stored into an SDK errors array or returned — and none compares by reference.
/// </remarks>
private static readonly ServiceResult DeniedResult = new(StatusCodes.BadUserAccessDenied);
private readonly IDataPlaneAuthoritySource _authority;
private readonly DataOperationPolicy _policy;
private readonly ILogger _log;
private readonly TimeProvider _time;
/// <summary>Initializes a new instance of the <see cref="DataPlaneAuthorizer"/> class.</summary>
/// <param name="authority">The node's current data-plane authorization inputs.</param>
/// <param name="evaluator">The permission evaluator reading the tries built alongside those inputs.</param>
/// <param name="enabled">Whether ACL evaluation decides authorization (<c>Security:Acl:Enabled</c>).</param>
/// <param name="log">The logger.</param>
/// <param name="time">Time provider, injected for testability.</param>
public DataPlaneAuthorizer(
IDataPlaneAuthoritySource authority,
IPermissionEvaluator evaluator,
bool enabled,
ILogger log,
TimeProvider? time = null)
{
ArgumentNullException.ThrowIfNull(authority);
ArgumentNullException.ThrowIfNull(evaluator);
ArgumentNullException.ThrowIfNull(log);
_authority = authority;
_policy = new DataOperationPolicy(authority, evaluator, time);
_log = log;
_time = time ?? TimeProvider.System;
Enabled = enabled;
}
/// <summary>
/// True when ACL grants — rather than the server-wide role set — decide write, alarm-command and
/// HistoryRead authorization.
/// </summary>
public bool Enabled { get; }
/// <summary>The clock this gate evaluates key expiry against.</summary>
/// <remarks>
/// Exposed so the composition root's wiring can be asserted by reference. The remarks on
/// <c>UserAuthorizationState</c> record what a second, diverging clock costs: every request denied,
/// with a verdict indistinguishable from "no grant matched". One registered singleton threaded into
/// every consumer is the fix, and a test that cannot see which instance landed here cannot pin it.
/// </remarks>
public TimeProvider Clock => _time;
/// <summary>
/// Memoized grant walks for the request-rate seams. See
/// <see cref="SessionAclDecisionCache"/> for what it is and is not allowed to cache.
/// </summary>
public SessionAclDecisionCache Decisions { get; } = new();
/// <summary>
/// The live-address-space lookup that says how a UNS-namespace node is placed (Gitea #808), attached by the
/// node manager that owns the address space this authorizer gates. Null ⇒ every UNS identifier is split as a
/// path, the pre-#808 behaviour (a test authorizer used without a node manager).
/// </summary>
/// <remarks>
/// Read per decision, BEFORE the decision cache: the facts it reports (a folder's live ancestry, a scripted
/// condition's live owner binding) change with the address space rather than with the generation, so they
/// must never be memoized. What the cache then memoizes is only the grant walk at the RESOLVED scope, keyed on
/// that scope — which is a pure function of the generation. Must be cheap and non-throwing: it runs on every
/// Read / Browse / subscribe decision on a UNS node.
/// </remarks>
public Func<string, UnsAclSubject>? UnsSubjectResolver { get; set; }
/// <summary>Live catalog classification owned by the node manager, consulted before either local path resolver.</summary>
public Func<AddressSpaceRealm, string, MappedNodeResolution>? MappedSubjectResolver { get; set; }
/// <summary>Optional actual-namespace filter for projected subject classification.</summary>
public Func<NodeId, bool>? MappedNamespacePredicate { get; set; }
/// <summary>Checks a mapped subject even when local ACL enforcement is disabled.</summary>
public ServiceResult? AuthorizeIfRequired(RoleCarryingUserIdentity? identity, OpcUaOperation operation,
NodeId nodeId, AddressSpaceRealm realm, bool cached = true) =>
Evaluate(identity, operation, nodeId, realm, cached, localBypass: !Enabled);
/// <summary>Checks a deployed mapping's local anchor scope regardless of the legacy ACL switch.</summary>
public bool AuthorizeProjectedAnchor(RoleCarryingUserIdentity? identity, NodeScope scope)
{
if (identity is null) return false;
var caller = new DataCallerIdentity(identity.Principal, identity.ApiKeyId,
identity.CredentialVersion, identity.CredentialExpiresUtc);
return _policy.AuthorizeLocal(caller, OpcUaOperation.Browse, scope);
}
/// <summary>Checks a mapping without changing the legacy local role gate.</summary>
public bool TryAuthorizeMapped(RoleCarryingUserIdentity? identity, OpcUaOperation operation,
NodeId nodeId, AddressSpaceRealm realm, out ServiceResult? veto)
{
var resolver = MappedSubjectResolver;
if (MappedNamespacePredicate is { } predicate && !predicate(nodeId)) { veto = null; return false; }
if (resolver is null) { veto = null; return false; }
if (!nodeId.TryGetValue(out string identifier) || identifier.Length == 0 || identifier.Contains('\0'))
{ veto = DeniedResult; return true; }
MappedNodeResolution resolved;
try { resolved = resolver(realm, identifier); }
catch (Exception ex)
{
_log.LogWarning(ex, "Mapped subject catalog lookup failed");
veto = DeniedResult;
return true;
}
if (resolved is null) { veto = DeniedResult; return true; }
if (resolved.Kind == MappedNodeResolutionKind.Local) { veto = null; return false; }
if (resolved.Kind != MappedNodeResolutionKind.Mapped || identity is null || resolved.View is null
|| resolved.Live is null || resolved.Resolver is null || resolved.Lease is null
|| (realm == AddressSpaceRealm.Raw ? resolved.View.Realm != DataRealm.Raw : resolved.View.Realm != DataRealm.Uns))
{ veto = DeniedResult; return true; }
// The SDK owns the publish queue after admission. Its stock monitored item can emit queued values after a
// lease expires, so a periodic detach is not a final-send gate. Until P08 installs a verified publish-time
// gate, do not admit mapped data or event subscriptions at all.
if (operation == OpcUaOperation.CreateMonitoredItems) { veto = DeniedResult; return true; }
// H3: HistoryRead on a mapped node is opened DELIBERATELY — it needs the mapping's own HistoryRead bit (masked by the
// export's) AND a local NodePermissions.HistoryRead grant on the mapping scope, with ACLs on or off (plan §6). Every
// other mapped operation outside this allowlist (HistoryUpdate, alarm methods…) stays closed.
if (operation is not (OpcUaOperation.Browse or OpcUaOperation.Read or OpcUaOperation.WriteOperate or OpcUaOperation.WriteTune
or OpcUaOperation.WriteConfigure or OpcUaOperation.TransferSubscriptions or OpcUaOperation.HistoryRead))
{ veto = DeniedResult; return true; }
var caller = new DataCallerIdentity(identity.Principal, identity.ApiKeyId,
identity.CredentialVersion, identity.CredentialExpiresUtc);
try
{
veto = _policy.AuthorizeMapped(caller, operation, resolved.View, resolved.Live.Serving,
resolved.Live, resolved.Resolver, resolved.Lease) ? null : DeniedResult;
}
catch (Exception ex)
{
_log.LogWarning(ex, "Mapped subject proof failed");
veto = DeniedResult;
}
return true;
}
/// <summary>
/// The path segment appended below an owning equipment / folder for a node that is NOT a UNS reference
/// variable — a scripted condition and its children, a virtual tag (Gitea #808). It can never be a grant path
/// segment (those are entity names), so the walk confers exactly the grants on the owner or an ancestor of it:
/// a <c>Tag</c> grant beneath the same equipment never matches, and — the reason it is not simply the owner's
/// own path — the owner's Browse TRANSIT (an ancestor of a Tag grant) is not inherited, so a principal holding
/// only a Tag grant cannot enumerate the equipment's alarms and virtual tags by browsing.
/// </summary>
internal const string OwnedNodeSegment = DataScopeSubjects.OwnedNodeSegment;
/// <summary>
/// The single segment, directly under the UNS realm, that an identifier no live node holds is placed at
/// (Gitea #808 review): only a realm-wide grant reaches it, and — unlike the realm root itself — it carries no
/// Browse transit, so a narrow grantee is never handed a removed opaque id (a NodeDeleted model change, a
/// probe) and a removed id can never match a narrow grant on an unrelated entity that shares its name.
/// </summary>
internal const string UnknownNodeSegment = "\u0000unknown";
/// <summary>The depth of a UNS reference-variable id: <c>Area/Line/Equipment/EffectiveName</c>.</summary>
private const int ReferenceVariableSegments = 4;
/// <summary>
/// Authorizes <paramref name="operation"/> on <paramref name="nodeId"/> through the decision cache —
/// the entry point for Read, Browse and subscription creation, which ask the same question many
/// times per request.
/// </summary>
/// <remarks>
/// Identical in outcome to <see cref="Authorize"/>; it differs only in memoizing the grant walk and
/// in logging denials at Debug rather than Information. The quieter log is deliberate: a browse of a
/// large folder by an ungranted principal would otherwise emit one Information line per child. The
/// per-request summary the node manager logs is the operator-facing signal; this is the detail behind
/// it.
/// </remarks>
/// <param name="identity">The role-carrying identity off the SDK context, or null when the session carries none.</param>
/// <param name="operation">The operation being attempted.</param>
/// <param name="nodeId">The target node.</param>
/// <param name="realm">The namespace the node was resolved in.</param>
/// <returns><c>null</c> to proceed; otherwise the veto to return to the SDK.</returns>
public ServiceResult? AuthorizeCached(
RoleCarryingUserIdentity? identity,
OpcUaOperation operation,
NodeId nodeId,
AddressSpaceRealm realm)
=> Evaluate(identity, operation, nodeId, realm, cached: true);
/// <summary>
/// Emits the one operator-facing line per gated request, summarising what a hot seam withheld.
/// </summary>
/// <remarks>
/// This exists because the per-node denials behind it are logged at Debug: a Browse of a large
/// folder by an ungranted principal would otherwise emit one Information line per child, and an
/// operator would be reading a flood rather than a fact. It lives on the authorizer rather than the
/// node manager purely because the node manager is a <c>CustomNodeManager2</c> and carries no
/// <c>ILogger</c> — everything it logs itself goes through the SDK's obsolete static trace.
/// </remarks>
/// <param name="operation">The service being filtered, e.g. <c>Browse</c>.</param>
/// <param name="principal">The calling principal, or null when the session resolved none.</param>
/// <param name="withheld">How many nodes or references were withheld.</param>
/// <param name="total">How many were considered.</param>
public void LogFiltered(string operation, string? principal, int withheld, int total)
{
if (withheld == 0) return;
_log.LogInformation(
"AclGate: {Operation} withheld {Withheld} of {Total} node(s) for principal {Principal}",
operation, withheld, total, principal ?? "(none)");
}
/// <summary>Whether <paramref name="identity"/> may perform <paramref name="operation"/>, as a bool.</summary>
/// <param name="identity">The role-carrying identity off the SDK context.</param>
/// <param name="operation">The operation being attempted.</param>
/// <param name="nodeId">The target node.</param>
/// <param name="realm">The namespace the node was resolved in.</param>
/// <returns><see langword="true"/> when the operation is permitted.</returns>
public bool IsAllowedCached(
RoleCarryingUserIdentity? identity,
OpcUaOperation operation,
NodeId nodeId,
AddressSpaceRealm realm)
=> AuthorizeCached(identity, operation, nodeId, realm) is null;
/// <summary>
/// Authorizes <paramref name="operation"/> on <paramref name="nodeId"/> for the session behind
/// <paramref name="identity"/>.
/// </summary>
/// <param name="identity">The role-carrying identity off the SDK context, or null when the session
/// carries none.</param>
/// <param name="operation">The operation being attempted.</param>
/// <param name="nodeId">The target node.</param>
/// <param name="realm">Which namespace the node was resolved in — passed rather than re-derived so the
/// caller's own realm resolution and this decision can never disagree.</param>
/// <returns><c>null</c> to proceed; otherwise the veto to return to the SDK.</returns>
public ServiceResult? Authorize(
RoleCarryingUserIdentity? identity,
OpcUaOperation operation,
NodeId nodeId,
AddressSpaceRealm realm)
=> Evaluate(identity, operation, nodeId, realm, cached: false);
/// <summary>
/// Whether the API key behind <paramref name="identity"/> is still usable — consulted by the two
/// server-wide role gates (<c>WriteOperate</c>, <c>AlarmAck</c>) <b>regardless of
/// <see cref="Enabled"/></b>.
/// </summary>
/// <remarks>
/// <para>
/// With the flag off a session's roles are resolved once, at activation, so before this check a
/// key that expired by the clock — or that a deployment disabled or removed — kept
/// <c>WriteOperate</c> / <c>AlarmAck</c> on its open session until the client disconnected. With
/// the flag on, <see cref="Authorize"/> already makes the identical check first thing, so the role
/// gates call this only on the flag-off path and the two postures agree on key usability.
/// </para>
/// <para>
/// It is the same <see cref="DataPlaneAuthoritySnapshot.FindUsableKey"/> probe against the same
/// snapshot and the same clock as <see cref="Authorize"/>: one dictionary lookup, no I/O, so it is
/// safe on the SDK's synchronous write and method-call threads. A session carrying <b>no</b> key id —
/// Anonymous, or a legacy identity — has nothing that can expire and always passes; its roles stay
/// exactly what activation resolved. A key absent from the snapshot denies, as it does with the flag
/// on: on a driver-only node the artifact is the only key source there is, so "absent" means
/// "removed by a deployment".
/// </para>
/// </remarks>
/// <param name="identity">The role-carrying identity off the SDK context, or null.</param>
/// <param name="operation">The operation being attempted, for the denial log.</param>
/// <param name="nodeId">The target node, for the denial log.</param>
/// <returns><c>null</c> to proceed to the role check; otherwise the veto to return to the SDK.</returns>
public ServiceResult? AuthorizeKeyUsable(
RoleCarryingUserIdentity? identity, OpcUaOperation operation, NodeId nodeId)
{
if (identity?.ApiKeyId is not { Length: > 0 } keyId) return null;
var snapshot = _authority.Current;
var caller = new DataCallerIdentity(identity.Principal, identity.ApiKeyId,
identity.CredentialVersion, identity.CredentialExpiresUtc);
return !_policy.IsCallerUsable(caller, allowLegacyUnversionedKey: true)
|| !ReferenceEquals(snapshot, _authority.Current)
? DenyRevokedKey(operation, nodeId, identity.Principal, keyId, snapshot.GenerationId, cached: false)
: null;
}
/// <summary>
/// Authorizes a Part 9 command on a <b>scripted</b> alarm condition at the scope of the equipment the
/// node manager has bound that exact live condition to (Gitea #797) — never at a scope parsed out of
/// the condition's NodeId.
/// </summary>
/// <remarks>
/// <para>
/// A scripted condition's NodeId is its opaque, operator-authored <c>ScriptedAlarmId</c>
/// (<c>^[A-Za-z0-9_-]+$</c>, e.g. <c>scripted-eqa-hi</c>). <see cref="Authorize"/> would split it as
/// a topology path — <c>[uns, scripted-eqa-hi]</c> — which no <c>Equipment</c> grant can ever
/// match, so before this entry point a session holding the owning equipment's grant was denied
/// while a <c>Cluster</c> grant passed. Worse, that one-segment scope would be satisfied by an
/// unrelated Area that happened to share the alarm's id.
/// </para>
/// <para>
/// <b>Every input is re-read at each call, and every gap denies.</b> The current snapshot (so the
/// current generation, trie and grants), the calling key's usability against this authorizer's
/// clock, and the owner's path in THAT generation's <see cref="DataPlaneAuthoritySnapshot.EquipmentScopePaths"/>.
/// No owner binding (an unknown, removed or replaced condition), an owner the generation cannot
/// place, or a path that does not name an equipment each deny — there is no fallback to the
/// realm root, the cluster, or the identifier. The decision cache is deliberately not used: the
/// binding lives in the address space, not in the generation, so a cached verdict keyed on the
/// NodeId could outlive a re-bind (delete + recreate of the same id under another equipment).
/// Alarm commands are not a request-rate seam, so the uncached walk costs nothing that matters.
/// </para>
/// <para>
/// The scope is the equipment's OWN node, not the equipment plus a leaf: grants on the equipment
/// or any ancestor (line, area, UNS namespace, cluster) confer the command, and a grant on a single
/// tag beneath the equipment does not — a tag grant is about that signal, not the equipment's alarms.
/// </para>
/// </remarks>
/// <param name="identity">The role-carrying identity off the SDK context, or null.</param>
/// <param name="operation">The alarm operation being attempted.</param>
/// <param name="conditionNodeId">The condition the method targets (for the denial log only — never parsed).</param>
/// <param name="ownerEquipmentId">The <c>EquipmentId</c> the live condition is bound to, or null when the
/// node manager holds no binding for this exact instance.</param>
/// <param name="ownerFolderChain">The LIVE folder-id ancestry of the equipment folder the condition hangs under
/// (root-first, ending at <paramref name="ownerEquipmentId"/>), or null when unbound (Gitea #808 review).</param>
/// <returns><c>null</c> to proceed; otherwise the veto to return to the SDK.</returns>
public ServiceResult? AuthorizeScriptedCondition(
RoleCarryingUserIdentity? identity,
OpcUaOperation operation,
NodeId conditionNodeId,
string? ownerEquipmentId,
IReadOnlyList<string>? ownerFolderChain)
{
if (identity is null)
return Deny(operation, conditionNodeId, principal: null, "the session carries no role-carrying identity");
if (string.IsNullOrEmpty(identity.Principal))
return Deny(operation, conditionNodeId, principal: null, "the session resolved no ACL principal");
var snapshot = _authority.Current;
if (string.IsNullOrWhiteSpace(snapshot.ClusterId))
{
return Deny(operation, conditionNodeId, identity.Principal,
"this node has no cluster identity, so no permission trie exists to evaluate against");
}
var now = _time.GetUtcNow().UtcDateTime;
if (identity.ApiKeyId is { Length: > 0 } keyId && snapshot.FindUsableKey(keyId, now) is null)
return DenyRevokedKey(operation, conditionNodeId, identity.Principal, keyId, snapshot.GenerationId, cached: false);
conditionNodeId.TryGetValue(out string alarmId);
if (!TryPlaceScriptedCondition(
snapshot, alarmId, ownerEquipmentId, ownerFolderChain, out var segments, out var reason))
{
return Deny(operation, conditionNodeId, identity.Principal, reason);
}
var scope = new NodeScope
{
ClusterId = snapshot.ClusterId!,
Kind = NodeHierarchyKind.Uns,
Segments = segments,
};
return Walk(snapshot, identity, operation, scope, now)
? null
: DenyNoGrant(operation, conditionNodeId, identity.Principal, snapshot.GenerationId, cached: false);
}
/// <summary>
/// Places a scripted condition at its owning equipment's UNS path in <paramref name="snapshot"/> — the one
/// rule both the Part 9 command gate (#797) and the Read / Browse / subscribe / event-visibility path (#808)
/// use, so "can see" and "can command" can never disagree about where the alarm lives.
/// </summary>
/// <param name="snapshot">The generation in force.</param>
/// <param name="alarmId">The condition's <c>ScriptedAlarmId</c>.</param>
/// <param name="ownerEquipmentId">The live owner binding, or null when unbound.</param>
/// <param name="ownerFolderChain">The live id ancestry of the owner's folder, or null when unbound.</param>
/// <param name="segments">The owning equipment's path below the UNS realm root.</param>
/// <param name="reason">Why placement failed (the caller denies).</param>
/// <returns><see langword="true"/> when the condition is placed.</returns>
private static bool TryPlaceScriptedCondition(
DataPlaneAuthoritySnapshot snapshot,
string? alarmId,
string? ownerEquipmentId,
IReadOnlyList<string>? ownerFolderChain,
out IReadOnlyList<string> segments,
out string reason)
{
segments = [];
if (string.IsNullOrEmpty(ownerEquipmentId))
{
reason = "the scripted condition has no live owner binding (unknown, removed or replaced)";
return false;
}
// The live binding describes the address space as last materialised; the generation is installed BEFORE
// its address space is applied, and a failed apply keeps the old one. Require both to name the SAME owner
// for this exact alarm id, so a moved alarm is denied — under its old AND its new owner's grant — until
// the address space catches up, rather than staying visible / commandable with the old owner's grant.
if (string.IsNullOrEmpty(alarmId)
|| !snapshot.TryGetScriptedAlarmOwner(alarmId, out var deployedOwner)
|| !string.Equals(deployedOwner, ownerEquipmentId, StringComparison.OrdinalIgnoreCase))
{
reason = $"the live owner binding ({ownerEquipmentId}) does not match generation {snapshot.GenerationId}'s deployed owner of this scripted alarm";
return false;
}
if (!snapshot.TryGetEquipmentUnsSegments(ownerEquipmentId, out segments))
{
reason = $"owner equipment {ownerEquipmentId} has no UNS path in generation {snapshot.GenerationId}";
return false;
}
// The owner's FOLDER must also sit where this generation deploys it (the folder rule, #808 review): an
// equipment moved to another line keeps its id, so the owner checks above pass while its folder — and this
// alarm under it — still hangs under the old line. Without this the new line's grant could read and command
// the alarm while the folder above it is denied.
if (ownerFolderChain is null
|| !snapshot.TryGetUnsFolderSegments(ownerEquipmentId, ownerFolderChain, out var folderSegments)
|| !folderSegments.SequenceEqual(segments, StringComparer.Ordinal))
{
segments = [];
reason = $"owner equipment {ownerEquipmentId}'s folder is not placed as generation {snapshot.GenerationId} deploys it (moved, or not yet rebuilt)";
return false;
}
reason = string.Empty;
return true;
}
/// <summary>
/// Turns a non-<see cref="UnsAclSubjectKind.Path"/> UNS subject into the segments it is authorized at in
/// <paramref name="snapshot"/> (Gitea #808). For a folder, a node a folder owns, a reference variable and a
/// scripted condition every gap fails — the caller denies, with no fallback to splitting the identifier, to
/// the realm root or to the cluster. The one deliberate exception is <see cref="UnsAclSubjectKind.Unknown"/>
/// (no live node holds the id): it is placed at <see cref="UnknownNodeSegment"/> directly under the realm, so
/// only a realm-wide (<c>Cluster</c> / <c>Namespace uns</c>) grant decides it — never a narrow grant that
/// happens to share a name with a removed opaque id — except a reference-variable-shaped id (exactly four
/// segments), which keeps its name-path split.
/// </summary>
/// <param name="identifier">The node's <c>s=</c> identifier (split only for the shapes that are paths).</param>
/// <param name="snapshot">The generation in force.</param>
/// <param name="subject">The live facts the node manager reported.</param>
/// <param name="segments">The resolved path below the UNS realm root.</param>
/// <param name="reason">Why placement failed.</param>
/// <returns><see langword="true"/> when the subject is placed.</returns>
private static bool TryPlaceUnsSubject(
string identifier,
DataPlaneAuthoritySnapshot snapshot,
in UnsAclSubject subject,
out IReadOnlyList<string> segments,
out string reason)
{
IReadOnlyList<string> owner;
bool owned;
switch (subject.Kind)
{
case UnsAclSubjectKind.Unknown:
{
var split = identifier.Split('/', StringSplitOptions.RemoveEmptyEntries);
segments = split.Length == ReferenceVariableSegments ? split : [UnknownNodeSegment];
reason = string.Empty;
return true;
}
case UnsAclSubjectKind.ReferenceVariable:
{
// A reference variable's id IS its name path, so a Tag grant keeps matching it — but only while that
// path is where THIS generation puts its equipment (plus one effective-name segment). An equipment
// moved to another line, or an Area/Line/Equipment renamed, leaves the variable's id on the OLD names
// until the address space re-points it; the old names' grants must not keep reading / writing it.
var split = identifier.Split('/', StringSplitOptions.RemoveEmptyEntries);
if (subject.FolderChain is not { Count: > 0 } equipmentChain
|| !snapshot.TryGetUnsFolderSegments(equipmentChain[^1], equipmentChain, out var equipment)
|| split.Length != equipment.Count + 1
|| !split.Take(equipment.Count).SequenceEqual(equipment, StringComparer.Ordinal))
{
segments = [];
reason = $"the UNS reference variable's path does not match its equipment {subject.FolderChain?.LastOrDefault() ?? "(none)"}'s placement in generation {snapshot.GenerationId} (moved, renamed, or not yet re-pointed)";
return false;
}
segments = split;
reason = string.Empty;
return true;
}
case UnsAclSubjectKind.Folder:
if (subject.FolderChain is not { Count: > 0 } chain
|| !snapshot.TryGetUnsFolderSegments(chain[^1], chain, out owner))
{
segments = [];
reason = $"the UNS folder {subject.FolderChain?.LastOrDefault() ?? "(none)"} is not placed as generation {snapshot.GenerationId} deploys it (unknown, moved, or not yet rebuilt)";
return false;
}
owned = !subject.IsFolderItself;
break;
case UnsAclSubjectKind.ScriptedCondition:
if (!TryPlaceScriptedCondition(
snapshot, subject.AlarmId, subject.OwnerEquipmentId, subject.FolderChain, out owner, out reason))
{
segments = [];
return false;
}
owned = true;
break;
default:
segments = [];
reason = "unrecognised UNS subject";
return false;
}
segments = owned ? [.. owner, OwnedNodeSegment] : owner;
reason = string.Empty;
return true;
}
/// <summary>
/// The decision-cache key for a node authorized at a RESOLVED scope rather than at its split identifier. It
/// names the scope, not the node, because the cached grant walk depends only on the scope — and keying on the
/// node would let a verdict outlive a re-bind or re-parent the resolver sees but the generation does not. The
/// leading NUL keeps it disjoint from every <c>s=</c> identifier — which <c>Evaluate</c> ENFORCES by denying any
/// identifier that contains a NUL before the cache is consulted (review of #808: otherwise a client reading
/// the nonexistent <c>s="\0Area1\0Line1\0Pump"</c> would memoize a deny under the real folder's key for its
/// whole key shard).
/// </summary>
/// <param name="segments">The resolved path below the UNS realm root.</param>
/// <returns>The cache key.</returns>
private static string ResolvedScopeCacheKey(IReadOnlyList<string> segments) =>
"\u0000" + string.Join('\u0000', segments);
/// <summary>
/// The decision itself. Ordered so the cached seams reach their answer having allocated nothing:
/// every check that must run per call comes first, the memoized verdict is consulted next, and the
/// scope build and grant walk happen only on a miss.
/// </summary>
/// <remarks>
/// The ordering is a correctness constraint before it is a performance one — see the key-revocation
/// comment inline, and <c>Key_revocation_is_rechecked_on_a_cache_hit</c> /
/// <c>NodeManagerStage6EnforcementTests.An_expired_key_is_denied_even_though_its_allow_is_cached</c>,
/// which fail if the cache lookup is moved above it.
/// </remarks>
/// <param name="identity">The role-carrying identity off the SDK context.</param>
/// <param name="operation">The operation being attempted.</param>
/// <param name="nodeId">The target node.</param>
/// <param name="realm">The namespace the node was resolved in.</param>
/// <param name="cached">Whether the grant walk may be memoized (the request-rate seams).</param>
/// <returns><c>null</c> to proceed; otherwise the veto to return to the SDK.</returns>
private ServiceResult? Evaluate(
RoleCarryingUserIdentity? identity,
OpcUaOperation operation,
NodeId nodeId,
AddressSpaceRealm realm,
bool cached,
bool localBypass = false)
{
if (TryAuthorizeMapped(identity, operation, nodeId, realm, out var mappedVeto)) return mappedVeto;
if (localBypass) return null;
if (identity is null)
return Deny(operation, nodeId, principal: null, "the session carries no role-carrying identity", cached);
if (string.IsNullOrEmpty(identity.Principal))
{
// An authenticator that predates the principal model, or a code path that built the identity
// through the legacy two-argument constructor. Guessing a principal here — from the display
// name, say — would silently authorize as whatever the token's username happened to be.
return Deny(operation, nodeId, principal: null, "the session resolved no ACL principal", cached);
}
var snapshot = _authority.Current;
if (string.IsNullOrWhiteSpace(snapshot.ClusterId))
{
return Deny(operation, nodeId, identity.Principal,
"this node has no cluster identity, so no permission trie exists to evaluate against", cached);
}
// Re-check revocation on every call. The key was verified at session activation, but a deployment
// since then may have disabled or expired it — and on a driver-only node the artifact is the ONLY
// revocation channel. Without this a revoked key keeps its open session's authority indefinitely,
// which on a machine-to-machine data plane means until the client chooses to reconnect.
// ⚠️ Deliberately OUTSIDE the decision cache, and it must stay ABOVE the lookup below. Grants and
// principals are fixed for a generation, so memoizing the grant walk is sound; a key's expiry
// passes with the CLOCK, so a cached allow consulted first would keep an expired key working until
// the next deploy — the generation never moves, so nothing would drop the entry.
var now = _time.GetUtcNow().UtcDateTime;
if (identity.ApiKeyId is { Length: > 0 } keyId
&& (!_policy.IsCallerUsable(new DataCallerIdentity(identity.Principal, identity.ApiKeyId,
identity.CredentialVersion, identity.CredentialExpiresUtc), allowLegacyUnversionedKey: true)
|| !ReferenceEquals(snapshot, _authority.Current)))
return DenyRevokedKey(operation, nodeId, identity.Principal, keyId, snapshot.GenerationId, cached);
// The s= identifier, read once: it is both the cache key and the raw material the scope is split
// from, and pulling it up here absorbs what used to be TryBuildScope's own guard. A NodeId that
// carries no string addresses no ACL scope at all, so it can never be answered from the cache.
if (!nodeId.TryGetValue(out string identifier) || identifier.Length == 0)
{
return Deny(operation, nodeId, identity.Principal,
"the node id carries no string identifier, so it addresses no ACL scope", cached);
}
// No node this server mints carries a NUL, and the resolved-scope cache keys are NUL-prefixed: refusing NUL
// here keeps the two keyspaces disjoint, so a client-chosen identifier can never collide with (and poison)
// a resolved scope's memoized verdict. Denied uncached, before the lookup.
if (identifier.Contains('\u0000'))
{
return Deny(operation, nodeId, identity.Principal,
"the node id carries a NUL, which no node in this address space does", cached);
}
var sessionKey = identity.ApiKeyId ?? identity.Principal;
// Gitea #808: a UNS folder minted under an opaque entity id, a node it owns, and a scripted condition (or
// child) are placed through the live address space + this generation instead of by splitting the id. The
// resolver runs on EVERY call, ahead of the cache, because what it reads moves with the address space; the
// cache below then memoizes only the grant walk at the resolved scope, keyed on that scope.
var cacheIdentifier = identifier;
IReadOnlyList<string>? resolvedSegments = null;
if (realm == AddressSpaceRealm.Uns && UnsSubjectResolver is { } resolve)
{
var subject = resolve(identifier);
if (subject.Kind != UnsAclSubjectKind.Path)
{
if (!TryPlaceUnsSubject(identifier, snapshot, subject, out var placed, out var reason))
return Deny(operation, nodeId, identity.Principal, reason, cached);
resolvedSegments = placed;
cacheIdentifier = ResolvedScopeCacheKey(placed);
}
}
if (cached &&
Decisions.TryGet(snapshot.GenerationId, sessionKey, operation, realm, cacheIdentifier, out var memoized))
{
// The whole point of the reorder: a hit returns HERE, having built no scope, no closure and no
// UserAuthorizationState. One Browse of a device folder asks this once per child.
return memoized && ReferenceEquals(snapshot, _authority.Current)
&& (identity.ApiKeyId is not { Length: > 0 } || _policy.IsCallerUsable(
new DataCallerIdentity(identity.Principal, identity.ApiKeyId,
identity.CredentialVersion, identity.CredentialExpiresUtc), allowLegacyUnversionedKey: true))
? null
: DenyNoGrant(operation, nodeId, identity.Principal, snapshot.GenerationId, cached);
}
var scope = resolvedSegments is null
? BuildScope(identifier, realm, snapshot.ClusterId)
: new NodeScope { ClusterId = snapshot.ClusterId!, Kind = NodeHierarchyKind.Uns, Segments = resolvedSegments };
var allowed = Walk(snapshot, identity, operation, scope, now);
// The single shared anchor fronts BOTH realm trees, so its browse must consider transit in
// either: a principal whose only Browse grant lives in the UNS tree still enters through this
// node. Browse only — transit confers navigation, never read/write/subscribe, matching the
// evaluator's own rule.
if (!allowed && operation == OpcUaOperation.Browse && IsSharedRootFolder(identifier, realm))
{
allowed = Walk(
snapshot, identity, operation,
new NodeScope
{
ClusterId = snapshot.ClusterId!,
Kind = NodeHierarchyKind.Uns,
Segments = [],
},
now);
}
if (cached) Decisions.Set(snapshot.GenerationId, sessionKey, operation, realm, cacheIdentifier, allowed);
return allowed && ReferenceEquals(snapshot, _authority.Current)
? null
: DenyNoGrant(operation, nodeId, identity.Principal, snapshot.GenerationId, cached);
}
/// <summary>The grant walk itself — the only part of a decision that is safe to memoize.</summary>
/// <param name="snapshot">The authority snapshot the decision is taken against.</param>
/// <param name="identity">The calling identity.</param>
/// <param name="operation">The operation being attempted.</param>
/// <param name="scope">The resolved node scope.</param>
/// <param name="now">The current time, for the authorization state's resolution stamp.</param>
/// <returns><see langword="true"/> when a grant confers the operation.</returns>
private bool Walk(
DataPlaneAuthoritySnapshot snapshot,
RoleCarryingUserIdentity identity,
OpcUaOperation operation,
NodeScope scope,
DateTime now)
{
var caller = new DataCallerIdentity(identity.Principal, identity.ApiKeyId,
identity.CredentialVersion, identity.CredentialExpiresUtc);
return _policy.AuthorizeLocal(caller, operation, scope, allowLegacyUnversionedKey: true);
}
/// <summary>
/// Projects a node's <c>s=</c> identifier onto the scope the permission trie is keyed by.
/// </summary>
/// <remarks>
/// The <c>s=</c> identifier IS the path in both realms — a RawPath
/// (<c>folder…/Driver/Device/group…/Tag</c>) or a UNS path
/// (<c>Area/Line/Equipment/EffectiveName</c>) — so the projection is a split, and the depth comes
/// out however deep the node actually is. That is why the scope model had to become variable-arity
/// in stage 3: a fixed set of level fields could not represent the raw tree at all.
/// <para>
/// Segments are compared ordinally, matching <c>RawPaths.Comparer</c> and OPC UA NodeId
/// identity — <c>Speed</c> and <c>speed</c> are different nodes and must be different scopes.
/// </para>
/// <para>
/// Takes the identifier rather than the <see cref="NodeId"/>, and cannot fail: the "not a
/// string" guard this used to carry moved up into <c>Evaluate</c>, where it has to run before
/// the cache lookup anyway — the identifier is the cache key.
/// </para>
/// <para>
/// <b>The one identifier that is not a path is the shared root folder</b>
/// (<see cref="V3NodeIds.SharedRootFolderId"/>), which both realm trees hang under. Its
/// identifier is its display identity, so splitting it yields a one-segment scope containing a
/// name no grant path can ever hold — which denied the anchor for every principal short of a
/// cluster grant, and the node manager refuses a whole Browse whose SOURCE is denied. It maps
/// instead onto the zero-segment scope: the realm root, which is exactly the question
/// <see cref="PermissionTrie.HasBrowseTransit"/> was written to answer ("is this an ancestor of
/// anything granted in this realm?") and which no production path had ever asked it.
/// </para>
/// <para>
/// Keying that on the identifier introduces no new ambiguity: a genuine top-level raw folder
/// literally named <c>OtOpcUa</c> would already mint the identical NodeId as the anchor in the
/// served address space itself (<c>EnsureFolder</c> takes the RawPath as the id), so the
/// collision — if an operator ever authors one — predates this mapping and lives in the address
/// space rather than in the gate. One narrowing side effect in that degenerate case: a grant
/// scoped to the colliding folder used to leak onto the anchor's own Read/Write (the old
/// one-segment scope descended into it); the zero-segment scope no longer does, which is the
/// fail-closed direction.
/// </para>
/// </remarks>
/// <param name="identifier">The node's non-empty <c>s=</c> identifier.</param>
/// <param name="realm">The namespace the node was resolved in.</param>
/// <param name="clusterId">The node's cluster.</param>
/// <returns>The scope to evaluate against.</returns>
private static NodeScope BuildScope(string identifier, AddressSpaceRealm realm, string clusterId) => new()
{
ClusterId = clusterId,
Kind = realm == AddressSpaceRealm.Raw ? NodeHierarchyKind.Raw : NodeHierarchyKind.Uns,
Segments = IsSharedRootFolder(identifier, realm)
? []
: identifier.Split('/', StringSplitOptions.RemoveEmptyEntries),
};
/// <summary>
/// Whether this node is the single shared root folder both realm trees hang under.
/// </summary>
/// <remarks>
/// <b>Realm-qualified on purpose.</b> The anchor is minted in the RAW namespace; in the UNS
/// namespace <c>s=OtOpcUa</c> is an ordinary Area an operator happened to name that way, and giving
/// it anchor semantics would collapse a real UNS path onto the realm root — silently widening every
/// browse of it.
/// </remarks>
/// <param name="identifier">The node's <c>s=</c> identifier.</param>
/// <param name="realm">The namespace the node was resolved in.</param>
/// <returns><see langword="true"/> when the node is the shared anchor folder.</returns>
private static bool IsSharedRootFolder(string identifier, AddressSpaceRealm realm) =>
realm == AddressSpaceRealm.Raw
&& string.Equals(identifier, V3NodeIds.SharedRootFolderId, StringComparison.Ordinal);
/// <summary>Denies with a constant reason — nothing to build, so nothing to defer.</summary>
/// <param name="operation">The operation being attempted.</param>
/// <param name="nodeId">The target node.</param>
/// <param name="principal">The calling principal, when one resolved.</param>
/// <param name="reason">The operator-facing explanation.</param>
/// <param name="cached">Whether this came from a request-rate seam (which logs at Debug).</param>
/// <returns>The veto to return to the SDK.</returns>
private ServiceResult Deny(
OpcUaOperation operation, NodeId? nodeId, string? principal, string reason, bool cached = false)
{
var level = LevelFor(cached);
if (_log.IsEnabled(level)) LogDenial(level, operation, nodeId, principal, reason);
return DeniedResult;
}
/// <summary>
/// Denies because the calling key is disabled or expired, composing the reason only if it will be
/// logged.
/// </summary>
/// <param name="operation">The operation being attempted.</param>
/// <param name="nodeId">The target node.</param>
/// <param name="principal">The calling principal.</param>
/// <param name="keyId">The key that is no longer usable.</param>
/// <param name="generation">The authorization generation the check ran under.</param>
/// <param name="cached">Whether this came from a request-rate seam (which logs at Debug).</param>
/// <returns>The veto to return to the SDK.</returns>
private ServiceResult DenyRevokedKey(
OpcUaOperation operation, NodeId? nodeId, string? principal, string keyId, long generation, bool cached)
{
var level = LevelFor(cached);
if (_log.IsEnabled(level))
{
LogDenial(level, operation, nodeId, principal,
$"key {keyId} is no longer enabled or has expired in generation {generation}");
}
return DeniedResult;
}
/// <summary>
/// Denies because no grant conferred the operation — the hot denial, hit once per child of an
/// ungranted folder, so the reason string is built only when Debug is actually on.
/// </summary>
/// <param name="operation">The operation being attempted.</param>
/// <param name="nodeId">The target node.</param>
/// <param name="principal">The calling principal.</param>
/// <param name="generation">The authorization generation the walk ran under.</param>
/// <param name="cached">Whether this came from a request-rate seam (which logs at Debug).</param>
/// <returns>The veto to return to the SDK.</returns>
private ServiceResult DenyNoGrant(
OpcUaOperation operation, NodeId? nodeId, string? principal, long generation, bool cached)
{
var level = LevelFor(cached);
if (_log.IsEnabled(level))
{
LogDenial(level, operation, nodeId, principal,
$"no grant in generation {generation} confers {operation} here");
}
return DeniedResult;
}
/// <summary>
/// The hot seams log at Debug because a single Browse of an ungranted folder would otherwise emit
/// one Information line per child. Their operator-facing signal is the per-request summary
/// <see cref="LogFiltered"/> emits, which says how many references were filtered and for whom.
/// </summary>
/// <param name="cached">Whether the denial came from a request-rate seam.</param>
/// <returns>The level to log the denial at.</returns>
private static LogLevel LevelFor(bool cached) => cached ? LogLevel.Debug : LogLevel.Information;
/// <summary>
/// Emits the denial detail. Callers guard with <see cref="ILogger.IsEnabled"/> first — not for the
/// message template, which costs nothing, but because every caller's <paramref name="reason"/> is a
/// composed string and two of them interpolate on the request-rate path.
/// </summary>
/// <param name="level">The level chosen by <see cref="LevelFor"/>.</param>
/// <param name="operation">The operation being attempted.</param>
/// <param name="nodeId">The target node.</param>
/// <param name="principal">The calling principal, when one resolved.</param>
/// <param name="reason">The operator-facing explanation.</param>
private void LogDenial(
LogLevel level, OpcUaOperation operation, NodeId? nodeId, string? principal, string reason)
=> _log.Log(
level,
"AclGate: denied {Operation} on {NodeId} for principal {Principal} — {Reason}",
operation, nodeId, principal ?? "(none)", reason);
}
/// <summary>Classification of a node identifier from the manager's trusted live catalog.</summary>
public enum MappedNodeResolutionKind { Local, Mapped, Deny }
/// <summary>Mapped catalog proof; unknown or retired projected identifiers must be Deny.</summary>
public sealed record MappedNodeResolution(MappedNodeResolutionKind Kind, DataView? View = null,
MappedNamespaceSubject? Live = null, MappedSubjectResolver? Resolver = null, IDataAuthorizationLease? Lease = null)
{
public static MappedNodeResolution Local { get; } = new(MappedNodeResolutionKind.Local);
public static MappedNodeResolution Deny { get; } = new(MappedNodeResolutionKind.Deny);
public static MappedNodeResolution Mapped(DataView view, MappedNamespaceSubject live,
MappedSubjectResolver resolver, IDataAuthorizationLease lease) =>
new(MappedNodeResolutionKind.Mapped, view, live, resolver, lease);
}