f7a3588b24
- Credential exfiltration (review 2): password references are scoped to secret:heidenhain/<name> and env:OTOPCUA_HEIDENHAIN_<NAME> only. Enforced by HeidenhainOptionsParser.TryParseCredentialReference (parser, probe, deploy gate) AND again at resolve time in HeidenhainCredentials (fail closed without consulting the store or the environment), so Test Connect can no longer send env:ConnectionStrings__ConfigDb or another subsystem's secret to an arbitrary Host. The probe also refuses an unsendable password. - Optional-role credentials (review 6): an unresolvable/NUL/non-Latin-1/>247-byte DNC or DATA credential never sends a login and never fails the session; the reads needing that role are BadConfigurationError (capability ConfigurationError) and INSPECT telemetry continues. A policy refusal inside AcquireAsync is per-tag, not a session teardown. - Start after DisposeAsync is a no-op (review 3); initial subscription push and Publish are ordered under one lock (review 4); JSON-null sections are normalised and the acquisition loop catches every fault (review 5); backoff resets only after a session published a poll batch, with clamped delays (review 7). Tests: HeidenhainReviewFixTests + namespace/normalisation tests in HeidenhainConfigTests; each was confirmed red against the reverted fix.
237 lines
11 KiB
C#
237 lines
11 KiB
C#
using System.Collections.Concurrent;
|
||
using Microsoft.Extensions.Logging.Abstractions;
|
||
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>Regression tests for the independent-review findings 3–7 on feat/803 (each fails on the pre-fix code).</summary>
|
||
[Trait("Category", "Unit")]
|
||
public sealed class HeidenhainReviewFixTests
|
||
{
|
||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||
|
||
private static async Task<(Lsv2Simulator Sim, HeidenhainSession Session)> OpenAsync(
|
||
SimulatedControl control, HeidenhainSessionSettings settings, HeidenhainSession.PasswordSource passwords)
|
||
{
|
||
var sim = Lsv2Simulator.WithControl(control);
|
||
var client = new Lsv2Client("127.0.0.1", sim.Port, TimeSpan.FromSeconds(1));
|
||
var session = new HeidenhainSession(client, settings, passwords);
|
||
await client.OpenAsync(Ct);
|
||
await session.InitializeAsync(Ct);
|
||
return (sim, session);
|
||
}
|
||
|
||
// ---- Finding 6: an unusable OPTIONAL-role credential degrades only the reads that need that role. ----
|
||
|
||
[Theory]
|
||
[InlineData("throw")] // unresolvable reference (unset variable / missing secret)
|
||
[InlineData("nul")] // a NUL the login payload cannot carry
|
||
[InlineData("non-latin1")] // € is not Latin-1
|
||
[InlineData("too-long")] // A_LG payload > 247 bytes
|
||
public async Task Bad_dnc_credential_keeps_inspect_telemetry_and_sends_no_dnc_login(string kind)
|
||
{
|
||
var control = new SimulatedControl();
|
||
control.Runtime[23] = () => SimulatedControl.U16(4);
|
||
var settings = new HeidenhainSessionSettings(true, true, false, 64, false, false, false);
|
||
var (sim, session) = await OpenAsync(control, settings, (role, _) => role == "DNC" ? BadPassword(kind) : ValueTask.FromResult(""));
|
||
await using var _ = sim;
|
||
await using var __ = session;
|
||
var tags = new[] { TestTags.Def("Status/ExecutionState"), TestTags.Def("Capabilities/DncLogin") };
|
||
var s1 = await session.ReadBatchAsync(tags, Ct);
|
||
var s2 = await session.ReadBatchAsync(tags, Ct);
|
||
s1[0].Value.ShouldBe(4);
|
||
s2[0].Value.ShouldBe(4);
|
||
s1[1].Value.ShouldBe("ConfigurationError");
|
||
session.CommunicationLost.ShouldBeFalse();
|
||
control.Logins.Select(l => l.Role).ShouldBe(new[] { "INSPECT" });
|
||
}
|
||
|
||
[Theory]
|
||
[InlineData("throw")]
|
||
[InlineData("nul")]
|
||
[InlineData("too-long")]
|
||
public async Task Bad_data_credential_is_BadConfigurationError_on_data_bindings_only(string kind)
|
||
{
|
||
var control = new SimulatedControl();
|
||
control.Runtime[23] = () => SimulatedControl.U16(4);
|
||
control.DataPaths["/x"] = SimReply.Ok("S_DP", [0, 0, 0, 3, 0, 0, 0, 42]);
|
||
var settings = new HeidenhainSessionSettings(true, false, true, 64, false, false, true);
|
||
var (sim, session) = await OpenAsync(control, settings, (role, _) => role == "DATA" ? BadPassword(kind) : ValueTask.FromResult(""));
|
||
await using var _ = sim;
|
||
await using var __ = session;
|
||
var tags = new[] { TestTags.Def("DATA:/x", "Int64"), TestTags.Def("Status/ExecutionState"), TestTags.Def("Capabilities/DataLogin") };
|
||
for (var i = 0; i < 2; i++)
|
||
{
|
||
var s = await session.ReadBatchAsync(tags, Ct);
|
||
s[0].Status.ShouldBe(HeidenhainStatus.BadConfigurationError);
|
||
s[1].Value.ShouldBe(4);
|
||
s[2].Value.ShouldBe("ConfigurationError");
|
||
}
|
||
|
||
session.CommunicationLost.ShouldBeFalse();
|
||
sim.Requests.ShouldNotContain(r => r.Command == "R_DP");
|
||
control.Logins.ShouldNotContain(l => l.Role == "DATA");
|
||
}
|
||
|
||
private static ValueTask<string> BadPassword(string kind) => kind switch
|
||
{
|
||
"throw" => throw new HeidenhainCredentialException("DATA password environment variable 'OTOPCUA_HEIDENHAIN_X' is not set (fail-closed)."),
|
||
"nul" => ValueTask.FromResult("a\0b"),
|
||
"non-latin1" => ValueTask.FromResult("p€ss"),
|
||
_ => ValueTask.FromResult(new string('x', 250)),
|
||
};
|
||
|
||
// ---- Finding 3: Start after DisposeAsync must not revive an orphan loop. ----
|
||
|
||
[Fact]
|
||
public async Task Start_after_dispose_is_a_no_op()
|
||
{
|
||
var control = new SimulatedControl();
|
||
control.Runtime[23] = () => SimulatedControl.U16(4);
|
||
await using var sim = Lsv2Simulator.WithControl(control);
|
||
var runtime = NewRuntime(sim.Port, (_, _) => { });
|
||
await runtime.DisposeAsync();
|
||
runtime.Start();
|
||
await Task.Delay(400, Ct);
|
||
sim.Connections.ShouldBe(0);
|
||
runtime.State.ShouldBe(HeidenhainConnectionState.Stopped);
|
||
}
|
||
|
||
// ---- Finding 5: null sections must not NRE, and nothing may kill the loop silently. ----
|
||
|
||
[Fact]
|
||
public async Task Null_option_sections_from_a_constructed_options_object_do_not_kill_the_loop()
|
||
{
|
||
int port;
|
||
await using (var probe = Lsv2Simulator.WithScript((_, _) => Task.CompletedTask)) port = probe.Port;
|
||
var options = new HeidenhainDriverOptions
|
||
{
|
||
Devices = [new HeidenhainDeviceOptions { Host = "127.0.0.1", Port = port, DeviceName = "dev1" }],
|
||
RawTags = [TestTags.Raw("Status/ExecutionState")],
|
||
Access = null!,
|
||
Polling = null!,
|
||
Reconnect = null!,
|
||
TimeoutMs = 300,
|
||
};
|
||
var attempts = new ConcurrentQueue<DateTime>();
|
||
await using var d = new HeidenhainDriver(options, "hh", null, new HeidenhainCredentials(null),
|
||
(h, p, t) => { attempts.Enqueue(DateTime.UtcNow); return new Lsv2Client(h, p, t); }, null);
|
||
await d.InitializeAsync("{}", Ct);
|
||
await d.SubscribeAsync([TestTags.Raw("Status/ExecutionState").RawPath], TimeSpan.FromSeconds(1), Ct);
|
||
await Task.Delay(3500, Ct);
|
||
attempts.Count.ShouldBeGreaterThanOrEqualTo(2); // the loop survived the first failure and retried
|
||
d.GetHealth().State.ShouldBe(DriverState.Degraded);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Null_option_sections_normalise_so_the_control_is_actually_read()
|
||
{
|
||
var control = new SimulatedControl();
|
||
control.Runtime[23] = () => SimulatedControl.U16(4);
|
||
await using var sim = Lsv2Simulator.WithControl(control);
|
||
var tag = TestTags.Raw("Status/ExecutionState");
|
||
var options = new HeidenhainDriverOptions
|
||
{
|
||
Devices = [new HeidenhainDeviceOptions { Host = "127.0.0.1", Port = sim.Port, DeviceName = "dev1" }],
|
||
RawTags = [tag],
|
||
Access = null!,
|
||
Polling = null!,
|
||
Reconnect = null!,
|
||
};
|
||
await using var d = new HeidenhainDriver(options, "hh", null, new HeidenhainCredentials(null), null, null);
|
||
await d.InitializeAsync("{}", Ct);
|
||
await d.SubscribeAsync([tag.RawPath], TimeSpan.FromSeconds(1), Ct);
|
||
var deadline = DateTime.UtcNow.AddSeconds(5);
|
||
while ((await d.ReadAsync([tag.RawPath], Ct))[0].StatusCode != HeidenhainStatus.Good && DateTime.UtcNow < deadline)
|
||
await Task.Delay(50, Ct);
|
||
(await d.ReadAsync([tag.RawPath], Ct))[0].Value.ShouldBe(4);
|
||
}
|
||
|
||
// ---- Finding 7: backoff resets only after real progress (a published poll batch). ----
|
||
|
||
[Fact]
|
||
public async Task A_control_that_accepts_login_then_drops_is_backed_off_not_hammered()
|
||
{
|
||
var control = new SimulatedControl();
|
||
control.Runtime[23] = SimReply.Drop; // login + version succeed, the first poll read drops
|
||
await using var sim = Lsv2Simulator.WithControl(control);
|
||
var runtime = NewRuntime(sim.Port, (_, _) => { });
|
||
await using var _ = runtime;
|
||
runtime.Start();
|
||
await Task.Delay(2000, Ct);
|
||
// initial 100 ms doubling to 800 ms: ~100+200+400+800 ⇒ ≤ 6 connects in 2 s; pre-fix it reset to
|
||
// 100 ms after every login and dialled ~15 times.
|
||
sim.Connections.ShouldBeInRange(2, 6);
|
||
runtime.ConsecutiveFailures.ShouldBeGreaterThanOrEqualTo(3);
|
||
}
|
||
|
||
[Fact]
|
||
public async Task Backoff_resets_after_a_session_that_published()
|
||
{
|
||
var reads = 0;
|
||
var control = new SimulatedControl();
|
||
control.Runtime[23] = () => Interlocked.Increment(ref reads) % 3 == 0 ? SimReply.Drop() : SimulatedControl.U16(4);
|
||
await using var sim = Lsv2Simulator.WithControl(control);
|
||
var runtime = NewRuntime(sim.Port, (_, _) => { });
|
||
await using var _ = runtime;
|
||
runtime.Start();
|
||
await Task.Delay(1500, Ct);
|
||
runtime.ConsecutiveFailures.ShouldBeLessThanOrEqualTo(1);
|
||
}
|
||
|
||
// ---- Finding 4: the initial subscription push can never deliver an older value after a newer one. ----
|
||
|
||
[Fact]
|
||
public async Task Initial_push_and_publish_are_ordered()
|
||
{
|
||
var options = new HeidenhainDriverOptions
|
||
{
|
||
Devices = [new HeidenhainDeviceOptions { Host = "127.0.0.1", Port = 1, DeviceName = "dev1" }],
|
||
RawTags = [TestTags.Raw("Status/ExecutionState")],
|
||
};
|
||
await using var d = new HeidenhainDriver(options, "hh", null, new HeidenhainCredentials(null), null, null);
|
||
await d.InitializeAsync("{}", Ct);
|
||
var raw = options.RawTags[0].RawPath;
|
||
var perSub = new ConcurrentDictionary<ISubscriptionHandle, List<int>>();
|
||
d.OnDataChange += (_, e) =>
|
||
{
|
||
if (e.Snapshot.Value is int v) perSub.GetOrAdd(e.SubscriptionHandle, _ => []).Add(v);
|
||
};
|
||
using var stop = new CancellationTokenSource();
|
||
var publisher = Task.Run(() =>
|
||
{
|
||
var now = DateTime.UtcNow;
|
||
for (var i = 1; i < 20_000 && !stop.IsCancellationRequested; i++)
|
||
d.Publish(raw, new DataValueSnapshot(i, HeidenhainStatus.Good, now, now));
|
||
}, Ct);
|
||
for (var i = 0; i < 200; i++)
|
||
await d.SubscribeAsync([raw], TimeSpan.FromSeconds(1), Ct);
|
||
await publisher;
|
||
foreach (var (_, values) in perSub)
|
||
{
|
||
List<int> copy;
|
||
lock (values) copy = values.ToList();
|
||
for (var i = 1; i < copy.Count; i++)
|
||
copy[i].ShouldBeGreaterThan(copy[i - 1], "a subscriber saw an older value after a newer one");
|
||
}
|
||
}
|
||
|
||
private static HeidenhainDeviceRuntime NewRuntime(int port, Action<string, DataValueSnapshot> publish)
|
||
{
|
||
var options = new HeidenhainDriverOptions
|
||
{
|
||
TimeoutMs = 500,
|
||
Polling = new HeidenhainPollingOptions { StatusMs = 100, CustomMs = 100, SlowMs = 100 },
|
||
Reconnect = new HeidenhainReconnectOptions { InitialDelayMs = 100, MaxDelayMs = 800 },
|
||
};
|
||
var device = new HeidenhainDeviceOptions { Host = "127.0.0.1", Port = port, DeviceName = "dev1" };
|
||
return new HeidenhainDeviceRuntime(device, options, [TestTags.Def("Status/ExecutionState")],
|
||
(_, _) => ValueTask.FromResult(""), publish, (_, _, _) => { },
|
||
(h, p, t) => new Lsv2Client(h, p, t), TimeProvider.System, NullLogger.Instance);
|
||
}
|
||
}
|