From d3559d7d3aaaf4c8e6cd22a449b71a0ac4f3166b Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Thu, 26 Nov 2026 00:49:50 +0100 Subject: [PATCH 01/14] fix: require account proof for activation and email change verification - Activation from another browser needs the password or linked OAuth sign-in - Email change verification requires a session of the requesting account - Revalidate authentication on SignalR hub invocations - Delete accounts that were never activated --- API.IntegrationTests/Tests/MailTests.cs | 362 ++++++++++++++++++ API/Controller/Account/Activate.cs | 42 +- .../Account/Authenticated/ChangePassword.cs | 2 +- .../Authenticated/OAuthConnectionRemove.cs | 21 +- .../Authenticated/VerifyEmailChange.cs | 44 +++ API/Controller/Account/VerifyEmail.cs | 54 --- API/Controller/OAuth/Authorize.cs | 5 +- API/Controller/OAuth/HandOff.cs | 26 +- API/Controller/OAuth/SignupFinalize.cs | 43 ++- API/Controller/OAuth/_ApiController.cs | 7 + API/OAuth/OAuthConstants.cs | 1 + API/OAuth/OAuthError.cs | 5 + API/OAuth/OAuthUtil.cs | 19 +- API/Services/Account/AccountService.cs | 183 ++++++++- API/Services/Account/IAccountService.cs | 57 ++- .../Authentication/ActivationResendCookie.cs | 6 +- Common/Constants/Constants.cs | 1 + Common/Errors/AccountError.cs | 13 +- .../Hubs/RevalidateAuthenticationHubFilter.cs | 90 +++++ Common/Hubs/UserHub.cs | 11 +- Common/OpenShockServiceHelper.cs | 8 +- .../Tests/DeleteUnactivatedAccountsTests.cs | 91 +++++ Cron/Jobs/DeleteUnactivatedAccountsJob.cs | 57 +++ 23 files changed, 1038 insertions(+), 110 deletions(-) create mode 100644 API/Controller/Account/Authenticated/VerifyEmailChange.cs delete mode 100644 API/Controller/Account/VerifyEmail.cs create mode 100644 Common/Hubs/RevalidateAuthenticationHubFilter.cs create mode 100644 Cron.IntegrationTests/Tests/DeleteUnactivatedAccountsTests.cs create mode 100644 Cron/Jobs/DeleteUnactivatedAccountsJob.cs diff --git a/API.IntegrationTests/Tests/MailTests.cs b/API.IntegrationTests/Tests/MailTests.cs index 3ed344cf4..8787b7732 100644 --- a/API.IntegrationTests/Tests/MailTests.cs +++ b/API.IntegrationTests/Tests/MailTests.cs @@ -416,6 +416,368 @@ public async Task PasswordResetComplete_UnactivatedUser_ActivatesAccount() await Assert.That(await db.UserActivationRequests.AsNoTracking().AnyAsync(r => r.UserId == userId)).IsFalse(); } + // A reset only signs sessions out. On an activated account every OAuth link and API token was put there + // by its owner, so they stay. + [Test] + public async Task PasswordResetComplete_ActivatedAccount_KeepsOAuthConnectionsAndApiTokens() + { + var email = TestHelper.UniqueEmail("mail-pwreset-recovery"); + var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailpwresetrecov"), email, "OldPassword123#"); + await AddOAuthConnectionAsync(userId, "discord"); + await AddOAuthConnectionAsync(userId, "google"); + var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, userId); + + var response = await CompleteSeededPasswordResetAsync(userId); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.UserOAuthConnections.AsNoTracking().CountAsync(c => c.UserId == userId)).IsEqualTo(2); + await Assert.That(await db.ApiTokens.AsNoTracking().AnyAsync(t => t.Id == tokenId)).IsTrue(); + + using var tokenClient = TestHelper.CreateApiTokenClient(WebApplicationFactory, rawToken); + await Assert.That((await tokenClient.GetAsync("/1/users/self")).StatusCode).IsEqualTo(HttpStatusCode.OK); + } + + // The reset is what activates this account, and the identity it was signed up with may be someone + // else's (anyone can do an OAuth signup naming this address), so that link must not survive. + [Test] + public async Task PasswordResetComplete_UnactivatedOAuthAccount_RemovesConnection() + { + var email = TestHelper.UniqueEmail("mail-pwreset-oauth-unact"); + var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailpwresetoauthu"), email, "OldPassword123#", activated: false); + await AddOAuthConnectionAsync(userId, "discord"); + + var response = await CompleteSeededPasswordResetAsync(userId); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.UserOAuthConnections.AsNoTracking().CountAsync(c => c.UserId == userId)).IsEqualTo(0); + } + + // --- A never activated account is a pending signup: it does not keep others off its email --- + + [Test] + public async Task Signup_EmailHeldByStalePendingAccount_ReplacesIt() + { + var email = TestHelper.UniqueEmail("mail-pending-stale"); + var pendingId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailpendingstale"), email, "SquatterPassword123#", activated: false); + await BackdateUserAsync(pendingId, TimeSpan.FromMinutes(11)); + + using var client = CreateCookielessClient(); + var response = await SignUpAsync(client, email, TestHelper.UniqueUsername("mailpendingowner")); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var holder = await db.Users.AsNoTracking().SingleAsync(u => u.Email == email); + await Assert.That(holder.Id).IsNotEqualTo(pendingId); + } + + // Inside the resend cooldown the pending account keeps the address, so its creator has time to open the + // link and repeated signups cannot mail the inbox more often than a resend could. + [Test] + public async Task Signup_EmailHeldByFreshPendingAccount_Returns409() + { + var email = TestHelper.UniqueEmail("mail-pending-fresh"); + var pendingId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailpendingfresh"), email, "FirstPassword123#", activated: false); + + using var client = CreateCookielessClient(); + var response = await SignUpAsync(client, email, TestHelper.UniqueUsername("mailpendingsecond")); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.Users.AsNoTracking().AnyAsync(u => u.Id == pendingId)).IsTrue(); + } + + [Test] + public async Task Signup_EmailHeldByActivatedAccount_Returns409() + { + var email = TestHelper.UniqueEmail("mail-pending-activated"); + var ownerId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailpendingact"), email, "OwnerPassword123#"); + await BackdateUserAsync(ownerId, TimeSpan.FromDays(1)); + + using var client = CreateCookielessClient(); + var response = await SignUpAsync(client, email, TestHelper.UniqueUsername("mailpendingact2")); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + } + + private async Task BackdateUserAsync(Guid userId, TimeSpan by) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await db.Users.Where(u => u.Id == userId).ExecuteUpdateAsync(s => s.SetProperty(u => u.CreatedAt, u => u.CreatedAt - by)); + } + + // --- Disconnecting a provider must not leave an account with no way to sign in --- + + [Test] + public async Task RemoveOAuthConnection_OnlyLoginMethod_Returns409_AndKeepsConnection() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailoauthlast"), TestHelper.UniqueEmail("mail-oauth-last"), "Placeholder123#"); + await AddOAuthConnectionAsync(user.Id, "discord"); + await using (var seedScope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var seedDb = seedScope.ServiceProvider.GetRequiredService(); + await seedDb.Users.Where(u => u.Id == user.Id).ExecuteUpdateAsync(s => s.SetProperty(u => u.PasswordHash, (string?)null)); + } + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var response = await client.DeleteAsync("/1/account/connections/discord"); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.UserOAuthConnections.AsNoTracking().CountAsync(c => c.UserId == user.Id)).IsEqualTo(1); + } + + [Test] + public async Task RemoveOAuthConnection_AccountWithPassword_RemovesIt() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailoauthpw"), TestHelper.UniqueEmail("mail-oauth-pw"), "OwnerPassword123#"); + await AddOAuthConnectionAsync(user.Id, "discord"); + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var response = await client.DeleteAsync("/1/account/connections/discord"); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NoContent); + } + + // --- Activation needs the emailed token and proof of having signed up --- + + [Test] + public async Task Activate_FromSignupBrowser_ActivatesWithTokenAlone() + { + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-activate-cookie", "OwnerPassword123#"); + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token, cookie: MintResendCookie(userId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await IsActivatedAsync(userId)).IsTrue(); + } + + // What the owner of the inbox has when someone else signed up with their address. + [Test] + public async Task Activate_TokenAloneFromAnotherBrowser_Returns403_AndLeavesAccountUnactivated() + { + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-activate-alone", "OwnerPassword123#"); + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Account.Activation.CredentialRequired"); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + + // The token stays usable for whoever does know the password. + var retry = await PostActivateAsync(client, token, password: "OwnerPassword123#"); + await Assert.That(retry.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await IsActivatedAsync(userId)).IsTrue(); + } + + [Test] + public async Task Activate_WrongPassword_Returns403() + { + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-activate-wrongpw", "OwnerPassword123#"); + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token, password: "NotThePassword123#"); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + [Test] + public async Task Activate_SignupCookieOfAnotherAccount_Returns403() + { + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-activate-othercookie", "OwnerPassword123#"); + var otherUserId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailactother"), TestHelper.UniqueEmail("mail-activate-other"), "OtherPassword123#", activated: false); + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token, cookie: MintResendCookie(otherUserId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + [Test] + public async Task Activate_OAuthOnlyAccount_TokenAlone_Returns403_NamingTheProvider() + { + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-activate-oauth", password: null); + await AddOAuthConnectionAsync(userId, "discord"); + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await response.Content.ReadAsStringAsync()).Contains("discord"); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + [Test] + public async Task Activate_UnknownToken_Returns400() + { + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, "no-such-activation-token"); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + } + + // --- An email change is only confirmed from a session of the account that asked for it --- + + [Test] + public async Task EmailChangeVerify_WithoutSession_Returns401_AndLeavesEmail() + { + var (user, token, _) = await CreateUserWithPendingEmailChangeAsync("mail-verify-anon"); + + using var client = CreateCookielessClient(); + var response = await client.PostAsync($"/1/account/email-change/verify?token={token}", null); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + await Assert.That(await GetEmailAsync(user.Id)).IsEqualTo(user.Email); + } + + [Test] + public async Task EmailChangeVerify_FromAnotherAccountsSession_Returns400_AndLeavesEmail() + { + var (user, token, _) = await CreateUserWithPendingEmailChangeAsync("mail-verify-other"); + var other = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailverifyother"), TestHelper.UniqueEmail("mail-verify-otheracct"), "SecurePassword123#"); + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, other.SessionToken); + var response = await client.PostAsync($"/1/account/email-change/verify?token={token}", null); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(await GetEmailAsync(user.Id)).IsEqualTo(user.Email); + } + + [Test] + public async Task EmailChangeVerify_FromOwnSession_AppliesChange() + { + var (user, token, newEmail) = await CreateUserWithPendingEmailChangeAsync("mail-verify-own"); + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var response = await client.PostAsync($"/1/account/email-change/verify?token={token}", null); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await GetEmailAsync(user.Id)).IsEqualTo(newEmail); + } + + // Stands in for the Cron delivery job, which mints the real activation token at send time. + private async Task<(Guid UserId, string Token)> CreateUnactivatedUserWithTokenAsync(string prefix, string? password) + { + var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername(prefix.Replace("-", "")), TestHelper.UniqueEmail(prefix), password ?? "Placeholder123#", activated: false); + var token = "activation-" + Guid.NewGuid().ToString("N"); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + if (password is null) + { + await db.Users.Where(u => u.Id == userId).ExecuteUpdateAsync(s => s.SetProperty(u => u.PasswordHash, (string?)null)); + } + db.UserActivationRequests.Add(new UserActivationRequest { UserId = userId, TokenHash = HashingUtils.HashToken(token) }); + await db.SaveChangesAsync(); + + return (userId, token); + } + + private static Task PostActivateAsync(HttpClient client, string token, string? password = null, string? cookie = null) + { + var request = new HttpRequestMessage(HttpMethod.Post, $"/1/account/activate?token={token}"); + if (password is not null) request.Content = TestHelper.JsonContent(new { password }); + if (cookie is not null) request.Headers.Add("Cookie", cookie); + return client.SendAsync(request); + } + + private async Task IsActivatedAsync(Guid userId) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.ActivatedAt != null).SingleAsync(); + } + + private async Task<(AuthenticatedUser User, string Token, string NewEmail)> CreateUserWithPendingEmailChangeAsync(string prefix) + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername(prefix.Replace("-", "")), TestHelper.UniqueEmail(prefix + "-old"), "SecurePassword123#"); + var newEmail = TestHelper.UniqueEmail(prefix + "-new"); + var token = "email-change-" + Guid.NewGuid().ToString("N"); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var stamp = await db.Users.AsNoTracking().Where(u => u.Id == user.Id).Select(u => u.SecurityStamp).SingleAsync(); + db.UserEmailChanges.Add(new UserEmailChange + { + Id = Guid.CreateVersion7(), + UserId = user.Id, + OldEmail = user.Email, + NewEmail = newEmail, + TokenHash = HashingUtils.HashToken(token), + SecurityStampAtCreate = stamp + }); + await db.SaveChangesAsync(); + + return (user, token, newEmail); + } + + private async Task GetEmailAsync(Guid userId) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.Email).SingleAsync(); + } + + [Test] + public async Task PasswordResetComplete_RevokesExistingSessions() + { + var email = TestHelper.UniqueEmail("mail-pwreset-sessions"); + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailpwresetsess"), email, "OldPassword123#"); + + var response = await CompleteSeededPasswordResetAsync(user.Id); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var selfResponse = await client.GetAsync("/1/users/self"); + await Assert.That(selfResponse.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + } + + // Stands in for the Cron delivery job (which mints the real token), then completes the reset. + private async Task CompleteSeededPasswordResetAsync(Guid userId) + { + const string secret = "test-password-reset-secret"; + var resetId = Guid.CreateVersion7(); + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var stamp = await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.SecurityStamp).SingleAsync(); + db.UserPasswordResets.Add(new UserPasswordReset + { + Id = resetId, + UserId = userId, + TokenHash = HashingUtils.HashToken(secret), + SecurityStampAtCreate = stamp + }); + await db.SaveChangesAsync(); + } + + using var client = WebApplicationFactory.CreateClient(); + return await client.PostAsync($"/1/account/password-reset/{resetId}/{secret}/complete", + TestHelper.JsonContent(new { password = "NewPassword123#" })); + } + + private async Task AddOAuthConnectionAsync(Guid userId, string provider) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.UserOAuthConnections.Add(new UserOAuthConnection + { + UserId = userId, + ProviderKey = provider, + ExternalId = Guid.CreateVersion7().ToString(), + DisplayName = "external" + }); + await db.SaveChangesAsync(); + } + [Test] public async Task PasswordResetComplete_LegacyRecoverRoute_Returns410Gone() { diff --git a/API/Controller/Account/Activate.cs b/API/Controller/Account/Activate.cs index e37090bfd..3d8313c0d 100644 --- a/API/Controller/Account/Activate.cs +++ b/API/Controller/Account/Activate.cs @@ -1,8 +1,13 @@ using System.Net.Mime; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.RateLimiting; +using OpenShock.API.Services.Account; using OpenShock.Common.ApiVersioning; +using OpenShock.Common.Authentication; using OpenShock.Common.Errors; using OpenShock.Internal.Common.Problems; +using Results = OpenShock.Common.Results; namespace OpenShock.API.Controller.Account; @@ -11,14 +16,41 @@ public sealed partial class AccountController /// /// Activate account /// + /// + /// In the browser that signed up, the emailed token is enough. From anywhere else the caller must also + /// show the account is theirs, since the token only proves control of the inbox and anyone can sign up + /// with somebody else's address: send the account's password in the body, or, for an account created + /// through OAuth, start a sign-in with the linked provider passing this token as activationToken. + /// + /// Account activated + /// No pending activation matches the token + /// The token is valid, but the account's password or linked sign-in is also required [HttpPost("activate")] [ApiVersion(1)] + [EnableRateLimiting("auth")] [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] - public async Task Activate([FromQuery(Name = "token")] string token, CancellationToken cancellationToken) + [ProducesResponseType(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] // AccountActivationNotFound + [ProducesResponseType(StatusCodes.Status403Forbidden, MediaTypeNames.Application.ProblemJson)] // AccountActivationCredentialRequired + public async Task Activate( + [FromQuery(Name = "token")] string token, + [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] ActivateRequest? body, + CancellationToken cancellationToken) { - bool ok = await _accountService.TryActivateAccountAsync(token, cancellationToken); - - return ok ? Ok() : Problem(AccountError.AccountActivationNotFound); + ActivationResendCookie.TryGetUserId(HttpContext, out var signupBrowserUserId); + + var result = await _accountService.ActivateAccountAsync(token, signupBrowserUserId, body?.Password, cancellationToken); + + return result switch + { + Results.Success => Ok(), + ActivationCredentialRequired required => Problem(AccountError.AccountActivationCredentialRequired(required.HasPassword, required.OAuthProviders, required.PasswordInvalid)), + Results.NotFound => Problem(AccountError.AccountActivationNotFound) + }; + } + + public sealed class ActivateRequest + { + /// The account's password. Only needed when activating from a browser other than the one that signed up. + public string? Password { get; init; } } } diff --git a/API/Controller/Account/Authenticated/ChangePassword.cs b/API/Controller/Account/Authenticated/ChangePassword.cs index 8d562b533..6d4d04263 100644 --- a/API/Controller/Account/Authenticated/ChangePassword.cs +++ b/API/Controller/Account/Authenticated/ChangePassword.cs @@ -29,7 +29,7 @@ public sealed partial class AuthenticatedAccountController public async Task ChangePassword([FromBody] ChangePasswordRequest body, CancellationToken cancellationToken) { // OAuth-only accounts that have never set a password must go through the email-confirmed - // /password/set flow rather than silently setting one through this endpoint. + // password reset flow rather than silently setting one through this endpoint. if (string.IsNullOrEmpty(CurrentUser.PasswordHash)) { return Problem(AccountError.PasswordNotSet); diff --git a/API/Controller/Account/Authenticated/OAuthConnectionRemove.cs b/API/Controller/Account/Authenticated/OAuthConnectionRemove.cs index 9796a6cfc..a875db9b3 100644 --- a/API/Controller/Account/Authenticated/OAuthConnectionRemove.cs +++ b/API/Controller/Account/Authenticated/OAuthConnectionRemove.cs @@ -1,6 +1,11 @@ -using Microsoft.AspNetCore.Mvc; +using System.Net.Mime; +using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; +using OpenShock.API.OAuth; using OpenShock.API.Services.OAuthConnection; using OpenShock.Common.ApiVersioning; +using OpenShock.Common.Problems; +using OpenShock.Internal.Common.Problems; namespace OpenShock.API.Controller.Account.Authenticated; @@ -14,12 +19,26 @@ public sealed partial class AuthenticatedAccountController /// /// Connection removed. /// No connection found for this provider. + /// The connection is the account's only way to sign in. [HttpDelete("connections/{provider}")] [ApiVersion(1)] [ProducesResponseType(StatusCodes.Status204NoContent)] [ProducesResponseType(StatusCodes.Status404NotFound)] + [ProducesResponseType(StatusCodes.Status409Conflict, MediaTypeNames.Application.ProblemJson)] // LastLoginMethod public async Task RemoveOAuthConnection([FromRoute] string provider, [FromServices] IOAuthConnectionService connectionService, CancellationToken cancellationToken) { + // An account without a password signs in through its connections only. Removing the last one would + // lock its owner out until they notice and go through a password reset. + if (string.IsNullOrEmpty(CurrentUser.PasswordHash)) + { + var providers = await connectionService.GetConnectionsAsNonTrackingQuery(CurrentUser.Id, cancellationToken) + .Select(c => c.ProviderKey) + .ToListAsync(cancellationToken); + + if (providers.Count == 1 && string.Equals(providers[0], provider, StringComparison.OrdinalIgnoreCase)) + return Problem(OAuthError.LastLoginMethod); + } + var deleted = await connectionService.TryRemoveConnectionAsync(CurrentUser.Id, provider, actorId: CurrentUser.Id, cancellationToken); if (!deleted) diff --git a/API/Controller/Account/Authenticated/VerifyEmailChange.cs b/API/Controller/Account/Authenticated/VerifyEmailChange.cs new file mode 100644 index 000000000..ca6dbfe3c --- /dev/null +++ b/API/Controller/Account/Authenticated/VerifyEmailChange.cs @@ -0,0 +1,44 @@ +using System.Diagnostics; +using System.Net.Mime; +using Microsoft.AspNetCore.Mvc; +using OpenShock.API.Services.Account; +using OpenShock.Common.ApiVersioning; +using OpenShock.Common.Errors; +using OpenShock.Common.Problems; +using Results = OpenShock.Common.Results; + +using OpenShock.Internal.Common.Problems; + +namespace OpenShock.API.Controller.Account.Authenticated; + +public sealed partial class AuthenticatedAccountController +{ + /// + /// Verify a pending email change of the current user using the token from the verification email. + /// + /// + /// Requires a session of the account that requested the change. The link is mailed to an address the + /// account does not own yet, so opening it proves nothing about the account: accepted anonymously, a + /// stranger's click would put their address on someone else's account. + /// + /// Email change verified and applied + /// Token is invalid, already used, expired, or belongs to another account + /// The new email address was claimed by another account before verification completed + [HttpPost("email-change/verify")] + [ApiVersion(1)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] // EmailChangeNotFound + [ProducesResponseType(StatusCodes.Status409Conflict, MediaTypeNames.Application.ProblemJson)] // EmailChangeAlreadyInUse + public async Task EmailVerify([FromQuery(Name = "token")] string token, CancellationToken cancellationToken) + { + var result = await _accountService.TryVerifyEmailAsync(token, CurrentUser.Id, cancellationToken); + + return result switch + { + VerifyEmailSuccess => Ok(), + Results.NotFound => Problem(AccountError.EmailChangeNotFound), + EmailAlreadyInUse => Problem(AccountError.EmailChangeAlreadyInUse), + _ => throw new UnreachableException() + }; + } +} diff --git a/API/Controller/Account/VerifyEmail.cs b/API/Controller/Account/VerifyEmail.cs deleted file mode 100644 index 0e5ee0ea1..000000000 --- a/API/Controller/Account/VerifyEmail.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System.Diagnostics; -using System.Net.Mime; -using Microsoft.AspNetCore.Mvc; -using OpenShock.API.Services.Account; -using OpenShock.Common.ApiVersioning; -using OpenShock.Common.Errors; -using OpenShock.Internal.Common.Problems; -using Results = OpenShock.Common.Results; - -namespace OpenShock.API.Controller.Account; - -public sealed partial class AccountController -{ - /// - /// Verify a pending email change using the token from the verification email. - /// - /// Email change verified and applied - /// Token is invalid, already used, or the request has expired - /// The new email address was claimed by another account before verification completed - [HttpPost("email-change/verify")] - [ApiVersion(1)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] - [ProducesResponseType(StatusCodes.Status409Conflict, MediaTypeNames.Application.ProblemJson)] - public Task EmailVerify([FromQuery(Name = "token")] string token, CancellationToken cancellationToken) - => VerifyPendingEmailChange(token, cancellationToken); - - /// - /// Verify a pending email change. Deprecated: use POST /email-change/verify instead. - /// - /// Email change verified and applied - /// Token is invalid, already used, or the request has expired - /// The new email address was claimed by another account before verification completed - [Obsolete("Use POST /email-change/verify instead.")] - [HttpPost("verify-email")] - [ApiVersion(1)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] - [ProducesResponseType(StatusCodes.Status409Conflict, MediaTypeNames.Application.ProblemJson)] - public Task EmailVerifyLegacy([FromQuery(Name = "token")] string token, CancellationToken cancellationToken) - => VerifyPendingEmailChange(token, cancellationToken); - - private async Task VerifyPendingEmailChange(string token, CancellationToken cancellationToken) - { - var result = await _accountService.TryVerifyEmailAsync(token, cancellationToken); - - return result switch - { - VerifyEmailSuccess => Ok(), - Results.NotFound => Problem(AccountError.EmailChangeNotFound), - EmailAlreadyInUse => Problem(AccountError.EmailChangeAlreadyInUse) - }; - } -} diff --git a/API/Controller/OAuth/Authorize.cs b/API/Controller/OAuth/Authorize.cs index 28d4a13de..6993b08dc 100644 --- a/API/Controller/OAuth/Authorize.cs +++ b/API/Controller/OAuth/Authorize.cs @@ -17,13 +17,14 @@ public sealed partial class OAuthController /// /// Provider key (e.g. discord). /// Flow to run + /// Token from the activation email; signing in with the account's linked provider then activates it. /// Redirect to the provider authorization page. /// Unsupported or misconfigured provider. [HttpPost("{provider}/authorize")] [ApiVersion(1)] [EnableRateLimiting("auth")] [ApiExplorerSettings(IgnoreApi = true)] - public async Task OAuthAuthorize([FromRoute] string provider, [FromQuery(Name="flow"), Required] OAuthFlow flow) + public async Task OAuthAuthorize([FromRoute] string provider, [FromQuery(Name="flow"), Required] OAuthFlow flow, [FromQuery(Name = "activationToken"), StringLength(128)] string? activationToken = null) { if (!await _schemeProvider.IsSupportedOAuthScheme(provider)) return Problem(OAuthError.UnsupportedProvider); @@ -40,6 +41,6 @@ public async Task OAuthAuthorize([FromRoute] string provider, [Fr return Problem(OAuthError.UnsupportedFlow); } - return OAuthUtil.StartOAuth(provider, flow); + return OAuthUtil.StartOAuth(provider, flow, flow == OAuthFlow.LoginOrCreate ? activationToken : null); } } diff --git a/API/Controller/OAuth/HandOff.cs b/API/Controller/OAuth/HandOff.cs index 89a22a441..481eb1a3a 100644 --- a/API/Controller/OAuth/HandOff.cs +++ b/API/Controller/OAuth/HandOff.cs @@ -67,8 +67,11 @@ public async Task OAuthHandOff( // If the provider returned an email that already belongs to an existing OpenShock // user, do not allow creating a second account with the same email. The user must // log in to that account and link the provider from the connections settings. + // Only for an address the provider verified: an unverified one is whatever the caller typed + // at the provider, and answering for it would tell anyone which emails are registered. var externalEmail = auth.Principal.FindFirst(ClaimTypes.Email)?.Value; if (!string.IsNullOrWhiteSpace(externalEmail) && + IsTruthy(auth.Principal.FindFirst(OAuthConstants.ClaimEmailVerified)?.Value) && await _accountService.IsEmailRegisteredAsync(externalEmail, cancellationToken)) { await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); @@ -87,22 +90,33 @@ await _accountService.IsEmailRegisteredAsync(externalEmail, cancellationToken)) return RedirectFrontendError("accountDeactivated"); } - if (connection.User.ActivatedAt is null) + // A flow started from the account's emailed activation link that comes back with the linked + // identity shows inbox and credential are held by the same party, so the account is theirs: + // activate it and carry on to the sign-in below. + var isActivated = connection.User.ActivatedAt is not null || + (auth.Properties.Items.TryGetValue(OAuthConstants.ItemKeyActivationToken, out var activationToken) && + !string.IsNullOrEmpty(activationToken) && + await _accountService.TryActivateAccountAsync(connection.UserId, activationToken, cancellationToken)); + + if (!isActivated) { - // The provider vouched for the identity, so the caller owns this account: (re)send the - // activation link (rate limited inside the service). + // The provider vouched for the identity, so the caller holds the account's credential: (re)send + // the activation link (rate limited inside the service). Opening it is still required, the + // address on the account was typed in at signup and is not known to be theirs. try { await _accountService.ResendActivationEmailAsync(connection.UserId, cancellationToken); } catch (Exception ex) when (ex is not OperationCanceledException) { - // Best effort: still clear the flow cookie and redirect with the real reason. + // Best effort: the redirect below still tells the user what is going on. _logger.LogError(ex, "Failed to resend activation email on OAuth login"); } - await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); - return RedirectFrontendError("accountNotActivated"); + // Back to the signup form with the flow cookie kept: it explains that activation is + // pending, and lets someone who mistyped their email correct it instead of being stuck + // with an account they can never activate (see OAuthSignupFinalize). + return RedirectFrontendPath($"/oauth/{Uri.EscapeDataString(provider)}/create?pending=1"); } // Direct sign-in diff --git a/API/Controller/OAuth/SignupFinalize.cs b/API/Controller/OAuth/SignupFinalize.cs index 9943cad7a..122861af9 100644 --- a/API/Controller/OAuth/SignupFinalize.cs +++ b/API/Controller/OAuth/SignupFinalize.cs @@ -88,12 +88,38 @@ public async Task OAuthSignupFinalize( var isVerifiedString = auth.Principal.FindFirst(OAuthConstants.ClaimEmailVerified)?.Value; var isEmailTrusted = IsTruthy(isVerifiedString) && string.Equals(externalAccountEmail, email, StringComparison.InvariantCultureIgnoreCase); - // Do not allow creation if this external is already linked anywhere. + // Do not allow creation if this external is already linked to a real account. var existing = await connectionService.GetByProviderExternalIdAsync(provider, auth.ExternalAccountId, cancellationToken); if (existing is not null) { - await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); - return Problem(OAuthError.ExternalAlreadyLinked); + if (existing.User.ActivatedAt is not null || existing.User.UserDeactivation is not null) + { + await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); + return Problem(OAuthError.ExternalAlreadyLinked); + } + + // Linked to a signup this identity started but never activated, most likely because the email + // was mistyped and the link never arrived. The caller just proved they hold the identity, and a + // pending account has nothing in it, so let them start over instead of being stuck with it. + if (isEmailTrusted) + { + // The provider vouches for the new address: replace the pending account with a real one below. + await _accountService.DiscardPendingAccountAsync(existing.UserId, cancellationToken); + } + else + { + var restarted = await _accountService.RestartPendingSignupAsync(existing.UserId, email, username, cancellationToken); + if (restarted.Value is not User pendingUser) + { + // Username or email already exists: keep the flow cookie so the frontend can retry. + return Problem(SignupError.UsernameOrEmailExists); + } + + ActivationResendCookie.Set(HttpContext, pendingUser.Id, domain); + await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); + + return Ok(LoginV2OkResponse.FromUser(pendingUser)); + } } var created = await _accountService.CreateOAuthOnlyAccountAsync( @@ -128,16 +154,5 @@ public async Task OAuthSignupFinalize( await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); return Ok(LoginV2OkResponse.FromUser(newUser)); - - static bool IsTruthy(string? value) - { - if (string.IsNullOrWhiteSpace(value)) return false; - return value.Trim().ToLowerInvariant() switch - { - "0" or "no" or "false" => false, - "1" or "yes" or "true" => true, - _ => false - }; - } } } diff --git a/API/Controller/OAuth/_ApiController.cs b/API/Controller/OAuth/_ApiController.cs index 87de71d25..70b356afd 100644 --- a/API/Controller/OAuth/_ApiController.cs +++ b/API/Controller/OAuth/_ApiController.cs @@ -27,6 +27,13 @@ public OAuthController(IAccountService accountService, IAuthenticationSchemeProv _logger = logger; } + /// Reads a provider's "email verified" claim, which arrives as a loosely typed string. + private static bool IsTruthy(string? value) + { + if (string.IsNullOrWhiteSpace(value)) return false; + return value.Trim().ToLowerInvariant() is "1" or "yes" or "true"; + } + private enum OAuthValidationError { FlowStateMissing, diff --git a/API/OAuth/OAuthConstants.cs b/API/OAuth/OAuthConstants.cs index f07fc8438..b1a6e3605 100644 --- a/API/OAuth/OAuthConstants.cs +++ b/API/OAuth/OAuthConstants.cs @@ -11,6 +11,7 @@ public static class OAuthConstants public static readonly string[] OAuth2Schemes = [DiscordScheme, GoogleScheme, TwitterScheme]; public const string ItemKeyFlowType = ".FlowType"; + public const string ItemKeyActivationToken = ".ActivationToken"; public const string ClaimEmailVerified = "openshock.oauth.email_verified"; public const string ClaimDisplayName = "openshock.oauth.display_name"; diff --git a/API/OAuth/OAuthError.cs b/API/OAuth/OAuthError.cs index b07d2ba6d..408bdf6d7 100644 --- a/API/OAuth/OAuthError.cs +++ b/API/OAuth/OAuthError.cs @@ -53,6 +53,11 @@ public static class OAuthError "Your account already has an OAuth connection for this provider", HttpStatusCode.Conflict); + public static OpenShockProblem LastLoginMethod => new( + "OAuth.Connection.LastLoginMethod", + "This is the only way to sign in to this account. Set a password before disconnecting it", + HttpStatusCode.Conflict); + public static OpenShockProblem ExternalAlreadyLinked => new( "OAuth.Connection.AlreadyLinked", "This external account is already linked to another user", diff --git a/API/OAuth/OAuthUtil.cs b/API/OAuth/OAuthUtil.cs index a6ed3e9db..d59e3e609 100644 --- a/API/OAuth/OAuthUtil.cs +++ b/API/OAuth/OAuthUtil.cs @@ -5,12 +5,25 @@ namespace OpenShock.API.OAuth; public static class OAuthUtil { - public static ChallengeResult StartOAuth(string provider, OAuthFlow flow) + /// + /// + /// + /// Token from the activation email, carried through the provider round trip so the handoff can + /// activate the account the returned identity is linked to. + /// + public static ChallengeResult StartOAuth(string provider, OAuthFlow flow, string? activationToken = null) { - return new ChallengeResult(provider, new AuthenticationProperties + var properties = new AuthenticationProperties { RedirectUri = $"/1/oauth/{provider}/handoff", Items = { { OAuthConstants.ItemKeyFlowType, flow.ToString() } } - }); + }; + + if (!string.IsNullOrEmpty(activationToken)) + { + properties.Items[OAuthConstants.ItemKeyActivationToken] = activationToken; + } + + return new ChallengeResult(provider, properties); } } diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index 0453e1a6a..341ece863 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -100,6 +100,8 @@ private async Task CreateAccount(string email, string use if (await IsUserNameBlacklisted(username, cancellationToken) || await IsEmailProviderBlacklisted(email, cancellationToken)) return new AccountWithEmailOrUsernameExists(); + await ReleaseEmailFromPendingAccountAsync(email, claimantOwnsEmail: false, exceptUserId: null, cancellationToken); + if (await _db.Users.AnyAsync(x => x.Email == email || x.Name == username, cancellationToken)) return new AccountWithEmailOrUsernameExists(); @@ -167,7 +169,89 @@ public async Task CreateAccountWithActivationFlowAsync(st public Task IsEmailRegisteredAsync(string email, CancellationToken cancellationToken = default) { email = email.ToLowerInvariant(); - return _db.Users.AnyAsync(u => u.Email == email, cancellationToken); + return _db.Users.AnyAsync(u => u.Email == email && u.ActivatedAt != null, cancellationToken); + } + + /// + /// A never activated account is only a pending signup: nobody has shown the address is theirs, so it + /// must not keep the real owner (or anyone else) from signing up with that address. This deletes the + /// pending account holding , if there is one and it may be released. + /// + /// Lowercased address. + /// + /// The caller proved the address is theirs (an OAuth provider verified it). Otherwise the pending account + /// is left alone while it is younger than the activation resend cooldown: that gives its creator time to + /// open the link, and keeps repeated signups from mailing the address more often than a resend could. + /// + /// A pending account that is the caller's own and must be kept. + /// + private async Task ReleaseEmailFromPendingAccountAsync(string email, bool claimantOwnsEmail, Guid? exceptUserId, CancellationToken cancellationToken) + { + var pending = await _db.Users + .Include(u => u.UserDeactivation) + .FirstOrDefaultAsync(u => u.Email == email && u.ActivatedAt == null, cancellationToken); + if (pending is null || pending.Id == exceptUserId) return; + if (pending.UserDeactivation is not null || PrivilegedRoles.Any(pending.Roles)) return; + if (!claimantOwnsEmail && pending.CreatedAt > DateTime.UtcNow - Duration.ActivationResendCooldown) return; + + _db.Users.Remove(pending); + await _db.SaveChangesAsync(); + } + + /// + public async Task DiscardPendingAccountAsync(Guid userId, CancellationToken cancellationToken = default) + { + var user = await _db.Users + .Include(u => u.UserDeactivation) + .FirstOrDefaultAsync(u => u.Id == userId, cancellationToken); + if (user is null || user.ActivatedAt is not null || user.UserDeactivation is not null || PrivilegedRoles.Any(user.Roles)) return false; + + _db.Users.Remove(user); + await _db.SaveChangesAsync(); + + return true; + } + + /// + public async Task> RestartPendingSignupAsync(Guid userId, string email, string username, CancellationToken cancellationToken = default) + { + email = email.ToLowerInvariant(); + + var user = await _db.Users + .Include(u => u.UserDeactivation) + .FirstOrDefaultAsync(u => u.Id == userId, cancellationToken); + if (user is null || user.ActivatedAt is not null || user.UserDeactivation is not null) return new NotFound(); + + var emailChanged = user.Email != email; + if (emailChanged || user.Name != username) + { + if (await IsUserNameBlacklisted(username, cancellationToken) || await IsEmailProviderBlacklisted(email, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); + + await ReleaseEmailFromPendingAccountAsync(email, claimantOwnsEmail: false, exceptUserId: userId, cancellationToken); + + if (await _db.Users.AnyAsync(u => u.Id != userId && (u.Email == email || u.Name == username), cancellationToken)) + return new AccountWithEmailOrUsernameExists(); + + user.Email = email; + user.Name = username; + + try + { + await _db.SaveChangesAsync(); + } + catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: "23505" }) + { + return new AccountWithEmailOrUsernameExists(); + } + } + + // A corrected address has not been mailed yet, so the cooldown (which protects an inbox from repeats) + // does not apply to it; the daily cap per account still does. A throttled result just means no new + // mail went out, and the resend button gets it later. + await ResendActivationEmailCoreAsync(userId, ignoreCooldown: emailChanged, cancellationToken); + + return user; } public async Task CreateOAuthOnlyAccountAsync( @@ -190,6 +274,9 @@ public async Task CreateOAuthOnlyAccountAsync( if (await IsUserNameBlacklisted(username, cancellationToken) || await IsEmailProviderBlacklisted(email, cancellationToken)) return new AccountWithEmailOrUsernameExists(); + // A provider-verified address belongs to this caller, so a pending account someone parked on it goes. + await ReleaseEmailFromPendingAccountAsync(email, claimantOwnsEmail: isEmailTrusted, exceptUserId: null, cancellationToken); + // Fast uniqueness check (optimistic; race handled by unique constraints below) var exists = await _db.Users.AnyAsync(u => u.Email == email || u.Name == username, cancellationToken); if (exists) return new AccountWithEmailOrUsernameExists(); @@ -258,13 +345,55 @@ public async Task CreateOAuthOnlyAccountAsync( } - public async Task TryActivateAccountAsync(string secret, CancellationToken cancellationToken = default) + /// + public async Task> ActivateAccountAsync(string activationToken, Guid? signupBrowserUserId, string? password, CancellationToken cancellationToken = default) + { + var hash = HashingUtils.HashToken(activationToken); + + var user = await _db.Users + .Include(u => u.UserActivationRequest) + .FirstOrDefaultAsync(x => x.ActivatedAt == null && x.UserDeactivation == null && x.UserActivationRequest != null && x.UserActivationRequest.TokenHash == hash, cancellationToken); + if (user?.UserActivationRequest is null) return new NotFound(); + + // The token proves the caller reads this inbox, nothing more: the account, and the password or OAuth + // identity on it, may have been set up by someone else using this address. So the caller must also + // be the one who signed up: the browser that did, or someone who knows the password. + var hasPassword = !string.IsNullOrEmpty(user.PasswordHash); + var credentialProven = signupBrowserUserId == user.Id; + var passwordInvalid = false; + if (!credentialProven && hasPassword && !string.IsNullOrEmpty(password)) + { + credentialProven = HashingUtils.VerifyPassword(password, user.PasswordHash!).Verified; + passwordInvalid = !credentialProven; + } + + if (!credentialProven) + { + var providers = await _db.UserOAuthConnections + .Where(c => c.UserId == user.Id) + .Select(c => c.ProviderKey) + .ToListAsync(cancellationToken); + + return new ActivationCredentialRequired(hasPassword, providers, passwordInvalid); + } + + user.ActivatedAt = DateTime.UtcNow; + + _db.UserActivationRequests.Remove(user.UserActivationRequest); + + await _db.SaveChangesAsync(); + + return new Success(); + } + + /// + public async Task TryActivateAccountAsync(Guid userId, string activationToken, CancellationToken cancellationToken = default) { - var hash = HashingUtils.HashToken(secret); + var hash = HashingUtils.HashToken(activationToken); var user = await _db.Users .Include(u => u.UserActivationRequest) - .FirstOrDefaultAsync(x => x.UserDeactivation == null && x.UserActivationRequest != null && x.UserActivationRequest.TokenHash == hash, cancellationToken); + .FirstOrDefaultAsync(x => x.Id == userId && x.ActivatedAt == null && x.UserDeactivation == null && x.UserActivationRequest != null && x.UserActivationRequest.TokenHash == hash, cancellationToken); if (user?.UserActivationRequest is null) return false; user.ActivatedAt = DateTime.UtcNow; @@ -291,7 +420,10 @@ public async Task - public async Task> ResendActivationEmailAsync(Guid userId, CancellationToken cancellationToken = default) + public Task> ResendActivationEmailAsync(Guid userId, CancellationToken cancellationToken = default) + => ResendActivationEmailCoreAsync(userId, ignoreCooldown: false, cancellationToken); + + private async Task> ResendActivationEmailCoreAsync(Guid userId, bool ignoreCooldown, CancellationToken cancellationToken) { // Without mail no link can be delivered (and such accounts are activated on creation anyway). if (!_mailOptions.IsEnabled) return new NotFound(); @@ -317,7 +449,7 @@ public async Task m.CreatedAt) .ToListAsync(cancellationToken); - if (recent.Count >= 5 || recent.Any(createdAt => createdAt >= DateTime.UtcNow - Duration.ActivationResendCooldown)) + if (recent.Count >= 5 || (!ignoreCooldown && recent.Any(createdAt => createdAt >= DateTime.UtcNow - Duration.ActivationResendCooldown))) return new TooManyActivationResends(); user.UserActivationRequest ??= new UserActivationRequest @@ -588,6 +720,7 @@ public async Task> { Reset = x, IsDeactivated = x.User.UserDeactivation != null, + WasActivated = x.User.ActivatedAt != null, UserSecurityStamp = x.User.SecurityStamp }) .FirstOrDefaultAsync(x => x.Reset.Id == passwordResetId && x.Reset.UsedAt == null && x.Reset.CreatedAt >= validSince @@ -625,6 +758,24 @@ await _db.UserPasswordResets .Where(r => r.Id == reset.Reset.Id && r.UsedAt == null) .ExecuteUpdateAsync(s => s.SetProperty(r => r.UsedAt, now)); + // This reset is what activates a not yet activated account. Such an account may have been created + // by someone else on this address through an OAuth signup, and its linked identity is then theirs: + // left in place it would let them sign in to the account the inbox owner just took over. Nobody + // has proven that link and this inbox belong together, so it goes. (An unactivated account cannot + // sign in, so it has no sessions or API tokens to worry about.) + // On an activated account the links are kept, like API tokens: activating required proving both + // the inbox and the credential, so every link on it was added by its owner. + List removedProviders = []; + if (!reset.WasActivated) + { + var connections = _db.UserOAuthConnections.Where(c => c.UserId == reset.Reset.UserId); + removedProviders = await connections.Select(c => c.ProviderKey).ToListAsync(); + if (removedProviders.Count > 0) + { + await connections.ExecuteDeleteAsync(); + } + } + // Unauthenticated email-token flow proving control of the account, so the actor is the account itself. await _auditService.LogAsync( reset.Reset.UserId, @@ -632,8 +783,22 @@ await _auditService.LogAsync( actorId: reset.Reset.UserId ); + foreach (var provider in removedProviders) + { + await _auditService.LogAsync( + reset.Reset.UserId, + action: AuditAction.OAuthDisconnected, + actorId: reset.Reset.UserId, + metadata: new OAuthDisconnectedMetadata(provider), + reason: "Password reset" + ); + } + await transaction.CommitAsync(); + // Whoever was signed in with the old password is signed out. + await _sessionService.DeleteSessionsByUserIdAsync(reset.Reset.UserId); + return new Success(); } @@ -865,13 +1030,15 @@ await _auditService.LogAsync( return new Success(); } - public async Task> TryVerifyEmailAsync(string token, CancellationToken cancellationToken = default) + public async Task> TryVerifyEmailAsync(string token, Guid userId, CancellationToken cancellationToken = default) { var hash = HashingUtils.HashToken(token); var validSince = DateTime.UtcNow - Duration.EmailChangeRequestLifetime; + // Scoped to the signed-in user: the link goes to an address that is not the account's yet, so + // whoever opens it may be a stranger being asked to vouch for someone else's account. var change = await _db.UserEmailChanges - .Where(x => x.TokenHash == hash && x.UsedAt == null && x.CreatedAt >= validSince + .Where(x => x.UserId == userId && x.TokenHash == hash && x.UsedAt == null && x.CreatedAt >= validSince && x.SecurityStampAtCreate == x.User.SecurityStamp && x.User.UserDeactivation == null && x.User.ActivatedAt != null) .Select(x => new diff --git a/API/Services/Account/IAccountService.cs b/API/Services/Account/IAccountService.cs index 3e19c8539..bcbf8affd 100644 --- a/API/Services/Account/IAccountService.cs +++ b/API/Services/Account/IAccountService.cs @@ -35,17 +35,49 @@ public interface IAccountService Task CreateOAuthOnlyAccountAsync(string email, string username, string provider, string providerAccountId, string? providerAccountName, bool isEmailTrusted, CancellationToken cancellationToken = default); /// - /// Returns true if the given email is already associated with an existing user account. + /// Returns true if the given email belongs to an activated account. A never activated account is only + /// a pending signup and does not reserve its address. /// Task IsEmailRegisteredAsync(string email, CancellationToken cancellationToken = default); /// - /// + /// Deletes a never activated account. Only call this for a caller who proved they hold its credential + /// (signed in with its linked OAuth identity) and is replacing it. /// - /// + /// False when there is no such pending account. + Task DiscardPendingAccountAsync(Guid userId, CancellationToken cancellationToken = default); + + /// + /// Lets the creator of a never activated account correct what they signed up with (typically a mistyped + /// email) and sends the activation email to the new address. Only call this for a caller who proved they + /// hold the account's credential. Sends are capped per account like any activation resend. + /// + Task> RestartPendingSignupAsync(Guid userId, string email, string username, CancellationToken cancellationToken = default); + + /// + /// Activates the account an emailed activation token belongs to. The token only proves control of the + /// inbox, and anyone can sign up with somebody else's address, so the caller must also show they are + /// the one who signed up: the signup browser's resend cookie () + /// or the account's password. An account created through OAuth is activated by signing in with the + /// linked provider instead, see . + /// + /// Token from the activation email. + /// User id from the activation resend cookie, if the request carries a valid one. + /// Password supplied alongside the token, if any. /// - /// - Task TryActivateAccountAsync(string token, CancellationToken cancellationToken = default); + /// + /// when the token is valid but that proof is missing or wrong; + /// the account stays unactivated and the token stays usable. + /// + Task> ActivateAccountAsync(string activationToken, Guid? signupBrowserUserId, string? password, CancellationToken cancellationToken = default); + + /// + /// Activates if is the token mailed to that + /// account. Only call this once the caller has proven they hold a credential of that account (a sign-in + /// with its linked OAuth identity). + /// + /// False when the token does not belong to this account or there is nothing to activate. + Task TryActivateAccountAsync(Guid userId, string activationToken, CancellationToken cancellationToken = default); /// /// Looks up the account by username or email and re-enqueues its activation email, see the overload below. @@ -100,7 +132,9 @@ public interface IAccountService /// /// Completes a password reset process, sets a new password. Since the reset link proves control of the - /// account's email, this also activates an unactivated account. + /// account's email, this also activates an unactivated account. All sessions are signed out; OAuth links + /// and API tokens are kept, except that an account activated by this reset loses the OAuth identity it + /// was signed up with (it may be someone else's). /// /// /// @@ -174,15 +208,24 @@ public interface IAccountService /// request creation and verification (race condition). /// /// + /// + /// The signed-in user confirming the change. The token is mailed to an address the account does not + /// control yet, so it only counts when presented from a session of the account that requested it. + /// /// /// - Task> TryVerifyEmailAsync(string token, CancellationToken cancellationToken = default); + Task> TryVerifyEmailAsync(string token, Guid userId, CancellationToken cancellationToken = default); } public union AccountCreationResult(User, AccountWithEmailOrUsernameExists); public sealed record VerifyEmailSuccess(Guid UserId, string OldEmail, string NewEmail); +/// Whether the account can be activated by supplying its password. +/// Providers linked to the account; signing in with one activates it. +/// A password was supplied but did not match. +public sealed record ActivationCredentialRequired(bool HasPassword, IReadOnlyList OAuthProviders, bool PasswordInvalid); + public sealed class AccountIsOAuthOnly; public sealed class AccountNotActivated; public sealed class AccountDeactivated; diff --git a/Common/Authentication/ActivationResendCookie.cs b/Common/Authentication/ActivationResendCookie.cs index 564921e74..2e2bc78c8 100644 --- a/Common/Authentication/ActivationResendCookie.cs +++ b/Common/Authentication/ActivationResendCookie.cs @@ -16,9 +16,13 @@ namespace OpenShock.Common.Authentication; /// so it is valid across API instances). It is removed on any successful session authentication, and by the /// resend endpoint once there is nothing left to resend. /// +/// It also marks this browser as the one that signed up: it is only ever issued in the response that creates +/// the account, and the activation endpoint accepts it in place of re-entering the password. +/// +/// /// Deliberately not HttpOnly: the frontend reads its presence to decide whether to offer the resend /// button. HttpOnly would buy little anyway - script on the page could call the endpoint with the cookie attached -/// regardless - and a leaked token can only resend (rate limited) activation emails to that account's own inbox. +/// regardless - and a leaked token is useless without the activation link mailed to that account's own inbox. /// /// public static class ActivationResendCookie diff --git a/Common/Constants/Constants.cs b/Common/Constants/Constants.cs index d4ff32036..372015cac 100644 --- a/Common/Constants/Constants.cs +++ b/Common/Constants/Constants.cs @@ -11,6 +11,7 @@ public static class Duration public static readonly TimeSpan ActivationResendCooldown = TimeSpan.FromMinutes(10); public static readonly TimeSpan ActivationResendWindow = TimeSpan.FromHours(24); + public static readonly TimeSpan UnactivatedAccountRetentionTime = TimeSpan.FromDays(7); public static readonly TimeSpan NameChangeCooldown = TimeSpan.FromDays(7); diff --git a/Common/Errors/AccountError.cs b/Common/Errors/AccountError.cs index 96b611f88..ac8bb2c09 100644 --- a/Common/Errors/AccountError.cs +++ b/Common/Errors/AccountError.cs @@ -29,12 +29,23 @@ public static class AccountError public static OpenShockProblem AccountActivationResendUnavailable => new OpenShockProblem("Account.Activation.ResendUnavailable", "No activation email can be resent from this browser", HttpStatusCode.BadRequest); public static OpenShockProblem AccountActivationResendTooMany => new OpenShockProblem("Account.Activation.ResendTooMany", "Too many activation emails have been requested. Please try again later", HttpStatusCode.TooManyRequests); public static OpenShockProblem AccountActivationNotFound => new OpenShockProblem("Account.Activation.NotFound", "There is no account activation request matching the supplied token", HttpStatusCode.BadRequest); + public static OpenShockProblem AccountActivationCredentialRequired(bool hasPassword, IReadOnlyList oauthProviders, bool passwordInvalid) => new OpenShockProblem( + "Account.Activation.CredentialRequired", + "Activating this account from this browser also requires its password or a sign-in with its linked provider", HttpStatusCode.Forbidden) + { + Extensions = new Dictionary + { + { "hasPassword", hasPassword }, + { "oauthProviders", oauthProviders }, + { "passwordInvalid", passwordInvalid } + } + }; public static OpenShockProblem AccountDeactivated => new OpenShockProblem("Account.Deactivated", "Your account has been deactivated", HttpStatusCode.Unauthorized); public static OpenShockProblem AccountOAuthOnly => new OpenShockProblem("Account.OAuthOnly", "This account is only accessible via OAuth", HttpStatusCode.Unauthorized); public static OpenShockProblem PasswordNotSet => new OpenShockProblem("Account.Password.NotSet", - "This account has no password set. Initiate a password set flow via POST /password/set instead.", HttpStatusCode.Conflict); + "This account has no password set. Set one through the password reset flow (POST /2/account/password-reset) instead.", HttpStatusCode.Conflict); public static OpenShockProblem EmailChangeAlreadyInUse => new OpenShockProblem("Account.Email.AlreadyInUse", "This email address is already in use", HttpStatusCode.Conflict); diff --git a/Common/Hubs/RevalidateAuthenticationHubFilter.cs b/Common/Hubs/RevalidateAuthenticationHubFilter.cs new file mode 100644 index 000000000..2c3615f20 --- /dev/null +++ b/Common/Hubs/RevalidateAuthenticationHubFilter.cs @@ -0,0 +1,90 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.SignalR; +using Microsoft.EntityFrameworkCore; +using OpenShock.Common.Authentication; +using OpenShock.Common.Extensions; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Services.Session; + +namespace OpenShock.Common.Hubs; + +/// +/// Re-checks, before every hub method call, that the session or API token a connection authenticated with is +/// still valid, and aborts the connection when it is not. +/// +/// +/// SignalR authenticates a connection once, when it opens, and then keeps it for as long as the client likes. +/// Without this, logging a session out or revoking, expiring or deactivating an API token would only stop new +/// connections: an open one could keep calling, and whatever calls it already had queued would still run. +/// Aborting also discards those queued calls. +/// +/// For an API token the row read here is handed to the hub method through +/// , so permissions, pause state and control limits +/// are the current ones rather than the ones from connect time. +/// +/// +public sealed class RevalidateAuthenticationHubFilter : IHubFilter +{ + /// + public async ValueTask InvokeMethodAsync(HubInvocationContext invocationContext, Func> next) + { + if (!await IsStillAuthenticated(invocationContext)) + { + invocationContext.Context.Abort(); + throw new HubException("Authentication is no longer valid"); + } + + return await next(invocationContext); + } + + private static async Task IsStillAuthenticated(HubInvocationContext invocationContext) + { + var context = invocationContext.Context; + var user = context.User; + + // Anonymous connection (a public share guest): nothing was granted that could have been revoked. + if (user is null) return true; + + if (user.HasOpenShockApiTokenIdentity()) + { + if (!user.TryGetClaimValueAsGuid(OpenShockAuthClaims.ApiTokenId, out var tokenId)) return false; + + var db = invocationContext.ServiceProvider.GetRequiredService(); + var token = await db.ApiTokens + .AsNoTracking() + .FirstOrDefaultAsync(x => + x.Id == tokenId && + (x.ValidUntil == null || x.ValidUntil >= DateTime.UtcNow) && + x.User.UserDeactivation == null, context.ConnectionAborted); + if (token is null) return false; + + context.Items[HubCallerContextExtensions.CurrentApiTokenKey] = token; + return true; + } + + if (user.TryGetOpenShockUserIdentity() is { } identity) + { + if (context.GetHttpContext() is not { } httpContext || !httpContext.TryGetUserSessionToken(out var sessionToken)) return false; + + // Sessions are deleted on logout, on deactivation and on a password reset, so existence is the check. + var sessionService = invocationContext.ServiceProvider.GetRequiredService(); + var session = await sessionService.GetSessionByTokenAsync(sessionToken); + + return session is not null && session.UserId == identity.GetClaimValueAsGuid(ClaimTypes.NameIdentifier); + } + + return true; + } +} + +public static class HubCallerContextExtensions +{ + internal static readonly object CurrentApiTokenKey = new(); + + /// + /// The API token this connection authenticated with, as it is in the database at the time of the current + /// call. Null for a session or anonymous connection, and outside of a hub method call. + /// + public static ApiToken? GetCurrentApiToken(this HubCallerContext context) + => context.Items.TryGetValue(CurrentApiTokenKey, out var token) ? token as ApiToken : null; +} diff --git a/Common/Hubs/UserHub.cs b/Common/Hubs/UserHub.cs index c3d3eea35..b996fbb9e 100644 --- a/Common/Hubs/UserHub.cs +++ b/Common/Hubs/UserHub.cs @@ -28,9 +28,11 @@ public sealed class UserHub : Hub /// connection. Derived per access: SignalR creates a hub instance per invocation, so a field /// set in would be null everywhere else. /// - private IReadOnlyList? TokenPermissions => Context.User?.HasOpenShockApiTokenIdentity() == true - ? Context.User.GetApiTokenPermissions() - : null; + private IReadOnlyList? TokenPermissions => Context.GetCurrentApiToken() is { } apiToken + ? apiToken.Permissions + : Context.User?.HasOpenShockApiTokenIdentity() == true + ? Context.User.GetApiTokenPermissions() + : null; public UserHub(ILogger logger, OpenShockContext db, IRedisConnectionProvider provider, IRedisPubService redisPubService, IControlSender controlSender) @@ -96,7 +98,8 @@ public async Task ControlV2(IReadOnlyList shocks, string? customName) }).FirstAsync(Context.ConnectionAborted); ApiTokenControlLimits? tokenLimits = null; - if (Context.GetHttpContext()?.GetItemByType() is { } apiToken) + // The token as it is now, not as it was when the connection opened (see RevalidateAuthenticationHubFilter). + if (Context.GetCurrentApiToken() is { } apiToken) { // A paused token may not control shockers. if (apiToken.ShockerControlPaused) return; diff --git a/Common/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index f330cfac1..36926ae21 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -421,8 +421,10 @@ await context.HttpContext.Response.WriteAsync("Too Many Requests. Please try aga PermitLimit = 120, Window = TimeSpan.FromMinutes(1), SegmentsPerWindow = 6, - QueueProcessingOrder = QueueProcessingOrder.OldestFirst, - QueueLimit = 10 + // No queue: this limiter runs after authentication, so a queued request would + // still execute, seconds later, with a session or API token that may have been + // revoked while it waited. Over the limit means 429, now. + QueueLimit = 0 }); }); @@ -476,7 +478,7 @@ await context.HttpContext.Response.WriteAsync("Too Many Requests. Please try aga public static IServiceCollection AddOpenShockSignalR(this IServiceCollection services, ConfigurationOptions redisConfig) { - services.AddSignalR() + services.AddSignalR(options => Microsoft.AspNetCore.SignalR.HubOptionsExtensions.AddFilter(options)) .AddOpenShockStackExchangeRedis(options => { options.Configuration = redisConfig; }) .AddJsonProtocol(options => { diff --git a/Cron.IntegrationTests/Tests/DeleteUnactivatedAccountsTests.cs b/Cron.IntegrationTests/Tests/DeleteUnactivatedAccountsTests.cs new file mode 100644 index 000000000..42ca1e0c0 --- /dev/null +++ b/Cron.IntegrationTests/Tests/DeleteUnactivatedAccountsTests.cs @@ -0,0 +1,91 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenShock.Common.Constants; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Utils; +using OpenShock.Cron.Jobs; + +namespace OpenShock.Cron.IntegrationTests.Tests; + +/// +/// Runs the unactivated-account cleanup against real Postgres, so the raw delete's role_type[] +/// parameter and the deactivation sub-select are exercised. +/// +public sealed class DeleteUnactivatedAccountsTests +{ + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required CronApplicationFactory Factory { get; init; } + + [Test] + public async Task Execute_DeletesOnlyStaleUnactivatedAccounts() + { + var stale = DateTime.UtcNow - Duration.UnactivatedAccountRetentionTime - TimeSpan.FromHours(1); + var recent = DateTime.UtcNow - TimeSpan.FromHours(1); + + var staleUnactivated = Guid.CreateVersion7(); + var recentUnactivated = Guid.CreateVersion7(); + var staleActivated = Guid.CreateVersion7(); + var staleUnactivatedStaff = Guid.CreateVersion7(); + var staleUnactivatedDeactivated = Guid.CreateVersion7(); + + await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + { + var pending = NewUser(staleUnactivated, stale, activated: false, []); + pending.UserActivationRequest = new UserActivationRequest + { + UserId = staleUnactivated, + TokenHash = HashingUtils.HashToken(Guid.NewGuid().ToString("N")) + }; + db.Users.Add(pending); + db.Users.Add(NewUser(recentUnactivated, recent, activated: false, [])); + db.Users.Add(NewUser(staleActivated, stale, activated: true, [])); + db.Users.Add(NewUser(staleUnactivatedStaff, stale, activated: false, [RoleType.Staff])); + + var deactivated = NewUser(staleUnactivatedDeactivated, stale, activated: false, []); + deactivated.UserDeactivation = new UserDeactivation + { + DeactivatedUserId = staleUnactivatedDeactivated, + DeactivatedByUserId = staleUnactivatedDeactivated, + DeleteLater = false + }; + db.Users.Add(deactivated); + + await db.SaveChangesAsync(); + } + + await using var scope = Factory.Services.CreateAsyncScope(); + var job = ActivatorUtilities.CreateInstance(scope.ServiceProvider); + + await job.Execute(); + + await using var verify = await Factory.DbContextFactory.CreateDbContextAsync(); + var remaining = await verify.Users + .Where(u => new[] { staleUnactivated, recentUnactivated, staleActivated, staleUnactivatedStaff, staleUnactivatedDeactivated }.Contains(u.Id)) + .Select(u => u.Id) + .ToListAsync(); + + await Assert.That(remaining).DoesNotContain(staleUnactivated); + await Assert.That(remaining).Contains(recentUnactivated); + await Assert.That(remaining).Contains(staleActivated); + await Assert.That(remaining).Contains(staleUnactivatedStaff); + await Assert.That(remaining).Contains(staleUnactivatedDeactivated); + + // The activation link dies with the account. + await Assert.That(await verify.UserActivationRequests.AnyAsync(r => r.UserId == staleUnactivated)).IsFalse(); + } + + private static User NewUser(Guid id, DateTime createdAt, bool activated, List roles) + { + var suffix = Guid.NewGuid().ToString("N")[..12]; + return new User + { + Id = id, + Name = $"unact{suffix}", + Email = $"unact-{suffix}@test.org", + SecurityStamp = Guid.CreateVersion7(), + Roles = roles, + CreatedAt = createdAt, + ActivatedAt = activated ? createdAt : null + }; + } +} diff --git a/Cron/Jobs/DeleteUnactivatedAccountsJob.cs b/Cron/Jobs/DeleteUnactivatedAccountsJob.cs new file mode 100644 index 000000000..109bcd1f5 --- /dev/null +++ b/Cron/Jobs/DeleteUnactivatedAccountsJob.cs @@ -0,0 +1,57 @@ +using Microsoft.EntityFrameworkCore; +using OpenShock.Common.Constants; +using OpenShock.Common.OpenShockDb; +using OpenShock.Cron.Attributes; + +namespace OpenShock.Cron.Jobs; + +/// +/// Hard-deletes accounts that were never activated within +/// of being created. Anyone can sign up with somebody else's address, and such an account would otherwise hold +/// that email and username forever and keep its activation link alive indefinitely. Deleting the account takes +/// its activation request with it, so this is also what expires the link. +/// +/// +/// An unactivated account has never had a session, so it owns nothing worth keeping. Deactivated accounts are +/// left to (a moderation record), and privileged accounts are never touched. +/// +[CronJob("30 * * * *")] // Every hour +public sealed class DeleteUnactivatedAccountsJob +{ + private readonly OpenShockContext _db; + private readonly IHostApplicationLifetime _lifetime; + private readonly ILogger _logger; + + /// + /// DI constructor + /// + /// + /// Its stopping token cancels the job when the server shuts down. + /// + public DeleteUnactivatedAccountsJob(OpenShockContext db, IHostApplicationLifetime lifetime, ILogger logger) + { + _db = db; + _lifetime = lifetime; + _logger = logger; + } + + public async Task Execute() + { + var cancellationToken = _lifetime.ApplicationStopping; + var createdBefore = DateTime.UtcNow - Duration.UnactivatedAccountRetentionTime; + + // One statement, so an account activated between a read and the delete can't be caught: + // Postgres rechecks a row that changed under the delete. + var nDeleted = await _db.Database.ExecuteSqlAsync($""" + DELETE FROM users AS u + WHERE u.activated_at IS NULL + AND u.created_at < {createdBefore} + AND NOT (u.roles && {PrivilegedRoles.All}) + AND NOT EXISTS (SELECT 1 FROM user_deactivations AS d WHERE d.deactivated_user_id = u.id) + """, cancellationToken); + + _logger.LogInformation("Deleted {DeletedCount} accounts that were never activated since {CreatedBefore}", nDeleted, createdBefore); + + return nDeleted; + } +} From 68e359d812aee4ab8fece22906cd6096e4ddcb1b Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Thu, 26 Nov 2026 20:23:12 +0100 Subject: [PATCH 02/14] test: cover hub auth revalidation and fix colliding test usernames The unique suffix for test usernames and emails was the timestamp half of a v7 GUID, which only changes about every 65 seconds, so two users with the same prefix collided on IX_users_name. Use a random suffix instead. Add UserHub tests over a real WebSocket connection: calls keep working with a valid session or API token, and the connection is closed once the session is deleted or the token is deleted, expired or its owner deactivated. --- API.IntegrationTests/Helpers/TestHelper.cs | 4 +- .../Tests/SignalRUserHubTests.cs | 158 ++++++++++++++++++ .../Tests/EmailOutboxDeliveryTests.cs | 2 +- 3 files changed, 161 insertions(+), 3 deletions(-) diff --git a/API.IntegrationTests/Helpers/TestHelper.cs b/API.IntegrationTests/Helpers/TestHelper.cs index d1d75e85a..4becab7a1 100644 --- a/API.IntegrationTests/Helpers/TestHelper.cs +++ b/API.IntegrationTests/Helpers/TestHelper.cs @@ -179,7 +179,7 @@ public static StringContent JsonContent(object obj) /// public static string UniqueEmail(string prefix) { - var suffix = Guid.CreateVersion7().ToString("N")[..8]; + var suffix = Guid.NewGuid().ToString("N")[..8]; return $"{prefix}-{suffix}@test.org"; } @@ -189,7 +189,7 @@ public static string UniqueEmail(string prefix) /// public static string UniqueUsername(string prefix) { - var suffix = Guid.CreateVersion7().ToString("N")[..8]; + var suffix = Guid.NewGuid().ToString("N")[..8]; return ($"{prefix}{suffix}").ToLowerInvariant(); } } diff --git a/API.IntegrationTests/Tests/SignalRUserHubTests.cs b/API.IntegrationTests/Tests/SignalRUserHubTests.cs index f1ecc415b..ba38e3d1e 100644 --- a/API.IntegrationTests/Tests/SignalRUserHubTests.cs +++ b/API.IntegrationTests/Tests/SignalRUserHubTests.cs @@ -1,8 +1,14 @@ using System.Net; using System.Text.Json; +using Microsoft.AspNetCore.Http.Connections; using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.SignalR.Client; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; using OpenShock.API.IntegrationTests.Helpers; using OpenShock.Common.Constants; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Services.Session; namespace OpenShock.API.IntegrationTests.Tests; @@ -99,4 +105,156 @@ public async Task PublicShareHub_Negotiate_WithoutAuth_ReturnsOk() // Should return OK (negotiate doesn't check auth or share existence) await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); } + + // --- An open connection stops working once its session or API token is no longer valid --- + + [Test] + public async Task Invoke_WithValidSession_KeepsWorking() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevalok"), TestHelper.UniqueEmail("hubrevalok"), "SecurePassword123#"); + await using var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); + + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + } + + [Test] + public async Task Invoke_AfterSessionDeleted_FailsAndClosesConnection() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevalsess"), TestHelper.UniqueEmail("hubrevalsess"), "SecurePassword123#"); + await using var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + await scope.ServiceProvider.GetRequiredService().DeleteSessionsByUserIdAsync(user.Id); + } + + await AssertInvokeFailsAndConnectionClosesAsync(connection); + } + + [Test] + public async Task Invoke_WithValidApiToken_KeepsWorking() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaltokok"), TestHelper.UniqueEmail("hubrevaltokok"), "SecurePassword123#"); + var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-ok"); + await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); + + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + } + + [Test] + public async Task Invoke_AfterApiTokenDeleted_FailsAndClosesConnection() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaltokdel"), TestHelper.UniqueEmail("hubrevaltokdel"), "SecurePassword123#"); + var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-deleted"); + await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + await db.ApiTokens.Where(t => t.Id == tokenId).ExecuteDeleteAsync(); + } + + await AssertInvokeFailsAndConnectionClosesAsync(connection); + } + + [Test] + public async Task Invoke_AfterApiTokenExpired_FailsAndClosesConnection() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaltokexp"), TestHelper.UniqueEmail("hubrevaltokexp"), "SecurePassword123#"); + var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-expired"); + await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var expired = DateTime.UtcNow.AddMinutes(-1); + await db.ApiTokens.Where(t => t.Id == tokenId).ExecuteUpdateAsync(s => s.SetProperty(t => t.ValidUntil, expired)); + } + + await AssertInvokeFailsAndConnectionClosesAsync(connection); + } + + [Test] + public async Task Invoke_AfterApiTokenOwnerDeactivated_FailsAndClosesConnection() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaltokdeact"), TestHelper.UniqueEmail("hubrevaltokdeact"), "SecurePassword123#"); + var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-deactivated"); + await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.UserDeactivations.Add(new UserDeactivation + { + DeactivatedUserId = user.Id, + DeactivatedByUserId = user.Id, + DeleteLater = false + }); + await db.SaveChangesAsync(); + } + + await AssertInvokeFailsAndConnectionClosesAsync(connection); + } + + /// + /// Opens a real hub connection against the in-process test server. The hub only allows WebSockets, which + /// the test server offers through its own client rather than through an HttpMessageHandler. + /// + private async Task ConnectAsync(string headerName, string headerValue) + { + var server = WebApplicationFactory.Server; + + var connection = new HubConnectionBuilder() + .WithUrl(new Uri(server.BaseAddress, "/1/hubs/user"), options => + { + options.Transports = HttpTransportType.WebSockets; + options.SkipNegotiation = true; + options.WebSocketFactory = async (context, cancellationToken) => + { + var client = server.CreateWebSocketClient(); + client.ConfigureRequest = request => request.Headers[headerName] = headerValue; + return await client.ConnectAsync(context.Uri, cancellationToken); + }; + }) + .Build(); + + await connection.StartAsync(); + return connection; + } + + private static async Task AssertInvokeFailsAndConnectionClosesAsync(HubConnection connection) + { + var closed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + connection.Closed += _ => + { + closed.TrySetResult(); + return Task.CompletedTask; + }; + + // The server answers with an error and aborts; which of the two the client sees first is a race. + Exception? failure = null; + try + { + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + } + catch (Exception ex) + { + failure = ex; + } + + await Assert.That(failure).IsNotNull(); + + await closed.Task.WaitAsync(TimeSpan.FromSeconds(30)); + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Disconnected); + } } diff --git a/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs b/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs index da1e9352b..f9bb4dee5 100644 --- a/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs +++ b/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs @@ -159,7 +159,7 @@ private async Task AddPendingResetOutboxAsync(Guid userId, Guid stamp, str return outbox.Id; } - private static string UniqueEmail(string prefix) => $"{prefix}-{Guid.CreateVersion7().ToString("N")[..8]}@test.org"; + private static string UniqueEmail(string prefix) => $"{prefix}-{Guid.NewGuid().ToString("N")[..8]}@test.org"; private static string? ExtractResetToken(string html) { From 12b8a0650658cb0c6bd6866ce6c90fc5638a1563 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Thu, 26 Nov 2026 20:31:54 +0100 Subject: [PATCH 03/14] fix: invalidate the mailed activation link when a pending signup changes its email Correcting the address of a pending OAuth signup left the link already mailed to the old address valid, so the account could be moved to someone else's address and activated with a link from an inbox the caller controls. The token hash is now replaced in the same commit as the address, activation consumes the request with a delete conditioned on the hash, and the outbox dispatcher skips an activation mail whose recipient is no longer the account's email and only mints over the hash it read. --- API.IntegrationTests/Tests/MailTests.cs | 52 +++++++++++ API/Services/Account/AccountService.cs | 63 ++++++++++---- .../Tests/EmailOutboxDeliveryTests.cs | 87 +++++++++++++++++++ .../Email/Outbox/EmailOutboxDispatcher.cs | 16 +++- 4 files changed, 201 insertions(+), 17 deletions(-) diff --git a/API.IntegrationTests/Tests/MailTests.cs b/API.IntegrationTests/Tests/MailTests.cs index 8787b7732..e2ee961d6 100644 --- a/API.IntegrationTests/Tests/MailTests.cs +++ b/API.IntegrationTests/Tests/MailTests.cs @@ -4,6 +4,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.API.Services.Account; using OpenShock.Common.Authentication; using OpenShock.Common.Constants; using OpenShock.Common.OpenShockDb; @@ -624,6 +625,57 @@ public async Task Activate_UnknownToken_Returns400() await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); } + [Test] + public async Task RestartPendingSignup_ChangedEmail_InvalidatesTheLinkMailedToTheOldAddress() + { + // Sign up with an inbox you control, then move the pending account onto somebody else's address: + // the link from the first inbox must not activate it there. + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-restart-oldtoken", password: null); + await AddOAuthConnectionAsync(userId, "discord"); + var victimEmail = TestHelper.UniqueEmail("mail-restart-victim"); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var username = await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.Name).SingleAsync(); + + var accountService = scope.ServiceProvider.GetRequiredService(); + var restarted = await accountService.RestartPendingSignupAsync(userId, victimEmail, username); + await Assert.That(restarted.Value is User).IsTrue(); + } + + await Assert.That(await GetEmailAsync(userId)).IsEqualTo(victimEmail); + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token, cookie: MintResendCookie(userId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + [Test] + public async Task RestartPendingSignup_SameEmail_KeepsTheMailedLinkWorking() + { + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-restart-sameemail", password: null); + await AddOAuthConnectionAsync(userId, "discord"); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var current = await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => new { u.Name, u.Email }).SingleAsync(); + + var accountService = scope.ServiceProvider.GetRequiredService(); + var restarted = await accountService.RestartPendingSignupAsync(userId, current.Email, current.Name); + await Assert.That(restarted.Value is User).IsTrue(); + } + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token, cookie: MintResendCookie(userId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await IsActivatedAsync(userId)).IsTrue(); + } + // --- An email change is only confirmed from a session of the account that asked for it --- [Test] diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index d926b9a79..a2fd72461 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -211,10 +211,11 @@ public async Task> Rest var user = await _db.Users .Include(u => u.UserDeactivation) + .Include(u => u.UserActivationRequest) .FirstOrDefaultAsync(u => u.Id == userId, cancellationToken); if (user is null || user.ActivatedAt is not null || user.UserDeactivation is not null) return new NotFound(); - var emailChanged = user.Email != email; + var emailChanged = !string.Equals(user.Email, email, StringComparison.OrdinalIgnoreCase); if (emailChanged || user.Name != username) { if (await IsUserNameBlacklisted(username, cancellationToken) || await IsEmailProviderBlacklisted(email, cancellationToken)) @@ -228,10 +229,26 @@ public async Task> Rest user.Email = email; user.Name = username; + // A link already mailed was mailed to the previous address, so it says nothing about the new + // one: it must stop working in the same commit that changes the address. Otherwise the caller + // could sign up with an inbox of their own, move the account to somebody else's address and + // activate it with the link they already hold. The delivery job mints the new token when it + // sends to the new address. + if (emailChanged && user.UserActivationRequest is not null) + { + user.UserActivationRequest.TokenHash = SeedTokenHash(); + } + try { await _db.SaveChangesAsync(); } + catch (DbUpdateConcurrencyException) + { + // The old link was redeemed while this ran: the account is activated on the address it was + // mailed to, and nothing was changed here. + return new NotFound(); + } catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: "23505" }) { return new AccountWithEmailOrUsernameExists(); @@ -369,13 +386,34 @@ public async Task> Activ return new ActivationCredentialRequired(hasPassword, providers, passwordInvalid); } - user.ActivatedAt = DateTime.UtcNow; + if (!await ConsumeActivationTokenAsync(user.Id, hash, cancellationToken)) return new NotFound(); - _db.UserActivationRequests.Remove(user.UserActivationRequest); + return new Success(); + } - await _db.SaveChangesAsync(); + /// + /// Activates the account by consuming its activation request, but only if the request still carries + /// . The check and the delete are one statement, so a token that was + /// replaced since the caller looked it up (the signup's address was changed, see + /// ) cannot activate the account on its new address. + /// + private async Task ConsumeActivationTokenAsync(Guid userId, string tokenHash, CancellationToken cancellationToken) + { + await using var transaction = await _db.Database.BeginTransactionAsync(cancellationToken); - return new Success(); + var consumed = await _db.UserActivationRequests + .Where(r => r.UserId == userId && r.TokenHash == tokenHash) + .ExecuteDeleteAsync(cancellationToken); + if (consumed == 0) return false; + + var now = DateTime.UtcNow; + await _db.Users + .Where(u => u.Id == userId && u.ActivatedAt == null) + .ExecuteUpdateAsync(s => s.SetProperty(u => u.ActivatedAt, now), cancellationToken); + + await transaction.CommitAsync(cancellationToken); + + return true; } /// @@ -383,18 +421,11 @@ public async Task TryActivateAccountAsync(Guid userId, string activationTo { var hash = HashingUtils.HashToken(activationToken); - var user = await _db.Users - .Include(u => u.UserActivationRequest) - .FirstOrDefaultAsync(x => x.Id == userId && x.ActivatedAt == null && x.UserDeactivation == null && x.UserActivationRequest != null && x.UserActivationRequest.TokenHash == hash, cancellationToken); - if (user?.UserActivationRequest is null) return false; - - user.ActivatedAt = DateTime.UtcNow; - - _db.UserActivationRequests.Remove(user.UserActivationRequest); + var matches = await _db.Users + .AnyAsync(x => x.Id == userId && x.ActivatedAt == null && x.UserDeactivation == null && x.UserActivationRequest != null && x.UserActivationRequest.TokenHash == hash, cancellationToken); + if (!matches) return false; - await _db.SaveChangesAsync(); - - return true; + return await ConsumeActivationTokenAsync(userId, hash, cancellationToken); } /// diff --git a/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs b/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs index f9bb4dee5..8e08fce6a 100644 --- a/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs +++ b/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs @@ -105,6 +105,93 @@ public async Task PasswordReset_NewerRequest_SupersedesOlder_OnlyNewestDelivered } } + [Test] + public async Task AccountActivation_QueuedForAPreviousAddress_IsSkipped_AndMintsNoToken() + { + // The pending signup's address was corrected after this message was queued: the link would activate + // the account on its new address, so it must not go to the old one. + var oldEmail = UniqueEmail("cron-activation-old"); + var newEmail = UniqueEmail("cron-activation-new"); + using var mailpit = Factory.CreateMailpitHelper(); + + var userId = Guid.CreateVersion7(); + var seededHash = HashingUtils.HashToken(CryptoUtils.RandomString(AuthConstants.GeneratedTokenLength)); + Guid outboxId; + await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + { + db.Users.Add(new User + { + Id = userId, + Name = "Activation User " + Guid.NewGuid().ToString("N")[..8], + Email = newEmail, + PasswordHash = null, + CreatedAt = DateTime.UtcNow, + ActivatedAt = null + }); + db.UserActivationRequests.Add(new UserActivationRequest { UserId = userId, TokenHash = seededHash }); + var outbox = EmailOutboxMessage.ForAccountActivation(userId, oldEmail, "Activation User"); + db.EmailOutbox.Add(outbox); + await db.SaveChangesAsync(); + outboxId = outbox.Id; + } + + await Factory.RunDeliveryAsync(); + + await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + { + var row = await db.EmailOutbox.AsNoTracking().SingleAsync(m => m.Id == outboxId); + await Assert.That(row.Status).IsEqualTo(EmailStatus.Skipped); + + var request = await db.UserActivationRequests.AsNoTracking().SingleAsync(r => r.UserId == userId); + await Assert.That(request.TokenHash).IsEqualTo(seededHash); + } + + await Assert.That((await mailpit.SearchByRecipientAsync(oldEmail)).Count).IsEqualTo(0); + } + + [Test] + public async Task AccountActivation_IsDelivered_AndEmailedTokenMatchesStoredHash() + { + var email = UniqueEmail("cron-activation"); + using var mailpit = Factory.CreateMailpitHelper(); + + var userId = Guid.CreateVersion7(); + await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + { + db.Users.Add(new User + { + Id = userId, + Name = "Activation User " + Guid.NewGuid().ToString("N")[..8], + Email = email, + PasswordHash = null, + CreatedAt = DateTime.UtcNow, + ActivatedAt = null + }); + db.UserActivationRequests.Add(new UserActivationRequest + { + UserId = userId, + TokenHash = HashingUtils.HashToken(CryptoUtils.RandomString(AuthConstants.GeneratedTokenLength)) + }); + db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(userId, email, "Activation User")); + await db.SaveChangesAsync(); + } + + await Factory.RunDeliveryAsync(); + + var message = await mailpit.WaitForMessageAsync(email); + await Assert.That(message).IsNotNull(); + + var full = await mailpit.GetMessageAsync(message!.Id); + var token = Regex.Match(full!.Html, @"activate\?token=([A-Za-z0-9_\-]+)").Groups[1].Value; + await Assert.That(token).IsNotEmpty(); + + await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + { + var request = await db.UserActivationRequests.AsNoTracking().SingleAsync(r => r.UserId == userId); + await Assert.That(request.TokenHash).IsEqualTo(HashingUtils.HashToken(token)); + } + } + // --- Helpers --- private async Task<(Guid UserId, Guid Stamp)> AddUserAsync(string email, string name) diff --git a/Cron/Services/Email/Outbox/EmailOutboxDispatcher.cs b/Cron/Services/Email/Outbox/EmailOutboxDispatcher.cs index d0af3d3f4..338e5bd7a 100644 --- a/Cron/Services/Email/Outbox/EmailOutboxDispatcher.cs +++ b/Cron/Services/Email/Outbox/EmailOutboxDispatcher.cs @@ -69,7 +69,21 @@ private async Task SendAccountActivation(EmailOutboxMessage if (request is null) return EmailDispatchResult.Skip("Activation request no longer exists"); if (request.User.ActivatedAt is not null) return EmailDispatchResult.Skip("Account already activated"); - var token = await MintTokenAsync(db, h => request.TokenHash = h, ct); + // A pending signup can have its address corrected after this message was queued. The link activates + // the account as it is now, so it may only go to the address the account has now. + if (!string.Equals(message.Recipient, request.User.Email, StringComparison.OrdinalIgnoreCase)) + return EmailDispatchResult.Skip("Account email changed since this message was queued"); + + // Changing the address also replaces the token hash, in the same commit. Writing the new hash only + // over the one read above therefore means the address cannot have changed in between. + var token = CryptoUtils.RandomString(AuthConstants.GeneratedTokenLength); + var newHash = HashingUtils.HashToken(token); + var previousHash = request.TokenHash; + var minted = await db.UserActivationRequests + .Where(r => r.UserId == userId && r.TokenHash == previousHash) + .ExecuteUpdateAsync(s => s.SetProperty(r => r.TokenHash, newHash), ct); + if (minted == 0) return EmailDispatchResult.Skip("Activation request changed since this message was queued"); + var link = new Uri(_frontendOptions.BaseUrl, $"/activate?token={token}"); return FromSend(await _emailService.ActivateAccount(ToContact(message), link, ct)); } From a8d6cca43df70ebcee03ea30e2322a8b1f1ac46f Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Thu, 26 Nov 2026 20:38:47 +0100 Subject: [PATCH 04/14] fix: bind the signup browser proof to the API host and test the OAuth flows Activation accepted the activation resend cookie as proof of being the signup browser. That cookie is readable by script and shared across the cookie domain, so a sibling subdomain could plant one. The proof is now a separate HttpOnly cookie without a Domain, with the __Host- prefix over HTTPS. Add tests that drive authorize, handoff and signup-finalize by minting the flow cookie the provider callback leaves behind, including the reported takeover end to end. --- API.IntegrationTests/Tests/MailTests.cs | 56 ++- API.IntegrationTests/Tests/OAuthFlowTests.cs | 411 ++++++++++++++++++ API.IntegrationTests/WebApplicationFactory.cs | 5 + API/Controller/Account/Activate.cs | 2 +- API/Services/Account/IAccountService.cs | 4 +- .../Authentication/ActivationResendCookie.cs | 14 +- Common/Authentication/SignupBrowserCookie.cs | 91 ++++ Common/Constants/AuthConstants.cs | 2 + 8 files changed, 573 insertions(+), 12 deletions(-) create mode 100644 API.IntegrationTests/Tests/OAuthFlowTests.cs create mode 100644 Common/Authentication/SignupBrowserCookie.cs diff --git a/API.IntegrationTests/Tests/MailTests.cs b/API.IntegrationTests/Tests/MailTests.cs index e2ee961d6..c360309ac 100644 --- a/API.IntegrationTests/Tests/MailTests.cs +++ b/API.IntegrationTests/Tests/MailTests.cs @@ -279,6 +279,12 @@ private string MintResendCookie(Guid userId) return $"{AuthConstants.ActivationResendCookieName}={ActivationResendCookie.CreateToken(provider, userId)}"; } + private string MintSignupBrowserCookie(Guid userId) + { + var provider = WebApplicationFactory.Services.GetRequiredService(); + return $"{AuthConstants.SignupBrowserSecureCookieName}={SignupBrowserCookie.CreateToken(provider, userId)}"; + } + private static Task PostResendAsync(HttpClient client, string? cookie) { var request = new HttpRequestMessage(HttpMethod.Post, "/1/account/activate/resend"); @@ -553,7 +559,7 @@ public async Task Activate_FromSignupBrowser_ActivatesWithTokenAlone() var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-activate-cookie", "OwnerPassword123#"); using var client = CreateCookielessClient(); - var response = await PostActivateAsync(client, token, cookie: MintResendCookie(userId)); + var response = await PostActivateAsync(client, token, cookie: MintSignupBrowserCookie(userId)); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); await Assert.That(await IsActivatedAsync(userId)).IsTrue(); @@ -590,6 +596,48 @@ public async Task Activate_WrongPassword_Returns403() await Assert.That(await IsActivatedAsync(userId)).IsFalse(); } + [Test] + public async Task Signup_SetsSignupBrowserCookie_BoundToTheApiHost() + { + using var client = CreateCookielessClient(); + var response = await SignUpAsync(client, TestHelper.UniqueEmail("mail-signup-browsercookie"), TestHelper.UniqueUsername("mailsignupbrowser")); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + // __Host- prefix, no Domain, HttpOnly: a sibling subdomain cannot plant one in someone else's browser. + var cookie = response.Headers.GetValues("Set-Cookie").Single(c => c.StartsWith(AuthConstants.SignupBrowserSecureCookieName + "=")); + await Assert.That(cookie.Contains("httponly", StringComparison.OrdinalIgnoreCase)).IsTrue(); + await Assert.That(cookie.Contains("secure", StringComparison.OrdinalIgnoreCase)).IsTrue(); + await Assert.That(cookie.Contains("path=/", StringComparison.OrdinalIgnoreCase)).IsTrue(); + await Assert.That(cookie.Contains("domain=", StringComparison.OrdinalIgnoreCase)).IsFalse(); + } + + [Test] + public async Task Activate_ResendCookieAlone_Returns403() + { + // The resend cookie is shared across the cookie domain and readable by script, so it proves nothing. + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-activate-resendcookie", "OwnerPassword123#"); + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token, cookie: MintResendCookie(userId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + [Test] + public async Task Activate_SignupBrowserCookieWithoutHostPrefix_Returns403() + { + // The unprefixed name is the one a sibling subdomain could set. + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-activate-noprefix", "OwnerPassword123#"); + var value = MintSignupBrowserCookie(userId)[(AuthConstants.SignupBrowserSecureCookieName.Length + 1)..]; + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token, cookie: $"{AuthConstants.SignupBrowserCookieName}={value}"); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + [Test] public async Task Activate_SignupCookieOfAnotherAccount_Returns403() { @@ -597,7 +645,7 @@ public async Task Activate_SignupCookieOfAnotherAccount_Returns403() var otherUserId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailactother"), TestHelper.UniqueEmail("mail-activate-other"), "OtherPassword123#", activated: false); using var client = CreateCookielessClient(); - var response = await PostActivateAsync(client, token, cookie: MintResendCookie(otherUserId)); + var response = await PostActivateAsync(client, token, cookie: MintSignupBrowserCookie(otherUserId)); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); await Assert.That(await IsActivatedAsync(userId)).IsFalse(); @@ -647,7 +695,7 @@ public async Task RestartPendingSignup_ChangedEmail_InvalidatesTheLinkMailedToTh await Assert.That(await GetEmailAsync(userId)).IsEqualTo(victimEmail); using var client = CreateCookielessClient(); - var response = await PostActivateAsync(client, token, cookie: MintResendCookie(userId)); + var response = await PostActivateAsync(client, token, cookie: MintSignupBrowserCookie(userId)); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); await Assert.That(await IsActivatedAsync(userId)).IsFalse(); @@ -670,7 +718,7 @@ public async Task RestartPendingSignup_SameEmail_KeepsTheMailedLinkWorking() } using var client = CreateCookielessClient(); - var response = await PostActivateAsync(client, token, cookie: MintResendCookie(userId)); + var response = await PostActivateAsync(client, token, cookie: MintSignupBrowserCookie(userId)); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); await Assert.That(await IsActivatedAsync(userId)).IsTrue(); diff --git a/API.IntegrationTests/Tests/OAuthFlowTests.cs b/API.IntegrationTests/Tests/OAuthFlowTests.cs new file mode 100644 index 000000000..277cbbbb4 --- /dev/null +++ b/API.IntegrationTests/Tests/OAuthFlowTests.cs @@ -0,0 +1,411 @@ +using System.Net; +using System.Security.Claims; +using System.Text.Json; +using System.Web; +using AspNet.Security.OAuth.Discord; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.API.OAuth; +using OpenShock.Common.Authentication; +using OpenShock.Common.Constants; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Utils; + +namespace OpenShock.API.IntegrationTests.Tests; + +/// +/// The OAuth endpoints around a not yet activated account: who may activate it, and what the identity that +/// signed up can and cannot do with it. +/// +/// +/// There is no provider to talk to in tests. What the provider round trip leaves behind is the flow cookie, +/// a ticket holding the provider's claims and the properties the flow was started with, so the tests mint +/// that cookie the way the callback would and drive the real endpoints from there. That the authorize +/// endpoint puts the activation token into those properties is covered separately, by reading the state it +/// sends to the provider. +/// +public sealed class OAuthFlowTests +{ + private const string Provider = "discord"; + + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required WebApplicationFactory WebApplicationFactory { get; init; } + + // --- authorize --- + + [Test] + public async Task Authorize_WithActivationToken_CarriesItThroughTheProviderRoundTrip() + { + using var client = CreateClient(); + var response = await client.PostAsync($"/1/oauth/{Provider}/authorize?flow=LoginOrCreate&activationToken=the-mailed-token", null); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Redirect); + var items = ReadStateItems(response); + await Assert.That(items[OAuthConstants.ItemKeyActivationToken]).IsEqualTo("the-mailed-token"); + } + + [Test] + public async Task Authorize_LinkFlow_DoesNotCarryAnActivationToken() + { + // Linking is for an account that is already signed in, so it never activates anything. + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("oauthlinkauth"), TestHelper.UniqueEmail("oauth-link-auth"), "SecurePassword123#"); + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var response = await client.PostAsync($"/1/oauth/{Provider}/authorize?flow=Link&activationToken=the-mailed-token", null); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Redirect); + await Assert.That(ReadStateItems(response).ContainsKey(OAuthConstants.ItemKeyActivationToken)).IsFalse(); + } + + // --- handoff: activating a pending account --- + + [Test] + public async Task Handoff_LinkedIdentityWithTheMailedToken_ActivatesAndSignsIn() + { + var externalId = NewExternalId(); + var (userId, token) = await CreatePendingOAuthAccountAsync("oauth-handoff-activate", externalId); + + using var client = CreateClient(); + var response = await HandoffAsync(client, MintFlowCookie(externalId, activationToken: token)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Redirect); + await Assert.That(response.Headers.Location!.AbsolutePath).IsEqualTo("/home"); + await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsTrue(); + await Assert.That(await IsActivatedAsync(userId)).IsTrue(); + } + + [Test] + public async Task Handoff_LinkedIdentityWithoutTheToken_StaysPending_AndIsNotSignedIn() + { + // The identity that signed up, on its own: it never showed it reads the inbox. + var externalId = NewExternalId(); + var (userId, _) = await CreatePendingOAuthAccountAsync("oauth-handoff-notoken", externalId); + + using var client = CreateClient(); + var response = await HandoffAsync(client, MintFlowCookie(externalId)); + + await AssertSentBackToSignupAsync(response, pending: true); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + [Test] + public async Task Handoff_LinkedIdentityWithATokenOfAnotherAccount_StaysPending() + { + // A link from an inbox the caller does control does not activate the account they parked elsewhere. + var externalId = NewExternalId(); + var (userId, _) = await CreatePendingOAuthAccountAsync("oauth-handoff-othertoken", externalId); + var (otherUserId, otherToken) = await CreatePendingOAuthAccountAsync("oauth-handoff-othertok2", NewExternalId()); + + using var client = CreateClient(); + var response = await HandoffAsync(client, MintFlowCookie(externalId, activationToken: otherToken)); + + await AssertSentBackToSignupAsync(response, pending: true); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + await Assert.That(await IsActivatedAsync(otherUserId)).IsFalse(); + } + + [Test] + public async Task Handoff_AnotherIdentityWithTheMailedToken_DoesNotActivate() + { + // The inbox owner clicking the link and signing in with their own provider account: that identity + // is not the one on the account somebody else created with their address. + var (userId, token) = await CreatePendingOAuthAccountAsync("oauth-handoff-otherid", NewExternalId()); + + using var client = CreateClient(); + var response = await HandoffAsync(client, MintFlowCookie(NewExternalId(), activationToken: token)); + + await AssertSentBackToSignupAsync(response, pending: false); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + // --- signup-finalize --- + + [Test] + public async Task SignupFinalize_EmailTheProviderDidNotVerify_CreatesAPendingAccount_WithoutASession() + { + var externalId = NewExternalId(); + var email = TestHelper.UniqueEmail("oauth-finalize-unverified"); + + using var client = CreateClient(); + var response = await FinalizeAsync(client, MintFlowCookie(externalId, email: TestHelper.UniqueEmail("oauth-finalize-provider"), emailVerified: true), email, TestHelper.UniqueUsername("oauthfinunver")); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsFalse(); + await Assert.That(SetsCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsTrue(); + + var user = await GetUserByEmailAsync(email); + await Assert.That(user.ActivatedAt).IsNull(); + } + + [Test] + public async Task SignupFinalize_EmailTheProviderVerified_CreatesAnActivatedAccount_AndSignsIn() + { + var externalId = NewExternalId(); + var email = TestHelper.UniqueEmail("oauth-finalize-verified"); + + using var client = CreateClient(); + var response = await FinalizeAsync(client, MintFlowCookie(externalId, email: email, emailVerified: true), email, TestHelper.UniqueUsername("oauthfinver")); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsTrue(); + + var user = await GetUserByEmailAsync(email); + await Assert.That(user.ActivatedAt).IsNotNull(); + } + + [Test] + public async Task SignupFinalize_PendingAccount_NewEmail_MovesIt_AndTheOldLinkNoLongerActivates() + { + // Sign up with an inbox of your own, then move the pending account onto someone else's address. + var externalId = NewExternalId(); + var (userId, oldToken) = await CreatePendingOAuthAccountAsync("oauth-finalize-move", externalId); + var username = await GetUsernameAsync(userId); + var victimEmail = TestHelper.UniqueEmail("oauth-finalize-victim"); + + using var client = CreateClient(); + var response = await FinalizeAsync(client, MintFlowCookie(externalId), victimEmail, username); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsFalse(); + var moved = await GetUserByEmailAsync(victimEmail); + await Assert.That(moved.Id).IsEqualTo(userId); + await Assert.That(moved.ActivatedAt).IsNull(); + + // Neither from the signup browser... + var activate = new HttpRequestMessage(HttpMethod.Post, $"/1/account/activate?token={oldToken}"); + activate.Headers.Add("Cookie", MintSignupBrowserCookie(userId)); + await Assert.That((await client.SendAsync(activate)).StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + + // ...nor through a provider sign-in. + var handoff = await HandoffAsync(client, MintFlowCookie(externalId, activationToken: oldToken)); + await AssertSentBackToSignupAsync(handoff, pending: true); + + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + [Test] + public async Task SignupFinalize_PendingAccount_EmailTheProviderVerified_ReplacesItWithAnActivatedAccount() + { + var externalId = NewExternalId(); + var (pendingUserId, _) = await CreatePendingOAuthAccountAsync("oauth-finalize-replace", externalId); + var email = TestHelper.UniqueEmail("oauth-finalize-replace-verified"); + + using var client = CreateClient(); + var response = await FinalizeAsync(client, MintFlowCookie(externalId, email: email, emailVerified: true), email, TestHelper.UniqueUsername("oauthfinrepl")); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsTrue(); + + var user = await GetUserByEmailAsync(email); + await Assert.That(user.Id).IsNotEqualTo(pendingUserId); + await Assert.That(user.ActivatedAt).IsNotNull(); + await Assert.That(await UserExistsAsync(pendingUserId)).IsFalse(); + } + + [Test] + public async Task SignupFinalize_IdentityOfAnActivatedAccount_Returns409() + { + var externalId = NewExternalId(); + var (userId, token) = await CreatePendingOAuthAccountAsync("oauth-finalize-activated", externalId); + using var client = CreateClient(); + await HandoffAsync(client, MintFlowCookie(externalId, activationToken: token)); + await Assert.That(await IsActivatedAsync(userId)).IsTrue(); + + var response = await FinalizeAsync(client, MintFlowCookie(externalId), TestHelper.UniqueEmail("oauth-finalize-activated-new"), TestHelper.UniqueUsername("oauthfinact")); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + } + + // --- the reported takeover, end to end --- + + [Test] + public async Task AccountSomeoneElseCreatedOnMyAddress_AfterITakeItOverByPasswordReset_TheirIdentityNoLongerSignsIn() + { + var attackerExternalId = NewExternalId(); + var victimEmail = TestHelper.UniqueEmail("oauth-takeover-victim"); + + // The attacker signs up through the provider, typing the victim's address. + using var client = CreateClient(); + var signup = await FinalizeAsync(client, MintFlowCookie(attackerExternalId, email: TestHelper.UniqueEmail("oauth-takeover-attacker"), emailVerified: true), victimEmail, TestHelper.UniqueUsername("oauthtakeover")); + await Assert.That(signup.StatusCode).IsEqualTo(HttpStatusCode.OK); + var account = await GetUserByEmailAsync(victimEmail); + + // The victim, who owns the inbox, resets the password. That activates the account. + var reset = await CompleteSeededPasswordResetAsync(account.Id); + await Assert.That(reset.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await IsActivatedAsync(account.Id)).IsTrue(); + + // The attacker's identity is no longer linked: signing in with it reaches no account. + var handoff = await HandoffAsync(client, MintFlowCookie(attackerExternalId)); + await AssertSentBackToSignupAsync(handoff, pending: false); + + // And it cannot be attached to that address again. + var again = await FinalizeAsync(client, MintFlowCookie(attackerExternalId), victimEmail, TestHelper.UniqueUsername("oauthtakeover2")); + await Assert.That(again.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + } + + // --- helpers --- + + private HttpClient CreateClient() => WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false, + HandleCookies = false + }); + + private static string NewExternalId() => Guid.NewGuid().ToString("N"); + + /// + /// The flow cookie as the provider callback leaves it: the provider's claims, plus the properties the + /// flow was started with. + /// + private string MintFlowCookie(string externalId, string? email = null, bool emailVerified = false, string? activationToken = null, OAuthFlow flow = OAuthFlow.LoginOrCreate) + { + var options = WebApplicationFactory.Services.GetRequiredService>().Get(OAuthConstants.FlowScheme); + + List claims = + [ + new(ClaimTypes.NameIdentifier, externalId), + new(ClaimTypes.Name, "external-" + externalId[..8]) + ]; + if (email is not null) claims.Add(new Claim(ClaimTypes.Email, email)); + if (emailVerified) claims.Add(new Claim(OAuthConstants.ClaimEmailVerified, "true")); + + var properties = new AuthenticationProperties + { + IssuedUtc = DateTimeOffset.UtcNow, + ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10) + }; + properties.Items[".AuthScheme"] = Provider; + properties.Items[OAuthConstants.ItemKeyFlowType] = flow.ToString(); + if (activationToken is not null) properties.Items[OAuthConstants.ItemKeyActivationToken] = activationToken; + + var ticket = new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(claims, Provider)), properties, OAuthConstants.FlowScheme); + + return $"{options.Cookie.Name}={options.TicketDataFormat.Protect(ticket)}"; + } + + private string MintSignupBrowserCookie(Guid userId) + { + var provider = WebApplicationFactory.Services.GetRequiredService(); + return $"{AuthConstants.SignupBrowserSecureCookieName}={SignupBrowserCookie.CreateToken(provider, userId)}"; + } + + /// The properties the authorize endpoint handed to the provider, read back from the state parameter. + private IDictionary ReadStateItems(HttpResponseMessage response) + { + var state = HttpUtility.ParseQueryString(response.Headers.Location!.Query)["state"]!; + var options = WebApplicationFactory.Services.GetRequiredService>().Get(Provider); + return options.StateDataFormat.Unprotect(state)!.Items; + } + + private static Task HandoffAsync(HttpClient client, string flowCookie) + { + var request = new HttpRequestMessage(HttpMethod.Get, $"/1/oauth/{Provider}/handoff"); + request.Headers.Add("Cookie", flowCookie); + return client.SendAsync(request); + } + + private static Task FinalizeAsync(HttpClient client, string flowCookie, string email, string username) + { + var request = new HttpRequestMessage(HttpMethod.Post, $"/1/oauth/{Provider}/signup-finalize") + { + Content = TestHelper.JsonContent(new { email, username }) + }; + request.Headers.Add("Cookie", flowCookie); + return client.SendAsync(request); + } + + /// Not signed in, and sent to the signup form: there is no usable account for this identity. + private static async Task AssertSentBackToSignupAsync(HttpResponseMessage response, bool pending) + { + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Redirect); + await Assert.That(response.Headers.Location!.AbsolutePath).IsEqualTo($"/oauth/{Provider}/create"); + await Assert.That(response.Headers.Location.Query).IsEqualTo(pending ? "?pending=1" : ""); + await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsFalse(); + } + + private static bool SetsCookie(HttpResponseMessage response, string name) => + response.Headers.TryGetValues("Set-Cookie", out var values) && + values.Any(c => c.StartsWith(name + "=") && !c.StartsWith(name + "=;")); + + /// + /// An account created through the provider with an address it did not verify, with its activation link + /// already mailed (the Cron delivery job mints the real token at send time). + /// + private async Task<(Guid UserId, string Token)> CreatePendingOAuthAccountAsync(string prefix, string externalId) + { + var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername(prefix.Replace("-", "")), TestHelper.UniqueEmail(prefix), "Placeholder123#", activated: false); + var token = "activation-" + Guid.NewGuid().ToString("N"); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await db.Users.Where(u => u.Id == userId).ExecuteUpdateAsync(s => s.SetProperty(u => u.PasswordHash, (string?)null)); + db.UserActivationRequests.Add(new UserActivationRequest { UserId = userId, TokenHash = HashingUtils.HashToken(token) }); + db.UserOAuthConnections.Add(new UserOAuthConnection + { + UserId = userId, + ProviderKey = Provider, + ExternalId = externalId, + DisplayName = "external" + }); + await db.SaveChangesAsync(); + + return (userId, token); + } + + private async Task CompleteSeededPasswordResetAsync(Guid userId) + { + const string secret = "test-password-reset-secret"; + var resetId = Guid.CreateVersion7(); + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var stamp = await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.SecurityStamp).SingleAsync(); + db.UserPasswordResets.Add(new UserPasswordReset + { + Id = resetId, + UserId = userId, + TokenHash = HashingUtils.HashToken(secret), + SecurityStampAtCreate = stamp + }); + await db.SaveChangesAsync(); + } + + using var client = WebApplicationFactory.CreateClient(); + return await client.PostAsync($"/1/account/password-reset/{resetId}/{secret}/complete", + TestHelper.JsonContent(new { password = "NewPassword123#" })); + } + + private async Task IsActivatedAsync(Guid userId) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.ActivatedAt != null).SingleAsync(); + } + + private async Task UserExistsAsync(Guid userId) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Users.AsNoTracking().AnyAsync(u => u.Id == userId); + } + + private async Task GetUsernameAsync(Guid userId) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.Name).SingleAsync(); + } + + private async Task GetUserByEmailAsync(string email) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Users.AsNoTracking().SingleAsync(u => u.Email == email); + } +} diff --git a/API.IntegrationTests/WebApplicationFactory.cs b/API.IntegrationTests/WebApplicationFactory.cs index 7d335f688..84ec5107d 100644 --- a/API.IntegrationTests/WebApplicationFactory.cs +++ b/API.IntegrationTests/WebApplicationFactory.cs @@ -73,6 +73,11 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) { "OPENSHOCK__TURNSTILE__SECRETKEY", "turnstile-secret-key" }, { "OPENSHOCK__TURNSTILE__SITEKEY", "turnstile-site-key" }, + // Never contacted: enough for the provider to be offered and for the authorize endpoint to + // build its redirect. OAuthFlowTests stands in for the provider's answer. + { "OPENSHOCK__OAUTH2__DISCORD__CLIENTID", "test-discord-client-id" }, + { "OPENSHOCK__OAUTH2__DISCORD__CLIENTSECRET", "test-discord-client-secret" }, + { "OPENSHOCK__LCG__FQDN", "de1-gateway.my-openshock-instance.net" }, { "OPENSHOCK__LCG__COUNTRYCODE", "DE" }, diff --git a/API/Controller/Account/Activate.cs b/API/Controller/Account/Activate.cs index 3d8313c0d..9da4913ad 100644 --- a/API/Controller/Account/Activate.cs +++ b/API/Controller/Account/Activate.cs @@ -36,7 +36,7 @@ public async Task Activate( [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] ActivateRequest? body, CancellationToken cancellationToken) { - ActivationResendCookie.TryGetUserId(HttpContext, out var signupBrowserUserId); + SignupBrowserCookie.TryGetUserId(HttpContext, out var signupBrowserUserId); var result = await _accountService.ActivateAccountAsync(token, signupBrowserUserId, body?.Password, cancellationToken); diff --git a/API/Services/Account/IAccountService.cs b/API/Services/Account/IAccountService.cs index bcbf8affd..f61124b6e 100644 --- a/API/Services/Account/IAccountService.cs +++ b/API/Services/Account/IAccountService.cs @@ -57,12 +57,12 @@ public interface IAccountService /// /// Activates the account an emailed activation token belongs to. The token only proves control of the /// inbox, and anyone can sign up with somebody else's address, so the caller must also show they are - /// the one who signed up: the signup browser's resend cookie () + /// the one who signed up: the signup browser's cookie () /// or the account's password. An account created through OAuth is activated by signing in with the /// linked provider instead, see . /// /// Token from the activation email. - /// User id from the activation resend cookie, if the request carries a valid one. + /// User id from , if the request carries a valid one. /// Password supplied alongside the token, if any. /// /// diff --git a/Common/Authentication/ActivationResendCookie.cs b/Common/Authentication/ActivationResendCookie.cs index 2e2bc78c8..38eafbe87 100644 --- a/Common/Authentication/ActivationResendCookie.cs +++ b/Common/Authentication/ActivationResendCookie.cs @@ -16,13 +16,13 @@ namespace OpenShock.Common.Authentication; /// so it is valid across API instances). It is removed on any successful session authentication, and by the /// resend endpoint once there is nothing left to resend. /// -/// It also marks this browser as the one that signed up: it is only ever issued in the response that creates -/// the account, and the activation endpoint accepts it in place of re-entering the password. -/// -/// /// Deliberately not HttpOnly: the frontend reads its presence to decide whether to offer the resend /// button. HttpOnly would buy little anyway - script on the page could call the endpoint with the cookie attached -/// regardless - and a leaked token is useless without the activation link mailed to that account's own inbox. +/// regardless - and a leaked token can only resend (rate limited) activation emails to that account's own inbox. +/// +/// +/// It is not proof of anything else. What marks this browser as the one that signed up, for activation, is +/// , which is set and removed together with this one. /// /// public static class ActivationResendCookie @@ -45,6 +45,8 @@ public static void Set(HttpContext context, Guid userId, string domain) SameSite = SameSiteMode.Lax, Domain = domain }); + + SignupBrowserCookie.Set(context, userId); } public static bool TryGetUserId(HttpContext context, [NotNullWhen(true)] out Guid? userId) @@ -70,6 +72,8 @@ public static bool TryGetUserId(HttpContext context, [NotNullWhen(true)] out Gui /// Deletes the cookie, if the request carries one, on every configured cookie domain. public static void Remove(HttpContext context) { + SignupBrowserCookie.Remove(context); + if (!context.Request.Cookies.ContainsKey(AuthConstants.ActivationResendCookieName)) return; var cookieDomains = context.RequestServices.GetRequiredService().CookieDomains; diff --git a/Common/Authentication/SignupBrowserCookie.cs b/Common/Authentication/SignupBrowserCookie.cs new file mode 100644 index 000000000..6c4460bb3 --- /dev/null +++ b/Common/Authentication/SignupBrowserCookie.cs @@ -0,0 +1,91 @@ +using System.Diagnostics.CodeAnalysis; +using System.Security.Cryptography; +using Microsoft.AspNetCore.DataProtection; +using OpenShock.Common.Constants; +using OpenShock.Common.Options; + +namespace OpenShock.Common.Authentication; + +/// +/// Marks the browser that created a not yet activated account. The activation endpoint accepts it, together +/// with the emailed link, in place of the account's password or a sign-in with its linked provider. +/// +/// +/// Issued and removed alongside , but kept separate because it is a +/// credential and that one is not. The resend cookie has to be readable by the frontend and shared across +/// the cookie domain, which means any sibling subdomain could plant one in a visitor's browser. Planting +/// this one would let someone who signed up with another person's address have that person's click on the +/// emailed link activate the account. So this cookie is bound to the API host alone: no Domain, +/// HttpOnly, and over HTTPS the __Host- name prefix, which browsers refuse to accept from +/// anything but this exact host. +/// +public static class SignupBrowserCookie +{ + private const string ProtectorPurpose = "OpenShock.SignupBrowserCookie"; + + /// The cookie name used for a request: __Host- prefixed whenever cookies are secure. + public static string GetName(HttpContext context) => IsSecure(context) + ? AuthConstants.SignupBrowserSecureCookieName + : AuthConstants.SignupBrowserCookieName; + + public static string CreateToken(IDataProtectionProvider provider, Guid userId) + => GetProtector(provider).Protect(userId.ToString(), Duration.ActivationResendWindow); + + public static void Set(HttpContext context, Guid userId) + { + var provider = context.RequestServices.GetRequiredService(); + + context.Response.Cookies.Append(GetName(context), CreateToken(provider, userId), new CookieOptions + { + Expires = DateTimeOffset.UtcNow.Add(Duration.ActivationResendWindow), + Secure = IsSecure(context), + HttpOnly = true, + SameSite = SameSiteMode.Lax, + Path = "/" + }); + } + + public static bool TryGetUserId(HttpContext context, [NotNullWhen(true)] out Guid? userId) + { + userId = null; + + // Only the name that matches this deployment: over HTTPS an unprefixed cookie is exactly what a + // sibling subdomain could have planted. + if (!context.Request.Cookies.TryGetValue(GetName(context), out var token) || string.IsNullOrEmpty(token)) + return false; + + var provider = context.RequestServices.GetRequiredService(); + try + { + if (!Guid.TryParse(GetProtector(provider).Unprotect(token), out var id)) return false; + userId = id; + return true; + } + catch (CryptographicException) + { + // Tampered, expired, or signed with a revoked key. + return false; + } + } + + /// Deletes the cookie, if the request carries one. + public static void Remove(HttpContext context) + { + var name = GetName(context); + if (!context.Request.Cookies.ContainsKey(name)) return; + + context.Response.Cookies.Delete(name, new CookieOptions + { + Secure = IsSecure(context), + HttpOnly = true, + SameSite = SameSiteMode.Lax, + Path = "/" + }); + } + + private static bool IsSecure(HttpContext context) + => context.Request.IsHttps || context.RequestServices.GetRequiredService().CookieSecure; + + private static ITimeLimitedDataProtector GetProtector(IDataProtectionProvider provider) + => provider.CreateProtector(ProtectorPurpose).ToTimeLimitedDataProtector(); +} diff --git a/Common/Constants/AuthConstants.cs b/Common/Constants/AuthConstants.cs index 3fdb5c6a1..06c854e7d 100644 --- a/Common/Constants/AuthConstants.cs +++ b/Common/Constants/AuthConstants.cs @@ -4,6 +4,8 @@ public static class AuthConstants { public const string UserSessionCookieName = "openShockSession"; public const string ActivationResendCookieName = "openShockActivationResend"; + public const string SignupBrowserCookieName = "openShockSignupBrowser"; + public const string SignupBrowserSecureCookieName = "__Host-openShockSignupBrowser"; public const string UserSessionHeaderName = "OpenShockSession"; public const string ApiTokenHeaderName = "OpenShockToken"; public const string HubTokenHeaderName = "DeviceToken"; From fb7c799b5161659641b182492f5d51567b5ce729 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Thu, 26 Nov 2026 20:46:12 +0100 Subject: [PATCH 05/14] fix: address review findings on pending signups, connection removal and revalidation Pending signups: a correction rotates the security stamp so a password reset link requested for the old address stops working, deleting a pending account is conditional on it still being pending, and releases and replacements roll back when the signup they make room for fails. The release cooldown also counts the latest activation mail, and mail being disabled no longer counts as proof of owning an address. Removing an OAuth connection checks for the last login method under a lock on the user row. A password reset signs sessions out before it commits. The hub revalidation filter also rejects sessions of deactivated or unactivated accounts. --- API.IntegrationTests/Tests/MailTests.cs | 145 ++++++++++++++++-- API.IntegrationTests/Tests/OAuthFlowTests.cs | 21 +++ .../Tests/SignalRUserHubTests.cs | 23 +++ .../Authenticated/OAuthConnectionRemove.cs | 25 +-- API/Controller/OAuth/SignupFinalize.cs | 5 +- API/Services/Account/AccountService.cs | 114 ++++++++++---- API/Services/Account/IAccountService.cs | 14 +- .../IOAuthConnectionService.cs | 15 +- .../OAuthConnection/OAuthConnectionService.cs | 36 +++-- .../Authentication/ActivationResendCookie.cs | 7 +- .../Hubs/RevalidateAuthenticationHubFilter.cs | 8 +- 11 files changed, 327 insertions(+), 86 deletions(-) diff --git a/API.IntegrationTests/Tests/MailTests.cs b/API.IntegrationTests/Tests/MailTests.cs index c360309ac..3078cf690 100644 --- a/API.IntegrationTests/Tests/MailTests.cs +++ b/API.IntegrationTests/Tests/MailTests.cs @@ -482,6 +482,30 @@ public async Task Signup_EmailHeldByStalePendingAccount_ReplacesIt() await Assert.That(holder.Id).IsNotEqualTo(pendingId); } + // The cooldown runs from the last activation mail, not only from signup: replacing the account would + // mail the same inbox again straight after a resend did. + [Test] + public async Task Signup_EmailHeldByStalePendingAccount_ThatWasJustMailedAgain_Returns409() + { + var email = TestHelper.UniqueEmail("mail-pending-resent"); + var pendingId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailpendingresent"), email, "FirstPassword123#", activated: false); + await BackdateUserAsync(pendingId, TimeSpan.FromMinutes(11)); + await using (var seedScope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var seedDb = seedScope.ServiceProvider.GetRequiredService(); + seedDb.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(pendingId, email, "pending")); + await seedDb.SaveChangesAsync(); + } + + using var client = CreateCookielessClient(); + var response = await SignUpAsync(client, email, TestHelper.UniqueUsername("mailpendingthird")); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.Users.AsNoTracking().AnyAsync(u => u.Id == pendingId)).IsTrue(); + } + // Inside the resend cooldown the pending account keeps the address, so its creator has time to open the // link and repeated signups cannot mail the inbox more often than a resend could. [Test] @@ -540,6 +564,49 @@ public async Task RemoveOAuthConnection_OnlyLoginMethod_Returns409_AndKeepsConne await Assert.That(await db.UserOAuthConnections.AsNoTracking().CountAsync(c => c.UserId == user.Id)).IsEqualTo(1); } + [Test] + public async Task RemoveOAuthConnection_PasswordlessAccountWithTwo_RemovesOne_ThenKeepsTheLast() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailoauthtwo"), TestHelper.UniqueEmail("mail-oauth-two"), "Placeholder123#"); + await AddOAuthConnectionAsync(user.Id, "discord"); + await AddOAuthConnectionAsync(user.Id, "google"); + await using (var seedScope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var seedDb = seedScope.ServiceProvider.GetRequiredService(); + await seedDb.Users.Where(u => u.Id == user.Id).ExecuteUpdateAsync(s => s.SetProperty(u => u.PasswordHash, (string?)null)); + } + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + await Assert.That((await client.DeleteAsync("/1/account/connections/discord")).StatusCode).IsEqualTo(HttpStatusCode.NoContent); + await Assert.That((await client.DeleteAsync("/1/account/connections/google")).StatusCode).IsEqualTo(HttpStatusCode.Conflict); + await Assert.That((await client.DeleteAsync("/1/account/connections/discord")).StatusCode).IsEqualTo(HttpStatusCode.NotFound); + } + + [Test] + public async Task RemoveOAuthConnection_PasswordlessAccountWithTwo_RemovedAtTheSameTime_KeepsOne() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailoauthrace"), TestHelper.UniqueEmail("mail-oauth-race"), "Placeholder123#"); + await AddOAuthConnectionAsync(user.Id, "discord"); + await AddOAuthConnectionAsync(user.Id, "google"); + await using (var seedScope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var seedDb = seedScope.ServiceProvider.GetRequiredService(); + await seedDb.Users.Where(u => u.Id == user.Id).ExecuteUpdateAsync(s => s.SetProperty(u => u.PasswordHash, (string?)null)); + } + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var responses = await Task.WhenAll( + client.DeleteAsync("/1/account/connections/discord"), + client.DeleteAsync("/1/account/connections/google")); + + await Assert.That(responses.Count(r => r.StatusCode == HttpStatusCode.NoContent)).IsEqualTo(1); + await Assert.That(responses.Count(r => r.StatusCode == HttpStatusCode.Conflict)).IsEqualTo(1); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.UserOAuthConnections.AsNoTracking().CountAsync(c => c.UserId == user.Id)).IsEqualTo(1); + } + [Test] public async Task RemoveOAuthConnection_AccountWithPassword_RemovesIt() { @@ -701,6 +768,51 @@ public async Task RestartPendingSignup_ChangedEmail_InvalidatesTheLinkMailedToTh await Assert.That(await IsActivatedAsync(userId)).IsFalse(); } + [Test] + public async Task RestartPendingSignup_ChangedEmail_InvalidatesAPasswordResetRequestedForTheOldAddress() + { + // The other link an inbox of your own can give you: a reset sets a password and activates. + var (userId, _) = await CreateUnactivatedUserWithTokenAsync("mail-restart-oldreset", password: null); + await AddOAuthConnectionAsync(userId, "discord"); + var (resetId, secret) = await SeedPasswordResetAsync(userId); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var username = await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.Name).SingleAsync(); + + var accountService = scope.ServiceProvider.GetRequiredService(); + var restarted = await accountService.RestartPendingSignupAsync(userId, TestHelper.UniqueEmail("mail-restart-victim2"), username); + await Assert.That(restarted.Value is User).IsTrue(); + } + + using var client = CreateCookielessClient(); + var response = await client.PostAsync($"/1/account/password-reset/{resetId}/{secret}/complete", + TestHelper.JsonContent(new { password = "NewPassword123#" })); + + await Assert.That(response.StatusCode).IsNotEqualTo(HttpStatusCode.OK); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + [Test] + public async Task RestartPendingSignup_Conflict_LeavesThePendingAccountHoldingTheRequestedAddress() + { + var (userId, _) = await CreateUnactivatedUserWithTokenAsync("mail-restart-conflict", password: null); + var heldEmail = TestHelper.UniqueEmail("mail-restart-held"); + var holderId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailrestartholder"), heldEmail, "HolderPassword123#", activated: false); + await BackdateUserAsync(holderId, TimeSpan.FromMinutes(11)); + var takenUsername = TestHelper.UniqueUsername("mailrestarttaken"); + await TestHelper.CreateUserInDb(WebApplicationFactory, takenUsername, TestHelper.UniqueEmail("mail-restart-taken"), "TakenPassword123#"); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var accountService = scope.ServiceProvider.GetRequiredService(); + var restarted = await accountService.RestartPendingSignupAsync(userId, heldEmail, takenUsername); + await Assert.That(restarted.Value is AccountWithEmailOrUsernameExists).IsTrue(); + + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.Users.AsNoTracking().AnyAsync(u => u.Id == holderId)).IsTrue(); + } + [Test] public async Task RestartPendingSignup_SameEmail_KeepsTheMailedLinkWorking() { @@ -742,7 +854,7 @@ public async Task EmailChangeVerify_WithoutSession_Returns401_AndLeavesEmail() public async Task EmailChangeVerify_FromAnotherAccountsSession_Returns400_AndLeavesEmail() { var (user, token, _) = await CreateUserWithPendingEmailChangeAsync("mail-verify-other"); - var other = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailverifyother"), TestHelper.UniqueEmail("mail-verify-otheracct"), "SecurePassword123#"); + var other = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailverifysecond"), TestHelper.UniqueEmail("mail-verify-second"), "SecurePassword123#"); using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, other.SessionToken); var response = await client.PostAsync($"/1/account/email-change/verify?token={token}", null); @@ -841,23 +953,28 @@ public async Task PasswordResetComplete_RevokesExistingSessions() } // Stands in for the Cron delivery job (which mints the real token), then completes the reset. - private async Task CompleteSeededPasswordResetAsync(Guid userId) + private async Task<(Guid ResetId, string Secret)> SeedPasswordResetAsync(Guid userId) { const string secret = "test-password-reset-secret"; var resetId = Guid.CreateVersion7(); - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var stamp = await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.SecurityStamp).SingleAsync(); + db.UserPasswordResets.Add(new UserPasswordReset { - var db = scope.ServiceProvider.GetRequiredService(); - var stamp = await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.SecurityStamp).SingleAsync(); - db.UserPasswordResets.Add(new UserPasswordReset - { - Id = resetId, - UserId = userId, - TokenHash = HashingUtils.HashToken(secret), - SecurityStampAtCreate = stamp - }); - await db.SaveChangesAsync(); - } + Id = resetId, + UserId = userId, + TokenHash = HashingUtils.HashToken(secret), + SecurityStampAtCreate = stamp + }); + await db.SaveChangesAsync(); + + return (resetId, secret); + } + + private async Task CompleteSeededPasswordResetAsync(Guid userId) + { + var (resetId, secret) = await SeedPasswordResetAsync(userId); using var client = WebApplicationFactory.CreateClient(); return await client.PostAsync($"/1/account/password-reset/{resetId}/{secret}/complete", diff --git a/API.IntegrationTests/Tests/OAuthFlowTests.cs b/API.IntegrationTests/Tests/OAuthFlowTests.cs index 277cbbbb4..631677a48 100644 --- a/API.IntegrationTests/Tests/OAuthFlowTests.cs +++ b/API.IntegrationTests/Tests/OAuthFlowTests.cs @@ -207,6 +207,27 @@ public async Task SignupFinalize_PendingAccount_EmailTheProviderVerified_Replace await Assert.That(await UserExistsAsync(pendingUserId)).IsFalse(); } + [Test] + public async Task SignupFinalize_PendingAccount_EmailTheProviderVerified_UsernameTaken_KeepsThePendingAccount() + { + var externalId = NewExternalId(); + var (pendingUserId, _) = await CreatePendingOAuthAccountAsync("oauth-finalize-keep", externalId); + var takenUsername = TestHelper.UniqueUsername("oauthfintaken"); + await TestHelper.CreateUserInDb(WebApplicationFactory, takenUsername, TestHelper.UniqueEmail("oauth-finalize-taken"), "TakenPassword123#"); + var email = TestHelper.UniqueEmail("oauth-finalize-keep-verified"); + + using var client = CreateClient(); + var response = await FinalizeAsync(client, MintFlowCookie(externalId, email: email, emailVerified: true), email, takenUsername); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + await Assert.That(await UserExistsAsync(pendingUserId)).IsTrue(); + + // The identity is still linked to it, so the signup can be retried with another username. + var retry = await FinalizeAsync(client, MintFlowCookie(externalId, email: email, emailVerified: true), email, TestHelper.UniqueUsername("oauthfinretry")); + await Assert.That(retry.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await UserExistsAsync(pendingUserId)).IsFalse(); + } + [Test] public async Task SignupFinalize_IdentityOfAnActivatedAccount_Returns409() { diff --git a/API.IntegrationTests/Tests/SignalRUserHubTests.cs b/API.IntegrationTests/Tests/SignalRUserHubTests.cs index ba38e3d1e..9672e6c44 100644 --- a/API.IntegrationTests/Tests/SignalRUserHubTests.cs +++ b/API.IntegrationTests/Tests/SignalRUserHubTests.cs @@ -135,6 +135,29 @@ public async Task Invoke_AfterSessionDeleted_FailsAndClosesConnection() await AssertInvokeFailsAndConnectionClosesAsync(connection); } + [Test] + public async Task Invoke_AfterAccountDeactivated_WithTheSessionLeftBehind_FailsAndClosesConnection() + { + // Deactivation removes sessions after its database commit; if that step fails the session survives. + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaldeact"), TestHelper.UniqueEmail("hubrevaldeact"), "SecurePassword123#"); + await using var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + db.UserDeactivations.Add(new UserDeactivation + { + DeactivatedUserId = user.Id, + DeactivatedByUserId = user.Id, + DeleteLater = false + }); + await db.SaveChangesAsync(); + } + + await AssertInvokeFailsAndConnectionClosesAsync(connection); + } + [Test] public async Task Invoke_WithValidApiToken_KeepsWorking() { diff --git a/API/Controller/Account/Authenticated/OAuthConnectionRemove.cs b/API/Controller/Account/Authenticated/OAuthConnectionRemove.cs index a875db9b3..fc4c797e7 100644 --- a/API/Controller/Account/Authenticated/OAuthConnectionRemove.cs +++ b/API/Controller/Account/Authenticated/OAuthConnectionRemove.cs @@ -1,6 +1,5 @@ using System.Net.Mime; using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; using OpenShock.API.OAuth; using OpenShock.API.Services.OAuthConnection; using OpenShock.Common.ApiVersioning; @@ -27,23 +26,13 @@ public sealed partial class AuthenticatedAccountController [ProducesResponseType(StatusCodes.Status409Conflict, MediaTypeNames.Application.ProblemJson)] // LastLoginMethod public async Task RemoveOAuthConnection([FromRoute] string provider, [FromServices] IOAuthConnectionService connectionService, CancellationToken cancellationToken) { - // An account without a password signs in through its connections only. Removing the last one would - // lock its owner out until they notice and go through a password reset. - if (string.IsNullOrEmpty(CurrentUser.PasswordHash)) - { - var providers = await connectionService.GetConnectionsAsNonTrackingQuery(CurrentUser.Id, cancellationToken) - .Select(c => c.ProviderKey) - .ToListAsync(cancellationToken); - - if (providers.Count == 1 && string.Equals(providers[0], provider, StringComparison.OrdinalIgnoreCase)) - return Problem(OAuthError.LastLoginMethod); - } - - var deleted = await connectionService.TryRemoveConnectionAsync(CurrentUser.Id, provider, actorId: CurrentUser.Id, cancellationToken); + var result = await connectionService.RemoveConnectionAsync(CurrentUser.Id, provider, actorId: CurrentUser.Id, cancellationToken); - if (!deleted) - return NotFound(); - - return NoContent(); + return result switch + { + RemoveConnectionResult.Removed => NoContent(), + RemoveConnectionResult.LastLoginMethod => Problem(OAuthError.LastLoginMethod), + _ => NotFound() + }; } } diff --git a/API/Controller/OAuth/SignupFinalize.cs b/API/Controller/OAuth/SignupFinalize.cs index 122861af9..773ca39bf 100644 --- a/API/Controller/OAuth/SignupFinalize.cs +++ b/API/Controller/OAuth/SignupFinalize.cs @@ -89,6 +89,7 @@ public async Task OAuthSignupFinalize( var isEmailTrusted = IsTruthy(isVerifiedString) && string.Equals(externalAccountEmail, email, StringComparison.InvariantCultureIgnoreCase); // Do not allow creation if this external is already linked to a real account. + Guid? replacePendingUserId = null; var existing = await connectionService.GetByProviderExternalIdAsync(provider, auth.ExternalAccountId, cancellationToken); if (existing is not null) { @@ -104,7 +105,8 @@ public async Task OAuthSignupFinalize( if (isEmailTrusted) { // The provider vouches for the new address: replace the pending account with a real one below. - await _accountService.DiscardPendingAccountAsync(existing.UserId, cancellationToken); + // It is only removed if that succeeds, so a taken username leaves the signup to retry with. + replacePendingUserId = existing.UserId; } else { @@ -129,6 +131,7 @@ public async Task OAuthSignupFinalize( auth.ExternalAccountId, auth.ExternalAccountDisplayName ?? auth.ExternalAccountName, isEmailTrusted, + replacePendingUserId, cancellationToken ); diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index a2fd72461..89cfb5123 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -180,28 +180,43 @@ public Task IsEmailRegisteredAsync(string email, CancellationToken cancell private async Task ReleaseEmailFromPendingAccountAsync(string email, bool claimantOwnsEmail, Guid? exceptUserId, CancellationToken cancellationToken) { var pending = await _db.Users - .Include(u => u.UserDeactivation) - .FirstOrDefaultAsync(u => u.Email == email && u.ActivatedAt == null, cancellationToken); + .AsNoTracking() + .Where(u => u.Email == email && u.ActivatedAt == null) + .Select(u => new { u.Id, u.CreatedAt }) + .FirstOrDefaultAsync(cancellationToken); if (pending is null || pending.Id == exceptUserId) return; - if (pending.UserDeactivation is not null || PrivilegedRoles.Any(pending.Roles)) return; - if (!claimantOwnsEmail && pending.CreatedAt > DateTime.UtcNow - Duration.ActivationResendCooldown) return; - _db.Users.Remove(pending); - await _db.SaveChangesAsync(); - } + if (!claimantOwnsEmail) + { + // Counted from the last activation mail, not only from signup: a pending account that just had + // its mail resent would otherwise be replaced by one that mails the same inbox again right away. + var cooldownStart = DateTime.UtcNow - Duration.ActivationResendCooldown; + if (pending.CreatedAt > cooldownStart) return; - /// - public async Task DiscardPendingAccountAsync(Guid userId, CancellationToken cancellationToken = default) - { - var user = await _db.Users - .Include(u => u.UserDeactivation) - .FirstOrDefaultAsync(u => u.Id == userId, cancellationToken); - if (user is null || user.ActivatedAt is not null || user.UserDeactivation is not null || PrivilegedRoles.Any(user.Roles)) return false; + var coalesceKey = EmailOutboxCoalesceKeys.AccountActivation(pending.Id); + if (await _db.EmailOutbox.AnyAsync(m => m.CoalesceKey == coalesceKey && m.CreatedAt >= cooldownStart, cancellationToken)) return; + } - _db.Users.Remove(user); - await _db.SaveChangesAsync(); + await DeletePendingAccountAsync(pending.Id, cancellationToken); + } - return true; + /// + /// Deletes an account only if it is still pending when the delete runs. The condition is part of the + /// statement, so an account that gets activated after the caller looked at it is left alone. + /// Deactivated and privileged accounts are never deleted this way. + /// + /// False when nothing was deleted. + private async Task DeletePendingAccountAsync(Guid userId, CancellationToken cancellationToken) + { + var deleted = await _db.Database.ExecuteSqlAsync($""" + DELETE FROM users AS u + WHERE u.id = {userId} + AND u.activated_at IS NULL + AND NOT (u.roles && {PrivilegedRoles.All}) + AND NOT EXISTS (SELECT 1 FROM user_deactivations AS d WHERE d.deactivated_user_id = u.id) + """, cancellationToken); + + return deleted > 0; } /// @@ -221,6 +236,10 @@ public async Task> Rest if (await IsUserNameBlacklisted(username, cancellationToken) || await IsEmailProviderBlacklisted(email, cancellationToken)) return new AccountWithEmailOrUsernameExists(); + // Releasing another pending account's hold on the address only stands if this correction goes + // through: every return below that does not commit rolls the release back. + await using var transaction = await _db.Database.BeginTransactionAsync(cancellationToken); + await ReleaseEmailFromPendingAccountAsync(email, claimantOwnsEmail: false, exceptUserId: userId, cancellationToken); if (await _db.Users.AnyAsync(u => u.Id != userId && (u.Email == email || u.Name == username), cancellationToken)) @@ -234,14 +253,23 @@ public async Task> Rest // could sign up with an inbox of their own, move the account to somebody else's address and // activate it with the link they already hold. The delivery job mints the new token when it // sends to the new address. - if (emailChanged && user.UserActivationRequest is not null) + if (emailChanged) { - user.UserActivationRequest.TokenHash = SeedTokenHash(); + if (user.UserActivationRequest is not null) + { + user.UserActivationRequest.TokenHash = SeedTokenHash(); + } + + // The same goes for a password reset link requested for the previous address: completing it + // would set a password and activate the account on the new one. Reset rows carry the stamp + // they were created under, so rotating it invalidates them. + user.SecurityStamp = Guid.CreateVersion7(); } try { await _db.SaveChangesAsync(); + await transaction.CommitAsync(cancellationToken); } catch (DbUpdateConcurrencyException) { @@ -270,11 +298,16 @@ public async Task CreateOAuthOnlyAccountAsync( string providerAccountId, string? providerAccountName, bool isEmailTrusted, + Guid? replacePendingUserId, CancellationToken cancellationToken) { email = email.ToLowerInvariant(); provider = provider.ToLowerInvariant(); + // Only a provider that verified the address shows it is the caller's. Mail being disabled (below) + // makes the new account usable without a link, it proves nothing about who owns the address. + var providerVerifiedEmail = isEmailTrusted; + // With mail disabled no activation link can reach the user, so an untrusted email cannot be // verified by any means; activate on creation rather than create a dead account. isEmailTrusted |= !_mailOptions.IsEnabled; @@ -283,17 +316,28 @@ public async Task CreateOAuthOnlyAccountAsync( if (await IsUserNameBlacklisted(username, cancellationToken) || await IsEmailProviderBlacklisted(email, cancellationToken)) return new AccountWithEmailOrUsernameExists(); - // A provider-verified address belongs to this caller, so a pending account someone parked on it goes. - await ReleaseEmailFromPendingAccountAsync(email, claimantOwnsEmail: isEmailTrusted, exceptUserId: null, cancellationToken); - - // Fast uniqueness check (optimistic; race handled by unique constraints below) - var exists = await _db.Users.AnyAsync(u => u.Email == email || u.Name == username, cancellationToken); - if (exists) return new AccountWithEmailOrUsernameExists(); - - await using var tx = await _db.Database.BeginTransactionAsync(); + // Pending accounts removed to make room only stay removed if the new account is created: every + // return below that does not commit rolls them back. + await using var tx = await _db.Database.BeginTransactionAsync(cancellationToken); try { + if (replacePendingUserId is not null) + { + await DeletePendingAccountAsync(replacePendingUserId.Value, cancellationToken); + + // The caller looked that account up through this context, and its OAuth connection has the + // key the new one is about to get. Nothing is tracked yet that this method needs. + _db.ChangeTracker.Clear(); + } + + // A provider-verified address belongs to this caller, so a pending account someone parked on it goes. + await ReleaseEmailFromPendingAccountAsync(email, claimantOwnsEmail: providerVerifiedEmail, exceptUserId: null, cancellationToken); + + // Fast uniqueness check (optimistic; race handled by unique constraints below) + var exists = await _db.Users.AnyAsync(u => u.Email == email || u.Name == username, cancellationToken); + if (exists) return new AccountWithEmailOrUsernameExists(); + var creationTime = DateTime.UtcNow; var user = new User @@ -813,10 +857,22 @@ await _auditService.LogAsync( ); } + // Whoever was signed in with the old password is signed out. Sessions live in Redis, outside this + // transaction, so they go first: if that fails nothing is committed and the link can be used again, + // rather than the reset succeeding with the old sessions left alive and no way to retry. + await _sessionService.DeleteSessionsByUserIdAsync(reset.Reset.UserId); + await transaction.CommitAsync(); - // Whoever was signed in with the old password is signed out. - await _sessionService.DeleteSessionsByUserIdAsync(reset.Reset.UserId); + // A sign-in with the old password may have slipped in between the two steps above. + try + { + await _sessionService.DeleteSessionsByUserIdAsync(reset.Reset.UserId); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to re-check sessions after password reset for user ID: [{Id}]", reset.Reset.UserId); + } return new Success(); } diff --git a/API/Services/Account/IAccountService.cs b/API/Services/Account/IAccountService.cs index f61124b6e..32f96f368 100644 --- a/API/Services/Account/IAccountService.cs +++ b/API/Services/Account/IAccountService.cs @@ -30,9 +30,14 @@ public interface IAccountService /// external subject/id from provider /// display name from provider /// + /// + /// A never activated account this same external identity signed up earlier, to be replaced by the new + /// one. Only pass this for a caller who just signed in with that identity. It is deleted in the same + /// transaction that creates the new account, so a conflict leaves it as it was. + /// /// /// Success with the created user, or AccountWithEmailOrUsernameExists when taken/blocked. - Task CreateOAuthOnlyAccountAsync(string email, string username, string provider, string providerAccountId, string? providerAccountName, bool isEmailTrusted, CancellationToken cancellationToken = default); + Task CreateOAuthOnlyAccountAsync(string email, string username, string provider, string providerAccountId, string? providerAccountName, bool isEmailTrusted, Guid? replacePendingUserId = null, CancellationToken cancellationToken = default); /// /// Returns true if the given email belongs to an activated account. A never activated account is only @@ -40,13 +45,6 @@ public interface IAccountService /// Task IsEmailRegisteredAsync(string email, CancellationToken cancellationToken = default); - /// - /// Deletes a never activated account. Only call this for a caller who proved they hold its credential - /// (signed in with its linked OAuth identity) and is replacing it. - /// - /// False when there is no such pending account. - Task DiscardPendingAccountAsync(Guid userId, CancellationToken cancellationToken = default); - /// /// Lets the creator of a never activated account correct what they signed up with (typically a mistyped /// email) and sends the activation email to the new address. Only call this for a caller who proved they diff --git a/API/Services/OAuthConnection/IOAuthConnectionService.cs b/API/Services/OAuthConnection/IOAuthConnectionService.cs index 993ca1c61..fe29bf5e9 100644 --- a/API/Services/OAuthConnection/IOAuthConnectionService.cs +++ b/API/Services/OAuthConnection/IOAuthConnectionService.cs @@ -12,5 +12,18 @@ public interface IOAuthConnectionService Task ConnectionExistsAsync(string provider, string providerAccountId, CancellationToken cancellationToken = default); Task HasConnectionAsync(Guid userId, string provider, CancellationToken cancellationToken = default); Task TryAddConnectionAsync(Guid userId, string provider, string providerAccountId, string? providerAccountName, Guid? actorId, CancellationToken cancellationToken = default); - Task TryRemoveConnectionAsync(Guid userId, string provider, Guid? actorId, CancellationToken cancellationToken = default); + + /// + /// Removes the connection of the user to , unless it is the only way left to + /// sign in to the account (no password and no other connection). Removals for one user run one at a + /// time, so two of them cannot each count the connection the other is removing as the one that remains. + /// + Task RemoveConnectionAsync(Guid userId, string provider, Guid? actorId, CancellationToken cancellationToken = default); +} + +public enum RemoveConnectionResult +{ + Removed, + NotFound, + LastLoginMethod } diff --git a/API/Services/OAuthConnection/OAuthConnectionService.cs b/API/Services/OAuthConnection/OAuthConnectionService.cs index 0d0b779b2..921c73e5b 100644 --- a/API/Services/OAuthConnection/OAuthConnectionService.cs +++ b/API/Services/OAuthConnection/OAuthConnectionService.cs @@ -83,19 +83,35 @@ await _auditService.LogAsync( return true; } - public async Task TryRemoveConnectionAsync(Guid userId, string provider, Guid? actorId, CancellationToken cancellationToken) + public async Task RemoveConnectionAsync(Guid userId, string provider, Guid? actorId, CancellationToken cancellationToken) { var p = provider.ToLowerInvariant(); - - await using var transaction = await _db.Database.BeginTransactionAsync(); - + + await using var transaction = await _db.Database.BeginTransactionAsync(cancellationToken); + + // Lock the user row until commit: the check below and the delete are then one step per user. + await _db.Database.ExecuteSqlAsync($"SELECT 1 FROM users WHERE id = {userId} FOR UPDATE", cancellationToken); + + // An account without a password signs in through its connections only. Removing the last one would + // lock its owner out until they notice and go through a password reset. + var hasPassword = await _db.Users.AnyAsync(u => u.Id == userId && u.PasswordHash != null && u.PasswordHash != "", cancellationToken); + if (!hasPassword) + { + var hasOtherConnection = await _db.UserOAuthConnections.AnyAsync(c => c.UserId == userId && c.ProviderKey != p, cancellationToken); + if (!hasOtherConnection) + { + var hasThisConnection = await _db.UserOAuthConnections.AnyAsync(c => c.UserId == userId && c.ProviderKey == p, cancellationToken); + return hasThisConnection ? RemoveConnectionResult.LastLoginMethod : RemoveConnectionResult.NotFound; + } + } + var nDeleted = await _db.UserOAuthConnections .Where(c => c.UserId == userId && c.ProviderKey == p) - .ExecuteDeleteAsync(); - + .ExecuteDeleteAsync(cancellationToken); + // Nothing was linked, so don't record a disconnection that never happened. // Disposing the transaction without committing rolls back the (no-op) delete. - if (nDeleted <= 0) return false; + if (nDeleted <= 0) return RemoveConnectionResult.NotFound; await _auditService.LogAsync( userId, @@ -103,9 +119,9 @@ await _auditService.LogAsync( actorId: actorId ?? userId, metadata: new OAuthDisconnectedMetadata(provider) ); - - await transaction.CommitAsync(); - return true; + await transaction.CommitAsync(cancellationToken); + + return RemoveConnectionResult.Removed; } } diff --git a/Common/Authentication/ActivationResendCookie.cs b/Common/Authentication/ActivationResendCookie.cs index 38eafbe87..c1dfaa088 100644 --- a/Common/Authentication/ActivationResendCookie.cs +++ b/Common/Authentication/ActivationResendCookie.cs @@ -7,9 +7,10 @@ namespace OpenShock.Common.Authentication; /// -/// Cookie set on signup when the new account still needs activation. It lets the browser that created the account -/// ask for the activation email again ("didn't get the email?") without typing an address, so the resend endpoint -/// can't be aimed at arbitrary inboxes or used to probe which emails are registered. +/// Cookie set while this browser has a signup waiting for activation: when it creates the account, and again when +/// an OAuth signup is restarted with corrected details. It lets that browser ask for the activation email again +/// ("didn't get the email?") without typing an address, so the resend endpoint can't be aimed at arbitrary inboxes +/// or used to probe which emails are registered. The cookie alone is enough for a (rate limited) resend. /// /// /// The value is a time-limited data protection payload holding the user id (keys are persisted to the database, diff --git a/Common/Hubs/RevalidateAuthenticationHubFilter.cs b/Common/Hubs/RevalidateAuthenticationHubFilter.cs index 2c3615f20..701530074 100644 --- a/Common/Hubs/RevalidateAuthenticationHubFilter.cs +++ b/Common/Hubs/RevalidateAuthenticationHubFilter.cs @@ -66,11 +66,15 @@ private static async Task IsStillAuthenticated(HubInvocationContext invoca { if (context.GetHttpContext() is not { } httpContext || !httpContext.TryGetUserSessionToken(out var sessionToken)) return false; - // Sessions are deleted on logout, on deactivation and on a password reset, so existence is the check. + // Sessions are deleted on logout, on deactivation and on a password reset. var sessionService = invocationContext.ServiceProvider.GetRequiredService(); var session = await sessionService.GetSessionByTokenAsync(sessionToken); + if (session is null || session.UserId != identity.GetClaimValueAsGuid(ClaimTypes.NameIdentifier)) return false; - return session is not null && session.UserId == identity.GetClaimValueAsGuid(ClaimTypes.NameIdentifier); + // That deletion happens in Redis after the database commit and can fail, leaving the session + // behind. The account itself is the authority, as it is when a session authenticates a request. + var db = invocationContext.ServiceProvider.GetRequiredService(); + return await db.Users.AnyAsync(u => u.Id == session.UserId && u.ActivatedAt != null && u.UserDeactivation == null, context.ConnectionAborted); } return true; From e428b3d176490bcbaf466c965641c827055b6c8e Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Thu, 26 Nov 2026 21:14:14 +0100 Subject: [PATCH 06/14] refactor: let StartOAuth decide which flows carry the activation token --- API/Controller/OAuth/Authorize.cs | 2 +- API/OAuth/OAuthUtil.cs | 5 +++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/API/Controller/OAuth/Authorize.cs b/API/Controller/OAuth/Authorize.cs index 6993b08dc..c9cd7d5d7 100644 --- a/API/Controller/OAuth/Authorize.cs +++ b/API/Controller/OAuth/Authorize.cs @@ -41,6 +41,6 @@ public async Task OAuthAuthorize([FromRoute] string provider, [Fr return Problem(OAuthError.UnsupportedFlow); } - return OAuthUtil.StartOAuth(provider, flow, flow == OAuthFlow.LoginOrCreate ? activationToken : null); + return OAuthUtil.StartOAuth(provider, flow, activationToken); } } diff --git a/API/OAuth/OAuthUtil.cs b/API/OAuth/OAuthUtil.cs index d59e3e609..f7e7beee1 100644 --- a/API/OAuth/OAuthUtil.cs +++ b/API/OAuth/OAuthUtil.cs @@ -9,7 +9,8 @@ public static class OAuthUtil /// /// /// Token from the activation email, carried through the provider round trip so the handoff can - /// activate the account the returned identity is linked to. + /// activate the account the returned identity is linked to. Only a + /// flow carries it: linking is for an account that is already signed in and never activates anything. /// public static ChallengeResult StartOAuth(string provider, OAuthFlow flow, string? activationToken = null) { @@ -19,7 +20,7 @@ public static ChallengeResult StartOAuth(string provider, OAuthFlow flow, string Items = { { OAuthConstants.ItemKeyFlowType, flow.ToString() } } }; - if (!string.IsNullOrEmpty(activationToken)) + if (flow == OAuthFlow.LoginOrCreate && !string.IsNullOrEmpty(activationToken)) { properties.Items[OAuthConstants.ItemKeyActivationToken] = activationToken; } From de7d668f1e2821258fc706f5228f9a926d8401bb Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Thu, 26 Nov 2026 21:45:38 +0100 Subject: [PATCH 07/14] feat: close hub connections when their session or API token is revoked Revocations are announced on Redis and the instance holding an affected UserHub connection closes it right away: deleted and expired sessions, deactivated or deleted accounts, and deleted API tokens. An edited token makes its connections read it again on their next call. The database check before hub method calls is now a fallback that runs once per minute per connection, plus once when a connection opens, instead of on every call. --- .../Tests/SignalRUserHubTests.cs | 106 ++++++++++++- API.IntegrationTests/WebApplicationFactory.cs | 8 + API/Realtime/RedisSubscriberService.cs | 64 ++++++++ API/Services/Account/AccountService.cs | 21 +++ Common/Hubs/HubConnectionTracker.cs | 139 ++++++++++++++++++ .../Hubs/RevalidateAuthenticationHubFilter.cs | 94 ++++++++++-- Common/OpenShockServiceHelper.cs | 4 + .../Services/RedisPubSub/IRedisPubService.cs | 13 ++ Common/Services/RedisPubSub/RedisChannels.cs | 17 +++ .../Services/RedisPubSub/RedisPubService.cs | 10 ++ Common/Services/Session/SessionService.cs | 34 ++++- 11 files changed, 487 insertions(+), 23 deletions(-) create mode 100644 Common/Hubs/HubConnectionTracker.cs diff --git a/API.IntegrationTests/Tests/SignalRUserHubTests.cs b/API.IntegrationTests/Tests/SignalRUserHubTests.cs index 9672e6c44..c5c85f664 100644 --- a/API.IntegrationTests/Tests/SignalRUserHubTests.cs +++ b/API.IntegrationTests/Tests/SignalRUserHubTests.cs @@ -6,6 +6,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.API.Services.Account; using OpenShock.Common.Constants; using OpenShock.Common.OpenShockDb; using OpenShock.Common.Services.Session; @@ -106,7 +107,88 @@ public async Task PublicShareHub_Negotiate_WithoutAuth_ReturnsOk() await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); } - // --- An open connection stops working once its session or API token is no longer valid --- + // --- A revocation closes the open connections it concerns right away, without them calling anything --- + + [Test] + public async Task Logout_ClosesTheSessionsOpenConnection() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkicklogout"), TestHelper.UniqueEmail("hubkicklogout"), "SecurePassword123#"); + var other = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkickother"), TestHelper.UniqueEmail("hubkickother"), "SecurePassword123#"); + await using var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); + await using var otherConnection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={other.SessionToken}"); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + await scope.ServiceProvider.GetRequiredService().DeleteSessionByTokenAsync(user.SessionToken); + } + + await AssertConnectionClosesAsync(connection); + + // Nobody else is affected. + await otherConnection.InvokeAsync("Reboot", Guid.CreateVersion7()); + await Assert.That(otherConnection.State).IsEqualTo(HubConnectionState.Connected); + } + + [Test] + public async Task DeletingAnApiToken_ClosesItsOpenConnection() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkicktoken"), TestHelper.UniqueEmail("hubkicktoken"), "SecurePassword123#"); + var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-kick-deleted"); + var (_, otherRawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-kick-kept"); + await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); + await using var otherConnection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, otherRawToken); + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var response = await client.DeleteAsync($"/1/tokens/{tokenId}"); + await Assert.That(response.IsSuccessStatusCode).IsTrue(); + + await AssertConnectionClosesAsync(connection); + + await otherConnection.InvokeAsync("Reboot", Guid.CreateVersion7()); + await Assert.That(otherConnection.State).IsEqualTo(HubConnectionState.Connected); + } + + [Test] + public async Task DeactivatingAnAccount_ClosesItsSessionAndApiTokenConnections() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkickdeact"), TestHelper.UniqueEmail("hubkickdeact"), "SecurePassword123#"); + var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-kick-deactivated"); + await using var sessionConnection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); + await using var tokenConnection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var accountService = scope.ServiceProvider.GetRequiredService(); + await accountService.DeactivateAccountAsync(user.Id, user.Id, deleteLater: false); + } + + await AssertConnectionClosesAsync(sessionConnection); + await AssertConnectionClosesAsync(tokenConnection); + } + + // --- The fallback: a connection whose revocation was never announced stops at its next periodic check --- + + [Test] + public async Task Invoke_ManyCallsInARow_ChecksTheApiTokenOncePerInterval() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevalcache"), TestHelper.UniqueEmail("hubrevalcache"), "SecurePassword123#"); + var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-cached"); + await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + await db.ApiTokens.Where(t => t.Id == tokenId).ExecuteDeleteAsync(); + } + + // Straight after the check above, the deleted token is not looked up again: the call goes through. + // (It would be rejected, and the connection closed, if every call queried the database.) + await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); + + await AssertInvokeFailsAndConnectionClosesAsync(connection); + } [Test] public async Task Invoke_WithValidSession_KeepsWorking() @@ -257,12 +339,9 @@ private async Task ConnectAsync(string headerName, string headerV private static async Task AssertInvokeFailsAndConnectionClosesAsync(HubConnection connection) { - var closed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - connection.Closed += _ => - { - closed.TrySetResult(); - return Task.CompletedTask; - }; + // The connection was checked moments ago and that result is kept for the interval, so the + // revocation only reaches it on the first call after that. + await Task.Delay(WebApplicationFactory.HubRevalidationInterval + TimeSpan.FromMilliseconds(500)); // The server answers with an error and aborts; which of the two the client sees first is a race. Exception? failure = null; @@ -277,7 +356,18 @@ private static async Task AssertInvokeFailsAndConnectionClosesAsync(HubConnectio await Assert.That(failure).IsNotNull(); - await closed.Task.WaitAsync(TimeSpan.FromSeconds(30)); + await AssertConnectionClosesAsync(connection); + } + + /// Waits for the server to close the connection, without calling anything on it. + private static async Task AssertConnectionClosesAsync(HubConnection connection) + { + var deadline = DateTime.UtcNow.AddSeconds(30); + while (connection.State != HubConnectionState.Disconnected && DateTime.UtcNow < deadline) + { + await Task.Delay(50); + } + await Assert.That(connection.State).IsEqualTo(HubConnectionState.Disconnected); } } diff --git a/API.IntegrationTests/WebApplicationFactory.cs b/API.IntegrationTests/WebApplicationFactory.cs index 84ec5107d..b10c5dc11 100644 --- a/API.IntegrationTests/WebApplicationFactory.cs +++ b/API.IntegrationTests/WebApplicationFactory.cs @@ -9,6 +9,7 @@ using Microsoft.Extensions.Options; using OpenShock.API.IntegrationTests.Docker; using OpenShock.API.IntegrationTests.HttpMessageHandlers; +using OpenShock.Common.Hubs; using Serilog; using Serilog.Events; @@ -26,6 +27,9 @@ public class WebApplicationFactory : WebApplicationFactory [ClassDataSource(Shared = SharedType.PerTestSession)] public required InMemoryRedis Redis { get; init; } + /// How long an open hub connection can go on after its session or API token was revoked, in tests. + public static readonly TimeSpan HubRevalidationInterval = TimeSpan.FromSeconds(1); + protected override void ConfigureClient(HttpClient client) { base.ConfigureClient(client); @@ -103,6 +107,10 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) { services.AddTransient(); + // Hub connections re-check their session or API token at most once per interval. Kept short so + // the tests that revoke one do not have to wait out the production interval. + services.Configure(options => options.Interval = HubRevalidationInterval); + // Disable rate limiting for integration tests so auth-endpoint tests // don't interfere with each other (10 req/min is too restrictive for test suites). // Rate limiter behavior is covered by dedicated unit tests. diff --git a/API/Realtime/RedisSubscriberService.cs b/API/Realtime/RedisSubscriberService.cs index 6351d50d7..4c2c09021 100644 --- a/API/Realtime/RedisSubscriberService.cs +++ b/API/Realtime/RedisSubscriberService.cs @@ -21,6 +21,7 @@ public sealed class RedisSubscriberService : IHostedService, IAsyncDisposable private readonly IHubContext _hubContext; private readonly IDbContextFactory _dbContextFactory; private readonly IRedisConnectionProvider _redisConnectionProvider; + private readonly HubConnectionTracker _hubConnections; private readonly ISubscriber _subscriber; private readonly ILogger _logger; @@ -31,18 +32,21 @@ public sealed class RedisSubscriberService : IHostedService, IAsyncDisposable /// /// /// + /// The hub connections open on this instance, closed here when what they authenticated with is revoked. /// public RedisSubscriberService( IConnectionMultiplexer connectionMultiplexer, IHubContext hubContext, IDbContextFactory dbContextFactory, IRedisConnectionProvider redisConnectionProvider, + HubConnectionTracker hubConnections, ILogger logger ) { _hubContext = hubContext; _dbContextFactory = dbContextFactory; _redisConnectionProvider = redisConnectionProvider; + _hubConnections = hubConnections; _subscriber = connectionMultiplexer.GetSubscriber(); _logger = logger; } @@ -52,6 +56,61 @@ public async Task StartAsync(CancellationToken cancellationToken) { await _subscriber.SubscribeAsync(RedisChannels.KeyEventExpired, HandleKeyExpired); await _subscriber.SubscribeAsync(RedisChannels.DeviceStatus, HandleDeviceStatus); + await _subscriber.SubscribeAsync(RedisChannels.SessionRevoked, HandleSessionRevoked); + await _subscriber.SubscribeAsync(RedisChannels.UserAuthRevoked, HandleUserAuthRevoked); + await _subscriber.SubscribeAsync(RedisChannels.ApiTokenUpdateAll, HandleApiTokenUpdate); + } + + private void HandleSessionRevoked(RedisChannel _, RedisValue message) + { + var sessionId = (string?)message; + if (string.IsNullOrEmpty(sessionId)) return; + + var closed = _hubConnections.AbortSession(sessionId); + if (closed > 0) _logger.LogDebug("Closed {Count} hub connection(s) of a deleted session", closed); + } + + private void HandleUserAuthRevoked(RedisChannel _, RedisValue message) + { + if (!Guid.TryParse((string?)message, out var userId)) return; + + var closed = _hubConnections.AbortUser(userId); + if (closed > 0) _logger.LogDebug("Closed {Count} hub connection(s) of user [{UserId}]", closed, userId); + } + + private void HandleApiTokenUpdate(RedisChannel channel, RedisValue _) + { + var channelName = (string?)channel; + if (channelName is null || !channelName.StartsWith(RedisChannels.ApiTokenUpdatePrefix, StringComparison.Ordinal)) return; + if (!Guid.TryParse(channelName.AsSpan(RedisChannels.ApiTokenUpdatePrefix.Length), out var tokenId)) return; + + // Most token changes concern no connection on this instance: no database round trip for those. + if (!_hubConnections.HasApiTokenConnections(tokenId)) return; + + OsTask.Run(() => ApplyApiTokenUpdate(tokenId)); + } + + /// + /// The same channel announces an edit and a deletion, so look: a token that is gone closes its + /// connections, one that changed makes them read it again on their next call. + /// + private async Task ApplyApiTokenUpdate(Guid tokenId) + { + await using var db = await _dbContextFactory.CreateDbContextAsync(); + + var stillValid = await db.ApiTokens.AnyAsync(x => + x.Id == tokenId && + (x.ValidUntil == null || x.ValidUntil >= DateTime.UtcNow) && + x.User.UserDeactivation == null); + + if (stillValid) + { + _hubConnections.InvalidateApiToken(tokenId); + return; + } + + var closed = _hubConnections.AbortApiToken(tokenId); + _logger.LogDebug("Closed {Count} hub connection(s) of revoked API token [{TokenId}]", closed, tokenId); } private void HandleKeyExpired(RedisChannel _, RedisValue message) @@ -94,6 +153,11 @@ private void HandleKeyExpired(RedisChannel _, RedisValue message) OsTask.Run(() => LogicDeviceOnlineStatus(id)); } + else if (typeNameSpan.SequenceEqual(typeof(LoginSession).FullName)) + { + // A session that reached its lifetime: same as a deleted one for the connections using it. + _hubConnections.AbortSession(guidSpan.ToString()); + } } private void HandleDeviceStatus(RedisChannel _, RedisValue value) diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index 89cfb5123..e60fd40c1 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -76,6 +76,23 @@ private async Task NotifyEmailOutboxAsync() } } + /// + /// Tells every instance the account may no longer be used, so its open connections are closed, the ones + /// that authenticated with an API token included. Deliberately swallows failures: the change is already + /// committed, and a connection that misses the message is caught by its next periodic check. + /// + private async Task NotifyUserAuthRevokedAsync(Guid userId) + { + try + { + await _redisPubService.SendUserAuthRevoked(userId); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to announce revoked access for user ID: [{Id}]; open connections close on their next check", userId); + } + } + private Task IsUserNameBlacklisted(string username, CancellationToken cancellationToken) => _db.UserNameBlacklists.Matching(username).AnyAsync(cancellationToken); @@ -587,6 +604,8 @@ await _auditService.LogAsync( await transaction.CommitAsync(); } + await NotifyUserAuthRevokedAsync(userId); + // Remove all login sessions await _sessionService.DeleteSessionsByUserIdAsync(userId); @@ -677,6 +696,8 @@ await _auditService.LogAsync( await transaction.CommitAsync(); + await NotifyUserAuthRevokedAsync(userId); + return new Success(); } diff --git a/Common/Hubs/HubConnectionTracker.cs b/Common/Hubs/HubConnectionTracker.cs new file mode 100644 index 000000000..d4d2a7634 --- /dev/null +++ b/Common/Hubs/HubConnectionTracker.cs @@ -0,0 +1,139 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using Microsoft.AspNetCore.SignalR; +using OpenShock.Common.Authentication; +using OpenShock.Common.Constants; +using OpenShock.Common.Extensions; +using OpenShock.Common.Utils; + +namespace OpenShock.Common.Hubs; + +/// +/// The authenticated hub connections open on this instance, by what they authenticated with. Lets a +/// revocation that arrives over Redis close the affected connections right away, instead of each connection +/// finding out the next time it asks the database (see ). +/// +/// +/// Local to the process: every instance tracks its own connections and reacts to the same Redis message. +/// Lookups scan all connections, which is fine for how rarely sessions and tokens are revoked. +/// +public sealed class HubConnectionTracker +{ + private readonly ConcurrentDictionary _connections = new(); + + public TrackedHubConnection? Get(string connectionId) + => _connections.GetValueOrDefault(connectionId); + + /// Starts tracking a connection. Anonymous connections hold nothing that can be revoked and are skipped. + /// The tracked connection, or null when it was skipped. + public TrackedHubConnection? Track(HubCallerContext context) + { + var user = context.User; + if (user is null) return null; + + Guid? userId = Guid.TryParse(context.UserIdentifier, out var parsedUserId) ? parsedUserId : null; + + if (user.HasOpenShockApiTokenIdentity()) + { + if (!user.TryGetClaimValueAsGuid(OpenShockAuthClaims.ApiTokenId, out var tokenId)) return null; + + return _connections[context.ConnectionId] = new TrackedHubConnection(context, userId, sessionId: null, tokenId); + } + + if (user.TryGetOpenShockUserIdentity() is not null + && context.GetHttpContext() is { } httpContext + && httpContext.TryGetUserSessionToken(out var sessionToken)) + { + return _connections[context.ConnectionId] = new TrackedHubConnection(context, userId, GetSessionId(sessionToken), apiTokenId: null); + } + + return null; + } + + public void Untrack(string connectionId) => _connections.TryRemove(connectionId, out _); + + /// Closes the connections that authenticated with this session. + /// The id the session is stored under, see . + /// How many connections were closed. + public int AbortSession(string sessionId) => Abort(c => c.SessionId == sessionId); + + /// Closes every connection of this user, whatever it authenticated with. + /// How many connections were closed. + public int AbortUser(Guid userId) => Abort(c => c.UserId == userId); + + /// Closes the connections that authenticated with this API token. + /// How many connections were closed. + public int AbortApiToken(Guid tokenId) => Abort(c => c.ApiTokenId == tokenId); + + public bool HasApiTokenConnections(Guid tokenId) + { + foreach (var connection in _connections.Values) + { + if (connection.ApiTokenId == tokenId) return true; + } + + return false; + } + + /// + /// Makes the connections using this API token read it from the database again on their next call, so a + /// change to its permissions, pause state or limits applies from then on. + /// + public void InvalidateApiToken(Guid tokenId) + { + foreach (var connection in _connections.Values) + { + if (connection.ApiTokenId == tokenId) connection.Invalidate(); + } + } + + /// The id a session is stored under in Redis: the hash of its token (old tokens are stored as they are). + public static string GetSessionId(string sessionToken) + => sessionToken.Length == AuthConstants.GeneratedTokenLength ? HashingUtils.HashToken(sessionToken) : sessionToken; + + private int Abort(Func predicate) + { + var aborted = 0; + foreach (var (connectionId, connection) in _connections) + { + if (!predicate(connection)) continue; + + // Dropped here as well as on disconnect, so a message that arrives twice finds nothing. + _connections.TryRemove(connectionId, out _); + connection.Context.Abort(); + aborted++; + } + + return aborted; + } +} + +public sealed class TrackedHubConnection +{ + // 0 means "not validated": Stopwatch timestamps are never 0 in practice, and a false "not validated" + // only costs one extra check. + private long _lastValidated; + + public TrackedHubConnection(HubCallerContext context, Guid? userId, string? sessionId, Guid? apiTokenId) + { + Context = context; + UserId = userId; + SessionId = sessionId; + ApiTokenId = apiTokenId; + } + + public HubCallerContext Context { get; } + public Guid? UserId { get; } + public string? SessionId { get; } + public Guid? ApiTokenId { get; } + + public bool WasValidatedWithin(TimeSpan interval) + { + var last = Volatile.Read(ref _lastValidated); + return last != 0 && Stopwatch.GetElapsedTime(last) < interval; + } + + public void MarkValidated() => Volatile.Write(ref _lastValidated, Stopwatch.GetTimestamp()); + + public void Invalidate() => Volatile.Write(ref _lastValidated, 0); +} diff --git a/Common/Hubs/RevalidateAuthenticationHubFilter.cs b/Common/Hubs/RevalidateAuthenticationHubFilter.cs index 701530074..f8d6da285 100644 --- a/Common/Hubs/RevalidateAuthenticationHubFilter.cs +++ b/Common/Hubs/RevalidateAuthenticationHubFilter.cs @@ -1,6 +1,7 @@ using System.Security.Claims; using Microsoft.AspNetCore.SignalR; using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; using OpenShock.Common.Authentication; using OpenShock.Common.Extensions; using OpenShock.Common.OpenShockDb; @@ -9,8 +10,7 @@ namespace OpenShock.Common.Hubs; /// -/// Re-checks, before every hub method call, that the session or API token a connection authenticated with is -/// still valid, and aborts the connection when it is not. +/// Keeps an open hub connection from outliving the session or API token it authenticated with. /// /// /// SignalR authenticates a connection once, when it opens, and then keeps it for as long as the client likes. @@ -18,28 +18,84 @@ namespace OpenShock.Common.Hubs; /// connections: an open one could keep calling, and whatever calls it already had queued would still run. /// Aborting also discards those queued calls. /// +/// Two things end a connection. The fast one is a Redis message: revocations are published, and the instance +/// holding the connection closes it right away (the filter registers every connection with +/// for that). The slow one is the check in this filter, which asks the +/// database before a hub method call. It exists for what the messages cannot cover, a message that was lost +/// or a token that simply reached its expiry, so it only runs once per +/// per connection, and never for an idle one. +/// +/// /// For an API token the row read here is handed to the hub method through -/// , so permissions, pause state and control limits -/// are the current ones rather than the ones from connect time. +/// . A change to the token invalidates the +/// connection's last check, so its permissions, pause state and control limits are read again on the next call. /// /// public sealed class RevalidateAuthenticationHubFilter : IHubFilter { + private readonly HubConnectionTracker _tracker; + private readonly IOptions _options; + + public RevalidateAuthenticationHubFilter(HubConnectionTracker tracker, IOptions options) + { + _tracker = tracker; + _options = options; + } + + /// + public async Task OnConnectedAsync(HubLifetimeContext context, Func next) + { + var tracked = _tracker.Track(context.Context); + + // The connection was authenticated before it was tracked. A revocation announced in between found + // nothing to close, so look once now that announcements can reach it. + if (tracked is not null) + { + if (!await IsStillAuthenticated(context.Context, context.ServiceProvider)) + { + _tracker.Untrack(context.Context.ConnectionId); + context.Context.Abort(); + return; + } + + tracked.MarkValidated(); + } + + await next(context); + } + + /// + public Task OnDisconnectedAsync(HubLifetimeContext context, Exception? exception, Func next) + { + _tracker.Untrack(context.Context.ConnectionId); + return next(context, exception); + } + /// public async ValueTask InvokeMethodAsync(HubInvocationContext invocationContext, Func> next) { - if (!await IsStillAuthenticated(invocationContext)) + var context = invocationContext.Context; + + // Untracked means anonymous (nothing to check), or a connection a revocation already closed whose + // queued calls are still draining: the check below turns those away. + var tracked = _tracker.Get(context.ConnectionId); + + if (tracked is null || !tracked.WasValidatedWithin(_options.Value.Interval)) { - invocationContext.Context.Abort(); - throw new HubException("Authentication is no longer valid"); + if (!await IsStillAuthenticated(context, invocationContext.ServiceProvider)) + { + context.Abort(); + throw new HubException("Authentication is no longer valid"); + } + + tracked?.MarkValidated(); } return await next(invocationContext); } - private static async Task IsStillAuthenticated(HubInvocationContext invocationContext) + private static async Task IsStillAuthenticated(HubCallerContext context, IServiceProvider services) { - var context = invocationContext.Context; var user = context.User; // Anonymous connection (a public share guest): nothing was granted that could have been revoked. @@ -49,7 +105,7 @@ private static async Task IsStillAuthenticated(HubInvocationContext invoca { if (!user.TryGetClaimValueAsGuid(OpenShockAuthClaims.ApiTokenId, out var tokenId)) return false; - var db = invocationContext.ServiceProvider.GetRequiredService(); + var db = services.GetRequiredService(); var token = await db.ApiTokens .AsNoTracking() .FirstOrDefaultAsync(x => @@ -67,13 +123,13 @@ private static async Task IsStillAuthenticated(HubInvocationContext invoca if (context.GetHttpContext() is not { } httpContext || !httpContext.TryGetUserSessionToken(out var sessionToken)) return false; // Sessions are deleted on logout, on deactivation and on a password reset. - var sessionService = invocationContext.ServiceProvider.GetRequiredService(); + var sessionService = services.GetRequiredService(); var session = await sessionService.GetSessionByTokenAsync(sessionToken); if (session is null || session.UserId != identity.GetClaimValueAsGuid(ClaimTypes.NameIdentifier)) return false; // That deletion happens in Redis after the database commit and can fail, leaving the session // behind. The account itself is the authority, as it is when a session authenticates a request. - var db = invocationContext.ServiceProvider.GetRequiredService(); + var db = services.GetRequiredService(); return await db.Users.AnyAsync(u => u.Id == session.UserId && u.ActivatedAt != null && u.UserDeactivation == null, context.ConnectionAborted); } @@ -81,13 +137,23 @@ private static async Task IsStillAuthenticated(HubInvocationContext invoca } } +public sealed class HubRevalidationOptions +{ + /// + /// How long a connection's last successful database check stays good. Revocations normally close a + /// connection at once through Redis; this bounds how long one can go on when that message was lost, or + /// when an API token expired on its own. + /// + public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(1); +} + public static class HubCallerContextExtensions { internal static readonly object CurrentApiTokenKey = new(); /// - /// The API token this connection authenticated with, as it is in the database at the time of the current - /// call. Null for a session or anonymous connection, and outside of a hub method call. + /// The API token this connection authenticated with, as it was in the database when the connection was + /// last checked. Null for a session or anonymous connection. /// public static ApiToken? GetCurrentApiToken(this HubCallerContext context) => context.Items.TryGetValue(CurrentApiTokenKey, out var token) ? token as ApiToken : null; diff --git a/Common/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index 52604e25d..4c3ad170b 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -479,6 +479,10 @@ await context.HttpContext.Response.WriteAsync("Too Many Requests. Please try aga public static IServiceCollection AddOpenShockSignalR(this IServiceCollection services, ConfigurationOptions redisConfig) { + services.AddOptions(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSignalR(options => Microsoft.AspNetCore.SignalR.HubOptionsExtensions.AddFilter(options)) .AddOpenShockStackExchangeRedis(options => { options.Configuration = redisConfig; }) .AddJsonProtocol(options => diff --git a/Common/Services/RedisPubSub/IRedisPubService.cs b/Common/Services/RedisPubSub/IRedisPubService.cs index 8e308f395..982433e9c 100644 --- a/Common/Services/RedisPubSub/IRedisPubService.cs +++ b/Common/Services/RedisPubSub/IRedisPubService.cs @@ -20,6 +20,19 @@ public interface IRedisPubService /// Task SendApiTokenUpdate(Guid tokenId); + /// + /// A login session was deleted. Notifies every instance so open connections that authenticated with it + /// are closed. Best-effort: a connection that misses it is caught by its next periodic check. + /// + /// The id the session was stored under. + Task SendSessionRevoked(string sessionId); + + /// + /// The account was deactivated or deleted. Notifies every instance so all open connections of the user + /// are closed, including ones that authenticated with an API token. + /// + Task SendUserAuthRevoked(Guid userId); + /// /// Notifies the email outbox consumer that one or more messages were just enqueued, so it drains /// them without waiting for its next safety-net poll. Best-effort: a lost notification only delays diff --git a/Common/Services/RedisPubSub/RedisChannels.cs b/Common/Services/RedisPubSub/RedisChannels.cs index d0df75bd5..53de95e72 100644 --- a/Common/Services/RedisPubSub/RedisChannels.cs +++ b/Common/Services/RedisPubSub/RedisChannels.cs @@ -12,6 +12,23 @@ public static class RedisChannels public static RedisChannel ApiTokenUpdate(Guid tokenId) => new($"api-token-update:{tokenId}", RedisChannel.PatternMode.Literal); + /// Every channel, for a subscriber that cares about all tokens. + public static readonly RedisChannel ApiTokenUpdateAll = new("api-token-update:*", RedisChannel.PatternMode.Pattern); + + public const string ApiTokenUpdatePrefix = "api-token-update:"; + + /// + /// Fired when a login session is deleted (logout, password reset, deactivation). The payload is the id + /// the session was stored under. Open connections that authenticated with it are closed. + /// + public static readonly RedisChannel SessionRevoked = new("session-revoked", RedisChannel.PatternMode.Literal); + + /// + /// Fired when an account may no longer be used at all (deactivated or deleted). The payload is the user + /// id. Every open connection of that user is closed, whatever it authenticated with. + /// + public static readonly RedisChannel UserAuthRevoked = new("user-auth-revoked", RedisChannel.PatternMode.Literal); + /// /// Fired when a row is added to the email outbox, so the email consumer drains it immediately /// instead of waiting for its next poll. Payload-less: it is purely a "wake up and check" nudge. diff --git a/Common/Services/RedisPubSub/RedisPubService.cs b/Common/Services/RedisPubSub/RedisPubService.cs index 9f334e91c..0e55f96a5 100644 --- a/Common/Services/RedisPubSub/RedisPubService.cs +++ b/Common/Services/RedisPubSub/RedisPubService.cs @@ -28,6 +28,16 @@ public Task SendApiTokenUpdate(Guid tokenId) return _subscriber.PublishAsync(RedisChannels.ApiTokenUpdate(tokenId), RedisValue.EmptyString); } + public Task SendSessionRevoked(string sessionId) + { + return _subscriber.PublishAsync(RedisChannels.SessionRevoked, sessionId); + } + + public Task SendUserAuthRevoked(Guid userId) + { + return _subscriber.PublishAsync(RedisChannels.UserAuthRevoked, userId.ToString()); + } + public Task SendEmailOutboxPending() { // Payload-less wake-up nudge; the consumer reads the actual rows from the database. diff --git a/Common/Services/Session/SessionService.cs b/Common/Services/Session/SessionService.cs index 0d5b307bb..4eedbe5db 100644 --- a/Common/Services/Session/SessionService.cs +++ b/Common/Services/Session/SessionService.cs @@ -5,6 +5,7 @@ using OpenShock.Common.Redis; using OpenShock.Common.Services.Audit; using OpenShock.Common.Services.Geo; +using OpenShock.Common.Services.RedisPubSub; using OpenShock.Common.Utils; using OpenShock.Internal.Common.Utils; using Redis.OM; @@ -20,16 +21,38 @@ public sealed class SessionService : ISessionService { private readonly IRedisCollection _loginSessions; private readonly IAuditService _auditService; + private readonly IRedisPubService _redisPubService; + private readonly ILogger _logger; /// /// DI constructor /// /// /// - public SessionService(IRedisConnectionProvider redisConnectionProvider, IAuditService auditService) + /// Announces deleted sessions so open connections using them are closed. + /// + public SessionService(IRedisConnectionProvider redisConnectionProvider, IAuditService auditService, IRedisPubService redisPubService, ILogger logger) { _loginSessions = redisConnectionProvider.RedisCollection(false); _auditService = auditService; + _redisPubService = redisPubService; + _logger = logger; + } + + /// + /// Tells every instance the session is gone. Deliberately swallows failures: the session is already + /// deleted, and a connection that misses the message is caught by its next periodic check. + /// + private async Task NotifyRevokedAsync(LoginSession session) + { + try + { + await _redisPubService.SendSessionRevoked(session.Id); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to announce a deleted session; open connections using it close on their next check"); + } } public async Task CreateSessionAsync(Guid userId, string userAgent, IPAddress ipAddress, Guid? actorId, IpEnrichmentData? enrichment = null) @@ -100,6 +123,7 @@ public async Task DeleteSessionByTokenAsync(string sessionToken) if (session is null) return false; await _loginSessions.DeleteAsync(session); + await NotifyRevokedAsync(session); return true; } @@ -109,6 +133,7 @@ public async Task DeleteSessionByIdAsync(Guid sessionId) if (session is null) return false; await _loginSessions.DeleteAsync(session); + await NotifyRevokedAsync(session); return true; } @@ -118,12 +143,18 @@ public async Task DeleteSessionsByUserIdAsync(Guid userId) await _loginSessions.DeleteAsync(sessions); + foreach (var session in sessions) + { + await NotifyRevokedAsync(session); + } + return sessions.Count; } public async Task DeleteSessionAsync(LoginSession loginSession) { await _loginSessions.DeleteAsync(loginSession); + await NotifyRevokedAsync(loginSession); } public async Task LogoutSessionAsync(LoginSession loginSession) @@ -138,5 +169,6 @@ await _auditService.LogAsync( ); await _loginSessions.DeleteAsync(loginSession); + await NotifyRevokedAsync(loginSession); } } From 882449a4b20cda21500e2afaf38c48f7fd72c9c1 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Thu, 26 Nov 2026 21:49:14 +0100 Subject: [PATCH 08/14] feat: bind the signup browser cookie to the country of the signup The cookie carries the country the signup came from. Presented from a different country it is ignored, so the caller is asked for the password or provider sign-in instead. An unknown country on either side is let through. --- .../GeoLocatedWebApplicationFactory.cs | 12 +- .../Tests/SignupBrowserCookieCountryTests.cs | 150 ++++++++++++++++++ Common/Authentication/SignupBrowserCookie.cs | 39 ++++- 3 files changed, 196 insertions(+), 5 deletions(-) create mode 100644 API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs diff --git a/API.IntegrationTests/GeoLocatedWebApplicationFactory.cs b/API.IntegrationTests/GeoLocatedWebApplicationFactory.cs index de90dabcf..39bf81174 100644 --- a/API.IntegrationTests/GeoLocatedWebApplicationFactory.cs +++ b/API.IntegrationTests/GeoLocatedWebApplicationFactory.cs @@ -21,6 +21,13 @@ public GeoPoint? ClientLocation set => _enrichment.Location = value; } + /// Country every request resolves to, or null for "unknown". + public string? ClientCountryCode + { + get => _enrichment.CountryCode; + set => _enrichment.CountryCode = value; + } + protected override void ConfigureWebHost(IWebHostBuilder builder) { base.ConfigureWebHost(builder); @@ -35,8 +42,11 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) private sealed class FakeIpEnrichmentService : IIpEnrichmentService { public GeoPoint? Location { get; set; } + public string? CountryCode { get; set; } public IpEnrichmentData? Enrich(IPAddress ip) => - Location is { } location ? new IpEnrichmentData(null, null, null, null, null, location, 20) : null; + Location is null && CountryCode is null + ? null + : new IpEnrichmentData(null, null, null, CountryCode, null, Location, Location is null ? null : 20); } } diff --git a/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs b/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs new file mode 100644 index 000000000..a5a71f7f1 --- /dev/null +++ b/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs @@ -0,0 +1,150 @@ +using System.Net; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.Common.Authentication; +using OpenShock.Common.Constants; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Utils; + +namespace OpenShock.API.IntegrationTests.Tests; + +/// +/// The signup browser cookie only stands in for the account's credential when it comes back from the +/// country the signup was made in. +/// +// One at a time: every test moves the single fake location all requests of this host resolve to. +[NotInParallel("signup-browser-country")] +public sealed class SignupBrowserCookieCountryTests +{ + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required GeoLocatedWebApplicationFactory WebApplicationFactory { get; init; } + + [After(Test)] + public void ResetCountry() => WebApplicationFactory.ClientCountryCode = null; + + [Test] + public async Task Activate_FromTheCountryOfTheSignup_ActivatesWithTokenAlone() + { + WebApplicationFactory.ClientCountryCode = "NO"; + var (userId, token, cookie) = await SignUpAndGetLinkAsync("countrysame"); + + var response = await PostActivateAsync(token, cookie); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await IsActivatedAsync(userId)).IsTrue(); + } + + [Test] + public async Task Activate_FromAnotherCountry_AsksForTheCredential() + { + WebApplicationFactory.ClientCountryCode = "NO"; + var (userId, token, cookie) = await SignUpAndGetLinkAsync("countryother"); + + WebApplicationFactory.ClientCountryCode = "DE"; + var response = await PostActivateAsync(token, cookie); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + + // The cookie is only ignored, not burned: back home it still works. + WebApplicationFactory.ClientCountryCode = "NO"; + await Assert.That((await PostActivateAsync(token, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); + } + + [Test] + public async Task Activate_WhenTheCountryCannotBeResolved_StillAcceptsTheCookie() + { + WebApplicationFactory.ClientCountryCode = "NO"; + var (userId, token, cookie) = await SignUpAndGetLinkAsync("countryunknown"); + + WebApplicationFactory.ClientCountryCode = null; + var response = await PostActivateAsync(token, cookie); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await IsActivatedAsync(userId)).IsTrue(); + } + + [Test] + public async Task Activate_CookieFromASignupOfUnknownCountry_IsAcceptedAnywhere() + { + var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("countrynone"), TestHelper.UniqueEmail("country-none"), "OwnerPassword123#", activated: false); + var token = await SeedActivationTokenAsync(userId); + var provider = WebApplicationFactory.Services.GetRequiredService(); + var cookie = $"{AuthConstants.SignupBrowserSecureCookieName}={SignupBrowserCookie.CreateToken(provider, userId)}"; + + WebApplicationFactory.ClientCountryCode = "DE"; + var response = await PostActivateAsync(token, cookie); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + } + + private HttpClient CreateClient() => WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false, + HandleCookies = false + }); + + /// Signs up through the API, and stands in for the Cron job that mails the activation link. + private async Task<(Guid UserId, string Token, string Cookie)> SignUpAndGetLinkAsync(string prefix) + { + var email = TestHelper.UniqueEmail(prefix); + + using var client = CreateClient(); + var response = await client.PostAsync("/2/account/signup", TestHelper.JsonContent(new + { + username = TestHelper.UniqueUsername(prefix), + password = "SecurePassword123#", + email, + turnstileResponse = "valid-token" + })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + var cookie = response.Headers.GetValues("Set-Cookie") + .Single(c => c.StartsWith(AuthConstants.SignupBrowserSecureCookieName + "=")) + .Split(';')[0]; + + Guid userId; + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + userId = await db.Users.AsNoTracking().Where(u => u.Email == email).Select(u => u.Id).SingleAsync(); + } + + return (userId, await SeedActivationTokenAsync(userId), cookie); + } + + private async Task SeedActivationTokenAsync(Guid userId) + { + var token = "activation-" + Guid.NewGuid().ToString("N"); + var hash = HashingUtils.HashToken(token); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var updated = await db.UserActivationRequests.Where(r => r.UserId == userId).ExecuteUpdateAsync(s => s.SetProperty(r => r.TokenHash, hash)); + if (updated == 0) + { + db.UserActivationRequests.Add(new UserActivationRequest { UserId = userId, TokenHash = hash }); + await db.SaveChangesAsync(); + } + + return token; + } + + private async Task PostActivateAsync(string token, string cookie) + { + using var client = CreateClient(); + var request = new HttpRequestMessage(HttpMethod.Post, $"/1/account/activate?token={token}"); + request.Headers.Add("Cookie", cookie); + return await client.SendAsync(request); + } + + private async Task IsActivatedAsync(Guid userId) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.ActivatedAt != null).SingleAsync(); + } +} diff --git a/Common/Authentication/SignupBrowserCookie.cs b/Common/Authentication/SignupBrowserCookie.cs index 6c4460bb3..caa154ccc 100644 --- a/Common/Authentication/SignupBrowserCookie.cs +++ b/Common/Authentication/SignupBrowserCookie.cs @@ -3,6 +3,8 @@ using Microsoft.AspNetCore.DataProtection; using OpenShock.Common.Constants; using OpenShock.Common.Options; +using OpenShock.Common.Services.Geo; +using OpenShock.Common.Utils; namespace OpenShock.Common.Authentication; @@ -18,24 +20,35 @@ namespace OpenShock.Common.Authentication; /// emailed link activate the account. So this cookie is bound to the API host alone: no Domain, /// HttpOnly, and over HTTPS the __Host- name prefix, which browsers refuse to accept from /// anything but this exact host. +/// +/// It also carries the country the signup came from, when that could be resolved. Presented from a +/// different country it is ignored, which only means the caller is asked for the password or provider +/// sign-in like any other browser. Country and not address: addresses change too often on mobile networks +/// for an exact match to be worth the false alarms. A request whose country cannot be resolved is let +/// through, so a missing GeoIP database does not disable the cookie. +/// /// public static class SignupBrowserCookie { private const string ProtectorPurpose = "OpenShock.SignupBrowserCookie"; + private const char PayloadSeparator = '|'; /// The cookie name used for a request: __Host- prefixed whenever cookies are secure. public static string GetName(HttpContext context) => IsSecure(context) ? AuthConstants.SignupBrowserSecureCookieName : AuthConstants.SignupBrowserCookieName; - public static string CreateToken(IDataProtectionProvider provider, Guid userId) - => GetProtector(provider).Protect(userId.ToString(), Duration.ActivationResendWindow); + /// + /// + /// Country the signup came from, or null when it is not known. + public static string CreateToken(IDataProtectionProvider provider, Guid userId, string? countryCode = null) + => GetProtector(provider).Protect($"{userId}{PayloadSeparator}{countryCode}", Duration.ActivationResendWindow); public static void Set(HttpContext context, Guid userId) { var provider = context.RequestServices.GetRequiredService(); - context.Response.Cookies.Append(GetName(context), CreateToken(provider, userId), new CookieOptions + context.Response.Cookies.Append(GetName(context), CreateToken(provider, userId, GetCountryCode(context)), new CookieOptions { Expires = DateTimeOffset.UtcNow.Add(Duration.ActivationResendWindow), Secure = IsSecure(context), @@ -57,7 +70,19 @@ public static bool TryGetUserId(HttpContext context, [NotNullWhen(true)] out Gui var provider = context.RequestServices.GetRequiredService(); try { - if (!Guid.TryParse(GetProtector(provider).Unprotect(token), out var id)) return false; + var payload = GetProtector(provider).Unprotect(token).AsSpan(); + var separator = payload.IndexOf(PayloadSeparator); + if (separator < 0 || !Guid.TryParse(payload[..separator], out var id)) return false; + + // Only a known mismatch counts: unknown on either side says nothing. + var signupCountry = payload[(separator + 1)..]; + if (!signupCountry.IsEmpty + && GetCountryCode(context) is { } currentCountry + && !signupCountry.Equals(currentCountry, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + userId = id; return true; } @@ -83,6 +108,12 @@ public static void Remove(HttpContext context) }); } + private static string? GetCountryCode(HttpContext context) + { + var countryCode = context.RequestServices.GetRequiredService().Enrich(context.GetRemoteIP())?.CountryCode; + return string.IsNullOrEmpty(countryCode) ? null : countryCode; + } + private static bool IsSecure(HttpContext context) => context.Request.IsHttps || context.RequestServices.GetRequiredService().CookieSecure; From 8a1a5602abc3ce6be8473247ec44e53d8c95ca31 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Thu, 26 Nov 2026 22:05:20 +0100 Subject: [PATCH 09/14] feat: cap activation emails per address An address is sent at most 5 activation emails per 24 hours, whichever accounts they are for. The cap per account did not protect an inbox, because a pending account can be replaced by a new signup that starts counting from zero. Signups and corrections past the cap are rejected like a taken address, resends like any other throttled resend. --- API.IntegrationTests/Tests/MailTests.cs | 30 +++++++++++++++++++ API/Services/Account/AccountService.cs | 39 ++++++++++++++++++++++++- 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/API.IntegrationTests/Tests/MailTests.cs b/API.IntegrationTests/Tests/MailTests.cs index 3078cf690..17fd680b7 100644 --- a/API.IntegrationTests/Tests/MailTests.cs +++ b/API.IntegrationTests/Tests/MailTests.cs @@ -482,6 +482,36 @@ public async Task Signup_EmailHeldByStalePendingAccount_ReplacesIt() await Assert.That(holder.Id).IsNotEqualTo(pendingId); } + // An address is only mailed so often, however many signups it takes: each replaced pending account + // would otherwise start its own count. + [Test] + public async Task Signup_AddressAlreadySentTheDailyCapOfActivationEmails_Returns409_AndMailsNothing() + { + var email = TestHelper.UniqueEmail("mail-address-cap"); + + using var client = CreateCookielessClient(); + for (var i = 0; i < 5; i++) + { + var response = await SignUpAsync(client, email, TestHelper.UniqueUsername("mailaddresscap")); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + // Step the pending account and its mail past the cooldown, so the next signup replaces it. + await BackdateOutboxAsync(email, TimeSpan.FromMinutes(11)); + await BackdatePendingAccountAsync(email, TimeSpan.FromMinutes(11)); + } + + var sixth = await SignUpAsync(client, email, TestHelper.UniqueUsername("mailaddresscap")); + await Assert.That(sixth.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(5); + } + + private async Task BackdatePendingAccountAsync(string email, TimeSpan by) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await db.Users.Where(u => u.Email == email).ExecuteUpdateAsync(s => s.SetProperty(u => u.CreatedAt, u => u.CreatedAt - by)); + } + // The cooldown runs from the last activation mail, not only from signup: replacing the account would // mail the same inbox again straight after a resend did. [Test] diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index e60fd40c1..ec6dd4938 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -93,6 +93,27 @@ private async Task NotifyUserAuthRevokedAsync(Guid userId) } } + /// Most activation emails one account, and one address, is sent per . + private const int MaxActivationEmailsPerWindow = 5; + + /// + /// Whether has already been sent as many activation emails as an address gets + /// per window, whichever accounts they were for. The cap per account alone does not protect an inbox: + /// a pending account can be replaced by a new signup, and every new account starts counting from zero. + /// Counted on the outbox, which is never pruned, so it holds across instances and deleted accounts. + /// + /// Lowercased address. + /// + private async Task IsActivationEmailCapReachedAsync(string email, CancellationToken cancellationToken) + { + var windowStart = DateTime.UtcNow - Duration.ActivationResendWindow; + var sent = await _db.EmailOutbox.CountAsync( + m => m.Recipient == email && m.Type == EmailType.AccountActivation && m.CreatedAt >= windowStart, + cancellationToken); + + return sent >= MaxActivationEmailsPerWindow; + } + private Task IsUserNameBlacklisted(string username, CancellationToken cancellationToken) => _db.UserNameBlacklists.Matching(username).AnyAsync(cancellationToken); @@ -110,6 +131,11 @@ private async Task CreateAccount(string email, string use if (await IsUserNameBlacklisted(username, cancellationToken) || await IsEmailProviderBlacklisted(email, cancellationToken)) return new AccountWithEmailOrUsernameExists(); + // This signup would mail the address (unless accounts are activated on creation). Past the cap it is + // turned away like a taken address, before it can replace whoever holds the address now. + if (!verifyOnCreation && await IsActivationEmailCapReachedAsync(email, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); + await ReleaseEmailFromPendingAccountAsync(email, claimantOwnsEmail: false, exceptUserId: null, cancellationToken); if (await _db.Users.AnyAsync(x => x.Email == email || x.Name == username, cancellationToken)) @@ -253,6 +279,10 @@ public async Task> Rest if (await IsUserNameBlacklisted(username, cancellationToken) || await IsEmailProviderBlacklisted(email, cancellationToken)) return new AccountWithEmailOrUsernameExists(); + // Moving the signup to another address mails that address. + if (emailChanged && await IsActivationEmailCapReachedAsync(email, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); + // Releasing another pending account's hold on the address only stands if this correction goes // through: every return below that does not commit rolls the release back. await using var transaction = await _db.Database.BeginTransactionAsync(cancellationToken); @@ -333,6 +363,10 @@ public async Task CreateOAuthOnlyAccountAsync( if (await IsUserNameBlacklisted(username, cancellationToken) || await IsEmailProviderBlacklisted(email, cancellationToken)) return new AccountWithEmailOrUsernameExists(); + // An unverified address gets an activation email. + if (!isEmailTrusted && await IsActivationEmailCapReachedAsync(email, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); + // Pending accounts removed to make room only stay removed if the new account is created: every // return below that does not commit rolls them back. await using var tx = await _db.Database.BeginTransactionAsync(cancellationToken); @@ -531,7 +565,10 @@ private async Task m.CreatedAt) .ToListAsync(cancellationToken); - if (recent.Count >= 5 || (!ignoreCooldown && recent.Any(createdAt => createdAt >= DateTime.UtcNow - Duration.ActivationResendCooldown))) + if (recent.Count >= MaxActivationEmailsPerWindow || (!ignoreCooldown && recent.Any(createdAt => createdAt >= DateTime.UtcNow - Duration.ActivationResendCooldown))) + return new TooManyActivationResends(); + + if (await IsActivationEmailCapReachedAsync(user.Email, cancellationToken)) return new TooManyActivationResends(); user.UserActivationRequest ??= new UserActivationRequest From cedaecf0e6af940f3e7288301db10472ea410516 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Thu, 26 Nov 2026 22:08:08 +0100 Subject: [PATCH 10/14] refactor: move hub connection revocation out to its own change Closing open SignalR connections of revoked sessions and API tokens is independent of the account activation fix and now lives on feature/hub-connection-revocation. This branch keeps signing sessions out on a password reset and the rate limiter change. --- .../Tests/SignalRUserHubTests.cs | 271 ------------------ API.IntegrationTests/WebApplicationFactory.cs | 8 - API/Realtime/RedisSubscriberService.cs | 64 ----- API/Services/Account/AccountService.cs | 21 -- Common/Hubs/HubConnectionTracker.cs | 139 --------- .../Hubs/RevalidateAuthenticationHubFilter.cs | 160 ----------- Common/Hubs/UserHub.cs | 11 +- Common/OpenShockServiceHelper.cs | 6 +- .../Services/RedisPubSub/IRedisPubService.cs | 13 - Common/Services/RedisPubSub/RedisChannels.cs | 17 -- .../Services/RedisPubSub/RedisPubService.cs | 10 - Common/Services/Session/SessionService.cs | 34 +-- 12 files changed, 6 insertions(+), 748 deletions(-) delete mode 100644 Common/Hubs/HubConnectionTracker.cs delete mode 100644 Common/Hubs/RevalidateAuthenticationHubFilter.cs diff --git a/API.IntegrationTests/Tests/SignalRUserHubTests.cs b/API.IntegrationTests/Tests/SignalRUserHubTests.cs index c5c85f664..f1ecc415b 100644 --- a/API.IntegrationTests/Tests/SignalRUserHubTests.cs +++ b/API.IntegrationTests/Tests/SignalRUserHubTests.cs @@ -1,15 +1,8 @@ using System.Net; using System.Text.Json; -using Microsoft.AspNetCore.Http.Connections; using Microsoft.AspNetCore.Mvc.Testing; -using Microsoft.AspNetCore.SignalR.Client; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.DependencyInjection; using OpenShock.API.IntegrationTests.Helpers; -using OpenShock.API.Services.Account; using OpenShock.Common.Constants; -using OpenShock.Common.OpenShockDb; -using OpenShock.Common.Services.Session; namespace OpenShock.API.IntegrationTests.Tests; @@ -106,268 +99,4 @@ public async Task PublicShareHub_Negotiate_WithoutAuth_ReturnsOk() // Should return OK (negotiate doesn't check auth or share existence) await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); } - - // --- A revocation closes the open connections it concerns right away, without them calling anything --- - - [Test] - public async Task Logout_ClosesTheSessionsOpenConnection() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkicklogout"), TestHelper.UniqueEmail("hubkicklogout"), "SecurePassword123#"); - var other = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkickother"), TestHelper.UniqueEmail("hubkickother"), "SecurePassword123#"); - await using var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); - await using var otherConnection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={other.SessionToken}"); - - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) - { - await scope.ServiceProvider.GetRequiredService().DeleteSessionByTokenAsync(user.SessionToken); - } - - await AssertConnectionClosesAsync(connection); - - // Nobody else is affected. - await otherConnection.InvokeAsync("Reboot", Guid.CreateVersion7()); - await Assert.That(otherConnection.State).IsEqualTo(HubConnectionState.Connected); - } - - [Test] - public async Task DeletingAnApiToken_ClosesItsOpenConnection() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkicktoken"), TestHelper.UniqueEmail("hubkicktoken"), "SecurePassword123#"); - var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-kick-deleted"); - var (_, otherRawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-kick-kept"); - await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); - await using var otherConnection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, otherRawToken); - - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - var response = await client.DeleteAsync($"/1/tokens/{tokenId}"); - await Assert.That(response.IsSuccessStatusCode).IsTrue(); - - await AssertConnectionClosesAsync(connection); - - await otherConnection.InvokeAsync("Reboot", Guid.CreateVersion7()); - await Assert.That(otherConnection.State).IsEqualTo(HubConnectionState.Connected); - } - - [Test] - public async Task DeactivatingAnAccount_ClosesItsSessionAndApiTokenConnections() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubkickdeact"), TestHelper.UniqueEmail("hubkickdeact"), "SecurePassword123#"); - var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-kick-deactivated"); - await using var sessionConnection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); - await using var tokenConnection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); - - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) - { - var accountService = scope.ServiceProvider.GetRequiredService(); - await accountService.DeactivateAccountAsync(user.Id, user.Id, deleteLater: false); - } - - await AssertConnectionClosesAsync(sessionConnection); - await AssertConnectionClosesAsync(tokenConnection); - } - - // --- The fallback: a connection whose revocation was never announced stops at its next periodic check --- - - [Test] - public async Task Invoke_ManyCallsInARow_ChecksTheApiTokenOncePerInterval() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevalcache"), TestHelper.UniqueEmail("hubrevalcache"), "SecurePassword123#"); - var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-cached"); - await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) - { - var db = scope.ServiceProvider.GetRequiredService(); - await db.ApiTokens.Where(t => t.Id == tokenId).ExecuteDeleteAsync(); - } - - // Straight after the check above, the deleted token is not looked up again: the call goes through. - // (It would be rejected, and the connection closed, if every call queried the database.) - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); - - await AssertInvokeFailsAndConnectionClosesAsync(connection); - } - - [Test] - public async Task Invoke_WithValidSession_KeepsWorking() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevalok"), TestHelper.UniqueEmail("hubrevalok"), "SecurePassword123#"); - await using var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); - - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - - await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); - } - - [Test] - public async Task Invoke_AfterSessionDeleted_FailsAndClosesConnection() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevalsess"), TestHelper.UniqueEmail("hubrevalsess"), "SecurePassword123#"); - await using var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) - { - await scope.ServiceProvider.GetRequiredService().DeleteSessionsByUserIdAsync(user.Id); - } - - await AssertInvokeFailsAndConnectionClosesAsync(connection); - } - - [Test] - public async Task Invoke_AfterAccountDeactivated_WithTheSessionLeftBehind_FailsAndClosesConnection() - { - // Deactivation removes sessions after its database commit; if that step fails the session survives. - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaldeact"), TestHelper.UniqueEmail("hubrevaldeact"), "SecurePassword123#"); - await using var connection = await ConnectAsync("Cookie", $"{AuthConstants.UserSessionCookieName}={user.SessionToken}"); - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) - { - var db = scope.ServiceProvider.GetRequiredService(); - db.UserDeactivations.Add(new UserDeactivation - { - DeactivatedUserId = user.Id, - DeactivatedByUserId = user.Id, - DeleteLater = false - }); - await db.SaveChangesAsync(); - } - - await AssertInvokeFailsAndConnectionClosesAsync(connection); - } - - [Test] - public async Task Invoke_WithValidApiToken_KeepsWorking() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaltokok"), TestHelper.UniqueEmail("hubrevaltokok"), "SecurePassword123#"); - var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-ok"); - await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); - - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - - await Assert.That(connection.State).IsEqualTo(HubConnectionState.Connected); - } - - [Test] - public async Task Invoke_AfterApiTokenDeleted_FailsAndClosesConnection() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaltokdel"), TestHelper.UniqueEmail("hubrevaltokdel"), "SecurePassword123#"); - var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-deleted"); - await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) - { - var db = scope.ServiceProvider.GetRequiredService(); - await db.ApiTokens.Where(t => t.Id == tokenId).ExecuteDeleteAsync(); - } - - await AssertInvokeFailsAndConnectionClosesAsync(connection); - } - - [Test] - public async Task Invoke_AfterApiTokenExpired_FailsAndClosesConnection() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaltokexp"), TestHelper.UniqueEmail("hubrevaltokexp"), "SecurePassword123#"); - var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-expired"); - await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) - { - var db = scope.ServiceProvider.GetRequiredService(); - var expired = DateTime.UtcNow.AddMinutes(-1); - await db.ApiTokens.Where(t => t.Id == tokenId).ExecuteUpdateAsync(s => s.SetProperty(t => t.ValidUntil, expired)); - } - - await AssertInvokeFailsAndConnectionClosesAsync(connection); - } - - [Test] - public async Task Invoke_AfterApiTokenOwnerDeactivated_FailsAndClosesConnection() - { - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("hubrevaltokdeact"), TestHelper.UniqueEmail("hubrevaltokdeact"), "SecurePassword123#"); - var (_, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, user.Id, "hub-revalidate-deactivated"); - await using var connection = await ConnectAsync(AuthConstants.ApiTokenHeaderName, rawToken); - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) - { - var db = scope.ServiceProvider.GetRequiredService(); - db.UserDeactivations.Add(new UserDeactivation - { - DeactivatedUserId = user.Id, - DeactivatedByUserId = user.Id, - DeleteLater = false - }); - await db.SaveChangesAsync(); - } - - await AssertInvokeFailsAndConnectionClosesAsync(connection); - } - - /// - /// Opens a real hub connection against the in-process test server. The hub only allows WebSockets, which - /// the test server offers through its own client rather than through an HttpMessageHandler. - /// - private async Task ConnectAsync(string headerName, string headerValue) - { - var server = WebApplicationFactory.Server; - - var connection = new HubConnectionBuilder() - .WithUrl(new Uri(server.BaseAddress, "/1/hubs/user"), options => - { - options.Transports = HttpTransportType.WebSockets; - options.SkipNegotiation = true; - options.WebSocketFactory = async (context, cancellationToken) => - { - var client = server.CreateWebSocketClient(); - client.ConfigureRequest = request => request.Headers[headerName] = headerValue; - return await client.ConnectAsync(context.Uri, cancellationToken); - }; - }) - .Build(); - - await connection.StartAsync(); - return connection; - } - - private static async Task AssertInvokeFailsAndConnectionClosesAsync(HubConnection connection) - { - // The connection was checked moments ago and that result is kept for the interval, so the - // revocation only reaches it on the first call after that. - await Task.Delay(WebApplicationFactory.HubRevalidationInterval + TimeSpan.FromMilliseconds(500)); - - // The server answers with an error and aborts; which of the two the client sees first is a race. - Exception? failure = null; - try - { - await connection.InvokeAsync("Reboot", Guid.CreateVersion7()); - } - catch (Exception ex) - { - failure = ex; - } - - await Assert.That(failure).IsNotNull(); - - await AssertConnectionClosesAsync(connection); - } - - /// Waits for the server to close the connection, without calling anything on it. - private static async Task AssertConnectionClosesAsync(HubConnection connection) - { - var deadline = DateTime.UtcNow.AddSeconds(30); - while (connection.State != HubConnectionState.Disconnected && DateTime.UtcNow < deadline) - { - await Task.Delay(50); - } - - await Assert.That(connection.State).IsEqualTo(HubConnectionState.Disconnected); - } } diff --git a/API.IntegrationTests/WebApplicationFactory.cs b/API.IntegrationTests/WebApplicationFactory.cs index b10c5dc11..84ec5107d 100644 --- a/API.IntegrationTests/WebApplicationFactory.cs +++ b/API.IntegrationTests/WebApplicationFactory.cs @@ -9,7 +9,6 @@ using Microsoft.Extensions.Options; using OpenShock.API.IntegrationTests.Docker; using OpenShock.API.IntegrationTests.HttpMessageHandlers; -using OpenShock.Common.Hubs; using Serilog; using Serilog.Events; @@ -27,9 +26,6 @@ public class WebApplicationFactory : WebApplicationFactory [ClassDataSource(Shared = SharedType.PerTestSession)] public required InMemoryRedis Redis { get; init; } - /// How long an open hub connection can go on after its session or API token was revoked, in tests. - public static readonly TimeSpan HubRevalidationInterval = TimeSpan.FromSeconds(1); - protected override void ConfigureClient(HttpClient client) { base.ConfigureClient(client); @@ -107,10 +103,6 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) { services.AddTransient(); - // Hub connections re-check their session or API token at most once per interval. Kept short so - // the tests that revoke one do not have to wait out the production interval. - services.Configure(options => options.Interval = HubRevalidationInterval); - // Disable rate limiting for integration tests so auth-endpoint tests // don't interfere with each other (10 req/min is too restrictive for test suites). // Rate limiter behavior is covered by dedicated unit tests. diff --git a/API/Realtime/RedisSubscriberService.cs b/API/Realtime/RedisSubscriberService.cs index 4c2c09021..6351d50d7 100644 --- a/API/Realtime/RedisSubscriberService.cs +++ b/API/Realtime/RedisSubscriberService.cs @@ -21,7 +21,6 @@ public sealed class RedisSubscriberService : IHostedService, IAsyncDisposable private readonly IHubContext _hubContext; private readonly IDbContextFactory _dbContextFactory; private readonly IRedisConnectionProvider _redisConnectionProvider; - private readonly HubConnectionTracker _hubConnections; private readonly ISubscriber _subscriber; private readonly ILogger _logger; @@ -32,21 +31,18 @@ public sealed class RedisSubscriberService : IHostedService, IAsyncDisposable /// /// /// - /// The hub connections open on this instance, closed here when what they authenticated with is revoked. /// public RedisSubscriberService( IConnectionMultiplexer connectionMultiplexer, IHubContext hubContext, IDbContextFactory dbContextFactory, IRedisConnectionProvider redisConnectionProvider, - HubConnectionTracker hubConnections, ILogger logger ) { _hubContext = hubContext; _dbContextFactory = dbContextFactory; _redisConnectionProvider = redisConnectionProvider; - _hubConnections = hubConnections; _subscriber = connectionMultiplexer.GetSubscriber(); _logger = logger; } @@ -56,61 +52,6 @@ public async Task StartAsync(CancellationToken cancellationToken) { await _subscriber.SubscribeAsync(RedisChannels.KeyEventExpired, HandleKeyExpired); await _subscriber.SubscribeAsync(RedisChannels.DeviceStatus, HandleDeviceStatus); - await _subscriber.SubscribeAsync(RedisChannels.SessionRevoked, HandleSessionRevoked); - await _subscriber.SubscribeAsync(RedisChannels.UserAuthRevoked, HandleUserAuthRevoked); - await _subscriber.SubscribeAsync(RedisChannels.ApiTokenUpdateAll, HandleApiTokenUpdate); - } - - private void HandleSessionRevoked(RedisChannel _, RedisValue message) - { - var sessionId = (string?)message; - if (string.IsNullOrEmpty(sessionId)) return; - - var closed = _hubConnections.AbortSession(sessionId); - if (closed > 0) _logger.LogDebug("Closed {Count} hub connection(s) of a deleted session", closed); - } - - private void HandleUserAuthRevoked(RedisChannel _, RedisValue message) - { - if (!Guid.TryParse((string?)message, out var userId)) return; - - var closed = _hubConnections.AbortUser(userId); - if (closed > 0) _logger.LogDebug("Closed {Count} hub connection(s) of user [{UserId}]", closed, userId); - } - - private void HandleApiTokenUpdate(RedisChannel channel, RedisValue _) - { - var channelName = (string?)channel; - if (channelName is null || !channelName.StartsWith(RedisChannels.ApiTokenUpdatePrefix, StringComparison.Ordinal)) return; - if (!Guid.TryParse(channelName.AsSpan(RedisChannels.ApiTokenUpdatePrefix.Length), out var tokenId)) return; - - // Most token changes concern no connection on this instance: no database round trip for those. - if (!_hubConnections.HasApiTokenConnections(tokenId)) return; - - OsTask.Run(() => ApplyApiTokenUpdate(tokenId)); - } - - /// - /// The same channel announces an edit and a deletion, so look: a token that is gone closes its - /// connections, one that changed makes them read it again on their next call. - /// - private async Task ApplyApiTokenUpdate(Guid tokenId) - { - await using var db = await _dbContextFactory.CreateDbContextAsync(); - - var stillValid = await db.ApiTokens.AnyAsync(x => - x.Id == tokenId && - (x.ValidUntil == null || x.ValidUntil >= DateTime.UtcNow) && - x.User.UserDeactivation == null); - - if (stillValid) - { - _hubConnections.InvalidateApiToken(tokenId); - return; - } - - var closed = _hubConnections.AbortApiToken(tokenId); - _logger.LogDebug("Closed {Count} hub connection(s) of revoked API token [{TokenId}]", closed, tokenId); } private void HandleKeyExpired(RedisChannel _, RedisValue message) @@ -153,11 +94,6 @@ private void HandleKeyExpired(RedisChannel _, RedisValue message) OsTask.Run(() => LogicDeviceOnlineStatus(id)); } - else if (typeNameSpan.SequenceEqual(typeof(LoginSession).FullName)) - { - // A session that reached its lifetime: same as a deleted one for the connections using it. - _hubConnections.AbortSession(guidSpan.ToString()); - } } private void HandleDeviceStatus(RedisChannel _, RedisValue value) diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index ec6dd4938..2adda96e2 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -76,23 +76,6 @@ private async Task NotifyEmailOutboxAsync() } } - /// - /// Tells every instance the account may no longer be used, so its open connections are closed, the ones - /// that authenticated with an API token included. Deliberately swallows failures: the change is already - /// committed, and a connection that misses the message is caught by its next periodic check. - /// - private async Task NotifyUserAuthRevokedAsync(Guid userId) - { - try - { - await _redisPubService.SendUserAuthRevoked(userId); - } - catch (Exception ex) - { - _logger.LogWarning(ex, "Failed to announce revoked access for user ID: [{Id}]; open connections close on their next check", userId); - } - } - /// Most activation emails one account, and one address, is sent per . private const int MaxActivationEmailsPerWindow = 5; @@ -641,8 +624,6 @@ await _auditService.LogAsync( await transaction.CommitAsync(); } - await NotifyUserAuthRevokedAsync(userId); - // Remove all login sessions await _sessionService.DeleteSessionsByUserIdAsync(userId); @@ -733,8 +714,6 @@ await _auditService.LogAsync( await transaction.CommitAsync(); - await NotifyUserAuthRevokedAsync(userId); - return new Success(); } diff --git a/Common/Hubs/HubConnectionTracker.cs b/Common/Hubs/HubConnectionTracker.cs deleted file mode 100644 index d4d2a7634..000000000 --- a/Common/Hubs/HubConnectionTracker.cs +++ /dev/null @@ -1,139 +0,0 @@ -using System.Collections.Concurrent; -using System.Diagnostics; -using Microsoft.AspNetCore.SignalR; -using OpenShock.Common.Authentication; -using OpenShock.Common.Constants; -using OpenShock.Common.Extensions; -using OpenShock.Common.Utils; - -namespace OpenShock.Common.Hubs; - -/// -/// The authenticated hub connections open on this instance, by what they authenticated with. Lets a -/// revocation that arrives over Redis close the affected connections right away, instead of each connection -/// finding out the next time it asks the database (see ). -/// -/// -/// Local to the process: every instance tracks its own connections and reacts to the same Redis message. -/// Lookups scan all connections, which is fine for how rarely sessions and tokens are revoked. -/// -public sealed class HubConnectionTracker -{ - private readonly ConcurrentDictionary _connections = new(); - - public TrackedHubConnection? Get(string connectionId) - => _connections.GetValueOrDefault(connectionId); - - /// Starts tracking a connection. Anonymous connections hold nothing that can be revoked and are skipped. - /// The tracked connection, or null when it was skipped. - public TrackedHubConnection? Track(HubCallerContext context) - { - var user = context.User; - if (user is null) return null; - - Guid? userId = Guid.TryParse(context.UserIdentifier, out var parsedUserId) ? parsedUserId : null; - - if (user.HasOpenShockApiTokenIdentity()) - { - if (!user.TryGetClaimValueAsGuid(OpenShockAuthClaims.ApiTokenId, out var tokenId)) return null; - - return _connections[context.ConnectionId] = new TrackedHubConnection(context, userId, sessionId: null, tokenId); - } - - if (user.TryGetOpenShockUserIdentity() is not null - && context.GetHttpContext() is { } httpContext - && httpContext.TryGetUserSessionToken(out var sessionToken)) - { - return _connections[context.ConnectionId] = new TrackedHubConnection(context, userId, GetSessionId(sessionToken), apiTokenId: null); - } - - return null; - } - - public void Untrack(string connectionId) => _connections.TryRemove(connectionId, out _); - - /// Closes the connections that authenticated with this session. - /// The id the session is stored under, see . - /// How many connections were closed. - public int AbortSession(string sessionId) => Abort(c => c.SessionId == sessionId); - - /// Closes every connection of this user, whatever it authenticated with. - /// How many connections were closed. - public int AbortUser(Guid userId) => Abort(c => c.UserId == userId); - - /// Closes the connections that authenticated with this API token. - /// How many connections were closed. - public int AbortApiToken(Guid tokenId) => Abort(c => c.ApiTokenId == tokenId); - - public bool HasApiTokenConnections(Guid tokenId) - { - foreach (var connection in _connections.Values) - { - if (connection.ApiTokenId == tokenId) return true; - } - - return false; - } - - /// - /// Makes the connections using this API token read it from the database again on their next call, so a - /// change to its permissions, pause state or limits applies from then on. - /// - public void InvalidateApiToken(Guid tokenId) - { - foreach (var connection in _connections.Values) - { - if (connection.ApiTokenId == tokenId) connection.Invalidate(); - } - } - - /// The id a session is stored under in Redis: the hash of its token (old tokens are stored as they are). - public static string GetSessionId(string sessionToken) - => sessionToken.Length == AuthConstants.GeneratedTokenLength ? HashingUtils.HashToken(sessionToken) : sessionToken; - - private int Abort(Func predicate) - { - var aborted = 0; - foreach (var (connectionId, connection) in _connections) - { - if (!predicate(connection)) continue; - - // Dropped here as well as on disconnect, so a message that arrives twice finds nothing. - _connections.TryRemove(connectionId, out _); - connection.Context.Abort(); - aborted++; - } - - return aborted; - } -} - -public sealed class TrackedHubConnection -{ - // 0 means "not validated": Stopwatch timestamps are never 0 in practice, and a false "not validated" - // only costs one extra check. - private long _lastValidated; - - public TrackedHubConnection(HubCallerContext context, Guid? userId, string? sessionId, Guid? apiTokenId) - { - Context = context; - UserId = userId; - SessionId = sessionId; - ApiTokenId = apiTokenId; - } - - public HubCallerContext Context { get; } - public Guid? UserId { get; } - public string? SessionId { get; } - public Guid? ApiTokenId { get; } - - public bool WasValidatedWithin(TimeSpan interval) - { - var last = Volatile.Read(ref _lastValidated); - return last != 0 && Stopwatch.GetElapsedTime(last) < interval; - } - - public void MarkValidated() => Volatile.Write(ref _lastValidated, Stopwatch.GetTimestamp()); - - public void Invalidate() => Volatile.Write(ref _lastValidated, 0); -} diff --git a/Common/Hubs/RevalidateAuthenticationHubFilter.cs b/Common/Hubs/RevalidateAuthenticationHubFilter.cs deleted file mode 100644 index f8d6da285..000000000 --- a/Common/Hubs/RevalidateAuthenticationHubFilter.cs +++ /dev/null @@ -1,160 +0,0 @@ -using System.Security.Claims; -using Microsoft.AspNetCore.SignalR; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; -using OpenShock.Common.Authentication; -using OpenShock.Common.Extensions; -using OpenShock.Common.OpenShockDb; -using OpenShock.Common.Services.Session; - -namespace OpenShock.Common.Hubs; - -/// -/// Keeps an open hub connection from outliving the session or API token it authenticated with. -/// -/// -/// SignalR authenticates a connection once, when it opens, and then keeps it for as long as the client likes. -/// Without this, logging a session out or revoking, expiring or deactivating an API token would only stop new -/// connections: an open one could keep calling, and whatever calls it already had queued would still run. -/// Aborting also discards those queued calls. -/// -/// Two things end a connection. The fast one is a Redis message: revocations are published, and the instance -/// holding the connection closes it right away (the filter registers every connection with -/// for that). The slow one is the check in this filter, which asks the -/// database before a hub method call. It exists for what the messages cannot cover, a message that was lost -/// or a token that simply reached its expiry, so it only runs once per -/// per connection, and never for an idle one. -/// -/// -/// For an API token the row read here is handed to the hub method through -/// . A change to the token invalidates the -/// connection's last check, so its permissions, pause state and control limits are read again on the next call. -/// -/// -public sealed class RevalidateAuthenticationHubFilter : IHubFilter -{ - private readonly HubConnectionTracker _tracker; - private readonly IOptions _options; - - public RevalidateAuthenticationHubFilter(HubConnectionTracker tracker, IOptions options) - { - _tracker = tracker; - _options = options; - } - - /// - public async Task OnConnectedAsync(HubLifetimeContext context, Func next) - { - var tracked = _tracker.Track(context.Context); - - // The connection was authenticated before it was tracked. A revocation announced in between found - // nothing to close, so look once now that announcements can reach it. - if (tracked is not null) - { - if (!await IsStillAuthenticated(context.Context, context.ServiceProvider)) - { - _tracker.Untrack(context.Context.ConnectionId); - context.Context.Abort(); - return; - } - - tracked.MarkValidated(); - } - - await next(context); - } - - /// - public Task OnDisconnectedAsync(HubLifetimeContext context, Exception? exception, Func next) - { - _tracker.Untrack(context.Context.ConnectionId); - return next(context, exception); - } - - /// - public async ValueTask InvokeMethodAsync(HubInvocationContext invocationContext, Func> next) - { - var context = invocationContext.Context; - - // Untracked means anonymous (nothing to check), or a connection a revocation already closed whose - // queued calls are still draining: the check below turns those away. - var tracked = _tracker.Get(context.ConnectionId); - - if (tracked is null || !tracked.WasValidatedWithin(_options.Value.Interval)) - { - if (!await IsStillAuthenticated(context, invocationContext.ServiceProvider)) - { - context.Abort(); - throw new HubException("Authentication is no longer valid"); - } - - tracked?.MarkValidated(); - } - - return await next(invocationContext); - } - - private static async Task IsStillAuthenticated(HubCallerContext context, IServiceProvider services) - { - var user = context.User; - - // Anonymous connection (a public share guest): nothing was granted that could have been revoked. - if (user is null) return true; - - if (user.HasOpenShockApiTokenIdentity()) - { - if (!user.TryGetClaimValueAsGuid(OpenShockAuthClaims.ApiTokenId, out var tokenId)) return false; - - var db = services.GetRequiredService(); - var token = await db.ApiTokens - .AsNoTracking() - .FirstOrDefaultAsync(x => - x.Id == tokenId && - (x.ValidUntil == null || x.ValidUntil >= DateTime.UtcNow) && - x.User.UserDeactivation == null, context.ConnectionAborted); - if (token is null) return false; - - context.Items[HubCallerContextExtensions.CurrentApiTokenKey] = token; - return true; - } - - if (user.TryGetOpenShockUserIdentity() is { } identity) - { - if (context.GetHttpContext() is not { } httpContext || !httpContext.TryGetUserSessionToken(out var sessionToken)) return false; - - // Sessions are deleted on logout, on deactivation and on a password reset. - var sessionService = services.GetRequiredService(); - var session = await sessionService.GetSessionByTokenAsync(sessionToken); - if (session is null || session.UserId != identity.GetClaimValueAsGuid(ClaimTypes.NameIdentifier)) return false; - - // That deletion happens in Redis after the database commit and can fail, leaving the session - // behind. The account itself is the authority, as it is when a session authenticates a request. - var db = services.GetRequiredService(); - return await db.Users.AnyAsync(u => u.Id == session.UserId && u.ActivatedAt != null && u.UserDeactivation == null, context.ConnectionAborted); - } - - return true; - } -} - -public sealed class HubRevalidationOptions -{ - /// - /// How long a connection's last successful database check stays good. Revocations normally close a - /// connection at once through Redis; this bounds how long one can go on when that message was lost, or - /// when an API token expired on its own. - /// - public TimeSpan Interval { get; set; } = TimeSpan.FromMinutes(1); -} - -public static class HubCallerContextExtensions -{ - internal static readonly object CurrentApiTokenKey = new(); - - /// - /// The API token this connection authenticated with, as it was in the database when the connection was - /// last checked. Null for a session or anonymous connection. - /// - public static ApiToken? GetCurrentApiToken(this HubCallerContext context) - => context.Items.TryGetValue(CurrentApiTokenKey, out var token) ? token as ApiToken : null; -} diff --git a/Common/Hubs/UserHub.cs b/Common/Hubs/UserHub.cs index b996fbb9e..c3d3eea35 100644 --- a/Common/Hubs/UserHub.cs +++ b/Common/Hubs/UserHub.cs @@ -28,11 +28,9 @@ public sealed class UserHub : Hub /// connection. Derived per access: SignalR creates a hub instance per invocation, so a field /// set in would be null everywhere else. /// - private IReadOnlyList? TokenPermissions => Context.GetCurrentApiToken() is { } apiToken - ? apiToken.Permissions - : Context.User?.HasOpenShockApiTokenIdentity() == true - ? Context.User.GetApiTokenPermissions() - : null; + private IReadOnlyList? TokenPermissions => Context.User?.HasOpenShockApiTokenIdentity() == true + ? Context.User.GetApiTokenPermissions() + : null; public UserHub(ILogger logger, OpenShockContext db, IRedisConnectionProvider provider, IRedisPubService redisPubService, IControlSender controlSender) @@ -98,8 +96,7 @@ public async Task ControlV2(IReadOnlyList shocks, string? customName) }).FirstAsync(Context.ConnectionAborted); ApiTokenControlLimits? tokenLimits = null; - // The token as it is now, not as it was when the connection opened (see RevalidateAuthenticationHubFilter). - if (Context.GetCurrentApiToken() is { } apiToken) + if (Context.GetHttpContext()?.GetItemByType() is { } apiToken) { // A paused token may not control shockers. if (apiToken.ShockerControlPaused) return; diff --git a/Common/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index 4c3ad170b..7dd8675ee 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -479,11 +479,7 @@ await context.HttpContext.Response.WriteAsync("Too Many Requests. Please try aga public static IServiceCollection AddOpenShockSignalR(this IServiceCollection services, ConfigurationOptions redisConfig) { - services.AddOptions(); - services.AddSingleton(); - services.AddSingleton(); - - services.AddSignalR(options => Microsoft.AspNetCore.SignalR.HubOptionsExtensions.AddFilter(options)) + services.AddSignalR() .AddOpenShockStackExchangeRedis(options => { options.Configuration = redisConfig; }) .AddJsonProtocol(options => { diff --git a/Common/Services/RedisPubSub/IRedisPubService.cs b/Common/Services/RedisPubSub/IRedisPubService.cs index 982433e9c..8e308f395 100644 --- a/Common/Services/RedisPubSub/IRedisPubService.cs +++ b/Common/Services/RedisPubSub/IRedisPubService.cs @@ -20,19 +20,6 @@ public interface IRedisPubService /// Task SendApiTokenUpdate(Guid tokenId); - /// - /// A login session was deleted. Notifies every instance so open connections that authenticated with it - /// are closed. Best-effort: a connection that misses it is caught by its next periodic check. - /// - /// The id the session was stored under. - Task SendSessionRevoked(string sessionId); - - /// - /// The account was deactivated or deleted. Notifies every instance so all open connections of the user - /// are closed, including ones that authenticated with an API token. - /// - Task SendUserAuthRevoked(Guid userId); - /// /// Notifies the email outbox consumer that one or more messages were just enqueued, so it drains /// them without waiting for its next safety-net poll. Best-effort: a lost notification only delays diff --git a/Common/Services/RedisPubSub/RedisChannels.cs b/Common/Services/RedisPubSub/RedisChannels.cs index 53de95e72..d0df75bd5 100644 --- a/Common/Services/RedisPubSub/RedisChannels.cs +++ b/Common/Services/RedisPubSub/RedisChannels.cs @@ -12,23 +12,6 @@ public static class RedisChannels public static RedisChannel ApiTokenUpdate(Guid tokenId) => new($"api-token-update:{tokenId}", RedisChannel.PatternMode.Literal); - /// Every channel, for a subscriber that cares about all tokens. - public static readonly RedisChannel ApiTokenUpdateAll = new("api-token-update:*", RedisChannel.PatternMode.Pattern); - - public const string ApiTokenUpdatePrefix = "api-token-update:"; - - /// - /// Fired when a login session is deleted (logout, password reset, deactivation). The payload is the id - /// the session was stored under. Open connections that authenticated with it are closed. - /// - public static readonly RedisChannel SessionRevoked = new("session-revoked", RedisChannel.PatternMode.Literal); - - /// - /// Fired when an account may no longer be used at all (deactivated or deleted). The payload is the user - /// id. Every open connection of that user is closed, whatever it authenticated with. - /// - public static readonly RedisChannel UserAuthRevoked = new("user-auth-revoked", RedisChannel.PatternMode.Literal); - /// /// Fired when a row is added to the email outbox, so the email consumer drains it immediately /// instead of waiting for its next poll. Payload-less: it is purely a "wake up and check" nudge. diff --git a/Common/Services/RedisPubSub/RedisPubService.cs b/Common/Services/RedisPubSub/RedisPubService.cs index 0e55f96a5..9f334e91c 100644 --- a/Common/Services/RedisPubSub/RedisPubService.cs +++ b/Common/Services/RedisPubSub/RedisPubService.cs @@ -28,16 +28,6 @@ public Task SendApiTokenUpdate(Guid tokenId) return _subscriber.PublishAsync(RedisChannels.ApiTokenUpdate(tokenId), RedisValue.EmptyString); } - public Task SendSessionRevoked(string sessionId) - { - return _subscriber.PublishAsync(RedisChannels.SessionRevoked, sessionId); - } - - public Task SendUserAuthRevoked(Guid userId) - { - return _subscriber.PublishAsync(RedisChannels.UserAuthRevoked, userId.ToString()); - } - public Task SendEmailOutboxPending() { // Payload-less wake-up nudge; the consumer reads the actual rows from the database. diff --git a/Common/Services/Session/SessionService.cs b/Common/Services/Session/SessionService.cs index 4eedbe5db..0d5b307bb 100644 --- a/Common/Services/Session/SessionService.cs +++ b/Common/Services/Session/SessionService.cs @@ -5,7 +5,6 @@ using OpenShock.Common.Redis; using OpenShock.Common.Services.Audit; using OpenShock.Common.Services.Geo; -using OpenShock.Common.Services.RedisPubSub; using OpenShock.Common.Utils; using OpenShock.Internal.Common.Utils; using Redis.OM; @@ -21,38 +20,16 @@ public sealed class SessionService : ISessionService { private readonly IRedisCollection _loginSessions; private readonly IAuditService _auditService; - private readonly IRedisPubService _redisPubService; - private readonly ILogger _logger; /// /// DI constructor /// /// /// - /// Announces deleted sessions so open connections using them are closed. - /// - public SessionService(IRedisConnectionProvider redisConnectionProvider, IAuditService auditService, IRedisPubService redisPubService, ILogger logger) + public SessionService(IRedisConnectionProvider redisConnectionProvider, IAuditService auditService) { _loginSessions = redisConnectionProvider.RedisCollection(false); _auditService = auditService; - _redisPubService = redisPubService; - _logger = logger; - } - - /// - /// Tells every instance the session is gone. Deliberately swallows failures: the session is already - /// deleted, and a connection that misses the message is caught by its next periodic check. - /// - private async Task NotifyRevokedAsync(LoginSession session) - { - try - { - await _redisPubService.SendSessionRevoked(session.Id); - } - catch (Exception ex) - { - _logger.LogWarning(ex, "Failed to announce a deleted session; open connections using it close on their next check"); - } } public async Task CreateSessionAsync(Guid userId, string userAgent, IPAddress ipAddress, Guid? actorId, IpEnrichmentData? enrichment = null) @@ -123,7 +100,6 @@ public async Task DeleteSessionByTokenAsync(string sessionToken) if (session is null) return false; await _loginSessions.DeleteAsync(session); - await NotifyRevokedAsync(session); return true; } @@ -133,7 +109,6 @@ public async Task DeleteSessionByIdAsync(Guid sessionId) if (session is null) return false; await _loginSessions.DeleteAsync(session); - await NotifyRevokedAsync(session); return true; } @@ -143,18 +118,12 @@ public async Task DeleteSessionsByUserIdAsync(Guid userId) await _loginSessions.DeleteAsync(sessions); - foreach (var session in sessions) - { - await NotifyRevokedAsync(session); - } - return sessions.Count; } public async Task DeleteSessionAsync(LoginSession loginSession) { await _loginSessions.DeleteAsync(loginSession); - await NotifyRevokedAsync(loginSession); } public async Task LogoutSessionAsync(LoginSession loginSession) @@ -169,6 +138,5 @@ await _auditService.LogAsync( ); await _loginSessions.DeleteAsync(loginSession); - await NotifyRevokedAsync(loginSession); } } From 22dd4c9b887349a247e824d69fcec7079e13f844 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Thu, 26 Nov 2026 22:21:49 +0100 Subject: [PATCH 11/14] fix: close races around pending signups, activation and password login Correcting a pending signup now checks and writes against the locked, current account row, so an account activated after the caller looked it up is left alone. Releasing an address decides under the holder's row lock and only deletes the holder while it still has that address. A resend uses the locked row's current address. Activation locks the user row before its activation request, the order every other flow uses, so it cannot deadlock against a password reset. A password login drops the session it just created if the account's security stamp changed since the password was checked, so a sign-in with the old password cannot slip past a reset's sign-out. --- API.IntegrationTests/Tests/MailTests.cs | 25 ++++++++ API/Controller/Account/LoginV2.cs | 5 +- API/Services/Account/AccountService.cs | 84 ++++++++++++++++++------- Common/OpenShockControllerBase.cs | 26 +++++++- 4 files changed, 117 insertions(+), 23 deletions(-) diff --git a/API.IntegrationTests/Tests/MailTests.cs b/API.IntegrationTests/Tests/MailTests.cs index 17fd680b7..493a05191 100644 --- a/API.IntegrationTests/Tests/MailTests.cs +++ b/API.IntegrationTests/Tests/MailTests.cs @@ -843,6 +843,31 @@ public async Task RestartPendingSignup_Conflict_LeavesThePendingAccountHoldingTh await Assert.That(await db.Users.AsNoTracking().AnyAsync(u => u.Id == holderId)).IsTrue(); } + [Test] + public async Task RestartPendingSignup_AccountActivatedAfterTheCallerLookedItUp_ChangesNothing() + { + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-restart-stale", "OwnerPassword123#"); + var originalEmail = await GetEmailAsync(userId); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + // The request looks the account up while it is pending, as the OAuth connection lookup does... + var tracked = await db.Users.SingleAsync(u => u.Id == userId); + await Assert.That(tracked.ActivatedAt).IsNull(); + + // ...and it is activated before the restart runs. + using var client = CreateCookielessClient(); + var activated = await PostActivateAsync(client, token, cookie: MintSignupBrowserCookie(userId)); + await Assert.That(activated.StatusCode).IsEqualTo(HttpStatusCode.OK); + + var accountService = scope.ServiceProvider.GetRequiredService(); + var restarted = await accountService.RestartPendingSignupAsync(userId, TestHelper.UniqueEmail("mail-restart-stale-new"), tracked.Name); + + await Assert.That(restarted.Value is User).IsFalse(); + await Assert.That(await GetEmailAsync(userId)).IsEqualTo(originalEmail); + } + [Test] public async Task RestartPendingSignup_SameEmail_KeepsTheMailedLinkWorking() { diff --git a/API/Controller/Account/LoginV2.cs b/API/Controller/Account/LoginV2.cs index 0b1b80be8..8beafabad 100644 --- a/API/Controller/Account/LoginV2.cs +++ b/API/Controller/Account/LoginV2.cs @@ -61,7 +61,10 @@ async Task CompleteLoginAsync(User account, string domain) if (!await automationTokens.TryRecordUseAsync(account.Id, AutomationTokenFlow.Login, cancellationToken)) return Problem(AutomationTokenError.NotAllowedForAccount); - await CreateSession(account.Id, domain); + // The password was checked against the account as it was read; if it was replaced since, this + // sign-in used the old one. + if (!await CreateSession(account.Id, domain, account.SecurityStamp)) + return Problem(LoginError.InvalidCredentials); return Ok(LoginV2OkResponse.FromUser(account)); } diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index 2adda96e2..c085eef0c 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -214,6 +214,10 @@ private async Task ReleaseEmailFromPendingAccountAsync(string email, bool claima if (!claimantOwnsEmail) { + // A resend takes this same lock before it queues mail, so one cannot slip in between the look at + // the outbox below and the delete. Held until the caller's transaction ends. + await _db.Database.ExecuteSqlAsync($"SELECT 1 FROM users WHERE id = {pending.Id} FOR UPDATE", cancellationToken); + // Counted from the last activation mail, not only from signup: a pending account that just had // its mail resent would otherwise be replaced by one that mails the same inbox again right away. var cooldownStart = DateTime.UtcNow - Duration.ActivationResendCooldown; @@ -223,7 +227,9 @@ private async Task ReleaseEmailFromPendingAccountAsync(string email, bool claima if (await _db.EmailOutbox.AnyAsync(m => m.CoalesceKey == coalesceKey && m.CreatedAt >= cooldownStart, cancellationToken)) return; } - await DeletePendingAccountAsync(pending.Id, cancellationToken); + // Only while it still holds this address: its creator may have moved it to another one since the + // lookup above, and then it is not in the way any more. + await DeletePendingAccountAsync(pending.Id, email, cancellationToken); } /// @@ -231,16 +237,28 @@ private async Task ReleaseEmailFromPendingAccountAsync(string email, bool claima /// statement, so an account that gets activated after the caller looked at it is left alone. /// Deactivated and privileged accounts are never deleted this way. /// + /// + /// When given, the account is only deleted while this is still its address. + /// /// False when nothing was deleted. - private async Task DeletePendingAccountAsync(Guid userId, CancellationToken cancellationToken) + private async Task DeletePendingAccountAsync(Guid userId, string? heldEmail, CancellationToken cancellationToken) { - var deleted = await _db.Database.ExecuteSqlAsync($""" - DELETE FROM users AS u - WHERE u.id = {userId} - AND u.activated_at IS NULL - AND NOT (u.roles && {PrivilegedRoles.All}) - AND NOT EXISTS (SELECT 1 FROM user_deactivations AS d WHERE d.deactivated_user_id = u.id) - """, cancellationToken); + var deleted = heldEmail is null + ? await _db.Database.ExecuteSqlAsync($""" + DELETE FROM users AS u + WHERE u.id = {userId} + AND u.activated_at IS NULL + AND NOT (u.roles && {PrivilegedRoles.All}) + AND NOT EXISTS (SELECT 1 FROM user_deactivations AS d WHERE d.deactivated_user_id = u.id) + """, cancellationToken) + : await _db.Database.ExecuteSqlAsync($""" + DELETE FROM users AS u + WHERE u.id = {userId} + AND u.email = {heldEmail} + AND u.activated_at IS NULL + AND NOT (u.roles && {PrivilegedRoles.All}) + AND NOT EXISTS (SELECT 1 FROM user_deactivations AS d WHERE d.deactivated_user_id = u.id) + """, cancellationToken); return deleted > 0; } @@ -250,11 +268,23 @@ public async Task> Rest { email = email.ToLowerInvariant(); + // Everything below, the "still pending" check included, runs with the account's row locked. An + // activation that commits first is seen here; one that comes later waits and then finds its token + // replaced. Releasing another pending account's hold on the address is part of the same + // transaction, so every return that does not commit rolls it back. + await using var transaction = await _db.Database.BeginTransactionAsync(cancellationToken); + await _db.Database.ExecuteSqlAsync($"SELECT 1 FROM users WHERE id = {userId} FOR UPDATE", cancellationToken); + var user = await _db.Users .Include(u => u.UserDeactivation) .Include(u => u.UserActivationRequest) .FirstOrDefaultAsync(u => u.Id == userId, cancellationToken); - if (user is null || user.ActivatedAt is not null || user.UserDeactivation is not null) return new NotFound(); + if (user is null) return new NotFound(); + + // The caller usually looked this account up through this same context already, and a query hands + // back that tracked instance as it was read then. Read the row as it is now. + await _db.Entry(user).ReloadAsync(cancellationToken); + if (user.ActivatedAt is not null || user.UserDeactivation is not null) return new NotFound(); var emailChanged = !string.Equals(user.Email, email, StringComparison.OrdinalIgnoreCase); if (emailChanged || user.Name != username) @@ -266,10 +296,6 @@ public async Task> Rest if (emailChanged && await IsActivationEmailCapReachedAsync(email, cancellationToken)) return new AccountWithEmailOrUsernameExists(); - // Releasing another pending account's hold on the address only stands if this correction goes - // through: every return below that does not commit rolls the release back. - await using var transaction = await _db.Database.BeginTransactionAsync(cancellationToken); - await ReleaseEmailFromPendingAccountAsync(email, claimantOwnsEmail: false, exceptUserId: userId, cancellationToken); if (await _db.Users.AnyAsync(u => u.Id != userId && (u.Email == email || u.Name == username), cancellationToken)) @@ -299,7 +325,6 @@ public async Task> Rest try { await _db.SaveChangesAsync(); - await transaction.CommitAsync(cancellationToken); } catch (DbUpdateConcurrencyException) { @@ -313,10 +338,13 @@ public async Task> Rest } } + await transaction.CommitAsync(cancellationToken); + // A corrected address has not been mailed yet, so the cooldown (which protects an inbox from repeats) // does not apply to it; the daily cap per account still does. A throttled result just means no new - // mail went out, and the resend button gets it later. - await ResendActivationEmailCoreAsync(userId, ignoreCooldown: emailChanged, cancellationToken); + // mail went out, and the resend button gets it later. If another correction got in since the commit + // above, the mail for this one is dropped: that correction queues its own. + await ResendActivationEmailCoreAsync(userId, ignoreCooldown: emailChanged, onlyIfEmailIs: emailChanged ? email : null, cancellationToken); return user; } @@ -358,7 +386,7 @@ public async Task CreateOAuthOnlyAccountAsync( { if (replacePendingUserId is not null) { - await DeletePendingAccountAsync(replacePendingUserId.Value, cancellationToken); + await DeletePendingAccountAsync(replacePendingUserId.Value, heldEmail: null, cancellationToken); // The caller looked that account up through this context, and its OAuth connection has the // key the new one is about to get. Nothing is tracked yet that this method needs. @@ -479,6 +507,10 @@ private async Task ConsumeActivationTokenAsync(Guid userId, string tokenHa { await using var transaction = await _db.Database.BeginTransactionAsync(cancellationToken); + // User row first, then the activation request: the order password reset, resend and signup + // correction take them in. Taking the request first could deadlock against any of those. + await _db.Database.ExecuteSqlAsync($"SELECT 1 FROM users WHERE id = {userId} FOR UPDATE", cancellationToken); + var consumed = await _db.UserActivationRequests .Where(r => r.UserId == userId && r.TokenHash == tokenHash) .ExecuteDeleteAsync(cancellationToken); @@ -520,9 +552,13 @@ public async Task public Task> ResendActivationEmailAsync(Guid userId, CancellationToken cancellationToken = default) - => ResendActivationEmailCoreAsync(userId, ignoreCooldown: false, cancellationToken); + => ResendActivationEmailCoreAsync(userId, ignoreCooldown: false, onlyIfEmailIs: null, cancellationToken); - private async Task> ResendActivationEmailCoreAsync(Guid userId, bool ignoreCooldown, CancellationToken cancellationToken) + /// + /// + /// When given, nothing is queued unless this is still the account's address. + /// + private async Task> ResendActivationEmailCoreAsync(Guid userId, bool ignoreCooldown, string? onlyIfEmailIs, CancellationToken cancellationToken) { // Without mail no link can be delivered (and such accounts are activated on creation anyway). if (!_mailOptions.IsEnabled) return new NotFound(); @@ -536,8 +572,14 @@ private async Task u.UserActivationRequest) .Include(u => u.UserDeactivation) .FirstOrDefaultAsync(u => u.Id == userId, cancellationToken); - if (user is null || user.ActivatedAt is not null) return new NotFound(); + if (user is null) return new NotFound(); + + // An instance this context already tracks comes back as it was first read, so read the locked row + // as it is now: the address below is the one that gets mailed and counted. + await _db.Entry(user).ReloadAsync(cancellationToken); + if (user.ActivatedAt is not null) return new NotFound(); if (user.UserDeactivation is not null) return new AccountDeactivated(); + if (onlyIfEmailIs is not null && !string.Equals(user.Email, onlyIfEmailIs, StringComparison.OrdinalIgnoreCase)) return new Success(); // Throttle on the outbox itself (it is never auto-pruned), so the limit holds across API instances // and restarts. The signup email counts towards it. diff --git a/Common/OpenShockControllerBase.cs b/Common/OpenShockControllerBase.cs index 1b60b3e18..3d63012fa 100644 --- a/Common/OpenShockControllerBase.cs +++ b/Common/OpenShockControllerBase.cs @@ -1,8 +1,10 @@ using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; using OpenShock.Common.Authentication; using OpenShock.Common.Constants; using OpenShock.Common.Extensions; using OpenShock.Common.Models; +using OpenShock.Common.OpenShockDb; using OpenShock.Common.Options; using OpenShock.Common.Services.Geo; using OpenShock.Common.Services.Session; @@ -51,8 +53,16 @@ protected OkObjectResult LegacyEmptyOk(string message = "") return DomainUtils.GetBestMatchingCookieDomain(HttpContext.Request.Host.Host, cookieDomains); } + /// + /// + /// + /// The account's security stamp as it was when the caller checked the credential it is signing in with. + /// If the stamp has changed by the time the session exists (a password reset completed in between, and + /// its sign-out of all sessions ran before this one was created), the session is dropped again. + /// + /// False when the session was dropped; nothing was set on the response. [NonAction] - protected async Task CreateSession(Guid accountId, string domain) + protected async Task CreateSession(Guid accountId, string domain, Guid? securityStamp = null) { var frontendOptions = HttpContext.RequestServices.GetRequiredService(); var sessionService = HttpContext.RequestServices.GetRequiredService(); @@ -64,6 +74,18 @@ protected async Task CreateSession(Guid accountId, string domain) var session = await sessionService.CreateSessionAsync(accountId, userAgent, remoteIp, actorId: accountId, enrichment: enrichment); + if (securityStamp is not null) + { + // Checked after the session exists: a reset that commits later than this still finds the + // session and deletes it, one that committed earlier shows up here. + var db = HttpContext.RequestServices.GetRequiredService(); + var currentStamp = await db.Users.Where(u => u.Id == accountId).Select(u => (Guid?)u.SecurityStamp).FirstOrDefaultAsync(); + if (currentStamp != securityStamp) + { + await sessionService.DeleteSessionByIdAsync(session.Id); + return false; + } + } HttpContext.Response.Cookies.Append(AuthConstants.UserSessionCookieName, session.Token, new CookieOptions { @@ -80,6 +102,8 @@ protected async Task CreateSession(Guid accountId, string domain) // Signed in, so the post-signup "didn't get the email?" cookie has served its purpose. ActivationResendCookie.Remove(HttpContext); + + return true; } [NonAction] From b88fe20c0e15ee9bcb0423daf582a756adafec47 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Thu, 26 Nov 2026 22:30:24 +0100 Subject: [PATCH 12/14] refactor: name awaited results instead of negating the await The login, the activation path and the OAuth handoff await into a named local and test that, instead of negating or combining the await inline. --- API/Controller/Account/LoginV2.cs | 4 ++-- API/Controller/OAuth/HandOff.cs | 11 +++++++---- API/Services/Account/AccountService.cs | 3 ++- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/API/Controller/Account/LoginV2.cs b/API/Controller/Account/LoginV2.cs index 8beafabad..1fad63224 100644 --- a/API/Controller/Account/LoginV2.cs +++ b/API/Controller/Account/LoginV2.cs @@ -63,8 +63,8 @@ async Task CompleteLoginAsync(User account, string domain) // The password was checked against the account as it was read; if it was replaced since, this // sign-in used the old one. - if (!await CreateSession(account.Id, domain, account.SecurityStamp)) - return Problem(LoginError.InvalidCredentials); + var signedIn = await CreateSession(account.Id, domain, account.SecurityStamp); + if (!signedIn) return Problem(LoginError.InvalidCredentials); return Ok(LoginV2OkResponse.FromUser(account)); } diff --git a/API/Controller/OAuth/HandOff.cs b/API/Controller/OAuth/HandOff.cs index 1864eb415..0ba59048d 100644 --- a/API/Controller/OAuth/HandOff.cs +++ b/API/Controller/OAuth/HandOff.cs @@ -94,10 +94,13 @@ await _accountService.IsEmailRegisteredAsync(externalEmail, cancellationToken)) // A flow started from the account's emailed activation link that comes back with the linked // identity shows inbox and credential are held by the same party, so the account is theirs: // activate it and carry on to the sign-in below. - var isActivated = connection.User.ActivatedAt is not null || - (auth.Properties.Items.TryGetValue(OAuthConstants.ItemKeyActivationToken, out var activationToken) && - !string.IsNullOrEmpty(activationToken) && - await _accountService.TryActivateAccountAsync(connection.UserId, activationToken, cancellationToken)); + var isActivated = connection.User.ActivatedAt is not null; + if (!isActivated && + auth.Properties.Items.TryGetValue(OAuthConstants.ItemKeyActivationToken, out var activationToken) && + !string.IsNullOrEmpty(activationToken)) + { + isActivated = await _accountService.TryActivateAccountAsync(connection.UserId, activationToken, cancellationToken); + } if (!isActivated) { diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index c085eef0c..4aae0c5d8 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -492,7 +492,8 @@ public async Task> Activ return new ActivationCredentialRequired(hasPassword, providers, passwordInvalid); } - if (!await ConsumeActivationTokenAsync(user.Id, hash, cancellationToken)) return new NotFound(); + var activated = await ConsumeActivationTokenAsync(user.Id, hash, cancellationToken); + if (!activated) return new NotFound(); return new Success(); } From e5a10299d9deb5e29c99850a3edcbfc9dd139c5d Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Thu, 26 Nov 2026 22:33:48 +0100 Subject: [PATCH 13/14] refactor: read and write OAuth flow state through extension properties The flow type and the activation token an OAuth flow carries are now Flow and ActivationToken properties on AuthenticationProperties, instead of string keys into its items at every call site. The stored keys are unchanged. --- API.IntegrationTests/Tests/OAuthFlowTests.cs | 13 ++++----- API/Controller/OAuth/HandOff.cs | 4 +-- API/Controller/OAuth/_ApiController.cs | 3 +- API/OAuth/OAuthFlowPropertiesExtensions.cs | 30 ++++++++++++++++++++ API/OAuth/OAuthUtil.cs | 6 ++-- 5 files changed, 41 insertions(+), 15 deletions(-) create mode 100644 API/OAuth/OAuthFlowPropertiesExtensions.cs diff --git a/API.IntegrationTests/Tests/OAuthFlowTests.cs b/API.IntegrationTests/Tests/OAuthFlowTests.cs index 631677a48..aca9967e6 100644 --- a/API.IntegrationTests/Tests/OAuthFlowTests.cs +++ b/API.IntegrationTests/Tests/OAuthFlowTests.cs @@ -46,8 +46,7 @@ public async Task Authorize_WithActivationToken_CarriesItThroughTheProviderRound var response = await client.PostAsync($"/1/oauth/{Provider}/authorize?flow=LoginOrCreate&activationToken=the-mailed-token", null); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Redirect); - var items = ReadStateItems(response); - await Assert.That(items[OAuthConstants.ItemKeyActivationToken]).IsEqualTo("the-mailed-token"); + await Assert.That(ReadState(response).ActivationToken).IsEqualTo("the-mailed-token"); } [Test] @@ -59,7 +58,7 @@ public async Task Authorize_LinkFlow_DoesNotCarryAnActivationToken() var response = await client.PostAsync($"/1/oauth/{Provider}/authorize?flow=Link&activationToken=the-mailed-token", null); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Redirect); - await Assert.That(ReadStateItems(response).ContainsKey(OAuthConstants.ItemKeyActivationToken)).IsFalse(); + await Assert.That(ReadState(response).ActivationToken).IsNull(); } // --- handoff: activating a pending account --- @@ -302,8 +301,8 @@ private string MintFlowCookie(string externalId, string? email = null, bool emai ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10) }; properties.Items[".AuthScheme"] = Provider; - properties.Items[OAuthConstants.ItemKeyFlowType] = flow.ToString(); - if (activationToken is not null) properties.Items[OAuthConstants.ItemKeyActivationToken] = activationToken; + properties.Flow = flow; + properties.ActivationToken = activationToken; var ticket = new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(claims, Provider)), properties, OAuthConstants.FlowScheme); @@ -317,11 +316,11 @@ private string MintSignupBrowserCookie(Guid userId) } /// The properties the authorize endpoint handed to the provider, read back from the state parameter. - private IDictionary ReadStateItems(HttpResponseMessage response) + private AuthenticationProperties ReadState(HttpResponseMessage response) { var state = HttpUtility.ParseQueryString(response.Headers.Location!.Query)["state"]!; var options = WebApplicationFactory.Services.GetRequiredService>().Get(Provider); - return options.StateDataFormat.Unprotect(state)!.Items; + return options.StateDataFormat.Unprotect(state)!; } private static Task HandoffAsync(HttpClient client, string flowCookie) diff --git a/API/Controller/OAuth/HandOff.cs b/API/Controller/OAuth/HandOff.cs index 0ba59048d..a378d20b7 100644 --- a/API/Controller/OAuth/HandOff.cs +++ b/API/Controller/OAuth/HandOff.cs @@ -95,9 +95,7 @@ await _accountService.IsEmailRegisteredAsync(externalEmail, cancellationToken)) // identity shows inbox and credential are held by the same party, so the account is theirs: // activate it and carry on to the sign-in below. var isActivated = connection.User.ActivatedAt is not null; - if (!isActivated && - auth.Properties.Items.TryGetValue(OAuthConstants.ItemKeyActivationToken, out var activationToken) && - !string.IsNullOrEmpty(activationToken)) + if (!isActivated && auth.Properties.ActivationToken is { } activationToken) { isActivated = await _accountService.TryActivateAccountAsync(connection.UserId, activationToken, cancellationToken); } diff --git a/API/Controller/OAuth/_ApiController.cs b/API/Controller/OAuth/_ApiController.cs index 87de71d25..b543dbb8c 100644 --- a/API/Controller/OAuth/_ApiController.cs +++ b/API/Controller/OAuth/_ApiController.cs @@ -56,8 +56,7 @@ private async Task> ValidateO } // 3) parse flow from properties - if (!auth.Properties.Items.TryGetValue(OAuthConstants.ItemKeyFlowType, out var flowStr) || - !Enum.TryParse(flowStr, true, out var flow)) + if (auth.Properties.Flow is not { } flow) { _logger.LogError("Invalid OAuth scheme"); await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); diff --git a/API/OAuth/OAuthFlowPropertiesExtensions.cs b/API/OAuth/OAuthFlowPropertiesExtensions.cs new file mode 100644 index 000000000..1761ef833 --- /dev/null +++ b/API/OAuth/OAuthFlowPropertiesExtensions.cs @@ -0,0 +1,30 @@ +using Microsoft.AspNetCore.Authentication; + +namespace OpenShock.API.OAuth; + +/// +/// What an OAuth flow carries through the provider round trip, as properties on +/// instead of string keys into its items. +/// +public static class OAuthFlowPropertiesExtensions +{ + extension(AuthenticationProperties properties) + { + /// The flow that was started, or null when the properties carry none (or one that is not known). + public OAuthFlow? Flow + { + get => Enum.TryParse(properties.GetString(OAuthConstants.ItemKeyFlowType), ignoreCase: true, out var flow) ? flow : null; + set => properties.SetString(OAuthConstants.ItemKeyFlowType, value?.ToString()); + } + + /// + /// Token from the activation email, carried along so the handoff can activate the account the returned + /// identity is linked to. Null when there is none; setting null or an empty value removes it. + /// + public string? ActivationToken + { + get => properties.GetString(OAuthConstants.ItemKeyActivationToken) is { Length: > 0 } token ? token : null; + set => properties.SetString(OAuthConstants.ItemKeyActivationToken, string.IsNullOrEmpty(value) ? null : value); + } + } +} diff --git a/API/OAuth/OAuthUtil.cs b/API/OAuth/OAuthUtil.cs index f7e7beee1..9c1947497 100644 --- a/API/OAuth/OAuthUtil.cs +++ b/API/OAuth/OAuthUtil.cs @@ -17,12 +17,12 @@ public static ChallengeResult StartOAuth(string provider, OAuthFlow flow, string var properties = new AuthenticationProperties { RedirectUri = $"/1/oauth/{provider}/handoff", - Items = { { OAuthConstants.ItemKeyFlowType, flow.ToString() } } + Flow = flow }; - if (flow == OAuthFlow.LoginOrCreate && !string.IsNullOrEmpty(activationToken)) + if (flow == OAuthFlow.LoginOrCreate) { - properties.Items[OAuthConstants.ItemKeyActivationToken] = activationToken; + properties.ActivationToken = activationToken; } return new ChallengeResult(provider, properties); From a7f6213fbabacbd09b4155a5e7e4c0520e9c4e32 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Thu, 26 Nov 2026 22:39:36 +0100 Subject: [PATCH 14/14] refactor: use OAuthUtil helpers for OAuth flow state instead of extension properties TryGetOAuthFlow, SetOAuthFlow, TryGetActivationToken and SetActivationToken on OAuthUtil replace the extension properties on AuthenticationProperties. --- API.IntegrationTests/Tests/OAuthFlowTests.cs | 9 +++--- API/Controller/OAuth/HandOff.cs | 2 +- API/Controller/OAuth/_ApiController.cs | 2 +- API/OAuth/OAuthFlowPropertiesExtensions.cs | 30 ----------------- API/OAuth/OAuthUtil.cs | 34 +++++++++++++++++--- 5 files changed, 37 insertions(+), 40 deletions(-) delete mode 100644 API/OAuth/OAuthFlowPropertiesExtensions.cs diff --git a/API.IntegrationTests/Tests/OAuthFlowTests.cs b/API.IntegrationTests/Tests/OAuthFlowTests.cs index aca9967e6..e6879395e 100644 --- a/API.IntegrationTests/Tests/OAuthFlowTests.cs +++ b/API.IntegrationTests/Tests/OAuthFlowTests.cs @@ -46,7 +46,8 @@ public async Task Authorize_WithActivationToken_CarriesItThroughTheProviderRound var response = await client.PostAsync($"/1/oauth/{Provider}/authorize?flow=LoginOrCreate&activationToken=the-mailed-token", null); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Redirect); - await Assert.That(ReadState(response).ActivationToken).IsEqualTo("the-mailed-token"); + await Assert.That(OAuthUtil.TryGetActivationToken(ReadState(response), out var carried)).IsTrue(); + await Assert.That(carried).IsEqualTo("the-mailed-token"); } [Test] @@ -58,7 +59,7 @@ public async Task Authorize_LinkFlow_DoesNotCarryAnActivationToken() var response = await client.PostAsync($"/1/oauth/{Provider}/authorize?flow=Link&activationToken=the-mailed-token", null); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Redirect); - await Assert.That(ReadState(response).ActivationToken).IsNull(); + await Assert.That(OAuthUtil.TryGetActivationToken(ReadState(response), out _)).IsFalse(); } // --- handoff: activating a pending account --- @@ -301,8 +302,8 @@ private string MintFlowCookie(string externalId, string? email = null, bool emai ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10) }; properties.Items[".AuthScheme"] = Provider; - properties.Flow = flow; - properties.ActivationToken = activationToken; + OAuthUtil.SetOAuthFlow(properties, flow); + OAuthUtil.SetActivationToken(properties, activationToken); var ticket = new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(claims, Provider)), properties, OAuthConstants.FlowScheme); diff --git a/API/Controller/OAuth/HandOff.cs b/API/Controller/OAuth/HandOff.cs index a378d20b7..a817756d3 100644 --- a/API/Controller/OAuth/HandOff.cs +++ b/API/Controller/OAuth/HandOff.cs @@ -95,7 +95,7 @@ await _accountService.IsEmailRegisteredAsync(externalEmail, cancellationToken)) // identity shows inbox and credential are held by the same party, so the account is theirs: // activate it and carry on to the sign-in below. var isActivated = connection.User.ActivatedAt is not null; - if (!isActivated && auth.Properties.ActivationToken is { } activationToken) + if (!isActivated && OAuthUtil.TryGetActivationToken(auth.Properties, out var activationToken)) { isActivated = await _accountService.TryActivateAccountAsync(connection.UserId, activationToken, cancellationToken); } diff --git a/API/Controller/OAuth/_ApiController.cs b/API/Controller/OAuth/_ApiController.cs index b543dbb8c..581ec95d1 100644 --- a/API/Controller/OAuth/_ApiController.cs +++ b/API/Controller/OAuth/_ApiController.cs @@ -56,7 +56,7 @@ private async Task> ValidateO } // 3) parse flow from properties - if (auth.Properties.Flow is not { } flow) + if (!OAuthUtil.TryGetOAuthFlow(auth.Properties, out var flow)) { _logger.LogError("Invalid OAuth scheme"); await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); diff --git a/API/OAuth/OAuthFlowPropertiesExtensions.cs b/API/OAuth/OAuthFlowPropertiesExtensions.cs deleted file mode 100644 index 1761ef833..000000000 --- a/API/OAuth/OAuthFlowPropertiesExtensions.cs +++ /dev/null @@ -1,30 +0,0 @@ -using Microsoft.AspNetCore.Authentication; - -namespace OpenShock.API.OAuth; - -/// -/// What an OAuth flow carries through the provider round trip, as properties on -/// instead of string keys into its items. -/// -public static class OAuthFlowPropertiesExtensions -{ - extension(AuthenticationProperties properties) - { - /// The flow that was started, or null when the properties carry none (or one that is not known). - public OAuthFlow? Flow - { - get => Enum.TryParse(properties.GetString(OAuthConstants.ItemKeyFlowType), ignoreCase: true, out var flow) ? flow : null; - set => properties.SetString(OAuthConstants.ItemKeyFlowType, value?.ToString()); - } - - /// - /// Token from the activation email, carried along so the handoff can activate the account the returned - /// identity is linked to. Null when there is none; setting null or an empty value removes it. - /// - public string? ActivationToken - { - get => properties.GetString(OAuthConstants.ItemKeyActivationToken) is { Length: > 0 } token ? token : null; - set => properties.SetString(OAuthConstants.ItemKeyActivationToken, string.IsNullOrEmpty(value) ? null : value); - } - } -} diff --git a/API/OAuth/OAuthUtil.cs b/API/OAuth/OAuthUtil.cs index 9c1947497..c8ade66fa 100644 --- a/API/OAuth/OAuthUtil.cs +++ b/API/OAuth/OAuthUtil.cs @@ -1,4 +1,5 @@ -using Microsoft.AspNetCore.Authentication; +using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Mvc; namespace OpenShock.API.OAuth; @@ -16,15 +17,40 @@ public static ChallengeResult StartOAuth(string provider, OAuthFlow flow, string { var properties = new AuthenticationProperties { - RedirectUri = $"/1/oauth/{provider}/handoff", - Flow = flow + RedirectUri = $"/1/oauth/{provider}/handoff" }; + SetOAuthFlow(properties, flow); + if (flow == OAuthFlow.LoginOrCreate) { - properties.ActivationToken = activationToken; + SetActivationToken(properties, activationToken); } return new ChallengeResult(provider, properties); } + + /// Reads the flow that was started. False when the properties carry none, or one that is not known. + public static bool TryGetOAuthFlow(AuthenticationProperties properties, out OAuthFlow flow) + => Enum.TryParse(properties.GetString(OAuthConstants.ItemKeyFlowType), ignoreCase: true, out flow); + + public static void SetOAuthFlow(AuthenticationProperties properties, OAuthFlow flow) + => properties.SetString(OAuthConstants.ItemKeyFlowType, flow.ToString()); + + /// + /// Reads the token from the activation email that the flow carries, so the handoff can activate the + /// account the returned identity is linked to. False when there is none. + /// + public static bool TryGetActivationToken(AuthenticationProperties properties, [NotNullWhen(true)] out string? activationToken) + { + activationToken = properties.GetString(OAuthConstants.ItemKeyActivationToken); + if (!string.IsNullOrEmpty(activationToken)) return true; + + activationToken = null; + return false; + } + + /// Sets the activation token the flow carries. Null or empty removes it. + public static void SetActivationToken(AuthenticationProperties properties, string? activationToken) + => properties.SetString(OAuthConstants.ItemKeyActivationToken, string.IsNullOrEmpty(activationToken) ? null : activationToken); }