fix(security): scope operator-authored credential references per driver (#815)
A Designer could point a Galaxy / OpcUaClient endpoint at a host they control, set a credential field to any reference the node can resolve (env:ConnectionStrings__ConfigDb, env:ServerHistorian__ApiKey, secret:<any>, Galaxy file:<any path>) and click Test Connect / live browse; the node resolved the value and sent it to that host. One shared rule in Core.Abstractions (CredentialReferences + DriverCredentialPolicy) generalises the #803 Heidenhain namespace: - Galaxy: secret:galaxy/... | secret:otopcua/galaxy/... | env:OTOPCUA_GALAXY_... | legacy env:GALAXY_MXGW_...; file: refused; dev:/literal API key unchanged. - OpcUaClient: secret:opcuaclient/... | env:OTOPCUA_OPCUACLIENT_...; literals unchanged. - Heidenhain adopts the shared parser/resolver (namespace unchanged). Enforced at the AdminUI save path (DriverConfigSaveGate), the deploy gate (CredentialReferenceDeployChecks, code CredentialReferenceOutOfScope), Test Connect (AdminOperationsActor, before any probe), live browse (BrowserSessionService, before any browser) and again at resolve time in every driver/browser (fail closed, before any store/env read). Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
+70
-41
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+42
@@ -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()
|
||||
{
|
||||
|
||||
+3
-3
@@ -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>(() =>
|
||||
|
||||
+59
-4
@@ -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,68 @@ 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");
|
||||
}
|
||||
|
||||
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>
|
||||
|
||||
Reference in New Issue
Block a user