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/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/MailTests.cs b/API.IntegrationTests/Tests/MailTests.cs index 3ed344cf4..493a05191 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; @@ -278,6 +279,12 @@ private string MintResendCookie(Guid userId) return $"{AuthConstants.ActivationResendCookieName}={ActivationResendCookie.CreateToken(provider, userId)}"; } + private string MintSignupBrowserCookie(Guid userId) + { + var provider = WebApplicationFactory.Services.GetRequiredService(); + return $"{AuthConstants.SignupBrowserSecureCookieName}={SignupBrowserCookie.CreateToken(provider, userId)}"; + } + private static Task PostResendAsync(HttpClient client, string? cookie) { var request = new HttpRequestMessage(HttpMethod.Post, "/1/account/activate/resend"); @@ -416,6 +423,633 @@ public async Task PasswordResetComplete_UnactivatedUser_ActivatesAccount() await Assert.That(await db.UserActivationRequests.AsNoTracking().AnyAsync(r => r.UserId == userId)).IsFalse(); } + // A reset only signs sessions out. On an activated account every OAuth link and API token was put there + // by its owner, so they stay. + [Test] + public async Task PasswordResetComplete_ActivatedAccount_KeepsOAuthConnectionsAndApiTokens() + { + var email = TestHelper.UniqueEmail("mail-pwreset-recovery"); + var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailpwresetrecov"), email, "OldPassword123#"); + await AddOAuthConnectionAsync(userId, "discord"); + await AddOAuthConnectionAsync(userId, "google"); + var (tokenId, rawToken) = await TestHelper.CreateApiTokenInDb(WebApplicationFactory, userId); + + var response = await CompleteSeededPasswordResetAsync(userId); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.UserOAuthConnections.AsNoTracking().CountAsync(c => c.UserId == userId)).IsEqualTo(2); + await Assert.That(await db.ApiTokens.AsNoTracking().AnyAsync(t => t.Id == tokenId)).IsTrue(); + + using var tokenClient = TestHelper.CreateApiTokenClient(WebApplicationFactory, rawToken); + await Assert.That((await tokenClient.GetAsync("/1/users/self")).StatusCode).IsEqualTo(HttpStatusCode.OK); + } + + // The reset is what activates this account, and the identity it was signed up with may be someone + // else's (anyone can do an OAuth signup naming this address), so that link must not survive. + [Test] + public async Task PasswordResetComplete_UnactivatedOAuthAccount_RemovesConnection() + { + var email = TestHelper.UniqueEmail("mail-pwreset-oauth-unact"); + var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailpwresetoauthu"), email, "OldPassword123#", activated: false); + await AddOAuthConnectionAsync(userId, "discord"); + + var response = await CompleteSeededPasswordResetAsync(userId); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.UserOAuthConnections.AsNoTracking().CountAsync(c => c.UserId == userId)).IsEqualTo(0); + } + + // --- A never activated account is a pending signup: it does not keep others off its email --- + + [Test] + public async Task Signup_EmailHeldByStalePendingAccount_ReplacesIt() + { + var email = TestHelper.UniqueEmail("mail-pending-stale"); + var pendingId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailpendingstale"), email, "SquatterPassword123#", activated: false); + await BackdateUserAsync(pendingId, TimeSpan.FromMinutes(11)); + + using var client = CreateCookielessClient(); + var response = await SignUpAsync(client, email, TestHelper.UniqueUsername("mailpendingowner")); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var holder = await db.Users.AsNoTracking().SingleAsync(u => u.Email == email); + await Assert.That(holder.Id).IsNotEqualTo(pendingId); + } + + // An address is only mailed so often, however many signups it takes: each replaced pending account + // would otherwise start its own count. + [Test] + public async Task Signup_AddressAlreadySentTheDailyCapOfActivationEmails_Returns409_AndMailsNothing() + { + var email = TestHelper.UniqueEmail("mail-address-cap"); + + using var client = CreateCookielessClient(); + for (var i = 0; i < 5; i++) + { + var response = await SignUpAsync(client, email, TestHelper.UniqueUsername("mailaddresscap")); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + // Step the pending account and its mail past the cooldown, so the next signup replaces it. + await BackdateOutboxAsync(email, TimeSpan.FromMinutes(11)); + await BackdatePendingAccountAsync(email, TimeSpan.FromMinutes(11)); + } + + var sixth = await SignUpAsync(client, email, TestHelper.UniqueUsername("mailaddresscap")); + await Assert.That(sixth.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + await Assert.That(await CountOutboxAsync(email)).IsEqualTo(5); + } + + private async Task BackdatePendingAccountAsync(string email, TimeSpan by) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await db.Users.Where(u => u.Email == email).ExecuteUpdateAsync(s => s.SetProperty(u => u.CreatedAt, u => u.CreatedAt - by)); + } + + // The cooldown runs from the last activation mail, not only from signup: replacing the account would + // mail the same inbox again straight after a resend did. + [Test] + public async Task Signup_EmailHeldByStalePendingAccount_ThatWasJustMailedAgain_Returns409() + { + var email = TestHelper.UniqueEmail("mail-pending-resent"); + var pendingId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailpendingresent"), email, "FirstPassword123#", activated: false); + await BackdateUserAsync(pendingId, TimeSpan.FromMinutes(11)); + await using (var seedScope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var seedDb = seedScope.ServiceProvider.GetRequiredService(); + seedDb.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(pendingId, email, "pending")); + await seedDb.SaveChangesAsync(); + } + + using var client = CreateCookielessClient(); + var response = await SignUpAsync(client, email, TestHelper.UniqueUsername("mailpendingthird")); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.Users.AsNoTracking().AnyAsync(u => u.Id == pendingId)).IsTrue(); + } + + // Inside the resend cooldown the pending account keeps the address, so its creator has time to open the + // link and repeated signups cannot mail the inbox more often than a resend could. + [Test] + public async Task Signup_EmailHeldByFreshPendingAccount_Returns409() + { + var email = TestHelper.UniqueEmail("mail-pending-fresh"); + var pendingId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailpendingfresh"), email, "FirstPassword123#", activated: false); + + using var client = CreateCookielessClient(); + var response = await SignUpAsync(client, email, TestHelper.UniqueUsername("mailpendingsecond")); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.Users.AsNoTracking().AnyAsync(u => u.Id == pendingId)).IsTrue(); + } + + [Test] + public async Task Signup_EmailHeldByActivatedAccount_Returns409() + { + var email = TestHelper.UniqueEmail("mail-pending-activated"); + var ownerId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailpendingact"), email, "OwnerPassword123#"); + await BackdateUserAsync(ownerId, TimeSpan.FromDays(1)); + + using var client = CreateCookielessClient(); + var response = await SignUpAsync(client, email, TestHelper.UniqueUsername("mailpendingact2")); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + } + + private async Task BackdateUserAsync(Guid userId, TimeSpan by) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await db.Users.Where(u => u.Id == userId).ExecuteUpdateAsync(s => s.SetProperty(u => u.CreatedAt, u => u.CreatedAt - by)); + } + + // --- Disconnecting a provider must not leave an account with no way to sign in --- + + [Test] + public async Task RemoveOAuthConnection_OnlyLoginMethod_Returns409_AndKeepsConnection() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailoauthlast"), TestHelper.UniqueEmail("mail-oauth-last"), "Placeholder123#"); + await AddOAuthConnectionAsync(user.Id, "discord"); + await using (var seedScope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var seedDb = seedScope.ServiceProvider.GetRequiredService(); + await seedDb.Users.Where(u => u.Id == user.Id).ExecuteUpdateAsync(s => s.SetProperty(u => u.PasswordHash, (string?)null)); + } + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var response = await client.DeleteAsync("/1/account/connections/discord"); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.UserOAuthConnections.AsNoTracking().CountAsync(c => c.UserId == user.Id)).IsEqualTo(1); + } + + [Test] + public async Task RemoveOAuthConnection_PasswordlessAccountWithTwo_RemovesOne_ThenKeepsTheLast() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailoauthtwo"), TestHelper.UniqueEmail("mail-oauth-two"), "Placeholder123#"); + await AddOAuthConnectionAsync(user.Id, "discord"); + await AddOAuthConnectionAsync(user.Id, "google"); + await using (var seedScope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var seedDb = seedScope.ServiceProvider.GetRequiredService(); + await seedDb.Users.Where(u => u.Id == user.Id).ExecuteUpdateAsync(s => s.SetProperty(u => u.PasswordHash, (string?)null)); + } + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + await Assert.That((await client.DeleteAsync("/1/account/connections/discord")).StatusCode).IsEqualTo(HttpStatusCode.NoContent); + await Assert.That((await client.DeleteAsync("/1/account/connections/google")).StatusCode).IsEqualTo(HttpStatusCode.Conflict); + await Assert.That((await client.DeleteAsync("/1/account/connections/discord")).StatusCode).IsEqualTo(HttpStatusCode.NotFound); + } + + [Test] + public async Task RemoveOAuthConnection_PasswordlessAccountWithTwo_RemovedAtTheSameTime_KeepsOne() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailoauthrace"), TestHelper.UniqueEmail("mail-oauth-race"), "Placeholder123#"); + await AddOAuthConnectionAsync(user.Id, "discord"); + await AddOAuthConnectionAsync(user.Id, "google"); + await using (var seedScope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var seedDb = seedScope.ServiceProvider.GetRequiredService(); + await seedDb.Users.Where(u => u.Id == user.Id).ExecuteUpdateAsync(s => s.SetProperty(u => u.PasswordHash, (string?)null)); + } + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var responses = await Task.WhenAll( + client.DeleteAsync("/1/account/connections/discord"), + client.DeleteAsync("/1/account/connections/google")); + + await Assert.That(responses.Count(r => r.StatusCode == HttpStatusCode.NoContent)).IsEqualTo(1); + await Assert.That(responses.Count(r => r.StatusCode == HttpStatusCode.Conflict)).IsEqualTo(1); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.UserOAuthConnections.AsNoTracking().CountAsync(c => c.UserId == user.Id)).IsEqualTo(1); + } + + [Test] + public async Task RemoveOAuthConnection_AccountWithPassword_RemovesIt() + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailoauthpw"), TestHelper.UniqueEmail("mail-oauth-pw"), "OwnerPassword123#"); + await AddOAuthConnectionAsync(user.Id, "discord"); + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var response = await client.DeleteAsync("/1/account/connections/discord"); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NoContent); + } + + // --- Activation needs the emailed token and proof of having signed up --- + + [Test] + public async Task Activate_FromSignupBrowser_ActivatesWithTokenAlone() + { + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-activate-cookie", "OwnerPassword123#"); + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token, cookie: MintSignupBrowserCookie(userId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await IsActivatedAsync(userId)).IsTrue(); + } + + // What the owner of the inbox has when someone else signed up with their address. + [Test] + public async Task Activate_TokenAloneFromAnotherBrowser_Returns403_AndLeavesAccountUnactivated() + { + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-activate-alone", "OwnerPassword123#"); + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await response.Content.ReadAsStringAsync()).Contains("Account.Activation.CredentialRequired"); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + + // The token stays usable for whoever does know the password. + var retry = await PostActivateAsync(client, token, password: "OwnerPassword123#"); + await Assert.That(retry.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await IsActivatedAsync(userId)).IsTrue(); + } + + [Test] + public async Task Activate_WrongPassword_Returns403() + { + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-activate-wrongpw", "OwnerPassword123#"); + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token, password: "NotThePassword123#"); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + [Test] + public async Task Signup_SetsSignupBrowserCookie_BoundToTheApiHost() + { + using var client = CreateCookielessClient(); + var response = await SignUpAsync(client, TestHelper.UniqueEmail("mail-signup-browsercookie"), TestHelper.UniqueUsername("mailsignupbrowser")); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + // __Host- prefix, no Domain, HttpOnly: a sibling subdomain cannot plant one in someone else's browser. + var cookie = response.Headers.GetValues("Set-Cookie").Single(c => c.StartsWith(AuthConstants.SignupBrowserSecureCookieName + "=")); + await Assert.That(cookie.Contains("httponly", StringComparison.OrdinalIgnoreCase)).IsTrue(); + await Assert.That(cookie.Contains("secure", StringComparison.OrdinalIgnoreCase)).IsTrue(); + await Assert.That(cookie.Contains("path=/", StringComparison.OrdinalIgnoreCase)).IsTrue(); + await Assert.That(cookie.Contains("domain=", StringComparison.OrdinalIgnoreCase)).IsFalse(); + } + + [Test] + public async Task Activate_ResendCookieAlone_Returns403() + { + // The resend cookie is shared across the cookie domain and readable by script, so it proves nothing. + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-activate-resendcookie", "OwnerPassword123#"); + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token, cookie: MintResendCookie(userId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + [Test] + public async Task Activate_SignupBrowserCookieWithoutHostPrefix_Returns403() + { + // The unprefixed name is the one a sibling subdomain could set. + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-activate-noprefix", "OwnerPassword123#"); + var value = MintSignupBrowserCookie(userId)[(AuthConstants.SignupBrowserSecureCookieName.Length + 1)..]; + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token, cookie: $"{AuthConstants.SignupBrowserCookieName}={value}"); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + [Test] + public async Task Activate_SignupCookieOfAnotherAccount_Returns403() + { + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-activate-othercookie", "OwnerPassword123#"); + var otherUserId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailactother"), TestHelper.UniqueEmail("mail-activate-other"), "OtherPassword123#", activated: false); + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token, cookie: MintSignupBrowserCookie(otherUserId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + [Test] + public async Task Activate_OAuthOnlyAccount_TokenAlone_Returns403_NamingTheProvider() + { + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-activate-oauth", password: null); + await AddOAuthConnectionAsync(userId, "discord"); + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await response.Content.ReadAsStringAsync()).Contains("discord"); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + [Test] + public async Task Activate_UnknownToken_Returns400() + { + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, "no-such-activation-token"); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + } + + [Test] + public async Task RestartPendingSignup_ChangedEmail_InvalidatesTheLinkMailedToTheOldAddress() + { + // Sign up with an inbox you control, then move the pending account onto somebody else's address: + // the link from the first inbox must not activate it there. + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-restart-oldtoken", password: null); + await AddOAuthConnectionAsync(userId, "discord"); + var victimEmail = TestHelper.UniqueEmail("mail-restart-victim"); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var username = await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.Name).SingleAsync(); + + var accountService = scope.ServiceProvider.GetRequiredService(); + var restarted = await accountService.RestartPendingSignupAsync(userId, victimEmail, username); + await Assert.That(restarted.Value is User).IsTrue(); + } + + await Assert.That(await GetEmailAsync(userId)).IsEqualTo(victimEmail); + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token, cookie: MintSignupBrowserCookie(userId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + [Test] + public async Task RestartPendingSignup_ChangedEmail_InvalidatesAPasswordResetRequestedForTheOldAddress() + { + // The other link an inbox of your own can give you: a reset sets a password and activates. + var (userId, _) = await CreateUnactivatedUserWithTokenAsync("mail-restart-oldreset", password: null); + await AddOAuthConnectionAsync(userId, "discord"); + var (resetId, secret) = await SeedPasswordResetAsync(userId); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var username = await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.Name).SingleAsync(); + + var accountService = scope.ServiceProvider.GetRequiredService(); + var restarted = await accountService.RestartPendingSignupAsync(userId, TestHelper.UniqueEmail("mail-restart-victim2"), username); + await Assert.That(restarted.Value is User).IsTrue(); + } + + using var client = CreateCookielessClient(); + var response = await client.PostAsync($"/1/account/password-reset/{resetId}/{secret}/complete", + TestHelper.JsonContent(new { password = "NewPassword123#" })); + + await Assert.That(response.StatusCode).IsNotEqualTo(HttpStatusCode.OK); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + [Test] + public async Task RestartPendingSignup_Conflict_LeavesThePendingAccountHoldingTheRequestedAddress() + { + var (userId, _) = await CreateUnactivatedUserWithTokenAsync("mail-restart-conflict", password: null); + var heldEmail = TestHelper.UniqueEmail("mail-restart-held"); + var holderId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("mailrestartholder"), heldEmail, "HolderPassword123#", activated: false); + await BackdateUserAsync(holderId, TimeSpan.FromMinutes(11)); + var takenUsername = TestHelper.UniqueUsername("mailrestarttaken"); + await TestHelper.CreateUserInDb(WebApplicationFactory, takenUsername, TestHelper.UniqueEmail("mail-restart-taken"), "TakenPassword123#"); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var accountService = scope.ServiceProvider.GetRequiredService(); + var restarted = await accountService.RestartPendingSignupAsync(userId, heldEmail, takenUsername); + await Assert.That(restarted.Value is AccountWithEmailOrUsernameExists).IsTrue(); + + var db = scope.ServiceProvider.GetRequiredService(); + await Assert.That(await db.Users.AsNoTracking().AnyAsync(u => u.Id == holderId)).IsTrue(); + } + + [Test] + public async Task RestartPendingSignup_AccountActivatedAfterTheCallerLookedItUp_ChangesNothing() + { + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-restart-stale", "OwnerPassword123#"); + var originalEmail = await GetEmailAsync(userId); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + // The request looks the account up while it is pending, as the OAuth connection lookup does... + var tracked = await db.Users.SingleAsync(u => u.Id == userId); + await Assert.That(tracked.ActivatedAt).IsNull(); + + // ...and it is activated before the restart runs. + using var client = CreateCookielessClient(); + var activated = await PostActivateAsync(client, token, cookie: MintSignupBrowserCookie(userId)); + await Assert.That(activated.StatusCode).IsEqualTo(HttpStatusCode.OK); + + var accountService = scope.ServiceProvider.GetRequiredService(); + var restarted = await accountService.RestartPendingSignupAsync(userId, TestHelper.UniqueEmail("mail-restart-stale-new"), tracked.Name); + + await Assert.That(restarted.Value is User).IsFalse(); + await Assert.That(await GetEmailAsync(userId)).IsEqualTo(originalEmail); + } + + [Test] + public async Task RestartPendingSignup_SameEmail_KeepsTheMailedLinkWorking() + { + var (userId, token) = await CreateUnactivatedUserWithTokenAsync("mail-restart-sameemail", password: null); + await AddOAuthConnectionAsync(userId, "discord"); + + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var current = await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => new { u.Name, u.Email }).SingleAsync(); + + var accountService = scope.ServiceProvider.GetRequiredService(); + var restarted = await accountService.RestartPendingSignupAsync(userId, current.Email, current.Name); + await Assert.That(restarted.Value is User).IsTrue(); + } + + using var client = CreateCookielessClient(); + var response = await PostActivateAsync(client, token, cookie: MintSignupBrowserCookie(userId)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await IsActivatedAsync(userId)).IsTrue(); + } + + // --- An email change is only confirmed from a session of the account that asked for it --- + + [Test] + public async Task EmailChangeVerify_WithoutSession_Returns401_AndLeavesEmail() + { + var (user, token, _) = await CreateUserWithPendingEmailChangeAsync("mail-verify-anon"); + + using var client = CreateCookielessClient(); + var response = await client.PostAsync($"/1/account/email-change/verify?token={token}", null); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + await Assert.That(await GetEmailAsync(user.Id)).IsEqualTo(user.Email); + } + + [Test] + public async Task EmailChangeVerify_FromAnotherAccountsSession_Returns400_AndLeavesEmail() + { + var (user, token, _) = await CreateUserWithPendingEmailChangeAsync("mail-verify-other"); + var other = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailverifysecond"), TestHelper.UniqueEmail("mail-verify-second"), "SecurePassword123#"); + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, other.SessionToken); + var response = await client.PostAsync($"/1/account/email-change/verify?token={token}", null); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + await Assert.That(await GetEmailAsync(user.Id)).IsEqualTo(user.Email); + } + + [Test] + public async Task EmailChangeVerify_FromOwnSession_AppliesChange() + { + var (user, token, newEmail) = await CreateUserWithPendingEmailChangeAsync("mail-verify-own"); + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var response = await client.PostAsync($"/1/account/email-change/verify?token={token}", null); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await GetEmailAsync(user.Id)).IsEqualTo(newEmail); + } + + // Stands in for the Cron delivery job, which mints the real activation token at send time. + private async Task<(Guid UserId, string Token)> CreateUnactivatedUserWithTokenAsync(string prefix, string? password) + { + var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername(prefix.Replace("-", "")), TestHelper.UniqueEmail(prefix), password ?? "Placeholder123#", activated: false); + var token = "activation-" + Guid.NewGuid().ToString("N"); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + if (password is null) + { + await db.Users.Where(u => u.Id == userId).ExecuteUpdateAsync(s => s.SetProperty(u => u.PasswordHash, (string?)null)); + } + db.UserActivationRequests.Add(new UserActivationRequest { UserId = userId, TokenHash = HashingUtils.HashToken(token) }); + await db.SaveChangesAsync(); + + return (userId, token); + } + + private static Task PostActivateAsync(HttpClient client, string token, string? password = null, string? cookie = null) + { + var request = new HttpRequestMessage(HttpMethod.Post, $"/1/account/activate?token={token}"); + if (password is not null) request.Content = TestHelper.JsonContent(new { password }); + if (cookie is not null) request.Headers.Add("Cookie", cookie); + return client.SendAsync(request); + } + + private async Task IsActivatedAsync(Guid userId) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.ActivatedAt != null).SingleAsync(); + } + + private async Task<(AuthenticatedUser User, string Token, string NewEmail)> CreateUserWithPendingEmailChangeAsync(string prefix) + { + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername(prefix.Replace("-", "")), TestHelper.UniqueEmail(prefix + "-old"), "SecurePassword123#"); + var newEmail = TestHelper.UniqueEmail(prefix + "-new"); + var token = "email-change-" + Guid.NewGuid().ToString("N"); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var stamp = await db.Users.AsNoTracking().Where(u => u.Id == user.Id).Select(u => u.SecurityStamp).SingleAsync(); + db.UserEmailChanges.Add(new UserEmailChange + { + Id = Guid.CreateVersion7(), + UserId = user.Id, + OldEmail = user.Email, + NewEmail = newEmail, + TokenHash = HashingUtils.HashToken(token), + SecurityStampAtCreate = stamp + }); + await db.SaveChangesAsync(); + + return (user, token, newEmail); + } + + private async Task GetEmailAsync(Guid userId) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.Email).SingleAsync(); + } + + [Test] + public async Task PasswordResetComplete_RevokesExistingSessions() + { + var email = TestHelper.UniqueEmail("mail-pwreset-sessions"); + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("mailpwresetsess"), email, "OldPassword123#"); + + var response = await CompleteSeededPasswordResetAsync(user.Id); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var selfResponse = await client.GetAsync("/1/users/self"); + await Assert.That(selfResponse.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized); + } + + // Stands in for the Cron delivery job (which mints the real token), then completes the reset. + private async Task<(Guid ResetId, string Secret)> SeedPasswordResetAsync(Guid userId) + { + const string secret = "test-password-reset-secret"; + var resetId = Guid.CreateVersion7(); + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var stamp = await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.SecurityStamp).SingleAsync(); + db.UserPasswordResets.Add(new UserPasswordReset + { + Id = resetId, + UserId = userId, + TokenHash = HashingUtils.HashToken(secret), + SecurityStampAtCreate = stamp + }); + await db.SaveChangesAsync(); + + return (resetId, secret); + } + + private async Task CompleteSeededPasswordResetAsync(Guid userId) + { + var (resetId, secret) = await SeedPasswordResetAsync(userId); + + using var client = WebApplicationFactory.CreateClient(); + return await client.PostAsync($"/1/account/password-reset/{resetId}/{secret}/complete", + TestHelper.JsonContent(new { password = "NewPassword123#" })); + } + + private async Task AddOAuthConnectionAsync(Guid userId, string provider) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + db.UserOAuthConnections.Add(new UserOAuthConnection + { + UserId = userId, + ProviderKey = provider, + ExternalId = Guid.CreateVersion7().ToString(), + DisplayName = "external" + }); + await db.SaveChangesAsync(); + } + [Test] public async Task PasswordResetComplete_LegacyRecoverRoute_Returns410Gone() { diff --git a/API.IntegrationTests/Tests/OAuthFlowTests.cs b/API.IntegrationTests/Tests/OAuthFlowTests.cs new file mode 100644 index 000000000..e6879395e --- /dev/null +++ b/API.IntegrationTests/Tests/OAuthFlowTests.cs @@ -0,0 +1,432 @@ +using System.Net; +using System.Security.Claims; +using System.Text.Json; +using System.Web; +using AspNet.Security.OAuth.Discord; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.API.OAuth; +using OpenShock.Common.Authentication; +using OpenShock.Common.Constants; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Utils; + +namespace OpenShock.API.IntegrationTests.Tests; + +/// +/// The OAuth endpoints around a not yet activated account: who may activate it, and what the identity that +/// signed up can and cannot do with it. +/// +/// +/// There is no provider to talk to in tests. What the provider round trip leaves behind is the flow cookie, +/// a ticket holding the provider's claims and the properties the flow was started with, so the tests mint +/// that cookie the way the callback would and drive the real endpoints from there. That the authorize +/// endpoint puts the activation token into those properties is covered separately, by reading the state it +/// sends to the provider. +/// +public sealed class OAuthFlowTests +{ + private const string Provider = "discord"; + + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required WebApplicationFactory WebApplicationFactory { get; init; } + + // --- authorize --- + + [Test] + public async Task Authorize_WithActivationToken_CarriesItThroughTheProviderRoundTrip() + { + using var client = CreateClient(); + var response = await client.PostAsync($"/1/oauth/{Provider}/authorize?flow=LoginOrCreate&activationToken=the-mailed-token", null); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Redirect); + await Assert.That(OAuthUtil.TryGetActivationToken(ReadState(response), out var carried)).IsTrue(); + await Assert.That(carried).IsEqualTo("the-mailed-token"); + } + + [Test] + public async Task Authorize_LinkFlow_DoesNotCarryAnActivationToken() + { + // Linking is for an account that is already signed in, so it never activates anything. + var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("oauthlinkauth"), TestHelper.UniqueEmail("oauth-link-auth"), "SecurePassword123#"); + using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken); + var response = await client.PostAsync($"/1/oauth/{Provider}/authorize?flow=Link&activationToken=the-mailed-token", null); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Redirect); + await Assert.That(OAuthUtil.TryGetActivationToken(ReadState(response), out _)).IsFalse(); + } + + // --- handoff: activating a pending account --- + + [Test] + public async Task Handoff_LinkedIdentityWithTheMailedToken_ActivatesAndSignsIn() + { + var externalId = NewExternalId(); + var (userId, token) = await CreatePendingOAuthAccountAsync("oauth-handoff-activate", externalId); + + using var client = CreateClient(); + var response = await HandoffAsync(client, MintFlowCookie(externalId, activationToken: token)); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Redirect); + await Assert.That(response.Headers.Location!.AbsolutePath).IsEqualTo("/home"); + await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsTrue(); + await Assert.That(await IsActivatedAsync(userId)).IsTrue(); + } + + [Test] + public async Task Handoff_LinkedIdentityWithoutTheToken_StaysPending_AndIsNotSignedIn() + { + // The identity that signed up, on its own: it never showed it reads the inbox. + var externalId = NewExternalId(); + var (userId, _) = await CreatePendingOAuthAccountAsync("oauth-handoff-notoken", externalId); + + using var client = CreateClient(); + var response = await HandoffAsync(client, MintFlowCookie(externalId)); + + await AssertSentBackToSignupAsync(response, pending: true); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + [Test] + public async Task Handoff_LinkedIdentityWithATokenOfAnotherAccount_StaysPending() + { + // A link from an inbox the caller does control does not activate the account they parked elsewhere. + var externalId = NewExternalId(); + var (userId, _) = await CreatePendingOAuthAccountAsync("oauth-handoff-othertoken", externalId); + var (otherUserId, otherToken) = await CreatePendingOAuthAccountAsync("oauth-handoff-othertok2", NewExternalId()); + + using var client = CreateClient(); + var response = await HandoffAsync(client, MintFlowCookie(externalId, activationToken: otherToken)); + + await AssertSentBackToSignupAsync(response, pending: true); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + await Assert.That(await IsActivatedAsync(otherUserId)).IsFalse(); + } + + [Test] + public async Task Handoff_AnotherIdentityWithTheMailedToken_DoesNotActivate() + { + // The inbox owner clicking the link and signing in with their own provider account: that identity + // is not the one on the account somebody else created with their address. + var (userId, token) = await CreatePendingOAuthAccountAsync("oauth-handoff-otherid", NewExternalId()); + + using var client = CreateClient(); + var response = await HandoffAsync(client, MintFlowCookie(NewExternalId(), activationToken: token)); + + await AssertSentBackToSignupAsync(response, pending: false); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + // --- signup-finalize --- + + [Test] + public async Task SignupFinalize_EmailTheProviderDidNotVerify_CreatesAPendingAccount_WithoutASession() + { + var externalId = NewExternalId(); + var email = TestHelper.UniqueEmail("oauth-finalize-unverified"); + + using var client = CreateClient(); + var response = await FinalizeAsync(client, MintFlowCookie(externalId, email: TestHelper.UniqueEmail("oauth-finalize-provider"), emailVerified: true), email, TestHelper.UniqueUsername("oauthfinunver")); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsFalse(); + await Assert.That(SetsCookie(response, AuthConstants.SignupBrowserSecureCookieName)).IsTrue(); + + var user = await GetUserByEmailAsync(email); + await Assert.That(user.ActivatedAt).IsNull(); + } + + [Test] + public async Task SignupFinalize_EmailTheProviderVerified_CreatesAnActivatedAccount_AndSignsIn() + { + var externalId = NewExternalId(); + var email = TestHelper.UniqueEmail("oauth-finalize-verified"); + + using var client = CreateClient(); + var response = await FinalizeAsync(client, MintFlowCookie(externalId, email: email, emailVerified: true), email, TestHelper.UniqueUsername("oauthfinver")); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsTrue(); + + var user = await GetUserByEmailAsync(email); + await Assert.That(user.ActivatedAt).IsNotNull(); + } + + [Test] + public async Task SignupFinalize_PendingAccount_NewEmail_MovesIt_AndTheOldLinkNoLongerActivates() + { + // Sign up with an inbox of your own, then move the pending account onto someone else's address. + var externalId = NewExternalId(); + var (userId, oldToken) = await CreatePendingOAuthAccountAsync("oauth-finalize-move", externalId); + var username = await GetUsernameAsync(userId); + var victimEmail = TestHelper.UniqueEmail("oauth-finalize-victim"); + + using var client = CreateClient(); + var response = await FinalizeAsync(client, MintFlowCookie(externalId), victimEmail, username); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsFalse(); + var moved = await GetUserByEmailAsync(victimEmail); + await Assert.That(moved.Id).IsEqualTo(userId); + await Assert.That(moved.ActivatedAt).IsNull(); + + // Neither from the signup browser... + var activate = new HttpRequestMessage(HttpMethod.Post, $"/1/account/activate?token={oldToken}"); + activate.Headers.Add("Cookie", MintSignupBrowserCookie(userId)); + await Assert.That((await client.SendAsync(activate)).StatusCode).IsEqualTo(HttpStatusCode.BadRequest); + + // ...nor through a provider sign-in. + var handoff = await HandoffAsync(client, MintFlowCookie(externalId, activationToken: oldToken)); + await AssertSentBackToSignupAsync(handoff, pending: true); + + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + } + + [Test] + public async Task SignupFinalize_PendingAccount_EmailTheProviderVerified_ReplacesItWithAnActivatedAccount() + { + var externalId = NewExternalId(); + var (pendingUserId, _) = await CreatePendingOAuthAccountAsync("oauth-finalize-replace", externalId); + var email = TestHelper.UniqueEmail("oauth-finalize-replace-verified"); + + using var client = CreateClient(); + var response = await FinalizeAsync(client, MintFlowCookie(externalId, email: email, emailVerified: true), email, TestHelper.UniqueUsername("oauthfinrepl")); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsTrue(); + + var user = await GetUserByEmailAsync(email); + await Assert.That(user.Id).IsNotEqualTo(pendingUserId); + await Assert.That(user.ActivatedAt).IsNotNull(); + await Assert.That(await UserExistsAsync(pendingUserId)).IsFalse(); + } + + [Test] + public async Task SignupFinalize_PendingAccount_EmailTheProviderVerified_UsernameTaken_KeepsThePendingAccount() + { + var externalId = NewExternalId(); + var (pendingUserId, _) = await CreatePendingOAuthAccountAsync("oauth-finalize-keep", externalId); + var takenUsername = TestHelper.UniqueUsername("oauthfintaken"); + await TestHelper.CreateUserInDb(WebApplicationFactory, takenUsername, TestHelper.UniqueEmail("oauth-finalize-taken"), "TakenPassword123#"); + var email = TestHelper.UniqueEmail("oauth-finalize-keep-verified"); + + using var client = CreateClient(); + var response = await FinalizeAsync(client, MintFlowCookie(externalId, email: email, emailVerified: true), email, takenUsername); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + await Assert.That(await UserExistsAsync(pendingUserId)).IsTrue(); + + // The identity is still linked to it, so the signup can be retried with another username. + var retry = await FinalizeAsync(client, MintFlowCookie(externalId, email: email, emailVerified: true), email, TestHelper.UniqueUsername("oauthfinretry")); + await Assert.That(retry.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await UserExistsAsync(pendingUserId)).IsFalse(); + } + + [Test] + public async Task SignupFinalize_IdentityOfAnActivatedAccount_Returns409() + { + var externalId = NewExternalId(); + var (userId, token) = await CreatePendingOAuthAccountAsync("oauth-finalize-activated", externalId); + using var client = CreateClient(); + await HandoffAsync(client, MintFlowCookie(externalId, activationToken: token)); + await Assert.That(await IsActivatedAsync(userId)).IsTrue(); + + var response = await FinalizeAsync(client, MintFlowCookie(externalId), TestHelper.UniqueEmail("oauth-finalize-activated-new"), TestHelper.UniqueUsername("oauthfinact")); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + } + + // --- the reported takeover, end to end --- + + [Test] + public async Task AccountSomeoneElseCreatedOnMyAddress_AfterITakeItOverByPasswordReset_TheirIdentityNoLongerSignsIn() + { + var attackerExternalId = NewExternalId(); + var victimEmail = TestHelper.UniqueEmail("oauth-takeover-victim"); + + // The attacker signs up through the provider, typing the victim's address. + using var client = CreateClient(); + var signup = await FinalizeAsync(client, MintFlowCookie(attackerExternalId, email: TestHelper.UniqueEmail("oauth-takeover-attacker"), emailVerified: true), victimEmail, TestHelper.UniqueUsername("oauthtakeover")); + await Assert.That(signup.StatusCode).IsEqualTo(HttpStatusCode.OK); + var account = await GetUserByEmailAsync(victimEmail); + + // The victim, who owns the inbox, resets the password. That activates the account. + var reset = await CompleteSeededPasswordResetAsync(account.Id); + await Assert.That(reset.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await IsActivatedAsync(account.Id)).IsTrue(); + + // The attacker's identity is no longer linked: signing in with it reaches no account. + var handoff = await HandoffAsync(client, MintFlowCookie(attackerExternalId)); + await AssertSentBackToSignupAsync(handoff, pending: false); + + // And it cannot be attached to that address again. + var again = await FinalizeAsync(client, MintFlowCookie(attackerExternalId), victimEmail, TestHelper.UniqueUsername("oauthtakeover2")); + await Assert.That(again.StatusCode).IsEqualTo(HttpStatusCode.Conflict); + } + + // --- helpers --- + + private HttpClient CreateClient() => WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false, + HandleCookies = false + }); + + private static string NewExternalId() => Guid.NewGuid().ToString("N"); + + /// + /// The flow cookie as the provider callback leaves it: the provider's claims, plus the properties the + /// flow was started with. + /// + private string MintFlowCookie(string externalId, string? email = null, bool emailVerified = false, string? activationToken = null, OAuthFlow flow = OAuthFlow.LoginOrCreate) + { + var options = WebApplicationFactory.Services.GetRequiredService>().Get(OAuthConstants.FlowScheme); + + List claims = + [ + new(ClaimTypes.NameIdentifier, externalId), + new(ClaimTypes.Name, "external-" + externalId[..8]) + ]; + if (email is not null) claims.Add(new Claim(ClaimTypes.Email, email)); + if (emailVerified) claims.Add(new Claim(OAuthConstants.ClaimEmailVerified, "true")); + + var properties = new AuthenticationProperties + { + IssuedUtc = DateTimeOffset.UtcNow, + ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(10) + }; + properties.Items[".AuthScheme"] = Provider; + OAuthUtil.SetOAuthFlow(properties, flow); + OAuthUtil.SetActivationToken(properties, activationToken); + + var ticket = new AuthenticationTicket(new ClaimsPrincipal(new ClaimsIdentity(claims, Provider)), properties, OAuthConstants.FlowScheme); + + return $"{options.Cookie.Name}={options.TicketDataFormat.Protect(ticket)}"; + } + + private string MintSignupBrowserCookie(Guid userId) + { + var provider = WebApplicationFactory.Services.GetRequiredService(); + return $"{AuthConstants.SignupBrowserSecureCookieName}={SignupBrowserCookie.CreateToken(provider, userId)}"; + } + + /// The properties the authorize endpoint handed to the provider, read back from the state parameter. + private AuthenticationProperties ReadState(HttpResponseMessage response) + { + var state = HttpUtility.ParseQueryString(response.Headers.Location!.Query)["state"]!; + var options = WebApplicationFactory.Services.GetRequiredService>().Get(Provider); + return options.StateDataFormat.Unprotect(state)!; + } + + private static Task HandoffAsync(HttpClient client, string flowCookie) + { + var request = new HttpRequestMessage(HttpMethod.Get, $"/1/oauth/{Provider}/handoff"); + request.Headers.Add("Cookie", flowCookie); + return client.SendAsync(request); + } + + private static Task FinalizeAsync(HttpClient client, string flowCookie, string email, string username) + { + var request = new HttpRequestMessage(HttpMethod.Post, $"/1/oauth/{Provider}/signup-finalize") + { + Content = TestHelper.JsonContent(new { email, username }) + }; + request.Headers.Add("Cookie", flowCookie); + return client.SendAsync(request); + } + + /// Not signed in, and sent to the signup form: there is no usable account for this identity. + private static async Task AssertSentBackToSignupAsync(HttpResponseMessage response, bool pending) + { + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Redirect); + await Assert.That(response.Headers.Location!.AbsolutePath).IsEqualTo($"/oauth/{Provider}/create"); + await Assert.That(response.Headers.Location.Query).IsEqualTo(pending ? "?pending=1" : ""); + await Assert.That(SetsCookie(response, AuthConstants.UserSessionCookieName)).IsFalse(); + } + + private static bool SetsCookie(HttpResponseMessage response, string name) => + response.Headers.TryGetValues("Set-Cookie", out var values) && + values.Any(c => c.StartsWith(name + "=") && !c.StartsWith(name + "=;")); + + /// + /// An account created through the provider with an address it did not verify, with its activation link + /// already mailed (the Cron delivery job mints the real token at send time). + /// + private async Task<(Guid UserId, string Token)> CreatePendingOAuthAccountAsync(string prefix, string externalId) + { + var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername(prefix.Replace("-", "")), TestHelper.UniqueEmail(prefix), "Placeholder123#", activated: false); + var token = "activation-" + Guid.NewGuid().ToString("N"); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await db.Users.Where(u => u.Id == userId).ExecuteUpdateAsync(s => s.SetProperty(u => u.PasswordHash, (string?)null)); + db.UserActivationRequests.Add(new UserActivationRequest { UserId = userId, TokenHash = HashingUtils.HashToken(token) }); + db.UserOAuthConnections.Add(new UserOAuthConnection + { + UserId = userId, + ProviderKey = Provider, + ExternalId = externalId, + DisplayName = "external" + }); + await db.SaveChangesAsync(); + + return (userId, token); + } + + private async Task CompleteSeededPasswordResetAsync(Guid userId) + { + const string secret = "test-password-reset-secret"; + var resetId = Guid.CreateVersion7(); + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + var stamp = await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.SecurityStamp).SingleAsync(); + db.UserPasswordResets.Add(new UserPasswordReset + { + Id = resetId, + UserId = userId, + TokenHash = HashingUtils.HashToken(secret), + SecurityStampAtCreate = stamp + }); + await db.SaveChangesAsync(); + } + + using var client = WebApplicationFactory.CreateClient(); + return await client.PostAsync($"/1/account/password-reset/{resetId}/{secret}/complete", + TestHelper.JsonContent(new { password = "NewPassword123#" })); + } + + private async Task IsActivatedAsync(Guid userId) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.ActivatedAt != null).SingleAsync(); + } + + private async Task UserExistsAsync(Guid userId) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Users.AsNoTracking().AnyAsync(u => u.Id == userId); + } + + private async Task GetUsernameAsync(Guid userId) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.Name).SingleAsync(); + } + + private async Task GetUserByEmailAsync(string email) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Users.AsNoTracking().SingleAsync(u => u.Email == email); + } +} diff --git a/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs b/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs new file mode 100644 index 000000000..a5a71f7f1 --- /dev/null +++ b/API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs @@ -0,0 +1,150 @@ +using System.Net; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenShock.API.IntegrationTests.Helpers; +using OpenShock.Common.Authentication; +using OpenShock.Common.Constants; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Utils; + +namespace OpenShock.API.IntegrationTests.Tests; + +/// +/// The signup browser cookie only stands in for the account's credential when it comes back from the +/// country the signup was made in. +/// +// One at a time: every test moves the single fake location all requests of this host resolve to. +[NotInParallel("signup-browser-country")] +public sealed class SignupBrowserCookieCountryTests +{ + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required GeoLocatedWebApplicationFactory WebApplicationFactory { get; init; } + + [After(Test)] + public void ResetCountry() => WebApplicationFactory.ClientCountryCode = null; + + [Test] + public async Task Activate_FromTheCountryOfTheSignup_ActivatesWithTokenAlone() + { + WebApplicationFactory.ClientCountryCode = "NO"; + var (userId, token, cookie) = await SignUpAndGetLinkAsync("countrysame"); + + var response = await PostActivateAsync(token, cookie); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await IsActivatedAsync(userId)).IsTrue(); + } + + [Test] + public async Task Activate_FromAnotherCountry_AsksForTheCredential() + { + WebApplicationFactory.ClientCountryCode = "NO"; + var (userId, token, cookie) = await SignUpAndGetLinkAsync("countryother"); + + WebApplicationFactory.ClientCountryCode = "DE"; + var response = await PostActivateAsync(token, cookie); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden); + await Assert.That(await IsActivatedAsync(userId)).IsFalse(); + + // The cookie is only ignored, not burned: back home it still works. + WebApplicationFactory.ClientCountryCode = "NO"; + await Assert.That((await PostActivateAsync(token, cookie)).StatusCode).IsEqualTo(HttpStatusCode.OK); + } + + [Test] + public async Task Activate_WhenTheCountryCannotBeResolved_StillAcceptsTheCookie() + { + WebApplicationFactory.ClientCountryCode = "NO"; + var (userId, token, cookie) = await SignUpAndGetLinkAsync("countryunknown"); + + WebApplicationFactory.ClientCountryCode = null; + var response = await PostActivateAsync(token, cookie); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await IsActivatedAsync(userId)).IsTrue(); + } + + [Test] + public async Task Activate_CookieFromASignupOfUnknownCountry_IsAcceptedAnywhere() + { + var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("countrynone"), TestHelper.UniqueEmail("country-none"), "OwnerPassword123#", activated: false); + var token = await SeedActivationTokenAsync(userId); + var provider = WebApplicationFactory.Services.GetRequiredService(); + var cookie = $"{AuthConstants.SignupBrowserSecureCookieName}={SignupBrowserCookie.CreateToken(provider, userId)}"; + + WebApplicationFactory.ClientCountryCode = "DE"; + var response = await PostActivateAsync(token, cookie); + + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + } + + private HttpClient CreateClient() => WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions + { + AllowAutoRedirect = false, + HandleCookies = false + }); + + /// Signs up through the API, and stands in for the Cron job that mails the activation link. + private async Task<(Guid UserId, string Token, string Cookie)> SignUpAndGetLinkAsync(string prefix) + { + var email = TestHelper.UniqueEmail(prefix); + + using var client = CreateClient(); + var response = await client.PostAsync("/2/account/signup", TestHelper.JsonContent(new + { + username = TestHelper.UniqueUsername(prefix), + password = "SecurePassword123#", + email, + turnstileResponse = "valid-token" + })); + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + + var cookie = response.Headers.GetValues("Set-Cookie") + .Single(c => c.StartsWith(AuthConstants.SignupBrowserSecureCookieName + "=")) + .Split(';')[0]; + + Guid userId; + await using (var scope = WebApplicationFactory.Services.CreateAsyncScope()) + { + var db = scope.ServiceProvider.GetRequiredService(); + userId = await db.Users.AsNoTracking().Where(u => u.Email == email).Select(u => u.Id).SingleAsync(); + } + + return (userId, await SeedActivationTokenAsync(userId), cookie); + } + + private async Task SeedActivationTokenAsync(Guid userId) + { + var token = "activation-" + Guid.NewGuid().ToString("N"); + var hash = HashingUtils.HashToken(token); + + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + var updated = await db.UserActivationRequests.Where(r => r.UserId == userId).ExecuteUpdateAsync(s => s.SetProperty(r => r.TokenHash, hash)); + if (updated == 0) + { + db.UserActivationRequests.Add(new UserActivationRequest { UserId = userId, TokenHash = hash }); + await db.SaveChangesAsync(); + } + + return token; + } + + private async Task PostActivateAsync(string token, string cookie) + { + using var client = CreateClient(); + var request = new HttpRequestMessage(HttpMethod.Post, $"/1/account/activate?token={token}"); + request.Headers.Add("Cookie", cookie); + return await client.SendAsync(request); + } + + private async Task IsActivatedAsync(Guid userId) + { + await using var scope = WebApplicationFactory.Services.CreateAsyncScope(); + var db = scope.ServiceProvider.GetRequiredService(); + return await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.ActivatedAt != null).SingleAsync(); + } +} diff --git a/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..9da4913ad 100644 --- a/API/Controller/Account/Activate.cs +++ b/API/Controller/Account/Activate.cs @@ -1,8 +1,13 @@ using System.Net.Mime; using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.RateLimiting; +using OpenShock.API.Services.Account; using OpenShock.Common.ApiVersioning; +using OpenShock.Common.Authentication; using OpenShock.Common.Errors; using OpenShock.Internal.Common.Problems; +using Results = OpenShock.Common.Results; namespace OpenShock.API.Controller.Account; @@ -11,14 +16,41 @@ public sealed partial class AccountController /// /// Activate account /// + /// + /// In the browser that signed up, the emailed token is enough. From anywhere else the caller must also + /// show the account is theirs, since the token only proves control of the inbox and anyone can sign up + /// with somebody else's address: send the account's password in the body, or, for an account created + /// through OAuth, start a sign-in with the linked provider passing this token as activationToken. + /// + /// Account activated + /// No pending activation matches the token + /// The token is valid, but the account's password or linked sign-in is also required [HttpPost("activate")] [ApiVersion(1)] + [EnableRateLimiting("auth")] [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] - public async Task Activate([FromQuery(Name = "token")] string token, CancellationToken cancellationToken) + [ProducesResponseType(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] // AccountActivationNotFound + [ProducesResponseType(StatusCodes.Status403Forbidden, MediaTypeNames.Application.ProblemJson)] // AccountActivationCredentialRequired + public async Task Activate( + [FromQuery(Name = "token")] string token, + [FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] ActivateRequest? body, + CancellationToken cancellationToken) { - bool ok = await _accountService.TryActivateAccountAsync(token, cancellationToken); - - return ok ? Ok() : Problem(AccountError.AccountActivationNotFound); + SignupBrowserCookie.TryGetUserId(HttpContext, out var signupBrowserUserId); + + var result = await _accountService.ActivateAccountAsync(token, signupBrowserUserId, body?.Password, cancellationToken); + + return result switch + { + Results.Success => Ok(), + ActivationCredentialRequired required => Problem(AccountError.AccountActivationCredentialRequired(required.HasPassword, required.OAuthProviders, required.PasswordInvalid)), + Results.NotFound => Problem(AccountError.AccountActivationNotFound) + }; + } + + public sealed class ActivateRequest + { + /// The account's password. Only needed when activating from a browser other than the one that signed up. + public string? Password { get; init; } } } diff --git a/API/Controller/Account/Authenticated/ChangePassword.cs b/API/Controller/Account/Authenticated/ChangePassword.cs index 8d562b533..6d4d04263 100644 --- a/API/Controller/Account/Authenticated/ChangePassword.cs +++ b/API/Controller/Account/Authenticated/ChangePassword.cs @@ -29,7 +29,7 @@ public sealed partial class AuthenticatedAccountController public async Task ChangePassword([FromBody] ChangePasswordRequest body, CancellationToken cancellationToken) { // OAuth-only accounts that have never set a password must go through the email-confirmed - // /password/set flow rather than silently setting one through this endpoint. + // password reset flow rather than silently setting one through this endpoint. if (string.IsNullOrEmpty(CurrentUser.PasswordHash)) { return Problem(AccountError.PasswordNotSet); diff --git a/API/Controller/Account/Authenticated/OAuthConnectionRemove.cs b/API/Controller/Account/Authenticated/OAuthConnectionRemove.cs index 9796a6cfc..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/Authenticated/VerifyEmailChange.cs b/API/Controller/Account/Authenticated/VerifyEmailChange.cs new file mode 100644 index 000000000..ca6dbfe3c --- /dev/null +++ b/API/Controller/Account/Authenticated/VerifyEmailChange.cs @@ -0,0 +1,44 @@ +using System.Diagnostics; +using System.Net.Mime; +using Microsoft.AspNetCore.Mvc; +using OpenShock.API.Services.Account; +using OpenShock.Common.ApiVersioning; +using OpenShock.Common.Errors; +using OpenShock.Common.Problems; +using Results = OpenShock.Common.Results; + +using OpenShock.Internal.Common.Problems; + +namespace OpenShock.API.Controller.Account.Authenticated; + +public sealed partial class AuthenticatedAccountController +{ + /// + /// Verify a pending email change of the current user using the token from the verification email. + /// + /// + /// Requires a session of the account that requested the change. The link is mailed to an address the + /// account does not own yet, so opening it proves nothing about the account: accepted anonymously, a + /// stranger's click would put their address on someone else's account. + /// + /// Email change verified and applied + /// Token is invalid, already used, expired, or belongs to another account + /// The new email address was claimed by another account before verification completed + [HttpPost("email-change/verify")] + [ApiVersion(1)] + [ProducesResponseType(StatusCodes.Status200OK)] + [ProducesResponseType(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] // EmailChangeNotFound + [ProducesResponseType(StatusCodes.Status409Conflict, MediaTypeNames.Application.ProblemJson)] // EmailChangeAlreadyInUse + public async Task EmailVerify([FromQuery(Name = "token")] string token, CancellationToken cancellationToken) + { + var result = await _accountService.TryVerifyEmailAsync(token, CurrentUser.Id, cancellationToken); + + return result switch + { + VerifyEmailSuccess => Ok(), + Results.NotFound => Problem(AccountError.EmailChangeNotFound), + EmailAlreadyInUse => Problem(AccountError.EmailChangeAlreadyInUse), + _ => throw new UnreachableException() + }; + } +} diff --git a/API/Controller/Account/LoginV2.cs b/API/Controller/Account/LoginV2.cs index 0b1b80be8..1fad63224 100644 --- a/API/Controller/Account/LoginV2.cs +++ b/API/Controller/Account/LoginV2.cs @@ -61,7 +61,10 @@ async Task CompleteLoginAsync(User account, string domain) if (!await automationTokens.TryRecordUseAsync(account.Id, AutomationTokenFlow.Login, cancellationToken)) return Problem(AutomationTokenError.NotAllowedForAccount); - await CreateSession(account.Id, domain); + // The password was checked against the account as it was read; if it was replaced since, this + // sign-in used the old one. + var signedIn = await CreateSession(account.Id, domain, account.SecurityStamp); + if (!signedIn) return Problem(LoginError.InvalidCredentials); return Ok(LoginV2OkResponse.FromUser(account)); } diff --git a/API/Controller/Account/VerifyEmail.cs b/API/Controller/Account/VerifyEmail.cs deleted file mode 100644 index 0e5ee0ea1..000000000 --- a/API/Controller/Account/VerifyEmail.cs +++ /dev/null @@ -1,54 +0,0 @@ -using System.Diagnostics; -using System.Net.Mime; -using Microsoft.AspNetCore.Mvc; -using OpenShock.API.Services.Account; -using OpenShock.Common.ApiVersioning; -using OpenShock.Common.Errors; -using OpenShock.Internal.Common.Problems; -using Results = OpenShock.Common.Results; - -namespace OpenShock.API.Controller.Account; - -public sealed partial class AccountController -{ - /// - /// Verify a pending email change using the token from the verification email. - /// - /// Email change verified and applied - /// Token is invalid, already used, or the request has expired - /// The new email address was claimed by another account before verification completed - [HttpPost("email-change/verify")] - [ApiVersion(1)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] - [ProducesResponseType(StatusCodes.Status409Conflict, MediaTypeNames.Application.ProblemJson)] - public Task EmailVerify([FromQuery(Name = "token")] string token, CancellationToken cancellationToken) - => VerifyPendingEmailChange(token, cancellationToken); - - /// - /// Verify a pending email change. Deprecated: use POST /email-change/verify instead. - /// - /// Email change verified and applied - /// Token is invalid, already used, or the request has expired - /// The new email address was claimed by another account before verification completed - [Obsolete("Use POST /email-change/verify instead.")] - [HttpPost("verify-email")] - [ApiVersion(1)] - [ProducesResponseType(StatusCodes.Status200OK)] - [ProducesResponseType(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] - [ProducesResponseType(StatusCodes.Status409Conflict, MediaTypeNames.Application.ProblemJson)] - public Task EmailVerifyLegacy([FromQuery(Name = "token")] string token, CancellationToken cancellationToken) - => VerifyPendingEmailChange(token, cancellationToken); - - private async Task VerifyPendingEmailChange(string token, CancellationToken cancellationToken) - { - var result = await _accountService.TryVerifyEmailAsync(token, cancellationToken); - - return result switch - { - VerifyEmailSuccess => Ok(), - Results.NotFound => Problem(AccountError.EmailChangeNotFound), - EmailAlreadyInUse => Problem(AccountError.EmailChangeAlreadyInUse) - }; - } -} diff --git a/API/Controller/OAuth/Authorize.cs b/API/Controller/OAuth/Authorize.cs index 28d4a13de..c9cd7d5d7 100644 --- a/API/Controller/OAuth/Authorize.cs +++ b/API/Controller/OAuth/Authorize.cs @@ -17,13 +17,14 @@ public sealed partial class OAuthController /// /// Provider key (e.g. discord). /// Flow to run + /// Token from the activation email; signing in with the account's linked provider then activates it. /// Redirect to the provider authorization page. /// Unsupported or misconfigured provider. [HttpPost("{provider}/authorize")] [ApiVersion(1)] [EnableRateLimiting("auth")] [ApiExplorerSettings(IgnoreApi = true)] - public async Task OAuthAuthorize([FromRoute] string provider, [FromQuery(Name="flow"), Required] OAuthFlow flow) + public async Task OAuthAuthorize([FromRoute] string provider, [FromQuery(Name="flow"), Required] OAuthFlow flow, [FromQuery(Name = "activationToken"), StringLength(128)] string? activationToken = null) { if (!await _schemeProvider.IsSupportedOAuthScheme(provider)) return Problem(OAuthError.UnsupportedProvider); @@ -40,6 +41,6 @@ public async Task OAuthAuthorize([FromRoute] string provider, [Fr return Problem(OAuthError.UnsupportedFlow); } - return OAuthUtil.StartOAuth(provider, flow); + return OAuthUtil.StartOAuth(provider, flow, activationToken); } } diff --git a/API/Controller/OAuth/HandOff.cs b/API/Controller/OAuth/HandOff.cs index 89a22a441..a817756d3 100644 --- a/API/Controller/OAuth/HandOff.cs +++ b/API/Controller/OAuth/HandOff.cs @@ -7,6 +7,7 @@ using OpenShock.Common.ApiVersioning; using OpenShock.Common.Extensions; using OpenShock.Common.Options; +using OpenShock.Common.Utils; namespace OpenShock.API.Controller.OAuth; @@ -67,8 +68,11 @@ public async Task OAuthHandOff( // If the provider returned an email that already belongs to an existing OpenShock // user, do not allow creating a second account with the same email. The user must // log in to that account and link the provider from the connections settings. + // Only for an address the provider verified: an unverified one is whatever the caller typed + // at the provider, and answering for it would tell anyone which emails are registered. var externalEmail = auth.Principal.FindFirst(ClaimTypes.Email)?.Value; if (!string.IsNullOrWhiteSpace(externalEmail) && + StringUtils.IsTruthy(auth.Principal.FindFirst(OAuthConstants.ClaimEmailVerified)?.Value) && await _accountService.IsEmailRegisteredAsync(externalEmail, cancellationToken)) { await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); @@ -87,22 +91,34 @@ await _accountService.IsEmailRegisteredAsync(externalEmail, cancellationToken)) return RedirectFrontendError("accountDeactivated"); } - if (connection.User.ActivatedAt is null) + // A flow started from the account's emailed activation link that comes back with the linked + // identity shows inbox and credential are held by the same party, so the account is theirs: + // activate it and carry on to the sign-in below. + var isActivated = connection.User.ActivatedAt is not null; + if (!isActivated && OAuthUtil.TryGetActivationToken(auth.Properties, out var activationToken)) { - // The provider vouched for the identity, so the caller owns this account: (re)send the - // activation link (rate limited inside the service). + isActivated = await _accountService.TryActivateAccountAsync(connection.UserId, activationToken, cancellationToken); + } + + if (!isActivated) + { + // The provider vouched for the identity, so the caller holds the account's credential: (re)send + // the activation link (rate limited inside the service). Opening it is still required, the + // address on the account was typed in at signup and is not known to be theirs. try { await _accountService.ResendActivationEmailAsync(connection.UserId, cancellationToken); } catch (Exception ex) when (ex is not OperationCanceledException) { - // Best effort: still clear the flow cookie and redirect with the real reason. + // Best effort: the redirect below still tells the user what is going on. _logger.LogError(ex, "Failed to resend activation email on OAuth login"); } - await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); - return RedirectFrontendError("accountNotActivated"); + // Back to the signup form with the flow cookie kept: it explains that activation is + // pending, and lets someone who mistyped their email correct it instead of being stuck + // with an account they can never activate (see OAuthSignupFinalize). + return RedirectFrontendPath($"/oauth/{Uri.EscapeDataString(provider)}/create?pending=1"); } // Direct sign-in diff --git a/API/Controller/OAuth/SignupFinalize.cs b/API/Controller/OAuth/SignupFinalize.cs index 7f60b4017..aaf2941e8 100644 --- a/API/Controller/OAuth/SignupFinalize.cs +++ b/API/Controller/OAuth/SignupFinalize.cs @@ -89,12 +89,40 @@ public async Task OAuthSignupFinalize( var isVerifiedString = auth.Principal.FindFirst(OAuthConstants.ClaimEmailVerified)?.Value; var isEmailTrusted = StringUtils.IsTruthy(isVerifiedString) && string.Equals(externalAccountEmail, email, StringComparison.InvariantCultureIgnoreCase); - // Do not allow creation if this external is already linked anywhere. + // Do not allow creation if this external is already linked to a real account. + Guid? replacePendingUserId = null; var existing = await connectionService.GetByProviderExternalIdAsync(provider, auth.ExternalAccountId, cancellationToken); if (existing is not null) { - await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); - return Problem(OAuthError.ExternalAlreadyLinked); + if (existing.User.ActivatedAt is not null || existing.User.UserDeactivation is not null) + { + await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); + return Problem(OAuthError.ExternalAlreadyLinked); + } + + // Linked to a signup this identity started but never activated, most likely because the email + // was mistyped and the link never arrived. The caller just proved they hold the identity, and a + // pending account has nothing in it, so let them start over instead of being stuck with it. + if (isEmailTrusted) + { + // The provider vouches for the new address: replace the pending account with a real one below. + // It is only removed if that succeeds, so a taken username leaves the signup to retry with. + replacePendingUserId = existing.UserId; + } + else + { + var restarted = await _accountService.RestartPendingSignupAsync(existing.UserId, email, username, cancellationToken); + if (restarted.Value is not User pendingUser) + { + // Username or email already exists: keep the flow cookie so the frontend can retry. + return Problem(SignupError.UsernameOrEmailExists); + } + + ActivationResendCookie.Set(HttpContext, pendingUser.Id, domain); + await HttpContext.SignOutAsync(OAuthConstants.FlowScheme); + + return Ok(LoginV2OkResponse.FromUser(pendingUser)); + } } var created = await _accountService.CreateOAuthOnlyAccountAsync( @@ -104,6 +132,7 @@ public async Task OAuthSignupFinalize( auth.ExternalAccountId, auth.ExternalAccountDisplayName ?? auth.ExternalAccountName, isEmailTrusted, + replacePendingUserId, cancellationToken ); 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/OAuth/OAuthConstants.cs b/API/OAuth/OAuthConstants.cs index f07fc8438..b1a6e3605 100644 --- a/API/OAuth/OAuthConstants.cs +++ b/API/OAuth/OAuthConstants.cs @@ -11,6 +11,7 @@ public static class OAuthConstants public static readonly string[] OAuth2Schemes = [DiscordScheme, GoogleScheme, TwitterScheme]; public const string ItemKeyFlowType = ".FlowType"; + public const string ItemKeyActivationToken = ".ActivationToken"; public const string ClaimEmailVerified = "openshock.oauth.email_verified"; public const string ClaimDisplayName = "openshock.oauth.display_name"; diff --git a/API/OAuth/OAuthError.cs b/API/OAuth/OAuthError.cs index b07d2ba6d..408bdf6d7 100644 --- a/API/OAuth/OAuthError.cs +++ b/API/OAuth/OAuthError.cs @@ -53,6 +53,11 @@ public static class OAuthError "Your account already has an OAuth connection for this provider", HttpStatusCode.Conflict); + public static OpenShockProblem LastLoginMethod => new( + "OAuth.Connection.LastLoginMethod", + "This is the only way to sign in to this account. Set a password before disconnecting it", + HttpStatusCode.Conflict); + public static OpenShockProblem ExternalAlreadyLinked => new( "OAuth.Connection.AlreadyLinked", "This external account is already linked to another user", diff --git a/API/OAuth/OAuthUtil.cs b/API/OAuth/OAuthUtil.cs index a6ed3e9db..c8ade66fa 100644 --- a/API/OAuth/OAuthUtil.cs +++ b/API/OAuth/OAuthUtil.cs @@ -1,16 +1,56 @@ -using Microsoft.AspNetCore.Authentication; +using System.Diagnostics.CodeAnalysis; +using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Mvc; namespace OpenShock.API.OAuth; public static class OAuthUtil { - public static ChallengeResult StartOAuth(string provider, OAuthFlow flow) + /// + /// + /// + /// Token from the activation email, carried through the provider round trip so the handoff can + /// activate the account the returned identity is linked to. Only a + /// flow carries it: linking is for an account that is already signed in and never activates anything. + /// + public static ChallengeResult StartOAuth(string provider, OAuthFlow flow, string? activationToken = null) { - 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); + + if (flow == OAuthFlow.LoginOrCreate) + { + SetActivationToken(properties, activationToken); + } + + return new ChallengeResult(provider, properties); } + + /// Reads the flow that was started. False when the properties carry none, or one that is not known. + public static bool TryGetOAuthFlow(AuthenticationProperties properties, out OAuthFlow flow) + => Enum.TryParse(properties.GetString(OAuthConstants.ItemKeyFlowType), ignoreCase: true, out flow); + + public static void SetOAuthFlow(AuthenticationProperties properties, OAuthFlow flow) + => properties.SetString(OAuthConstants.ItemKeyFlowType, flow.ToString()); + + /// + /// Reads the token from the activation email that the flow carries, so the handoff can activate the + /// account the returned identity is linked to. False when there is none. + /// + public static bool TryGetActivationToken(AuthenticationProperties properties, [NotNullWhen(true)] out string? activationToken) + { + activationToken = properties.GetString(OAuthConstants.ItemKeyActivationToken); + if (!string.IsNullOrEmpty(activationToken)) return true; + + activationToken = null; + return false; + } + + /// Sets the activation token the flow carries. Null or empty removes it. + public static void SetActivationToken(AuthenticationProperties properties, string? activationToken) + => properties.SetString(OAuthConstants.ItemKeyActivationToken, string.IsNullOrEmpty(activationToken) ? null : activationToken); } diff --git a/API/Services/Account/AccountService.cs b/API/Services/Account/AccountService.cs index c975c8320..99a856884 100644 --- a/API/Services/Account/AccountService.cs +++ b/API/Services/Account/AccountService.cs @@ -76,6 +76,27 @@ private async Task NotifyEmailOutboxAsync() } } + /// Most activation emails one account, and one address, is sent per . + private const int MaxActivationEmailsPerWindow = 5; + + /// + /// Whether has already been sent as many activation emails as an address gets + /// per window, whichever accounts they were for. The cap per account alone does not protect an inbox: + /// a pending account can be replaced by a new signup, and every new account starts counting from zero. + /// Counted on the outbox, which is never pruned, so it holds across instances and deleted accounts. + /// + /// Lowercased address. + /// + private async Task IsActivationEmailCapReachedAsync(string email, CancellationToken cancellationToken) + { + var windowStart = DateTime.UtcNow - Duration.ActivationResendWindow; + var sent = await _db.EmailOutbox.CountAsync( + m => m.Recipient == email && m.Type == EmailType.AccountActivation && m.CreatedAt >= windowStart, + cancellationToken); + + return sent >= MaxActivationEmailsPerWindow; + } + private Task IsUserNameBlacklisted(string username, CancellationToken cancellationToken) => _db.UserNameBlacklists.Matching(username).AnyAsync(cancellationToken); @@ -93,6 +114,13 @@ private async Task CreateAccount(string email, string use if (await IsUserNameBlacklisted(username, cancellationToken) || await IsEmailProviderBlacklisted(email, cancellationToken)) return new AccountWithEmailOrUsernameExists(); + // This signup would mail the address (unless accounts are activated on creation). Past the cap it is + // turned away like a taken address, before it can replace whoever holds the address now. + if (!verifyOnCreation && await IsActivationEmailCapReachedAsync(email, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); + + await ReleaseEmailFromPendingAccountAsync(email, claimantOwnsEmail: false, exceptUserId: null, cancellationToken); + if (await _db.Users.AnyAsync(x => x.Email == email || x.Name == username, cancellationToken)) return new AccountWithEmailOrUsernameExists(); @@ -159,7 +187,166 @@ public async Task CreateAccountWithActivationFlowAsync(st public Task IsEmailRegisteredAsync(string email, CancellationToken cancellationToken = default) { - return _db.Users.AnyAsync(u => u.Email == email, cancellationToken); + return _db.Users.AnyAsync(u => u.Email == email && u.ActivatedAt != null, cancellationToken); + } + + /// + /// A never activated account is only a pending signup: nobody has shown the address is theirs, so it + /// must not keep the real owner (or anyone else) from signing up with that address. This deletes the + /// pending account holding , if there is one and it may be released. + /// + /// Lowercased address. + /// + /// The caller proved the address is theirs (an OAuth provider verified it). Otherwise the pending account + /// is left alone while it is younger than the activation resend cooldown: that gives its creator time to + /// open the link, and keeps repeated signups from mailing the address more often than a resend could. + /// + /// A pending account that is the caller's own and must be kept. + /// + private async Task ReleaseEmailFromPendingAccountAsync(string email, bool claimantOwnsEmail, Guid? exceptUserId, CancellationToken cancellationToken) + { + var pending = await _db.Users + .AsNoTracking() + .Where(u => u.Email == email && u.ActivatedAt == null) + .Select(u => new { u.Id, u.CreatedAt }) + .FirstOrDefaultAsync(cancellationToken); + if (pending is null || pending.Id == exceptUserId) return; + + if (!claimantOwnsEmail) + { + // A resend takes this same lock before it queues mail, so one cannot slip in between the look at + // the outbox below and the delete. Held until the caller's transaction ends. + await _db.Database.ExecuteSqlAsync($"SELECT 1 FROM users WHERE id = {pending.Id} FOR UPDATE", cancellationToken); + + // Counted from the last activation mail, not only from signup: a pending account that just had + // its mail resent would otherwise be replaced by one that mails the same inbox again right away. + var cooldownStart = DateTime.UtcNow - Duration.ActivationResendCooldown; + if (pending.CreatedAt > cooldownStart) return; + + var coalesceKey = EmailOutboxCoalesceKeys.AccountActivation(pending.Id); + if (await _db.EmailOutbox.AnyAsync(m => m.CoalesceKey == coalesceKey && m.CreatedAt >= cooldownStart, cancellationToken)) return; + } + + // Only while it still holds this address: its creator may have moved it to another one since the + // lookup above, and then it is not in the way any more. + await DeletePendingAccountAsync(pending.Id, email, cancellationToken); + } + + /// + /// Deletes an account only if it is still pending when the delete runs. The condition is part of the + /// statement, so an account that gets activated after the caller looked at it is left alone. + /// Deactivated and privileged accounts are never deleted this way. + /// + /// + /// When given, the account is only deleted while this is still its address. + /// + /// False when nothing was deleted. + private async Task DeletePendingAccountAsync(Guid userId, string? heldEmail, CancellationToken cancellationToken) + { + var deleted = heldEmail is null + ? await _db.Database.ExecuteSqlAsync($""" + DELETE FROM users AS u + WHERE u.id = {userId} + AND u.activated_at IS NULL + AND NOT (u.roles && {PrivilegedRoles.All}) + AND NOT EXISTS (SELECT 1 FROM user_deactivations AS d WHERE d.deactivated_user_id = u.id) + """, cancellationToken) + : await _db.Database.ExecuteSqlAsync($""" + DELETE FROM users AS u + WHERE u.id = {userId} + AND u.email = {heldEmail} + AND u.activated_at IS NULL + AND NOT (u.roles && {PrivilegedRoles.All}) + AND NOT EXISTS (SELECT 1 FROM user_deactivations AS d WHERE d.deactivated_user_id = u.id) + """, cancellationToken); + + return deleted > 0; + } + + /// + public async Task> RestartPendingSignupAsync(Guid userId, string email, string username, CancellationToken cancellationToken = default) + { + email = email.ToLowerInvariant(); + + // Everything below, the "still pending" check included, runs with the account's row locked. An + // activation that commits first is seen here; one that comes later waits and then finds its token + // replaced. Releasing another pending account's hold on the address is part of the same + // transaction, so every return that does not commit rolls it back. + await using var transaction = await _db.Database.BeginTransactionAsync(cancellationToken); + await _db.Database.ExecuteSqlAsync($"SELECT 1 FROM users WHERE id = {userId} FOR UPDATE", cancellationToken); + + var user = await _db.Users + .Include(u => u.UserDeactivation) + .Include(u => u.UserActivationRequest) + .FirstOrDefaultAsync(u => u.Id == userId, cancellationToken); + if (user is null) return new NotFound(); + + // The caller usually looked this account up through this same context already, and a query hands + // back that tracked instance as it was read then. Read the row as it is now. + await _db.Entry(user).ReloadAsync(cancellationToken); + if (user.ActivatedAt is not null || user.UserDeactivation is not null) return new NotFound(); + + var emailChanged = !string.Equals(user.Email, email, StringComparison.OrdinalIgnoreCase); + if (emailChanged || user.Name != username) + { + if (await IsUserNameBlacklisted(username, cancellationToken) || await IsEmailProviderBlacklisted(email, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); + + // Moving the signup to another address mails that address. + if (emailChanged && await IsActivationEmailCapReachedAsync(email, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); + + await ReleaseEmailFromPendingAccountAsync(email, claimantOwnsEmail: false, exceptUserId: userId, cancellationToken); + + if (await _db.Users.AnyAsync(u => u.Id != userId && (u.Email == email || u.Name == username), cancellationToken)) + return new AccountWithEmailOrUsernameExists(); + + user.Email = email; + user.Name = username; + + // A link already mailed was mailed to the previous address, so it says nothing about the new + // one: it must stop working in the same commit that changes the address. Otherwise the caller + // could sign up with an inbox of their own, move the account to somebody else's address and + // activate it with the link they already hold. The delivery job mints the new token when it + // sends to the new address. + if (emailChanged) + { + if (user.UserActivationRequest is not null) + { + user.UserActivationRequest.TokenHash = SeedTokenHash(); + } + + // The same goes for a password reset link requested for the previous address: completing it + // would set a password and activate the account on the new one. Reset rows carry the stamp + // they were created under, so rotating it invalidates them. + user.SecurityStamp = Guid.CreateVersion7(); + } + + try + { + await _db.SaveChangesAsync(); + } + catch (DbUpdateConcurrencyException) + { + // The old link was redeemed while this ran: the account is activated on the address it was + // mailed to, and nothing was changed here. + return new NotFound(); + } + catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: "23505" }) + { + return new AccountWithEmailOrUsernameExists(); + } + } + + await transaction.CommitAsync(cancellationToken); + + // A corrected address has not been mailed yet, so the cooldown (which protects an inbox from repeats) + // does not apply to it; the daily cap per account still does. A throttled result just means no new + // mail went out, and the resend button gets it later. If another correction got in since the commit + // above, the mail for this one is dropped: that correction queues its own. + await ResendActivationEmailCoreAsync(userId, ignoreCooldown: emailChanged, onlyIfEmailIs: emailChanged ? email : null, cancellationToken); + + return user; } public async Task CreateOAuthOnlyAccountAsync( @@ -169,11 +356,16 @@ public async Task CreateOAuthOnlyAccountAsync( string providerAccountId, string? providerAccountName, bool isEmailTrusted, + Guid? replacePendingUserId, CancellationToken cancellationToken) { email = email.ToLowerInvariant(); provider = provider.ToLowerInvariant(); + // Only a provider that verified the address shows it is the caller's. Mail being disabled (below) + // makes the new account usable without a link, it proves nothing about who owns the address. + var providerVerifiedEmail = isEmailTrusted; + // With mail disabled no activation link can reach the user, so an untrusted email cannot be // verified by any means; activate on creation rather than create a dead account. isEmailTrusted |= !_mailOptions.IsEnabled; @@ -182,14 +374,32 @@ public async Task CreateOAuthOnlyAccountAsync( 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(); + // An unverified address gets an activation email. + if (!isEmailTrusted && await IsActivationEmailCapReachedAsync(email, cancellationToken)) + return new AccountWithEmailOrUsernameExists(); - await using var tx = await _db.Database.BeginTransactionAsync(); + // Pending accounts removed to make room only stay removed if the new account is created: every + // return below that does not commit rolls them back. + await using var tx = await _db.Database.BeginTransactionAsync(cancellationToken); try { + if (replacePendingUserId is not null) + { + await DeletePendingAccountAsync(replacePendingUserId.Value, heldEmail: null, cancellationToken); + + // The caller looked that account up through this context, and its OAuth connection has the + // key the new one is about to get. Nothing is tracked yet that this method needs. + _db.ChangeTracker.Clear(); + } + + // A provider-verified address belongs to this caller, so a pending account someone parked on it goes. + await ReleaseEmailFromPendingAccountAsync(email, claimantOwnsEmail: providerVerifiedEmail, exceptUserId: null, cancellationToken); + + // Fast uniqueness check (optimistic; race handled by unique constraints below) + var exists = await _db.Users.AnyAsync(u => u.Email == email || u.Name == username, cancellationToken); + if (exists) return new AccountWithEmailOrUsernameExists(); + var creationTime = DateTime.UtcNow; var user = new User @@ -250,24 +460,85 @@ public async Task CreateOAuthOnlyAccountAsync( } - public async Task TryActivateAccountAsync(string secret, CancellationToken cancellationToken = default) + /// + public async Task> ActivateAccountAsync(string activationToken, Guid? signupBrowserUserId, string? password, CancellationToken cancellationToken = default) { - var hash = HashingUtils.HashToken(secret); + var hash = HashingUtils.HashToken(activationToken); var user = await _db.Users .Include(u => u.UserActivationRequest) - .FirstOrDefaultAsync(x => x.UserDeactivation == null && x.UserActivationRequest != null && x.UserActivationRequest.TokenHash == hash, cancellationToken); - if (user?.UserActivationRequest is null) return false; + .FirstOrDefaultAsync(x => x.ActivatedAt == null && x.UserDeactivation == null && x.UserActivationRequest != null && x.UserActivationRequest.TokenHash == hash, cancellationToken); + if (user?.UserActivationRequest is null) return new NotFound(); + + // The token proves the caller reads this inbox, nothing more: the account, and the password or OAuth + // identity on it, may have been set up by someone else using this address. So the caller must also + // be the one who signed up: the browser that did, or someone who knows the password. + var hasPassword = !string.IsNullOrEmpty(user.PasswordHash); + var credentialProven = signupBrowserUserId == user.Id; + var passwordInvalid = false; + if (!credentialProven && hasPassword && !string.IsNullOrEmpty(password)) + { + credentialProven = HashingUtils.VerifyPassword(password, user.PasswordHash!).Verified; + passwordInvalid = !credentialProven; + } - user.ActivatedAt = DateTime.UtcNow; + if (!credentialProven) + { + var providers = await _db.UserOAuthConnections + .Where(c => c.UserId == user.Id) + .Select(c => c.ProviderKey) + .ToListAsync(cancellationToken); - _db.UserActivationRequests.Remove(user.UserActivationRequest); + return new ActivationCredentialRequired(hasPassword, providers, passwordInvalid); + } - await _db.SaveChangesAsync(); + var activated = await ConsumeActivationTokenAsync(user.Id, hash, cancellationToken); + if (!activated) return new NotFound(); + + return new Success(); + } + + /// + /// Activates the account by consuming its activation request, but only if the request still carries + /// . The check and the delete are one statement, so a token that was + /// replaced since the caller looked it up (the signup's address was changed, see + /// ) cannot activate the account on its new address. + /// + private async Task ConsumeActivationTokenAsync(Guid userId, string tokenHash, CancellationToken cancellationToken) + { + await using var transaction = await _db.Database.BeginTransactionAsync(cancellationToken); + + // User row first, then the activation request: the order password reset, resend and signup + // correction take them in. Taking the request first could deadlock against any of those. + await _db.Database.ExecuteSqlAsync($"SELECT 1 FROM users WHERE id = {userId} FOR UPDATE", cancellationToken); + + var consumed = await _db.UserActivationRequests + .Where(r => r.UserId == userId && r.TokenHash == tokenHash) + .ExecuteDeleteAsync(cancellationToken); + if (consumed == 0) return false; + + var now = DateTime.UtcNow; + await _db.Users + .Where(u => u.Id == userId && u.ActivatedAt == null) + .ExecuteUpdateAsync(s => s.SetProperty(u => u.ActivatedAt, now), cancellationToken); + + await transaction.CommitAsync(cancellationToken); return true; } + /// + public async Task TryActivateAccountAsync(Guid userId, string activationToken, CancellationToken cancellationToken = default) + { + var hash = HashingUtils.HashToken(activationToken); + + var matches = await _db.Users + .AnyAsync(x => x.Id == userId && x.ActivatedAt == null && x.UserDeactivation == null && x.UserActivationRequest != null && x.UserActivationRequest.TokenHash == hash, cancellationToken); + if (!matches) return false; + + return await ConsumeActivationTokenAsync(userId, hash, cancellationToken); + } + /// public async Task> ResendActivationEmailAsync(string usernameOrEmail, CancellationToken cancellationToken = default) { @@ -281,7 +552,14 @@ public async Task - public async Task> ResendActivationEmailAsync(Guid userId, CancellationToken cancellationToken = default) + public Task> ResendActivationEmailAsync(Guid userId, CancellationToken cancellationToken = default) + => ResendActivationEmailCoreAsync(userId, ignoreCooldown: false, onlyIfEmailIs: null, cancellationToken); + + /// + /// + /// When given, nothing is queued unless this is still the account's address. + /// + private async Task> ResendActivationEmailCoreAsync(Guid userId, bool ignoreCooldown, string? onlyIfEmailIs, CancellationToken cancellationToken) { // Without mail no link can be delivered (and such accounts are activated on creation anyway). if (!_mailOptions.IsEnabled) return new NotFound(); @@ -295,8 +573,14 @@ public async Task u.UserActivationRequest) .Include(u => u.UserDeactivation) .FirstOrDefaultAsync(u => u.Id == userId, cancellationToken); - if (user is null || user.ActivatedAt is not null) return new NotFound(); + if (user is null) return new NotFound(); + + // An instance this context already tracks comes back as it was first read, so read the locked row + // as it is now: the address below is the one that gets mailed and counted. + await _db.Entry(user).ReloadAsync(cancellationToken); + if (user.ActivatedAt is not null) return new NotFound(); if (user.UserDeactivation is not null) return new AccountDeactivated(); + if (onlyIfEmailIs is not null && !string.Equals(user.Email, onlyIfEmailIs, StringComparison.OrdinalIgnoreCase)) return new Success(); // Throttle on the outbox itself (it is never auto-pruned), so the limit holds across API instances // and restarts. The signup email counts towards it. @@ -307,7 +591,10 @@ public async Task m.CreatedAt) .ToListAsync(cancellationToken); - if (recent.Count >= 5 || recent.Any(createdAt => createdAt >= DateTime.UtcNow - Duration.ActivationResendCooldown)) + if (recent.Count >= MaxActivationEmailsPerWindow || (!ignoreCooldown && recent.Any(createdAt => createdAt >= DateTime.UtcNow - Duration.ActivationResendCooldown))) + return new TooManyActivationResends(); + + if (await IsActivationEmailCapReachedAsync(user.Email, cancellationToken)) return new TooManyActivationResends(); user.UserActivationRequest ??= new UserActivationRequest @@ -586,6 +873,7 @@ public async Task> { Reset = x, IsDeactivated = x.User.UserDeactivation != null, + WasActivated = x.User.ActivatedAt != null, UserSecurityStamp = x.User.SecurityStamp }) .FirstOrDefaultAsync(x => x.Reset.Id == passwordResetId && x.Reset.UsedAt == null && x.Reset.CreatedAt >= validSince @@ -623,6 +911,24 @@ await _db.UserPasswordResets .Where(r => r.Id == reset.Reset.Id && r.UsedAt == null) .ExecuteUpdateAsync(s => s.SetProperty(r => r.UsedAt, now)); + // This reset is what activates a not yet activated account. Such an account may have been created + // by someone else on this address through an OAuth signup, and its linked identity is then theirs: + // left in place it would let them sign in to the account the inbox owner just took over. Nobody + // has proven that link and this inbox belong together, so it goes. (An unactivated account cannot + // sign in, so it has no sessions or API tokens to worry about.) + // On an activated account the links are kept, like API tokens: activating required proving both + // the inbox and the credential, so every link on it was added by its owner. + List removedProviders = []; + if (!reset.WasActivated) + { + var connections = _db.UserOAuthConnections.Where(c => c.UserId == reset.Reset.UserId); + removedProviders = await connections.Select(c => c.ProviderKey).ToListAsync(); + if (removedProviders.Count > 0) + { + await connections.ExecuteDeleteAsync(); + } + } + // Unauthenticated email-token flow proving control of the account, so the actor is the account itself. await _auditService.LogAsync( reset.Reset.UserId, @@ -630,8 +936,34 @@ await _auditService.LogAsync( actorId: reset.Reset.UserId ); + foreach (var provider in removedProviders) + { + await _auditService.LogAsync( + reset.Reset.UserId, + action: AuditAction.OAuthDisconnected, + actorId: reset.Reset.UserId, + metadata: new OAuthDisconnectedMetadata(provider), + reason: "Password reset" + ); + } + + // Whoever was signed in with the old password is signed out. Sessions live in Redis, outside this + // transaction, so they go first: if that fails nothing is committed and the link can be used again, + // rather than the reset succeeding with the old sessions left alive and no way to retry. + 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. + try + { + await _sessionService.DeleteSessionsByUserIdAsync(reset.Reset.UserId); + } + catch (Exception ex) + { + _logger.LogWarning(ex, "Failed to re-check sessions after password reset for user ID: [{Id}]", reset.Reset.UserId); + } + return new Success(); } @@ -861,13 +1193,15 @@ await _auditService.LogAsync( return new Success(); } - public async Task> TryVerifyEmailAsync(string token, CancellationToken cancellationToken = default) + public async Task> TryVerifyEmailAsync(string token, Guid userId, CancellationToken cancellationToken = default) { var hash = HashingUtils.HashToken(token); var validSince = DateTime.UtcNow - Duration.EmailChangeRequestLifetime; + // Scoped to the signed-in user: the link goes to an address that is not the account's yet, so + // whoever opens it may be a stranger being asked to vouch for someone else's account. var change = await _db.UserEmailChanges - .Where(x => x.TokenHash == hash && x.UsedAt == null && x.CreatedAt >= validSince + .Where(x => x.UserId == userId && x.TokenHash == hash && x.UsedAt == null && x.CreatedAt >= validSince && x.SecurityStampAtCreate == x.User.SecurityStamp && x.User.UserDeactivation == null && x.User.ActivatedAt != null) .Select(x => new diff --git a/API/Services/Account/IAccountService.cs b/API/Services/Account/IAccountService.cs index 3e19c8539..32f96f368 100644 --- a/API/Services/Account/IAccountService.cs +++ b/API/Services/Account/IAccountService.cs @@ -30,22 +30,52 @@ public interface IAccountService /// external subject/id from provider /// display name from provider /// + /// + /// A never activated account this same external identity signed up earlier, to be replaced by the new + /// one. Only pass this for a caller who just signed in with that identity. It is deleted in the same + /// transaction that creates the new account, so a conflict leaves it as it was. + /// /// /// Success with the created user, or AccountWithEmailOrUsernameExists when taken/blocked. - Task CreateOAuthOnlyAccountAsync(string email, string username, string provider, string providerAccountId, string? providerAccountName, bool isEmailTrusted, CancellationToken cancellationToken = default); + Task CreateOAuthOnlyAccountAsync(string email, string username, string provider, string providerAccountId, string? providerAccountName, bool isEmailTrusted, Guid? replacePendingUserId = null, CancellationToken cancellationToken = default); /// - /// Returns true if the given email is already associated with an existing user account. + /// Returns true if the given email belongs to an activated account. A never activated account is only + /// a pending signup and does not reserve its address. /// Task IsEmailRegisteredAsync(string email, CancellationToken cancellationToken = default); /// - /// + /// Lets the creator of a never activated account correct what they signed up with (typically a mistyped + /// email) and sends the activation email to the new address. Only call this for a caller who proved they + /// hold the account's credential. Sends are capped per account like any activation resend. /// - /// + Task> RestartPendingSignupAsync(Guid userId, string email, string username, CancellationToken cancellationToken = default); + + /// + /// Activates the account an emailed activation token belongs to. The token only proves control of the + /// inbox, and anyone can sign up with somebody else's address, so the caller must also show they are + /// the one who signed up: the signup browser's cookie () + /// or the account's password. An account created through OAuth is activated by signing in with the + /// linked provider instead, see . + /// + /// Token from the activation email. + /// User id from , if the request carries a valid one. + /// Password supplied alongside the token, if any. /// - /// - Task TryActivateAccountAsync(string token, CancellationToken cancellationToken = default); + /// + /// when the token is valid but that proof is missing or wrong; + /// the account stays unactivated and the token stays usable. + /// + Task> ActivateAccountAsync(string activationToken, Guid? signupBrowserUserId, string? password, CancellationToken cancellationToken = default); + + /// + /// Activates if is the token mailed to that + /// account. Only call this once the caller has proven they hold a credential of that account (a sign-in + /// with its linked OAuth identity). + /// + /// False when the token does not belong to this account or there is nothing to activate. + Task TryActivateAccountAsync(Guid userId, string activationToken, CancellationToken cancellationToken = default); /// /// Looks up the account by username or email and re-enqueues its activation email, see the overload below. @@ -100,7 +130,9 @@ public interface IAccountService /// /// Completes a password reset process, sets a new password. Since the reset link proves control of the - /// account's email, this also activates an unactivated account. + /// account's email, this also activates an unactivated account. All sessions are signed out; OAuth links + /// and API tokens are kept, except that an account activated by this reset loses the OAuth identity it + /// was signed up with (it may be someone else's). /// /// /// @@ -174,15 +206,24 @@ public interface IAccountService /// request creation and verification (race condition). /// /// + /// + /// The signed-in user confirming the change. The token is mailed to an address the account does not + /// control yet, so it only counts when presented from a session of the account that requested it. + /// /// /// - Task> TryVerifyEmailAsync(string token, CancellationToken cancellationToken = default); + Task> TryVerifyEmailAsync(string token, Guid userId, CancellationToken cancellationToken = default); } public union AccountCreationResult(User, AccountWithEmailOrUsernameExists); public sealed record VerifyEmailSuccess(Guid UserId, string OldEmail, string NewEmail); +/// Whether the account can be activated by supplying its password. +/// Providers linked to the account; signing in with one activates it. +/// A password was supplied but did not match. +public sealed record ActivationCredentialRequired(bool HasPassword, IReadOnlyList OAuthProviders, bool PasswordInvalid); + public sealed class AccountIsOAuthOnly; public sealed class AccountNotActivated; public sealed class AccountDeactivated; diff --git a/API/Services/OAuthConnection/IOAuthConnectionService.cs b/API/Services/OAuthConnection/IOAuthConnectionService.cs index 993ca1c61..fe29bf5e9 100644 --- a/API/Services/OAuthConnection/IOAuthConnectionService.cs +++ b/API/Services/OAuthConnection/IOAuthConnectionService.cs @@ -12,5 +12,18 @@ public interface IOAuthConnectionService Task ConnectionExistsAsync(string provider, string providerAccountId, CancellationToken cancellationToken = default); Task HasConnectionAsync(Guid userId, string provider, CancellationToken cancellationToken = default); Task TryAddConnectionAsync(Guid userId, string provider, string providerAccountId, string? providerAccountName, Guid? actorId, CancellationToken cancellationToken = default); - Task TryRemoveConnectionAsync(Guid userId, string provider, Guid? actorId, CancellationToken cancellationToken = default); + + /// + /// Removes the connection of the user to , unless it is the only way left to + /// sign in to the account (no password and no other connection). Removals for one user run one at a + /// time, so two of them cannot each count the connection the other is removing as the one that remains. + /// + Task RemoveConnectionAsync(Guid userId, string provider, Guid? actorId, CancellationToken cancellationToken = default); +} + +public enum RemoveConnectionResult +{ + Removed, + NotFound, + LastLoginMethod } diff --git a/API/Services/OAuthConnection/OAuthConnectionService.cs b/API/Services/OAuthConnection/OAuthConnectionService.cs index 0d0b779b2..921c73e5b 100644 --- a/API/Services/OAuthConnection/OAuthConnectionService.cs +++ b/API/Services/OAuthConnection/OAuthConnectionService.cs @@ -83,19 +83,35 @@ await _auditService.LogAsync( return true; } - public async Task TryRemoveConnectionAsync(Guid userId, string provider, Guid? actorId, CancellationToken cancellationToken) + public async Task RemoveConnectionAsync(Guid userId, string provider, Guid? actorId, CancellationToken cancellationToken) { var p = provider.ToLowerInvariant(); - - await using var transaction = await _db.Database.BeginTransactionAsync(); - + + await using var transaction = await _db.Database.BeginTransactionAsync(cancellationToken); + + // Lock the user row until commit: the check below and the delete are then one step per user. + await _db.Database.ExecuteSqlAsync($"SELECT 1 FROM users WHERE id = {userId} FOR UPDATE", cancellationToken); + + // An account without a password signs in through its connections only. Removing the last one would + // lock its owner out until they notice and go through a password reset. + var hasPassword = await _db.Users.AnyAsync(u => u.Id == userId && u.PasswordHash != null && u.PasswordHash != "", cancellationToken); + if (!hasPassword) + { + var hasOtherConnection = await _db.UserOAuthConnections.AnyAsync(c => c.UserId == userId && c.ProviderKey != p, cancellationToken); + if (!hasOtherConnection) + { + var hasThisConnection = await _db.UserOAuthConnections.AnyAsync(c => c.UserId == userId && c.ProviderKey == p, cancellationToken); + return hasThisConnection ? RemoveConnectionResult.LastLoginMethod : RemoveConnectionResult.NotFound; + } + } + var nDeleted = await _db.UserOAuthConnections .Where(c => c.UserId == userId && c.ProviderKey == p) - .ExecuteDeleteAsync(); - + .ExecuteDeleteAsync(cancellationToken); + // Nothing was linked, so don't record a disconnection that never happened. // Disposing the transaction without committing rolls back the (no-op) delete. - if (nDeleted <= 0) return false; + if (nDeleted <= 0) return RemoveConnectionResult.NotFound; await _auditService.LogAsync( userId, @@ -103,9 +119,9 @@ await _auditService.LogAsync( actorId: actorId ?? userId, metadata: new OAuthDisconnectedMetadata(provider) ); - - await transaction.CommitAsync(); - return true; + await transaction.CommitAsync(cancellationToken); + + return RemoveConnectionResult.Removed; } } diff --git a/Common/Authentication/ActivationResendCookie.cs b/Common/Authentication/ActivationResendCookie.cs index 564921e74..c1dfaa088 100644 --- a/Common/Authentication/ActivationResendCookie.cs +++ b/Common/Authentication/ActivationResendCookie.cs @@ -7,9 +7,10 @@ namespace OpenShock.Common.Authentication; /// -/// Cookie set on signup when the new account still needs activation. It lets the browser that created the account -/// ask for the activation email again ("didn't get the email?") without typing an address, so the resend endpoint -/// can't be aimed at arbitrary inboxes or used to probe which emails are registered. +/// Cookie set while this browser has a signup waiting for activation: when it creates the account, and again when +/// an OAuth signup is restarted with corrected details. It lets that browser ask for the activation email again +/// ("didn't get the email?") without typing an address, so the resend endpoint can't be aimed at arbitrary inboxes +/// or used to probe which emails are registered. The cookie alone is enough for a (rate limited) resend. /// /// /// The value is a time-limited data protection payload holding the user id (keys are persisted to the database, @@ -20,6 +21,10 @@ namespace OpenShock.Common.Authentication; /// 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. /// +/// +/// It is not proof of anything else. What marks this browser as the one that signed up, for activation, is +/// , which is set and removed together with this one. +/// /// public static class ActivationResendCookie { @@ -41,6 +46,8 @@ public static void Set(HttpContext context, Guid userId, string domain) SameSite = SameSiteMode.Lax, Domain = domain }); + + SignupBrowserCookie.Set(context, userId); } public static bool TryGetUserId(HttpContext context, [NotNullWhen(true)] out Guid? userId) @@ -66,6 +73,8 @@ public static bool TryGetUserId(HttpContext context, [NotNullWhen(true)] out Gui /// Deletes the cookie, if the request carries one, on every configured cookie domain. public static void Remove(HttpContext context) { + SignupBrowserCookie.Remove(context); + if (!context.Request.Cookies.ContainsKey(AuthConstants.ActivationResendCookieName)) return; var cookieDomains = context.RequestServices.GetRequiredService().CookieDomains; diff --git a/Common/Authentication/SignupBrowserCookie.cs b/Common/Authentication/SignupBrowserCookie.cs new file mode 100644 index 000000000..caa154ccc --- /dev/null +++ b/Common/Authentication/SignupBrowserCookie.cs @@ -0,0 +1,122 @@ +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 the browser that created a not yet activated account. The activation endpoint accepts it, together +/// with the emailed link, in place of the account's password or a sign-in with its linked provider. +/// +/// +/// Issued and removed alongside , but kept separate because it is a +/// credential and that one is not. The resend cookie has to be readable by the frontend and shared across +/// the cookie domain, which means any sibling subdomain could plant one in a visitor's browser. Planting +/// this one would let someone who signed up with another person's address have that person's click on the +/// emailed link activate the account. So this cookie is bound to the API host alone: no Domain, +/// HttpOnly, and over HTTPS the __Host- name prefix, which browsers refuse to accept from +/// anything but this exact host. +/// +/// It also carries the country the signup came from, when that could be resolved. Presented from a +/// different country it is ignored, which only means the caller is asked for the password or provider +/// sign-in like any other browser. Country and not address: addresses change too often on mobile networks +/// for an exact match to be worth the false alarms. A request whose country cannot be resolved is let +/// through, so a missing GeoIP database does not disable the cookie. +/// +/// +public static class SignupBrowserCookie +{ + private const string ProtectorPurpose = "OpenShock.SignupBrowserCookie"; + private const char PayloadSeparator = '|'; + + /// The cookie name used for a request: __Host- prefixed whenever cookies are secure. + public static string GetName(HttpContext context) => IsSecure(context) + ? AuthConstants.SignupBrowserSecureCookieName + : AuthConstants.SignupBrowserCookieName; + + /// + /// + /// Country the signup came from, or null when it is not known. + public static string CreateToken(IDataProtectionProvider provider, Guid userId, string? countryCode = null) + => GetProtector(provider).Protect($"{userId}{PayloadSeparator}{countryCode}", Duration.ActivationResendWindow); + + public static void Set(HttpContext context, Guid userId) + { + var provider = context.RequestServices.GetRequiredService(); + + context.Response.Cookies.Append(GetName(context), CreateToken(provider, userId, GetCountryCode(context)), new CookieOptions + { + Expires = DateTimeOffset.UtcNow.Add(Duration.ActivationResendWindow), + Secure = IsSecure(context), + HttpOnly = true, + SameSite = SameSiteMode.Lax, + Path = "/" + }); + } + + public static bool TryGetUserId(HttpContext context, [NotNullWhen(true)] out Guid? userId) + { + userId = null; + + // Only the name that matches this deployment: over HTTPS an unprefixed cookie is exactly what a + // sibling subdomain could have planted. + if (!context.Request.Cookies.TryGetValue(GetName(context), out var token) || string.IsNullOrEmpty(token)) + return false; + + var provider = context.RequestServices.GetRequiredService(); + try + { + var payload = GetProtector(provider).Unprotect(token).AsSpan(); + var separator = payload.IndexOf(PayloadSeparator); + if (separator < 0 || !Guid.TryParse(payload[..separator], out var id)) return false; + + // Only a known mismatch counts: unknown on either side says nothing. + var signupCountry = payload[(separator + 1)..]; + if (!signupCountry.IsEmpty + && GetCountryCode(context) is { } currentCountry + && !signupCountry.Equals(currentCountry, StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + userId = id; + return true; + } + catch (CryptographicException) + { + // Tampered, expired, or signed with a revoked key. + return false; + } + } + + /// Deletes the cookie, if the request carries one. + public static void Remove(HttpContext context) + { + var name = GetName(context); + if (!context.Request.Cookies.ContainsKey(name)) return; + + context.Response.Cookies.Delete(name, new CookieOptions + { + Secure = IsSecure(context), + HttpOnly = true, + SameSite = SameSiteMode.Lax, + Path = "/" + }); + } + + private static 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/AuthConstants.cs b/Common/Constants/AuthConstants.cs index 3fdb5c6a1..06c854e7d 100644 --- a/Common/Constants/AuthConstants.cs +++ b/Common/Constants/AuthConstants.cs @@ -4,6 +4,8 @@ public static class AuthConstants { public const string UserSessionCookieName = "openShockSession"; public const string ActivationResendCookieName = "openShockActivationResend"; + public const string SignupBrowserCookieName = "openShockSignupBrowser"; + public const string SignupBrowserSecureCookieName = "__Host-openShockSignupBrowser"; public const string UserSessionHeaderName = "OpenShockSession"; public const string ApiTokenHeaderName = "OpenShockToken"; public const string HubTokenHeaderName = "DeviceToken"; diff --git a/Common/Constants/Constants.cs b/Common/Constants/Constants.cs index d4ff32036..372015cac 100644 --- a/Common/Constants/Constants.cs +++ b/Common/Constants/Constants.cs @@ -11,6 +11,7 @@ public static class Duration public static readonly TimeSpan ActivationResendCooldown = TimeSpan.FromMinutes(10); public static readonly TimeSpan ActivationResendWindow = TimeSpan.FromHours(24); + public static readonly TimeSpan UnactivatedAccountRetentionTime = TimeSpan.FromDays(7); public static readonly TimeSpan NameChangeCooldown = TimeSpan.FromDays(7); diff --git a/Common/Errors/AccountError.cs b/Common/Errors/AccountError.cs index 96b611f88..ac8bb2c09 100644 --- a/Common/Errors/AccountError.cs +++ b/Common/Errors/AccountError.cs @@ -29,12 +29,23 @@ public static class AccountError public static OpenShockProblem AccountActivationResendUnavailable => new OpenShockProblem("Account.Activation.ResendUnavailable", "No activation email can be resent from this browser", HttpStatusCode.BadRequest); public static OpenShockProblem AccountActivationResendTooMany => new OpenShockProblem("Account.Activation.ResendTooMany", "Too many activation emails have been requested. Please try again later", HttpStatusCode.TooManyRequests); public static OpenShockProblem AccountActivationNotFound => new OpenShockProblem("Account.Activation.NotFound", "There is no account activation request matching the supplied token", HttpStatusCode.BadRequest); + public static OpenShockProblem AccountActivationCredentialRequired(bool hasPassword, IReadOnlyList oauthProviders, bool passwordInvalid) => new OpenShockProblem( + "Account.Activation.CredentialRequired", + "Activating this account from this browser also requires its password or a sign-in with its linked provider", HttpStatusCode.Forbidden) + { + Extensions = new Dictionary + { + { "hasPassword", hasPassword }, + { "oauthProviders", oauthProviders }, + { "passwordInvalid", passwordInvalid } + } + }; public static OpenShockProblem AccountDeactivated => new OpenShockProblem("Account.Deactivated", "Your account has been deactivated", HttpStatusCode.Unauthorized); public static OpenShockProblem AccountOAuthOnly => new OpenShockProblem("Account.OAuthOnly", "This account is only accessible via OAuth", HttpStatusCode.Unauthorized); public static OpenShockProblem PasswordNotSet => new OpenShockProblem("Account.Password.NotSet", - "This account has no password set. Initiate a password set flow via POST /password/set instead.", HttpStatusCode.Conflict); + "This account has no password set. Set one through the password reset flow (POST /2/account/password-reset) instead.", HttpStatusCode.Conflict); public static OpenShockProblem EmailChangeAlreadyInUse => new OpenShockProblem("Account.Email.AlreadyInUse", "This email address is already in use", HttpStatusCode.Conflict); diff --git a/Common/OpenShockControllerBase.cs b/Common/OpenShockControllerBase.cs index 1b60b3e18..3d63012fa 100644 --- a/Common/OpenShockControllerBase.cs +++ b/Common/OpenShockControllerBase.cs @@ -1,8 +1,10 @@ using Microsoft.AspNetCore.Mvc; +using Microsoft.EntityFrameworkCore; using OpenShock.Common.Authentication; using OpenShock.Common.Constants; using OpenShock.Common.Extensions; using OpenShock.Common.Models; +using OpenShock.Common.OpenShockDb; using OpenShock.Common.Options; using OpenShock.Common.Services.Geo; using OpenShock.Common.Services.Session; @@ -51,8 +53,16 @@ protected OkObjectResult LegacyEmptyOk(string message = "") return DomainUtils.GetBestMatchingCookieDomain(HttpContext.Request.Host.Host, cookieDomains); } + /// + /// + /// + /// The account's security stamp as it was when the caller checked the credential it is signing in with. + /// If the stamp has changed by the time the session exists (a password reset completed in between, and + /// its sign-out of all sessions ran before this one was created), the session is dropped again. + /// + /// False when the session was dropped; nothing was set on the response. [NonAction] - protected async Task CreateSession(Guid accountId, string domain) + protected async Task CreateSession(Guid accountId, string domain, Guid? securityStamp = null) { var frontendOptions = HttpContext.RequestServices.GetRequiredService(); var sessionService = HttpContext.RequestServices.GetRequiredService(); @@ -64,6 +74,18 @@ protected async Task CreateSession(Guid accountId, string domain) var session = await sessionService.CreateSessionAsync(accountId, userAgent, remoteIp, actorId: accountId, enrichment: enrichment); + if (securityStamp is not null) + { + // Checked after the session exists: a reset that commits later than this still finds the + // session and deletes it, one that committed earlier shows up here. + var db = HttpContext.RequestServices.GetRequiredService(); + var currentStamp = await db.Users.Where(u => u.Id == accountId).Select(u => (Guid?)u.SecurityStamp).FirstOrDefaultAsync(); + if (currentStamp != securityStamp) + { + await sessionService.DeleteSessionByIdAsync(session.Id); + return false; + } + } HttpContext.Response.Cookies.Append(AuthConstants.UserSessionCookieName, session.Token, new CookieOptions { @@ -80,6 +102,8 @@ protected async Task CreateSession(Guid accountId, string domain) // Signed in, so the post-signup "didn't get the email?" cookie has served its purpose. ActivationResendCookie.Remove(HttpContext); + + return true; } [NonAction] diff --git a/Common/OpenShockServiceHelper.cs b/Common/OpenShockServiceHelper.cs index 896a50594..7dd8675ee 100644 --- a/Common/OpenShockServiceHelper.cs +++ b/Common/OpenShockServiceHelper.cs @@ -422,8 +422,10 @@ await context.HttpContext.Response.WriteAsync("Too Many Requests. Please try aga PermitLimit = 120, Window = TimeSpan.FromMinutes(1), SegmentsPerWindow = 6, - QueueProcessingOrder = QueueProcessingOrder.OldestFirst, - QueueLimit = 10 + // No queue: this limiter runs after authentication, so a queued request would + // still execute, seconds later, with a session or API token that may have been + // revoked while it waited. Over the limit means 429, now. + QueueLimit = 0 }); }); diff --git a/Cron.IntegrationTests/Tests/DeleteUnactivatedAccountsTests.cs b/Cron.IntegrationTests/Tests/DeleteUnactivatedAccountsTests.cs new file mode 100644 index 000000000..42ca1e0c0 --- /dev/null +++ b/Cron.IntegrationTests/Tests/DeleteUnactivatedAccountsTests.cs @@ -0,0 +1,91 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using OpenShock.Common.Constants; +using OpenShock.Common.OpenShockDb; +using OpenShock.Common.Utils; +using OpenShock.Cron.Jobs; + +namespace OpenShock.Cron.IntegrationTests.Tests; + +/// +/// Runs the unactivated-account cleanup against real Postgres, so the raw delete's role_type[] +/// parameter and the deactivation sub-select are exercised. +/// +public sealed class DeleteUnactivatedAccountsTests +{ + [ClassDataSource(Shared = SharedType.PerTestSession)] + public required CronApplicationFactory Factory { get; init; } + + [Test] + public async Task Execute_DeletesOnlyStaleUnactivatedAccounts() + { + var stale = DateTime.UtcNow - Duration.UnactivatedAccountRetentionTime - TimeSpan.FromHours(1); + var recent = DateTime.UtcNow - TimeSpan.FromHours(1); + + var staleUnactivated = Guid.CreateVersion7(); + var recentUnactivated = Guid.CreateVersion7(); + var staleActivated = Guid.CreateVersion7(); + var staleUnactivatedStaff = Guid.CreateVersion7(); + var staleUnactivatedDeactivated = Guid.CreateVersion7(); + + await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + { + var pending = NewUser(staleUnactivated, stale, activated: false, []); + pending.UserActivationRequest = new UserActivationRequest + { + UserId = staleUnactivated, + TokenHash = HashingUtils.HashToken(Guid.NewGuid().ToString("N")) + }; + db.Users.Add(pending); + db.Users.Add(NewUser(recentUnactivated, recent, activated: false, [])); + db.Users.Add(NewUser(staleActivated, stale, activated: true, [])); + db.Users.Add(NewUser(staleUnactivatedStaff, stale, activated: false, [RoleType.Staff])); + + var deactivated = NewUser(staleUnactivatedDeactivated, stale, activated: false, []); + deactivated.UserDeactivation = new UserDeactivation + { + DeactivatedUserId = staleUnactivatedDeactivated, + DeactivatedByUserId = staleUnactivatedDeactivated, + DeleteLater = false + }; + db.Users.Add(deactivated); + + await db.SaveChangesAsync(); + } + + await using var scope = Factory.Services.CreateAsyncScope(); + var job = ActivatorUtilities.CreateInstance(scope.ServiceProvider); + + await job.Execute(); + + await using var verify = await Factory.DbContextFactory.CreateDbContextAsync(); + var remaining = await verify.Users + .Where(u => new[] { staleUnactivated, recentUnactivated, staleActivated, staleUnactivatedStaff, staleUnactivatedDeactivated }.Contains(u.Id)) + .Select(u => u.Id) + .ToListAsync(); + + await Assert.That(remaining).DoesNotContain(staleUnactivated); + await Assert.That(remaining).Contains(recentUnactivated); + await Assert.That(remaining).Contains(staleActivated); + await Assert.That(remaining).Contains(staleUnactivatedStaff); + await Assert.That(remaining).Contains(staleUnactivatedDeactivated); + + // The activation link dies with the account. + await Assert.That(await verify.UserActivationRequests.AnyAsync(r => r.UserId == staleUnactivated)).IsFalse(); + } + + private static User NewUser(Guid id, DateTime createdAt, bool activated, List roles) + { + var suffix = Guid.NewGuid().ToString("N")[..12]; + return new User + { + Id = id, + Name = $"unact{suffix}", + Email = $"unact-{suffix}@test.org", + SecurityStamp = Guid.CreateVersion7(), + Roles = roles, + CreatedAt = createdAt, + ActivatedAt = activated ? createdAt : null + }; + } +} diff --git a/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs b/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs index da1e9352b..8e08fce6a 100644 --- a/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs +++ b/Cron.IntegrationTests/Tests/EmailOutboxDeliveryTests.cs @@ -105,6 +105,93 @@ public async Task PasswordReset_NewerRequest_SupersedesOlder_OnlyNewestDelivered } } + [Test] + public async Task AccountActivation_QueuedForAPreviousAddress_IsSkipped_AndMintsNoToken() + { + // The pending signup's address was corrected after this message was queued: the link would activate + // the account on its new address, so it must not go to the old one. + var oldEmail = UniqueEmail("cron-activation-old"); + var newEmail = UniqueEmail("cron-activation-new"); + using var mailpit = Factory.CreateMailpitHelper(); + + var userId = Guid.CreateVersion7(); + var seededHash = HashingUtils.HashToken(CryptoUtils.RandomString(AuthConstants.GeneratedTokenLength)); + Guid outboxId; + await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + { + db.Users.Add(new User + { + Id = userId, + Name = "Activation User " + Guid.NewGuid().ToString("N")[..8], + Email = newEmail, + PasswordHash = null, + CreatedAt = DateTime.UtcNow, + ActivatedAt = null + }); + db.UserActivationRequests.Add(new UserActivationRequest { UserId = userId, TokenHash = seededHash }); + var outbox = EmailOutboxMessage.ForAccountActivation(userId, oldEmail, "Activation User"); + db.EmailOutbox.Add(outbox); + await db.SaveChangesAsync(); + outboxId = outbox.Id; + } + + await Factory.RunDeliveryAsync(); + + await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + { + var row = await db.EmailOutbox.AsNoTracking().SingleAsync(m => m.Id == outboxId); + await Assert.That(row.Status).IsEqualTo(EmailStatus.Skipped); + + var request = await db.UserActivationRequests.AsNoTracking().SingleAsync(r => r.UserId == userId); + await Assert.That(request.TokenHash).IsEqualTo(seededHash); + } + + await Assert.That((await mailpit.SearchByRecipientAsync(oldEmail)).Count).IsEqualTo(0); + } + + [Test] + public async Task AccountActivation_IsDelivered_AndEmailedTokenMatchesStoredHash() + { + var email = UniqueEmail("cron-activation"); + using var mailpit = Factory.CreateMailpitHelper(); + + var userId = Guid.CreateVersion7(); + await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + { + db.Users.Add(new User + { + Id = userId, + Name = "Activation User " + Guid.NewGuid().ToString("N")[..8], + Email = email, + PasswordHash = null, + CreatedAt = DateTime.UtcNow, + ActivatedAt = null + }); + db.UserActivationRequests.Add(new UserActivationRequest + { + UserId = userId, + TokenHash = HashingUtils.HashToken(CryptoUtils.RandomString(AuthConstants.GeneratedTokenLength)) + }); + db.EmailOutbox.Add(EmailOutboxMessage.ForAccountActivation(userId, email, "Activation User")); + await db.SaveChangesAsync(); + } + + await Factory.RunDeliveryAsync(); + + var message = await mailpit.WaitForMessageAsync(email); + await Assert.That(message).IsNotNull(); + + var full = await mailpit.GetMessageAsync(message!.Id); + var token = Regex.Match(full!.Html, @"activate\?token=([A-Za-z0-9_\-]+)").Groups[1].Value; + await Assert.That(token).IsNotEmpty(); + + await using (var db = await Factory.DbContextFactory.CreateDbContextAsync()) + { + var request = await db.UserActivationRequests.AsNoTracking().SingleAsync(r => r.UserId == userId); + await Assert.That(request.TokenHash).IsEqualTo(HashingUtils.HashToken(token)); + } + } + // --- Helpers --- private async Task<(Guid UserId, Guid Stamp)> AddUserAsync(string email, string name) @@ -159,7 +246,7 @@ private async Task AddPendingResetOutboxAsync(Guid userId, Guid stamp, str return outbox.Id; } - private static string UniqueEmail(string prefix) => $"{prefix}-{Guid.CreateVersion7().ToString("N")[..8]}@test.org"; + private static string UniqueEmail(string prefix) => $"{prefix}-{Guid.NewGuid().ToString("N")[..8]}@test.org"; private static string? ExtractResetToken(string html) { diff --git a/Cron/Jobs/DeleteUnactivatedAccountsJob.cs b/Cron/Jobs/DeleteUnactivatedAccountsJob.cs new file mode 100644 index 000000000..109bcd1f5 --- /dev/null +++ b/Cron/Jobs/DeleteUnactivatedAccountsJob.cs @@ -0,0 +1,57 @@ +using Microsoft.EntityFrameworkCore; +using OpenShock.Common.Constants; +using OpenShock.Common.OpenShockDb; +using OpenShock.Cron.Attributes; + +namespace OpenShock.Cron.Jobs; + +/// +/// Hard-deletes accounts that were never activated within +/// of being created. Anyone can sign up with somebody else's address, and such an account would otherwise hold +/// that email and username forever and keep its activation link alive indefinitely. Deleting the account takes +/// its activation request with it, so this is also what expires the link. +/// +/// +/// An unactivated account has never had a session, so it owns nothing worth keeping. Deactivated accounts are +/// left to (a moderation record), and privileged accounts are never touched. +/// +[CronJob("30 * * * *")] // Every hour +public sealed class DeleteUnactivatedAccountsJob +{ + private readonly OpenShockContext _db; + private readonly IHostApplicationLifetime _lifetime; + private readonly ILogger _logger; + + /// + /// DI constructor + /// + /// + /// Its stopping token cancels the job when the server shuts down. + /// + public DeleteUnactivatedAccountsJob(OpenShockContext db, IHostApplicationLifetime lifetime, ILogger logger) + { + _db = db; + _lifetime = lifetime; + _logger = logger; + } + + public async Task Execute() + { + var cancellationToken = _lifetime.ApplicationStopping; + var createdBefore = DateTime.UtcNow - Duration.UnactivatedAccountRetentionTime; + + // One statement, so an account activated between a read and the delete can't be caught: + // Postgres rechecks a row that changed under the delete. + var nDeleted = await _db.Database.ExecuteSqlAsync($""" + DELETE FROM users AS u + WHERE u.activated_at IS NULL + AND u.created_at < {createdBefore} + AND NOT (u.roles && {PrivilegedRoles.All}) + AND NOT EXISTS (SELECT 1 FROM user_deactivations AS d WHERE d.deactivated_user_id = u.id) + """, cancellationToken); + + _logger.LogInformation("Deleted {DeletedCount} accounts that were never activated since {CreatedBefore}", nDeleted, createdBefore); + + return nDeleted; + } +} diff --git a/Cron/Services/Email/Outbox/EmailOutboxDispatcher.cs b/Cron/Services/Email/Outbox/EmailOutboxDispatcher.cs index d0af3d3f4..338e5bd7a 100644 --- a/Cron/Services/Email/Outbox/EmailOutboxDispatcher.cs +++ b/Cron/Services/Email/Outbox/EmailOutboxDispatcher.cs @@ -69,7 +69,21 @@ private async Task SendAccountActivation(EmailOutboxMessage if (request is null) return EmailDispatchResult.Skip("Activation request no longer exists"); if (request.User.ActivatedAt is not null) return EmailDispatchResult.Skip("Account already activated"); - var token = await MintTokenAsync(db, h => request.TokenHash = h, ct); + // A pending signup can have its address corrected after this message was queued. The link activates + // the account as it is now, so it may only go to the address the account has now. + if (!string.Equals(message.Recipient, request.User.Email, StringComparison.OrdinalIgnoreCase)) + return EmailDispatchResult.Skip("Account email changed since this message was queued"); + + // Changing the address also replaces the token hash, in the same commit. Writing the new hash only + // over the one read above therefore means the address cannot have changed in between. + var token = CryptoUtils.RandomString(AuthConstants.GeneratedTokenLength); + var newHash = HashingUtils.HashToken(token); + var previousHash = request.TokenHash; + var minted = await db.UserActivationRequests + .Where(r => r.UserId == userId && r.TokenHash == previousHash) + .ExecuteUpdateAsync(s => s.SetProperty(r => r.TokenHash, newHash), ct); + if (minted == 0) return EmailDispatchResult.Skip("Activation request changed since this message was queued"); + var link = new Uri(_frontendOptions.BaseUrl, $"/activate?token={token}"); return FromSend(await _emailService.ActivateAccount(ToContact(message), link, ct)); }