fix(security): running drivers refuse out-of-namespace credential refs at resolve time (#834)
v2-ci / unit-tests (push) Has been cancelled
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
This commit is contained in:
+190
@@ -0,0 +1,190 @@
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
-146
@@ -1,146 +0,0 @@
|
||||
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)));
|
||||
}
|
||||
}
|
||||
}
|
||||
+113
@@ -0,0 +1,113 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
||||
using ZB.MOM.WW.Secrets.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.OpcUaClient.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#834 (follow-up to #815 / #836): the warn-only compatibility window is over. A RUNNING OpcUaClient
|
||||
/// driver whose stored config carries an out-of-namespace credential reference, or a user-certificate path outside
|
||||
/// the node's certificate directory, now refuses it at resolve time in the session open
|
||||
/// (<see cref="CredentialReferenceException"/>, before any store / environment read and before any endpoint is
|
||||
/// dialled) — exactly as save, deploy, Test Connect and browse already did.
|
||||
/// </summary>
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class OpcUaClientDriverCredentialScopeTests
|
||||
{
|
||||
private const string PlainPassword = "resolved-plaintext";
|
||||
|
||||
private static OpcUaClientDriverOptions Username(string password) => new()
|
||||
{
|
||||
EndpointUrl = "opc.tcp://127.0.0.1:1",
|
||||
AuthType = OpcUaAuthType.Username,
|
||||
Username = "plant-user",
|
||||
Password = password,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Out-of-namespace values that the pre-#834 running driver resolved with the old semantics: a <c>secret:</c>
|
||||
/// outside <c>opcuaclient/</c>, a case-variant <c>SECRET:</c> prefix, and an <c>env:</c> outside
|
||||
/// <c>OTOPCUA_OPCUACLIENT_</c> (which it sent verbatim as a literal password).
|
||||
/// </summary>
|
||||
[Theory]
|
||||
[InlineData("secret:otopcua/configdb-password")]
|
||||
[InlineData("SECRET:opcuaclient/inst/password")]
|
||||
[InlineData("env:NOT_A_REF")]
|
||||
public async Task A_running_driver_refuses_an_out_of_namespace_password_ref_before_reading_or_dialling(string reference)
|
||||
{
|
||||
var store = new CountingResolver();
|
||||
using var driver = new OpcUaClientDriver(Username(reference), "ouc-834", secretResolver: store);
|
||||
var opened = 0;
|
||||
driver.OpenSessionForTest = (_, _) =>
|
||||
{
|
||||
opened++;
|
||||
throw new InvalidOperationException("no server in this test");
|
||||
};
|
||||
|
||||
var ex = await Should.ThrowAsync<CredentialReferenceException>(
|
||||
() => driver.InitializeAsync("{}", TestContext.Current.CancellationToken));
|
||||
|
||||
ex.Message.ShouldContain("Password");
|
||||
ex.Message.ShouldNotContain(PlainPassword);
|
||||
store.Calls.ShouldBe(0);
|
||||
opened.ShouldBe(0, "the credential is refused before any endpoint is dialled");
|
||||
driver.GetHealth().State.ShouldBe(DriverState.Faulted);
|
||||
}
|
||||
|
||||
/// <summary>lmxopcua#836: a fully-qualified (pre-#836) user-certificate path is refused, not loaded.</summary>
|
||||
[Fact]
|
||||
public async Task A_running_driver_refuses_an_absolute_user_certificate_path()
|
||||
{
|
||||
var abs = Path.Combine(Path.GetTempPath(), $"ouc-834-{Guid.NewGuid():N}.pfx");
|
||||
var options = new OpcUaClientDriverOptions
|
||||
{
|
||||
EndpointUrl = "opc.tcp://127.0.0.1:1",
|
||||
AuthType = OpcUaAuthType.Certificate,
|
||||
UserCertificatePath = abs,
|
||||
UserCertificatePassword = "pw",
|
||||
};
|
||||
using var driver = new OpcUaClientDriver(options, "ouc-834-cert", secretResolver: new CountingResolver());
|
||||
var opened = 0;
|
||||
driver.OpenSessionForTest = (_, _) =>
|
||||
{
|
||||
opened++;
|
||||
throw new InvalidOperationException("no server in this test");
|
||||
};
|
||||
|
||||
await Should.ThrowAsync<CredentialReferenceException>(
|
||||
() => driver.InitializeAsync("{}", TestContext.Current.CancellationToken));
|
||||
opened.ShouldBe(0);
|
||||
}
|
||||
|
||||
/// <summary>Positive control: a namespaced reference resolves and the session open is reached.</summary>
|
||||
[Fact]
|
||||
public async Task A_namespaced_password_ref_resolves_and_the_session_open_is_reached()
|
||||
{
|
||||
var store = new CountingResolver();
|
||||
using var driver = new OpcUaClientDriver(
|
||||
Username("secret:opcuaclient/inst/password"), "ouc-834-ok", secretResolver: store);
|
||||
var opened = 0;
|
||||
driver.OpenSessionForTest = (_, _) =>
|
||||
{
|
||||
opened++;
|
||||
throw new InvalidOperationException("no server in this test");
|
||||
};
|
||||
|
||||
await Should.ThrowAsync<AggregateException>(
|
||||
() => driver.InitializeAsync("{}", TestContext.Current.CancellationToken));
|
||||
store.Calls.ShouldBe(1);
|
||||
opened.ShouldBe(1);
|
||||
}
|
||||
|
||||
private sealed class CountingResolver : ISecretResolver
|
||||
{
|
||||
public int Calls { get; private set; }
|
||||
|
||||
public Task<string?> GetAsync(SecretName name, CancellationToken ct)
|
||||
{
|
||||
Calls++;
|
||||
return Task.FromResult<string?>(PlainPassword);
|
||||
}
|
||||
}
|
||||
}
|
||||
-29
@@ -124,35 +124,6 @@ public sealed class OpcUaClientSecretResolutionTests
|
||||
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; }
|
||||
|
||||
-26
@@ -88,32 +88,6 @@ public sealed class OpcUaClientUserCertificatePathTests : IDisposable
|
||||
Cert("user.pfx"), null, TestContext.Current.CancellationToken, userCertificateDirectory: _dir));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_running_driver_keeps_loading_a_legacy_absolute_path_and_warns()
|
||||
{
|
||||
var abs = Path.Combine(_outside, "legacy.pfx");
|
||||
WritePfx(abs);
|
||||
var warnings = new List<string>();
|
||||
var tracker = new LegacyCredentialReferenceTracker(DriverCredentialPolicy.OpcUaClientScope, "ouc", warnings.Add);
|
||||
|
||||
var resolved = await OpcUaUserIdentityFactory.ResolveSecretRefsAsync(
|
||||
Cert(abs), null, TestContext.Current.CancellationToken, legacy: tracker, userCertificateDirectory: _dir);
|
||||
|
||||
resolved.UserCertificatePath.ShouldBe(abs);
|
||||
OpcUaUserIdentityFactory.Build(resolved).TokenType.ShouldBe(Opc.Ua.UserTokenType.Certificate);
|
||||
warnings.ShouldHaveSingleItem().ShouldContain("lmxopcua#836");
|
||||
warnings[0].ShouldNotContain(abs);
|
||||
tracker.Diagnostics.ShouldContainKey(LegacyCredentialReferenceTracker.DiagnosticsKeyPrefix + "UserCertificatePath");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task The_legacy_tracker_does_not_relax_a_relative_path_that_escapes()
|
||||
{
|
||||
var tracker = new LegacyCredentialReferenceTracker(DriverCredentialPolicy.OpcUaClientScope, "ouc", _ => { });
|
||||
await Should.ThrowAsync<CredentialReferenceException>(() => OpcUaUserIdentityFactory.ResolveSecretRefsAsync(
|
||||
Cert("../x.pfx"), null, TestContext.Current.CancellationToken, legacy: tracker, userCertificateDirectory: _dir));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task A_non_certificate_auth_type_leaves_the_path_alone()
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user