27fdb576ba
Routes.razor used RouteView, which ignores [Authorize]. With the interactive router, an in-circuit navigation never meets endpoint authorization, so anonymous localhost could open /alarms and a Viewer could open /admin/secrets (secret metadata list). Both were confirmed reachable by the new route test before the change; AuthorizeRouteView now renders a Not Authorized panel instead.
336 lines
14 KiB
C#
336 lines
14 KiB
C#
using System.Security.Claims;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Components;
|
|
using Microsoft.AspNetCore.Components.Authorization;
|
|
using Microsoft.AspNetCore.Components.Routing;
|
|
using Microsoft.AspNetCore.Components.Web;
|
|
using Microsoft.AspNetCore.Components.Web.HtmlRendering;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Extensions.Options;
|
|
using Microsoft.JSInterop;
|
|
using ZB.MOM.WW.Auth.AspNetCore;
|
|
using ZB.MOM.WW.MxGateway.Server.Alarms;
|
|
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
|
using ZB.MOM.WW.MxGateway.Server.Dashboard;
|
|
using ZB.MOM.WW.MxGateway.Server.Dashboard.Components;
|
|
using ZB.MOM.WW.MxGateway.Tests.TestSupport;
|
|
using ZB.MOM.WW.Secrets.Ui;
|
|
|
|
namespace ZB.MOM.WW.MxGateway.Tests.Dashboard;
|
|
|
|
/// <summary>
|
|
/// Proves the dashboard router enforces page <c>[Authorize]</c> attributes on in-circuit
|
|
/// navigation (DSH-001, #243).
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// A page's <c>[Authorize]</c> attribute is enforced by endpoint routing only on a full HTTP
|
|
/// request. The dashboard router is interactive, so a navigation that starts inside an existing
|
|
/// circuit (a click on an in-page link, or <c>Blazor.navigateTo</c> from the console) never issues
|
|
/// an HTTP request: the in-circuit <c>Router</c> resolves the route and renders it. A plain
|
|
/// <c>RouteView</c> does not evaluate <c>[Authorize]</c>; <c>AuthorizeRouteView</c> does.
|
|
/// </para>
|
|
/// <para>
|
|
/// These tests render the production <see cref="Routes"/> component, park it on a page that has
|
|
/// no attribute, then call <see cref="NavigationManager.NavigateTo(string, bool)"/> — the same
|
|
/// <c>LocationChanged</c> path an in-circuit navigation drives. Each negative test asserts both
|
|
/// that the gated page's markup is absent and that its data source was never called, so a page
|
|
/// that rendered and then threw cannot pass for a gate.
|
|
/// </para>
|
|
/// <para>
|
|
/// The shared <c>ZB.MOM.WW.Secrets.Ui</c> page is not rendered for real: under the static
|
|
/// <see cref="HtmlRenderer"/> its Theme-based markup overflows the HTML writer's stack in this
|
|
/// harness, and its internals are not what is under test. A component activator substitutes a
|
|
/// marker component when the router activates <see cref="SecretsPage"/>, so "activated" means
|
|
/// exactly "the router decided to render the page".
|
|
/// </para>
|
|
/// </remarks>
|
|
public sealed class DashboardRouteAuthorizationTests
|
|
{
|
|
private const string StartPath = "/route-authorization-test-start";
|
|
private const string SecretsPageMarker = "secrets-page-activated";
|
|
private const string AlarmsPageMarker = "Active Alarms";
|
|
private const string NotAuthorizedMarker = "Not Authorized";
|
|
|
|
/// <summary>
|
|
/// A Viewer is not granted <c>secrets:manage</c>. Navigating in-circuit to
|
|
/// <c>/admin/secrets</c> must render the not-authorized content and must not list secrets.
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Viewer_InCircuitNavigationToSecrets_IsNotAuthorized()
|
|
{
|
|
RouteHarness harness = await RouteHarness.StartAsync(DashboardRoles.Viewer);
|
|
await using (harness.ConfigureAwait(false))
|
|
{
|
|
string html = await harness.NavigateAsync("/admin/secrets");
|
|
|
|
Assert.DoesNotContain(SecretsPageMarker, html, StringComparison.Ordinal);
|
|
Assert.Contains(NotAuthorizedMarker, html, StringComparison.Ordinal);
|
|
Assert.Equal(0, harness.Activator.SecretsPageActivations);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Control for the Viewer case: an Administrator satisfies <c>secrets:manage</c>, so the same
|
|
/// in-circuit navigation renders the page and lists secrets. Without this, a router that
|
|
/// rendered nothing at all would pass the negative test.
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Administrator_InCircuitNavigationToSecrets_RendersPage()
|
|
{
|
|
RouteHarness harness = await RouteHarness.StartAsync(DashboardRoles.Admin);
|
|
await using (harness.ConfigureAwait(false))
|
|
{
|
|
string html = await harness.NavigateAsync("/admin/secrets");
|
|
|
|
Assert.Contains(SecretsPageMarker, html, StringComparison.Ordinal);
|
|
Assert.DoesNotContain(NotAuthorizedMarker, html, StringComparison.Ordinal);
|
|
Assert.Equal(1, harness.Activator.SecretsPageActivations);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Anonymous localhost passes the endpoint <c>ViewerPolicy</c> but never the Alarms policy.
|
|
/// In-circuit navigation to <c>/alarms</c> must not render the galaxy-wide alarm list or
|
|
/// start its poll loop.
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Anonymous_InCircuitNavigationToAlarms_IsNotAuthorized()
|
|
{
|
|
RouteHarness harness = await RouteHarness.StartAsync();
|
|
await using (harness.ConfigureAwait(false))
|
|
{
|
|
string html = await harness.NavigateAsync("/alarms");
|
|
|
|
Assert.DoesNotContain(AlarmsPageMarker, html, StringComparison.Ordinal);
|
|
Assert.Contains(NotAuthorizedMarker, html, StringComparison.Ordinal);
|
|
Assert.Equal(0, harness.LiveData.AlarmQueries);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Control for the anonymous case: an authenticated Viewer holds a real dashboard role and so
|
|
/// satisfies the Alarms policy; the page renders and polls.
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Viewer_InCircuitNavigationToAlarms_RendersPage()
|
|
{
|
|
RouteHarness harness = await RouteHarness.StartAsync(DashboardRoles.Viewer);
|
|
await using (harness.ConfigureAwait(false))
|
|
{
|
|
string html = await harness.NavigateAsync("/alarms");
|
|
|
|
Assert.Contains(AlarmsPageMarker, html, StringComparison.Ordinal);
|
|
Assert.DoesNotContain(NotAuthorizedMarker, html, StringComparison.Ordinal);
|
|
Assert.True(harness.LiveData.AlarmQueries >= 1);
|
|
}
|
|
}
|
|
|
|
// Owns the service provider, the renderer and the rendered Routes root for one test.
|
|
private sealed class RouteHarness : IAsyncDisposable
|
|
{
|
|
private readonly ServiceProvider _provider;
|
|
private readonly HtmlRenderer _renderer;
|
|
private readonly HtmlRootComponent _root;
|
|
|
|
private RouteHarness(
|
|
ServiceProvider provider,
|
|
HtmlRenderer renderer,
|
|
HtmlRootComponent root,
|
|
SecretsPageSubstitutingActivator activator,
|
|
CountingLiveDataService liveData)
|
|
{
|
|
_provider = provider;
|
|
_renderer = renderer;
|
|
_root = root;
|
|
Activator = activator;
|
|
LiveData = liveData;
|
|
}
|
|
|
|
public SecretsPageSubstitutingActivator Activator { get; }
|
|
|
|
public CountingLiveDataService LiveData { get; }
|
|
|
|
public static async Task<RouteHarness> StartAsync(params string[] roles)
|
|
{
|
|
SecretsPageSubstitutingActivator activator = new();
|
|
CountingLiveDataService liveData = new();
|
|
|
|
ServiceCollection services = new();
|
|
services.AddLogging();
|
|
services.AddAuthorization(options =>
|
|
{
|
|
options.AddSecretsAuthorization();
|
|
options.AddPolicy(
|
|
DashboardAuthenticationDefaults.AlarmsPolicy,
|
|
policy => policy.AddRequirements(AuthenticatedDashboardRoleRequirement.AnyDashboardRole));
|
|
});
|
|
services.AddSingleton<IAuthorizationHandler, AuthenticatedDashboardRoleHandler>();
|
|
services.AddCascadingAuthenticationState();
|
|
services.AddSingleton<AuthenticationStateProvider>(new StubAuthenticationStateProvider(roles));
|
|
services.AddSingleton<NavigationManager, InCircuitNavigationManager>();
|
|
services.AddSingleton<INavigationInterception, NoOpNavigationInterception>();
|
|
services.AddSingleton<IScrollToLocationHash, NoOpScrollToLocationHash>();
|
|
services.AddSingleton<IJSRuntime, NoOpJsRuntime>();
|
|
services.AddSingleton<IComponentActivator>(activator);
|
|
services.AddSingleton<IDashboardLiveDataService>(liveData);
|
|
services.AddSingleton<IGatewayAlarmService>(new FakeGatewayAlarmService());
|
|
services.AddSingleton<IOptions<GatewayOptions>>(
|
|
Options.Create(new GatewayOptions { Alarms = new AlarmsOptions { Enabled = true } }));
|
|
|
|
ServiceProvider provider = services.BuildServiceProvider();
|
|
HtmlRenderer renderer = new(provider, provider.GetRequiredService<ILoggerFactory>());
|
|
HtmlRootComponent root = await renderer.Dispatcher.InvokeAsync(
|
|
() => renderer.RenderComponentAsync<Routes>());
|
|
|
|
return new RouteHarness(provider, renderer, root, activator, liveData);
|
|
}
|
|
|
|
public async Task<string> NavigateAsync(string path)
|
|
{
|
|
NavigationManager navigation = _provider.GetRequiredService<NavigationManager>();
|
|
await _renderer.Dispatcher.InvokeAsync(() => navigation.NavigateTo(path));
|
|
|
|
// The router re-renders asynchronously after LocationChanged; wait for the start
|
|
// page's not-found content to be replaced before reading the markup.
|
|
string html = string.Empty;
|
|
await Eventually.WaitUntilAsync(
|
|
async () =>
|
|
{
|
|
html = await _renderer.Dispatcher.InvokeAsync(_root.ToHtmlString);
|
|
return !html.Contains("The requested dashboard page does not exist", StringComparison.Ordinal);
|
|
},
|
|
TimeSpan.FromSeconds(10),
|
|
$"the router to leave the start page after navigating to {path}");
|
|
return html;
|
|
}
|
|
|
|
public async ValueTask DisposeAsync()
|
|
{
|
|
await _renderer.DisposeAsync();
|
|
await _provider.DisposeAsync();
|
|
}
|
|
}
|
|
|
|
// A principal with an authentication type and role claims, or an unauthenticated one when no
|
|
// roles are given (the anonymous-localhost shape).
|
|
private sealed class StubAuthenticationStateProvider(string[] roles) : AuthenticationStateProvider
|
|
{
|
|
/// <inheritdoc />
|
|
public override Task<AuthenticationState> GetAuthenticationStateAsync()
|
|
{
|
|
ClaimsIdentity identity = roles.Length == 0
|
|
? new ClaimsIdentity()
|
|
: new ClaimsIdentity(
|
|
roles.Select(role => new Claim(ZbClaimTypes.Role, role)),
|
|
authenticationType: "Test",
|
|
nameType: ZbClaimTypes.Name,
|
|
roleType: ZbClaimTypes.Role);
|
|
|
|
return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(identity)));
|
|
}
|
|
}
|
|
|
|
// Navigation stays in process: NavigateTo updates the URI and raises LocationChanged, which
|
|
// is exactly what an in-circuit navigation does — no HTTP request, so no endpoint authorization.
|
|
private sealed class InCircuitNavigationManager : NavigationManager
|
|
{
|
|
/// <summary>Initializes the manager on the attribute-free start path.</summary>
|
|
public InCircuitNavigationManager() => Initialize("https://localhost/", $"https://localhost{StartPath}");
|
|
|
|
/// <inheritdoc />
|
|
protected override void NavigateToCore(string uri, NavigationOptions options)
|
|
{
|
|
Uri = ToAbsoluteUri(uri).ToString();
|
|
NotifyLocationChanged(isInterceptedLink: false);
|
|
}
|
|
}
|
|
|
|
private sealed class NoOpNavigationInterception : INavigationInterception
|
|
{
|
|
/// <inheritdoc />
|
|
public Task EnableNavigationInterceptionAsync() => Task.CompletedTask;
|
|
}
|
|
|
|
private sealed class NoOpScrollToLocationHash : IScrollToLocationHash
|
|
{
|
|
/// <inheritdoc />
|
|
public Task RefreshScrollPositionForHash(string locationAbsolute) => Task.CompletedTask;
|
|
}
|
|
|
|
private sealed class NoOpJsRuntime : IJSRuntime
|
|
{
|
|
/// <inheritdoc />
|
|
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, object?[]? args) => default;
|
|
|
|
/// <inheritdoc />
|
|
public ValueTask<TValue> InvokeAsync<TValue>(
|
|
string identifier,
|
|
CancellationToken cancellationToken,
|
|
object?[]? args) => default;
|
|
}
|
|
|
|
// Answers the Alarms page's poll with an empty result and counts the calls; a non-zero count
|
|
// means the page initialized and started its galaxy-wide alarm loop.
|
|
private sealed class CountingLiveDataService : IDashboardLiveDataService
|
|
{
|
|
private int _alarmQueries;
|
|
|
|
public int AlarmQueries => Volatile.Read(ref _alarmQueries);
|
|
|
|
public Task<DashboardLiveReadResult> ReadAsync(
|
|
IReadOnlyCollection<string> tagAddresses,
|
|
CancellationToken cancellationToken) =>
|
|
Task.FromResult(DashboardLiveReadResult.Empty);
|
|
|
|
public async Task<DashboardAlarmQueryResult> QueryAlarmsAsync(CancellationToken cancellationToken)
|
|
{
|
|
if (Interlocked.Increment(ref _alarmQueries) > 1)
|
|
{
|
|
await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
return new DashboardAlarmQueryResult(
|
|
Alarms: [],
|
|
Error: null,
|
|
WorkerProcessId: null,
|
|
SnapshotTruncated: false);
|
|
}
|
|
}
|
|
|
|
// Activates components normally, except SecretsPage, which it counts and replaces with a
|
|
// marker. Renderer resolves IComponentActivator from the service provider.
|
|
private sealed class SecretsPageSubstitutingActivator : IComponentActivator
|
|
{
|
|
private int _secretsPageActivations;
|
|
|
|
public int SecretsPageActivations => Volatile.Read(ref _secretsPageActivations);
|
|
|
|
/// <inheritdoc />
|
|
public IComponent CreateInstance(Type componentType)
|
|
{
|
|
if (componentType == typeof(SecretsPage))
|
|
{
|
|
Interlocked.Increment(ref _secretsPageActivations);
|
|
return new SecretsPageStandIn();
|
|
}
|
|
|
|
return (IComponent)System.Activator.CreateInstance(componentType)!;
|
|
}
|
|
}
|
|
|
|
private sealed class SecretsPageStandIn : ComponentBase
|
|
{
|
|
/// <inheritdoc />
|
|
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder)
|
|
{
|
|
builder.AddMarkupContent(0, $"<p>{SecretsPageMarker}</p>");
|
|
}
|
|
}
|
|
}
|