fix(security): validate the API-key pepper at start, finish JWT bearer, circuit-aware audit actor
- ApiKeyOptionsValidator (ValidateOnStart on any driver/admin node): a blank or placeholder Security:ApiKeys:Pepper fails host start instead of rejecting every key after a green boot (R03:2.3). - JWT is finished and opt-in by key (R03:2.4): with Security:Jwt:SigningKey set, a Bearer scheme (JwtBearerAuthenticationHandler over JwtTokenService.TryValidate / BuildValidationParameters, fail closed) accepts the tokens /auth/token mints; the default scheme is a cookie-or-bearer policy scheme and the fallback policy names it, so /api/* and every RequireAuthorization endpoint take a browser session OR a machine token. JwtOptions are validated at start (JwtOptionsValidator). Without a key, /auth/token is not mapped (404, not the former constructor 500) and no bearer scheme exists. A direct AddJwtBearer needs Microsoft.AspNetCore.Authentication.JwtBearer in Directory.Packages.props (not this lane's file) — the handler is a drop-in to swap. - AuthenticationStateAuditActorAccessor is the registered IAuditActorAccessor: the Blazor circuit's principal first, HttpContext as the fallback (R03:2.5). HttpAuditActorAccessor shares its resolver. - CookieAuthenticationStateProvider (unregistered, fire-and-forget ping loop) is deleted (R03:1.5/2.5). - /auth/login logs the LDAP exception at Warning before answering 503 (R03:2.7). - Admin operations reply with a fixed message + correlation id instead of ex.Message (R03:4.1). Refs #733 Claude-Session: https://claude.ai/code/session_01Ub9hGmYLQvn9XETzw7CMsT
This commit is contained in:
@@ -11,6 +11,7 @@ using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Hosting;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Shouldly;
|
||||
using Xunit;
|
||||
using ZB.MOM.WW.Auth.AspNetCore;
|
||||
@@ -37,6 +38,7 @@ public sealed class AuthEndpointsIntegrationTests : IAsyncLifetime
|
||||
private IHost _host = null!;
|
||||
private TestServer _server = null!;
|
||||
private readonly StubLdapGroupRoleMappingService _roleMappings = new();
|
||||
private readonly CapturingLoggerProvider _logs = new();
|
||||
|
||||
private static CancellationToken Ct => TestContext.Current.CancellationToken;
|
||||
|
||||
@@ -70,6 +72,7 @@ public sealed class AuthEndpointsIntegrationTests : IAsyncLifetime
|
||||
["Security:Ldap:GroupToRole:ReadOnly"] = "Viewer",
|
||||
}).Build();
|
||||
services.AddOtOpcUaAuth(configuration);
|
||||
services.AddLogging(l => l.AddProvider(_logs));
|
||||
services.AddSingleton<ILdapAuthService, StubLdapAuthService>();
|
||||
// The login handler now resolves the DB role-map service via DI to merge
|
||||
// DB-backed grants on top of the appsettings baseline. Register the stub so
|
||||
@@ -96,6 +99,10 @@ public sealed class AuthEndpointsIntegrationTests : IAsyncLifetime
|
||||
.ToArray();
|
||||
return Results.Ok(claims);
|
||||
}).RequireAuthorization();
|
||||
// A role-gated machine endpoint: proves a bearer principal's roles resolve through
|
||||
// IsInRole (the validation parameters pair RoleClaimType with the minted key).
|
||||
e.MapGet("/api/viewer-only", () => Results.Ok("viewer"))
|
||||
.RequireAuthorization(p => p.RequireRole("Viewer"));
|
||||
});
|
||||
});
|
||||
})
|
||||
@@ -153,6 +160,66 @@ public sealed class AuthEndpointsIntegrationTests : IAsyncLifetime
|
||||
new AuthEndpoints.LoginRequest("ldap-down", "anything"), Ct);
|
||||
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.ServiceUnavailable);
|
||||
// R03:2.7 — the outage is named in the server log, not inferred from the directory side.
|
||||
_logs.Entries.Any(e =>
|
||||
e.Level == LogLevel.Warning && e.Message.Contains("LDAP authentication failed") && e.Exception != null)
|
||||
.ShouldBeTrue("a Warning naming the LDAP failure must be logged");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// R03:2.4 — a token from <c>/auth/token</c> authenticates a request carrying it as a bearer:
|
||||
/// the fallback-protected root AND a role-gated endpoint (the bearer principal's "Role" claims
|
||||
/// resolve through <c>IsInRole</c>). No cookie is sent.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task Bearer_token_authenticates_api_requests_without_a_cookie()
|
||||
{
|
||||
var token = await LoginAndIssueTokenAsync();
|
||||
var client = NewClient();
|
||||
|
||||
var root = new HttpRequestMessage(HttpMethod.Get, "/");
|
||||
root.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
|
||||
(await client.SendAsync(root, Ct)).StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
|
||||
var gated = new HttpRequestMessage(HttpMethod.Get, "/api/viewer-only");
|
||||
gated.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
|
||||
var gatedResponse = await client.SendAsync(gated, Ct);
|
||||
gatedResponse.StatusCode.ShouldBe(HttpStatusCode.OK);
|
||||
(await gatedResponse.Content.ReadAsStringAsync(Ct)).ShouldContain("viewer");
|
||||
}
|
||||
|
||||
/// <summary>A tampered or garbage bearer fails closed (401), it never falls through to anonymous.</summary>
|
||||
[Theory]
|
||||
[InlineData("not-a-jwt")]
|
||||
[InlineData("tampered")]
|
||||
public async Task Bad_bearer_token_is_rejected(string kind)
|
||||
{
|
||||
var token = kind == "tampered"
|
||||
? (await LoginAndIssueTokenAsync()) + "x"
|
||||
: kind;
|
||||
var client = NewClient();
|
||||
var req = new HttpRequestMessage(HttpMethod.Get, "/");
|
||||
req.Headers.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);
|
||||
req.Headers.Add("X-Requested-With", "XMLHttpRequest");
|
||||
|
||||
var response = await client.SendAsync(req, Ct);
|
||||
|
||||
response.StatusCode.ShouldBe(HttpStatusCode.Unauthorized);
|
||||
response.Headers.WwwAuthenticate.ToString().ShouldContain("Bearer");
|
||||
}
|
||||
|
||||
private async Task<string> LoginAndIssueTokenAsync()
|
||||
{
|
||||
var client = NewClient();
|
||||
var loginResponse = await client.PostAsJsonAsync("/auth/login",
|
||||
new AuthEndpoints.LoginRequest("alice", "valid-password"), Ct);
|
||||
loginResponse.EnsureSuccessStatusCode();
|
||||
var tokenReq = new HttpRequestMessage(HttpMethod.Post, "/auth/token");
|
||||
AttachCookies(tokenReq, loginResponse);
|
||||
var response = await client.SendAsync(tokenReq, Ct);
|
||||
response.EnsureSuccessStatusCode();
|
||||
var payload = await response.Content.ReadFromJsonAsync<JsonElement>(Ct);
|
||||
return payload.GetProperty("token").GetString()!;
|
||||
}
|
||||
|
||||
/// <summary>Tests that ping anonymous returns 401.</summary>
|
||||
|
||||
Reference in New Issue
Block a user