From 5a642d1cdf7a9dae673b34ed4303d4a574059d82 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 17 Nov 2026 11:21:00 -0500 Subject: [PATCH] fix(auth): refuse zero-role sign-in at /auth/login and /auth/token (#144) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- .../Auth/AuthEndpoints.cs | 121 ++++++++--- .../Auth/AuthLoginRoleRefusalTests.cs | 193 ++++++++++++++++++ .../Auth/AuthTokenEndpointTests.cs | 117 ++++++++++- .../Auth/CapturingLoggerProvider.cs | 37 ++++ .../Auth/RoutePolicyCoverageTests.cs | 4 + 5 files changed, 443 insertions(+), 29 deletions(-) create mode 100644 tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/AuthLoginRoleRefusalTests.cs create mode 100644 tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/CapturingLoggerProvider.cs diff --git a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Auth/AuthEndpoints.cs b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Auth/AuthEndpoints.cs index 7f6aeff1..b5c9e72d 100644 --- a/src/ZB.MOM.WW.ScadaBridge.CentralUI/Auth/AuthEndpoints.cs +++ b/src/ZB.MOM.WW.ScadaBridge.CentralUI/Auth/AuthEndpoints.cs @@ -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 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 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. /// /// The current HTTP context. - /// The token JSON on success; 400/401/404/429 otherwise. + /// 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 401 AUTH_FAILED as a bad password. public static async Task HandleTokenAsync(HttpContext context) { var disableLogin = context.RequestServices.GetService>()?.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 }); } + /// The logger category for the sign-in refusals logged by these endpoints. + public const string LoggerCategory = "ZB.MOM.WW.ScadaBridge.CentralUI.Auth.AuthEndpoints"; + + /// + /// Maps a successful bind's groups to roles for /auth/login and /auth/token, enforcing + /// the family rule no role, no login (ScadaBridge#144; scadaproj NAM cutover plan §3.2). + /// Returns — 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. + /// + /// The current HTTP context (services, request-aborted token). + /// The group→role mapping seam. + /// The successful LDAP bind result. + /// The username as typed, used when the bind returned no canonical name. + /// The endpoint name, for the log line. + /// The mapping and its site scope, or when sign-in must be refused. + private static async Task<(GroupRoleMapping Mapping, RoleMappingResult Scope)?> ResolveSignInRolesAsync( + HttpContext context, + IGroupRoleMapper roleMapper, + LdapAuthResult authResult, + string username, + string endpoint) + { + var logger = context.RequestServices.GetService()?.CreateLogger(LoggerCategory) + ?? NullLogger.Instance; + var who = string.IsNullOrEmpty(authResult.Username) ? username : authResult.Username; + + GroupRoleMapping 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 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); + } + /// /// Handler for GET /auth/ping. Returns 200 while the caller's /// cookie session is still valid and 401 once it has lapsed diff --git a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/AuthLoginRoleRefusalTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/AuthLoginRoleRefusalTests.cs new file mode 100644 index 00000000..96bd89af --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/AuthLoginRoleRefusalTests.cs @@ -0,0 +1,193 @@ +using Microsoft.AspNetCore.Antiforgery; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using NSubstitute; +using NSubstitute.ExceptionExtensions; +using ZB.MOM.WW.Auth.Abstractions.Ldap; +using ZB.MOM.WW.Auth.Abstractions.Roles; +using ZB.MOM.WW.ScadaBridge.CentralUI.Auth; +using ZB.MOM.WW.ScadaBridge.Security; + +namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Auth; + +/// +/// ScadaBridge#144 — POST /auth/login refuses a successful LDAP bind whose groups map to no +/// ScadaBridge role, and one whose role mapping throws. The refusal must be indistinguishable from a +/// bad password: the same redirect and message, no session cookie, and a login-throttle failure. The +/// reason is logged server-side with the username. +/// +public class AuthLoginRoleRefusalTests +{ + private const string Category = AuthEndpoints.LoggerCategory; + + private sealed record Outcome(int Status, string Location, IReadOnlyList SetCookies); + + private static RequestDelegate LoginDelegate() + { + var builder = WebApplication.CreateBuilder(); + builder.Services.AddRouting(); + builder.Services.AddAntiforgery(); + builder.Services.AddSingleton(); + builder.Services.AddSingleton(TimeProvider.System); + using var app = builder.Build(); + app.MapAuthEndpoints(); + return ((IEndpointRouteBuilder)app).DataSources + .SelectMany(ds => ds.Endpoints) + .OfType() + .Single(e => e.RoutePattern.RawText == "/auth/login" + && (e.Metadata.GetMetadata()?.HttpMethods.Contains("POST") ?? false)) + .RequestDelegate!; + } + + /// Builds the service rig: LDAP accepts alice/password (groups ["G"]) and rejects alice/wrong. + private static ServiceProvider Services( + IGroupRoleMapper mapper, LoginThrottle throttle, CapturingLoggerProvider logs) + { + var services = new ServiceCollection(); + services.AddLogging(b => b.AddProvider(logs)); + services.AddAntiforgery(); + services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(); + services.AddSingleton(throttle); + var ldap = Substitute.For(); + ldap.AuthenticateAsync("alice", "password", Arg.Any()) + .Returns(LdapAuthResult.Success("alice", "Alice", ["Domain Users"])); + ldap.AuthenticateAsync("alice", "wrong", Arg.Any()) + .Returns(LdapAuthResult.Fail(LdapAuthFailure.BadCredentials)); + services.AddSingleton(ldap); + services.AddSingleton(mapper); + return services.BuildServiceProvider(); + } + + private static async Task PostLogin(ServiceProvider provider, string password) + { + var tokenContext = new DefaultHttpContext { RequestServices = provider }; + var tokens = provider.GetRequiredService().GetAndStoreTokens(tokenContext); + var antiforgeryCookie = tokenContext.Response.Headers.SetCookie.Single()!.Split(';')[0]; + + var context = new DefaultHttpContext { RequestServices = provider }; + context.Connection.RemoteIpAddress = System.Net.IPAddress.Loopback; + context.Request.Headers.Cookie = antiforgeryCookie; + context.Request.Method = "POST"; + context.Request.ContentType = "application/x-www-form-urlencoded"; + var form = $"username=alice&password={password}&{tokens.FormFieldName}={Uri.EscapeDataString(tokens.RequestToken!)}"; + context.Request.Body = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(form)); + + await LoginDelegate()(context); + + return new Outcome( + context.Response.StatusCode, + context.Response.Headers.Location.ToString(), + context.Response.Headers.SetCookie.Select(v => v!).ToList()); + } + + private static IGroupRoleMapper MapperReturning(params string[] roles) + { + var mapper = Substitute.For>(); + mapper.MapAsync(Arg.Any>(), Arg.Any()) + .Returns(new GroupRoleMapping(roles, Scope: new RoleMappingResult(roles, [], true))); + return mapper; + } + + private static IGroupRoleMapper MapperThrowing() + { + var mapper = Substitute.For>(); + mapper.MapAsync(Arg.Any>(), Arg.Any()) + .ThrowsAsync(new InvalidOperationException("configuration database unreachable")); + return mapper; + } + + private static LoginThrottle Throttle(int maxFailures = 5) => new(TimeProvider.System, Options.Create(new SecurityOptions + { + MaxLoginFailuresPerWindow = maxFailures, + PerIpMaxFailures = 25, + })); + + private static bool HasSessionCookie(Outcome o) => + o.SetCookies.Any(v => v.StartsWith(".AspNetCore.Cookies=", StringComparison.Ordinal)); + + /// The bad-password response every refusal must match exactly. + private static async Task BadPasswordOutcome() + { + using var provider = Services(MapperReturning(Roles.Viewer), Throttle(), new CapturingLoggerProvider()); + return await PostLogin(provider, "wrong"); + } + + /// A bind whose groups map to zero roles is refused exactly like a bad password, and logged. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Login_ZeroRoles_IsRefusedLikeABadPassword_NoCookie_Logged() + { + var logs = new CapturingLoggerProvider(); + using var provider = Services(MapperReturning(), Throttle(), logs); + + var outcome = await PostLogin(provider, "password"); + var badPassword = await BadPasswordOutcome(); + + Assert.Equal(StatusCodes.Status302Found, outcome.Status); + Assert.Equal(badPassword.Status, outcome.Status); + Assert.Equal(badPassword.Location, outcome.Location); + Assert.Equal("/login?error=" + Uri.EscapeDataString(LdapAuthFailureMessages.InvalidCredentials), outcome.Location); + Assert.False(HasSessionCookie(outcome)); + var entry = Assert.Single(logs.Entries, e => e.Category == Category && e.Level == LogLevel.Warning); + Assert.Contains("alice", entry.Message); + Assert.Contains("maps to a ScadaBridge role", entry.Message); + } + + /// A bind whose role mapping throws is refused exactly like a bad password, and logged with the exception. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Login_MapperThrows_IsRefusedLikeABadPassword_NoCookie_Logged() + { + var logs = new CapturingLoggerProvider(); + using var provider = Services(MapperThrowing(), Throttle(), logs); + + var outcome = await PostLogin(provider, "password"); + var badPassword = await BadPasswordOutcome(); + + Assert.Equal(badPassword.Status, outcome.Status); + Assert.Equal(badPassword.Location, outcome.Location); + Assert.False(HasSessionCookie(outcome)); + var entry = Assert.Single(logs.Entries, e => e.Category == Category && e.Level == LogLevel.Warning); + Assert.Contains("alice", entry.Message); + Assert.Contains("role mapping failed", entry.Message); + Assert.IsType(entry.Exception); + } + + /// + /// A zero-role refusal counts against the login throttle like a bad password, so the throttle + /// cannot be used to tell "right password, no role" apart from "wrong password". + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Login_ZeroRoles_CountsAsAThrottleFailure() + { + var throttle = Throttle(maxFailures: 2); + using var provider = Services(MapperReturning(), throttle, new CapturingLoggerProvider()); + + await PostLogin(provider, "password"); + await PostLogin(provider, "password"); + + Assert.True(throttle.IsLockedOut("alice", System.Net.IPAddress.Loopback.ToString())); + } + + /// One mapped role still signs in and sets the session cookie, with no refusal logged. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Login_OneRole_SignsIn() + { + var logs = new CapturingLoggerProvider(); + using var provider = Services(MapperReturning(Roles.Viewer), Throttle(), logs); + + var outcome = await PostLogin(provider, "password"); + + Assert.Equal(StatusCodes.Status302Found, outcome.Status); + Assert.Equal("/", outcome.Location); + Assert.True(HasSessionCookie(outcome)); + Assert.DoesNotContain(logs.Entries, e => e.Category == Category && e.Level >= LogLevel.Warning); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/AuthTokenEndpointTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/AuthTokenEndpointTests.cs index 77e864e2..dd95197a 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/AuthTokenEndpointTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/AuthTokenEndpointTests.cs @@ -1,9 +1,11 @@ using System.Text.Json; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Microsoft.Extensions.Options; using NSubstitute; +using NSubstitute.ExceptionExtensions; using ZB.MOM.WW.Auth.Abstractions.Ldap; using ZB.MOM.WW.Auth.Abstractions.Roles; using ZB.MOM.WW.ScadaBridge.CentralUI.Auth; @@ -21,22 +23,38 @@ public class AuthTokenEndpointTests { private const string Key = "this-is-a-test-signing-key-for-hmac-sha256-must-be-long-enough"; - private static HttpContext Context(bool disableLogin, RoleMappingResult mapping, out JwtTokenService jwt) + private static HttpContext Context(bool disableLogin, RoleMappingResult mapping, out JwtTokenService jwt, + string password = "pw", Exception? mapperThrows = null, CapturingLoggerProvider? logs = null, + LoginThrottle? throttle = null) { var ldap = Substitute.For(); ldap.AuthenticateAsync("alice", "pw", Arg.Any()) .Returns(LdapAuthResult.Success("alice", "Alice A", ["SiteDeployers"])); + ldap.AuthenticateAsync("alice", "wrong", Arg.Any()) + .Returns(LdapAuthResult.Fail(LdapAuthFailure.BadCredentials)); var mapper = Substitute.For>(); - mapper.MapAsync(Arg.Any>(), Arg.Any()) - .Returns(new GroupRoleMapping(mapping.Roles, Scope: mapping)); + if (mapperThrows is not null) + { + mapper.MapAsync(Arg.Any>(), Arg.Any()).ThrowsAsync(mapperThrows); + } + else + { + mapper.MapAsync(Arg.Any>(), Arg.Any()) + .Returns(new GroupRoleMapping(mapping.Roles, Scope: mapping)); + } + var options = Options.Create(new SecurityOptions { JwtSigningKey = Key, JwtExpiryMinutes = 15 }); jwt = new JwtTokenService(options, NullLogger.Instance); - var services = new ServiceCollection().AddLogging(); + var services = new ServiceCollection().AddLogging(b => + { + if (logs is not null) b.AddProvider(logs); + }); services.AddSingleton(Options.Create(new AuthDisableLoginOptions { DisableLogin = disableLogin })); services.AddSingleton>(options); services.AddSingleton(TimeProvider.System); - services.AddSingleton(); + if (throttle is not null) services.AddSingleton(throttle); + else services.AddSingleton(); services.AddSingleton(ldap); services.AddSingleton(mapper); services.AddSingleton(jwt); @@ -46,8 +64,9 @@ public class AuthTokenEndpointTests context.Request.Form = new FormCollection(new() { ["username"] = "alice", - ["password"] = "pw", + ["password"] = password, }); + context.Connection.RemoteIpAddress = System.Net.IPAddress.Loopback; context.Response.Body = new MemoryStream(); return context; } @@ -106,4 +125,90 @@ public class AuthTokenEndpointTests Assert.Equal(404, status); Assert.False(body.TryGetProperty("access_token", out _)); } + + // ---- ScadaBridge#144: no role, no token ---- + + private static async Task<(int Status, JsonElement Body)> BadPassword() + { + var context = Context(false, new RoleMappingResult([Roles.Deployer], [], true), out _, password: "wrong"); + return await Execute(context); + } + + private static void AssertSameAsBadPassword((int Status, JsonElement Body) refused, (int Status, JsonElement Body) badPassword) + { + Assert.Equal(401, refused.Status); + Assert.Equal(badPassword.Status, refused.Status); + Assert.Equal(badPassword.Body.GetRawText(), refused.Body.GetRawText()); + Assert.Equal(LdapAuthFailureMessages.InvalidCredentials, refused.Body.GetProperty("error").GetString()); + Assert.Equal("AUTH_FAILED", refused.Body.GetProperty("code").GetString()); + Assert.False(refused.Body.TryGetProperty("access_token", out _)); + } + + /// A bind whose groups map to zero roles gets the bad-password 401 and no token; the reason is logged. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Token_ZeroRoles_IsRefusedLikeABadPassword_Logged() + { + var logs = new CapturingLoggerProvider(); + var context = Context(false, new RoleMappingResult([], [], false), out _, logs: logs); + + var refused = await Execute(context); + + AssertSameAsBadPassword(refused, await BadPassword()); + var entry = Assert.Single(logs.Entries, e => e.Category == AuthEndpoints.LoggerCategory && e.Level == LogLevel.Warning); + Assert.Contains("alice", entry.Message); + Assert.Contains("/auth/token", entry.Message); + Assert.Contains("maps to a ScadaBridge role", entry.Message); + } + + /// A bind whose role mapping throws gets the bad-password 401 and no token; the exception is logged. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Token_MapperThrows_IsRefusedLikeABadPassword_Logged() + { + var logs = new CapturingLoggerProvider(); + var context = Context(false, new RoleMappingResult([Roles.Deployer], [], true), out _, + mapperThrows: new InvalidOperationException("configuration database unreachable"), logs: logs); + + var refused = await Execute(context); + + AssertSameAsBadPassword(refused, await BadPassword()); + var entry = Assert.Single(logs.Entries, e => e.Category == AuthEndpoints.LoggerCategory && e.Level == LogLevel.Warning); + Assert.Contains("alice", entry.Message); + Assert.Contains("role mapping failed", entry.Message); + Assert.IsType(entry.Exception); + } + + /// A zero-role refusal counts against the login throttle, like a bad password. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Token_ZeroRoles_CountsAsAThrottleFailure() + { + var throttle = new LoginThrottle(TimeProvider.System, Options.Create(new SecurityOptions + { + MaxLoginFailuresPerWindow = 2, + PerIpMaxFailures = 25, + })); + + await Execute(Context(false, new RoleMappingResult([], [], false), out _, throttle: throttle)); + await Execute(Context(false, new RoleMappingResult([], [], false), out _, throttle: throttle)); + + Assert.True(throttle.IsLockedOut("alice", System.Net.IPAddress.Loopback.ToString())); + } + + /// Exactly one mapped role still gets a token carrying that role. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Token_OneRole_IsIssued() + { + var logs = new CapturingLoggerProvider(); + var context = Context(false, new RoleMappingResult([Roles.Viewer], [], true), out var jwt, logs: logs); + + var (status, body) = await Execute(context); + + Assert.Equal(200, status); + var principal = jwt.ValidateToken(body.GetProperty("access_token").GetString()!); + Assert.Equal([Roles.Viewer], principal!.FindAll(JwtTokenService.RoleClaimType).Select(c => c.Value)); + Assert.DoesNotContain(logs.Entries, e => e.Category == AuthEndpoints.LoggerCategory && e.Level >= LogLevel.Warning); + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/CapturingLoggerProvider.cs b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/CapturingLoggerProvider.cs new file mode 100644 index 00000000..b3757702 --- /dev/null +++ b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/CapturingLoggerProvider.cs @@ -0,0 +1,37 @@ +using System.Collections.Concurrent; +using Microsoft.Extensions.Logging; + +namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Auth; + +/// An in-memory logger provider that records every formatted log line with its category and level. +internal sealed class CapturingLoggerProvider : ILoggerProvider +{ + /// One captured log entry. + /// The logger category. + /// The log level. + /// The formatted message. + /// The logged exception, if any. + public sealed record Entry(string Category, LogLevel Level, string Message, Exception? Exception); + + /// Every entry logged through this provider, in order. + public ConcurrentQueue Entries { get; } = new(); + + /// + public ILogger CreateLogger(string categoryName) => new Logger(categoryName, Entries); + + /// + public void Dispose() + { + } + + private sealed class Logger(string category, ConcurrentQueue sink) : ILogger + { + public IDisposable? BeginScope(TState state) where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => true; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, + Func formatter) => + sink.Enqueue(new Entry(category, logLevel, formatter(state, exception), exception)); + } +} diff --git a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/RoutePolicyCoverageTests.cs b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/RoutePolicyCoverageTests.cs index 9df21df0..bb627bd1 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/RoutePolicyCoverageTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.CentralUI.Tests/Auth/RoutePolicyCoverageTests.cs @@ -12,6 +12,10 @@ public class RoutePolicyCoverageTests [Fact] public void EveryRoutableComponent_HasItsReviewedPolicy_IncludingExternalSecrets() { + // "authenticated" (bare [Authorize]) is safe only because sign-in requires a mapped role: + // /auth/login and /auth/token refuse a zero-role bind, and a session whose roles drop to zero + // is ended by CookieSessionValidator (ScadaBridge#144, "no role, no login"). Do not add an + // "authenticated" page that would be unsafe for a holder of any single role. var expected = new Dictionary { ["/"] = "authenticated",