f0c6cf9640
v2-ci / unit-tests (push) Has been cancelled
The #815 warn-only compatibility window is over. A running Galaxy driver (InitializeAsync, every gateway ReopenAsync, the ack fallback password) and a running OpcUaClient driver (session open) now refuse an out-of-namespace credential reference with the same CredentialReferenceException that save, deploy (CredentialReferenceOutOfScope), Test Connect and browse already raise, before any store / environment / file read and before any endpoint is dialled. The one existing scope check (CredentialReferences.Parse/ResolveAsync) is now the only path; nothing new was added. Removed: - LegacyCredentialReferenceTracker (Core.Abstractions), its rate-limited WARN and the credential-compat:<field> diagnostics entry. - The per-driver Legacy* resolve methods and every `legacy` parameter (GalaxySecretRef, GalaxyAckCredentialResolver, OpcUaUserIdentityFactory, OpcUaUserCertificatePaths, OpcUaClientSecretResolution). - IDriverDiagnostics on GalaxyDriver / OpcUaClientDriver (it only carried the tracker's entries). - The tracker also kept a pre-#836 absolute UserCertificatePath loading on a running OpcUaClient driver; that is refused now too. Preflight / banner decision: KEPT, as a hard error. The Running source (driver-health credential-compat entries) and CredentialReferenceBannerModel are gone with the tracker, but the ConfigDb scan still tells an operator something no other surface does: a Deployed finding is now a driver that is not connecting, a Draft finding is a deploy the gate will refuse - named before anyone deploys, e.g. after restoring an old ConfigDb backup or importing a pre-#815 config. It also carries the #835 cross-instance and #836/#850 path checks. CredentialReferencePreflightService now logs one Error per finding (was Warning) with no warn-only wording, and the /raw banner is alert-danger. DEV and QA ConfigDbs hold no Galaxy/OpcUaClient driver (checked 2026-11-13); no production install exists. Tests: GalaxyDriverLegacyCredentialTests replaced by GalaxyDriverCredentialScopeTests; new OpcUaClientDriverCredentialScopeTests; tracker tests in OpcUaClientSecretResolutionTests / OpcUaClientUserCertificatePathTests deleted; AdminUI preflight tests drop the Running/banner-model cases and assert Error level. Against the old code the new refusal tests fail (Galaxy 5/6, OpcUaClient 4/5; the two positive controls pass on both). docs/security.md: the migration table now says running drivers refuse; the warn-only section is replaced by "The compatibility window is over". Claude-Session: https://claude.ai/code/session_01GT67ACmpMR7b9LGRPLijMi
191 lines
7.7 KiB
C#
191 lines
7.7 KiB
C#
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#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
|
|
/// <c>env:MX_API_KEY</c>, any <c>file:</c> reference, a <c>secret:</c> outside <c>galaxy/</c> — now refuses it at
|
|
/// resolve time (<see cref="CredentialReferenceException"/>, before any store / environment / file read), on
|
|
/// <c>InitializeAsync</c>, on every gateway reconnect, and on the ack fallback password — exactly as save, deploy,
|
|
/// Test Connect and browse already did.
|
|
/// </summary>
|
|
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),
|
|
};
|
|
|
|
/// <summary>
|
|
/// The old Galaxy form default (<c>env:MX_API_KEY</c>-style, an unprefixed variable) is refused on init and on
|
|
/// every reconnect — both build the client options through <see cref="GalaxyDriver.BuildClientOptionsAsync"/> —
|
|
/// even with the variable set, and the value never reaches the message.
|
|
/// </summary>
|
|
[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<CredentialReferenceException>(
|
|
() => 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);
|
|
}
|
|
}
|
|
|
|
/// <summary>A <c>file:</c> reference is refused before the file is opened, even when it exists.</summary>
|
|
[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<CredentialReferenceException>(
|
|
() => driver.BuildClientOptionsAsync(options.Gateway, TestContext.Current.CancellationToken));
|
|
ex.Message.ShouldNotContain("key-from-file");
|
|
}
|
|
finally
|
|
{
|
|
File.Delete(path);
|
|
}
|
|
}
|
|
|
|
/// <summary>A <c>secret:</c> outside <c>galaxy/</c> (and a case-variant prefix) is refused without a store read.</summary>
|
|
[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<CredentialReferenceException>(
|
|
() => driver.BuildClientOptionsAsync(options.Gateway, TestContext.Current.CancellationToken));
|
|
store.Calls.ShouldBe(0);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
[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<DriverOperationRefusedException>(() => 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);
|
|
}
|
|
}
|
|
|
|
/// <summary>Positive control: a namespaced reference still resolves through the same running-driver path.</summary>
|
|
[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<string?> GetAsync(SecretName name, CancellationToken ct)
|
|
{
|
|
Calls++;
|
|
return Task.FromResult<string?>("LEAKED");
|
|
}
|
|
}
|
|
|
|
private sealed class RecordingAcknowledger : IGalaxyAlarmAcknowledger
|
|
{
|
|
public int Calls { get; private set; }
|
|
|
|
public Task<GalaxyAckOutcome> AcknowledgeAsync(
|
|
string alarmFullReference, string comment, GalaxyAckCredential credential, CancellationToken cancellationToken)
|
|
{
|
|
Calls++;
|
|
return Task.FromResult(GalaxyAckOutcome.Applied);
|
|
}
|
|
}
|
|
|
|
private sealed class CaptureLogger : ILogger<GalaxyDriver>
|
|
{
|
|
private readonly List<string> _entries = [];
|
|
|
|
public string AllText
|
|
{
|
|
get
|
|
{
|
|
lock (_entries) return string.Join("\n", _entries);
|
|
}
|
|
}
|
|
|
|
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(formatter(state, exception));
|
|
}
|
|
}
|
|
}
|