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

363 lines
17 KiB
C#

using System.Net;
using System.Security.Claims;
using System.Text.Encodings.Web;
using Bunit;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Components;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using NSubstitute;
using ZB.MOM.WW.ScadaBridge.CentralUI.Audit;
using ZB.MOM.WW.ScadaBridge.CentralUI.Services;
using ZB.MOM.WW.Audit;
using ZB.MOM.WW.ScadaBridge.Commons.Interfaces.Repositories;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Audit;
using ZB.MOM.WW.ScadaBridge.Commons.Types.Enums;
using ZB.MOM.WW.ScadaBridge.Security;
using AuditLogPage = ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Audit.AuditLogPage;
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Pages;
/// <summary>
/// Permission-gating tests for the Audit Log surface (Bundle G).
///
/// <para>
/// Bundle G introduces two new policies:
/// <list type="bullet">
/// <item><c>OperationalAudit</c> — read access to the Audit Log page +
/// Configuration Audit Log page + nav group.</item>
/// <item><c>AuditExport</c> — additional gate on the Export-CSV button and
/// the streaming export endpoint.</item>
/// </list>
/// After the role consolidation, <c>AuditExport</c> is satisfied only by the
/// <c>Administrator</c> role (which absorbed the former <c>Audit</c> role);
/// <c>OperationalAudit</c> is additionally satisfied by the <c>Viewer</c> role
/// (the home of the former <c>AuditReadOnly</c> role) — Viewer reads but cannot
/// export. The tests pin both the page-level + endpoint-level enforcement, and
/// the Export-button visibility split.
/// </para>
/// </summary>
public class AuditLogPagePermissionTests : BunitContext
{
/// <summary>Initializes the test context and registers the fake authentication and service stand-ins.</summary>
public AuditLogPagePermissionTests()
{
// The page hosts AuditResultsGrid, whose OnAfterRenderAsync wires the
// column resize/reorder UX via audit-grid.js (a sessionStorage load +
// an init call). Loose mode lets those unconfigured JS calls no-op so
// the permission-gating tests need not configure browser interop.
JSInterop.Mode = JSRuntimeMode.Loose;
}
private static ClaimsPrincipal BuildPrincipal(params string[] roles)
{
var claims = new List<Claim> { new(JwtTokenService.UsernameClaimType, "tester") };
claims.AddRange(roles.Select(r => new Claim(JwtTokenService.RoleClaimType, r)));
return new ClaimsPrincipal(new ClaimsIdentity(claims, "TestAuth"));
}
private void WireUpPageDependencies()
{
// The page hosts AuditFilterBar + AuditResultsGrid which depend on
// ISiteRepository and IAuditLogQueryService — provide stand-ins so
// a permitted render is exercised end-to-end.
Services.AddSingleton(Substitute.For<ISiteRepository>());
Services.AddSingleton(Substitute.For<IAuditLogQueryService>());
// The page now injects IKpiHistoryQueryService for the Trends
// panel — register a stand-in so a permitted render is exercised end-to-end.
Services.AddSingleton(Substitute.For<IKpiHistoryQueryService>());
}
private IRenderedComponent<AuditLogPage> RenderAuditLogPage(params string[] roles)
{
var user = BuildPrincipal(roles);
Services.AddSingleton<AuthenticationStateProvider>(new TestAuthStateProvider(user));
Services.AddAuthorizationCore();
Services.AddTestConfigurationMutations();
AuthorizationPolicies.AddScadaBridgeAuthorization(Services);
Services.AddSingleton<IAuthorizationService, DefaultAuthorizationService>();
WireUpPageDependencies();
// Page-level [Authorize(Policy=...)] is enforced by the router in a
// live app. bUnit renders the component directly, so we wrap the
// page in a CascadingAuthenticationState so the in-page
// AuthorizeView for the Export button can read the principal.
var host = Render<CascadingAuthenticationState>(parameters => parameters
.Add(p => p.ChildContent, (RenderFragment)(builder =>
{
builder.OpenComponent<AuditLogPage>(0);
builder.CloseComponent();
})));
return host.FindComponent<AuditLogPage>();
}
// ─────────────────────────────────────────────────────────────────────
// Test 1: WithoutOperationalAudit_PageReturns403_OrHidden
// ─────────────────────────────────────────────────────────────────────
//
// Page-level enforcement is the [Authorize(Policy = "OperationalAudit")]
// attribute on the .razor page. We can't easily smoke-test routing here,
// so we verify the attribute is present + the policy denies a principal
// that holds none of the permitting roles.
/// <summary>Verifies that a user without the OperationalAudit permission is denied by the policy.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task WithoutOperationalAudit_PolicyDenies()
{
// A Designer-only user (not Administrator, not Viewer) must NOT satisfy
// the OperationalAudit policy.
var services = new ServiceCollection();
services.AddLogging();
services.AddScadaBridgeAuthorization();
using var provider = services.BuildServiceProvider();
var authService = provider.GetRequiredService<IAuthorizationService>();
var principal = BuildPrincipal("Designer");
var result = await authService.AuthorizeAsync(
principal, null, AuthorizationPolicies.OperationalAudit);
Assert.False(result.Succeeded);
}
/// <summary>Verifies that the Audit Log page carries the OperationalAudit authorize attribute.</summary>
[Fact]
public void AuditLogPage_HasOperationalAuditAuthorizeAttribute()
{
// Sanity-pin the attribute so the page-level gate can't regress to
// [Authorize] (any-authenticated) by accident.
var attributes = typeof(AuditLogPage)
.GetCustomAttributes(typeof(AuthorizeAttribute), inherit: true)
.Cast<AuthorizeAttribute>()
.ToList();
Assert.Contains(attributes, a => a.Policy == AuthorizationPolicies.OperationalAudit);
}
/// <summary>Verifies that the Configuration Audit Log page carries the OperationalAudit authorize attribute.</summary>
[Fact]
public void ConfigurationAuditLogPage_HasOperationalAuditAuthorizeAttribute()
{
// ConfigurationAuditLog mirrors the gate — both Audit-group pages
// share the OperationalAudit permission so the nav-group policy
// remains coherent with the per-page gates.
var configType = typeof(ZB.MOM.WW.ScadaBridge.CentralUI.Components.Pages.Audit.ConfigurationAuditLog);
var attributes = configType
.GetCustomAttributes(typeof(AuthorizeAttribute), inherit: true)
.Cast<AuthorizeAttribute>()
.ToList();
Assert.Contains(attributes, a => a.Policy == AuthorizationPolicies.OperationalAudit);
}
// ─────────────────────────────────────────────────────────────────────
// Test 2 + 3: Export button visibility split.
// ─────────────────────────────────────────────────────────────────────
/// <summary>Verifies that a user with OperationalAudit but without AuditExport sees the page with the export button hidden.</summary>
[Fact]
public void WithOperationalAudit_NoAuditExport_PageRenders_ExportButtonHidden()
{
// The "Administrator" role grants OperationalAudit + AuditExport, so we
// test the split by handing the user ONLY the "Viewer" role, which maps
// to OperationalAudit (read) but NOT AuditExport — the preserved
// half-SoD after the AuditReadOnly→Viewer collapse
// (see AuthorizationPolicies).
var cut = RenderAuditLogPage("Viewer");
cut.WaitForAssertion(() =>
{
// The page rendered (heading + container present) but the
// Export-CSV anchor is gone because AuditExport is denied.
Assert.Contains("Audit Log", cut.Markup);
Assert.DoesNotContain("Export CSV", cut.Markup);
});
}
/// <summary>Verifies that a user with both OperationalAudit and AuditExport sees the page with the export button visible.</summary>
[Fact]
public void WithOperationalAudit_AndAuditExport_PageRenders_ExportButtonVisible()
{
var cut = RenderAuditLogPage("Administrator");
cut.WaitForAssertion(() =>
{
Assert.Contains("Audit Log", cut.Markup);
Assert.Contains("Export CSV", cut.Markup);
});
}
/// <summary>Verifies that an Administrator sees the page and the export button.</summary>
[Fact]
public void AdminUser_SeesPage_AndExportButton()
{
// Administrator holds every permission by convention — both policies must
// succeed for a plain Administrator user.
var cut = RenderAuditLogPage("Administrator");
cut.WaitForAssertion(() =>
{
Assert.Contains("Audit Log", cut.Markup);
Assert.Contains("Export CSV", cut.Markup);
});
}
// ─────────────────────────────────────────────────────────────────────
// Test 4 + 5: Endpoint-level enforcement.
// ─────────────────────────────────────────────────────────────────────
/// <summary>Verifies that the export endpoint returns 403 for a caller without AuditExport.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task AuditExportEndpoint_WithoutAuditExport_Returns403()
{
// A user holding only Designer must NOT be able to call the export
// endpoint. Live wiring re-uses AuthorizationPolicies.AuditExport.
var (client, _, host) = await BuildEndpointHostAsync(roles: new[] { "Designer" });
using (host)
{
var response = await client.GetAsync("/api/centralui/audit/export");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
}
/// <summary>Verifies that the export endpoint returns 200 for a caller with AuditExport.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task AuditExportEndpoint_WithAuditExport_Returns200()
{
var (client, _, host) = await BuildEndpointHostAsync(roles: new[] { "Administrator" });
using (host)
{
var response = await client.GetAsync("/api/centralui/audit/export");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
/// <summary>Verifies that the export endpoint returns 200 for an Administrator alone.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task AuditExportEndpoint_AdminAlone_Returns200()
{
// Administrator alone must pass — it absorbed the former Audit role and
// holds AuditExport by convention (defence in depth).
var (client, _, host) = await BuildEndpointHostAsync(roles: new[] { "Administrator" });
using (host)
{
var response = await client.GetAsync("/api/centralui/audit/export");
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
}
}
/// <summary>Verifies that the export endpoint returns 403 for a Viewer.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task AuditExportEndpoint_Viewer_Returns403()
{
// Viewer (former AuditReadOnly) grants OperationalAudit but NOT
// AuditExport, so the endpoint must refuse — the page is readable but
// the bulk export path is gated separately (preserved half-SoD).
var (client, _, host) = await BuildEndpointHostAsync(roles: new[] { "Viewer" });
using (host)
{
var response = await client.GetAsync("/api/centralui/audit/export");
Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
}
}
// ─────────────────────────────────────────────────────────────────────
// Helper: tiny in-process host with the real AuthorizationPolicies.
// ─────────────────────────────────────────────────────────────────────
private static async Task<(HttpClient Client, IAuditLogRepository Repo, IHost Host)> BuildEndpointHostAsync(
string[] roles)
{
var repo = Substitute.For<IAuditLogRepository>();
repo.QueryAsync(Arg.Any<AuditLogQueryFilter>(), Arg.Any<AuditLogPaging>(), Arg.Any<CancellationToken>())
.Returns(
Task.FromResult<IReadOnlyList<AuditEvent>>(Array.Empty<AuditEvent>()),
Task.FromResult<IReadOnlyList<AuditEvent>>(Array.Empty<AuditEvent>()));
var hostBuilder = new HostBuilder()
.ConfigureWebHost(web =>
{
web.UseTestServer();
web.ConfigureServices(services =>
{
services.AddRouting();
services.AddAuthentication(FakeAuthHandler.SchemeName)
.AddScheme<FakeAuthHandlerOptions, FakeAuthHandler>(
FakeAuthHandler.SchemeName, opts => opts.Roles = roles);
// Real policies — the whole point of these tests is to
// exercise the production AddScadaBridgeAuthorization wiring.
services.AddScadaBridgeAuthorization();
services.AddSingleton(repo);
services.AddScoped<IAuditLogExportService, AuditLogExportService>();
});
web.Configure(app =>
{
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapAuditExportEndpoints();
});
});
});
var host = await hostBuilder.StartAsync();
var client = host.GetTestClient();
return (client, repo, host);
}
/// <summary>
/// Test-only authentication handler that signs every request in with
/// the configured set of roles.
/// </summary>
private sealed class FakeAuthHandler : AuthenticationHandler<FakeAuthHandlerOptions>
{
public const string SchemeName = "FakeAuth";
/// <summary>Initializes the handler with the standard authentication handler dependencies.</summary>
/// <param name="options">The options monitor for the fake handler.</param>
/// <param name="logger">The logger factory.</param>
/// <param name="encoder">The URL encoder.</param>
public FakeAuthHandler(
IOptionsMonitor<FakeAuthHandlerOptions> options,
ILoggerFactory logger,
UrlEncoder encoder)
: base(options, logger, encoder) { }
/// <inheritdoc />
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
{
var claims = new List<Claim> { new(ClaimTypes.Name, "test-user") };
foreach (var role in Options.Roles)
{
claims.Add(new Claim(JwtTokenService.RoleClaimType, role));
}
var identity = new ClaimsIdentity(claims, SchemeName);
var principal = new ClaimsPrincipal(identity);
var ticket = new AuthenticationTicket(principal, SchemeName);
return Task.FromResult(AuthenticateResult.Success(ticket));
}
}
private sealed class FakeAuthHandlerOptions : AuthenticationSchemeOptions
{
/// <summary>Gets or sets the roles granted to the fake authenticated user.</summary>
public string[] Roles { get; set; } = Array.Empty<string>();
}
}