Files
mxaccessgw/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/AlarmFeedAuthorizationTests.cs
T
Joseph Doherty 2ef7b93761 fix(SEC-41, SEC-40): re-resolve dashboard tag grants; gate the alarm feed on a real role
Committed together because the two changes share the same doc paragraphs (the ACL
section of GatewayDashboardDesign.md, the GroupToTag / AllowAnonymousLocalhost rows
of GatewayConfiguration.md, and CLAUDE.md's authentication paragraph), and splitting
them would leave one of the two describing behaviour that does not yet exist.

SEC-41 — tag grants no longer trusted from login-stamped claims
---------------------------------------------------------------
DashboardSessionAcl read the zb:dashboardtag claims stamped into the cookie at
login. GatewayOptions binds once at startup, so applying a GroupToTag edit needs a
restart — but the restart does not clear the auth cookie (data-protection keys
persist), so a browser returning afterwards re-authenticated with tag claims
resolved under the OLD map. A revoked grant therefore survived on the cookie seam
for the sliding 8-hour idle life, renewable indefinitely by activity, while the
hub-token seam had no such gap because its mint re-resolves.

CanViewSession now re-resolves the grant on every subscribe from the caller's
mxgateway:ldap_group claims through DashboardGroupTagMapping.MapGroupsToTags
against the currently bound map — the same one call HubTokenService.Issue makes.

Fallback (documented on the class and in the design doc): a principal carrying NO
group claims falls back to its stamped tag claims. That arm exists for the
hub-token principal — HubTokenService.Validate rehydrates roles and tags but not
groups, so re-resolution already happened at mint, one lifetime ago at worst. It
cannot re-open the cookie hole: DashboardAuthenticator stamps group and tag claims
from one group list, so a cookie principal holding a tag claim always holds the
groups it came from, and a login yielding no groups yields no tags. A principal
with neither kind of claim stays an empty-grant Viewer.

SEC-40 — the alarm feed requires a real authenticated dashboard role
--------------------------------------------------------------------
AlarmsHub sat behind HubClientsPolicy, which the read-only environment bypasses
satisfy, so an anonymous-localhost caller or a Mode=Disabled deployment received
galaxy-wide alarm metadata — alarm reference (a full tag path), state, severity,
category, area, acknowledging operator — for the whole subscription expression.

Decided: tighten the gate, keep the scope. New AuthenticatedDashboardRoleRequirement
+ its handler, and a MxGateway.Dashboard.Alarms policy built from it. Because
DashboardAuthorizationHandler is typed to DashboardAuthorizationRequirement, it is
never invoked for the new type, so neither Authentication:Mode=Disabled nor
anonymous localhost can satisfy the policy — the same structural device the mounted
Secrets UI already relies on. The policy keeps both schemes so external hub clients
can still authenticate with a bearer token, and DisableLogin auto-login is
unaffected (it mints a genuinely authenticated both-roles principal).

The /alarms page carries the same policy, not just the hub: it reads the same
central monitor in process, so gating only the hub would have left the disclosure
one navigation away. The side rail hides the Alarms link for callers the policy
denies, matching the Secrets link precedent. AlarmsHubPublisher is unchanged and
stays unfiltered by design — audience is decided at hub admission, and the monitor
carries no per-session provenance to narrow by.

Alarm metadata deliberately remains galaxy-wide for authenticated Viewers: an
AlarmFeedMessage has no session id or owning key for the SEC-25 tag intersection to
work against, and equating a visibility tag with an alarm-reference prefix would
turn GroupToTag into the data-access constraint it explicitly is not.

Tests
-----
DashboardSessionAclTests: the SEC-41 regression — a cookie-style principal whose
stale tag claim is no longer granted by any of its groups under the current map is
denied; plus the allowing direction (including with no stamped tag at all, which
proves the decision comes from the groups), the ignore-case corner, group claims
that map to nothing, and the hub-token fallback asserted against an EMPTY map so
dropping the fallback would fail loudly.

AlarmFeedAuthorizationTests (new): both handlers run together in the most permissive
environment (Mode=Disabled + loopback + AllowAnonymousLocalhost) do not satisfy the
alarm requirement, with the bypassable requirement as the control so the negative
cannot pass because the bypass was misconfigured; authenticated Viewer/Admin do
satisfy it; an unauthenticated role claim does not; the registered policy carries
the non-bypassable requirement and both schemes; and both readers — the hub type's
[Authorize] and the /alarms endpoint metadata — carry it.

SecretsNavRenderTests: registers the new policy (an unregistered policy name throws
rather than denying in an AuthorizeView) and gains the Alarms-link negative/control
pair.

Verified: dotnet build src/ZB.MOM.WW.MxGateway.NonWindows.slnx (zero warnings);
filtered run of the touched classes — 92 passed, 0 failed.
2026-08-20 09:29:44 -04:00

199 lines
8.9 KiB
C#

using System.Net;
using System.Reflection;
using System.Security.Claims;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.MxGateway.Server;
using ZB.MOM.WW.MxGateway.Server.Configuration;
using ZB.MOM.WW.MxGateway.Server.Dashboard;
using ZB.MOM.WW.MxGateway.Server.Dashboard.Hubs;
using AuthenticationOptions = ZB.MOM.WW.MxGateway.Server.Configuration.AuthenticationOptions;
namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Dashboard;
/// <summary>
/// Covers SEC-40: the alarm feed requires a real authenticated dashboard role, so the read-only
/// environment bypasses (<c>Authentication:Mode=Disabled</c>, anonymous localhost) no longer
/// receive galaxy-wide alarm metadata.
/// </summary>
/// <remarks>
/// The enforcement is a requirement TYPE distinction — <see cref="DashboardAuthorizationHandler"/>
/// is an <c>AuthorizationHandler&lt;DashboardAuthorizationRequirement&gt;</c> and therefore never
/// runs for <see cref="AuthenticatedDashboardRoleRequirement"/> — so the tests below assert both
/// halves: that both handlers together still deny a bypassed caller, and that the policy the two
/// alarm surfaces actually carry is built from that requirement rather than the bypassable one.
/// Asserting only the handler would pass even if the hub were left on the old policy.
/// </remarks>
public sealed class AlarmFeedAuthorizationTests
{
/// <summary>
/// The bypass that satisfies <see cref="DashboardAuthorizationRequirement.AnyDashboardRole"/>
/// — auth disabled AND a loopback request with <c>AllowAnonymousLocalhost</c> on, i.e. both
/// arms at once — does not satisfy the alarm requirement, with the real bypass handler present
/// in the same evaluation.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task AlarmRequirement_AnonymousLocalhostAndAuthDisabled_DoesNotSucceed()
{
AuthorizationHandlerContext context = await EvaluateAsync(
new ClaimsPrincipal(new ClaimsIdentity()),
AuthenticatedDashboardRoleRequirement.AnyDashboardRole);
Assert.False(context.HasSucceeded);
}
/// <summary>
/// Control: the SAME evaluation environment satisfies the bypassable requirement. Without this
/// pairing the test above could pass because the bypass was misconfigured rather than because
/// the requirement type excludes it.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task ViewerRequirement_AnonymousLocalhostAndAuthDisabled_StillSucceeds()
{
AuthorizationHandlerContext context = await EvaluateAsync(
new ClaimsPrincipal(new ClaimsIdentity()),
DashboardAuthorizationRequirement.AnyDashboardRole);
Assert.True(context.HasSucceeded);
}
/// <summary>
/// An authenticated Viewer — the ordinary LDAP-logged-in dashboard user — does satisfy the
/// alarm requirement: SEC-40 excludes the environment bypasses, not Viewers. Alarm metadata
/// stays galaxy-wide for them because the monitor is gateway-central and carries no
/// per-session provenance to tag-scope by.
/// </summary>
/// <param name="role">The dashboard role the authenticated caller holds.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[Theory]
[InlineData(DashboardRoles.Viewer)]
[InlineData(DashboardRoles.Admin)]
public async Task AlarmRequirement_AuthenticatedDashboardRole_Succeeds(string role)
{
AuthorizationHandlerContext context = await EvaluateAsync(
CreatePrincipal(role),
AuthenticatedDashboardRoleRequirement.AnyDashboardRole);
Assert.True(context.HasSucceeded);
}
/// <summary>
/// A principal carrying a dashboard role claim but no authentication type does not satisfy the
/// requirement: "real role claim" means an authenticated identity, matching how the session
/// ACL and <c>DashboardSessionAdminService</c> read a role.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task AlarmRequirement_UnauthenticatedRoleClaim_DoesNotSucceed()
{
ClaimsPrincipal principal = new(new ClaimsIdentity(
[new Claim(ClaimTypes.Role, DashboardRoles.Admin)],
authenticationType: null,
nameType: ClaimTypes.Name,
roleType: ClaimTypes.Role));
AuthorizationHandlerContext context = await EvaluateAsync(
principal,
AuthenticatedDashboardRoleRequirement.AnyDashboardRole);
Assert.False(context.HasSucceeded);
}
/// <summary>
/// The registered policy is built from the non-bypassable requirement and from neither
/// <see cref="DashboardAuthorizationRequirement"/> nor a role list the bypass handler could
/// reach, and it still accepts both hub-capable schemes so an external hub client can
/// authenticate with a bearer token.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task AlarmsPolicy_IsRegisteredWithNonBypassableRequirement()
{
await using WebApplication app = GatewayApplication.Build([]);
IAuthorizationPolicyProvider provider = app.Services
.GetRequiredService<IAuthorizationPolicyProvider>();
AuthorizationPolicy? policy = await provider
.GetPolicyAsync(DashboardAuthenticationDefaults.AlarmsPolicy);
Assert.NotNull(policy);
Assert.Contains(policy.Requirements, r => r is AuthenticatedDashboardRoleRequirement);
Assert.DoesNotContain(policy.Requirements, r => r is DashboardAuthorizationRequirement);
Assert.Equal(
[
DashboardAuthenticationDefaults.AuthenticationScheme,
DashboardAuthenticationDefaults.HubAuthenticationScheme,
],
policy.AuthenticationSchemes);
}
/// <summary>
/// Both readers of the one central monitor carry the alarm policy: the hub (external clients)
/// and the <c>/alarms</c> Razor endpoint (the in-page reader). Gating only the hub would leave
/// the same metadata one navigation away for a bypassed caller.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task AlarmsHubAndAlarmsPage_BothCarryTheAlarmsPolicy()
{
AuthorizeAttribute? hubAttribute = typeof(AlarmsHub)
.GetCustomAttribute<AuthorizeAttribute>(inherit: false);
Assert.Equal(DashboardAuthenticationDefaults.AlarmsPolicy, hubAttribute?.Policy);
await using WebApplication app = GatewayApplication.Build([]);
RouteEndpoint alarmsPage = ((IEndpointRouteBuilder)app).DataSources
.SelectMany(source => source.Endpoints)
.OfType<RouteEndpoint>()
.Single(endpoint => endpoint.RoutePattern.RawText == "/alarms");
Assert.Contains(
alarmsPage.Metadata.OfType<IAuthorizeData>(),
data => data.Policy == DashboardAuthenticationDefaults.AlarmsPolicy);
}
/// <summary>
/// Runs BOTH dashboard authorization handlers over one requirement in the most permissive
/// environment the gateway supports (auth disabled, loopback, anonymous localhost allowed),
/// mirroring how the authorization service invokes every registered handler.
/// </summary>
/// <param name="principal">The caller.</param>
/// <param name="requirement">The single requirement under evaluation.</param>
/// <returns>The context after both handlers have run.</returns>
private static async Task<AuthorizationHandlerContext> EvaluateAsync(
ClaimsPrincipal principal,
IAuthorizationRequirement requirement)
{
DefaultHttpContext httpContext = new();
httpContext.Connection.RemoteIpAddress = IPAddress.Loopback;
IOptions<GatewayOptions> options = Options.Create(new GatewayOptions
{
Authentication = new AuthenticationOptions { Mode = AuthenticationMode.Disabled },
Dashboard = new DashboardOptions { AllowAnonymousLocalhost = true },
});
AuthorizationHandlerContext context = new([requirement], principal, httpContext);
await new DashboardAuthorizationHandler(
new HttpContextAccessor { HttpContext = httpContext },
options).HandleAsync(context);
await new AuthenticatedDashboardRoleHandler().HandleAsync(context);
return context;
}
private static ClaimsPrincipal CreatePrincipal(string role) =>
new(new ClaimsIdentity(
[new Claim(ClaimTypes.Role, role)],
DashboardAuthenticationDefaults.AuthenticationScheme,
ClaimTypes.Name,
ClaimTypes.Role));
}