Files
ScadaBridge/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Admin/ApiKeyFormAuditDrillinTests.cs
T
Joseph Doherty 513fa1aa16 docs(tests): fix CommentChecker findings across tests/ — 13,392 → 0 (repo-wide scan clean)
Comment/XML-doc changes only:
- add summaries to ~10k test methods, fixtures, fakes and helpers
  (+ <param> on theories, <returns> on async Task methods,
  <inheritdoc/> on interface implementations the checker can resolve)
- strip ~2.6k project-tracking references (WP*, P*-*, row-NN, Task N,
  #NN, Component-0NN) from comments, keeping the explanatory text;
  reword false positives in comments only
- real docs on fakes implementing BCL/library interfaces
  (IDisposable, ILogger, IOptionsMonitor, IAsyncLifetime)
- reword the last 5 src/ false positives (CWE-1236, failures-1,
  year-0001, M365)

Only non-comment edits: four one-line nested classes split across lines
so members can carry docs. Build 0 errors / 0 warnings.
2026-10-07 15:05:49 -04:00

148 lines
6.8 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>
/// Drill-in test 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>();
/// <summary>Creates the test class and registers the stubbed services the page needs.</summary>
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();
Services.AddTestConfigurationMutations();
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);
/// <summary>Verifies that the edit page has a recent audit activity link filtered by actor and the inbound API channel.</summary>
[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);
});
}
/// <summary>Verifies that the create page has no recent audit activity link.</summary>
[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\"]"));
});
}
/// <summary>Verifies that creating a key with a method selected shows the one-time token and key id.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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>());
}
/// <summary>Verifies that creating a key with no method selected shows a validation error and creates nothing.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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>());
}
}