Files
lmxopcua/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverWriteOutcomeTests.cs
T
Joseph Doherty 8e2a793000 feat(grpc-data): #1084 secured writes over a data connection need an export-level opt-in; #1091 Galaxy reports gRPC write outcomes definitively
#1084 - DataExport.AllowSecuredWrites (default false; migration AddDataExportAllowSecuredWrites, a bit NOT NULL DEFAULT 0
column, no constraint => no MigrationPreChecks twin; the preflight's legacy-schema tolerance covers the missing column).
- Valid only with Write: validator code DataExportSecuredWriteInvalid at authoring, the deploy gate and on a deployed
  row (an artifact row breaking it fails closed), modelled on AllowGalaxyServiceAck.
- LocalExportCatalog keeps it per rule (counts only with Write) and answers AllowsSecuredWrite(principal, node): an
  export of the principal, in the node's realm, granting Write, opted in, whose root contains the node.
- DataWriteExecutor stamps DataWriteAdmission.AllowsSecuredWrite (new, default false) from the catalog generation that
  admitted the write (re-checked by the dispatch gate's commit), never from the request.
- DriverInstanceActor.RichCaller returns null without it, so the driver gets NO caller: the driver option
  MxAccess.SecuredWritesOverDataConnections alone no longer lets a forwarding consumer cluster's link key write
  SecuredWrite attributes. Fail closed by default.
- AdminUI export editor: "Allow secured writes under this peer's key identity" checkbox (enabled only with Write).

#1091 (a) - GalaxyDriver implements IWriteOutcomeCapability + ICallerAwareWriteOutcomeCapability. GalaxyWriteOutcomes
maps BadUserAccessDenied and the OnWriteComplete verdicts BadNotWritable/BadTypeMismatch/BadOutOfRange/
BadConfigurationError to DriverConfirmedFailure, Good to AcceptedUnconfirmed (a provisional Good is indistinguishable),
everything else to OutcomeUnknown. A refused secured write is now a definite BadUserAccessDenied, not OutcomeUnknown.
- RunRichWriteAsync precedence: caller-aware outcome overload (caller present) -> outcome overload -> ICallerAwareWritable
  (caller present) -> IWritable. Both earlier behaviours kept; the OPC UA path is unchanged.

Tests (each failed before its fix where applicable):
- End to end through the runtime path (artifact -> catalog -> DataWriteRuntime executor -> ActorDataWriteRoute ->
  DriverInstanceActor behind the real dispatch gate -> real GalaxyDriver): export opt-in x driver option matrix; only
  both commit as the key's identity, either alone refuses BadUserAccessDenied definitively with no identity lookup.
  Ignoring the flag in RichCaller fails 3 tests.
- Catalog scope (root containment, Write, principal), artifact round-trip + fail-closed row, validator, migration SQL +
  no pending model changes, AdminUI checkbox enable/save (bUnit), actor precedence, Galaxy outcome mapping.
- ScriptForeignKeysAndExternalIdUniquenessMigrationTests now migrate to THEIR migration, not the latest.

Docs: DataConnections.md (two-gate table), Galaxy.md, security.md, rules/drivers.md.
2026-12-04 14:58:16 -05:00

125 lines
6.7 KiB
C#

using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
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>
/// #1091 — the Galaxy driver reports gRPC data-connection writes through <see cref="IWriteOutcomeCapability"/> (and its
/// caller-aware overload), so a refused secured write is a definite <see cref="DataWriteState.DriverConfirmedFailure"/> +
/// <c>BadUserAccessDenied</c> instead of the legacy path's <c>OutcomeUnknown</c>; only verdict-only statuses are definite.
/// </summary>
public sealed class GalaxyDriverWriteOutcomeTests
{
[Theory]
[InlineData(StatusCodeMap.Good, DataWriteState.AcceptedUnconfirmed)]
[InlineData(StatusCodeMap.BadUserAccessDenied, DataWriteState.DriverConfirmedFailure)]
[InlineData(StatusCodeMap.BadNotWritable, DataWriteState.DriverConfirmedFailure)]
[InlineData(StatusCodeMap.BadTypeMismatch, DataWriteState.DriverConfirmedFailure)]
[InlineData(StatusCodeMap.BadOutOfRange, DataWriteState.DriverConfirmedFailure)]
[InlineData(StatusCodeMap.BadConfigurationError, DataWriteState.DriverConfirmedFailure)]
[InlineData(StatusCodeMap.BadCommunicationError, DataWriteState.OutcomeUnknown)]
[InlineData(StatusCodeMap.BadTimeout, DataWriteState.OutcomeUnknown)]
[InlineData(StatusCodeMap.BadInternalError, DataWriteState.OutcomeUnknown)]
[InlineData(StatusCodeMap.BadOutOfService, DataWriteState.OutcomeUnknown)]
[InlineData(StatusCodeMap.Uncertain, DataWriteState.OutcomeUnknown)]
[InlineData(StatusCodeMap.Bad, DataWriteState.OutcomeUnknown)]
public void A_write_result_maps_to_a_definite_outcome_only_for_a_verdict_status(uint status, DataWriteState expected)
{
var outcome = GalaxyWriteOutcomes.From(new WriteResult(status));
outcome.State.ShouldBe(expected);
outcome.StatusCode.ShouldBe(status, "the status rides the outcome unchanged");
}
[Fact]
public async Task A_secured_write_with_no_caller_is_reported_as_a_definite_access_refusal()
{
var (driver, writer) = Build(overDataConnections: true);
var outcomes = await driver.WriteWithOutcomesAsync([new WriteRequest("Plant/Tank1/SP", 1.0)],
TestContext.Current.CancellationToken);
var outcome = outcomes.ShouldHaveSingleItem();
outcome.State.ShouldBe(DataWriteState.DriverConfirmedFailure);
outcome.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied);
writer.Sources.ShouldHaveSingleItem().ShouldBeNull("no caller ⇒ no identity source");
}
[Fact]
public async Task The_caller_overload_follows_the_same_origin_rules_as_the_legacy_one()
{
var (driver, writer) = Build(overDataConnections: false);
var caller = new WriteCaller("svc-mes", "0a1b2c3d4e5f6071", WriteCallerOrigin.DataConnection);
var refused = await driver.WriteWithOutcomesAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], caller,
TestContext.Current.CancellationToken);
refused.ShouldHaveSingleItem().State.ShouldBe(DataWriteState.DriverConfirmedFailure,
"a data-connection caller gets no identity without MxAccess.SecuredWritesOverDataConnections");
var (optedIn, optedInWriter) = Build(overDataConnections: true);
var written = await optedIn.WriteWithOutcomesAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], caller,
TestContext.Current.CancellationToken);
written.ShouldHaveSingleItem().State.ShouldBe(DataWriteState.AcceptedUnconfirmed);
optedInWriter.Sources.ShouldHaveSingleItem().ShouldNotBeNull("positive control: the opted-in driver writes as the key");
writer.Sources.ShouldHaveSingleItem().ShouldBeNull();
}
[Fact]
public async Task Outcomes_keep_request_order_for_a_mixed_batch()
{
var (driver, _) = Build(overDataConnections: true, statuses: [StatusCodeMap.Good, StatusCodeMap.BadCommunicationError, StatusCodeMap.BadNotWritable]);
var outcomes = await driver.WriteWithOutcomesAsync(
[new WriteRequest("Plant/Tank1/SP", 1.0), new WriteRequest("Plant/Tank1/SP", 2.0), new WriteRequest("Plant/Tank1/SP", 3.0)],
TestContext.Current.CancellationToken);
outcomes.Select(o => o.State).ShouldBe(
[DataWriteState.AcceptedUnconfirmed, DataWriteState.OutcomeUnknown, DataWriteState.DriverConfirmedFailure]);
}
private static (GalaxyDriver Driver, SecuredWriter Writer) Build(bool overDataConnections, uint[]? statuses = null)
{
var writer = new SecuredWriter(statuses);
var options = new GalaxyDriverOptions(
new GalaxyGatewayOptions("https://mxgw.test:5001", "key"),
new GalaxyMxAccessOptions("OtOpcUa-A")
{
SecuredWrites = GalaxySecuredWriteMode.ApiKeyIdentity,
SecuredWritesOverDataConnections = overDataConnections,
},
new GalaxyRepositoryOptions(WatchDeployEvents: false),
new GalaxyReconnectOptions())
{
RawTags = [new RawTagEntry("Plant/Tank1/SP", """{"attributeRef":"Tank1.SP"}""", false)],
};
return (new GalaxyDriver("g", options, hierarchySource: null, dataWriter: writer,
ackCredentialResolver: FixedAckCredentialResolver.Fallback()), writer);
}
/// <summary>Like the real writer for a SecuredWrite tag: refuses <c>BadUserAccessDenied</c> without an identity source;
/// with one (or with canned <paramref name="statuses"/>) answers per request.</summary>
private sealed class SecuredWriter(uint[]? statuses) : IGalaxyDataWriter
{
public List<Func<CancellationToken, Task<GalaxyAckCredentialResolution>>?> Sources { get; } = [];
public Task<IReadOnlyList<WriteResult>> WriteAsync(IReadOnlyList<WriteRequest> writes,
Func<string, SecurityClassification> securityResolver, CancellationToken cancellationToken)
=> ((IGalaxyDataWriter)this).WriteAsync(writes, securityResolver, null, cancellationToken);
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>>(statuses is not null
? [.. statuses.Select(s => new WriteResult(s))]
: [.. writes.Select(_ => new WriteResult(securedCredential is null ? StatusCodeMap.BadUserAccessDenied : StatusCodeMap.Good))]);
}
public void InvalidateHandleCaches() { }
}
}