feat(auth): ScadaBridge CentralUI pages onto IInboundApiKeyAdmin seam (re-arch C3; string keyId, method-scopes replace ApprovedApiKeyIds, token-once display, approved-keys<->scopes inversion)
This commit is contained in:
@@ -3,30 +3,37 @@ using Bunit;
|
||||
using Microsoft.AspNetCore.Components;
|
||||
using Microsoft.AspNetCore.Components.Authorization;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.JSInterop;
|
||||
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. The chip
|
||||
/// routes operators into the central Audit Log pre-filtered by Actor = ApiKey.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.
|
||||
/// 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("Username", "admin"),
|
||||
@@ -38,16 +45,21 @@ public class ApiKeyFormAuditDrillinTests : BunitContext
|
||||
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()
|
||||
{
|
||||
var key = ApiKey.FromHash("Orders-Integration", "k-hash");
|
||||
key.Id = 11;
|
||||
_repo.GetApiKeyByIdAsync(11, Arg.Any<CancellationToken>()).Returns(key);
|
||||
_repo.GetAllApiMethodsAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<ApiMethod>>(new List<ApiMethod>()));
|
||||
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.Id, 11));
|
||||
var cut = Render<ApiKeyForm>(p => p.Add(c => c.KeyId, keyId));
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
{
|
||||
@@ -62,6 +74,9 @@ public class ApiKeyFormAuditDrillinTests : BunitContext
|
||||
[Fact]
|
||||
public void CreatePage_HasNoRecentAuditActivityLink()
|
||||
{
|
||||
_admin.ListAsync(Arg.Any<CancellationToken>())
|
||||
.Returns(Task.FromResult<IReadOnlyList<InboundApiKeyInfo>>(Array.Empty<InboundApiKeyInfo>()));
|
||||
|
||||
var cut = Render<ApiKeyForm>();
|
||||
|
||||
cut.WaitForAssertion(() =>
|
||||
@@ -69,4 +84,56 @@ public class ApiKeyFormAuditDrillinTests : BunitContext
|
||||
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>());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
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("Username", "admin"),
|
||||
new Claim(JwtTokenService.RoleClaimType, "Admin"),
|
||||
};
|
||||
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>());
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
using ZB.MOM.WW.ScadaBridge.CentralUI.Services;
|
||||
|
||||
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Inbound-API key re-arch (C3): unit tests for <see cref="ApiMethodKeyScopeReconciler"/>, which
|
||||
/// inverts the API-method form's "Approved API Keys" selection into per-key method-scope edits.
|
||||
/// Covers approve, revoke (preserving other scopes), the empty-last-scope guard, and the no-op case.
|
||||
/// </summary>
|
||||
public sealed class ApiMethodKeyScopeReconcilerTests
|
||||
{
|
||||
private static IReadOnlyDictionary<string, IReadOnlyList<string>> Current(
|
||||
params (string KeyId, string[] Methods)[] entries) =>
|
||||
entries.ToDictionary(
|
||||
e => e.KeyId,
|
||||
e => (IReadOnlyList<string>)e.Methods.ToList(),
|
||||
StringComparer.Ordinal);
|
||||
|
||||
private static IReadOnlyDictionary<string, string> Names(params (string KeyId, string Name)[] entries) =>
|
||||
entries.ToDictionary(e => e.KeyId, e => e.Name, StringComparer.Ordinal);
|
||||
|
||||
[Fact]
|
||||
public void Approve_AddsMethodToKey_PreservingExistingScopes()
|
||||
{
|
||||
var result = ApiMethodKeyScopeReconciler.Reconcile(
|
||||
methodName: "PlaceOrder",
|
||||
selectedKeyIds: new HashSet<string> { "k1" },
|
||||
initialKeyIds: new HashSet<string>(),
|
||||
currentMethodsByKey: Current(("k1", new[] { "GetStatus" })),
|
||||
keyNamesById: Names(("k1", "Key One")));
|
||||
|
||||
Assert.Empty(result.EmptyScopeKeyNames);
|
||||
var update = Assert.Single(result.Updates);
|
||||
Assert.Equal("k1", update.KeyId);
|
||||
Assert.Equal(new[] { "GetStatus", "PlaceOrder" }, update.NewMethods);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Approve_KeyWithNoExistingScopes_GetsJustThisMethod()
|
||||
{
|
||||
var result = ApiMethodKeyScopeReconciler.Reconcile(
|
||||
methodName: "PlaceOrder",
|
||||
selectedKeyIds: new HashSet<string> { "k1" },
|
||||
initialKeyIds: new HashSet<string>(),
|
||||
currentMethodsByKey: Current(("k1", Array.Empty<string>())),
|
||||
keyNamesById: Names(("k1", "Key One")));
|
||||
|
||||
var update = Assert.Single(result.Updates);
|
||||
Assert.Equal(new[] { "PlaceOrder" }, update.NewMethods);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Revoke_RemovesMethod_LeavingOtherScopesIntact()
|
||||
{
|
||||
var result = ApiMethodKeyScopeReconciler.Reconcile(
|
||||
methodName: "PlaceOrder",
|
||||
selectedKeyIds: new HashSet<string>(),
|
||||
initialKeyIds: new HashSet<string> { "k1" },
|
||||
currentMethodsByKey: Current(("k1", new[] { "PlaceOrder", "GetStatus" })),
|
||||
keyNamesById: Names(("k1", "Key One")));
|
||||
|
||||
Assert.Empty(result.EmptyScopeKeyNames);
|
||||
var update = Assert.Single(result.Updates);
|
||||
Assert.Equal("k1", update.KeyId);
|
||||
Assert.Equal(new[] { "GetStatus" }, update.NewMethods);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Revoke_LastScope_ReportedAsEmptyConflict_AndNotInUpdates()
|
||||
{
|
||||
var result = ApiMethodKeyScopeReconciler.Reconcile(
|
||||
methodName: "PlaceOrder",
|
||||
selectedKeyIds: new HashSet<string>(),
|
||||
initialKeyIds: new HashSet<string> { "k1" },
|
||||
currentMethodsByKey: Current(("k1", new[] { "PlaceOrder" })),
|
||||
keyNamesById: Names(("k1", "Key One")));
|
||||
|
||||
Assert.Empty(result.Updates);
|
||||
var emptyName = Assert.Single(result.EmptyScopeKeyNames);
|
||||
Assert.Equal("Key One", emptyName);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Mixed_ApproveOneRevokeAnother_ProducesBothUpdates()
|
||||
{
|
||||
var result = ApiMethodKeyScopeReconciler.Reconcile(
|
||||
methodName: "PlaceOrder",
|
||||
selectedKeyIds: new HashSet<string> { "k2" }, // approve k2
|
||||
initialKeyIds: new HashSet<string> { "k1" }, // revoke k1
|
||||
currentMethodsByKey: Current(
|
||||
("k1", new[] { "PlaceOrder", "GetStatus" }),
|
||||
("k2", new[] { "Ping" })),
|
||||
keyNamesById: Names(("k1", "Key One"), ("k2", "Key Two")));
|
||||
|
||||
Assert.Empty(result.EmptyScopeKeyNames);
|
||||
Assert.Equal(2, result.Updates.Count);
|
||||
|
||||
var k1 = result.Updates.Single(u => u.KeyId == "k1");
|
||||
Assert.Equal(new[] { "GetStatus" }, k1.NewMethods);
|
||||
|
||||
var k2 = result.Updates.Single(u => u.KeyId == "k2");
|
||||
Assert.Equal(new[] { "Ping", "PlaceOrder" }, k2.NewMethods);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void NoChange_ProducesNoUpdates()
|
||||
{
|
||||
var result = ApiMethodKeyScopeReconciler.Reconcile(
|
||||
methodName: "PlaceOrder",
|
||||
selectedKeyIds: new HashSet<string> { "k1" },
|
||||
initialKeyIds: new HashSet<string> { "k1" },
|
||||
currentMethodsByKey: Current(("k1", new[] { "PlaceOrder" })),
|
||||
keyNamesById: Names(("k1", "Key One")));
|
||||
|
||||
Assert.Empty(result.Updates);
|
||||
Assert.Empty(result.EmptyScopeKeyNames);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user