fix(security): no role, no login — refuse zero-role and mapper-fault AdminUI sign-in and tokens (#913)
/auth/login signed users in with an empty role set (and did so when the role mapper threw), and AuthenticatedRead / the fallback policy admit any authenticated user — with a domain-root SearchBase any AD user would get AdminUI read access and a token. - Empty mapped role set: refused like bad credentials (JSON 401; form redirect to /login with a generic message), no cookie, Warning logged with the groups. - Mapper throws: refused, fail closed (JSON 503 like an LDAP outage; form redirect with a generic "temporarily unavailable"), exception logged. - /auth/token: refuses (401) a cookie session carrying no role claim. - Replaces Login_when_role_mapper_throws_signs_in_with_no_role_claims with refusal tests (JSON + form), adds zero-role refused (JSON + form), one-mapped-role signs in, zero-role cookie gets no token. JwtConfigurationGateTests' stub user now holds a mapped group. Claude-Session: https://claude.ai/code/session_01GT67AFKC45MBz1wPZnVbX8
This commit is contained in:
@@ -99,29 +99,31 @@ public static class AuthEndpoints
|
||||
{
|
||||
// R03:2.7 — a directory outage used to leave NOTHING in the server log from this path; the
|
||||
// operator had to infer every 503 from the directory side.
|
||||
http.RequestServices.GetService<ILoggerFactory>()?
|
||||
.CreateLogger("ZB.MOM.WW.OtOpcUa.Security.AuthEndpoints")
|
||||
.LogWarning(ex, "LDAP authentication failed for {User}; answering 503", username);
|
||||
Logger(http).LogWarning(ex, "LDAP authentication failed for {User}; answering 503", username);
|
||||
return Results.StatusCode(StatusCodes.Status503ServiceUnavailable);
|
||||
}
|
||||
|
||||
if (!result.Success)
|
||||
{
|
||||
if (!isForm) return Results.Unauthorized();
|
||||
|
||||
var qs = $"?error={Uri.EscapeDataString(result.Error ?? "Invalid credentials")}";
|
||||
if (!string.IsNullOrWhiteSpace(returnUrl))
|
||||
qs += $"&returnUrl={Uri.EscapeDataString(returnUrl)}";
|
||||
return Results.Redirect("/login" + qs);
|
||||
return RedirectToLogin(result.Error ?? "Invalid credentials", returnUrl);
|
||||
}
|
||||
|
||||
// Role resolution now lives behind the shared IGroupRoleMapper<string> seam
|
||||
// Role resolution lives behind the shared IGroupRoleMapper<string> seam
|
||||
// (OtOpcUaGroupRoleMapper): it applies the appsettings GroupToRole baseline AND merges
|
||||
// system-wide DB grants from the user's LDAP groups. result.Roles is empty on the real
|
||||
// LDAP path (the library returns groups, not roles); it is only pre-populated on the
|
||||
// DevStub success path (FleetAdmin) — union that pre-resolved set in so the dev grant
|
||||
// DevStub success path (Administrator) — union that pre-resolved set in so the dev grant
|
||||
// survives the move to the mapper.
|
||||
IReadOnlyList<string> roles = result.Roles;
|
||||
//
|
||||
// No role, no login (lmxopcua#913; family standard, scadaproj NAM cutover plan §3.2):
|
||||
// - a mapper fault REFUSES the sign-in (fail closed) — it used to sign the user in with
|
||||
// the baseline roles, which are empty on the real path;
|
||||
// - an empty mapped role set REFUSES the sign-in exactly like bad credentials. The
|
||||
// fallback policy and AdminUiPolicies.AuthenticatedRead only require an authenticated
|
||||
// user, so a role-less cookie would grant AdminUI read access to ANY directory user
|
||||
// once SearchBase is a whole AD domain.
|
||||
IReadOnlyList<string> roles;
|
||||
try
|
||||
{
|
||||
var mapping = await roleMapper.MapAsync(result.Groups, ct);
|
||||
@@ -129,17 +131,19 @@ public static class AuthEndpoints
|
||||
}
|
||||
catch (Exception ex) when (ex is not OperationCanceledException)
|
||||
{
|
||||
// A DB hiccup (or any mapper fault) must never block sign-in — fall back to the
|
||||
// pre-resolved baseline roles (empty on the real path, FleetAdmin under DevStub).
|
||||
// This is intentionally FAIL-CLOSED on the real LDAP path: result.Roles is empty there
|
||||
// (the library returns groups, never roles — the mapper is the sole role source), so a
|
||||
// mapper fault signs the user in AUTHENTICATED but with ZERO role claims. They can prove
|
||||
// identity but are denied every role-gated action until the mapper recovers — strictly
|
||||
// safer than failing open with a stale/guessed role set. (See AuthEndpoints test
|
||||
// Login_when_role_mapper_throws_signs_in_with_no_role_claims.)
|
||||
http.RequestServices.GetService<ILoggerFactory>()?
|
||||
.CreateLogger("ZB.MOM.WW.OtOpcUa.Security.AuthEndpoints")
|
||||
.LogWarning(ex, "Role-map lookup failed for {User}; using pre-resolved baseline roles", username);
|
||||
Logger(http).LogWarning(ex,
|
||||
"Role-map lookup failed for {User}; refusing sign-in (fail closed)", username);
|
||||
if (!isForm) return Results.StatusCode(StatusCodes.Status503ServiceUnavailable);
|
||||
return RedirectToLogin(SignInUnavailableMessage, returnUrl);
|
||||
}
|
||||
|
||||
if (roles.Count == 0)
|
||||
{
|
||||
Logger(http).LogWarning(
|
||||
"Sign-in refused for {User}: authenticated, but groups [{Groups}] map to no role",
|
||||
username, string.Join(", ", result.Groups));
|
||||
if (!isForm) return Results.Unauthorized();
|
||||
return RedirectToLogin(NotAuthorizedMessage, returnUrl);
|
||||
}
|
||||
|
||||
var claims = new List<Claim>
|
||||
@@ -167,6 +171,28 @@ public static class AuthEndpoints
|
||||
return Results.Redirect(destination);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Login-page text for an authenticated user whose groups map to no role. Deliberately generic:
|
||||
/// it does not say which of "bad password" / "no role" applied.
|
||||
/// </summary>
|
||||
internal const string NotAuthorizedMessage = "Invalid username or password, or the account is not authorized.";
|
||||
|
||||
/// <summary>Login-page text when role resolution itself failed (the mapper threw).</summary>
|
||||
internal const string SignInUnavailableMessage = "Sign-in is temporarily unavailable. Try again later.";
|
||||
|
||||
private static ILogger Logger(HttpContext http) =>
|
||||
http.RequestServices.GetService<ILoggerFactory>()?
|
||||
.CreateLogger("ZB.MOM.WW.OtOpcUa.Security.AuthEndpoints")
|
||||
?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance;
|
||||
|
||||
private static IResult RedirectToLogin(string error, string returnUrl)
|
||||
{
|
||||
var qs = $"?error={Uri.EscapeDataString(error)}";
|
||||
if (!string.IsNullOrWhiteSpace(returnUrl))
|
||||
qs += $"&returnUrl={Uri.EscapeDataString(returnUrl)}";
|
||||
return Results.Redirect("/login" + qs);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Returns <see langword="true"/> when <paramref name="url"/> is a relative (local) URL
|
||||
/// safe to redirect to after login. Rejects absolute URLs (with a scheme, e.g.
|
||||
@@ -205,6 +231,15 @@ public static class AuthEndpoints
|
||||
var displayName = user.FindFirst(JwtTokenService.DisplayNameClaimType)?.Value ?? username;
|
||||
var roles = user.FindAll(ZbClaimTypes.Role).Select(c => c.Value).ToArray();
|
||||
|
||||
// No role, no token (lmxopcua#913). /auth/login no longer issues a role-less cookie, but a
|
||||
// cookie minted before that fix (or by any other sign-in path) must not be turned into a
|
||||
// bearer token that the fallback policy would then accept for AdminUI read access.
|
||||
if (roles.Length == 0)
|
||||
{
|
||||
Logger(http).LogWarning("Token refused for {User}: the session carries no role", username);
|
||||
return Results.Unauthorized();
|
||||
}
|
||||
|
||||
return Results.Ok(new TokenResponse(jwt.Issue(displayName, username, roles)));
|
||||
}
|
||||
|
||||
|
||||
@@ -104,6 +104,19 @@ public sealed class AuthEndpointsIntegrationTests : IAsyncLifetime
|
||||
// IsInRole (the validation parameters pair RoleClaimType with the minted key).
|
||||
e.MapGet("/api/viewer-only", () => Results.Ok("viewer"))
|
||||
.RequireAuthorization(p => p.RequireRole("Viewer"));
|
||||
// lmxopcua#913: mints a cookie session carrying NO role claim — the shape a
|
||||
// pre-fix /auth/login produced — so /auth/token's zero-role refusal is testable.
|
||||
e.MapPost("/test/signin-no-role", async (HttpContext ctx) =>
|
||||
{
|
||||
var identity = new ClaimsIdentity(
|
||||
[new Claim(ZbClaimTypes.Name, "legacy"), new Claim(ZbClaimTypes.Username, "legacy")],
|
||||
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme);
|
||||
await Microsoft.AspNetCore.Authentication.AuthenticationHttpContextExtensions.SignInAsync(
|
||||
ctx,
|
||||
Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationDefaults.AuthenticationScheme,
|
||||
new ClaimsPrincipal(identity));
|
||||
return Results.NoContent();
|
||||
}).AllowAnonymous().DisableAntiforgery();
|
||||
});
|
||||
});
|
||||
})
|
||||
@@ -393,35 +406,130 @@ public sealed class AuthEndpointsIntegrationTests : IAsyncLifetime
|
||||
roles.ShouldContain("Administrator"); // DB grant merged in
|
||||
}
|
||||
|
||||
/// <summary>Fail-closed (review I3): when the role mapper throws on the real production path
|
||||
/// (the auth result carries no pre-resolved roles — roles come only from the mapper), sign-in
|
||||
/// still SUCCEEDS but the user is granted ZERO role claims. They are authenticated (can prove
|
||||
/// identity) yet authorized for nothing role-gated until the mapper recovers — the safe
|
||||
/// fail-closed behaviour, not a fail-open with a stale role set.</summary>
|
||||
/// <summary>
|
||||
/// lmxopcua#913 (reverses the former <c>Login_when_role_mapper_throws_signs_in_with_no_role_claims</c>):
|
||||
/// when the role mapper throws, the JSON login is REFUSED — 503, no cookie — and the fault is
|
||||
/// logged. It used to sign the user in with zero roles, and the fallback policy then granted
|
||||
/// AdminUI read access to any authenticated user.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Login_when_role_mapper_throws_signs_in_with_no_role_claims()
|
||||
public async Task Login_when_role_mapper_throws_is_refused_without_a_cookie()
|
||||
{
|
||||
// Simulate a mapper fault on the real path. The whole MapAsync throws (the appsettings
|
||||
// baseline is computed inside the mapper, so it does NOT survive the throw): the login
|
||||
// endpoint falls back to result.Roles, which is empty on the real LDAP path.
|
||||
_roleMappings.Throws = true;
|
||||
|
||||
var client = NewClient();
|
||||
var loginResponse = await client.PostAsJsonAsync("/auth/login",
|
||||
new AuthEndpoints.LoginRequest("alice", "valid-password"), Ct);
|
||||
|
||||
// Login proceeds despite the simulated DB outage — authenticated.
|
||||
loginResponse.StatusCode.ShouldBe(HttpStatusCode.NoContent);
|
||||
loginResponse.StatusCode.ShouldBe(HttpStatusCode.ServiceUnavailable);
|
||||
loginResponse.Headers.Contains("Set-Cookie").ShouldBeFalse("a refused login must not issue a cookie");
|
||||
_logs.Entries.Any(e =>
|
||||
e.Level == LogLevel.Warning && e.Message.Contains("Role-map lookup failed") && e.Exception != null)
|
||||
.ShouldBeTrue("the mapper fault must be logged with its exception");
|
||||
}
|
||||
|
||||
/// <summary>lmxopcua#913: the form login with a throwing mapper redirects back to /login with a
|
||||
/// generic message (no cause leaked) and no cookie.</summary>
|
||||
[Fact]
|
||||
public async Task Form_login_when_role_mapper_throws_redirects_to_login_without_a_cookie()
|
||||
{
|
||||
_roleMappings.Throws = true;
|
||||
|
||||
var resp = await NewClientNoRedirect().PostAsync("/auth/login", new FormUrlEncodedContent(
|
||||
new Dictionary<string, string> { ["username"] = "alice", ["password"] = "valid-password" }), Ct);
|
||||
|
||||
resp.StatusCode.ShouldBe(HttpStatusCode.Found);
|
||||
var location = Uri.UnescapeDataString(resp.Headers.Location!.OriginalString);
|
||||
location.ShouldStartWith("/login?error=");
|
||||
location.ShouldContain(AuthEndpoints.SignInUnavailableMessage);
|
||||
location.ShouldNotContain("simulated DB outage");
|
||||
resp.Headers.Contains("Set-Cookie").ShouldBeFalse();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#913 / family standard "no role, no login": a user who authenticates but whose groups
|
||||
/// map to no role is refused exactly like bad credentials — 401, no cookie — and it is logged.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Login_with_groups_that_map_to_no_role_returns_401_without_a_cookie()
|
||||
{
|
||||
var response = await NewClient().PostAsJsonAsync("/auth/login",
|
||||
new AuthEndpoints.LoginRequest(StubLdapAuthService.NoRoleUser, "valid-password"), Ct);
|
||||
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
||||
response.Headers.Contains("Set-Cookie").ShouldBeFalse("a zero-role login must not issue a cookie");
|
||||
_logs.Entries.Any(e => e.Level == LogLevel.Warning && e.Message.Contains("map to no role"))
|
||||
.ShouldBeTrue("the zero-role refusal must be logged");
|
||||
}
|
||||
|
||||
/// <summary>lmxopcua#913: the zero-role form login redirects to /login with the generic message.</summary>
|
||||
[Fact]
|
||||
public async Task Form_login_with_groups_that_map_to_no_role_redirects_with_generic_error()
|
||||
{
|
||||
var resp = await NewClientNoRedirect().PostAsync("/auth/login", new FormUrlEncodedContent(
|
||||
new Dictionary<string, string>
|
||||
{
|
||||
["username"] = StubLdapAuthService.NoRoleUser,
|
||||
["password"] = "valid-password",
|
||||
["returnUrl"] = "/clusters",
|
||||
}), Ct);
|
||||
|
||||
resp.StatusCode.ShouldBe(HttpStatusCode.Found);
|
||||
var location = Uri.UnescapeDataString(resp.Headers.Location!.OriginalString);
|
||||
location.ShouldStartWith("/login?error=");
|
||||
location.ShouldContain(AuthEndpoints.NotAuthorizedMessage);
|
||||
location.ShouldContain("returnUrl=/clusters");
|
||||
resp.Headers.Contains("Set-Cookie").ShouldBeFalse();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#913: a zero-role user is admitted once a DB grant gives their group a role — the
|
||||
/// refusal keys on the mapped role set, not on the group name.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Login_with_one_mapped_role_signs_in()
|
||||
{
|
||||
_roleMappings.Rows.Add(new LdapGroupRoleMapping
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
LdapGroup = StubLdapAuthService.NoRoleGroup,
|
||||
Role = AdminRole.Viewer,
|
||||
IsSystemWide = true,
|
||||
ClusterId = null,
|
||||
});
|
||||
|
||||
var response = await NewClient().PostAsJsonAsync("/auth/login",
|
||||
new AuthEndpoints.LoginRequest(StubLdapAuthService.NoRoleUser, "valid-password"), Ct);
|
||||
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.NoContent);
|
||||
response.Headers.GetValues("Set-Cookie").ShouldContain(c => c.StartsWith("ZB.MOM.WW.OtOpcUa.Auth="));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// lmxopcua#913: <c>/auth/token</c> refuses a cookie session that carries no role (a cookie minted
|
||||
/// before the login fix) — 401, no token. Positive control: the same request shape with a role-
|
||||
/// bearing session is <c>Token_after_cookie_login_returns_jwt</c>.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Token_for_a_zero_role_cookie_session_is_refused()
|
||||
{
|
||||
var client = NewClient();
|
||||
var signIn = await client.PostAsync("/test/signin-no-role", null, Ct);
|
||||
signIn.StatusCode.ShouldBe(HttpStatusCode.NoContent);
|
||||
|
||||
// The zero-role cookie authenticates (positive control on the session itself) …
|
||||
var ping = new HttpRequestMessage(HttpMethod.Get, "/auth/ping");
|
||||
AttachCookies(ping, signIn);
|
||||
(await client.SendAsync(ping, Ct)).StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
|
||||
// … but cannot mint a bearer token.
|
||||
var tokenReq = new HttpRequestMessage(HttpMethod.Post, "/auth/token");
|
||||
AttachCookies(tokenReq, loginResponse);
|
||||
AttachCookies(tokenReq, signIn);
|
||||
var tokenResp = await client.SendAsync(tokenReq, Ct);
|
||||
tokenResp.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
|
||||
// No role claims at all — fail closed.
|
||||
var payload = await tokenResp.Content.ReadFromJsonAsync<JsonElement>(Ct);
|
||||
var roles = JwtRoleClaims(payload.GetProperty("token").GetString()!);
|
||||
roles.ShouldBeEmpty();
|
||||
tokenResp.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
||||
(await tokenResp.Content.ReadAsStringAsync(Ct)).ShouldNotContain("token");
|
||||
_logs.Entries.Any(e => e.Level == LogLevel.Warning && e.Message.Contains("Token refused"))
|
||||
.ShouldBeTrue();
|
||||
}
|
||||
|
||||
/// <summary>Parses the payload segment of a JWT and returns it as a <see cref="JsonElement"/>.</summary>
|
||||
@@ -673,6 +781,11 @@ public sealed class AuthEndpointsIntegrationTests : IAsyncLifetime
|
||||
|
||||
private sealed class StubLdapAuthService : ILdapAuthService
|
||||
{
|
||||
/// <summary>A user whose valid credentials yield only <see cref="NoRoleGroup"/>, which no
|
||||
/// baseline GroupToRole entry maps.</summary>
|
||||
public const string NoRoleUser = "norole";
|
||||
public const string NoRoleGroup = "UnmappedGroup";
|
||||
|
||||
/// <summary>Authenticates a user asynchronously using the stub service.</summary>
|
||||
/// <param name="username">The username to authenticate.</param>
|
||||
/// <param name="password">The password to verify.</param>
|
||||
@@ -682,6 +795,10 @@ public sealed class AuthEndpointsIntegrationTests : IAsyncLifetime
|
||||
{
|
||||
if (username == "ldap-down")
|
||||
throw new InvalidOperationException("simulated LDAP outage");
|
||||
if (username == NoRoleUser && password == "valid-password")
|
||||
return Task.FromResult(new LdapAuthResult(
|
||||
Success: true, DisplayName: "No Role", Username: username,
|
||||
Groups: [NoRoleGroup], Roles: [], Error: null));
|
||||
if (password == "valid-password")
|
||||
return Task.FromResult(new LdapAuthResult(
|
||||
Success: true,
|
||||
|
||||
@@ -83,7 +83,8 @@ public sealed class JwtConfigurationGateTests
|
||||
private static async Task<IHost> StartHostAsync(string? signingKey)
|
||||
{
|
||||
var dbName = $"jwt-gate-{Guid.NewGuid():N}";
|
||||
var settings = new Dictionary<string, string?>();
|
||||
// lmxopcua#913: a login whose groups map to no role is refused, so alice's group must map.
|
||||
var settings = new Dictionary<string, string?> { ["Security:Ldap:GroupToRole:ReadOnly"] = "Viewer" };
|
||||
if (signingKey is not null) settings["Security:Jwt:SigningKey"] = signingKey;
|
||||
var configuration = new ConfigurationBuilder().AddInMemoryCollection(settings).Build();
|
||||
|
||||
@@ -122,6 +123,6 @@ public sealed class JwtConfigurationGateTests
|
||||
public Task<LdapAuthResult> AuthenticateAsync(string username, string password, CancellationToken ct = default) =>
|
||||
Task.FromResult(new LdapAuthResult(
|
||||
Success: password == "valid-password", DisplayName: "Alice", Username: username,
|
||||
Groups: [], Roles: [], Error: null));
|
||||
Groups: ["ReadOnly"], Roles: [], Error: null));
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user