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:
Joseph Doherty
2026-11-17 11:18:18 -05:00
parent c996b462c4
commit 46d9a19bc5
3 changed files with 195 additions and 42 deletions
@@ -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));
}
}