Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Layout/NavMenuTests.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

160 lines
6.2 KiB
C#

using System.Security.Claims;
using Bunit;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Rendering;
using Microsoft.Extensions.DependencyInjection;
using ZB.MOM.WW.ScadaBridge.Security;
using NavMenu = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Layout.NavMenu;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Layout;
/// <summary>
/// bUnit rendering tests for the sidebar <see cref="NavMenu"/>. They verify the
/// collapsible section behaviour (sections collapsed by default, a toggle
/// reveals a section's items and persists state to a cookie) and that the
/// Notifications section's items are gated per-policy. The
/// <c>AuthorizeView Policy=...</c> blocks evaluate the real policies, which
/// require a claim of type <see cref="JwtTokenService.RoleClaimType"/> (the
/// canonical <c>ZbClaimTypes.Role</c> framework URI), so the test principal
/// carries claims of that exact type.
/// </summary>
public class NavMenuTests : BunitContext
{
public NavMenuTests()
{
// NavMenu reads the nav-collapse cookie via the navState.get JS interop
// call in OnAfterRenderAsync and writes it via navState.set on toggle.
// Loose mode lets navState.get no-op (returns null) so the sidebar
// renders collapsed, and still records navState.set invocations.
JSInterop.Mode = JSRuntimeMode.Loose;
}
/// <summary>
/// Renders <see cref="NavMenu"/> under a principal holding the given roles.
/// <see cref="NavMenu"/>'s top-level <c>AuthorizeView</c> requires the
/// cascading <see cref="AuthenticationState"/>, so it is rendered inside a
/// <see cref="CascadingAuthenticationState"/>; the real policies are
/// registered so the per-item <c>AuthorizeView Policy=...</c> blocks are
/// genuinely evaluated.
/// </summary>
private IRenderedComponent<NavMenu> RenderWithRoles(params string[] roles)
{
var claims = new List<Claim> { new(JwtTokenService.UsernameClaimType, "tester") };
claims.AddRange(roles.Select(r => new Claim(JwtTokenService.RoleClaimType, r)));
var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"));
Services.AddSingleton<AuthenticationStateProvider>(new TestAuthStateProvider(user));
Services.AddAuthorizationCore();
AuthorizationPolicies.AddScadaBridgeAuthorization(Services);
// BunitContext pre-registers a placeholder IAuthorizationService that
// throws when AuthorizeView evaluates a policy. Force the real service
// so the per-item policy gating is genuinely exercised.
Services.AddSingleton<IAuthorizationService, DefaultAuthorizationService>();
var host = Render<CascadingAuthenticationState>(parameters => parameters
.Add(p => p.ChildContent, (RenderFragment)(builder =>
{
builder.OpenComponent<NavMenu>(0);
builder.CloseComponent();
})));
return host.FindComponent<NavMenu>();
}
/// <summary>
/// Clicks the collapsible section header whose title matches, expanding it.
/// </summary>
private static void ExpandSection(IRenderedComponent<NavMenu> cut, string title)
{
var toggle = cut.FindAll("button.nav-section-toggle")
.Single(b => b.TextContent.Contains(title, StringComparison.Ordinal));
toggle.Click();
}
[Fact]
public void Sections_AreCollapsedByDefault()
{
var cut = RenderWithRoles("Administrator", "Designer", "Deployer");
cut.WaitForAssertion(() =>
{
// Section headers render unconditionally...
Assert.Contains(">Notifications<", cut.Markup);
Assert.Contains(">Deployment<", cut.Markup);
// ...but their items stay out of the DOM until the section opens.
Assert.DoesNotContain("/notifications/smtp", cut.Markup);
Assert.DoesNotContain("/deployment/topology", cut.Markup);
});
}
[Fact]
public void TogglingSection_RevealsItsItems()
{
var cut = RenderWithRoles("Deployer");
Assert.DoesNotContain("/deployment/topology", cut.Markup);
ExpandSection(cut, "Deployment");
Assert.Contains("/deployment/topology", cut.Markup);
Assert.Contains("/deployment/deployments", cut.Markup);
Assert.Contains("/deployment/debug-view", cut.Markup);
}
[Fact]
public void TogglingSection_PersistsStateToCookie()
{
var cut = RenderWithRoles("Deployer");
ExpandSection(cut, "Deployment");
// Expanding wrote the cookie through the navState.set JS interop call.
var invocation = JSInterop.Invocations.Last(i => i.Identifier == "navState.set");
Assert.Equal("deployment", invocation.Arguments[0]);
}
[Fact]
public void NotificationsSection_ShowsAllItems_ForMultiRoleUser()
{
var cut = RenderWithRoles("Administrator", "Designer", "Deployer");
ExpandSection(cut, "Notifications");
cut.WaitForAssertion(() =>
{
Assert.Contains("Notifications", cut.Markup);
Assert.Contains("/notifications/smtp", cut.Markup);
Assert.Contains("/notifications/lists", cut.Markup);
Assert.Contains("/notifications/report", cut.Markup);
Assert.Contains("/notifications/kpis", cut.Markup);
});
}
[Fact]
public void NotificationsSection_AdminOnlyUser_SeesOnlySmtp()
{
var cut = RenderWithRoles("Administrator");
ExpandSection(cut, "Notifications");
cut.WaitForAssertion(() =>
{
Assert.Contains("/notifications/smtp", cut.Markup);
Assert.DoesNotContain("/notifications/report", cut.Markup);
Assert.DoesNotContain("/notifications/lists", cut.Markup);
Assert.DoesNotContain("/notifications/kpis", cut.Markup);
});
}
[Fact]
public void OldRoutes_AreNoLongerLinked()
{
var cut = RenderWithRoles("Administrator", "Designer", "Deployer");
cut.WaitForAssertion(() =>
{
Assert.DoesNotContain("/admin/smtp", cut.Markup);
Assert.DoesNotContain("/monitoring/notification-outbox", cut.Markup);
});
}
}