From 9a9aaf0740d4b3607c4a42e7fcebbe78f01bb91a Mon Sep 17 00:00:00 2001 From: Timothy Date: Sun, 12 Jul 2026 16:46:41 +0200 Subject: [PATCH] =?UTF-8?q?fix(api):=20#295=20PR1=20=E2=80=94=20logout=20e?= =?UTF-8?q?nds=20the=20session=20server-side=20(E2E-caught)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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) --- .../Auth/RotateLocalAdminSecurityStamp.cs | 9 +++ .../RotateLocalAdminSecurityStampHandler.cs | 28 ++++++++ ...tateLocalAdminSecurityStampHandlerTests.cs | 65 +++++++++++++++++++ ErsatzTV/Controllers/Api/AuthController.cs | 19 +++++- docs/decisions.md | 6 +- 5 files changed, 124 insertions(+), 3 deletions(-) create mode 100644 ErsatzTV.Application/Auth/RotateLocalAdminSecurityStamp.cs create mode 100644 ErsatzTV.Application/Auth/RotateLocalAdminSecurityStampHandler.cs create mode 100644 ErsatzTV.Tests/Application/Auth/RotateLocalAdminSecurityStampHandlerTests.cs diff --git a/ErsatzTV.Application/Auth/RotateLocalAdminSecurityStamp.cs b/ErsatzTV.Application/Auth/RotateLocalAdminSecurityStamp.cs new file mode 100644 index 000000000..d083e7058 --- /dev/null +++ b/ErsatzTV.Application/Auth/RotateLocalAdminSecurityStamp.cs @@ -0,0 +1,9 @@ +namespace ErsatzTV.Application.Auth; + +/// +/// Rotates the local admin security stamp, revoking every outstanding local session server-side (their +/// cookies carry the old stamp and fail OnValidatePrincipal 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). +/// +public record RotateLocalAdminSecurityStamp : IRequest; diff --git a/ErsatzTV.Application/Auth/RotateLocalAdminSecurityStampHandler.cs b/ErsatzTV.Application/Auth/RotateLocalAdminSecurityStampHandler.cs new file mode 100644 index 000000000..4f01ee161 --- /dev/null +++ b/ErsatzTV.Application/Auth/RotateLocalAdminSecurityStampHandler.cs @@ -0,0 +1,28 @@ +using ErsatzTV.Core.Domain; +using ErsatzTV.Infrastructure.Data; +using Microsoft.EntityFrameworkCore; + +namespace ErsatzTV.Application.Auth; + +public class RotateLocalAdminSecurityStampHandler(IDbContextFactory dbContextFactory) + : IRequestHandler +{ + public async Task 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; + } +} diff --git a/ErsatzTV.Tests/Application/Auth/RotateLocalAdminSecurityStampHandlerTests.cs b/ErsatzTV.Tests/Application/Auth/RotateLocalAdminSecurityStampHandlerTests.cs new file mode 100644 index 000000000..7b1209e6f --- /dev/null +++ b/ErsatzTV.Tests/Application/Auth/RotateLocalAdminSecurityStampHandlerTests.cs @@ -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 claim = await new ClaimLocalAdminHandler(_db.Factory, _passwordHasher) + .Handle(new ClaimLocalAdmin("admin", "supersecret"), CancellationToken.None); + claim.IsRight.ShouldBeTrue(); + + Option before = + await _configElementRepository.GetValue(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 after = + await _configElementRepository.GetValue(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 stamp = + await _configElementRepository.GetValue(ConfigElementKey.AuthSecurityStamp, CancellationToken.None); + stamp.IsNone.ShouldBeTrue(); + } +} diff --git a/ErsatzTV/Controllers/Api/AuthController.cs b/ErsatzTV/Controllers/Api/AuthController.cs index 682bc93e2..52dbca279 100644 --- a/ErsatzTV/Controllers/Api/AuthController.cs +++ b/ErsatzTV/Controllers/Api/AuthController.cs @@ -87,9 +87,15 @@ public class AuthController(IMediator mediator) : ControllerBase }); } - /// Sign out of the cookie session. Requires the CSRF header (this controller is filter-exempt). + /// + /// 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 server-side (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. + /// [HttpPost("/api/auth/logout")] - public async Task Logout() + public async Task 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(); } diff --git a/docs/decisions.md b/docs/decisions.md index b386bd43d..2eb2899d9 100644 --- a/docs/decisions.md +++ b/docs/decisions.md @@ -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.