Merge fix/815-credential-ref-scoping

# Conflicts:
#	.claude/rules/drivers.md
#	docs/drivers/Heidenhain.md
This commit is contained in:
Joseph Doherty
2026-11-11 02:08:24 -05:00
43 changed files with 2268 additions and 304 deletions
@@ -0,0 +1,62 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests;
/// <summary>lmxopcua#815: the credential-reference namespace deploy gate (Galaxy, OpcUaClient).</summary>
[Trait("Category", "Unit")]
public sealed class DraftValidatorCredentialReferenceTests
{
private static IReadOnlyList<ValidationError> Validate(string type, string driverConfig, string deviceConfig = "{}") =>
DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1,
ClusterId = "c",
DriverInstances = [new DriverInstance { DriverInstanceId = "drv", ClusterId = "c", Name = "drv", DriverType = type, DriverConfig = driverConfig }],
Devices = [new Device { DeviceId = "dev", DriverInstanceId = "drv", Name = "dev1", DeviceConfig = deviceConfig }],
Tags = [],
}).Where(e => e.Code == CredentialReferenceDeployChecks.Code).ToList();
[Theory]
[InlineData("GalaxyMxGateway", """{"Gateway":{"Endpoint":"http://evil:5001","ApiKeySecretRef":"env:ConnectionStrings__ConfigDb"}}""")]
[InlineData("GalaxyMxGateway", """{"Gateway":{"ApiKeySecretRef":"env:ServerHistorian__ApiKey"}}""")]
[InlineData("GalaxyMxGateway", """{"Gateway":{"ApiKeySecretRef":"file:C:\\otopcua\\appsettings.json"}}""")]
[InlineData("GalaxyMxGateway", """{"AlarmAck":{"FallbackPasswordSecretRef":"secret:otopcua/apikeys/ab/galaxy-ack-password"}}""")]
[InlineData("OpcUaClient", """{"EndpointUrl":"opc.tcp://evil:4840","Password":"secret:otopcua/historian/api-key"}""")]
[InlineData("OpcUaClient", """{"UserCertificatePassword":"env:ConnectionStrings__ConfigDb"}""")]
public void An_out_of_namespace_reference_is_refused_naming_the_allowed_form(string type, string config)
{
var e = Validate(type, config).ShouldHaveSingleItem();
e.Context.ShouldBe("drv");
e.Message.ShouldContain("secret:");
e.Message.ShouldContain("lmxopcua#815");
e.Message.ShouldContain("Migrate it before deploying");
e.Message.ShouldNotContain("ConnectionStrings__ConfigDb");
}
[Fact]
public void A_reference_in_a_device_config_is_checked_too()
=> Validate("GalaxyMxGateway", "{}", """{"Gateway":{"ApiKeySecretRef":"env:ConnectionStrings__ConfigDb"}}""")
.ShouldHaveSingleItem().Context.ShouldBe("dev");
[Theory]
[InlineData("GalaxyMxGateway", """{"Gateway":{"ApiKeySecretRef":"secret:galaxy/main/apikey"},"AlarmAck":{"FallbackPasswordSecretRef":"secret:otopcua/galaxy/ack-fallback"}}""")]
[InlineData("GalaxyMxGateway", """{"Gateway":{"ApiKeySecretRef":"env:GALAXY_MXGW_API_KEY"}}""")]
[InlineData("GalaxyMxGateway", """{"Gateway":{"ApiKeySecretRef":"dev:k"}}""")]
[InlineData("OpcUaClient", """{"Password":"literal","UserCertificatePassword":"env:OTOPCUA_OPCUACLIENT_CERT_PW"}""")]
[InlineData("Modbus", """{"Password":"env:ConnectionStrings__ConfigDb"}""")]
public void Namespaced_literal_and_unrelated_configs_pass(string type, string config)
=> Validate(type, config).ShouldBeEmpty();
[Fact]
public void Heidenhain_is_reported_once_by_its_own_gate_not_twice()
=> DraftValidator.Validate(new DraftSnapshot
{
GenerationId = 1, ClusterId = "c",
DriverInstances = [new DriverInstance { DriverInstanceId = "hh", ClusterId = "c", Name = "hh", DriverType = "Heidenhain", DriverConfig = """{"Access":{"InspectPassword":"env:ConnectionStrings__ConfigDb"}}""" }],
Devices = [], Tags = [],
})
.Count(e => e.Code is CredentialReferenceDeployChecks.Code or HeidenhainDeployChecks.CredentialCode).ShouldBe(1);
}
@@ -0,0 +1,134 @@
using Shouldly;
using Xunit;
namespace ZB.MOM.WW.OtOpcUa.Core.Abstractions.Tests;
/// <summary>lmxopcua#815 — the shared credential-reference parser, resolver and per-driver policy table.</summary>
public sealed class CredentialReferencesTests
{
private static readonly CredentialScope Galaxy = DriverCredentialPolicy.GalaxyScope;
[Theory]
[InlineData(null, CredentialReferenceKind.Blank)]
[InlineData("", CredentialReferenceKind.Blank)]
[InlineData("secret:galaxy/inst/apikey", CredentialReferenceKind.Secret)]
[InlineData("${secret:galaxy/inst/apikey}", CredentialReferenceKind.Secret)]
[InlineData("secret:otopcua/galaxy/ack-fallback", CredentialReferenceKind.Secret)]
[InlineData("env:OTOPCUA_GALAXY_API_KEY", CredentialReferenceKind.Environment)]
[InlineData("env:GALAXY_MXGW_API_KEY", CredentialReferenceKind.Environment)]
[InlineData("plain-key", CredentialReferenceKind.Literal)]
[InlineData("dev:k", CredentialReferenceKind.Literal)]
[InlineData("secret:otopcua/historian/api-key", CredentialReferenceKind.OutOfScope)]
[InlineData("secret:otopcua/apikeys/ab/galaxy-ack-password", CredentialReferenceKind.OutOfScope)]
[InlineData("secret:OT-MESH-PSK-MAIN", CredentialReferenceKind.OutOfScope)]
[InlineData("secret:galaxy/", CredentialReferenceKind.OutOfScope)]
[InlineData("secret:galaxy/../otopcua/historian/api-key", CredentialReferenceKind.OutOfScope)]
[InlineData("secret:galaxy//x", CredentialReferenceKind.OutOfScope)]
[InlineData("secret:galaxyx/y", CredentialReferenceKind.OutOfScope)]
[InlineData("${secret:galaxy/x", CredentialReferenceKind.OutOfScope)]
[InlineData("SECRET:galaxy/x", CredentialReferenceKind.OutOfScope)]
[InlineData("Env:OTOPCUA_GALAXY_X", CredentialReferenceKind.OutOfScope)]
[InlineData("env:ConnectionStrings__ConfigDb", CredentialReferenceKind.OutOfScope)]
[InlineData("env:ServerHistorian__ApiKey", CredentialReferenceKind.OutOfScope)]
[InlineData("env:OTOPCUA_GALAXY_", CredentialReferenceKind.OutOfScope)]
[InlineData("env:OTOPCUA_GALAXY_lower", CredentialReferenceKind.OutOfScope)]
[InlineData("env:OTOPCUA_HEIDENHAIN_X", CredentialReferenceKind.OutOfScope)]
[InlineData("file:appsettings.json", CredentialReferenceKind.OutOfScope)]
[InlineData("FILE:x", CredentialReferenceKind.OutOfScope)]
public void Parse_classifies_against_the_galaxy_scope(string? value, CredentialReferenceKind expected) =>
CredentialReferences.Parse(value, Galaxy, out _).ShouldBe(expected);
[Fact]
public void Scopes_do_not_overlap_across_drivers()
{
CredentialReferences.Parse("secret:heidenhain/x", Galaxy, out _).ShouldBe(CredentialReferenceKind.OutOfScope);
CredentialReferences.Parse("secret:galaxy/x", DriverCredentialPolicy.OpcUaClientScope, out _)
.ShouldBe(CredentialReferenceKind.OutOfScope);
CredentialReferences.Parse("env:OTOPCUA_GALAXY_X", DriverCredentialPolicy.HeidenhainScope, out _)
.ShouldBe(CredentialReferenceKind.OutOfScope);
}
[Theory]
[InlineData(CredentialLiteralPolicy.Allowed, "plain", true)]
[InlineData(CredentialLiteralPolicy.Refused, "plain", false)]
[InlineData(CredentialLiteralPolicy.Refused, "dev:x", false)]
[InlineData(CredentialLiteralPolicy.DevPrefixOnly, "dev:x", true)]
[InlineData(CredentialLiteralPolicy.DevPrefixOnly, "plain", false)]
[InlineData(CredentialLiteralPolicy.Allowed, "env:ConnectionStrings__ConfigDb", false)]
public void IsAcceptable_applies_the_literal_policy(CredentialLiteralPolicy policy, string value, bool expected) =>
CredentialReferences.IsAcceptable(value, Galaxy, policy).ShouldBe(expected);
/// <summary>The fail-closed core: an out-of-scope reference throws before either source is consulted.</summary>
[Theory]
[InlineData("env:ConnectionStrings__ConfigDb")]
[InlineData("secret:otopcua/historian/api-key")]
[InlineData("file:appsettings.json")]
public async Task Resolve_never_reads_for_an_out_of_scope_reference(string value)
{
var reads = 0;
var ex = await Should.ThrowAsync<CredentialReferenceException>(async () => await CredentialReferences.ResolveAsync(
value, Galaxy, "F", CredentialLiteralPolicy.Allowed,
(_, _) => { reads++; return ValueTask.FromResult<string?>("LEAKED"); },
_ => { reads++; return "LEAKED"; },
CancellationToken.None));
reads.ShouldBe(0);
ex.Message.ShouldContain("'secret:galaxy/<name>'");
ex.Message.ShouldContain("'env:OTOPCUA_GALAXY_<NAME>'");
ex.Message.ShouldNotContain("LEAKED");
}
[Fact]
public async Task Resolve_reads_scoped_references_and_fails_closed_when_absent()
{
(await CredentialReferences.ResolveAsync("secret:galaxy/a", Galaxy, "F", CredentialLiteralPolicy.Refused,
(n, _) => ValueTask.FromResult<string?>(n == "galaxy/a" ? "v" : null), _ => null, CancellationToken.None))
.ShouldBe("v");
(await CredentialReferences.ResolveAsync("env:OTOPCUA_GALAXY_A", Galaxy, "F", CredentialLiteralPolicy.Refused,
null, n => n == "OTOPCUA_GALAXY_A" ? "e" : null, CancellationToken.None)).ShouldBe("e");
(await Should.ThrowAsync<CredentialReferenceException>(async () => await CredentialReferences.ResolveAsync(
"secret:galaxy/missing", Galaxy, "F", CredentialLiteralPolicy.Refused,
(_, _) => ValueTask.FromResult<string?>(null), null, CancellationToken.None))).Message.ShouldContain("absent");
(await Should.ThrowAsync<CredentialReferenceException>(async () => await CredentialReferences.ResolveAsync(
"env:OTOPCUA_GALAXY_UNSET", Galaxy, "F", CredentialLiteralPolicy.Refused,
null, _ => null, CancellationToken.None))).Message.ShouldContain("not set");
(await Should.ThrowAsync<CredentialReferenceException>(async () => await CredentialReferences.ResolveAsync(
"secret:galaxy/a", Galaxy, "F", CredentialLiteralPolicy.Refused,
null, null, CancellationToken.None))).Message.ShouldContain("no secret store");
}
[Fact]
public void DescribeProblems_scans_every_depth_case_insensitively_and_never_echoes_the_value()
{
const string json = """
{
"gateway": { "endpoint": "http://evil:5001", "apiKeySecretRef": "env:ConnectionStrings__ConfigDb" },
"Devices": [ { "AlarmAck": { "FallbackPasswordSecretRef": "hunter2" } } ]
}
""";
var problems = DriverCredentialPolicy.DescribeProblems(DriverTypeNames.Galaxy, json);
problems.Count.ShouldBe(2);
problems.ShouldContain(p => p.StartsWith("gateway.apiKeySecretRef", StringComparison.Ordinal));
problems.ShouldContain(p => p.StartsWith("Devices[0].AlarmAck.FallbackPasswordSecretRef", StringComparison.Ordinal));
problems.ShouldAllBe(p => !p.Contains("hunter2") && !p.Contains("ConnectionStrings__ConfigDb"));
}
[Theory]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"ApiKeySecretRef":"secret:galaxy/main/apikey"},"AlarmAck":{"FallbackPasswordSecretRef":"dev:x"}}""")]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"ApiKeySecretRef":"literal-key"}}""")]
[InlineData(DriverTypeNames.OpcUaClient, """{"Password":"plain","UserCertificatePassword":"secret:opcuaclient/plant/cert"}""")]
[InlineData(DriverTypeNames.Heidenhain, """{"Access":{"InspectPassword":"env:OTOPCUA_HEIDENHAIN_INSPECT"}}""")]
[InlineData(DriverTypeNames.Modbus, """{"Password":"env:ConnectionStrings__ConfigDb"}""")]
[InlineData(DriverTypeNames.Galaxy, "")]
public void DescribeProblems_accepts_namespaced_and_unrelated_configs(string driverType, string json) =>
DriverCredentialPolicy.DescribeProblems(driverType, json).ShouldBeEmpty();
[Theory]
[InlineData(DriverTypeNames.OpcUaClient, """{"Password":"secret:galaxy/main/apikey"}""")]
[InlineData(DriverTypeNames.OpcUaClient, """{"UserCertificatePassword":"env:ServerHistorian__ApiKey"}""")]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"ApiKeySecretRef":"file:C:\\ProgramData\\x.txt"}}""")]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"ApiKeySecretRef":42}}""")]
[InlineData(DriverTypeNames.Heidenhain, """{"InspectPassword":"plain"}""")]
[InlineData(DriverTypeNames.Galaxy, "{not json")]
public void DescribeProblems_refuses_out_of_namespace_configs(string driverType, string json) =>
DriverCredentialPolicy.DescribeProblems(driverType, json).ShouldNotBeEmpty();
}
@@ -54,6 +54,23 @@ public sealed class GalaxyDriverBrowserTests
ex.Message.ShouldContain("ClientName");
}
/// <summary>
/// lmxopcua#815: the browser runs on the admin node against an operator-chosen endpoint with no deploy, so it
/// never gets the running driver's warn-only compatibility — a legacy ref (the old form default
/// <c>env:MX_API_KEY</c>, a <c>file:</c> path, another subsystem's secret) is refused before any connect.
/// </summary>
[Theory]
[InlineData("env:MX_API_KEY")]
[InlineData("file:appsettings.json")]
[InlineData("secret:otopcua/historian/api-key")]
public async Task OpenAsync_refuses_an_out_of_namespace_api_key_ref_with_no_warn_only_fallback(string reference)
{
var json = "{\"Gateway\":{\"Endpoint\":\"http://127.0.0.1:1\",\"ApiKeySecretRef\":\"" + reference
+ "\"},\"MxAccess\":{\"ClientName\":\"X\"},\"Repository\":{},\"Reconnect\":{}}";
await Should.ThrowAsync<ZB.MOM.WW.OtOpcUa.Core.Abstractions.CredentialReferenceException>(
() => _sut.OpenAsync(json, TestContext.Current.CancellationToken));
}
/// <summary>A JSON literal that deserializes to null must fail fast with a
/// "deserialized to null" message — never a downstream NRE.</summary>
[Fact]
@@ -1,14 +1,15 @@
using Microsoft.Extensions.Logging;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
using ZB.MOM.WW.Secrets.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests;
/// <summary>
/// Follow-up #2 + G-2a — pins the five resolution forms supported by
/// <see cref="GalaxySecretRef.ResolveApiKeyAsync"/>: <c>env:NAME</c>, <c>file:PATH</c>,
/// Follow-up #2 + G-2a + lmxopcua#815 — pins the resolution forms supported by
/// <see cref="GalaxySecretRef.ResolveApiKeyAsync"/>: <c>env:OTOPCUA_GALAXY_NAME</c> (<c>file:</c> is refused),
/// <c>dev:KEY</c>, <c>secret:NAME</c> (via the shared <see cref="ISecretResolver"/>), and
/// the literal-string fallback. The <c>secret:</c> arm is fail-closed — an absent secret
/// throws rather than leaking the ref string as the key. (The resolver was extracted from
@@ -38,7 +39,7 @@ public sealed class GalaxyDriverApiKeyResolverTests
[Fact]
public async Task Env_prefix_resolves_to_environment_variable()
{
const string name = "OTOPCUA_TEST_GALAXY_API_KEY";
const string name = "OTOPCUA_GALAXY_TEST_API_KEY";
Environment.SetEnvironmentVariable(name, "key-from-env");
try
{
@@ -55,41 +56,13 @@ public sealed class GalaxyDriverApiKeyResolverTests
[Fact]
public async Task Env_prefix_unset_variable_throws_with_descriptive_message()
{
const string name = "OTOPCUA_TEST_GALAXY_API_KEY_UNSET";
const string name = "OTOPCUA_GALAXY_TEST_API_KEY_UNSET";
Environment.SetEnvironmentVariable(name, null);
var ex = await Should.ThrowAsync<InvalidOperationException>(() =>
GalaxySecretRef.ResolveApiKeyAsync($"env:{name}", FakeResolver()));
ex.Message.ShouldContain(name);
ex.Message.ShouldContain("unset");
}
/// <summary>Verifies that file: prefix resolves to trimmed file contents.</summary>
[Fact]
public async Task File_prefix_resolves_to_trimmed_file_contents()
{
var path = Path.Combine(Path.GetTempPath(), $"galaxy-key-{Guid.NewGuid():N}.txt");
File.WriteAllText(path, " key-from-file \n");
try
{
(await GalaxySecretRef.ResolveApiKeyAsync($"file:{path}", FakeResolver(), ct: TestContext.Current.CancellationToken))
.ShouldBe("key-from-file");
}
finally
{
File.Delete(path);
}
}
/// <summary>Verifies that file: prefix with missing path throws.</summary>
[Fact]
public async Task File_prefix_missing_path_throws()
{
var path = Path.Combine(Path.GetTempPath(), $"does-not-exist-{Guid.NewGuid():N}.txt");
var ex = await Should.ThrowAsync<InvalidOperationException>(() =>
GalaxySecretRef.ResolveApiKeyAsync($"file:{path}", FakeResolver()));
ex.Message.ShouldContain(path);
ex.Message.ShouldContain("doesn't exist");
ex.Message.ShouldContain("not set");
}
// ===== G-2a: secret: arm — resolves through the shared ISecretResolver, fail-closed =====
@@ -161,7 +134,7 @@ public sealed class GalaxyDriverApiKeyResolverTests
[Fact]
public async Task Env_prefix_does_not_emit_literal_warning()
{
const string name = "OTOPCUA_TEST_GALAXY_API_KEY_NOWARN";
const string name = "OTOPCUA_GALAXY_TEST_API_KEY_NOWARN";
Environment.SetEnvironmentVariable(name, "v");
try
{
@@ -211,21 +184,77 @@ public sealed class GalaxyDriverApiKeyResolverTests
: null);
}
/// <summary>Verifies that file: prefix with empty file throws.</summary>
[Fact]
public async Task File_prefix_empty_file_throws()
// ===== lmxopcua#815: references are confined to the Galaxy namespace, checked before any read =====
/// <summary>
/// An out-of-namespace reference — another subsystem's secret or process variable — throws, and neither the
/// store nor the environment is consulted (the value is never read, so it can never be sent).
/// </summary>
[Theory]
[InlineData("env:ConnectionStrings__ConfigDb")]
[InlineData("env:ServerHistorian__ApiKey")]
[InlineData("env:OTOPCUA_GALAXY_lower")]
[InlineData("secret:otopcua/historian/api-key")]
[InlineData("secret:OT-MESH-PSK-MAIN")]
[InlineData("secret:galaxy/../otopcua/historian/api-key")]
[InlineData("${secret:otopcua/apikeys/abc/galaxy-ack-password}")]
[InlineData("SECRET:galaxy/inst1/apikey")]
[InlineData("file:/tmp/any-file")]
[InlineData("file:appsettings.json")]
public async Task Out_of_namespace_reference_is_refused_without_reading_store_or_environment(string reference)
{
var path = Path.Combine(Path.GetTempPath(), $"galaxy-key-empty-{Guid.NewGuid():N}.txt");
File.WriteAllText(path, " \n ");
var store = new CountingResolver();
var envReads = 0;
var ex = await Should.ThrowAsync<CredentialReferenceException>(() => GalaxySecretRef.ResolveApiKeyAsync(
reference, store, ct: TestContext.Current.CancellationToken, environment: _ => { envReads++; return "LEAKED"; }));
ex.Message.ShouldContain("secret:galaxy/<name>");
ex.Message.ShouldContain("env:OTOPCUA_GALAXY_<NAME>");
ex.Message.ShouldNotContain("LEAKED");
store.Calls.ShouldBe(0);
envReads.ShouldBe(0);
}
/// <summary>The namespaced environment forms (incl. the legacy GALAXY_MXGW_ variable) resolve.</summary>
[Theory]
[InlineData("env:OTOPCUA_GALAXY_API_KEY", "OTOPCUA_GALAXY_API_KEY")]
[InlineData("env:GALAXY_MXGW_API_KEY", "GALAXY_MXGW_API_KEY")]
public async Task Namespaced_environment_reference_resolves(string reference, string variable)
{
var key = await GalaxySecretRef.ResolveApiKeyAsync(
reference, FakeResolver(), ct: TestContext.Current.CancellationToken,
environment: n => n == variable ? "the-key" : null);
key.ShouldBe("the-key");
}
/// <summary>A file reference is refused even when the file exists — its contents are never returned.</summary>
[Fact]
public async Task File_reference_is_refused_even_when_the_file_exists()
{
var path = Path.Combine(Path.GetTempPath(), $"galaxy-key-{Guid.NewGuid():N}.txt");
File.WriteAllText(path, "key-from-file");
try
{
var ex = await Should.ThrowAsync<InvalidOperationException>(() =>
var ex = await Should.ThrowAsync<CredentialReferenceException>(() =>
GalaxySecretRef.ResolveApiKeyAsync($"file:{path}", FakeResolver()));
ex.Message.ShouldContain("empty");
ex.Message.ShouldNotContain("key-from-file");
}
finally
{
File.Delete(path);
}
}
/// <summary>Counts store lookups.</summary>
private sealed class CountingResolver : ISecretResolver
{
/// <summary>Gets the number of lookups.</summary>
public int Calls { get; private set; }
/// <inheritdoc />
public Task<string?> GetAsync(SecretName name, CancellationToken ct)
{
Calls++;
return Task.FromResult<string?>("LEAKED");
}
}
}
@@ -0,0 +1,146 @@
using Microsoft.Extensions.Logging;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
using ZB.MOM.WW.Secrets.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests;
/// <summary>
/// lmxopcua#815 warn-only compatibility (deprecated): an ALREADY-DEPLOYED Galaxy driver whose config predates the
/// namespaces — e.g. the old AdminUI form default <c>env:MX_API_KEY</c> — keeps resolving it on init and on every
/// gateway reconnect (<c>ReopenAsync</c> → <c>BuildClientOptionsAsync</c>), warning rate-limited and surfacing it
/// on the diagnostics bag; while the admin-node paths (browser) stay hard-fail.
/// </summary>
public sealed class GalaxyDriverLegacyCredentialTests
{
private const string LegacyVariable = "MX_API_KEY_815_TEST";
private static GalaxyDriverOptions Opts(string apiKeyRef, string? ackRef = null) => new(
new GalaxyGatewayOptions("https://mxgw.test:5001", apiKeyRef),
new GalaxyMxAccessOptions("Compat815"),
new GalaxyRepositoryOptions(WatchDeployEvents: false),
new GalaxyReconnectOptions())
{
AlarmAck = ackRef is null ? new GalaxyAlarmAckOptions() : new GalaxyAlarmAckOptions("ack-svc", null, ackRef),
};
[Fact]
public async Task A_running_driver_with_a_legacy_env_ref_resolves_on_init_and_every_reconnect_and_warns_once()
{
Environment.SetEnvironmentVariable(LegacyVariable, "the-real-key");
try
{
var logger = new CaptureLogger();
var driver = new GalaxyDriver("gx-legacy", Opts($"env:{LegacyVariable}"), new NullResolver(), logger);
var ct = TestContext.Current.CancellationToken;
// InitializeAsync and each ReopenAsync (gateway reconnect) build the client options through this one method.
(await driver.BuildClientOptionsAsync(Opts($"env:{LegacyVariable}").Gateway, ct)).ApiKey.ShouldBe("the-real-key");
(await driver.BuildClientOptionsAsync(Opts($"env:{LegacyVariable}").Gateway, ct)).ApiKey.ShouldBe("the-real-key");
(await driver.BuildClientOptionsAsync(Opts($"env:{LegacyVariable}").Gateway, ct)).ApiKey.ShouldBe("the-real-key");
var warnings = logger.Entries.Where(e => e.Level == LogLevel.Warning && e.Message.Contains("lmxopcua#815")).ToList();
warnings.Count.ShouldBe(1); // rate-limited: one per field per hour, not one per reconnect
warnings[0].Message.ShouldContain("Gateway.ApiKeySecretRef");
warnings[0].Message.ShouldContain("env:OTOPCUA_GALAXY_<NAME>");
warnings[0].Message.ShouldNotContain("the-real-key");
var diagnostics = ((IDriverDiagnostics)driver).GetDiagnostics();
diagnostics.Keys.ShouldContain(LegacyCredentialReferenceTracker.DiagnosticsKeyPrefix + "Gateway.ApiKeySecretRef");
diagnostics.Values.ShouldAllBe(v => !v.Contains("the-real-key"));
DriverDiagnostics.Bound(diagnostics).Values.ShouldAllBe(v => v.Length <= DriverDiagnostics.MaxValueLength);
}
finally
{
Environment.SetEnvironmentVariable(LegacyVariable, null);
}
}
[Fact]
public async Task A_running_driver_keeps_the_old_case_insensitive_and_file_semantics()
{
var path = Path.Combine(Path.GetTempPath(), $"gx-815-{Guid.NewGuid():N}.txt");
File.WriteAllText(path, " key-from-file \n");
try
{
var driver = new GalaxyDriver("gx-legacy-file", Opts($"file:{path}"), new NullResolver());
(await driver.BuildClientOptionsAsync(Opts($"file:{path}").Gateway, TestContext.Current.CancellationToken))
.ApiKey.ShouldBe("key-from-file");
((IDriverDiagnostics)driver).GetDiagnostics().ShouldNotBeEmpty();
}
finally
{
File.Delete(path);
}
}
[Fact]
public async Task A_namespaced_ref_resolves_without_a_compatibility_warning()
{
var logger = new CaptureLogger();
var driver = new GalaxyDriver("gx-ok", Opts("dev:k"), new NullResolver(), logger);
(await driver.BuildClientOptionsAsync(Opts("dev:k").Gateway, TestContext.Current.CancellationToken)).ApiKey.ShouldBe("k");
logger.Entries.ShouldNotContain(e => e.Message.Contains("lmxopcua#815"));
((IDriverDiagnostics)driver).GetDiagnostics().ShouldBeEmpty();
}
/// <summary>The same legacy ref through the admin-node browser path (no tracker) is refused before any read.</summary>
[Fact]
public async Task The_same_ref_without_a_tracker_is_refused()
{
var reads = 0;
await Should.ThrowAsync<CredentialReferenceException>(() => GalaxySecretRef.ResolveApiKeyAsync(
"env:MX_API_KEY", new NullResolver(), ct: TestContext.Current.CancellationToken,
environment: _ => { reads++; return "the-real-key"; }));
reads.ShouldBe(0);
}
[Fact]
public async Task The_running_ack_fallback_keeps_a_legacy_ref_and_warns()
{
var warnings = new List<string>();
var tracker = new LegacyCredentialReferenceTracker(DriverCredentialPolicy.GalaxyScope, "gx", warnings.Add);
var resolver = new GalaxyAckCredentialResolver(
"gx", new GalaxyAlarmAckOptions("ack-svc", null, "env:LEGACY_ACK_PW"), new NullResolver(), new CaptureLogger(),
n => n == "LEGACY_ACK_PW" ? "pw" : null, tracker);
(await resolver.ResolveAsync(null, TestContext.Current.CancellationToken)).Credential.ShouldNotBeNull().Password.ShouldBe("pw");
warnings.ShouldHaveSingleItem().ShouldContain("AlarmAck.FallbackPasswordSecretRef");
}
[Fact]
public void The_tracker_re_warns_after_the_interval()
{
var now = new DateTime(2026, 11, 11, 0, 0, 0, DateTimeKind.Utc);
var warnings = new List<string>();
var tracker = new LegacyCredentialReferenceTracker(DriverCredentialPolicy.GalaxyScope, "gx", warnings.Add, () => now);
tracker.Report("F");
tracker.Report("F");
now += LegacyCredentialReferenceTracker.WarnInterval;
tracker.Report("F");
tracker.Report("G");
warnings.Count.ShouldBe(3);
}
private sealed class NullResolver : ISecretResolver
{
public Task<string?> GetAsync(SecretName name, CancellationToken ct) => Task.FromResult<string?>(null);
}
private sealed class CaptureLogger : ILogger<GalaxyDriver>
{
public List<(LogLevel Level, string Message)> Entries { get; } = new();
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
lock (Entries) Entries.Add((logLevel, formatter(state, exception)));
}
}
}
@@ -300,6 +300,48 @@ public sealed class GalaxyAckCredentialTests
.Password.ShouldBe(FallbackPassword);
}
/// <summary>
/// lmxopcua#815: the fallback password is sent to the operator-authored gateway endpoint, so a reference
/// outside the Galaxy namespace is refused — the store/environment value is never read, never sent.
/// </summary>
[Theory]
[InlineData("secret:otopcua/apikeys/0a1b/galaxy-ack-password")]
[InlineData("${secret:otopcua/historian/api-key}")]
[InlineData("env:ConnectionStrings__ConfigDb")]
[InlineData("file:appsettings.json")]
public async Task Resolver_refuses_a_fallback_reference_outside_the_galaxy_namespace(string reference)
{
const string Stolen = "stolen-value";
var secrets = new DictSecretResolver
{
["otopcua/apikeys/0a1b/galaxy-ack-password"] = Stolen,
["otopcua/historian/api-key"] = Stolen,
};
var envReads = 0;
var logger = new CapturingLogger();
var resolver = new GalaxyAckCredentialResolver(
"drv", new GalaxyAlarmAckOptions("ack-svc", null, reference), secrets, logger,
_ => { envReads++; return Stolen; });
var result = await resolver.ResolveAsync(null, CancellationToken.None);
result.Credential.ShouldBeNull();
result.RefusalReason.ShouldNotBeNull().ShouldNotContain(Stolen);
logger.AllText.ShouldNotContain(Stolen);
envReads.ShouldBe(0);
}
[Fact]
public async Task Resolver_resolves_a_namespaced_environment_fallback()
{
var resolver = new GalaxyAckCredentialResolver(
"drv", new GalaxyAlarmAckOptions("ack-svc", null, "env:OTOPCUA_GALAXY_ACK_PASSWORD"), new DictSecretResolver(),
new CapturingLogger(), n => n == "OTOPCUA_GALAXY_ACK_PASSWORD" ? FallbackPassword : null);
(await resolver.ResolveAsync(null, CancellationToken.None)).Credential.ShouldNotBeNull()
.Password.ShouldBe(FallbackPassword);
}
[Fact]
public async Task Resolver_secret_store_fault_is_a_refusal_not_a_throw()
{
@@ -56,11 +56,11 @@ public sealed class OpcUaClientBrowserCertificateAuthTests
{
AuthType = OpcUaAuthType.Certificate,
UserCertificatePath = path,
UserCertificatePassword = "secret:opcua/browse-cert",
UserCertificatePassword = "secret:opcuaclient/browse-cert",
};
var identity = await OpcUaClientDriverBrowser.BuildBrowseUserIdentityAsync(
opts, new OneSecret("opcua/browse-cert", "s3cret-pw"), TestContext.Current.CancellationToken);
opts, new OneSecret("opcuaclient/browse-cert", "s3cret-pw"), TestContext.Current.CancellationToken);
identity.TokenType.ShouldBe(UserTokenType.Certificate);
}
@@ -78,7 +78,7 @@ public sealed class OpcUaClientBrowserCertificateAuthTests
{
AuthType = OpcUaAuthType.Username,
Username = "op",
Password = "secret:opcua/pw",
Password = "secret:opcuaclient/pw",
};
var ex = await Should.ThrowAsync<InvalidOperationException>(() =>
@@ -1,5 +1,6 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient;
using ZB.MOM.WW.Secrets.Abstractions;
@@ -16,9 +17,9 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests;
/// </summary>
public sealed class OpcUaClientSecretResolutionTests
{
private const string KnownPwName = "opcua/inst/password";
private const string KnownPwName = "opcuaclient/inst/password";
private const string KnownPwValue = "resolved-password-plaintext";
private const string KnownCertPwName = "opcua/inst/cert-pw";
private const string KnownCertPwName = "opcuaclient/inst/cert-pw";
private const string KnownCertPwValue = "resolved-cert-pw-plaintext";
/// <summary>A fake resolver: returns known values for two known names, null otherwise.</summary>
@@ -70,14 +71,97 @@ public sealed class OpcUaClientSecretResolutionTests
[Fact]
public async Task Unknown_secret_ref_is_fail_closed()
{
var options = new OpcUaClientDriverOptions { Password = "secret:opcua/inst/absent" };
var options = new OpcUaClientDriverOptions { Password = "secret:opcuaclient/inst/absent" };
var ex = await Should.ThrowAsync<InvalidOperationException>(() =>
OpcUaClientSecretResolution.ResolveSecretRefsAsync(
options, FakeResolver(), CancellationToken.None));
ex.Message.ShouldContain("Password");
ex.Message.ShouldContain("opcua/inst/absent");
ex.Message.ShouldContain("opcuaclient/inst/absent");
}
/// <summary>
/// lmxopcua#815: the password is sent to the operator-authored endpoint, so a reference outside the
/// OpcUaClient namespace throws BEFORE the store or the environment is read — it is never resolved, never sent.
/// </summary>
[Theory]
[InlineData("secret:otopcua/historian/api-key")]
[InlineData("secret:galaxy/inst1/apikey")]
[InlineData("secret:OT-MESH-PSK-MAIN")]
[InlineData("env:ConnectionStrings__ConfigDb")]
[InlineData("env:ServerHistorian__ApiKey")]
[InlineData("Secret:opcuaclient/inst/password")]
[InlineData("file:appsettings.json")]
public async Task Out_of_namespace_reference_is_refused_without_reading(string reference)
{
var store = new CountingResolver();
var envReads = 0;
foreach (var options in new[]
{
new OpcUaClientDriverOptions { Password = reference },
new OpcUaClientDriverOptions { UserCertificatePassword = reference },
})
{
var ex = await Should.ThrowAsync<CredentialReferenceException>(() =>
OpcUaUserIdentityFactory.ResolveSecretRefsAsync(
options, store, CancellationToken.None, _ => { envReads++; return "LEAKED"; }));
ex.Message.ShouldContain("secret:opcuaclient/<name>");
ex.Message.ShouldNotContain("LEAKED");
}
store.Calls.ShouldBe(0);
envReads.ShouldBe(0);
}
/// <summary>A namespaced environment reference resolves.</summary>
[Fact]
public async Task Namespaced_environment_reference_resolves()
{
var resolved = await OpcUaUserIdentityFactory.ResolveSecretRefsAsync(
new OpcUaClientDriverOptions { Password = "env:OTOPCUA_OPCUACLIENT_PLANT_PW" }, FakeResolver(),
CancellationToken.None, n => n == "OTOPCUA_OPCUACLIENT_PLANT_PW" ? "pw" : null);
resolved.Password.ShouldBe("pw");
}
/// <summary>
/// lmxopcua#815 warn-only compatibility (deprecated): the RUNNING driver's session open keeps the old semantics
/// for an out-of-namespace value — a case-insensitive <c>secret:</c> resolves, anything else is a literal — and
/// warns once; the browser (no tracker) refuses the same value (see the theory above).
/// </summary>
[Fact]
public async Task The_running_driver_keeps_old_semantics_for_a_legacy_value_and_warns()
{
var warnings = new List<string>();
var tracker = new LegacyCredentialReferenceTracker(DriverCredentialPolicy.OpcUaClientScope, "ouc", warnings.Add);
var legacyOptions = new OpcUaClientDriverOptions
{
Password = $"SECRET:{KnownPwName}", // pre-#815: case-insensitive secret: resolved
UserCertificatePassword = "env:NOT_A_REF", // pre-#815: only secret: resolved — a literal password
};
for (var i = 0; i < 3; i++)
{
var resolved = await OpcUaClientSecretResolution.ResolveSecretRefsAsync(
legacyOptions, FakeResolver(), CancellationToken.None, tracker);
resolved.Password.ShouldBe(KnownPwValue);
resolved.UserCertificatePassword.ShouldBe("env:NOT_A_REF");
}
warnings.Count.ShouldBe(2); // one per field, rate-limited across the three session opens
warnings.ShouldAllBe(w => !w.Contains(KnownPwValue));
tracker.Diagnostics.Count.ShouldBe(2);
}
private sealed class CountingResolver : ISecretResolver
{
public int Calls { get; private set; }
public Task<string?> GetAsync(SecretName name, CancellationToken ct)
{
Calls++;
return Task.FromResult<string?>("LEAKED");
}
}
/// <summary>A fake resolver: returns known values for two known names, null otherwise.</summary>
@@ -0,0 +1,78 @@
using Microsoft.Extensions.Logging.Abstractions;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Browsing;
using ZB.MOM.WW.OtOpcUa.Commons.Browsing;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Browsing;
/// <summary>
/// lmxopcua#815: the AdminUI live browse (Galaxy / OpcUaClient bespoke browsers, and the Discover-backed universal
/// browser) resolves the config's credential references and sends them to the author-chosen endpoint — an
/// out-of-namespace reference is refused before any browser is opened.
/// </summary>
[Trait("Category", "Unit")]
public sealed class BrowserSessionCredentialScopeTests
{
[Theory]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"Endpoint":"http://evil:5001","ApiKeySecretRef":"env:ConnectionStrings__ConfigDb"}}""")]
[InlineData(DriverTypeNames.OpcUaClient, """{"EndpointUrl":"opc.tcp://evil:4840","Password":"secret:otopcua/historian/api-key"}""")]
[InlineData(DriverTypeNames.Heidenhain, """{"Access":{"InspectPassword":"secret:galaxy/main/apikey"}}""")]
public async Task Out_of_namespace_reference_never_opens_a_browser(string driverType, string config)
{
var bespoke = new RecordingBrowser(DriverTypeNames.Galaxy);
var bespoke2 = new RecordingBrowser(DriverTypeNames.OpcUaClient);
var universal = new RecordingUniversal();
var svc = new BrowserSessionService(
[bespoke, bespoke2], new BrowseSessionRegistry(), NullLogger<BrowserSessionService>.Instance, universal, null!, null!);
var result = await svc.OpenAsync(driverType, config, TestContext.Current.CancellationToken);
result.Ok.ShouldBeFalse();
result.Message.ShouldNotBeNull().ShouldContain("lmxopcua#815");
bespoke.Opens.ShouldBe(0);
bespoke2.Opens.ShouldBe(0);
universal.Opens.ShouldBe(0);
}
/// <summary>Positive control: a namespaced reference reaches the browser.</summary>
[Fact]
public async Task A_namespaced_reference_reaches_the_browser()
{
var bespoke = new RecordingBrowser(DriverTypeNames.Galaxy);
var svc = new BrowserSessionService(
[bespoke], new BrowseSessionRegistry(), NullLogger<BrowserSessionService>.Instance, new RecordingUniversal(), null!, null!);
await svc.OpenAsync(DriverTypeNames.Galaxy, """{"Gateway":{"ApiKeySecretRef":"secret:galaxy/main/apikey"}}""",
TestContext.Current.CancellationToken);
bespoke.Opens.ShouldBe(1);
}
private sealed class RecordingBrowser(string driverType) : IDriverBrowser
{
public int Opens { get; private set; }
public string DriverType => driverType;
public Task<IBrowseSession> OpenAsync(string configJson, CancellationToken cancellationToken)
{
Opens++;
throw new InvalidOperationException("opened");
}
}
private sealed class RecordingUniversal : IUniversalDriverBrowser
{
public int Opens { get; private set; }
public bool CanBrowse(string driverType, string configJson) => true;
public Task<IBrowseSession> OpenAsync(string driverType, string configJson, CancellationToken ct)
{
Opens++;
throw new InvalidOperationException("opened");
}
}
}
@@ -0,0 +1,177 @@
using System.Text;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Deployments;
using ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Drivers;
using ZB.MOM.WW.OtOpcUa.Configuration;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Deployments;
/// <summary>
/// lmxopcua#815 upgrade preflight: stored (draft) and deployed configs with out-of-namespace credential references
/// are listed and logged — driver, device, field, allowed form — and never the value; nothing is resolved.
/// </summary>
[Trait("Category", "Unit")]
public sealed class CredentialReferencePreflightTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
private const string LegacyGalaxy = """{"Gateway":{"Endpoint":"http://gw:5001","ApiKeySecretRef":"env:MX_API_KEY"}}""";
private static string SeedLegacy()
{
var name = RawTreeTestDb.SeedFresh();
using var db = RawTreeTestDb.CreateNamed(name);
// Written straight to the DB, as a pre-#815 build would have — the save gate now refuses it.
db.DriverInstances.Add(new DriverInstance
{
DriverInstanceId = "gx-old", ClusterId = RawTreeTestDb.ClusterId, Name = "Galaxy main",
DriverType = DriverTypeNames.Galaxy, DriverConfig = LegacyGalaxy,
});
db.Devices.Add(new Device
{
DeviceId = "ouc-dev", DriverInstanceId = "gx-old", Name = "gw1",
DeviceConfig = """{"AlarmAck":{"FallbackPasswordSecretRef":"file:C:\\keys\\ack.txt"}}""",
});
db.DriverInstances.Add(new DriverInstance
{
DriverInstanceId = "mb", ClusterId = RawTreeTestDb.ClusterId, Name = "modbus",
DriverType = DriverTypeNames.Modbus, DriverConfig = """{"Password":"env:ConnectionStrings__ConfigDb"}""",
});
var artifact = """
{"DriverInstances":[{"DriverInstanceId":"ouc","Name":"Upstream","DriverType":"OpcUaClient",
"DriverConfig":"{\"Password\":\"secret:plant/opcua-pw\"}"}]}
""";
db.Deployments.Add(new Deployment { RevisionHash = "abc", CreatedBy = "t", ArtifactBlob = Encoding.UTF8.GetBytes(artifact) });
db.SaveChanges();
return name;
}
[Fact]
public async Task Scan_lists_draft_rows_devices_and_the_deployed_artifact_without_values()
{
var findings = await new CredentialReferencePreflight(RawTreeTestDb.Factory(SeedLegacy())).ScanAsync(Ct);
findings.ShouldContain(f => f.Source == CredentialFindingSource.Draft && f.DriverName == "Galaxy main"
&& f.DeviceName == null && f.Problem.Contains("Gateway.ApiKeySecretRef")
&& f.Problem.Contains("env:OTOPCUA_GALAXY_<NAME>"));
findings.ShouldContain(f => f.Source == CredentialFindingSource.Draft && f.DeviceName == "gw1"
&& f.Problem.Contains("AlarmAck.FallbackPasswordSecretRef"));
findings.ShouldContain(f => f.Source == CredentialFindingSource.Deployed && f.DriverName == "Upstream"
&& f.Problem.Contains("secret:opcuaclient/<name>"));
findings.ShouldNotContain(f => f.DriverInstanceId == "mb"); // not a credential-resolving driver
findings.ShouldAllBe(f => !f.Problem.Contains("MX_API_KEY") && !f.Problem.Contains("plant/opcua-pw")
&& !f.Problem.Contains("ack.txt"));
}
[Fact]
public async Task A_clean_database_has_no_findings()
=> (await new CredentialReferencePreflight(RawTreeTestDb.Factory(RawTreeTestDb.SeedFresh())).ScanAsync(Ct)).ShouldBeEmpty();
[Fact]
public async Task The_boot_pass_logs_one_warning_per_finding_and_publishes_the_state()
{
var services = new ServiceCollection()
.AddSingleton(RawTreeTestDb.Factory(SeedLegacy()))
.BuildServiceProvider();
var state = new CredentialReferencePreflightState();
var logger = new CaptureLogger();
var svc = new CredentialReferencePreflightService(services, new FakeLifetime(), state, logger) { StartDelay = TimeSpan.Zero };
var findings = await svc.RunOnceAsync(Ct);
findings.Count.ShouldBe(3);
state.Current.Findings.Count.ShouldBe(3);
state.Current.ScannedAtUtc.ShouldNotBeNull();
var warnings = logger.Entries.Where(e => e.Level == LogLevel.Warning).ToList();
warnings.Count.ShouldBe(3);
warnings.ShouldAllBe(w => w.Message.Contains("lmxopcua#815") && !w.Message.Contains("MX_API_KEY"));
warnings.ShouldContain(w => w.Message.Contains("Galaxy main") && w.Message.Contains("Gateway.ApiKeySecretRef"));
}
[Fact]
public async Task A_node_without_a_config_db_skips_quietly()
{
var svc = new CredentialReferencePreflightService(
new ServiceCollection().BuildServiceProvider(), new FakeLifetime(), new CredentialReferencePreflightState(), new CaptureLogger());
(await svc.RunOnceAsync(Ct)).ShouldBeEmpty();
}
[Fact]
public async Task The_hosted_service_waits_for_ApplicationStarted_before_scanning()
{
var services = new ServiceCollection().AddSingleton(RawTreeTestDb.Factory(SeedLegacy())).BuildServiceProvider();
var lifetime = new FakeLifetime();
var state = new CredentialReferencePreflightState();
var svc = new CredentialReferencePreflightService(services, lifetime, state, new CaptureLogger()) { StartDelay = TimeSpan.Zero };
await svc.StartAsync(Ct);
await Task.Delay(100, Ct);
state.Current.ScannedAtUtc.ShouldBeNull(); // nothing before the host has started
lifetime.Start();
var deadline = DateTime.UtcNow.AddSeconds(10);
while (state.Current.ScannedAtUtc is null && DateTime.UtcNow < deadline) await Task.Delay(20, Ct);
state.Current.Findings.Count.ShouldBe(3);
await svc.StopAsync(Ct);
}
[Fact]
public void Running_drivers_reporting_warn_only_resolution_are_surfaced_from_driver_health()
{
var snapshots = new[]
{
new DriverHealthChanged("c", "gx-old", "Healthy", null, null, 0, DateTime.UtcNow,
Diagnostics: new Dictionary<string, string>
{
[LegacyCredentialReferenceTracker.DiagnosticsKeyPrefix + "Gateway.ApiKeySecretRef"] = "deprecated …",
["s7.pdu"] = "480",
}),
new DriverHealthChanged("c", "mb", "Healthy", null, null, 0, DateTime.UtcNow),
};
var running = CredentialReferencePreflight.RunningFindings(snapshots);
running.ShouldHaveSingleItem().ShouldSatisfyAllConditions(
f => f.Source.ShouldBe(CredentialFindingSource.Running),
f => f.DriverInstanceId.ShouldBe("gx-old"),
f => f.Problem.ShouldStartWith("Gateway.ApiKeySecretRef"));
}
private sealed class FakeLifetime : IHostApplicationLifetime
{
private readonly CancellationTokenSource _started = new();
public CancellationToken ApplicationStarted => _started.Token;
public CancellationToken ApplicationStopping => CancellationToken.None;
public CancellationToken ApplicationStopped => CancellationToken.None;
public void Start() => _started.Cancel();
public void StopApplication()
{
}
}
private sealed class CaptureLogger : ILogger<CredentialReferencePreflightService>
{
public List<(LogLevel Level, string Message)> Entries { get; } = new();
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
lock (Entries) Entries.Add((logLevel, formatter(state, exception)));
}
}
}
@@ -0,0 +1,77 @@
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
/// <summary>
/// lmxopcua#815 at the SAVE path (RawTreeService): a Galaxy / OpcUaClient credential reference outside the
/// driver's namespace never reaches the config DB, through driver and device create + update.
/// </summary>
[Trait("Category", "Unit")]
public sealed class CredentialReferenceSavePathTests
{
private static CancellationToken Ct => TestContext.Current.CancellationToken;
[Theory]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"Endpoint":"http://evil:5001","ApiKeySecretRef":"env:ConnectionStrings__ConfigDb"}}""")]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"ApiKeySecretRef":"file:appsettings.json"}}""")]
[InlineData(DriverTypeNames.Galaxy, """{"AlarmAck":{"FallbackPasswordSecretRef":"secret:otopcua/apikeys/ab/galaxy-ack-password"}}""")]
[InlineData(DriverTypeNames.OpcUaClient, """{"EndpointUrl":"opc.tcp://evil:4840","Password":"secret:otopcua/historian/api-key"}""")]
[InlineData(DriverTypeNames.OpcUaClient, """{"UserCertificatePassword":"env:ServerHistorian__ApiKey"}""")]
public async Task CreateDriver_refuses_an_out_of_namespace_reference_and_persists_nothing(string type, string config)
{
var name = RawTreeTestDb.SeedFresh();
var svc = new RawTreeService(RawTreeTestDb.Factory(name));
var result = await svc.CreateDriverAsync(RawTreeTestDb.ClusterId, null, "d815", type, config, Ct);
result.Ok.ShouldBeFalse();
result.Error!.ShouldContain("lmxopcua#815");
using var db = RawTreeTestDb.CreateNamed(name);
db.DriverInstances.ShouldNotContain(d => d.Name == "d815");
}
[Fact]
public async Task Update_paths_refuse_and_keep_the_stored_config()
{
var name = RawTreeTestDb.SeedFresh();
var svc = new RawTreeService(RawTreeTestDb.Factory(name));
var created = await svc.CreateDriverAsync(RawTreeTestDb.ClusterId, null, "gx", DriverTypeNames.Galaxy,
"""{"Gateway":{"Endpoint":"http://gw:5001","ApiKeySecretRef":"secret:galaxy/gx/apikey"}}""", Ct);
created.Ok.ShouldBeTrue(created.Error);
byte[] rv;
string deviceId;
byte[] deviceRv;
using (var db = RawTreeTestDb.CreateNamed(name))
{
rv = db.DriverInstances.Single(d => d.DriverInstanceId == created.CreatedId).RowVersion;
var device = db.Devices.Single(d => d.DriverInstanceId == created.CreatedId);
deviceId = device.DeviceId;
deviceRv = device.RowVersion;
}
(await svc.UpdateDriverAsync(created.CreatedId!, "gx",
"""{"Gateway":{"ApiKeySecretRef":"env:ConnectionStrings__ConfigDb"}}""", null, rv, Ct)).Ok.ShouldBeFalse();
(await svc.UpdateDeviceAsync(deviceId, "dev",
"""{"Gateway":{"ApiKeySecretRef":"env:ConnectionStrings__ConfigDb"}}""", true, deviceRv, Ct)).Ok.ShouldBeFalse();
(await svc.CreateDeviceAsync(created.CreatedId!, "dev2",
"""{"Gateway":{"ApiKeySecretRef":"secret:otopcua/historian/api-key"}}""", Ct)).Ok.ShouldBeFalse();
using var check = RawTreeTestDb.CreateNamed(name);
check.DriverInstances.Single(d => d.DriverInstanceId == created.CreatedId).DriverConfig.ShouldContain("secret:galaxy/gx/apikey");
check.Devices.Where(d => d.DriverInstanceId == created.CreatedId)
.ShouldAllBe(d => !d.DeviceConfig.Contains("ConnectionStrings") && !d.DeviceConfig.Contains("historian"));
}
[Theory]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"ApiKeySecretRef":"env:GALAXY_MXGW_API_KEY"},"AlarmAck":{"FallbackPasswordSecretRef":"secret:otopcua/galaxy/ack-fallback"}}""")]
[InlineData(DriverTypeNames.OpcUaClient, """{"Password":"literal-password","UserCertificatePassword":"secret:opcuaclient/plant/cert"}""")]
public async Task Namespaced_references_save(string type, string config)
{
var name = RawTreeTestDb.SeedFresh();
var svc = new RawTreeService(RawTreeTestDb.Factory(name));
var result = await svc.CreateDriverAsync(RawTreeTestDb.ClusterId, null, "ok815", type, config, Ct);
result.Ok.ShouldBeTrue(result.Error);
}
}
@@ -0,0 +1,67 @@
using Akka.Actor;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Commons.Messages.Admin;
using ZB.MOM.WW.OtOpcUa.ControlPlane.AdminOperations;
using ZB.MOM.WW.OtOpcUa.ControlPlane.Tests.Harness;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
namespace ZB.MOM.WW.OtOpcUa.ControlPlane.Tests;
/// <summary>
/// lmxopcua#815: Test Connect with a credential reference outside the driver's namespace is refused BEFORE any
/// probe runs — the probe is the seam that would resolve the reference (store / environment) and send the value
/// to the author-chosen endpoint, so "the probe was never invoked" is "nothing was read".
/// </summary>
public sealed class AdminOperationsActorCredentialScopeTests : ControlPlaneActorTestBase
{
[Theory]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"Endpoint":"http://attacker:5001","ApiKeySecretRef":"env:ConnectionStrings__ConfigDb"}}""")]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"Endpoint":"http://attacker:5001","ApiKeySecretRef":"env:MX_API_KEY"}}""")]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"Endpoint":"http://attacker:5001","ApiKeySecretRef":"env:ServerHistorian__ApiKey"}}""")]
[InlineData(DriverTypeNames.Galaxy, """{"Gateway":{"Endpoint":"http://attacker:5001","ApiKeySecretRef":"file:appsettings.json"}}""")]
[InlineData(DriverTypeNames.OpcUaClient, """{"EndpointUrl":"opc.tcp://attacker:4840","Password":"secret:otopcua/historian/api-key"}""")]
[InlineData(DriverTypeNames.Heidenhain, """{"Access":{"InspectPassword":"secret:galaxy/main/apikey"},"Devices":[{"Host":"attacker"}]}""")]
public void Out_of_namespace_reference_never_reaches_the_probe(string driverType, string config)
{
var probe = new RecordingProbe(driverType);
var actor = Sys.ActorOf(AdminOperationsActor.Props(NewInMemoryDbFactory(), CreateTestProbe("coord").Ref, new IDriverProbe[] { probe }));
actor.Tell(new TestDriverConnect(driverType, config, 5, Guid.NewGuid()));
var reply = ExpectMsg<TestDriverConnectResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken);
reply.Ok.ShouldBeFalse();
reply.Message.ShouldNotBeNull().ShouldContain("Test Connect refused");
reply.Message.ShouldContain("lmxopcua#815");
probe.Calls.ShouldBe(0);
}
/// <summary>Positive control: a namespaced reference does reach the probe (the refusal is not blanket).</summary>
[Fact]
public void A_namespaced_reference_reaches_the_probe()
{
var probe = new RecordingProbe(DriverTypeNames.Galaxy);
var actor = Sys.ActorOf(AdminOperationsActor.Props(NewInMemoryDbFactory(), CreateTestProbe("coord").Ref, new IDriverProbe[] { probe }));
actor.Tell(new TestDriverConnect(
DriverTypeNames.Galaxy, """{"Gateway":{"Endpoint":"http://gw:5001","ApiKeySecretRef":"secret:galaxy/main/apikey"}}""", 5, Guid.NewGuid()));
ExpectMsg<TestDriverConnectResult>(PresenceBudget, cancellationToken: TestContext.Current.CancellationToken).Ok.ShouldBeTrue();
probe.Calls.ShouldBe(1);
}
private sealed class RecordingProbe(string driverType) : IDriverProbe
{
private int _calls;
public int Calls => Volatile.Read(ref _calls);
public string DriverType => driverType;
public Task<DriverProbeResult> ProbeAsync(string configJson, TimeSpan timeout, CancellationToken ct)
{
Interlocked.Increment(ref _calls);
return Task.FromResult(new DriverProbeResult(true, null, TimeSpan.Zero));
}
}
}