Beschikbaarheidspoort: verlopen token op een geblokkeerde route geeft 401 i.p.v. 503, zodat de app de sessie stil ververst en als admin door de poort komt
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -257,5 +257,76 @@ public class AvailabilityMiddlewareTests
|
||||
|
||||
await _next.Received(1).Invoke(context);
|
||||
}
|
||||
|
||||
private string Token(string role, DateTime notBefore, DateTime expires, string? secret = null) =>
|
||||
new JwtSecurityTokenHandler().WriteToken(new JwtSecurityToken(
|
||||
issuer: Issuer, audience: Audience, claims: [new Claim(ClaimTypes.Role, role)],
|
||||
notBefore: notBefore, expires: expires,
|
||||
signingCredentials: new SigningCredentials(
|
||||
new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secret ?? Secret)), SecurityAlgorithms.HmacSha256)));
|
||||
|
||||
private async Task<int> StatusForAsync(string? token, bool masterDown = false)
|
||||
{
|
||||
var context = TestContexts.Api();
|
||||
context.Response.Body = new MemoryStream();
|
||||
if (token is not null) context.Request.Headers.Authorization = $"Bearer {token}";
|
||||
_service.IsAvailableAsync().Returns(masterDown ? AvailabilityStatus.Available : AvailabilityStatus.NotAvailable);
|
||||
_masterService.GetMasterStatus().Returns(new MasterGateStatus(!masterDown, masterDown ? "Down" : null));
|
||||
|
||||
await _middleware.InvokeAsync(context, _service, _masterService);
|
||||
return context.Response.StatusCode;
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public async Task AnExpiredOwnerToken_Gets401_SoTheAppRefreshesItsSession_LocalOrMaster(bool masterDown)
|
||||
{
|
||||
var expired = Token("Owner", DateTime.UtcNow.AddHours(-2), DateTime.UtcNow.AddHours(-1));
|
||||
|
||||
(await StatusForAsync(expired, masterDown)).Should().Be(StatusCodes.Status401Unauthorized);
|
||||
await _next.DidNotReceive().Invoke(Arg.Any<HttpContext>());
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public async Task NoToken_AForgedToken_AWrongKeyOrANonAdmin_StillGet503(bool masterDown)
|
||||
{
|
||||
var other = Token("Owner", DateTime.UtcNow.AddMinutes(-1), DateTime.UtcNow.AddHours(1), "another-secret-that-is-long-enough-for-hmac-256!!");
|
||||
var user = Token("User", DateTime.UtcNow.AddMinutes(-1), DateTime.UtcNow.AddHours(1));
|
||||
|
||||
(await StatusForAsync(null, masterDown)).Should().Be(StatusCodes.Status503ServiceUnavailable);
|
||||
(await StatusForAsync("not-a-token", masterDown)).Should().Be(StatusCodes.Status503ServiceUnavailable);
|
||||
(await StatusForAsync(other, masterDown)).Should().Be(StatusCodes.Status503ServiceUnavailable);
|
||||
(await StatusForAsync(user, masterDown)).Should().Be(StatusCodes.Status503ServiceUnavailable);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task TheOwnersWholeStory_ExpiredTokenIs401_ThenTheFreshTokenGetsThrough()
|
||||
{
|
||||
(await StatusForAsync(Token("Owner", DateTime.UtcNow.AddHours(-2), DateTime.UtcNow.AddHours(-1)))).Should().Be(StatusCodes.Status401Unauthorized);
|
||||
|
||||
var fresh = Token("Owner", DateTime.UtcNow.AddMinutes(-1), DateTime.UtcNow.AddHours(1));
|
||||
var context = TestContexts.Api();
|
||||
context.Request.Headers.Authorization = $"Bearer {fresh}";
|
||||
_service.IsAvailableAsync().Returns(AvailabilityStatus.NotAvailable);
|
||||
await _middleware.InvokeAsync(context, _service, _masterService);
|
||||
|
||||
await _next.Received(1).Invoke(context);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AnExpiredToken_OnAnAvailableCms_IsNotAnsweredByTheGateAtAll()
|
||||
{
|
||||
var expired = Token("Owner", DateTime.UtcNow.AddHours(-2), DateTime.UtcNow.AddHours(-1));
|
||||
var context = TestContexts.Api();
|
||||
context.Request.Headers.Authorization = $"Bearer {expired}";
|
||||
_service.IsAvailableAsync().Returns(AvailabilityStatus.Available);
|
||||
|
||||
await _middleware.InvokeAsync(context, _service, _masterService);
|
||||
|
||||
await _next.Received(1).Invoke(context); // the normal authentication answers 401 itself
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,7 +69,8 @@ public class AvailabilityMiddleware
|
||||
return;
|
||||
}
|
||||
|
||||
if (IsAdminBypass(context))
|
||||
var admin = CheckAdmin(context);
|
||||
if (admin.IsVerifiedAdmin)
|
||||
{
|
||||
await _next(context);
|
||||
return;
|
||||
@@ -81,6 +82,7 @@ public class AvailabilityMiddleware
|
||||
_logger.LogWarning(
|
||||
"Request blocked by master gate. Path: {Path}, DisableMessage: {DisableMessage}",
|
||||
path, masterStatus.DisableMessage);
|
||||
if (await TryAnswerExpiredTokenAsync(context, admin)) return;
|
||||
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
|
||||
await context.Response.WriteAsJsonAsync(new ProblemDetails
|
||||
{
|
||||
@@ -100,6 +102,7 @@ public class AvailabilityMiddleware
|
||||
}
|
||||
|
||||
_logger.LogWarning("Request geblokkeerd vanwege systeemstatus: {Status}. Path: {Path}", status, context.Request.Path);
|
||||
if (await TryAnswerExpiredTokenAsync(context, admin)) return;
|
||||
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
|
||||
await context.Response.WriteAsJsonAsync(new ProblemDetails
|
||||
{
|
||||
@@ -122,7 +125,7 @@ public class AvailabilityMiddleware
|
||||
/// without verifying the signature, which meant an unauthenticated caller could present a
|
||||
/// self-made token carrying an Owner role claim and bypass the gate.
|
||||
/// </remarks>
|
||||
private bool IsAdminBypass(HttpContext context)
|
||||
private AdminTokenResult CheckAdmin(HttpContext context)
|
||||
{
|
||||
var result = _adminTokenValidator.Validate(context.Request.Headers.Authorization.ToString());
|
||||
|
||||
@@ -135,6 +138,26 @@ public class AvailabilityMiddleware
|
||||
SecurityEvents.AdminBypassRejected(_logger, context.Request.Path, result.Reason);
|
||||
}
|
||||
|
||||
return result.IsVerifiedAdmin;
|
||||
return result;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// A token that has merely EXPIRED is answered with 401 instead of 503. The 503 left a signed-in Owner stuck on a
|
||||
/// disabled CMS: the app only refreshes its session on a 401, so it never got a fresh token and never got back
|
||||
/// through the gate as an admin. An expired token reveals nothing; a missing, forged or non-admin token still gets 503.
|
||||
/// </summary>
|
||||
private async Task<bool> TryAnswerExpiredTokenAsync(HttpContext context, AdminTokenResult admin)
|
||||
{
|
||||
if (admin.Reason != BypassRejectionReason.Expired) return false;
|
||||
|
||||
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
|
||||
await context.Response.WriteAsJsonAsync(new ProblemDetails
|
||||
{
|
||||
Status = StatusCodes.Status401Unauthorized,
|
||||
Title = "Unauthorized",
|
||||
Detail = "De sessie is verlopen. Ververs de sessie en probeer het opnieuw.",
|
||||
Instance = context.Request.Path
|
||||
});
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user