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
215 lines
10 KiB
C#
215 lines
10 KiB
C#
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;
|
|
using ZB.MOM.WW.ScadaBridge.Security;
|
|
using ZB.MOM.WW.ScadaBridge.Security.Auth;
|
|
|
|
namespace ZB.MOM.WW.ScadaBridge.CentralUI.Tests.Auth;
|
|
|
|
/// <summary>
|
|
/// <c>POST /auth/token</c> (review 2026-10-21 05/U1): the minted token carries everything
|
|
/// <c>ManagementAuthenticator</c> needs (username, roles, site scope), the response advertises
|
|
/// <c>management_bearer</c> + <c>expires_in</c>, and a login-disabled deployment refuses the exchange.
|
|
/// </summary>
|
|
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,
|
|
string password = "pw", Exception? mapperThrows = null, CapturingLoggerProvider? logs = null,
|
|
LoginThrottle? throttle = null)
|
|
{
|
|
var ldap = Substitute.For<ILdapAuthService>();
|
|
ldap.AuthenticateAsync("alice", "pw", Arg.Any<CancellationToken>())
|
|
.Returns(LdapAuthResult.Success("alice", "Alice A", ["SiteDeployers"]));
|
|
ldap.AuthenticateAsync("alice", "wrong", Arg.Any<CancellationToken>())
|
|
.Returns(LdapAuthResult.Fail(LdapAuthFailure.BadCredentials));
|
|
var mapper = Substitute.For<IGroupRoleMapper<string>>();
|
|
if (mapperThrows is not null)
|
|
{
|
|
mapper.MapAsync(Arg.Any<IReadOnlyList<string>>(), Arg.Any<CancellationToken>()).ThrowsAsync(mapperThrows);
|
|
}
|
|
else
|
|
{
|
|
mapper.MapAsync(Arg.Any<IReadOnlyList<string>>(), Arg.Any<CancellationToken>())
|
|
.Returns(new GroupRoleMapping<string>(mapping.Roles, Scope: mapping));
|
|
}
|
|
|
|
var options = Options.Create(new SecurityOptions { JwtSigningKey = Key, JwtExpiryMinutes = 15 });
|
|
jwt = new JwtTokenService(options, NullLogger<JwtTokenService>.Instance);
|
|
|
|
var services = new ServiceCollection().AddLogging(b =>
|
|
{
|
|
if (logs is not null) b.AddProvider(logs);
|
|
});
|
|
services.AddSingleton(Options.Create(new AuthDisableLoginOptions { DisableLogin = disableLogin }));
|
|
services.AddSingleton<IOptions<SecurityOptions>>(options);
|
|
services.AddSingleton(TimeProvider.System);
|
|
if (throttle is not null) services.AddSingleton(throttle);
|
|
else services.AddSingleton<LoginThrottle>();
|
|
services.AddSingleton(ldap);
|
|
services.AddSingleton(mapper);
|
|
services.AddSingleton(jwt);
|
|
var context = new DefaultHttpContext { RequestServices = services.BuildServiceProvider() };
|
|
context.Request.Method = "POST";
|
|
context.Request.ContentType = "application/x-www-form-urlencoded";
|
|
context.Request.Form = new FormCollection(new()
|
|
{
|
|
["username"] = "alice",
|
|
["password"] = password,
|
|
});
|
|
context.Connection.RemoteIpAddress = System.Net.IPAddress.Loopback;
|
|
context.Response.Body = new MemoryStream();
|
|
return context;
|
|
}
|
|
|
|
private static async Task<(int Status, JsonElement Body)> Execute(HttpContext context)
|
|
{
|
|
var result = await AuthEndpoints.HandleTokenAsync(context);
|
|
await result.ExecuteAsync(context);
|
|
context.Response.Body.Position = 0;
|
|
using var doc = await JsonDocument.ParseAsync(context.Response.Body);
|
|
return (context.Response.StatusCode, doc.RootElement.Clone());
|
|
}
|
|
|
|
/// <summary>The token round-trips the user's roles and site scope and advertises bearer support.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Token_CarriesRolesAndScope_AndAdvertisesBearer()
|
|
{
|
|
var context = Context(false, new RoleMappingResult([Roles.Deployer], ["4", "9"], false), out var jwt);
|
|
|
|
var (status, body) = await Execute(context);
|
|
|
|
Assert.Equal(200, status);
|
|
Assert.True(body.GetProperty("management_bearer").GetBoolean());
|
|
Assert.Equal(15 * 60, body.GetProperty("expires_in").GetInt32());
|
|
var principal = jwt.ValidateToken(body.GetProperty("access_token").GetString()!);
|
|
Assert.NotNull(principal);
|
|
Assert.Equal("alice", principal!.FindFirst(JwtTokenService.UsernameClaimType)!.Value);
|
|
Assert.Equal("Alice A", principal.FindFirst(JwtTokenService.DisplayNameClaimType)!.Value);
|
|
Assert.Equal([Roles.Deployer], principal.FindAll(JwtTokenService.RoleClaimType).Select(c => c.Value));
|
|
Assert.Equal(["4", "9"], principal.FindAll(JwtTokenService.SiteIdClaimType).Select(c => c.Value));
|
|
}
|
|
|
|
/// <summary>A system-wide grant carries no site-id claims (empty == system-wide downstream).</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Token_SystemWide_HasNoSiteClaims()
|
|
{
|
|
var context = Context(false, new RoleMappingResult([Roles.Deployer], [], true), out var jwt);
|
|
|
|
var (_, body) = await Execute(context);
|
|
|
|
var principal = jwt.ValidateToken(body.GetProperty("access_token").GetString()!);
|
|
Assert.Empty(principal!.FindAll(JwtTokenService.SiteIdClaimType));
|
|
}
|
|
|
|
/// <summary>A login-disabled deployment refuses the exchange so the CLI falls back to Basic.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[Fact]
|
|
public async Task Token_WhenLoginDisabled_Is404()
|
|
{
|
|
var context = Context(true, new RoleMappingResult([Roles.Deployer], [], true), out _);
|
|
|
|
var (status, body) = await Execute(context);
|
|
|
|
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 _));
|
|
}
|
|
|
|
/// <summary>A bind whose groups map to zero roles gets the bad-password 401 and no token; the reason is logged.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[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);
|
|
}
|
|
|
|
/// <summary>A bind whose role mapping throws gets the bad-password 401 and no token; the exception is logged.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[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<InvalidOperationException>(entry.Exception);
|
|
}
|
|
|
|
/// <summary>A zero-role refusal counts against the login throttle, like a bad password.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[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()));
|
|
}
|
|
|
|
/// <summary>Exactly one mapped role still gets a token carrying that role.</summary>
|
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
|
[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);
|
|
}
|
|
}
|