Files
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

140 lines
6.1 KiB
C#

using System.Security.Claims;
using Bunit;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.Extensions.DependencyInjection;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.Commons.Entities.InboundApi;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Security;
using ZB.MOM.WW.ScadaBridge.Security;
using ApiKeyForm = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Admin.ApiKeyForm;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Admin;
/// <summary>
/// Bundle D drill-in test (#23 M7-T12) for the API Keys edit page, re-wired for the
/// inbound-API-key re-arch (C3) onto the <see cref="IInboundApiKeyAdmin"/> seam. The chip
/// routes operators into the central Audit Log pre-filtered by Actor = key Name AND
/// Channel = ApiInbound (no other channel uses the key name as actor, but the explicit
/// channel scope keeps deep links tight). Create mode suppresses the link — there's no API
/// key to drill into yet. Also covers the new seam-driven list and one-time-token panel.
/// </summary>
public class ApiKeyFormAuditDrillinTests : BunitContext
{
private readonly IInboundApiKeyAdmin _admin = Substitute.For<IInboundApiKeyAdmin>();
private readonly IInboundApiRepository _repo = Substitute.For<IInboundApiRepository>();
public ApiKeyFormAuditDrillinTests()
{
Services.AddSingleton(_admin);
Services.AddSingleton(_repo);
// Methods still come from the SQL Server repository; default to none unless a test overrides.
_repo.GetAllApiMethodsAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<ApiMethod>>(new List<ApiMethod>()));
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 = true, params string[] methods) =>
new(keyId, name, enabled, methods, DateTimeOffset.UnixEpoch, null);
[Fact]
public void EditPage_HasRecentAuditActivityLink_WithActorAndApiInboundChannel()
{
const string keyId = "abc123def456";
var info = Key(keyId, "Orders-Integration", true, "PlaceOrder");
_admin.ListAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<InboundApiKeyInfo>>(new[] { info }));
_admin.GetMethodsForKeyAsync(keyId, Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<string>>(new[] { "PlaceOrder" }));
var cut = Render<ApiKeyForm>(p => p.Add(c => c.KeyId, keyId));
cut.WaitForAssertion(() =>
{
var link = cut.Find("a[data-test=\"audit-link\"]");
Assert.Equal(
"/audit/log?actor=Orders-Integration&channel=ApiInbound",
link.GetAttribute("href"));
Assert.Contains("Recent audit activity", link.TextContent);
});
}
[Fact]
public void CreatePage_HasNoRecentAuditActivityLink()
{
_admin.ListAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<InboundApiKeyInfo>>(Array.Empty<InboundApiKeyInfo>()));
var cut = Render<ApiKeyForm>();
cut.WaitForAssertion(() =>
{
Assert.Empty(cut.FindAll("a[data-test=\"audit-link\"]"));
});
}
[Fact]
public async Task CreatePage_WithMethodSelected_ShowsOneTimeTokenAndKeyId()
{
_admin.ListAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<InboundApiKeyInfo>>(Array.Empty<InboundApiKeyInfo>()));
_repo.GetAllApiMethodsAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<ApiMethod>>(
new List<ApiMethod> { new("PlaceOrder", "return null;") { Id = 1 } }));
_admin.CreateAsync("MES-Production", Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>())
.Returns(Task.FromResult(new InboundApiKeyCreated("new-key-id", "sbk_new-key-id_secret")));
var cut = Render<ApiKeyForm>();
// Fill name, check the only method, save.
cut.WaitForElement("input[type=text]").Change("MES-Production");
cut.Find("#method-access-1").Change(true);
await cut.Find("button.btn-success").ClickAsync(new());
cut.WaitForAssertion(() =>
{
var token = cut.Find("[data-test=\"created-token\"]");
Assert.Contains("sbk_new-key-id_secret", token.TextContent);
Assert.Contains("new-key-id", cut.Markup);
Assert.Contains("will not be shown again", cut.Markup);
});
await _admin.Received(1).CreateAsync(
"MES-Production",
Arg.Is<IReadOnlyCollection<string>>(m => m.Count == 1 && m.Contains("PlaceOrder")),
Arg.Any<CancellationToken>());
}
[Fact]
public async Task CreatePage_WithNoMethodSelected_ShowsValidationError_AndDoesNotCreate()
{
_admin.ListAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<InboundApiKeyInfo>>(Array.Empty<InboundApiKeyInfo>()));
_repo.GetAllApiMethodsAsync(Arg.Any<CancellationToken>())
.Returns(Task.FromResult<IReadOnlyList<ApiMethod>>(
new List<ApiMethod> { new("PlaceOrder", "return null;") { Id = 1 } }));
var cut = Render<ApiKeyForm>();
cut.WaitForElement("input[type=text]").Change("MES-Production");
await cut.Find("button.btn-success").ClickAsync(new());
cut.WaitForAssertion(() =>
Assert.Contains("at least one API method", cut.Markup));
await _admin.DidNotReceive().CreateAsync(
Arg.Any<string>(), Arg.Any<IReadOnlyCollection<string>>(), Arg.Any<CancellationToken>());
}
}