fix(api): #295 PR1 — logout ends the session server-side (E2E-caught)
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 6s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 4m20s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 5m11s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
Build ErsatzTV Image / Docs update reminder (pull_request) Successful in 6s
Build ErsatzTV Image / EF migration integrity (SQLite + MySql) (pull_request) Successful in 4m20s
Build ErsatzTV Image / Build & test (.NET) (pull_request) Successful in 5m11s
Build ErsatzTV Image / Build & push image (amd64) (pull_request) Has been skipped
Live E2E found that replaying a pre-logout cookie still authenticated (200, not 401): SignOutAsync only clears the CLIENT cookie, but the stateless encrypted cookie ticket stays valid server-side because its security stamp is unchanged — a captured cookie was replayable after logout until ticket expiry. Fix: logout now rotates the local-admin security stamp (RotateLocalAdminSecurityStamp), so every outstanding local session (old stamp) fails OnValidatePrincipal on its next request. For the single admin this is "log out everywhere". Gated on an authenticated local session so an unauthenticated caller can't force-revoke the admin. OIDC sessions (no stamp) are unaffected; SignOutAsync still clears the client cookie for UX. +2 handler tests (rotate-when-configured / no-op-when-unconfigured). Auth suite green (21). Docs: decisions.md note updated. Refs #295 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
namespace ErsatzTV.Application.Auth;
|
||||
|
||||
/// <summary>
|
||||
/// Rotates the local admin security stamp, revoking every outstanding local session server-side (their
|
||||
/// cookies carry the old stamp and fail <c>OnValidatePrincipal</c> on their next request). Used by logout
|
||||
/// so signing out actually ends the session server-side, not just client-side. A no-op when no local
|
||||
/// admin is configured. OIDC sessions are unaffected (they carry no stamp).
|
||||
/// </summary>
|
||||
public record RotateLocalAdminSecurityStamp : IRequest<Unit>;
|
||||
@@ -0,0 +1,28 @@
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Infrastructure.Data;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
|
||||
namespace ErsatzTV.Application.Auth;
|
||||
|
||||
public class RotateLocalAdminSecurityStampHandler(IDbContextFactory<TvContext> dbContextFactory)
|
||||
: IRequestHandler<RotateLocalAdminSecurityStamp, Unit>
|
||||
{
|
||||
public async Task<Unit> Handle(RotateLocalAdminSecurityStamp request, CancellationToken cancellationToken)
|
||||
{
|
||||
await using TvContext dbContext = await dbContextFactory.CreateDbContextAsync(cancellationToken);
|
||||
|
||||
ConfigElement stampRow = await dbContext.ConfigElements
|
||||
.FirstOrDefaultAsync(c => c.Key == ConfigElementKey.AuthSecurityStamp.Key, cancellationToken);
|
||||
|
||||
// No local admin configured → nothing to revoke.
|
||||
if (stampRow is null)
|
||||
{
|
||||
return Unit.Default;
|
||||
}
|
||||
|
||||
stampRow.Value = LocalAdminHelpers.NewSecurityStamp();
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return Unit.Default;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
using ErsatzTV.Application.Auth;
|
||||
using ErsatzTV.Core;
|
||||
using ErsatzTV.Core.Domain;
|
||||
using ErsatzTV.Core.Interfaces.Repositories;
|
||||
using ErsatzTV.Infrastructure.Data.Repositories;
|
||||
using ErsatzTV.Tests.Support;
|
||||
using LanguageExt;
|
||||
using NUnit.Framework;
|
||||
using Shouldly;
|
||||
|
||||
namespace ErsatzTV.Tests.Application.Auth;
|
||||
|
||||
[TestFixture]
|
||||
public class RotateLocalAdminSecurityStampHandlerTests
|
||||
{
|
||||
private InMemoryTvContext _db = null!;
|
||||
private IConfigElementRepository _configElementRepository = null!;
|
||||
private ILocalPasswordHasher _passwordHasher = null!;
|
||||
|
||||
[SetUp]
|
||||
public async Task SetUp()
|
||||
{
|
||||
_db = await InMemoryTvContext.CreateAsync();
|
||||
_configElementRepository = new ConfigElementRepository(_db.Factory);
|
||||
_passwordHasher = new LocalPasswordHasher();
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public async Task TearDown() => await _db.DisposeAsync();
|
||||
|
||||
private RotateLocalAdminSecurityStampHandler MakeHandler() => new(_db.Factory);
|
||||
|
||||
[Test]
|
||||
public async Task Handle_Should_Rotate_The_Stamp_When_Configured()
|
||||
{
|
||||
// Arrange: claim an admin so a stamp exists.
|
||||
Either<BaseError, LocalAdminPrincipal> claim = await new ClaimLocalAdminHandler(_db.Factory, _passwordHasher)
|
||||
.Handle(new ClaimLocalAdmin("admin", "supersecret"), CancellationToken.None);
|
||||
claim.IsRight.ShouldBeTrue();
|
||||
|
||||
Option<string> before =
|
||||
await _configElementRepository.GetValue<string>(ConfigElementKey.AuthSecurityStamp, CancellationToken.None);
|
||||
string originalStamp = before.Match(s => s, () => throw new ShouldAssertException("expected a stamp"));
|
||||
|
||||
// Act
|
||||
await MakeHandler().Handle(new RotateLocalAdminSecurityStamp(), CancellationToken.None);
|
||||
|
||||
// Assert: the stamp changed (all outstanding sessions carrying the old stamp are now stale).
|
||||
Option<string> after =
|
||||
await _configElementRepository.GetValue<string>(ConfigElementKey.AuthSecurityStamp, CancellationToken.None);
|
||||
string rotatedStamp = after.Match(s => s, () => throw new ShouldAssertException("expected a stamp"));
|
||||
rotatedStamp.ShouldNotBe(originalStamp);
|
||||
rotatedStamp.ShouldNotBeNullOrEmpty();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task Handle_Should_Be_A_No_Op_When_Unconfigured()
|
||||
{
|
||||
await MakeHandler().Handle(new RotateLocalAdminSecurityStamp(), CancellationToken.None);
|
||||
|
||||
Option<string> stamp =
|
||||
await _configElementRepository.GetValue<string>(ConfigElementKey.AuthSecurityStamp, CancellationToken.None);
|
||||
stamp.IsNone.ShouldBeTrue();
|
||||
}
|
||||
}
|
||||
@@ -87,9 +87,15 @@ public class AuthController(IMediator mediator) : ControllerBase
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>Sign out of the cookie session. Requires the CSRF header (this controller is filter-exempt).</summary>
|
||||
/// <summary>
|
||||
/// Sign out of the cookie session. Requires the CSRF header (this controller is filter-exempt). For a
|
||||
/// local session this rotates the security stamp, ending the session <b>server-side</b> (a captured
|
||||
/// cookie can't be replayed after logout) — which, for the single local admin, revokes all local
|
||||
/// sessions ("log out everywhere"). Gated on an authenticated session so an unauthenticated caller
|
||||
/// can't force-revoke the admin.
|
||||
/// </summary>
|
||||
[HttpPost("/api/auth/logout")]
|
||||
public async Task<IActionResult> Logout()
|
||||
public async Task<IActionResult> Logout(CancellationToken cancellationToken)
|
||||
{
|
||||
// Prevent forced-logout CSRF: a same-site form POST carries the Lax cookie but can't set a custom
|
||||
// header. The whole controller is [SkipApiAuthorization], so the filter's CSRF check doesn't apply.
|
||||
@@ -98,6 +104,15 @@ public class AuthController(IMediator mediator) : ControllerBase
|
||||
return csrfError;
|
||||
}
|
||||
|
||||
if (User.Identity?.IsAuthenticated == true &&
|
||||
string.Equals(
|
||||
User.FindFirst(AuthConstants.AuthMethodClaim)?.Value,
|
||||
AuthConstants.MethodLocal,
|
||||
StringComparison.Ordinal))
|
||||
{
|
||||
await mediator.Send(new RotateLocalAdminSecurityStamp(), cancellationToken);
|
||||
}
|
||||
|
||||
await HttpContext.SignOutAsync(AuthConstants.CookieScheme);
|
||||
return NoContent();
|
||||
}
|
||||
|
||||
+5
-1
@@ -1150,7 +1150,11 @@ cookie carrying the pre-change stamp → revoked next request); (c) **env-seed w
|
||||
`SystemStartup.WaitForDatabase`** (the migrator is a `BackgroundService`, so registration order alone didn't
|
||||
guarantee the schema existed) — moved to `Services/RunOnce/`. Also: **logout + password require `X-CSRF`**
|
||||
(the `[SkipApiAuthorization]` auth surface isn't covered by the filter's CSRF check → forced-logout CSRF), and
|
||||
input length caps on username/password. **Deferred with a tracked gate:** side-effecting `[RequiresAuthentication]`
|
||||
input length caps on username/password. **Logout rotates the security stamp** when called from a local session
|
||||
(E2E-caught: `SignOutAsync` alone only clears the *client* cookie, leaving the stateless encrypted ticket
|
||||
replayable server-side) — so signing out actually ends the session server-side; for the single admin this
|
||||
revokes all local sessions ("log out everywhere"). Gated on an authenticated session so an unauthenticated
|
||||
caller can't force-revoke the admin. **Deferred with a tracked gate:** side-effecting `[RequiresAuthentication]`
|
||||
GETs (troubleshoot playback/archive) aren't CSRF-covered — **#301**, gating PR2 (latent in PR1: the SPA still
|
||||
uses the machine key). OIDC-session revocation lever (no local stamp) noted for PR3 operator docs.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user