Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests/DataConnections/ImportedConditionClassifierTests.cs
T
Joseph Doherty 6be0b8dc4b fix(grpc-data): A3 r2 — a released marked EventFieldList never re-enters the SDK's process-wide pool
SDK 2.0.1 pools EventFieldList (PooledEncodeableType); SentMessageQueue Reuse()s every
list of an acknowledged message and the base ReuseCore returns it, whatever its runtime
type, to the shared stock pool. A recycled ProjectedEventFieldList was then rented by any
server's GetEventFields (an unrelated session's RefreshStart/RefreshEnd or local event)
still carrying an imported condition's marker, and ProjectedNotificationRewriter dropped it
when that marker's gate denied. Root cause of the intermittent OI ConditionRefresh failures
(#854/#855 classes). Mirrors ProjectedSdkNotification on the data path: override ReuseCore,
clear the marker, never return to the pool; a released (marker-less) list fails closed.
2026-11-24 21:36:47 -05:00

223 lines
13 KiB
C#

using System.Security.Cryptography;
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.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.OpcUaServer.Security;
namespace ZB.MOM.WW.OtOpcUa.OpcUaServer.Tests.DataConnections;
/// <summary>
/// A3a (plan §5.2 N4, §5.4): an imported-condition id is classified BEFORE <c>RealmOf</c> on every authorizer entry point
/// (read, history, call, subscribe), whatever realm the caller computed; and the publish-time rewriter drops a marked
/// imported event whose re-check fails, and re-gates an unmarked one for the publishing session.
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A3")]
public sealed class ImportedConditionClassifierTests : IAsyncDisposable
{
private readonly string _pki = Path.Combine(Path.GetTempPath(), $"otopcua-imported-classifier-{Guid.NewGuid():N}");
private OpcUaApplicationHost? _host;
[Theory]
[InlineData(true)]
[InlineData(false)]
public void A_condition_namespace_id_is_never_decided_by_the_realm_walk_on_any_authorizer_entry_point(bool aclEnabled)
{
var f = new Fixture(aclEnabled); // a Cluster-wide grant: the Raw/Uns walk would ALLOW everything
var conditionId = new NodeId("c1.anything", 9);
var calls = new List<(OpcUaOperation, NodeId)>();
f.Gate.ImportedConditionClassifier = (_, op, id) =>
{
if (id.NamespaceIndex != 9) return null;
calls.Add((op, id));
return false;
};
foreach (var realm in new[] { AddressSpaceRealm.Raw, AddressSpaceRealm.Uns })
{
foreach (var op in new[] { OpcUaOperation.Read, OpcUaOperation.Browse, OpcUaOperation.HistoryRead, OpcUaOperation.Call,
OpcUaOperation.CreateMonitoredItems, OpcUaOperation.AlarmAcknowledge })
{
f.Gate.Authorize(f.Identity, op, conditionId, realm).ShouldNotBeNull($"Authorize {op} {realm}");
f.Gate.AuthorizeIfRequired(f.Identity, op, conditionId, realm).ShouldNotBeNull($"AuthorizeIfRequired {op} {realm}");
f.Gate.IsAllowedCached(f.Identity, op, conditionId, realm).ShouldBeFalse($"IsAllowedCached {op} {realm}");
f.Gate.TryAuthorizeMapped(f.Identity, op, conditionId, realm, out var veto).ShouldBeTrue();
veto.ShouldNotBeNull();
}
}
calls.Count.ShouldBe(2 * 6 * 4, "every entry point asked the condition classifier, never the realm");
// Positive control: the same identity on an ordinary Raw id is decided by the grant walk (allowed).
f.Gate.Authorize(f.Identity, OpcUaOperation.Read, new NodeId("Plant/x", 2), AddressSpaceRealm.Raw).ShouldBeNull();
}
[Fact]
public async Task The_node_manager_classifier_allows_Read_and_Subscribe_through_the_condition_and_refuses_history_and_calls()
{
var nm = await BootAsync();
var f = new Fixture(aclEnabled: true);
nm.Authorizer = f.Gate;
var access = new Access();
nm.ProjectedConditionAccess = access;
var key = Convert.ToBase64String(SHA256.HashData("k"u8.ToArray())).TrimEnd('=').Replace('+', '-').Replace('/', '_');
var view = new DataView(new DataAddress("origin", "https://zb.com/otopcua/raw", "string", "Plant/dev1/HR"), DataRealm.Raw, null, 0, "Plant/dev1/HR");
var placement = new ImportedConditionPlacement("map-a", DataRealm.Raw, view, "Plant/remote-a/dev1", "dev1/HR");
var state = new DataConditionState(key, 1, false, true, new DataConditionInfo("AlarmConditionType", "HR", DataConditionSourceKind.Native,
[view], 3), true, false, true, true, 0, 500, "m", 0, null, 0, DateTimeOffset.UtcNow, true, new DataActivationMarker("i", 1));
nm.ApplyConditions([new ImportedConditionUpdate("conn-a", state, state.Info, [placement], "Plant/remote-a/dev1/HR")]);
var alarm = nm.FindImportedCondition("conn-a", key).ShouldNotBeNull();
nm.IsImportedConditionId(alarm.NodeId).ShouldBeTrue();
var child = alarm.ActiveState!.Id!.NodeId;
nm.IsImportedConditionId(child).ShouldBeTrue("children live in the condition's namespace (#629)");
foreach (var realm in new[] { AddressSpaceRealm.Raw, AddressSpaceRealm.Uns })
{
access.Visible = true;
f.Gate.Authorize(f.Identity, OpcUaOperation.Read, child, realm).ShouldBeNull();
f.Gate.Authorize(f.Identity, OpcUaOperation.CreateMonitoredItems, alarm.NodeId, realm).ShouldBeNull();
f.Gate.Authorize(f.Identity, OpcUaOperation.HistoryRead, alarm.NodeId, realm).ShouldNotBeNull("no imported condition history");
f.Gate.Authorize(f.Identity, OpcUaOperation.Call, alarm.NodeId, realm).ShouldNotBeNull("remote methods are A3b");
f.Gate.Authorize(f.Identity, OpcUaOperation.AlarmAcknowledge, alarm.NodeId, realm).ShouldNotBeNull();
access.Visible = false;
access.Generation++;
f.Gate.Authorize(f.Identity, OpcUaOperation.Read, child, realm).ShouldNotBeNull("not visible ⇒ denied despite the Cluster grant");
}
}
[Fact]
public void The_rewriter_drops_a_failed_marked_event_and_regates_an_unmarked_imported_one()
{
var keep = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => true)) { ClientHandle = 1 };
var drop = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => false)) { ClientHandle = 2 };
var unmarkedDenied = new EventFieldList { ClientHandle = 3 };
var unmarkedOther = new EventFieldList { ClientHandle = 4 };
var throwing = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => throw new InvalidOperationException())) { ClientHandle = 5 };
var message = new NotificationMessage
{
SequenceNumber = 7,
NotificationData = [new ExtensionObject(new EventNotificationList { Events = [keep, drop, unmarkedDenied, unmarkedOther, throwing] })],
};
var projected = ProjectedNotificationRewriter.Project(message, republish: false, list => list.ClientHandle == 3 ? false : null);
var events = projected.NotificationData[0].TryGetValue<EventNotificationList>(out var list) ? list! : throw new InvalidOperationException();
projected.NotificationData.Count.ShouldBe(1);
events.Events.ToArray()!.Select(e => e.ClientHandle).ShouldBe([1u, 4u]);
// Every denied event emptied ⇒ the payload is left out entirely (events have no Bad-value form).
var allDenied = new NotificationMessage { SequenceNumber = 8,
NotificationData = [new ExtensionObject(new EventNotificationList { Events = [drop] })] };
ProjectedNotificationRewriter.Project(allDenied, republish: true, null).NotificationData.Count.ShouldBe(0);
// No imported gate and no marker: v1 messages pass through as the same instance.
var plain = new NotificationMessage { SequenceNumber = 9, NotificationData = [new ExtensionObject(new EventNotificationList { Events = [unmarkedOther] })] };
ReferenceEquals(ProjectedNotificationRewriter.Project(plain, republish: false, null), plain).ShouldBeTrue();
}
/// <summary>
/// A3 review round 2 (root cause of the intermittent OI ConditionRefresh failures): SDK 2.0.1 pools EventFieldList
/// process-wide, and <c>SentMessageQueue</c> calls <c>Reuse()</c> on every list of an acknowledged message. A marked
/// list that went back to the stock pool was rented by an unrelated server/session's <c>GetEventFields</c> (its
/// RefreshStart/RefreshEnd), carrying a revoked marker, and the rewriter dropped it. A released marked list must never
/// be rentable, and must not keep its marker (closure over condition + identity) alive.
/// </summary>
[Fact]
public void A_released_marked_event_list_never_returns_to_the_SDK_pool_so_no_other_session_rents_its_marker()
{
var marked = new ProjectedEventFieldList(new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => false)) { ClientHandle = 77 };
((IPooledEncodeable)marked).Reuse(); // exactly what SentMessageQueue.ReuseNotificationPayloads does on ACK / eviction
marked.Marker.ShouldBeNull("a released list holds no authority (and keeps no closure alive)");
// Drain more than the pool can hold: had the marked instance been returned, it would come out here.
var rented = new List<EventFieldList>();
try
{
for (var i = 0; i < PooledEncodeableType<EventFieldList>.DefaultMaximumRetained + 64; i++)
rented.Add((EventFieldList)EventFieldListActivator.Instance.CreateInstance());
rented.ShouldNotContain(l => l is ProjectedEventFieldList, "a stock list rented for any event is never a marked one");
}
finally
{
foreach (var l in rented) ((IPooledEncodeable)l).Reuse();
}
// A released marked list that somehow reached the rewriter fails closed (never judged by a stale marker).
var message = new NotificationMessage { SequenceNumber = 10,
NotificationData = [new ExtensionObject(new EventNotificationList { Events = [marked] })] };
ProjectedNotificationRewriter.Project(message, republish: false, null).NotificationData.Count.ShouldBe(0);
}
[Fact]
public void S2_a_cached_positive_verdict_is_re_proved_past_the_credential_expiry_and_past_the_positive_TTL()
{
var registry = new ProjectedConditionRegistry();
var condition = new ImportedCondition(new AlarmConditionState(null) { NodeId = new NodeId("c", 9) }, "conn", "k");
var computes = 0;
bool Allow() { computes++; return true; }
var now = DateTimeOffset.UtcNow;
var expiringKey = new object();
registry.Verdict(expiringKey, condition, 1, now, now.AddSeconds(2), Allow).ShouldBeTrue();
registry.Verdict(expiringKey, condition, 1, now.AddSeconds(1), now.AddSeconds(2), Allow).ShouldBeTrue();
computes.ShouldBe(1, "served from cache inside both bounds");
registry.Verdict(expiringKey, condition, 1, now.AddSeconds(3), now.AddSeconds(2), () => { computes++; return false; })
.ShouldBeFalse("past the key's expiry the verdict is re-proved (and the policy now denies)");
var longLived = new object();
registry.Verdict(longLived, condition, 1, now, null, Allow).ShouldBeTrue();
registry.Verdict(longLived, condition, 1, now + ProjectedConditionRegistry.PositiveVerdictTtl + TimeSpan.FromSeconds(1), null, Allow);
computes.ShouldBe(4, "a positive verdict lives at most the TTL");
}
private async Task<OtOpcUaNodeManager> BootAsync()
{
var started = await OpcUaHostStart.StartAsync(port => new OpcUaApplicationHost(new OpcUaApplicationHostOptions
{
ApplicationName = "ImportedClassifier", ApplicationUri = $"urn:ImportedClassifier:{Guid.NewGuid():N}",
OpcUaPort = port, PublicHostname = "localhost", PkiStoreRoot = _pki,
}, NullLogger<OpcUaApplicationHost>.Instance), () => new OtOpcUaSdkServer(), TestContext.Current.CancellationToken);
_host = started.Host;
return started.Server.NodeManager!;
}
public async ValueTask DisposeAsync()
{
if (_host is not null) await _host.DisposeAsync();
if (Directory.Exists(_pki))
try { Directory.Delete(_pki, recursive: true); } catch (IOException) { }
}
private sealed class Access : IProjectedConditionAccess
{
public bool Visible { get; set; }
public long Generation { get; set; } = 1;
public bool CanSee(RoleCarryingUserIdentity? caller, IReadOnlyList<ImportedConditionPlacement> placements) => caller is not null && Visible;
public long AuthorityGeneration => Generation;
public IDisposable? AcquireEventDemand(RoleCarryingUserIdentity? caller) => null;
public bool CanSubscribeFolder(RoleCarryingUserIdentity? caller, string mappingId, string folderLocalSubject) => caller is not null && Visible;
public bool IsConditionBearingMapping(string mappingId) => true;
}
private sealed class Fixture
{
private readonly DataPlaneAuthorityState _state = new();
private readonly ApiKey _key = new() { ApiKeyId = "key-a", Name = "key-a", Principal = "reader", SecretHash = "hash", Enabled = true,
ExpiresUtc = DateTime.UtcNow.AddHours(1) };
public DataPlaneAuthorizer Gate { get; }
public Fixture(bool aclEnabled)
{
_state.Apply("c1", "rev", [_key],
[new NodeAcl { NodeAclId = "acl", ClusterId = "c1", Principal = "reader", ScopeKind = NodeAclScopeKind.Cluster,
PermissionFlags = (NodePermissions)~0 }],
new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>());
Gate = new DataPlaneAuthorizer(_state, new TriePermissionEvaluator(_state.Tries, TimeProvider.System), aclEnabled,
NullLogger.Instance, TimeProvider.System);
}
public RoleCarryingUserIdentity Identity => new(new UserNameIdentityToken { UserName = "apikey" }, [], "reader", _key.ApiKeyId,
DataCallerIdentity.CredentialVersionFor(_key), DateTimeOffset.UtcNow.AddMinutes(5));
}
}