fix(auth): refuse zero-role sign-in at /auth/login and /auth/token (#144)
A successful LDAP bind whose groups map to no ScadaBridge role, or whose role mapping throws, is now refused at both sign-in endpoints exactly like a bad password: the same redirect/401 body, no cookie, no token, and a login-throttle failure (so the throttle is not an oracle). The reason is logged server-side at Warning with the endpoint and username. Family standard: scadaproj NAM AD cutover plan §3.2 (Phase A2, §2A). Tests: zero roles, mapper throws, and one role for both endpoints, plus the throttle accounting; RoutePolicyCoverageTests now notes that the two bare [Authorize] pages rely on this rule. Claude-Session: https://claude.ai/code/session_01GT67AFKC45MBz1wPZnVbX8
This commit is contained in:
@@ -6,6 +6,8 @@ using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Routing;
|
||||
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.Auth.Abstractions.Roles;
|
||||
@@ -66,25 +68,27 @@ public static class AuthEndpoints
|
||||
return;
|
||||
}
|
||||
|
||||
throttle.RecordSuccess(username, remoteIp!);
|
||||
|
||||
// Map LDAP groups to roles via the shared IGroupRoleMapper<string> seam
|
||||
// (ScadaBridgeGroupRoleMapper, wrapping the DB-backed RoleMapper).
|
||||
// The full RoleMappingResult — including PermittedSiteIds and the
|
||||
// system-wide flag — is carried in the mapping's opaque Scope so the
|
||||
// site-scope→SiteId claims below are built exactly as before.
|
||||
var roleMapping = await roleMapper.MapAsync(authResult.Groups, context.RequestAborted);
|
||||
//
|
||||
// No role, no login (ScadaBridge#144; scadaproj NAM cutover plan §3.2): a
|
||||
// successful bind whose groups map to zero roles — or whose mapping throws —
|
||||
// is refused exactly like a bad password: same message, a throttle failure, no
|
||||
// cookie. The reason is logged server-side only.
|
||||
var resolved = await ResolveSignInRolesAsync(context, roleMapper, authResult, username, "/auth/login");
|
||||
if (resolved is null)
|
||||
{
|
||||
throttle.RecordFailure(username, remoteIp!);
|
||||
var errorMsg = Uri.EscapeDataString(LdapAuthFailureMessages.InvalidCredentials);
|
||||
context.Response.Redirect($"/login?error={errorMsg}");
|
||||
return;
|
||||
}
|
||||
|
||||
// The ScadaBridge mapper carries the full RoleMappingResult in the seam's
|
||||
// opaque Scope (see ScadaBridgeGroupRoleMapper). Guard the unwrap (review I4):
|
||||
// a future/alternate IGroupRoleMapper<string> could leave Scope null or set a
|
||||
// different type. Rather than throw InvalidCastException mid-login, fall back to
|
||||
// the most restrictive interpretation — not a system-wide deployment and no
|
||||
// permitted sites — so no SiteId claims are stamped (deny-by-omission). The real
|
||||
// ScadaBridge mapper always supplies a RoleMappingResult, so behaviour is unchanged.
|
||||
var scope = roleMapping.Scope is RoleMappingResult mapped
|
||||
? mapped
|
||||
: new RoleMappingResult(roleMapping.Roles, [], IsSystemWideDeployment: false);
|
||||
throttle.RecordSuccess(username, remoteIp!);
|
||||
var scope = resolved.Value.Scope;
|
||||
|
||||
// Build claims from LDAP auth + role mapping.
|
||||
// No fixed "expires_at" absolute-cap claim is stamped
|
||||
@@ -171,7 +175,8 @@ public static class AuthEndpoints
|
||||
/// sharing the signing key might honour.
|
||||
/// </remarks>
|
||||
/// <param name="context">The current HTTP context.</param>
|
||||
/// <returns>The token JSON on success; 400/401/404/429 otherwise.</returns>
|
||||
/// <returns>The token JSON on success; 400/401/404/429 otherwise. A bind whose groups map to no
|
||||
/// role (or whose role mapping fails) answers the same <c>401 AUTH_FAILED</c> as a bad password.</returns>
|
||||
public static async Task<IResult> HandleTokenAsync(HttpContext context)
|
||||
{
|
||||
var disableLogin = context.RequestServices.GetService<IOptions<AuthDisableLoginOptions>>()?.Value;
|
||||
@@ -220,16 +225,19 @@ public static class AuthEndpoints
|
||||
statusCode: 401);
|
||||
}
|
||||
|
||||
// No role, no token (ScadaBridge#144): refused exactly like a bad password — the
|
||||
// same 401 body, a throttle failure, no token. See ResolveSignInRolesAsync.
|
||||
var resolved = await ResolveSignInRolesAsync(context, roleMapper, authResult, username, "/auth/token");
|
||||
if (resolved is null)
|
||||
{
|
||||
throttle.RecordFailure(username, remoteIp!);
|
||||
return Results.Json(
|
||||
new { error = LdapAuthFailureMessages.InvalidCredentials, code = "AUTH_FAILED" },
|
||||
statusCode: 401);
|
||||
}
|
||||
|
||||
throttle.RecordSuccess(username, remoteIp!);
|
||||
|
||||
var roleMapping = await roleMapper.MapAsync(authResult.Groups, context.RequestAborted);
|
||||
|
||||
// Guard the opaque-Scope unwrap (review I4); see the matching note on
|
||||
// /auth/login. Fall back to no site-scope rather than throwing if a future
|
||||
// mapper leaves Scope null or sets a different type.
|
||||
var scope = roleMapping.Scope is RoleMappingResult mapped
|
||||
? mapped
|
||||
: new RoleMappingResult(roleMapping.Roles, [], IsSystemWideDeployment: false);
|
||||
var (roleMapping, scope) = resolved.Value;
|
||||
|
||||
var displayName = string.IsNullOrEmpty(authResult.DisplayName) ? username : authResult.DisplayName;
|
||||
var resolvedUsername = string.IsNullOrEmpty(authResult.Username) ? username : authResult.Username;
|
||||
@@ -254,6 +262,73 @@ public static class AuthEndpoints
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>The logger category for the sign-in refusals logged by these endpoints.</summary>
|
||||
public const string LoggerCategory = "ZB.MOM.WW.ScadaBridge.CentralUI.Auth.AuthEndpoints";
|
||||
|
||||
/// <summary>
|
||||
/// Maps a successful bind's groups to roles for <c>/auth/login</c> and <c>/auth/token</c>, enforcing
|
||||
/// the family rule <b>no role, no login</b> (ScadaBridge#144; scadaproj NAM cutover plan §3.2).
|
||||
/// 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 username
|
||||
/// and the reason. Cancellation of the request is not a refusal and propagates.
|
||||
/// </summary>
|
||||
/// <param name="context">The current HTTP context (services, request-aborted token).</param>
|
||||
/// <param name="roleMapper">The group→role mapping seam.</param>
|
||||
/// <param name="authResult">The successful LDAP bind result.</param>
|
||||
/// <param name="username">The username as typed, used when the bind returned no canonical name.</param>
|
||||
/// <param name="endpoint">The endpoint name, for the log line.</param>
|
||||
/// <returns>The mapping and its site scope, or <see langword="null"/> when sign-in must be refused.</returns>
|
||||
private static async Task<(GroupRoleMapping<string> Mapping, RoleMappingResult Scope)?> ResolveSignInRolesAsync(
|
||||
HttpContext context,
|
||||
IGroupRoleMapper<string> roleMapper,
|
||||
LdapAuthResult authResult,
|
||||
string username,
|
||||
string endpoint)
|
||||
{
|
||||
var logger = context.RequestServices.GetService<ILoggerFactory>()?.CreateLogger(LoggerCategory)
|
||||
?? NullLogger.Instance;
|
||||
var who = string.IsNullOrEmpty(authResult.Username) ? username : authResult.Username;
|
||||
|
||||
GroupRoleMapping<string> roleMapping;
|
||||
try
|
||||
{
|
||||
roleMapping = await roleMapper.MapAsync(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 (roleMapping.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;
|
||||
}
|
||||
|
||||
// The ScadaBridge mapper carries the full RoleMappingResult in the seam's
|
||||
// opaque Scope (see ScadaBridgeGroupRoleMapper). Guard the unwrap (review I4):
|
||||
// a future/alternate IGroupRoleMapper<string> could leave Scope null or set a
|
||||
// different type. Rather than throw InvalidCastException mid-login, fall back to
|
||||
// the most restrictive interpretation — not a system-wide deployment and no
|
||||
// permitted sites — so no SiteId claims are stamped (deny-by-omission). The real
|
||||
// ScadaBridge mapper always supplies a RoleMappingResult, so behaviour is unchanged.
|
||||
var scope = roleMapping.Scope is RoleMappingResult mapped
|
||||
? mapped
|
||||
: new RoleMappingResult(roleMapping.Roles, [], IsSystemWideDeployment: false);
|
||||
return (roleMapping, scope);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Handler for <c>GET /auth/ping</c>. Returns <c>200</c> while the caller's
|
||||
/// cookie session is still valid and <c>401</c> once it has lapsed
|
||||
|
||||
Reference in New Issue
Block a user