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

96 lines
3.8 KiB
C#

using System.Security.Claims;
using Bunit;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.CentralUI.Components.Shared;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Security;
using ZB.MOM.WW.ScadaBridge.Security;
using ApiKeys = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Admin.ApiKeys;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Admin;
/// <summary>
/// Inbound-API key re-arch (C3): the API Keys list page now reads keys from the
/// <see cref="IInboundApiKeyAdmin"/> seam (string KeyId + method-scopes) instead of the SQL
/// Server ApiKey entity. There is no retrievable hash, so the old masked Key-Hash column is gone.
/// </summary>
public class ApiKeysListPageTests : BunitContext
{
private readonly IInboundApiKeyAdmin _admin = Substitute.For<IInboundApiKeyAdmin>();
public ApiKeysListPageTests()
{
Services.AddSingleton(_admin);
Services.AddSingleton<IDialogService>(Substitute.For<IDialogService>());
var claims = new[]
{
new Claim(JwtTokenService.UsernameClaimType, "admin"),
new Claim(JwtTokenService.RoleClaimType, "Administrator"),
};
var user = new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"));
Services.AddSingleton<AuthenticationStateProvider>(new TestAuthStateProvider(user));
Services.AddAuthorizationCore();
AuthorizationPolicies.AddScadaBridgeAuthorization(Services);
}
private static InboundApiKeyInfo Key(
string keyId, string name, bool enabled, params string[] methods) =>
new(keyId, name, enabled, methods, DateTimeOffset.UnixEpoch, null);
[Fact]
public void List_RendersKeysFromSeam_WithNoKeyHashColumn()
{
_admin.ListAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<InboundApiKeyInfo>>(new[]
{
Key("aaaaaaaaaaaa1111", "Orders-Integration", true, "PlaceOrder", "GetStatus"),
Key("bbbbbbbbbbbb2222", "Disabled-Key", false, "Ping"),
}));
var cut = Render<ApiKeys>();
cut.WaitForAssertion(() =>
{
// Both key names render.
Assert.Contains("Orders-Integration", cut.Markup);
Assert.Contains("Disabled-Key", cut.Markup);
// The disabled key carries the Disabled badge.
Assert.Contains("Disabled", cut.Markup);
// No Key-Hash column header.
var headers = cut.FindAll("th").Select(h => h.TextContent.Trim()).ToList();
Assert.DoesNotContain(headers, h => h.Contains("Hash", StringComparison.OrdinalIgnoreCase));
Assert.Contains(headers, h => h == "Key ID");
Assert.Contains(headers, h => h == "Methods");
// KeyId renders truncated (first 12 chars + ellipsis), not the full value.
Assert.Contains("aaaaaaaaaaaa…", cut.Markup);
// The Methods column shows the per-key scope count (2 for the first key).
var cells = cut.FindAll("td").Select(c => c.TextContent.Trim()).ToList();
Assert.Contains("2", cells);
});
}
[Fact]
public async Task ToggleKey_CallsSetEnabledOnSeam()
{
_admin.ListAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<InboundApiKeyInfo>>(new[]
{
Key("aaaaaaaaaaaa1111", "Orders-Integration", true, "PlaceOrder"),
}));
var cut = Render<ApiKeys>();
// The dropdown's first item toggles enabled state (currently enabled -> Disable).
var disableButton = cut.WaitForElement("button.dropdown-item");
await disableButton.ClickAsync(new());
await _admin.Received(1).SetEnabledAsync("aaaaaaaaaaaa1111", false, Arg.Any<CancellationToken>());
}
}