fix(acl): close the #808 review findings — reference variables, owner folder chain, NUL keys, unknown ids (#808)

Review of af5c9744:
1. UNS reference variables (s=Area/Line/Equip/Eff) of a moved or renamed
   equipment stayed readable/writable under the OLD names' grants: they now
   resolve as ReferenceVariable and are authorized at their split path only
   while it equals their live equipment folder's placement (live chain ==
   generation chain) + one name; otherwise denied (Read and Write).
2. TryPlaceScriptedCondition now also requires the owner folder's live chain
   to match the generation (AuthorizeScriptedCondition gains ownerFolderChain),
   so a moved equipment's alarm/children/commands follow its folder.
3. Identifiers containing NUL are denied before the decision cache, keeping
   client ids disjoint from the NUL-prefixed resolved-scope keys (a client
   could otherwise poison a real folder's cached verdict for its key shard).
4. An id no live node holds is Unknown: placed at [\0unknown] so only
   Cluster / Namespace-uns grants decide it (a removed opaque id can no longer
   split onto a same-named narrow grant; narrow grantees get no NodeDeleted for
   removed UNS folders/vtags/conditions — documented); 4-segment
   reference-shaped ids keep their split.
5. A wire test drives placements from DeploymentArtifact.ParseDataPlaneAuthority.

Baseline updates: #797 owner tests (unit + wire) and Sdk2RepeatedAlarmAuthority
now install folder scopes; Sdk2HistoryAuthority's UNS alias used the RAW path
as its UNS id (never minted in production) and now carries EqA/HistoryAlias.
Each new guard was falsified (reverting it fails its test).
This commit is contained in:
Joseph Doherty
2026-11-10 23:44:11 -05:00
parent af5c9744b7
commit e39a125069
11 changed files with 557 additions and 64 deletions
@@ -298,6 +298,23 @@ public sealed class ScriptedAlarmOwnerScopeWireTests
new Dictionary<string, (string UnsLineId, string Name)> { [Pump] = (LineId, "Pump"), [Fan] = (LineId, "Fan") },
[]);
/// <summary>
/// The topology's UNS folder placements (Gitea #808), from the same resolver: a scripted condition is placed
/// only while its owner's live folder ancestry matches the generation's.
/// </summary>
private static Dictionary<string, UnsFolderScope> FolderScopes()
{
var resolver = Resolver();
NodeAclPath One(NodeAclScopeKind kind, string id) => resolver.ResolveOne(kind, id).ShouldHaveSingleItem();
return new Dictionary<string, UnsFolderScope>
{
[AreaId] = new(One(NodeAclScopeKind.UnsArea, AreaId), [AreaId]),
[LineId] = new(One(NodeAclScopeKind.UnsLine, LineId), [AreaId, LineId]),
[Pump] = new(One(NodeAclScopeKind.Equipment, Pump), [AreaId, LineId, Pump]),
[Fan] = new(One(NodeAclScopeKind.Equipment, Fan), [AreaId, LineId, Fan]),
};
}
private static Dictionary<string, NodeAclPath> OwnerPaths()
{
var resolver = Resolver();
@@ -324,7 +341,7 @@ public sealed class ScriptedAlarmOwnerScopeWireTests
private static void Reapply(
DataPlaneAuthorityState state, string revision, IReadOnlyDictionary<string, string> deployedOwners,
ApiKey[] keys, params NodeAcl[] grants) =>
state.Apply(ServerEventRig.Cluster, revision, keys, grants, Resolver().Resolve(grants), OwnerPaths(), deployedOwners);
state.Apply(ServerEventRig.Cluster, revision, keys, grants, Resolver().Resolve(grants), OwnerPaths(), deployedOwners, FolderScopes());
/// <summary>The generation's deployed scripted-alarm owners; <paramref name="alarmOwner"/> moves the Pump alarm.</summary>
private static Dictionary<string, string> Deployed(string alarmOwner = Pump) =>
@@ -18,6 +18,11 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
public sealed class Sdk2HistoryAuthorityWireTests
{
private const string ValuePath = RawDeviceFolder + "/History";
// Gitea #808 review: a UNS variable is authorized at its placed path, and a reference-variable id that is not
// its equipment's path + a name is denied (a moved/renamed equipment's stale ids). The alias used to reuse the
// RAW path as its UNS id — a shape production never mints — so it now carries a UNS-shaped id under EqA.
private const string AliasPath = EqA + "/HistoryAlias";
private static readonly DateTime Epoch = new(2026, 10, 1, 0, 0, 0, DateTimeKind.Utc);
public static TheoryData<string, string> Cases => new(
@@ -79,20 +84,20 @@ public sealed class Sdk2HistoryAuthorityWireTests
private static void Apply(DataPlaneAuthorityState state, ApiKey key, NodeAcl[] grants) =>
state.Apply(ServerEventRig.Cluster, Guid.NewGuid().ToString("N"), [key], grants,
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>(), unsFolderScopes: FolderScopes());
private static void Materialise(ServerEventRig rig)
{
rig.MaterialiseNative();
rig.Sink.EnsureVariable(ValuePath, RawDeviceFolder, "History", "Double", false, AddressSpaceRealm.Raw, "same-backend-tag");
rig.Sink.EnsureVariable(ValuePath, EqA, "HistoryAlias", "Double", false, AddressSpaceRealm.Uns, "same-backend-tag");
rig.Sink.EnsureVariable(AliasPath, EqA, "HistoryAlias", "Double", false, AddressSpaceRealm.Uns, "same-backend-tag");
}
private static async Task<Opc.Ua.HistoryReadResult> PageAsync(ISession session, string kind, bool alias,
ByteString point, CancellationToken ct)
{
var realm = alias ? V3NodeIds.UnsNamespaceUri : V3NodeIds.RawNamespaceUri;
var path = kind == "events" ? alias ? EqA : RawDeviceFolder : ValuePath;
var path = kind == "events" ? alias ? EqA : RawDeviceFolder : alias ? AliasPath : ValuePath;
var node = new NodeId(path, (ushort)session.NamespaceUris.GetIndex(realm));
HistoryReadDetails details = kind == "events" ? new ReadEventDetails
{
@@ -95,7 +95,7 @@ public sealed class Sdk2RepeatedAlarmAuthorityWireTests
if (change == "grant") grants = [];
if (change == "key") { var disabled = Key(); disabled.Enabled = false; keys = [disabled]; }
if (change == "expiry") clock.Advance(TimeSpan.FromMinutes(20));
else state.Apply(ServerEventRig.Cluster, "revoked", keys, grants, scopes, EquipmentOwnerPaths(), ScriptedAlarmOwners());
else state.Apply(ServerEventRig.Cluster, "revoked", keys, grants, scopes, EquipmentOwnerPaths(), ScriptedAlarmOwners(), FolderScopes());
var error = await Should.ThrowAsync<ServiceResultException>(() => session.CallAsync(condition.NodeId, methodId, ct,
Variant.From(currentId), Variant.From(new LocalizedText("must not be recorded"))));
@@ -107,7 +107,7 @@ public sealed class Sdk2RepeatedAlarmAuthorityWireTests
confirmNode.Value.ShouldBe(beforeConfirm);
// A subsequent authorized same-item sentinel drains any queued method event before the assertion.
clock.Reset();
state.Apply(ServerEventRig.Cluster, "restored", [key], [grant], scopes, EquipmentOwnerPaths(), ScriptedAlarmOwners());
state.Apply(ServerEventRig.Cluster, "restored", [key], [grant], scopes, EquipmentOwnerPaths(), ScriptedAlarmOwners(), FolderScopes());
rig.Project(native, new AlarmConditionSnapshot(true, true, true, true, AlarmShelvingKind.Unshelved, 500, "sentinel"));
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "sentinel"));
events.Of(item).Count.ShouldBe(beforeEvents + 1, "the denied retry emits nothing before the sentinel");
@@ -212,34 +212,223 @@ public sealed class UnsFolderScopeWireTests
/// <summary>
/// An EQUIPMENT moved to another line by the generation while its folder still hangs under the old line: the live
/// folder ancestry disagrees with the generation's, so the folder and everything it owns are denied under the
/// new line's grant AND the old one's. After the rebuild re-parents it, the new line's grant reads it and the old
/// line's does not.
/// folder ancestry disagrees with the generation's, so the folder, everything it owns, its scripted alarm (read
/// AND Acknowledge) and its UNS reference variable (still on its OLD-name id — read AND write) are denied under
/// the new line's grant AND the old one's. After the rebuild re-parents it (and re-ids the reference variable),
/// the new line's grant reaches all of it and the old line's reaches none of it.
/// </summary>
[Theory]
[InlineData(Line1)]
[InlineData(Line2)]
public async Task A_moved_equipment_folder_is_denied_until_the_rebuild_reparents_it(string grantedLine)
public async Task A_moved_equipment_and_everything_under_it_is_denied_until_the_rebuild_reparents_it(string grantedLine)
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync($"Uns808Folder{grantedLine[^1..]}", encrypted: false, ct);
rig.KeyRoles = [];
Topology(rig, pumpLine: Line1);
Install(rig, pumpLine: Line2, Deployed(), LineGrant(grantedLine));
var routed = Route(rig);
using var session = await rig.ConnectAsync(anonymous: false, ct);
var oldFlow = FlowId(Line1);
(await ReadAsync(session, Uns(session, Pump), Attributes.DisplayName, ct)).ShouldBe(StatusCodes.BadUserAccessDenied);
(await ReadAsync(session, Uns(session, PumpSpeed), Attributes.DisplayName, ct)).ShouldBe(StatusCodes.BadUserAccessDenied);
// Positive control: the sibling, placed identically by both, follows the grant.
(await ReadAsync(session, Uns(session, oldFlow), Attributes.DisplayName, ct)).ShouldBe(StatusCodes.BadUserAccessDenied);
(await WriteAsync(session, Uns(session, oldFlow), 1.5, ct)).ShouldBe(StatusCodes.BadUserAccessDenied);
(await ReadAsync(session, Uns(session, Alarm), Attributes.DisplayName, ct)).ShouldBe(StatusCodes.BadUserAccessDenied);
// The condition must carry a real EventId first, or the SDK refuses the call before any gate runs.
Project(rig, Alarm, new AlarmConditionSnapshot(true, false, false, true, AlarmShelvingKind.Unshelved, 700, "base"));
(await Should.ThrowAsync<ServiceResultException>(ConditionMethodEventTests.CallAsync(
session, Uns(session, Alarm), "Acknowledge", rig.Nm.TryGetAlarmCondition(Alarm)!.EventId!.Value.ToArray(), ct)))
.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied);
routed.ShouldBeEmpty();
// Positive control: the sibling, placed identically by both generations, follows the grant.
(await ReadAsync(session, Uns(session, Fan), Attributes.DisplayName, ct))
.ShouldBe(grantedLine == Line1 ? StatusCodes.Good : StatusCodes.BadUserAccessDenied);
rig.Sink.RebuildAddressSpace();
Topology(rig, pumpLine: Line2);
var expected = grantedLine == Line2 ? StatusCodes.Good : StatusCodes.BadUserAccessDenied;
var allowed = grantedLine == Line2;
var expected = allowed ? StatusCodes.Good : StatusCodes.BadUserAccessDenied;
var newFlow = FlowId(Line2);
(await ReadAsync(session, Uns(session, Pump), Attributes.DisplayName, ct)).ShouldBe(expected);
(await ReadAsync(session, Uns(session, PumpSpeed), Attributes.DisplayName, ct)).ShouldBe(expected);
(await ReadAsync(session, Uns(session, newFlow), Attributes.DisplayName, ct)).ShouldBe(expected);
(await ReadAsync(session, Uns(session, Alarm), Attributes.DisplayName, ct)).ShouldBe(expected);
var write = await WriteAsync(session, Uns(session, newFlow), 1.5, ct);
if (allowed) write.ShouldNotBe(StatusCodes.BadUserAccessDenied, "the new line's grant reaches the re-ided variable");
else write.ShouldBe(StatusCodes.BadUserAccessDenied);
Project(rig, Alarm, new AlarmConditionSnapshot(true, false, false, true, AlarmShelvingKind.Unshelved, 700, "rebuilt"));
var ack = ConditionMethodEventTests.CallAsync(
session, Uns(session, Alarm), "Acknowledge", rig.Nm.TryGetAlarmCondition(Alarm)!.EventId!.Value.ToArray(), ct);
if (allowed) await ack;
else (await Should.ThrowAsync<ServiceResultException>(ack)).StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied);
routed.Count.ShouldBe(allowed ? 1 : 0);
await session.CloseAsync(ct);
}
/// <summary>
/// An Area RENAMED by the generation before the address space re-ids its reference variables: the folders keep
/// their opaque ids (still placed — the Equipment grant reads the folder and its virtual tag), but the reference
/// variable's id still spells the OLD name, so it is denied until it is re-pointed.
/// </summary>
[Fact]
public async Task A_reference_variable_on_a_stale_name_path_is_denied_while_its_folder_is_placed()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("Uns808Rename", encrypted: false, ct);
rig.KeyRoles = [];
Topology(rig, pumpLine: Line1);
// The Tag grant's path still spells the OLD Area name (Install plants it at Area1/Line1/Pump/Flow) — standing in
// for any grant that names the old path, e.g. another Area that has since been given the name "Area1".
Install(rig, pumpLine: Line1, Deployed(), areaName: "AreaRenamed", EquipmentGrant(Pump, Operator), TagGrant());
using var session = await rig.ConnectAsync(anonymous: false, ct);
(await ReadAsync(session, Uns(session, Pump), Attributes.DisplayName, ct)).ShouldBe(StatusCodes.Good);
(await ReadAsync(session, Uns(session, PumpSpeed), Attributes.DisplayName, ct)).ShouldBe(StatusCodes.Good);
(await ReadAsync(session, Uns(session, PumpFlow), Attributes.DisplayName, ct)).ShouldBe(StatusCodes.BadUserAccessDenied);
await session.CloseAsync(ct);
}
/// <summary>
/// Review of #808 (cache poisoning): the resolved-scope cache keys are NUL-prefixed, so a client that first
/// Reads the nonexistent <c>s="\0Area1\0Line1\0Pump"</c> — the exact cache key of the real Pump folder — must
/// not memoize a deny the real folder then inherits. A NUL-bearing id is refused before the cache.
/// </summary>
[Fact]
public async Task A_nul_bearing_identifier_cannot_poison_a_resolved_scopes_cached_verdict()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("Uns808Nul", encrypted: false, ct);
rig.KeyRoles = [];
Topology(rig, pumpLine: Line1);
Install(rig, pumpLine: Line1, Deployed(), EquipmentGrant(Pump, Operator));
using var session = await rig.ConnectAsync(anonymous: false, ct);
(await ReadAsync(session, Uns(session, "\u0000Area1\u0000Line1\u0000Pump"), Attributes.DisplayName, ct))
.ShouldBe(StatusCodes.BadUserAccessDenied);
(await ReadAsync(session, Uns(session, Pump), Attributes.DisplayName, ct)).ShouldBe(StatusCodes.Good);
(await ReadAsync(session, Uns(session, Pump), Attributes.DisplayName, ct)).ShouldBe(StatusCodes.Good);
await session.CloseAsync(ct);
}
/// <summary>
/// Review of #808: an identifier NO live node holds (a removed folder, virtual tag or scripted alarm — what a
/// NodeDeleted model change names — or a probe) is decided only by a realm-wide grant. It no longer splits, so a
/// removed opaque id never matches a narrow grant on an unrelated entity of the same NAME (an Area named like a
/// removed alarm id). A reference-variable-shaped id (four segments) keeps its name-path split.
/// </summary>
[Fact]
public async Task An_unknown_uns_identifier_is_decided_only_by_a_realm_wide_grant()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("Uns808Unknown", encrypted: false, ct);
rig.KeyRoles = [];
Topology(rig, pumpLine: Line1);
Install(rig, pumpLine: Line1, Deployed(),
KeyGrant("area", NodeAclScopeKind.UnsArea, AreaId, NodePermissions.ReadOnly),
new NodeAcl
{
NodeAclId = "anon-cluster", ClusterId = ServerEventRig.Cluster, Principal = OpcUaPrincipals.Anonymous,
ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.ReadOnly,
});
using var narrow = await rig.ConnectAsync(anonymous: false, ct);
using var wide = await rig.ConnectAsync(anonymous: true, ct);
// "Area1" is the granted Area's NAME — a removed scripted alarm with that id used to split onto it.
foreach (var gone in new[] { "Area1", "EQ-00000000dead", "Area1/Line1", "scripted-removed/EnabledState" })
{
(await ReadAsync(narrow, Uns(narrow, gone), Attributes.DisplayName, ct))
.ShouldBe(StatusCodes.BadUserAccessDenied, gone);
(await ReadAsync(wide, Uns(wide, gone), Attributes.DisplayName, ct))
.ShouldBe(StatusCodes.BadNodeIdUnknown, $"{gone}: a realm-wide grant still decides it");
}
// A four-segment (reference-variable-shaped) id keeps its name-path split under the Area grant.
(await ReadAsync(narrow, Uns(narrow, "Area1/Line1/Pump/Gone"), Attributes.DisplayName, ct))
.ShouldBe(StatusCodes.BadNodeIdUnknown);
// Positive control: the live Area folder itself.
(await ReadAsync(narrow, Uns(narrow, AreaId), Attributes.DisplayName, ct)).ShouldBe(StatusCodes.Good);
await narrow.CloseAsync(ct);
await wide.CloseAsync(ct);
}
/// <summary>
/// The placements through the PRODUCTION producer: a deployment artifact's UNS rows, scripted alarms and grant →
/// <c>DeploymentArtifact.ParseDataPlaneAuthority</c> (its folder scopes, owner paths, deployed owners and grant
/// paths) → install → wire decisions, with no hand-built scope anywhere.
/// </summary>
[Fact]
public async Task Placements_decoded_from_a_deployment_artifact_authorize_a_narrow_grant_over_the_wire()
{
var ct = TestContext.Current.CancellationToken;
await using var rig = await ServerEventRig.StartAsync("Uns808Artifact", encrypted: false, ct);
rig.KeyRoles = [];
Topology(rig, pumpLine: Line1);
var routed = Route(rig);
var artifact = $$"""
{
"UnsAreas": [{"UnsAreaId":"{{AreaId}}","ClusterId":"{{ServerEventRig.Cluster}}","Name":"Area1"}],
"UnsLines": [
{"UnsLineId":"{{Line1}}","UnsAreaId":"{{AreaId}}","Name":"Line1"},
{"UnsLineId":"{{Line2}}","UnsAreaId":"{{AreaId}}","Name":"Line2"}
],
"Equipment": [
{"EquipmentId":"{{Pump}}","UnsLineId":"{{Line1}}","Name":"Pump"},
{"EquipmentId":"{{Fan}}","UnsLineId":"{{Line1}}","Name":"Fan"}
],
"ScriptedAlarms": [
{"ScriptedAlarmId":"{{Alarm}}","EquipmentId":"{{Pump}}","Name":"hi"},
{"ScriptedAlarmId":"{{PumpLo}}","EquipmentId":"{{Pump}}","Name":"lo"},
{"ScriptedAlarmId":"{{FanAlarm}}","EquipmentId":"{{Fan}}","Name":"fan hi"}
],
"NodeAcls": [
{"NodeAclId":"acl-pump","ClusterId":"{{ServerEventRig.Cluster}}","Principal":"{{ServerEventRig.KeyPrincipal}}",
"ScopeKind":{{(int)NodeAclScopeKind.Equipment}},"ScopeId":"{{Pump}}","PermissionFlags":{{(int)Operator}}}
]
}
""";
var projection = ZB.MOM.WW.OtOpcUa.Runtime.Drivers.DeploymentArtifact.ParseDataPlaneAuthority(
System.Text.Encoding.UTF8.GetBytes(artifact), "node-a:4840");
projection.UnsFolderScopes.Keys.Order(StringComparer.Ordinal).ShouldBe([Pump, Fan, AreaId, Line1, Line2]);
var state = new DataPlaneAuthorityState();
state.Apply(ServerEventRig.Cluster, "rev-artifact", [ServerEventRig.Key()], projection.Grants,
projection.ScopePaths, projection.EquipmentScopePaths, projection.ScriptedAlarmOwners, projection.UnsFolderScopes);
rig.Nm.DataPlaneAuthority = state;
rig.Nm.Authorizer = new DataPlaneAuthorizer(
state, new TriePermissionEvaluator(state.Tries), true, NullLogger.Instance, TimeProvider.System);
using var session = await rig.ConnectAsync(anonymous: false, ct);
(await BrowseAsync(session, Uns(session, Line1), ct)).Ids.ShouldBe([Pump]);
(await ReadAsync(session, Uns(session, Pump), Attributes.DisplayName, ct)).ShouldBe(StatusCodes.Good);
(await ReadAsync(session, Uns(session, PumpSpeed), Attributes.DisplayName, ct)).ShouldBe(StatusCodes.Good);
(await ReadAsync(session, Uns(session, PumpFlow), Attributes.DisplayName, ct)).ShouldBe(StatusCodes.Good);
(await ReadAsync(session, Uns(session, ChildId(rig, Alarm, c => c.EnabledState!.Id!)), Attributes.Value, ct))
.ShouldBe(StatusCodes.Good);
(await ReadAsync(session, Uns(session, Fan), Attributes.DisplayName, ct)).ShouldBe(StatusCodes.BadUserAccessDenied);
var events = new RecordedEvents();
var subscription = await RecordedEvents.SubscribeAsync(session, events, ct);
var server = RecordedEvents.AddEventItem(subscription, ObjectIds.Server);
await subscription.ApplyChangesAsync(ct);
var pre = new AlarmConditionSnapshot(true, false, false, true, AlarmShelvingKind.Unshelved, 700, "base");
Project(rig, FanAlarm, pre with { Message = "fan-base" });
Project(rig, Alarm, pre);
await RecordedEvents.WaitUntilAsync(() => events.Has(server, "base"));
events.Has(server, "fan-base").ShouldBeFalse();
await ConditionMethodEventTests.CallAsync(
session, Uns(session, Alarm), "Acknowledge", events.LatestEventId(server, "base"), ct);
routed.Select(c => (c.AlarmId, c.Operation)).ShouldBe([(Alarm, "Acknowledge")]);
await session.CloseAsync(ct);
}
@@ -260,19 +449,22 @@ public sealed class UnsFolderScopeWireTests
rig.Sink.EnsureFolder(Fan, parentNodeId: Line1, displayName: "Fan", realm: AddressSpaceRealm.Uns);
rig.Sink.EnsureVariable(PumpSpeed, Pump, "Speed", "Double", writable: false, AddressSpaceRealm.Uns);
rig.Sink.EnsureVariable(FanSpeed, Fan, "Speed", "Double", writable: false, AddressSpaceRealm.Uns);
rig.Sink.EnsureVariable(PumpFlow, Pump, "Flow", "Double", writable: false, AddressSpaceRealm.Uns);
rig.Sink.EnsureVariable(FlowId(pumpLine), Pump, "Flow", "Double", writable: true, AddressSpaceRealm.Uns);
rig.Sink.MaterialiseAlarmCondition(Alarm, Pump, "hi", "AlarmCondition", 500, AddressSpaceRealm.Uns);
rig.Sink.MaterialiseAlarmCondition(PumpLo, Pump, "lo", "AlarmCondition", 300, AddressSpaceRealm.Uns);
rig.Sink.MaterialiseAlarmCondition(FanAlarm, Fan, "fan hi", "AlarmCondition", 500, AddressSpaceRealm.Uns);
}
private static AclScopePathResolver Resolver(string pumpLine) => new(
/// <summary>The live reference variable's id when Pump hangs under <paramref name="pumpLine"/> (its NAME path).</summary>
private static string FlowId(string pumpLine) => $"Area1/{(pumpLine == Line1 ? "Line1" : "Line2")}/Pump/Flow";
private static AclScopePathResolver Resolver(string pumpLine, string areaName) => new(
new Dictionary<string, (string? ParentId, string Name)>(),
new Dictionary<string, (string? RawFolderId, string Name)>(),
new Dictionary<string, (string DriverInstanceId, string Name)>(),
new Dictionary<string, (string? ParentId, string DeviceId, string Name)>(),
new Dictionary<string, (string DeviceId, string? TagGroupId, string Name)>(),
new Dictionary<string, string> { [AreaId] = "Area1" },
new Dictionary<string, string> { [AreaId] = areaName },
new Dictionary<string, (string UnsAreaId, string Name)> { [Line1] = (AreaId, "Line1"), [Line2] = (AreaId, "Line2") },
new Dictionary<string, (string UnsLineId, string Name)> { [Pump] = (pumpLine, "Pump"), [Fan] = (Line1, "Fan") },
[]);
@@ -282,9 +474,16 @@ public sealed class UnsFolderScopeWireTests
/// scopes and grant paths all from ONE resolver, as <c>DeploymentArtifact.ParseDataPlaneAuthority</c> does.
/// </summary>
private static void Install(
ServerEventRig rig, string pumpLine, IReadOnlyDictionary<string, string> deployedOwners, params NodeAcl[] grants)
ServerEventRig rig, string pumpLine, IReadOnlyDictionary<string, string> deployedOwners, params NodeAcl[] grants) =>
Install(rig, pumpLine, deployedOwners, "Area1", grants);
/// <summary>As above, with the generation naming the Area <paramref name="areaName"/> (a rename the address space
/// has not caught up with when it differs from the live <c>Area1</c>).</summary>
private static void Install(
ServerEventRig rig, string pumpLine, IReadOnlyDictionary<string, string> deployedOwners, string areaName,
params NodeAcl[] grants)
{
var resolver = Resolver(pumpLine);
var resolver = Resolver(pumpLine, areaName);
var scopePaths = new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>(resolver.Resolve(grants))
{
// A Tag grant's UNS projection (the resolver would derive it from raw rows this rig does not model).
@@ -322,7 +521,7 @@ public sealed class UnsFolderScopeWireTests
KeyGrant($"eq-{equipmentId}", NodeAclScopeKind.Equipment, equipmentId, flags);
private static NodeAcl LineGrant(string lineId) =>
KeyGrant($"line-{lineId}", NodeAclScopeKind.UnsLine, lineId, NodePermissions.ReadOnly);
KeyGrant($"line-{lineId}", NodeAclScopeKind.UnsLine, lineId, Operator | NodePermissions.WriteOperate);
private static NodeAcl TagGrant() => KeyGrant("tag-flow", NodeAclScopeKind.Tag, FlowTagId, Operator);
@@ -370,6 +569,15 @@ public sealed class UnsFolderScopeWireTests
return response.Results.ToList().ShouldHaveSingleItem().StatusCode;
}
private static async Task<StatusCode> WriteAsync(ISession session, NodeId node, double value, CancellationToken ct)
{
var response = await session.WriteAsync(null, new WriteValue[]
{
new() { NodeId = node, AttributeId = Attributes.Value, Value = new DataValue(SdkTestValues.FromClr(value)) },
}, ct);
return response.Results.ToList().ShouldHaveSingleItem();
}
private static async Task<(StatusCode Status, List<string> Ids)> BrowseAsync(
ISession session, NodeId parent, CancellationToken ct)
{
@@ -72,6 +72,75 @@ public sealed class NodeManagerModelChangeFilterTests : IDisposable
finally { await host.DisposeAsync(); }
}
/// <summary>
/// Gitea #808 review — NodeDeleted delivery on a production-shaped (opaque-id) tree. A NodesAdded change for a
/// LIVE equipment folder reaches the narrow Equipment grantee (it is placed); a NodeDeleted change names a node
/// no live map holds any more, so only a realm-wide grantee receives it — the removed opaque id (a virtual tag,
/// a scripted alarm whose id equals the granted Area's NAME) is never split onto an unrelated narrow grant.
/// </summary>
[Fact]
public async Task A_removed_opaque_uns_node_is_announced_only_to_realm_wide_grantees()
{
var (host, server) = await BootAsync();
try
{
var nm = server.NodeManager!;
var sink = new SdkAddressSpaceSink(nm);
sink.EnsureFolder("UA-1", null, "Area1", AddressSpaceRealm.Uns);
sink.EnsureFolder("UL-1", "UA-1", "Line1", AddressSpaceRealm.Uns);
sink.EnsureFolder("EQ-1", "UL-1", "Pump", AddressSpaceRealm.Uns);
var state = new DataPlaneAuthorityState();
NodeAcl[] grants =
[
new NodeAcl
{
NodeAclId = "acl-eq", ClusterId = Cluster, Principal = Principal,
ScopeKind = NodeAclScopeKind.Equipment, ScopeId = "EQ-1", PermissionFlags = NodePermissions.Browse,
},
new NodeAcl
{
NodeAclId = "acl-area", ClusterId = Cluster, Principal = "area-key",
ScopeKind = NodeAclScopeKind.UnsArea, ScopeId = "UA-1", PermissionFlags = NodePermissions.Browse,
},
new NodeAcl
{
NodeAclId = "acl-all", ClusterId = Cluster, Principal = "everything",
ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Browse,
},
];
var area = new NodeAclPath([NodeAclRealms.Uns, "Area1"]);
var line = new NodeAclPath([NodeAclRealms.Uns, "Area1", "Line1"]);
var pump = new NodeAclPath([NodeAclRealms.Uns, "Area1", "Line1", "Pump"]);
state.Apply(Cluster, "rev-1", [], grants,
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>
{
[new AclScopeRef(NodeAclScopeKind.Equipment, "EQ-1")] = [pump],
[new AclScopeRef(NodeAclScopeKind.UnsArea, "UA-1")] = [area],
},
new Dictionary<string, NodeAclPath> { ["EQ-1"] = pump },
unsFolderScopes: new Dictionary<string, UnsFolderScope>
{
["UA-1"] = new(area, ["UA-1"]),
["UL-1"] = new(line, ["UA-1", "UL-1"]),
["EQ-1"] = new(pump, ["UA-1", "UL-1", "EQ-1"]),
});
nm.Authorizer = new DataPlaneAuthorizer(state, new TriePermissionEvaluator(state.Tries), true, NullLogger.Instance);
var added = nm.BuildNodesAddedModelChange("EQ-1", AddressSpaceRealm.Uns);
nm.FilterModelChangeFor(Identity(Principal), added).ShouldBeSameAs(added, "the live folder is placed");
foreach (var gone in new[] { "EQ-1/Speed", "Area1", "scripted-gone" })
{
var deleted = nm.BuildNodesRemovedModelChange(gone, AddressSpaceRealm.Uns);
nm.FilterModelChangeFor(Identity(Principal), deleted).ShouldBeNull(gone);
nm.FilterModelChangeFor(Identity("area-key"), deleted).ShouldBeNull($"{gone}: no name-collision match");
nm.FilterModelChangeFor(Identity("everything"), deleted).ShouldBeSameAs(deleted, gone);
}
}
finally { await host.DisposeAsync(); }
}
private static DataPlaneAuthorizer Authorizer(params NodeAcl[] grants)
{
var state = new DataPlaneAuthorityState();
@@ -234,7 +234,7 @@ public sealed class NodeManagerScriptedAlarmOwnerScopeTests : IDisposable
// The generation no longer places the owner (equipment deleted from the artifact while the
// node is still served): the grant's own scope stays resolvable, the owner does not.
state.Apply(Cluster, "rev-2", [key], [grant], Resolver().Resolve([grant]),
new Dictionary<string, NodeAclPath>(), Deployed());
new Dictionary<string, NodeAclPath>(), Deployed(), FolderScopes());
break;
}
@@ -595,7 +595,7 @@ public sealed class NodeManagerScriptedAlarmOwnerScopeTests : IDisposable
{
[new AclScopeRef(NodeAclScopeKind.RawDevice, "dev1")] = [new NodeAclPath([NodeAclRealms.Raw, "Plant", "Modbus", "dev1"])],
};
state.Apply(Cluster, "rev-raw", [Key()], [rawDevice], scopes, OwnerPaths(), Deployed());
state.Apply(Cluster, "rev-raw", [Key()], [rawDevice], scopes, OwnerPaths(), Deployed(), FolderScopes());
condition.OnAcknowledge!(ctx, condition, EventId(), new LocalizedText("raw grant")).ShouldBe(ServiceResult.Good);
condition.OnAddComment!(ctx, condition, EventId(), new LocalizedText("raw note")).ShouldBe(ServiceResult.Good);
@@ -684,6 +684,23 @@ public sealed class NodeManagerScriptedAlarmOwnerScopeTests : IDisposable
};
}
/// <summary>
/// Gitea #808 review: the scripted-condition placement also requires the owner's LIVE folder ancestry to match
/// the generation's, so every install here carries the topology's folder scopes (same resolver as the owners).
/// </summary>
private static Dictionary<string, UnsFolderScope> FolderScopes()
{
var resolver = Resolver();
NodeAclPath One(NodeAclScopeKind kind, string id) => resolver.ResolveOne(kind, id).ShouldHaveSingleItem();
return new Dictionary<string, UnsFolderScope>
{
[AreaId] = new(One(NodeAclScopeKind.UnsArea, AreaId), [AreaId]),
[LineId] = new(One(NodeAclScopeKind.UnsLine, LineId), [AreaId, LineId]),
[Pump] = new(One(NodeAclScopeKind.Equipment, Pump), [AreaId, LineId, Pump]),
[Fan] = new(One(NodeAclScopeKind.Equipment, Fan), [AreaId, LineId, Fan]),
};
}
private static (DataPlaneAuthorityState State, DataPlaneAuthorizer Authorizer) Wire(
OtOpcUaNodeManager nm, TimeProvider clock, ApiKey[] keys, params NodeAcl[] grants) =>
Wire(nm, clock, keys, enabled: true, Areas(), grants);
@@ -702,7 +719,7 @@ public sealed class NodeManagerScriptedAlarmOwnerScopeTests : IDisposable
IReadOnlyDictionary<string, string> areas, NodeAcl[] grants)
{
var state = new DataPlaneAuthorityState();
state.Apply(Cluster, "rev-1", keys, grants, Resolver(areas).Resolve(grants), OwnerPaths(), Deployed());
state.Apply(Cluster, "rev-1", keys, grants, Resolver(areas).Resolve(grants), OwnerPaths(), Deployed(), FolderScopes());
var authorizer = new DataPlaneAuthorizer(
state, new TriePermissionEvaluator(state.Tries), enabled, NullLogger.Instance, clock);
nm.DataPlaneAuthority = state;
@@ -717,7 +734,7 @@ public sealed class NodeManagerScriptedAlarmOwnerScopeTests : IDisposable
private static void Reapply(
DataPlaneAuthorityState state, string revision, IReadOnlyDictionary<string, string> deployedOwners,
ApiKey[] keys, params NodeAcl[] grants) =>
state.Apply(Cluster, revision, keys, grants, Resolver().Resolve(grants), OwnerPaths(), deployedOwners);
state.Apply(Cluster, revision, keys, grants, Resolver().Resolve(grants), OwnerPaths(), deployedOwners, FolderScopes());
/// <summary>
/// The generation's deployed scripted-alarm owners (the artifact's <c>ScriptedAlarms</c> rows);