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;
///
/// lmxopcua#834 (follow-up to #815): the warn-only compatibility window is over. A RUNNING Galaxy driver whose
/// stored config carries an out-of-namespace credential reference — the old AdminUI form default
/// env:MX_API_KEY, any file: reference, a secret: outside galaxy/ — now refuses it at
/// resolve time (, before any store / environment / file read), on
/// InitializeAsync, on every gateway reconnect, and on the ack fallback password — exactly as save, deploy,
/// Test Connect and browse already did.
///
public sealed class GalaxyDriverCredentialScopeTests
{
private const string LegacyVariable = "MX_API_KEY_834_TEST";
private static GalaxyDriverOptions Opts(string apiKeyRef, string? ackRef = null) => new(
new GalaxyGatewayOptions("https://mxgw.test:5001", apiKeyRef),
new GalaxyMxAccessOptions("Scope834"),
new GalaxyRepositoryOptions(WatchDeployEvents: false),
new GalaxyReconnectOptions())
{
AlarmAck = ackRef is null ? new GalaxyAlarmAckOptions() : new GalaxyAlarmAckOptions("ack-svc", null, ackRef),
};
///
/// The old Galaxy form default (env:MX_API_KEY-style, an unprefixed variable) is refused on init and on
/// every reconnect — both build the client options through —
/// even with the variable set, and the value never reaches the message.
///
[Fact]
public async Task A_running_driver_refuses_an_out_of_namespace_env_ref_on_init_and_every_reconnect()
{
Environment.SetEnvironmentVariable(LegacyVariable, "the-real-key");
try
{
var logger = new CaptureLogger();
var options = Opts($"env:{LegacyVariable}");
using var driver = new GalaxyDriver("gx-legacy", options, new CountingResolver(), logger);
var ct = TestContext.Current.CancellationToken;
for (var i = 0; i < 2; i++)
{
var ex = await Should.ThrowAsync(
() => driver.BuildClientOptionsAsync(options.Gateway, ct));
ex.Message.ShouldContain("Gateway.ApiKeySecretRef");
ex.Message.ShouldNotContain("the-real-key");
}
logger.AllText.ShouldNotContain("the-real-key");
}
finally
{
Environment.SetEnvironmentVariable(LegacyVariable, null);
}
}
/// A file: reference is refused before the file is opened, even when it exists.
[Fact]
public async Task A_running_driver_refuses_a_file_ref_even_when_the_file_exists()
{
var path = Path.Combine(Path.GetTempPath(), $"gx-834-{Guid.NewGuid():N}.txt");
File.WriteAllText(path, "key-from-file");
try
{
var options = Opts($"file:{path}");
using var driver = new GalaxyDriver("gx-legacy-file", options, new CountingResolver());
var ex = await Should.ThrowAsync(
() => driver.BuildClientOptionsAsync(options.Gateway, TestContext.Current.CancellationToken));
ex.Message.ShouldNotContain("key-from-file");
}
finally
{
File.Delete(path);
}
}
/// A secret: outside galaxy/ (and a case-variant prefix) is refused without a store read.
[Theory]
[InlineData("secret:otopcua/configdb-password")]
[InlineData("SECRET:galaxy/api-key")]
public async Task A_running_driver_refuses_an_out_of_namespace_secret_ref_without_reading_the_store(string reference)
{
var store = new CountingResolver();
var options = Opts(reference);
using var driver = new GalaxyDriver("gx-legacy-secret", options, store);
await Should.ThrowAsync(
() => driver.BuildClientOptionsAsync(options.Gateway, TestContext.Current.CancellationToken));
store.Calls.ShouldBe(0);
}
///
/// The running driver's ack fallback password: an out-of-namespace reference refuses the acknowledge — nothing
/// reaches the gateway — instead of resolving it with the old semantics.
///
[Fact]
public async Task A_running_driver_refuses_an_ack_with_an_out_of_namespace_fallback_password_ref()
{
Environment.SetEnvironmentVariable("LEGACY_ACK_PW_834", "pw");
try
{
var ack = new RecordingAcknowledger();
var logger = new CaptureLogger();
using var driver = new GalaxyDriver(
"gx-ack", Opts("dev:k", "env:LEGACY_ACK_PW_834"), hierarchySource: null, alarmAcknowledger: ack,
logger: logger, secretResolver: new CountingResolver());
await Should.ThrowAsync(() => driver.AcknowledgeAsync(
[new AlarmAcknowledgeRequest("src", "Tank01.Level.HiHi", null, OperatorUser: "anonymous")],
TestContext.Current.CancellationToken));
ack.Calls.ShouldBe(0);
logger.AllText.ShouldNotContain("lmxopcua#815 warn-only");
}
finally
{
Environment.SetEnvironmentVariable("LEGACY_ACK_PW_834", null);
}
}
/// Positive control: a namespaced reference still resolves through the same running-driver path.
[Fact]
public async Task A_namespaced_ref_still_resolves()
{
Environment.SetEnvironmentVariable("OTOPCUA_GALAXY_KEY_834", "namespaced-key");
try
{
var options = Opts("env:OTOPCUA_GALAXY_KEY_834");
using var driver = new GalaxyDriver("gx-ok", options, new CountingResolver());
(await driver.BuildClientOptionsAsync(options.Gateway, TestContext.Current.CancellationToken))
.ApiKey.ShouldBe("namespaced-key");
}
finally
{
Environment.SetEnvironmentVariable("OTOPCUA_GALAXY_KEY_834", null);
}
}
private sealed class CountingResolver : ISecretResolver
{
public int Calls { get; private set; }
public Task GetAsync(SecretName name, CancellationToken ct)
{
Calls++;
return Task.FromResult("LEAKED");
}
}
private sealed class RecordingAcknowledger : IGalaxyAlarmAcknowledger
{
public int Calls { get; private set; }
public Task AcknowledgeAsync(
string alarmFullReference, string comment, GalaxyAckCredential credential, CancellationToken cancellationToken)
{
Calls++;
return Task.FromResult(GalaxyAckOutcome.Applied);
}
}
private sealed class CaptureLogger : ILogger
{
private readonly List _entries = [];
public string AllText
{
get
{
lock (_entries) return string.Join("\n", _entries);
}
}
public IDisposable? BeginScope(TState state) where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => true;
public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter)
{
lock (_entries) _entries.Add(formatter(state, exception));
}
}
}