Files
lmxopcua/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverSecuredWriteIdentityTests.cs
T
Joseph Doherty 13521354cc feat(galaxy): #1017 SecuredWrite attributes can be written as the calling API key's Galaxy identity (opt-in); VerifiedWrite stays refused
- MxAccess.SecuredWrites = Refuse (default, unchanged #991 local BadUserAccessDenied) |
  ApiKeyIdentity. Opted in, a SecuredWrite runs as the calling key's own /api-keys Galaxy
  identity (ResolveKeyIdentityAsync: no fallback account; anonymous / no identity / broken
  identity refused before the wire): own plain-advised handle (apart from the raw path's
  supervisory handle) -> AuthenticateUser every write -> WriteSecured(userId, 0), the sequence
  mxaccessgw live-captured committing. Auth failure / user id 0 -> BadUserAccessDenied; password
  only in the AuthenticateUser command, scrubbed from every log. Identity resolved once per batch.
- VerifiedWrite is refused in every mode: an OPC UA Write carries no verifier (MXAccess refuses
  no verifier 1008 / self-verifier 8018), and a stored verifier would defeat the two-person rule.
- Caller plumbing: WriteCaller + optional ICallerAwareWritable (Core.Abstractions); node manager
  passes principal + key id -> IOpcUaNodeWriteGateway caller overload (default drops it) ->
  RouteNodeWrite.Caller -> WriteAttribute.Caller -> ICallerAwareWritable. The gRPC data-connection
  write path carries no caller yet (secured writes refused there).
- AdminUI Galaxy form 'Secured writes' select (owned path); enum serialises as its name; factory
  refuses an unknown value. Docs: Galaxy.md design + live-gate checklist. Not live-gated.
2026-12-03 15:29:02 -05:00

124 lines
5.5 KiB
C#

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;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
/// <summary>
/// #1017 — the driver hands its writer the CALLER's Galaxy identity source only when
/// <c>MxAccess.SecuredWrites = ApiKeyIdentity</c> AND the write carries a caller; the source resolves the key's
/// own identity (<see cref="IGalaxyAckCredentialResolver.ResolveKeyIdentityAsync"/> — never the ack fallback).
/// </summary>
public sealed class GalaxyDriverSecuredWriteIdentityTests
{
private static GalaxyDriverOptions Opts(GalaxySecuredWriteMode mode) => new(
new GalaxyGatewayOptions("https://mxgw.test:5001", "key"),
new GalaxyMxAccessOptions("OtOpcUa-A") { SecuredWrites = mode },
new GalaxyRepositoryOptions(WatchDeployEvents: false),
new GalaxyReconnectOptions())
{
RawTags = [new RawTagEntry("Plant/Tank1/SP", """{"attributeRef":"Tank1.SP"}""", false)],
};
private sealed class IdentityRecordingWriter : IGalaxyDataWriter
{
public List<Func<CancellationToken, Task<GalaxyAckCredentialResolution>>?> Sources { get; } = [];
public Task<IReadOnlyList<WriteResult>> WriteAsync(
IReadOnlyList<WriteRequest> writes, Func<string, SecurityClassification> securityResolver,
CancellationToken cancellationToken)
{
Sources.Add(null);
return Task.FromResult<IReadOnlyList<WriteResult>>([.. writes.Select(_ => new WriteResult(StatusCodeMap.Good))]);
}
Task<IReadOnlyList<WriteResult>> IGalaxyDataWriter.WriteAsync(
IReadOnlyList<WriteRequest> writes, Func<string, SecurityClassification> securityResolver,
Func<CancellationToken, Task<GalaxyAckCredentialResolution>>? securedCredential, CancellationToken cancellationToken)
{
Sources.Add(securedCredential);
return Task.FromResult<IReadOnlyList<WriteResult>>([.. writes.Select(_ => new WriteResult(StatusCodeMap.Good))]);
}
public void InvalidateHandleCaches() { }
}
private static (GalaxyDriver Driver, IdentityRecordingWriter Writer, FixedAckCredentialResolver Resolver) Build(
GalaxySecuredWriteMode mode)
{
var writer = new IdentityRecordingWriter();
var resolver = FixedAckCredentialResolver.Fallback();
var driver = new GalaxyDriver("g", Opts(mode), hierarchySource: null, dataWriter: writer, ackCredentialResolver: resolver);
return (driver, writer, resolver);
}
[Fact]
public async Task ApiKeyIdentity_mode_with_a_caller_passes_a_key_only_identity_source()
{
var (driver, writer, resolver) = Build(GalaxySecuredWriteMode.ApiKeyIdentity);
await ((ICallerAwareWritable)driver).WriteAsync(
[new WriteRequest("Plant/Tank1/SP", 1.0)], new WriteCaller("svc-mes", "0a1b2c3d4e5f6071"),
TestContext.Current.CancellationToken);
var source = writer.Sources.ShouldHaveSingleItem().ShouldNotBeNull();
var resolution = await source(TestContext.Current.CancellationToken);
resolution.Credential.ShouldNotBeNull();
resolver.SecuredWriteKeyIds.ShouldBe(["0a1b2c3d4e5f6071"]);
resolver.RequestedKeyIds.ShouldBeEmpty("a secured write never uses the ack resolution (with its fallback)");
}
[Fact]
public async Task ApiKeyIdentity_mode_for_an_anonymous_caller_resolves_a_refusal()
{
var (driver, writer, resolver) = Build(GalaxySecuredWriteMode.ApiKeyIdentity);
await driver.WriteAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], new WriteCaller("anonymous", null),
TestContext.Current.CancellationToken);
var resolution = await writer.Sources.ShouldHaveSingleItem().ShouldNotBeNull()(TestContext.Current.CancellationToken);
resolution.Credential.ShouldBeNull();
resolver.SecuredWriteKeyIds.ShouldBe([null]);
}
[Fact]
public async Task Refuse_mode_passes_no_identity_source_even_with_a_caller()
{
var (driver, writer, _) = Build(GalaxySecuredWriteMode.Refuse);
await driver.WriteAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], new WriteCaller("svc", "0a1b2c3d4e5f6071"),
TestContext.Current.CancellationToken);
writer.Sources.ShouldHaveSingleItem().ShouldBeNull();
}
[Fact]
public async Task A_write_without_a_caller_passes_no_identity_source()
{
var (driver, writer, _) = Build(GalaxySecuredWriteMode.ApiKeyIdentity);
await driver.WriteAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], TestContext.Current.CancellationToken);
writer.Sources.ShouldHaveSingleItem().ShouldBeNull();
}
[Theory]
[InlineData(null, GalaxySecuredWriteMode.Refuse)]
[InlineData("", GalaxySecuredWriteMode.Refuse)]
[InlineData("refuse", GalaxySecuredWriteMode.Refuse)]
[InlineData("ApiKeyIdentity", GalaxySecuredWriteMode.ApiKeyIdentity)]
[InlineData("apikeyidentity", GalaxySecuredWriteMode.ApiKeyIdentity)]
public void The_factory_parses_SecuredWrites(string? value, GalaxySecuredWriteMode expected)
=> GalaxyDriverFactoryExtensions.ParseSecuredWrites(value, "g").ShouldBe(expected);
[Theory]
[InlineData("ApiKey")]
[InlineData("1")]
[InlineData("Fallback")]
public void The_factory_refuses_an_unknown_SecuredWrites_value(string value)
=> Should.Throw<InvalidOperationException>(() => GalaxyDriverFactoryExtensions.ParseSecuredWrites(value, "g"))
.Message.ShouldContain("SecuredWrites");
}