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;
///
/// #1084 — a secured (caller-identity) write over a gRPC data connection needs BOTH the origin export's opt-in
/// (DataExport.AllowSecuredWrites) AND the Galaxy driver's MxAccess.SecuredWritesOverDataConnections.
/// Driven end to end through the runtime write path: a deployed artifact → the compiled export catalog → the real
/// executor (admission) → the real → the
/// behind the real dispatch gate → a real GalaxyDriver (#1091 outcomes).
///
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");
}
}
/// #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.
[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();
}
/// #1084: the flag rides the artifact; on a deployed row without the Write grant it fails closed.
[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(() => 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();
}
/// The export's AllowSecuredWrites; null omits the field (a pre-#1084 artifact).
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());
}
/// Stands in for 's rich-write routing: hands the routed write to the one child.
private sealed class RichRouteForwarder : ReceiveActor
{
public RichRouteForwarder(IActorRef child) =>
Receive(msg =>
child.Forward(new DriverInstanceActor.WriteAttributeWithOutcome(msg.Ticket, msg.Claim)));
}
}