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;
///
/// Turns an inbound OPC UA request into a node-scoped ACL decision. The one place
/// the address space's meets .
///
///
///
/// Dormant unless . With Security:Acl:Enabled false —
/// the default — is never consulted and the node manager keeps its
/// server-wide role gates. See for why the two are alternatives rather
/// than a chain.
///
///
/// Every failure path denies. No identity, no principal, no cluster identity, a NodeId
/// whose identifier is not a string, a trie that was never installed — each returns
/// BadUserAccessDenied. 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 OpcUaPublish is where an operator confirms a trie exists at
/// all.
///
///
/// Authorization state is built per call, not per session.
/// 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.
///
///
/// Stage 6's request-rate seams — Read, Browse, subscription creation — go through
/// instead, which memoizes the grant walk in
/// . That is a cache of the walk, not 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.
///
///
/// and
/// 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 explicitly (AuthCacheMaxStaleness = TimeSpan.MaxValue) 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".
///
///
public sealed class DataPlaneAuthorizer
{
///
/// The single veto every denial returns. Logged, never explained to the client: the client gets an
/// undifferentiated BadUserAccessDenied 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 DenyMessage.
///
///
/// Shared rather than per-call, because is immutable to us.
/// Verified by reflection against the pinned Opc.Ua.Core 1.5.378.106: every one of its properties
/// (StatusCode, SymbolicId, NamespaceUri, LocalizedText,
/// AdditionalInfo, InnerResult) has a private setter, and its only non-getter
/// method — Append(StringBuilder) — formats rather than mutates, so no code outside the type
/// can change an instance. The SDK itself publishes ServiceResult.Good and
/// ServiceResult.Bad as shared static readonly 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.
///
private static readonly ServiceResult DeniedResult = new(StatusCodes.BadUserAccessDenied);
private readonly IDataPlaneAuthoritySource _authority;
private readonly DataOperationPolicy _policy;
private readonly ILogger _log;
private readonly TimeProvider _time;
/// Initializes a new instance of the class.
/// The node's current data-plane authorization inputs.
/// The permission evaluator reading the tries built alongside those inputs.
/// Whether ACL evaluation decides authorization (Security:Acl:Enabled).
/// The logger.
/// Time provider, injected for testability.
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;
}
///
/// True when ACL grants — rather than the server-wide role set — decide write, alarm-command and
/// HistoryRead authorization.
///
public bool Enabled { get; }
/// The clock this gate evaluates key expiry against.
///
/// Exposed so the composition root's wiring can be asserted by reference. The remarks on
/// UserAuthorizationState 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.
///
public TimeProvider Clock => _time;
///
/// Memoized grant walks for the request-rate seams. See
/// for what it is and is not allowed to cache.
///
public SessionAclDecisionCache Decisions { get; } = new();
///
/// 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).
///
///
/// 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.
///
public Func? UnsSubjectResolver { get; set; }
/// Live catalog classification owned by the node manager, consulted before either local path resolver.
public Func? MappedSubjectResolver { get; set; }
/// Optional actual-namespace filter for projected subject classification.
public Func? MappedNamespacePredicate { get; set; }
/// Checks a mapped subject even when local ACL enforcement is disabled.
public ServiceResult? AuthorizeIfRequired(RoleCarryingUserIdentity? identity, OpcUaOperation operation,
NodeId nodeId, AddressSpaceRealm realm, bool cached = true) =>
Evaluate(identity, operation, nodeId, realm, cached, localBypass: !Enabled);
/// Checks a deployed mapping's local anchor scope regardless of the legacy ACL switch.
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);
}
/// Checks a mapping without changing the legacy local role gate.
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;
}
///
/// 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 Tag 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.
///
internal const string OwnedNodeSegment = DataScopeSubjects.OwnedNodeSegment;
///
/// 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.
///
internal const string UnknownNodeSegment = "\u0000unknown";
/// The depth of a UNS reference-variable id: Area/Line/Equipment/EffectiveName.
private const int ReferenceVariableSegments = 4;
///
/// Authorizes on through the decision cache —
/// the entry point for Read, Browse and subscription creation, which ask the same question many
/// times per request.
///
///
/// Identical in outcome to ; 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.
///
/// The role-carrying identity off the SDK context, or null when the session carries none.
/// The operation being attempted.
/// The target node.
/// The namespace the node was resolved in.
/// null to proceed; otherwise the veto to return to the SDK.
public ServiceResult? AuthorizeCached(
RoleCarryingUserIdentity? identity,
OpcUaOperation operation,
NodeId nodeId,
AddressSpaceRealm realm)
=> Evaluate(identity, operation, nodeId, realm, cached: true);
///
/// Emits the one operator-facing line per gated request, summarising what a hot seam withheld.
///
///
/// 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 CustomNodeManager2 and carries no
/// ILogger — everything it logs itself goes through the SDK's obsolete static trace.
///
/// The service being filtered, e.g. Browse.
/// The calling principal, or null when the session resolved none.
/// How many nodes or references were withheld.
/// How many were considered.
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)");
}
/// Whether may perform , as a bool.
/// The role-carrying identity off the SDK context.
/// The operation being attempted.
/// The target node.
/// The namespace the node was resolved in.
/// when the operation is permitted.
public bool IsAllowedCached(
RoleCarryingUserIdentity? identity,
OpcUaOperation operation,
NodeId nodeId,
AddressSpaceRealm realm)
=> AuthorizeCached(identity, operation, nodeId, realm) is null;
///
/// Authorizes on for the session behind
/// .
///
/// The role-carrying identity off the SDK context, or null when the session
/// carries none.
/// The operation being attempted.
/// The target node.
/// 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.
/// null to proceed; otherwise the veto to return to the SDK.
public ServiceResult? Authorize(
RoleCarryingUserIdentity? identity,
OpcUaOperation operation,
NodeId nodeId,
AddressSpaceRealm realm)
=> Evaluate(identity, operation, nodeId, realm, cached: false);
///
/// Whether the API key behind is still usable — consulted by the two
/// server-wide role gates (WriteOperate, AlarmAck) regardless of
/// .
///
///
///
/// 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
/// WriteOperate / AlarmAck on its open session until the client disconnected. With
/// the flag on, 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.
///
///
/// It is the same probe against the same
/// snapshot and the same clock as : one dictionary lookup, no I/O, so it is
/// safe on the SDK's synchronous write and method-call threads. A session carrying no 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".
///
///
/// The role-carrying identity off the SDK context, or null.
/// The operation being attempted, for the denial log.
/// The target node, for the denial log.
/// null to proceed to the role check; otherwise the veto to return to the SDK.
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;
}
///
/// Authorizes a Part 9 command on a scripted 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.
///
///
///
/// A scripted condition's NodeId is its opaque, operator-authored ScriptedAlarmId
/// (^[A-Za-z0-9_-]+$, e.g. scripted-eqa-hi). would split it as
/// a topology path — [uns, scripted-eqa-hi] — which no Equipment grant can ever
/// match, so before this entry point a session holding the owning equipment's grant was denied
/// while a Cluster grant passed. Worse, that one-segment scope would be satisfied by an
/// unrelated Area that happened to share the alarm's id.
///
///
/// Every input is re-read at each call, and every gap denies. 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 .
/// 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.
///
///
/// 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.
///
///
/// The role-carrying identity off the SDK context, or null.
/// The alarm operation being attempted.
/// The condition the method targets (for the denial log only — never parsed).
/// The EquipmentId the live condition is bound to, or null when the
/// node manager holds no binding for this exact instance.
/// The LIVE folder-id ancestry of the equipment folder the condition hangs under
/// (root-first, ending at ), or null when unbound (Gitea #808 review).
/// null to proceed; otherwise the veto to return to the SDK.
public ServiceResult? AuthorizeScriptedCondition(
RoleCarryingUserIdentity? identity,
OpcUaOperation operation,
NodeId conditionNodeId,
string? ownerEquipmentId,
IReadOnlyList? 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);
}
///
/// Places a scripted condition at its owning equipment's UNS path in — 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.
///
/// The generation in force.
/// The condition's ScriptedAlarmId.
/// The live owner binding, or null when unbound.
/// The live id ancestry of the owner's folder, or null when unbound.
/// The owning equipment's path below the UNS realm root.
/// Why placement failed (the caller denies).
/// when the condition is placed.
private static bool TryPlaceScriptedCondition(
DataPlaneAuthoritySnapshot snapshot,
string? alarmId,
string? ownerEquipmentId,
IReadOnlyList? ownerFolderChain,
out IReadOnlyList 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;
}
///
/// Turns a non- UNS subject into the segments it is authorized at in
/// (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
/// (no live node holds the id): it is placed at directly under the realm, so
/// only a realm-wide (Cluster / Namespace uns) 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.
///
/// The node's s= identifier (split only for the shapes that are paths).
/// The generation in force.
/// The live facts the node manager reported.
/// The resolved path below the UNS realm root.
/// Why placement failed.
/// when the subject is placed.
private static bool TryPlaceUnsSubject(
string identifier,
DataPlaneAuthoritySnapshot snapshot,
in UnsAclSubject subject,
out IReadOnlyList segments,
out string reason)
{
IReadOnlyList 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;
}
///
/// 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 s= identifier — which Evaluate ENFORCES by denying any
/// identifier that contains a NUL before the cache is consulted (review of #808: otherwise a client reading
/// the nonexistent s="\0Area1\0Line1\0Pump" would memoize a deny under the real folder's key for its
/// whole key shard).
///
/// The resolved path below the UNS realm root.
/// The cache key.
private static string ResolvedScopeCacheKey(IReadOnlyList segments) =>
"\u0000" + string.Join('\u0000', segments);
///
/// 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.
///
///
/// The ordering is a correctness constraint before it is a performance one — see the key-revocation
/// comment inline, and Key_revocation_is_rechecked_on_a_cache_hit /
/// NodeManagerStage6EnforcementTests.An_expired_key_is_denied_even_though_its_allow_is_cached,
/// which fail if the cache lookup is moved above it.
///
/// The role-carrying identity off the SDK context.
/// The operation being attempted.
/// The target node.
/// The namespace the node was resolved in.
/// Whether the grant walk may be memoized (the request-rate seams).
/// null to proceed; otherwise the veto to return to the SDK.
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? 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);
}
/// The grant walk itself — the only part of a decision that is safe to memoize.
/// The authority snapshot the decision is taken against.
/// The calling identity.
/// The operation being attempted.
/// The resolved node scope.
/// The current time, for the authorization state's resolution stamp.
/// when a grant confers the operation.
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);
}
///
/// Projects a node's s= identifier onto the scope the permission trie is keyed by.
///
///
/// The s= identifier IS the path in both realms — a RawPath
/// (folder…/Driver/Device/group…/Tag) or a UNS path
/// (Area/Line/Equipment/EffectiveName) — 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.
///
/// Segments are compared ordinally, matching RawPaths.Comparer and OPC UA NodeId
/// identity — Speed and speed are different nodes and must be different scopes.
///
///
/// Takes the identifier rather than the , and cannot fail: the "not a
/// string" guard this used to carry moved up into Evaluate, where it has to run before
/// the cache lookup anyway — the identifier is the cache key.
///
///
/// The one identifier that is not a path is the shared root folder
/// (), 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
/// was written to answer ("is this an ancestor of
/// anything granted in this realm?") and which no production path had ever asked it.
///
///
/// Keying that on the identifier introduces no new ambiguity: a genuine top-level raw folder
/// literally named OtOpcUa would already mint the identical NodeId as the anchor in the
/// served address space itself (EnsureFolder 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.
///
///
/// The node's non-empty s= identifier.
/// The namespace the node was resolved in.
/// The node's cluster.
/// The scope to evaluate against.
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),
};
///
/// Whether this node is the single shared root folder both realm trees hang under.
///
///
/// Realm-qualified on purpose. The anchor is minted in the RAW namespace; in the UNS
/// namespace s=OtOpcUa 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.
///
/// The node's s= identifier.
/// The namespace the node was resolved in.
/// when the node is the shared anchor folder.
private static bool IsSharedRootFolder(string identifier, AddressSpaceRealm realm) =>
realm == AddressSpaceRealm.Raw
&& string.Equals(identifier, V3NodeIds.SharedRootFolderId, StringComparison.Ordinal);
/// Denies with a constant reason — nothing to build, so nothing to defer.
/// The operation being attempted.
/// The target node.
/// The calling principal, when one resolved.
/// The operator-facing explanation.
/// Whether this came from a request-rate seam (which logs at Debug).
/// The veto to return to the SDK.
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;
}
///
/// Denies because the calling key is disabled or expired, composing the reason only if it will be
/// logged.
///
/// The operation being attempted.
/// The target node.
/// The calling principal.
/// The key that is no longer usable.
/// The authorization generation the check ran under.
/// Whether this came from a request-rate seam (which logs at Debug).
/// The veto to return to the SDK.
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;
}
///
/// 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.
///
/// The operation being attempted.
/// The target node.
/// The calling principal.
/// The authorization generation the walk ran under.
/// Whether this came from a request-rate seam (which logs at Debug).
/// The veto to return to the SDK.
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;
}
///
/// 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
/// emits, which says how many references were filtered and for whom.
///
/// Whether the denial came from a request-rate seam.
/// The level to log the denial at.
private static LogLevel LevelFor(bool cached) => cached ? LogLevel.Debug : LogLevel.Information;
///
/// Emits the denial detail. Callers guard with first — not for the
/// message template, which costs nothing, but because every caller's is a
/// composed string and two of them interpolate on the request-rate path.
///
/// The level chosen by .
/// The operation being attempted.
/// The target node.
/// The calling principal, when one resolved.
/// The operator-facing explanation.
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);
}
/// Classification of a node identifier from the manager's trusted live catalog.
public enum MappedNodeResolutionKind { Local, Mapped, Deny }
/// Mapped catalog proof; unknown or retired projected identifiers must be Deny.
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);
}