e61db01686
S3: the SDK installs a new identity object on every ActivateSession (decompiled Opc.Ua.Server 2.0.1: Session.UpdateUserIdentity assigns EffectiveIdentity; MonitoredItem/Subscription.EffectiveIdentity read the current session's), so an object-keyed admission forgot a re-activated or transferred session. Admission is now keyed on RoleCarryingUserIdentity.AdmissionKey (principal + api key id), and a removal also tells an item that passes the current gate (uncached). S4: the per-condition record is a lazily allocated locked HashSet<string> (no ConditionalWeakTable per condition), one entry per credential, capped at 1024, dropped after the removal's RefreshRequired is decided. N4: Verdict writes back only while that instance is still live. Tests: OI re-activation (red on revert), unit S3/S4 + N4 (red on revert); docs. Also DataConnections.md for #933 r1 S1/S2.
299 lines
18 KiB
C#
299 lines
18 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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Verification review r2: the rewriter never sees the queued instance — SDK 2.0.1 <c>SentMessageQueue</c> hands Publish
|
|
/// and Republish a <c>CoreUtils.Clone</c> of the stored message. The gate holds only because
|
|
/// <see cref="EventFieldList.Clone"/> is <c>MemberwiseClone</c>, which keeps the subclass, the marker and the handle. Pins
|
|
/// that dependency: an SDK that cloned through the activator (a stock list) would turn this red.
|
|
/// </summary>
|
|
[Fact]
|
|
public void Cloning_a_marked_event_list_the_way_the_SDK_does_keeps_the_subclass_and_the_marker()
|
|
{
|
|
var marker = new ProjectedEventMarker(null, new NodeId("c", 9), 1, () => false);
|
|
var marked = new ProjectedEventFieldList(marker) { ClientHandle = 42 };
|
|
|
|
var direct = marked.Clone().ShouldBeOfType<ProjectedEventFieldList>();
|
|
direct.Marker.ShouldBeSameAs(marker);
|
|
direct.ClientHandle.ShouldBe(42u);
|
|
|
|
var message = new NotificationMessage { SequenceNumber = 11,
|
|
NotificationData = [new ExtensionObject(new EventNotificationList { Events = [marked] })] };
|
|
var delivered = CoreUtils.Clone(message)!; // exactly what SentMessageQueue returns for Publish / Republish
|
|
delivered.NotificationData[0].TryGetValue<EventNotificationList>(out var list).ShouldBeTrue();
|
|
var events = list!.Events;
|
|
var cloned = events[0].ShouldBeOfType<ProjectedEventFieldList>();
|
|
cloned.ShouldNotBeSameAs(marked, "the SDK delivers a copy, not the queued instance");
|
|
cloned.Marker.ShouldBeSameAs(marker);
|
|
ProjectedNotificationRewriter.Project(delivered, republish: false, null).NotificationData.Count
|
|
.ShouldBe(0, "the copy is still judged by its marker (and dropped when the re-check fails)");
|
|
}
|
|
|
|
[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");
|
|
registry.Add(condition); // #936 review r1 N4: verdicts are cached only for a live instance
|
|
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");
|
|
}
|
|
|
|
[Fact]
|
|
public void Issue936_r1_N4_a_verdict_computed_while_its_condition_was_removed_is_not_served_to_a_same_NodeId_re_creation()
|
|
{
|
|
var registry = new ProjectedConditionRegistry();
|
|
var id = new NodeId("c", 9);
|
|
var removed = new ImportedCondition(new AlarmConditionState(null) { NodeId = id }, "conn", "k");
|
|
registry.Add(removed);
|
|
var caller = new object();
|
|
// The compute runs off the verdict gate; the condition is removed while it runs (Remove purges this NodeId's verdicts).
|
|
registry.Verdict(caller, removed, 1, DateTimeOffset.UtcNow, null, () => { registry.Remove(removed); return true; }).ShouldBeTrue();
|
|
|
|
var recreated = new ImportedCondition(new AlarmConditionState(null) { NodeId = id }, "conn", "k");
|
|
registry.Add(recreated);
|
|
var computes = 0;
|
|
registry.Verdict(caller, recreated, 1, DateTimeOffset.UtcNow, null, () => { computes++; return false; })
|
|
.ShouldBeFalse("the new instance is decided (and admitted) afresh, not served the removed instance's verdict");
|
|
computes.ShouldBe(1);
|
|
// Positive control: a live instance's verdict IS cached.
|
|
registry.Verdict(caller, recreated, 1, DateTimeOffset.UtcNow, null, () => { computes++; return true; }).ShouldBeFalse();
|
|
computes.ShouldBe(1);
|
|
}
|
|
|
|
[Fact]
|
|
public void Issue936_r1_S3_S4_admission_is_recorded_lazily_per_credential_and_survives_a_new_identity_object()
|
|
{
|
|
var condition = new ImportedCondition(new AlarmConditionState(null) { NodeId = new NodeId("c", 9) }, "conn", "k");
|
|
condition.AdmittedAllocated.ShouldBeFalse("nothing is allocated for a condition nobody was admitted to");
|
|
RoleCarryingUserIdentity Identity(string principal, string? key) =>
|
|
new(new UserNameIdentityToken { UserName = "apikey" }, [], principal, key);
|
|
var first = Identity("reader", "key-a");
|
|
condition.WasAdmitted(first).ShouldBeFalse();
|
|
condition.Admit(first);
|
|
// The SDK builds a NEW identity object on every ActivateSession (re-activation, transfer): still admitted.
|
|
condition.WasAdmitted(Identity("reader", "key-a")).ShouldBeTrue();
|
|
condition.WasAdmitted(Identity("reader", "key-b")).ShouldBeFalse("another key is another credential");
|
|
condition.WasAdmitted(Identity("other", "key-a")).ShouldBeFalse();
|
|
condition.WasAdmitted(new object()).ShouldBeFalse();
|
|
// Bounded by credentials, not sessions: many sessions of one key are one entry.
|
|
for (var i = 0; i < 50; i++) condition.Admit(Identity("reader", "key-a"));
|
|
condition.AdmittedCount.ShouldBe(1);
|
|
for (var i = 0; i < ImportedCondition.MaxAdmittedCredentials + 10; i++) condition.Admit(Identity("p" + i, "k" + i));
|
|
condition.AdmittedCount.ShouldBe(ImportedCondition.MaxAdmittedCredentials, "capped per condition");
|
|
condition.ForgetAdmitted();
|
|
condition.AdmittedAllocated.ShouldBeFalse("dropped with the removal");
|
|
condition.WasAdmitted(first).ShouldBeFalse();
|
|
}
|
|
|
|
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));
|
|
}
|
|
}
|