feat(secrets): G-2a secret: arm on GalaxySecretRef via ISecretResolver (Task 7)
Add a secret:NAME arm to GalaxySecretRef.ResolveApiKey that resolves the Galaxy gateway API key through the shared ISecretResolver — fail-closed if the secret is absent (never falls through to the cleartext literal arm), retiring the dev:/literal in-DB path for production. Because GetAsync is async the method becomes ResolveApiKeyAsync; the await cascade threads ISecretResolver by ctor injection into GalaxyDriver + GalaxyDriverBrowser and (since GalaxyDriver is built by a static factory closure, not DI) through GalaxyDriverFactoryExtensions + DriverFactoryBootstrap (which pulls the real resolver from the service provider — registered unconditionally in Slice 1). A NullSecretResolver null-object backs the parse-only/test paths only; the runtime path always gets the real resolver (verified end-to-end). TDD: 3 new secret:-arm tests (resolve / fail-closed-on-absent / no-literal-warning) RED without the arm, GREEN with it; 338 Galaxy tests pass; no sync-over-async.
This commit is contained in:
+12
-1
@@ -1,5 +1,6 @@
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.Secrets.Abstractions;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browser.Tests;
|
||||
|
||||
@@ -14,7 +15,17 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browser.Tests;
|
||||
[Trait("Category", "Unit")]
|
||||
public sealed class GalaxyDriverBrowserTests
|
||||
{
|
||||
private readonly GalaxyDriverBrowser _sut = new();
|
||||
// These unit tests exercise only the pre-connect validation paths (empty endpoint,
|
||||
// blank client name) that throw BEFORE the API-key secret: arm is resolved, so a
|
||||
// null-returning stub resolver suffices — it is never consulted.
|
||||
private readonly GalaxyDriverBrowser _sut = new(new StubSecretResolver());
|
||||
|
||||
/// <summary>A no-op resolver: every name resolves to null. Never consulted by these tests.</summary>
|
||||
private sealed class StubSecretResolver : ISecretResolver
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public Task<string?> GetAsync(SecretName name, CancellationToken ct) => Task.FromResult<string?>(null);
|
||||
}
|
||||
|
||||
/// <summary>The DriverType key must match the AdminUI's persisted "GalaxyMxGateway" value
|
||||
/// so the factory wire-up picks the right browser implementation.</summary>
|
||||
|
||||
+94
-27
@@ -2,35 +2,48 @@ using Microsoft.Extensions.Logging;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
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 — pins the three resolution forms supported by
|
||||
/// <see cref="GalaxySecretRef.ResolveApiKey"/>: <c>env:NAME</c>, <c>file:PATH</c>,
|
||||
/// and the literal-string fallback. A future DPAPI arm slots in here without
|
||||
/// touching the call site. (The resolver was extracted from <c>GalaxyDriver</c> to
|
||||
/// the shared <c>GalaxySecretRef</c> in Driver.Galaxy.Contracts so the runtime
|
||||
/// driver and the AdminUI browser share one copy.)
|
||||
/// Follow-up #2 + G-2a — pins the five resolution forms supported by
|
||||
/// <see cref="GalaxySecretRef.ResolveApiKeyAsync"/>: <c>env:NAME</c>, <c>file:PATH</c>,
|
||||
/// <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
|
||||
/// <c>GalaxyDriver</c> to the shared <c>GalaxySecretRef</c> in Driver.Galaxy.Contracts so the
|
||||
/// runtime driver and the AdminUI browser share one copy.)
|
||||
/// </summary>
|
||||
public sealed class GalaxyDriverApiKeyResolverTests
|
||||
{
|
||||
/// <summary>Name the fake resolver knows; matches the SecretName-normalized form.</summary>
|
||||
private const string KnownSecretName = "galaxy/inst1/apikey";
|
||||
|
||||
/// <summary>The value the fake resolver returns for <see cref="KnownSecretName"/>.</summary>
|
||||
private const string KnownSecretValue = "key-from-secret-store";
|
||||
|
||||
/// <summary>A fake resolver: returns a known value for one known name, null otherwise.</summary>
|
||||
private static ISecretResolver FakeResolver() => new StubSecretResolver();
|
||||
|
||||
/// <summary>Verifies that a literal string is returned unchanged.</summary>
|
||||
[Fact]
|
||||
public void Literal_string_is_returned_unchanged()
|
||||
public async Task Literal_string_is_returned_unchanged()
|
||||
{
|
||||
GalaxySecretRef.ResolveApiKey("plain-text-key").ShouldBe("plain-text-key");
|
||||
(await GalaxySecretRef.ResolveApiKeyAsync("plain-text-key", FakeResolver()))
|
||||
.ShouldBe("plain-text-key");
|
||||
}
|
||||
|
||||
/// <summary>Verifies that env: prefix resolves to an environment variable.</summary>
|
||||
[Fact]
|
||||
public void Env_prefix_resolves_to_environment_variable()
|
||||
public async Task Env_prefix_resolves_to_environment_variable()
|
||||
{
|
||||
const string name = "OTOPCUA_TEST_GALAXY_API_KEY";
|
||||
Environment.SetEnvironmentVariable(name, "key-from-env");
|
||||
try
|
||||
{
|
||||
GalaxySecretRef.ResolveApiKey($"env:{name}").ShouldBe("key-from-env");
|
||||
(await GalaxySecretRef.ResolveApiKeyAsync($"env:{name}", FakeResolver()))
|
||||
.ShouldBe("key-from-env");
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -40,26 +53,27 @@ public sealed class GalaxyDriverApiKeyResolverTests
|
||||
|
||||
/// <summary>Verifies that unset environment variables throw with a descriptive message.</summary>
|
||||
[Fact]
|
||||
public void Env_prefix_unset_variable_throws_with_descriptive_message()
|
||||
public async Task Env_prefix_unset_variable_throws_with_descriptive_message()
|
||||
{
|
||||
const string name = "OTOPCUA_TEST_GALAXY_API_KEY_UNSET";
|
||||
Environment.SetEnvironmentVariable(name, null);
|
||||
|
||||
var ex = Should.Throw<InvalidOperationException>(() =>
|
||||
GalaxySecretRef.ResolveApiKey($"env:{name}"));
|
||||
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 void File_prefix_resolves_to_trimmed_file_contents()
|
||||
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
|
||||
{
|
||||
GalaxySecretRef.ResolveApiKey($"file:{path}").ShouldBe("key-from-file");
|
||||
(await GalaxySecretRef.ResolveApiKeyAsync($"file:{path}", FakeResolver()))
|
||||
.ShouldBe("key-from-file");
|
||||
}
|
||||
finally
|
||||
{
|
||||
@@ -69,26 +83,60 @@ public sealed class GalaxyDriverApiKeyResolverTests
|
||||
|
||||
/// <summary>Verifies that file: prefix with missing path throws.</summary>
|
||||
[Fact]
|
||||
public void File_prefix_missing_path_throws()
|
||||
public async Task File_prefix_missing_path_throws()
|
||||
{
|
||||
var path = Path.Combine(Path.GetTempPath(), $"does-not-exist-{Guid.NewGuid():N}.txt");
|
||||
var ex = Should.Throw<InvalidOperationException>(() =>
|
||||
GalaxySecretRef.ResolveApiKey($"file:{path}"));
|
||||
var ex = await Should.ThrowAsync<InvalidOperationException>(() =>
|
||||
GalaxySecretRef.ResolveApiKeyAsync($"file:{path}", FakeResolver()));
|
||||
ex.Message.ShouldContain(path);
|
||||
ex.Message.ShouldContain("doesn't exist");
|
||||
}
|
||||
|
||||
// ===== G-2a: secret: arm — resolves through the shared ISecretResolver, fail-closed =====
|
||||
|
||||
/// <summary>Verifies that secret: prefix resolves through the ISecretResolver.</summary>
|
||||
[Fact]
|
||||
public async Task Secret_prefix_resolves_through_secret_resolver()
|
||||
{
|
||||
(await GalaxySecretRef.ResolveApiKeyAsync($"secret:{KnownSecretName}", FakeResolver()))
|
||||
.ShouldBe(KnownSecretValue);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that an absent secret throws (fail-closed) and does NOT leak the ref string.</summary>
|
||||
[Fact]
|
||||
public async Task Secret_prefix_absent_secret_throws_fail_closed()
|
||||
{
|
||||
const string missingRef = "secret:galaxy/missing/apikey";
|
||||
|
||||
var ex = await Should.ThrowAsync<InvalidOperationException>(() =>
|
||||
GalaxySecretRef.ResolveApiKeyAsync(missingRef, FakeResolver()));
|
||||
|
||||
// Fail-closed: must throw, must reference the secret + "absent"/"fail-closed", and
|
||||
// must NOT return the ref string as the key.
|
||||
ex.Message.ShouldContain("galaxy/missing/apikey");
|
||||
ex.Message.ShouldContain("absent");
|
||||
}
|
||||
|
||||
/// <summary>Verifies that the secret: arm does not consult the logger's literal warning.</summary>
|
||||
[Fact]
|
||||
public async Task Secret_prefix_does_not_emit_literal_warning()
|
||||
{
|
||||
var logger = new CaptureLogger();
|
||||
await GalaxySecretRef.ResolveApiKeyAsync($"secret:{KnownSecretName}", FakeResolver(), logger);
|
||||
logger.Entries.ShouldNotContain(e => e.Level == LogLevel.Warning);
|
||||
}
|
||||
|
||||
// ===== Driver.Galaxy-010 regression: literal arm warns + dev: prefix path =====
|
||||
|
||||
/// <summary>Verifies that literal strings emit a warning when a logger is supplied.</summary>
|
||||
[Fact]
|
||||
public void Literal_string_emits_warning_when_logger_supplied()
|
||||
public async Task Literal_string_emits_warning_when_logger_supplied()
|
||||
{
|
||||
// A literal API key on a production deployment means the cleartext key sits
|
||||
// in the DriverConfig JSON. The resolver must surface a warning so an
|
||||
// operator who committed one by accident sees it at startup.
|
||||
var logger = new CaptureLogger();
|
||||
var key = GalaxySecretRef.ResolveApiKey("plain-text-key", logger);
|
||||
var key = await GalaxySecretRef.ResolveApiKeyAsync("plain-text-key", FakeResolver(), logger);
|
||||
|
||||
key.ShouldBe("plain-text-key");
|
||||
logger.Entries.ShouldContain(e =>
|
||||
@@ -97,13 +145,13 @@ public sealed class GalaxyDriverApiKeyResolverTests
|
||||
|
||||
/// <summary>Verifies that dev: prefix returns literal text without emitting warnings.</summary>
|
||||
[Fact]
|
||||
public void Dev_prefix_returns_literal_without_warning()
|
||||
public async Task Dev_prefix_returns_literal_without_warning()
|
||||
{
|
||||
// An explicit dev: prefix signals the operator knowingly opted into a literal
|
||||
// key (dev / parity rig). The resolver must accept it AND suppress the
|
||||
// warning so production logs aren't polluted on a deliberate dev choice.
|
||||
var logger = new CaptureLogger();
|
||||
var key = GalaxySecretRef.ResolveApiKey("dev:plain-text-key", logger);
|
||||
var key = await GalaxySecretRef.ResolveApiKeyAsync("dev:plain-text-key", FakeResolver(), logger);
|
||||
|
||||
key.ShouldBe("plain-text-key");
|
||||
logger.Entries.ShouldNotContain(e => e.Level == LogLevel.Warning);
|
||||
@@ -111,14 +159,14 @@ public sealed class GalaxyDriverApiKeyResolverTests
|
||||
|
||||
/// <summary>Verifies that env: prefix does not emit literal string warnings.</summary>
|
||||
[Fact]
|
||||
public void Env_prefix_does_not_emit_literal_warning()
|
||||
public async Task Env_prefix_does_not_emit_literal_warning()
|
||||
{
|
||||
const string name = "OTOPCUA_TEST_GALAXY_API_KEY_NOWARN";
|
||||
Environment.SetEnvironmentVariable(name, "v");
|
||||
try
|
||||
{
|
||||
var logger = new CaptureLogger();
|
||||
GalaxySecretRef.ResolveApiKey($"env:{name}", logger);
|
||||
await GalaxySecretRef.ResolveApiKeyAsync($"env:{name}", FakeResolver(), logger);
|
||||
logger.Entries.ShouldNotContain(e => e.Level == LogLevel.Warning);
|
||||
}
|
||||
finally
|
||||
@@ -127,6 +175,14 @@ public sealed class GalaxyDriverApiKeyResolverTests
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Verifies that a null resolver is rejected (ArgumentNullException).</summary>
|
||||
[Fact]
|
||||
public async Task Null_resolver_throws()
|
||||
{
|
||||
await Should.ThrowAsync<ArgumentNullException>(() =>
|
||||
GalaxySecretRef.ResolveApiKeyAsync("plain-text-key", resolver: null!));
|
||||
}
|
||||
|
||||
/// <summary>A test logger that captures log entries for verification.</summary>
|
||||
private sealed class CaptureLogger : ILogger
|
||||
{
|
||||
@@ -144,16 +200,27 @@ public sealed class GalaxyDriverApiKeyResolverTests
|
||||
=> Entries.Add((logLevel, formatter(state, exception)));
|
||||
}
|
||||
|
||||
/// <summary>A fake ISecretResolver returning one known value; null for every other name.</summary>
|
||||
private sealed class StubSecretResolver : ISecretResolver
|
||||
{
|
||||
/// <inheritdoc />
|
||||
public Task<string?> GetAsync(SecretName name, CancellationToken ct) =>
|
||||
Task.FromResult<string?>(
|
||||
string.Equals(name.Value, KnownSecretName, StringComparison.Ordinal)
|
||||
? KnownSecretValue
|
||||
: null);
|
||||
}
|
||||
|
||||
/// <summary>Verifies that file: prefix with empty file throws.</summary>
|
||||
[Fact]
|
||||
public void File_prefix_empty_file_throws()
|
||||
public async Task File_prefix_empty_file_throws()
|
||||
{
|
||||
var path = Path.Combine(Path.GetTempPath(), $"galaxy-key-empty-{Guid.NewGuid():N}.txt");
|
||||
File.WriteAllText(path, " \n ");
|
||||
try
|
||||
{
|
||||
var ex = Should.Throw<InvalidOperationException>(() =>
|
||||
GalaxySecretRef.ResolveApiKey($"file:{path}"));
|
||||
var ex = await Should.ThrowAsync<InvalidOperationException>(() =>
|
||||
GalaxySecretRef.ResolveApiKeyAsync($"file:{path}", FakeResolver()));
|
||||
ex.Message.ShouldContain("empty");
|
||||
}
|
||||
finally
|
||||
|
||||
@@ -143,7 +143,7 @@ public sealed class GalaxyDriverFactoryTests
|
||||
public void Register_AddsFactoryToRegistry()
|
||||
{
|
||||
var registry = new DriverFactoryRegistry();
|
||||
GalaxyDriverFactoryExtensions.Register(registry);
|
||||
GalaxyDriverFactoryExtensions.Register(registry, NullSecretResolver.Instance);
|
||||
|
||||
registry.RegisteredTypes.ShouldContain(GalaxyDriverFactoryExtensions.DriverTypeName);
|
||||
|
||||
|
||||
+1
-1
@@ -78,7 +78,7 @@ public sealed class GalaxyDriverReadTests
|
||||
// _dataReader and _subscriber are both null. The follow-up read path can't
|
||||
// synthesise a Read without one, so it surfaces a NotSupportedException
|
||||
// pointing at the misuse rather than NullRef'ing inside the pump path.
|
||||
var driver = new GalaxyDriver("g", Opts());
|
||||
var driver = new GalaxyDriver("g", Opts(), hierarchySource: null);
|
||||
|
||||
var ex = await Should.ThrowAsync<NotSupportedException>(() =>
|
||||
driver.ReadAsync(["x"], CancellationToken.None));
|
||||
|
||||
+1
-1
@@ -242,7 +242,7 @@ public sealed class GalaxyDriverSubscribeTests
|
||||
[Fact]
|
||||
public async Task SubscribeAsync_NoSubscriber_Throws()
|
||||
{
|
||||
using var driver = new GalaxyDriver("g", Opts());
|
||||
using var driver = new GalaxyDriver("g", Opts(), hierarchySource: null);
|
||||
var ex = await Should.ThrowAsync<NotSupportedException>(() =>
|
||||
driver.SubscribeAsync(["x"], TimeSpan.FromSeconds(1), CancellationToken.None));
|
||||
ex.Message.ShouldContain("GalaxyDriver.SubscribeAsync requires");
|
||||
|
||||
+1
-1
@@ -192,7 +192,7 @@ public sealed class GalaxyDriverWriteTests
|
||||
[Fact]
|
||||
public async Task WriteAsync_NoWriter_Throws()
|
||||
{
|
||||
var driver = new GalaxyDriver("g", Opts());
|
||||
var driver = new GalaxyDriver("g", Opts(), hierarchySource: null);
|
||||
|
||||
var ex = await Should.ThrowAsync<NotSupportedException>(() =>
|
||||
driver.WriteAsync([new WriteRequest("x", 1)], CancellationToken.None));
|
||||
|
||||
Reference in New Issue
Block a user