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