Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/DataConnectionFormTests.cs
T
Joseph Doherty b104760b3a feat(auth)!: ScadaBridge canonical roles + SoD collapse (Audit→Administrator, AuditReadOnly→Viewer) + config-DB migration (Task 1.7)
Standardize role string VALUES on the canonical vocabulary
(Administrator/Designer/Deployer/Viewer; Operator/Engineer unused here):
  Admin        -> Administrator
  Design       -> Designer
  Deployment   -> Deployer
  Audit        -> Administrator   (COLLAPSE; accepted privilege escalation)
  AuditReadOnly-> Viewer          (COLLAPSE; keeps audit-read, no export)

SoD: OperationalAuditRoles = { Administrator, Viewer },
     AuditExportRoles      = { Administrator }
so Viewer reads the audit log + nav but cannot bulk-export, while
Administrator does both + holds the full admin surface (the documented,
accepted auditor/admin SoD collapse).

Atomic move across every enforcement site:
- Roles constants; AuthorizationPolicies (RequireClaim values + SoD arrays +
  honest XML-doc); RoleMapper Deployer check.
- ManagementActor.GetRequiredRole switch + the hard-coded site-scope
  admin-bypass (now Roles.Administrator at all 6 sites). Site-scoping logic
  is otherwise unchanged.
- DebugStreamHub Administrator/Deployer gates (Deployer kept case-sensitive).
- CentralUI BrowseService/BindingTester Designer guards; LdapMappingForm
  dropdown now offers canonical values (incl. Viewer).
- Config-DB seed (LdapGroupMappings Id 1-4) + EF migration CanonicalizeRoles:
  Id-keyed UpdateData for seed rows + idempotent raw catch-all UPDATEs for
  operator-added rows. Down is lossy on the collapse (documented in-file).
  No pending model changes.

Tests reworked to the collapsed model across Security/CentralUI/
ManagementService/ConfigurationDatabase/Integration suites, incl. explicit
Viewer-reads-not-exports and former-Audit-now-Administrator-escalation cases.

CHANGELOG: BREAKING security note documenting the canonicalization + SoD
collapse.
2026-06-02 08:00:47 -04:00

156 lines
6.1 KiB
C#

using System.Security.Claims;
using ZB.MOM.WW.ScadaBridge.Security;
using System.Text.Json;
using Bunit;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using DataConnectionForm = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Design.DataConnectionForm;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests;
public class DataConnectionFormTests : BunitContext
{
private readonly ISiteRepository _siteRepo = Substitute.For<ISiteRepository>();
public DataConnectionFormTests()
{
Services.AddSingleton(_siteRepo);
AddTestAuth();
var sites = new List<Site> { new("Plant-A", "plant-a") { Id = 1 } };
_siteRepo.GetAllSitesAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<Site>>(sites));
}
private void AddTestAuth()
{
var claims = new[]
{
new Claim(JwtTokenService.UsernameClaimType, "tester"),
new Claim(JwtTokenService.RoleClaimType, "Administrator")
};
var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"));
Services.AddSingleton<AuthenticationStateProvider>(new TestAuthStateProvider(user));
Services.AddAuthorizationCore();
}
private IRenderedComponent<DataConnectionForm> RenderForCreateSite(int siteId)
{
Services.GetRequiredService<NavigationManager>()
.NavigateTo($"/admin/connections/create?siteId={siteId}");
return Render<DataConnectionForm>();
}
[Fact]
public void ProtocolDropdown_IsRendered_OnCreate_WithBothProtocols()
{
var cut = RenderForCreateSite(1);
var labels = cut.FindAll("label").Select(l => l.TextContent.Trim()).ToList();
Assert.Contains(labels, l => l == "Protocol");
// The protocol select offers OPC UA and MxGateway.
var optionTexts = cut.FindAll("option").Select(o => o.TextContent.Trim()).ToList();
Assert.Contains("OPC UA", optionTexts);
Assert.Contains("MxGateway", optionTexts);
}
[Fact]
public async Task Save_MxGateway_PersistsTypedJsonAndProtocolMxGateway()
{
DataConnection? captured = null;
await _siteRepo.AddDataConnectionAsync(
Arg.Do<DataConnection>(d => captured = d));
var cut = RenderForCreateSite(1);
// Switch protocol to MxGateway — re-renders with the MxGateway editor.
cut.FindAll("select")
.First(s => s.QuerySelectorAll("option").Any(o => o.TextContent.Trim() == "MxGateway"))
.Change("MxGateway");
// Name (skip readonly Site plaintext input; MxGateway editor inputs carry placeholders).
cut.FindAll("input[type='text']")
.First(i => !i.HasAttribute("readonly") && i.GetAttribute("placeholder") is null)
.Change("MX-1");
// Gateway endpoint
cut.FindAll("input[type='text']")
.First(i => i.GetAttribute("placeholder")?.StartsWith("http://") == true)
.Change("http://gw:5000");
// API key (password input)
cut.FindAll("input[type='password']")
.First(i => i.GetAttribute("placeholder")?.Contains("API key") == true)
.Change("secret");
await cut.FindAll("button")
.First(b => b.TextContent.Trim() == "Save").ClickAsync(new());
Assert.NotNull(captured);
Assert.Equal("MxGateway", captured!.Protocol);
Assert.NotNull(captured.PrimaryConfiguration);
using var doc = JsonDocument.Parse(captured.PrimaryConfiguration!);
Assert.Equal("http://gw:5000",
doc.RootElement.GetProperty("endpoint").GetString());
}
[Fact]
public async Task Save_InvalidPrimaryUrl_DoesNotCallRepo()
{
var cut = RenderForCreateSite(1);
cut.FindAll("input[type='text']")
.First(i => i.GetAttribute("placeholder")?.StartsWith("opc.tcp") == true)
.Change("not-a-url");
// Name field (the first editable text input that is NOT the OPC URL).
// Site renders as a readonly plaintext input when locked — skip it.
cut.FindAll("input[type='text']")
.First(i => !i.HasAttribute("readonly")
&& (i.GetAttribute("placeholder") is null
|| !i.GetAttribute("placeholder")!.StartsWith("opc.tcp")))
.Change("My Connection");
await cut.FindAll("button")
.First(b => b.TextContent.Trim() == "Save").ClickAsync(new());
await _siteRepo.DidNotReceive().AddDataConnectionAsync(Arg.Any<DataConnection>());
Assert.Contains("Endpoint URL must be a valid", cut.Markup);
}
[Fact]
public async Task Save_ValidConfig_PersistsTypedJsonAndProtocolOpcUa()
{
DataConnection? captured = null;
await _siteRepo.AddDataConnectionAsync(
Arg.Do<DataConnection>(d => captured = d));
var cut = RenderForCreateSite(1);
// Name (skip readonly Site plaintext input)
cut.FindAll("input[type='text']")
.First(i => !i.HasAttribute("readonly")
&& (i.GetAttribute("placeholder") is null
|| !i.GetAttribute("placeholder")!.StartsWith("opc.tcp")))
.Change("PLC-1");
// Endpoint URL
cut.FindAll("input[type='text']")
.First(i => i.GetAttribute("placeholder")?.StartsWith("opc.tcp") == true)
.Change("opc.tcp://plant-a:4840");
await cut.FindAll("button")
.First(b => b.TextContent.Trim() == "Save").ClickAsync(new());
Assert.NotNull(captured);
Assert.Equal("OpcUa", captured!.Protocol);
Assert.NotNull(captured.PrimaryConfiguration);
using var doc = JsonDocument.Parse(captured.PrimaryConfiguration!);
Assert.Equal("opc.tcp://plant-a:4840",
doc.RootElement.GetProperty("endpointUrl").GetString());
Assert.Equal(60000,
doc.RootElement.GetProperty("sessionTimeoutMs").GetInt32());
}
}