fix(alarms,acl): one condition event per Part 9 method call; gate Server-object model-change/audit events (#587, #588)

#587 — a client Acknowledge/Confirm/AddComment/Shelve/Enable/Disable emitted no condition event: the SDK's
ReportStateChange is gated on AutoReportStateChanges (never set), and the engine re-projection found the node
already in the new state and was suppressed by the delta-gate. WireMethodTransitionReporting now wraps each
method's SDK handler and, on Good, reports exactly once via ReportConditionEvent, under Lock so the routed
re-projection cannot race in ahead of the SDK applying the state. Independent of the SDK's imprecise
AreEventsMonitored bookkeeping. The shelve methods' state is applied by the wrapper (the SDK never applies
it). Native conditions' Confirmed/Shelving are method-owned (NativeAlarmProjector's constants would re-report
every ack and undo every shelve). MaxTimeShelved set to int.MaxValue ms at materialise — Create() left it 0
and every TimedShelve failed BadShelvingTimeOutOfRange. Wrong "SDK auto-fires (E2)" comments fixed.

#588 — with ACL on, GeneralModelChange and AuditWriteUpdate events no longer go to Server.ReportEvent
(ungated to every i=2253 item): ReportToServerObject delivers them per item, a model change narrowed to the
Affected nodes the session may Browse (dropped when none), an audit write only with Read on its source plus
the SDK audit/encryption guard. Flag off: unchanged.

#586 review: materialise raises only the new condition's monitored unit (was a full O(N) reconcile per
condition ⇒ O(N²) deploys under Lock).

Claude-Session: https://claude.ai/code/session_01Ef2ozxS7QPanGT8uoATbTe
This commit is contained in:
Joseph Doherty
2026-10-08 00:54:08 -04:00
parent 390c8269a0
commit 167a48bffa
10 changed files with 1454 additions and 66 deletions
@@ -0,0 +1,125 @@
using Microsoft.Extensions.Logging.Abstractions;
using Opc.Ua;
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.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests;
/// <summary>
/// Gitea #588 — <see cref="OtOpcUaNodeManager.FilterModelChangeFor"/> narrows a model-change event to the
/// changes a session may browse. Every builder in the manager emits one change, so the over-the-wire tests
/// only ever see "whole or nothing"; this pins the multi-change copy at its seam.
/// </summary>
public sealed class NodeManagerModelChangeFilterTests : IDisposable
{
private const string Cluster = "SITE-A";
private const string Principal = "scadabridge";
private const string RawFolder = "Plant/Modbus/dev1";
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private readonly string _pkiRoot = Path.Combine(Path.GetTempPath(), $"otopcua-mcfilter-{Guid.NewGuid():N}");
/// <summary>
/// A session granted one equipment folder receives a copy carrying only that folder's change — same
/// EventId, and a Message that no longer names the hidden node — while a fully granted session receives
/// the original and an ungranted one nothing.
/// </summary>
[Fact]
public async Task A_multi_change_event_is_narrowed_to_the_changes_the_session_may_browse()
{
var (host, server) = await BootAsync();
try
{
var nm = server.NodeManager!;
var sink = new SdkAddressSpaceSink(nm);
sink.EnsureFolder("EqA", null, "A", AddressSpaceRealm.Uns);
sink.EnsureFolder(RawFolder, null, "dev1", AddressSpaceRealm.Raw);
var e = nm.BuildNodesAddedModelChange("EqA", AddressSpaceRealm.Uns);
var eqA = e.Changes.Value[0];
var raw = nm.BuildNodesAddedModelChange(RawFolder, AddressSpaceRealm.Raw).Changes.Value[0];
e.Changes.Value = [eqA, raw];
e.Message.Value = new LocalizedText($"Nodes added under {eqA.Affected} and {raw.Affected}");
nm.Authorizer = Authorizer(
new NodeAcl
{
NodeAclId = "acl-eqa", ClusterId = Cluster, Principal = Principal,
ScopeKind = NodeAclScopeKind.Equipment, ScopeId = "eq-EqA",
PermissionFlags = NodePermissions.Browse,
},
new NodeAcl
{
NodeAclId = "acl-all", ClusterId = Cluster, Principal = "everything",
ScopeKind = NodeAclScopeKind.Cluster, PermissionFlags = NodePermissions.Browse,
});
var narrowed = nm.FilterModelChangeFor(Identity(Principal), e).ShouldNotBeNull();
narrowed.ShouldNotBeSameAs(e);
narrowed.Changes.Value.Select(c => c.Affected).ShouldBe([eqA.Affected]);
narrowed.EventId.Value.ShouldBe(e.EventId.Value);
narrowed.Message.Value.Text.ShouldNotContain(RawFolder);
nm.FilterModelChangeFor(Identity("everything"), e).ShouldBeSameAs(e);
nm.FilterModelChangeFor(Identity("nobody"), e).ShouldBeNull();
}
finally { await host.DisposeAsync(); }
}
private static DataPlaneAuthorizer Authorizer(params NodeAcl[] grants)
{
var state = new DataPlaneAuthorityState();
state.Apply(Cluster, "rev-1", [], grants,
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>
{
[new AclScopeRef(NodeAclScopeKind.Equipment, "eq-EqA")] = [new NodeAclPath([NodeAclRealms.Uns, "EqA"])],
});
return new DataPlaneAuthorizer(state, new TriePermissionEvaluator(state.Tries), true, NullLogger.Instance);
}
private static RoleCarryingUserIdentity Identity(string principal) =>
new(new UserNameIdentityToken { UserName = "apikey" }, [], principal, apiKeyId: null);
private async Task<(OpcUaApplicationHost Host, OtOpcUaSdkServer Server)> BootAsync()
{
var host = new OpcUaApplicationHost(
new OpcUaApplicationHostOptions
{
ApplicationName = "OtOpcUa.ModelChangeFilterTest",
ApplicationUri = $"urn:OtOpcUa.ModelChangeFilterTest:{Guid.NewGuid():N}",
OpcUaPort = AllocateFreePort(),
PublicHostname = "localhost",
PkiStoreRoot = _pkiRoot,
},
NullLogger<OpcUaApplicationHost>.Instance);
var server = new OtOpcUaSdkServer();
await host.StartAsync(server, Ct);
return (host, server);
}
private static int AllocateFreePort()
{
using var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
listener.Start();
var port = ((System.Net.IPEndPoint)listener.LocalEndpoint).Port;
listener.Stop();
return port;
}
/// <summary>Cleans up the PKI root directory.</summary>
public void Dispose()
{
if (Directory.Exists(_pkiRoot))
{
try { Directory.Delete(_pkiRoot, recursive: true); }
catch (IOException) { /* best effort */ }
}
}
}