feat(galaxy): operator-authenticated alarm ack — send Galaxy credential to mxaccessgw (#749)
v2-ci / unit-tests (push) Failing after 1h8m43s
v2-ci / unit-tests (push) Failing after 1h8m43s
mxaccessgw 488649c+ acknowledges by AuthenticateUser as the operator and
writing <alarm>.AckMsg, so AcknowledgeAlarmRequest now needs a real Galaxy
operator_user + operator_domain + operator_password. The OPC UA data plane is
API-key/anonymous and carries no Galaxy password, so the driver resolves the
account per ack:
1. the session's API key's Galaxy ack identity, set on AdminUI /apikeys and
held ONLY in the encrypted Secrets store
(otopcua/apikeys/<keyId>/galaxy-ack-{user,password}); a key with a user but
no password secret is refused, never silently downgraded;
2. else the driver instance's AlarmAck fallback account (DriverConfig
FallbackUser/FallbackDomain/FallbackPasswordSecretRef; secret:/${secret:}/
env:/file:/dev: only — a literal is refused);
3. else DriverOperationRefusedException: nothing is sent, never an empty
operator_user. Refusals are excluded from the resilience retry/breaker.
- Pins ZB.MOM.WW.MxGateway.Client/Contracts 0.2.1 -> 0.3.0 (vendored into
nuget-packages/ from the Gitea feed, per the local-mxgw source mapping).
- The session ApiKeyId (not a secret) rides NativeAlarmAck ->
RouteNativeAlarmAck -> RouteAlarmAck -> AlarmAcknowledgeRequest; the password
is resolved in the driver and never travels through actor messages.
- The OPC UA principal + key id are appended to the AckMsg comment
("[OPC UA: <principal>, key <id>]") and logged, so a shared fallback
account does not lose who acknowledged.
- Password never logged: GalaxyAckCredential.ToString omits it, the
acknowledger scrubs it from every gateway message it echoes and withholds
any exception that echoes it; audit rows carry only the key id.
- AdminUI: /apikeys "Ack identity" editor (set/remove; delete-key clears it),
Galaxy driver form gains the fallback section.
- Synchronous OPC UA status for a refusal is follow-up #760 (the native ack
path is fire-and-forget after the Part 9 method returns).
Tests: request mapping (password populated), password absent from logs and
exception text (mutation-checked), key-mapped / fallback / refused paths at
resolver and driver level, breaker non-trip, key-id propagation through node
manager and DriverHostActor, AdminUI service + form round-trip.
Closes #749
This commit is contained in:
+15
-12
@@ -191,8 +191,9 @@ public sealed class GalaxyDriverAlarmSourceTests
|
||||
|
||||
ack.Calls.Count.ShouldBe(2);
|
||||
ack.Calls[0].AlarmRef.ShouldBe("Tank01.Level.HiHi");
|
||||
ack.Calls[0].Comment.ShouldBe("shift handover");
|
||||
ack.Calls[0].Operator.ShouldBe(string.Empty); // null OperatorUser must fall back to empty string
|
||||
ack.Calls[0].Comment.ShouldBe("shift handover [OPC UA: anonymous]");
|
||||
// lmxopcua#749: the gateway is sent the resolved Galaxy account, never an empty operator.
|
||||
ack.Calls[0].Operator.ShouldBe("ack-op");
|
||||
ack.Calls[1].AlarmRef.ShouldBe("Tank02.Level.HiHi");
|
||||
}
|
||||
|
||||
@@ -212,23 +213,24 @@ public sealed class GalaxyDriverAlarmSourceTests
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that AcknowledgeAsync forwards the request's authenticated principal
|
||||
/// (<see cref="AlarmAcknowledgeRequest.OperatorUser"/>) to the acknowledger so the
|
||||
/// gateway records WHO acked, rather than the generic empty-string fallback.
|
||||
/// Verifies that the request's OPC UA principal + key id (<see cref="AlarmAcknowledgeRequest.OperatorUser"/>,
|
||||
/// <see cref="AlarmAcknowledgeRequest.ApiKeyId"/>) are recorded in the ack comment, and the key id is what
|
||||
/// the credential resolver is asked about — the gateway operator is the resolved Galaxy account (#749).
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task AcknowledgeAsync_forwards_OperatorUser()
|
||||
public async Task AcknowledgeAsync_records_OpcUa_principal_in_comment()
|
||||
{
|
||||
var feed = new FakeAlarmFeed();
|
||||
var ack = new RecordingAcknowledger();
|
||||
using var driver = NewDriver(feed, ack);
|
||||
|
||||
await driver.AcknowledgeAsync(
|
||||
[new AlarmAcknowledgeRequest("src", "Obj.Alarm", "cmt", "alice")],
|
||||
[new AlarmAcknowledgeRequest("src", "Obj.Alarm", "cmt", "alice", ApiKeyId: "0a1b2c")],
|
||||
CancellationToken.None);
|
||||
|
||||
ack.Calls.ShouldHaveSingleItem();
|
||||
ack.Calls[0].Operator.ShouldBe("alice");
|
||||
ack.Calls[0].Operator.ShouldBe("ack-op");
|
||||
ack.Calls[0].Comment.ShouldBe("cmt [OPC UA: alice, key 0a1b2c]");
|
||||
}
|
||||
|
||||
/// <summary>Verifies that AcknowledgeAsync throws NotSupportedException without an acknowledger.</summary>
|
||||
@@ -257,7 +259,8 @@ public sealed class GalaxyDriverAlarmSourceTests
|
||||
options: options,
|
||||
hierarchySource: null,
|
||||
alarmAcknowledger: alarmAcknowledger,
|
||||
alarmFeed: alarmFeed);
|
||||
alarmFeed: alarmFeed,
|
||||
ackCredentialResolver: ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime.FixedAckCredentialResolver.Fallback());
|
||||
}
|
||||
|
||||
private static GalaxyAlarmTransition NewTransition(
|
||||
@@ -311,12 +314,12 @@ public sealed class GalaxyDriverAlarmSourceTests
|
||||
/// <summary>Records an acknowledge call.</summary>
|
||||
/// <param name="alarmFullReference">The alarm full reference.</param>
|
||||
/// <param name="comment">The acknowledgment comment.</param>
|
||||
/// <param name="operatorUser">The operator user.</param>
|
||||
/// <param name="credential">The resolved Galaxy credential.</param>
|
||||
/// <param name="cancellationToken">Cancellation token.</param>
|
||||
/// <returns>A completed task.</returns>
|
||||
public Task AcknowledgeAsync(string alarmFullReference, string comment, string operatorUser, CancellationToken cancellationToken)
|
||||
public Task AcknowledgeAsync(string alarmFullReference, string comment, GalaxyAckCredential credential, CancellationToken cancellationToken)
|
||||
{
|
||||
Calls.Add((alarmFullReference, comment, operatorUser));
|
||||
Calls.Add((alarmFullReference, comment, credential.User));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,6 +41,27 @@ public sealed class GalaxyDriverFactoryTests
|
||||
driver.Options.Reconnect.ReplayOnSessionLost.ShouldBeTrue();
|
||||
}
|
||||
|
||||
/// <summary>lmxopcua#749: the AlarmAck fallback section binds; absent means no fallback.</summary>
|
||||
[Fact]
|
||||
public void CreateInstance_BindsAlarmAckFallback()
|
||||
{
|
||||
GalaxyDriverFactoryExtensions.CreateInstance("g", MinimalConfig).Options.AlarmAck.HasFallback.ShouldBeFalse();
|
||||
|
||||
const string json = """
|
||||
{
|
||||
"Gateway": { "Endpoint": "https://mxgw.test:5001", "ApiKeySecretRef": "galaxy:apiKey" },
|
||||
"MxAccess": { "ClientName": "OtOpcUa-A" },
|
||||
"alarmAck": { "fallbackUser": "ack-svc", "fallbackDomain": "PLANT", "fallbackPasswordSecretRef": "secret:otopcua/galaxy/ack" }
|
||||
}
|
||||
""";
|
||||
var ack = GalaxyDriverFactoryExtensions.CreateInstance("g", json).Options.AlarmAck;
|
||||
|
||||
ack.HasFallback.ShouldBeTrue();
|
||||
ack.FallbackUser.ShouldBe("ack-svc");
|
||||
ack.FallbackDomain.ShouldBe("PLANT");
|
||||
ack.FallbackPasswordSecretRef.ShouldBe("secret:otopcua/galaxy/ack");
|
||||
}
|
||||
|
||||
/// <summary>Verifies that defaults are overridden from full config.</summary>
|
||||
[Fact]
|
||||
public void CreateInstance_OverridesDefaults_FromFullConfig()
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
|
||||
|
||||
/// <summary>Logger that records every formatted message (and exception text) for leak assertions.</summary>
|
||||
internal sealed class CapturingLogger : ILogger
|
||||
{
|
||||
/// <summary>Gets the formatted entries, each including the exception's ToString when present.</summary>
|
||||
public List<(LogLevel Level, string Text)> Entries { get; } = [];
|
||||
|
||||
/// <summary>Gets every entry's text joined, for a single contains-check.</summary>
|
||||
public string AllText => string.Join("\n", Entries.Select(e => e.Text));
|
||||
|
||||
/// <inheritdoc />
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => null;
|
||||
|
||||
/// <inheritdoc />
|
||||
public bool IsEnabled(LogLevel logLevel) => true;
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Log<TState>(
|
||||
LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
|
||||
{
|
||||
// Include the structured state values too — a password passed as a template argument would
|
||||
// reach a structured sink even if the template text omitted it.
|
||||
var values = state is IEnumerable<KeyValuePair<string, object?>> kvs
|
||||
? string.Join(";", kvs.Select(kv => $"{kv.Key}={kv.Value}"))
|
||||
: string.Empty;
|
||||
Entries.Add((logLevel, $"{formatter(state, exception)} | {values} | {exception}"));
|
||||
}
|
||||
}
|
||||
+417
@@ -0,0 +1,417 @@
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.MxGateway.Client;
|
||||
using ZB.MOM.WW.MxGateway.Contracts.Proto;
|
||||
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.Runtime;
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#749 — operator-authenticated Galaxy ack (mxaccessgw 488649c+): the request carries a real
|
||||
/// Galaxy account + password resolved from the API key's identity or the driver's fallback account,
|
||||
/// refuses with neither, and never lets the password reach a log line or exception text.
|
||||
/// </summary>
|
||||
public sealed class GalaxyAckCredentialTests
|
||||
{
|
||||
private const string KeyId = "0a1b2c3d4e5f6071";
|
||||
private const string KeyPassword = "key-pw-S3cr3t!";
|
||||
private const string FallbackPassword = "fallback-pw-S3cr3t!";
|
||||
|
||||
// ------------------------------------------------------------------ request mapping
|
||||
|
||||
[Fact]
|
||||
public void BuildRequest_carries_user_domain_and_password()
|
||||
{
|
||||
var credential = new GalaxyAckCredential("alice", "CORP", KeyPassword, GalaxyAckCredentialSource.ApiKey);
|
||||
|
||||
var request = GatewayGalaxyAlarmAcknowledger.BuildRequest("Tank01.Level.HiHi", "investigating", credential);
|
||||
|
||||
request.AlarmFullReference.ShouldBe("Tank01.Level.HiHi");
|
||||
request.Comment.ShouldBe("investigating");
|
||||
request.OperatorUser.ShouldBe("alice");
|
||||
request.OperatorDomain.ShouldBe("CORP");
|
||||
request.OperatorPassword.ShouldBe(KeyPassword);
|
||||
request.ClientCorrelationId.ShouldNotBeNullOrEmpty();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void BuildRequest_allows_empty_password_but_never_empty_user()
|
||||
{
|
||||
// Galaxy accounts can have empty passwords (gateway contract) — the field is sent empty.
|
||||
var request = GatewayGalaxyAlarmAcknowledger.BuildRequest(
|
||||
"A.B", "c", new GalaxyAckCredential("bob", null, null, GalaxyAckCredentialSource.Fallback));
|
||||
request.OperatorPassword.ShouldBe(string.Empty);
|
||||
request.OperatorDomain.ShouldBe(string.Empty);
|
||||
request.OperatorUser.ShouldBe("bob");
|
||||
|
||||
// The credential type itself cannot be built with an empty user — the gateway rejects one.
|
||||
Should.Throw<ArgumentException>(() => new GalaxyAckCredential(" ", "D", "p", GalaxyAckCredentialSource.Fallback));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Credential_and_resolution_ToString_omit_the_password()
|
||||
{
|
||||
var credential = new GalaxyAckCredential("alice", "CORP", KeyPassword, GalaxyAckCredentialSource.ApiKey);
|
||||
credential.ToString().ShouldNotContain(KeyPassword);
|
||||
credential.ToString().ShouldContain("CORP\\alice");
|
||||
GalaxyAckCredentialResolution.Resolved(credential).ToString().ShouldNotContain(KeyPassword);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ reply handling / redaction
|
||||
|
||||
[Fact]
|
||||
public void EvaluateReply_protocol_failure_throws_with_password_scrubbed()
|
||||
{
|
||||
var credential = new GalaxyAckCredential("alice", "CORP", KeyPassword, GalaxyAckCredentialSource.ApiKey);
|
||||
var reply = new AcknowledgeAlarmReply
|
||||
{
|
||||
ProtocolStatus = new ProtocolStatus
|
||||
{
|
||||
Code = ProtocolStatusCode.InvalidRequest,
|
||||
// Pathological gateway echo — the scrub is defence in depth over the gateway's contract.
|
||||
Message = $"auth failed for alice/{KeyPassword}",
|
||||
},
|
||||
};
|
||||
var logger = new CapturingLogger();
|
||||
|
||||
var ex = Should.Throw<InvalidOperationException>(
|
||||
() => GatewayGalaxyAlarmAcknowledger.EvaluateReply(reply, "A.B", credential, logger));
|
||||
|
||||
ex.ToString().ShouldNotContain(KeyPassword);
|
||||
ex.Message.ShouldContain(GatewayGalaxyAlarmAcknowledger.Redacted);
|
||||
ex.Message.ShouldContain("CORP\\alice");
|
||||
logger.AllText.ShouldNotContain(KeyPassword);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EvaluateReply_native_failure_warns_without_password()
|
||||
{
|
||||
var credential = new GalaxyAckCredential("alice", "CORP", KeyPassword, GalaxyAckCredentialSource.ApiKey);
|
||||
var reply = new AcknowledgeAlarmReply
|
||||
{
|
||||
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
|
||||
Hresult = unchecked((int)0x80070005),
|
||||
};
|
||||
var logger = new CapturingLogger();
|
||||
|
||||
GatewayGalaxyAlarmAcknowledger.EvaluateReply(reply, "A.B", credential, logger);
|
||||
|
||||
logger.Entries.ShouldHaveSingleItem().Level.ShouldBe(LogLevel.Warning);
|
||||
logger.AllText.ShouldContain("CORP\\alice");
|
||||
logger.AllText.ShouldNotContain(KeyPassword);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Acknowledger_transport_failure_exception_text_has_no_password()
|
||||
{
|
||||
var client = MxGatewayClient.Create(new MxGatewayClientOptions
|
||||
{
|
||||
Endpoint = new Uri("http://127.0.0.1:1", UriKind.Absolute),
|
||||
ApiKey = "test-key",
|
||||
UseTls = false,
|
||||
ConnectTimeout = TimeSpan.FromMilliseconds(200),
|
||||
DefaultCallTimeout = TimeSpan.FromMilliseconds(200),
|
||||
});
|
||||
await using (client)
|
||||
{
|
||||
var logger = new CapturingLogger();
|
||||
var acknowledger = new GatewayGalaxyAlarmAcknowledger(client, logger);
|
||||
var credential = new GalaxyAckCredential("alice", "CORP", KeyPassword, GalaxyAckCredentialSource.ApiKey);
|
||||
|
||||
var ex = await Record.ExceptionAsync(
|
||||
() => acknowledger.AcknowledgeAsync("A.B", "c", credential, CancellationToken.None));
|
||||
|
||||
ex.ShouldNotBeNull();
|
||||
ex.ToString().ShouldNotContain(KeyPassword);
|
||||
logger.AllText.ShouldNotContain(KeyPassword);
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Scrub_replaces_every_occurrence_and_ignores_empty_secret()
|
||||
{
|
||||
GatewayGalaxyAlarmAcknowledger.Scrub("a pw b pw", "pw").ShouldBe("a *** b ***");
|
||||
GatewayGalaxyAlarmAcknowledger.Scrub("unchanged", string.Empty).ShouldBe("unchanged");
|
||||
GatewayGalaxyAlarmAcknowledger.Scrub(null, "pw").ShouldBe(string.Empty);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ resolver paths
|
||||
|
||||
[Fact]
|
||||
public async Task Resolver_key_mapped_identity_wins_over_fallback()
|
||||
{
|
||||
var secrets = new DictSecretResolver
|
||||
{
|
||||
[GalaxyAckIdentitySecrets.UserSecretName(KeyId)] = "CORP\\alice",
|
||||
[GalaxyAckIdentitySecrets.PasswordSecretName(KeyId)] = KeyPassword,
|
||||
["otopcua/galaxy/ack-fallback"] = FallbackPassword,
|
||||
};
|
||||
var logger = new CapturingLogger();
|
||||
var resolver = new GalaxyAckCredentialResolver("drv", WithFallback(), secrets, logger);
|
||||
|
||||
var result = await resolver.ResolveAsync(KeyId, CancellationToken.None);
|
||||
|
||||
var credential = result.Credential.ShouldNotBeNull();
|
||||
credential.Source.ShouldBe(GalaxyAckCredentialSource.ApiKey);
|
||||
credential.User.ShouldBe("alice");
|
||||
credential.Domain.ShouldBe("CORP");
|
||||
credential.Password.ShouldBe(KeyPassword);
|
||||
logger.AllText.ShouldNotContain(KeyPassword);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resolver_key_without_identity_uses_fallback()
|
||||
{
|
||||
var secrets = new DictSecretResolver { ["otopcua/galaxy/ack-fallback"] = FallbackPassword };
|
||||
var resolver = new GalaxyAckCredentialResolver("drv", WithFallback(), secrets, new CapturingLogger());
|
||||
|
||||
var credential = (await resolver.ResolveAsync(KeyId, CancellationToken.None)).Credential.ShouldNotBeNull();
|
||||
|
||||
credential.Source.ShouldBe(GalaxyAckCredentialSource.Fallback);
|
||||
credential.User.ShouldBe("ack-svc");
|
||||
credential.Domain.ShouldBe("PLANT");
|
||||
credential.Password.ShouldBe(FallbackPassword);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resolver_anonymous_uses_fallback()
|
||||
{
|
||||
var secrets = new DictSecretResolver { ["otopcua/galaxy/ack-fallback"] = FallbackPassword };
|
||||
var resolver = new GalaxyAckCredentialResolver("drv", WithFallback(), secrets, new CapturingLogger());
|
||||
|
||||
var result = await resolver.ResolveAsync(apiKeyId: null, CancellationToken.None);
|
||||
|
||||
result.Credential.ShouldNotBeNull().Source.ShouldBe(GalaxyAckCredentialSource.Fallback);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData(KeyId)]
|
||||
public async Task Resolver_refuses_with_no_identity_and_no_fallback(string? apiKeyId)
|
||||
{
|
||||
var resolver = new GalaxyAckCredentialResolver(
|
||||
"drv-x", new GalaxyAlarmAckOptions(), new DictSecretResolver(), new CapturingLogger());
|
||||
|
||||
var result = await resolver.ResolveAsync(apiKeyId, CancellationToken.None);
|
||||
|
||||
result.Credential.ShouldBeNull();
|
||||
result.RefusalReason.ShouldNotBeNull();
|
||||
result.RefusalReason.ShouldContain("drv-x");
|
||||
result.RefusalReason.ShouldContain("FallbackUser");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resolver_refuses_key_with_user_but_no_password_even_when_fallback_exists()
|
||||
{
|
||||
// A key the admin explicitly mapped must not silently ack as the shared fallback account.
|
||||
var secrets = new DictSecretResolver
|
||||
{
|
||||
[GalaxyAckIdentitySecrets.UserSecretName(KeyId)] = "alice",
|
||||
["otopcua/galaxy/ack-fallback"] = FallbackPassword,
|
||||
};
|
||||
var resolver = new GalaxyAckCredentialResolver("drv", WithFallback(), secrets, new CapturingLogger());
|
||||
|
||||
var result = await resolver.ResolveAsync(KeyId, CancellationToken.None);
|
||||
|
||||
result.Credential.ShouldBeNull();
|
||||
result.RefusalReason.ShouldNotBeNull().ShouldContain("no password secret");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resolver_key_with_empty_password_is_allowed()
|
||||
{
|
||||
var secrets = new DictSecretResolver
|
||||
{
|
||||
[GalaxyAckIdentitySecrets.UserSecretName(KeyId)] = "alice",
|
||||
[GalaxyAckIdentitySecrets.PasswordSecretName(KeyId)] = string.Empty,
|
||||
};
|
||||
var resolver = new GalaxyAckCredentialResolver("drv", new GalaxyAlarmAckOptions(), secrets, new CapturingLogger());
|
||||
|
||||
var credential = (await resolver.ResolveAsync(KeyId, CancellationToken.None)).Credential.ShouldNotBeNull();
|
||||
credential.Password.ShouldBe(string.Empty);
|
||||
credential.Domain.ShouldBe(string.Empty);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resolver_refuses_literal_fallback_password_without_echoing_it()
|
||||
{
|
||||
var logger = new CapturingLogger();
|
||||
var resolver = new GalaxyAckCredentialResolver(
|
||||
"drv", new GalaxyAlarmAckOptions("ack-svc", null, FallbackPassword), new DictSecretResolver(), logger);
|
||||
|
||||
var result = await resolver.ResolveAsync(null, CancellationToken.None);
|
||||
|
||||
result.Credential.ShouldBeNull();
|
||||
result.RefusalReason.ShouldNotBeNull().ShouldNotContain(FallbackPassword);
|
||||
logger.AllText.ShouldNotContain(FallbackPassword);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Resolver_refuses_when_fallback_secret_absent()
|
||||
{
|
||||
var resolver = new GalaxyAckCredentialResolver("drv", WithFallback(), new DictSecretResolver(), new CapturingLogger());
|
||||
|
||||
var result = await resolver.ResolveAsync(null, CancellationToken.None);
|
||||
|
||||
result.Credential.ShouldBeNull();
|
||||
result.RefusalReason.ShouldNotBeNull().ShouldContain("secret:otopcua/galaxy/ack-fallback");
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("${secret:otopcua/galaxy/ack-fallback}")]
|
||||
[InlineData("secret:otopcua/galaxy/ack-fallback")]
|
||||
public async Task Resolver_accepts_both_secret_reference_spellings(string reference)
|
||||
{
|
||||
var secrets = new DictSecretResolver { ["otopcua/galaxy/ack-fallback"] = FallbackPassword };
|
||||
var resolver = new GalaxyAckCredentialResolver(
|
||||
"drv", new GalaxyAlarmAckOptions("ack-svc", null, reference), secrets, new CapturingLogger());
|
||||
|
||||
(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()
|
||||
{
|
||||
var logger = new CapturingLogger();
|
||||
var resolver = new GalaxyAckCredentialResolver(
|
||||
"drv", WithFallback(), new ThrowingSecretResolver(KeyPassword), logger);
|
||||
|
||||
var result = await resolver.ResolveAsync(KeyId, CancellationToken.None);
|
||||
|
||||
result.Credential.ShouldBeNull();
|
||||
result.RefusalReason.ShouldNotBeNull().ShouldNotContain(KeyPassword);
|
||||
logger.AllText.ShouldNotContain(KeyPassword);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Identity_secret_names_and_parsing()
|
||||
{
|
||||
GalaxyAckIdentitySecrets.UserSecretName("0A1B").ShouldBe("otopcua/apikeys/0a1b/galaxy-ack-user");
|
||||
GalaxyAckIdentitySecrets.PasswordSecretName("0a1b").ShouldBe("otopcua/apikeys/0a1b/galaxy-ack-password");
|
||||
Should.Throw<ArgumentException>(() => GalaxyAckIdentitySecrets.UserSecretName("../x"));
|
||||
GalaxyAckIdentitySecrets.ParseIdentity("CORP\\alice").ShouldBe(("alice", "CORP"));
|
||||
GalaxyAckIdentitySecrets.ParseIdentity("alice").ShouldBe(("alice", string.Empty));
|
||||
GalaxyAckIdentitySecrets.FormatIdentity("alice", "CORP").ShouldBe("CORP\\alice");
|
||||
GalaxyAckIdentitySecrets.FormatIdentity("alice", " ").ShouldBe("alice");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ driver paths
|
||||
|
||||
[Fact]
|
||||
public async Task Driver_key_mapped_path_sends_the_keys_account()
|
||||
{
|
||||
var ack = new CredentialRecordingAcknowledger();
|
||||
var secrets = new DictSecretResolver
|
||||
{
|
||||
[GalaxyAckIdentitySecrets.UserSecretName(KeyId)] = "CORP\\alice",
|
||||
[GalaxyAckIdentitySecrets.PasswordSecretName(KeyId)] = KeyPassword,
|
||||
};
|
||||
var logger = new CapturingLogger();
|
||||
using var driver = NewDriver(Opts(), ack, secrets, logger);
|
||||
|
||||
await driver.AcknowledgeAsync(
|
||||
[new AlarmAcknowledgeRequest("src", "Tank01.Level.HiHi", "cmt", "mes-line1", KeyId)], CancellationToken.None);
|
||||
|
||||
var call = ack.Calls.ShouldHaveSingleItem();
|
||||
call.Credential.User.ShouldBe("alice");
|
||||
call.Credential.Password.ShouldBe(KeyPassword);
|
||||
call.Comment.ShouldBe($"cmt [OPC UA: mes-line1, key {KeyId}]");
|
||||
logger.AllText.ShouldNotContain(KeyPassword);
|
||||
logger.AllText.ShouldContain("mes-line1");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Driver_fallback_path_sends_the_fallback_account()
|
||||
{
|
||||
var ack = new CredentialRecordingAcknowledger();
|
||||
var secrets = new DictSecretResolver { ["otopcua/galaxy/ack-fallback"] = FallbackPassword };
|
||||
var logger = new CapturingLogger();
|
||||
using var driver = NewDriver(Opts() with { AlarmAck = WithFallback() }, ack, secrets, logger);
|
||||
|
||||
await driver.AcknowledgeAsync(
|
||||
[new AlarmAcknowledgeRequest("src", "Tank01.Level.HiHi", null, OperatorUser: "anonymous")], CancellationToken.None);
|
||||
|
||||
var call = ack.Calls.ShouldHaveSingleItem();
|
||||
call.Credential.Source.ShouldBe(GalaxyAckCredentialSource.Fallback);
|
||||
call.Credential.User.ShouldBe("ack-svc");
|
||||
call.Credential.Password.ShouldBe(FallbackPassword);
|
||||
call.Comment.ShouldBe("[OPC UA: anonymous]");
|
||||
logger.AllText.ShouldNotContain(FallbackPassword);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Driver_refused_path_sends_nothing_and_throws_refusal()
|
||||
{
|
||||
var ack = new CredentialRecordingAcknowledger();
|
||||
var logger = new CapturingLogger();
|
||||
using var driver = NewDriver(Opts(), ack, new DictSecretResolver(), logger);
|
||||
|
||||
var ex = await Should.ThrowAsync<DriverOperationRefusedException>(() => driver.AcknowledgeAsync(
|
||||
[new AlarmAcknowledgeRequest("src", "Tank01.Level.HiHi", "cmt", "mes-line1", KeyId)], CancellationToken.None));
|
||||
|
||||
ack.Calls.ShouldBeEmpty(); // never reaches the gateway — and so never with an empty operator_user
|
||||
ex.Message.ShouldContain("Tank01.Level.HiHi");
|
||||
logger.Entries.ShouldContain(e => e.Level == LogLevel.Warning && e.Text.Contains("refused"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Annotate_comment_forms()
|
||||
{
|
||||
GalaxyDriver.AnnotateAckComment("x", "p", "k").ShouldBe("x [OPC UA: p, key k]");
|
||||
GalaxyDriver.AnnotateAckComment(" ", null, null).ShouldBe("[OPC UA: anonymous]");
|
||||
GalaxyDriver.AnnotateAckComment(null, "p", null).ShouldBe("[OPC UA: p]");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ helpers
|
||||
|
||||
private static GalaxyAlarmAckOptions WithFallback() =>
|
||||
new("ack-svc", "PLANT", "secret:otopcua/galaxy/ack-fallback");
|
||||
|
||||
private static GalaxyDriverOptions Opts() => new(
|
||||
new GalaxyGatewayOptions("https://mxgw.test:5001", "dev:key"),
|
||||
new GalaxyMxAccessOptions("OtOpcUa-A"),
|
||||
new GalaxyRepositoryOptions(),
|
||||
new GalaxyReconnectOptions());
|
||||
|
||||
private static GalaxyDriver NewDriver(
|
||||
GalaxyDriverOptions options, IGalaxyAlarmAcknowledger ack, ISecretResolver secrets, ILogger logger) =>
|
||||
new("drv", options, hierarchySource: null, alarmAcknowledger: ack,
|
||||
logger: new TypedLogger<GalaxyDriver>(logger), secretResolver: secrets);
|
||||
|
||||
private sealed class TypedLogger<T>(ILogger inner) : ILogger<T>
|
||||
{
|
||||
public IDisposable? BeginScope<TState>(TState state) where TState : notnull => inner.BeginScope(state);
|
||||
public bool IsEnabled(LogLevel logLevel) => inner.IsEnabled(logLevel);
|
||||
public void Log<TState>(LogLevel l, EventId id, TState s, Exception? e, Func<TState, Exception?, string> f)
|
||||
=> inner.Log(l, id, s, e, f);
|
||||
}
|
||||
|
||||
private sealed class CredentialRecordingAcknowledger : IGalaxyAlarmAcknowledger
|
||||
{
|
||||
public List<(string AlarmRef, string Comment, GalaxyAckCredential Credential)> Calls { get; } = [];
|
||||
|
||||
public Task AcknowledgeAsync(
|
||||
string alarmFullReference, string comment, GalaxyAckCredential credential, CancellationToken cancellationToken)
|
||||
{
|
||||
Calls.Add((alarmFullReference, comment, credential));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class DictSecretResolver : Dictionary<string, string>, ISecretResolver
|
||||
{
|
||||
public Task<string?> GetAsync(SecretName name, CancellationToken ct) =>
|
||||
Task.FromResult(TryGetValue(name.Value, out var v) ? v : null);
|
||||
}
|
||||
|
||||
private sealed class ThrowingSecretResolver(string leak) : ISecretResolver
|
||||
{
|
||||
public Task<string?> GetAsync(SecretName name, CancellationToken ct) =>
|
||||
throw new InvalidOperationException($"store exploded near {leak}");
|
||||
}
|
||||
}
|
||||
+4
-3
@@ -124,7 +124,8 @@ public sealed class GalaxyDriverRawPathKeyingTests
|
||||
var feed = new FakeAlarmFeed();
|
||||
var ack = new RecordingAcknowledger();
|
||||
using var driver = new GalaxyDriver(
|
||||
"g", OptsWithRawTags(), hierarchySource: null, alarmAcknowledger: ack, alarmFeed: feed);
|
||||
"g", OptsWithRawTags(), hierarchySource: null, alarmAcknowledger: ack, alarmFeed: feed,
|
||||
ackCredentialResolver: FixedAckCredentialResolver.Fallback());
|
||||
|
||||
var handle = await driver.SubscribeAlarmsAsync(["Tank1"], CancellationToken.None);
|
||||
var observed = new List<AlarmEventArgs>();
|
||||
@@ -251,9 +252,9 @@ public sealed class GalaxyDriverRawPathKeyingTests
|
||||
{
|
||||
public List<(string AlarmRef, string Comment, string Operator)> Calls { get; } = [];
|
||||
|
||||
public Task AcknowledgeAsync(string alarmFullReference, string comment, string operatorUser, CancellationToken cancellationToken)
|
||||
public Task AcknowledgeAsync(string alarmFullReference, string comment, GalaxyAckCredential credential, CancellationToken cancellationToken)
|
||||
{
|
||||
Calls.Add((alarmFullReference, comment, operatorUser));
|
||||
Calls.Add((alarmFullReference, comment, credential.User));
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
+16
-10
@@ -45,10 +45,10 @@ public sealed class GatewayGalaxyAlarmAcknowledgerTests
|
||||
public Task AcknowledgeAsync(
|
||||
string alarmFullReference,
|
||||
string comment,
|
||||
string operatorUser,
|
||||
GalaxyAckCredential credential,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
Calls.Add((alarmFullReference, comment, operatorUser));
|
||||
Calls.Add((alarmFullReference, comment, credential.User));
|
||||
return _outcomes.Count > 0 ? _outcomes.Dequeue()() : Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
@@ -59,6 +59,9 @@ public sealed class GatewayGalaxyAlarmAcknowledgerTests
|
||||
new GalaxyRepositoryOptions(),
|
||||
new GalaxyReconnectOptions());
|
||||
|
||||
private static readonly GalaxyAckCredential Alice =
|
||||
new("alice", "CORP", "alice-pw", GalaxyAckCredentialSource.ApiKey);
|
||||
|
||||
private static AlarmAcknowledgeRequest Ack(string conditionId, string comment = "c", string source = "")
|
||||
=> new(SourceNodeId: source, ConditionId: conditionId, Comment: comment);
|
||||
|
||||
@@ -79,7 +82,8 @@ public sealed class GatewayGalaxyAlarmAcknowledgerTests
|
||||
fake.Enqueue(() => Task.CompletedTask);
|
||||
|
||||
var driver = new GalaxyDriver("g", Opts(),
|
||||
hierarchySource: null, alarmAcknowledger: fake);
|
||||
hierarchySource: null, alarmAcknowledger: fake,
|
||||
ackCredentialResolver: FixedAckCredentialResolver.Fallback());
|
||||
|
||||
await Should.ThrowAsync<IOException>(
|
||||
() => driver.AcknowledgeAsync(
|
||||
@@ -93,8 +97,8 @@ public sealed class GatewayGalaxyAlarmAcknowledgerTests
|
||||
|
||||
fake.Calls.Count.ShouldBe(2);
|
||||
fake.Calls[0].AlarmRef.ShouldBe("Tank01.Level.HiHi");
|
||||
fake.Calls[0].Comment.ShouldBe("investigating");
|
||||
fake.Calls[1].Comment.ShouldBe("resolved");
|
||||
fake.Calls[0].Comment.ShouldBe("investigating [OPC UA: anonymous]");
|
||||
fake.Calls[1].Comment.ShouldBe("resolved [OPC UA: anonymous]");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
@@ -109,7 +113,8 @@ public sealed class GatewayGalaxyAlarmAcknowledgerTests
|
||||
fake.Enqueue(() => Task.CompletedTask);
|
||||
|
||||
var driver = new GalaxyDriver("g", Opts(),
|
||||
hierarchySource: null, alarmAcknowledger: fake);
|
||||
hierarchySource: null, alarmAcknowledger: fake,
|
||||
ackCredentialResolver: FixedAckCredentialResolver.Fallback());
|
||||
|
||||
await Should.ThrowAsync<InvalidOperationException>(
|
||||
() => driver.AcknowledgeAsync(
|
||||
@@ -131,14 +136,15 @@ public sealed class GatewayGalaxyAlarmAcknowledgerTests
|
||||
var fake = new FakeAcknowledger();
|
||||
|
||||
var driver = new GalaxyDriver("g", Opts(),
|
||||
hierarchySource: null, alarmAcknowledger: fake);
|
||||
hierarchySource: null, alarmAcknowledger: fake,
|
||||
ackCredentialResolver: FixedAckCredentialResolver.Fallback());
|
||||
|
||||
await driver.AcknowledgeAsync(
|
||||
[Ack("Pump01.Flow.Low", "operator comment")], CancellationToken.None);
|
||||
|
||||
fake.Calls.ShouldHaveSingleItem();
|
||||
fake.Calls[0].AlarmRef.ShouldBe("Pump01.Flow.Low");
|
||||
fake.Calls[0].Comment.ShouldBe("operator comment");
|
||||
fake.Calls[0].Comment.ShouldBe("operator comment [OPC UA: anonymous]");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -179,10 +185,10 @@ public sealed class GatewayGalaxyAlarmAcknowledgerTests
|
||||
|
||||
var ex1 = await Record.ExceptionAsync(
|
||||
() => acknowledger.AcknowledgeAsync(
|
||||
"Tank01.Level.HiHi", "c1", "alice", CancellationToken.None));
|
||||
"Tank01.Level.HiHi", "c1", Alice, CancellationToken.None));
|
||||
var ex2 = await Record.ExceptionAsync(
|
||||
() => acknowledger.AcknowledgeAsync(
|
||||
"Tank01.Level.HiHi", "c2", "alice", CancellationToken.None));
|
||||
"Tank01.Level.HiHi", "c2", Alice, CancellationToken.None));
|
||||
|
||||
// Both calls must fault — not a success.
|
||||
ex1.ShouldNotBeNull("first call to unreachable endpoint should throw");
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
||||
|
||||
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IGalaxyAckCredentialResolver"/> test double that resolves every acknowledge to one fixed
|
||||
/// credential (or refuses all), recording the key ids it was asked about.
|
||||
/// </summary>
|
||||
internal sealed class FixedAckCredentialResolver : IGalaxyAckCredentialResolver
|
||||
{
|
||||
private readonly GalaxyAckCredential? _credential;
|
||||
|
||||
private FixedAckCredentialResolver(GalaxyAckCredential? credential) => _credential = credential;
|
||||
|
||||
/// <summary>Gets the key ids the driver resolved for, in order.</summary>
|
||||
public List<string?> RequestedKeyIds { get; } = [];
|
||||
|
||||
/// <summary>A resolver that always returns a fallback account <c>ACKDOM\ack-op</c> / <c>pw</c>.</summary>
|
||||
public static FixedAckCredentialResolver Fallback() =>
|
||||
new(new GalaxyAckCredential("ack-op", "ACKDOM", "pw", GalaxyAckCredentialSource.Fallback));
|
||||
|
||||
/// <summary>A resolver that refuses every acknowledge.</summary>
|
||||
public static FixedAckCredentialResolver RefuseAll() => new(null);
|
||||
|
||||
/// <inheritdoc />
|
||||
public Task<GalaxyAckCredentialResolution> ResolveAsync(string? apiKeyId, CancellationToken cancellationToken)
|
||||
{
|
||||
RequestedKeyIds.Add(apiKeyId);
|
||||
return Task.FromResult(_credential is null
|
||||
? GalaxyAckCredentialResolution.Refused("test refusal")
|
||||
: GalaxyAckCredentialResolution.Resolved(_credential));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user