Files
lmxopcua/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GatewayGalaxyDataWriterSecuredWriteTests.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

288 lines
13 KiB
C#

using Shouldly;
using Xunit;
using ZB.MOM.WW.MxGateway.Contracts.Proto;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime;
/// <summary>
/// #1017 — a SecuredWrite attribute is written under the CALLER's Galaxy identity (the session's API key identity,
/// resolved by the driver and handed to the writer): the writer's own plain-advised handle →
/// <c>AuthenticateUser(DOMAIN\user, password)</c> → <c>WriteSecured(current = that user, verifier = 0)</c>.
/// No usable identity (no resolver, a refused resolution, an authentication MXAccess rejects) is still the #991
/// local <c>BadUserAccessDenied</c> refusal, and a VerifiedWrite is ALWAYS refused (no second, verifying identity).
/// </summary>
[Collection(ProcessWideTelemetryCollection.Name)]
public sealed class GatewayGalaxyDataWriterSecuredWriteTests
{
private const string Password = "S3cr3t-pw!";
private const int AuthenticatedUserId = 4242;
private static GatewayGalaxyDataWriter NewWriter(CapturingLogger? logger = null)
=> new(new GalaxyMxSession(new Config.GalaxyMxAccessOptions(ClientName: "OtOpcUa-Test")), writeUserId: 0, logger);
private static Func<CancellationToken, Task<GalaxyAckCredentialResolution>> Identity(
string user = "op", string? domain = "PLANT", string password = Password) =>
_ => Task.FromResult(GalaxyAckCredentialResolution.Resolved(
new GalaxyAckCredential(user, domain, password, GalaxyAckCredentialSource.ApiKey)));
private static MxCommandReply Ok() => new() { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok } };
private static SecuredFakeOps HappyOps() => new()
{
InvokeResponder = r => r.Command.Kind switch
{
MxCommandKind.AuthenticateUser => new MxCommandReply
{
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
AuthenticateUser = new AuthenticateUserReply { UserId = AuthenticatedUserId },
},
MxCommandKind.WriteSecured => new MxCommandReply
{
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
Statuses = { new MxStatusProxy { Success = 1, Category = MxStatusCategory.Ok } },
},
_ => Ok(),
},
};
[Fact]
public async Task SecuredWrite_with_a_caller_identity_authenticates_then_writes_secured_on_a_plain_advised_handle()
{
var ops = HappyOps();
var logger = new CapturingLogger();
var writer = NewWriter(logger);
var result = await writer.WriteOneForTestAsync(
ops, new WriteRequest("Tank.SetPoint", 12.5), SecurityClassification.SecuredWrite, CancellationToken.None,
Identity());
result.StatusCode.ShouldBe(StatusCodeMap.Good);
ops.AddItemRefs.ShouldBe(["Tank.SetPoint"]);
ops.RawWriteHandles.ShouldBeEmpty(); // never the supervisory raw path
ops.Invokes.Select(i => i.Command.Kind).ShouldBe(
[MxCommandKind.Advise, MxCommandKind.AuthenticateUser, MxCommandKind.WriteSecured]);
var advise = ops.Invokes[0].Command.Advise;
advise.ServerHandle.ShouldBe(ops.ServerHandle);
advise.ItemHandle.ShouldBe(ops.NextHandle);
var auth = ops.Invokes[1].Command.AuthenticateUser;
auth.ServerHandle.ShouldBe(ops.ServerHandle);
auth.VerifyUser.ShouldBe("PLANT\\op");
auth.VerifyUserPassword.ShouldBe(Password);
var write = ops.Invokes[2].Command.WriteSecured;
write.ItemHandle.ShouldBe(ops.NextHandle);
write.CurrentUserId.ShouldBe(AuthenticatedUserId);
write.VerifierUserId.ShouldBe(0);
write.Value.ShouldNotBeNull();
logger.AllText.ShouldNotContain(Password);
}
[Fact]
public async Task SecuredWrite_reuses_the_advised_handle_but_authenticates_every_write()
{
var ops = HappyOps();
var writer = NewWriter();
await writer.WriteOneForTestAsync(ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, Identity());
await writer.WriteOneForTestAsync(ops, new WriteRequest("T.A", 2), SecurityClassification.SecuredWrite, CancellationToken.None, Identity());
ops.AddItemRefs.Count.ShouldBe(1);
ops.Invokes.Count(i => i.Command.Kind == MxCommandKind.Advise).ShouldBe(1);
ops.Invokes.Count(i => i.Command.Kind == MxCommandKind.AuthenticateUser).ShouldBe(2);
ops.Invokes.Count(i => i.Command.Kind == MxCommandKind.WriteSecured).ShouldBe(2);
}
/// <summary>The secured handle is NOT the raw path's supervisory handle (one advise mode per handle).</summary>
[Fact]
public async Task SecuredWrite_uses_its_own_handle_apart_from_the_supervisory_raw_handle()
{
var ops = HappyOps();
var writer = NewWriter();
writer.SeedHandleCachesForTest("T.A", itemHandle: 99, supervised: true);
await writer.WriteOneForTestAsync(ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, Identity());
ops.AddItemRefs.ShouldBe(["T.A"]); // a fresh handle for the secured path
ops.Invokes.Single(i => i.Command.Kind == MxCommandKind.WriteSecured).Command.WriteSecured.ItemHandle.ShouldBe(ops.NextHandle);
ops.Invokes.ShouldNotContain(i => i.Command.Kind == MxCommandKind.AdviseSupervisory);
}
[Fact]
public async Task SecuredWrite_without_an_identity_source_is_refused_without_touching_the_wire()
{
var ops = HappyOps();
var result = await NewWriter().WriteOneForTestAsync(
ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, securedCredential: null);
result.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied);
ops.AddItemRefs.ShouldBeEmpty();
ops.Invokes.ShouldBeEmpty();
}
[Fact]
public async Task SecuredWrite_with_a_refused_identity_is_refused_without_touching_the_wire_and_logs_the_reason()
{
var ops = HappyOps();
var logger = new CapturingLogger();
var result = await NewWriter(logger).WriteOneForTestAsync(
ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None,
_ => Task.FromResult(GalaxyAckCredentialResolution.Refused("API key 'k1' has no Galaxy identity")));
result.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied);
ops.AddItemRefs.ShouldBeEmpty();
ops.Invokes.ShouldBeEmpty();
logger.AllText.ShouldContain("has no Galaxy identity");
}
/// <summary>A VerifiedWrite needs a second, verifying user — never supplied, so it stays refused even WITH an identity.</summary>
[Fact]
public async Task VerifiedWrite_is_refused_even_with_an_identity()
{
var ops = HappyOps();
var resolved = 0;
var result = await NewWriter().WriteOneForTestAsync(
ops, new WriteRequest("T.A", 1), SecurityClassification.VerifiedWrite, CancellationToken.None,
ct => { resolved++; return Identity()(ct); });
result.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied);
ops.Invokes.ShouldBeEmpty();
ops.AddItemRefs.ShouldBeEmpty();
resolved.ShouldBe(0);
}
[Theory]
[InlineData(true)] // MXAccess rejected the credential: no user id
[InlineData(false)] // protocol-level failure
public async Task An_authentication_MXAccess_rejects_is_BadUserAccessDenied_and_nothing_is_written(bool zeroUserId)
{
var ops = new SecuredFakeOps
{
InvokeResponder = r => r.Command.Kind == MxCommandKind.AuthenticateUser
? zeroUserId
? new MxCommandReply { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok }, AuthenticateUser = new AuthenticateUserReply { UserId = 0 } }
: new MxCommandReply { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.MxaccessFailure, Message = $"bad credential {Password}" }, Hresult = unchecked((int)0x80070005) }
: Ok(),
};
var logger = new CapturingLogger();
var result = await NewWriter(logger).WriteOneForTestAsync(
ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, Identity());
result.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied);
ops.Invokes.ShouldNotContain(i => i.Command.Kind == MxCommandKind.WriteSecured);
logger.AllText.ShouldContain("PLANT\\op");
logger.AllText.ShouldNotContain(Password);
}
/// <summary>A failed plain advise fails the write CLOSED (no AuthenticateUser, no WriteSecured), like the raw path.</summary>
[Fact]
public async Task A_failed_advise_fails_closed_before_authenticating()
{
var ops = new SecuredFakeOps
{
InvokeResponder = r => r.Command.Kind == MxCommandKind.Advise
? new MxCommandReply { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.MxaccessFailure, Message = "E_INVALIDARG" } }
: Ok(),
};
var result = await NewWriter().WriteOneForTestAsync(
ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, Identity());
result.StatusCode.ShouldBe(StatusCodeMap.BadCommunicationError);
ops.Invokes.Select(i => i.Command.Kind).ShouldBe([MxCommandKind.Advise]);
}
/// <summary>MXAccess refusing the user's rights on the secured write (1016) is an access refusal.</summary>
[Fact]
public async Task A_secured_write_MXAccess_refuses_for_rights_is_BadUserAccessDenied()
{
var ops = new SecuredFakeOps
{
InvokeResponder = r => r.Command.Kind switch
{
MxCommandKind.AuthenticateUser => new MxCommandReply { ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok }, AuthenticateUser = new AuthenticateUserReply { UserId = 7 } },
MxCommandKind.WriteSecured => new MxCommandReply
{
ProtocolStatus = new ProtocolStatus { Code = ProtocolStatusCode.Ok },
Statuses = { new MxStatusProxy { Success = 0, Category = MxStatusCategory.SecurityError, Detail = 1016 } },
},
_ => Ok(),
},
};
var result = await NewWriter().WriteOneForTestAsync(
ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, Identity());
result.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied);
}
/// <summary>A whole batch resolves the caller's identity ONCE, however many secured tags it carries.</summary>
[Fact]
public async Task A_batch_resolves_the_identity_once()
{
var ops = HappyOps();
var resolved = 0;
var writer = NewWriter();
var results = await writer.WriteBatchForTestAsync(ops,
[new WriteRequest("T.A", 1), new WriteRequest("T.B", 2), new WriteRequest("T.C", 3)],
_ => SecurityClassification.SecuredWrite, CancellationToken.None,
ct => { Interlocked.Increment(ref resolved); return Identity()(ct); });
results.ShouldAllBe(r => r.StatusCode == StatusCodeMap.Good);
resolved.ShouldBe(1);
}
/// <summary>Invalidation (a reconnect) forgets the secured handles too, so a fresh session re-adds + re-advises.</summary>
[Fact]
public async Task InvalidateHandleCaches_forgets_secured_handles()
{
var ops = HappyOps();
var writer = NewWriter();
await writer.WriteOneForTestAsync(ops, new WriteRequest("T.A", 1), SecurityClassification.SecuredWrite, CancellationToken.None, Identity());
writer.InvalidateHandleCaches();
await writer.WriteOneForTestAsync(ops, new WriteRequest("T.A", 2), SecurityClassification.SecuredWrite, CancellationToken.None, Identity());
ops.AddItemRefs.Count.ShouldBe(2);
ops.Invokes.Count(i => i.Command.Kind == MxCommandKind.Advise).ShouldBe(2);
}
private sealed class SecuredFakeOps : IMxWriteOps
{
public string SessionId => "sess-1";
public int ServerHandle => 100;
public int NextHandle { get; init; } = 7;
public List<string> AddItemRefs { get; } = new();
public List<MxCommandRequest> Invokes { get; } = new();
public List<int> RawWriteHandles { get; } = new();
public Func<MxCommandRequest, MxCommandReply>? InvokeResponder { get; init; }
public Task<int> AddItemAsync(string fullRef, CancellationToken ct)
{
AddItemRefs.Add(fullRef);
return Task.FromResult(NextHandle);
}
public Task<MxCommandReply> InvokeAsync(MxCommandRequest request, CancellationToken ct)
{
lock (Invokes) Invokes.Add(request);
return Task.FromResult(InvokeResponder?.Invoke(request) ?? new MxCommandReply());
}
public Task<MxCommandReply> WriteRawAsync(int itemHandle, MxValue value, int userId, CancellationToken ct)
{
RawWriteHandles.Add(itemHandle);
return Task.FromResult(new MxCommandReply());
}
}
}