From 5a642d1cdf7a9dae673b34ed4303d4a574059d82 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 17 Nov 2026 11:21:00 -0500 Subject: [PATCH 1/3] 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", From 2d8d5a3d6fcda1580e5668544af3f313531bfc2f Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 17 Nov 2026 11:21:00 -0500 Subject: [PATCH 2/3] fix(auth): end a cookie session whose roles drop to zero on refresh (#144) The mid-session refresh ended a session only when the directory returned no groups (or the user was gone/disabled/ambiguous). A user still in some groups but in no mapped one, or whose DB mappings were all revoked, kept a signed-in, role-less session that could read the bare-[Authorize] pages. CookieSessionValidator now rejects when the re-map yields zero roles, on ordinary and fail-closed paths. A mapper fault keeps its existing policy (keep grants; fail closed when asked). Docs: Component-Security "No role, no login" (incl. the HTTP Basic gap left as a follow-up), Component-CentralUI, CLAUDE.md. Claude-Session: https://claude.ai/code/session_01GT67AFKC45MBz1wPZnVbX8 --- CLAUDE.md | 1 + docs/requirements/Component-CentralUI.md | 1 + docs/requirements/Component-Security.md | 19 +++++-- .../CookieSessionValidator.cs | 19 ++++++- .../ServiceCollectionExtensions.cs | 2 +- .../CookieSessionValidatorTests.cs | 50 ++++++++++++++++--- .../DirectoryGroupRefreshTests.cs | 41 ++++++++++++++- 7 files changed, 119 insertions(+), 14 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b46485c6..a20a6c3d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -195,6 +195,7 @@ spec for each is `docs/requirements/Component-.md`, and `README.md` carrie - Authentication: direct LDAP bind (username/password), no Kerberos/NTLM. LDAPS/StartTLS required. - Two session models: the **UI** uses an HttpOnly/Secure cookie carrying a data-protected claims ticket (no embedded JWT; shared Data Protection keys; 30-minute idle timeout, DB-only role re-map every 15 min); the **CLI/API** exchanges credentials once per invocation at `POST /auth/token` for a 15-minute HS256 **bearer** JWT (`JwtSigningKey`, >= 32 bytes, shared by both centrals; `management_bearer: true` capability flag; Basic stays as fallback). Bearer roles are authoritative until expiry (revocation lag <= `JwtExpiryMinutes`; rotating the key kills every token). Cookies are the correct transport for Blazor Server (SignalR circuits). Spec: `Component-Security.md`. - LDAP failure: new logins fail; active sessions continue with current roles. +- **No role, no login (ScadaBridge#144, 2026-11-17).** `/auth/login` and `/auth/token` refuse a bind whose groups map to zero roles (or whose role mapping throws) with the exact bad-password response + a throttle failure; the reason is logged server-side only. A cookie session whose refresh maps to zero roles is ended (`CookieSessionValidator` → Reject). HTTP Basic on the management surfaces is not covered yet (follow-up). Spec: `Component-Security.md` *No role, no login*. - Load balancer in front of central UI; cookie-embedded JWT + shared Data Protection keys for failover transparency. - Two-person MxGateway secured writes (M7): two new global roles — `Operator` (initiates) + `Verifier` (approves) — added alongside the canonical `Administrator`/`Designer`/`Deployer`/`Viewer`, with `RequireOperator`/`RequireVerifier` policies. An Operator submits a secured write from the Central UI Secured Writes page (`/operations/secured-writes`); it stays a `Pending` `PendingSecuredWrite` row until a *distinct* Verifier approves it (no-self-approval enforced server-side in the ManagementActor, plus a compare-and-swap race guard). Approval relays a `WriteTagRequest` to the site MxGateway; MxGateway-protocol connections only; each lifecycle event (submit/approve/reject/execute) emits a best-effort `AuditChannel.SecuredWrite` / `AuditKind.SecuredWrite*` central-direct-write row sharing the row id as `CorrelationId`. (SecuredWrite audit rows stamp `SourceNode` via `ICentralAuditWriter`/`INodeIdentityProvider`.) Pending secured writes expire server-side after a configurable TTL (`ManagementServiceOptions.SecuredWritePendingTtl`, default 24 h): an overdue `Pending` row is CAS'd to `Expired` (never relayed) — enforced at approve/reject and swept opportunistically on list (arch-review S2, `AuditKind.SecuredWriteExpire`). - **Inbound API key store — per node by default, shared on central pairs (2026-09-02, register row 108).** The shared `ZB.MOM.WW.Auth.ApiKeys` library stores inbound keys in **SQLite per node** unless `ScadaBridge:InboundApi:ApiKeyStore:Provider=SqlServer`, which points both central nodes at the same `zbauth` schema in the configuration database (library `ZB.MOM.WW.Auth.ApiKeys.SqlServer` 0.3.0) — under `SqlServer`, create/revoke/rotate/scope changes are cluster-wide immediately; a node's existing SQLite file is imported once at boot (insert-where-absent, safe on both nodes of a pair) and renamed `*.imported`. Central pairs **MUST** run `Provider=SqlServer` — a clustered Central left on `Sqlite` boots fine but `StartupValidator` logs a Warning, because a failover otherwise 401s every inbound client until keys are re-issued on the survivor. Both docker rigs (`docker/`, `docker-env2/`) run `SqlServer`; QA (`vq03`/`vq04`) runs `SqlServer` for both inbound keys and secrets since 2026-10-22 (deployment record `2026-10-22-wonder-app-vq03-vq04-3808b49f.md`); DEV (`vd03`, single node — not production) is not switched. The boot import's `*.imported` rename needs the importer's pooled SQLite handle released first — Windows refuses to rename an open file (fixed `6ed6800b`; pre-fix Windows builds need the manual rename in the runbook). Design: `docs/plans/2026-09-02-inbound-api-key-shared-store-design.md`; runbook: `docs/operations/inbound-api-key-reissue.md` → *Central pairs*. diff --git a/docs/requirements/Component-CentralUI.md b/docs/requirements/Component-CentralUI.md index b7f8274b..9f9cdcd4 100644 --- a/docs/requirements/Component-CentralUI.md +++ b/docs/requirements/Component-CentralUI.md @@ -25,6 +25,7 @@ Central cluster only. Sites have no user interface. ## Review hardening (2026-09-09) - Cookie login validates an antiforgery token before reading credentials or calling LDAP; the login form supplies the token. The JSON token endpoint retains its non-cookie client contract. +- Cookie login and the token endpoint refuse a bind whose groups map to no role, or whose role mapping fails, exactly as for a bad password (ScadaBridge#144; see `Component-Security.md` *No role, no login*). This is what makes the two bare-`[Authorize]` pages (`/`, `/monitoring/health`) safe. - Manual failover goes through a scoped `AuthorizedManualFailoverService` that refreshes the circuit's Administrator grant before calling the host singleton. The component's visibility policy is an additional presentation guard. - Flow Debugger method-entry Live runs are unavailable to a site-scoped Deployer (Gitea #55): the *Inbound API method* entry is disabled with the reason as a tooltip and an inline note, the page starts on script entry, a `?methodId=` drill-in or a stored method choice is ignored, and the server refuses the command regardless. Script entry on a permitted instance and Replay stay available. - Flow Debugger retry/discard validates the current Deployer grant and resolves site scope inside its service. Scoped callers cannot relay an unknown site. Refresh merges preserve Replay's event ordering and append only rows known exclusively to the live run. diff --git a/docs/requirements/Component-Security.md b/docs/requirements/Component-Security.md index e7623150..b4513096 100644 --- a/docs/requirements/Component-Security.md +++ b/docs/requirements/Component-Security.md @@ -32,6 +32,17 @@ Central cluster. Sites do not have user-facing interfaces and do not perform ind Set in a local or docker-dev environment via the environment variable `ScadaBridge__Security__Auth__DisableLogin=true`. Note that `ScadaBridge:Security:Auth` is a child sub-section nested inside `ScadaBridge:Security`. +## No role, no login (ScadaBridge#144) + +A successful LDAP bind is **not** enough to sign in: the user's groups must map to **at least one** ScadaBridge role. This is the family standard (scadaproj NAM AD cutover plan §3.2), and it matters once the LDAP search base is domain-wide — without it, any directory user could sign in role-less and read the bare-`[Authorize]` pages (`/` and `/monitoring/health`). + +- **Both sign-in endpoints refuse.** `POST /auth/login` and `POST /auth/token` refuse a bind whose groups map to **zero roles**, and a bind whose **role mapping throws** (e.g. the configuration database is unreachable). +- **Indistinguishable from a bad password.** The client gets exactly the bad-credentials response — `/auth/login` redirects to `/login?error=Invalid username or password.` with no session cookie; `/auth/token` answers `401` `{ error: "Invalid username or password.", code: "AUTH_FAILED" }` with no token. The refusal also **counts as a login-throttle failure**, so the throttle cannot be used to tell "right password, no role" from "wrong password". +- **Logged server-side only.** Each refusal is logged at Warning (category `ZB.MOM.WW.ScadaBridge.CentralUI.Auth.AuthEndpoints`) with the endpoint, the username and the reason (no mapped role, with the group count; or the mapping exception). There is no login audit event in the Audit Log — sign-in success and failure are not audited today — so the log line is the record. +- **Sessions end the same way.** A cookie session whose groups map to zero roles on a refresh is ended (see *Cookie session lifecycle*). +- **HTTP Basic is not covered yet.** `ManagementAuthenticator`'s Basic branch (`POST /management`, the audit REST endpoints, the debug-stream hub) still authenticates a zero-role bind. Role-gated commands deny it, but the read-only management queries that `ManagementActor.GetRequiredRoles` opens to *any authenticated user* answer it. Closing that is a follow-up to ScadaBridge#144. +- Under the dev/test `DisableLogin` flag none of this runs: the auto-login identity holds every role. + ## Session Management ### Interactive sessions — cookie claims ticket @@ -41,7 +52,7 @@ Set in a local or docker-dev environment via the environment variable `ScadaBrid - Both central nodes share the ASP.NET Data Protection key ring, so either node can read a cookie the other issued. ### CLI / API sessions — bearer JWT (`POST /auth/token`) -- `POST /auth/token` (form `username`/`password`) performs the LDAP bind (login-throttled), maps the groups to roles and site scope, and returns a short-lived **HS256 JWT** signed with `SecurityOptions.JwtSigningKey`, shared by both central nodes: `{ access_token, token_type: "Bearer", expires_in, management_bearer: true, username, display_name, roles }`. +- `POST /auth/token` (form `username`/`password`) performs the LDAP bind (login-throttled), maps the groups to roles and site scope (zero roles, or a mapping fault, is refused as a bad password — *No role, no login* above), and returns a short-lived **HS256 JWT** signed with `SecurityOptions.JwtSigningKey`, shared by both central nodes: `{ access_token, token_type: "Bearer", expires_in, management_bearer: true, username, display_name, roles }`. - **JWT claims**: display name, username, roles, and for a site-scoped Deployer the permitted site IDs (no site claims = system-wide, the same normalisation the Basic path uses). Issuer and audience are both fixed to `scadabridge-central`. Lifetime is `JwtExpiryMinutes` (default **15**). - `ManagementAuthenticator` accepts `Authorization: Bearer ` alongside HTTP Basic on every CLI-facing surface: `POST /management`, the audit REST endpoints, and the debug-stream hub (`/hubs/debug-stream`, token in the `Authorization` header of the negotiate request and WebSocket upgrade). Validation checks the HS256 signature, issuer, audience and lifetime (30 s clock skew for node-to-node drift; `nbf` is back-dated by the same skew so a peer whose clock lags the issuer accepts a fresh token after failover); unsigned (`alg=none`) or other-algorithm tokens are rejected, and a failure is a plain `401 AUTH_FAILED` (no LDAP bind, so it does not feed the login throttle). The token is never logged. - **Roles and scope inside a valid token are authoritative for its lifetime**: a bearer request performs no LDAP bind and no role re-map. A role revocation therefore reaches a bearer caller when its token expires (≤ `JwtExpiryMinutes`); rotating `JwtSigningKey` invalidates every outstanding token immediately. @@ -52,15 +63,15 @@ Set in a local or docker-dev environment via the environment variable `ScadaBrid ### Cookie session lifecycle - **Idle timeout**: Configurable, default **30 minutes**. Without eligible activity within the idle window, the session is rejected and the user must re-login. Passive `/auth/ping`, activity prevalidation, and Blazor transport requests preserve the activity anchor and suppress sliding renewal; the activity endpoint renews only after authentication and antiforgery validation. Tracked via a `LastActivity` last-activity timestamp claim. The cookie's `ExpireTimeSpan` is set to the idle timeout and `SlidingExpiration` renews it on activity, so the cookie window and the explicit `OnValidatePrincipal` idle check use the **same** value and cannot contradict each other. -- **Role-mapping refresh (DB)**: Configurable, default **15 minutes** (`SecurityOptions.RoleRefreshThresholdMinutes`). At login the session stores the user's raw LDAP groups (one `zb:group` claim each) plus a `zb:lastrolerefresh` anchor. Once the anchor is older than the threshold, `OnValidatePrincipal` re-runs the **DB-backed** `RoleMapper` on the session's groups (the stored ones, or the ones just re-read from the directory — see the next item), rebuilds the role/scope claims via the shared claim-builder, advances the anchor, and re-issues the cookie. Central role-mapping (DB) changes — including a **revoked** mapping that drops the user's roles, and changed site-scope rules — take effect within this window. Ordinary HTTP validation uses this threshold. A live circuit refreshes mappings in fresh scopes on authentication-state reads — display reads (`GetAuthenticationStateAsync`) at most once per `CookieAuthenticationStateProvider.NonAuthoritativeRefreshInterval` (10 s) per circuit — and mutation entrypoints (`GetAuthoritativeStateAsync`) require a successful current mapping before every dispatch. +- **Role-mapping refresh (DB)**: Configurable, default **15 minutes** (`SecurityOptions.RoleRefreshThresholdMinutes`). At login the session stores the user's raw LDAP groups (one `zb:group` claim each) plus a `zb:lastrolerefresh` anchor. Once the anchor is older than the threshold, `OnValidatePrincipal` re-runs the **DB-backed** `RoleMapper` on the session's groups (the stored ones, or the ones just re-read from the directory — see the next item), rebuilds the role/scope claims via the shared claim-builder, advances the anchor, and re-issues the cookie. Central role-mapping (DB) changes — including a **revoked** mapping that drops some of the user's roles, and changed site-scope rules — take effect within this window. A refresh under which the user's groups map to **no role at all** ends the session (HTTP rejects the principal and clears the cookie; a circuit's state becomes anonymous), on ordinary and fail-closed validation alike, because a new login would be refused (ScadaBridge#144). A mapping **fault** is not this case: it keeps the current grants on ordinary validation and fails closed on authoritative checks (see *Session Validation*). Ordinary HTTP validation uses this threshold. A live circuit refreshes mappings in fresh scopes on authentication-state reads — display reads (`GetAuthenticationStateAsync`) at most once per `CookieAuthenticationStateProvider.NonAuthoritativeRefreshInterval` (10 s) per circuit — and mutation entrypoints (`GetAuthoritativeStateAsync`) require a successful current mapping before every dispatch. - **Directory group re-query (ScadaBridge#46)**: Configurable, default **on, every 15 minutes** (`SecurityOptions.LdapGroupRefresh`: `Enabled` = `true`, `IntervalMinutes` = `15`, `CacheSeconds` = `60`; config `ScadaBridge:Security:LdapGroupRefresh:*`). Login also stamps a `zb:lastgrouprefresh` anchor. Once it is older than `IntervalMinutes`, the next validation — HTTP `OnValidatePrincipal`, a circuit display read or an authoritative mutation check — re-reads the user's groups from the directory through the shared library's passwordless `ILdapGroupLookup` (Auth `0.5.0`; it binds as the configured **service account**, never the user), replaces the stored `zb:group` claims, re-runs the role mapping, and advances the anchor. A directory group removal or addition therefore reaches an open session — browser and circuit — within the interval, without re-login. Its cadence is independent of `RoleRefreshThresholdMinutes` and of the 10 s circuit refresh: a circuit queries the directory at most once per interval. One user's answer is reused on a node for `CacheSeconds`, so the cookie path and every circuit of that user cost one directory query. A cookie issued before this feature (no anchor) is due on its first validation. - - **Outcome policy.** *Directory unavailable* (connect/TLS, service-account bind or search failed on every endpoint, including `FallbackServers`) **keeps the stored groups and roles** and logs a warning — on every path, including the fail-closed authoritative check — and the anchor still advances, so an outage costs one attempt per interval rather than one per request (availability first, consistent with *LDAP Connection Failure* below). Any answer under which a **new login would now be refused for a user-side reason** — account **not found** (deleted/renamed), **disabled** (AD `userAccountControl`), **ambiguous** (two entries), or found with **no groups** — **ends the session** on every path: HTTP rejects the principal and clears the cookie (the user lands on `/login`), and a circuit's state becomes anonymous so the next gate denies. Ending the session (rather than leaving a signed-in, role-less session) is chosen because it is what the login path would decide and it cannot be mistaken for a working account. *Not supported* (LDAP configured with `BindMode = User`, i.e. no service account) or LDAP disabled keeps the stored groups; the feature is then inert and logs that once. + - **Outcome policy.** *Directory unavailable* (connect/TLS, service-account bind or search failed on every endpoint, including `FallbackServers`) **keeps the stored groups and roles** and logs a warning — on every path, including the fail-closed authoritative check — and the anchor still advances, so an outage costs one attempt per interval rather than one per request (availability first, consistent with *LDAP Connection Failure* below). Any answer under which a **new login would now be refused for a user-side reason** — account **not found** (deleted/renamed), **disabled** (AD `userAccountControl`), **ambiguous** (two entries), or found with **no groups** — **ends the session** on every path (and so does a directory answer whose groups all map to **no role**, through the zero-role rule of the DB re-map above — ScadaBridge#144): HTTP rejects the principal and clears the cookie (the user lands on `/login`), and a circuit's state becomes anonymous so the next gate denies. Ending the session (rather than leaving a signed-in, role-less session) is chosen because it is what the login path would decide and it cannot be mistaken for a working account. *Not supported* (LDAP configured with `BindMode = User`, i.e. no service account) or LDAP disabled keeps the stored groups; the feature is then inert and logs that once. - **Off switches.** `LdapGroupRefresh:Enabled = false` restores the pre-#46 behaviour (stored groups until next login). Under `ScadaBridge:Security:Auth:DisableLogin` no cookie validation runs at all, so no directory query is made. Bearer tokens and HTTP Basic are unaffected: a token's claims are authoritative for its lifetime, and Basic binds per request. - **Role-mapping cache**: `RoleMapper` reads the LDAP-group→role table and the scope rules of every Deployer mapping through a process-wide `RoleMappingCache` snapshot (`SecurityOptions.RoleMappingCacheSeconds`, default **30**; `0` disables). One refresh loads the whole table plus all Deployer scope rules, so a cache hit costs no database round-trip — previously every Basic-authenticated management request and every circuit auth-state read issued `GetAllMappingsAsync` plus one `GetScopeRulesForMappingAsync` per matched Deployer mapping. Without an explicit invalidation a mapping or scope-rule change is therefore visible on every node within the TTL. `RoleMappingCache.Invalidate()` discards the calling node's snapshot so its next mapping re-reads the database (a refresh started before an invalidation is never published over it); the Management Service's mapping/scope-rule handlers also publish `RoleMappingsInvalidated` on the central cache-invalidation topic, so the peer central node discards its snapshot too (audit D1, ScadaBridge#100 item 3) and the TTL is only the fallback. `RoleMappingCacheSeconds = 0` bypasses the snapshot and reads only the matched mappings' scope rules per call. #### Session Validation (`OnValidatePrincipal`) - The cookie principal is built at login by a **single shared claim-builder** (`SessionClaimBuilder`). The `OnValidatePrincipal` role-refresh path rebuilds the principal through the **same** builder, so the login and refresh claim shapes cannot drift. -- **Failure policy**: ordinary cookie validation and display-state refresh retain existing grants on a mapping lookup error. Authoritative circuit mutation checks fail closed on the same error, so a mutation cannot proceed using grants that could not be refreshed. Idle timeout rejects the principal. +- **Failure policy**: ordinary cookie validation and display-state refresh retain existing grants on a mapping lookup error. Authoritative circuit mutation checks fail closed on the same error, so a mutation cannot proceed using grants that could not be refreshed. Idle timeout rejects the principal, and so does a successful refresh that maps the user to no role (ScadaBridge#144). > **Directory group-membership changes (resolved by ScadaBridge#46).** Earlier builds re-mapped > only the **stored** groups mid-session, so a directory group change waited for the next login; diff --git a/src/ZB.MOM.WW.ScadaBridge.Security/CookieSessionValidator.cs b/src/ZB.MOM.WW.ScadaBridge.Security/CookieSessionValidator.cs index bf54c74e..edb2289e 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Security/CookieSessionValidator.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Security/CookieSessionValidator.cs @@ -37,7 +37,7 @@ public enum SessionValidationAction /// Leave the principal as-is (no idle timeout, no refresh due, or a refresh error we swallow). Keep, - /// The session is idle-timed-out, or the directory says the user can no longer sign in; reject + sign out. + /// The session is idle-timed-out, the directory says the user can no longer sign in, or the user's groups now map to no role; reject + sign out. Reject, /// The role mapping was refreshed; replace the principal. The HTTP adapter decides whether renewal is appropriate. @@ -66,7 +66,9 @@ public enum SessionValidationAction /// = 15): when the elapsed time since /// exceeds the threshold, the stored groups are re-mapped and the principal is rebuilt via /// (identical shape to /auth/login). If the DB -/// mapping revoked the user's roles, the rebuilt principal reflects the loss. +/// mapping revoked some of the user's roles, the rebuilt principal reflects the loss; if it revoked +/// ALL of them, the session ends () — the same +/// "no role, no login" rule /auth/login applies (ScadaBridge#144). /// /// /// Directory group re-query (ScadaBridge#46): when the session's @@ -251,6 +253,19 @@ public sealed class CookieSessionValidator // Re-run the DB-backed mapping on the (possibly just re-read) groups. var mapping = await _roleMapper.MapAsync(groups, ct).ConfigureAwait(false); + + // No role, no session (ScadaBridge#144): a login whose groups map to no role is refused, so a + // session whose groups now map to no role ends the same way — on the DB-only re-map and after + // a directory re-query alike. A mapper FAULT is not this case: it throws above and the failure + // policy in ValidateAsync applies (keep on ordinary validation, propagate when fail-closed). + if (mapping.Roles is not { Count: > 0 }) + { + _logger.LogWarning( + "Cookie session for {Username} ended: its {GroupCount} group(s) now map to no ScadaBridge role (a new sign-in would be refused).", + username, groups.Count); + return SessionValidationResult.Reject; + } + var scope = mapping.Scope is RoleMappingResult mapped ? mapped : new RoleMappingResult(mapping.Roles, [], IsSystemWideDeployment: false); diff --git a/src/ZB.MOM.WW.ScadaBridge.Security/ServiceCollectionExtensions.cs b/src/ZB.MOM.WW.ScadaBridge.Security/ServiceCollectionExtensions.cs index 19a7ba76..3c2c87c6 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Security/ServiceCollectionExtensions.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Security/ServiceCollectionExtensions.cs @@ -254,7 +254,7 @@ public static class ServiceCollectionExtensions /// adapter. It resolves the request-scoped , /// asks it for a decision, and applies it to the cookie context: /// - /// → + sign out (idle timeout, or the directory reports the user gone/disabled/ambiguous/group-less — ScadaBridge#46). + /// → + sign out (idle timeout, the directory reports the user gone/disabled/ambiguous/group-less — ScadaBridge#46, or the user's groups now map to no role — ScadaBridge#144). /// → + renewal only for non-passive requests (role mapping refreshed). /// → no-op (no refresh due, or a swallowed refresh fault). /// diff --git a/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/CookieSessionValidatorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/CookieSessionValidatorTests.cs index cacd78cc..f79c4400 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/CookieSessionValidatorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/CookieSessionValidatorTests.cs @@ -214,10 +214,17 @@ public class CookieSessionValidatorTests Assert.Equal(clock.GetUtcNow(), refreshedAt); } - /// Verifies that a user whose group was revoked loses the roles on refresh. + /// + /// Verifies that a user whose every role mapping was revoked has the session ENDED on refresh + /// (ScadaBridge#144: no role, no login — and so no role-less session either). Before #144 the + /// session was replaced with a role-less principal that could still read bare-[Authorize] pages. + /// + /// Whether the caller is an authoritative (fail-closed) check. /// A task that represents the asynchronous operation. - [Fact] - public async Task ValidateAsync_RevokedGroupUser_LosesRolesOnRefresh() + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ValidateAsync_RevokedGroupUser_RefreshToZeroRoles_EndsTheSession(bool failClosed) { var clock = new TestTimeProvider(Start); var principal = Session(Start, ["SCADA-Admins"], @@ -227,13 +234,44 @@ public class CookieSessionValidatorTests var mapper = new FakeGroupRoleMapper(new RoleMappingResult([], [], IsSystemWideDeployment: false)); var sut = CreateValidator(mapper, clock); + clock.Advance(TimeSpan.FromMinutes(16)); + var result = await sut.ValidateAsync(principal, failClosed: failClosed); + + Assert.Equal(SessionValidationAction.Reject, result.Action); + Assert.Null(result.Principal); + Assert.Equal(1, mapper.CallCount); + } + + /// A forced (circuit) refresh to zero roles ends the session too, before the threshold. + /// A task that represents the asynchronous operation. + [Fact] + public async Task ValidateAsync_ForcedRefreshToZeroRoles_EndsTheSession() + { + var clock = new TestTimeProvider(Start); + var principal = Session(Start, ["SCADA-Admins"], + new RoleMappingResult([Roles.Administrator], [], true)); + var sut = CreateValidator(new FakeGroupRoleMapper(new RoleMappingResult([], [], false)), clock); + + var result = await sut.ValidateAsync(principal, recordActivity: false, forceRefresh: true); + + Assert.Equal(SessionValidationAction.Reject, result.Action); + } + + /// A refresh that keeps one role still replaces the principal (the zero-role rule is not over-broad). + /// A task that represents the asynchronous operation. + [Fact] + public async Task ValidateAsync_RefreshToOneRole_KeepsTheSession() + { + var clock = new TestTimeProvider(Start); + var principal = Session(Start, ["SCADA-Admins"], + new RoleMappingResult([Roles.Administrator], [], true)); + var sut = CreateValidator(new FakeGroupRoleMapper(new RoleMappingResult([Roles.Viewer], [], false)), clock); + clock.Advance(TimeSpan.FromMinutes(16)); var result = await sut.ValidateAsync(principal); Assert.Equal(SessionValidationAction.Replace, result.Action); - // The user has lost ALL roles mid-session — every authorization policy will now deny. - Assert.Empty(result.Principal!.FindAll(JwtTokenService.RoleClaimType)); - Assert.Empty(result.Principal.FindAll(JwtTokenService.SiteIdClaimType)); + Assert.Equal([Roles.Viewer], result.Principal!.FindAll(JwtTokenService.RoleClaimType).Select(c => c.Value)); } /// Verifies that validation does not refresh roles before the refresh threshold. diff --git a/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/DirectoryGroupRefreshTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/DirectoryGroupRefreshTests.cs index 8e68476e..53198d46 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/DirectoryGroupRefreshTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/DirectoryGroupRefreshTests.cs @@ -27,6 +27,9 @@ public class DirectoryGroupRefreshTests } /// Maps each group to a role by name (Admins→Administrator, Designers→Designer, else Viewer). + // A group that maps to no ScadaBridge role (e.g. "Domain Users" under a domain-wide search base). + private const string UnmappedGroup = "Domain Users"; + private sealed class NamingMapper : IGroupRoleMapper { public int Calls { get; private set; } @@ -40,8 +43,9 @@ public class DirectoryGroupRefreshTests { "SCADA-Admins" => Roles.Administrator, "SCADA-Designers" => Roles.Designer, + UnmappedGroup => null, _ => Roles.Viewer, - }).Distinct().ToList(); + }).OfType().Distinct().ToList(); var result = new RoleMappingResult(roles, [], IsSystemWideDeployment: true); return Task.FromResult(new GroupRoleMapping(roles, Scope: result)); } @@ -255,6 +259,41 @@ public class DirectoryGroupRefreshTests Assert.Equal(SessionValidationAction.Reject, result.Action); } + /// + /// ScadaBridge#144: the directory still answers with groups, but none of them maps to a role + /// (the user was removed from every mapped AD group and keeps only e.g. "Domain Users"). Before + /// #144 this kept a signed-in, role-less session; a new login would now be refused, so the + /// session ends — on ordinary validation and on the fail-closed authoritative path. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task FoundWithOnlyUnmappedGroups_EndsTheSession(bool failClosed) + { + var rig = Build(); + rig.Lookup.Answer = _ => FoundWith(UnmappedGroup); + rig.Clock.Advance(TimeSpan.FromMinutes(16)); + + var result = await rig.Sut.ValidateAsync(Login(["SCADA-Admins"]), forceRefresh: failClosed, failClosed: failClosed); + + Assert.Equal(SessionValidationAction.Reject, result.Action); + Assert.Equal([UnmappedGroup], rig.Mapper.LastGroups); + } + + /// A directory answer that keeps one mapped group alongside unmapped ones keeps the session. + [Fact] + public async Task FoundWithOneMappedGroup_KeepsTheSession() + { + var rig = Build(); + rig.Lookup.Answer = _ => FoundWith(UnmappedGroup, "SCADA-Designers"); + rig.Clock.Advance(TimeSpan.FromMinutes(16)); + + var result = await rig.Sut.ValidateAsync(Login(["SCADA-Admins"])); + + Assert.Equal(SessionValidationAction.Replace, result.Action); + Assert.Equal([Roles.Designer], RolesOf(result.Principal!)); + } + [Theory] [InlineData(LdapGroupLookupStatus.NotSupported)] [InlineData(LdapGroupLookupStatus.ProviderDisabled)] From 764e75c32f0de3de2f479bb9a83f2b8931a6b329 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 17 Nov 2026 11:27:23 -0500 Subject: [PATCH 3/3] test(integration): give the live GLAuth auth tests a seeded group mapper (#144) The integration factory's in-memory configuration database is never seeded, so it holds no LdapGroupMappings and the live GLAuth users mapped to zero roles. LoginEndpoint_WithValidLdapCredentials_SetsCookieAndRedirects and ActiveSession_GroupsAreReReadFromTheDirectory_AndAnUnknownUserIsEnded were passing only because zero-role sign-in and zero-role sessions were allowed. They now run against a factory variant whose IGroupRoleMapper mirrors the seeded mappings (SecurityConfiguration.HasData). Claude-Session: https://claude.ai/code/session_01GT67AFKC45MBz1wPZnVbX8 --- .../AuthFlowTests.cs | 38 +++++++++++++++++-- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/tests/ZB.MOM.WW.ScadaBridge.IntegrationTests/AuthFlowTests.cs b/tests/ZB.MOM.WW.ScadaBridge.IntegrationTests/AuthFlowTests.cs index 5e7f53c3..4f3d695f 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.IntegrationTests/AuthFlowTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.IntegrationTests/AuthFlowTests.cs @@ -1,6 +1,9 @@ using System.Net; using System.Text.RegularExpressions; +using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.AspNetCore.Mvc.Testing; using ZB.MOM.WW.ScadaBridge.CentralUI.Auth; using ZB.MOM.WW.ScadaBridge.Security; using ZB.MOM.WW.Auth.Abstractions.Roles; @@ -14,12 +17,39 @@ namespace ZB.MOM.WW.ScadaBridge.IntegrationTests; public class AuthFlowTests : IClassFixture { private readonly ScadaBridgeWebApplicationFactory _factory; + private readonly WebApplicationFactory _mapped; /// Initializes the test with the shared web application factory. /// The web application factory hosting the app under test. public AuthFlowTests(ScadaBridgeWebApplicationFactory factory) { _factory = factory; + // The factory's in-memory configuration database is never seeded, so it holds no LDAP group + // mappings and every live GLAuth user would map to zero roles — which /auth/login and the + // session refresh now refuse (ScadaBridge#144). The live tests run against this variant, + // whose mapper mirrors the seeded LdapGroupMappings (SecurityConfiguration.HasData). + _mapped = factory.WithWebHostBuilder(b => b.ConfigureTestServices(services => + services.Replace(ServiceDescriptor.Scoped, SeededGroupRoleMapper>()))); + } + + /// Maps groups exactly as the seeded LdapGroupMappings rows do (system-wide, no scope rules). + private sealed class SeededGroupRoleMapper : IGroupRoleMapper + { + private static readonly Dictionary Seed = new(StringComparer.OrdinalIgnoreCase) + { + ["SCADA-Admins"] = Roles.Administrator, + ["SCADA-Designers"] = Roles.Designer, + ["SCADA-Deploy-All"] = Roles.Deployer, + ["SCADA-Deploy-SiteA"] = Roles.Deployer, + ["SCADA-Viewers"] = Roles.Viewer, + }; + + public Task> MapAsync(IReadOnlyList groups, CancellationToken ct) + { + var roles = groups.Where(Seed.ContainsKey).Select(g => Seed[g]).Distinct().ToList(); + var result = new RoleMappingResult(roles, [], IsSystemWideDeployment: true); + return Task.FromResult(new GroupRoleMapping(roles, Scope: result)); + } } /// Verifies that the login endpoint with empty credentials redirects to the login page with an error. @@ -124,7 +154,7 @@ public class AuthFlowTests : IClassFixture return; } - var client = _factory.CreateClient(new Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactoryClientOptions + var client = _mapped.CreateClient(new Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); @@ -197,7 +227,7 @@ public class AuthFlowTests : IClassFixture return; // GLAuth not running locally — see the login test above. } - var refresher = _factory.Services.GetRequiredService(); + var refresher = _mapped.Services.GetRequiredService(); Assert.True(refresher.IsActive); refresher.Clear(); @@ -206,7 +236,7 @@ public class AuthFlowTests : IClassFixture var stale = SessionClaimBuilder.Build("designer", "designer", ["SCADA-Admins"], new RoleMappingResult([Roles.Administrator], [], true), issued); - using (var scope = _factory.Services.CreateScope()) + using (var scope = _mapped.Services.CreateScope()) { var validator = scope.ServiceProvider.GetRequiredService(); var result = await validator.ValidateAsync(stale); @@ -219,7 +249,7 @@ public class AuthFlowTests : IClassFixture var gone = SessionClaimBuilder.Build("no-such-user-46", "x", ["SCADA-Admins"], new RoleMappingResult([Roles.Administrator], [], true), issued); - using (var scope = _factory.Services.CreateScope()) + using (var scope = _mapped.Services.CreateScope()) { var validator = scope.ServiceProvider.GetRequiredService(); Assert.Equal(SessionValidationAction.Reject, (await validator.ValidateAsync(gone)).Action);