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.
250 lines
13 KiB
C#
250 lines
13 KiB
C#
using Shouldly;
|
|
using Xunit;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Driver.Heidenhain.Tests;
|
|
|
|
/// <summary>TagConfig grammar, catalog and options validation (reference <c>HeidenhainBindingsTest</c> / <c>HeidenhainConfigTest</c>).</summary>
|
|
[Trait("Category", "Unit")]
|
|
public sealed class HeidenhainConfigTests
|
|
{
|
|
private static bool Accepts(string json) => HeidenhainTagDefinitionFactory.TryFromTagConfig("p", "d", json, out _, out _);
|
|
|
|
[Fact]
|
|
public void Parses_both_binding_families_and_preserves_colons_in_data_paths()
|
|
{
|
|
HeidenhainTagDefinitionFactory.TryFromTagConfig("p", "d", """{"address":"PLC:MARKER:32","dataType":"Boolean"}""", out var a, out _).ShouldBeTrue();
|
|
a!.Address.Area.ShouldBe(HeidenhainPlcArea.Marker);
|
|
a.Address.Index.ShouldBe(32);
|
|
HeidenhainTagDefinitionFactory.TryFromTagConfig("p", "d", """{"address":"DATA:/TABLE/TNC:TOOL/DOC","dataType":"String"}""", out var b, out _).ShouldBeTrue();
|
|
b!.Address.DataPath.ShouldBe("/TABLE/TNC:TOOL/DOC");
|
|
b.DataType.ShouldBe(DriverDataType.String);
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("""{"address":"PLC:WORD:0","dataType":"Boolean"}""")] // area/type mismatch
|
|
[InlineData("""{"address":"PLC:MARKER:0","dataType":"Int32"}""")]
|
|
[InlineData("""{"address":"PLC:BYTE:-1","dataType":"Int16"}""")]
|
|
[InlineData("""{"address":"PLC:DWORD:0","dataType":"Int16"}""")] // narrows native range
|
|
[InlineData("""{"address":"PLC:INPUT_WORD:0","dataType":"Int16"}""")] // uint16 into int16
|
|
[InlineData("""{"address":"PLC:STRING:0","dataType":"Int32"}""")]
|
|
[InlineData("""{"address":"PLC:WORD:99999999999","dataType":"Int64"}""")] // > uint32
|
|
[InlineData("""{"address":"PLC:WORD:4294967296","dataType":"Int64"}""")]
|
|
[InlineData("""{"address":"PLC:WORDS:0","dataType":"Int64"}""")]
|
|
[InlineData("""{"address":"PLC:WORD:0"}""")] // custom needs a dataType
|
|
[InlineData("""{"address":"PLC:WORD:0","dataType":"Float32"}""")]
|
|
[InlineData("""{"address":"PLC:WORD:0","dataType":"UInt16"}""")]
|
|
[InlineData("""{"address":"PLC:WORD:0","dataType":"8"}""")] // numerically-serialized enum
|
|
[InlineData("""{"address":"PLC:WORD:0","dataType":8}""")]
|
|
[InlineData("""{"address":"DATA:/a\u0000b","dataType":"String"}""")]
|
|
[InlineData("""{"address":"DATA:/€","dataType":"String"}""")]
|
|
[InlineData("""{"address":"DATA:","dataType":"String"}""")]
|
|
[InlineData("""{"address":"Status/Nope"}""")]
|
|
[InlineData("""{"address":"status/executionstate"}""")]
|
|
[InlineData("""{"address":"Status/ExecutionState","dataType":"String"}""")] // catalog type mismatch
|
|
[InlineData("""{"address":"Axes/Names"}""")] // array leaf without isArray
|
|
[InlineData("""{"address":"Status/ExecutionState","isArray":true}""")] // scalar marked array
|
|
[InlineData("""{"address":"Status/ExecutionState","writable":true}""")] // read-only driver
|
|
[InlineData("""{"address":42}""")]
|
|
[InlineData("""[]""")]
|
|
[InlineData("""not json""")]
|
|
[InlineData("")]
|
|
public void Rejects_unsafe_mismatched_or_malformed_blobs(string json)
|
|
{
|
|
Accepts(json).ShouldBeFalse(json);
|
|
HeidenhainTagDefinitionFactory.Inspect(json).ShouldNotBeEmpty();
|
|
}
|
|
|
|
[Fact]
|
|
public void Inspect_is_never_stricter_than_the_runtime_parse()
|
|
{
|
|
foreach (var e in HeidenhainCatalog.Entries)
|
|
{
|
|
var json = TestTags.Config(e.Address);
|
|
Accepts(json).ShouldBeTrue(json);
|
|
HeidenhainTagDefinitionFactory.Inspect(json).ShouldBeEmpty();
|
|
}
|
|
|
|
Accepts("""{"address":"PLC:INPUT_WORD:0","dataType":"Int32","isHistorized":true}""").ShouldBeTrue();
|
|
Accepts("""{"address":"Status/ExecutionState","dataType":"int32"}""").ShouldBeTrue();
|
|
}
|
|
|
|
[Fact]
|
|
public void Catalog_is_general_purpose_read_only_and_without_oee_mapping()
|
|
{
|
|
HeidenhainCatalog.Entries.ShouldContain(e => e.Address == "Axes/Positions" && e.IsArray && e.DataType == DriverDataType.Float64);
|
|
HeidenhainCatalog.Entries.ShouldContain(e => e.Address == "Status/ExecutionState" && e.DataType == DriverDataType.Int32);
|
|
HeidenhainCatalog.Entries.ShouldNotContain(e => e.Address.Contains("RunState") || e.Address.Contains("GoodCount") || e.Address.Contains("IdealRate"));
|
|
HeidenhainCatalog.Entries.Select(e => e.Address).ShouldBeUnique();
|
|
HeidenhainCatalog.Entries.Where(e => e.IsCapability).ShouldAllBe(e => e.DataType == DriverDataType.String);
|
|
HeidenhainCatalog.Entries.Count(e => e.Address.StartsWith("Timers/")).ShouldBe(5);
|
|
}
|
|
|
|
[Fact]
|
|
public void Options_have_reference_defaults()
|
|
{
|
|
var o = HeidenhainOptionsParser.Parse("{}");
|
|
o.TimeoutMs.ShouldBe(5000);
|
|
o.Polling.StatusMs.ShouldBe(1000);
|
|
o.Polling.CustomMs.ShouldBe(1000);
|
|
o.Polling.SlowMs.ShouldBe(10000);
|
|
o.Polling.MaxAlarms.ShouldBe(64);
|
|
o.Polling.TimersEnabled.ShouldBeFalse();
|
|
o.Access.TelemetryEnabled.ShouldBeTrue();
|
|
o.Access.DataEnabled.ShouldBeFalse();
|
|
new HeidenhainDeviceOptions().Port.ShouldBe(19000);
|
|
HeidenhainOptionsParser.Validate(o).ShouldBeEmpty();
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("""{"TimeoutMs":99}""")]
|
|
[InlineData("""{"TimeoutMs":60001}""")]
|
|
[InlineData("""{"Polling":{"StatusMs":50}}""")]
|
|
[InlineData("""{"Polling":{"SlowMs":3600001}}""")]
|
|
[InlineData("""{"Polling":{"MaxAlarms":0}}""")]
|
|
[InlineData("""{"Polling":{"MaxAlarms":257}}""")]
|
|
[InlineData("""{"Reconnect":{"InitialDelayMs":5000,"MaxDelayMs":1000}}""")]
|
|
[InlineData("""{"Access":{"InspectPassword":"hunter2"}}""")]
|
|
[InlineData("""{"Access":{"DncPassword":"secret:"}}""")]
|
|
[InlineData("""{"Devices":[{"Host":"h","DataPassword":"plain"}]}""")]
|
|
public void Invalid_options_are_rejected_without_echoing_credentials(string json)
|
|
{
|
|
var errors = HeidenhainOptionsParser.Validate(HeidenhainOptionsParser.Parse(json));
|
|
errors.ShouldNotBeEmpty();
|
|
string.Join(" ", errors).ShouldNotContain("hunter2");
|
|
string.Join(" ", errors).ShouldNotContain("plain'");
|
|
Should.Throw<InvalidOperationException>(() => HeidenhainDriver.ParseOptions(json));
|
|
}
|
|
|
|
[Theory]
|
|
[InlineData("secret:heidenhain/inspect")]
|
|
[InlineData("secret:heidenhain/line3/cnc-7.inspect")]
|
|
[InlineData("env:OTOPCUA_HEIDENHAIN_DNC_PASSWORD")]
|
|
[InlineData("")]
|
|
[InlineData(null)]
|
|
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")]
|
|
[InlineData("host name")]
|
|
[InlineData("a\\b")]
|
|
public void Device_hosts_are_validated(string host) =>
|
|
HeidenhainOptionsParser.ValidateDevice(new HeidenhainDeviceOptions { Host = host }).ShouldNotBeEmpty();
|
|
|
|
[Fact]
|
|
public void Device_port_is_validated() =>
|
|
HeidenhainOptionsParser.ValidateDevice(new HeidenhainDeviceOptions { Host = "10.0.0.1", Port = 0 }).ShouldNotBeEmpty();
|
|
|
|
[Fact]
|
|
public async Task Credentials_resolve_from_secret_store_and_environment_and_fail_closed()
|
|
{
|
|
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: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<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: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 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);
|
|
}
|
|
}
|
|
}
|