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/Helpers/PendingSignupHelper.cs b/API.IntegrationTests/Helpers/PendingSignupHelper.cs new file mode 100644 index 000000000..248cc7d8e --- /dev/null +++ b/API.IntegrationTests/Helpers/PendingSignupHelper.cs @@ -0,0 +1,161 @@ +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, string? code = null) + { + code ??= SignupCode.Generate(); + var hash = SignupCode.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; + } + + 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 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 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 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"); + 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/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/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 3ed344cf4..039ca1ad0 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; @@ -16,404 +17,330 @@ 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 { [ClassDataSource(Shared = SharedType.PerTestSession)] public required WebApplicationFactory WebApplicationFactory { get; init; } - // --- Account Activation --- - - [Test] - public async Task V2Signup_EnqueuesActivationOutbox() + private HttpClient CreateCookielessClient() => WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions { - 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); + AllowAutoRedirect = false, + HandleCookies = false + }); + private async Task CountOutboxAsync(string email) + { 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()); + return await db.EmailOutbox.AsNoTracking().CountAsync(m => m.Recipient == email); } - // --- Resend Activation --- + // --- Password Reset --- [Test] - public async Task V2Signup_Unactivated_SetsActivationResendCookie() + public async Task V1PasswordReset_Retired_Returns410Gone() { - 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); + using var client = WebApplicationFactory.CreateClient(); + var response = await client.PostAsync("/1/account/reset", TestHelper.JsonContent(new { email = "whatever@test.org" })); - 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(); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Gone); } [Test] - public async Task ResendActivation_UnactivatedUser_EnqueuesActivationOutbox() + public async Task ResetPasswordAlias_Retired_Returns410Gone() { - var email = TestHelper.UniqueEmail("mail-resend-activate"); - var username = TestHelper.UniqueUsername("mailresendactivate"); + using var client = WebApplicationFactory.CreateClient(); + var response = await client.PostAsync("/2/account/reset-password", TestHelper.JsonContent(new + { + email = "whatever@test.org", + turnstileResponse = "valid-token" + })); - // Unactivated user with no existing activation request - exercises the create-request path. - var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "SecurePassword123#", activated: false); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Gone); + } - using var client = CreateCookielessClient(); - var response = await PostResendAsync(client, MintResendCookie(userId)); + [Test] + public async Task V2PasswordReset_EnqueuesResetOutbox() + { + var email = TestHelper.UniqueEmail("mail-pwreset-v2"); + var username = TestHelper.UniqueUsername("mailpwresetv2"); + var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "OldPassword123#"); + + 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(); - - // 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 reset = await db.UserPasswordResets.AsNoTracking().SingleAsync(r => r.UserId == userId); var row = await db.EmailOutbox.AsNoTracking().SingleAsync(m => m.Recipient == email); - await Assert.That(row.Type).IsEqualTo(EmailType.AccountActivation); + await Assert.That(row.Type).IsEqualTo(EmailType.PasswordReset); await Assert.That(row.Status).IsEqualTo(EmailStatus.Pending); - await Assert.That(row.CoalesceKey).IsEqualTo(EmailOutboxCoalesceKeys.AccountActivation(userId)); + await Assert.That(row.CoalesceKey).IsEqualTo(EmailOutboxCoalesceKeys.PasswordReset(userId)); + await Assert.That(row.Payload[EmailOutboxPayloadKeys.PasswordResetId]).IsEqualTo(reset.Id.ToString()); } + // 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 ResendActivation_WithSignupCookie_EnqueuesAnotherActivationOutbox() + public async Task PasswordResetComplete_ActivatedAccount_KeepsOAuthConnectionsAndApiTokens() { - 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)); + 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); - // 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); + 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(); - var user = await db.Users.AsNoTracking().FirstAsync(u => u.Email == email); + 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(); - 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(); + using var tokenClient = TestHelper.CreateApiTokenClient(WebApplicationFactory, rawToken); + await Assert.That((await tokenClient.GetAsync("/1/users/self")).StatusCode).IsEqualTo(HttpStatusCode.OK); } + // --- Disconnecting a provider must not leave an account with no way to sign in --- + [Test] - public async Task ResendActivation_WithinCooldown_Returns429_AndEnqueuesNothing() + public async Task RemoveOAuthConnection_OnlyLoginMethod_Returns409_AndKeepsConnection() { - 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); + 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 = CreateCookielessClient(); - await Assert.That((await PostResendAsync(client, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); - await Assert.That((await PostResendAsync(client, cookie)).StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests); + 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 Assert.That(await CountOutboxAsync(email)).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 ResendActivation_DailyCapReached_Returns429() + public async Task RemoveOAuthConnection_PasswordlessAccountWithTwo_RemovesOne_ThenKeepsTheLast() { - 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++) + 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()) { - 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)); + var seedDb = seedScope.ServiceProvider.GetRequiredService(); + await seedDb.Users.Where(u => u.Id == user.Id).ExecuteUpdateAsync(s => s.SetProperty(u => u.PasswordHash, (string?)null)); } - await Assert.That((await PostResendAsync(client, cookie)).StatusCode).IsEqualTo(HttpStatusCode.TooManyRequests); - await Assert.That(await CountOutboxAsync(email)).IsEqualTo(5); + 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 ResendActivation_AlreadyActivatedUser_Returns400_AndRemovesCookie() + public async Task RemoveOAuthConnection_PasswordlessAccountWithTwo_RemovedAtTheSameTime_KeepsOne() { - var email = TestHelper.UniqueEmail("mail-resend-activated"); - var username = TestHelper.UniqueUsername("mailresendactivated"); - var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "SecurePassword123#", activated: true); + 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 = CreateCookielessClient(); - var response = await PostResendAsync(client, MintResendCookie(userId)); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); - await Assert.That(DeletesResendCookie(response)).IsTrue(); + 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(await CountOutboxAsync(email)).IsEqualTo(0); - } + await Assert.That(responses.Count(r => r.StatusCode == HttpStatusCode.NoContent)).IsEqualTo(1); + await Assert.That(responses.Count(r => r.StatusCode == HttpStatusCode.Conflict)).IsEqualTo(1); - [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); + 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 ResendActivation_TamperedCookie_Returns400_AndRemovesCookie() + public async Task RemoveOAuthConnection_AccountWithPassword_RemovesIt() { - 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(); + 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); } + // --- An email change is only confirmed from a session of the account that asked for it --- + [Test] - public async Task Login_Success_RemovesActivationResendCookie() + public async Task EmailChangeVerify_WithoutSession_Returns401_AndLeavesEmail() { - var email = TestHelper.UniqueEmail("mail-login-clears"); - var username = TestHelper.UniqueUsername("maillogclears"); - var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "SecurePassword123#", activated: true); + var (user, token, _) = await CreateUserWithPendingEmailChangeAsync("mail-verify-anon"); 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.PostAsync($"/1/account/email-change/verify?token={token}", null); - var response = await client.SendAsync(request); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); - await Assert.That(DeletesResendCookie(response)).IsTrue(); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + await Assert.That(await GetEmailAsync(user.Id)).IsEqualTo(user.Email); } [Test] - public async Task Login_UnactivatedUser_CorrectPassword_ReturnsNotActivated_AndEnqueuesActivation() + public async Task EmailChangeVerify_FromAnotherAccountsSession_Returns400_AndLeavesEmail() { - var email = TestHelper.UniqueEmail("mail-login-unactivated"); - var username = TestHelper.UniqueUsername("maillogunact"); - var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "SecurePassword123#", activated: false); + var (user, token, _) = await CreateUserWithPendingEmailChangeAsync("mail-verify-other"); + var other = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailverifysecond"), TestHelper.UniqueEmail("mail-verify-second"), "SecurePassword123#"); - 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"); + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, other.SessionToken); + var response = await client.PostAsync($"/1/account/email-change/verify?token={token}", null); - 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)); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(await GetEmailAsync(user.Id)).IsEqualTo(user.Email); } [Test] - public async Task Login_UnactivatedUser_WrongPassword_EnqueuesNothing() + public async Task EmailChangeVerify_FromOwnSession_AppliesChange() { - var email = TestHelper.UniqueEmail("mail-login-unact-wrong"); - var username = TestHelper.UniqueUsername("maillogunactw"); - await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "SecurePassword123#", activated: false); + var (user, token, newEmail) = await CreateUserWithPendingEmailChangeAsync("mail-verify-own"); - 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); + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var response = await client.PostAsync($"/1/account/email-change/verify?token={token}", null); - await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await GetEmailAsync(user.Id)).IsEqualTo(newEmail); } - private HttpClient CreateCookielessClient() => WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions + // 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() { - AllowAutoRedirect = false, - HandleCookies = false - }); + var (user, token, newEmail) = await CreateUserWithPendingEmailChangeAsync("mail-verify-legacy"); - 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" - })); + using var anonymous = CreateCookielessClient(); + var rejected = await anonymous.PostAsync($"/1/account/verify-email?token={token}", null); + await Assert.That(rejected.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); - private string MintResendCookie(Guid userId) - { - var provider = WebApplicationFactory.Services.GetRequiredService(); - return $"{AuthConstants.ActivationResendCookieName}={ActivationResendCookie.CreateToken(provider, userId)}"; + 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); } - private static Task PostResendAsync(HttpClient client, string? cookie) + [Test] + public async Task EmailChangeVerify_AddressHeldByActivatedAccount_Returns409_AndLeavesEmail() { - var request = new HttpRequestMessage(HttpMethod.Post, "/1/account/activate/resend"); - if (cookie is not null) request.Headers.Add("Cookie", cookie); - return client.SendAsync(request); - } + var (user, token, newEmail) = await CreateUserWithPendingEmailChangeAsync("mail-verify-taken"); + await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailverifytaken"), newEmail, "HolderPassword123#"); - // 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)); + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var response = await client.PostAsync($"/1/account/email-change/verify?token={token}", null); - 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); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + await Assert.That(await GetEmailAsync(user.Id)).IsEqualTo(user.Email); } - private async Task BackdateOutboxAsync(string email, TimeSpan by) + 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(); - await db.EmailOutbox - .Where(m => m.Recipient == email) - .ExecuteUpdateAsync(s => s.SetProperty(m => m.CreatedAt, m => m.CreatedAt - by)); - } - - // --- Password Reset --- - - [Test] - public async Task V1PasswordReset_Retired_Returns410Gone() - { - using var client = WebApplicationFactory.CreateClient(); - var response = await client.PostAsync("/1/account/reset", TestHelper.JsonContent(new { email = "whatever@test.org" })); - - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Gone); - } - - [Test] - public async Task ResetPasswordAlias_Retired_Returns410Gone() - { - using var client = WebApplicationFactory.CreateClient(); - var response = await client.PostAsync("/2/account/reset-password", TestHelper.JsonContent(new + var stamp = await db.Users.AsNoTracking().Where(u => u.Id == user.Id).Select(u => u.SecurityStamp).SingleAsync(); + db.UserEmailChanges.Add(new UserEmailChange { - email = "whatever@test.org", - turnstileResponse = "valid-token" - })); + Id = Guid.CreateVersion7(), + UserId = user.Id, + OldEmail = user.Email, + NewEmail = newEmail, + TokenHash = HashingUtils.HashToken(token), + SecurityStampAtCreate = stamp + }); + await db.SaveChangesAsync(); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Gone); + return (user, token, newEmail); } - [Test] - public async Task V2PasswordReset_EnqueuesResetOutbox() + private async Task GetEmailAsync(Guid userId) { - var email = TestHelper.UniqueEmail("mail-pwreset-v2"); - var username = TestHelper.UniqueUsername("mailpwresetv2"); - var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "OldPassword123#"); - - 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 reset = await db.UserPasswordResets.AsNoTracking().SingleAsync(r => r.UserId == userId); - - var row = await db.EmailOutbox.AsNoTracking().SingleAsync(m => m.Recipient == email); - await Assert.That(row.Type).IsEqualTo(EmailType.PasswordReset); - await Assert.That(row.Status).IsEqualTo(EmailStatus.Pending); - await Assert.That(row.CoalesceKey).IsEqualTo(EmailOutboxCoalesceKeys.PasswordReset(userId)); - await Assert.That(row.Payload[EmailOutboxPayloadKeys.PasswordResetId]).IsEqualTo(reset.Id.ToString()); + return await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.Email).SingleAsync(); } [Test] - public async Task V2PasswordReset_UnactivatedUser_EnqueuesResetOutbox() + public async Task PasswordResetComplete_RevokesExistingSessions() { - var email = TestHelper.UniqueEmail("mail-pwreset-unact"); - var username = TestHelper.UniqueUsername("mailpwresetunact"); - var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, username, email, "OldPassword123#", activated: false); + var email = TestHelper.UniqueEmail("mail-pwreset-sessions"); + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailpwresetsess"), email, "OldPassword123#"); - using var client = WebApplicationFactory.CreateClient(); - var response = await client.PostAsync("/2/account/password-reset", TestHelper.JsonContent(new - { - email, - turnstileResponse = "valid-token" - })); + var response = await CompleteSeededPasswordResetAsync(user.Id); 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)); + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var selfResponse = await client.GetAsync("/1/users/self"); + await Assert.That(selfResponse.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); } - [Test] - public async Task PasswordResetComplete_UnactivatedUser_ActivatesAccount() + // Stands in for the Cron delivery job (which mints the real token), then completes the reset. + private async Task<(Guid ResetId, string Secret)> SeedPasswordResetAsync(Guid userId) { - 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()) + 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 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(); - } + 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(); - var response = await client.PostAsync($"/1/account/password-reset/{resetId}/{secret}/complete", + return await client.PostAsync($"/1/account/password-reset/{resetId}/{secret}/complete", TestHelper.JsonContent(new { password = "NewPassword123#" })); - await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + } + private async Task AddOAuthConnectionAsync(Guid userId, string provider) + { 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(); + db.UserOAuthConnections.Add(new UserOAuthConnection + { + UserId = userId, + ProviderKey = provider, + ExternalId = Guid.CreateVersion7().ToString(), + DisplayName = "external" + }); + await db.SaveChangesAsync(); } [Test] diff --git a/API.IntegrationTests/Tests/OAuthFlowTests.cs b/API.IntegrationTests/Tests/OAuthFlowTests.cs new file mode 100644 index 000000000..032edc1ce --- /dev/null +++ b/API.IntegrationTests/Tests/OAuthFlowTests.cs @@ -0,0 +1,362 @@ +using System.Net; +using System.Security.Claims; +using System.Text.Json; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +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.Constants; +using OpenShock.Common.OpenShockDb; +using static OpenShock.API.IntegrationTests.Helpers.PendingSignupHelper; + +namespace OpenShock.API.IntegrationTests.Tests; + +/// +/// 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. +/// +public sealed class OAuthFlowTests +{ + private const string Provider = "discord"; + + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required WebApplicationFactory WebApplicationFactory { get; init; } + + // --- handoff --- + + [Test] + public async Task Handoff_IdentityNobodyKnows_GoesToTheSignupForm() + { + using var client = CreateClient(); + var response = await HandoffAsync(client, MintFlowCookie(NewExternalId())); + + 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_IdentityWithAPendingSignup_HoldsTheSignup_MailsACode_AndIsNotSignedIn() + { + var externalId = NewExternalId(); + 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 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_AnotherIdentity_DoesNotGetToHoldSomeoneElsesSignup() + { + var email = TestHelper.UniqueEmail("oauth-handoff-otherid"); + await CreatePendingOAuthSignupAsync(email, "oauthhandoffotherid", NewExternalId()); + + using var client = CreateClient(); + var response = await HandoffAsync(client, MintFlowCookie(NewExternalId(), email: email, emailVerified: false)); + + await AssertSentBackToSignupAsync(response, pending: false); + await Assert.That(SetsCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsFalse(); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(0); + } + + // --- signup-finalize --- + + [Test] + public async Task SignupFinalize_EmailTheProviderDidNotVerify_StartsAPendingSignup_WithoutAnAccountOrSession() + { + 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(); + + 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_CreatesTheAccount_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 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_PendingSignup_NewEmail_ReplacesIt_AndTheOldCodeNoLongerWorks() + { + var externalId = NewExternalId(); + 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(); + 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(); + + 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); + + 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(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNull(); + } + + [Test] + public async Task SignupFinalize_PendingSignup_EmailTheProviderVerified_ReplacesItWithAnAccount() + { + var externalId = NewExternalId(); + var pendingId = await CreatePendingOAuthSignupAsync(TestHelper.UniqueEmail("oauth-finalize-replace"), "oauthfinreplace", 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 FindUserByEmailAsync(WebApplicationFactory, email); + await Assert.That(user!.ActivatedAt).IsNotNull(); + await Assert.That(await FindAsync(WebApplicationFactory, pendingId)).IsNull(); + } + + [Test] + public async Task SignupFinalize_PendingSignup_UsernameTaken_KeepsThePendingSignup() + { + var externalId = NewExternalId(); + 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"); + + 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 FindAsync(WebApplicationFactory, pendingId)).IsNotNull(); + + // 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 FindAsync(WebApplicationFactory, pendingId)).IsNull(); + } + + [Test] + public async Task SignupFinalize_IdentityOfAnAccount_Returns409() + { + var externalId = NewExternalId(); + var email = TestHelper.UniqueEmail("oauth-finalize-linked"); + using var client = CreateClient(); + 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-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 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 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 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); + + // ...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); + } + + // --- 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, 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; + OAuthUtil.SetOAuthFlow(properties, flow); + + var ticket = new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(claims, Provider)), properties, OAuthConstants.FlowScheme); + + return $"{options.Cookie.Name}={options.TicketDataFormat.Protect(ticket)}"; + } + + 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(); + } + + /// 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 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); + } +} 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..945ad93a9 --- /dev/null +++ b/API.IntegrationTests/Tests/SignupActivationTests.cs @@ -0,0 +1,872 @@ +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 OpenShock.Common.Utils; +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_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); + 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 cookie has done its job. + await Assert.That(DeletesCookie(response, AuthConstants.SignupBrowserSecureCookieName)).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_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, "RGHT-0001"); + var cookie = MintSignupBrowserCookie(WebApplicationFactory, pendingId); + + using var client = CreateClient(); + 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.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); + } + + // 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, "RGHT-0001"); + var cookie = MintSignupBrowserCookie(WebApplicationFactory, pendingId); + + using var client = CreateClient(); + for (var i = 0; i < AuthConstants.SignupCodeMaxAttempts; i++) + { + var wrong = await PostActivateAsync(client, "WRNG-0001", 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, "AAAA-0000", 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(); + } + + // 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] + [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-notacode"), TestHelper.UniqueUsername("activatenotacode")); + await MailCodeAsync(WebApplicationFactory, pendingId); + + using var client = CreateClient(); + var response = await PostActivateAsync(client, notACode, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + 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() + { + 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"); + } + + // --- 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] + 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.SignupBrowserSecureCookieName); + 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 = MintSignupBrowserCookie(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 = MintSignupBrowserCookie(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, MintSignupBrowserCookie(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, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(DeletesCookie(response, AuthConstants.SignupBrowserSecureCookieName)).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() + { + using var client = CreateClient(); + var response = await PostResendAsync(client, $"{AuthConstants.SignupBrowserSecureCookieName}=not-a-valid-token"); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + } + + // --- 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, MintSignupBrowserCookie(WebApplicationFactory, userId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(DeletesCookie(response, AuthConstants.SignupBrowserSecureCookieName)).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 new file mode 100644 index 000000000..a55f899f0 --- /dev/null +++ b/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs @@ -0,0 +1,109 @@ +using System.Net; +using Microsoft.AspNetCore.Mvc.Testing; +using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.Common.Constants; +using static OpenShock.API.IntegrationTests.Helpers.PendingSignupHelper; + +namespace OpenShock.API.IntegrationTests.Tests; + +/// +/// 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. +[NotInParallel("gateway_assignment")] +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_CreatesTheAccount() + { + WebApplicationFactory.ClientCountryCode = "NO"; + var (email, code, cookie) = await SignUpAndGetCodeAsync("countrysame"); + + var response = await PostActivateAsync(code, cookie); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNotNull(); + } + + [Test] + public async Task Activate_FromAnotherCountry_IgnoresTheCookie() + { + WebApplicationFactory.ClientCountryCode = "NO"; + var (email, code, cookie) = await SignUpAndGetCodeAsync("countryother"); + + WebApplicationFactory.ClientCountryCode = "DE"; + var response = await PostActivateAsync(code, cookie); + + 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"; + 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 (email, code, cookie) = await SignUpAndGetCodeAsync("countryunknown"); + + WebApplicationFactory.ClientCountryCode = null; + var response = await PostActivateAsync(code, cookie); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await FindUserByEmailAsync(WebApplicationFactory, email)).IsNotNull(); + } + + [Test] + public async Task Activate_CookieFromASignupOfUnknownCountry_IsAcceptedAnywhere() + { + 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(code, MintSignupBrowserCookie(WebApplicationFactory, pendingId)); + + 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 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 PostSignupAsync(client, email, TestHelper.UniqueUsername(prefix)); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + var cookie = ReadSetCookie(response, AuthConstants.SignupBrowserSecureCookieName); + var pending = (await FindByEmailAsync(WebApplicationFactory, email)).Single(); + + return (email, await MailCodeAsync(WebApplicationFactory, pending.Id), cookie); + } + + private async Task PostActivateAsync(string code, string cookie) + { + using var client = CreateClient(); + return await PendingSignupHelper.PostActivateAsync(client, code, cookie); + } +} 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 e37090bfd..5186d93d6 100644 --- a/API/Controller/Account/Activate.cs +++ b/API/Controller/Account/Activate.cs @@ -1,24 +1,115 @@ 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.DataAnnotations; 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; public sealed partial class AccountController { /// - /// Activate account + /// Complete the signup this browser holds with the code mailed to its address /// + /// + /// 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 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)] - public async Task Activate([FromQuery(Name = "token")] string token, 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) { - bool ok = await _accountService.TryActivateAccountAsync(token, cancellationToken); - - return ok ? Ok() : Problem(AccountError.AccountActivationNotFound); + // 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)) + return Problem(AccountError.AccountActivationNotFound); + + var result = await _accountService.ActivatePendingSignupAsync(signupId.Value, body.Code, cancellationToken); + + // Completed or gone: the cookie has nothing left to do. + if (result is DbUser or Results.NotFound) + SignupBrowserCookie.Remove(HttpContext); + + return result switch + { + DbUser => Ok(), + ActivationCodeInvalid invalid => Problem(AccountError.AccountActivationCodeInvalid(invalid.AttemptsRemaining)), + ActivationCodeExpired => Problem(AccountError.AccountActivationCodeExpired), + AccountWithEmailOrUsernameExists => Problem(SignupError.UsernameOrEmailExists), + Results.NotFound => Problem(AccountError.AccountActivationNotFound) + }; + } + + /// + /// 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. + [SignupCode] + public required string Code { 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..fc4c797e7 100644 --- a/API/Controller/Account/Authenticated/OAuthConnectionRemove.cs +++ b/API/Controller/Account/Authenticated/OAuthConnectionRemove.cs @@ -1,6 +1,10 @@ -using Microsoft.AspNetCore.Mvc; +using System.Net.Mime; +using Microsoft.AspNetCore.Mvc; +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,17 +18,21 @@ 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) { - 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/Account/VerifyEmail.cs b/API/Controller/Account/Authenticated/VerifyEmailChange.cs similarity index 60% rename from API/Controller/Account/VerifyEmail.cs rename to API/Controller/Account/Authenticated/VerifyEmailChange.cs index 0e5ee0ea1..937c8190c 100644 --- a/API/Controller/Account/VerifyEmail.cs +++ b/API/Controller/Account/Authenticated/VerifyEmailChange.cs @@ -1,54 +1,62 @@ -using System.Diagnostics; +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 OpenShock.Common.Problems; using Results = OpenShock.Common.Results; -namespace OpenShock.API.Controller.Account; +using OpenShock.Internal.Common.Problems; + +namespace OpenShock.API.Controller.Account.Authenticated; -public sealed partial class AccountController +public sealed partial class AuthenticatedAccountController { /// - /// Verify a pending email change using the token from the verification email. + /// 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, or the request has expired + /// 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)] - [ProducesResponseType(StatusCodes.Status409Conflict, MediaTypeNames.Application.ProblemJson)] + [ProducesResponseType(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] // EmailChangeNotFound + [ProducesResponseType(StatusCodes.Status409Conflict, MediaTypeNames.Application.ProblemJson)] // EmailChangeAlreadyInUse 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. + /// 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, or the request has expired + /// 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)] - [ProducesResponseType(StatusCodes.Status409Conflict, MediaTypeNames.Application.ProblemJson)] + [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, cancellationToken); + var result = await _accountService.TryVerifyEmailAsync(token, CurrentUser.Id, cancellationToken); return result switch { VerifyEmailSuccess => Ok(), Results.NotFound => Problem(AccountError.EmailChangeNotFound), - EmailAlreadyInUse => Problem(AccountError.EmailChangeAlreadyInUse) + EmailAlreadyInUse => Problem(AccountError.EmailChangeAlreadyInUse), + _ => throw new UnreachableException() }; } } diff --git a/API/Controller/Account/LoginV2.cs b/API/Controller/Account/LoginV2.cs index 0b1b80be8..e49448ac1 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) }; async Task CompleteLoginAsync(User account, string domain) @@ -61,24 +63,29 @@ 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. + var signedIn = await CreateSession(account.Id, domain, account.SecurityStamp); + if (!signedIn) return Problem(LoginError.InvalidCredentials); 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) { + SignupBrowserCookie.Set(HttpContext, pendingSignupId); + 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..f2580e2a3 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 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. /// /// 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,22 @@ 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 (!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); } - 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) - ActivationResendCookie.Remove(HttpContext); + // Completed or gone: the cookie has nothing left to do. + if (result is Results.NotFound) + SignupBrowserCookie.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..1bef62887 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,22 +47,19 @@ 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) - { - ActivationResendCookie.Set(HttpContext, newUser.Id, cookieDomain); - } + // Lets this browser enter the code mailed to the address, and ask for it again. + SignupBrowserCookie.Set(HttpContext, pending.Id); 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/HandOff.cs b/API/Controller/OAuth/HandOff.cs index 89a22a441..00b7f653f 100644 --- a/API/Controller/OAuth/HandOff.cs +++ b/API/Controller/OAuth/HandOff.cs @@ -5,8 +5,10 @@ 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; namespace OpenShock.API.Controller.OAuth; @@ -67,44 +69,52 @@ 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) && + StringUtils.IsTruthy(auth.Principal.FindFirst(OAuthConstants.ClaimEmailVerified)?.Value) && await _accountService.IsEmailRegisteredAsync(externalEmail, cancellationToken)) { await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); 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) + { + SignupBrowserCookie.Set(HttpContext, pending.Id); + + 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"); } - if (connection.User.ActivatedAt is null) - { - // The provider vouched for the identity, so the caller owns this account: (re)send the - // activation link (rate limited inside the service). - 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. - _logger.LogError(ex, "Failed to resend activation email on OAuth login"); - } - - await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); - return RedirectFrontendError("accountNotActivated"); - } - // 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 7f60b4017..d60ce9b26 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; @@ -23,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,14 +94,15 @@ public async Task OAuthSignupFinalize( var isEmailTrusted = StringUtils.IsTruthy(isVerifiedString) && string.Equals(externalAccountEmail, email, StringComparison.InvariantCultureIgnoreCase); // Do not allow creation if this external is already linked anywhere. - var existing = await connectionService.GetByProviderExternalIdAsync(provider, auth.ExternalAccountId, cancellationToken); - if (existing is not null) + if (await connectionService.ConnectionExistsAsync(provider, auth.ExternalAccountId, cancellationToken)) { 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, @@ -107,27 +112,24 @@ public async Task OAuthSignupFinalize( 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); - } + 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)); - // 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); - } - - // 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. + SignupBrowserCookie.Set(HttpContext, pending.Id); + 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/Controller/OAuth/_ApiController.cs b/API/Controller/OAuth/_ApiController.cs index 87de71d25..581ec95d1 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 (!OAuthUtil.TryGetOAuthFlow(auth.Properties, out var flow)) { _logger.LogError("Invalid OAuth scheme"); await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); 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/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..196a7a18d 100644 --- a/API/OAuth/OAuthUtil.cs +++ b/API/OAuth/OAuthUtil.cs @@ -1,4 +1,4 @@ -using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Mvc; namespace OpenShock.API.OAuth; @@ -7,10 +7,20 @@ public static class OAuthUtil { public static ChallengeResult StartOAuth(string provider, OAuthFlow flow) { - return new ChallengeResult(provider, new AuthenticationProperties + var properties = new AuthenticationProperties { - RedirectUri = $"/1/oauth/{provider}/handoff", - Items = { { OAuthConstants.ItemKeyFlowType, flow.ToString() } } - }); + RedirectUri = $"/1/oauth/{provider}/handoff" + }; + + SetOAuthFlow(properties, flow); + + 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()); } 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 c975c8320..2f21c085f 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,6 +78,44 @@ private async Task NotifyEmailOutboxAsync() } } + /// 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 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, 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. + /// + /// 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, + cancellationToken); + + return sent >= MaxActivationEmailsPerWindow; + } + private Task IsUserNameBlacklisted(string username, CancellationToken cancellationToken) => _db.UserNameBlacklists.Matching(username).AnyAsync(cancellationToken); @@ -86,75 +126,136 @@ 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) + private Task IsEmailOrUsernameTakenAsync(string email, string username, CancellationToken cancellationToken) + => _db.Users.AnyAsync(u => u.Email == email || u.Name == username, cancellationToken); + + /// Name of the transaction lock that serializes signups asking for one username. + private static string SignupUsernameLockName(string username) => "signup-username:" + username.ToLowerInvariant(); + + /// + /// 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) { - email = email.ToLowerInvariant(); + var reservedSince = DateTime.UtcNow - Duration.PendingSignupUsernameReservation; + return _db.PendingSignups.AnyAsync(p => p.Username == username && p.CreatedAt >= reservedSince, cancellationToken); + } - if (await IsUserNameBlacklisted(username, cancellationToken) || await IsEmailProviderBlacklisted(email, cancellationToken)) - return new AccountWithEmailOrUsernameExists(); - - if (await _db.Users.AnyAsync(x => x.Email == email || x.Name == username, cancellationToken)) - return new AccountWithEmailOrUsernameExists(); + /// + /// 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) + { + if (!await _db.Database.TryLockForTransactionAsync(SignupUsernameLockName(username), cancellationToken)) + return true; - var user = new User + return await IsUsernameReservedAsync(username, cancellationToken); + } + + /// Pending signups that can still be completed. + private IQueryable LivePendingSignups() + { + var createdSince = DateTime.UtcNow - Duration.PendingSignupLifetime; + return _db.PendingSignups.Where(p => p.CreatedAt >= createdSince); + } + + /// + /// 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. + /// + private PendingSignup AddPendingSignup(string email, string username, string? passwordHash, string? oauthProvider, string? oauthExternalId, string? oauthDisplayName) + { + var pending = new PendingSignup { - Name = username, + Id = Guid.CreateVersion7(), Email = email, - PasswordHash = HashingUtils.HashPassword(password), - CreatedByAutomationTokenId = createdByAutomationTokenId + 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 }; - _db.Users.Add(user); - await _db.SaveChangesAsync(); + _db.PendingSignups.Add(pending); + _db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(pending.Id, email, username)); - // 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)); - } - - return user; + return pending; } /// - public async Task CreateAccountWithActivationFlowAsync(string email, string username, string password, CancellationToken cancellationToken = default) + public async Task SignUpAsync(string email, string username, string password, CancellationToken cancellationToken = default) { - // 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; + email = email.ToLowerInvariant(); - // 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(); + if (await IsUserNameBlacklisted(username, cancellationToken) || await IsEmailProviderBlacklisted(email, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); + + if (await IsEmailOrUsernameTakenAsync(email, username, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); + + var passwordHash = HashingUtils.HashPassword(password); - // 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; + await using var transaction = await _db.Database.BeginTransactionAsync(cancellationToken); - if (mailEnabled) + if (await IsUsernameReservedForSignupAsync(username, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); + + // 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) { - // 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 + var now = DateTime.UtcNow; + var user = new User { - UserId = user.Id, - TokenHash = SeedTokenHash() + Name = username, + Email = email, + PasswordHash = passwordHash, + CreatedAt = now, + ActivatedAt = now, + CreatedByAutomationTokenId = _automationTokens.Current?.Id }; + _db.Users.Add(user); - _db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(user.Id, email, username)); + try + { + await _db.SaveChangesAsync(cancellationToken); + } + catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: PostgresErrorCodes.UniqueViolation }) + { + return new AccountWithEmailOrUsernameExists(); + } - await _db.SaveChangesAsync(); + // 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; } - await _automationTokens.RecordSignupAsync(user.Id); + // 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(); - await transaction.CommitAsync(); + var pending = AddPendingSignup(email, username, passwordHash, oauthProvider: null, oauthExternalId: null, oauthDisplayName: null); - if (mailEnabled) await NotifyEmailOutboxAsync(); + await _db.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(cancellationToken); - return user; + await NotifyEmailOutboxAsync(); + + return pending; } public Task IsEmailRegisteredAsync(string email, CancellationToken cancellationToken = default) @@ -162,7 +263,8 @@ public Task IsEmailRegisteredAsync(string email, CancellationToken cancell return _db.Users.AnyAsync(u => u.Email == email, cancellationToken); } - public async Task CreateOAuthOnlyAccountAsync( + /// + public async Task SignUpWithOAuthAsync( string email, string username, string provider, @@ -174,152 +276,255 @@ public async Task CreateOAuthOnlyAccountAsync( email = email.ToLowerInvariant(); provider = provider.ToLowerInvariant(); - // 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(); - // 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(); + // 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 tx = await _db.Database.BeginTransactionAsync(); + await using var transaction = await _db.Database.BeginTransactionAsync(cancellationToken); try { - var creationTime = DateTime.UtcNow; - + // Fast uniqueness check (optimistic; race handled by unique constraints below) + if (await IsEmailOrUsernameTakenAsync(email, username, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); + + // 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) + { + if (await IsActivationEmailCapReachedAsync(email, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); + + var pending = AddPendingSignup(email, username, passwordHash: null, provider, providerAccountId, providerAccountName); + + await _db.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(cancellationToken); + + await NotifyEmailOutboxAsync(); + + 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 TryActivateAccountAsync(string secret, CancellationToken cancellationToken = default) + /// + public async Task ActivatePendingSignupAsync(Guid pendingSignupId, string code, CancellationToken cancellationToken = default) { - var hash = HashingUtils.HashToken(secret); + await using var transaction = await _db.Database.BeginTransactionAsync(cancellationToken); - var user = await _db.Users - .Include(u => u.UserActivationRequest) - .FirstOrDefaultAsync(x => x.UserDeactivation == null && x.UserActivationRequest != null && x.UserActivationRequest.TokenHash == hash, cancellationToken); - if (user?.UserActivationRequest is null) return false; + // 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); - user.ActivatedAt = DateTime.UtcNow; + var pending = await LivePendingSignups().FirstOrDefaultAsync(p => p.Id == pendingSignupId, cancellationToken); + if (pending is null) return new NotFound(); - _db.UserActivationRequests.Remove(user.UserActivationRequest); + // 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.SignupCodeMaxAttempts) + { + return new ActivationCodeExpired(); + } - await _db.SaveChangesAsync(); + 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) + { + pending.FailedAttempts++; + await _db.SaveChangesAsync(cancellationToken); + await transaction.CommitAsync(cancellationToken); - return true; + return new ActivationCodeInvalid(AuthConstants.SignupCodeMaxAttempts - pending.FailedAttempts); + } + + // 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; + 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); + + 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 + }); + } + + _db.PendingSignups.Remove(pending); + + 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(); + } + + // 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); + + await _auditService.LogAsync( + user.Id, + action: AuditAction.AutomationTokenUsed, + actorId: user.Id, + metadata: new AutomationTokenUsedMetadata(automationTokenId, automationTokenName, nameof(AutomationTokenFlow.Signup))); + } + + await transaction.CommitAsync(cancellationToken); + + return user; } /// - public async Task> ResendActivationEmailAsync(string usernameOrEmail, CancellationToken cancellationToken = default) + public async Task GetPendingSignupStatusAsync(Guid pendingSignupId, CancellationToken cancellationToken = default) { - var userId = await _db.Users - .Where(u => u.Email == usernameOrEmail || u.Name == usernameOrEmail) - .Select(u => (Guid?)u.Id) + var pending = await LivePendingSignups() + .AsNoTracking() + .Where(p => p.Id == pendingSignupId) + .Select(p => new { p.Email, p.Username }) .FirstOrDefaultAsync(cancellationToken); - if (userId is null) return new NotFound(); + if (pending is null) return null; - return await ResendActivationEmailAsync(userId.Value, cancellationToken); + // 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> ResendActivationEmailAsync(Guid userId, CancellationToken cancellationToken = default) + 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); + await using var transaction = await _db.Database.BeginTransactionAsync(cancellationToken); + await _db.Database.ExecuteSqlAsync($"SELECT 1 FROM pending_signups WHERE id = {pendingSignupId} 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 || user.ActivatedAt is not null) return new NotFound(); - if (user.UserDeactivation is not null) return new AccountDeactivated(); + 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 coalesceKey = EmailOutboxCoalesceKeys.AccountActivation(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); - if (recent.Count >= 5 || recent.Any(createdAt => createdAt >= DateTime.UtcNow - Duration.ActivationResendCooldown)) + if (recent.Count >= MaxActivationEmailsPerWindow || recent.Any(createdAt => createdAt >= DateTime.UtcNow - Duration.ActivationResendCooldown)) return new TooManyActivationResends(); - user.UserActivationRequest ??= new UserActivationRequest - { - UserId = user.Id, - TokenHash = SeedTokenHash(), - CreatedAt = DateTime.UtcNow - }; + if (await IsActivationEmailCapReachedAsync(pending.Email, cancellationToken)) + return new TooManyActivationResends(); - _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(); @@ -327,6 +532,40 @@ public 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) { @@ -484,7 +723,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() @@ -492,7 +731,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(); } @@ -552,8 +794,6 @@ public async Task= 3) return new TooManyPasswordResets(); @@ -601,8 +841,6 @@ public async Task> // 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; @@ -610,19 +848,16 @@ 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)); + // 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( reset.Reset.UserId, @@ -630,8 +865,35 @@ await _auditService.LogAsync( actorId: reset.Reset.UserId ); + // 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(); + // 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++) + { + 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(); } @@ -659,6 +921,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(); } @@ -861,13 +1126,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 @@ -898,8 +1165,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 3e19c8539..51fae60ad 100644 --- a/API/Services/Account/IAccountService.cs +++ b/API/Services/Account/IAccountService.cs @@ -10,61 +10,81 @@ 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 (no activation flow). 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 - /// + /// 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, CancellationToken cancellationToken = default); + /// See . + Task SignUpWithOAuthAsync(string email, string username, string provider, string providerAccountId, string? providerAccountName, bool isEmailTrusted, 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); /// - /// Returns true if the given email is already associated with an existing user account. + /// Returns true if the given email belongs to an account. A pending signup is not one and does not + /// reserve its address. /// Task IsEmailRegisteredAsync(string email, CancellationToken cancellationToken = default); /// - /// + /// 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. /// - /// + /// + /// Code from the activation email. /// - /// - Task TryActivateAccountAsync(string token, CancellationToken cancellationToken = default); + /// + /// 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 ActivatePendingSignupAsync(Guid pendingSignupId, string code, 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. + /// 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> ResendActivationEmailAsync(string usernameOrEmail, CancellationToken cancellationToken = default); + Task GetPendingSignupStatusAsync(Guid pendingSignupId, 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). + /// 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. /// - /// + /// /// - /// NotFound when there is nothing to resend (unknown user, already activated, or mail disabled). - Task> ResendActivationEmailAsync(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); @@ -79,7 +99,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 @@ -99,8 +119,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. + /// Completes a password reset process, sets a new password. All sessions are signed out; OAuth links + /// and API tokens are kept. /// /// /// @@ -174,12 +194,35 @@ 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 union SignupResult(User, PendingSignup, AccountWithEmailOrUsernameExists); + +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); + +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. +/// +public sealed record PendingSignupCredentials(Guid PendingSignupId); public sealed record VerifyEmailSuccess(Guid UserId, string OldEmail, string NewEmail); 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 deleted file mode 100644 index 564921e74..000000000 --- a/Common/Authentication/ActivationResendCookie.cs +++ /dev/null @@ -1,80 +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 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. -/// -/// -/// 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. -/// -/// 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. -/// -/// -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 void Set(HttpContext context, Guid userId, string domain) - { - var provider = context.RequestServices.GetRequiredService(); - var frontendOptions = context.RequestServices.GetRequiredService(); - - context.Response.Cookies.Append(AuthConstants.ActivationResendCookieName, CreateToken(provider, userId), new CookieOptions - { - Expires = DateTimeOffset.UtcNow.Add(Duration.ActivationResendWindow), - Secure = context.Request.IsHttps || frontendOptions.CookieSecure, - HttpOnly = false, - SameSite = SameSiteMode.Lax, - Domain = domain - }); - } - - public static bool TryGetUserId(HttpContext context, [NotNullWhen(true)] out Guid? userId) - { - userId = 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; - userId = 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) - { - if (!context.Request.Cookies.ContainsKey(AuthConstants.ActivationResendCookieName)) return; - - var cookieDomains = context.RequestServices.GetRequiredService().CookieDomains; - foreach (var domain in 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 new file mode 100644 index 000000000..46dc8e249 --- /dev/null +++ b/Common/Authentication/SignupBrowserCookie.cs @@ -0,0 +1,135 @@ +using System.Diagnostics.CodeAnalysis; +using System.Security.Cryptography; +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; + +/// +/// 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. +/// +/// +/// 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 +/// 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; + + /// + /// + /// Country the signup came from, or null when it is not known. + 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 signupId) + { + var provider = context.RequestServices.GetRequiredService(); + + context.Response.Cookies.Append(GetName(context), CreateToken(provider, signupId, GetCountryCode(context)), new CookieOptions + { + Expires = DateTimeOffset.UtcNow.Add(Duration.ActivationResendWindow), + Secure = IsSecure(context), + HttpOnly = true, + SameSite = SameSiteMode.Lax, + Path = "/" + }); + } + + public static bool TryGetSignupId(HttpContext context, [NotNullWhen(true)] out Guid? signupId) + { + signupId = 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 + { + 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; + } + + signupId = id; + return true; + } + catch (CryptographicException) + { + // Tampered, expired, or signed with a revoked key. + return false; + } + } + + /// 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) + { + // 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 = secure, + HttpOnly = true, + SameSite = SameSiteMode.Lax, + Path = "/" + }); + } + + 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; + + private static ITimeLimitedDataProtector GetProtector(IDataProtectionProvider provider) + => provider.CreateProtector(ProtectorPurpose).ToTimeLimitedDataProtector(); +} 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 3fdb5c6a1..54319ca0c 100644 --- a/Common/Constants/AuthConstants.cs +++ b/Common/Constants/AuthConstants.cs @@ -3,12 +3,16 @@ 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"; public const string AutomationTokenHeaderName = "X-OpenShock-Automation-Token"; public const int GeneratedTokenLength = 32; + + /// Wrong codes a signup may enter before the mailed code stops working and a new one must be requested. + public const int SignupCodeMaxAttempts = 5; public const int ApiTokenLength = 64; } diff --git a/Common/Constants/Constants.cs b/Common/Constants/Constants.cs index d4ff32036..3f1cbd43c 100644 --- a/Common/Constants/Constants.cs +++ b/Common/Constants/Constants.cs @@ -12,6 +12,25 @@ public static class Duration public static readonly TimeSpan ActivationResendCooldown = TimeSpan.FromMinutes(10); public static readonly TimeSpan ActivationResendWindow = TimeSpan.FromHours(24); + /// + /// 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 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); public static readonly TimeSpan LoginSessionLifetime = TimeSpan.FromDays(30); 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/Errors/AccountError.cs b/Common/Errors/AccountError.cs index 96b611f88..7942930e6 100644 --- a/Common/Errors/AccountError.cs +++ b/Common/Errors/AccountError.cs @@ -26,15 +26,24 @@ 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 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 + { + { "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); 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/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/OpenShockControllerBase.cs b/Common/OpenShockControllerBase.cs index 1b60b3e18..29042daec 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,36 @@ 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(); + 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); + return false; + } + } HttpContext.Response.Cookies.Append(AuthConstants.UserSessionCookieName, session.Token, new CookieOptions { @@ -78,8 +118,10 @@ protected async Task CreateSession(Guid accountId, string domain) 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; } [NonAction] 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); + } +} 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/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index 896a50594..7dd8675ee 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -422,8 +422,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 }); }); 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/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/EmailOutboxDeliveryTests.cs b/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs index da1e9352b..e37e18189 100644 --- a/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs +++ b/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs @@ -105,6 +105,120 @@ public async Task PasswordReset_NewerRequest_SupersedesOlder_OnlyNewestDelivered } } + [Test] + public async Task AccountActivation_ForASignupThatNoLongerExists_IsSkipped() + { + // 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(); + + Guid outboxId; + await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + { + var outbox = EmailOutboxMessage.ForAccountActivation(Guid.CreateVersion7(), email, "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); + } + + await Assert.That((await mailpit.SearchByRecipientAsync(email)).Count).IsEqualTo(0); + } + + [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 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_AndEmailedCodeMatchesStoredHash() + { + var email = UniqueEmail("cron-activation"); + using var mailpit = Factory.CreateMailpitHelper(); + + var (pendingSignupId, seededHash) = await AddPendingSignupAsync(email, failedAttempts: 3); + await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + { + db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(pendingSignupId, email, "Activation User")); + await db.SaveChangesAsync(); + } + + await Factory.RunDeliveryAsync(); + + 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 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?"); + + await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + { + var pending = await db.PendingSignups.AsNoTracking().SingleAsync(p => p.Id == pendingSignupId); + await Assert.That(pending.CodeHash).IsNotEqualTo(seededHash); + 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); + } + } + + // --- 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) @@ -159,7 +273,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) { 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/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 d0af3d3f4..b9196d7fa 100644 --- a/Cron/Services/Email/Outbox/EmailOutboxDispatcher.cs +++ b/Cron/Services/Email/Outbox/EmailOutboxDispatcher.cs @@ -60,18 +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"); - - var token = await MintTokenAsync(db, h => request.TokenHash = h, ct); - 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 = SignupCode.Generate(); + var codeHash = SignupCode.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) @@ -131,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, 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/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..36b526e65 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:4px;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..aa9c012f1 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: 'ABCD-1234', }; 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..b372978d8 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: '4px', + textAlign: 'center' as const, + color: colors.foreground, + }, notice: { backgroundColor: colors.muted, border: `1px solid ${colors.border}`,