Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSecuredWriteExportTests.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

176 lines
12 KiB
C#

using System.Text;
using System.Text.Json.Nodes;
using Akka.Actor;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections;
using ZB.MOM.WW.OtOpcUa.Core.Authorization;
using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections;
using ZB.MOM.WW.OtOpcUa.Runtime.Drivers;
using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy;
namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections;
/// <summary>
/// #1084 — a secured (caller-identity) write over a gRPC data connection needs BOTH the origin export's opt-in
/// (<c>DataExport.AllowSecuredWrites</c>) AND the Galaxy driver's <c>MxAccess.SecuredWritesOverDataConnections</c>.
/// Driven end to end through the runtime write path: a deployed artifact → the compiled export catalog → the real
/// <see cref="DataWriteRuntime"/> executor (admission) → the real <see cref="ActorDataWriteRoute"/> → the
/// <see cref="DriverInstanceActor"/> behind the real dispatch gate → a real <c>GalaxyDriver</c> (#1091 outcomes).
/// </summary>
public sealed partial class GrpcDataDriverOutcomeTests
{
[Theory]
[InlineData(true, true)]
[InlineData(false, true)]
[InlineData(true, false)]
public async Task A_secured_write_over_a_data_connection_needs_both_the_export_opt_in_and_the_driver_option(
bool exportOptIn, bool driverOption)
{
var ct = TestContext.Current.CancellationToken;
var clock = TimeProvider.System;
var fence = new DataWriteDispatchFence();
var authority = new DataPlaneAuthorityState(fence);
var activation = new CatalogActivation(fence);
var role = new RedundancyRoleView(fence);
role.PublishPrimaryRole(true);
var serving = new ServingIdentity("node-a", "serving", "Primary", 0, 0);
var coordinator = new LocalCatalogCoordinator(activation, authority, () => serving);
var bytes = SecuredWriteArtifact(exportOptIn);
var attempt = coordinator.BeginAttempt("catalog-revision");
coordinator.InstallAuthority(attempt, DeploymentArtifact.ParseDataPlaneAuthority(bytes, "node-a")).ShouldBeTrue();
using (var parsed = DeploymentArtifact.Open(bytes))
coordinator.Stage(attempt, parsed.ParseLocalCatalogSnapshot("node-a")!, "node-a").ShouldBeTrue();
coordinator.Complete(attempt, true).ShouldBeTrue();
var catalog = coordinator.Current.ShouldNotBeNull();
var node = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag");
var key = authority.Current.FindUsableKey("peer-key", clock.GetUtcNow().UtcDateTime).ShouldNotBeNull();
var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000,
TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1));
var capabilities = new DataCapabilitiesProvider("cluster", () => coordinator.Current!.Serving, () => true, limits);
var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, clock), clock);
var bounds = new DriverWriteBounds(TimeSpan.FromSeconds(5));
var runtime = new DataWriteRuntime(coordinator, activation, authority, policy, capabilities, role, clock, bounds,
"serving", 16, 16_384, 16_384, 4, TimeSpan.FromMinutes(1));
var writer = new GalaxyIdentityRecordingWriter();
var resolver = new KeyIdentityResolver();
var galaxy = new ZB.MOM.WW.OtOpcUa.Driver.Galaxy.GalaxyDriver("driver", GalaxyOptions(driverOption),
hierarchySource: null, dataWriter: writer, ackCredentialResolver: resolver);
var actor = Connect(new GalaxyWriteHost(galaxy), runtime.Gate, runtime.Observer, writeClock: clock,
writeRouteState: runtime.Routes);
var incarnation = runtime.Routes.CurrentDriverIncarnation("driver").ShouldNotBeNull();
runtime.Routes.Publish(node.Metadata.View, "driver", "Plant/Tank1/SP", incarnation);
var host = Sys.ActorOf(Props.Create(() => new RichRouteForwarder(actor)));
var context = new DataAuthenticatedContext("peer", "peer-key", DataCallerIdentity.CredentialVersionFor(key),
null, catalog.AuthorityEpoch);
var results = await runtime.ForCaller(context, () => host).WriteAsync(new WriteBatch(
[new WriteItem("c1", "secured-op", node.Metadata.View, DataValue.FromScalar(DataValueKind.Int32, 7),
catalog.Serving.CatalogEpoch, "serving", TimeSpan.FromSeconds(30))],
new DataBudget(TimeSpan.FromSeconds(30), 8, 64_000)), ct);
var outcome = results.ShouldHaveSingleItem().Outcome;
if (exportOptIn && driverOption)
{
outcome.State.ShouldBe(DataWriteState.AcceptedUnconfirmed, outcome.Diagnostic);
writer.ResolvedUsers.ShouldBe(["mes-writer"], "the secured write ran as the connection key's own Galaxy identity");
resolver.SecuredWriteKeyIds.ShouldBe(["peer-key"]);
}
else
{
outcome.State.ShouldBe(DataWriteState.DriverConfirmedFailure, outcome.Diagnostic);
outcome.StatusCode.ShouldBe(0x801F0000u, "BadUserAccessDenied, reported definitively (#1091)");
writer.Refusals.ShouldBe(1);
writer.ResolvedUsers.ShouldBeEmpty();
resolver.SecuredWriteKeyIds.ShouldBeEmpty("no identity is looked up unless both opt-ins are set");
}
}
/// <summary>#1084: the opt-in is per export and per root — only an export of the principal that grants Write AND opts in,
/// and whose root contains the node, lets a write carry the caller; another principal's export never does.</summary>
[Fact]
public void Only_an_opted_in_Write_export_whose_root_contains_the_node_allows_a_secured_write()
{
var root = JsonNode.Parse(SecuredWriteArtifact(exportOptIn: false))!.AsObject();
root["Devices"]!.AsArray().Add(JsonNode.Parse("""{"DeviceId":"device2","DriverInstanceId":"driver","Name":"Other","DeviceConfig":"{}","Enabled":true}"""));
root["Tags"]!.AsArray().Add(JsonNode.Parse("""{"TagId":"tag2","DeviceId":"device2","Name":"Level","DataType":"Int32","AccessLevel":1,"TagConfig":"{}"}"""));
root["DataExports"]!.AsArray().Add(JsonNode.Parse("""
{"DataExportId":"device-only","ClusterId":"cluster","Enabled":true,"Realm":1,"RootKind":"RawDevice","RootEntityId":"device",
"PrincipalId":"peer","AllowedOperations":8,"AllowSecuredWrites":true}
"""));
root["DataExports"]!.AsArray().Add(JsonNode.Parse("""
{"DataExportId":"other-principal","ClusterId":"cluster","Enabled":true,"Realm":1,"RootKind":"Cluster","RootEntityId":"cluster",
"PrincipalId":"other","AllowedOperations":12,"AllowSecuredWrites":true}
"""));
var catalog = Compile(Encoding.UTF8.GetBytes(root.ToJsonString()));
var inside = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag");
var outside = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag2");
catalog.AllowsSecuredWrite("peer", inside).ShouldBeTrue("the device-rooted export opts in and contains the tag");
catalog.AllowsSecuredWrite("peer", outside).ShouldBeFalse("only the whole-realm export without the opt-in covers it");
catalog.AllowsExport("peer", outside, DataOperations.Write).ShouldBeTrue("the write itself is still admitted");
catalog.AllowsSecuredWrite("PEER", inside).ShouldBeTrue("principals compare case-insensitively, as for every grant");
catalog.AllowsSecuredWrite("stranger", inside).ShouldBeFalse();
}
/// <summary>#1084: the flag rides the artifact; on a deployed row without the Write grant it fails closed.</summary>
[Fact]
public void AllowSecuredWrites_rides_the_artifact_and_without_Write_fails_the_row_closed()
{
using (var parsed = DeploymentArtifact.Open(SecuredWriteArtifact(exportOptIn: true)))
parsed.ParseDataExports("node-a").ShouldHaveSingleItem().AllowSecuredWrites.ShouldBeTrue();
var root = JsonNode.Parse(SecuredWriteArtifact(exportOptIn: true))!.AsObject();
root["DataExports"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.Read);
using var bad = DeploymentArtifact.Open(Encoding.UTF8.GetBytes(root.ToJsonString()));
Should.Throw<InvalidDataException>(() => bad.ParseDataExports("node-a"));
using var old = DeploymentArtifact.Open(SecuredWriteArtifact(exportOptIn: null));
old.ParseDataExports("node-a").ShouldHaveSingleItem().AllowSecuredWrites.ShouldBeFalse("a pre-#1084 artifact grants none");
}
private static LocalExportCatalog Compile(byte[] bytes)
{
var fence = new DataWriteDispatchFence();
var authority = new DataPlaneAuthorityState(fence);
var coordinator = new LocalCatalogCoordinator(new CatalogActivation(fence), authority,
() => new ServingIdentity("node-a", "serving", "Primary", 0, 0));
var attempt = coordinator.BeginAttempt("catalog-revision");
coordinator.InstallAuthority(attempt, DeploymentArtifact.ParseDataPlaneAuthority(bytes, "node-a")).ShouldBeTrue();
using (var parsed = DeploymentArtifact.Open(bytes))
coordinator.Stage(attempt, parsed.ParseLocalCatalogSnapshot("node-a")!, "node-a").ShouldBeTrue();
coordinator.Complete(attempt, true).ShouldBeTrue();
return coordinator.Current.ShouldNotBeNull();
}
/// <param name="exportOptIn">The export's AllowSecuredWrites; null omits the field (a pre-#1084 artifact).</param>
private static byte[] SecuredWriteArtifact(bool? exportOptIn)
{
var root = JsonNode.Parse("""
{
"Clusters":[{"ClusterId":"cluster","Name":"Cluster","Enterprise":"ent","Site":"site","CreatedBy":"test","RedundancyMode":0,"Enabled":true}],
"Nodes":[{"NodeId":"node-a","ClusterId":"cluster","Host":"node-a","ApplicationUri":"urn:node-a","CreatedBy":"test","Enabled":true,"MaintenanceMode":false}],
"ApiKeys":[{"ApiKeyId":"peer-key","Name":"peer-key","SecretHash":"hash","Principal":"peer","Enabled":true}],
"NodeAcls":[{"NodeAclId":"acl","ClusterId":"cluster","Principal":"peer","ScopeKind":0,"PermissionFlags":16}],
"RawFolders":[{"RawFolderId":"folder","ClusterId":"cluster","Name":"Plant"}],
"DriverInstances":[{"DriverInstanceId":"driver","ClusterId":"cluster","RawFolderId":"folder","Name":"Driver","DriverType":"Modbus","DriverConfig":"{}","Enabled":true}],
"Devices":[{"DeviceId":"device","DriverInstanceId":"driver","Name":"Device","DeviceConfig":"{}","Enabled":true}],
"Tags":[{"TagId":"tag","DeviceId":"device","Name":"Speed","DataType":"Int32","AccessLevel":1,"TagConfig":"{}"}],
"TagGroups":[],"UnsAreas":[],"UnsLines":[],"Equipment":[],"UnsTagReferences":[],"VirtualTags":[],
"DataConnections":[],"RemoteNamespaceMappings":[],
"DataExports":[{"DataExportId":"raw","ClusterId":"cluster","Enabled":true,"Realm":1,"RootKind":"Cluster","RootEntityId":"cluster","PrincipalId":"peer","AllowedOperations":8}]
}
""")!.AsObject();
if (exportOptIn is { } optIn) root["DataExports"]![0]!["AllowSecuredWrites"] = optIn;
return Encoding.UTF8.GetBytes(root.ToJsonString());
}
/// <summary>Stands in for <see cref="DriverHostActor"/>'s rich-write routing: hands the routed write to the one child.</summary>
private sealed class RichRouteForwarder : ReceiveActor
{
public RichRouteForwarder(IActorRef child) =>
Receive<DriverHostActor.RouteRichWrite>(msg =>
child.Forward(new DriverInstanceActor.WriteAttributeWithOutcome(msg.Ticket, msg.Claim)));
}
}