From d3559d7d3aaaf4c8e6cd22a449b71a0ac4f3166b Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Thu, 26 Nov 2026 00:49:50 +0100 Subject: [PATCH 01/20] 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/20] 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/20] 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/20] 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/20] 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/20] 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/20] 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/20] 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/20] 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/20] 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/20] 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/20] 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/20] 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/20] 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); } From c631646fecbe2be93943f2df933e614050ce91e6 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 28 Nov 2026 00:14:35 +0100 Subject: [PATCH 15/20] fix: address review findings in the account activation flow - Remove the signup browser cookie by the names on the request, so services without FrontendOptions (the LiveControlGateway) no longer fail on it - Restore POST account/verify-email, session-gated like email-change/verify - Refuse a pending signup's address correction past the account's daily mail cap instead of killing the mailed link with no new one queued - Hold a pending signup's address for an hour (PendingSignupHoldTime) before an unproven signup can replace it - Decide inside the transaction whether a password reset activates the account, so it cannot strip OAuth links from one activated meanwhile - Lock both rows in id order when a correction moves onto a held address - Let email changes ignore pending signups and release them on verification - Return 409 instead of 500 when a verified address is already taken - Map signup-finalize restart results separately - Run the country cookie tests under the LCG suites' parallel key --- API.IntegrationTests/Tests/MailTests.cs | 149 +++++++++++++++++- .../Tests/SignupBrowserCookieCountryTests.cs | 5 +- .../Authenticated/VerifyEmailChange.cs | 20 ++- API/Controller/OAuth/SignupFinalize.cs | 23 ++- API/Services/Account/AccountService.cs | 96 ++++++++--- API/Services/Account/IAccountService.cs | 9 +- .../Authentication/ActivationResendCookie.cs | 8 +- Common/Authentication/SignupBrowserCookie.cs | 20 ++- Common/Constants/Constants.cs | 8 + 9 files changed, 293 insertions(+), 45 deletions(-) diff --git a/API.IntegrationTests/Tests/MailTests.cs b/API.IntegrationTests/Tests/MailTests.cs index 493a05191..9549976be 100644 --- a/API.IntegrationTests/Tests/MailTests.cs +++ b/API.IntegrationTests/Tests/MailTests.cs @@ -21,6 +21,9 @@ namespace OpenShock.API.IntegrationTests.Tests; /// public sealed class MailTests { + /// Just longer than a pending signup keeps its address from an unproven new signup. + private static readonly TimeSpan PastPendingSignupHold = Duration.PendingSignupHoldTime + TimeSpan.FromMinutes(1); + [ClassDataSource(Shared = SharedType.PerTestSession)] public required WebApplicationFactory WebApplicationFactory { get; init; } @@ -470,7 +473,7 @@ 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)); + await BackdateUserAsync(pendingId, PastPendingSignupHold); using var client = CreateCookielessClient(); var response = await SignUpAsync(client, email, TestHelper.UniqueUsername("mailpendingowner")); @@ -495,9 +498,9 @@ public async Task Signup_AddressAlreadySentTheDailyCapOfActivationEmails_Returns 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)); + // Step the pending account and its mail past the hold, so the next signup replaces it. + await BackdateOutboxAsync(email, PastPendingSignupHold); + await BackdatePendingAccountAsync(email, PastPendingSignupHold); } var sixth = await SignUpAsync(client, email, TestHelper.UniqueUsername("mailaddresscap")); @@ -512,14 +515,14 @@ private async Task BackdatePendingAccountAsync(string email, TimeSpan by) 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 + // The hold 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 BackdateUserAsync(pendingId, PastPendingSignupHold); await using (var seedScope = WebApplicationFactory.Services.CreateAsyncScope()) { var seedDb = seedScope.ServiceProvider.GetRequiredService(); @@ -536,7 +539,7 @@ public async Task Signup_EmailHeldByStalePendingAccount_ThatWasJustMailedAgain_R 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 + // While its hold lasts 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() @@ -830,7 +833,7 @@ public async Task RestartPendingSignup_Conflict_LeavesThePendingAccountHoldingTh 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)); + await BackdateUserAsync(holderId, PastPendingSignupHold); var takenUsername = TestHelper.UniqueUsername("mailrestarttaken"); await TestHelper.CreateUserInDb(WebApplicationFactory, takenUsername, TestHelper.UniqueEmail("mail-restart-taken"), "TakenPassword123#"); @@ -891,6 +894,68 @@ public async Task RestartPendingSignup_SameEmail_KeepsTheMailedLinkWorking() await Assert.That(await IsActivatedAsync(userId)).IsTrue(); } + // Past the account's daily cap no mail could go to the corrected address, and the correction kills the + // link already mailed: it has to be refused whole, not leave an account with no working link. + [Test] + public async Task RestartPendingSignup_ChangedEmail_AccountAtTheDailyCap_ChangesNothing_AndKeepsTheMailedLinkWorking() + { + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-restart-cap", password: null); + await AddOAuthConnectionAsync(userId, "discord"); + var originalEmail = await GetEmailAsync(userId); + var newEmail = TestHelper.UniqueEmail("mail-restart-cap-new"); + + 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(); + + // Mailed to a few addresses, as earlier corrections would have: the cap counted is the account's. + for (var i = 0; i < 5; i++) + { + db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(userId, TestHelper.UniqueEmail("mail-restart-cap-earlier"), username)); + } + await db.SaveChangesAsync(); + + var accountService = scope.ServiceProvider.GetRequiredService(); + var restarted = await accountService.RestartPendingSignupAsync(userId, newEmail, username); + await Assert.That(restarted.Value is TooManyActivationResends).IsTrue(); + } + + await Assert.That(await GetEmailAsync(userId)).IsEqualTo(originalEmail); + await Assert.That(await CountOutboxAsync(newEmail)).IsEqualTo(0); + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token, cookie: MintSignupBrowserCookie(userId)); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + } + + // Each moves onto the address the other holds, so each needs both rows locked: taken in the same order + // one waits for the other, taken in opposite orders the database would abort one as a deadlock. + [Test] + public async Task RestartPendingSignup_TwoSignupsMovingOntoEachOthersAddress_DoNotDeadlock() + { + var (firstId, _) = await CreateUnactivatedUserWithTokenAsync("mail-restart-swap-a", password: null); + var (secondId, _) = await CreateUnactivatedUserWithTokenAsync("mail-restart-swap-b", password: null); + await BackdateUserAsync(firstId, PastPendingSignupHold); + await BackdateUserAsync(secondId, PastPendingSignupHold); + var firstEmail = await GetEmailAsync(firstId); + var secondEmail = await GetEmailAsync(secondId); + + async Task RestartAsync(Guid userId, string email) + { + 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(); + return (await accountService.RestartPendingSignupAsync(userId, email, username)).Value!; + } + + // Neither call throws. The one that gets there first takes the other's address and removes it. + var results = await Task.WhenAll(RestartAsync(firstId, secondEmail), RestartAsync(secondId, firstEmail)); + + await Assert.That(results.Count(r => r is User)).IsEqualTo(1); + } + // --- An email change is only confirmed from a session of the account that asked for it --- [Test] @@ -930,6 +995,74 @@ public async Task EmailChangeVerify_FromOwnSession_AppliesChange() await Assert.That(await GetEmailAsync(user.Id)).IsEqualTo(newEmail); } + // The route the verification link used before email-change/verify existed still works, under the same rule. + [Test] + public async Task EmailChangeVerify_LegacyRoute_FromOwnSession_AppliesChange() + { + var (user, token, newEmail) = await CreateUserWithPendingEmailChangeAsync("mail-verify-legacy"); + + using var anonymous = CreateCookielessClient(); + var rejected = await anonymous.PostAsync($"/1/account/verify-email?token={token}", null); + await Assert.That(rejected.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var response = await client.PostAsync($"/1/account/verify-email?token={token}", null); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await GetEmailAsync(user.Id)).IsEqualTo(newEmail); + } + + // --- A never activated account does not keep an existing user from moving to its address --- + + [Test] + public async Task ChangeEmail_AddressHeldByPendingSignup_IsAccepted() + { + const string password = "SecurePassword123#"; + var heldEmail = TestHelper.UniqueEmail("mail-chgemail-pending-held"); + await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailchgemailpending1"), heldEmail, password, activated: false); + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailchgemailpending2"), TestHelper.UniqueEmail("mail-chgemail-pending-own"), password); + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + + var response = await client.PostAsync("/1/account/email-change", TestHelper.JsonContent(new + { + currentPassword = password, + email = heldEmail + })); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + } + + [Test] + public async Task EmailChangeVerify_AddressHeldByPendingSignup_ReleasesIt_AndAppliesChange() + { + var (user, token, newEmail) = await CreateUserWithPendingEmailChangeAsync("mail-verify-pending"); + // Fresh, so a plain signup could not replace it yet: opening the mailed link is proof a signup lacks. + var pendingId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailverifypending"), newEmail, "SquatterPassword123#", activated: false); + + 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); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.Users.AsNoTracking().AnyAsync(u => u.Id == pendingId)).IsFalse(); + } + + [Test] + public async Task EmailChangeVerify_AddressHeldByActivatedAccount_Returns409_AndLeavesEmail() + { + var (user, token, newEmail) = await CreateUserWithPendingEmailChangeAsync("mail-verify-taken"); + await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailverifytaken"), newEmail, "HolderPassword123#"); + + 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.Conflict); + await Assert.That(await GetEmailAsync(user.Id)).IsEqualTo(user.Email); + } + // 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) { diff --git a/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs b/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs index a5a71f7f1..a1e674dd0 100644 --- a/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs +++ b/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs @@ -15,8 +15,9 @@ 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")] +// One at a time: every test moves the single fake location all requests of this host resolve to. The key is +// the one the LCG assignment suites use, because they share this host and read the same fake location. +[NotInParallel("gateway_assignment")] public sealed class SignupBrowserCookieCountryTests { [ClassDataSource(Shared = SharedType.PerTestSession)] diff --git a/API/Controller/Account/Authenticated/VerifyEmailChange.cs b/API/Controller/Account/Authenticated/VerifyEmailChange.cs index ca6dbfe3c..937c8190c 100644 --- a/API/Controller/Account/Authenticated/VerifyEmailChange.cs +++ b/API/Controller/Account/Authenticated/VerifyEmailChange.cs @@ -29,7 +29,25 @@ public sealed partial class AuthenticatedAccountController [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) + public Task EmailVerify([FromQuery(Name = "token")] string token, CancellationToken cancellationToken) + => VerifyPendingEmailChange(token, cancellationToken); + + /// + /// Verify a pending email change of the current user. Deprecated: use POST /email-change/verify instead. + /// + /// 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 + [Obsolete("Use POST /email-change/verify instead.")] + [HttpPost("verify-email")] + [ApiVersion(1)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] // EmailChangeNotFound + [ProducesResponseType(StatusCodes.Status409Conflict, MediaTypeNames.Application.ProblemJson)] // EmailChangeAlreadyInUse + 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, CurrentUser.Id, cancellationToken); diff --git a/API/Controller/OAuth/SignupFinalize.cs b/API/Controller/OAuth/SignupFinalize.cs index aaf2941e8..767e44955 100644 --- a/API/Controller/OAuth/SignupFinalize.cs +++ b/API/Controller/OAuth/SignupFinalize.cs @@ -5,6 +5,7 @@ using OpenShock.API.Models.Requests; using OpenShock.API.Models.Response; using OpenShock.API.OAuth; +using OpenShock.API.Services.Account; using OpenShock.API.Services.OAuthConnection; using OpenShock.Common.ApiVersioning; using OpenShock.Common.Authentication; @@ -112,10 +113,26 @@ public async Task OAuthSignupFinalize( else { var restarted = await _accountService.RestartPendingSignupAsync(existing.UserId, email, username, cancellationToken); - if (restarted.Value is not User pendingUser) + User pendingUser; + switch (restarted.Value) { - // Username or email already exists: keep the flow cookie so the frontend can retry. - return Problem(SignupError.UsernameOrEmailExists); + case User restartedUser: + pendingUser = restartedUser; + break; + case AccountWithEmailOrUsernameExists: + // Keep the flow cookie so the frontend can retry with other details. + return Problem(SignupError.UsernameOrEmailExists); + case TooManyActivationResends: + // Nothing was changed and the link already mailed still works. Other details would + // be refused the same way until the window rolls over, so the flow ends here. + await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); + return Problem(AccountError.AccountActivationResendTooMany); + default: + // No longer a pending signup: it was activated, deactivated or cleaned up since the + // lookup above. Nothing is wrong with the details, so do not ask for different + // ones: signing in with the provider again takes the path that fits what it is now. + await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); + return Problem(OAuthError.FlowNotFound); } ActivationResendCookie.Set(HttpContext, pendingUser.Id, domain); diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index 99a856884..688c6af5e 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -97,6 +97,17 @@ private async Task IsActivationEmailCapReachedAsync(string email, Cancella return sent >= MaxActivationEmailsPerWindow; } + /// The activation emails queued for one account within . + private IQueryable RecentActivationEmails(Guid userId) + { + var coalesceKey = EmailOutboxCoalesceKeys.AccountActivation(userId); + var windowStart = DateTime.UtcNow - Duration.ActivationResendWindow; + return _db.EmailOutbox.Where(m => m.CoalesceKey == coalesceKey && m.CreatedAt >= windowStart); + } + + private Task CountRecentActivationEmailsAsync(Guid userId, CancellationToken cancellationToken) + => RecentActivationEmails(userId).CountAsync(cancellationToken); + private Task IsUserNameBlacklisted(string username, CancellationToken cancellationToken) => _db.UserNameBlacklists.Matching(username).AnyAsync(cancellationToken); @@ -197,9 +208,11 @@ public Task IsEmailRegisteredAsync(string email, CancellationToken cancell /// /// 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. + /// The caller proved the address is theirs (an OAuth provider verified it, or they opened a link mailed + /// to it). Otherwise the pending account is left alone for + /// after it was created or last mailed: that gives its creator time to receive and open the link before + /// someone who merely knows the address can take the signup away, 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. /// @@ -220,11 +233,11 @@ private async Task ReleaseEmailFromPendingAccountAsync(string email, bool claima // 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; + var holdStart = DateTime.UtcNow - Duration.PendingSignupHoldTime; + if (pending.CreatedAt > holdStart) return; var coalesceKey = EmailOutboxCoalesceKeys.AccountActivation(pending.Id); - if (await _db.EmailOutbox.AnyAsync(m => m.CoalesceKey == coalesceKey && m.CreatedAt >= cooldownStart, cancellationToken)) return; + if (await _db.EmailOutbox.AnyAsync(m => m.CoalesceKey == coalesceKey && m.CreatedAt >= holdStart, cancellationToken)) return; } // Only while it still holds this address: its creator may have moved it to another one since the @@ -264,7 +277,7 @@ AND NOT EXISTS (SELECT 1 FROM user_deactivations AS d WHERE d.deactivated_user_i } /// - public async Task> RestartPendingSignupAsync(Guid userId, string email, string username, CancellationToken cancellationToken = default) + public async Task> RestartPendingSignupAsync(Guid userId, string email, string username, CancellationToken cancellationToken = default) { email = email.ToLowerInvariant(); @@ -273,7 +286,16 @@ public async Task> Rest // 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); + + // Releasing the address locks the pending account that holds it as well. Both rows are taken here, + // in id order: two signups each moving onto the other's address would otherwise lock them in + // opposite order and deadlock. + var holderId = await _db.Users + .Where(u => u.Email == email && u.ActivatedAt == null && u.Id != userId) + .Select(u => (Guid?)u.Id) + .FirstOrDefaultAsync(cancellationToken); + Guid[] lockIds = holderId is null ? [userId] : [userId, holderId.Value]; + await _db.Database.ExecuteSqlAsync($"SELECT 1 FROM users WHERE id = ANY({lockIds}) ORDER BY id FOR UPDATE", cancellationToken); var user = await _db.Users .Include(u => u.UserDeactivation) @@ -292,9 +314,18 @@ 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(); + if (emailChanged) + { + // Moving the signup to another address kills the link already mailed, so the new address + // has to get one. Checked before anything changes: past the account's cap no mail would be + // queued below, leaving an account that reports success and has no working link at all. + if (await CountRecentActivationEmailsAsync(userId, cancellationToken) >= MaxActivationEmailsPerWindow) + return new TooManyActivationResends(); + + // Moving the signup to another address mails that address. + if (await IsActivationEmailCapReachedAsync(email, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); + } await ReleaseEmailFromPendingAccountAsync(email, claimantOwnsEmail: false, exceptUserId: userId, cancellationToken); @@ -341,9 +372,10 @@ 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. If another correction got in since the commit - // above, the mail for this one is dropped: that correction queues its own. + // does not apply to it; the daily cap per account was checked above, before the old link was killed. + // For unchanged details a throttled result just means no new mail went out: the link already mailed + // still works, and the resend button gets a new one 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; @@ -584,10 +616,7 @@ private async Task m.CoalesceKey == coalesceKey && m.CreatedAt >= windowStart) + var recent = await RecentActivationEmails(userId) .Select(m => m.CreatedAt) .ToListAsync(cancellationToken); @@ -873,7 +902,6 @@ 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 @@ -886,6 +914,15 @@ public async Task> await using var transaction = await _db.Database.BeginTransactionAsync(); + // Whether this reset is what activates the account decides below if its OAuth links are dropped. + // Activating does not rotate the security stamp, so the stamp check in the update cannot tell that + // the account was activated since the read above: lock the row, as activation does, and look now. + await _db.Database.ExecuteSqlAsync($"SELECT 1 FROM users WHERE id = {reset.Reset.UserId} FOR UPDATE", cancellationToken); + var wasActivated = await _db.Users + .Where(u => u.Id == reset.Reset.UserId) + .Select(u => u.ActivatedAt != null) + .FirstOrDefaultAsync(cancellationToken); + // Race-safe consume + apply: only updates if SecurityStamp still matches the snapshot. // If a sibling reset (or a separate password/email change) completed since the read above, // the stamp has rotated and the predicate matches zero rows. @@ -919,7 +956,7 @@ await _db.UserPasswordResets // 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) + if (!wasActivated) { var connections = _db.UserOAuthConnections.Where(c => c.UserId == reset.Reset.UserId); removedProviders = await connections.Select(c => c.ProviderKey).ToListAsync(); @@ -971,7 +1008,8 @@ await _auditService.LogAsync( public async Task> CheckEmailAvailability(string email, CancellationToken cancellationToken = default) { - var isTaken = await _db.Users.AnyAsync(x => x.Email == email, cancellationToken: cancellationToken); + // A never activated account is only a pending signup and does not reserve its address. + var isTaken = await _db.Users.AnyAsync(x => x.Email == email && x.ActivatedAt != null, cancellationToken: cancellationToken); if (isTaken) return new EmailTaken(); return new Success(); @@ -1069,6 +1107,10 @@ public async Task> await using var transaction = await _db.Database.BeginTransactionAsync(); + // An administrator decided whose address this is, so a pending signup parked on it goes. Part of + // this transaction: it only stays removed if the change is committed. + await ReleaseEmailFromPendingAccountAsync(email, claimantOwnsEmail: true, exceptUserId: userId, cancellationToken); + user.Email = email; // Outstanding reset and email-change rows carry the stamp they were created under, so rotating // it invalidates them here. Without this a pending email-change verification could later @@ -1149,8 +1191,10 @@ public async Task x.Email == lowerCaseEmail, cancellationToken)) + if (await _db.Users.AnyAsync(x => x.Email == lowerCaseEmail && x.ActivatedAt != null, cancellationToken)) return new EmailAlreadyInUse(); // The verification token is minted lazily by the outbox delivery job at send time, so no usable @@ -1225,6 +1269,11 @@ public async Task> TryVe var newStamp = Guid.CreateVersion7(); try { + // The caller opened the link mailed to the new address while signed in, which proves it is + // theirs: a pending signup someone parked on it goes. Rolled back with the transaction on every + // return below that does not commit. + await ReleaseEmailFromPendingAccountAsync(change.NewEmail, claimantOwnsEmail: true, exceptUserId: change.UserId, cancellationToken); + var userRows = await _db.Users .Where(u => u.Id == change.UserId && u.SecurityStamp == change.SecurityStampAtCreate) .ExecuteUpdateAsync(s => s @@ -1232,8 +1281,9 @@ public async Task> TryVe .SetProperty(u => u.SecurityStamp, newStamp)); if (userRows == 0) return new NotFound(); } - catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: "23505" }) + catch (PostgresException ex) when (ex.SqlState == PostgresErrorCodes.UniqueViolation) { + // A bulk update is not wrapped in a DbUpdateException the way SaveChanges wraps it. // Another account claimed this email between request creation and verification. // The pending row stays as-is (not marked used) so it can expire naturally. return new EmailAlreadyInUse(); diff --git a/API/Services/Account/IAccountService.cs b/API/Services/Account/IAccountService.cs index 32f96f368..dad2343c0 100644 --- a/API/Services/Account/IAccountService.cs +++ b/API/Services/Account/IAccountService.cs @@ -48,9 +48,14 @@ public interface IAccountService /// /// 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. + /// hold the account's credential. Sends are capped per account like any activation resend: an address + /// change past that cap is refused with and changes nothing, + /// because the link already mailed would stop working with no new one to replace it. /// - Task> RestartPendingSignupAsync(Guid userId, string email, string username, CancellationToken cancellationToken = default); + /// + /// when the account is not a pending signup (any more): activated, deactivated or deleted. + /// + 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 diff --git a/Common/Authentication/ActivationResendCookie.cs b/Common/Authentication/ActivationResendCookie.cs index c1dfaa088..a733076be 100644 --- a/Common/Authentication/ActivationResendCookie.cs +++ b/Common/Authentication/ActivationResendCookie.cs @@ -77,8 +77,12 @@ public static void Remove(HttpContext context) if (!context.Request.Cookies.ContainsKey(AuthConstants.ActivationResendCookieName)) return; - var cookieDomains = context.RequestServices.GetRequiredService().CookieDomains; - foreach (var domain in cookieDomains) + // A service without frontend options (the LiveControlGateway) never issues this cookie and does not + // know the domains to remove it from: leave it for the API, rather than fail the request over it. + var frontendOptions = context.RequestServices.GetService(); + if (frontendOptions is null) return; + + foreach (var domain in frontendOptions.CookieDomains) { context.Response.Cookies.Delete(AuthConstants.ActivationResendCookieName, new CookieOptions { Domain = domain }); } diff --git a/Common/Authentication/SignupBrowserCookie.cs b/Common/Authentication/SignupBrowserCookie.cs index caa154ccc..bb568bc88 100644 --- a/Common/Authentication/SignupBrowserCookie.cs +++ b/Common/Authentication/SignupBrowserCookie.cs @@ -93,15 +93,27 @@ public static bool TryGetUserId(HttpContext context, [NotNullWhen(true)] out Gui } } - /// Deletes the cookie, if the request carries one. + /// Deletes the cookie, if the request carries one, under either of its names. + /// + /// Goes by what the request carries instead of : this runs on every request a + /// session authenticates, also in services that never issue the cookie and have no + /// registered (the LiveControlGateway). + /// public static void Remove(HttpContext context) { - var name = GetName(context); - if (!context.Request.Cookies.ContainsKey(name)) return; + // A __Host- cookie only exists as a secure one, and browsers ignore its removal unless that is secure too. + if (context.Request.Cookies.ContainsKey(AuthConstants.SignupBrowserSecureCookieName)) + Delete(context, AuthConstants.SignupBrowserSecureCookieName, secure: true); + if (context.Request.Cookies.ContainsKey(AuthConstants.SignupBrowserCookieName)) + Delete(context, AuthConstants.SignupBrowserCookieName, secure: context.Request.IsHttps); + } + + private static void Delete(HttpContext context, string name, bool secure) + { context.Response.Cookies.Delete(name, new CookieOptions { - Secure = IsSecure(context), + Secure = secure, HttpOnly = true, SameSite = SameSiteMode.Lax, Path = "/" diff --git a/Common/Constants/Constants.cs b/Common/Constants/Constants.cs index 372015cac..f9b6209a6 100644 --- a/Common/Constants/Constants.cs +++ b/Common/Constants/Constants.cs @@ -11,6 +11,14 @@ public static class Duration public static readonly TimeSpan ActivationResendCooldown = TimeSpan.FromMinutes(10); public static readonly TimeSpan ActivationResendWindow = TimeSpan.FromHours(24); + + /// + /// How long a never activated account keeps its address from a new signup that has not proven the + /// address is theirs, counted from its creation and from its last activation email. Long enough for a + /// delayed email to arrive and be opened, so someone who only knows the address cannot take a signup + /// away from the person completing it. + /// + public static readonly TimeSpan PendingSignupHoldTime = TimeSpan.FromHours(1); public static readonly TimeSpan UnactivatedAccountRetentionTime = TimeSpan.FromDays(7); public static readonly TimeSpan NameChangeCooldown = TimeSpan.FromDays(7); From f2dde1468c7a1c12e077258535cb7d91a349f72a Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 28 Nov 2026 02:15:01 +0100 Subject: [PATCH 16/20] fix: address remaining account flow review findings - Assert invalidated password reset links return 404 - Reserve activation capacity for OAuth resend and normalize recipients - Queue corrected signup activation mail transactionally - Recheck activation state and clean up failed login sessions - Document pending OAuth signup behavior and harden concurrent tests --- API.IntegrationTests/Tests/MailTests.cs | 88 +++++++++++++++++++++++-- API/Controller/OAuth/HandOff.cs | 2 +- API/Services/Account/AccountService.cs | 76 ++++++++++++++++----- API/Services/Account/IAccountService.cs | 12 +++- Common/OpenShockControllerBase.cs | 20 +++++- 5 files changed, 171 insertions(+), 27 deletions(-) diff --git a/API.IntegrationTests/Tests/MailTests.cs b/API.IntegrationTests/Tests/MailTests.cs index 9549976be..bab6270d5 100644 --- a/API.IntegrationTests/Tests/MailTests.cs +++ b/API.IntegrationTests/Tests/MailTests.cs @@ -823,7 +823,7 @@ public async Task RestartPendingSignup_ChangedEmail_InvalidatesAPasswordResetReq 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(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound); await Assert.That(await IsActivatedAsync(userId)).IsFalse(); } @@ -929,6 +929,75 @@ public async Task RestartPendingSignup_ChangedEmail_AccountAtTheDailyCap_Changes await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); } + // The mail to the corrected address is queued by the correction itself, in its transaction: there is + // no moment where the old link is dead and nothing is on its way to the new address. + [Test] + public async Task RestartPendingSignup_ChangedEmail_QueuesTheMailToTheNewAddress() + { + var (userId, _) = await CreateUnactivatedUserWithTokenAsync("mail-restart-queued", password: null); + var newEmail = TestHelper.UniqueEmail("mail-restart-queued-new"); + + 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, newEmail, username); + + await Assert.That(restarted.Value is User).IsTrue(); + await Assert.That(await CountOutboxAsync(newEmail)).IsEqualTo(1); + } + + // The delivery job skips an activation mail whose account has no activation request to mint a token on, + // so a correction has to leave one behind even where none existed. + [Test] + public async Task RestartPendingSignup_ChangedEmail_AccountWithoutActivationRequest_CreatesOne() + { + var (userId, _) = await CreateUnactivatedUserWithTokenAsync("mail-restart-norequest", password: null); + var newEmail = TestHelper.UniqueEmail("mail-restart-norequest-new"); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await db.UserActivationRequests.Where(r => r.UserId == userId).ExecuteDeleteAsync(); + 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, newEmail, username); + + await Assert.That(restarted.Value is User).IsTrue(); + await Assert.That(await db.UserActivationRequests.AsNoTracking().CountAsync(r => r.UserId == userId)).IsEqualTo(1); + await Assert.That(await CountOutboxAsync(newEmail)).IsEqualTo(1); + } + + // The resend an OAuth sign-in triggers on its own stops one short of the account's cap: the last send + // is kept for correcting the address, which a resend the user asks for may still use. + [Test] + public async Task ResendActivationForOAuth_OneSendLeftInTheWindow_LeavesItForACorrection() + { + var (userId, _) = await CreateUnactivatedUserWithTokenAsync("mail-oauth-reserve", password: null); + var email = await GetEmailAsync(userId); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + for (var i = 0; i < 4; i++) + { + db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(userId, email, "pending")); + } + await db.SaveChangesAsync(); + // Past the cooldown, so only the cap is left to refuse a resend. + await BackdateOutboxAsync(email, TimeSpan.FromMinutes(11)); + + var accountService = scope.ServiceProvider.GetRequiredService(); + + var automatic = await accountService.ResendActivationEmailForOAuthAsync(userId); + await Assert.That(automatic.Value is TooManyActivationResends).IsTrue(); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(4); + + var requested = await accountService.ResendActivationEmailAsync(userId); + await Assert.That(requested.Value is OpenShock.Common.Results.Success).IsTrue(); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(5); + } + // Each moves onto the address the other holds, so each needs both rows locked: taken in the same order // one waits for the other, taken in opposite orders the database would abort one as a deadlock. [Test] @@ -940,18 +1009,25 @@ public async Task RestartPendingSignup_TwoSignupsMovingOntoEachOthersAddress_DoN await BackdateUserAsync(secondId, PastPendingSignupHold); var firstEmail = await GetEmailAsync(firstId); var secondEmail = await GetEmailAsync(secondId); - - async Task RestartAsync(Guid userId, string email) + await using var usernameScope = WebApplicationFactory.Services.CreateAsyncScope(); + var usernameDb = usernameScope.ServiceProvider.GetRequiredService(); + var usernames = await usernameDb.Users.AsNoTracking() + .Where(u => u.Id == firstId || u.Id == secondId) + .ToDictionaryAsync(u => u.Id, u => u.Name); + var firstUsername = usernames[firstId]; + var secondUsername = usernames[secondId]; + + async Task RestartAsync(Guid userId, string email, string username) { 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(); return (await accountService.RestartPendingSignupAsync(userId, email, username)).Value!; } // Neither call throws. The one that gets there first takes the other's address and removes it. - var results = await Task.WhenAll(RestartAsync(firstId, secondEmail), RestartAsync(secondId, firstEmail)); + var results = await Task.WhenAll( + RestartAsync(firstId, secondEmail, firstUsername), + RestartAsync(secondId, firstEmail, secondUsername)); await Assert.That(results.Count(r => r is User)).IsEqualTo(1); } diff --git a/API/Controller/OAuth/HandOff.cs b/API/Controller/OAuth/HandOff.cs index a817756d3..09cd3d63d 100644 --- a/API/Controller/OAuth/HandOff.cs +++ b/API/Controller/OAuth/HandOff.cs @@ -107,7 +107,7 @@ await _accountService.IsEmailRegisteredAsync(externalEmail, cancellationToken)) // address on the account was typed in at signup and is not known to be theirs. try { - await _accountService.ResendActivationEmailAsync(connection.UserId, cancellationToken); + await _accountService.ResendActivationEmailForOAuthAsync(connection.UserId, cancellationToken); } catch (Exception ex) when (ex is not OperationCanceledException) { diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index 688c6af5e..db14e43c5 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -182,7 +182,7 @@ public async Task CreateAccountWithActivationFlowAsync(st TokenHash = SeedTokenHash() }; - _db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(user.Id, email, username)); + _db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(user.Id, user.Email, username)); await _db.SaveChangesAsync(); } @@ -346,11 +346,23 @@ public async Task ConsumeActivationTokenAsync(Guid userId, string tokenHa // 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 canActivate = await _db.Users + .AnyAsync(u => u.Id == userId && u.ActivatedAt == null && u.UserDeactivation == null, cancellationToken); + if (!canActivate) return false; + var consumed = await _db.UserActivationRequests .Where(r => r.UserId == userId && r.TokenHash == tokenHash) .ExecuteDeleteAsync(cancellationToken); @@ -585,13 +606,21 @@ public async Task public Task> ResendActivationEmailAsync(Guid userId, CancellationToken cancellationToken = default) - => ResendActivationEmailCoreAsync(userId, ignoreCooldown: false, onlyIfEmailIs: null, cancellationToken); + => ResendActivationEmailCoreAsync(userId, ignoreCooldown: false, onlyIfEmailIs: null, reserveCorrectionCapacity: false, cancellationToken); + + /// + public Task> ResendActivationEmailForOAuthAsync(Guid userId, CancellationToken cancellationToken = default) + => ResendActivationEmailCoreAsync(userId, ignoreCooldown: false, onlyIfEmailIs: null, reserveCorrectionCapacity: true, cancellationToken); /// /// /// When given, nothing is queued unless this is still the account's address. + /// + /// Stop one short of the account's cap, so a resend nobody asked for cannot use up the send that + /// correcting the signup's address needs. + /// /// - private async Task> ResendActivationEmailCoreAsync(Guid userId, bool ignoreCooldown, string? onlyIfEmailIs, CancellationToken cancellationToken) + private async Task> ResendActivationEmailCoreAsync(Guid userId, bool ignoreCooldown, string? onlyIfEmailIs, bool reserveCorrectionCapacity, CancellationToken cancellationToken) { // Without mail no link can be delivered (and such accounts are activated on creation anyway). if (!_mailOptions.IsEnabled) return new NotFound(); @@ -620,7 +649,8 @@ private async Task m.CreatedAt) .ToListAsync(cancellationToken); - if (recent.Count >= MaxActivationEmailsPerWindow || (!ignoreCooldown && recent.Any(createdAt => createdAt >= DateTime.UtcNow - Duration.ActivationResendCooldown))) + var maxRecent = reserveCorrectionCapacity ? MaxActivationEmailsPerWindow - 1 : MaxActivationEmailsPerWindow; + if (recent.Count >= maxRecent || (!ignoreCooldown && recent.Any(createdAt => createdAt >= DateTime.UtcNow - Duration.ActivationResendCooldown))) return new TooManyActivationResends(); if (await IsActivationEmailCapReachedAsync(user.Email, cancellationToken)) @@ -991,14 +1021,26 @@ await _auditService.LogAsync( await transaction.CommitAsync(); - // 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) + // A sign-in with the old password may have slipped in between the two steps above. The reset is + // committed and its link used up, so failing the request here would report an error for a password + // that did change, with nothing left to retry: try the sign-out again instead, and give up loudly. + const int signOutAttempts = 3; + for (var attempt = 1; attempt <= signOutAttempts; attempt++) { - _logger.LogWarning(ex, "Failed to re-check sessions after password reset for user ID: [{Id}]", reset.Reset.UserId); + try + { + await _sessionService.DeleteSessionsByUserIdAsync(reset.Reset.UserId); + break; + } + catch (Exception ex) when (attempt < signOutAttempts) + { + _logger.LogWarning(ex, "Failed to re-check sessions after password reset for user ID: [{Id}], retrying", reset.Reset.UserId); + await Task.Delay(TimeSpan.FromMilliseconds(100 * attempt), CancellationToken.None); + } + catch (Exception ex) + { + _logger.LogError(ex, "Failed to re-check sessions after password reset for user ID: [{Id}]; a session created during the reset may still be alive", reset.Reset.UserId); + } } return new Success(); diff --git a/API/Services/Account/IAccountService.cs b/API/Services/Account/IAccountService.cs index dad2343c0..deb2b9a8e 100644 --- a/API/Services/Account/IAccountService.cs +++ b/API/Services/Account/IAccountService.cs @@ -21,8 +21,10 @@ public interface IAccountService /// /// Creates an OAuth-only (passwordless) account and links the external identity in a single transaction. - /// The new user is activated immediately (no activation flow). Returns a conflict-style result if the - /// username/email is taken or the external identity is already linked. + /// The new user is activated immediately for a trusted provider address (or when mail is disabled). + /// With mail enabled and an unverified provider address, the user remains pending and an activation + /// email is queued; SignupFinalize does not create a session until that flow is completed. Returns a + /// conflict-style result if the username/email is taken or the external identity is already linked. /// /// Email to set on the user. /// Desired unique username. @@ -101,6 +103,12 @@ public interface IAccountService /// NotFound when there is nothing to resend (unknown user, already activated, or mail disabled). Task> ResendActivationEmailAsync(Guid userId, CancellationToken cancellationToken = default); + /// + /// Re-enqueues an activation email after an OAuth login while preserving one account-level send slot + /// for a pending-signup email correction. + /// + Task> ResendActivationEmailForOAuthAsync(Guid userId, CancellationToken cancellationToken = default); + public Task> DeactivateAccountAsync(Guid executingUserId, Guid userId, bool deleteLater = true, string? reason = null, CancellationToken cancellationToken = default); public Task> ReactivateAccountAsync(Guid executingUserId, Guid userId, string? reason = null, CancellationToken cancellationToken = default); diff --git a/Common/OpenShockControllerBase.cs b/Common/OpenShockControllerBase.cs index 3d63012fa..2c29881ec 100644 --- a/Common/OpenShockControllerBase.cs +++ b/Common/OpenShockControllerBase.cs @@ -79,7 +79,25 @@ protected async Task CreateSession(Guid accountId, string domain, Guid? se // 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(); + Guid? currentStamp; + try + { + currentStamp = await db.Users.Where(u => u.Id == accountId).Select(u => (Guid?)u.SecurityStamp).FirstOrDefaultAsync(); + } + catch + { + try + { + await sessionService.DeleteSessionByIdAsync(session.Id); + } + catch (Exception cleanupException) + { + HttpContext.RequestServices.GetRequiredService>() + .LogError(cleanupException, "Failed to clean up session {SessionId} after the security-stamp check failed", session.Id); + } + + throw; + } if (currentStamp != securityStamp) { await sessionService.DeleteSessionByIdAsync(session.Id); From 65a594b46469e9623571d0de742f38cd9245ded5 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 28 Nov 2026 21:15:49 +0100 Subject: [PATCH 17/20] fix: serialize the per-address activation email cap The cap counted an address's activation mail without a lock, so requests for different accounts could read the same count and all queue mail. - Add TryLockForTransactionAsync, a transaction-scoped lock on any name - Lock the address before counting and hold it until the mail commits - Refuse a request that meets the lock instead of waiting, which would deadlock against the row locks other paths take first - Move the OAuth signup's cap check inside its transaction --- API.IntegrationTests/Tests/MailTests.cs | 27 +++++++++++++++ API/Services/Account/AccountService.cs | 23 ++++++++++--- .../Extensions/TransactionLockExtensions.cs | 33 +++++++++++++++++++ 3 files changed, 79 insertions(+), 4 deletions(-) create mode 100644 Common/OpenShockDb/Extensions/TransactionLockExtensions.cs diff --git a/API.IntegrationTests/Tests/MailTests.cs b/API.IntegrationTests/Tests/MailTests.cs index bab6270d5..443cd49a0 100644 --- a/API.IntegrationTests/Tests/MailTests.cs +++ b/API.IntegrationTests/Tests/MailTests.cs @@ -508,6 +508,33 @@ public async Task Signup_AddressAlreadySentTheDailyCapOfActivationEmails_Returns await Assert.That(await CountOutboxAsync(email)).IsEqualTo(5); } + // The count behind the cap is only good while nobody else queues mail for the address, so counting and + // queueing hold a lock on the address. A request that meets the lock is turned away, not left to queue + // on a count that is about to be out of date. + [Test] + public async Task Signup_WhileAnotherRequestQueuesActivationMailForTheAddress_Returns409_AndMailsNothing() + { + var email = TestHelper.UniqueEmail("mail-address-lock"); + + using var client = CreateCookielessClient(); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + // Stands in for a request that has counted the address's mail and not yet committed its own. + var db = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await db.Database.BeginTransactionAsync(); + await Assert.That(await db.Database.TryLockForTransactionAsync(AccountService.ActivationEmailLockName(email))).IsTrue(); + + var blocked = await SignUpAsync(client, email, TestHelper.UniqueUsername("mailaddresslock")); + await Assert.That(blocked.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); + } + + var afterwards = await SignUpAsync(client, email, TestHelper.UniqueUsername("mailaddresslock")); + await Assert.That(afterwards.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(1); + } + private async Task BackdatePendingAccountAsync(string email, TimeSpan by) { await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index db14e43c5..50fd39fa3 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -79,16 +79,31 @@ private async Task NotifyEmailOutboxAsync() /// Most activation emails one account, and one address, is sent per . private const int MaxActivationEmailsPerWindow = 5; + /// Name of the transaction lock that serializes queueing activation mail for one address. + /// Lowercased address. + public static string ActivationEmailLockName(string email) => "activation-email:" + email; + /// /// 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. /// + /// + /// Must be called inside the transaction that queues the mail. The count is only good until someone + /// else queues mail for the address, so the address is locked from here to the end of that transaction: + /// without it, requests for different accounts could all read the same count and all queue. + /// A request that finds the address locked is turned away as if the cap were reached, instead of + /// waiting: another activation mail to that inbox is being queued this very moment, and waiting would + /// mean holding this lock and row locks in an order other requests take the other way around. + /// /// Lowercased address. /// private async Task IsActivationEmailCapReachedAsync(string email, CancellationToken cancellationToken) { + if (!await _db.Database.TryLockForTransactionAsync(ActivationEmailLockName(email), cancellationToken)) + return true; + var windowStart = DateTime.UtcNow - Duration.ActivationResendWindow; var sent = await _db.EmailOutbox.CountAsync( m => m.Recipient == email && m.Type == EmailType.AccountActivation && m.CreatedAt >= windowStart, @@ -423,16 +438,16 @@ 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); try { + // An unverified address gets an activation email. Checked before anything is removed to make room. + if (!isEmailTrusted && await IsActivationEmailCapReachedAsync(email, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); + if (replacePendingUserId is not null) { await DeletePendingAccountAsync(replacePendingUserId.Value, heldEmail: null, cancellationToken); diff --git a/Common/OpenShockDb/Extensions/TransactionLockExtensions.cs b/Common/OpenShockDb/Extensions/TransactionLockExtensions.cs new file mode 100644 index 000000000..fea4a337d --- /dev/null +++ b/Common/OpenShockDb/Extensions/TransactionLockExtensions.cs @@ -0,0 +1,33 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; + +namespace OpenShock.Common.OpenShockDb; + +public static class TransactionLockExtensions +{ + /// + /// Tries to lock an arbitrary name for the rest of the current transaction, without waiting. Use it to + /// serialize work that has no row of its own to lock, such as a count followed by an insert. + /// + /// + /// The lock is a Postgres advisory lock: it locks nothing but the name, and only against others that + /// ask for the same name. It is released when the transaction commits or rolls back, and asking again + /// inside the same transaction succeeds. The name is hashed to the 64 bit key such a lock takes, so two + /// names can in theory collide; that costs a refusal that was not needed, never a missed lock. + /// + /// + /// What to lock. Prefix it with its purpose so unrelated uses cannot meet. + /// + /// False when another transaction holds the lock. + /// There is no transaction for the lock to live in. + public static async Task TryLockForTransactionAsync(this DatabaseFacade database, string name, CancellationToken cancellationToken = default) + { + if (database.CurrentTransaction is null) + throw new InvalidOperationException("A transaction lock can only be taken inside a transaction"); + + // SqlQuery reads a scalar from a column named Value. + return await database + .SqlQuery($"""SELECT pg_try_advisory_xact_lock(hashtextextended({name}, 0)) AS "Value" """) + .SingleAsync(cancellationToken); + } +} From 18452fea733ed6cc21280d3845b86a2cfc47a755 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sat, 28 Nov 2026 23:29:48 +0100 Subject: [PATCH 18/20] feat: verify the address before an account exists, with a mailed code Signing up no longer creates an account. It records a pending signup, holding the password hash or OAuth identity, and mails a six digit code. The account is created when that code is entered in a browser that holds the signup: the one that started it, or one that has since signed in with the signup's password or provider. A code instead of a link, so nothing in the mail can be clicked by whoever merely receives it. That removes the password prompt on activation, the 403 Account.Activation.CredentialRequired response and the activation token carried through the OAuth round trip. Pending signups live in their own table and do not reserve the address, so any number can wait on one address and the first to enter its code gets it. That removes the hold time, the release of pending accounts and the row lock ordering that came with keeping them in users. The username is kept from other signups and renames for one hour, then opens up again. - POST /1/account/activate takes { code } and the signup cookie - codes last one hour and allow five wrong attempts; a resend replaces them - user_activation_requests is dropped; the migration turns never activated accounts into pending signups, leaving deactivated and privileged ones and any that own a hub or API token - the hourly cleanup deletes pending signups older than 24 hours - password reset no longer activates or unlinks anything, since an unverified account cannot exist - the admin user view loses activationRequest --- .../Helpers/PendingSignupHelper.cs | 165 ++ .../Tests/AccountSignupTests.cs | 10 + API.IntegrationTests/Tests/AccountTests.cs | 11 + .../Tests/AutomationTokenTests.cs | 11 + .../Tests/MailDisabledTests.cs | 8 +- API.IntegrationTests/Tests/MailTests.cs | 947 +------- API.IntegrationTests/Tests/OAuthFlowTests.cs | 348 ++- .../Tests/PendingSignupsMigrationTests.cs | 108 + .../Tests/SignupActivationTests.cs | 793 +++++++ .../Tests/SignupBrowserCookieCountryTests.cs | 108 +- API/Controller/Account/Activate.cs | 57 +- API/Controller/Account/LoginV2.cs | 20 +- API/Controller/Account/ResendActivation.cs | 19 +- API/Controller/Account/SignupV2.cs | 24 +- API/Controller/Admin/GetUser.cs | 14 - API/Controller/OAuth/Authorize.cs | 5 +- API/Controller/OAuth/HandOff.cs | 58 +- API/Controller/OAuth/SignupFinalize.cs | 98 +- API/Models/Response/LoginV2OkResponse.cs | 15 + API/OAuth/OAuthConstants.cs | 1 - API/OAuth/OAuthUtil.cs | 34 +- API/Program.cs | 4 +- API/Services/Account/AccountService.cs | 803 +++---- API/Services/Account/IAccountService.cs | 140 +- .../Authentication/ActivationResendCookie.cs | 37 +- Common/Authentication/SignupBrowserCookie.cs | 38 +- Common/Constants/ApiHardLimits.cs | 1 - Common/Constants/AuthConstants.cs | 6 + Common/Constants/Constants.cs | 22 +- Common/Errors/AccountError.cs | 14 +- .../20261128213633_PendingSignups.Designer.cs | 1927 +++++++++++++++++ .../20261128213633_PendingSignups.cs | 142 ++ .../OpenShockContextModelSnapshot.cs | 151 +- .../Keys/EmailOutboxCoalesceKeys.cs | 4 +- .../Keys/EmailOutboxPayloadKeys.cs | 4 +- .../OpenShockDb/Models/EmailOutboxMessage.cs | 8 +- Common/OpenShockDb/Models/PendingSignup.cs | 58 + Common/OpenShockDb/Models/User.cs | 1 - .../Models/UserActivationRequest.cs | 20 - Common/OpenShockDb/OpenShockContext.cs | 70 +- Common/Utils/ActivationCode.cs | 28 + .../Tests/DeleteExpiredPendingSignupsTests.cs | 59 + .../Tests/DeleteUnactivatedAccountsTests.cs | 91 - .../Tests/EmailOutboxDeliveryTests.cs | 111 +- Cron/Jobs/DeleteExpiredPendingSignupsJob.cs | 46 + Cron/Jobs/DeleteUnactivatedAccountsJob.cs | 57 - Cron/Services/Email/IEmailService.cs | 8 +- .../Email/Mailjet/MailjetEmailService.cs | 4 +- Cron/Services/Email/NoneEmailService.cs | 2 +- .../Email/Outbox/EmailOutboxDispatcher.cs | 53 +- Cron/Services/Email/Smtp/SmtpEmailService.cs | 4 +- Cron/SmtpTemplates/AccountActivation.liquid | 58 +- SeedE2E/Program.cs | 1 - .../Seeders/UserActivationRequestSeeder.cs | 43 - email-templates/emails/AccountActivation.tsx | 27 +- email-templates/emails/_lib/components.tsx | 5 + email-templates/emails/_lib/styles.ts | 14 + 57 files changed, 4430 insertions(+), 2485 deletions(-) create mode 100644 API.IntegrationTests/Helpers/PendingSignupHelper.cs create mode 100644 API.IntegrationTests/Tests/PendingSignupsMigrationTests.cs create mode 100644 API.IntegrationTests/Tests/SignupActivationTests.cs create mode 100644 Common/Migrations/20261128213633_PendingSignups.Designer.cs create mode 100644 Common/Migrations/20261128213633_PendingSignups.cs create mode 100644 Common/OpenShockDb/Models/PendingSignup.cs delete mode 100644 Common/OpenShockDb/Models/UserActivationRequest.cs create mode 100644 Common/Utils/ActivationCode.cs create mode 100644 Cron.IntegrationTests/Tests/DeleteExpiredPendingSignupsTests.cs delete mode 100644 Cron.IntegrationTests/Tests/DeleteUnactivatedAccountsTests.cs create mode 100644 Cron/Jobs/DeleteExpiredPendingSignupsJob.cs delete mode 100644 Cron/Jobs/DeleteUnactivatedAccountsJob.cs delete mode 100644 SeedE2E/Seeders/UserActivationRequestSeeder.cs diff --git a/API.IntegrationTests/Helpers/PendingSignupHelper.cs b/API.IntegrationTests/Helpers/PendingSignupHelper.cs new file mode 100644 index 000000000..cc5d71df7 --- /dev/null +++ b/API.IntegrationTests/Helpers/PendingSignupHelper.cs @@ -0,0 +1,165 @@ +using Microsoft.AspNetCore.DataProtection; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenShock.Common.Authentication; +using OpenShock.Common.Constants; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Utils; + +namespace OpenShock.API.IntegrationTests.Helpers; + +/// +/// Pending signups for tests, and the two things a browser needs to complete one: the cookies that say it +/// holds the signup, and the code mailed to its address. The code is minted by the Cron delivery job when +/// it sends the mail, so tests that want one stand in for that job with . +/// +public static class PendingSignupHelper +{ + public const string Password = "SecurePassword123#"; + + /// Creates a pending signup directly in the DB, with no mail queued for it and no code mailed. + public static async Task CreateInDbAsync( + WebApplicationFactory factory, + string email, + string username, + string? password = Password, + string? oauthProvider = null, + string? oauthExternalId = null) + { + await using var scope = factory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + var id = Guid.CreateVersion7(); + db.PendingSignups.Add(new PendingSignup + { + Id = id, + Email = email, + Username = username, + PasswordHash = password is null ? null : HashingUtils.HashPassword(password), + OAuthProviderKey = oauthProvider, + OAuthExternalId = oauthExternalId, + OAuthDisplayName = oauthProvider is null ? null : "external", + CodeHash = HashingUtils.HashToken(Guid.NewGuid().ToString("N")), + CreatedAt = DateTime.UtcNow + }); + await db.SaveChangesAsync(); + + return id; + } + + /// + /// Stands in for the Cron delivery job mailing the signup its code: stores the hash of a new code, starts + /// its lifetime and gives it all its attempts back. Returns the code "the mail" carries. + /// + public static async Task MailCodeAsync(WebApplicationFactory factory, Guid pendingSignupId) + { + var code = ActivationCode.Generate(); + var hash = ActivationCode.Hash(pendingSignupId, code); + var now = DateTime.UtcNow; + + await using var scope = factory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var updated = await db.PendingSignups + .Where(p => p.Id == pendingSignupId) + .ExecuteUpdateAsync(s => s + .SetProperty(p => p.CodeHash, hash) + .SetProperty(p => p.CodeSentAt, now) + .SetProperty(p => p.FailedAttempts, 0)); + if (updated != 1) throw new InvalidOperationException($"No pending signup {pendingSignupId} to mail a code to"); + + return code; + } + + /// A code that is certainly not . + public static string AnotherCode(string code) + => ((int.Parse(code) + 1) % (int)Math.Pow(10, AuthConstants.ActivationCodeLength)).ToString($"D{AuthConstants.ActivationCodeLength}"); + + public static async Task FindAsync(WebApplicationFactory factory, Guid pendingSignupId) + { + await using var scope = factory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.PendingSignups.AsNoTracking().FirstOrDefaultAsync(p => p.Id == pendingSignupId); + } + + public static async Task> FindByEmailAsync(WebApplicationFactory factory, string email) + { + await using var scope = factory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.PendingSignups.AsNoTracking().Where(p => p.Email == email).OrderBy(p => p.CreatedAt).ToListAsync(); + } + + public static async Task FindUserByEmailAsync(WebApplicationFactory factory, string email) + { + await using var scope = factory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Users.AsNoTracking().FirstOrDefaultAsync(u => u.Email == email); + } + + /// The cookie that lets a browser enter the code, as the API would have set it over HTTPS. + public static string MintSignupBrowserCookie(WebApplicationFactory factory, Guid pendingSignupId, string? countryCode = null) + { + var provider = factory.Services.GetRequiredService(); + return $"{AuthConstants.SignupBrowserSecureCookieName}={SignupBrowserCookie.CreateToken(provider, pendingSignupId, countryCode)}"; + } + + /// The cookie that lets a browser ask for the code again. + public static string MintResendCookie(WebApplicationFactory factory, Guid pendingSignupId) + { + var provider = factory.Services.GetRequiredService(); + return $"{AuthConstants.ActivationResendCookieName}={ActivationResendCookie.CreateToken(provider, pendingSignupId)}"; + } + + /// The name=value part of a cookie a response sets, ready to send back in a Cookie header. + public static string ReadSetCookie(HttpResponseMessage response, string name) + => response.Headers.GetValues("Set-Cookie").Single(c => c.StartsWith(name + "=")).Split(';')[0]; + + public static bool SetsCookie(HttpResponseMessage response, string name) => + response.Headers.TryGetValues("Set-Cookie", out var values) && + values.Any(c => c.StartsWith(name + "=") && !c.StartsWith(name + "=;")); + + // A deleted cookie comes back as an empty value with an expiry in the past. + public static bool DeletesCookie(HttpResponseMessage response, string name) => + response.Headers.TryGetValues("Set-Cookie", out var values) && + values.Any(c => c.StartsWith(name + "=;") && c.Contains("expires=Thu, 01 Jan 1970", StringComparison.OrdinalIgnoreCase)); + + public static Task PostSignupAsync(HttpClient client, string email, string username, string password = Password) => + client.PostAsync("/2/account/signup", TestHelper.JsonContent(new + { + username, + password, + email, + turnstileResponse = "valid-token" + })); + + public static Task PostActivateAsync(HttpClient client, string code, string? cookie) + { + var request = new HttpRequestMessage(HttpMethod.Post, "/1/account/activate") + { + Content = TestHelper.JsonContent(new { code }) + }; + if (cookie is not null) request.Headers.Add("Cookie", cookie); + return client.SendAsync(request); + } + + public static Task PostResendAsync(HttpClient client, string? cookie) + { + var request = new HttpRequestMessage(HttpMethod.Post, "/1/account/activate/resend"); + if (cookie is not null) request.Headers.Add("Cookie", cookie); + return client.SendAsync(request); + } + + public static Task PostLoginAsync(HttpClient client, string usernameOrEmail, string password, string? cookie = null) + { + var request = new HttpRequestMessage(HttpMethod.Post, "/2/account/login") + { + Content = TestHelper.JsonContent(new + { + usernameOrEmail, + password, + turnstileResponse = "valid-token" + }) + }; + if (cookie is not null) request.Headers.Add("Cookie", cookie); + return client.SendAsync(request); + } +} diff --git a/API.IntegrationTests/Tests/AccountSignupTests.cs b/API.IntegrationTests/Tests/AccountSignupTests.cs index 3ae077165..918a39946 100644 --- a/API.IntegrationTests/Tests/AccountSignupTests.cs +++ b/API.IntegrationTests/Tests/AccountSignupTests.cs @@ -1,7 +1,9 @@ using System.Net; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.Common.Constants; using OpenShock.Common.OpenShockDb; namespace OpenShock.API.IntegrationTests.Tests; @@ -45,6 +47,14 @@ public async Task V2Signup_Success_CreatesUser() await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + // The account exists once the mailed code is entered in the browser that signed up. + var pending = (await PendingSignupHelper.FindByEmailAsync(WebApplicationFactory, "v2user@test.org")).Single(); + var code = await PendingSignupHelper.MailCodeAsync(WebApplicationFactory, pending.Id); + var cookie = PendingSignupHelper.ReadSetCookie(response, AuthConstants.SignupBrowserSecureCookieName); + using var browser = WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions { HandleCookies = false }); + var activated = await PendingSignupHelper.PostActivateAsync(browser, code, cookie); + await Assert.That(activated.StatusCode).IsEqualTo(HttpStatusCode.OK); + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); var user = await db.Users.FirstOrDefaultAsync(u => u.Email == "v2user@test.org"); diff --git a/API.IntegrationTests/Tests/AccountTests.cs b/API.IntegrationTests/Tests/AccountTests.cs index 173f6af91..f33926d18 100644 --- a/API.IntegrationTests/Tests/AccountTests.cs +++ b/API.IntegrationTests/Tests/AccountTests.cs @@ -1,7 +1,10 @@ using System.Net; using System.Text.Json; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; +using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.Common.Constants; using OpenShock.Common.OpenShockDb; namespace OpenShock.API.IntegrationTests.Tests; @@ -29,6 +32,14 @@ public async Task CreateAccount_ShouldAdd_NewUserToDatabase() await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + // The account exists once the mailed code is entered in the browser that signed up. + var pending = (await PendingSignupHelper.FindByEmailAsync(WebApplicationFactory, "bob@example.com")).Single(); + var code = await PendingSignupHelper.MailCodeAsync(WebApplicationFactory, pending.Id); + var cookie = PendingSignupHelper.ReadSetCookie(response, AuthConstants.SignupBrowserSecureCookieName); + using var browser = WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions { HandleCookies = false }); + var activated = await PendingSignupHelper.PostActivateAsync(browser, code, cookie); + await Assert.That(activated.StatusCode).IsEqualTo(HttpStatusCode.OK); + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); diff --git a/API.IntegrationTests/Tests/AutomationTokenTests.cs b/API.IntegrationTests/Tests/AutomationTokenTests.cs index 086e1f1ba..2dc11310c 100644 --- a/API.IntegrationTests/Tests/AutomationTokenTests.cs +++ b/API.IntegrationTests/Tests/AutomationTokenTests.cs @@ -1,5 +1,6 @@ using System.Net; using System.Text.Json; +using Microsoft.AspNetCore.Mvc.Testing; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using OpenShock.API.IntegrationTests.Helpers; @@ -41,6 +42,16 @@ public async Task Signup_WithTurnstileToken_BypassesTurnstileAndLinksAccount() await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + // The signup is linked to the token right away, and the account it becomes carries that over + // together with the audit entry for the use, whether or not the completing request has the token. + var pending = (await PendingSignupHelper.FindByEmailAsync(WebApplicationFactory, email)).Single(); + await Assert.That(pending.CreatedByAutomationTokenId).IsEqualTo(tokenId); + + var code = await PendingSignupHelper.MailCodeAsync(WebApplicationFactory, pending.Id); + using var browser = WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions { HandleCookies = false }); + var activated = await PendingSignupHelper.PostActivateAsync(browser, code, PendingSignupHelper.MintSignupBrowserCookie(WebApplicationFactory, pending.Id)); + await Assert.That(activated.StatusCode).IsEqualTo(HttpStatusCode.OK); + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); var user = await db.Users.AsNoTracking().FirstAsync(u => u.Email == email); diff --git a/API.IntegrationTests/Tests/MailDisabledTests.cs b/API.IntegrationTests/Tests/MailDisabledTests.cs index deaa9fc90..bb12eaa27 100644 --- a/API.IntegrationTests/Tests/MailDisabledTests.cs +++ b/API.IntegrationTests/Tests/MailDisabledTests.cs @@ -8,7 +8,7 @@ namespace OpenShock.API.IntegrationTests.Tests; /// -/// With no mail provider configured no activation link can ever be delivered, so signup must activate +/// With no mail provider configured no activation code can ever be delivered, so signup must activate /// the account outright instead of parking it behind an activation flow it can never complete. /// public sealed class MailDisabledTests @@ -35,13 +35,11 @@ public async Task V2Signup_MailDisabled_ActivatesAccountAndEnqueuesNoEmail() await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); - var user = await db.Users - .Include(u => u.UserActivationRequest) - .FirstOrDefaultAsync(u => u.Email == email); + var user = await db.Users.FirstOrDefaultAsync(u => u.Email == email); await Assert.That(user).IsNotNull(); await Assert.That(user!.ActivatedAt).IsNotNull(); - await Assert.That(user.UserActivationRequest).IsNull(); + await Assert.That(await db.PendingSignups.AnyAsync(p => p.Email == email)).IsFalse(); var activationMails = await db.EmailOutbox .CountAsync(m => m.Recipient == email && m.Type == EmailType.AccountActivation); diff --git a/API.IntegrationTests/Tests/MailTests.cs b/API.IntegrationTests/Tests/MailTests.cs index 443cd49a0..039ca1ad0 100644 --- a/API.IntegrationTests/Tests/MailTests.cs +++ b/API.IntegrationTests/Tests/MailTests.cs @@ -17,290 +17,20 @@ namespace OpenShock.API.IntegrationTests.Tests; /// row (and its business row) atomically - it never sends mail. These tests assert exactly that: the right /// outbox row is enqueued (type, recipient, coalesce key, payload) or, for rejected requests, that nothing /// is enqueued. Actual delivery, lazy token minting, the emailed-link flows, and newest-wins coalescing are -/// the Cron host's job and are covered by Cron.IntegrationTests. +/// the Cron host's job and are covered by Cron.IntegrationTests. Signing up and activating is covered by +/// . /// public sealed class MailTests { - /// Just longer than a pending signup keeps its address from an unproven new signup. - private static readonly TimeSpan PastPendingSignupHold = Duration.PendingSignupHoldTime + TimeSpan.FromMinutes(1); - [ClassDataSource(Shared = SharedType.PerTestSession)] public required WebApplicationFactory WebApplicationFactory { get; init; } - // --- Account Activation --- - - [Test] - public async Task V2Signup_EnqueuesActivationOutbox() - { - var email = TestHelper.UniqueEmail("mail-activation"); - var username = TestHelper.UniqueUsername("mailactivation"); - using var client = WebApplicationFactory.CreateClient(); - - var response = await client.PostAsync("/2/account/signup", TestHelper.JsonContent(new - { - username, - password = "SecurePassword123#", - email, - turnstileResponse = "valid-token" - })); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - - await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); - var db = scope.ServiceProvider.GetRequiredService(); - var user = await db.Users.AsNoTracking().FirstAsync(u => u.Email == email); - - var row = await db.EmailOutbox.AsNoTracking().SingleAsync(m => m.Recipient == email); - await Assert.That(row.Type).IsEqualTo(EmailType.AccountActivation); - await Assert.That(row.Status).IsEqualTo(EmailStatus.Pending); - await Assert.That(row.CoalesceKey).IsEqualTo(EmailOutboxCoalesceKeys.AccountActivation(user.Id)); - await Assert.That(row.Payload[EmailOutboxPayloadKeys.UserId]).IsEqualTo(user.Id.ToString()); - } - - // --- Resend Activation --- - - [Test] - public async Task V2Signup_Unactivated_SetsActivationResendCookie() - { - using var client = CreateCookielessClient(); - var response = await SignUpAsync(client, TestHelper.UniqueEmail("mail-signup-cookie"), TestHelper.UniqueUsername("mailsignupcookie")); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - - var setCookie = response.Headers.GetValues("Set-Cookie").ToArray(); - var resendCookie = setCookie.Single(c => c.StartsWith(AuthConstants.ActivationResendCookieName + "=")); - // Readable by the frontend, which shows the resend button only while the cookie exists. - await Assert.That(resendCookie.Contains("httponly", StringComparison.OrdinalIgnoreCase)).IsFalse(); - } - - [Test] - public async Task ResendActivation_UnactivatedUser_EnqueuesActivationOutbox() - { - var email = TestHelper.UniqueEmail("mail-resend-activate"); - var username = TestHelper.UniqueUsername("mailresendactivate"); - - // Unactivated user with no existing activation request - exercises the create-request path. - var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "SecurePassword123#", activated: false); - - using var client = CreateCookielessClient(); - var response = await PostResendAsync(client, MintResendCookie(userId)); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - - await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); - var db = scope.ServiceProvider.GetRequiredService(); - - // The missing activation request was created, and a fresh activation email was enqueued. - var hasRequest = await db.UserActivationRequests.AsNoTracking().AnyAsync(r => r.UserId == userId); - await Assert.That(hasRequest).IsTrue(); - - var row = await db.EmailOutbox.AsNoTracking().SingleAsync(m => m.Recipient == email); - await Assert.That(row.Type).IsEqualTo(EmailType.AccountActivation); - await Assert.That(row.Status).IsEqualTo(EmailStatus.Pending); - await Assert.That(row.CoalesceKey).IsEqualTo(EmailOutboxCoalesceKeys.AccountActivation(userId)); - } - - [Test] - public async Task ResendActivation_WithSignupCookie_EnqueuesAnotherActivationOutbox() - { - var email = TestHelper.UniqueEmail("mail-resend-rotate"); - var username = TestHelper.UniqueUsername("mailresendrotate"); - using var client = CreateCookielessClient(); - - // Sign up (V2) - creates an unactivated user, its activation request, the first enqueue, and the cookie. - var signupResponse = await SignUpAsync(client, email, username); - await Assert.That(signupResponse.StatusCode).IsEqualTo(HttpStatusCode.OK); - var cookie = signupResponse.Headers.GetValues("Set-Cookie") - .Single(c => c.StartsWith(AuthConstants.ActivationResendCookieName + "=")) - .Split(';')[0]; - - // Move the signup email out of the resend cooldown. - await BackdateOutboxAsync(email, TimeSpan.FromMinutes(11)); - - // Resend enqueues another activation email. The delivery job re-mints the token and supersedes the - // older row at send time (coalesce key) - that token rotation is covered in Cron.IntegrationTests. - var resendResponse = await PostResendAsync(client, cookie); - await Assert.That(resendResponse.StatusCode).IsEqualTo(HttpStatusCode.OK); - - await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); - var db = scope.ServiceProvider.GetRequiredService(); - var user = await db.Users.AsNoTracking().FirstAsync(u => u.Email == email); - - var rows = await db.EmailOutbox.AsNoTracking().Where(m => m.Recipient == email).ToListAsync(); - await Assert.That(rows.Count).IsEqualTo(2); - await Assert.That(rows.All(r => r.Type == EmailType.AccountActivation)).IsTrue(); - await Assert.That(rows.All(r => r.CoalesceKey == EmailOutboxCoalesceKeys.AccountActivation(user.Id))).IsTrue(); - } - - [Test] - public async Task ResendActivation_WithinCooldown_Returns429_AndEnqueuesNothing() - { - var email = TestHelper.UniqueEmail("mail-resend-cooldown"); - var username = TestHelper.UniqueUsername("mailresendcooldown"); - var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "SecurePassword123#", activated: false); - var cookie = MintResendCookie(userId); - - using var client = CreateCookielessClient(); - await Assert.That((await PostResendAsync(client, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); - await Assert.That((await PostResendAsync(client, cookie)).StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests); - - await Assert.That(await CountOutboxAsync(email)).IsEqualTo(1); - } - - [Test] - public async Task ResendActivation_DailyCapReached_Returns429() - { - var email = TestHelper.UniqueEmail("mail-resend-cap"); - var username = TestHelper.UniqueUsername("mailresendcap"); - var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "SecurePassword123#", activated: false); - var cookie = MintResendCookie(userId); - - using var client = CreateCookielessClient(); - for (var i = 0; i < 5; i++) - { - await Assert.That((await PostResendAsync(client, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); - // Step past the cooldown each time; only the 24h cap of 5 should stop the sixth. - await BackdateOutboxAsync(email, TimeSpan.FromMinutes(11)); - } - await Assert.That((await PostResendAsync(client, cookie)).StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests); - - await Assert.That(await CountOutboxAsync(email)).IsEqualTo(5); - } - - [Test] - public async Task ResendActivation_AlreadyActivatedUser_Returns400_AndRemovesCookie() - { - var email = TestHelper.UniqueEmail("mail-resend-activated"); - var username = TestHelper.UniqueUsername("mailresendactivated"); - var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "SecurePassword123#", activated: true); - - using var client = CreateCookielessClient(); - var response = await PostResendAsync(client, MintResendCookie(userId)); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); - await Assert.That(DeletesResendCookie(response)).IsTrue(); - - await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); - } - - [Test] - public async Task ResendActivation_NoCookie_Returns400() - { - using var client = CreateCookielessClient(); - var response = await PostResendAsync(client, cookie: null); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); - } - - [Test] - public async Task ResendActivation_TamperedCookie_Returns400_AndRemovesCookie() - { - using var client = CreateCookielessClient(); - var response = await PostResendAsync(client, $"{AuthConstants.ActivationResendCookieName}=not-a-valid-token"); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); - await Assert.That(DeletesResendCookie(response)).IsTrue(); - } - - [Test] - public async Task Login_Success_RemovesActivationResendCookie() - { - var email = TestHelper.UniqueEmail("mail-login-clears"); - var username = TestHelper.UniqueUsername("maillogclears"); - var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "SecurePassword123#", activated: true); - - using var client = CreateCookielessClient(); - using var request = new HttpRequestMessage(HttpMethod.Post, "/2/account/login"); - request.Content = TestHelper.JsonContent(new - { - usernameOrEmail = email, - password = "SecurePassword123#", - turnstileResponse = "valid-token" - }); - request.Headers.Add("Cookie", MintResendCookie(userId)); - - var response = await client.SendAsync(request); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - await Assert.That(DeletesResendCookie(response)).IsTrue(); - } - - [Test] - public async Task Login_UnactivatedUser_CorrectPassword_ReturnsNotActivated_AndEnqueuesActivation() - { - var email = TestHelper.UniqueEmail("mail-login-unactivated"); - var username = TestHelper.UniqueUsername("maillogunact"); - var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "SecurePassword123#", activated: false); - - using var client = WebApplicationFactory.CreateClient(); - var response = await client.PostAsync("/2/account/login", TestHelper.JsonContent(new - { - usernameOrEmail = email, - password = "SecurePassword123#", - turnstileResponse = "valid-token" - })); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); - await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Account.AccountNotActivated"); - - await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); - var db = scope.ServiceProvider.GetRequiredService(); - var row = await db.EmailOutbox.AsNoTracking().SingleAsync(m => m.Recipient == email); - await Assert.That(row.Type).IsEqualTo(EmailType.AccountActivation); - await Assert.That(row.CoalesceKey).IsEqualTo(EmailOutboxCoalesceKeys.AccountActivation(userId)); - } - - [Test] - public async Task Login_UnactivatedUser_WrongPassword_EnqueuesNothing() - { - var email = TestHelper.UniqueEmail("mail-login-unact-wrong"); - var username = TestHelper.UniqueUsername("maillogunactw"); - await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "SecurePassword123#", activated: false); - - using var client = WebApplicationFactory.CreateClient(); - var response = await client.PostAsync("/2/account/login", TestHelper.JsonContent(new - { - usernameOrEmail = email, - password = "WrongPassword123#", - turnstileResponse = "valid-token" - })); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); - - await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); - } - private HttpClient CreateCookielessClient() => WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false, HandleCookies = false }); - private static Task SignUpAsync(HttpClient client, string email, string username) => - client.PostAsync("/2/account/signup", TestHelper.JsonContent(new - { - username, - password = "SecurePassword123#", - email, - turnstileResponse = "valid-token" - })); - - private string MintResendCookie(Guid userId) - { - var provider = WebApplicationFactory.Services.GetRequiredService(); - 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"); - if (cookie is not null) request.Headers.Add("Cookie", cookie); - return client.SendAsync(request); - } - - // A deleted cookie comes back as an empty value with an expiry in the past. - private static bool DeletesResendCookie(HttpResponseMessage response) => - response.Headers.TryGetValues("Set-Cookie", out var values) && - values.Any(c => c.StartsWith(AuthConstants.ActivationResendCookieName + "=;") && - c.Contains("expires=Thu, 01 Jan 1970", StringComparison.OrdinalIgnoreCase)); - private async Task CountOutboxAsync(string email) { await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); @@ -308,15 +38,6 @@ private async Task CountOutboxAsync(string email) return await db.EmailOutbox.AsNoTracking().CountAsync(m => m.Recipient == email); } - private async Task BackdateOutboxAsync(string email, TimeSpan by) - { - await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); - var db = scope.ServiceProvider.GetRequiredService(); - await db.EmailOutbox - .Where(m => m.Recipient == email) - .ExecuteUpdateAsync(s => s.SetProperty(m => m.CreatedAt, m => m.CreatedAt - by)); - } - // --- Password Reset --- [Test] @@ -367,65 +88,6 @@ public async Task V2PasswordReset_EnqueuesResetOutbox() await Assert.That(row.Payload[EmailOutboxPayloadKeys.PasswordResetId]).IsEqualTo(reset.Id.ToString()); } - [Test] - public async Task V2PasswordReset_UnactivatedUser_EnqueuesResetOutbox() - { - var email = TestHelper.UniqueEmail("mail-pwreset-unact"); - var username = TestHelper.UniqueUsername("mailpwresetunact"); - var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "OldPassword123#", activated: false); - - using var client = WebApplicationFactory.CreateClient(); - var response = await client.PostAsync("/2/account/password-reset", TestHelper.JsonContent(new - { - email, - turnstileResponse = "valid-token" - })); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - - await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); - var db = scope.ServiceProvider.GetRequiredService(); - var row = await db.EmailOutbox.AsNoTracking().SingleAsync(m => m.Recipient == email); - await Assert.That(row.Type).IsEqualTo(EmailType.PasswordReset); - await Assert.That(row.CoalesceKey).IsEqualTo(EmailOutboxCoalesceKeys.PasswordReset(userId)); - } - - [Test] - public async Task PasswordResetComplete_UnactivatedUser_ActivatesAccount() - { - var email = TestHelper.UniqueEmail("mail-pwreset-activates"); - var username = TestHelper.UniqueUsername("mailpwresetact"); - var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "OldPassword123#", activated: false); - - // Stand in for the Cron delivery job: seed the activation request and a reset with a known secret. - const string secret = "test-password-reset-secret"; - var resetId = Guid.CreateVersion7(); - await using (var seedScope = WebApplicationFactory.Services.CreateAsyncScope()) - { - var seedDb = seedScope.ServiceProvider.GetRequiredService(); - var user = await seedDb.Users.FirstAsync(u => u.Id == userId); - seedDb.UserActivationRequests.Add(new UserActivationRequest { UserId = userId, TokenHash = HashingUtils.HashToken("unused-activation-secret") }); - seedDb.UserPasswordResets.Add(new UserPasswordReset - { - Id = resetId, - UserId = userId, - TokenHash = HashingUtils.HashToken(secret), - SecurityStampAtCreate = user.SecurityStamp - }); - await seedDb.SaveChangesAsync(); - } - - using var client = WebApplicationFactory.CreateClient(); - var response = await client.PostAsync($"/1/account/password-reset/{resetId}/{secret}/complete", - TestHelper.JsonContent(new { password = "NewPassword123#" })); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - - await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); - var db = scope.ServiceProvider.GetRequiredService(); - var activatedAt = await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.ActivatedAt).SingleAsync(); - await Assert.That(activatedAt).IsNotNull(); - 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] @@ -449,159 +111,6 @@ public async Task PasswordResetComplete_ActivatedAccount_KeepsOAuthConnectionsAn 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, PastPendingSignupHold); - - 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); - } - - // 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 hold, so the next signup replaces it. - await BackdateOutboxAsync(email, PastPendingSignupHold); - await BackdatePendingAccountAsync(email, PastPendingSignupHold); - } - - 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); - } - - // The count behind the cap is only good while nobody else queues mail for the address, so counting and - // queueing hold a lock on the address. A request that meets the lock is turned away, not left to queue - // on a count that is about to be out of date. - [Test] - public async Task Signup_WhileAnotherRequestQueuesActivationMailForTheAddress_Returns409_AndMailsNothing() - { - var email = TestHelper.UniqueEmail("mail-address-lock"); - - using var client = CreateCookielessClient(); - - await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) - { - // Stands in for a request that has counted the address's mail and not yet committed its own. - var db = scope.ServiceProvider.GetRequiredService(); - await using var transaction = await db.Database.BeginTransactionAsync(); - await Assert.That(await db.Database.TryLockForTransactionAsync(AccountService.ActivationEmailLockName(email))).IsTrue(); - - var blocked = await SignUpAsync(client, email, TestHelper.UniqueUsername("mailaddresslock")); - await Assert.That(blocked.StatusCode).IsEqualTo(HttpStatusCode.Conflict); - await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); - } - - var afterwards = await SignUpAsync(client, email, TestHelper.UniqueUsername("mailaddresslock")); - await Assert.That(afterwards.StatusCode).IsEqualTo(HttpStatusCode.OK); - await Assert.That(await CountOutboxAsync(email)).IsEqualTo(1); - } - - 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 hold 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, PastPendingSignupHold); - 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(); - } - - // While its hold lasts 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] @@ -678,387 +187,6 @@ public async Task RemoveOAuthConnection_AccountWithPassword_RemovesIt() 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: MintSignupBrowserCookie(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 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() - { - 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: MintSignupBrowserCookie(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); - } - - [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: MintSignupBrowserCookie(userId)); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); - 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).IsEqualTo(HttpStatusCode.NotFound); - 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, PastPendingSignupHold); - 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_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() - { - 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: MintSignupBrowserCookie(userId)); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - await Assert.That(await IsActivatedAsync(userId)).IsTrue(); - } - - // Past the account's daily cap no mail could go to the corrected address, and the correction kills the - // link already mailed: it has to be refused whole, not leave an account with no working link. - [Test] - public async Task RestartPendingSignup_ChangedEmail_AccountAtTheDailyCap_ChangesNothing_AndKeepsTheMailedLinkWorking() - { - var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-restart-cap", password: null); - await AddOAuthConnectionAsync(userId, "discord"); - var originalEmail = await GetEmailAsync(userId); - var newEmail = TestHelper.UniqueEmail("mail-restart-cap-new"); - - 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(); - - // Mailed to a few addresses, as earlier corrections would have: the cap counted is the account's. - for (var i = 0; i < 5; i++) - { - db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(userId, TestHelper.UniqueEmail("mail-restart-cap-earlier"), username)); - } - await db.SaveChangesAsync(); - - var accountService = scope.ServiceProvider.GetRequiredService(); - var restarted = await accountService.RestartPendingSignupAsync(userId, newEmail, username); - await Assert.That(restarted.Value is TooManyActivationResends).IsTrue(); - } - - await Assert.That(await GetEmailAsync(userId)).IsEqualTo(originalEmail); - await Assert.That(await CountOutboxAsync(newEmail)).IsEqualTo(0); - - using var client = CreateCookielessClient(); - var response = await PostActivateAsync(client, token, cookie: MintSignupBrowserCookie(userId)); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - } - - // The mail to the corrected address is queued by the correction itself, in its transaction: there is - // no moment where the old link is dead and nothing is on its way to the new address. - [Test] - public async Task RestartPendingSignup_ChangedEmail_QueuesTheMailToTheNewAddress() - { - var (userId, _) = await CreateUnactivatedUserWithTokenAsync("mail-restart-queued", password: null); - var newEmail = TestHelper.UniqueEmail("mail-restart-queued-new"); - - 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, newEmail, username); - - await Assert.That(restarted.Value is User).IsTrue(); - await Assert.That(await CountOutboxAsync(newEmail)).IsEqualTo(1); - } - - // The delivery job skips an activation mail whose account has no activation request to mint a token on, - // so a correction has to leave one behind even where none existed. - [Test] - public async Task RestartPendingSignup_ChangedEmail_AccountWithoutActivationRequest_CreatesOne() - { - var (userId, _) = await CreateUnactivatedUserWithTokenAsync("mail-restart-norequest", password: null); - var newEmail = TestHelper.UniqueEmail("mail-restart-norequest-new"); - - await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); - var db = scope.ServiceProvider.GetRequiredService(); - await db.UserActivationRequests.Where(r => r.UserId == userId).ExecuteDeleteAsync(); - 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, newEmail, username); - - await Assert.That(restarted.Value is User).IsTrue(); - await Assert.That(await db.UserActivationRequests.AsNoTracking().CountAsync(r => r.UserId == userId)).IsEqualTo(1); - await Assert.That(await CountOutboxAsync(newEmail)).IsEqualTo(1); - } - - // The resend an OAuth sign-in triggers on its own stops one short of the account's cap: the last send - // is kept for correcting the address, which a resend the user asks for may still use. - [Test] - public async Task ResendActivationForOAuth_OneSendLeftInTheWindow_LeavesItForACorrection() - { - var (userId, _) = await CreateUnactivatedUserWithTokenAsync("mail-oauth-reserve", password: null); - var email = await GetEmailAsync(userId); - - await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); - var db = scope.ServiceProvider.GetRequiredService(); - for (var i = 0; i < 4; i++) - { - db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(userId, email, "pending")); - } - await db.SaveChangesAsync(); - // Past the cooldown, so only the cap is left to refuse a resend. - await BackdateOutboxAsync(email, TimeSpan.FromMinutes(11)); - - var accountService = scope.ServiceProvider.GetRequiredService(); - - var automatic = await accountService.ResendActivationEmailForOAuthAsync(userId); - await Assert.That(automatic.Value is TooManyActivationResends).IsTrue(); - await Assert.That(await CountOutboxAsync(email)).IsEqualTo(4); - - var requested = await accountService.ResendActivationEmailAsync(userId); - await Assert.That(requested.Value is OpenShock.Common.Results.Success).IsTrue(); - await Assert.That(await CountOutboxAsync(email)).IsEqualTo(5); - } - - // Each moves onto the address the other holds, so each needs both rows locked: taken in the same order - // one waits for the other, taken in opposite orders the database would abort one as a deadlock. - [Test] - public async Task RestartPendingSignup_TwoSignupsMovingOntoEachOthersAddress_DoNotDeadlock() - { - var (firstId, _) = await CreateUnactivatedUserWithTokenAsync("mail-restart-swap-a", password: null); - var (secondId, _) = await CreateUnactivatedUserWithTokenAsync("mail-restart-swap-b", password: null); - await BackdateUserAsync(firstId, PastPendingSignupHold); - await BackdateUserAsync(secondId, PastPendingSignupHold); - var firstEmail = await GetEmailAsync(firstId); - var secondEmail = await GetEmailAsync(secondId); - await using var usernameScope = WebApplicationFactory.Services.CreateAsyncScope(); - var usernameDb = usernameScope.ServiceProvider.GetRequiredService(); - var usernames = await usernameDb.Users.AsNoTracking() - .Where(u => u.Id == firstId || u.Id == secondId) - .ToDictionaryAsync(u => u.Id, u => u.Name); - var firstUsername = usernames[firstId]; - var secondUsername = usernames[secondId]; - - async Task RestartAsync(Guid userId, string email, string username) - { - await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); - var accountService = scope.ServiceProvider.GetRequiredService(); - return (await accountService.RestartPendingSignupAsync(userId, email, username)).Value!; - } - - // Neither call throws. The one that gets there first takes the other's address and removes it. - var results = await Task.WhenAll( - RestartAsync(firstId, secondEmail, firstUsername), - RestartAsync(secondId, firstEmail, secondUsername)); - - await Assert.That(results.Count(r => r is User)).IsEqualTo(1); - } - // --- An email change is only confirmed from a session of the account that asked for it --- [Test] @@ -1115,44 +243,6 @@ public async Task EmailChangeVerify_LegacyRoute_FromOwnSession_AppliesChange() await Assert.That(await GetEmailAsync(user.Id)).IsEqualTo(newEmail); } - // --- A never activated account does not keep an existing user from moving to its address --- - - [Test] - public async Task ChangeEmail_AddressHeldByPendingSignup_IsAccepted() - { - const string password = "SecurePassword123#"; - var heldEmail = TestHelper.UniqueEmail("mail-chgemail-pending-held"); - await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailchgemailpending1"), heldEmail, password, activated: false); - var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailchgemailpending2"), TestHelper.UniqueEmail("mail-chgemail-pending-own"), password); - using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); - - var response = await client.PostAsync("/1/account/email-change", TestHelper.JsonContent(new - { - currentPassword = password, - email = heldEmail - })); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - } - - [Test] - public async Task EmailChangeVerify_AddressHeldByPendingSignup_ReleasesIt_AndAppliesChange() - { - var (user, token, newEmail) = await CreateUserWithPendingEmailChangeAsync("mail-verify-pending"); - // Fresh, so a plain signup could not replace it yet: opening the mailed link is proof a signup lacks. - var pendingId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailverifypending"), newEmail, "SquatterPassword123#", activated: false); - - 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); - - await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); - var db = scope.ServiceProvider.GetRequiredService(); - await Assert.That(await db.Users.AsNoTracking().AnyAsync(u => u.Id == pendingId)).IsFalse(); - } - [Test] public async Task EmailChangeVerify_AddressHeldByActivatedAccount_Returns409_AndLeavesEmail() { @@ -1166,39 +256,6 @@ public async Task EmailChangeVerify_AddressHeldByActivatedAccount_Returns409_And await Assert.That(await GetEmailAsync(user.Id)).IsEqualTo(user.Email); } - // 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#"); diff --git a/API.IntegrationTests/Tests/OAuthFlowTests.cs b/API.IntegrationTests/Tests/OAuthFlowTests.cs index e6879395e..032edc1ce 100644 --- a/API.IntegrationTests/Tests/OAuthFlowTests.cs +++ b/API.IntegrationTests/Tests/OAuthFlowTests.cs @@ -1,34 +1,28 @@ 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; +using static OpenShock.API.IntegrationTests.Helpers.PendingSignupHelper; 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. +/// The OAuth endpoints around a signup that is not completed yet: what a provider sign-in leaves behind +/// when the provider did not verify the address, and what the identity that started it can and cannot do. /// /// /// 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. +/// that cookie the way the callback would and drive the real endpoints from there. /// public sealed class OAuthFlowTests { @@ -37,96 +31,63 @@ public sealed class OAuthFlowTests [ClassDataSource(Shared = SharedType.PerTestSession)] public required WebApplicationFactory WebApplicationFactory { get; init; } - // --- authorize --- + // --- handoff --- [Test] - public async Task Authorize_WithActivationToken_CarriesItThroughTheProviderRoundTrip() + public async Task Handoff_IdentityNobodyKnows_GoesToTheSignupForm() { using var client = CreateClient(); - var response = await client.PostAsync($"/1/oauth/{Provider}/authorize?flow=LoginOrCreate&activationToken=the-mailed-token", null); + var response = await HandoffAsync(client, MintFlowCookie(NewExternalId())); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Redirect); - await Assert.That(OAuthUtil.TryGetActivationToken(ReadState(response), out var carried)).IsTrue(); - await Assert.That(carried).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(OAuthUtil.TryGetActivationToken(ReadState(response), out _)).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(); + await AssertSentBackToSignupAsync(response, pending: false); + await Assert.That(SetsCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsFalse(); } + // The identity that started a signup, coming back: it holds the signup's credential, so this browser + // holds the signup from now on. It is still not signed in, the address was never shown to be theirs. [Test] - public async Task Handoff_LinkedIdentityWithoutTheToken_StaysPending_AndIsNotSignedIn() + public async Task Handoff_IdentityWithAPendingSignup_HoldsTheSignup_MailsACode_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); + var email = TestHelper.UniqueEmail("oauth-handoff-pending"); + var pendingId = await CreatePendingOAuthSignupAsync(email, "oauthhandoffpending", externalId); using var client = CreateClient(); var response = await HandoffAsync(client, MintFlowCookie(externalId)); await AssertSentBackToSignupAsync(response, pending: true); - await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(1); + + // The cookie it handed out completes the signup with the mailed code, and links the identity. + var cookie = ReadSetCookie(response, AuthConstants.SignupBrowserSecureCookieName); + var code = await MailCodeAsync(WebApplicationFactory, pendingId); + await Assert.That((await PostActivateAsync(client, code, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); + + var signIn = await HandoffAsync(client, MintFlowCookie(externalId)); + await Assert.That(signIn.StatusCode).IsEqualTo(HttpStatusCode.Redirect); + await Assert.That(signIn.Headers.Location!.AbsolutePath).IsEqualTo("/home"); + await Assert.That(SetsCookie(signIn, AuthConstants.UserSessionCookieName)).IsTrue(); } [Test] - public async Task Handoff_LinkedIdentityWithATokenOfAnotherAccount_StaysPending() + public async Task Handoff_AnotherIdentity_DoesNotGetToHoldSomeoneElsesSignup() { - // 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()); + var email = TestHelper.UniqueEmail("oauth-handoff-otherid"); + await CreatePendingOAuthSignupAsync(email, "oauthhandoffotherid", 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)); + var response = await HandoffAsync(client, MintFlowCookie(NewExternalId(), email: email, emailVerified: false)); await AssertSentBackToSignupAsync(response, pending: false); - await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + await Assert.That(SetsCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsFalse(); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); } // --- signup-finalize --- [Test] - public async Task SignupFinalize_EmailTheProviderDidNotVerify_CreatesAPendingAccount_WithoutASession() + public async Task SignupFinalize_EmailTheProviderDidNotVerify_StartsAPendingSignup_WithoutAnAccountOrSession() { var externalId = NewExternalId(); var email = TestHelper.UniqueEmail("oauth-finalize-unverified"); @@ -138,12 +99,20 @@ public async Task SignupFinalize_EmailTheProviderDidNotVerify_CreatesAPendingAcc 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(); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); + var pending = (await FindByEmailAsync(WebApplicationFactory, email)).Single(); + await Assert.That(pending.OAuthProviderKey).IsEqualTo(Provider); + await Assert.That(pending.OAuthExternalId).IsEqualTo(externalId); + await Assert.That(pending.PasswordHash).IsNull(); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(1); + + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + await Assert.That(body.RootElement.GetProperty("isVerified").GetBoolean()).IsFalse(); + await Assert.That(body.RootElement.GetProperty("accountId").GetGuid()).IsEqualTo(pending.Id); } [Test] - public async Task SignupFinalize_EmailTheProviderVerified_CreatesAnActivatedAccount_AndSignsIn() + public async Task SignupFinalize_EmailTheProviderVerified_CreatesTheAccount_AndSignsIn() { var externalId = NewExternalId(); var email = TestHelper.UniqueEmail("oauth-finalize-verified"); @@ -154,17 +123,22 @@ public async Task SignupFinalize_EmailTheProviderVerified_CreatesAnActivatedAcco 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(); + var user = await FindUserByEmailAsync(WebApplicationFactory, email); + await Assert.That(user!.ActivatedAt).IsNotNull(); + await Assert.That(await FindByEmailAsync(WebApplicationFactory, email)).IsEmpty(); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); } + // Sign up with an inbox of your own, read the code, then start over on someone else's address: the + // code that was mailed belongs to the first signup, which no longer exists. [Test] - public async Task SignupFinalize_PendingAccount_NewEmail_MovesIt_AndTheOldLinkNoLongerActivates() + public async Task SignupFinalize_PendingSignup_NewEmail_ReplacesIt_AndTheOldCodeNoLongerWorks() { - // 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 oldEmail = TestHelper.UniqueEmail("oauth-finalize-move"); + var username = TestHelper.UniqueUsername("oauthfinmove"); + var oldPendingId = await CreatePendingOAuthSignupAsync(oldEmail, username, externalId, uniqueUsername: false); + var oldCode = await MailCodeAsync(WebApplicationFactory, oldPendingId); var victimEmail = TestHelper.UniqueEmail("oauth-finalize-victim"); using var client = CreateClient(); @@ -172,27 +146,45 @@ public async Task SignupFinalize_PendingAccount_NewEmail_MovesIt_AndTheOldLinkNo 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); + await Assert.That(await FindAsync(WebApplicationFactory, oldPendingId)).IsNull(); + var moved = (await FindByEmailAsync(WebApplicationFactory, victimEmail)).Single(); + await Assert.That(moved.Id).IsNotEqualTo(oldPendingId); + // The new address has to be mailed a code of its own before anything is accepted. + await Assert.That(moved.CodeSentAt).IsNull(); + + // Neither the cookie of the old signup... + var withOldCookie = await PostActivateAsync(client, oldCode, MintSignupBrowserCookie(WebApplicationFactory, oldPendingId)); + await Assert.That(withOldCookie.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + + // ...nor the cookie of the new one makes the old code work. + var withNewCookie = await PostActivateAsync(client, oldCode, ReadSetCookie(response, AuthConstants.SignupBrowserSecureCookieName)); + await Assert.That(withNewCookie.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 FindUserByEmailAsync(WebApplicationFactory, victimEmail)).IsNull(); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, oldEmail)).IsNull(); + } + + // Another identity cannot take the name a signup was just started with. + [Test] + public async Task SignupFinalize_UsernameOfAnotherPendingSignupStartedWithinTheHour_Returns409() + { + var username = TestHelper.UniqueUsername("oauthfinreserved"); + await CreatePendingOAuthSignupAsync(TestHelper.UniqueEmail("oauth-finalize-reserved"), username, NewExternalId(), uniqueUsername: false); + var email = TestHelper.UniqueEmail("oauth-finalize-reserved-other"); + + using var client = CreateClient(); + var response = await FinalizeAsync(client, MintFlowCookie(NewExternalId(), email: email, emailVerified: true), email, username); - await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); } [Test] - public async Task SignupFinalize_PendingAccount_EmailTheProviderVerified_ReplacesItWithAnActivatedAccount() + public async Task SignupFinalize_PendingSignup_EmailTheProviderVerified_ReplacesItWithAnAccount() { var externalId = NewExternalId(); - var (pendingUserId, _) = await CreatePendingOAuthAccountAsync("oauth-finalize-replace", externalId); + var pendingId = await CreatePendingOAuthSignupAsync(TestHelper.UniqueEmail("oauth-finalize-replace"), "oauthfinreplace", externalId); var email = TestHelper.UniqueEmail("oauth-finalize-replace-verified"); using var client = CreateClient(); @@ -201,17 +193,16 @@ public async Task SignupFinalize_PendingAccount_EmailTheProviderVerified_Replace 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(); + var user = await FindUserByEmailAsync(WebApplicationFactory, email); + await Assert.That(user!.ActivatedAt).IsNotNull(); + await Assert.That(await FindAsync(WebApplicationFactory, pendingId)).IsNull(); } [Test] - public async Task SignupFinalize_PendingAccount_EmailTheProviderVerified_UsernameTaken_KeepsThePendingAccount() + public async Task SignupFinalize_PendingSignup_UsernameTaken_KeepsThePendingSignup() { var externalId = NewExternalId(); - var (pendingUserId, _) = await CreatePendingOAuthAccountAsync("oauth-finalize-keep", externalId); + var pendingId = await CreatePendingOAuthSignupAsync(TestHelper.UniqueEmail("oauth-finalize-keep"), "oauthfinkeep", 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"); @@ -220,52 +211,75 @@ public async Task SignupFinalize_PendingAccount_EmailTheProviderVerified_Usernam 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(); + await Assert.That(await FindAsync(WebApplicationFactory, pendingId)).IsNotNull(); - // The identity is still linked to it, so the signup can be retried with another username. + // The flow is still open, 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(); + await Assert.That(await FindAsync(WebApplicationFactory, pendingId)).IsNull(); } [Test] - public async Task SignupFinalize_IdentityOfAnActivatedAccount_Returns409() + public async Task SignupFinalize_IdentityOfAnAccount_Returns409() { var externalId = NewExternalId(); - var (userId, token) = await CreatePendingOAuthAccountAsync("oauth-finalize-activated", externalId); + var email = TestHelper.UniqueEmail("oauth-finalize-linked"); using var client = CreateClient(); - await HandoffAsync(client, MintFlowCookie(externalId, activationToken: token)); - await Assert.That(await IsActivatedAsync(userId)).IsTrue(); + var created = await FinalizeAsync(client, MintFlowCookie(externalId, email: email, emailVerified: true), email, TestHelper.UniqueUsername("oauthfinlinked")); + await Assert.That(created.StatusCode).IsEqualTo(HttpStatusCode.OK); - var response = await FinalizeAsync(client, MintFlowCookie(externalId), TestHelper.UniqueEmail("oauth-finalize-activated-new"), TestHelper.UniqueUsername("oauthfinact")); + var response = await FinalizeAsync(client, MintFlowCookie(externalId), TestHelper.UniqueEmail("oauth-finalize-linked-new"), TestHelper.UniqueUsername("oauthfinlinked2")); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); } // --- the reported takeover, end to end --- + // Someone signs up through a provider, typing an address that is not theirs. Nothing they did may + // end up on the account the owner of that address later creates. [Test] - public async Task AccountSomeoneElseCreatedOnMyAddress_AfterITakeItOverByPasswordReset_TheirIdentityNoLongerSignsIn() + public async Task SignupSomeoneElseStartedOnMyAddress_NeverBecomesMyAccount_AndDoesNotKeepMeFromSigningUp() { 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(); + var attackerSignup = await FinalizeAsync(client, MintFlowCookie(attackerExternalId, email: TestHelper.UniqueEmail("oauth-takeover-attacker"), emailVerified: true), victimEmail, TestHelper.UniqueUsername("oauthtakeover")); + await Assert.That(attackerSignup.StatusCode).IsEqualTo(HttpStatusCode.OK); + var attackerPending = (await FindByEmailAsync(WebApplicationFactory, victimEmail)).Single(); + + // The victim gets that mail. The code in it does nothing in their browser... + var attackerCode = await MailCodeAsync(WebApplicationFactory, attackerPending.Id); + await Assert.That((await PostActivateAsync(client, attackerCode, cookie: null)).StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + + // ...and the address is still free for them to sign up with, which they do, and complete. + var victimSignup = await PostSignupAsync(client, victimEmail, TestHelper.UniqueUsername("oauthvictim"), "VictimPassword123#"); + await Assert.That(victimSignup.StatusCode).IsEqualTo(HttpStatusCode.OK); + var victimPending = (await FindByEmailAsync(WebApplicationFactory, victimEmail)).Single(p => p.Id != attackerPending.Id); + var victimCode = await MailCodeAsync(WebApplicationFactory, victimPending.Id); + var activated = await PostActivateAsync(client, victimCode, ReadSetCookie(victimSignup, AuthConstants.SignupBrowserSecureCookieName)); + await Assert.That(activated.StatusCode).IsEqualTo(HttpStatusCode.OK); + + // The account is the victim's signup, with no identity linked to it. + var account = await FindUserByEmailAsync(WebApplicationFactory, victimEmail); + await Assert.That(account!.Id).IsEqualTo(victimPending.Id); + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.UserOAuthConnections.AsNoTracking().AnyAsync(c => c.UserId == account.Id)).IsFalse(); + } - // The attacker's identity is no longer linked: signing in with it reaches no account. + // The attacker's signup is gone: signing in with their identity reaches nothing... + await Assert.That(await FindAsync(WebApplicationFactory, attackerPending.Id)).IsNull(); var handoff = await HandoffAsync(client, MintFlowCookie(attackerExternalId)); await AssertSentBackToSignupAsync(handoff, pending: false); - // And it cannot be attached to that address again. + // ...their code does nothing even in their own browser... + var late = await PostActivateAsync(client, attackerCode, MintSignupBrowserCookie(WebApplicationFactory, attackerPending.Id)); + await Assert.That(late.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + + // ...and the address cannot be signed up with again. var again = await FinalizeAsync(client, MintFlowCookie(attackerExternalId), victimEmail, TestHelper.UniqueUsername("oauthtakeover2")); await Assert.That(again.StatusCode).IsEqualTo(HttpStatusCode.Conflict); } @@ -284,7 +298,7 @@ private HttpClient CreateClient() => WebApplicationFactory.CreateClient(new WebA /// 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) + private string MintFlowCookie(string externalId, string? email = null, bool emailVerified = false, OAuthFlow flow = OAuthFlow.LoginOrCreate) { var options = WebApplicationFactory.Services.GetRequiredService>().Get(OAuthConstants.FlowScheme); @@ -303,27 +317,12 @@ private string MintFlowCookie(string externalId, string? email = null, bool emai }; properties.Items[".AuthScheme"] = Provider; OAuthUtil.SetOAuthFlow(properties, flow); - OAuthUtil.SetActivationToken(properties, 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 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)!; - } - private static Task HandoffAsync(HttpClient client, string flowCookie) { var request = new HttpRequestMessage(HttpMethod.Get, $"/1/oauth/{Provider}/handoff"); @@ -350,83 +349,14 @@ private static async Task AssertSentBackToSignupAsync(HttpResponseMessage respon 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(); - } + /// A signup started through the provider with an address it did not verify, with no mail queued yet. + private Task CreatePendingOAuthSignupAsync(string email, string username, string externalId, bool uniqueUsername = true) + => CreateInDbAsync(WebApplicationFactory, email, uniqueUsername ? TestHelper.UniqueUsername(username) : username, password: null, oauthProvider: Provider, oauthExternalId: externalId); - private async Task GetUserByEmailAsync(string email) + private async Task CountOutboxAsync(string email) { await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); var db = scope.ServiceProvider.GetRequiredService(); - return await db.Users.AsNoTracking().SingleAsync(u => u.Email == email); + return await db.EmailOutbox.AsNoTracking().CountAsync(m => m.Recipient == email); } } diff --git a/API.IntegrationTests/Tests/PendingSignupsMigrationTests.cs b/API.IntegrationTests/Tests/PendingSignupsMigrationTests.cs new file mode 100644 index 000000000..b98d4290f --- /dev/null +++ b/API.IntegrationTests/Tests/PendingSignupsMigrationTests.cs @@ -0,0 +1,108 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.Extensions.Logging.Abstractions; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Utils; +using Testcontainers.PostgreSql; + +namespace OpenShock.API.IntegrationTests.Tests; + +/// +/// Runs the PendingSignups migration over a database that still has never activated accounts in it, the way +/// production has: each becomes a pending signup, except the ones a person should look at first. +/// +public sealed class PendingSignupsMigrationTests +{ + private const string MigrationBefore = "20261126000339_PostgresNativeCleanup"; + + [Test] + public async Task NeverActivatedAccounts_BecomePendingSignups_AndTheRestIsLeftAlone() + { + await using var container = new PostgreSqlBuilder(image: "timescale/timescaledb:latest-pg18").Build(); + await container.StartAsync(); + + MigrationOpenShockContext CreateContext() => new(container.GetConnectionString(), false, NullLoggerFactory.Instance); + + var withPassword = Guid.CreateVersion7(); + var withOAuth = Guid.CreateVersion7(); + var activated = Guid.CreateVersion7(); + var staff = Guid.CreateVersion7(); + var deactivated = Guid.CreateVersion7(); + var ownsHub = Guid.CreateVersion7(); + var passwordHash = HashingUtils.HashPassword("SeedPassword123#"); + + await using (var db = CreateContext()) + { + await db.GetService().MigrateAsync(MigrationBefore); + + db.Users.AddRange( + NewUser(withPassword, "migratepassword", passwordHash, isActivated: false), + NewUser(withOAuth, "migrateoauth", passwordHash: null, isActivated: false), + NewUser(activated, "migrateactivated", passwordHash, isActivated: true), + NewUser(staff, "migratestaff", passwordHash, isActivated: false, RoleType.Staff), + NewUser(deactivated, "migratedeactivated", passwordHash, isActivated: false), + NewUser(ownsHub, "migratehub", passwordHash, isActivated: false)); + db.UserOAuthConnections.Add(new UserOAuthConnection { UserId = withOAuth, ProviderKey = "discord", ExternalId = "migrate-external-id", DisplayName = "External" }); + db.UserDeactivations.Add(new UserDeactivation { DeactivatedUserId = deactivated, DeactivatedByUserId = deactivated, DeleteLater = false }); + db.Devices.Add(new Device { Id = Guid.CreateVersion7(), OwnerId = ownsHub, Name = "Hub", Token = "pending-signups-migration-token" }); + await db.SaveChangesAsync(); + + // The table the migration drops, with the link that was mailed for one of the accounts. + await db.Database.ExecuteSqlAsync( + $"INSERT INTO user_activation_requests (user_id, token_hash, email_send_attempts) VALUES ({withPassword}, {HashingUtils.HashToken("mailed-link-token")}, 1)"); + } + + await using (var db = CreateContext()) + { + await db.Database.MigrateAsync(); + } + + await using (var db = CreateContext()) + { + var users = await db.Users.AsNoTracking().Select(u => u.Id).ToListAsync(); + await Assert.That(users).DoesNotContain(withPassword); + await Assert.That(users).DoesNotContain(withOAuth); + await Assert.That(users).Contains(activated); + await Assert.That(users).Contains(staff); + await Assert.That(users).Contains(deactivated); + await Assert.That(users).Contains(ownsHub); + + var pending = await db.PendingSignups.AsNoTracking().ToDictionaryAsync(p => p.Id); + await Assert.That(pending.Count).IsEqualTo(2); + + // Same id, address, username and credential, so signing in with it finds the signup again. + var password = pending[withPassword]; + await Assert.That(password.Email).IsEqualTo("migratepassword@test.org"); + await Assert.That(password.Username).IsEqualTo("migratepassword"); + await Assert.That(password.PasswordHash).IsEqualTo(passwordHash); + await Assert.That(password.OAuthProviderKey).IsNull(); + // No code is accepted until one has been mailed, and the link mailed before is worth nothing. + await Assert.That(password.CodeSentAt).IsNull(); + await Assert.That(password.CodeHash).IsNotEqualTo(HashingUtils.HashToken("mailed-link-token")); + await Assert.That(password.CodeHash.Length).IsEqualTo(64); + // The lifetime starts over at the migration. + await Assert.That(password.CreatedAt).IsGreaterThan(DateTime.UtcNow - TimeSpan.FromMinutes(5)); + + var oauth = pending[withOAuth]; + await Assert.That(oauth.PasswordHash).IsNull(); + await Assert.That(oauth.OAuthProviderKey).IsEqualTo("discord"); + await Assert.That(oauth.OAuthExternalId).IsEqualTo("migrate-external-id"); + await Assert.That(oauth.OAuthDisplayName).IsEqualTo("External"); + + // The identity is free again for the account the signup turns into. + await Assert.That(await db.UserOAuthConnections.AsNoTracking().AnyAsync(c => c.ExternalId == "migrate-external-id")).IsFalse(); + } + } + + private static User NewUser(Guid id, string name, string? passwordHash, bool isActivated, params RoleType[] roles) => new() + { + Id = id, + Name = name, + Email = $"{name}@test.org", + PasswordHash = passwordHash, + Roles = [.. roles], + CreatedAt = DateTime.UtcNow - TimeSpan.FromDays(30), + ActivatedAt = isActivated ? DateTime.UtcNow - TimeSpan.FromDays(30) : null + }; +} diff --git a/API.IntegrationTests/Tests/SignupActivationTests.cs b/API.IntegrationTests/Tests/SignupActivationTests.cs new file mode 100644 index 000000000..a3a0c473a --- /dev/null +++ b/API.IntegrationTests/Tests/SignupActivationTests.cs @@ -0,0 +1,793 @@ +using System.Net; +using System.Text.Json; +using Microsoft.AspNetCore.Mvc.Testing; +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 static OpenShock.API.IntegrationTests.Helpers.PendingSignupHelper; + +namespace OpenShock.API.IntegrationTests.Tests; + +/// +/// Signing up creates no account. It records a pending signup and mails a code, and the account only comes +/// to exist when that code is entered in a browser that holds the signup. These tests cover that: what a +/// signup leaves behind, who can complete it, and what the code and the cookie are each worth alone. +/// +/// +/// The code is minted by the Cron delivery job when it sends the mail (covered in Cron.IntegrationTests), +/// so the tests stand in for it with . +/// +public sealed class SignupActivationTests +{ + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required WebApplicationFactory WebApplicationFactory { get; init; } + + // --- Signing up --- + + [Test] + public async Task Signup_CreatesNoAccount_AndEnqueuesTheActivationCode() + { + var email = TestHelper.UniqueEmail("signup-pending"); + var username = TestHelper.UniqueUsername("signuppending"); + using var client = CreateClient(); + + var response = await PostSignupAsync(client, email, username); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); + + var pending = (await FindByEmailAsync(WebApplicationFactory, email)).Single(); + await Assert.That(pending.Username).IsEqualTo(username); + await Assert.That(pending.PasswordHash).IsNotNull(); + // No code is accepted until the delivery job has mailed one. + await Assert.That(pending.CodeSentAt).IsNull(); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var row = await db.EmailOutbox.AsNoTracking().SingleAsync(m => m.Recipient == email); + await Assert.That(row.Type).IsEqualTo(EmailType.AccountActivation); + await Assert.That(row.Status).IsEqualTo(EmailStatus.Pending); + await Assert.That(row.CoalesceKey).IsEqualTo(EmailOutboxCoalesceKeys.AccountActivation(pending.Id)); + await Assert.That(row.Payload[EmailOutboxPayloadKeys.PendingSignupId]).IsEqualTo(pending.Id.ToString()); + } + + [Test] + public async Task Signup_SetsTheResendCookie_ReadableByTheFrontend() + { + using var client = CreateClient(); + var response = await PostSignupAsync(client, TestHelper.UniqueEmail("signup-resendcookie"), TestHelper.UniqueUsername("signupresendcookie")); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + // The frontend offers the code form and the resend button only while the cookie exists. + var cookie = response.Headers.GetValues("Set-Cookie").Single(c => c.StartsWith(AuthConstants.ActivationResendCookieName + "=")); + await Assert.That(cookie.Contains("httponly", StringComparison.OrdinalIgnoreCase)).IsFalse(); + } + + [Test] + public async Task Signup_SetsTheSignupBrowserCookie_BoundToTheApiHost() + { + using var client = CreateClient(); + var response = await PostSignupAsync(client, TestHelper.UniqueEmail("signup-browsercookie"), TestHelper.UniqueUsername("signupbrowsercookie")); + 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(); + } + + // A pending signup does not reserve its address: someone who signs up with an address that is not + // theirs does not keep its owner (or anyone else) from signing up with it. + [Test] + public async Task Signup_AddressOfAPendingSignup_IsAccepted() + { + var email = TestHelper.UniqueEmail("signup-twice"); + using var client = CreateClient(); + + await Assert.That((await PostSignupAsync(client, email, TestHelper.UniqueUsername("signuptwicea"))).StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That((await PostSignupAsync(client, email, TestHelper.UniqueUsername("signuptwiceb"), "AnotherPassword123#")).StatusCode).IsEqualTo(HttpStatusCode.OK); + + await Assert.That((await FindByEmailAsync(WebApplicationFactory, email)).Count).IsEqualTo(2); + } + + // The username is different: whoever is entering their code keeps the name while they do. + [Test] + public async Task Signup_UsernameOfAPendingSignupStartedWithinTheHour_Returns409() + { + var username = TestHelper.UniqueUsername("signupreserved"); + var email = TestHelper.UniqueEmail("signup-reserved-second"); + using var client = CreateClient(); + + await Assert.That((await PostSignupAsync(client, TestHelper.UniqueEmail("signup-reserved-first"), username)).StatusCode).IsEqualTo(HttpStatusCode.OK); + + var response = await PostSignupAsync(client, email, username); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + await Assert.That(await FindByEmailAsync(WebApplicationFactory, email)).IsEmpty(); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); + } + + [Test] + public async Task CheckUsername_UsernameOfAPendingSignupStartedWithinTheHour_IsTaken() + { + var username = TestHelper.UniqueUsername("checkreserved"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, TestHelper.UniqueEmail("check-reserved"), username); + + using var client = CreateClient(); + await Assert.That(await CheckUsernameAsync(client, username)).IsEqualTo("Taken"); + + await BackdateSignupAsync(pendingId, Duration.PendingSignupUsernameReservation + TimeSpan.FromMinutes(1)); + await Assert.That(await CheckUsernameAsync(client, username)).IsEqualTo("Available"); + } + + // After the hour the name is open again, though the older signup can still be completed: the first of + // them to enter its code gets the name, and the other is told it is taken. + [Test] + public async Task Signup_UsernameOfAPendingSignupOlderThanTheHour_IsAccepted_AndTheFirstToActivateGetsIt() + { + var username = TestHelper.UniqueUsername("signupreleased"); + var olderEmail = TestHelper.UniqueEmail("signup-released-older"); + var newerEmail = TestHelper.UniqueEmail("signup-released-newer"); + var older = await CreateInDbAsync(WebApplicationFactory, olderEmail, username); + await BackdateSignupAsync(older, Duration.PendingSignupUsernameReservation + TimeSpan.FromMinutes(1)); + + using var client = CreateClient(); + var signup = await PostSignupAsync(client, newerEmail, username); + await Assert.That(signup.StatusCode).IsEqualTo(HttpStatusCode.OK); + var newer = (await FindByEmailAsync(WebApplicationFactory, newerEmail)).Single(); + + var newerCode = await MailCodeAsync(WebApplicationFactory, newer.Id); + var first = await PostActivateAsync(client, newerCode, ReadSetCookie(signup, AuthConstants.SignupBrowserSecureCookieName)); + await Assert.That(first.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That((await FindUserByEmailAsync(WebApplicationFactory, newerEmail))!.Name).IsEqualTo(username); + + var olderCode = await MailCodeAsync(WebApplicationFactory, older); + var second = await PostActivateAsync(client, olderCode, MintSignupBrowserCookie(WebApplicationFactory, older)); + await Assert.That(second.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, olderEmail)).IsNull(); + } + + // An account changing its name is kept off a reserved name like a signup is. + [Test] + public async Task ChangeUsername_ToTheUsernameOfAPendingSignupStartedWithinTheHour_Returns409() + { + var username = TestHelper.UniqueUsername("renamereserved"); + await CreateInDbAsync(WebApplicationFactory, TestHelper.UniqueEmail("rename-reserved"), username); + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("renamereserveduser"), TestHelper.UniqueEmail("rename-reserved-user"), Password); + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var response = await client.PostAsync("/1/account/username", TestHelper.JsonContent(new { username })); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + } + + [Test] + public async Task Signup_EmailOfAnAccount_Returns409() + { + var email = TestHelper.UniqueEmail("signup-taken-email"); + await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("signuptakenemail"), email, Password); + + using var client = CreateClient(); + var response = await PostSignupAsync(client, email, TestHelper.UniqueUsername("signuptakenemail")); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + await Assert.That(await FindByEmailAsync(WebApplicationFactory, email)).IsEmpty(); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); + } + + [Test] + public async Task Signup_UsernameOfAnAccount_Returns409() + { + var username = TestHelper.UniqueUsername("signuptakenname"); + await TestHelper.CreateUserInDb(WebApplicationFactory, username, TestHelper.UniqueEmail("signup-taken-name"), Password); + var email = TestHelper.UniqueEmail("signup-taken-name-new"); + + using var client = CreateClient(); + var response = await PostSignupAsync(client, email, username); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); + } + + // An address is only mailed so often, however many signups it takes: each signup would otherwise start + // its own count, and signing up again and again would flood somebody's inbox. + [Test] + public async Task Signup_AddressAlreadySentTheDailyCapOfActivationEmails_Returns409_AndMailsNothing() + { + var email = TestHelper.UniqueEmail("signup-address-cap"); + + using var client = CreateClient(); + for (var i = 0; i < 5; i++) + { + var response = await PostSignupAsync(client, email, TestHelper.UniqueUsername("signupaddresscap")); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + } + + var sixth = await PostSignupAsync(client, email, TestHelper.UniqueUsername("signupaddresscap")); + await Assert.That(sixth.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(5); + await Assert.That((await FindByEmailAsync(WebApplicationFactory, email)).Count).IsEqualTo(5); + } + + // The count behind the cap is only good while nobody else queues mail for the address, so counting and + // queueing hold a lock on the address. A request that meets the lock is turned away, not left to queue + // on a count that is about to be out of date. + [Test] + public async Task Signup_WhileAnotherRequestQueuesActivationMailForTheAddress_Returns409_AndMailsNothing() + { + var email = TestHelper.UniqueEmail("signup-address-lock"); + + using var client = CreateClient(); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + // Stands in for a request that has counted the address's mail and not yet committed its own. + var db = scope.ServiceProvider.GetRequiredService(); + await using var transaction = await db.Database.BeginTransactionAsync(); + await Assert.That(await db.Database.TryLockForTransactionAsync(AccountService.ActivationEmailLockName(email))).IsTrue(); + + var blocked = await PostSignupAsync(client, email, TestHelper.UniqueUsername("signupaddresslock")); + await Assert.That(blocked.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); + } + + var afterwards = await PostSignupAsync(client, email, TestHelper.UniqueUsername("signupaddresslock")); + await Assert.That(afterwards.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(1); + } + + // --- Completing a signup: the mailed code, entered in a browser that holds the signup --- + + [Test] + public async Task Activate_CodeFromTheMail_InTheSignupBrowser_CreatesTheAccount() + { + var email = TestHelper.UniqueEmail("activate-ok"); + var username = TestHelper.UniqueUsername("activateok"); + using var client = CreateClient(); + + var signup = await PostSignupAsync(client, email, username); + // Both cookies of the signup, as the browser that made it sends them. + var cookie = $"{ReadSetCookie(signup, AuthConstants.SignupBrowserSecureCookieName)}; {ReadSetCookie(signup, AuthConstants.ActivationResendCookieName)}"; + var pending = (await FindByEmailAsync(WebApplicationFactory, email)).Single(); + var code = await MailCodeAsync(WebApplicationFactory, pending.Id); + + var response = await PostActivateAsync(client, code, cookie); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + // The cookies have done their job. + await Assert.That(DeletesCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsTrue(); + await Assert.That(DeletesCookie(response, AuthConstants.ActivationResendCookieName)).IsTrue(); + + var user = await FindUserByEmailAsync(WebApplicationFactory, email); + await Assert.That(user).IsNotNull(); + await Assert.That(user!.Id).IsEqualTo(pending.Id); + await Assert.That(user.Name).IsEqualTo(username); + await Assert.That(user.ActivatedAt).IsNotNull(); + await Assert.That(await FindAsync(WebApplicationFactory, pending.Id)).IsNull(); + + // The account has the password it was signed up with. + var login = await PostLoginAsync(client, email, Password); + await Assert.That(login.StatusCode).IsEqualTo(HttpStatusCode.OK); + } + + // The mail goes to whoever owns the address, who may not be the one who signed up and chose the + // password. The code alone is worth nothing to them, and nothing in the mail can be clicked. + [Test] + public async Task Activate_CodeWithoutTheSignupCookie_Returns400_AndCreatesNoAccount() + { + var email = TestHelper.UniqueEmail("activate-nocookie"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activatenocookie")); + var code = await MailCodeAsync(WebApplicationFactory, pendingId); + + using var client = CreateClient(); + var response = await PostActivateAsync(client, code, cookie: null); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Account.Activation.NotFound"); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); + await Assert.That(await FindAsync(WebApplicationFactory, pendingId)).IsNotNull(); + } + + // Two signups for one address, by two people. Each browser can only complete its own signup, and only + // with the code of that signup: the owner of the inbox cannot be made to complete the other one, and + // the other one cannot use a code its owner reads off their own mail. + [Test] + public async Task Activate_CodeOfAnotherSignupForTheSameAddress_Returns400() + { + var email = TestHelper.UniqueEmail("activate-othersignup"); + var theirs = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activateothers"), "TheirPassword123#"); + var mine = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activatemine")); + await MailCodeAsync(WebApplicationFactory, theirs); + var myCode = await MailCodeAsync(WebApplicationFactory, mine); + + using var client = CreateClient(); + var response = await PostActivateAsync(client, myCode, MintSignupBrowserCookie(WebApplicationFactory, theirs)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Account.Activation.CodeInvalid"); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); + } + + [Test] + public async Task Activate_ResendCookieAlone_Returns400() + { + // The resend cookie is shared across the cookie domain and readable by script, so it proves nothing. + var email = TestHelper.UniqueEmail("activate-resendcookie"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activateresendcookie")); + var code = await MailCodeAsync(WebApplicationFactory, pendingId); + + using var client = CreateClient(); + var response = await PostActivateAsync(client, code, MintResendCookie(WebApplicationFactory, pendingId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); + } + + [Test] + public async Task Activate_SignupBrowserCookieWithoutHostPrefix_Returns400() + { + // The unprefixed name is the one a sibling subdomain could set. + var email = TestHelper.UniqueEmail("activate-noprefix"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activatenoprefix")); + var code = await MailCodeAsync(WebApplicationFactory, pendingId); + var value = MintSignupBrowserCookie(WebApplicationFactory, pendingId)[(AuthConstants.SignupBrowserSecureCookieName.Length + 1)..]; + + using var client = CreateClient(); + var response = await PostActivateAsync(client, code, $"{AuthConstants.SignupBrowserCookieName}={value}"); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); + } + + [Test] + public async Task Activate_WrongCode_Returns400_WithTheAttemptsLeft() + { + var email = TestHelper.UniqueEmail("activate-wrong"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activatewrong")); + var code = await MailCodeAsync(WebApplicationFactory, pendingId); + var cookie = MintSignupBrowserCookie(WebApplicationFactory, pendingId); + + using var client = CreateClient(); + var response = await PostActivateAsync(client, AnotherCode(code), cookie); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + await Assert.That(problem.RootElement.GetProperty("type").GetString()).IsEqualTo("Account.Activation.CodeInvalid"); + await Assert.That(problem.RootElement.GetProperty("attemptsRemaining").GetInt32()).IsEqualTo(AuthConstants.ActivationCodeMaxAttempts - 1); + + // A wrong guess does not cost the signup: the right code still works. + await Assert.That((await PostActivateAsync(client, code, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); + } + + // Six digits are only safe while they cannot be guessed at freely. + [Test] + public async Task Activate_AfterTooManyWrongCodes_EvenTheRightOneIsRefused_UntilANewOneIsMailed() + { + var email = TestHelper.UniqueEmail("activate-attempts"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activateattempts")); + var code = await MailCodeAsync(WebApplicationFactory, pendingId); + var cookie = MintSignupBrowserCookie(WebApplicationFactory, pendingId); + + using var client = CreateClient(); + for (var i = 0; i < AuthConstants.ActivationCodeMaxAttempts; i++) + { + var wrong = await PostActivateAsync(client, AnotherCode(code), cookie); + await Assert.That(await wrong.Content.ReadAsStringAsync()).Contains("Account.Activation.CodeInvalid"); + } + + var response = await PostActivateAsync(client, code, cookie); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Account.Activation.CodeExpired"); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); + + // A newly mailed code starts over. + var newCode = await MailCodeAsync(WebApplicationFactory, pendingId); + await Assert.That((await PostActivateAsync(client, newCode, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); + } + + [Test] + public async Task Activate_CodeOlderThanItsLifetime_Returns400() + { + var email = TestHelper.UniqueEmail("activate-oldcode"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activateoldcode")); + var code = await MailCodeAsync(WebApplicationFactory, pendingId); + await BackdateCodeAsync(pendingId, Duration.ActivationCodeLifetime + TimeSpan.FromMinutes(1)); + + using var client = CreateClient(); + var response = await PostActivateAsync(client, code, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Account.Activation.CodeExpired"); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); + } + + [Test] + public async Task Activate_BeforeAnyCodeWasMailed_Returns400() + { + // The row is created with a throwaway hash; nothing may match it. + var email = TestHelper.UniqueEmail("activate-nocode"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activatenocode")); + + using var client = CreateClient(); + var response = await PostActivateAsync(client, "000000", MintSignupBrowserCookie(WebApplicationFactory, pendingId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Account.Activation.CodeExpired"); + } + + [Test] + public async Task Activate_SignupOlderThanItsLifetime_Returns400_AndRemovesTheCookies() + { + var email = TestHelper.UniqueEmail("activate-oldsignup"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activateoldsignup")); + var code = await MailCodeAsync(WebApplicationFactory, pendingId); + await BackdateSignupAsync(pendingId, Duration.PendingSignupLifetime + TimeSpan.FromMinutes(1)); + + using var client = CreateClient(); + var response = await PostActivateAsync(client, code, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Account.Activation.NotFound"); + await Assert.That(DeletesCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsTrue(); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); + } + + [Test] + public async Task Activate_MalformedCode_Returns400() + { + var pendingId = await CreateInDbAsync(WebApplicationFactory, TestHelper.UniqueEmail("activate-malformed"), TestHelper.UniqueUsername("activatemalformed")); + await MailCodeAsync(WebApplicationFactory, pendingId); + + using var client = CreateClient(); + var response = await PostActivateAsync(client, "12", MintSignupBrowserCookie(WebApplicationFactory, pendingId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + // Refused before it is looked at, so it does not count as a guess. + await Assert.That((await FindAsync(WebApplicationFactory, pendingId))!.FailedAttempts).IsEqualTo(0); + } + + // Whoever enters their code first gets the address. The others can no longer be completed. + [Test] + public async Task Activate_TwoSignupsForOneAddress_TheFirstToEnterItsCodeGetsIt() + { + var email = TestHelper.UniqueEmail("activate-race"); + var first = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activateracea"), "FirstPassword123#"); + var second = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activateraceb"), "SecondPassword123#"); + await MailCodeAsync(WebApplicationFactory, first); + var secondCode = await MailCodeAsync(WebApplicationFactory, second); + + using var client = CreateClient(); + var response = await PostActivateAsync(client, secondCode, MintSignupBrowserCookie(WebApplicationFactory, second)); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + var user = await FindUserByEmailAsync(WebApplicationFactory, email); + await Assert.That(user!.Id).IsEqualTo(second); + + // The other signup is gone, and with it the password its creator chose for this address. + await Assert.That(await FindAsync(WebApplicationFactory, first)).IsNull(); + await Assert.That((await PostLoginAsync(client, email, "FirstPassword123#")).StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + await Assert.That((await PostLoginAsync(client, email, "SecondPassword123#")).StatusCode).IsEqualTo(HttpStatusCode.OK); + } + + [Test] + public async Task Activate_AddressTakenByAnAccountWhileTheSignupWasPending_Returns409() + { + var email = TestHelper.UniqueEmail("activate-taken"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activatetaken")); + var code = await MailCodeAsync(WebApplicationFactory, pendingId); + var existingUserId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("activatetakenby"), email, "TheirPassword123#"); + + using var client = CreateClient(); + var response = await PostActivateAsync(client, code, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + await Assert.That((await FindUserByEmailAsync(WebApplicationFactory, email))!.Id).IsEqualTo(existingUserId); + } + + [Test] + public async Task Activate_UsernameTakenByAnAccountWhileTheSignupWasPending_Returns409() + { + var email = TestHelper.UniqueEmail("activate-nametaken"); + var username = TestHelper.UniqueUsername("activatenametaken"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, username); + var code = await MailCodeAsync(WebApplicationFactory, pendingId); + await TestHelper.CreateUserInDb(WebApplicationFactory, username, TestHelper.UniqueEmail("activate-nametaken-by"), "TheirPassword123#"); + + using var client = CreateClient(); + var response = await PostActivateAsync(client, code, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); + } + + [Test] + public async Task Activate_Twice_SecondReturns400() + { + var email = TestHelper.UniqueEmail("activate-twice"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activatetwice")); + var code = await MailCodeAsync(WebApplicationFactory, pendingId); + var cookie = MintSignupBrowserCookie(WebApplicationFactory, pendingId); + + using var client = CreateClient(); + await Assert.That((await PostActivateAsync(client, code, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); + + var again = await PostActivateAsync(client, code, cookie); + await Assert.That(again.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(await again.Content.ReadAsStringAsync()).Contains("Account.Activation.NotFound"); + } + + // --- Asking for the code again --- + + [Test] + public async Task ResendActivation_WithSignupCookie_EnqueuesAnotherActivationCode() + { + var email = TestHelper.UniqueEmail("resend-ok"); + using var client = CreateClient(); + + var signup = await PostSignupAsync(client, email, TestHelper.UniqueUsername("resendok")); + var cookie = ReadSetCookie(signup, AuthConstants.ActivationResendCookieName); + var pending = (await FindByEmailAsync(WebApplicationFactory, email)).Single(); + + // Move the signup email out of the resend cooldown. + await BackdateOutboxAsync(email, TimeSpan.FromMinutes(11)); + + // The delivery job mints a new code for the newer row and supersedes the older one at send time + // (coalesce key); that rotation is covered in Cron.IntegrationTests. + var response = await PostResendAsync(client, cookie); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var rows = await db.EmailOutbox.AsNoTracking().Where(m => m.Recipient == email).ToListAsync(); + await Assert.That(rows.Count).IsEqualTo(2); + await Assert.That(rows.All(r => r.Type == EmailType.AccountActivation)).IsTrue(); + await Assert.That(rows.All(r => r.CoalesceKey == EmailOutboxCoalesceKeys.AccountActivation(pending.Id))).IsTrue(); + } + + [Test] + public async Task ResendActivation_WithinCooldown_Returns429_AndEnqueuesNothing() + { + var email = TestHelper.UniqueEmail("resend-cooldown"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("resendcooldown")); + var cookie = MintResendCookie(WebApplicationFactory, pendingId); + + using var client = CreateClient(); + await Assert.That((await PostResendAsync(client, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That((await PostResendAsync(client, cookie)).StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests); + + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(1); + } + + [Test] + public async Task ResendActivation_DailyCapReached_Returns429() + { + var email = TestHelper.UniqueEmail("resend-cap"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("resendcap")); + var cookie = MintResendCookie(WebApplicationFactory, pendingId); + + using var client = CreateClient(); + for (var i = 0; i < 5; i++) + { + await Assert.That((await PostResendAsync(client, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); + // Step past the cooldown each time; only the 24h cap of 5 should stop the sixth. + await BackdateOutboxAsync(email, TimeSpan.FromMinutes(11)); + } + await Assert.That((await PostResendAsync(client, cookie)).StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests); + + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(5); + } + + // The cap of an address counts across signups, so a second signup cannot get it mailed past the cap. + [Test] + public async Task ResendActivation_AddressAtItsDailyCapThroughOtherSignups_Returns429() + { + var email = TestHelper.UniqueEmail("resend-address-cap"); + using var client = CreateClient(); + for (var i = 0; i < 5; i++) + { + await Assert.That((await PostSignupAsync(client, email, TestHelper.UniqueUsername("resendaddresscap"))).StatusCode).IsEqualTo(HttpStatusCode.OK); + } + + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("resendaddresscap")); + var response = await PostResendAsync(client, MintResendCookie(WebApplicationFactory, pendingId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(5); + } + + [Test] + public async Task ResendActivation_SignupAlreadyCompleted_Returns400_AndRemovesCookie() + { + var email = TestHelper.UniqueEmail("resend-completed"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("resendcompleted")); + var code = await MailCodeAsync(WebApplicationFactory, pendingId); + + using var client = CreateClient(); + await Assert.That((await PostActivateAsync(client, code, MintSignupBrowserCookie(WebApplicationFactory, pendingId))).StatusCode).IsEqualTo(HttpStatusCode.OK); + + var response = await PostResendAsync(client, MintResendCookie(WebApplicationFactory, pendingId)); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(DeletesCookie(response, AuthConstants.ActivationResendCookieName)).IsTrue(); + + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); + } + + [Test] + public async Task ResendActivation_NoCookie_Returns400() + { + using var client = CreateClient(); + var response = await PostResendAsync(client, cookie: null); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + } + + [Test] + public async Task ResendActivation_TamperedCookie_Returns400_AndRemovesCookie() + { + using var client = CreateClient(); + var response = await PostResendAsync(client, $"{AuthConstants.ActivationResendCookieName}=not-a-valid-token"); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(DeletesCookie(response, AuthConstants.ActivationResendCookieName)).IsTrue(); + } + + // --- Signing in with what a pending signup was started with --- + + // Whoever knows the password a signup carries is whoever started it. Signing in with it does not sign + // in (there is no account), but makes this browser hold the signup and mails a new code, so a signup + // can be completed from a browser other than the one it was started in. + [Test] + public async Task Login_PendingSignup_CorrectPassword_ReturnsNotActivated_HoldsTheSignup_AndMailsACode() + { + var email = TestHelper.UniqueEmail("login-pending"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("loginpending")); + + using var client = CreateClient(); + var response = await PostLoginAsync(client, email, Password); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Account.AccountNotActivated"); + await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsFalse(); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var row = await db.EmailOutbox.AsNoTracking().SingleAsync(m => m.Recipient == email); + await Assert.That(row.Type).IsEqualTo(EmailType.AccountActivation); + await Assert.That(row.CoalesceKey).IsEqualTo(EmailOutboxCoalesceKeys.AccountActivation(pendingId)); + } + + // The cookie the sign-in handed out completes the signup with the mailed code. + var cookie = ReadSetCookie(response, AuthConstants.SignupBrowserSecureCookieName); + var code = await MailCodeAsync(WebApplicationFactory, pendingId); + await Assert.That((await PostActivateAsync(client, code, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); + } + + [Test] + public async Task Login_PendingSignup_ByUsername_HoldsTheSignup() + { + var username = TestHelper.UniqueUsername("loginpendingname"); + await CreateInDbAsync(WebApplicationFactory, TestHelper.UniqueEmail("login-pending-name"), username); + + using var client = CreateClient(); + var response = await PostLoginAsync(client, username, Password); + + await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Account.AccountNotActivated"); + await Assert.That(SetsCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsTrue(); + } + + [Test] + public async Task Login_PendingSignup_WrongPassword_IsAnOrdinaryFailedSignIn() + { + var email = TestHelper.UniqueEmail("login-pending-wrong"); + await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("loginpendingwrong")); + + using var client = CreateClient(); + var response = await PostLoginAsync(client, email, "WrongPassword123#"); + + // Nothing tells a signup for this address exists. + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + await Assert.That(await response.Content.ReadAsStringAsync()).DoesNotContain("Account.AccountNotActivated"); + await Assert.That(SetsCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsFalse(); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); + } + + // Several people can have a signup waiting on one address. The password picks out whose it is. + [Test] + public async Task Login_SeveralPendingSignupsForOneAddress_HoldsTheOneWithThatPassword() + { + var email = TestHelper.UniqueEmail("login-pending-several"); + var mine = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("loginseveralmine"), "MyPassword123#"); + await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("loginseveralother"), "TheirPassword123#"); + + using var client = CreateClient(); + var response = await PostLoginAsync(client, email, "MyPassword123#"); + await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Account.AccountNotActivated"); + + var cookie = ReadSetCookie(response, AuthConstants.SignupBrowserSecureCookieName); + var code = await MailCodeAsync(WebApplicationFactory, mine); + await Assert.That((await PostActivateAsync(client, code, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That((await FindUserByEmailAsync(WebApplicationFactory, email))!.Id).IsEqualTo(mine); + } + + // An account always wins over a signup still waiting on the same address. + [Test] + public async Task Login_AccountExists_PendingSignupWithTheSameAddress_IsIgnored() + { + var email = TestHelper.UniqueEmail("login-account-wins"); + await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("loginaccountwins"), email, "AccountPassword123#"); + await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("loginaccountpending"), "PendingPassword123#"); + + using var client = CreateClient(); + var response = await PostLoginAsync(client, email, "PendingPassword123#"); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + await Assert.That(await response.Content.ReadAsStringAsync()).DoesNotContain("Account.AccountNotActivated"); + await Assert.That(SetsCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsFalse(); + } + + [Test] + public async Task Login_Success_RemovesTheSignupCookies() + { + var email = TestHelper.UniqueEmail("login-clears"); + var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("loginclears"), email, Password); + + using var client = CreateClient(); + var response = await PostLoginAsync(client, email, Password, MintResendCookie(WebApplicationFactory, userId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(DeletesCookie(response, AuthConstants.ActivationResendCookieName)).IsTrue(); + } + + // --- helpers --- + + private HttpClient CreateClient() => WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false, + HandleCookies = false + }); + + private static async Task CheckUsernameAsync(HttpClient client, string username) + { + var response = await client.PostAsync("/1/account/username/check", TestHelper.JsonContent(new { username })); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + return body.RootElement.GetProperty("availability").GetString(); + } + + private async Task CountOutboxAsync(string email) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.EmailOutbox.AsNoTracking().CountAsync(m => m.Recipient == email); + } + + private async Task BackdateOutboxAsync(string email, TimeSpan by) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await db.EmailOutbox + .Where(m => m.Recipient == email) + .ExecuteUpdateAsync(s => s.SetProperty(m => m.CreatedAt, m => m.CreatedAt - by)); + } + + private async Task BackdateCodeAsync(Guid pendingSignupId, TimeSpan by) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await db.PendingSignups + .Where(p => p.Id == pendingSignupId) + .ExecuteUpdateAsync(s => s.SetProperty(p => p.CodeSentAt, p => p.CodeSentAt - by)); + } + + private async Task BackdateSignupAsync(Guid pendingSignupId, TimeSpan by) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await db.PendingSignups + .Where(p => p.Id == pendingSignupId) + .ExecuteUpdateAsync(s => s.SetProperty(p => p.CreatedAt, p => p.CreatedAt - by)); + } +} diff --git a/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs b/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs index a1e674dd0..c74ddff12 100644 --- a/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs +++ b/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs @@ -1,19 +1,14 @@ 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; +using static OpenShock.API.IntegrationTests.Helpers.PendingSignupHelper; 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. +/// The signup browser cookie only lets a browser enter the code 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. The key is // the one the LCG assignment suites use, because they share this host and read the same fake location. @@ -27,57 +22,58 @@ public sealed class SignupBrowserCookieCountryTests public void ResetCountry() => WebApplicationFactory.ClientCountryCode = null; [Test] - public async Task Activate_FromTheCountryOfTheSignup_ActivatesWithTokenAlone() + public async Task Activate_FromTheCountryOfTheSignup_CreatesTheAccount() { WebApplicationFactory.ClientCountryCode = "NO"; - var (userId, token, cookie) = await SignUpAndGetLinkAsync("countrysame"); + var (email, code, cookie) = await SignUpAndGetCodeAsync("countrysame"); - var response = await PostActivateAsync(token, cookie); + var response = await PostActivateAsync(code, cookie); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - await Assert.That(await IsActivatedAsync(userId)).IsTrue(); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNotNull(); } [Test] - public async Task Activate_FromAnotherCountry_AsksForTheCredential() + public async Task Activate_FromAnotherCountry_IgnoresTheCookie() { WebApplicationFactory.ClientCountryCode = "NO"; - var (userId, token, cookie) = await SignUpAndGetLinkAsync("countryother"); + var (email, code, cookie) = await SignUpAndGetCodeAsync("countryother"); WebApplicationFactory.ClientCountryCode = "DE"; - var response = await PostActivateAsync(token, cookie); + var response = await PostActivateAsync(code, cookie); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); - await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); - // 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); + // The signup itself is untouched, and signing in with its password holds it from here as well. + WebApplicationFactory.ClientCountryCode = "DE"; + using var client = CreateClient(); + var login = await PostLoginAsync(client, email, Password); + var abroad = await PostActivateAsync(code, ReadSetCookie(login, AuthConstants.SignupBrowserSecureCookieName)); + await Assert.That(abroad.StatusCode).IsEqualTo(HttpStatusCode.OK); } [Test] public async Task Activate_WhenTheCountryCannotBeResolved_StillAcceptsTheCookie() { WebApplicationFactory.ClientCountryCode = "NO"; - var (userId, token, cookie) = await SignUpAndGetLinkAsync("countryunknown"); + var (email, code, cookie) = await SignUpAndGetCodeAsync("countryunknown"); WebApplicationFactory.ClientCountryCode = null; - var response = await PostActivateAsync(token, cookie); + var response = await PostActivateAsync(code, cookie); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - await Assert.That(await IsActivatedAsync(userId)).IsTrue(); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNotNull(); } [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)}"; + var pendingId = await CreateInDbAsync(WebApplicationFactory, TestHelper.UniqueEmail("country-none"), TestHelper.UniqueUsername("countrynone")); + var code = await MailCodeAsync(WebApplicationFactory, pendingId); WebApplicationFactory.ClientCountryCode = "DE"; - var response = await PostActivateAsync(token, cookie); + var response = await PostActivateAsync(code, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); } @@ -88,64 +84,24 @@ private HttpClient CreateClient() => WebApplicationFactory.CreateClient(new WebA 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) + /// Signs up through the API, and stands in for the Cron job that mails the activation code. + private async Task<(string Email, string Code, string Cookie)> SignUpAndGetCodeAsync(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" - })); + var response = await PostSignupAsync(client, email, TestHelper.UniqueUsername(prefix)); 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); - } + var cookie = ReadSetCookie(response, AuthConstants.SignupBrowserSecureCookieName); + var pending = (await FindByEmailAsync(WebApplicationFactory, email)).Single(); - 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; + return (email, await MailCodeAsync(WebApplicationFactory, pending.Id), cookie); } - private async Task PostActivateAsync(string token, string cookie) + private async Task PostActivateAsync(string code, 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(); + return await PendingSignupHelper.PostActivateAsync(client, code, cookie); } } diff --git a/API/Controller/Account/Activate.cs b/API/Controller/Account/Activate.cs index 9da4913ad..27817baec 100644 --- a/API/Controller/Account/Activate.cs +++ b/API/Controller/Account/Activate.cs @@ -1,12 +1,14 @@ -using System.Net.Mime; +using System.ComponentModel.DataAnnotations; +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.Constants; using OpenShock.Common.Errors; using OpenShock.Internal.Common.Problems; +using DbUser = OpenShock.Common.OpenShockDb.User; using Results = OpenShock.Common.Results; namespace OpenShock.API.Controller.Account; @@ -14,43 +16,54 @@ namespace OpenShock.API.Controller.Account; public sealed partial class AccountController { /// - /// Activate account + /// Complete the signup this browser holds with the code mailed to its address /// /// - /// 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. + /// The signup is identified by a cookie, set when the signup was started and again when its password or + /// linked provider is used to sign in. The code only works together with it: anyone can sign up with + /// somebody else's address, so the mail alone proves nothing about who chose the account's credential. + /// The account is created by this call. It does not sign in. /// - /// Account activated - /// No pending activation matches the token - /// The token is valid, but the account's password or linked sign-in is also required + /// Account created + /// This browser holds no pending signup, the code is wrong, or it has expired + /// The email or username was taken while the signup was pending [HttpPost("activate")] [ApiVersion(1)] [EnableRateLimiting("auth")] + [Consumes(MediaTypeNames.Application.Json)] [ProducesResponseType(StatusCodes.Status200OK)] - [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) + [ProducesResponseType(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] // AccountActivationNotFound, AccountActivationCodeInvalid, AccountActivationCodeExpired + [ProducesResponseType(StatusCodes.Status409Conflict, MediaTypeNames.Application.ProblemJson)] // UsernameOrEmailExists + public async Task Activate([FromBody] ActivateRequest body, CancellationToken cancellationToken) { - SignupBrowserCookie.TryGetUserId(HttpContext, out var signupBrowserUserId); + if (!SignupBrowserCookie.TryGetSignupId(HttpContext, out var signupId)) + { + // Tampered or expired (a no-op when there is no cookie), so the frontend stops offering the form. + ActivationResendCookie.Remove(HttpContext); + return Problem(AccountError.AccountActivationNotFound); + } + + var result = await _accountService.ActivatePendingSignupAsync(signupId.Value, body.Code, cancellationToken); - var result = await _accountService.ActivateAccountAsync(token, signupBrowserUserId, body?.Password, cancellationToken); + // Completed or gone: the cookies have nothing left to do. + if (result is DbUser or Results.NotFound) + ActivationResendCookie.Remove(HttpContext); return result switch { - Results.Success => Ok(), - ActivationCredentialRequired required => Problem(AccountError.AccountActivationCredentialRequired(required.HasPassword, required.OAuthProviders, required.PasswordInvalid)), + DbUser => Ok(), + ActivationCodeInvalid invalid => Problem(AccountError.AccountActivationCodeInvalid(invalid.AttemptsRemaining)), + ActivationCodeExpired => Problem(AccountError.AccountActivationCodeExpired), + AccountWithEmailOrUsernameExists => Problem(SignupError.UsernameOrEmailExists), 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; } + /// The code from the activation email. + [Required] + [StringLength(AuthConstants.ActivationCodeLength, MinimumLength = AuthConstants.ActivationCodeLength)] + public required string Code { get; init; } } } diff --git a/API/Controller/Account/LoginV2.cs b/API/Controller/Account/LoginV2.cs index 1fad63224..c47637ca9 100644 --- a/API/Controller/Account/LoginV2.cs +++ b/API/Controller/Account/LoginV2.cs @@ -7,6 +7,7 @@ using OpenShock.API.Services.Account; using OpenShock.API.Services.Turnstile; using OpenShock.Common.ApiVersioning; +using OpenShock.Common.Authentication; using OpenShock.Common.Errors; using OpenShock.Common.OpenShockDb; using OpenShock.Common.Services.AutomationTokens; @@ -52,8 +53,9 @@ public async Task LoginV2( User account => await CompleteLoginAsync(account, cookieDomain), Results.NotFound => Problem(LoginError.InvalidCredentials), AccountDeactivated => Problem(AccountError.AccountDeactivated), - AccountNotActivated => await ResendActivationAndRejectAsync(), - AccountIsOAuthOnly => Problem(AccountError.AccountOAuthOnly) + AccountNotActivated => Problem(AccountError.AccountNotActivated), + AccountIsOAuthOnly => Problem(AccountError.AccountOAuthOnly), + PendingSignupCredentials pending => await ResumeSignupAndRejectAsync(pending.PendingSignupId, cookieDomain) }; async Task CompleteLoginAsync(User account, string domain) @@ -69,19 +71,21 @@ async Task CompleteLoginAsync(User account, string domain) return Ok(LoginV2OkResponse.FromUser(account)); } - // AccountNotActivated is only returned after the password checked out, so the caller owns this - // account: (re)send the activation link. Rate limited inside the service, and the response is the - // same whether or not a mail went out. - async Task ResendActivationAndRejectAsync() + // The password is the one a signup was started with, so the caller is whoever started it: this + // browser holds the signup from now on and can enter its code. A new code is mailed as well (rate + // limited inside the service), and the response is the same whether or not a mail went out. + async Task ResumeSignupAndRejectAsync(Guid pendingSignupId, string domain) { + ActivationResendCookie.Set(HttpContext, pendingSignupId, domain); + try { - await _accountService.ResendActivationEmailAsync(body.UsernameOrEmail, cancellationToken); + await _accountService.ResendActivationCodeAsync(pendingSignupId, cancellationToken); } catch (Exception ex) when (ex is not OperationCanceledException) { // Best effort: a failed resend must not turn the AccountNotActivated answer into a 500. - _logger.LogError(ex, "Failed to resend activation email on login"); + _logger.LogError(ex, "Failed to resend activation code on login"); } return Problem(AccountError.AccountNotActivated); diff --git a/API/Controller/Account/ResendActivation.cs b/API/Controller/Account/ResendActivation.cs index 9054b0003..b1bfa36ad 100644 --- a/API/Controller/Account/ResendActivation.cs +++ b/API/Controller/Account/ResendActivation.cs @@ -13,14 +13,15 @@ namespace OpenShock.API.Controller.Account; public sealed partial class AccountController { /// - /// Resend the account activation email for the account this browser just signed up + /// Mail a new activation code for the signup this browser holds /// /// - /// Identifies the account by the activation-resend cookie set on signup, not by an email address, - /// so it can only target an account created from this browser and can't be used to probe registered emails. + /// Identifies the signup by the activation-resend cookie, not by an email address, so it can only target + /// a signup this browser started (or signed in to) and can't be used to probe registered emails. The new + /// code replaces the previous one. /// /// Activation email enqueued - /// No pending activation for this browser (missing/expired cookie, or already activated) + /// No pending signup for this browser (missing/expired cookie, or already completed) /// An activation email was sent too recently [HttpPost("activate/resend")] [ApiVersion(1)] @@ -30,24 +31,24 @@ public sealed partial class AccountController [ProducesResponseType(StatusCodes.Status429TooManyRequests, MediaTypeNames.Application.ProblemJson)] // AccountActivationResendTooMany public async Task ResendActivation(CancellationToken cancellationToken) { - if (!ActivationResendCookie.TryGetUserId(HttpContext, out var userId)) + if (!ActivationResendCookie.TryGetSignupId(HttpContext, out var signupId)) { // Tampered or expired (a no-op when there is no cookie), so the frontend stops offering the button. ActivationResendCookie.Remove(HttpContext); return Problem(AccountError.AccountActivationResendUnavailable); } - var result = await _accountService.ResendActivationEmailAsync(userId.Value, cancellationToken); + var result = await _accountService.ResendActivationCodeAsync(signupId.Value, cancellationToken); - // Already activated, deactivated, or gone: the cookie has nothing left to do. - if (result is AccountDeactivated or Results.NotFound) + // Completed or gone: the cookie has nothing left to do. + if (result is Results.NotFound) ActivationResendCookie.Remove(HttpContext); return result switch { Results.Success => Ok(), TooManyActivationResends => Problem(AccountError.AccountActivationResendTooMany), - AccountDeactivated or Results.NotFound => Problem(AccountError.AccountActivationResendUnavailable) + Results.NotFound => Problem(AccountError.AccountActivationResendUnavailable) }; } } diff --git a/API/Controller/Account/SignupV2.cs b/API/Controller/Account/SignupV2.cs index 8871bb453..bad29d7a7 100644 --- a/API/Controller/Account/SignupV2.cs +++ b/API/Controller/Account/SignupV2.cs @@ -18,11 +18,15 @@ public sealed partial class AccountController /// /// Signs up a new user /// + /// + /// Mails an activation code to the address. The account is created once that code is entered in this + /// browser, see POST /1/account/activate. + /// /// /// /// /// - /// User successfully signed up + /// Signup started, activation code mailed /// Username or email already exists [HttpPost("signup")] [ApiVersion(2)] @@ -43,21 +47,21 @@ public async Task SignUpV2( var turnstileError = await VerifyTurnstileAsync(turnstileService, body.TurnstileResponse, cancellationToken); if (turnstileError is not null) return turnstileError; - // Created with an automation token, the account is linked to it and the use audited in the same transaction. - var creationAction = await _accountService.CreateAccountWithActivationFlowAsync( - body.Email, body.Username, body.Password, cancellationToken); - return creationAction switch + var signup = await _accountService.SignUpAsync(body.Email, body.Username, body.Password, cancellationToken); + return signup switch { - User newUser => CompleteSignup(newUser), + // Mail is disabled, so the account exists already. + User _ => Ok(), + PendingSignup pending => CompleteSignup(pending), AccountWithEmailOrUsernameExists => Problem(SignupError.UsernameOrEmailExists) }; - IActionResult CompleteSignup(User newUser) + IActionResult CompleteSignup(PendingSignup pending) { - // Lets this browser ask for the activation email again without typing the address. - if (newUser.ActivatedAt is null && GetCurrentCookieDomain() is { } cookieDomain) + // Lets this browser enter the code mailed to the address, and ask for it again. + if (GetCurrentCookieDomain() is { } cookieDomain) { - ActivationResendCookie.Set(HttpContext, newUser.Id, cookieDomain); + ActivationResendCookie.Set(HttpContext, pending.Id, cookieDomain); } return Ok(); diff --git a/API/Controller/Admin/GetUser.cs b/API/Controller/Admin/GetUser.cs index 67d5a2e29..f79932881 100644 --- a/API/Controller/Admin/GetUser.cs +++ b/API/Controller/Admin/GetUser.cs @@ -46,11 +46,6 @@ public sealed class AdminUserView_PasswordReset public required DateTimeOffset CreatedAt { get; init; } public required DateTimeOffset? UsedAt { get; init; } } - public sealed class AdminUserView_UserActivationRequest - { - public required int EmailSendAttempts { get; init; } - public required DateTimeOffset CreatedAt { get; init; } - } public sealed class AdminUserView_UserDeactivation { public required AdminUserView_UserRef DeactivatedBy { get; init; } @@ -88,7 +83,6 @@ public sealed class AdminUserView public required Guid? CreatedByAutomationTokenId { get; init; } - public required AdminUserView_UserActivationRequest? ActivationRequest { get; init; } public required AdminUserView_UserDeactivation? Deactivation { get; init; } @@ -149,13 +143,6 @@ public sealed class AdminUserView UsedAt = reset.UsedAt, } ).ToArray(), - ActivationRequest = u.UserActivationRequest == null - ? null - : new AdminUserView_UserActivationRequest - { - EmailSendAttempts = u.UserActivationRequest.EmailSendAttempts, - CreatedAt = u.UserActivationRequest.CreatedAt, - }, Deactivation = u.UserDeactivation == null ? null : new @@ -207,7 +194,6 @@ public sealed class AdminUserView Hubs = user.Hubs, ApiTokens = user.ApiTokens, PasswordResets = user.PasswordResets, - ActivationRequest = user.ActivationRequest, Deactivation = user.Deactivation is null ? null : new AdminUserView_UserDeactivation diff --git a/API/Controller/OAuth/Authorize.cs b/API/Controller/OAuth/Authorize.cs index c9cd7d5d7..28d4a13de 100644 --- a/API/Controller/OAuth/Authorize.cs +++ b/API/Controller/OAuth/Authorize.cs @@ -17,14 +17,13 @@ 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, [FromQuery(Name = "activationToken"), StringLength(128)] string? activationToken = null) + public async Task OAuthAuthorize([FromRoute] string provider, [FromQuery(Name="flow"), Required] OAuthFlow flow) { if (!await _schemeProvider.IsSupportedOAuthScheme(provider)) return Problem(OAuthError.UnsupportedProvider); @@ -41,6 +40,6 @@ public async Task OAuthAuthorize([FromRoute] string provider, [Fr return Problem(OAuthError.UnsupportedFlow); } - return OAuthUtil.StartOAuth(provider, flow, activationToken); + return OAuthUtil.StartOAuth(provider, flow); } } diff --git a/API/Controller/OAuth/HandOff.cs b/API/Controller/OAuth/HandOff.cs index 09cd3d63d..4856d7c03 100644 --- a/API/Controller/OAuth/HandOff.cs +++ b/API/Controller/OAuth/HandOff.cs @@ -5,6 +5,7 @@ using OpenShock.API.OAuth; using OpenShock.API.Services.OAuthConnection; using OpenShock.Common.ApiVersioning; +using OpenShock.Common.Authentication; using OpenShock.Common.Extensions; using OpenShock.Common.Options; using OpenShock.Common.Utils; @@ -79,48 +80,41 @@ await _accountService.IsEmailRegisteredAsync(externalEmail, cancellationToken)) return RedirectFrontendError("emailAlreadyRegistered"); } + // The identity started a signup that was never completed. The caller just proved they hold + // the identity, so this browser holds the signup from now on and can enter its code. A new + // code is mailed as well (rate limited inside the service). The flow cookie is kept: the + // signup form lets someone who mistyped their email start over with the right one instead + // of waiting for a mail that never arrives (see OAuthSignupFinalize). + var pending = await _accountService.GetPendingSignupByOAuthIdentityAsync(provider, auth.ExternalAccountId, cancellationToken); + if (pending is not null && GetCurrentCookieDomain() is { } pendingCookieDomain) + { + ActivationResendCookie.Set(HttpContext, pending.Id, pendingCookieDomain); + + try + { + await _accountService.ResendActivationCodeAsync(pending.Id, cancellationToken); + } + catch (Exception ex) when (ex is not OperationCanceledException) + { + // Best effort: the redirect below still tells the user what is going on. + _logger.LogError(ex, "Failed to resend activation code on OAuth login"); + } + + return RedirectFrontendPath($"/oauth/{Uri.EscapeDataString(provider)}/create?pending=1"); + } + // No connection -> continue to CREATE flow on frontend return RedirectFrontendPath($"/oauth/{Uri.EscapeDataString(provider)}/create"); } - // Session auth rejects (and deletes) sessions of unactivated or deactivated users, so creating one - // here would bounce the user silently back to the login page. Surface the reason instead. + // Session auth rejects (and deletes) sessions of deactivated users, so creating one here would + // bounce the user silently back to the login page. Surface the reason instead. if (connection.User.UserDeactivation is not null) { await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); return RedirectFrontendError("accountDeactivated"); } - // 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; - if (!isActivated && OAuthUtil.TryGetActivationToken(auth.Properties, out var activationToken)) - { - isActivated = await _accountService.TryActivateAccountAsync(connection.UserId, activationToken, cancellationToken); - } - - if (!isActivated) - { - // 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.ResendActivationEmailForOAuthAsync(connection.UserId, cancellationToken); - } - catch (Exception ex) when (ex is not OperationCanceledException) - { - // Best effort: the redirect below still tells the user what is going on. - _logger.LogError(ex, "Failed to resend activation email on OAuth login"); - } - - // 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 var domain = GetCurrentCookieDomain(); if (string.IsNullOrEmpty(domain)) diff --git a/API/Controller/OAuth/SignupFinalize.cs b/API/Controller/OAuth/SignupFinalize.cs index 767e44955..54622ead1 100644 --- a/API/Controller/OAuth/SignupFinalize.cs +++ b/API/Controller/OAuth/SignupFinalize.cs @@ -24,7 +24,10 @@ public sealed partial class OAuthController /// /// /// Authenticates via the temporary OAuth flow cookie (set during the provider callback). - /// Sets the regular session cookie on success. No access/refresh tokens are returned. + /// When the provider verified the email, the account is created and the regular session cookie set. + /// Otherwise an activation code is mailed and the response has isVerified false: the account is + /// created once that code is entered in this browser, see POST /1/account/activate. + /// No access/refresh tokens are returned. /// /// Provider key (e.g. discord). /// Request body containing optional Email and Username overrides. @@ -90,90 +93,43 @@ public async Task OAuthSignupFinalize( var isVerifiedString = auth.Principal.FindFirst(OAuthConstants.ClaimEmailVerified)?.Value; var isEmailTrusted = StringUtils.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) + // Do not allow creation if this external is already linked anywhere. + if (await connectionService.ConnectionExistsAsync(provider, auth.ExternalAccountId, cancellationToken)) { - 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. - // It is only removed if that succeeds, so a taken username leaves the signup to retry with. - replacePendingUserId = existing.UserId; - } - else - { - var restarted = await _accountService.RestartPendingSignupAsync(existing.UserId, email, username, cancellationToken); - User pendingUser; - switch (restarted.Value) - { - case User restartedUser: - pendingUser = restartedUser; - break; - case AccountWithEmailOrUsernameExists: - // Keep the flow cookie so the frontend can retry with other details. - return Problem(SignupError.UsernameOrEmailExists); - case TooManyActivationResends: - // Nothing was changed and the link already mailed still works. Other details would - // be refused the same way until the window rolls over, so the flow ends here. - await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); - return Problem(AccountError.AccountActivationResendTooMany); - default: - // No longer a pending signup: it was activated, deactivated or cleaned up since the - // lookup above. Nothing is wrong with the details, so do not ask for different - // ones: signing in with the provider again takes the path that fits what it is now. - await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); - return Problem(OAuthError.FlowNotFound); - } - - ActivationResendCookie.Set(HttpContext, pendingUser.Id, domain); - await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); - - return Ok(LoginV2OkResponse.FromUser(pendingUser)); - } + await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); + return Problem(OAuthError.ExternalAlreadyLinked); } - var created = await _accountService.CreateOAuthOnlyAccountAsync( + // Replaces whatever signup this identity left unfinished, most likely because the email was + // mistyped and the code never arrived. + var signup = await _accountService.SignUpWithOAuthAsync( email, username, provider, auth.ExternalAccountId, auth.ExternalAccountDisplayName ?? auth.ExternalAccountName, isEmailTrusted, - replacePendingUserId, cancellationToken ); - if (created is not User newUser) + switch (signup.Value) { - // Username or email already exists — conflict. - // Do NOT clear the flow cookie so the frontend can retry with a different username. - return Problem(SignupError.UsernameOrEmailExists); - } - - // Authenticate the client if its activated (create session and set session cookie) - if (newUser.ActivatedAt is not null) - { - await CreateSession(newUser.Id, domain); - } - else - { - // Lets this browser ask for the activation email again without typing the address. - ActivationResendCookie.Set(HttpContext, newUser.Id, domain); - } + case User newUser: + // The provider vouches for the address, so the account exists: sign in. + await CreateSession(newUser.Id, domain); + await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); + return Ok(LoginV2OkResponse.FromUser(newUser)); - // Clear the temporary OAuth flow cookie. - await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); + case PendingSignup pending: + // Lets this browser enter the code mailed to the address, and ask for it again. + ActivationResendCookie.Set(HttpContext, pending.Id, domain); + await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); + return Ok(LoginV2OkResponse.FromPendingSignup(pending)); - return Ok(LoginV2OkResponse.FromUser(newUser)); + default: + // Username or email already exists: conflict. + // Do NOT clear the flow cookie so the frontend can retry with a different username. + return Problem(SignupError.UsernameOrEmailExists); + } } } diff --git a/API/Models/Response/LoginV2OkResponse.cs b/API/Models/Response/LoginV2OkResponse.cs index 09c6a4dda..9c867e3d9 100644 --- a/API/Models/Response/LoginV2OkResponse.cs +++ b/API/Models/Response/LoginV2OkResponse.cs @@ -1,5 +1,6 @@ using OpenShock.Common.Extensions; using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Utils; namespace OpenShock.API.Models.Response; @@ -21,4 +22,18 @@ public sealed class LoginV2OkResponse ProfileImage = argUser.GetImageUrl(), AccountRoles = argUser.Roles }; + + /// + /// A signup whose address still has to be verified. There is no account yet; is + /// the id the account gets once the mailed code is entered. + /// + public static LoginV2OkResponse FromPendingSignup(PendingSignup pending) => new() + { + AccountId = pending.Id, + AccountName = pending.Username, + AccountEmail = pending.Email, + IsVerified = false, + ProfileImage = GravatarUtils.GetUserImageUrl(pending.Email), + AccountRoles = [] + }; } diff --git a/API/OAuth/OAuthConstants.cs b/API/OAuth/OAuthConstants.cs index b1a6e3605..f07fc8438 100644 --- a/API/OAuth/OAuthConstants.cs +++ b/API/OAuth/OAuthConstants.cs @@ -11,7 +11,6 @@ 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/OAuthUtil.cs b/API/OAuth/OAuthUtil.cs index c8ade66fa..196a7a18d 100644 --- a/API/OAuth/OAuthUtil.cs +++ b/API/OAuth/OAuthUtil.cs @@ -1,19 +1,11 @@ -using System.Diagnostics.CodeAnalysis; -using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Mvc; namespace OpenShock.API.OAuth; 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. 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) + public static ChallengeResult StartOAuth(string provider, OAuthFlow flow) { var properties = new AuthenticationProperties { @@ -22,11 +14,6 @@ public static ChallengeResult StartOAuth(string provider, OAuthFlow flow, string SetOAuthFlow(properties, flow); - if (flow == OAuthFlow.LoginOrCreate) - { - SetActivationToken(properties, activationToken); - } - return new ChallengeResult(provider, properties); } @@ -36,21 +23,4 @@ public static bool TryGetOAuthFlow(AuthenticationProperties properties, out OAut 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); } diff --git a/API/Program.cs b/API/Program.cs index 1afa88147..fb2c40ce8 100644 --- a/API/Program.cs +++ b/API/Program.cs @@ -29,7 +29,7 @@ builder.RegisterGeoOptions(); builder.RegisterAccountOptions(); // The API never sends mail, but it must know whether anything ever will: with mail disabled there is -// no activation link, so accounts are activated on creation instead of waiting for one. +// no activation code, so accounts are created on signup instead of waiting for one. builder.RegisterMailOptions(); builder.Services @@ -71,7 +71,7 @@ options.ClientSecret = googleOptions.ClientSecret; // The default Google claim actions don't map email_verified (OIDC userinfo v3). Without it every - // Google signup is treated as an untrusted email and the account is left unactivated. + // Google signup is treated as an untrusted email and has to be completed with a mailed code. options.ClaimActions.MapJsonKey(OAuthConstants.ClaimEmailVerified, "email_verified"); options.Validate(); diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index 50fd39fa3..6c5cf570a 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -1,4 +1,6 @@ using System.Net.Mail; +using System.Security.Cryptography; +using System.Text; using Microsoft.EntityFrameworkCore; using Npgsql; using OpenShock.Common.Constants; @@ -37,7 +39,7 @@ public sealed class AccountService : IAccountService /// /// /// The automation token this request carries, if any; an account it creates is linked to it. - /// Decides whether an activation link can ever reach the user. + /// Decides whether an activation code can ever reach the user. /// public AccountService(OpenShockContext db, IRedisPubService redisPubService, ISessionService sessionService, IAuditService auditService, IAutomationTokenService automationTokens, MailOptions mailOptions, ILogger logger) { @@ -76,26 +78,28 @@ private async Task NotifyEmailOutboxAsync() } } - /// Most activation emails one account, and one address, is sent per . + /// Most activation emails one signup, and one address, is sent per . private const int MaxActivationEmailsPerWindow = 5; + /// Most pending signups a sign-in looks at when no account matches what was typed. + private const int MaxPendingSignupsCheckedOnLogin = 5; + /// Name of the transaction lock that serializes queueing activation mail for one address. /// Lowercased address. public static string ActivationEmailLockName(string email) => "activation-email:" + email; /// /// 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. + /// per window, whichever signups they were for. A cap per signup alone does not protect an inbox: + /// anyone can start any number of signups for an address, and each starts counting from zero. + /// Counted on the outbox, which is never pruned, so it holds across instances and deleted signups. /// /// /// Must be called inside the transaction that queues the mail. The count is only good until someone /// else queues mail for the address, so the address is locked from here to the end of that transaction: - /// without it, requests for different accounts could all read the same count and all queue. + /// without it, concurrent requests could all read the same count and all queue. /// A request that finds the address locked is turned away as if the cap were reached, instead of - /// waiting: another activation mail to that inbox is being queued this very moment, and waiting would - /// mean holding this lock and row locks in an order other requests take the other way around. + /// waiting: another activation mail to that inbox is being queued this very moment. /// /// Lowercased address. /// @@ -112,17 +116,6 @@ private async Task IsActivationEmailCapReachedAsync(string email, Cancella return sent >= MaxActivationEmailsPerWindow; } - /// The activation emails queued for one account within . - private IQueryable RecentActivationEmails(Guid userId) - { - var coalesceKey = EmailOutboxCoalesceKeys.AccountActivation(userId); - var windowStart = DateTime.UtcNow - Duration.ActivationResendWindow; - return _db.EmailOutbox.Where(m => m.CoalesceKey == coalesceKey && m.CreatedAt >= windowStart); - } - - private Task CountRecentActivationEmailsAsync(Guid userId, CancellationToken cancellationToken) - => RecentActivationEmails(userId).CountAsync(cancellationToken); - private Task IsUserNameBlacklisted(string username, CancellationToken cancellationToken) => _db.UserNameBlacklists.Matching(username).AnyAsync(cancellationToken); @@ -133,554 +126,377 @@ private async Task IsEmailProviderBlacklisted(string email, CancellationTo return await _db.EmailProviderBlacklists.AnyAsync(e => e.Domain == domain, cancellationToken); } - private async Task CreateAccount(string email, string username, string password, bool verifyOnCreation, Guid? createdByAutomationTokenId, CancellationToken cancellationToken) - { - email = email.ToLowerInvariant(); - - 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)) - return new AccountWithEmailOrUsernameExists(); - - var user = new User - { - Name = username, - Email = email, - PasswordHash = HashingUtils.HashPassword(password), - CreatedByAutomationTokenId = createdByAutomationTokenId - }; - _db.Users.Add(user); - - await _db.SaveChangesAsync(); + private Task IsEmailOrUsernameTakenAsync(string email, string username, CancellationToken cancellationToken) + => _db.Users.AnyAsync(u => u.Email == email || u.Name == username, cancellationToken); - // Use date created by the database to keep timing consistent - if (verifyOnCreation) - { - await _db.Users - .Where(u => u.Id == user.Id) - .ExecuteUpdateAsync(spc => spc.SetProperty(u => u.ActivatedAt, u => u.CreatedAt)); - } + /// Name of the transaction lock that serializes signups asking for one username. + private static string SignupUsernameLockName(string username) => "signup-username:" + username.ToLowerInvariant(); - return user; + /// + /// Whether a pending signup started within has + /// . Such a name is kept from other signups and from accounts changing their + /// name, so whoever is entering their code does not lose the name while doing so. An older signup holds + /// nothing: the name is open again, and the first signup to be completed with it gets it. + /// + private Task IsUsernameReservedAsync(string username, CancellationToken cancellationToken) + { + var reservedSince = DateTime.UtcNow - Duration.PendingSignupUsernameReservation; + return _db.PendingSignups.AnyAsync(p => p.Username == username && p.CreatedAt >= reservedSince, cancellationToken); } - /// - public async Task CreateAccountWithActivationFlowAsync(string email, string username, string password, CancellationToken cancellationToken = default) + /// + /// for a signup that is about to take the name itself. Must be + /// called inside the transaction that creates the signup or account: the name is locked from here to + /// the end of it, so two signups asking for one free name at the same moment cannot both get it. One + /// that finds the name locked is turned away as if it were reserved, which it is about to be. + /// + private async Task IsUsernameReservedForSignupAsync(string username, CancellationToken cancellationToken) { - // With mail disabled the activation email is never delivered, so an activation flow would leave - // the account permanently unusable. Activate on creation instead. - var mailEnabled = _mailOptions.IsEnabled; - - // An account an automation token creates must never exist without the audit entry for that use, so the - // account, its activation request and the audit entry commit together. - await using var transaction = await _db.Database.BeginTransactionAsync(); - - // Created with an automation token, the account is linked to it on insert, which makes it an automated account. - var accountCreate = await CreateAccount(email, username, password, !mailEnabled, _automationTokens.Current?.Id, cancellationToken); - if (accountCreate.Value is not User user) return accountCreate; - - if (mailEnabled) - { - // The real activation token is minted by the outbox delivery job at send time; here we record the - // request (with a seeded hash) and durably enqueue the email. - user.UserActivationRequest = new UserActivationRequest - { - UserId = user.Id, - TokenHash = SeedTokenHash() - }; - - _db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(user.Id, user.Email, username)); - - await _db.SaveChangesAsync(); - } - - await _automationTokens.RecordSignupAsync(user.Id); - - await transaction.CommitAsync(); - - if (mailEnabled) await NotifyEmailOutboxAsync(); + if (!await _db.Database.TryLockForTransactionAsync(SignupUsernameLockName(username), cancellationToken)) + return true; - return user; + return await IsUsernameReservedAsync(username, cancellationToken); } - public Task IsEmailRegisteredAsync(string email, CancellationToken cancellationToken = default) + /// Pending signups that can still be completed. + private IQueryable LivePendingSignups() { - return _db.Users.AnyAsync(u => u.Email == email && u.ActivatedAt != null, cancellationToken); + var createdSince = DateTime.UtcNow - Duration.PendingSignupLifetime; + return _db.PendingSignups.Where(p => p.CreatedAt >= createdSince); } /// - /// 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. + /// Adds a pending signup and the mail carrying its code to the context. The caller saves and commits + /// them together, and has checked in that transaction. /// - /// Lowercased address. - /// - /// The caller proved the address is theirs (an OAuth provider verified it, or they opened a link mailed - /// to it). Otherwise the pending account is left alone for - /// after it was created or last mailed: that gives its creator time to receive and open the link before - /// someone who merely knows the address can take the signup away, 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) + private PendingSignup AddPendingSignup(string email, string username, string? passwordHash, string? oauthProvider, string? oauthExternalId, string? oauthDisplayName) { - var pending = await _db.Users - .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 (!claimantOwnsEmail) + var pending = new PendingSignup { - // 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 holdStart = DateTime.UtcNow - Duration.PendingSignupHoldTime; - if (pending.CreatedAt > holdStart) return; - - var coalesceKey = EmailOutboxCoalesceKeys.AccountActivation(pending.Id); - if (await _db.EmailOutbox.AnyAsync(m => m.CoalesceKey == coalesceKey && m.CreatedAt >= holdStart, cancellationToken)) return; - } + Id = Guid.CreateVersion7(), + Email = email, + Username = username, + PasswordHash = passwordHash, + OAuthProviderKey = oauthProvider, + OAuthExternalId = oauthExternalId, + OAuthDisplayName = oauthDisplayName?.Truncate(ApiHardLimits.OAuthDisplayNameMaxLength), + // Replaced by the delivery job when it mails the code; nothing is accepted before that. + CodeHash = SeedTokenHash(), + CreatedByAutomationTokenId = _automationTokens.Current?.Id, + CreatedAt = DateTime.UtcNow + }; - // 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); - } + _db.PendingSignups.Add(pending); + _db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(pending.Id, email, username)); - /// - /// 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. - /// - /// - /// When given, the account is only deleted while this is still its address. - /// - /// False when nothing was deleted. - private async Task DeletePendingAccountAsync(Guid userId, string? heldEmail, CancellationToken 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; + return pending; } /// - public async Task> RestartPendingSignupAsync(Guid userId, string email, string username, CancellationToken cancellationToken = default) + public async Task SignUpAsync(string email, string username, string password, CancellationToken cancellationToken = default) { 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); - - // Releasing the address locks the pending account that holds it as well. Both rows are taken here, - // in id order: two signups each moving onto the other's address would otherwise lock them in - // opposite order and deadlock. - var holderId = await _db.Users - .Where(u => u.Email == email && u.ActivatedAt == null && u.Id != userId) - .Select(u => (Guid?)u.Id) - .FirstOrDefaultAsync(cancellationToken); - Guid[] lockIds = holderId is null ? [userId] : [userId, holderId.Value]; - await _db.Database.ExecuteSqlAsync($"SELECT 1 FROM users WHERE id = ANY({lockIds}) ORDER BY id 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) 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) - { - if (await IsUserNameBlacklisted(username, cancellationToken) || await IsEmailProviderBlacklisted(email, cancellationToken)) - return new AccountWithEmailOrUsernameExists(); - - if (emailChanged) - { - // Moving the signup to another address kills the link already mailed, so the new address - // has to get one. Checked before anything changes: past the account's cap no mail would be - // queued below, leaving an account that reports success and has no working link at all. - if (await CountRecentActivationEmailsAsync(userId, cancellationToken) >= MaxActivationEmailsPerWindow) - return new TooManyActivationResends(); + if (await IsUserNameBlacklisted(username, cancellationToken) || await IsEmailProviderBlacklisted(email, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); - // Moving the signup to another address mails that address. - if (await IsActivationEmailCapReachedAsync(email, cancellationToken)) - return new AccountWithEmailOrUsernameExists(); - } + if (await IsEmailOrUsernameTakenAsync(email, username, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); - await ReleaseEmailFromPendingAccountAsync(email, claimantOwnsEmail: false, exceptUserId: userId, cancellationToken); + var passwordHash = HashingUtils.HashPassword(password); - if (await _db.Users.AnyAsync(u => u.Id != userId && (u.Email == email || u.Name == username), cancellationToken)) - return new AccountWithEmailOrUsernameExists(); + await using var transaction = await _db.Database.BeginTransactionAsync(cancellationToken); - user.Email = email; - user.Name = username; + if (await IsUsernameReservedForSignupAsync(username, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); - // 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) + // With mail disabled no code can reach the user, so the address cannot be verified by any means: + // create the account right away rather than a signup that can never be completed. + if (!_mailOptions.IsEnabled) + { + var now = DateTime.UtcNow; + var user = new User { - if (user.UserActivationRequest is not null) - { - user.UserActivationRequest.TokenHash = SeedTokenHash(); - } - else - { - // The delivery job skips an activation mail that has no request to mint a token on. - user.UserActivationRequest = new UserActivationRequest - { - UserId = user.Id, - TokenHash = SeedTokenHash(), - CreatedAt = DateTime.UtcNow - }; - } - - // 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(); - - _db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(user.Id, user.Email, user.Name)); - } + Name = username, + Email = email, + PasswordHash = passwordHash, + CreatedAt = now, + ActivatedAt = now, + CreatedByAutomationTokenId = _automationTokens.Current?.Id + }; + _db.Users.Add(user); 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(); + await _db.SaveChangesAsync(cancellationToken); } - catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: "23505" }) + catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: PostgresErrorCodes.UniqueViolation }) { return new AccountWithEmailOrUsernameExists(); } + + // An account an automation token creates must never exist without the audit entry for that + // use, so the two commit together. + await _automationTokens.RecordSignupAsync(user.Id); + + await transaction.CommitAsync(cancellationToken); + + return user; } + // Past the cap the signup is turned away like a taken address: it would mail the inbox again. + if (await IsActivationEmailCapReachedAsync(email, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); + + var pending = AddPendingSignup(email, username, passwordHash, oauthProvider: null, oauthExternalId: null, oauthDisplayName: null); + + await _db.SaveChangesAsync(cancellationToken); await transaction.CommitAsync(cancellationToken); - if (emailChanged) - { - // The replacement mail is part of the same transaction as the address and token change. - await NotifyEmailOutboxAsync(); - } - else - { - // For unchanged details a throttled result just means no new mail went out: the link already - // mailed still works, and the resend button gets a new one later. - await ResendActivationEmailCoreAsync(userId, ignoreCooldown: false, onlyIfEmailIs: null, reserveCorrectionCapacity: false, cancellationToken); - } + await NotifyEmailOutboxAsync(); - return user; + return pending; + } + + public Task IsEmailRegisteredAsync(string email, CancellationToken cancellationToken = default) + { + return _db.Users.AnyAsync(u => u.Email == email, cancellationToken); } - public async Task CreateOAuthOnlyAccountAsync( + /// + public async Task SignUpWithOAuthAsync( string email, string username, string provider, 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; - - // Reuse your existing guards if (await IsUserNameBlacklisted(username, cancellationToken) || await IsEmailProviderBlacklisted(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); + // With mail disabled no code can reach the user, so an address the provider did not verify cannot + // be verified by any means; create the account right away rather than a dead signup. + var createAccountNow = isEmailTrusted || !_mailOptions.IsEnabled; + + await using var transaction = await _db.Database.BeginTransactionAsync(cancellationToken); try { - // An unverified address gets an activation email. Checked before anything is removed to make room. - if (!isEmailTrusted && await IsActivationEmailCapReachedAsync(email, cancellationToken)) + // Fast uniqueness check (optimistic; race handled by unique constraints below) + if (await IsEmailOrUsernameTakenAsync(email, username, cancellationToken)) return new AccountWithEmailOrUsernameExists(); - if (replacePendingUserId is not null) + // Starting over replaces whatever signup this identity left unfinished (typically one with a + // mistyped address). Part of this transaction, so a refusal below leaves it as it was. + await _db.PendingSignups + .Where(p => p.OAuthProviderKey == provider && p.OAuthExternalId == providerAccountId) + .ExecuteDeleteAsync(cancellationToken); + + // Checked after the identity's own signup is out of the way, so starting over keeps its name. + if (await IsUsernameReservedForSignupAsync(username, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); + + if (!createAccountNow) { - await DeletePendingAccountAsync(replacePendingUserId.Value, heldEmail: null, cancellationToken); + if (await IsActivationEmailCapReachedAsync(email, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); - // 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(); - } + var pending = AddPendingSignup(email, username, passwordHash: null, provider, providerAccountId, providerAccountName); - // 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); + await _db.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(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 NotifyEmailOutboxAsync(); - var creationTime = DateTime.UtcNow; - + return pending; + } + + var now = DateTime.UtcNow; var user = new User { + Id = Guid.CreateVersion7(), Name = username, Email = email, PasswordHash = null, - CreatedAt = creationTime, - ActivatedAt = isEmailTrusted ? creationTime : null + CreatedAt = now, + ActivatedAt = now }; - _db.Users.Add(user); - await _db.SaveChangesAsync(); - - // If email isn't trusted, create an activation request and durably enqueue the activation - // email. The token itself is minted by the outbox delivery job at send time. - if (!isEmailTrusted) - { - user.UserActivationRequest = new UserActivationRequest - { - UserId = user.Id, - TokenHash = SeedTokenHash(), - CreatedAt = creationTime - }; - - _db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(user.Id, email, username)); - await _db.SaveChangesAsync(); - } - - // Link external identity _db.UserOAuthConnections.Add(new UserOAuthConnection { UserId = user.Id, ProviderKey = provider, ExternalId = providerAccountId, DisplayName = providerAccountName?.Truncate(ApiHardLimits.OAuthDisplayNameMaxLength), - CreatedAt = creationTime, + CreatedAt = now, }); - await _db.SaveChangesAsync(); - - await tx.CommitAsync(); - - // Notify the outbox delivery job only after a successful commit. - if (!isEmailTrusted) - { - await NotifyEmailOutboxAsync(); - } + await _db.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(cancellationToken); return user; } - catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: "23505" }) + catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: PostgresErrorCodes.UniqueViolation }) { - await tx.RollbackAsync(); return new AccountWithEmailOrUsernameExists(); } } + /// + public Task GetPendingSignupByOAuthIdentityAsync(string provider, string providerAccountId, CancellationToken cancellationToken = default) + { + provider = provider.ToLowerInvariant(); + + return LivePendingSignups() + .AsNoTracking() + .FirstOrDefaultAsync(p => p.OAuthProviderKey == provider && p.OAuthExternalId == providerAccountId, cancellationToken); + } /// - public async Task> ActivateAccountAsync(string activationToken, Guid? signupBrowserUserId, string? password, CancellationToken cancellationToken = default) + public async Task ActivatePendingSignupAsync(Guid pendingSignupId, string code, CancellationToken cancellationToken = default) { - var hash = HashingUtils.HashToken(activationToken); + await using var transaction = await _db.Database.BeginTransactionAsync(cancellationToken); - 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)) + // Everything below runs with the signup's row locked: attempts are counted one at a time, and the + // delivery job, which replaces the code when it mails a new one, cannot do so halfway through. + await _db.Database.ExecuteSqlAsync($"SELECT 1 FROM pending_signups WHERE id = {pendingSignupId} FOR UPDATE", cancellationToken); + + var pending = await LivePendingSignups().FirstOrDefaultAsync(p => p.Id == pendingSignupId, cancellationToken); + if (pending is null) return new NotFound(); + + // No code mailed yet, the mailed one too old, or guessed at too often: a new one has to be requested. + if (pending.CodeSentAt is null + || pending.CodeSentAt < DateTime.UtcNow - Duration.ActivationCodeLifetime + || pending.FailedAttempts >= AuthConstants.ActivationCodeMaxAttempts) { - credentialProven = HashingUtils.VerifyPassword(password, user.PasswordHash!).Verified; - passwordInvalid = !credentialProven; + return new ActivationCodeExpired(); } - if (!credentialProven) + var codeMatches = ActivationCode.IsWellFormed(code) && CryptographicOperations.FixedTimeEquals( + Encoding.ASCII.GetBytes(ActivationCode.Hash(pending.Id, code)), + Encoding.ASCII.GetBytes(pending.CodeHash)); + if (!codeMatches) { - var providers = await _db.UserOAuthConnections - .Where(c => c.UserId == user.Id) - .Select(c => c.ProviderKey) - .ToListAsync(cancellationToken); + pending.FailedAttempts++; + await _db.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(cancellationToken); - return new ActivationCredentialRequired(hasPassword, providers, passwordInvalid); + return new ActivationCodeInvalid(AuthConstants.ActivationCodeMaxAttempts - pending.FailedAttempts); } - var activated = await ConsumeActivationTokenAsync(user.Id, hash, cancellationToken); - if (!activated) return new NotFound(); - - return new Success(); - } - - /// - /// 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); - - // 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 canActivate = await _db.Users - .AnyAsync(u => u.Id == userId && u.ActivatedAt == null && u.UserDeactivation == null, cancellationToken); - if (!canActivate) return false; - - var consumed = await _db.UserActivationRequests - .Where(r => r.UserId == userId && r.TokenHash == tokenHash) - .ExecuteDeleteAsync(cancellationToken); - if (consumed == 0) return false; + // A pending signup reserves nothing, so someone else may have taken the address or the username + // since. The signup is left as it is: nothing about it can be completed any more, and it expires. + if (await IsEmailOrUsernameTakenAsync(pending.Email, pending.Username, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); var now = DateTime.UtcNow; - await _db.Users - .Where(u => u.Id == userId && u.ActivatedAt == null) - .ExecuteUpdateAsync(s => s.SetProperty(u => u.ActivatedAt, now), cancellationToken); + var user = new User + { + Id = pending.Id, + Name = pending.Username, + Email = pending.Email, + PasswordHash = pending.PasswordHash, + CreatedAt = now, + ActivatedAt = now, + CreatedByAutomationTokenId = pending.CreatedByAutomationTokenId + }; + _db.Users.Add(user); - await transaction.CommitAsync(cancellationToken); + if (pending.OAuthProviderKey is not null && pending.OAuthExternalId is not null) + { + _db.UserOAuthConnections.Add(new UserOAuthConnection + { + UserId = user.Id, + ProviderKey = pending.OAuthProviderKey, + ExternalId = pending.OAuthExternalId, + DisplayName = pending.OAuthDisplayName, + CreatedAt = now + }); + } - return true; - } + _db.PendingSignups.Remove(pending); - /// - public async Task TryActivateAccountAsync(Guid userId, string activationToken, CancellationToken cancellationToken = default) - { - var hash = HashingUtils.HashToken(activationToken); + try + { + await _db.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: PostgresErrorCodes.UniqueViolation }) + { + // Lost a race for the address, the username or the OAuth identity. + return new AccountWithEmailOrUsernameExists(); + } - 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; + // The address is taken now, so every other signup waiting on it can no longer be completed. One + // that is being completed this very moment has its row locked and is waiting on the account just + // inserted: it is skipped, since waiting for it in turn would deadlock, and it expires on its own. + var email = pending.Email; + await _db.Database.ExecuteSqlAsync($""" + DELETE FROM pending_signups + WHERE id IN (SELECT id FROM pending_signups WHERE email = {email} FOR UPDATE SKIP LOCKED) + """, cancellationToken); + + // An account an automation token creates must never exist without the audit entry for that use, + // so the two commit together. The token is the one the signup was started with, which this + // request need not carry. + if (pending.CreatedByAutomationTokenId is { } automationTokenId) + { + var automationTokenName = await _db.AutomationTokens + .Where(t => t.Id == automationTokenId) + .Select(t => t.Name) + .FirstAsync(cancellationToken); - return await ConsumeActivationTokenAsync(userId, hash, cancellationToken); - } + await _auditService.LogAsync( + user.Id, + action: AuditAction.AutomationTokenUsed, + actorId: user.Id, + metadata: new AutomationTokenUsedMetadata(automationTokenId, automationTokenName, nameof(AutomationTokenFlow.Signup))); + } - /// - public async Task> ResendActivationEmailAsync(string usernameOrEmail, CancellationToken cancellationToken = default) - { - var userId = await _db.Users - .Where(u => u.Email == usernameOrEmail || u.Name == usernameOrEmail) - .Select(u => (Guid?)u.Id) - .FirstOrDefaultAsync(cancellationToken); - if (userId is null) return new NotFound(); + await transaction.CommitAsync(cancellationToken); - return await ResendActivationEmailAsync(userId.Value, cancellationToken); + return user; } /// - public Task> ResendActivationEmailAsync(Guid userId, CancellationToken cancellationToken = default) - => ResendActivationEmailCoreAsync(userId, ignoreCooldown: false, onlyIfEmailIs: null, reserveCorrectionCapacity: false, cancellationToken); - - /// - public Task> ResendActivationEmailForOAuthAsync(Guid userId, CancellationToken cancellationToken = default) - => ResendActivationEmailCoreAsync(userId, ignoreCooldown: false, onlyIfEmailIs: null, reserveCorrectionCapacity: true, cancellationToken); - - /// - /// - /// When given, nothing is queued unless this is still the account's address. - /// - /// Stop one short of the account's cap, so a resend nobody asked for cannot use up the send that - /// correcting the signup's address needs. - /// - /// - private async Task> ResendActivationEmailCoreAsync(Guid userId, bool ignoreCooldown, string? onlyIfEmailIs, bool reserveCorrectionCapacity, CancellationToken cancellationToken) + public async Task> ResendActivationCodeAsync(Guid pendingSignupId, CancellationToken cancellationToken = default) { - // Without mail no link can be delivered (and such accounts are activated on creation anyway). + // Without mail no code can be delivered (and no signup is ever left pending anyway). if (!_mailOptions.IsEnabled) return new NotFound(); - // Serialize resends per user: lock the user row for the whole check-then-enqueue, so concurrent + // Serialize resends per signup: lock its row for the whole check-then-enqueue, so concurrent // requests can't both pass the limit below. Released on commit/rollback. - await using var tx = await _db.Database.BeginTransactionAsync(); - await _db.Database.ExecuteSqlAsync($"SELECT 1 FROM users WHERE id = {userId} FOR UPDATE", cancellationToken); - - var user = await _db.Users - .Include(u => u.UserActivationRequest) - .Include(u => u.UserDeactivation) - .FirstOrDefaultAsync(u => u.Id == userId, cancellationToken); - if (user is null) return new NotFound(); + await using var transaction = await _db.Database.BeginTransactionAsync(cancellationToken); + await _db.Database.ExecuteSqlAsync($"SELECT 1 FROM pending_signups WHERE id = {pendingSignupId} FOR UPDATE", cancellationToken); - // 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(); + var pending = await LivePendingSignups() + .AsNoTracking() + .FirstOrDefaultAsync(p => p.Id == pendingSignupId, cancellationToken); + if (pending is null) return new NotFound(); // 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. - var recent = await RecentActivationEmails(userId) + var coalesceKey = EmailOutboxCoalesceKeys.AccountActivation(pendingSignupId); + var windowStart = DateTime.UtcNow - Duration.ActivationResendWindow; + var recent = await _db.EmailOutbox + .Where(m => m.CoalesceKey == coalesceKey && m.CreatedAt >= windowStart) .Select(m => m.CreatedAt) .ToListAsync(cancellationToken); - var maxRecent = reserveCorrectionCapacity ? MaxActivationEmailsPerWindow - 1 : MaxActivationEmailsPerWindow; - if (recent.Count >= maxRecent || (!ignoreCooldown && recent.Any(createdAt => createdAt >= DateTime.UtcNow - Duration.ActivationResendCooldown))) + if (recent.Count >= MaxActivationEmailsPerWindow || recent.Any(createdAt => createdAt >= DateTime.UtcNow - Duration.ActivationResendCooldown)) return new TooManyActivationResends(); - if (await IsActivationEmailCapReachedAsync(user.Email, cancellationToken)) + if (await IsActivationEmailCapReachedAsync(pending.Email, cancellationToken)) return new TooManyActivationResends(); - user.UserActivationRequest ??= new UserActivationRequest - { - UserId = user.Id, - TokenHash = SeedTokenHash(), - CreatedAt = DateTime.UtcNow - }; - - _db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(user.Id, user.Email, user.Name)); - await _db.SaveChangesAsync(); - await tx.CommitAsync(); + _db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(pending.Id, pending.Email, pending.Username)); + await _db.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(cancellationToken); // Notify the outbox delivery job only after a successful commit. await NotifyEmailOutboxAsync(); @@ -688,6 +504,40 @@ private async Task + /// The pending signup that and were + /// signed up with, if there is one. Whoever knows the password a signup carries is whoever started it, + /// which is what holding the signup means (see ). + /// + /// + /// Any number of signups can wait on one address, each with a password of its own, so the newest few + /// are all tried. Does the work of at least one password check either way, like a sign-in to an + /// account that does not exist. + /// + private async Task FindPendingSignupByCredentialsAsync(string usernameOrEmail, string password, CancellationToken cancellationToken) + { + var candidates = await LivePendingSignups() + .AsNoTracking() + .Where(p => p.PasswordHash != null && (p.Email == usernameOrEmail || p.Username == usernameOrEmail)) + .OrderByDescending(p => p.CreatedAt) + .Select(p => new { p.Id, p.PasswordHash }) + .Take(MaxPendingSignupsCheckedOnLogin) + .ToListAsync(cancellationToken); + + if (candidates.Count == 0) + { + await HashingUtils.VerifyPasswordFake(); + return null; + } + + foreach (var candidate in candidates) + { + if (HashingUtils.VerifyPassword(password, candidate.PasswordHash!).Verified) return candidate.Id; + } + + return null; + } + /// public async Task> DeactivateAccountAsync(Guid executingUserId, Guid userId, bool deleteLater, string? reason = null, CancellationToken cancellationToken = default) { @@ -845,7 +695,7 @@ await _auditService.LogAsync( } /// - public async Task> GetAccountByCredentialsAsync(string usernameOrEmail, string password, CancellationToken cancellationToken) + public async Task> GetAccountByCredentialsAsync(string usernameOrEmail, string password, CancellationToken cancellationToken) { var user = await _db.Users .AsNoTracking() @@ -853,7 +703,10 @@ public async Task x.Email == usernameOrEmail || x.Name == usernameOrEmail, cancellationToken); if (user is null) { - await HashingUtils.VerifyPasswordFake(); + // No account, but maybe a signup that was never completed. + var pendingSignupId = await FindPendingSignupByCredentialsAsync(usernameOrEmail, password, cancellationToken); + if (pendingSignupId is not null) return new PendingSignupCredentials(pendingSignupId.Value); + return new NotFound(); } @@ -913,8 +766,6 @@ public async Task= 3) return new TooManyPasswordResets(); @@ -959,20 +810,9 @@ public async Task> await using var transaction = await _db.Database.BeginTransactionAsync(); - // Whether this reset is what activates the account decides below if its OAuth links are dropped. - // Activating does not rotate the security stamp, so the stamp check in the update cannot tell that - // the account was activated since the read above: lock the row, as activation does, and look now. - await _db.Database.ExecuteSqlAsync($"SELECT 1 FROM users WHERE id = {reset.Reset.UserId} FOR UPDATE", cancellationToken); - var wasActivated = await _db.Users - .Where(u => u.Id == reset.Reset.UserId) - .Select(u => u.ActivatedAt != null) - .FirstOrDefaultAsync(cancellationToken); - // Race-safe consume + apply: only updates if SecurityStamp still matches the snapshot. // If a sibling reset (or a separate password/email change) completed since the read above, // the stamp has rotated and the predicate matches zero rows. - // The reset link was delivered to the account's email, so completing it also verifies that email: - // an unactivated account is activated here (an already activated one keeps its original timestamp). var newPasswordHash = HashingUtils.HashPassword(newPassword); var newStamp = Guid.CreateVersion7(); var now = DateTime.UtcNow; @@ -980,36 +820,15 @@ public async Task> .Where(u => u.Id == reset.Reset.UserId && u.SecurityStamp == reset.Reset.SecurityStampAtCreate) .ExecuteUpdateAsync(s => s .SetProperty(u => u.PasswordHash, newPasswordHash) - .SetProperty(u => u.SecurityStamp, newStamp) - .SetProperty(u => u.ActivatedAt, u => u.ActivatedAt ?? now)); + .SetProperty(u => u.SecurityStamp, newStamp)); if (userRows == 0) return new NotFound(); - // Any pending activation request is moot now; dropping it also makes the outbox skip a queued activation email. - await _db.UserActivationRequests - .Where(r => r.UserId == reset.Reset.UserId) - .ExecuteDeleteAsync(); - 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 (!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(); - } - } + // OAuth links are kept, like API tokens: an account only exists once its address was verified by + // whoever holds its credential, so every link on it was added by its owner. // Unauthenticated email-token flow proving control of the account, so the actor is the account itself. await _auditService.LogAsync( @@ -1018,17 +837,6 @@ 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" - ); - } - // 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. @@ -1065,8 +873,7 @@ await _auditService.LogAsync( public async Task> CheckEmailAvailability(string email, CancellationToken cancellationToken = default) { - // A never activated account is only a pending signup and does not reserve its address. - var isTaken = await _db.Users.AnyAsync(x => x.Email == email && x.ActivatedAt != null, cancellationToken: cancellationToken); + var isTaken = await _db.Users.AnyAsync(x => x.Email == email, cancellationToken: cancellationToken); if (isTaken) return new EmailTaken(); return new Success(); @@ -1086,6 +893,9 @@ public async Task> CheckUsernameAv var isTaken = await _db.Users.AnyAsync(x => x.Name == username, cancellationToken: cancellationToken); if (isTaken) return new UsernameTaken(); + // A signup that is being completed right now has the name for the time being. + if (await IsUsernameReservedAsync(username, cancellationToken)) return new UsernameTaken(); + return new Success(); } @@ -1164,10 +974,6 @@ public async Task> await using var transaction = await _db.Database.BeginTransactionAsync(); - // An administrator decided whose address this is, so a pending signup parked on it goes. Part of - // this transaction: it only stays removed if the change is committed. - await ReleaseEmailFromPendingAccountAsync(email, claimantOwnsEmail: true, exceptUserId: userId, cancellationToken); - user.Email = email; // Outstanding reset and email-change rows carry the stamp they were created under, so rotating // it invalidates them here. Without this a pending email-change verification could later @@ -1248,10 +1054,8 @@ public async Task x.Email == lowerCaseEmail && x.ActivatedAt != null, cancellationToken)) + if (await _db.Users.AnyAsync(x => x.Email == lowerCaseEmail, cancellationToken)) return new EmailAlreadyInUse(); // The verification token is minted lazily by the outbox delivery job at send time, so no usable @@ -1326,11 +1130,6 @@ public async Task> TryVe var newStamp = Guid.CreateVersion7(); try { - // The caller opened the link mailed to the new address while signed in, which proves it is - // theirs: a pending signup someone parked on it goes. Rolled back with the transaction on every - // return below that does not commit. - await ReleaseEmailFromPendingAccountAsync(change.NewEmail, claimantOwnsEmail: true, exceptUserId: change.UserId, cancellationToken); - var userRows = await _db.Users .Where(u => u.Id == change.UserId && u.SecurityStamp == change.SecurityStampAtCreate) .ExecuteUpdateAsync(s => s diff --git a/API/Services/Account/IAccountService.cs b/API/Services/Account/IAccountService.cs index deb2b9a8e..54ee176d2 100644 --- a/API/Services/Account/IAccountService.cs +++ b/API/Services/Account/IAccountService.cs @@ -10,104 +10,74 @@ namespace OpenShock.API.Services.Account; public interface IAccountService { /// - /// When a user uses the signup form, this also initiates an account activation flow + /// Starts a signup with a password. No account exists until the address is verified: this records a + /// and mails its activation code, see . + /// With mail disabled no code could ever arrive, so the account is created right away instead. /// /// /// /// /// - /// - public Task CreateAccountWithActivationFlowAsync(string email, string username, string password, CancellationToken cancellationToken = default); + /// + /// The (or, with mail disabled, the ). + /// when an account has the address or the username, a + /// signup started within the last hour has the username, either is blacklisted, or the address was + /// mailed too many activation codes already. + /// + Task SignUpAsync(string email, string username, string password, CancellationToken cancellationToken = default); /// - /// Creates an OAuth-only (passwordless) account and links the external identity in a single transaction. - /// The new user is activated immediately for a trusted provider address (or when mail is disabled). - /// With mail enabled and an unverified provider address, the user remains pending and an activation - /// email is queued; SignupFinalize does not create a session until that flow is completed. Returns a - /// conflict-style result if the username/email is taken or the external identity is already linked. + /// Starts a signup with an OAuth identity, replacing any signup that identity left unfinished. When the + /// provider verified the address (or mail is disabled) the account is created right away with the + /// identity linked. Otherwise this records a and mails its activation code, + /// like . Only call this for a caller who just signed in with the identity. /// - /// Email to set on the user. + /// Email to sign up with. /// Desired unique username. /// e.g. "discord" /// 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. - /// + /// The provider verified that belongs to the identity. /// - /// Success with the created user, or AccountWithEmailOrUsernameExists when taken/blocked. - Task CreateOAuthOnlyAccountAsync(string email, string username, string provider, string providerAccountId, string? providerAccountName, bool isEmailTrusted, Guid? replacePendingUserId = null, CancellationToken cancellationToken = default); + /// See . + Task SignUpWithOAuthAsync(string email, string username, string provider, string providerAccountId, string? providerAccountName, bool isEmailTrusted, CancellationToken cancellationToken = default); - /// - /// 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); + /// The signup an OAuth identity started and has not completed, if there is one. + Task GetPendingSignupByOAuthIdentityAsync(string provider, string providerAccountId, 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: an address - /// change past that cap is refused with and changes nothing, - /// because the link already mailed would stop working with no new one to replace it. + /// Returns true if the given email belongs to an account. A pending signup is not one and does not + /// reserve its address. /// - /// - /// when the account is not a pending signup (any more): activated, deactivated or deleted. - /// - Task> RestartPendingSignupAsync(Guid userId, string email, string username, CancellationToken cancellationToken = default); + Task IsEmailRegisteredAsync(string email, 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 cookie () - /// or the account's password. An account created through OAuth is activated by signing in with the - /// linked provider instead, see . + /// Completes a pending signup with the code mailed to its address, creating the account. Only call this + /// for a caller who holds the signup (): + /// the code shows the address is read by whoever enters it, the cookie that they are the one who chose + /// the credential the account gets. Neither is worth anything alone. /// - /// Token from the activation email. - /// User id from , if the request carries a valid one. - /// Password supplied alongside the token, if any. + /// + /// Code from the activation email. /// /// - /// when the token is valid but that proof is missing or wrong; - /// the account stays unactivated and the token stays usable. + /// The created . for a wrong code, which counts + /// against the few attempts a mailed code gets. when the code is + /// too old or used up and a new one has to be requested. + /// when the address or the username was taken while the signup was pending. + /// when there is no such signup (any more). /// - Task> ActivateAccountAsync(string activationToken, Guid? signupBrowserUserId, string? password, CancellationToken cancellationToken = default); + Task ActivatePendingSignupAsync(Guid pendingSignupId, string code, 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). + /// Mails a pending signup a new activation code, which replaces the previous one. Only call this for a + /// caller who holds the signup or its credential. Rate limited per signup: one email per 10 minutes, + /// at most 5 per 24 hours (the signup email included), and capped per address across signups. /// - /// 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. - /// Only call this after the caller has proven ownership (e.g. a correct password), as the result reveals - /// account state. - /// - /// + /// /// - Task> ResendActivationEmailAsync(string usernameOrEmail, CancellationToken cancellationToken = default); - - /// - /// Re-enqueues the activation email for an unactivated, non-deactivated account. Only call this after the - /// caller has proven ownership (correct password or OAuth identity). Rate limited per user: one email per - /// 10 minutes, at most 5 per 24 hours (the signup email included). - /// - /// - /// - /// NotFound when there is nothing to resend (unknown user, already activated, or mail disabled). - Task> ResendActivationEmailAsync(Guid userId, CancellationToken cancellationToken = default); - - /// - /// Re-enqueues an activation email after an OAuth login while preserving one account-level send slot - /// for a pending-signup email correction. - /// - Task> ResendActivationEmailForOAuthAsync(Guid userId, CancellationToken cancellationToken = default); + /// NotFound when there is nothing to resend (no such signup, or mail disabled). + Task> ResendActivationCodeAsync(Guid pendingSignupId, CancellationToken cancellationToken = default); public Task> DeactivateAccountAsync(Guid executingUserId, Guid userId, bool deleteLater = true, string? reason = null, CancellationToken cancellationToken = default); @@ -122,7 +92,7 @@ public interface IAccountService /// /// /// - public Task> GetAccountByCredentialsAsync(string usernameOrEmail, string password, CancellationToken cancellationToken = default); + public Task> GetAccountByCredentialsAsync(string usernameOrEmail, string password, CancellationToken cancellationToken = default); /// /// Check if a password reset request exists and the secret is valid @@ -142,10 +112,8 @@ public interface IAccountService public Task> CreatePasswordResetFlowAsync(string email, CancellationToken cancellationToken = default); /// - /// 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. 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). + /// Completes a password reset process, sets a new password. All sessions are signed out; OAuth links + /// and API tokens are kept. /// /// /// @@ -228,14 +196,22 @@ public interface IAccountService Task> TryVerifyEmailAsync(string token, Guid userId, CancellationToken cancellationToken = default); } -public union AccountCreationResult(User, AccountWithEmailOrUsernameExists); +public union SignupResult(User, PendingSignup, AccountWithEmailOrUsernameExists); -public sealed record VerifyEmailSuccess(Guid UserId, string OldEmail, string NewEmail); +public union ActivationResult(User, ActivationCodeInvalid, ActivationCodeExpired, AccountWithEmailOrUsernameExists, NotFound); + +/// How many more wrong codes are accepted before a new code has to be requested. +public sealed record ActivationCodeInvalid(int AttemptsRemaining); -/// 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 ActivationCodeExpired; + +/// +/// The credentials are not those of an account, but of a signup that was never completed. Whoever sent +/// them is whoever started it. +/// +public sealed record PendingSignupCredentials(Guid PendingSignupId); + +public sealed record VerifyEmailSuccess(Guid UserId, string OldEmail, string NewEmail); public sealed class AccountIsOAuthOnly; public sealed class AccountNotActivated; diff --git a/Common/Authentication/ActivationResendCookie.cs b/Common/Authentication/ActivationResendCookie.cs index a733076be..70be718b2 100644 --- a/Common/Authentication/ActivationResendCookie.cs +++ b/Common/Authentication/ActivationResendCookie.cs @@ -7,22 +7,21 @@ namespace OpenShock.Common.Authentication; /// -/// 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. +/// Cookie set while this browser has a signup waiting for its activation code. It tells the frontend that +/// there is one (so it can offer the code form and the "didn't get the email?" button) and lets the browser +/// ask for the code again 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, -/// 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. +/// The value is a time-limited data protection payload holding the pending signup's id (keys are persisted to +/// the database, so every API instance can read it); it cannot be forged or pointed at another signup. /// -/// 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. +/// Deliberately not HttpOnly: the frontend is a static SPA and reads the cookie's presence to decide what to +/// show. 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) codes to that signup's own inbox. /// /// -/// It is not proof of anything else. What marks this browser as the one that signed up, for activation, is +/// It is not proof of anything else. What lets a browser enter the code is /// , which is set and removed together with this one. /// /// @@ -30,15 +29,15 @@ public static class ActivationResendCookie { private const string ProtectorPurpose = "OpenShock.ActivationResendCookie"; - public static string CreateToken(IDataProtectionProvider provider, Guid userId) - => GetProtector(provider).Protect(userId.ToString(), Duration.ActivationResendWindow); + public static string CreateToken(IDataProtectionProvider provider, Guid signupId) + => GetProtector(provider).Protect(signupId.ToString(), Duration.ActivationResendWindow); - public static void Set(HttpContext context, Guid userId, string domain) + public static void Set(HttpContext context, Guid signupId, string domain) { var provider = context.RequestServices.GetRequiredService(); var frontendOptions = context.RequestServices.GetRequiredService(); - context.Response.Cookies.Append(AuthConstants.ActivationResendCookieName, CreateToken(provider, userId), new CookieOptions + context.Response.Cookies.Append(AuthConstants.ActivationResendCookieName, CreateToken(provider, signupId), new CookieOptions { Expires = DateTimeOffset.UtcNow.Add(Duration.ActivationResendWindow), Secure = context.Request.IsHttps || frontendOptions.CookieSecure, @@ -47,12 +46,12 @@ public static void Set(HttpContext context, Guid userId, string domain) Domain = domain }); - SignupBrowserCookie.Set(context, userId); + SignupBrowserCookie.Set(context, signupId); } - public static bool TryGetUserId(HttpContext context, [NotNullWhen(true)] out Guid? userId) + public static bool TryGetSignupId(HttpContext context, [NotNullWhen(true)] out Guid? signupId) { - userId = null; + signupId = null; if (!context.Request.Cookies.TryGetValue(AuthConstants.ActivationResendCookieName, out var token) || string.IsNullOrEmpty(token)) return false; @@ -60,7 +59,7 @@ public static bool TryGetUserId(HttpContext context, [NotNullWhen(true)] out Gui try { if (!Guid.TryParse(GetProtector(provider).Unprotect(token), out var id)) return false; - userId = id; + signupId = id; return true; } catch (CryptographicException) diff --git a/Common/Authentication/SignupBrowserCookie.cs b/Common/Authentication/SignupBrowserCookie.cs index bb568bc88..caa667b00 100644 --- a/Common/Authentication/SignupBrowserCookie.cs +++ b/Common/Authentication/SignupBrowserCookie.cs @@ -9,23 +9,25 @@ 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. +/// Marks a browser that holds a pending signup: the one that started it, or one that has since signed in +/// with the credential the signup carries. Only such a browser can enter the mailed activation code, so +/// the code is worth nothing to whoever merely receives the mail, and a signup started by someone else +/// cannot be completed by the person the mail went to. /// /// /// 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. +/// this one would let someone who signed up with another person's address have that person complete the +/// signup for them. 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. +/// different country it is ignored, and the signup has to be started (or signed in to) again. 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 @@ -39,16 +41,16 @@ public static string GetName(HttpContext context) => IsSecure(context) : AuthConstants.SignupBrowserCookieName; /// - /// + /// /// 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 string CreateToken(IDataProtectionProvider provider, Guid signupId, string? countryCode = null) + => GetProtector(provider).Protect($"{signupId}{PayloadSeparator}{countryCode}", Duration.ActivationResendWindow); - public static void Set(HttpContext context, Guid userId) + public static void Set(HttpContext context, Guid signupId) { var provider = context.RequestServices.GetRequiredService(); - context.Response.Cookies.Append(GetName(context), CreateToken(provider, userId, GetCountryCode(context)), new CookieOptions + context.Response.Cookies.Append(GetName(context), CreateToken(provider, signupId, GetCountryCode(context)), new CookieOptions { Expires = DateTimeOffset.UtcNow.Add(Duration.ActivationResendWindow), Secure = IsSecure(context), @@ -58,9 +60,9 @@ public static void Set(HttpContext context, Guid userId) }); } - public static bool TryGetUserId(HttpContext context, [NotNullWhen(true)] out Guid? userId) + public static bool TryGetSignupId(HttpContext context, [NotNullWhen(true)] out Guid? signupId) { - userId = null; + signupId = null; // Only the name that matches this deployment: over HTTPS an unprefixed cookie is exactly what a // sibling subdomain could have planted. @@ -83,7 +85,7 @@ public static bool TryGetUserId(HttpContext context, [NotNullWhen(true)] out Gui return false; } - userId = id; + signupId = id; return true; } catch (CryptographicException) diff --git a/Common/Constants/ApiHardLimits.cs b/Common/Constants/ApiHardLimits.cs index d3bd51a45..beb00dc0c 100644 --- a/Common/Constants/ApiHardLimits.cs +++ b/Common/Constants/ApiHardLimits.cs @@ -21,7 +21,6 @@ public static class ApiHardLimits public const int EmailOutboxCoalesceKeyMaxLength = 128; public const int UserEmailChangeSecretMaxLength = 128; - public const int UserActivationRequestSecretMaxLength = 128; public const int PasswordResetSecretMaxLength = 100; public const int AuditReasonMaxLength = 512; diff --git a/Common/Constants/AuthConstants.cs b/Common/Constants/AuthConstants.cs index 06c854e7d..f1f77a4fc 100644 --- a/Common/Constants/AuthConstants.cs +++ b/Common/Constants/AuthConstants.cs @@ -12,5 +12,11 @@ public static class AuthConstants public const string AutomationTokenHeaderName = "X-OpenShock-Automation-Token"; public const int GeneratedTokenLength = 32; + + /// Digits in the code mailed to activate a signup. + public const int ActivationCodeLength = 6; + + /// Wrong codes a signup may enter before the mailed code stops working and a new one must be requested. + public const int ActivationCodeMaxAttempts = 5; public const int ApiTokenLength = 64; } diff --git a/Common/Constants/Constants.cs b/Common/Constants/Constants.cs index f9b6209a6..3f1cbd43c 100644 --- a/Common/Constants/Constants.cs +++ b/Common/Constants/Constants.cs @@ -13,13 +13,23 @@ public static class Duration public static readonly TimeSpan ActivationResendWindow = TimeSpan.FromHours(24); /// - /// How long a never activated account keeps its address from a new signup that has not proven the - /// address is theirs, counted from its creation and from its last activation email. Long enough for a - /// delayed email to arrive and be opened, so someone who only knows the address cannot take a signup - /// away from the person completing it. + /// How long a mailed activation code is accepted. Long enough for a delayed email to arrive; a newer + /// mail replaces the code regardless. /// - public static readonly TimeSpan PendingSignupHoldTime = TimeSpan.FromHours(1); - public static readonly TimeSpan UnactivatedAccountRetentionTime = TimeSpan.FromDays(7); + public static readonly TimeSpan ActivationCodeLifetime = TimeSpan.FromHours(1); + + /// + /// How long a pending signup is kept. The same as , which is how + /// long the cookies that let a browser complete it live. + /// + public static readonly TimeSpan PendingSignupLifetime = ActivationResendWindow; + + /// + /// How long a pending signup keeps its username to itself. Long enough to receive and enter the code + /// without someone else signing up with the same name in the meantime; after that the name is open to + /// other signups again, and whichever of them is completed first gets it. + /// + public static readonly TimeSpan PendingSignupUsernameReservation = TimeSpan.FromHours(1); public static readonly TimeSpan NameChangeCooldown = TimeSpan.FromDays(7); diff --git a/Common/Errors/AccountError.cs b/Common/Errors/AccountError.cs index ac8bb2c09..7942930e6 100644 --- a/Common/Errors/AccountError.cs +++ b/Common/Errors/AccountError.cs @@ -26,20 +26,18 @@ public static class AccountError "Account.Username.RecentlyChanged", "You have recently changed your username. You can only change your username every 7 days", HttpStatusCode.Forbidden); public static OpenShockProblem AccountNotActivated => new OpenShockProblem("Account.AccountNotActivated", "Your account has not been activated", HttpStatusCode.Unauthorized); - public static OpenShockProblem AccountActivationResendUnavailable => new OpenShockProblem("Account.Activation.ResendUnavailable", "No activation email can be resent from this browser", HttpStatusCode.BadRequest); + public static OpenShockProblem AccountActivationResendUnavailable => new OpenShockProblem("Account.Activation.ResendUnavailable", "No activation code 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) + public static OpenShockProblem AccountActivationNotFound => new OpenShockProblem("Account.Activation.NotFound", "This browser has no signup waiting to be activated. Sign up again, or sign in with what you signed up with", HttpStatusCode.BadRequest); + public static OpenShockProblem AccountActivationCodeInvalid(int attemptsRemaining) => new OpenShockProblem( + "Account.Activation.CodeInvalid", "The activation code is not correct", HttpStatusCode.BadRequest) { Extensions = new Dictionary { - { "hasPassword", hasPassword }, - { "oauthProviders", oauthProviders }, - { "passwordInvalid", passwordInvalid } + { "attemptsRemaining", attemptsRemaining } } }; + public static OpenShockProblem AccountActivationCodeExpired => new OpenShockProblem("Account.Activation.CodeExpired", "The activation code has expired or was entered wrong too often. Request a new one", HttpStatusCode.BadRequest); 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); diff --git a/Common/Migrations/20261128213633_PendingSignups.Designer.cs b/Common/Migrations/20261128213633_PendingSignups.Designer.cs new file mode 100644 index 000000000..24a7c4c09 --- /dev/null +++ b/Common/Migrations/20261128213633_PendingSignups.Designer.cs @@ -0,0 +1,1927 @@ +// +using System; +using System.Collections.Generic; +using System.Net; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; +using OpenShock.Common.OpenShockDb; + +#nullable disable + +namespace OpenShock.Common.Migrations; + +[DbContext(typeof(MigrationOpenShockContext))] +[Migration("20261128213633_PendingSignups")] +partial class _20261128213633_PendingSignups +{ + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("Npgsql:CollationDefinition:public.ndcoll", "und-u-ks-level2,und-u-ks-level2,icu,False") + .HasAnnotation("ProductVersion", "11.0.0") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "audit_action", new[] { "login", "logout", "password_changed", "email_change_requested", "email_changed", "username_changed", "api_token_created", "api_token_deleted", "oauth_connected", "oauth_disconnected", "account_deactivated", "account_reactivated", "account_deleted", "automation_token_created", "automation_token_updated", "automation_token_rotated", "automation_token_deleted", "automation_token_used" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "automation_token_type", new[] { "turnstile", "rate_limit", "control_stats_read" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "configuration_value_type", new[] { "string", "bool", "int", "float", "json" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "control_limit_mode", new[] { "clamp", "lerp" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "control_type", new[] { "stop", "shock", "vibrate", "sound" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "email_status", new[] { "pending", "sending", "sent", "failed", "skipped" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "email_type", new[] { "account_activation", "password_reset", "email_verification", "email_change_notice" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "match_type_enum", new[] { "exact", "contains" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "ota_update_status", new[] { "started", "running", "finished", "error", "timeout" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "password_encryption_type", new[] { "bcrypt_enhanced", "pbkdf2" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "permission_type", new[] { "shockers.use", "shockers.edit", "shockers.pause", "devices.edit", "devices.auth", "usershares.edit", "usershares.pause", "publicshares.pause", "publicshares.edit" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "role_type", new[] { "support", "staff", "admin", "system" }); + NpgsqlModelBuilderExtensions.HasPostgresEnum(modelBuilder, "shocker_model_type", new[] { "cai_xianlin", "petrainer", "petrainer_998dr", "wellturn_t330" }); + NpgsqlModelBuilderExtensions.HasPostgresExtension(modelBuilder, "timescaledb"); + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer"); + + NpgsqlPropertyBuilderExtensions.UseIdentityByDefaultColumn(id); + + b.Property("FriendlyName") + .HasColumnType("text"); + + b.Property("Xml") + .HasColumnType("text"); + + b.HasKey("Id"); + + b.ToTable("DataProtectionKeys"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.AdminUsersView", b => + { + b.Property("ActivatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("activated_at"); + + b.Property("ApiTokenCount") + .HasColumnType("integer") + .HasColumnName("api_token_count"); + + b.Property("CreatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at"); + + b.Property("CreatedByAutomationTokenId") + .HasColumnType("uuid") + .HasColumnName("created_by_automation_token_id"); + + b.Property("DeactivatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("deactivated_at"); + + b.Property("DeactivatedByUserId") + .HasColumnType("uuid") + .HasColumnName("deactivated_by_user_id"); + + b.Property("DeviceCount") + .HasColumnType("integer") + .HasColumnName("device_count"); + + b.Property("Email") + .IsRequired() + .HasColumnType("character varying") + .HasColumnName("email"); + + b.Property("EmailChangeRequestCount") + .HasColumnType("integer") + .HasColumnName("email_change_request_count"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("Name") + .IsRequired() + .HasColumnType("character varying") + .HasColumnName("name"); + + b.Property("NameChangeRequestCount") + .HasColumnType("integer") + .HasColumnName("name_change_request_count"); + + b.Property("PasswordHashType") + .HasColumnType("character varying") + .HasColumnName("password_hash_type"); + + b.Property("PasswordResetCount") + .HasColumnType("integer") + .HasColumnName("password_reset_count"); + + b.Property("Roles") + .IsRequired() + .HasColumnType("role_type[]") + .HasColumnName("roles"); + + b.Property("ShockerControlLogCount") + .HasColumnType("integer") + .HasColumnName("shocker_control_log_count"); + + b.Property("ShockerCount") + .HasColumnType("integer") + .HasColumnName("shocker_count"); + + b.Property("ShockerPublicShareCount") + .HasColumnType("integer") + .HasColumnName("shocker_public_share_count"); + + b.Property("ShockerUserShareCount") + .HasColumnType("integer") + .HasColumnName("shocker_user_share_count"); + + b.ToTable((string)null); + + b.ToView("admin_users_view", (string)null); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ApiToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("CreatedByIp") + .IsRequired() + .HasColumnType("inet") + .HasColumnName("created_by_ip"); + + b.Property("LastUsed") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_used"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name"); + + b.Property>("Permissions") + .IsRequired() + .HasColumnType("permission_type[]") + .HasColumnName("permissions"); + + b.Property("ShockerControlDurationMax") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(65535) + .HasColumnName("shocker_control_duration_max"); + + b.Property("ShockerControlDurationMin") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(300) + .HasColumnName("shocker_control_duration_min"); + + b.Property("ShockerControlDurationMode") + .ValueGeneratedOnAdd() + .HasColumnType("control_limit_mode") + .HasDefaultValue(ControlLimitMode.Clamp) + .HasColumnName("shocker_control_duration_mode"); + + b.Property("ShockerControlIntensityMax") + .ValueGeneratedOnAdd() + .HasColumnType("smallint") + .HasDefaultValue((byte)100) + .HasColumnName("shocker_control_intensity_max"); + + b.Property("ShockerControlIntensityMin") + .ValueGeneratedOnAdd() + .HasColumnType("smallint") + .HasDefaultValue((byte)0) + .HasColumnName("shocker_control_intensity_min"); + + b.Property("ShockerControlIntensityMode") + .ValueGeneratedOnAdd() + .HasColumnType("control_limit_mode") + .HasDefaultValue(ControlLimitMode.Clamp) + .HasColumnName("shocker_control_intensity_mode"); + + b.Property("ShockerControlPaused") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("shocker_control_paused"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("token_hash") + .UseCollation("C"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.Property("ValidUntil") + .HasColumnType("timestamp with time zone") + .HasColumnName("valid_until"); + + b.HasKey("Id") + .HasName("api_tokens_pkey"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.HasIndex("UserId"); + + b.HasIndex("ValidUntil"); + + b.ToTable("api_tokens", t => + { + t.HasCheckConstraint("ck_api_tokens_shocker_control_duration", "shocker_control_duration_min >= 300 AND shocker_control_duration_max <= 65535 AND shocker_control_duration_min <= shocker_control_duration_max"); + + t.HasCheckConstraint("ck_api_tokens_shocker_control_intensity", "shocker_control_intensity_min >= 0 AND shocker_control_intensity_max <= 100 AND shocker_control_intensity_min <= shocker_control_intensity_max"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ApiTokenReport", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AffectedCount") + .HasColumnType("integer") + .HasColumnName("affected_count"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("IpAddress") + .IsRequired() + .HasColumnType("inet") + .HasColumnName("ip_address"); + + b.Property("IpCountry") + .HasMaxLength(4) + .HasColumnType("character varying(4)") + .HasColumnName("ip_country"); + + b.Property("SubmittedCount") + .HasColumnType("integer") + .HasColumnName("submitted_count"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("api_token_reports_pkey"); + + b.HasIndex("UserId"); + + b.ToTable("api_token_reports"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.AutomationToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AutoCleanupAfter") + .HasColumnType("interval") + .HasColumnName("auto_cleanup_after"); + + b.Property("AutoCleanupUsers") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("auto_cleanup_users"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("LastRotatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_rotated_at"); + + b.Property("LastUsedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("last_used_at"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("token_hash") + .UseCollation("C"); + + b.Property>("Types") + .IsRequired() + .HasColumnType("automation_token_type[]") + .HasColumnName("types"); + + b.Property("UseCount") + .ValueGeneratedOnAdd() + .HasColumnType("bigint") + .HasDefaultValue(0L) + .HasColumnName("use_count"); + + b.HasKey("Id") + .HasName("automation_tokens_pkey"); + + b.HasIndex("TokenHash") + .IsUnique(); + + b.ToTable("automation_tokens"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ConfigurationItem", b => + { + b.Property("Name") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name") + .UseCollation("C"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("Description") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("description"); + + b.Property("Type") + .HasColumnType("configuration_value_type") + .HasColumnName("type"); + + b.Property("UpdatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("updated_at"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(4096) + .HasColumnType("character varying(4096)") + .HasColumnName("value"); + + b.HasKey("Name") + .HasName("configuration_pkey"); + + b.ToTable("configuration"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ControlStat", b => + { + b.Property("Bucket") + .HasColumnType("timestamp with time zone") + .HasColumnName("bucket"); + + b.Property("ControllerUserId") + .HasColumnType("uuid") + .HasColumnName("controller_user_id"); + + b.Property("Count") + .HasColumnType("bigint") + .HasColumnName("count"); + + b.Property("DurationMs") + .HasColumnType("bigint") + .HasColumnName("duration_ms"); + + b.Property("IntensityMs") + .HasColumnType("bigint") + .HasColumnName("intensity_ms"); + + b.Property("Live") + .HasColumnType("boolean") + .HasColumnName("live"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.Property("OwnerUserId") + .HasColumnType("uuid") + .HasColumnName("owner_user_id"); + + b.Property("ShockerId") + .HasColumnType("uuid") + .HasColumnName("shocker_id"); + + b.Property("Type") + .HasColumnType("control_type") + .HasColumnName("type"); + + b.ToTable((string)null); + + b.ToView("control_stats", (string)null); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.Device", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name"); + + b.Property("OwnerId") + .HasColumnType("uuid") + .HasColumnName("owner_id"); + + b.Property("Token") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("character varying(256)") + .HasColumnName("token") + .UseCollation("C"); + + b.HasKey("Id") + .HasName("devices_pkey"); + + b.HasIndex("OwnerId"); + + b.HasIndex("Token") + .IsUnique(); + + b.ToTable("devices"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.DeviceOtaUpdate", b => + { + b.Property("DeviceId") + .HasColumnType("uuid") + .HasColumnName("device_id"); + + b.Property("UpdateId") + .HasColumnType("integer") + .HasColumnName("update_id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("Message") + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("message"); + + b.Property("Status") + .HasColumnType("ota_update_status") + .HasColumnName("status"); + + b.Property("Version") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("version"); + + b.HasKey("DeviceId", "UpdateId") + .HasName("device_ota_updates_pkey"); + + b.HasIndex(new[] { "CreatedAt" }, "device_ota_updates_created_at_idx"); + + b.ToTable("device_ota_updates"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.DiscordWebhook", b => + { + b.Property("Name") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("Id") + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("WebhookId") + .HasColumnType("bigint") + .HasColumnName("webhook_id"); + + b.Property("WebhookToken") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("webhook_token"); + + b.HasKey("Name") + .HasName("discord_webhooks_pkey"); + + b.ToTable("discord_webhooks"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.EmailOutboxMessage", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AttemptCount") + .IsConcurrencyToken() + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0) + .HasColumnName("attempt_count"); + + b.Property("CoalesceKey") + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("coalesce_key"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("FailedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("failed_at"); + + b.Property("LastError") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)") + .HasColumnName("last_error"); + + b.Property("NextAttemptAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("next_attempt_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property>("Payload") + .IsRequired() + .HasColumnType("jsonb") + .HasColumnName("payload"); + + b.Property("Recipient") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)") + .HasColumnName("recipient"); + + b.Property("RecipientName") + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("recipient_name"); + + b.Property("SentAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("sent_at"); + + b.Property("Status") + .HasColumnType("email_status") + .HasColumnName("status"); + + b.Property("Type") + .HasColumnType("email_type") + .HasColumnName("type"); + + b.HasKey("Id") + .HasName("email_outbox_pkey"); + + b.HasIndex("CoalesceKey") + .HasFilter("coalesce_key IS NOT NULL"); + + b.HasIndex("NextAttemptAt") + .HasFilter("status IN ('pending', 'sending')"); + + b.HasIndex("Recipient"); + + b.ToTable("email_outbox"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.EmailProviderBlacklist", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("Domain") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("domain") + .UseCollation("ndcoll"); + + b.HasKey("Id") + .HasName("email_provider_blacklist_pkey"); + + var index = b.HasIndex("Domain") + .IsUnique(); + + NpgsqlIndexBuilderExtensions.UseCollation(index, new[] { "ndcoll" }); + + b.ToTable("email_provider_blacklist"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PendingSignup", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CodeHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("code_hash") + .UseCollation("C"); + + b.Property("CodeSentAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("code_sent_at"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("CreatedByAutomationTokenId") + .HasColumnType("uuid") + .HasColumnName("created_by_automation_token_id"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)") + .HasColumnName("email") + .UseCollation("ndcoll"); + + b.Property("FailedAttempts") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0) + .HasColumnName("failed_attempts"); + + b.Property("OAuthDisplayName") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("oauth_display_name"); + + b.Property("OAuthExternalId") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("oauth_external_id"); + + b.Property("OAuthProviderKey") + .HasMaxLength(16) + .HasColumnType("character varying(16)") + .HasColumnName("oauth_provider_key") + .UseCollation("C"); + + b.Property("PasswordHash") + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("password_hash") + .UseCollation("C"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("username") + .UseCollation("ndcoll"); + + b.HasKey("Id") + .HasName("pending_signups_pkey"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("CreatedByAutomationTokenId"); + + var index = b.HasIndex("Email"); + + NpgsqlIndexBuilderExtensions.UseCollation(index, new[] { "ndcoll" }); + + var index0 = b.HasIndex("Username"); + + NpgsqlIndexBuilderExtensions.UseCollation(index0, new[] { "ndcoll" }); + + b.HasIndex("OAuthProviderKey", "OAuthExternalId") + .IsUnique() + .HasFilter("oauth_provider_key IS NOT NULL"); + + b.ToTable("pending_signups"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PublicShare", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("ExpiresAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("expires_at"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name"); + + b.Property("OwnerId") + .HasColumnType("uuid") + .HasColumnName("owner_id"); + + b.HasKey("Id") + .HasName("public_shares_pkey"); + + b.HasIndex("OwnerId"); + + b.ToTable("public_shares"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PublicShareShocker", b => + { + b.Property("PublicShareId") + .HasColumnType("uuid") + .HasColumnName("public_share_id"); + + b.Property("ShockerId") + .HasColumnType("uuid") + .HasColumnName("shocker_id"); + + b.Property("AllowLiveControl") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("allow_livecontrol"); + + b.Property("AllowShock") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_shock"); + + b.Property("AllowSound") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_sound"); + + b.Property("AllowVibrate") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_vibrate"); + + b.Property("Cooldown") + .HasColumnType("integer") + .HasColumnName("cooldown"); + + b.Property("IsPaused") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("is_paused"); + + b.Property("MaxDuration") + .HasColumnType("integer") + .HasColumnName("max_duration"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.HasKey("PublicShareId", "ShockerId") + .HasName("public_share_shockers_pkey"); + + b.HasIndex("ShockerId"); + + b.ToTable("public_share_shockers", t => + { + t.HasCheckConstraint("ck_public_share_shockers_cooldown", "cooldown >= 0"); + + t.HasCheckConstraint("ck_public_share_shockers_max_duration", "max_duration BETWEEN 300 AND 65535"); + + t.HasCheckConstraint("ck_public_share_shockers_max_intensity", "max_intensity BETWEEN 0 AND 100"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.Shocker", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("DeviceId") + .HasColumnType("uuid") + .HasColumnName("device_id"); + + b.Property("IsPaused") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("is_paused"); + + b.Property("Model") + .HasColumnType("shocker_model_type") + .HasColumnName("model"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("name"); + + b.Property("RfId") + .HasColumnType("integer") + .HasColumnName("rf_id"); + + b.HasKey("Id") + .HasName("shockers_pkey"); + + b.HasIndex("DeviceId"); + + b.ToTable("shockers", t => + { + t.HasCheckConstraint("ck_shockers_rf_id", "rf_id BETWEEN 0 AND 65535"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ShockerControlLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("ControlledByUserId") + .HasColumnType("uuid") + .HasColumnName("controlled_by_user_id"); + + b.Property("CustomName") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("custom_name"); + + b.Property("Duration") + .HasColumnType("bigint") + .HasColumnName("duration"); + + b.Property("InsertedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("inserted_at") + .HasDefaultValueSql("now()"); + + b.Property("Intensity") + .HasColumnType("smallint") + .HasColumnName("intensity"); + + b.Property("LiveControl") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("live_control"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.Property("OwnerUserId") + .HasColumnType("uuid") + .HasColumnName("owner_user_id"); + + b.Property("ShockerId") + .HasColumnType("uuid") + .HasColumnName("shocker_id"); + + b.Property("Type") + .HasColumnType("control_type") + .HasColumnName("type"); + + b.HasKey("Id", "CreatedAt") + .HasName("shocker_control_logs_pkey"); + + b.HasIndex("ControlledByUserId"); + + b.HasIndex("OwnerUserId", "CreatedAt"); + + b.HasIndex("ShockerId", "CreatedAt"); + + b.ToTable("shocker_control_logs"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ShockerShareCode", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("AllowLiveControl") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_livecontrol"); + + b.Property("AllowShock") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_shock"); + + b.Property("AllowSound") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_sound"); + + b.Property("AllowVibrate") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_vibrate"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("IsPaused") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("is_paused"); + + b.Property("MaxDuration") + .HasColumnType("integer") + .HasColumnName("max_duration"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.Property("ShockerId") + .HasColumnType("uuid") + .HasColumnName("shocker_id"); + + b.HasKey("Id") + .HasName("shocker_share_codes_pkey"); + + b.HasIndex("ShockerId"); + + b.ToTable("shocker_share_codes", t => + { + t.HasCheckConstraint("ck_shocker_share_codes_max_duration", "max_duration BETWEEN 300 AND 65535"); + + t.HasCheckConstraint("ck_shocker_share_codes_max_intensity", "max_intensity BETWEEN 0 AND 100"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.User", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("ActivatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("activated_at"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("CreatedByAutomationTokenId") + .HasColumnType("uuid") + .HasColumnName("created_by_automation_token_id"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)") + .HasColumnName("email") + .UseCollation("ndcoll"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("name") + .UseCollation("ndcoll"); + + b.Property("PasswordHash") + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("password_hash") + .UseCollation("C"); + + b.Property>("Roles") + .IsRequired() + .HasColumnType("role_type[]") + .HasColumnName("roles"); + + b.Property("SecurityStamp") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("security_stamp") + .HasDefaultValueSql("gen_random_uuid()"); + + b.HasKey("Id") + .HasName("users_pkey"); + + b.HasIndex("CreatedByAutomationTokenId"); + + var index = b.HasIndex("Email") + .IsUnique(); + + NpgsqlIndexBuilderExtensions.UseCollation(index, new[] { "ndcoll" }); + + var index0 = b.HasIndex("Name") + .IsUnique(); + + NpgsqlIndexBuilderExtensions.UseCollation(index0, new[] { "ndcoll" }); + + b.ToTable("users"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserAuditLog", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("Action") + .HasColumnType("audit_action") + .HasColumnName("action"); + + b.Property("ActorId") + .HasColumnType("uuid") + .HasColumnName("actor_id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("IpAddress") + .HasColumnType("inet") + .HasColumnName("ip_address"); + + b.Property("Metadata") + .HasColumnType("jsonb") + .HasColumnName("metadata"); + + b.Property("Reason") + .HasMaxLength(512) + .HasColumnType("character varying(512)") + .HasColumnName("reason"); + + b.Property("UserAgent") + .HasMaxLength(1024) + .HasColumnType("character varying(1024)") + .HasColumnName("user_agent"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("user_audit_logs_pkey"); + + b.HasIndex("ActorId"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("UserId"); + + b.ToTable("user_audit_logs"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserDeactivation", b => + { + b.Property("DeactivatedUserId") + .HasColumnType("uuid") + .HasColumnName("deactivated_user_id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("DeactivatedByUserId") + .HasColumnType("uuid") + .HasColumnName("deactivated_by_user_id"); + + b.Property("DeleteLater") + .HasColumnType("boolean") + .HasColumnName("delete_later"); + + b.Property("UserModerationId") + .HasColumnType("uuid") + .HasColumnName("user_moderation_id"); + + b.HasKey("DeactivatedUserId") + .HasName("user_deactivations_pkey"); + + b.HasIndex("DeactivatedByUserId"); + + b.ToTable("user_deactivations"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserEmailChange", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("NewEmail") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)") + .HasColumnName("email_new"); + + b.Property("OldEmail") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)") + .HasColumnName("email_old"); + + b.Property("SecurityStampAtCreate") + .HasColumnType("uuid") + .HasColumnName("security_stamp_at_create"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("character varying(128)") + .HasColumnName("token_hash") + .UseCollation("C"); + + b.Property("UsedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("used_at"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("user_email_changes_pkey"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("UsedAt"); + + b.HasIndex("UserId"); + + b.ToTable("user_email_changes"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserNameBlacklist", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("MatchType") + .HasColumnType("match_type_enum") + .HasColumnName("match_type"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("value") + .UseCollation("ndcoll"); + + b.HasKey("Id") + .HasName("user_name_blacklist_pkey"); + + var index = b.HasIndex("Value") + .IsUnique(); + + NpgsqlIndexBuilderExtensions.UseCollation(index, new[] { "ndcoll" }); + + b.ToTable("user_name_blacklist"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserNameChange", b => + { + var id = b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasColumnName("id"); + + NpgsqlPropertyBuilderExtensions.UseIdentityAlwaysColumn(id); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("OldName") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("old_name"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("user_name_changes_pkey"); + + b.HasIndex("UserId", "CreatedAt"); + + b.ToTable("user_name_changes"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserOAuthConnection", b => + { + b.Property("ProviderKey") + .HasMaxLength(16) + .HasColumnType("character varying(16)") + .HasColumnName("provider_key") + .UseCollation("C"); + + b.Property("ExternalId") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("external_id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("DisplayName") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("display_name"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("ProviderKey", "ExternalId") + .HasName("user_oauth_connections_pkey"); + + b.HasIndex("UserId"); + + b.ToTable("user_oauth_connections"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserPasswordReset", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("SecurityStampAtCreate") + .HasColumnType("uuid") + .HasColumnName("security_stamp_at_create"); + + b.Property("TokenHash") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("token_hash") + .UseCollation("C"); + + b.Property("UsedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("used_at"); + + b.Property("UserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("user_password_resets_pkey"); + + b.HasIndex("UserId"); + + b.ToTable("user_password_resets"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShare", b => + { + b.Property("SharedWithUserId") + .HasColumnType("uuid") + .HasColumnName("shared_with_user_id"); + + b.Property("ShockerId") + .HasColumnType("uuid") + .HasColumnName("shocker_id"); + + b.Property("AllowLiveControl") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_livecontrol"); + + b.Property("AllowShock") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_shock"); + + b.Property("AllowSound") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_sound"); + + b.Property("AllowVibrate") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_vibrate"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("IsPaused") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("is_paused"); + + b.Property("MaxDuration") + .HasColumnType("integer") + .HasColumnName("max_duration"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.HasKey("SharedWithUserId", "ShockerId") + .HasName("user_shares_pkey"); + + b.HasIndex("ShockerId"); + + b.ToTable("user_shares", t => + { + t.HasCheckConstraint("ck_user_shares_max_duration", "max_duration BETWEEN 300 AND 65535"); + + t.HasCheckConstraint("ck_user_shares_max_intensity", "max_intensity BETWEEN 0 AND 100"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShareInvite", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("OwnerId") + .HasColumnType("uuid") + .HasColumnName("owner_id"); + + b.Property("RecipientUserId") + .HasColumnType("uuid") + .HasColumnName("user_id"); + + b.HasKey("Id") + .HasName("user_share_invites_pkey"); + + b.HasIndex("OwnerId"); + + b.HasIndex("RecipientUserId"); + + b.ToTable("user_share_invites"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShareInviteShocker", b => + { + b.Property("InviteId") + .HasColumnType("uuid") + .HasColumnName("invite_id"); + + b.Property("ShockerId") + .HasColumnType("uuid") + .HasColumnName("shocker_id"); + + b.Property("AllowLiveControl") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_livecontrol"); + + b.Property("AllowShock") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_shock"); + + b.Property("AllowSound") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_sound"); + + b.Property("AllowVibrate") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(true) + .HasColumnName("allow_vibrate"); + + b.Property("IsPaused") + .ValueGeneratedOnAdd() + .HasColumnType("boolean") + .HasDefaultValue(false) + .HasColumnName("is_paused"); + + b.Property("MaxDuration") + .HasColumnType("integer") + .HasColumnName("max_duration"); + + b.Property("MaxIntensity") + .HasColumnType("smallint") + .HasColumnName("max_intensity"); + + b.HasKey("InviteId", "ShockerId") + .HasName("user_share_invite_shockers_pkey"); + + b.HasIndex("ShockerId"); + + b.ToTable("user_share_invite_shockers", t => + { + t.HasCheckConstraint("ck_user_share_invite_shockers_max_duration", "max_duration BETWEEN 300 AND 65535"); + + t.HasCheckConstraint("ck_user_share_invite_shockers_max_intensity", "max_intensity BETWEEN 0 AND 100"); + }); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ApiToken", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithMany("ApiTokens") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_api_tokens_user_id"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ApiTokenReport", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "ReportedByUser") + .WithMany("ReportedApiTokens") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_api_token_reports_reported_by_user_id"); + + b.Navigation("ReportedByUser"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.Device", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "Owner") + .WithMany("Devices") + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_devices_owner_id"); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.DeviceOtaUpdate", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.Device", "Device") + .WithMany("OtaUpdates") + .HasForeignKey("DeviceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_device_ota_updates_device_id"); + + b.Navigation("Device"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PendingSignup", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.AutomationToken", "CreatedByAutomationToken") + .WithMany() + .HasForeignKey("CreatedByAutomationTokenId") + .OnDelete(DeleteBehavior.Cascade) + .HasConstraintName("fk_pending_signups_created_by_automation_token_id"); + + b.Navigation("CreatedByAutomationToken"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PublicShare", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "Owner") + .WithMany("OwnedPublicShares") + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_public_shares_owner_id"); + + b.Navigation("Owner"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PublicShareShocker", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.PublicShare", "PublicShare") + .WithMany("ShockerMappings") + .HasForeignKey("PublicShareId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_public_share_shockers_public_share_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.Shocker", "Shocker") + .WithMany("PublicShareMappings") + .HasForeignKey("ShockerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_public_share_shockers_shocker_id"); + + b.Navigation("PublicShare"); + + b.Navigation("Shocker"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.Shocker", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.Device", "Device") + .WithMany("Shockers") + .HasForeignKey("DeviceId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_shockers_device_id"); + + b.Navigation("Device"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ShockerControlLog", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", null) + .WithMany() + .HasForeignKey("OwnerUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_shocker_control_logs_owner_user_id"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.ShockerShareCode", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.Shocker", "Shocker") + .WithMany("ShockerShareCodes") + .HasForeignKey("ShockerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_shocker_share_codes_shocker_id"); + + b.Navigation("Shocker"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.User", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.AutomationToken", "CreatedByAutomationToken") + .WithMany("CreatedUsers") + .HasForeignKey("CreatedByAutomationTokenId") + .OnDelete(DeleteBehavior.Restrict) + .HasConstraintName("fk_users_created_by_automation_token_id"); + + b.Navigation("CreatedByAutomationToken"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserAuditLog", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "Actor") + .WithMany("ActorAuditLogs") + .HasForeignKey("ActorId") + .OnDelete(DeleteBehavior.SetNull) + .HasConstraintName("fk_user_audit_logs_actor_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithMany("AuditLogs") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_audit_logs_user_id"); + + b.Navigation("Actor"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserDeactivation", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "DeactivatedByUser") + .WithMany() + .HasForeignKey("DeactivatedByUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_deactivations_deactivated_by_user_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.User", "DeactivatedUser") + .WithOne("UserDeactivation") + .HasForeignKey("OpenShock.Common.OpenShockDb.UserDeactivation", "DeactivatedUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_deactivations_deactivated_user_id"); + + b.Navigation("DeactivatedByUser"); + + b.Navigation("DeactivatedUser"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserEmailChange", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithMany("EmailChanges") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_email_changes_user_id"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserNameChange", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithMany("NameChanges") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_name_changes_user_id"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserOAuthConnection", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithMany("OAuthConnections") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_oauth_connections_user_id"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserPasswordReset", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "User") + .WithMany("PasswordResets") + .HasForeignKey("UserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_password_resets_user_id"); + + b.Navigation("User"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShare", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "SharedWithUser") + .WithMany("IncomingUserShares") + .HasForeignKey("SharedWithUserId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_shares_shared_with_user_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.Shocker", "Shocker") + .WithMany("UserShares") + .HasForeignKey("ShockerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_shares_shocker_id"); + + b.Navigation("SharedWithUser"); + + b.Navigation("Shocker"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShareInvite", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.User", "Owner") + .WithMany("OutgoingUserShareInvites") + .HasForeignKey("OwnerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_share_invites_owner_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.User", "RecipientUser") + .WithMany("IncomingUserShareInvites") + .HasForeignKey("RecipientUserId") + .OnDelete(DeleteBehavior.Cascade) + .HasConstraintName("fk_user_share_invites_recipient_user_id"); + + b.Navigation("Owner"); + + b.Navigation("RecipientUser"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShareInviteShocker", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.UserShareInvite", "Invite") + .WithMany("ShockerMappings") + .HasForeignKey("InviteId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_share_invite_shockers_invite_id"); + + b.HasOne("OpenShock.Common.OpenShockDb.Shocker", "Shocker") + .WithMany("UserShareInviteShockerMappings") + .HasForeignKey("ShockerId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired() + .HasConstraintName("fk_user_share_invite_shockers_shocker_id"); + + b.Navigation("Invite"); + + b.Navigation("Shocker"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.AutomationToken", b => + { + b.Navigation("CreatedUsers"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.Device", b => + { + b.Navigation("OtaUpdates"); + + b.Navigation("Shockers"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PublicShare", b => + { + b.Navigation("ShockerMappings"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.Shocker", b => + { + b.Navigation("PublicShareMappings"); + + b.Navigation("ShockerShareCodes"); + + b.Navigation("UserShareInviteShockerMappings"); + + b.Navigation("UserShares"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.User", b => + { + b.Navigation("ActorAuditLogs"); + + b.Navigation("ApiTokens"); + + b.Navigation("AuditLogs"); + + b.Navigation("Devices"); + + b.Navigation("EmailChanges"); + + b.Navigation("IncomingUserShareInvites"); + + b.Navigation("IncomingUserShares"); + + b.Navigation("NameChanges"); + + b.Navigation("OAuthConnections"); + + b.Navigation("OutgoingUserShareInvites"); + + b.Navigation("OwnedPublicShares"); + + b.Navigation("PasswordResets"); + + b.Navigation("ReportedApiTokens"); + + b.Navigation("UserDeactivation"); + }); + + modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserShareInvite", b => + { + b.Navigation("ShockerMappings"); + }); +#pragma warning restore 612, 618 + } +} diff --git a/Common/Migrations/20261128213633_PendingSignups.cs b/Common/Migrations/20261128213633_PendingSignups.cs new file mode 100644 index 000000000..6107605ae --- /dev/null +++ b/Common/Migrations/20261128213633_PendingSignups.cs @@ -0,0 +1,142 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace OpenShock.Common.Migrations; + +/// +public partial class _20261128213633_PendingSignups : Migration +{ + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "user_activation_requests"); + + migrationBuilder.CreateTable( + name: "pending_signups", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false), + email = table.Column(type: "character varying(320)", maxLength: 320, nullable: false, collation: "ndcoll"), + username = table.Column(type: "character varying(32)", maxLength: 32, nullable: false, collation: "ndcoll"), + password_hash = table.Column(type: "character varying(100)", maxLength: 100, nullable: true, collation: "C"), + oauth_provider_key = table.Column(type: "character varying(16)", maxLength: 16, nullable: true, collation: "C"), + oauth_external_id = table.Column(type: "character varying(255)", maxLength: 255, nullable: true), + oauth_display_name = table.Column(type: "character varying(64)", maxLength: 64, nullable: true), + code_hash = table.Column(type: "character varying(64)", maxLength: 64, nullable: false, collation: "C"), + code_sent_at = table.Column(type: "timestamp with time zone", nullable: true), + failed_attempts = table.Column(type: "integer", nullable: false, defaultValue: 0), + created_by_automation_token_id = table.Column(type: "uuid", nullable: true), + created_at = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP") + }, + constraints: table => + { + table.PrimaryKey("pending_signups_pkey", x => x.id); + table.ForeignKey( + name: "fk_pending_signups_created_by_automation_token_id", + column: x => x.created_by_automation_token_id, + principalTable: "automation_tokens", + principalColumn: "id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_pending_signups_created_at", + table: "pending_signups", + column: "created_at"); + + migrationBuilder.CreateIndex( + name: "IX_pending_signups_created_by_automation_token_id", + table: "pending_signups", + column: "created_by_automation_token_id"); + + migrationBuilder.CreateIndex( + name: "IX_pending_signups_email", + table: "pending_signups", + column: "email") + .Annotation("Relational:Collation", new[] { "ndcoll" }); + + migrationBuilder.CreateIndex( + name: "IX_pending_signups_oauth_provider_key_oauth_external_id", + table: "pending_signups", + columns: new[] { "oauth_provider_key", "oauth_external_id" }, + unique: true, + filter: "oauth_provider_key IS NOT NULL"); + + migrationBuilder.CreateIndex( + name: "IX_pending_signups_username", + table: "pending_signups", + column: "username") + .Annotation("Relational:Collation", new[] { "ndcoll" }); + + // An account that was never activated is what a pending signup is now: move each one over, so its + // creator can still complete it (by signing in with what they signed up with, which mails a code), + // and remove the account. created_at starts over, giving every one of them the full lifetime of a + // pending signup from the moment this runs; no code is accepted until one has been mailed. + // + // Left alone, for a person to look at: deactivated and privileged accounts, and any that own a hub + // or an API token. An unactivated account cannot sign in and should own nothing, so the latter + // should not exist, and are not something to delete unseen if they do. + migrationBuilder.Sql(""" + WITH unactivated AS ( + SELECT u.id, u.email, u.name, u.password_hash, u.created_by_automation_token_id + FROM users AS u + WHERE u.activated_at IS NULL + AND NOT (u.roles && ARRAY['staff', 'admin', 'system']::role_type[]) + AND NOT EXISTS (SELECT 1 FROM user_deactivations AS d WHERE d.deactivated_user_id = u.id) + AND NOT EXISTS (SELECT 1 FROM devices AS h WHERE h.owner_id = u.id) + AND NOT EXISTS (SELECT 1 FROM api_tokens AS t WHERE t.user_id = u.id) + ), moved AS ( + INSERT INTO pending_signups (id, email, username, password_hash, oauth_provider_key, oauth_external_id, oauth_display_name, code_hash, created_by_automation_token_id) + SELECT u.id, lower(u.email), u.name, NULLIF(u.password_hash, ''), c.provider_key, c.external_id, c.display_name, + encode(sha256(gen_random_uuid()::text::bytea), 'hex'), u.created_by_automation_token_id + FROM unactivated AS u + LEFT JOIN LATERAL ( + SELECT o.provider_key, o.external_id, o.display_name + FROM user_oauth_connections AS o + WHERE o.user_id = u.id + ORDER BY o.created_at + LIMIT 1 + ) AS c ON TRUE + WHERE NULLIF(u.password_hash, '') IS NOT NULL OR c.provider_key IS NOT NULL + ) + DELETE FROM users AS u USING unactivated AS p WHERE u.id = p.id; + """); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + // The accounts Up turned into pending signups are not brought back: whoever started one signs up again. + migrationBuilder.DropTable( + name: "pending_signups"); + + migrationBuilder.CreateTable( + name: "user_activation_requests", + columns: table => new + { + user_id = table.Column(type: "uuid", nullable: false), + created_at = table.Column(type: "timestamp with time zone", nullable: false, defaultValueSql: "CURRENT_TIMESTAMP"), + email_send_attempts = table.Column(type: "integer", nullable: false), + token_hash = table.Column(type: "character varying(128)", maxLength: 128, nullable: false, collation: "C") + }, + constraints: table => + { + table.PrimaryKey("user_activation_requests_pkey", x => x.user_id); + table.ForeignKey( + name: "fk_user_activation_requests_user_id", + column: x => x.user_id, + principalTable: "users", + principalColumn: "id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_user_activation_requests_token_hash", + table: "user_activation_requests", + column: "token_hash", + unique: true); + } +} diff --git a/Common/Migrations/OpenShockContextModelSnapshot.cs b/Common/Migrations/OpenShockContextModelSnapshot.cs index 939bdd8f6..6305824aa 100644 --- a/Common/Migrations/OpenShockContextModelSnapshot.cs +++ b/Common/Migrations/OpenShockContextModelSnapshot.cs @@ -18,7 +18,7 @@ partial class OpenShockContextModelSnapshot : ModelSnapshot // If you encounter a merge conflict in the line below, it means you need to // discard one of the migration branches and recreate its migrations on top of // the other branch. See https://aka.ms/efcore-docs-migrations-conflicts for more info. - public override string LastMigrationId => "20261126000339_PostgresNativeCleanup"; + public override string LastMigrationId => "20261128213633_PendingSignups"; protected override void BuildModel(ModelBuilder modelBuilder) { @@ -677,6 +677,98 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("email_provider_blacklist"); }); + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PendingSignup", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id"); + + b.Property("CodeHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("code_hash") + .UseCollation("C"); + + b.Property("CodeSentAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("code_sent_at"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("CURRENT_TIMESTAMP"); + + b.Property("CreatedByAutomationTokenId") + .HasColumnType("uuid") + .HasColumnName("created_by_automation_token_id"); + + b.Property("Email") + .IsRequired() + .HasMaxLength(320) + .HasColumnType("character varying(320)") + .HasColumnName("email") + .UseCollation("ndcoll"); + + b.Property("FailedAttempts") + .ValueGeneratedOnAdd() + .HasColumnType("integer") + .HasDefaultValue(0) + .HasColumnName("failed_attempts"); + + b.Property("OAuthDisplayName") + .HasMaxLength(64) + .HasColumnType("character varying(64)") + .HasColumnName("oauth_display_name"); + + b.Property("OAuthExternalId") + .HasMaxLength(255) + .HasColumnType("character varying(255)") + .HasColumnName("oauth_external_id"); + + b.Property("OAuthProviderKey") + .HasMaxLength(16) + .HasColumnType("character varying(16)") + .HasColumnName("oauth_provider_key") + .UseCollation("C"); + + b.Property("PasswordHash") + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("password_hash") + .UseCollation("C"); + + b.Property("Username") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("character varying(32)") + .HasColumnName("username") + .UseCollation("ndcoll"); + + b.HasKey("Id") + .HasName("pending_signups_pkey"); + + b.HasIndex("CreatedAt"); + + b.HasIndex("CreatedByAutomationTokenId"); + + var index = b.HasIndex("Email"); + + NpgsqlIndexBuilderExtensions.UseCollation(index, new[] { "ndcoll" }); + + var index0 = b.HasIndex("Username"); + + NpgsqlIndexBuilderExtensions.UseCollation(index0, new[] { "ndcoll" }); + + b.HasIndex("OAuthProviderKey", "OAuthExternalId") + .IsUnique() + .HasFilter("oauth_provider_key IS NOT NULL"); + + b.ToTable("pending_signups"); + }); + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PublicShare", b => { b.Property("Id") @@ -1035,38 +1127,6 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.ToTable("users"); }); - modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserActivationRequest", b => - { - b.Property("UserId") - .HasColumnType("uuid") - .HasColumnName("user_id"); - - b.Property("CreatedAt") - .ValueGeneratedOnAdd() - .HasColumnType("timestamp with time zone") - .HasColumnName("created_at") - .HasDefaultValueSql("CURRENT_TIMESTAMP"); - - b.Property("EmailSendAttempts") - .HasColumnType("integer") - .HasColumnName("email_send_attempts"); - - b.Property("TokenHash") - .IsRequired() - .HasMaxLength(128) - .HasColumnType("character varying(128)") - .HasColumnName("token_hash") - .UseCollation("C"); - - b.HasKey("UserId") - .HasName("user_activation_requests_pkey"); - - b.HasIndex("TokenHash") - .IsUnique(); - - b.ToTable("user_activation_requests"); - }); - modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserAuditLog", b => { b.Property("Id") @@ -1561,6 +1621,17 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("Device"); }); + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PendingSignup", b => + { + b.HasOne("OpenShock.Common.OpenShockDb.AutomationToken", "CreatedByAutomationToken") + .WithMany() + .HasForeignKey("CreatedByAutomationTokenId") + .OnDelete(DeleteBehavior.Cascade) + .HasConstraintName("fk_pending_signups_created_by_automation_token_id"); + + b.Navigation("CreatedByAutomationToken"); + }); + modelBuilder.Entity("OpenShock.Common.OpenShockDb.PublicShare", b => { b.HasOne("OpenShock.Common.OpenShockDb.User", "Owner") @@ -1639,18 +1710,6 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("CreatedByAutomationToken"); }); - modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserActivationRequest", b => - { - b.HasOne("OpenShock.Common.OpenShockDb.User", "User") - .WithOne("UserActivationRequest") - .HasForeignKey("OpenShock.Common.OpenShockDb.UserActivationRequest", "UserId") - .OnDelete(DeleteBehavior.Cascade) - .IsRequired() - .HasConstraintName("fk_user_activation_requests_user_id"); - - b.Navigation("User"); - }); - modelBuilder.Entity("OpenShock.Common.OpenShockDb.UserAuditLog", b => { b.HasOne("OpenShock.Common.OpenShockDb.User", "Actor") @@ -1858,8 +1917,6 @@ protected override void BuildModel(ModelBuilder modelBuilder) b.Navigation("ReportedApiTokens"); - b.Navigation("UserActivationRequest"); - b.Navigation("UserDeactivation"); }); diff --git a/Common/OpenShockDb/Keys/EmailOutboxCoalesceKeys.cs b/Common/OpenShockDb/Keys/EmailOutboxCoalesceKeys.cs index 5986e9596..a37a2362f 100644 --- a/Common/OpenShockDb/Keys/EmailOutboxCoalesceKeys.cs +++ b/Common/OpenShockDb/Keys/EmailOutboxCoalesceKeys.cs @@ -16,8 +16,8 @@ namespace OpenShock.Common.OpenShockDb; /// public static class EmailOutboxCoalesceKeys { - /// Newest account-activation email per user wins. - public static string AccountActivation(Guid userId) => $"activation:{userId}"; + /// Newest activation-code email per pending signup wins. + public static string AccountActivation(Guid pendingSignupId) => $"activation:{pendingSignupId}"; /// Newest password-reset email per user wins. public static string PasswordReset(Guid userId) => $"pwreset:{userId}"; diff --git a/Common/OpenShockDb/Keys/EmailOutboxPayloadKeys.cs b/Common/OpenShockDb/Keys/EmailOutboxPayloadKeys.cs index 9919fab9c..97b5cf194 100644 --- a/Common/OpenShockDb/Keys/EmailOutboxPayloadKeys.cs +++ b/Common/OpenShockDb/Keys/EmailOutboxPayloadKeys.cs @@ -10,8 +10,8 @@ namespace OpenShock.Common.OpenShockDb; /// public static class EmailOutboxPayloadKeys { - /// Target user id. Used by . - public const string UserId = "userId"; + /// id. Used by . + public const string PendingSignupId = "pendingSignupId"; /// id. Used by . public const string PasswordResetId = "passwordResetId"; diff --git a/Common/OpenShockDb/Models/EmailOutboxMessage.cs b/Common/OpenShockDb/Models/EmailOutboxMessage.cs index 31ee95609..adee7285e 100644 --- a/Common/OpenShockDb/Models/EmailOutboxMessage.cs +++ b/Common/OpenShockDb/Models/EmailOutboxMessage.cs @@ -133,11 +133,11 @@ public static EmailOutboxMessage Create(EmailType type, string recipient, string // callers never repeat it - and so the three can never drift out of sync. Newest-wins types key on // the user; the change notice is always-delivered and carries no key. - /// Account-activation email for . Newest activation per user wins. - public static EmailOutboxMessage ForAccountActivation(Guid userId, string recipient, string? recipientName) => + /// Activation-code email for pending signup . Newest per signup wins. + public static EmailOutboxMessage ForAccountActivation(Guid pendingSignupId, string recipient, string? recipientName) => Create(EmailType.AccountActivation, recipient, recipientName, - new Dictionary { [EmailOutboxPayloadKeys.UserId] = userId.ToString() }, - EmailOutboxCoalesceKeys.AccountActivation(userId)); + new Dictionary { [EmailOutboxPayloadKeys.PendingSignupId] = pendingSignupId.ToString() }, + EmailOutboxCoalesceKeys.AccountActivation(pendingSignupId)); /// Password-reset email for reset . Newest reset per user wins. public static EmailOutboxMessage ForPasswordReset(Guid passwordResetId, Guid userId, string recipient, string? recipientName) => diff --git a/Common/OpenShockDb/Models/PendingSignup.cs b/Common/OpenShockDb/Models/PendingSignup.cs new file mode 100644 index 000000000..157fea6e7 --- /dev/null +++ b/Common/OpenShockDb/Models/PendingSignup.cs @@ -0,0 +1,58 @@ +namespace OpenShock.Common.OpenShockDb; + +/// +/// A signup that has not shown yet that its email address belongs to whoever started it. It is not an +/// account: nothing can sign in with it, and it does not reserve the address, so any number of them can +/// exist for one address. The username is kept from others for a short while only +/// (Duration.PendingSignupUsernameReservation), after which other signups may ask for it too. +/// The account is created when the code mailed to the address is entered in a browser that holds the +/// signup (see SignupBrowserCookie), and whichever signup does that first gets the address and +/// the name. +/// +/// +/// Carries the credential the account will have: a password hash, an OAuth identity, or both never. It +/// is kept here and not on a user row so that a credential chosen by someone who merely typed an +/// address can never end up on an account before the address is verified. +/// +public sealed class PendingSignup +{ + /// Primary key. Becomes the id of the account this signup turns into. + public Guid Id { get; init; } + + /// Lowercased address the code is mailed to. + public required string Email { get; init; } + + public required string Username { get; init; } + + /// Password hash for a password signup, null for an OAuth signup. + public string? PasswordHash { get; init; } + + /// Provider of the OAuth identity that started this signup, null for a password signup. + public string? OAuthProviderKey { get; init; } + + /// Id of that identity at the provider. An identity has at most one pending signup. + public string? OAuthExternalId { get; init; } + + public string? OAuthDisplayName { get; init; } + + /// + /// Hash of the code last mailed, bound to this signup's id. Seeded with a throwaway value on creation + /// and replaced by the email outbox delivery job every time it sends, so only the newest mail's code + /// works and the queue never holds a usable one. + /// + public required string CodeHash { get; set; } + + /// When the current code was mailed. Null until the first mail went out; no code is accepted before. + public DateTime? CodeSentAt { get; set; } + + /// Wrong codes entered against the current code. Reset when a new code is mailed. + public int FailedAttempts { get; set; } + + /// The automation token that started this signup, carried over to the account. + public Guid? CreatedByAutomationTokenId { get; init; } + + public DateTime CreatedAt { get; init; } + + // Navigations + public AutomationToken? CreatedByAutomationToken { get; init; } +} diff --git a/Common/OpenShockDb/Models/User.cs b/Common/OpenShockDb/Models/User.cs index 2e3fad5d2..fa53deff7 100644 --- a/Common/OpenShockDb/Models/User.cs +++ b/Common/OpenShockDb/Models/User.cs @@ -32,7 +32,6 @@ public sealed class User public Guid? CreatedByAutomationTokenId { get; init; } // Navigations - public UserActivationRequest? UserActivationRequest { get; set; } public UserDeactivation? UserDeactivation { get; set; } public ICollection OAuthConnections { get; set; } = []; public ICollection ApiTokens { get; } = []; diff --git a/Common/OpenShockDb/Models/UserActivationRequest.cs b/Common/OpenShockDb/Models/UserActivationRequest.cs deleted file mode 100644 index 6cc1ac2e7..000000000 --- a/Common/OpenShockDb/Models/UserActivationRequest.cs +++ /dev/null @@ -1,20 +0,0 @@ -namespace OpenShock.Common.OpenShockDb; - -public sealed class UserActivationRequest -{ - public required Guid UserId { get; set; } - - /// - /// Hash of the secret activation token. The plaintext is never stored. Seeded when the request is - /// created and re-minted by the email outbox consumer on every (re)send, so the queue never holds - /// a usable activation link. See . - /// - public required string TokenHash { get; set; } - - public int EmailSendAttempts { get; set; } - - public DateTime CreatedAt { get; init; } - - // Navigations - public User User { get; init; } = null!; -} diff --git a/Common/OpenShockDb/OpenShockContext.cs b/Common/OpenShockDb/OpenShockContext.cs index ffa41d2a2..6ba04524b 100644 --- a/Common/OpenShockDb/OpenShockContext.cs +++ b/Common/OpenShockDb/OpenShockContext.cs @@ -99,7 +99,7 @@ public static void ConfigureOptionsBuilder(DbContextOptionsBuilder optionsBuilde public DbSet UserOAuthConnections { get; set; } - public DbSet UserActivationRequests { get; set; } + public DbSet PendingSignups { get; set; } public DbSet UserDeactivations { get; set; } @@ -625,29 +625,69 @@ protected override void OnModelCreating(ModelBuilder modelBuilder) .HasConstraintName("fk_user_oauth_connections_user_id"); }); - modelBuilder.Entity(entity => + modelBuilder.Entity(entity => { - entity.HasKey(e => e.UserId).HasName("user_activation_requests_pkey"); + entity.HasKey(e => e.Id).HasName("pending_signups_pkey"); - entity.HasIndex(e => e.TokenHash).IsUnique(); + entity.ToTable("pending_signups"); - entity.ToTable("user_activation_requests"); + // Deliberately not unique: a pending signup does not reserve its address, and its username only + // for a while (enforced when another signup asks for the name, not by the database). + entity.HasIndex(e => e.Email).UseCollation("ndcoll"); + entity.HasIndex(e => e.Username).UseCollation("ndcoll"); + entity.HasIndex(e => e.CreatedAt); + entity.HasIndex(e => e.CreatedByAutomationTokenId); - entity.Property(e => e.UserId) - .HasColumnName("user_id"); - entity.Property(e => e.TokenHash) + // An OAuth identity has at most one pending signup; starting over replaces it. + entity.HasIndex(e => new { e.OAuthProviderKey, e.OAuthExternalId }) + .IsUnique() + .HasFilter("oauth_provider_key IS NOT NULL"); + + entity.Property(e => e.Id) + .ValueGeneratedOnAdd() + .HasColumnName("id"); + entity.Property(e => e.Email) + .UseCollation("ndcoll") + .HasMaxLength(HardLimits.EmailAddressMaxLength) + .HasColumnName("email"); + entity.Property(e => e.Username) + .UseCollation("ndcoll") + .HasMaxLength(HardLimits.UsernameMaxLength) + .HasColumnName("username"); + entity.Property(e => e.PasswordHash) .UseCollation("C") - .HasMaxLength(ApiHardLimits.UserActivationRequestSecretMaxLength) - .HasColumnName("token_hash"); - entity.Property(e => e.EmailSendAttempts) - .HasColumnName("email_send_attempts"); + .HasMaxLength(ApiHardLimits.PasswordHashMaxLength) + .HasColumnName("password_hash"); + entity.Property(e => e.OAuthProviderKey) + .UseCollation("C") + .HasMaxLength(ApiHardLimits.OAuthProviderKeyMaxLength) + .HasColumnName("oauth_provider_key"); + entity.Property(e => e.OAuthExternalId) + .HasMaxLength(ApiHardLimits.OAuthExternalIdMaxLength) + .HasColumnName("oauth_external_id"); + entity.Property(e => e.OAuthDisplayName) + .HasMaxLength(ApiHardLimits.OAuthDisplayNameMaxLength) + .HasColumnName("oauth_display_name"); + entity.Property(e => e.CodeHash) + .UseCollation("C") + .HasMaxLength(HardLimits.Sha256HashHexLength) + .HasColumnName("code_hash"); + entity.Property(e => e.CodeSentAt) + .HasColumnName("code_sent_at"); + entity.Property(e => e.FailedAttempts) + .HasDefaultValue(0) + .HasColumnName("failed_attempts"); + entity.Property(e => e.CreatedByAutomationTokenId) + .HasColumnName("created_by_automation_token_id"); entity.Property(e => e.CreatedAt) .HasDefaultValueSql("CURRENT_TIMESTAMP") .HasColumnName("created_at"); - entity.HasOne(d => d.User).WithOne(p => p.UserActivationRequest) - .HasForeignKey(d => d.UserId) - .HasConstraintName("fk_user_activation_requests_user_id"); + // A pending signup is nothing worth keeping a token around for: it goes with the token. + entity.HasOne(d => d.CreatedByAutomationToken).WithMany() + .HasForeignKey(d => d.CreatedByAutomationTokenId) + .OnDelete(DeleteBehavior.Cascade) + .HasConstraintName("fk_pending_signups_created_by_automation_token_id"); }); modelBuilder.Entity(entity => diff --git a/Common/Utils/ActivationCode.cs b/Common/Utils/ActivationCode.cs new file mode 100644 index 000000000..dc0e084b9 --- /dev/null +++ b/Common/Utils/ActivationCode.cs @@ -0,0 +1,28 @@ +using System.Security.Cryptography; +using OpenShock.Common.Constants; + +namespace OpenShock.Common.Utils; + +/// +/// The short numeric code mailed to complete a signup. It is typed into a browser that holds the signup, +/// so it only has to be unguessable within the few attempts a signup gets +/// ( per mailed code), not on its own. +/// +public static class ActivationCode +{ + private static readonly int Exclusive = (int)Math.Pow(10, AuthConstants.ActivationCodeLength); + + public static string Generate() + => RandomNumberGenerator.GetInt32(Exclusive).ToString($"D{AuthConstants.ActivationCodeLength}"); + + /// + /// Hash stored for a code. Bound to the signup it was mailed for: with so few possible codes, a bare + /// hash would be the same for every signup that happened to get the same digits. + /// + public static string Hash(Guid pendingSignupId, string code) + => HashingUtils.HashToken($"{pendingSignupId:N}:{code}"); + + /// Whether has the shape of a code at all, before anything is looked up. + public static bool IsWellFormed(string? code) + => code is { Length: AuthConstants.ActivationCodeLength } && code.All(char.IsAsciiDigit); +} diff --git a/Cron.IntegrationTests/Tests/DeleteExpiredPendingSignupsTests.cs b/Cron.IntegrationTests/Tests/DeleteExpiredPendingSignupsTests.cs new file mode 100644 index 000000000..2dfada234 --- /dev/null +++ b/Cron.IntegrationTests/Tests/DeleteExpiredPendingSignupsTests.cs @@ -0,0 +1,59 @@ +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 pending-signup cleanup against real Postgres. +/// +public sealed class DeleteExpiredPendingSignupsTests +{ + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required CronApplicationFactory Factory { get; init; } + + [Test] + public async Task Execute_DeletesOnlyPendingSignupsPastTheirLifetime() + { + var expired = Guid.CreateVersion7(); + var live = Guid.CreateVersion7(); + + await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + { + db.PendingSignups.Add(NewPendingSignup(expired, DateTime.UtcNow - Duration.PendingSignupLifetime - TimeSpan.FromHours(1))); + db.PendingSignups.Add(NewPendingSignup(live, DateTime.UtcNow - TimeSpan.FromHours(1))); + 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.PendingSignups + .Where(p => p.Id == expired || p.Id == live) + .Select(p => p.Id) + .ToListAsync(); + + await Assert.That(remaining).DoesNotContain(expired); + await Assert.That(remaining).Contains(live); + } + + private static PendingSignup NewPendingSignup(Guid id, DateTime createdAt) + { + var suffix = Guid.NewGuid().ToString("N")[..12]; + return new PendingSignup + { + Id = id, + Email = $"pending-{suffix}@test.org", + Username = $"pending{suffix}", + PasswordHash = HashingUtils.HashPassword("SeedPassword123#"), + CodeHash = HashingUtils.HashToken(Guid.NewGuid().ToString("N")), + CreatedAt = createdAt + }; + } +} diff --git a/Cron.IntegrationTests/Tests/DeleteUnactivatedAccountsTests.cs b/Cron.IntegrationTests/Tests/DeleteUnactivatedAccountsTests.cs deleted file mode 100644 index 42ca1e0c0..000000000 --- a/Cron.IntegrationTests/Tests/DeleteUnactivatedAccountsTests.cs +++ /dev/null @@ -1,91 +0,0 @@ -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.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs b/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs index 8e08fce6a..f45f29c7f 100644 --- a/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs +++ b/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs @@ -106,30 +106,16 @@ public async Task PasswordReset_NewerRequest_SupersedesOlder_OnlyNewestDelivered } [Test] - public async Task AccountActivation_QueuedForAPreviousAddress_IsSkipped_AndMintsNoToken() + public async Task AccountActivation_ForASignupThatNoLongerExists_IsSkipped() { - // 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"); + // Completed, replaced or expired since this message was queued: there is nothing to mail a code for. + var email = UniqueEmail("cron-activation-gone"); 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"); + var outbox = EmailOutboxMessage.ForAccountActivation(Guid.CreateVersion7(), email, "Activation User"); db.EmailOutbox.Add(outbox); await db.SaveChangesAsync(); outboxId = outbox.Id; @@ -141,38 +127,52 @@ public async Task AccountActivation_QueuedForAPreviousAddress_IsSkipped_AndMints { var row = await db.EmailOutbox.AsNoTracking().SingleAsync(m => m.Id == outboxId); await Assert.That(row.Status).IsEqualTo(EmailStatus.Skipped); + } + + await Assert.That((await mailpit.SearchByRecipientAsync(email)).Count).IsEqualTo(0); + } - var request = await db.UserActivationRequests.AsNoTracking().SingleAsync(r => r.UserId == userId); - await Assert.That(request.TokenHash).IsEqualTo(seededHash); + [Test] + public async Task AccountActivation_ForASignupPastItsLifetime_IsSkipped_AndMintsNoCode() + { + var email = UniqueEmail("cron-activation-expired"); + using var mailpit = Factory.CreateMailpitHelper(); + + var (pendingSignupId, seededHash) = await AddPendingSignupAsync(email, createdAt: DateTime.UtcNow - Duration.PendingSignupLifetime - TimeSpan.FromMinutes(1)); + Guid outboxId; + await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + { + var outbox = EmailOutboxMessage.ForAccountActivation(pendingSignupId, email, "Activation User"); + db.EmailOutbox.Add(outbox); + await db.SaveChangesAsync(); + outboxId = outbox.Id; } - await Assert.That((await mailpit.SearchByRecipientAsync(oldEmail)).Count).IsEqualTo(0); + 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 pending = await db.PendingSignups.AsNoTracking().SingleAsync(p => p.Id == pendingSignupId); + await Assert.That(pending.CodeHash).IsEqualTo(seededHash); + await Assert.That(pending.CodeSentAt).IsNull(); + } + + await Assert.That((await mailpit.SearchByRecipientAsync(email)).Count).IsEqualTo(0); } [Test] - public async Task AccountActivation_IsDelivered_AndEmailedTokenMatchesStoredHash() + public async Task AccountActivation_IsDelivered_AndEmailedCodeMatchesStoredHash() { var email = UniqueEmail("cron-activation"); using var mailpit = Factory.CreateMailpitHelper(); - var userId = Guid.CreateVersion7(); + var (pendingSignupId, seededHash) = await AddPendingSignupAsync(email, failedAttempts: 3); 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")); + db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(pendingSignupId, email, "Activation User")); await db.SaveChangesAsync(); } @@ -181,19 +181,46 @@ public async Task AccountActivation_IsDelivered_AndEmailedTokenMatchesStoredHash var message = await mailpit.WaitForMessageAsync(email); await Assert.That(message).IsNotNull(); + // The mail carries a code to type in, and nothing to click that would complete the signup. 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(); + var code = Regex.Match(full!.Html, @">\s*(\d{6})\s*<").Groups[1].Value; + await Assert.That(code).IsNotEmpty(); + await Assert.That(full.Html).DoesNotContain("activate?"); 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)); + var pending = await db.PendingSignups.AsNoTracking().SingleAsync(p => p.Id == pendingSignupId); + await Assert.That(pending.CodeHash).IsNotEqualTo(seededHash); + await Assert.That(pending.CodeHash).IsEqualTo(ActivationCode.Hash(pendingSignupId, code)); + await Assert.That(pending.CodeSentAt).IsNotNull(); + // A new code starts with all its attempts. + await Assert.That(pending.FailedAttempts).IsEqualTo(0); } } // --- Helpers --- + private async Task<(Guid PendingSignupId, string SeededHash)> AddPendingSignupAsync(string email, DateTime? createdAt = null, int failedAttempts = 0) + { + await using var db = await Factory.DbContextFactory.CreateDbContextAsync(); + var pending = new PendingSignup + { + Id = Guid.CreateVersion7(), + Email = email, + Username = "activation" + Guid.NewGuid().ToString("N")[..8], + PasswordHash = HashingUtils.HashPassword("SeedPassword123#"), + CodeHash = HashingUtils.HashToken(CryptoUtils.RandomString(AuthConstants.GeneratedTokenLength)), + FailedAttempts = failedAttempts, + CreatedAt = createdAt ?? DateTime.UtcNow + }; + db.PendingSignups.Add(pending); + await db.SaveChangesAsync(); + + return (pending.Id, pending.CodeHash); + } + + // --- Helpers --- + private async Task<(Guid UserId, Guid Stamp)> AddUserAsync(string email, string name) { await using var db = await Factory.DbContextFactory.CreateDbContextAsync(); diff --git a/Cron/Jobs/DeleteExpiredPendingSignupsJob.cs b/Cron/Jobs/DeleteExpiredPendingSignupsJob.cs new file mode 100644 index 000000000..25a0c866a --- /dev/null +++ b/Cron/Jobs/DeleteExpiredPendingSignupsJob.cs @@ -0,0 +1,46 @@ +using Microsoft.EntityFrameworkCore; +using OpenShock.Common.Constants; +using OpenShock.Common.OpenShockDb; +using OpenShock.Cron.Attributes; + +namespace OpenShock.Cron.Jobs; + +/// +/// Deletes pending signups that were not completed within . +/// They stop being accepted at that age anyway; this only clears them out, together with the password +/// hash or OAuth identity each one carries. +/// +[CronJob("30 * * * *")] // Every hour +public sealed class DeleteExpiredPendingSignupsJob +{ + 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 DeleteExpiredPendingSignupsJob(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.PendingSignupLifetime; + + var nDeleted = await _db.PendingSignups + .Where(p => p.CreatedAt < createdBefore) + .ExecuteDeleteAsync(cancellationToken); + + _logger.LogInformation("Deleted {DeletedCount} pending signups started before {CreatedBefore}", nDeleted, createdBefore); + + return nDeleted; + } +} diff --git a/Cron/Jobs/DeleteUnactivatedAccountsJob.cs b/Cron/Jobs/DeleteUnactivatedAccountsJob.cs deleted file mode 100644 index 109bcd1f5..000000000 --- a/Cron/Jobs/DeleteUnactivatedAccountsJob.cs +++ /dev/null @@ -1,57 +0,0 @@ -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; - } -} diff --git a/Cron/Services/Email/IEmailService.cs b/Cron/Services/Email/IEmailService.cs index f520e6e41..a1c138021 100644 --- a/Cron/Services/Email/IEmailService.cs +++ b/Cron/Services/Email/IEmailService.cs @@ -12,13 +12,15 @@ namespace OpenShock.Cron.Services.Email; public interface IEmailService { /// - /// When a user uses the signup form we send this email to let them activate their account + /// When a user signs up we send this email with the code that completes the signup. A code and not a + /// link: it has to be entered in a browser that holds the signup, so there must be nothing in the mail + /// that whoever merely receives it could click. /// /// - /// + /// /// /// The outcome of the send attempt. - public Task ActivateAccount(Contact to, Uri activationLink, CancellationToken cancellationToken = default); + public Task ActivateAccount(Contact to, string activationCode, CancellationToken cancellationToken = default); /// /// Send a password reset email diff --git a/Cron/Services/Email/Mailjet/MailjetEmailService.cs b/Cron/Services/Email/Mailjet/MailjetEmailService.cs index 388970889..30ced3acd 100644 --- a/Cron/Services/Email/Mailjet/MailjetEmailService.cs +++ b/Cron/Services/Email/Mailjet/MailjetEmailService.cs @@ -29,9 +29,9 @@ ILogger logger #region Interface methods - public async Task ActivateAccount(Contact to, Uri activationLink, CancellationToken cancellationToken = default) + public async Task ActivateAccount(Contact to, string activationCode, CancellationToken cancellationToken = default) { - var (subject, htmlBody) = await _templates.AccountActivation.RenderAsync(new { To = to, ActivationLink = activationLink }); + var (subject, htmlBody) = await _templates.AccountActivation.RenderAsync(new { To = to, ActivationCode = activationCode }); return await SendMail(to, subject, htmlBody, cancellationToken); } diff --git a/Cron/Services/Email/NoneEmailService.cs b/Cron/Services/Email/NoneEmailService.cs index 688954652..9d695a2e8 100644 --- a/Cron/Services/Email/NoneEmailService.cs +++ b/Cron/Services/Email/NoneEmailService.cs @@ -18,7 +18,7 @@ public NoneEmailService(ILogger logger) // Returns Sent (not a failure) on purpose: in a deployment with mail disabled the outbox should // mark messages terminal rather than retrying them forever. - public Task ActivateAccount(Contact to, Uri activationLink, CancellationToken cancellationToken = default) + public Task ActivateAccount(Contact to, string activationCode, CancellationToken cancellationToken = default) { _logger.LogError("Account activation email not sent, this is a noop implementation of the email service"); return Task.FromResult(EmailSendResult.Sent); diff --git a/Cron/Services/Email/Outbox/EmailOutboxDispatcher.cs b/Cron/Services/Email/Outbox/EmailOutboxDispatcher.cs index 338e5bd7a..682d5b1e7 100644 --- a/Cron/Services/Email/Outbox/EmailOutboxDispatcher.cs +++ b/Cron/Services/Email/Outbox/EmailOutboxDispatcher.cs @@ -60,32 +60,31 @@ public async Task SendAsync(EmailOutboxMessage message, Ope private async Task SendAccountActivation(EmailOutboxMessage message, OpenShockContext db, CancellationToken ct) { - if (!TryGetGuid(message, EmailOutboxPayloadKeys.UserId, out var userId)) - return EmailDispatchResult.Permanent($"Payload missing {EmailOutboxPayloadKeys.UserId}"); - - var request = await db.UserActivationRequests - .Include(r => r.User) - .FirstOrDefaultAsync(r => r.UserId == userId, ct); - 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"); - - // 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)); + if (!TryGetGuid(message, EmailOutboxPayloadKeys.PendingSignupId, out var pendingSignupId)) + return EmailDispatchResult.Permanent($"Payload missing {EmailOutboxPayloadKeys.PendingSignupId}"); + + var createdAt = await db.PendingSignups + .Where(p => p.Id == pendingSignupId) + .Select(p => (DateTime?)p.CreatedAt) + .FirstOrDefaultAsync(ct); + if (createdAt is null) return EmailDispatchResult.Skip("Pending signup no longer exists"); + if (createdAt < DateTime.UtcNow - Duration.PendingSignupLifetime) return EmailDispatchResult.Skip("Pending signup expired"); + + // The code is minted here and only its hash stored, so the queue never holds a usable one, and + // each mail replaces the code of the one before it. A new code starts with all its attempts. + // Waits for an attempt to enter the previous code that is in flight right now (it locks the row). + var code = ActivationCode.Generate(); + var codeHash = ActivationCode.Hash(pendingSignupId, code); + var now = DateTime.UtcNow; + var minted = await db.PendingSignups + .Where(p => p.Id == pendingSignupId) + .ExecuteUpdateAsync(s => s + .SetProperty(p => p.CodeHash, codeHash) + .SetProperty(p => p.CodeSentAt, now) + .SetProperty(p => p.FailedAttempts, 0), ct); + if (minted == 0) return EmailDispatchResult.Skip("Pending signup no longer exists"); + + return FromSend(await _emailService.ActivateAccount(ToContact(message), code, ct)); } private async Task SendPasswordReset(EmailOutboxMessage message, OpenShockContext db, CancellationToken ct) @@ -145,7 +144,7 @@ private async Task SendPreview(EmailOutboxMessage message, return message.Type switch { - EmailType.AccountActivation => FromSend(await _emailService.ActivateAccount(to, link, ct)), + EmailType.AccountActivation => FromSend(await _emailService.ActivateAccount(to, "123456", ct)), EmailType.PasswordReset => FromSend(await _emailService.PasswordReset(to, link, ct)), EmailType.EmailVerification => FromSend(await _emailService.VerifyEmail(to, link, ct)), EmailType.EmailChangeNotice => FromSend(await _emailService.EmailChangeNotice(to, "new-address@example.com", ct)), diff --git a/Cron/Services/Email/Smtp/SmtpEmailService.cs b/Cron/Services/Email/Smtp/SmtpEmailService.cs index 8fe69ede7..87ba76d52 100644 --- a/Cron/Services/Email/Smtp/SmtpEmailService.cs +++ b/Cron/Services/Email/Smtp/SmtpEmailService.cs @@ -26,8 +26,8 @@ ILogger logger _logger = logger; } - public Task ActivateAccount(Contact to, Uri activationLink, CancellationToken cancellationToken = default) - => SendMail(to, _templates.AccountActivation, new { To = to, ActivationLink = activationLink }, cancellationToken); + public Task ActivateAccount(Contact to, string activationCode, CancellationToken cancellationToken = default) + => SendMail(to, _templates.AccountActivation, new { To = to, ActivationCode = activationCode }, cancellationToken); /// public Task PasswordReset(Contact to, Uri resetLink, CancellationToken cancellationToken = default) diff --git a/Cron/SmtpTemplates/AccountActivation.liquid b/Cron/SmtpTemplates/AccountActivation.liquid index 4f7728ecc..fd8f5b05d 100644 --- a/Cron/SmtpTemplates/AccountActivation.liquid +++ b/Cron/SmtpTemplates/AccountActivation.liquid @@ -1,19 +1,21 @@ -Activate your OpenShock account +Your OpenShock activation code - One last step: activate your new OpenShock account. + + One last step: enter this code to activate your new OpenShock account. +
- One last step: activate your new OpenShock account. + One last step: enter this code to activate your new OpenShock account.
-  ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ +  ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍ ‌​‍
@@ -82,46 +84,26 @@ Activate your OpenShock account

- Thanks for signing up! Confirm this is your email - address to finish setting up your OpenShock - account. + Thanks for signing up! Enter this code on the page + where you signed up to finish setting up your + OpenShock account.

- - - - - - -
- Activate account -

- If the button above doesn't work, copy and - paste this link into your browser: + style='font-size:28px;line-height:36px;font-family:ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;background-color:#f4f4f5;border:1px solid #e4e4e7;border-radius:8px;padding:14px 16px;margin:4px 0 20px;font-weight:600;letter-spacing:6px;text-align:center;color:#09090b;margin-top:4px;margin-right:0;margin-bottom:20px;margin-left:0'> + {{ ActivationCode }} +

+

+ The code is valid for one hour. If you closed the + page, sign in with what you signed up with and you + will be asked for it.

- {{ ActivationLink }}

If you did not sign up for OpenShock, you can - safely ignore this email. No account will be - created without confirmation. + safely ignore this email and should not share this + code with anyone. No account will be created + without it.

diff --git a/SeedE2E/Program.cs b/SeedE2E/Program.cs index 6c736d2bc..76c17a112 100644 --- a/SeedE2E/Program.cs +++ b/SeedE2E/Program.cs @@ -57,7 +57,6 @@ await PublicShareShockerSeeder.SeedAsync(db, logger); await UserEmailChangeSeeder.SeedAsync(db, logger); await UserNameChangeSeeder.SeedAsync(db, logger); - await UserActivationRequestSeeder.SeedAsync(db, logger); await UserDeactivationSeeder.SeedAsync(db, logger); // Discord webhooks diff --git a/SeedE2E/Seeders/UserActivationRequestSeeder.cs b/SeedE2E/Seeders/UserActivationRequestSeeder.cs deleted file mode 100644 index c1ad7aa96..000000000 --- a/SeedE2E/Seeders/UserActivationRequestSeeder.cs +++ /dev/null @@ -1,43 +0,0 @@ -using Bogus; -using Microsoft.Extensions.Logging; -using OpenShock.Common.Constants; -using OpenShock.Common.OpenShockDb; -using OpenShock.Common.Utils; - -namespace OpenShock.SeedE2E.Seeders; - -public static class UserActivationRequestSeeder -{ - public static async Task SeedAsync(OpenShockContext db, ILogger logger) - { - if (db.UserActivationRequests.Any()) - return; - - logger.LogInformation("Generating UserActivationRequests..."); - - var allUserIds = db.Users.Where(u => u.ActivatedAt == default).Select(u => u.Id).ToList(); - if (allUserIds.Count == 0) - return; - - var activationFaker = new Faker() - .RuleFor(a => a.TokenHash, f => - { - var token = f.Random.AlphaNumeric(AuthConstants.GeneratedTokenLength); - return HashingUtils.HashToken(token); - }) - .RuleFor(a => a.EmailSendAttempts, f => f.Random.Number(0, 3)) - .RuleFor(a => a.CreatedAt, f => f.Date.RecentOffset(20).UtcDateTime); - - List requests = [with(capacity: allUserIds.Count)]; - for (int i = 0; i < allUserIds.Count; i++) - { - var faked = activationFaker.Generate(); - faked.UserId = allUserIds[i]; - - requests.Add(faked); - } - - db.UserActivationRequests.AddRange(requests); - await db.SaveChangesAsync(); - } -} diff --git a/email-templates/emails/AccountActivation.tsx b/email-templates/emails/AccountActivation.tsx index ea2ec570f..7a2f735f7 100644 --- a/email-templates/emails/AccountActivation.tsx +++ b/email-templates/emails/AccountActivation.tsx @@ -1,41 +1,44 @@ import { - CtaButton, + CodeDisplay, Greeting, Layout, Paragraph, - RawLinkFallback, SecurityNotice, Signoff, } from './_lib/components.tsx'; export interface AccountActivationProps { 'To.Name': string; - ActivationLink: string; + ActivationCode: string; } -export const subject = 'Activate your OpenShock account'; +export const subject = 'Your OpenShock activation code'; export const sampleProps: AccountActivationProps = { 'To.Name': 'shockee', - ActivationLink: 'https://openshock.app/activate?token=preview', + ActivationCode: '123456', }; export function AccountActivation(props: AccountActivationProps) { return ( - Thanks for signing up! Confirm this is your email address to finish - setting up your OpenShock account. + Thanks for signing up! Enter this code on the page where you signed up + to finish setting up your OpenShock account. + + {props.ActivationCode} + + The code is valid for one hour. If you closed the page, sign in with + what you signed up with and you will be asked for it. - Activate account - - If you did not sign up for OpenShock, you can safely ignore this email. - No account will be created without confirmation. + If you did not sign up for OpenShock, you can safely ignore this email + and should not share this code with anyone. No account will be created + without it. diff --git a/email-templates/emails/_lib/components.tsx b/email-templates/emails/_lib/components.tsx index 2d6f631de..24b5a2995 100644 --- a/email-templates/emails/_lib/components.tsx +++ b/email-templates/emails/_lib/components.tsx @@ -135,6 +135,11 @@ export function RawLinkFallback({ href }: { href: string }) { ); } +/** A short code the reader types in somewhere else, set large enough to read off another screen. */ +export function CodeDisplay({ children }: { children: ReactNode }) { + return {children}; +} + export function SecurityNotice({ children }: { children: ReactNode }) { return {children}; } diff --git a/email-templates/emails/_lib/styles.ts b/email-templates/emails/_lib/styles.ts index 47f46229f..95c614a8b 100644 --- a/email-templates/emails/_lib/styles.ts +++ b/email-templates/emails/_lib/styles.ts @@ -107,6 +107,20 @@ export const styles = { borderRadius: '4px', fontSize: '13px', }, + codeDisplay: { + fontFamily: monoStack, + backgroundColor: colors.codeBg, + border: `1px solid ${colors.border}`, + borderRadius: '8px', + padding: '14px 16px', + margin: '4px 0 20px', + fontSize: '28px', + lineHeight: '36px', + fontWeight: 600, + letterSpacing: '6px', + textAlign: 'center' as const, + color: colors.foreground, + }, notice: { backgroundColor: colors.muted, border: `1px solid ${colors.border}`, From 603cf9d2d486d35025423c6c8843c5bf0e4f6406 Mon Sep 17 00:00:00 2001 From: HeavenVR Date: Sun, 29 Nov 2026 02:58:04 +0100 Subject: [PATCH 19/20] feat: mail signup codes as two groups of four letters or digits The code is now uppercase A-Z and 0-9 in the form ABCD-1234, validated by a [SignupCode] attribute on the activate request. It is accepted in lowercase and without the dash, and normalised before it is compared. A value that is not shaped like a code is rejected without counting as an attempt. --- .../Helpers/PendingSignupHelper.cs | 10 +-- .../Tests/SignupActivationTests.cs | 61 +++++++++++--- API/Controller/Account/Activate.cs | 10 +-- API/Services/Account/AccountService.cs | 8 +- Common/Constants/AuthConstants.cs | 5 +- Common/DataAnnotations/SignupCodeAttribute.cs | 45 ++++++++++ Common/Utils/ActivationCode.cs | 28 ------- Common/Utils/SignupCode.cs | 82 +++++++++++++++++++ .../Tests/EmailOutboxDeliveryTests.cs | 4 +- .../Email/Outbox/EmailOutboxDispatcher.cs | 6 +- Cron/SmtpTemplates/AccountActivation.liquid | 2 +- email-templates/emails/AccountActivation.tsx | 2 +- email-templates/emails/_lib/styles.ts | 2 +- 13 files changed, 196 insertions(+), 69 deletions(-) create mode 100644 Common/DataAnnotations/SignupCodeAttribute.cs delete mode 100644 Common/Utils/ActivationCode.cs create mode 100644 Common/Utils/SignupCode.cs diff --git a/API.IntegrationTests/Helpers/PendingSignupHelper.cs b/API.IntegrationTests/Helpers/PendingSignupHelper.cs index cc5d71df7..24b8710cb 100644 --- a/API.IntegrationTests/Helpers/PendingSignupHelper.cs +++ b/API.IntegrationTests/Helpers/PendingSignupHelper.cs @@ -51,10 +51,10 @@ public static async Task CreateInDbAsync( /// Stands in for the Cron delivery job mailing the signup its code: stores the hash of a new code, starts /// its lifetime and gives it all its attempts back. Returns the code "the mail" carries. ///

- public static async Task MailCodeAsync(WebApplicationFactory factory, Guid pendingSignupId) + public static async Task MailCodeAsync(WebApplicationFactory factory, Guid pendingSignupId, string? code = null) { - var code = ActivationCode.Generate(); - var hash = ActivationCode.Hash(pendingSignupId, code); + code ??= SignupCode.Generate(); + var hash = SignupCode.Hash(pendingSignupId, code); var now = DateTime.UtcNow; await using var scope = factory.Services.CreateAsyncScope(); @@ -70,10 +70,6 @@ public static async Task MailCodeAsync(WebApplicationFactory factory, Gu return code; } - /// A code that is certainly not . - public static string AnotherCode(string code) - => ((int.Parse(code) + 1) % (int)Math.Pow(10, AuthConstants.ActivationCodeLength)).ToString($"D{AuthConstants.ActivationCodeLength}"); - public static async Task FindAsync(WebApplicationFactory factory, Guid pendingSignupId) { await using var scope = factory.Services.CreateAsyncScope(); diff --git a/API.IntegrationTests/Tests/SignupActivationTests.cs b/API.IntegrationTests/Tests/SignupActivationTests.cs index a3a0c473a..7e5daa7a5 100644 --- a/API.IntegrationTests/Tests/SignupActivationTests.cs +++ b/API.IntegrationTests/Tests/SignupActivationTests.cs @@ -7,6 +7,7 @@ using OpenShock.API.Services.Account; using OpenShock.Common.Constants; using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Utils; using static OpenShock.API.IntegrationTests.Helpers.PendingSignupHelper; namespace OpenShock.API.IntegrationTests.Tests; @@ -349,34 +350,34 @@ public async Task Activate_WrongCode_Returns400_WithTheAttemptsLeft() { var email = TestHelper.UniqueEmail("activate-wrong"); var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activatewrong")); - var code = await MailCodeAsync(WebApplicationFactory, pendingId); + var code = await MailCodeAsync(WebApplicationFactory, pendingId, "RGHT-0001"); var cookie = MintSignupBrowserCookie(WebApplicationFactory, pendingId); using var client = CreateClient(); - var response = await PostActivateAsync(client, AnotherCode(code), cookie); + var response = await PostActivateAsync(client, "WRNG-0001", cookie); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); using var problem = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); await Assert.That(problem.RootElement.GetProperty("type").GetString()).IsEqualTo("Account.Activation.CodeInvalid"); - await Assert.That(problem.RootElement.GetProperty("attemptsRemaining").GetInt32()).IsEqualTo(AuthConstants.ActivationCodeMaxAttempts - 1); + await Assert.That(problem.RootElement.GetProperty("attemptsRemaining").GetInt32()).IsEqualTo(AuthConstants.SignupCodeMaxAttempts - 1); // A wrong guess does not cost the signup: the right code still works. await Assert.That((await PostActivateAsync(client, code, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); } - // Six digits are only safe while they cannot be guessed at freely. + // A short code is only safe while it cannot be guessed at freely. [Test] public async Task Activate_AfterTooManyWrongCodes_EvenTheRightOneIsRefused_UntilANewOneIsMailed() { var email = TestHelper.UniqueEmail("activate-attempts"); var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activateattempts")); - var code = await MailCodeAsync(WebApplicationFactory, pendingId); + var code = await MailCodeAsync(WebApplicationFactory, pendingId, "RGHT-0001"); var cookie = MintSignupBrowserCookie(WebApplicationFactory, pendingId); using var client = CreateClient(); - for (var i = 0; i < AuthConstants.ActivationCodeMaxAttempts; i++) + for (var i = 0; i < AuthConstants.SignupCodeMaxAttempts; i++) { - var wrong = await PostActivateAsync(client, AnotherCode(code), cookie); + var wrong = await PostActivateAsync(client, "WRNG-0001", cookie); await Assert.That(await wrong.Content.ReadAsStringAsync()).Contains("Account.Activation.CodeInvalid"); } @@ -414,7 +415,7 @@ public async Task Activate_BeforeAnyCodeWasMailed_Returns400() var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activatenocode")); using var client = CreateClient(); - var response = await PostActivateAsync(client, "000000", MintSignupBrowserCookie(WebApplicationFactory, pendingId)); + var response = await PostActivateAsync(client, "AAAA-0000", MintSignupBrowserCookie(WebApplicationFactory, pendingId)); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Account.Activation.CodeExpired"); @@ -437,20 +438,56 @@ public async Task Activate_SignupOlderThanItsLifetime_Returns400_AndRemovesTheCo await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); } + // The code is read off a mail and typed in, often on another device: neither the case it is typed in + // nor a left out dash should make it wrong. + [Test] + [Arguments(true, true)] + [Arguments(true, false)] + [Arguments(false, true)] + public async Task Activate_CodeTypedInLowercaseOrWithoutTheDash_IsAccepted(bool lowercase, bool withoutDash) + { + var email = TestHelper.UniqueEmail("activate-typed"); + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activatetyped")); + var code = await MailCodeAsync(WebApplicationFactory, pendingId); + + var typed = code; + if (lowercase) typed = typed.ToLowerInvariant(); + if (withoutDash) typed = typed.Replace("-", ""); + + using var client = CreateClient(); + var response = await PostActivateAsync(client, typed, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNotNull(); + } + [Test] - public async Task Activate_MalformedCode_Returns400() + [Arguments("12")] + [Arguments("ABCD_1234")] + [Arguments("ABC-D1234")] + [Arguments("ABCD-12345")] + [Arguments("ABCD-12!4")] + public async Task Activate_NotACode_Returns400_WithoutCountingAsAGuess(string notACode) { - var pendingId = await CreateInDbAsync(WebApplicationFactory, TestHelper.UniqueEmail("activate-malformed"), TestHelper.UniqueUsername("activatemalformed")); + var pendingId = await CreateInDbAsync(WebApplicationFactory, TestHelper.UniqueEmail("activate-notacode"), TestHelper.UniqueUsername("activatenotacode")); await MailCodeAsync(WebApplicationFactory, pendingId); using var client = CreateClient(); - var response = await PostActivateAsync(client, "12", MintSignupBrowserCookie(WebApplicationFactory, pendingId)); + var response = await PostActivateAsync(client, notACode, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); - // Refused before it is looked at, so it does not count as a guess. await Assert.That((await FindAsync(WebApplicationFactory, pendingId))!.FailedAttempts).IsEqualTo(0); } + [Test] + public async Task MailedCode_IsTwoGroupsOfFourUppercaseLettersOrDigits() + { + for (var i = 0; i < 50; i++) + { + await Assert.That(SignupCode.Generate()).Matches("^[A-Z0-9]{4}-[A-Z0-9]{4}$"); + } + } + // Whoever enters their code first gets the address. The others can no longer be completed. [Test] public async Task Activate_TwoSignupsForOneAddress_TheFirstToEnterItsCodeGetsIt() diff --git a/API/Controller/Account/Activate.cs b/API/Controller/Account/Activate.cs index 27817baec..57ae8c515 100644 --- a/API/Controller/Account/Activate.cs +++ b/API/Controller/Account/Activate.cs @@ -1,11 +1,10 @@ -using System.ComponentModel.DataAnnotations; -using System.Net.Mime; +using System.Net.Mime; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.RateLimiting; using OpenShock.API.Services.Account; using OpenShock.Common.ApiVersioning; using OpenShock.Common.Authentication; -using OpenShock.Common.Constants; +using OpenShock.Common.DataAnnotations; using OpenShock.Common.Errors; using OpenShock.Internal.Common.Problems; using DbUser = OpenShock.Common.OpenShockDb.User; @@ -61,9 +60,8 @@ public async Task Activate([FromBody] ActivateRequest body, Cance public sealed class ActivateRequest { - /// The code from the activation email. - [Required] - [StringLength(AuthConstants.ActivationCodeLength, MinimumLength = AuthConstants.ActivationCodeLength)] + /// The code from the activation email. Case and the dash do not matter. + [SignupCode] public required string Code { get; init; } } } diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index 6c5cf570a..d11c7efb2 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -373,13 +373,13 @@ public async Task ActivatePendingSignupAsync(Guid pendingSignu // No code mailed yet, the mailed one too old, or guessed at too often: a new one has to be requested. if (pending.CodeSentAt is null || pending.CodeSentAt < DateTime.UtcNow - Duration.ActivationCodeLifetime - || pending.FailedAttempts >= AuthConstants.ActivationCodeMaxAttempts) + || pending.FailedAttempts >= AuthConstants.SignupCodeMaxAttempts) { return new ActivationCodeExpired(); } - var codeMatches = ActivationCode.IsWellFormed(code) && CryptographicOperations.FixedTimeEquals( - Encoding.ASCII.GetBytes(ActivationCode.Hash(pending.Id, code)), + var codeMatches = SignupCode.TryNormalize(code, out var normalizedCode) && CryptographicOperations.FixedTimeEquals( + Encoding.ASCII.GetBytes(SignupCode.Hash(pending.Id, normalizedCode)), Encoding.ASCII.GetBytes(pending.CodeHash)); if (!codeMatches) { @@ -387,7 +387,7 @@ public async Task ActivatePendingSignupAsync(Guid pendingSignu await _db.SaveChangesAsync(cancellationToken); await transaction.CommitAsync(cancellationToken); - return new ActivationCodeInvalid(AuthConstants.ActivationCodeMaxAttempts - pending.FailedAttempts); + return new ActivationCodeInvalid(AuthConstants.SignupCodeMaxAttempts - pending.FailedAttempts); } // A pending signup reserves nothing, so someone else may have taken the address or the username diff --git a/Common/Constants/AuthConstants.cs b/Common/Constants/AuthConstants.cs index f1f77a4fc..911775446 100644 --- a/Common/Constants/AuthConstants.cs +++ b/Common/Constants/AuthConstants.cs @@ -13,10 +13,7 @@ public static class AuthConstants public const int GeneratedTokenLength = 32; - /// Digits in the code mailed to activate a signup. - public const int ActivationCodeLength = 6; - /// Wrong codes a signup may enter before the mailed code stops working and a new one must be requested. - public const int ActivationCodeMaxAttempts = 5; + public const int SignupCodeMaxAttempts = 5; public const int ApiTokenLength = 64; } diff --git a/Common/DataAnnotations/SignupCodeAttribute.cs b/Common/DataAnnotations/SignupCodeAttribute.cs new file mode 100644 index 000000000..2991da717 --- /dev/null +++ b/Common/DataAnnotations/SignupCodeAttribute.cs @@ -0,0 +1,45 @@ +using System.ComponentModel.DataAnnotations; +using System.Text.Json.Nodes; +using Microsoft.OpenApi; +using OpenShock.Common.DataAnnotations.Interfaces; +using OpenShock.Common.Utils; + +namespace OpenShock.Common.DataAnnotations; + +/// +/// An attribute used to validate whether a value has the shape of a signup code, see . +/// It says nothing about whether the code is the right one. +/// +/// +/// Inherits from . +/// +[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)] +public sealed class SignupCodeAttribute : ValidationAttribute, IParameterAttribute +{ + private const string ErrMsgCannotBeNull = "Signup code cannot be null"; + private const string ErrMsgMustBeString = "Signup code must be a string"; + private const string ErrMsgMalformed = "Signup code must be two groups of four letters or digits, like " + SignupCode.Example; + + /// + protected override ValidationResult? IsValid(object? value, ValidationContext validationContext) + { + if (value is null) return new ValidationResult(ErrMsgCannotBeNull); + + if (value is not string code) return new ValidationResult(ErrMsgMustBeString); + + return SignupCode.TryNormalize(code, out _) ? ValidationResult.Success : new ValidationResult(ErrMsgMalformed); + } + + /// + public void Apply(OpenApiSchema schema) + { + schema.Pattern = SignupCode.InputPattern; + schema.Examples = [JsonValue.Create(SignupCode.Example)]; + } + + /// + public void Apply(OpenApiParameter parameter) + { + if (parameter.Schema is OpenApiSchema schema) Apply(schema); + } +} diff --git a/Common/Utils/ActivationCode.cs b/Common/Utils/ActivationCode.cs deleted file mode 100644 index dc0e084b9..000000000 --- a/Common/Utils/ActivationCode.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System.Security.Cryptography; -using OpenShock.Common.Constants; - -namespace OpenShock.Common.Utils; - -/// -/// The short numeric code mailed to complete a signup. It is typed into a browser that holds the signup, -/// so it only has to be unguessable within the few attempts a signup gets -/// ( per mailed code), not on its own. -/// -public static class ActivationCode -{ - private static readonly int Exclusive = (int)Math.Pow(10, AuthConstants.ActivationCodeLength); - - public static string Generate() - => RandomNumberGenerator.GetInt32(Exclusive).ToString($"D{AuthConstants.ActivationCodeLength}"); - - /// - /// Hash stored for a code. Bound to the signup it was mailed for: with so few possible codes, a bare - /// hash would be the same for every signup that happened to get the same digits. - /// - public static string Hash(Guid pendingSignupId, string code) - => HashingUtils.HashToken($"{pendingSignupId:N}:{code}"); - - /// Whether has the shape of a code at all, before anything is looked up. - public static bool IsWellFormed(string? code) - => code is { Length: AuthConstants.ActivationCodeLength } && code.All(char.IsAsciiDigit); -} diff --git a/Common/Utils/SignupCode.cs b/Common/Utils/SignupCode.cs new file mode 100644 index 000000000..595779331 --- /dev/null +++ b/Common/Utils/SignupCode.cs @@ -0,0 +1,82 @@ +using System.Diagnostics.CodeAnalysis; +using System.Security.Cryptography; +using OpenShock.Common.Constants; + +namespace OpenShock.Common.Utils; + +/// +/// The short code mailed to complete a signup: two groups of four uppercase letters and digits, like +/// ABCD-1234. It is typed into a browser that holds the signup, so it only has to be unguessable +/// within the few attempts a signup gets ( per mailed +/// code), not on its own. +/// +public static class SignupCode +{ + /// Characters a code is made of. + public const string Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + + /// Characters in each of the two groups. + public const int GroupLength = 4; + + public const char Separator = '-'; + + /// Length of a code as mailed and stored, separator included. + public const int Length = GroupLength * 2 + 1; + + /// + /// What a code looks like as typed. Lowercase and a left out separator are accepted here and put right + /// by : both are how people copy a code off another screen. + /// + public const string InputPattern = "^[A-Za-z0-9]{4}-?[A-Za-z0-9]{4}$"; + + public const string Example = "ABCD-1234"; + + public static string Generate() + { + var characters = RandomNumberGenerator.GetString(Alphabet, GroupLength * 2); + return string.Concat(characters.AsSpan(0, GroupLength), [Separator], characters.AsSpan(GroupLength)); + } + + /// + /// Brings a code as typed into the form it was mailed in: uppercase, with the separator. False when + /// it is not a code at all. + /// + public static bool TryNormalize(string? input, [NotNullWhen(true)] out string? code) + { + code = null; + if (input is null) return false; + + var typed = input.AsSpan().Trim(); + if (typed.Length == Length) + { + if (typed[GroupLength] != Separator) return false; + } + else if (typed.Length != GroupLength * 2) + { + return false; + } + + Span normalized = stackalloc char[Length]; + var written = 0; + for (var i = 0; i < typed.Length; i++) + { + if (typed.Length == Length && i == GroupLength) continue; + + var character = char.ToUpperInvariant(typed[i]); + if (!char.IsAsciiLetterUpper(character) && !char.IsAsciiDigit(character)) return false; + + if (written == GroupLength) normalized[written++] = Separator; + normalized[written++] = character; + } + + code = new string(normalized); + return true; + } + + /// + /// Hash stored for a code, which must be in its mailed form (see ). Bound to + /// the signup it was mailed for, so a hash says nothing about any other signup. + /// + public static string Hash(Guid pendingSignupId, string code) + => HashingUtils.HashToken($"{pendingSignupId:N}:{code}"); +} diff --git a/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs b/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs index f45f29c7f..e37e18189 100644 --- a/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs +++ b/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs @@ -183,7 +183,7 @@ public async Task AccountActivation_IsDelivered_AndEmailedCodeMatchesStoredHash( // The mail carries a code to type in, and nothing to click that would complete the signup. var full = await mailpit.GetMessageAsync(message!.Id); - var code = Regex.Match(full!.Html, @">\s*(\d{6})\s*<").Groups[1].Value; + var code = Regex.Match(full!.Html, @">\s*([A-Z0-9]{4}-[A-Z0-9]{4})\s*<").Groups[1].Value; await Assert.That(code).IsNotEmpty(); await Assert.That(full.Html).DoesNotContain("activate?"); @@ -191,7 +191,7 @@ public async Task AccountActivation_IsDelivered_AndEmailedCodeMatchesStoredHash( { var pending = await db.PendingSignups.AsNoTracking().SingleAsync(p => p.Id == pendingSignupId); await Assert.That(pending.CodeHash).IsNotEqualTo(seededHash); - await Assert.That(pending.CodeHash).IsEqualTo(ActivationCode.Hash(pendingSignupId, code)); + await Assert.That(pending.CodeHash).IsEqualTo(SignupCode.Hash(pendingSignupId, code)); await Assert.That(pending.CodeSentAt).IsNotNull(); // A new code starts with all its attempts. await Assert.That(pending.FailedAttempts).IsEqualTo(0); diff --git a/Cron/Services/Email/Outbox/EmailOutboxDispatcher.cs b/Cron/Services/Email/Outbox/EmailOutboxDispatcher.cs index 682d5b1e7..b9196d7fa 100644 --- a/Cron/Services/Email/Outbox/EmailOutboxDispatcher.cs +++ b/Cron/Services/Email/Outbox/EmailOutboxDispatcher.cs @@ -73,8 +73,8 @@ private async Task SendAccountActivation(EmailOutboxMessage // The code is minted here and only its hash stored, so the queue never holds a usable one, and // each mail replaces the code of the one before it. A new code starts with all its attempts. // Waits for an attempt to enter the previous code that is in flight right now (it locks the row). - var code = ActivationCode.Generate(); - var codeHash = ActivationCode.Hash(pendingSignupId, code); + var code = SignupCode.Generate(); + var codeHash = SignupCode.Hash(pendingSignupId, code); var now = DateTime.UtcNow; var minted = await db.PendingSignups .Where(p => p.Id == pendingSignupId) @@ -144,7 +144,7 @@ private async Task SendPreview(EmailOutboxMessage message, return message.Type switch { - EmailType.AccountActivation => FromSend(await _emailService.ActivateAccount(to, "123456", ct)), + EmailType.AccountActivation => FromSend(await _emailService.ActivateAccount(to, SignupCode.Example, ct)), EmailType.PasswordReset => FromSend(await _emailService.PasswordReset(to, link, ct)), EmailType.EmailVerification => FromSend(await _emailService.VerifyEmail(to, link, ct)), EmailType.EmailChangeNotice => FromSend(await _emailService.EmailChangeNotice(to, "new-address@example.com", ct)), diff --git a/Cron/SmtpTemplates/AccountActivation.liquid b/Cron/SmtpTemplates/AccountActivation.liquid index fd8f5b05d..36b526e65 100644 --- a/Cron/SmtpTemplates/AccountActivation.liquid +++ b/Cron/SmtpTemplates/AccountActivation.liquid @@ -89,7 +89,7 @@ Your OpenShock activation code OpenShock account.

+ style='font-size:28px;line-height:36px;font-family:ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;background-color:#f4f4f5;border:1px solid #e4e4e7;border-radius:8px;padding:14px 16px;margin:4px 0 20px;font-weight:600;letter-spacing:4px;text-align:center;color:#09090b;margin-top:4px;margin-right:0;margin-bottom:20px;margin-left:0'> {{ ActivationCode }}

Date: Sun, 29 Nov 2026 17:48:50 +0100 Subject: [PATCH 20/20] maybe fix --- .../Helpers/PendingSignupHelper.cs | 16 +-- .../Tests/SignupActivationTests.cs | 126 ++++++++++++------ .../Tests/SignupBrowserCookieCountryTests.cs | 2 + API/Controller/Account/Activate.cs | 60 ++++++++- API/Controller/Account/LoginV2.cs | 6 +- API/Controller/Account/ResendActivation.cs | 8 +- API/Controller/Account/SignupV2.cs | 5 +- API/Controller/OAuth/HandOff.cs | 4 +- API/Controller/OAuth/SignupFinalize.cs | 2 +- API/Services/Account/AccountService.cs | 28 ++++ API/Services/Account/IAccountService.cs | 13 ++ .../Authentication/ActivationResendCookie.cs | 92 ------------- .../UserSessionAuthentication.cs | 4 +- Common/Authentication/SignupBrowserCookie.cs | 13 +- Common/Constants/AuthConstants.cs | 1 - Common/OpenShockControllerBase.cs | 4 +- 16 files changed, 209 insertions(+), 175 deletions(-) delete mode 100644 Common/Authentication/ActivationResendCookie.cs diff --git a/API.IntegrationTests/Helpers/PendingSignupHelper.cs b/API.IntegrationTests/Helpers/PendingSignupHelper.cs index 24b8710cb..248cc7d8e 100644 --- a/API.IntegrationTests/Helpers/PendingSignupHelper.cs +++ b/API.IntegrationTests/Helpers/PendingSignupHelper.cs @@ -91,20 +91,13 @@ public static async Task> FindByEmailAsync(WebApplicationFac return await db.Users.AsNoTracking().FirstOrDefaultAsync(u => u.Email == email); } - ///

The cookie that lets a browser enter the code, as the API would have set it over HTTPS. + /// The cookie that marks a browser as holding the signup, as the API would have set it over HTTPS. public static string MintSignupBrowserCookie(WebApplicationFactory factory, Guid pendingSignupId, string? countryCode = null) { var provider = factory.Services.GetRequiredService(); return $"{AuthConstants.SignupBrowserSecureCookieName}={SignupBrowserCookie.CreateToken(provider, pendingSignupId, countryCode)}"; } - /// The cookie that lets a browser ask for the code again. - public static string MintResendCookie(WebApplicationFactory factory, Guid pendingSignupId) - { - var provider = factory.Services.GetRequiredService(); - return $"{AuthConstants.ActivationResendCookieName}={ActivationResendCookie.CreateToken(provider, pendingSignupId)}"; - } - /// The name=value part of a cookie a response sets, ready to send back in a Cookie header. public static string ReadSetCookie(HttpResponseMessage response, string name) => response.Headers.GetValues("Set-Cookie").Single(c => c.StartsWith(name + "=")).Split(';')[0]; @@ -137,6 +130,13 @@ public static Task PostActivateAsync(HttpClient client, str return client.SendAsync(request); } + public static Task GetPendingActivationAsync(HttpClient client, string? cookie) + { + var request = new HttpRequestMessage(HttpMethod.Get, "/1/account/activate"); + if (cookie is not null) request.Headers.Add("Cookie", cookie); + return client.SendAsync(request); + } + public static Task PostResendAsync(HttpClient client, string? cookie) { var request = new HttpRequestMessage(HttpMethod.Post, "/1/account/activate/resend"); diff --git a/API.IntegrationTests/Tests/SignupActivationTests.cs b/API.IntegrationTests/Tests/SignupActivationTests.cs index 7e5daa7a5..945ad93a9 100644 --- a/API.IntegrationTests/Tests/SignupActivationTests.cs +++ b/API.IntegrationTests/Tests/SignupActivationTests.cs @@ -55,18 +55,6 @@ public async Task Signup_CreatesNoAccount_AndEnqueuesTheActivationCode() await Assert.That(row.Payload[EmailOutboxPayloadKeys.PendingSignupId]).IsEqualTo(pending.Id.ToString()); } - [Test] - public async Task Signup_SetsTheResendCookie_ReadableByTheFrontend() - { - using var client = CreateClient(); - var response = await PostSignupAsync(client, TestHelper.UniqueEmail("signup-resendcookie"), TestHelper.UniqueUsername("signupresendcookie")); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - - // The frontend offers the code form and the resend button only while the cookie exists. - var cookie = response.Headers.GetValues("Set-Cookie").Single(c => c.StartsWith(AuthConstants.ActivationResendCookieName + "=")); - await Assert.That(cookie.Contains("httponly", StringComparison.OrdinalIgnoreCase)).IsFalse(); - } - [Test] public async Task Signup_SetsTheSignupBrowserCookie_BoundToTheApiHost() { @@ -252,17 +240,15 @@ public async Task Activate_CodeFromTheMail_InTheSignupBrowser_CreatesTheAccount( using var client = CreateClient(); var signup = await PostSignupAsync(client, email, username); - // Both cookies of the signup, as the browser that made it sends them. - var cookie = $"{ReadSetCookie(signup, AuthConstants.SignupBrowserSecureCookieName)}; {ReadSetCookie(signup, AuthConstants.ActivationResendCookieName)}"; + var cookie = ReadSetCookie(signup, AuthConstants.SignupBrowserSecureCookieName); var pending = (await FindByEmailAsync(WebApplicationFactory, email)).Single(); var code = await MailCodeAsync(WebApplicationFactory, pending.Id); var response = await PostActivateAsync(client, code, cookie); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - // The cookies have done their job. + // The cookie has done its job. await Assert.That(DeletesCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsTrue(); - await Assert.That(DeletesCookie(response, AuthConstants.ActivationResendCookieName)).IsTrue(); var user = await FindUserByEmailAsync(WebApplicationFactory, email); await Assert.That(user).IsNotNull(); @@ -314,21 +300,6 @@ public async Task Activate_CodeOfAnotherSignupForTheSameAddress_Returns400() await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); } - [Test] - public async Task Activate_ResendCookieAlone_Returns400() - { - // The resend cookie is shared across the cookie domain and readable by script, so it proves nothing. - var email = TestHelper.UniqueEmail("activate-resendcookie"); - var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("activateresendcookie")); - var code = await MailCodeAsync(WebApplicationFactory, pendingId); - - using var client = CreateClient(); - var response = await PostActivateAsync(client, code, MintResendCookie(WebApplicationFactory, pendingId)); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); - await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); - } - [Test] public async Task Activate_SignupBrowserCookieWithoutHostPrefix_Returns400() { @@ -558,6 +529,78 @@ public async Task Activate_Twice_SecondReturns400() await Assert.That(await again.Content.ReadAsStringAsync()).Contains("Account.Activation.NotFound"); } + // --- What a browser can find out about the signup it holds --- + + // The cookie cannot be read by script, so this is how a frontend knows to offer the code form. + [Test] + public async Task GetPendingActivation_BrowserHoldingASignup_ReturnsWhereTheCodeWent_AndWhenItCanBeResent() + { + var email = TestHelper.UniqueEmail("pending-status"); + var username = TestHelper.UniqueUsername("pendingstatus"); + using var client = CreateClient(); + var signup = await PostSignupAsync(client, email, username); + var cookie = ReadSetCookie(signup, AuthConstants.SignupBrowserSecureCookieName); + + var response = await GetPendingActivationAsync(client, cookie); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + await Assert.That(body.RootElement.GetProperty("email").GetString()).IsEqualTo(email); + await Assert.That(body.RootElement.GetProperty("username").GetString()).IsEqualTo(username); + // The signup mail was just queued: four left today, and the cooldown is running. + await Assert.That(body.RootElement.GetProperty("resendsRemaining").GetInt32()).IsEqualTo(4); + await Assert.That(body.RootElement.GetProperty("resendAvailableAt").GetDateTime().ToUniversalTime()).IsGreaterThan(DateTime.UtcNow); + + // What it says is what a resend does. + await Assert.That((await PostResendAsync(client, cookie)).StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests); + await BackdateOutboxAsync(email, Duration.ActivationResendCooldown + TimeSpan.FromMinutes(1)); + using var later = JsonDocument.Parse(await (await GetPendingActivationAsync(client, cookie)).Content.ReadAsStringAsync()); + await Assert.That(later.RootElement.GetProperty("resendAvailableAt").GetDateTime().ToUniversalTime()).IsLessThanOrEqualTo(DateTime.UtcNow); + await Assert.That((await PostResendAsync(client, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); + } + + [Test] + public async Task GetPendingActivation_AddressAtItsDailyCapThroughOtherSignups_HasNoResendsLeft() + { + var email = TestHelper.UniqueEmail("pending-status-cap"); + using var client = CreateClient(); + for (var i = 0; i < 5; i++) + { + await PostSignupAsync(client, email, TestHelper.UniqueUsername("pendingstatuscap")); + } + var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("pendingstatuscap")); + + var response = await GetPendingActivationAsync(client, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); + + using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync()); + await Assert.That(body.RootElement.GetProperty("resendsRemaining").GetInt32()).IsEqualTo(0); + } + + [Test] + public async Task GetPendingActivation_NoCookie_Returns400() + { + using var client = CreateClient(); + var response = await GetPendingActivationAsync(client, cookie: null); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Account.Activation.NotFound"); + } + + [Test] + public async Task GetPendingActivation_SignupAlreadyCompleted_Returns400_AndRemovesCookie() + { + var pendingId = await CreateInDbAsync(WebApplicationFactory, TestHelper.UniqueEmail("pending-status-done"), TestHelper.UniqueUsername("pendingstatusdone")); + var code = await MailCodeAsync(WebApplicationFactory, pendingId); + var cookie = MintSignupBrowserCookie(WebApplicationFactory, pendingId); + + using var client = CreateClient(); + await Assert.That((await PostActivateAsync(client, code, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); + + var response = await GetPendingActivationAsync(client, cookie); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(DeletesCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsTrue(); + } + // --- Asking for the code again --- [Test] @@ -567,7 +610,7 @@ public async Task ResendActivation_WithSignupCookie_EnqueuesAnotherActivationCod using var client = CreateClient(); var signup = await PostSignupAsync(client, email, TestHelper.UniqueUsername("resendok")); - var cookie = ReadSetCookie(signup, AuthConstants.ActivationResendCookieName); + var cookie = ReadSetCookie(signup, AuthConstants.SignupBrowserSecureCookieName); var pending = (await FindByEmailAsync(WebApplicationFactory, email)).Single(); // Move the signup email out of the resend cooldown. @@ -591,7 +634,7 @@ public async Task ResendActivation_WithinCooldown_Returns429_AndEnqueuesNothing( { var email = TestHelper.UniqueEmail("resend-cooldown"); var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("resendcooldown")); - var cookie = MintResendCookie(WebApplicationFactory, pendingId); + var cookie = MintSignupBrowserCookie(WebApplicationFactory, pendingId); using var client = CreateClient(); await Assert.That((await PostResendAsync(client, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); @@ -605,7 +648,7 @@ public async Task ResendActivation_DailyCapReached_Returns429() { var email = TestHelper.UniqueEmail("resend-cap"); var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("resendcap")); - var cookie = MintResendCookie(WebApplicationFactory, pendingId); + var cookie = MintSignupBrowserCookie(WebApplicationFactory, pendingId); using var client = CreateClient(); for (var i = 0; i < 5; i++) @@ -631,7 +674,7 @@ public async Task ResendActivation_AddressAtItsDailyCapThroughOtherSignups_Retur } var pendingId = await CreateInDbAsync(WebApplicationFactory, email, TestHelper.UniqueUsername("resendaddresscap")); - var response = await PostResendAsync(client, MintResendCookie(WebApplicationFactory, pendingId)); + var response = await PostResendAsync(client, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests); await Assert.That(await CountOutboxAsync(email)).IsEqualTo(5); @@ -647,9 +690,9 @@ public async Task ResendActivation_SignupAlreadyCompleted_Returns400_AndRemovesC using var client = CreateClient(); await Assert.That((await PostActivateAsync(client, code, MintSignupBrowserCookie(WebApplicationFactory, pendingId))).StatusCode).IsEqualTo(HttpStatusCode.OK); - var response = await PostResendAsync(client, MintResendCookie(WebApplicationFactory, pendingId)); + var response = await PostResendAsync(client, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); - await Assert.That(DeletesCookie(response, AuthConstants.ActivationResendCookieName)).IsTrue(); + await Assert.That(DeletesCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsTrue(); await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); } @@ -663,12 +706,11 @@ public async Task ResendActivation_NoCookie_Returns400() } [Test] - public async Task ResendActivation_TamperedCookie_Returns400_AndRemovesCookie() + public async Task ResendActivation_TamperedCookie_Returns400() { using var client = CreateClient(); - var response = await PostResendAsync(client, $"{AuthConstants.ActivationResendCookieName}=not-a-valid-token"); + var response = await PostResendAsync(client, $"{AuthConstants.SignupBrowserSecureCookieName}=not-a-valid-token"); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); - await Assert.That(DeletesCookie(response, AuthConstants.ActivationResendCookieName)).IsTrue(); } // --- Signing in with what a pending signup was started with --- @@ -773,10 +815,10 @@ public async Task Login_Success_RemovesTheSignupCookies() var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("loginclears"), email, Password); using var client = CreateClient(); - var response = await PostLoginAsync(client, email, Password, MintResendCookie(WebApplicationFactory, userId)); + var response = await PostLoginAsync(client, email, Password, MintSignupBrowserCookie(WebApplicationFactory, userId)); await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - await Assert.That(DeletesCookie(response, AuthConstants.ActivationResendCookieName)).IsTrue(); + await Assert.That(DeletesCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsTrue(); } // --- helpers --- diff --git a/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs b/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs index c74ddff12..a55f899f0 100644 --- a/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs +++ b/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs @@ -44,6 +44,8 @@ public async Task Activate_FromAnotherCountry_IgnoresTheCookie() await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); + // Only ignored, not removed: it works again from where the signup was made. + await Assert.That(DeletesCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsFalse(); // The signup itself is untouched, and signing in with its password holds it from here as well. WebApplicationFactory.ClientCountryCode = "DE"; diff --git a/API/Controller/Account/Activate.cs b/API/Controller/Account/Activate.cs index 57ae8c515..5186d93d6 100644 --- a/API/Controller/Account/Activate.cs +++ b/API/Controller/Account/Activate.cs @@ -35,18 +35,16 @@ public sealed partial class AccountController [ProducesResponseType(StatusCodes.Status409Conflict, MediaTypeNames.Application.ProblemJson)] // UsernameOrEmailExists public async Task Activate([FromBody] ActivateRequest body, CancellationToken cancellationToken) { + // An unusable cookie is left in place: it may only be unusable from here (see the country check in + // SignupBrowserCookie), and it expires on its own. if (!SignupBrowserCookie.TryGetSignupId(HttpContext, out var signupId)) - { - // Tampered or expired (a no-op when there is no cookie), so the frontend stops offering the form. - ActivationResendCookie.Remove(HttpContext); return Problem(AccountError.AccountActivationNotFound); - } var result = await _accountService.ActivatePendingSignupAsync(signupId.Value, body.Code, cancellationToken); - // Completed or gone: the cookies have nothing left to do. + // Completed or gone: the cookie has nothing left to do. if (result is DbUser or Results.NotFound) - ActivationResendCookie.Remove(HttpContext); + SignupBrowserCookie.Remove(HttpContext); return result switch { @@ -58,6 +56,56 @@ public async Task Activate([FromBody] ActivateRequest body, Cance }; } + /// + /// The signup this browser holds and can complete, if any + /// + /// + /// The cookie that marks a browser as holding a signup is not readable by script, so this is how a + /// frontend finds out whether to offer the code form, which address the code went to, and whether a + /// new code can be requested yet. + /// + /// This browser holds a pending signup + /// This browser holds no pending signup + [HttpGet("activate")] + [ApiVersion(1)] + [ResponseCache(NoStore = true)] + [ProducesResponseType(StatusCodes.Status200OK, MediaTypeNames.Application.Json)] + [ProducesResponseType(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] // AccountActivationNotFound + public async Task GetPendingActivation(CancellationToken cancellationToken) + { + if (!SignupBrowserCookie.TryGetSignupId(HttpContext, out var signupId)) + return Problem(AccountError.AccountActivationNotFound); + + var status = await _accountService.GetPendingSignupStatusAsync(signupId.Value, cancellationToken); + if (status is null) + { + SignupBrowserCookie.Remove(HttpContext); + return Problem(AccountError.AccountActivationNotFound); + } + + return Ok(new PendingActivationResponse + { + Email = status.Email, + Username = status.Username, + ResendAvailableAt = status.ResendAvailableAt, + ResendsRemaining = status.ResendsRemaining + }); + } + + public sealed class PendingActivationResponse + { + /// The address the code was mailed to. + public required string Email { get; init; } + + public required string Username { get; init; } + + /// When a new code can be requested. In the past when one can be requested now. + public required DateTime ResendAvailableAt { get; init; } + + /// How many more codes can be requested today. At zero a resend is refused whatever the time. + public required int ResendsRemaining { get; init; } + } + public sealed class ActivateRequest { /// The code from the activation email. Case and the dash do not matter. diff --git a/API/Controller/Account/LoginV2.cs b/API/Controller/Account/LoginV2.cs index c47637ca9..e49448ac1 100644 --- a/API/Controller/Account/LoginV2.cs +++ b/API/Controller/Account/LoginV2.cs @@ -55,7 +55,7 @@ public async Task LoginV2( AccountDeactivated => Problem(AccountError.AccountDeactivated), AccountNotActivated => Problem(AccountError.AccountNotActivated), AccountIsOAuthOnly => Problem(AccountError.AccountOAuthOnly), - PendingSignupCredentials pending => await ResumeSignupAndRejectAsync(pending.PendingSignupId, cookieDomain) + PendingSignupCredentials pending => await ResumeSignupAndRejectAsync(pending.PendingSignupId) }; async Task CompleteLoginAsync(User account, string domain) @@ -74,9 +74,9 @@ async Task CompleteLoginAsync(User account, string domain) // The password is the one a signup was started with, so the caller is whoever started it: this // browser holds the signup from now on and can enter its code. A new code is mailed as well (rate // limited inside the service), and the response is the same whether or not a mail went out. - async Task ResumeSignupAndRejectAsync(Guid pendingSignupId, string domain) + async Task ResumeSignupAndRejectAsync(Guid pendingSignupId) { - ActivationResendCookie.Set(HttpContext, pendingSignupId, domain); + SignupBrowserCookie.Set(HttpContext, pendingSignupId); try { diff --git a/API/Controller/Account/ResendActivation.cs b/API/Controller/Account/ResendActivation.cs index b1bfa36ad..f2580e2a3 100644 --- a/API/Controller/Account/ResendActivation.cs +++ b/API/Controller/Account/ResendActivation.cs @@ -16,7 +16,7 @@ public sealed partial class AccountController /// Mail a new activation code for the signup this browser holds /// /// - /// Identifies the signup by the activation-resend cookie, not by an email address, so it can only target + /// Identifies the signup by the signup cookie, not by an email address, so it can only target /// a signup this browser started (or signed in to) and can't be used to probe registered emails. The new /// code replaces the previous one. /// @@ -31,10 +31,8 @@ public sealed partial class AccountController [ProducesResponseType(StatusCodes.Status429TooManyRequests, MediaTypeNames.Application.ProblemJson)] // AccountActivationResendTooMany public async Task ResendActivation(CancellationToken cancellationToken) { - if (!ActivationResendCookie.TryGetSignupId(HttpContext, out var signupId)) + if (!SignupBrowserCookie.TryGetSignupId(HttpContext, out var signupId)) { - // Tampered or expired (a no-op when there is no cookie), so the frontend stops offering the button. - ActivationResendCookie.Remove(HttpContext); return Problem(AccountError.AccountActivationResendUnavailable); } @@ -42,7 +40,7 @@ public async Task ResendActivation(CancellationToken cancellation // Completed or gone: the cookie has nothing left to do. if (result is Results.NotFound) - ActivationResendCookie.Remove(HttpContext); + SignupBrowserCookie.Remove(HttpContext); return result switch { diff --git a/API/Controller/Account/SignupV2.cs b/API/Controller/Account/SignupV2.cs index bad29d7a7..1bef62887 100644 --- a/API/Controller/Account/SignupV2.cs +++ b/API/Controller/Account/SignupV2.cs @@ -59,10 +59,7 @@ public async Task SignUpV2( IActionResult CompleteSignup(PendingSignup pending) { // Lets this browser enter the code mailed to the address, and ask for it again. - if (GetCurrentCookieDomain() is { } cookieDomain) - { - ActivationResendCookie.Set(HttpContext, pending.Id, cookieDomain); - } + SignupBrowserCookie.Set(HttpContext, pending.Id); return Ok(); } diff --git a/API/Controller/OAuth/HandOff.cs b/API/Controller/OAuth/HandOff.cs index 4856d7c03..00b7f653f 100644 --- a/API/Controller/OAuth/HandOff.cs +++ b/API/Controller/OAuth/HandOff.cs @@ -86,9 +86,9 @@ await _accountService.IsEmailRegisteredAsync(externalEmail, cancellationToken)) // signup form lets someone who mistyped their email start over with the right one instead // of waiting for a mail that never arrives (see OAuthSignupFinalize). var pending = await _accountService.GetPendingSignupByOAuthIdentityAsync(provider, auth.ExternalAccountId, cancellationToken); - if (pending is not null && GetCurrentCookieDomain() is { } pendingCookieDomain) + if (pending is not null) { - ActivationResendCookie.Set(HttpContext, pending.Id, pendingCookieDomain); + SignupBrowserCookie.Set(HttpContext, pending.Id); try { diff --git a/API/Controller/OAuth/SignupFinalize.cs b/API/Controller/OAuth/SignupFinalize.cs index 54622ead1..d60ce9b26 100644 --- a/API/Controller/OAuth/SignupFinalize.cs +++ b/API/Controller/OAuth/SignupFinalize.cs @@ -122,7 +122,7 @@ public async Task OAuthSignupFinalize( case PendingSignup pending: // Lets this browser enter the code mailed to the address, and ask for it again. - ActivationResendCookie.Set(HttpContext, pending.Id, domain); + SignupBrowserCookie.Set(HttpContext, pending.Id); await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); return Ok(LoginV2OkResponse.FromPendingSignup(pending)); diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index d11c7efb2..2f21c085f 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -463,6 +463,34 @@ await _auditService.LogAsync( return user; } + /// + public async Task GetPendingSignupStatusAsync(Guid pendingSignupId, CancellationToken cancellationToken = default) + { + var pending = await LivePendingSignups() + .AsNoTracking() + .Where(p => p.Id == pendingSignupId) + .Select(p => new { p.Email, p.Username }) + .FirstOrDefaultAsync(cancellationToken); + if (pending is null) return null; + + // The same counts ResendActivationCodeAsync refuses on, read without its locks: this only tells a + // frontend what to expect, the resend itself decides. + var coalesceKey = EmailOutboxCoalesceKeys.AccountActivation(pendingSignupId); + var windowStart = DateTime.UtcNow - Duration.ActivationResendWindow; + var sentForSignup = await _db.EmailOutbox + .Where(m => m.CoalesceKey == coalesceKey && m.CreatedAt >= windowStart) + .Select(m => m.CreatedAt) + .ToListAsync(cancellationToken); + var sentToAddress = await _db.EmailOutbox.CountAsync( + m => m.Recipient == pending.Email && m.Type == EmailType.AccountActivation && m.CreatedAt >= windowStart, + cancellationToken); + + var resendAvailableAt = sentForSignup.Count == 0 ? DateTime.UtcNow : sentForSignup.Max() + Duration.ActivationResendCooldown; + var resendsRemaining = Math.Max(0, MaxActivationEmailsPerWindow - Math.Max(sentForSignup.Count, sentToAddress)); + + return new PendingSignupStatus(pending.Email, pending.Username, resendAvailableAt, resendsRemaining); + } + /// public async Task> ResendActivationCodeAsync(Guid pendingSignupId, CancellationToken cancellationToken = default) { diff --git a/API/Services/Account/IAccountService.cs b/API/Services/Account/IAccountService.cs index 54ee176d2..51fae60ad 100644 --- a/API/Services/Account/IAccountService.cs +++ b/API/Services/Account/IAccountService.cs @@ -69,6 +69,13 @@ public interface IAccountService /// Task ActivatePendingSignupAsync(Guid pendingSignupId, string code, CancellationToken cancellationToken = default); + /// + /// What a browser holding a pending signup needs to show its code form: where the code went, and + /// whether would mail another one. Only call this for a caller + /// who holds the signup. Null when there is no such signup (any more). + /// + Task GetPendingSignupStatusAsync(Guid pendingSignupId, CancellationToken cancellationToken = default); + /// /// Mails a pending signup a new activation code, which replaces the previous one. Only call this for a /// caller who holds the signup or its credential. Rate limited per signup: one email per 10 minutes, @@ -205,6 +212,12 @@ public sealed record ActivationCodeInvalid(int AttemptsRemaining); public sealed class ActivationCodeExpired; +/// +/// +/// When the resend cooldown ends. In the past when it is not running. +/// Activation mails left in the window, for the signup and for its address, whichever is fewer. +public sealed record PendingSignupStatus(string Email, string Username, DateTime ResendAvailableAt, int ResendsRemaining); + /// /// The credentials are not those of an account, but of a signup that was never completed. Whoever sent /// them is whoever started it. diff --git a/Common/Authentication/ActivationResendCookie.cs b/Common/Authentication/ActivationResendCookie.cs deleted file mode 100644 index 70be718b2..000000000 --- a/Common/Authentication/ActivationResendCookie.cs +++ /dev/null @@ -1,92 +0,0 @@ -using System.Diagnostics.CodeAnalysis; -using System.Security.Cryptography; -using Microsoft.AspNetCore.DataProtection; -using OpenShock.Common.Constants; -using OpenShock.Common.Options; - -namespace OpenShock.Common.Authentication; - -/// -/// Cookie set while this browser has a signup waiting for its activation code. It tells the frontend that -/// there is one (so it can offer the code form and the "didn't get the email?" button) and lets the browser -/// ask for the code again 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 pending signup's id (keys are persisted to -/// the database, so every API instance can read it); it cannot be forged or pointed at another signup. -/// -/// Deliberately not HttpOnly: the frontend is a static SPA and reads the cookie's presence to decide what to -/// show. 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) codes to that signup's own inbox. -/// -/// -/// It is not proof of anything else. What lets a browser enter the code is -/// , which is set and removed together with this one. -/// -/// -public static class ActivationResendCookie -{ - private const string ProtectorPurpose = "OpenShock.ActivationResendCookie"; - - public static string CreateToken(IDataProtectionProvider provider, Guid signupId) - => GetProtector(provider).Protect(signupId.ToString(), Duration.ActivationResendWindow); - - public static void Set(HttpContext context, Guid signupId, string domain) - { - var provider = context.RequestServices.GetRequiredService(); - var frontendOptions = context.RequestServices.GetRequiredService(); - - context.Response.Cookies.Append(AuthConstants.ActivationResendCookieName, CreateToken(provider, signupId), new CookieOptions - { - Expires = DateTimeOffset.UtcNow.Add(Duration.ActivationResendWindow), - Secure = context.Request.IsHttps || frontendOptions.CookieSecure, - HttpOnly = false, - SameSite = SameSiteMode.Lax, - Domain = domain - }); - - SignupBrowserCookie.Set(context, signupId); - } - - public static bool TryGetSignupId(HttpContext context, [NotNullWhen(true)] out Guid? signupId) - { - signupId = null; - if (!context.Request.Cookies.TryGetValue(AuthConstants.ActivationResendCookieName, 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; - signupId = id; - return true; - } - catch (CryptographicException) - { - // Tampered, expired, or signed with a revoked key. - return false; - } - } - - /// 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; - - // A service without frontend options (the LiveControlGateway) never issues this cookie and does not - // know the domains to remove it from: leave it for the API, rather than fail the request over it. - var frontendOptions = context.RequestServices.GetService(); - if (frontendOptions is null) return; - - foreach (var domain in frontendOptions.CookieDomains) - { - context.Response.Cookies.Delete(AuthConstants.ActivationResendCookieName, new CookieOptions { Domain = domain }); - } - } - - private static ITimeLimitedDataProtector GetProtector(IDataProtectionProvider provider) - => provider.CreateProtector(ProtectorPurpose).ToTimeLimitedDataProtector(); -} diff --git a/Common/Authentication/AuthenticationHandlers/UserSessionAuthentication.cs b/Common/Authentication/AuthenticationHandlers/UserSessionAuthentication.cs index e15dffda3..2e722d1d4 100644 --- a/Common/Authentication/AuthenticationHandlers/UserSessionAuthentication.cs +++ b/Common/Authentication/AuthenticationHandlers/UserSessionAuthentication.cs @@ -70,8 +70,8 @@ protected override async Task HandleAuthenticateAsync() Context.SetItemByType(session); Context.SetItemByType(user); - // An authenticated (hence activated) session has no use for the post-signup resend cookie. - ActivationResendCookie.Remove(Context); + // Signed in to an account, so a signup this browser still held has nothing left to do here. + SignupBrowserCookie.Remove(Context); List claims = [ diff --git a/Common/Authentication/SignupBrowserCookie.cs b/Common/Authentication/SignupBrowserCookie.cs index caa667b00..46dc8e249 100644 --- a/Common/Authentication/SignupBrowserCookie.cs +++ b/Common/Authentication/SignupBrowserCookie.cs @@ -15,13 +15,12 @@ namespace OpenShock.Common.Authentication; /// cannot be completed by the person the mail went to. /// /// -/// 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 complete the -/// signup for them. 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 is the only trace of the signup in the browser, and it is a credential, so nothing but the API gets +/// to see it: HttpOnly, no Domain, and over HTTPS the __Host- name prefix, which +/// browsers refuse to accept from anything but this exact host. A cookie shared across the cookie domain +/// could be planted by any sibling subdomain, and planting this one would let someone who signed up with +/// another person's address have that person complete the signup for them. The frontend cannot read it +/// either; it asks the API whether this browser holds a signup (GET /1/account/activate). /// /// It also carries the country the signup came from, when that could be resolved. Presented from a /// different country it is ignored, and the signup has to be started (or signed in to) again. Country and diff --git a/Common/Constants/AuthConstants.cs b/Common/Constants/AuthConstants.cs index 911775446..54319ca0c 100644 --- a/Common/Constants/AuthConstants.cs +++ b/Common/Constants/AuthConstants.cs @@ -3,7 +3,6 @@ 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"; diff --git a/Common/OpenShockControllerBase.cs b/Common/OpenShockControllerBase.cs index 2c29881ec..29042daec 100644 --- a/Common/OpenShockControllerBase.cs +++ b/Common/OpenShockControllerBase.cs @@ -118,8 +118,8 @@ protected async Task CreateSession(Guid accountId, string domain, Guid? se Domain = domain }); - // Signed in, so the post-signup "didn't get the email?" cookie has served its purpose. - ActivationResendCookie.Remove(HttpContext); + // Signed in, so the cookie of a signup this browser held has served its purpose. + SignupBrowserCookie.Remove(HttpContext); return true; }