Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/GalaxyDriverPageFormSerializationTests.cs
T
Joseph Doherty 29ad36c028 feat(galaxy): #1074 secured writes over gRPC data connections are a separate opt-in, default off
- WriteCaller gains an additive Origin (WriteCallerOrigin: Unspecified (default) | OpcUaSession | DataConnection),
  stamped by the runtime at the receiving seam: OtOpcUaNodeManager -> OpcUaSession, the rich (gRPC data-connection)
  write path -> DataConnection. Never parsed from the principal/key.
- New driver-config option MxAccess.SecuredWritesOverDataConnections (default false; factory key
  mxAccess.securedWritesOverDataConnections; AdminUI "Also for gRPC data-connection writes", owned path). The
  Galaxy driver gives a caller an identity source only in ApiKeyIdentity mode AND for an allowed origin:
  OpcUaSession always, DataConnection only with the option, Unspecified never (fail closed). Off => a secured write
  over a data connection is refused exactly as before #1074 (local BadUserAccessDenied, no identity lookup; the gRPC
  caller sees the same OutcomeUnknown as before).
- Tests: option off refuses a gRPC write end to end into the real GalaxyDriver (with an OPC UA positive control on
  the same driver); option-on end-to-end kept; driver-level origin matrix incl. Unspecified; factory binding; AdminUI
  round-trip; node-manager callers now carry OpcUaSession.
- Docs: Galaxy.md (origin table, opt-in, forwarded-write delegation caveat, live-gate leg), security.md,
  DataConnections.md, Configuration.md, rules/drivers.md.
2026-12-03 16:51:26 -05:00

426 lines
19 KiB
C#

using System.Text.Json;
using System.Text.Json.Serialization;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Drivers.Forms;
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests;
public sealed class GalaxyDriverPageFormSerializationTests
{
// Matches GalaxyDriverForm._jsonOpts (camelCase, no PropertyNameCaseInsensitive).
private static readonly JsonSerializerOptions _opts = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
WriteIndented = false,
};
// Matches the page's _jsonOpts exactly: camelCase + case-insensitive read + UnmappedMemberHandling.Skip.
private static readonly JsonSerializerOptions _pageOpts = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
PropertyNameCaseInsensitive = true,
UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip,
WriteIndented = false,
};
[Fact]
public void RoundTrip_PreservesKnownFields()
{
var original = new GalaxyDriverOptions(
Gateway: new GalaxyGatewayOptions(
Endpoint: "https://gw.internal:5001",
ApiKeySecretRef: "env:MY_API_KEY",
UseTls: true,
CaCertificatePath: "C:\\certs\\ca.pem",
ConnectTimeoutSeconds: 15,
DefaultCallTimeoutSeconds: 45,
StreamTimeoutSeconds: 0),
MxAccess: new GalaxyMxAccessOptions(
ClientName: "OtOpcUa-Primary",
PublishingIntervalMs: 500,
WriteUserId: 1,
EventPumpChannelCapacity: 100_000),
Repository: new GalaxyRepositoryOptions(
DiscoverPageSize: 2000,
WatchDeployEvents: false),
Reconnect: new GalaxyReconnectOptions(
InitialBackoffMs: 1000,
MaxBackoffMs: 60_000,
ReplayOnSessionLost: false))
{
ProbeTimeoutSeconds = 45,
};
var json = JsonSerializer.Serialize(original, _opts);
var back = JsonSerializer.Deserialize<GalaxyDriverOptions>(json, _opts);
back.ShouldNotBeNull();
back.Gateway.Endpoint.ShouldBe("https://gw.internal:5001");
back.Gateway.ApiKeySecretRef.ShouldBe("env:MY_API_KEY");
back.Gateway.UseTls.ShouldBeTrue();
back.Gateway.CaCertificatePath.ShouldBe("C:\\certs\\ca.pem");
back.Gateway.ConnectTimeoutSeconds.ShouldBe(15);
back.Gateway.DefaultCallTimeoutSeconds.ShouldBe(45);
back.Gateway.StreamTimeoutSeconds.ShouldBe(0);
back.MxAccess.ClientName.ShouldBe("OtOpcUa-Primary");
back.MxAccess.PublishingIntervalMs.ShouldBe(500);
back.MxAccess.WriteUserId.ShouldBe(1);
back.MxAccess.EventPumpChannelCapacity.ShouldBe(100_000);
back.Repository.DiscoverPageSize.ShouldBe(2000);
back.Repository.WatchDeployEvents.ShouldBeFalse();
back.Reconnect.InitialBackoffMs.ShouldBe(1000);
back.Reconnect.MaxBackoffMs.ShouldBe(60_000);
back.Reconnect.ReplayOnSessionLost.ShouldBeFalse();
back.ProbeTimeoutSeconds.ShouldBe(45);
}
[Fact]
public void Deserialize_DropsUnknownFields()
{
// Minimal JSON that sets only ProbeTimeoutSeconds and an unknown field.
// The nested records must supply their required positional args for JSON deserialization
// to succeed — provide them here so the test exercises the Unknown-field skip path.
var jsonWithExtra = """
{
"unknownField": "old-value",
"gateway": { "endpoint": "https://localhost:5001", "apiKeySecretRef": "dev:test" },
"mxAccess": { "clientName": "OtOpcUa" },
"repository": {},
"reconnect": {},
"probeTimeoutSeconds": 20
}
""";
var optsWithSkip = new JsonSerializerOptions(_opts)
{
UnmappedMemberHandling = JsonUnmappedMemberHandling.Skip,
};
var back = JsonSerializer.Deserialize<GalaxyDriverOptions>(jsonWithExtra, optsWithSkip);
back.ShouldNotBeNull();
back.ProbeTimeoutSeconds.ShouldBe(20);
back.Gateway.Endpoint.ShouldBe("https://localhost:5001");
}
/// <summary>
/// Regression test: the seed SQL stores PascalCase JSON. With
/// <c>PropertyNameCaseInsensitive = true</c> the page must read the real values, not
/// fall back to defaults. FAILS against case-sensitive opts; PASSES with the fix.
/// </summary>
[Fact]
public void Seeded_pascalcase_config_loads_real_values()
{
// Exact JSON from docker-dev/seed/seed-clusters.sql (lines 130-151).
var seededJson = """
{
"Gateway": {
"Endpoint": "http://10.100.0.48:5120",
"ApiKeySecretRef": "env:GALAXY_MXGW_API_KEY",
"UseTls": false,
"ConnectTimeoutSeconds": 10,
"DefaultCallTimeoutSeconds": 30
},
"MxAccess": {
"ClientName": "OtOpcUa-MAIN-docker-dev",
"PublishingIntervalMs": 1000
},
"Repository": {
"DiscoverPageSize": 5000,
"WatchDeployEvents": true
},
"Reconnect": {
"InitialBackoffMs": 500,
"MaxBackoffMs": 30000,
"ReplayOnSessionLost": true
}
}
""";
// Deserialize with page-mirrored opts (camelCase + case-insensitive, as fixed).
var driverOpts = JsonSerializer.Deserialize<GalaxyDriverOptions>(seededJson, _pageOpts);
driverOpts.ShouldNotBeNull();
var form = GalaxyDriverForm.GalaxyFormModel.FromRecord(driverOpts!);
// Assert REAL seeded values — not defaults.
form.GatewayEndpoint.ShouldBe("http://10.100.0.48:5120");
form.GatewayApiKeySecretRef.ShouldBe("env:GALAXY_MXGW_API_KEY");
form.GatewayUseTls.ShouldBeFalse();
form.MxClientName.ShouldBe("OtOpcUa-MAIN-docker-dev");
form.RepositoryDiscoverPageSize.ShouldBe(5000);
form.ReconnectInitialBackoffMs.ShouldBe(500);
}
/// <summary>
/// Defence-in-depth: a config that genuinely OMITS a section (no Reconnect key at all)
/// must not throw — <see cref="GalaxyDriverForm.GalaxyFormModel.FromRecord"/> must
/// null-coalesce the missing section to its default value.
/// </summary>
[Fact]
public void FromRecord_with_omitted_section_uses_defaults()
{
// Only gateway section present — Reconnect intentionally absent.
var partialJson = """
{
"gateway": {
"endpoint": "opc://x",
"apiKeySecretRef": "env:K"
}
}
""";
var driverOpts = JsonSerializer.Deserialize<GalaxyDriverOptions>(partialJson, _pageOpts);
driverOpts.ShouldNotBeNull();
// FromRecord must not throw even though Reconnect (and other sections) is null.
var form = Should.NotThrow(() => GalaxyDriverForm.GalaxyFormModel.FromRecord(driverOpts!));
// Omitted Reconnect section falls back to GalaxyReconnectOptions() defaults.
var defaultRc = new GalaxyReconnectOptions();
form.ReconnectInitialBackoffMs.ShouldBe(defaultRc.InitialBackoffMs);
form.ReconnectMaxBackoffMs.ShouldBe(defaultRc.MaxBackoffMs);
form.ReconnectReplayOnSessionLost.ShouldBe(defaultRc.ReplayOnSessionLost);
}
/// <summary>
/// Confirms that <see cref="GalaxyDriverForm.GalaxyFormModel.FromRecord"/> still
/// round-trips correctly when all nested records are populated (non-regressed path).
/// </summary>
[Fact]
public void FromRecord_with_fully_populated_options_round_trips()
{
var original = new GalaxyDriverOptions(
Gateway: new GalaxyGatewayOptions(
Endpoint: "https://gw.example.com:5001",
ApiKeySecretRef: "env:MY_KEY",
UseTls: true,
CaCertificatePath: null,
ConnectTimeoutSeconds: 12,
DefaultCallTimeoutSeconds: 40,
StreamTimeoutSeconds: 0),
MxAccess: new GalaxyMxAccessOptions(
ClientName: "OtOpcUa-Test",
PublishingIntervalMs: 750,
WriteUserId: 2,
EventPumpChannelCapacity: 25_000),
Repository: new GalaxyRepositoryOptions(
DiscoverPageSize: 3000,
WatchDeployEvents: false),
Reconnect: new GalaxyReconnectOptions(
InitialBackoffMs: 800,
MaxBackoffMs: 45_000,
ReplayOnSessionLost: false))
{
ProbeTimeoutSeconds = 20,
};
var form = GalaxyDriverForm.GalaxyFormModel.FromRecord(original);
form.GatewayEndpoint.ShouldBe("https://gw.example.com:5001");
form.GatewayApiKeySecretRef.ShouldBe("env:MY_KEY");
form.GatewayUseTls.ShouldBeTrue();
form.GatewayConnectTimeoutSeconds.ShouldBe(12);
form.GatewayDefaultCallTimeoutSeconds.ShouldBe(40);
form.MxClientName.ShouldBe("OtOpcUa-Test");
form.MxPublishingIntervalMs.ShouldBe(750);
form.MxWriteUserId.ShouldBe(2);
form.MxEventPumpChannelCapacity.ShouldBe(25_000);
form.RepositoryDiscoverPageSize.ShouldBe(3000);
form.RepositoryWatchDeployEvents.ShouldBeFalse();
form.ReconnectInitialBackoffMs.ShouldBe(800);
form.ReconnectMaxBackoffMs.ShouldBe(45_000);
form.ReconnectReplayOnSessionLost.ShouldBeFalse();
form.ProbeTimeoutSeconds.ShouldBe(20);
}
/// <summary>
/// lmxopcua#749: the form must carry the AlarmAck fallback through FromRecord/ToRecord, or saving the
/// Galaxy driver page would silently drop the fallback account and every anonymous ack would refuse.
/// </summary>
[Fact]
public void FormModel_RoundTrips_AlarmAckFallback()
{
var original = new GalaxyDriverOptions(
new GalaxyGatewayOptions("https://gw:5001", "env:K"),
new GalaxyMxAccessOptions("OtOpcUa"),
new GalaxyRepositoryOptions(),
new GalaxyReconnectOptions())
{
AlarmAck = new GalaxyAlarmAckOptions("ack-svc", "PLANT", "secret:otopcua/galaxy/ack"),
};
var back = GalaxyDriverForm.GalaxyFormModel.FromRecord(original).ToRecord();
back.AlarmAck.ShouldBe(original.AlarmAck);
var json = JsonSerializer.Serialize(back, _pageOpts);
json.ShouldContain("\"fallbackPasswordSecretRef\":\"secret:otopcua/galaxy/ack\"");
json.ShouldNotContain("hasFallback");
JsonSerializer.Deserialize<GalaxyDriverOptions>(json, _pageOpts)!.AlarmAck.ShouldBe(original.AlarmAck);
}
/// <summary>
/// lmxopcua#869: the ack-confirmation window must survive FromRecord/ToRecord and JSON, or saving the page
/// would silently reset an operator's setting (e.g. the 0 = do-not-wait opt-out) to the default.
/// </summary>
[Fact]
public void FormModel_RoundTrips_AlarmAckConfirmTimeout()
{
var original = new GalaxyDriverOptions(
new GalaxyGatewayOptions("https://gw:5001", "env:K"),
new GalaxyMxAccessOptions("OtOpcUa"),
new GalaxyRepositoryOptions(),
new GalaxyReconnectOptions())
{
AlarmAck = new GalaxyAlarmAckOptions { ConfirmTimeoutMs = 0 },
};
var back = GalaxyDriverForm.GalaxyFormModel.FromRecord(original).ToRecord();
back.AlarmAck.ConfirmTimeoutMs.ShouldBe(0);
var json = JsonSerializer.Serialize(back, _pageOpts);
json.ShouldContain("\"confirmTimeoutMs\":0");
json.ShouldNotContain("\"confirmTimeout\":");
JsonSerializer.Deserialize<GalaxyDriverOptions>(json, _pageOpts)!.AlarmAck.ConfirmTimeoutMs.ShouldBe(0);
new GalaxyDriverForm.GalaxyFormModel().AckConfirmTimeoutMs.ShouldBe(GalaxyAlarmAckOptions.DefaultConfirmTimeoutMs);
}
/// <summary>
/// lmxopcua#1045: the HTTP/2 keep-alive knobs (#991 G-19) must survive FromRecord/ToRecord, or saving the
/// Galaxy driver page silently resets an operator's setting (e.g. the 0 = no-pings opt-out) to the default.
/// </summary>
[Fact]
public void FormModel_RoundTrips_KeepAlivePings()
{
var original = new GalaxyDriverOptions(
new GalaxyGatewayOptions("https://gw:5001", "env:K", KeepAlivePingDelaySeconds: 0, KeepAlivePingTimeoutSeconds: 7),
new GalaxyMxAccessOptions("OtOpcUa"),
new GalaxyRepositoryOptions(),
new GalaxyReconnectOptions());
var form = GalaxyDriverForm.GalaxyFormModel.FromRecord(original);
form.GatewayKeepAlivePingDelaySeconds.ShouldBe(0);
form.GatewayKeepAlivePingTimeoutSeconds.ShouldBe(7);
var back = form.ToRecord();
back.Gateway.KeepAlivePingDelaySeconds.ShouldBe(0);
back.Gateway.KeepAlivePingTimeoutSeconds.ShouldBe(7);
var defaults = new GalaxyGatewayOptions("e", "k");
var fresh = new GalaxyDriverForm.GalaxyFormModel();
fresh.GatewayKeepAlivePingDelaySeconds.ShouldBe(defaults.KeepAlivePingDelaySeconds);
fresh.GatewayKeepAlivePingTimeoutSeconds.ShouldBe(defaults.KeepAlivePingTimeoutSeconds);
}
/// <summary>
/// lmxopcua#1045: a key the form does not model (a newer option, a hand-edited key) must survive a save —
/// the form overlays only the paths it owns onto the stored JSON instead of re-serialising the typed record.
/// </summary>
[Fact]
public void Serialize_preserves_unmodelled_keys_and_overwrites_owned_ones()
{
var stored = """
{
"Gateway": { "Endpoint": "http://old:5120", "ApiKeySecretRef": "env:GALAXY_MXGW_API_KEY", "FutureGatewayKnob": 42 },
"MxAccess": { "ClientName": "OtOpcUa-A" },
"Repository": {},
"Reconnect": {},
"futureTopLevel": "keep-me"
}
""";
var opts = JsonSerializer.Deserialize<GalaxyDriverOptions>(stored, _pageOpts)!;
var form = GalaxyDriverForm.GalaxyFormModel.FromRecord(opts);
form.GatewayEndpoint = "http://new:5120";
form.GatewayKeepAlivePingDelaySeconds = 0;
var json = GalaxyDriverForm.Serialize(form.ToRecord(), stored);
var root = System.Text.Json.Nodes.JsonNode.Parse(json)!.AsObject();
root["futureTopLevel"]!.GetValue<string>().ShouldBe("keep-me");
var gw = root["Gateway"]!.AsObject();
gw["FutureGatewayKnob"]!.GetValue<int>().ShouldBe(42);
gw["endpoint"]!.GetValue<string>().ShouldBe("http://new:5120");
gw.ContainsKey("Endpoint").ShouldBeFalse();
gw["keepAlivePingDelaySeconds"]!.GetValue<int>().ShouldBe(0);
var back = JsonSerializer.Deserialize<GalaxyDriverOptions>(json, _pageOpts)!;
back.Gateway.Endpoint.ShouldBe("http://new:5120");
back.Gateway.KeepAlivePingDelaySeconds.ShouldBe(0);
back.MxAccess.ClientName.ShouldBe("OtOpcUa-A");
}
/// <summary>
/// #1017: <c>MxAccess.SecuredWrites</c> round-trips through the form and is saved as a STRING the driver
/// factory parses (it refuses an unknown value, and a numeric enum would be unknown).
/// </summary>
[Fact]
public void FormModel_RoundTrips_SecuredWrites_as_a_string()
{
var original = new GalaxyDriverOptions(
new GalaxyGatewayOptions("https://gw:5001", "env:K"),
new GalaxyMxAccessOptions("OtOpcUa") { SecuredWrites = GalaxySecuredWriteMode.ApiKeyIdentity },
new GalaxyRepositoryOptions(),
new GalaxyReconnectOptions());
var form = GalaxyDriverForm.GalaxyFormModel.FromRecord(original);
form.MxSecuredWrites.ShouldBe(GalaxySecuredWriteMode.ApiKeyIdentity);
new GalaxyDriverForm.GalaxyFormModel().MxSecuredWrites.ShouldBe(GalaxySecuredWriteMode.Refuse);
var json = GalaxyDriverForm.Serialize(form.ToRecord(), originalJson: null);
json.ShouldContain("\"securedWrites\":\"ApiKeyIdentity\"");
JsonSerializer.Deserialize<GalaxyDriverOptions>(json, new JsonSerializerOptions(_pageOpts) { Converters = { new JsonStringEnumConverter() } })!
.MxAccess.SecuredWrites.ShouldBe(GalaxySecuredWriteMode.ApiKeyIdentity);
}
/// <summary>
/// #1074: <c>MxAccess.SecuredWritesOverDataConnections</c> defaults off and round-trips through the form under
/// the camelCase key the driver factory reads.
/// </summary>
[Fact]
public void FormModel_RoundTrips_SecuredWritesOverDataConnections()
{
new GalaxyDriverForm.GalaxyFormModel().MxSecuredWritesOverDataConnections.ShouldBeFalse();
var original = new GalaxyDriverOptions(
new GalaxyGatewayOptions("https://gw:5001", "env:K"),
new GalaxyMxAccessOptions("OtOpcUa")
{ SecuredWrites = GalaxySecuredWriteMode.ApiKeyIdentity, SecuredWritesOverDataConnections = true },
new GalaxyRepositoryOptions(),
new GalaxyReconnectOptions());
var form = GalaxyDriverForm.GalaxyFormModel.FromRecord(original);
form.MxSecuredWritesOverDataConnections.ShouldBeTrue();
var json = GalaxyDriverForm.Serialize(form.ToRecord(), originalJson: null);
json.ShouldContain("\"securedWritesOverDataConnections\":true");
JsonSerializer.Deserialize<GalaxyDriverOptions>(json, new JsonSerializerOptions(_pageOpts) { Converters = { new JsonStringEnumConverter() } })!
.MxAccess.SecuredWritesOverDataConnections.ShouldBeTrue();
}
/// <summary>
/// lmxopcua#1045 guard: every leaf the form's record serialises must be an owned path, or an edit to it is
/// silently discarded by the overlay on save (<c>rawTags</c> is authored elsewhere and deliberately not owned).
/// </summary>
[Fact]
public void Every_serialised_leaf_is_an_owned_path()
{
var json = GalaxyDriverForm.Serialize(new GalaxyDriverForm.GalaxyFormModel().ToRecord(), originalJson: null);
var leaves = new List<string>();
void Walk(System.Text.Json.Nodes.JsonObject o, string prefix)
{
foreach (var (k, v) in o)
{
var path = prefix.Length == 0 ? k : $"{prefix}.{k}";
if (v is System.Text.Json.Nodes.JsonObject child) Walk(child, path);
else leaves.Add(path);
}
}
Walk(System.Text.Json.Nodes.JsonNode.Parse(json)!.AsObject(), "");
leaves.ShouldContain("gateway.keepAlivePingDelaySeconds");
leaves.Where(l => l != "rawTags")
.Except(GalaxyDriverForm.OwnedPaths, StringComparer.OrdinalIgnoreCase)
.ShouldBeEmpty();
}
}