diff --git a/docs/GatewayDashboardDesign.md b/docs/GatewayDashboardDesign.md index 40e36bd4..06debee3 100644 --- a/docs/GatewayDashboardDesign.md +++ b/docs/GatewayDashboardDesign.md @@ -627,6 +627,15 @@ policy `AlarmsHub` carries — the two read one central monitor and must not dis may see it — and the side rail hides the Alarms link for callers the policy denies. What a permitted caller sees is galaxy-wide and not tag-scoped; see "Alarm-feed visibility". +The attribute is enforced on both routes into the page. A full HTTP request meets endpoint +authorization. An in-circuit navigation (an in-page link, or `Blazor.navigateTo` from the +console) issues no HTTP request, so `Routes.razor` renders pages through `AuthorizeRouteView`, +which evaluates the page's `[Authorize]` attribute against the circuit's principal and renders a +"Not Authorized" panel instead. Before DSH-001 (#243) the router used a plain `RouteView`, so an +anonymous-localhost caller could reach this page, and a Viewer could reach the mounted Secrets +page (`/admin/secrets`, `secrets:manage`) and its secret-metadata list, by navigating inside an +existing circuit. + ### Live data source Both the Browse subscription panel and the Alarms page read live MXAccess data @@ -817,8 +826,10 @@ they do not use. The in-process page feeds carry no authentication of their own, and need none: `MapRazorComponents()` applies `RequireAuthorization(ViewerPolicy)` to the component endpoints, so a page can only run inside a circuit whose principal is -already an authorized Viewer. The hub-token flow below therefore covers only the -remote hub surface. +already an authorized Viewer. Pages with a stricter `[Authorize]` attribute (Alarms, +the mounted Secrets page) are re-checked by `AuthorizeRouteView` on every in-circuit +navigation, because that navigation never reaches the endpoint. The hub-token flow +below therefore covers only the remote hub surface. Neither policy scopes a Viewer to particular sessions — that is `IDashboardSessionAcl`'s job (SEC-25 / TST-15), consulted by both subscribe seams: diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Routes.razor b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Routes.razor index c5296533..f76a13fd 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Routes.razor +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Routes.razor @@ -1,7 +1,27 @@ +@* AuthorizeRouteView, not RouteView (DSH-001): the router is interactive, so a navigation that + starts inside a circuit never issues an HTTP request and never meets endpoint authorization. + Only AuthorizeRouteView evaluates a page's [Authorize] attribute on that path — the Alarms page + (AlarmsPolicy) and the shared Secrets page (secrets:manage) both rely on it. Pages without an + attribute are rendered as before; the endpoint ViewerPolicy still gates the initial request. *@ - + + + Dashboard - Not Authorized +
+

Not Authorized

+ @if (context.User.Identity?.IsAuthenticated == true) + { +

Your dashboard role does not grant access to this page.

+ } + else + { +

This page requires a signed-in dashboard role. Sign in

+ } +
+
+
diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Dashboard/DashboardRouteAuthorizationTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Dashboard/DashboardRouteAuthorizationTests.cs new file mode 100644 index 00000000..3215758c --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Tests/Dashboard/DashboardRouteAuthorizationTests.cs @@ -0,0 +1,335 @@ +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; + +/// +/// Proves the dashboard router enforces page [Authorize] attributes on in-circuit +/// navigation (DSH-001, #243). +/// +/// +/// +/// A page's [Authorize] 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 Blazor.navigateTo from the console) never issues +/// an HTTP request: the in-circuit Router resolves the route and renders it. A plain +/// RouteView does not evaluate [Authorize]; AuthorizeRouteView does. +/// +/// +/// These tests render the production component, park it on a page that has +/// no attribute, then call — the same +/// LocationChanged 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. +/// +/// +/// The shared ZB.MOM.WW.Secrets.Ui page is not rendered for real: under the static +/// 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 , so "activated" means +/// exactly "the router decided to render the page". +/// +/// +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"; + + /// + /// A Viewer is not granted secrets:manage. Navigating in-circuit to + /// /admin/secrets must render the not-authorized content and must not list secrets. + /// + /// A task that represents the asynchronous operation. + [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); + } + } + + /// + /// Control for the Viewer case: an Administrator satisfies secrets:manage, 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. + /// + /// A task that represents the asynchronous operation. + [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); + } + } + + /// + /// Anonymous localhost passes the endpoint ViewerPolicy but never the Alarms policy. + /// In-circuit navigation to /alarms must not render the galaxy-wide alarm list or + /// start its poll loop. + /// + /// A task that represents the asynchronous operation. + [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); + } + } + + /// + /// Control for the anonymous case: an authenticated Viewer holds a real dashboard role and so + /// satisfies the Alarms policy; the page renders and polls. + /// + /// A task that represents the asynchronous operation. + [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 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(); + services.AddCascadingAuthenticationState(); + services.AddSingleton(new StubAuthenticationStateProvider(roles)); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(activator); + services.AddSingleton(liveData); + services.AddSingleton(new FakeGatewayAlarmService()); + services.AddSingleton>( + Options.Create(new GatewayOptions { Alarms = new AlarmsOptions { Enabled = true } })); + + ServiceProvider provider = services.BuildServiceProvider(); + HtmlRenderer renderer = new(provider, provider.GetRequiredService()); + HtmlRootComponent root = await renderer.Dispatcher.InvokeAsync( + () => renderer.RenderComponentAsync()); + + return new RouteHarness(provider, renderer, root, activator, liveData); + } + + public async Task NavigateAsync(string path) + { + NavigationManager navigation = _provider.GetRequiredService(); + 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 + { + /// + public override Task 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 + { + /// Initializes the manager on the attribute-free start path. + public InCircuitNavigationManager() => Initialize("https://localhost/", $"https://localhost{StartPath}"); + + /// + protected override void NavigateToCore(string uri, NavigationOptions options) + { + Uri = ToAbsoluteUri(uri).ToString(); + NotifyLocationChanged(isInterceptedLink: false); + } + } + + private sealed class NoOpNavigationInterception : INavigationInterception + { + /// + public Task EnableNavigationInterceptionAsync() => Task.CompletedTask; + } + + private sealed class NoOpScrollToLocationHash : IScrollToLocationHash + { + /// + public Task RefreshScrollPositionForHash(string locationAbsolute) => Task.CompletedTask; + } + + private sealed class NoOpJsRuntime : IJSRuntime + { + /// + public ValueTask InvokeAsync(string identifier, object?[]? args) => default; + + /// + public ValueTask InvokeAsync( + 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 ReadAsync( + IReadOnlyCollection tagAddresses, + CancellationToken cancellationToken) => + Task.FromResult(DashboardLiveReadResult.Empty); + + public async Task 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); + + /// + 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 + { + /// + protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) + { + builder.AddMarkupContent(0, $"

{SecretsPageMarker}

"); + } + } +}