fix(management): refuse zero-role principals on the management/CLI surfaces (#145)

ManagementAuthenticator — the only identity source for POST /management, the
audit REST endpoints and the debug-stream hub — now enforces "no role, no
login" the way #144 does for /auth/login and /auth/token:

- HTTP Basic: a bind whose groups map to zero roles, or whose role mapping
  throws, answers the bad-password 401 AUTH_FAILED body and counts as a
  LoginThrottle failure. RecordSuccess moved after the mapping, so a refusal
  no longer clears earlier failures. Request cancellation still propagates.
- Bearer: a token with no role claim (minted before #144 shipped) gets the
  invalid-token 401; no throttle, as for every bearer failure.
- Each refusal is logged at Warning (category ManagementAuthenticator) with
  the request path, the username and the reason.

Before this, a zero-role Basic caller reached every command that
ManagementActor.GetRequiredRoles opens to any authenticated user.
DisableLogin is unchanged.

Tests: ManagementZeroRoleRefusalTests — zero roles / mapper throws / one role
over Basic and Bearer for /management (ListSites), /api/audit/query and the
debug-stream hub; every null-role command is unreachable by a zero-role
principal; throttle accounting. 47 of the 58 fail against the old
authenticator (the 11 that pass are the one-role/bypass regression guards).

Claude-Session: https://claude.ai/code/session_01GT67AFKC45MBz1wPZnVbX8
This commit is contained in:
Joseph Doherty
2026-11-17 11:45:51 -05:00
parent d48e1667f1
commit 1d2170a152
3 changed files with 668 additions and 5 deletions
@@ -1,6 +1,8 @@
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using ZB.MOM.WW.Auth.Abstractions.Ldap;
using ZB.MOM.WW.ScadaBridge.Commons.Messages.Management;
@@ -42,9 +44,24 @@ namespace ZB.MOM.WW.ScadaBridge.ManagementService;
/// <see cref="AuthenticatedUser.PermittedSiteIds"/>). The startup <c>AUTH DISABLED</c> warning
/// (emitted by <c>AddSecurity</c>) already announces this posture. Dev/test ONLY.
/// </para>
/// <para>
/// <b>No role, no login</b> (ScadaBridge#145, the management-surface half of #144; scadaproj NAM
/// cutover plan §3.2): a Basic bind whose groups map to zero roles, or whose role mapping throws,
/// is refused exactly like a bad password — the same <c>401 AUTH_FAILED</c> body and a
/// <see cref="LoginThrottle"/> failure — and a bearer token that carries no role claim is refused
/// like any other invalid token. Every refusal is logged at Warning under
/// <see cref="LoggerCategory"/> with the endpoint, the username and the reason. Because the three
/// callers (<see cref="ManagementEndpoints"/>, <see cref="AuditEndpoints"/>, the debug-stream hub)
/// take their <see cref="AuthenticatedUser"/> only from here, none of them can admit a role-less
/// principal — including the commands <c>ManagementActor.GetRequiredRoles</c> opens to any
/// authenticated user.
/// </para>
/// </remarks>
public static class ManagementAuthenticator
{
/// <summary>The logger category for the sign-in refusals logged by this authenticator.</summary>
public const string LoggerCategory = "ZB.MOM.WW.ScadaBridge.ManagementService.ManagementAuthenticator";
/// <summary>Outcome of <see cref="AuthenticateAsync"/>: exactly one of the two fields is set.</summary>
/// <param name="User">The authenticated principal on success; otherwise <see langword="null"/>.</param>
/// <param name="Failure">The 401 <see cref="IResult"/> to return on failure; otherwise <see langword="null"/>.</param>
@@ -143,11 +160,19 @@ public static class ManagementAuthenticator
new { error = LdapAuthFailureMessages.ToMessage(authResult.Failure), code = "AUTH_FAILED" }, statusCode: 401));
}
throttle.RecordSuccess(username, remoteIp!);
// 3. Role resolution. No role, no login (ScadaBridge#145, mirrors #144's /auth/login and
// /auth/token): a successful bind whose groups map to zero roles — or whose mapping
// throws — is refused exactly like a bad password: same 401 body, a throttle failure.
// The reason is logged server-side only.
var mappingResult = await ResolveBasicRolesAsync(context, authResult, username);
if (mappingResult is null)
{
throttle.RecordFailure(username, remoteIp!);
return new AuthOutcome(null, Results.Json(
new { error = LdapAuthFailureMessages.InvalidCredentials, code = "AUTH_FAILED" }, statusCode: 401));
}
// 3. Role resolution
var roleMapper = context.RequestServices.GetRequiredService<RoleMapper>();
var mappingResult = await roleMapper.MapGroupsToRolesAsync(authResult.Groups, context.RequestAborted);
throttle.RecordSuccess(username, remoteIp!);
var permittedSiteIds = mappingResult.IsSystemWideDeployment
? Array.Empty<string>()
@@ -162,10 +187,67 @@ public static class ManagementAuthenticator
return new AuthOutcome(resolvedUser, null);
}
/// <summary>
/// Maps a successful Basic bind's groups to roles, enforcing <b>no role, no login</b>
/// (ScadaBridge#145). Returns <see langword="null"/> — the caller then answers exactly as for a
/// bad password — when the groups map to zero roles or the mapper throws; the refusal is logged
/// at Warning with the endpoint, the username and the reason. Cancellation of the request is not
/// a refusal and propagates.
/// </summary>
/// <param name="context">The current HTTP context (services, request path, request-aborted token).</param>
/// <param name="authResult">The successful LDAP bind result.</param>
/// <param name="username">The username as sent, used when the bind returned no canonical name.</param>
/// <returns>The role mapping, or <see langword="null"/> when the request must be refused.</returns>
private static async Task<RoleMappingResult?> ResolveBasicRolesAsync(
HttpContext context, LdapAuthResult authResult, string username)
{
var logger = Logger(context);
var endpoint = EndpointName(context);
var who = string.IsNullOrEmpty(authResult.Username) ? username : authResult.Username;
RoleMappingResult mappingResult;
try
{
var roleMapper = context.RequestServices.GetRequiredService<RoleMapper>();
mappingResult = await roleMapper.MapGroupsToRolesAsync(authResult.Groups, context.RequestAborted);
}
catch (OperationCanceledException) when (context.RequestAborted.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
logger.LogWarning(ex,
"Sign-in refused at {Endpoint} for {Username}: the LDAP bind succeeded but role mapping failed. " +
"The client sees the bad-credentials response.",
endpoint, who);
return null;
}
if (mappingResult.Roles is not { Count: > 0 })
{
logger.LogWarning(
"Sign-in refused at {Endpoint} for {Username}: the LDAP bind succeeded but none of the user's {GroupCount} " +
"group(s) maps to a ScadaBridge role. The client sees the bad-credentials response.",
endpoint, who, authResult.Groups.Count);
return null;
}
return mappingResult;
}
private static ILogger Logger(HttpContext context) =>
context.RequestServices.GetService<ILoggerFactory>()?.CreateLogger(LoggerCategory) ?? NullLogger.Instance;
private static string EndpointName(HttpContext context) =>
context.Request.Path.HasValue ? context.Request.Path.Value! : "management";
/// <summary>
/// Validates a bearer JWT and projects its claims onto an <see cref="AuthenticatedUser"/>.
/// The token's roles and site scope are taken as-is (authoritative until expiry); an
/// empty site-id set is the same system-wide signal the Basic path produces.
/// empty site-id set is the same system-wide signal the Basic path produces. A token with
/// no role claim is refused like an invalid token (ScadaBridge#145): <c>/auth/token</c> no
/// longer mints one, but a token minted before that rule shipped stays valid until it expires.
/// </summary>
private static AuthOutcome AuthenticateBearer(HttpContext context, string token)
{
@@ -181,8 +263,21 @@ public static class ManagementAuthenticator
var displayName = principal.FindFirst(JwtTokenService.DisplayNameClaimType)?.Value;
var roles = principal.FindAll(JwtTokenService.RoleClaimType)
.Select(c => c.Value)
.Where(r => !string.IsNullOrWhiteSpace(r))
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToArray();
// No role, no login (ScadaBridge#145): the same 401 as an invalid token. Like any other
// bearer failure it performs no LDAP bind, so it does not feed the login throttle.
if (roles.Length == 0)
{
Logger(context).LogWarning(
"Sign-in refused at {Endpoint} for {Username}: the bearer token carries no ScadaBridge role. " +
"The client sees the invalid-token response.",
EndpointName(context), username);
return new AuthOutcome(null, Results.Json(
new { error = "Invalid or expired bearer token.", code = "AUTH_FAILED" }, statusCode: 401));
}
var permittedSiteIds = principal.FindAll(JwtTokenService.SiteIdClaimType)
.Select(c => c.Value)
.Distinct(StringComparer.Ordinal)