Files
lmxopcua/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests/Lsv2ReadOnlyPolicyTests.cs
T
Joseph Doherty d50ee809e3 feat(heidenhain): native read-only LSV2 driver + in-process simulator (#803)
Native LSV2 TCP transport (default port 19000; no Java/Python/vendor SDK), ported from
the ignitionoee v0.20.3 reference driver:

- Lsv2ReadOnlyPolicy: payload-aware outbound allowlist (A_LG INSPECT/DNC/DATA, R_VR, R_PR,
  R_RI 22-28/30-34/51, bounded R_MB, R_DP), applied in Lsv2Codec.Frame before any byte is
  written; no public raw-command API.
- Lsv2Client: serialized transactions, one monotonic deadline per transaction, EOF/oversize/
  unexpected/trickle close the client; Close never waits on the gate.
- Lsv2Data / HeidenhainBindingCodec: reference decoders, R_PR byte-capacity + element-index
  rules, next-area cap, DATA Boolean 00/01/FF, strict non-truncating coercion.
- HeidenhainSession: per-batch wire cache, refusal suppression, provisional DNC denial retry,
  alarm cursor (57 = end, overflow = BadOutOfRange), capability strings.
- HeidenhainDeviceRuntime: one loop per control, generation-guarded publication, all-node
  BadNoCommunication on comms loss, bounded exponential reconnect.
- HeidenhainDriver: cached ReadAsync, push subscriptions deduped on (value,status), static
  catalog discovery (no connect), host status, diagnostics, skipped-tag report. No IWritable.
- Probe (INSPECT login + version) and factory registered in DriverFactoryBootstrap (probe on
  admin nodes too); DriverTypeNames.Heidenhain.

Tests: 159 unit tests against an in-process LSV2 simulator incl. the Java fixtures' captured
iTNC 530 replies as golden vectors; env-gated LiveIntegration category for real hardware.
2026-11-10 23:08:30 -05:00

144 lines
7.2 KiB
C#

using System.Reflection;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Lsv2;
using ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests.Simulator;
namespace ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests;
/// <summary>
/// The payload-aware outbound allowlist (ported from the reference <c>rejectsEveryWriteAndElevatedRole</c> /
/// <c>validatesSelectorsMemoryAndPathsBeforeTransmission</c>), plus proof that a refused request never puts a
/// single byte on the wire and that the driver has no write surface at all.
/// </summary>
[Trait("Category", "Unit")]
public sealed class Lsv2ReadOnlyPolicyTests
{
public static TheoryData<string> WriteAndControlCommands() =>
[
// file / PLC / parameter / buffer writes and transfers, logout, file reads, key & scope operations,
// and response mnemonics that must never be sent as requests.
"C_CC", "C_FL", "C_MB", "C_DC", "C_DD", "C_FD", "C_FC", "C_PR", "C_EK", "C_LK", "C_MC", "C_TP",
"A_LO", "R_MC", "R_FL", "R_DI", "R_FI", "R_DR", "R_ST", "R_TP", "R_OC", "T_OK", "T_ER", "S_RI", "XXXX",
];
[Theory]
[MemberData(nameof(WriteAndControlCommands))]
public void Every_non_allowlisted_command_is_refused(string command)
{
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.Check(command, []));
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.Check(command, [0, 22]));
Should.Throw<Lsv2PolicyException>(() => Lsv2Codec.Frame(command, []));
}
[Theory]
[InlineData("PLCDEBUG")]
[InlineData("MONITOR")]
[InlineData("FILE")]
[InlineData("DIAGNOSTICS")]
[InlineData("DNC\0PLCDEBUG")]
[InlineData("inspect")]
[InlineData("")]
public void Elevated_or_unknown_roles_are_refused(string role) =>
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.LoginPayload(role, ""));
[Fact]
public void Login_payloads_are_checked_for_embedded_nul_and_role_smuggling()
{
Should.Throw<ArgumentException>(() => Lsv2ReadOnlyPolicy.LoginPayload("DNC", "x\0y"));
// a hand-built payload that names an elevated role after a permitted one
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.Check("A_LG", "PLCDEBUG\0"u8.ToArray()));
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.Check("A_LG", "INSPECT"u8.ToArray()));
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.Check("A_LG", "INSPECT\0a\0b\0"u8.ToArray()));
Lsv2ReadOnlyPolicy.LoginPayload("INSPECT", "").ShouldBe("INSPECT\0"u8.ToArray());
Lsv2ReadOnlyPolicy.LoginPayload("DATA", "pw").ShouldBe("DATA\0pw\0"u8.ToArray());
}
[Theory]
[InlineData(0)]
[InlineData(21)]
[InlineData(29)]
[InlineData(35)]
[InlineData(50)]
[InlineData(52)]
[InlineData(0xFFFF)]
public void Runtime_selectors_outside_the_allowlist_are_refused(int selector) =>
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.RuntimePayload(selector));
[Fact]
public void Allowlisted_selectors_pass_and_payload_shape_is_enforced()
{
foreach (var s in new[] { 22, 23, 24, 25, 26, 27, 28, 30, 31, 32, 33, 34, 51 })
Lsv2ReadOnlyPolicy.RuntimePayload(s).Length.ShouldBe(2);
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.Check("R_RI", [0, 23, 0]));
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.Check("R_VR", [0]));
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.Check("R_PR", [1, 2]));
}
[Fact]
public void Memory_reads_are_bounded_and_cannot_wrap()
{
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.Check("R_MB", new byte[5])); // zero count
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.MemoryPayload(0, 248));
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.MemoryPayload(-1, 1));
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.MemoryPayload(0xFFFF_FFFF, 2)); // wraps
Lsv2ReadOnlyPolicy.MemoryPayload(0xFFFF_FFFF, 1).ShouldBe(new byte[] { 0xFF, 0xFF, 0xFF, 0xFF, 1 });
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.Check("R_MB", new byte[6]));
}
[Fact]
public void Data_paths_are_validated_before_transmission()
{
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.DataPathPayload("/a\0/b"));
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.DataPathPayload("/a/€"));
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.DataPathPayload(new string('/', 244)));
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.DataPathPayload(" "));
Should.Throw<Lsv2PolicyException>(() => Lsv2ReadOnlyPolicy.Check("R_DP", [0, 0, 0, 1, 65, 0])); // nonzero prefix
Lsv2ReadOnlyPolicy.DataPathPayload("/PLC/memory/W/2").ShouldBe("\0\0\0\0\\PLC\\memory\\W\\2\0"u8.ToArray());
}
[Fact]
public async Task A_refused_request_never_reaches_the_socket()
{
var received = 0;
await using var sim = Lsv2Simulator.WithScript(async (c, ct) =>
{
while (await c.ReadByteAsync(ct) >= 0) Interlocked.Increment(ref received);
});
var client = new Lsv2Client("127.0.0.1", sim.Port, TimeSpan.FromSeconds(1));
await client.OpenAsync(TestContext.Current.CancellationToken);
foreach (var cmd in new[] { "C_CC", "C_MB", "A_LO", "R_FL" })
await Should.ThrowAsync<Lsv2PolicyException>(() => client.ExchangeAsync(cmd, [], "T_OK", TestContext.Current.CancellationToken));
await Should.ThrowAsync<Lsv2PolicyException>(() => client.ExchangeAsync("R_RI", [0, 29], "S_RI", TestContext.Current.CancellationToken));
await Should.ThrowAsync<Lsv2PolicyException>(() => client.ExchangeAsync("A_LG", "PLCDEBUG\0"u8.ToArray(), "T_OK", TestContext.Current.CancellationToken));
client.RequestsSent.ShouldBe(0);
client.IsClosed.ShouldBeFalse(); // a policy refusal is not a transport failure
client.Close();
await Task.Delay(100, TestContext.Current.CancellationToken);
Volatile.Read(ref received).ShouldBe(0);
}
[Fact]
public void Client_public_surface_has_no_raw_command_api()
{
var methods = typeof(Lsv2Client).GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
.Where(m => !m.IsSpecialName).Select(m => m.Name).OrderBy(n => n).ToArray();
methods.ShouldBe(new[]
{
"Close", "DisposeAsync", "LoginAsync", "OpenAsync", "ReadDataPathAsync", "ReadMemoryAsync",
"ReadParametersAsync", "ReadRuntimeAsync", "ReadVersionAsync",
});
typeof(Lsv2Client).GetMethod("ExchangeAsync", BindingFlags.Public | BindingFlags.Instance).ShouldBeNull();
}
[Fact]
public void Driver_has_no_write_capability()
{
typeof(IWritable).IsAssignableFrom(typeof(HeidenhainDriver)).ShouldBeFalse();
typeof(HeidenhainDriver).GetMethods().ShouldNotContain(m => m.Name.Contains("Write", StringComparison.Ordinal));
Lsv2ReadOnlyPolicy.Commands.ShouldBe(new[] { "A_LG", "R_VR", "R_PR", "R_RI", "R_MB", "R_DP" }, ignoreOrder: true);
Lsv2ReadOnlyPolicy.Roles.ShouldBe(new[] { "INSPECT", "DNC", "DATA" }, ignoreOrder: true);
}
}