feat(security): enforce node ACLs on write, alarms and HistoryRead (#520 stage 5)

`Security:Acl:Enabled` (default false) makes scoped `NodeAcl` grants decide
data-plane authorization at the three seams that have one, and gives HistoryRead
a check it never had. Read, Browse and Subscribe stay ungated — stage 6.

The ACL decision REPLACES the server-wide role check rather than chaining with
it. Chained, a grant would have to confer the role as well as pass the scope
check, and only Cluster-scoped grants confer a role — so every narrow grant
would have stayed inert and the flag would have looked inert too. The
load-bearing test is an ALLOW: a session carrying no roles at all writing
successfully on the strength of its grant. A deny-only test passes against a
build where the ACL is never consulted, because the role gate denies too.

Found en route: the principal never reached the session. The authenticator
passed it as OpcUaUserAuthResult.DisplayName, but RoleCarryingUserIdentity
derives DisplayName from the presented token — for a key-bearing client that is
the static username `apikey`, identical fleet-wide. So the trie's matching key
was dropped at the identity boundary, and the audit ClientUserId on a rejected
write recorded `apikey` for every consuming system. Principal and ApiKeyId are
now carried explicitly.

Beyond the stage as sketched:

- Revocation reaches an OPEN session. Every decision re-checks the
  authenticating key against the current snapshot; without it a key revoked by a
  deployment kept its authority until the client chose to reconnect, which for a
  machine-to-machine consumer can be indefinitely.
- UserAuthorizationState is built per CALL, not per session. The per-session
  shape exists so an LDAP session can re-resolve membership that changed out of
  band; nothing can change out of band under API keys, so the generation stamp is
  the whole invalidation signal and a per-call record picks it up for free.
  IsStale/NeedsRefresh therefore cannot fire here and are documented as vestigial.
- The trie is built inside DataPlaneAuthorityState.Apply, under the same
  generation as the snapshot, rather than by a second wiring at the publish
  actor. An uninstalled trie denies everything — indistinguishable from working
  enforcement. Deleting the install turns 13 of the 22 new tests red.
- The deploy log reports what the BUILD dropped instead of re-deriving it. The
  old count agreed with the builder on one of its four drop reasons; a rule with
  a blank ScopeId, a retired scope kind, or a path not starting at a realm
  vanished with the log reading zero.

Both IApiKeyStore implementations widened to the full grant set. The narrowing
was redundant — ApiKeyInterimRoleMapper applies the same filter itself — and
became a trap once scope was enforced. Pinned by asserting the roles are
unchanged, with the two grants carrying different flags so it cannot pass by
accident.

Falsified by mutation: enforcement never engaging, the write seam ignoring the
ACL, the realm dropped from the scope, the revocation check removed, and the
trie never installed each turn the intended tests red and no others.

Full solution suite green.

Claude-Session: https://claude.ai/code/session_015p7wGqy3YpZNCpDzTpGMKo
This commit is contained in:
Joseph Doherty
2026-08-01 05:00:28 -04:00
parent 9499099028
commit f692f6afe4
25 changed files with 1845 additions and 151 deletions
@@ -276,6 +276,33 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
private volatile IDataPlaneAuthoritySource _dataPlaneAuthority = EmptyDataPlaneAuthoritySource.Instance;
/// <summary>
/// The node-scoped ACL gate (#520 stage 5), or <c>null</c> when none is wired. Consulted by the
/// write, alarm-command and HistoryRead seams <b>only while
/// <see cref="Security.DataPlaneAuthorizer.Enabled"/> is true</b>; otherwise each keeps its
/// server-wide role check and behaviour is identical to before this stage.
/// </summary>
/// <remarks>
/// Null means "not wired" and is treated as not-enabled, not as deny-all. That looks like the wrong
/// direction for a security control, but the alternative denies every write on any node that has
/// not been given an authorizer — including every existing test host and the admin-only nodes — to
/// protect a feature that is off by default. The real fail-closed behaviour lives one level in:
/// once an authorizer IS wired and enabled, every unresolvable case denies.
/// </remarks>
public DataPlaneAuthorizer? Authorizer
{
get => _authorizer;
set => _authorizer = value;
}
private volatile DataPlaneAuthorizer? _authorizer;
/// <summary>
/// True when a wired authorizer is switched on — i.e. when ACL grants, rather than the server-wide
/// role set, decide the gated operations.
/// </summary>
private bool AclEnforced => _authorizer is { Enabled: true };
/// <summary>
/// The upper bound on the bounded over-fetch <see cref="ServeRawPaged"/> uses to page WITHIN an
/// oversized "tie cluster" — more raw samples sharing one SourceTimestamp than the client's per-page
@@ -1181,17 +1208,13 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
// Resolve the principal the SAME way the SDK's own GetCurrentUserId does, then narrow to the
// role-carrying identity T17 attached. Anonymous / non-role-carrying identities ⇒ null ⇒ denied.
var identity = (context as ISessionOperationContext)?.UserIdentity as RoleCarryingUserIdentity;
if (identity is null || !identity.Roles.Contains(OpcUaDataPlaneRoles.AlarmAck, StringComparer.OrdinalIgnoreCase))
{
// Fail closed: no role / no identity ⇒ veto. Returning a bad ServiceResult aborts the SDK's
// state change and surfaces the status to the client; we never route or mutate.
return new ServiceResult(StatusCodes.BadUserAccessDenied);
}
var gate = EvaluateAlarmCommandGate(identity, condition, operation);
if (gate is not null) return gate;
var cmd = new AlarmCommand(
AlarmId: condition.NodeId.Identifier?.ToString() ?? string.Empty,
Operation: operation,
User: identity.DisplayName ?? string.Empty,
User: AlarmOperatorName(identity!),
Comment: comment?.Text,
UnshelveAtUtc: unshelveAt);
@@ -1223,10 +1246,8 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
// Resolve + gate the SAME way HandleAlarmCommand does so native and scripted acks share one authz
// contract. Anonymous / non-role-carrying identities ⇒ null ⇒ denied (fail closed, never route).
var identity = (context as ISessionOperationContext)?.UserIdentity as RoleCarryingUserIdentity;
if (identity is null || !identity.Roles.Contains(OpcUaDataPlaneRoles.AlarmAck, StringComparer.OrdinalIgnoreCase))
{
return new ServiceResult(StatusCodes.BadUserAccessDenied);
}
var gate = EvaluateAlarmCommandGate(identity, condition, "Acknowledge");
if (gate is not null) return gate;
// Same condition-node-id extraction HandleAlarmCommand uses (condition.NodeId.Identifier?.ToString()):
// for a native condition this is the folder-scoped NodeId string the DriverHostActor inverse map
@@ -1235,12 +1256,72 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
NativeAlarmAckRouter?.Invoke(new NativeAlarmAck(
ConditionNodeId: condition.NodeId.Identifier?.ToString() ?? string.Empty,
Comment: comment?.Text,
OperatorUser: identity.DisplayName ?? string.Empty));
OperatorUser: AlarmOperatorName(identity!)));
// Good ⇒ the SDK applies the node-state change + auto-fires its own condition event.
return ServiceResult.Good;
}
/// <summary>
/// The one authorization gate both alarm-command paths share — scripted
/// (<see cref="HandleAlarmCommand"/>) and native (<see cref="HandleNativeAlarmAck"/>).
/// </summary>
/// <remarks>
/// <para>
/// Extracted in #520 stage 5 because the two had a copy of the same role check and were about
/// to acquire a copy of the same ACL check. They must not drift: an ack that the scripted path
/// refuses and the native path allows is a hole whose shape depends on which kind of alarm the
/// operator happened to click.
/// </para>
/// <para>
/// With ACLs enforced, the Part 9 <c>Acknowledge</c> / <c>Confirm</c> / shelve calls map onto
/// their own <see cref="OpcUaOperation"/> members, so a grant CAN distinguish them — unlike the
/// role gate this replaces, where one <c>AlarmAck</c> role covered all three. Anything not
/// recognised as confirm or shelve is treated as an acknowledge, which is the most restrictive
/// reading available: <c>AlarmAcknowledge</c> is the permission an operator authoring "can this
/// principal act on alarms at all" grants first.
/// </para>
/// </remarks>
/// <param name="identity">The role-carrying identity off the SDK context, or null.</param>
/// <param name="condition">The condition the method targets.</param>
/// <param name="operation">The Part 9 operation name.</param>
/// <returns><c>null</c> to proceed; otherwise the veto to return to the SDK.</returns>
private ServiceResult? EvaluateAlarmCommandGate(
RoleCarryingUserIdentity? identity, ConditionState condition, string operation)
{
if (AclEnforced)
{
return _authorizer!.Authorize(
identity, AlarmOperationFor(operation), condition.NodeId, RealmOf(condition.NodeId));
}
// Fail closed: no role / no identity ⇒ veto. Returning a bad ServiceResult aborts the SDK's
// state change and surfaces the status to the client; we never route or mutate.
return identity is null
|| !identity.Roles.Contains(OpcUaDataPlaneRoles.AlarmAck, StringComparer.OrdinalIgnoreCase)
? new ServiceResult(StatusCodes.BadUserAccessDenied)
: null;
}
/// <summary>Maps a Part 9 method name onto the permission it requires.</summary>
/// <param name="operation">The Part 9 operation name.</param>
/// <returns>The operation to authorize.</returns>
internal static OpcUaOperation AlarmOperationFor(string operation) => operation switch
{
"Confirm" => OpcUaOperation.AlarmConfirm,
"OneShotShelve" or "TimedShelve" or "Unshelve" => OpcUaOperation.AlarmShelve,
_ => OpcUaOperation.AlarmAcknowledge,
};
/// <summary>
/// The operator name recorded on an alarm command. Prefers the ACL principal over the SDK display
/// name, which for a key-bearing client is the static username every key presents.
/// </summary>
/// <param name="identity">The authenticated identity.</param>
/// <returns>The name to record.</returns>
private static string AlarmOperatorName(RoleCarryingUserIdentity identity) =>
identity.Principal.Length > 0 ? identity.Principal : identity.DisplayName ?? string.Empty;
/// <summary>
/// The <see cref="NodeValueEventHandler"/> attached to a writable equipment-tag variable by
/// <see cref="EnsureVariable"/>. The OPC UA SDK invokes it when a client writes the
@@ -1284,7 +1365,15 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
{
var identity = (context as ISessionOperationContext)?.UserIdentity as RoleCarryingUserIdentity;
var gateway = _nodeWriteGateway;
var gate = EvaluateEquipmentWriteGate(identity, gateway is not NullOpcUaNodeWriteGateway);
var gatewayWired = gateway is not NullOpcUaNodeWriteGateway;
// #520 stage 5. With ACLs enforced the scoped decision REPLACES the server-wide WriteOperate role
// check — see AclOptions for why chaining them would leave every narrow grant inert. The
// gateway-wired check applies either way: it is an availability fact, not an authorization one.
var gate = AclEnforced
? _authorizer!.Authorize(identity, OpcUaOperation.WriteOperate, node.NodeId, RealmOf(node.NodeId))
?? (gatewayWired ? null : new ServiceResult(StatusCodes.BadNotWritable, "writes unavailable"))
: EvaluateEquipmentWriteGate(identity, gatewayWired);
if (gate is not null) return gate;
// Item A (synchronous structural fail-fast): reject a structurally-invalid write INLINE — return Bad
@@ -1314,7 +1403,9 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
// event can populate ClientUserId. Resolved here off the same identity the gate used (null when the
// session is anonymous / carries no role-carrying identity — the gate would already have vetoed, so in
// practice non-null on this path, but kept defensive).
var clientUserId = identity?.DisplayName;
// Prefer the ACL principal: for a key-bearing client DisplayName is the static username every key
// presents ("apikey"), so an audit trail built on it cannot tell two consuming systems apart.
var clientUserId = identity is { Principal.Length: > 0 } ? identity.Principal : identity?.DisplayName;
// Fire-and-forget — MUST NOT block under Lock. On a FAILED outcome, compare-and-revert (off-Lock
// continuation). A faulted/cancelled WriteAsync is treated as a failure so the optimistic value never
@@ -2520,6 +2611,67 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
// backend throw) never throws out of the batch.
// ---------------------------------------------------------------------------------------------
/// <summary>
/// Drops the handles in a HistoryRead batch the calling session is not granted
/// <see cref="OpcUaOperation.HistoryRead"/> on, marking each denied slot
/// <c>BadUserAccessDenied</c> (#520 stage 5).
/// </summary>
/// <remarks>
/// <para>
/// <b>Until this stage HistoryRead carried no authorization check whatsoever</b> — any session
/// that could open a connection could read the full history of every historized node. It was
/// not a regression; it had simply never been gated, because the only two gates in the server
/// were the write and alarm role checks.
/// </para>
/// <para>
/// Denial is <b>per node, not per batch</b>: OPC UA Part 11 gives every node in a HistoryRead
/// its own result slot, and a client reading ten nodes of which one is off-limits should get
/// nine answers and one denial rather than a whole failed request. Failing the batch would also
/// leak more than it protects — the client learns exactly which read was refused either way,
/// but a batch failure additionally denies data it was entitled to.
/// </para>
/// <para>
/// Returns the original list unchanged when enforcement is off, so the non-ACL path allocates
/// nothing and behaves exactly as before.
/// </para>
/// </remarks>
/// <param name="context">The SDK context carrying the session identity.</param>
/// <param name="nodesToProcess">The pre-filtered handles the base dispatcher built.</param>
/// <param name="results">The service-level results list.</param>
/// <param name="errors">The service-level errors list.</param>
/// <returns>The handles that may proceed.</returns>
private List<NodeHandle> AuthorizeHistoryRead(
ServerSystemContext context,
List<NodeHandle> nodesToProcess,
IList<SdkHistoryReadResult> results,
IList<ServiceResult> errors)
{
if (!AclEnforced) return nodesToProcess;
var identity = (context as ISessionOperationContext)?.UserIdentity as RoleCarryingUserIdentity
?? context.OperationContext?.UserIdentity as RoleCarryingUserIdentity;
var allowed = new List<NodeHandle>(nodesToProcess.Count);
foreach (var handle in nodesToProcess)
{
var veto = _authorizer!.Authorize(
identity, OpcUaOperation.HistoryRead, handle.NodeId, RealmOf(handle.NodeId));
if (veto is null)
{
allowed.Add(handle);
continue;
}
// Set both slots explicitly rather than relying on the base's pre-seeded
// BadHistoryOperationUnsupported — "unsupported" would tell the client the node has no history,
// which is a different fact from "you may not read it" and sends them debugging the wrong thing.
errors[handle.Index] = veto;
results[handle.Index] = new SdkHistoryReadResult { StatusCode = StatusCodes.BadUserAccessDenied };
}
return allowed;
}
/// <inheritdoc />
protected override void HistoryReadRawModified(
ServerSystemContext context,
@@ -2532,6 +2684,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
IDictionary<NodeId, NodeState> cache)
{
var session = context.OperationContext?.Session;
nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors);
WithHistoryReadBatchLimiter(nodesToProcess, results, errors, () =>
{
using var deadline = CreateDeadline();
@@ -2569,6 +2722,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
{
// OPC UA ProcessingInterval is a Duration in milliseconds — convert once per batch.
var interval = TimeSpan.FromMilliseconds(details.ProcessingInterval);
nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors);
WithHistoryReadBatchLimiter(nodesToProcess, results, errors, () =>
{
using var deadline = CreateDeadline();
@@ -2618,6 +2772,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
{
// Snapshot the requested timestamps once — the same list is read for every node.
var timestamps = details.ReqTimes?.ToList() ?? new List<DateTime>();
nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors);
WithHistoryReadBatchLimiter(nodesToProcess, results, errors, () =>
{
using var deadline = CreateDeadline();
@@ -2649,6 +2804,7 @@ public sealed class OtOpcUaNodeManager : CustomNodeManager2
// Snapshot the select clauses once — the same filter projects every node's events.
var selectClauses = details.Filter?.SelectClauses ?? new SimpleAttributeOperandCollection();
nodesToProcess = AuthorizeHistoryRead(context, nodesToProcess, results, errors);
WithHistoryReadBatchLimiter(nodesToProcess, results, errors, () =>
{
using var deadline = CreateDeadline();