Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataConditionMethodTests.cs
T

230 lines
14 KiB
C#
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>
/// A2b origin facade of <c>CallConditionMethod</c> (plan §5.6 "Origin", §6): Primary-only, placement-resolved and
/// authorized on the PLACEMENT's subject, the Galaxy service-ack opt-in, the operation registry (a duplicate id joins),
/// and the audit log (sanitised text, audit only).
/// </summary>
[Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "A2")]
public sealed class GrpcDataConditionMethodTests
{
private const DataOperations Methods = DataOperations.AlarmAcknowledge | DataOperations.AlarmConfirm;
private const uint BadUserAccessDenied = 0x801F0000u, BadInvalidState = 0x80AF0000u, BadNodeIdUnknown = 0x80340000u,
BadNotSupported = 0x803D0000u, BadEventIdUnknown = 0x809A0000u, BadInvalidArgument = 0x80AB0000u, BadTimeout = 0x800A0000u;
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private static readonly DataActivationMarker Marker = new("inc", 1);
private static DataView RawPlacement(int i) => new(new("cluster", "https://zb.com/otopcua/raw", "string", FakeConditionSource.IdOf(i)),
DataRealm.Raw, null, 0, FakeConditionSource.IdOf(i));
private static DataView UnsPlacement(int i) => new(new("cluster", "https://zb.com/otopcua/uns", "string", $"Area/Line/Equipment/Alarm{i}"),
DataRealm.Uns, null, 0, $"Area/Line/Equipment/Alarm{i}");
private static DataConditionMethodRequest Request(DataView placement, DataConditionMethods method = DataConditionMethods.Acknowledge,
string op = "op-1", string? comment = "ack", string incarnation = "serving-1", TimeSpan? budget = null, string? onBehalfOf = null) =>
new(op, placement, method, Marker, comment, incarnation, budget ?? TimeSpan.FromSeconds(5), onBehalfOf);
private static Task<DataConditionMethodResult> CallAsync(ConditionFixture f, DataConditionMethodRequest request) =>
((IDataConditionMethodService)f.Services.Create(f.Context, f.Target)).CallConditionMethodAsync(request, Ct);
private static NodeAcl Acl(NodeAclScopeKind kind, string? scopeId, NodePermissions permissions, string id = "grant") =>
new() { NodeAclId = id, ClusterId = "cluster", Principal = "peer", ScopeKind = kind, ScopeId = scopeId, PermissionFlags = permissions };
[Fact]
public async Task A_remote_native_ack_reaches_the_node_manager_once_as_accepted_unconfirmed()
{
using var f = new ConditionFixture(2, extraOperations: Methods, acls: [Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator)]);
var result = await CallAsync(f, Request(RawPlacement(1)));
result.State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
result.StatusCode.ShouldBe(0u);
result.Diagnostic.ShouldNotBeNull().ShouldContain("AcceptedUnconfirmed");
result.Serving.ShouldBe(f.Serving);
f.Source.MethodCalls.ShouldHaveSingleItem().ShouldBe(new OriginConditionMethodCall(AddressSpaceRealm.Raw, FakeConditionSource.IdOf(1),
"Acknowledge", "ack", new ConditionActivationMarker("inc", 1), "peer", "peer-key"));
}
[Fact]
public async Task Capabilities_carry_the_method_bits_and_mask_only_on_the_Primary()
{
using var primary = new ConditionFixture(1, extraOperations: Methods);
var caps = await primary.Services.Create(primary.Context, primary.Target).GetCapabilitiesAsync(LocalDataFixture.Budget, Ct);
(caps.Operations & Methods).ShouldBe(Methods);
caps.Conditions.ShouldNotBeNull().Methods.ShouldBe(7u);
using var secondary = new ConditionFixture(1, role: "Secondary", extraOperations: Methods);
var target = new DataTarget(DataTargetMode.Node, "cluster", "node-a", DataConsistency.ReadyReplica);
var standby = await secondary.Services.Create(secondary.Context, target).GetCapabilitiesAsync(LocalDataFixture.Budget, Ct);
(standby.Operations & Methods).ShouldBe(DataOperations.None);
standby.Conditions.ShouldNotBeNull().Methods.ShouldBe(0u);
}
[Fact]
public async Task Off_Primary_and_a_node_manager_refusal_are_RejectedBeforeDispatch()
{
using var secondary = new ConditionFixture(1, role: "Secondary", extraOperations: Methods,
acls: [Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator)]);
var target = new DataTarget(DataTargetMode.Node, "cluster", "node-a", DataConsistency.ReadyReplica);
var refused = await ((IDataConditionMethodService)secondary.Services.Create(secondary.Context, target))
.CallConditionMethodAsync(Request(RawPlacement(0)), Ct);
refused.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
refused.StatusCode.ShouldBe(BadInvalidState);
secondary.Source.MethodCalls.ShouldBeEmpty();
// Warm Standby (and the native Primary gate) are the node manager's verdict: passed through, nothing applied.
using var warm = new ConditionFixture(1, extraOperations: Methods, acls: [Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator)]);
warm.Source.Execute = _ => new(false, true, BadInvalidState, "This server is the Warm redundancy standby");
var standby = await CallAsync(warm, Request(RawPlacement(0)));
standby.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
standby.StatusCode.ShouldBe(BadInvalidState);
}
[Fact]
public async Task Galaxy_without_the_opt_in_is_denied_before_the_node_manager_and_allowed_with_it()
{
var acls = new[] { Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator) };
using var off = new ConditionFixture(1, extraOperations: Methods, acls: acls, driverType: DriverTypeNames.Galaxy);
var denied = await CallAsync(off, Request(RawPlacement(0)));
denied.ShouldSatisfyAllConditions(r => r.State.ShouldBe(DataWriteState.RejectedBeforeDispatch),
r => r.StatusCode.ShouldBe(BadUserAccessDenied));
(await CallAsync(off, Request(RawPlacement(0), DataConditionMethods.AddComment, op: "op-2"))).StatusCode.ShouldBe(BadUserAccessDenied);
off.Source.MethodCalls.ShouldBeEmpty(); // no state change: nothing reached the node manager
using var on = new ConditionFixture(1, extraOperations: Methods, acls: acls, driverType: DriverTypeNames.Galaxy, galaxyAck: true);
(await CallAsync(on, Request(RawPlacement(0)))).State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
on.Source.MethodCalls.ShouldHaveSingleItem().ApiKeyId.ShouldBe("peer-key"); // the service key's Galaxy ack identity (§6)
// The opt-in counts only next to AlarmAcknowledge (an export without the bit grants nothing).
using var confirmOnly = new ConditionFixture(1, extraOperations: DataOperations.AlarmConfirm, acls: acls,
driverType: DriverTypeNames.Galaxy, galaxyAck: true);
(await CallAsync(confirmOnly, Request(RawPlacement(0)))).StatusCode.ShouldBe(BadNodeIdUnknown);
}
[Fact]
public async Task A_UNS_placement_resolves_to_the_condition_and_is_authorized_on_the_equipment_subject()
{
var paths = new Dictionary<AclScopeRef, IReadOnlyList<NodeAclPath>>
{
[new(NodeAclScopeKind.Equipment, "eq")] = [new NodeAclPath(["uns", "Area", "Line", "Equipment"])],
[new(NodeAclScopeKind.RawFolder, "folder")] = [new NodeAclPath(["raw", "Plant"])],
};
using var equipment = new ConditionFixture(1, unsPrincipal: true, extraOperations: Methods, scopePaths: paths,
acls: [Acl(NodeAclScopeKind.Equipment, "eq", NodePermissions.AlarmAcknowledge)]);
(await CallAsync(equipment, Request(UnsPlacement(0)))).State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
// The UNS reference id resolves to the native condition (Raw, RawPath) — the node manager never sees the reference.
equipment.Source.MethodCalls.ShouldHaveSingleItem().ShouldSatisfyAllConditions(
c => c.Realm.ShouldBe(AddressSpaceRealm.Raw), c => c.ConditionId.ShouldBe(FakeConditionSource.IdOf(0)));
// The same condition's RAW subject granted (not the equipment's) does not authorize the UNS placement.
using var rawOnly = new ConditionFixture(1, unsPrincipal: true, extraOperations: Methods, scopePaths: paths,
acls: [Acl(NodeAclScopeKind.RawFolder, "folder", NodePermissions.AlarmAcknowledge)]);
(await CallAsync(rawOnly, Request(UnsPlacement(0)))).StatusCode.ShouldBe(BadUserAccessDenied);
rawOnly.Source.MethodCalls.ShouldBeEmpty();
}
[Fact]
public async Task Ungranted_unknown_native_Confirm_stale_and_expired_calls_are_refused_unsent()
{
var acls = new[] { Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator) };
using var ungranted = new ConditionFixture(1, extraOperations: DataOperations.AlarmConfirm, acls: acls);
(await CallAsync(ungranted, Request(RawPlacement(0)))).StatusCode.ShouldBe(BadNodeIdUnknown); // no AlarmAcknowledge export
using var f = new ConditionFixture(1, extraOperations: Methods, acls: acls);
(await CallAsync(f, Request(RawPlacement(9)))).StatusCode.ShouldBe(BadNodeIdUnknown);
(await CallAsync(f, Request(RawPlacement(0), DataConditionMethods.Confirm))).StatusCode.ShouldBe(BadNotSupported);
(await CallAsync(f, Request(RawPlacement(0), incarnation: "old"))).StatusCode.ShouldBe(BadInvalidState);
(await CallAsync(f, Request(RawPlacement(0), budget: TimeSpan.Zero))).StatusCode.ShouldBe(BadTimeout);
f.Source.MethodCalls.ShouldBeEmpty();
// The ACL decides with the export granted: ReadOnly carries no AlarmAcknowledge.
using var readOnly = new ConditionFixture(1, extraOperations: Methods, acls: [Acl(NodeAclScopeKind.Cluster, null, NodePermissions.ReadOnly)]);
(await CallAsync(readOnly, Request(RawPlacement(0)))).StatusCode.ShouldBe(BadUserAccessDenied);
}
[Fact]
public async Task An_activation_marker_mismatch_answers_BadEventIdUnknown_with_the_marker_passed_verbatim()
{
using var f = new ConditionFixture(1, extraOperations: Methods, acls: [Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator)]);
f.Source.Execute = call => call.ExpectedActivation == new ConditionActivationMarker("inc", 1)
? new(false, true, BadEventIdUnknown, "The condition has a newer occurrence.") : new(true, true, 0, null);
var result = await CallAsync(f, Request(RawPlacement(0)));
result.State.ShouldBe(DataWriteState.RejectedBeforeDispatch);
result.StatusCode.ShouldBe(BadEventIdUnknown);
}
[Fact]
public async Task A_duplicate_operation_id_joins_and_a_reused_id_with_another_call_is_refused()
{
using var f = new ConditionFixture(1, extraOperations: Methods, acls: [Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator)]);
var first = await CallAsync(f, Request(RawPlacement(0)));
var second = await CallAsync(f, Request(RawPlacement(0)));
second.ShouldBe(first);
f.Source.MethodCalls.Count.ShouldBe(1); // joined: never executed twice
f.AuditLog.Entries.Select(e => e.Joined).ShouldBe([false, true]);
(await CallAsync(f, Request(RawPlacement(0), comment: "different"))).StatusCode.ShouldBe(BadInvalidArgument);
f.Source.MethodCalls.Count.ShouldBe(1);
}
[Fact]
public async Task Audit_text_is_sanitised_and_written_only_to_the_audit_log()
{
using var f = new ConditionFixture(1, extraOperations: Methods, acls: [Acl(NodeAclScopeKind.Cluster, null, NodePermissions.Operator)]);
var hostile = "op\u0000erator\r\n‮evil\u0007" + new string('x', 300);
await CallAsync(f, Request(RawPlacement(0), onBehalfOf: hostile));
var entry = f.AuditLog.Entries.ShouldHaveSingleItem();
entry.OnBehalfOf.ShouldNotBeNull().Length.ShouldBe(DataConditionMethodRequest.MaxOnBehalfOfLength);
entry.OnBehalfOf.ShouldStartWith("operatorevilxxx");
entry.OnBehalfOf.ShouldAllBe(c => !char.IsControl(c) && c != '‮');
entry.ShouldSatisfyAllConditions(e => e.Principal.ShouldBe("peer"), e => e.OperationId.ShouldBe("op-1"),
e => e.Placement.ShouldBe(RawPlacement(0)), e => e.State.ShouldBe(DataWriteState.AcceptedUnconfirmed));
// The node manager (and so AlarmCommand / ClientUserId) sees the service principal and the Part 9 comment only.
var call = f.Source.MethodCalls.ShouldHaveSingleItem();
call.Principal.ShouldBe("peer");
call.Comment.ShouldBe("ack");
call.ToString().ShouldNotContain("evil");
}
[Theory]
[InlineData(null, null)]
[InlineData("\u0000​\r\n", null)]
[InlineData("ops \U0001F600 team", "ops \U0001F600 team")]
public void SanitizeAuditText_drops_control_format_and_unpaired_surrogates(string? input, string? expected) =>
LocalDataServices.SanitizeAuditText(input).ShouldBe(expected);
[Fact]
public void SanitizeAuditText_drops_an_unpaired_surrogate_and_never_splits_a_pair_at_the_cap()
{
LocalDataServices.SanitizeAuditText("a" + '\uD800' + "b").ShouldBe("ab");
var capped = LocalDataServices.SanitizeAuditText(new string('x', 127) + "\U0001F600").ShouldNotBeNull();
capped.ShouldBe(new string('x', 127)); // the pair would cross 128: dropped whole
}
[Theory]
[InlineData(Methods, null, false, 3u)] // native: Acknowledge | AddComment, never Confirm
[InlineData(Methods, DriverTypeNames.Galaxy, false, 0u)] // Galaxy without the opt-in: nothing callable
[InlineData(Methods, DriverTypeNames.Galaxy, true, 3u)]
[InlineData(DataOperations.None, null, false, 0u)] // no method grant
public async Task The_listing_advertises_the_methods_this_caller_may_call(DataOperations grants, string? driver, bool optIn, uint expected)
{
using var f = new ConditionFixture(1, extraOperations: grants, driverType: driver, galaxyAck: optIn);
await using var stream = await f.OpenAsync();
var snapshot = await stream.ReadSnapshotAsync();
snapshot.Records.ShouldHaveSingleItem().Info.ShouldNotBeNull().SupportedMethods.ShouldBe(expected);
}
}