5a642d1cdf
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
194 lines
9.0 KiB
C#
194 lines
9.0 KiB
C#
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;
|
|
|
|
/// <summary>
|
|
/// ScadaBridge#144 — <c>POST /auth/login</c> 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.
|
|
/// </summary>
|
|
public class AuthLoginRoleRefusalTests
|
|
{
|
|
private const string Category = AuthEndpoints.LoggerCategory;
|
|
|
|
private sealed record Outcome(int Status, string Location, IReadOnlyList<string> SetCookies);
|
|
|
|
private static RequestDelegate LoginDelegate()
|
|
{
|
|
var builder = WebApplication.CreateBuilder();
|
|
builder.Services.AddRouting();
|
|
builder.Services.AddAntiforgery();
|
|
builder.Services.AddSingleton<SessionActivityTracker>();
|
|
builder.Services.AddSingleton(TimeProvider.System);
|
|
using var app = builder.Build();
|
|
app.MapAuthEndpoints();
|
|
return ((IEndpointRouteBuilder)app).DataSources
|
|
.SelectMany(ds => ds.Endpoints)
|
|
.OfType<RouteEndpoint>()
|
|
.Single(e => e.RoutePattern.RawText == "/auth/login"
|
|
&& (e.Metadata.GetMetadata<HttpMethodMetadata>()?.HttpMethods.Contains("POST") ?? false))
|
|
.RequestDelegate!;
|
|
}
|
|
|
|
/// <summary>Builds the service rig: LDAP accepts alice/password (groups ["G"]) and rejects alice/wrong.</summary>
|
|
private static ServiceProvider Services(
|
|
IGroupRoleMapper<string> 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<ILdapAuthService>();
|
|
ldap.AuthenticateAsync("alice", "password", Arg.Any<CancellationToken>())
|
|
.Returns(LdapAuthResult.Success("alice", "Alice", ["Domain Users"]));
|
|
ldap.AuthenticateAsync("alice", "wrong", Arg.Any<CancellationToken>())
|
|
.Returns(LdapAuthResult.Fail(LdapAuthFailure.BadCredentials));
|
|
services.AddSingleton(ldap);
|
|
services.AddSingleton(mapper);
|
|
return services.BuildServiceProvider();
|
|
}
|
|
|
|
private static async Task<Outcome> PostLogin(ServiceProvider provider, string password)
|
|
{
|
|
var tokenContext = new DefaultHttpContext { RequestServices = provider };
|
|
var tokens = provider.GetRequiredService<IAntiforgery>().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<string> MapperReturning(params string[] roles)
|
|
{
|
|
var mapper = Substitute.For<IGroupRoleMapper<string>>();
|
|
mapper.MapAsync(Arg.Any<IReadOnlyList<string>>(), Arg.Any<CancellationToken>())
|
|
.Returns(new GroupRoleMapping<string>(roles, Scope: new RoleMappingResult(roles, [], true)));
|
|
return mapper;
|
|
}
|
|
|
|
private static IGroupRoleMapper<string> MapperThrowing()
|
|
{
|
|
var mapper = Substitute.For<IGroupRoleMapper<string>>();
|
|
mapper.MapAsync(Arg.Any<IReadOnlyList<string>>(), Arg.Any<CancellationToken>())
|
|
.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));
|
|
|
|
/// <summary>The bad-password response every refusal must match exactly.</summary>
|
|
private static async Task<Outcome> BadPasswordOutcome()
|
|
{
|
|
using var provider = Services(MapperReturning(Roles.Viewer), Throttle(), new CapturingLoggerProvider());
|
|
return await PostLogin(provider, "wrong");
|
|
}
|
|
|
|
/// <summary>A bind whose groups map to zero roles is refused exactly like a bad password, and logged.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[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);
|
|
}
|
|
|
|
/// <summary>A bind whose role mapping throws is refused exactly like a bad password, and logged with the exception.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[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<InvalidOperationException>(entry.Exception);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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".
|
|
/// </summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[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()));
|
|
}
|
|
|
|
/// <summary>One mapped role still signs in and sets the session cookie, with no refusal logged.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[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);
|
|
}
|
|
}
|