Files
lmxopcua/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/DataConnectionRootPickerTests.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

212 lines
12 KiB
C#

using System.Security.Claims;
using Bunit;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.JSInterop;
using Shouldly;
using Xunit;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Pages.Clusters;
using ZB.MOM.WW.OtOpcUa.AdminUI.Components.Shared.Raw;
using ZB.MOM.WW.OtOpcUa.AdminUI.DataConnections;
using ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Uns;
using ZB.MOM.WW.OtOpcUa.AdminUI.Uns;
using ZB.MOM.WW.OtOpcUa.Commons.Interfaces;
using ZB.MOM.WW.OtOpcUa.Commons.Types;
using ZB.MOM.WW.OtOpcUa.Configuration.Entities;
using ZB.MOM.WW.OtOpcUa.Configuration.Enums;
using ZB.MOM.WW.OtOpcUa.Configuration.Validation;
using ZB.MOM.WW.OtOpcUa.Security.Auth;
namespace ZB.MOM.WW.OtOpcUa.AdminUI.Tests.Pages;
/// <summary>#1077: the export-root / remote-root fields are cluster-scoped tree pickers.</summary>
[Trait("Category", "Unit")]
public sealed class DataConnectionRootPickerTests : BunitContext
{
private const string Cluster = RawTreeTestDb.ClusterId;
private sealed class NoDiagnostics : IFleetDiagnosticsClient
{
public Task<NodeDiagnosticsSnapshot> GetDiagnosticsAsync(NodeId nodeId, CancellationToken ct) => throw new NotSupportedException();
}
private sealed class PrincipalState : AuthenticationStateProvider
{
public override Task<AuthenticationState> GetAuthenticationStateAsync() => Task.FromResult(
new AuthenticationState(new ClaimsPrincipal(new ClaimsIdentity([new(ClaimTypes.Name, "fixture"), new(ClaimTypes.Role, "Administrator")], "fixture"))));
}
public DataConnectionRootPickerTests()
{
// Node-pick mode never mutates or lazy-loads, so RawTree's mutation dialogs are stubbed and its service refuses any call.
var names = new HashSet<string> { "DriverConfigModal", "DeviceModal", "RawTagModal", "RawManualTagEntryModal", "RawCsvImportModal", "RawCsvExportModal", "RawBrowseModal", "RawNameDialog", "RawConfirmDialog", "RawDriverTypeDialog", "RawStubModal" };
ComponentFactories.AddStub(type => names.Contains(type.Name));
Services.AddSingleton(System.Reflection.DispatchProxy.Create<IRawTreeService, RefusingRawService>());
JSInterop.Mode = JSRuntimeMode.Loose;
JSInterop.Setup<bool>("otDialog.activate", _ => true).SetResult(true); // ModalFrame closes itself when activation is refused.
}
public class RefusingRawService : System.Reflection.DispatchProxy
{
protected override object? Invoke(System.Reflection.MethodInfo? method, object?[]? args) => throw new NotSupportedException("Node-pick mode must not call " + method?.Name);
}
private string? _dbName;
private IRenderedComponent<CascadingValue<Task<AuthenticationState>>> RenderPage()
{
Services.RemoveAll<IAuthorizationService>();
Services.RemoveAll<IAuthorizationPolicyProvider>();
Services.AddAuthorizationCore(o => o.AddPolicy(AdminUiPolicies.ConfigEditor, p => p.RequireRole("Administrator", "Designer")));
Services.AddCascadingAuthenticationState();
Services.AddSingleton<AuthenticationStateProvider>(new PrincipalState());
Services.AddSingleton<IFleetDiagnosticsClient>(new NoDiagnostics());
var name = _dbName = RawTreeTestDb.SeedFresh();
using (var db = RawTreeTestDb.CreateNamed(name))
{
db.UnsAreas.Add(new UnsArea { UnsAreaId = "AREA-1", ClusterId = Cluster, Name = "Packaging" });
db.UnsLines.Add(new UnsLine { UnsLineId = "LINE-1", UnsAreaId = "AREA-1", Name = "Line one" });
// Another cluster's entities must be unreachable from this cluster's pickers.
db.ServerClusters.Add(new ServerCluster { ClusterId = "OTHER", Name = "Other", Enterprise = "zb", Site = "x", RedundancyMode = RedundancyMode.None, CreatedBy = "test" });
db.UnsAreas.Add(new UnsArea { UnsAreaId = "AREA-OTHER", ClusterId = "OTHER", Name = "Foreign area" });
db.DataConnections.Add(new DataConnection { DataConnectionId = "CONN-1", ClusterId = Cluster, ExpectedClusterId = "OTHER" });
db.SaveChanges();
}
Services.AddSingleton(RawTreeTestDb.Factory(name));
Services.AddSingleton<DataConnectionAdminService>();
var state = new PrincipalState().GetAuthenticationStateAsync();
return Render<CascadingValue<Task<AuthenticationState>>>(p => p.Add(x => x.Value, state)
.AddChildContent<ClusterDataConnections>(c => c.Add(x => x.ClusterId, Cluster)));
}
[Fact]
public void ExportRoot_RawTreePicker_PicksADeviceAndFillsTheField()
{
var cut = RenderPage();
cut.WaitForAssertion(() => cut.Find("button.btn-primary:contains('New export')"));
cut.Find("button:contains('New export')").Click();
cut.WaitForAssertion(() => cut.Find("#export-root"));
cut.Find("#export-root").GetAttribute("value").ShouldBe("No root chosen");
cut.Find("#export-root-browse").Click();
// A dialog opened by a click renders on a later pass.
cut.WaitForAssertion(() => cut.Find("[role=dialog]"));
cut.WaitForAssertion(() => cut.FindAll("input[type=radio]").Count.ShouldBeGreaterThan(0));
cut.Find("#root-picker-confirm").HasAttribute("disabled").ShouldBeTrue();
// Expand down to the device: cluster root is open; folder -> driver -> device.
cut.Find("button[aria-label='Expand PLCs']").Click();
cut.WaitForElement("button[aria-label='Expand modbus-1']").Click();
cut.WaitForElement("input[title='Device dev:" + RawTreeTestDb.FolderedDeviceId + "']").Change(true);
cut.WaitForAssertion(() => cut.Find("#root-picker-selected").TextContent.ShouldBe("RawDevice " + RawTreeTestDb.FolderedDeviceId));
cut.Find("#root-picker-confirm").Click();
cut.WaitForAssertion(() => cut.Find("#export-root").GetAttribute("value").ShouldBe("RawDevice " + RawTreeTestDb.FolderedDeviceId));
cut.FindAll("[role=dialog]").Count.ShouldBe(0);
}
[Fact]
public void ExportRoot_UnsTreePicker_IsClusterScopedAndPicksAnArea()
{
var cut = RenderPage();
cut.WaitForElement("button:contains('New export')").Click();
cut.WaitForElement("#export-realm").Change("Uns");
cut.Find("#export-root-browse").Click();
cut.WaitForAssertion(() => cut.Find("[role=dialog]"));
cut.WaitForAssertion(() => cut.FindAll(".uns-root-picker input[type=radio]").Count.ShouldBeGreaterThan(0));
cut.Markup.ShouldContain("Packaging");
cut.Find("[role=dialog]").InnerHtml.ShouldNotContain("Foreign area");
cut.Find("input[title='UnsArea AREA-1']").Change(true);
cut.Find("#root-picker-confirm").Click();
cut.WaitForAssertion(() => cut.Find("#export-root").GetAttribute("value").ShouldBe("UnsArea AREA-1"));
}
[Fact]
public void RemoteRoot_PickerBrowsesTheTargetClusterOnly_AndFillsTheRootId()
{
var cut = RenderPage();
cut.WaitForElement("button:contains('New mapping')").Click();
cut.WaitForElement("#remote-root-browse").HasAttribute("disabled").ShouldBeTrue(); // no connection chosen yet
cut.Find("#mapping-connection").Change("CONN-1");
cut.Find("#mapping-realm").Change("Uns");
cut.Find("#remote-root-browse").HasAttribute("disabled").ShouldBeFalse();
cut.Find("#remote-root-browse").Click();
cut.WaitForElement("[role=dialog]");
cut.WaitForAssertion(() => cut.FindAll(".uns-root-picker input[type=radio]").Count.ShouldBeGreaterThan(0));
cut.Find("[role=dialog]").InnerHtml.ShouldContain("Foreign area");
cut.Find("[role=dialog]").InnerHtml.ShouldNotContain("Packaging");
cut.Find("input[title='UnsArea AREA-OTHER']").Change(true);
cut.Find("#root-picker-confirm").Click();
cut.WaitForAssertion(() => cut.Find("#remote-root").GetAttribute("value").ShouldBe("AREA-OTHER"));
}
/// <summary>#1084: the export editor's secured-write opt-in is offered only with the Write grant and is saved to the row.</summary>
[Fact]
public void Export_SecuredWritesCheckbox_RequiresWrite_AndIsSaved()
{
var cut = RenderPage();
cut.WaitForElement("button:contains('New export')").Click();
cut.WaitForElement("#export-secured-writes").HasAttribute("disabled").ShouldBeTrue("a new export has no Write grant");
cut.Find("#export-id").Change("EXP-SW");
cut.Find("#principal").Change("peer-principal");
cut.Find("#export-root-id").Change("RawDevice|" + RawTreeTestDb.FolderedDeviceId);
cut.FindAll("fieldset label").Single(l => l.TextContent.Trim() == "Write").QuerySelector("input")!.Change(true);
cut.WaitForAssertion(() => cut.Find("#export-secured-writes").HasAttribute("disabled").ShouldBeFalse());
cut.Find("#export-secured-writes").Change(true);
cut.Find("button:contains('Save draft')").Click();
cut.WaitForAssertion(() => cut.Markup.ShouldContain("Draft saved"));
using var db = RawTreeTestDb.CreateNamed(_dbName!);
var saved = db.DataExports.Single(x => x.DataExportId == "EXP-SW");
saved.AllowSecuredWrites.ShouldBeTrue();
saved.AllowedOperations.HasFlag(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataOperations.Write).ShouldBeTrue();
}
[Fact]
public void Cancel_LeavesTheFieldUnchanged()
{
var cut = RenderPage();
cut.WaitForElement("button:contains('New export')").Click();
cut.WaitForElement("#export-root-browse").Click();
cut.WaitForAssertion(() => cut.Find("[role=dialog]"));
cut.Find("[role=dialog] .modal-footer button:contains('Cancel')").Click();
cut.WaitForAssertion(() => cut.FindAll("[role=dialog]").Count.ShouldBe(0));
cut.Find("#export-root").GetAttribute("value").ShouldBe("No root chosen");
}
[Fact]
public void RawTree_NodePickMode_OffersARadioOnEveryEntityKind_AndLeavesTagPickerModeAlone()
{
var tag = new RawNode { Kind = RawNodeKind.Tag, Key = "tag:t", EntityId = "t", DisplayName = "T" };
var device = new RawNode { Kind = RawNodeKind.Device, Key = "dev:d", EntityId = "d", DisplayName = "D", Expanded = true };
device.Children.Add(tag);
RawNode? picked = null;
var cut = Render<RawTree>(p => p.Add(x => x.Roots, new[] { device }).Add(x => x.NodePickMode, true)
.Add(x => x.OnNodePicked, n => picked = n));
cut.FindAll("input[type=radio]").Count.ShouldBe(2);
cut.Find("input[title='Device dev:d']").Change(true);
picked.ShouldBeSameAs(device);
// The tag picker mode is unchanged: a checkbox on tags only, no radios.
var multi = Render<RawTree>(p => p.Add(x => x.Roots, new[] { device }).Add(x => x.PickerMode, true).Add(x => x.SelectedTagIds, new HashSet<string>()));
multi.FindAll("input[type=radio]").Count.ShouldBe(0);
multi.FindAll("input[type=checkbox]").Count.ShouldBe(1);
}
[Fact]
public async Task Trees_AreClusterScoped_AndNestFoldersGroupsAndTags()
{
var name = RawTreeTestDb.SeedFresh();
using var db = RawTreeTestDb.CreateNamed(name);
var snapshot = await DraftSnapshotFactory.FromConfigDbAsync(db, CancellationToken.None);
var raw = DataRootTrees.BuildRaw(snapshot, Cluster);
raw.Children.Select(c => c.EntityId).ShouldContain(RawTreeTestDb.RootFolderId);
var group = raw.Children.Single(c => c.EntityId == RawTreeTestDb.RootFolderId).Children.Single().Children.Single().Children.Single();
group.Kind.ShouldBe(RawNodeKind.TagGroup);
group.Children.Select(c => c.EntityId).ShouldBe([RawTreeTestDb.HistorizedTagId, RawTreeTestDb.PlainTagId], ignoreOrder: true);
DataRootTrees.BuildRaw(snapshot, "NOPE").Children.ShouldBeEmpty();
DataRootTrees.BuildRaw(snapshot, Cluster, includeTags: false).Children.SelectMany(Flatten).ShouldNotContain(n => n.Kind == RawNodeKind.Tag);
}
private static IEnumerable<RawNode> Flatten(RawNode n) => new[] { n }.Concat(n.Children.SelectMany(Flatten));
}