feat(acl): variable-depth scope model + the scopePaths producer (#520 stage 3)

Makes the /raw device tree addressable by an ACL rule, and builds the
scope-path producer PermissionTrieBuilder has accepted since it was written
but which had no caller anywhere.

The plan for this stage said "add NodeHierarchyKind.Raw, whose path is the
RawPath segments Folder/Driver/Device/TagGroup/Tag". That shape is wrong.
RawFolder.ParentRawFolderId and TagGroup.ParentTagGroupId are both
self-referencing, so folders and tag groups each nest without bound and a real
RawPath is folder…/Driver/Device/group…/Tag. NodeScope was fixed-arity and
PermissionTrie.CollectMatches was five hardcoded steps, so the scope model
could not address a real raw tree at all. NodeScope is now {ClusterId, Kind,
Segments} and the walk is a segment loop. The trie STRUCTURE was already
variable-depth (NodeAclPath.Segments is a list, Children is a recursive
dictionary), so only the walker and the scope record had to change.

Four decisions worth keeping:

- The namespace level became the realm. Level 1 gated on NodeScope.NamespaceId,
  but v3 has no Namespace entity — the snapshot was retired when the address
  space went dual-namespace, and the identifier appears nowhere in production
  outside NodeScope. So the level could only ever fail to match, which silently
  made every sub-cluster grant unreachable while cluster grants kept working.
  It is now a realm token derived from the scope's Kind, not carried on it, so
  the walk and the producer cannot disagree about its spelling.
- Provenance comes from the granting row's own ScopeKind, recorded on TrieGrant
  at build time. Depth-derived provenance could not name a raw level at all,
  since the depth of "Device" varies with folder nesting.
- The trie comparer moved from OrdinalIgnoreCase to Ordinal. Raw sibling-name
  uniqueness is ordinal, so Speed and speed can both exist under one device and
  a grant on either would have matched both.
- The null-scopePaths "deterministic test mode" is deleted. It planted
  unresolvable rows at a direct child of the trie root, a position the walker
  cannot reach, so the grant looked placed and could never match — and every
  test using that mode proved nothing about production placement. scopePaths is
  now required, and a row that does not resolve is dropped with a diagnostic.

A scope resolves to a LIST of paths: a raw tag projected into N equipments is
reachable at N+1 NodeIds and a write through any of them lands on the same
driver reference, so a Tag-scoped grant covering only the raw node would be
bypassable through a UNS one. The lookup is keyed on (ScopeKind, ScopeId), not
ScopeId alone — ScopeId has no FK and no type discriminator, so an id collision
across entity types would hand a grant the wrong node's paths.

Also closed here, all found by review rather than asked for:

- NodeAcl rows had no deploy-time validation of any kind and were not reachable
  from DraftValidator at all (DraftSnapshot carried no NodeAcls). They are now
  gated for dangling ids, cross-cluster scopes, blank/contradictory ScopeId, the
  retired FolderSegment kind, and undefined ordinals.
- ConfigDbApiKeyStore conferred roles from Cluster-scoped grants authored in ANY
  cluster, because it filtered on scope kind with no ClusterId predicate while
  ArtifactApiKeyStore read an already-cluster-filtered snapshot. On a fused
  admin+driver node that was a cross-cluster over-grant. Its doc comment claimed
  the two stores matched.
- The two AdminUI ACL banners still said enforcement was LDAP-group -> role
  mapping, which stages 1/2 made false in both directions.
- The /apikeys page was never classified in PageAuthorizationGuardTests, so that
  test has been red since the key-minting commit merged — I did not run
  AdminUI.Tests before merging stage 4.

Falsified rather than assumed: 8 mutations against the trie tests, 5 against the
deploy gate (including one proving a cross-cluster row is not silently
mis-diagnosed as unresolved), a staged red->green for the over-grant regression,
and the realm gate, the comparer and the malformed-path guard each broken
individually to confirm only their own tests go red.

Node ACLs are still not ENFORCED — nothing constructs a NodeScope or calls the
evaluator yet. That is stages 5 and 6; this stage makes the model able to
express what those will enforce.

Claude-Session: https://claude.ai/code/session_015p7wGqy3YpZNCpDzTpGMKo
This commit is contained in:
Joseph Doherty
2026-08-01 01:07:59 -04:00
parent fbe7403ca5
commit 3a6b2a1daf
28 changed files with 3063 additions and 363 deletions
@@ -1,18 +1,62 @@
namespace ZB.MOM.WW.OtOpcUa.Configuration.Enums;
/// <summary>ACL scope level. Per <c>acl-design.md</c> §"Scope Hierarchy".</summary>
/// <remarks>
/// ⚠️ <b>Append new members only — never insert.</b> SQL Server stores this as a string
/// (<c>nvarchar(16)</c>, so a member name must also stay ≤ 16 characters), but the deployment
/// artifact serialises it as the <b>integer ordinal</b> and the node-side decoder reads it back
/// with <c>Enum.IsDefined</c>. Inserting a member mid-enum silently re-maps every grant in every
/// already-deployed artifact to a different scope level.
/// </remarks>
public enum NodeAclScopeKind
{
/// <summary>The whole cluster — the only kind that carries a null <c>ScopeId</c>.</summary>
Cluster,
Namespace,
UnsArea,
UnsLine,
Equipment,
/// <summary>
/// A folder segment anchored below a namespace (used for FolderPath-scoped tags).
/// Distinguishes folder grants from UNS <see cref="Equipment"/> grants in the
/// <c>AuthorizationDecision.Provenance</c> audit trail and Admin UI diagnostics.
/// One whole OPC UA namespace (realm). <c>ScopeId</c> is the realm token <c>raw</c> or
/// <c>uns</c>; see <c>NodeAclRealms</c>, which is the single authority for that spelling.
/// </summary>
Namespace,
/// <summary>A UNS area. <c>ScopeId</c> is a <c>UnsArea.UnsAreaId</c>.</summary>
UnsArea,
/// <summary>A UNS line. <c>ScopeId</c> is a <c>UnsLine.UnsLineId</c>.</summary>
UnsLine,
/// <summary>A UNS equipment. <c>ScopeId</c> is an <c>Equipment.EquipmentId</c>.</summary>
Equipment,
/// <summary>
/// ⚠️ <b>Retired v2 concept — do not author new rows with this kind.</b> It described a folder
/// segment under the v2 <c>SystemPlatform</c>/Galaxy hierarchy, which v3 deleted along with the
/// <c>WalkSystemPlatform</c> walker. The v3 replacement is <see cref="RawFolder"/>. The member
/// survives only because removing it would shift every later ordinal in already-deployed
/// artifacts; a row still carrying it resolves no scope path and is reported as an unresolved
/// scope by the deploy gate.
/// </summary>
FolderSegment,
/// <summary>
/// A single tag. <c>ScopeId</c> is a <c>Tag.TagId</c> — i.e. a <b>raw</b> tag, which is the only
/// kind of tag v3 has. Because one raw tag can be projected into several equipments by
/// <c>UnsTagReference</c> rows, a Tag-scoped grant resolves to <b>several</b> trie paths: the raw
/// node plus every UNS projection of it. That is deliberate — a write routes to the same driver
/// reference through either NodeId, so a grant that covered only one of them would be bypassable
/// through the other.
/// </summary>
Tag,
/// <summary>A raw-tree folder. <c>ScopeId</c> is a <c>RawFolder.RawFolderId</c>. (v3; appended.)</summary>
RawFolder,
/// <summary>A raw-tree driver instance. <c>ScopeId</c> is a <c>DriverInstance.DriverInstanceId</c>. (v3; appended.)</summary>
RawDriver,
/// <summary>A raw-tree device. <c>ScopeId</c> is a <c>Device.DeviceId</c>. (v3; appended.)</summary>
RawDevice,
/// <summary>A raw-tree tag group. <c>ScopeId</c> is a <c>TagGroup.TagGroupId</c>. (v3; appended.)</summary>
RawTagGroup,
}
@@ -62,6 +62,10 @@ public sealed class DraftSnapshot
/// <summary>Gets the list of poll groups.</summary>
public IReadOnlyList<PollGroup> PollGroups { get; init; } = [];
/// <summary>ACL grants. Drive the scope-resolution rule: a scope that names nothing deployed is
/// silently dropped when the permission trie is built, so the grant has to be caught here instead.</summary>
public IReadOnlyList<NodeAcl> NodeAcls { get; init; } = [];
/// <summary>Prior Equipment rows (any generation, same cluster) for stability checks.</summary>
public IReadOnlyList<Equipment> PriorEquipment { get; init; } = [];
@@ -52,6 +52,7 @@ public static class DraftSnapshotFactory
ScriptedAlarms = await db.ScriptedAlarms.AsNoTracking().ToListAsync(ct),
Scripts = await db.Scripts.AsNoTracking().ToListAsync(ct),
PollGroups = await db.PollGroups.AsNoTracking().ToListAsync(ct),
NodeAcls = await db.NodeAcls.AsNoTracking().ToListAsync(ct),
PriorEquipment = [], // intentional: no prior-generation table to diff against at this level
ActiveReservations = await db.ExternalIdReservations
.AsNoTracking()
@@ -1,4 +1,5 @@
using System.Text.RegularExpressions;
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
@@ -42,9 +43,235 @@ public static class DraftValidator
ValidateEquipReferenceResolution(draft, errors);
ValidateCalculationTags(draft, errors);
ValidateSqlConnectionStringNotPersisted(draft, errors);
ValidateNodeAclScopes(draft, errors);
return errors;
}
/// <summary>
/// #520 stage 3: every <see cref="NodeAcl"/> row's scope must name something the deployed address
/// space actually contains.
/// </summary>
/// <remarks>
/// <para>
/// ACL rows have had <b>no</b> validation anywhere until now, and the failure mode is the worst
/// shape a security control can have: <c>AclScopePathResolver</c> returns no path for a scope it
/// cannot resolve, the trie builder then drops the grant with a build-time diagnostic, and the
/// deploy still seals green. An operator who mistypes a <c>ScopeId</c>, or scopes a grant at an
/// entity someone later deleted, gets a row that reads as a live grant in the AdminUI and
/// authorizes nothing at runtime. Silently dropping a grant is fail-closed and therefore safe,
/// but it is not <em>visible</em> — which is why the check belongs at the deploy gate, where the
/// author is still standing in front of the mistake.
/// </para>
/// <para>
/// <b>The realm tokens are duplicated here, deliberately.</b> <c>NodeAclRealms</c> in
/// <c>Core.Authorization</c> is the authority for their spelling, but <c>Core</c> references
/// <c>Configuration</c> and not the reverse, so this project cannot reach it. The two namespace
/// <em>URIs</em> come from <see cref="V3NodeIds"/> in <c>Commons</c>, which both sides do share;
/// only the two short tokens are literals. If a third realm is ever added, it must be added in
/// both places — the accepted cost of not inverting the project graph for one gate.
/// </para>
/// <para>
/// Existence is checked with the same ordinal, untrimmed comparison
/// <c>AclScopePathResolver</c>'s dictionary lookups use, so a row this rule passes is a row that
/// resolver resolves. The realm check mirrors <c>NodeAclRealms.TryCanonicalize</c> instead
/// (trimmed, case-insensitive) for the same reason.
/// </para>
/// <para>
/// <b>Containment is checked as well as existence.</b> A grant in cluster A naming an entity that
/// belongs to cluster B is not the "names nothing" failure — it resolves to a real trie path, and
/// so it silently confers authority across a cluster boundary. It gets its own code because the
/// remedy is different: an unresolved id is a typo or a deletion, a cross-cluster id is a grant
/// authored against the wrong cluster. The lookups are deliberately <b>fleet-wide, not
/// cluster-filtered</b> — a per-cluster lookup would make a cross-cluster id present as merely
/// unresolved, which is the wrong diagnosis and would leave this check unable to ever fire.
/// </para>
/// <para>
/// Ownership is not a uniform property. <c>RawFolder</c>, <c>DriverInstance</c> and <c>UnsArea</c>
/// carry <c>ClusterId</c>; <c>Device</c>, <c>TagGroup</c>, <c>Tag</c>, <c>UnsLine</c> and
/// <c>Equipment</c> do not, and inherit it through their parent. Both chains are at most three
/// hops and neither can loop (<c>TagGroup</c> and <c>RawFolder</c> nest, but both reach the
/// cluster through a non-nesting link — <c>DeviceId</c> and <c>ClusterId</c> respectively), so
/// unlike the resolver's ancestry walks these need no depth guard. A broken chain means the
/// owning cluster is unknowable, which is the same state as unresolvable: it reports
/// <c>NodeAclScopeUnresolved</c> and never both codes.
/// </para>
/// </remarks>
private static void ValidateNodeAclScopes(DraftSnapshot draft, List<ValidationError> errors)
{
if (draft.NodeAcls.Count == 0) return;
// One map per ancestry link, built once for the whole pass. Their key sets double as the existence
// sets, so "does this id name a row of the kind's type" and "which cluster owns it" cannot disagree.
// GroupBy/First rather than ToDictionary: a duplicated id is another rule's business, and throwing
// here would take down every remaining check in the same pass.
var folderCluster = Link(draft.RawFolders, f => f.RawFolderId, f => f.ClusterId);
var driverCluster = Link(draft.DriverInstances, d => d.DriverInstanceId, d => d.ClusterId);
var deviceDriver = Link(draft.Devices, d => d.DeviceId, d => d.DriverInstanceId);
var groupDevice = Link(draft.TagGroups, g => g.TagGroupId, g => g.DeviceId);
var tagDevice = Link(draft.Tags, t => t.TagId, t => t.DeviceId);
var areaCluster = Link(draft.UnsAreas, a => a.UnsAreaId, a => a.ClusterId);
var lineArea = Link(draft.UnsLines, l => l.UnsLineId, l => l.UnsAreaId);
var equipLine = Link(draft.Equipment, e => e.EquipmentId, e => e.UnsLineId);
static Dictionary<string, string> Link<T>(
IReadOnlyList<T> rows, Func<T, string> key, Func<T, string> value) =>
rows.GroupBy(key, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => value(g.First()), StringComparer.Ordinal);
// Owning cluster, or null when a link in the chain is dangling. Direct-ClusterId kinds bottom out
// immediately; the rest hop through their parent.
string? ClusterOfDevice(string deviceId) =>
deviceDriver.TryGetValue(deviceId, out var driverId) ? driverCluster.GetValueOrDefault(driverId) : null;
string? ClusterOfLine(string lineId) =>
lineArea.TryGetValue(lineId, out var areaId) ? areaCluster.GetValueOrDefault(areaId) : null;
foreach (var acl in draft.NodeAcls)
{
var id = acl.NodeAclId;
// An ordinal outside the enum comes from a hand-edited row or a schema the code no longer
// matches. Every later check switches on the kind, so nothing below it would be meaningful.
if (!Enum.IsDefined(acl.ScopeKind))
{
errors.Add(new("NodeAclScopeKindUndefined",
$"NodeAcl '{id}' has ScopeKind ordinal {(int)acl.ScopeKind}, which is not a defined " +
"NodeAclScopeKind; the row cannot be evaluated. Re-author it with a valid scope kind.",
id));
continue;
}
if (acl.ScopeKind == NodeAclScopeKind.Cluster)
{
// Cluster is the one kind with nothing to point at, so a ScopeId here means the author
// intended a narrower scope and picked the wrong kind — the grant is cluster-wide either
// way, i.e. broader than intended, which is the direction that must never pass silently.
if (!string.IsNullOrWhiteSpace(acl.ScopeId))
errors.Add(new("NodeAclScopeIdUnexpected",
$"NodeAcl '{id}' is Cluster-scoped but carries ScopeId '{acl.ScopeId}'. A Cluster grant " +
"covers the whole cluster and ignores ScopeId; clear it, or change ScopeKind to the level " +
"the id names.",
id));
continue;
}
// Ahead of the missing-ScopeId check on purpose: the retirement is the actionable fact, and
// telling someone to supply a ScopeId for a kind that can never resolve sends them the wrong way.
if (acl.ScopeKind == NodeAclScopeKind.FolderSegment)
{
errors.Add(new("NodeAclScopeKindRetired",
$"NodeAcl '{id}' uses the retired v2 scope kind FolderSegment, which has no v3 entity behind " +
"it and can never resolve, whatever its ScopeId. Re-scope the grant to RawFolder (the v3 " +
"replacement) and point ScopeId at the RawFolderId that replaced the old folder segment.",
id));
continue;
}
if (string.IsNullOrWhiteSpace(acl.ScopeId))
{
errors.Add(new("NodeAclScopeIdMissing",
$"NodeAcl '{id}' has ScopeKind {acl.ScopeKind} but no ScopeId. Only Cluster grants may omit " +
"it; every other kind resolves no scope path without one and the grant is dropped at build " +
"time. Set the ScopeId, or change ScopeKind to Cluster.",
id));
continue;
}
var scopeId = acl.ScopeId!;
if (acl.ScopeKind == NodeAclScopeKind.Namespace)
{
if (CanonicalRealm(scopeId) is null)
errors.Add(new("NodeAclNamespaceInvalid",
$"NodeAcl '{id}' is Namespace-scoped but ScopeId '{scopeId}' names no OPC UA namespace. " +
$"Use '{RealmRaw}' or '{RealmUns}' (or the full URI '{V3NodeIds.RawNamespaceUri}' / " +
$"'{V3NodeIds.UnsNamespaceUri}').",
id));
continue;
}
// Each arm names the entity type the kind's ScopeId is drawn from, whether a row with that id
// exists at all, and which cluster owns it. Switch arms evaluate lazily, so only the matched
// kind's chain is walked.
var (entity, exists, owner) = acl.ScopeKind switch
{
NodeAclScopeKind.UnsArea =>
("UnsArea", areaCluster.ContainsKey(scopeId), areaCluster.GetValueOrDefault(scopeId)),
NodeAclScopeKind.UnsLine =>
("UnsLine", lineArea.ContainsKey(scopeId), ClusterOfLine(scopeId)),
NodeAclScopeKind.Equipment =>
("Equipment", equipLine.ContainsKey(scopeId),
equipLine.TryGetValue(scopeId, out var eqLine) ? ClusterOfLine(eqLine) : null),
NodeAclScopeKind.Tag =>
("Tag", tagDevice.ContainsKey(scopeId),
tagDevice.TryGetValue(scopeId, out var tagDev) ? ClusterOfDevice(tagDev) : null),
NodeAclScopeKind.RawFolder =>
("RawFolder", folderCluster.ContainsKey(scopeId), folderCluster.GetValueOrDefault(scopeId)),
NodeAclScopeKind.RawDriver =>
("DriverInstance", driverCluster.ContainsKey(scopeId), driverCluster.GetValueOrDefault(scopeId)),
NodeAclScopeKind.RawDevice =>
("Device", deviceDriver.ContainsKey(scopeId), ClusterOfDevice(scopeId)),
NodeAclScopeKind.RawTagGroup =>
("TagGroup", groupDevice.ContainsKey(scopeId),
groupDevice.TryGetValue(scopeId, out var grpDev) ? ClusterOfDevice(grpDev) : null),
// Cluster / Namespace / FolderSegment all returned above; the undefined case did too.
_ => (string.Empty, true, acl.ClusterId),
};
if (!exists)
{
errors.Add(new("NodeAclScopeUnresolved",
$"NodeAcl '{id}' is scoped at {acl.ScopeKind} '{scopeId}', which is not a {entity} in this " +
"configuration. The grant would be dropped at build time and authorize nothing. Correct the " +
"ScopeId, or delete the grant if the entity was removed.",
id));
continue;
}
if (owner is null)
{
// The row exists but its parent chain is dangling, so it has no place in any cluster's tree
// and resolves to no path — the same outcome as a missing row, reported under the same code.
errors.Add(new("NodeAclScopeUnresolved",
$"NodeAcl '{id}' is scoped at {acl.ScopeKind} '{scopeId}', which exists but whose parent " +
$"chain is broken, so no cluster owns it and it resolves to no scope path. Repair the {entity}'s " +
"parent reference, or delete the grant.",
id));
continue;
}
if (!string.Equals(owner, acl.ClusterId, StringComparison.Ordinal))
errors.Add(new("NodeAclScopeCrossCluster",
$"NodeAcl '{id}' is a grant in cluster '{acl.ClusterId}' but is scoped at {acl.ScopeKind} " +
$"'{scopeId}', which belongs to cluster '{owner}'. The id is real, so the grant would resolve " +
"and confer authority across a cluster boundary. Re-author the grant under cluster " +
$"'{owner}', or point ScopeId at the matching {entity} in '{acl.ClusterId}'.",
id));
}
}
// Realm tokens — see ValidateNodeAclScopes for why these are duplicated rather than referenced.
// Core.Authorization.NodeAclRealms is the authority; keep the two in step.
private const string RealmRaw = "raw";
private const string RealmUns = "uns";
/// <summary>Mirror of <c>NodeAclRealms.TryCanonicalize</c>: accepts either short realm token or either
/// full namespace URI, trimmed and case-insensitive. Null when the id names no realm.</summary>
private static string? CanonicalRealm(string scopeId)
{
var trimmed = scopeId.Trim();
if (string.Equals(trimmed, RealmRaw, StringComparison.OrdinalIgnoreCase)
|| string.Equals(trimmed, V3NodeIds.RawNamespaceUri, StringComparison.OrdinalIgnoreCase))
return RealmRaw;
if (string.Equals(trimmed, RealmUns, StringComparison.OrdinalIgnoreCase)
|| string.Equals(trimmed, V3NodeIds.UnsNamespaceUri, StringComparison.OrdinalIgnoreCase))
return RealmUns;
return null;
}
/// <summary>
/// The <c>Sql</c> driver's "a pasted literal connection string is never persisted" guarantee, enforced
/// at the deploy gate (Gitea #498).