fix(acl): authorize scripted alarm commands at their owning equipment's scope (#797)
Scripted condition NodeIds are opaque ScriptedAlarmIds, so splitting them as a topology path could never match an Equipment grant: a narrow equipment grant was denied while a Cluster grant passed. - OtOpcUaNodeManager binds each LIVE scripted condition instance to the EquipmentId it was materialised under (only when it hangs under that folder); dropped on remove / drop-recreate / equipment-subtree removal / rebuild; a same-id re-materialise under another equipment re-parents and re-binds. - DataPlaneAuthoritySnapshot carries EquipmentScopePaths (EquipmentId -> [uns, Area, Line, Equipment]) decoded from the artifact by the same AclScopePathResolver call that plants Equipment grants. - DataPlaneAuthorizer.AuthorizeScriptedCondition re-reads key, grant and generation per call (uncached) and evaluates at the owner path; unbound, replaced or unplaceable owners deny under every grant. No id-split or realm-root fallback. - Native conditions (RawPath) and the ACL-off role gate are unchanged. NodeIds and AlarmCommand.AlarmId are unchanged. Sdk2OpaqueScriptedScopeBaselineTests deliberately flipped: it pinned the denial and now pins owner-grant allow / sibling deny / cluster allow. Follow-up #808 (folder ids + Server-object event visibility for narrow UNS grants).
This commit is contained in:
+2
-2
@@ -697,7 +697,7 @@ public sealed class ConditionMethodEventTests
|
||||
};
|
||||
}
|
||||
|
||||
private static void AssertNewState(string method, bool native, ArrayOf<Variant> e)
|
||||
internal static void AssertNewState(string method, bool native, ArrayOf<Variant> e)
|
||||
{
|
||||
// A native condition is never Unconfirmed, whatever the method (the SDK's ack would make it so).
|
||||
if (native) e[RecordedEvents.ConfirmedField].ClrValue()!.ShouldBe(true);
|
||||
@@ -719,7 +719,7 @@ public sealed class ConditionMethodEventTests
|
||||
/// Calls one Part 9 method on the condition by its type's method id (the SDK resolves it against the
|
||||
/// condition's method declarations — the shelve methods included); throws on a bad result.
|
||||
/// </summary>
|
||||
private static async Task CallAsync(
|
||||
internal static async Task CallAsync(
|
||||
ISession session, NodeId condition, string method, byte[]? eventId, CancellationToken ct, double shelvingTimeMs = 60_000,
|
||||
string? ackComment = "ack")
|
||||
{
|
||||
|
||||
+370
@@ -0,0 +1,370 @@
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Commons.OpcUa;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
|
||||
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
|
||||
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
|
||||
|
||||
/// <summary>
|
||||
/// Gitea #797 over the wire — a real activated <c>apikey</c> session with <b>zero</b> application-wide roles,
|
||||
/// holding only an <c>Equipment</c> grant, drives the Part 9 methods on a scripted condition whose id is a
|
||||
/// production-valid opaque <c>ScriptedAlarmId</c>, under a production-shaped UNS tree (every folder an opaque
|
||||
/// entity id, grant + owner paths resolved by <see cref="AclScopePathResolver"/> from the NAMES).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Observation is through a SEPARATE anonymous session that holds a Cluster grant carrying only
|
||||
/// Browse/Read/Subscribe/AlarmRead — no alarm-command flag — so it sees every condition event while its
|
||||
/// own presence can never be what authorizes a command. Every count is read after a later sentinel
|
||||
/// transition on the same item, so a late duplicate would already be queued ahead of it.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// The rig's NodeIds stay exactly what production publishes: the condition is <c>s=scripted-eqa-hi</c> in
|
||||
/// the UNS namespace and every routed <see cref="AlarmCommand.AlarmId"/> is that id unchanged — the
|
||||
/// ScadaBridge-visible wire contract.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class ScriptedAlarmOwnerScopeWireTests
|
||||
{
|
||||
private const string AreaId = "UA-0000000001";
|
||||
private const string LineId = "UL-0000000001";
|
||||
private const string Pump = "EQ-00000000a1b2";
|
||||
private const string Fan = "EQ-00000000c3d4";
|
||||
private const string Alarm = ServerEventRig.ScriptedAlarmId; // "scripted-eqa-hi"
|
||||
private const string FanAlarm = "scripted-fan-hi";
|
||||
|
||||
private const NodePermissions Commands =
|
||||
NodePermissions.ReadOnly | NodePermissions.AlarmAcknowledge | NodePermissions.AlarmConfirm
|
||||
| NodePermissions.AlarmShelve | NodePermissions.MethodCall;
|
||||
|
||||
private const NodePermissions ObserveOnly =
|
||||
NodePermissions.Browse | NodePermissions.Read | NodePermissions.Subscribe | NodePermissions.AlarmRead;
|
||||
|
||||
/// <summary>
|
||||
/// Every gated condition method, authorized by the narrow owner grant alone: routes exactly once with the
|
||||
/// opaque id unchanged and reports exactly one condition event — while the same method on the SIBLING
|
||||
/// equipment's scripted alarm, on the same session, is denied, routes nothing and reports nothing.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("Acknowledge")]
|
||||
[InlineData("Confirm")]
|
||||
[InlineData("AddComment")]
|
||||
[InlineData("OneShotShelve")]
|
||||
[InlineData("TimedShelve")]
|
||||
[InlineData("Unshelve")]
|
||||
[InlineData("Disable")]
|
||||
[InlineData("Enable")]
|
||||
public async Task A_narrow_equipment_grant_authorizes_each_method_once_and_its_sibling_is_denied(string method)
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
await using var rig = await ServerEventRig.StartAsync($"Owner797{method}", encrypted: false, ct);
|
||||
rig.KeyRoles = [];
|
||||
Topology(rig);
|
||||
Install(rig, new Clock(), [ServerEventRig.Key()], OwnerGrant(Pump), Observer());
|
||||
var routed = Route(rig);
|
||||
|
||||
using var session = await rig.ConnectAsync(anonymous: false, ct);
|
||||
AssertNoRoles(rig);
|
||||
var (events, observer, item) = await ObserveAsync(rig, ct);
|
||||
|
||||
var pre = ConditionMethodEventTests.PreState(method, native: false);
|
||||
Project(rig, Alarm, pre with { Message = "base" });
|
||||
Project(rig, FanAlarm, pre with { Message = "fan-base" });
|
||||
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base") && events.Has(item, "fan-base"));
|
||||
|
||||
await ConditionMethodEventTests.CallAsync(
|
||||
session, Uns(session, Alarm), method, events.LatestEventId(item, "base"), ct);
|
||||
var denied = await Should.ThrowAsync<ServiceResultException>(ConditionMethodEventTests.CallAsync(
|
||||
session, Uns(session, FanAlarm), method, events.LatestEventId(item, "fan-base"), ct));
|
||||
denied.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied);
|
||||
|
||||
Project(rig, Alarm, pre with { Message = "sentinel" });
|
||||
Project(rig, FanAlarm, pre with { Message = "fan-sentinel" });
|
||||
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "sentinel") && events.Has(item, "fan-sentinel"));
|
||||
|
||||
var mine = events.ConditionEvents(item, "base");
|
||||
mine.Count.ShouldBe(2, $"the base transition plus exactly one {method} event");
|
||||
ConditionMethodEventTests.AssertNewState(method, native: false, mine[1]);
|
||||
events.ConditionEvents(item, "fan-base").Count.ShouldBe(1, "the denied sibling call reports nothing");
|
||||
routed.Select(c => (c.AlarmId, c.Operation)).ShouldBe([(Alarm, method)]);
|
||||
|
||||
await observer.CloseAsync(ct);
|
||||
await session.CloseAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Initial and repeated Acknowledge / Confirm on the narrow grant: every call is authorized and routed (the
|
||||
/// engine owns the retry decision), and the condition events are exactly the documented contract — the ack,
|
||||
/// the COMMENTED re-ack (its comment changed), the confirm, and nothing for the re-confirm (no delta).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Initial_and_repeated_ack_and_confirm_route_every_call_and_report_exact_events()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
await using var rig = await ServerEventRig.StartAsync("Owner797Repeat", encrypted: false, ct);
|
||||
rig.KeyRoles = [];
|
||||
Topology(rig);
|
||||
Install(rig, new Clock(), [ServerEventRig.Key()], OwnerGrant(Pump), Observer());
|
||||
var routed = Route(rig);
|
||||
|
||||
using var session = await rig.ConnectAsync(anonymous: false, ct);
|
||||
AssertNoRoles(rig);
|
||||
var (events, observer, item) = await ObserveAsync(rig, ct);
|
||||
|
||||
var pre = new AlarmConditionSnapshot(true, false, false, true, AlarmShelvingKind.Unshelved, 700, "base");
|
||||
Project(rig, Alarm, pre);
|
||||
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base"));
|
||||
var condition = Uns(session, Alarm);
|
||||
|
||||
await ConditionMethodEventTests.CallAsync(session, condition, "Acknowledge", events.LatestEventId(item, "base"), ct, ackComment: "ack");
|
||||
await RecordedEvents.WaitUntilAsync(() => events.ConditionEvents(item, "base").Count == 2);
|
||||
await ConditionMethodEventTests.CallAsync(session, condition, "Acknowledge", events.LatestEventId(item, "base"), ct, ackComment: "again");
|
||||
await RecordedEvents.WaitUntilAsync(() => events.ConditionEvents(item, "base").Count == 3);
|
||||
await ConditionMethodEventTests.CallAsync(session, condition, "Confirm", events.LatestEventId(item, "base"), ct);
|
||||
await RecordedEvents.WaitUntilAsync(() => events.ConditionEvents(item, "base").Count == 4);
|
||||
await ConditionMethodEventTests.CallAsync(session, condition, "Confirm", events.LatestEventId(item, "base"), ct);
|
||||
|
||||
Project(rig, Alarm, pre with { Acknowledged = true, Confirmed = true, Message = "sentinel" });
|
||||
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "sentinel"));
|
||||
|
||||
events.ConditionEvents(item, "base").Count.ShouldBe(4, "base + ack + commented re-ack + confirm; the re-confirm is silent");
|
||||
routed.Select(c => (c.AlarmId, c.Operation)).ShouldBe(
|
||||
[(Alarm, "Acknowledge"), (Alarm, "Acknowledge"), (Alarm, "Confirm"), (Alarm, "Confirm")]);
|
||||
|
||||
await observer.CloseAsync(ct);
|
||||
await session.CloseAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The grant, the key and the clock are re-read at every call on the open session: revoking any of them
|
||||
/// denies the next command (no route, no event, no state change); restoring the authority restores the
|
||||
/// allow, on the same session, without reconnecting.
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("grant")]
|
||||
[InlineData("key")]
|
||||
[InlineData("expiry")]
|
||||
public async Task A_revoked_or_expired_authority_denies_the_next_command_on_the_open_session(string change)
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
await using var rig = await ServerEventRig.StartAsync($"Owner797Revoke{change}", encrypted: false, ct);
|
||||
rig.KeyRoles = [];
|
||||
Topology(rig);
|
||||
var clock = new Clock();
|
||||
var key = ServerEventRig.Key();
|
||||
key.ExpiresUtc = clock.GetUtcNow().UtcDateTime.AddMinutes(10);
|
||||
var state = Install(rig, clock, [key], OwnerGrant(Pump), Observer());
|
||||
var routed = Route(rig);
|
||||
|
||||
using var session = await rig.ConnectAsync(anonymous: false, ct);
|
||||
AssertNoRoles(rig);
|
||||
var (events, observer, item) = await ObserveAsync(rig, ct);
|
||||
var pre = new AlarmConditionSnapshot(true, false, false, true, AlarmShelvingKind.Unshelved, 700, "base");
|
||||
Project(rig, Alarm, pre);
|
||||
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base"));
|
||||
var condition = Uns(session, Alarm);
|
||||
|
||||
await ConditionMethodEventTests.CallAsync(session, condition, "Acknowledge", events.LatestEventId(item, "base"), ct);
|
||||
await RecordedEvents.WaitUntilAsync(() => events.ConditionEvents(item, "base").Count == 2);
|
||||
|
||||
switch (change)
|
||||
{
|
||||
case "grant": Reapply(state, "rev-2", [key], Observer()); break;
|
||||
case "key":
|
||||
var disabled = ServerEventRig.Key();
|
||||
disabled.Enabled = false;
|
||||
Reapply(state, "rev-2", [disabled], OwnerGrant(Pump), Observer());
|
||||
break;
|
||||
case "expiry": clock.Advance(TimeSpan.FromMinutes(20)); break;
|
||||
}
|
||||
|
||||
var condState = rig.Nm.TryGetAlarmCondition(Alarm)!;
|
||||
var commentBefore = condState.Comment!.Value;
|
||||
foreach (var method in new[] { "AddComment", "Confirm", "OneShotShelve" })
|
||||
{
|
||||
var error = await Should.ThrowAsync<ServiceResultException>(ConditionMethodEventTests.CallAsync(
|
||||
session, condition, method, events.LatestEventId(item, "base"), ct));
|
||||
error.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied, method);
|
||||
}
|
||||
|
||||
condState.Comment!.Value.ShouldBe(commentBefore);
|
||||
routed.Count.ShouldBe(1);
|
||||
|
||||
clock.Reset();
|
||||
Reapply(state, "rev-3", [key], OwnerGrant(Pump), Observer());
|
||||
await ConditionMethodEventTests.CallAsync(session, condition, "AddComment", events.LatestEventId(item, "base"), ct);
|
||||
|
||||
Project(rig, Alarm, pre with { Acknowledged = true, Message = "sentinel" });
|
||||
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "sentinel"));
|
||||
events.ConditionEvents(item, "base").Count.ShouldBe(3, "base + ack + the restored AddComment; the denied calls report nothing");
|
||||
routed.Select(c => c.Operation).ShouldBe(["Acknowledge", "AddComment"]);
|
||||
|
||||
await observer.CloseAsync(ct);
|
||||
await session.CloseAsync(ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delete + recreate of the SAME opaque id under ANOTHER equipment: the old equipment's grant is denied on
|
||||
/// the recreated condition and the new equipment's grant authorizes it; the routed id never changes. An id
|
||||
/// with no live condition is refused by the server before any gate, and routes nothing.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task A_recreated_alarm_follows_its_new_owner_and_an_unknown_id_routes_nothing()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
await using var rig = await ServerEventRig.StartAsync("Owner797Recreate", encrypted: false, ct);
|
||||
rig.KeyRoles = [];
|
||||
Topology(rig);
|
||||
var state = Install(rig, new Clock(), [ServerEventRig.Key()], OwnerGrant(Pump), Observer());
|
||||
var routed = Route(rig);
|
||||
|
||||
using var session = await rig.ConnectAsync(anonymous: false, ct);
|
||||
AssertNoRoles(rig);
|
||||
var (events, observer, item) = await ObserveAsync(rig, ct);
|
||||
var pre = new AlarmConditionSnapshot(true, false, false, true, AlarmShelvingKind.Unshelved, 700, "base");
|
||||
Project(rig, Alarm, pre);
|
||||
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "base"));
|
||||
await ConditionMethodEventTests.CallAsync(session, Uns(session, Alarm), "Acknowledge", events.LatestEventId(item, "base"), ct);
|
||||
|
||||
((ISurgicalAddressSpaceSink)rig.Sink).RemoveAlarmConditionNode(Alarm, AddressSpaceRealm.Uns).ShouldBeTrue();
|
||||
rig.Sink.MaterialiseAlarmCondition(Alarm, Fan, "hi", "AlarmCondition", 500, AddressSpaceRealm.Uns);
|
||||
rig.Nm.ScriptedAlarmOwnerOf(Alarm).ShouldBe(Fan);
|
||||
Project(rig, Alarm, pre with { Message = "recreated" });
|
||||
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "recreated"));
|
||||
|
||||
var oldGrant = await Should.ThrowAsync<ServiceResultException>(ConditionMethodEventTests.CallAsync(
|
||||
session, Uns(session, Alarm), "Acknowledge", events.LatestEventId(item, "recreated"), ct));
|
||||
oldGrant.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied);
|
||||
routed.Count.ShouldBe(1);
|
||||
|
||||
Reapply(state, "rev-fan", [ServerEventRig.Key()], OwnerGrant(Fan), Observer());
|
||||
await ConditionMethodEventTests.CallAsync(
|
||||
session, Uns(session, Alarm), "Acknowledge", events.LatestEventId(item, "recreated"), ct);
|
||||
|
||||
var unknown = await Should.ThrowAsync<ServiceResultException>(ConditionMethodEventTests.CallAsync(
|
||||
session, Uns(session, "scripted-never-deployed"), "Acknowledge", [1, 2, 3], ct));
|
||||
unknown.StatusCode.ShouldNotBe(StatusCodes.Good);
|
||||
|
||||
Project(rig, Alarm, pre with { Acknowledged = true, Message = "sentinel" });
|
||||
await RecordedEvents.WaitUntilAsync(() => events.Has(item, "sentinel"));
|
||||
events.ConditionEvents(item, "recreated").Count.ShouldBe(2, "the recreated base plus the new owner's one ack");
|
||||
routed.Select(c => (c.AlarmId, c.Operation)).ShouldBe([(Alarm, "Acknowledge"), (Alarm, "Acknowledge")]);
|
||||
|
||||
await observer.CloseAsync(ct);
|
||||
await session.CloseAsync(ct);
|
||||
}
|
||||
|
||||
// ───────────────────────────── helpers ─────────────────────────────
|
||||
|
||||
/// <summary>Area1 / Line1 / {Pump, Fan} under opaque entity ids, one scripted alarm under each equipment.</summary>
|
||||
private static void Topology(ServerEventRig rig)
|
||||
{
|
||||
rig.Sink.EnsureFolder(AreaId, parentNodeId: null, displayName: "Area1", realm: AddressSpaceRealm.Uns);
|
||||
rig.Sink.EnsureFolder(LineId, parentNodeId: AreaId, displayName: "Line1", realm: AddressSpaceRealm.Uns);
|
||||
rig.Sink.EnsureFolder(Pump, parentNodeId: LineId, displayName: "Pump", realm: AddressSpaceRealm.Uns);
|
||||
rig.Sink.EnsureFolder(Fan, parentNodeId: LineId, displayName: "Fan", realm: AddressSpaceRealm.Uns);
|
||||
rig.Sink.MaterialiseAlarmCondition(Alarm, Pump, "hi", "AlarmCondition", 500, AddressSpaceRealm.Uns);
|
||||
rig.Sink.MaterialiseAlarmCondition(FanAlarm, Fan, "fan hi", "AlarmCondition", 500, AddressSpaceRealm.Uns);
|
||||
}
|
||||
|
||||
private static AclScopePathResolver Resolver() => 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 UnsAreaId, string Name)> { [LineId] = (AreaId, "Line1") },
|
||||
new Dictionary<string, (string UnsLineId, string Name)> { [Pump] = (LineId, "Pump"), [Fan] = (LineId, "Fan") },
|
||||
[]);
|
||||
|
||||
private static Dictionary<string, NodeAclPath> OwnerPaths()
|
||||
{
|
||||
var resolver = Resolver();
|
||||
return new Dictionary<string, NodeAclPath>
|
||||
{
|
||||
[Pump] = resolver.ResolveOne(NodeAclScopeKind.Equipment, Pump).ShouldHaveSingleItem(),
|
||||
[Fan] = resolver.ResolveOne(NodeAclScopeKind.Equipment, Fan).ShouldHaveSingleItem(),
|
||||
};
|
||||
}
|
||||
|
||||
private static DataPlaneAuthorityState Install(ServerEventRig rig, TimeProvider clock, ApiKey[] keys, params NodeAcl[] grants)
|
||||
{
|
||||
var state = new DataPlaneAuthorityState();
|
||||
Reapply(state, "rev-1", keys, grants);
|
||||
rig.Nm.DataPlaneAuthority = state;
|
||||
rig.Nm.Authorizer = new DataPlaneAuthorizer(
|
||||
state, new TriePermissionEvaluator(state.Tries), true, NullLogger.Instance, clock);
|
||||
return state;
|
||||
}
|
||||
|
||||
private static void Reapply(DataPlaneAuthorityState state, string revision, ApiKey[] keys, params NodeAcl[] grants) =>
|
||||
state.Apply(ServerEventRig.Cluster, revision, keys, grants, Resolver().Resolve(grants), OwnerPaths());
|
||||
|
||||
/// <summary>The key's ONLY alarm authority: an Equipment grant on <paramref name="equipmentId"/>.</summary>
|
||||
private static NodeAcl OwnerGrant(string equipmentId) => new()
|
||||
{
|
||||
NodeAclId = $"owner-{equipmentId}",
|
||||
ClusterId = ServerEventRig.Cluster,
|
||||
Principal = ServerEventRig.KeyPrincipal,
|
||||
ScopeKind = NodeAclScopeKind.Equipment,
|
||||
ScopeId = equipmentId,
|
||||
PermissionFlags = Commands,
|
||||
};
|
||||
|
||||
/// <summary>The anonymous observer: sees everything, may command nothing.</summary>
|
||||
private static NodeAcl Observer() => new()
|
||||
{
|
||||
NodeAclId = "observer",
|
||||
ClusterId = ServerEventRig.Cluster,
|
||||
Principal = OpcUaPrincipals.Anonymous,
|
||||
ScopeKind = NodeAclScopeKind.Cluster,
|
||||
PermissionFlags = ObserveOnly,
|
||||
};
|
||||
|
||||
private static List<AlarmCommand> Route(ServerEventRig rig)
|
||||
{
|
||||
var routed = new List<AlarmCommand>();
|
||||
rig.Nm.AlarmCommandRouter = cmd => { lock (routed) routed.Add(cmd); };
|
||||
return routed;
|
||||
}
|
||||
|
||||
private static void AssertNoRoles(ServerEventRig rig) =>
|
||||
rig.Server.CurrentInstance.SessionManager.GetSessions()
|
||||
.Select(s => s.EffectiveIdentity).OfType<RoleCarryingUserIdentity>()
|
||||
.Single(i => i.ApiKeyId == ServerEventRig.KeyId)
|
||||
.Roles.ShouldBeEmpty("the narrow grant alone must authorize — the session holds no server-wide role");
|
||||
|
||||
private static async Task<(RecordedEvents Events, ISession Observer, MonitoredItem Item)> ObserveAsync(
|
||||
ServerEventRig rig, CancellationToken ct)
|
||||
{
|
||||
var observer = await rig.ConnectAsync(anonymous: true, ct);
|
||||
var events = new RecordedEvents();
|
||||
var subscription = await RecordedEvents.SubscribeAsync(observer, events, ct);
|
||||
var item = RecordedEvents.AddEventItem(subscription, ObjectIds.Server);
|
||||
await subscription.ApplyChangesAsync(ct);
|
||||
item.Status.Error.ShouldBeNull();
|
||||
return (events, observer, item);
|
||||
}
|
||||
|
||||
private static void Project(ServerEventRig rig, string alarmId, AlarmConditionSnapshot state) =>
|
||||
rig.Sink.WriteAlarmCondition(alarmId, state, DateTime.UtcNow, AddressSpaceRealm.Uns);
|
||||
|
||||
private static NodeId Uns(ISession session, string id) => ServerEventRig.UnsNodeId(session, id);
|
||||
|
||||
private sealed class Clock : TimeProvider
|
||||
{
|
||||
private readonly DateTimeOffset _initial = DateTimeOffset.UtcNow;
|
||||
private TimeSpan _offset;
|
||||
public override DateTimeOffset GetUtcNow() => _initial + _offset;
|
||||
public void Advance(TimeSpan by) => _offset += by;
|
||||
public void Reset() => _offset = TimeSpan.Zero;
|
||||
}
|
||||
}
|
||||
+27
-10
@@ -1,4 +1,8 @@
|
||||
// The same application-authored opaque ID and two grant outcomes are independently exercised on SDK1.5.
|
||||
// Gitea #797: this test USED to pin the denial (an Equipment grant could not authorize an opaque scripted
|
||||
// alarm id; only a Cluster grant could). The owner binding fixed that deliberately, so it now pins the fixed
|
||||
// behaviour: the owning equipment's grant allows, the sibling equipment's grant denies, a cluster grant still
|
||||
// allows. The SDK 1.5 baseline probe under scripts/validation/opcua-scripted-alarm-baseline records the
|
||||
// pre-fix denial on the original application commit and is unaffected.
|
||||
using Opc.Ua;
|
||||
using Opc.Ua.Client;
|
||||
using Shouldly;
|
||||
@@ -13,32 +17,45 @@ namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.IntegrationTests;
|
||||
public sealed class Sdk2OpaqueScriptedScopeBaselineTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task Opaque_scripted_ID_is_denied_by_its_equipment_grant_but_allowed_by_a_cluster_grant()
|
||||
public async Task Opaque_scripted_ID_is_allowed_by_its_equipment_grant_denied_by_a_sibling_grant_and_allowed_by_a_cluster_grant()
|
||||
{
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
await using var rig = await StartAsync("BaselineScriptedScope", encrypted: false, ct);
|
||||
rig.KeyRoles = [];
|
||||
const NodePermissions permissions = NodePermissions.ReadOnly | NodePermissions.AlarmAcknowledge | NodePermissions.MethodCall;
|
||||
rig.Enforce(true, [Key()], new NodeAcl
|
||||
NodeAcl Narrow(string equipment) => new()
|
||||
{
|
||||
NodeAclId = "narrow", ClusterId = ServerEventRig.Cluster, Principal = KeyPrincipal,
|
||||
ScopeKind = NodeAclScopeKind.Equipment, ScopeId = $"eq-{EqA}", PermissionFlags = permissions,
|
||||
});
|
||||
NodeAclId = $"narrow-{equipment}", ClusterId = ServerEventRig.Cluster, Principal = KeyPrincipal,
|
||||
ScopeKind = NodeAclScopeKind.Equipment, ScopeId = $"eq-{equipment}", PermissionFlags = permissions,
|
||||
};
|
||||
|
||||
// Sibling first: a grant on EqB must not authorize EqA's alarm.
|
||||
rig.Enforce(true, [Key()], Narrow(EqB));
|
||||
rig.MaterialiseScripted();
|
||||
rig.Nm.ScriptedAlarmOwnerOf(ScriptedAlarmId).ShouldBe(EqA);
|
||||
var routed = 0;
|
||||
rig.Nm.AlarmCommandRouter = _ => routed++;
|
||||
using var session = await rig.ConnectAsync(anonymous: false, ct);
|
||||
rig.Project(false, new AlarmConditionSnapshot(true, true, true, true, AlarmShelvingKind.Unshelved, 500, "scope"));
|
||||
rig.Project(false, new AlarmConditionSnapshot(true, false, false, true, AlarmShelvingKind.Unshelved, 500, "scope"));
|
||||
var condition = rig.Nm.TryGetAlarmCondition(ScriptedAlarmId, AddressSpaceRealm.Uns).ShouldNotBeNull();
|
||||
condition.NodeId.IdentifierAsString.ShouldBe(ScriptedAlarmId, "the opaque NodeId is unchanged");
|
||||
var eventId = condition.EventId.ShouldNotBeNull().Value;
|
||||
var denied = await Should.ThrowAsync<ServiceResultException>(() => session.CallAsync(condition.NodeId,
|
||||
MethodIds.AcknowledgeableConditionType_Acknowledge, ct, new Variant[] { Variant.From(eventId), Variant.From(new LocalizedText("denied")) }));
|
||||
MethodIds.AcknowledgeableConditionType_Acknowledge, ct, new Variant[] { Variant.From(eventId), Variant.From(new LocalizedText("sibling")) }));
|
||||
denied.StatusCode.ShouldBe(StatusCodes.BadUserAccessDenied);
|
||||
routed.ShouldBe(0);
|
||||
|
||||
// The owning equipment's narrow grant now authorizes the same opaque id (#797 fixed).
|
||||
rig.Enforce(true, [Key()], Narrow(EqA));
|
||||
await session.CallAsync(condition.NodeId, MethodIds.AcknowledgeableConditionType_Acknowledge, ct,
|
||||
new Variant[] { Variant.From(eventId), Variant.From(new LocalizedText("owner")) });
|
||||
routed.ShouldBe(1);
|
||||
|
||||
// The existing cluster contract is preserved.
|
||||
rig.Enforce(true, [Key()], ClusterGrant(KeyPrincipal, "cluster-positive", permissions));
|
||||
await session.CallAsync(condition.NodeId, MethodIds.AcknowledgeableConditionType_Acknowledge, ct,
|
||||
new Variant[] { Variant.From(eventId), Variant.From(new LocalizedText("allowed")) });
|
||||
routed.ShouldBe(1);
|
||||
new Variant[] { Variant.From(condition.EventId!.Value), Variant.From(new LocalizedText("cluster")) });
|
||||
routed.ShouldBe(2);
|
||||
await session.CloseAsync(ct);
|
||||
}
|
||||
}
|
||||
|
||||
+5
-4
@@ -56,8 +56,9 @@ public sealed class Sdk2RepeatedAlarmAuthorityWireTests
|
||||
var identity = rig.Server.CurrentInstance.SessionManager.GetSessions().ShouldHaveSingleItem().EffectiveIdentity
|
||||
.ShouldBeOfType<RoleCarryingUserIdentity>();
|
||||
identity.Roles.ShouldBeEmpty("the positive retry must be authorized by the application grant alone");
|
||||
// Native: narrow raw-device scope. Scripted: preserve the existing cluster-scope contract;
|
||||
// opaque scripted IDs are not under their equipment ACL path (a separately tracked baseline defect).
|
||||
// Native: narrow raw-device scope. Scripted: the existing cluster-scope contract (the narrow
|
||||
// equipment-scope case for opaque scripted IDs is Gitea #797's ScriptedAlarmOwnerScopeWireTests).
|
||||
// Every re-Apply below carries the owner paths, so a scripted denial is the key/grant/clock change's.
|
||||
identity.ApiKeyId.ShouldBe(KeyId);
|
||||
var events = new RecordedEvents();
|
||||
var subscription = await RecordedEvents.SubscribeAsync(session, events, ct);
|
||||
@@ -94,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);
|
||||
else state.Apply(ServerEventRig.Cluster, "revoked", keys, grants, scopes, EquipmentOwnerPaths());
|
||||
|
||||
var error = await Should.ThrowAsync<ServiceResultException>(() => session.CallAsync(condition.NodeId, methodId, ct,
|
||||
Variant.From(currentId), Variant.From(new LocalizedText("must not be recorded"))));
|
||||
@@ -106,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);
|
||||
state.Apply(ServerEventRig.Cluster, "restored", [key], [grant], scopes, EquipmentOwnerPaths());
|
||||
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");
|
||||
|
||||
@@ -114,10 +114,19 @@ internal sealed class ServerEventRig : IAsyncDisposable
|
||||
/// <summary>Wires the authorizer over the given keys, scope paths and grants, enforcing or not.</summary>
|
||||
public DataPlaneAuthorityState Enforce(
|
||||
bool enabled, ApiKey[] keys, IReadOnlyDictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> scopePaths,
|
||||
params NodeAcl[] grants)
|
||||
params NodeAcl[] grants) =>
|
||||
Enforce(enabled, keys, scopePaths, EquipmentOwnerPaths(), grants);
|
||||
|
||||
/// <summary>
|
||||
/// Wires the authorizer over the given keys, scope paths, equipment owner paths (the scripted-alarm owner
|
||||
/// lookup, Gitea #797) and grants, enforcing or not.
|
||||
/// </summary>
|
||||
public DataPlaneAuthorityState Enforce(
|
||||
bool enabled, ApiKey[] keys, IReadOnlyDictionary<AclScopeRef, IReadOnlyList<NodeAclPath>> scopePaths,
|
||||
IReadOnlyDictionary<string, NodeAclPath> equipmentOwnerPaths, params NodeAcl[] grants)
|
||||
{
|
||||
var state = new DataPlaneAuthorityState();
|
||||
state.Apply(Cluster, "rev-1", keys, grants, scopePaths);
|
||||
state.Apply(Cluster, "rev-1", keys, grants, scopePaths, equipmentOwnerPaths);
|
||||
Nm.DataPlaneAuthority = state;
|
||||
Nm.Authorizer = new DataPlaneAuthorizer(
|
||||
state, new TriePermissionEvaluator(state.Tries), enabled, NullLogger.Instance, TimeProvider.System);
|
||||
@@ -160,6 +169,18 @@ internal sealed class ServerEventRig : IAsyncDisposable
|
||||
[new AclScopeRef(NodeAclScopeKind.Equipment, $"eq-{EqB}")] = [new NodeAclPath([NodeAclRealms.Uns, EqB])],
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// The rig's equipment owner paths: its equipment folders' ids ARE their EquipmentIds, sitting directly at
|
||||
/// <c>[uns, EqA]</c> / <c>[uns, EqB]</c> — the same nodes <see cref="ScopePaths"/> plants the Equipment
|
||||
/// grants at.
|
||||
/// </summary>
|
||||
public static IReadOnlyDictionary<string, NodeAclPath> EquipmentOwnerPaths() =>
|
||||
new Dictionary<string, NodeAclPath>
|
||||
{
|
||||
[EqA] = new NodeAclPath([NodeAclRealms.Uns, EqA]),
|
||||
[EqB] = new NodeAclPath([NodeAclRealms.Uns, EqB]),
|
||||
};
|
||||
|
||||
/// <summary>The native condition, wired as an event source of both equipment folders.</summary>
|
||||
public void MaterialiseNative()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user