fix(heidenhain): namespaced credentials, optional-role credential isolation, loop robustness (#803 review)
- 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.
This commit is contained in:
@@ -117,13 +117,94 @@ public sealed class HeidenhainConfigTests
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("secret:lsv2-inspect")]
|
||||
[InlineData("env:LSV2_DNC_PASSWORD")]
|
||||
[InlineData("secret:heidenhain/inspect")]
|
||||
[InlineData("secret:heidenhain/line3/cnc-7.inspect")]
|
||||
[InlineData("env:OTOPCUA_HEIDENHAIN_DNC_PASSWORD")]
|
||||
[InlineData("")]
|
||||
[InlineData(null)]
|
||||
public void Credential_references_are_accepted(string? value) =>
|
||||
public void Namespaced_credential_references_are_accepted(string? value) =>
|
||||
HeidenhainOptionsParser.IsCredentialReference(value).ShouldBeTrue();
|
||||
|
||||
/// <summary>
|
||||
/// Review finding 2: an unscoped reference let a Designer exfiltrate any node secret by pointing Host at their
|
||||
/// own machine and clicking Test Connect (the value is sent in cleartext in A_LG).
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("env:ConnectionStrings__ConfigDb")]
|
||||
[InlineData("env:ServerHistorian__ApiKey")]
|
||||
[InlineData("env:HEIDENHAIN_PW")]
|
||||
[InlineData("env:otopcua_heidenhain_pw")]
|
||||
[InlineData("env:OTOPCUA_HEIDENHAIN_")]
|
||||
[InlineData("env:OTOPCUA_HEIDENHAIN_A-B")]
|
||||
[InlineData("secret:galaxy/inst1/apikey")]
|
||||
[InlineData("secret:opcua/inst/password")]
|
||||
[InlineData("secret:heidenhain/")]
|
||||
[InlineData("secret:heidenhain/../galaxy/apikey")]
|
||||
[InlineData("secret:heidenhain//x")]
|
||||
[InlineData("secret:HEIDENHAIN/x")]
|
||||
[InlineData("SECRET:heidenhain/x")]
|
||||
[InlineData("secret:")]
|
||||
[InlineData("hunter2")]
|
||||
public void References_outside_the_heidenhain_namespace_are_refused(string value)
|
||||
{
|
||||
HeidenhainOptionsParser.IsCredentialReference(value).ShouldBeFalse(value);
|
||||
HeidenhainOptionsParser.Validate(new HeidenhainDriverOptions { Access = new() { InspectPassword = value } }).ShouldNotBeEmpty();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("env:ConnectionStrings__ConfigDb")]
|
||||
[InlineData("secret:galaxy/inst1/apikey")]
|
||||
public async Task The_resolver_fails_closed_for_out_of_namespace_references_without_consulting_store_or_environment(string reference)
|
||||
{
|
||||
var resolver = new FakeResolver(new() { ["galaxy/inst1/apikey"] = "GALAXY-KEY" });
|
||||
var envReads = 0;
|
||||
var c = new HeidenhainCredentials(resolver, n => { envReads++; return "CONFIG-DB-CONNSTR"; });
|
||||
var ex = await Should.ThrowAsync<HeidenhainCredentialException>(() => c.ResolveReferenceAsync(reference, "INSPECT", TestContext.Current.CancellationToken).AsTask());
|
||||
ex.Message.ShouldNotContain("GALAXY-KEY");
|
||||
ex.Message.ShouldNotContain("CONFIG-DB-CONNSTR");
|
||||
envReads.ShouldBe(0);
|
||||
resolver.Reads.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_probe_never_sends_an_out_of_namespace_credential()
|
||||
{
|
||||
var sent = 0;
|
||||
await using var sim = Simulator.Lsv2Simulator.WithScript(async (conn, ct) => { while (await conn.ReadByteAsync(ct) >= 0) sent++; });
|
||||
var json = $$$"""{"Devices":[{"Host":"127.0.0.1","Port":{{{sim.Port}}},"DeviceName":"d"}],"Access":{"InspectPassword":"env:ConnectionStrings__ConfigDb"}}""";
|
||||
var result = await new HeidenhainDriverProbe(new FakeResolver(new())).ProbeAsync(json, TimeSpan.FromSeconds(2), TestContext.Current.CancellationToken);
|
||||
result.Ok.ShouldBeFalse();
|
||||
await Task.Delay(100, TestContext.Current.CancellationToken);
|
||||
sim.Connections.ShouldBe(0);
|
||||
sent.ShouldBe(0);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("""{"Access":null,"Polling":null,"Reconnect":null,"Devices":null,"RawTags":null}""")]
|
||||
[InlineData("""{"Devices":[null],"RawTags":[null]}""")]
|
||||
public void Null_sections_normalise_to_defaults(string json)
|
||||
{
|
||||
var o = HeidenhainOptionsParser.Parse(json);
|
||||
o.Access.ShouldNotBeNull();
|
||||
o.Polling.MaxAlarms.ShouldBe(64);
|
||||
o.Reconnect.InitialDelayMs.ShouldBe(1000);
|
||||
o.Devices.ShouldBeEmpty();
|
||||
o.RawTags.ShouldBeEmpty();
|
||||
HeidenhainOptionsParser.Validate(o).ShouldBeEmpty();
|
||||
Should.NotThrow(() => HeidenhainDriver.ParseOptions(json));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Raw_config_scan_finds_literals_at_every_level_case_insensitively()
|
||||
{
|
||||
HeidenhainOptionsParser.DescribeCredentialProblems("""{"Host":"h","dncpassword":"hunter2"}""").Count.ShouldBe(1);
|
||||
HeidenhainOptionsParser.DescribeCredentialProblems("""{"access":{"InspectPassword":"hunter2"}}""").Count.ShouldBe(1);
|
||||
HeidenhainOptionsParser.DescribeCredentialProblems("""{"Devices":[{"DataPassword":"x"},{"DataPassword":7}]}""").Count.ShouldBe(2);
|
||||
HeidenhainOptionsParser.DescribeCredentialProblems("""{"Access":{"InspectPassword":"secret:heidenhain/a"}}""").ShouldBeEmpty();
|
||||
string.Join(" ", HeidenhainOptionsParser.DescribeCredentialProblems("""{"Access":{"InspectPassword":"hunter2"}}""")).ShouldNotContain("hunter2");
|
||||
HeidenhainOptionsParser.DescribeCredentialProblems("not json").ShouldNotBeEmpty();
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("")]
|
||||
[InlineData("http://host")]
|
||||
@@ -139,25 +220,30 @@ public sealed class HeidenhainConfigTests
|
||||
[Fact]
|
||||
public async Task Credentials_resolve_from_secret_store_and_environment_and_fail_closed()
|
||||
{
|
||||
var resolver = new FakeResolver(new() { ["lsv2"] = "s3cret" });
|
||||
var env = new Dictionary<string, string> { ["LSV2_PW"] = "envpw" };
|
||||
var resolver = new FakeResolver(new() { ["heidenhain/lsv2"] = "s3cret" });
|
||||
var env = new Dictionary<string, string> { ["OTOPCUA_HEIDENHAIN_PW"] = "envpw" };
|
||||
var c = new HeidenhainCredentials(resolver, n => env.GetValueOrDefault(n));
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
(await c.ResolveReferenceAsync("secret:lsv2", "INSPECT", ct)).ShouldBe("s3cret");
|
||||
(await c.ResolveReferenceAsync("env:LSV2_PW", "DNC", ct)).ShouldBe("envpw");
|
||||
(await c.ResolveReferenceAsync("secret:heidenhain/lsv2", "INSPECT", ct)).ShouldBe("s3cret");
|
||||
(await c.ResolveReferenceAsync("env:OTOPCUA_HEIDENHAIN_PW", "DNC", ct)).ShouldBe("envpw");
|
||||
(await c.ResolveReferenceAsync(null, "DNC", ct)).ShouldBe("");
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => c.ResolveReferenceAsync("secret:missing", "DNC", ct).AsTask());
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => c.ResolveReferenceAsync("env:UNSET", "DNC", ct).AsTask());
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => c.ResolveReferenceAsync("literal", "DNC", ct).AsTask());
|
||||
await Should.ThrowAsync<InvalidOperationException>(() => new HeidenhainCredentials(null).ResolveReferenceAsync("secret:lsv2", "DNC", ct).AsTask());
|
||||
await Should.ThrowAsync<HeidenhainCredentialException>(() => c.ResolveReferenceAsync("secret:heidenhain/missing", "DNC", ct).AsTask());
|
||||
await Should.ThrowAsync<HeidenhainCredentialException>(() => c.ResolveReferenceAsync("env:OTOPCUA_HEIDENHAIN_UNSET", "DNC", ct).AsTask());
|
||||
await Should.ThrowAsync<HeidenhainCredentialException>(() => c.ResolveReferenceAsync("literal", "DNC", ct).AsTask());
|
||||
await Should.ThrowAsync<HeidenhainCredentialException>(() => new HeidenhainCredentials(null).ResolveReferenceAsync("secret:heidenhain/lsv2", "DNC", ct).AsTask());
|
||||
// device override wins over the driver-level reference
|
||||
var o = new HeidenhainDriverOptions { Access = new() { InspectPassword = "secret:missing" } };
|
||||
(await c.ResolveAsync(o, new HeidenhainDeviceOptions { Host = "h", InspectPassword = "secret:lsv2" }, "INSPECT", ct)).ShouldBe("s3cret");
|
||||
var o = new HeidenhainDriverOptions { Access = new() { InspectPassword = "secret:heidenhain/missing" } };
|
||||
(await c.ResolveAsync(o, new HeidenhainDeviceOptions { Host = "h", InspectPassword = "secret:heidenhain/lsv2" }, "INSPECT", ct)).ShouldBe("s3cret");
|
||||
}
|
||||
|
||||
private sealed class FakeResolver(Dictionary<string, string> secrets) : ZB.MOM.WW.Secrets.Abstractions.ISecretResolver
|
||||
{
|
||||
public Task<string?> GetAsync(ZB.MOM.WW.Secrets.Abstractions.SecretName name, CancellationToken ct) =>
|
||||
Task.FromResult(secrets.TryGetValue(name.Value, out var v) ? v : null);
|
||||
public int Reads { get; private set; }
|
||||
|
||||
public Task<string?> GetAsync(ZB.MOM.WW.Secrets.Abstractions.SecretName name, CancellationToken ct)
|
||||
{
|
||||
Reads++;
|
||||
return Task.FromResult(secrets.TryGetValue(name.Value, out var v) ? v : null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -275,7 +275,7 @@ public sealed class HeidenhainDriverTests
|
||||
{
|
||||
var registry = new DriverFactoryRegistry();
|
||||
HeidenhainDriverFactoryExtensions.Register(registry);
|
||||
var json = """{"Devices":[{"Host":"10.0.0.5","DeviceName":"d"}],"Access":{"InspectPassword":"secret:lsv2/inspect"}}""";
|
||||
var json = """{"Devices":[{"Host":"10.0.0.5","DeviceName":"d"}],"Access":{"InspectPassword":"secret:heidenhain/inspect"}}""";
|
||||
var driver = registry.TryGet(DriverTypeNames.Heidenhain)!("hh", json);
|
||||
driver.ShouldBeOfType<HeidenhainDriver>();
|
||||
driver.DriverType.ShouldBe(DriverTypeNames.Heidenhain);
|
||||
|
||||
+3
-3
@@ -12,7 +12,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests;
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Env: <c>HEIDENHAIN_LSV2_HOST</c> (required), <c>HEIDENHAIN_LSV2_PORT</c> (default 19000),
|
||||
/// <c>HEIDENHAIN_LSV2_INSPECT_PASSWORD</c> (optional; never logged).
|
||||
/// <c>OTOPCUA_HEIDENHAIN_INSPECT_PASSWORD</c> (optional; never logged).
|
||||
/// </remarks>
|
||||
[Trait("Category", "LiveIntegration")]
|
||||
public sealed class HeidenhainLiveIntegrationTests
|
||||
@@ -28,7 +28,7 @@ public sealed class HeidenhainLiveIntegrationTests
|
||||
var ct = TestContext.Current.CancellationToken;
|
||||
await using var client = new Lsv2Client(Host!, Port, TimeSpan.FromSeconds(5));
|
||||
await client.OpenAsync(ct);
|
||||
await client.LoginAsync("INSPECT", Environment.GetEnvironmentVariable("HEIDENHAIN_LSV2_INSPECT_PASSWORD") ?? "", ct);
|
||||
await client.LoginAsync("INSPECT", Environment.GetEnvironmentVariable("OTOPCUA_HEIDENHAIN_INSPECT_PASSWORD") ?? "", ct);
|
||||
var versions = Lsv2Data.Versions(await client.ReadVersionAsync(ct));
|
||||
TestContext.Current.SendDiagnosticMessage($"model={versions.Model} nc={versions.Nc} plc={versions.Plc}");
|
||||
versions.Model.ShouldNotBeNullOrWhiteSpace();
|
||||
@@ -68,7 +68,7 @@ public sealed class HeidenhainLiveIntegrationTests
|
||||
{
|
||||
Devices = [new HeidenhainDeviceOptions { Host = Host!, Port = Port, DeviceName = "dev1" }],
|
||||
RawTags = tags,
|
||||
Access = new HeidenhainAccessOptions { InspectPassword = Environment.GetEnvironmentVariable("HEIDENHAIN_LSV2_INSPECT_PASSWORD") is { Length: > 0 } ? "env:HEIDENHAIN_LSV2_INSPECT_PASSWORD" : null },
|
||||
Access = new HeidenhainAccessOptions { InspectPassword = Environment.GetEnvironmentVariable("OTOPCUA_HEIDENHAIN_INSPECT_PASSWORD") is { Length: > 0 } ? "env:OTOPCUA_HEIDENHAIN_INSPECT_PASSWORD" : null },
|
||||
};
|
||||
await using var driver = new HeidenhainDriver(options, "live");
|
||||
await driver.InitializeAsync("{}", ct);
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user