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

167 lines
6.2 KiB
C#

using System.Security.Claims;
using Akka.Actor;
using Bunit;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.Sites;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Notification;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Notifications;
using ZB.MOM.WW.ScadaBridge.Communication;
using ZB.MOM.WW.ScadaBridge.Security;
using NotificationKpisPage = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Notifications.NotificationKpis;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Pages;
/// <summary>
/// bUnit rendering tests for the Notification KPIs page.
///
/// Testability note: <see cref="CommunicationService"/> is a concrete class with
/// non-virtual methods, so NSubstitute cannot intercept it. Both the global and
/// per-site KPI calls route through an injected <see cref="IActorRef"/> (the
/// notification-outbox proxy), so the tests wire a real, lightweight
/// <see cref="ActorSystem"/> with a scripted <see cref="ReceiveActor"/> that
/// answers both <see cref="NotificationKpiRequest"/> and
/// <see cref="PerSiteNotificationKpiRequest"/> — the same seam
/// <c>SetNotificationOutbox</c> exists for.
/// </summary>
public class NotificationKpisPageTests : BunitContext
{
private readonly ActorSystem _system = ActorSystem.Create("notif-kpis-tests");
private readonly CommunicationService _comms;
// Mutable scripted replies — individual tests can override before rendering.
private NotificationKpiResponse _kpiReply =
new("k", true, null, QueueDepth: 7, StuckCount: 2, ParkedCount: 1,
DeliveredLastInterval: 42, OldestPendingAge: TimeSpan.FromMinutes(9));
private PerSiteNotificationKpiResponse _perSiteReply =
new("p", true, null, new List<SiteNotificationKpiSnapshot>
{
new("plant-a", QueueDepth: 4, StuckCount: 1, ParkedCount: 0,
DeliveredLastInterval: 9, OldestPendingAge: TimeSpan.FromMinutes(7)),
});
public NotificationKpisPageTests()
{
_comms = new CommunicationService(
Options.Create(new CommunicationOptions()),
NullLogger<CommunicationService>.Instance);
var outbox = _system.ActorOf(Props.Create(() => new ScriptedOutboxActor(this)));
_comms.SetNotificationOutbox(outbox);
Services.AddSingleton(_comms);
var siteRepo = Substitute.For<ISiteRepository>();
siteRepo.GetAllSitesAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<Site>>(new List<Site>
{
new("Plant A", "plant-a") { Id = 1 },
new("Plant B", "plant-b") { Id = 2 },
}));
Services.AddSingleton(siteRepo);
var claims = new[]
{
new Claim(JwtTokenService.UsernameClaimType, "tester"),
new Claim(JwtTokenService.RoleClaimType, "Deployer"),
};
var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"));
Services.AddSingleton<AuthenticationStateProvider>(new TestAuthStateProvider(user));
Services.AddAuthorizationCore();
}
[Fact]
public void Page_RequiresDeploymentPolicy()
{
var attr = typeof(NotificationKpisPage)
.GetCustomAttributes(typeof(AuthorizeAttribute), true)
.Cast<AuthorizeAttribute>()
.FirstOrDefault();
Assert.NotNull(attr);
Assert.Equal(AuthorizationPolicies.RequireDeployment, attr!.Policy);
}
[Fact]
public void RendersGlobalTilesAndPerSiteRows()
{
var cut = Render<NotificationKpisPage>();
cut.WaitForAssertion(() =>
{
Assert.Contains("Queue Depth", cut.Markup);
Assert.Contains("7", cut.Markup); // global tile value
// Per-site row — site identifier "plant-a" resolves to its friendly name.
Assert.Contains("Plant A", cut.Markup);
});
}
[Fact]
public void ShowsKpiError_WhenGlobalKpiQueryFails()
{
_kpiReply = new NotificationKpiResponse(
"k", false, "kpi down", 0, 0, 0, 0, null);
var cut = Render<NotificationKpisPage>();
cut.WaitForAssertion(() => Assert.Contains("kpi down", cut.Markup));
}
[Fact]
public void ShowsPerSiteError_WhenPerSiteKpiQueryFails()
{
// Only the per-site path errors — the global KPI reply stays successful.
_perSiteReply = new PerSiteNotificationKpiResponse(
"p", false, "per-site down", new List<SiteNotificationKpiSnapshot>());
var cut = Render<NotificationKpisPage>();
cut.WaitForAssertion(() =>
{
Assert.Contains("Per-site KPIs unavailable: per-site down", cut.Markup);
// The two error paths are isolated — the global KPI alert (whose markup
// opens ">KPIs unavailable:", without the "Per-site " prefix) must not appear.
Assert.DoesNotContain(">KPIs unavailable:", cut.Markup);
});
}
[Fact]
public void ShowsPerSiteEmptyState_WhenNoSites()
{
_perSiteReply = new PerSiteNotificationKpiResponse(
"p", true, null, new List<SiteNotificationKpiSnapshot>());
var cut = Render<NotificationKpisPage>();
cut.WaitForAssertion(() => Assert.Contains("No per-site activity", cut.Markup));
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
_system.Terminate().Wait(TimeSpan.FromSeconds(5));
}
base.Dispose(disposing);
}
/// <summary>
/// Stand-in for the notification-outbox actor. Replies to each KPI message
/// type with the test's currently-scripted response.
/// </summary>
private sealed class ScriptedOutboxActor : ReceiveActor
{
public ScriptedOutboxActor(NotificationKpisPageTests test)
{
Receive<NotificationKpiRequest>(_ => Sender.Tell(test._kpiReply));
Receive<PerSiteNotificationKpiRequest>(_ => Sender.Tell(test._perSiteReply));
}
}
}