Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
28 commits
Select commit Hold shift + click to select a range
d3559d7
fix: require account proof for activation and email change verification
hhvrc Nov 25, 2026
79aad39
Merge branch 'develop' into fix/account-activation-email-verification
hhvrc Nov 26, 2026
68e359d
test: cover hub auth revalidation and fix colliding test usernames
hhvrc Nov 26, 2026
12b8a06
fix: invalidate the mailed activation link when a pending signup chan…
hhvrc Nov 26, 2026
a8d6cca
fix: bind the signup browser proof to the API host and test the OAuth…
hhvrc Nov 26, 2026
fb7c799
fix: address review findings on pending signups, connection removal a…
hhvrc Nov 26, 2026
f05b1ff
Merge branch 'develop' into fix/account-activation-email-verification
hhvrc Nov 26, 2026
e428b3d
refactor: let StartOAuth decide which flows carry the activation token
hhvrc Nov 26, 2026
de7d668
feat: close hub connections when their session or API token is revoked
hhvrc Nov 26, 2026
882449a
feat: bind the signup browser cookie to the country of the signup
hhvrc Nov 26, 2026
8a1a560
feat: cap activation emails per address
hhvrc Nov 26, 2026
cedaecf
refactor: move hub connection revocation out to its own change
hhvrc Nov 26, 2026
22dd4c9
fix: close races around pending signups, activation and password login
hhvrc Nov 26, 2026
b88fe20
refactor: name awaited results instead of negating the await
hhvrc Nov 26, 2026
e5a1029
refactor: read and write OAuth flow state through extension properties
hhvrc Nov 26, 2026
a7f6213
refactor: use OAuthUtil helpers for OAuth flow state instead of exten…
hhvrc Nov 26, 2026
8dcdba0
Merge branch 'develop' into fix/account-activation-email-verification
hhvrc Nov 26, 2026
c631646
fix: address review findings in the account activation flow
hhvrc Nov 27, 2026
f2dde14
fix: address remaining account flow review findings
hhvrc Nov 28, 2026
65a594b
fix: serialize the per-address activation email cap
hhvrc Nov 28, 2026
18452fe
feat: verify the address before an account exists, with a mailed code
hhvrc Nov 28, 2026
603cf9d
feat: mail signup codes as two groups of four letters or digits
hhvrc Nov 29, 2026
219f199
maybe fix
hhvrc Nov 29, 2026
3789393
Merge branch 'develop' into fix/account-activation-email-verification
hhvrc Nov 29, 2026
5e2bd44
refactor: share account creation, signup resume and signup audit code
hhvrc Nov 30, 2026
da4fd5e
Merge remote-tracking branch 'origin/develop' into fix/account-activa…
hhvrc Dec 4, 2026
bea7671
fix migration name
hhvrc Dec 4, 2026
112406a
fix: address review findings on pending signups and split out SignupS…
hhvrc Dec 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion API.IntegrationTests/GeoLocatedWebApplicationFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ public GeoPoint? ClientLocation
set => _enrichment.Location = value;
}

/// <summary>Country every request resolves to, or null for "unknown".</summary>
public string? ClientCountryCode
{
get => _enrichment.CountryCode;
set => _enrichment.CountryCode = value;
}

protected override void ConfigureWebHost(IWebHostBuilder builder)
{
base.ConfigureWebHost(builder);
Expand All @@ -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);
}
}
167 changes: 167 additions & 0 deletions API.IntegrationTests/Helpers/PendingSignupHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenShock.Common.Authentication;
using OpenShock.Common.Constants;
using OpenShock.Common.OpenShockDb;
using OpenShock.Common.Utils;

namespace OpenShock.API.IntegrationTests.Helpers;

/// <summary>
/// Pending signups for tests, and the two things a browser needs to complete one: the cookies that say it
/// holds the signup, and the code mailed to its address. The code is minted by the Cron delivery job when
/// it sends the mail, so tests that want one stand in for that job with <see cref="MailCodeAsync"/>.
/// </summary>
public static class PendingSignupHelper
{
public const string Password = "SecurePassword123#";

/// <summary>Creates a pending signup directly in the DB, with no mail queued for it and no code mailed.</summary>
public static async Task<Guid> CreateInDbAsync(
WebApplicationFactory factory,
string email,
string username,
string? password = Password,
string? oauthProvider = null,
string? oauthExternalId = null)
{
await using var scope = factory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();

var id = Guid.CreateVersion7();
db.PendingSignups.Add(new PendingSignup
{
Id = id,
Email = email,
Username = username,
PasswordHash = password is null ? null : HashingUtils.HashPassword(password),
OAuthProviderKey = oauthProvider,
OAuthExternalId = oauthExternalId,
OAuthDisplayName = oauthProvider is null ? null : "external",
CodeHash = HashingUtils.HashToken(Guid.NewGuid().ToString("N")),
CreatedAt = DateTime.UtcNow
});
await db.SaveChangesAsync();

return id;
}

/// <summary>
/// Stands in for the Cron delivery job mailing the signup its code: stores the hash of a new code, starts
/// its lifetime and gives it all its attempts back. Returns the code "the mail" carries.
/// </summary>
public static async Task<string> MailCodeAsync(WebApplicationFactory factory, Guid pendingSignupId, string? code = null)
{
code ??= SignupCode.Generate();
var hash = SignupCode.Hash(pendingSignupId, code);
var now = DateTime.UtcNow;

await using var scope = factory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();
var updated = await db.PendingSignups
.Where(p => p.Id == pendingSignupId)
.ExecuteUpdateAsync(s => s
.SetProperty(p => p.CodeHash, hash)
.SetProperty(p => p.CodeSentAt, now)
.SetProperty(p => p.FailedAttempts, 0));
if (updated != 1) throw new InvalidOperationException($"No pending signup {pendingSignupId} to mail a code to");

return code;
}

public static async Task<PendingSignup?> FindAsync(WebApplicationFactory factory, Guid pendingSignupId)
{
await using var scope = factory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();
return await db.PendingSignups.AsNoTracking().FirstOrDefaultAsync(p => p.Id == pendingSignupId);
}

public static async Task<List<PendingSignup>> FindByEmailAsync(WebApplicationFactory factory, string email)
{
await using var scope = factory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();
return await db.PendingSignups.AsNoTracking().Where(p => p.Email == email).OrderBy(p => p.CreatedAt).ToListAsync();
}

public static async Task<User?> FindUserByEmailAsync(WebApplicationFactory factory, string email)
{
await using var scope = factory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();
return await db.Users.AsNoTracking().FirstOrDefaultAsync(u => u.Email == email);
}

/// <summary>The cookie that marks a browser as holding the signup, as the API would have set it over HTTPS.</summary>
public static string MintSignupBrowserCookie(WebApplicationFactory factory, Guid pendingSignupId, string? countryCode = null)
{
var provider = factory.Services.GetRequiredService<IDataProtectionProvider>();
return $"{AuthConstants.SignupBrowserSecureCookieName}={SignupBrowserCookie.CreateToken(provider, pendingSignupId, countryCode)}";
}

/// <summary>The <c>name=value</c> part of a cookie a response sets, ready to send back in a Cookie header.</summary>
public static string ReadSetCookie(HttpResponseMessage response, string name)
=> response.Headers.GetValues("Set-Cookie").Single(c => c.StartsWith(name + "=")).Split(';')[0];

public static bool SetsCookie(HttpResponseMessage response, string name) =>
response.Headers.TryGetValues("Set-Cookie", out var values) &&
values.Any(c => c.StartsWith(name + "=") && !c.StartsWith(name + "=;"));

// A deleted cookie comes back as an empty value with an expiry in the past.
public static bool DeletesCookie(HttpResponseMessage response, string name) =>
response.Headers.TryGetValues("Set-Cookie", out var values) &&
values.Any(c => c.StartsWith(name + "=;") && c.Contains("expires=Thu, 01 Jan 1970", StringComparison.OrdinalIgnoreCase));

public static Task<HttpResponseMessage> PostSignupAsync(HttpClient client, string email, string username, string password = Password) =>
client.PostAsync("/2/account/signup", TestHelper.JsonContent(new
{
username,
password,
email,
turnstileResponse = "valid-token"
}));

public static Task<HttpResponseMessage> PostActivateAsync(HttpClient client, string code, string? cookie)
{
var request = new HttpRequestMessage(HttpMethod.Post, "/1/account/activate")
{
Content = TestHelper.JsonContent(new { code })
};
if (cookie is not null) request.Headers.Add("Cookie", cookie);
return client.SendAsync(request);
}

public static Task<HttpResponseMessage> GetPendingActivationAsync(HttpClient client, string? cookie)
{
var request = new HttpRequestMessage(HttpMethod.Get, "/1/account/activate");
if (cookie is not null) request.Headers.Add("Cookie", cookie);
return client.SendAsync(request);
}

public static Task<HttpResponseMessage> PostResendAsync(HttpClient client, string? cookie)
{
var request = new HttpRequestMessage(HttpMethod.Post, "/1/account/activate/resend");
if (cookie is not null) request.Headers.Add("Cookie", cookie);
return client.SendAsync(request);
}

/// <param name="client"></param>
/// <param name="usernameOrEmail"></param>
/// <param name="password"></param>
/// <param name="cookie"></param>
/// <param name="origin">The page a browser would be sending this from. Null for a request no page sent.</param>
public static Task<HttpResponseMessage> PostLoginAsync(HttpClient client, string usernameOrEmail, string password, string? cookie = null, string? origin = null)
{
var request = new HttpRequestMessage(HttpMethod.Post, "/2/account/login")
{
Content = TestHelper.JsonContent(new
{
usernameOrEmail,
password,
turnstileResponse = "valid-token"
})
};
if (cookie is not null) request.Headers.Add("Cookie", cookie);
if (origin is not null) request.Headers.Add("Origin", origin);
return client.SendAsync(request);
}
}
10 changes: 10 additions & 0 deletions API.IntegrationTests/Tests/AccountSignupTests.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
using System.Net;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenShock.API.IntegrationTests.Helpers;
using OpenShock.Common.Constants;
using OpenShock.Common.OpenShockDb;

namespace OpenShock.API.IntegrationTests.Tests;
Expand Down Expand Up @@ -45,6 +47,14 @@ public async Task V2Signup_Success_CreatesUser()

await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);

// The account exists once the mailed code is entered in the browser that signed up.
var pending = (await PendingSignupHelper.FindByEmailAsync(WebApplicationFactory, "v2user@test.org")).Single();
var code = await PendingSignupHelper.MailCodeAsync(WebApplicationFactory, pending.Id);
var cookie = PendingSignupHelper.ReadSetCookie(response, AuthConstants.SignupBrowserSecureCookieName);
using var browser = WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions { HandleCookies = false });
var activated = await PendingSignupHelper.PostActivateAsync(browser, code, cookie);
await Assert.That(activated.StatusCode).IsEqualTo(HttpStatusCode.OK);

await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();
var user = await db.Users.FirstOrDefaultAsync(u => u.Email == "v2user@test.org");
Expand Down
11 changes: 11 additions & 0 deletions API.IntegrationTests/Tests/AccountTests.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
using System.Net;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenShock.API.IntegrationTests.Helpers;
using OpenShock.Common.Constants;
using OpenShock.Common.OpenShockDb;

namespace OpenShock.API.IntegrationTests.Tests;
Expand Down Expand Up @@ -29,6 +32,14 @@ public async Task CreateAccount_ShouldAdd_NewUserToDatabase()

await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);

// The account exists once the mailed code is entered in the browser that signed up.
var pending = (await PendingSignupHelper.FindByEmailAsync(WebApplicationFactory, "bob@example.com")).Single();
var code = await PendingSignupHelper.MailCodeAsync(WebApplicationFactory, pending.Id);
var cookie = PendingSignupHelper.ReadSetCookie(response, AuthConstants.SignupBrowserSecureCookieName);
using var browser = WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions { HandleCookies = false });
var activated = await PendingSignupHelper.PostActivateAsync(browser, code, cookie);
await Assert.That(activated.StatusCode).IsEqualTo(HttpStatusCode.OK);

await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();

Expand Down
113 changes: 113 additions & 0 deletions API.IntegrationTests/Tests/AdminSignupTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
using System.Net;
using System.Text.Json;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenShock.API.IntegrationTests.Helpers;
using OpenShock.Common.Models;
using OpenShock.Common.OpenShockDb;
using static OpenShock.API.IntegrationTests.Helpers.PendingSignupHelper;

namespace OpenShock.API.IntegrationTests.Tests;

/// <summary>
/// What an admin can do about signups that are not accounts: see and delete the pending ones, and activate
/// an account from before accounts were created activated, which nothing else can activate any more.
/// </summary>
public sealed class AdminSignupTests
{
[ClassDataSource<WebApplicationFactory>(Shared = SharedType.PerTestSession)]
public required WebApplicationFactory WebApplicationFactory { get; init; }

[Test]
public async Task ListPendingSignups_ByEmail_ReturnsTheSignup_WithoutItsCredentialOrCode()
{
var email = TestHelper.UniqueEmail("admin-pending-list");
var username = TestHelper.UniqueUsername("adminpendinglist");
var pendingId = await CreateInDbAsync(WebApplicationFactory, email, username);
using var client = await CreateAdminClient("adminpendinglister");

var response = await client.GetAsync($"/1/admin/pendingSignups?match={Uri.EscapeDataString(email)}");

await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);
var body = await response.Content.ReadAsStringAsync();
using var json = JsonDocument.Parse(body);
var signups = json.RootElement.EnumerateArray().ToList();
await Assert.That(signups.Count).IsEqualTo(1);
await Assert.That(signups[0].GetProperty("id").GetGuid()).IsEqualTo(pendingId);
await Assert.That(signups[0].GetProperty("username").GetString()).IsEqualTo(username);
await Assert.That(body).DoesNotContain("passwordHash", StringComparison.OrdinalIgnoreCase);
await Assert.That(body).DoesNotContain("codeHash", StringComparison.OrdinalIgnoreCase);
}

[Test]
public async Task DeletePendingSignup_RemovesIt_AndASecondDeleteReturns404()
{
var pendingId = await CreateInDbAsync(WebApplicationFactory, TestHelper.UniqueEmail("admin-pending-delete"), TestHelper.UniqueUsername("adminpendingdelete"));
using var client = await CreateAdminClient("adminpendingdeleter");

var first = await client.DeleteAsync($"/1/admin/pendingSignups/{pendingId}");
var second = await client.DeleteAsync($"/1/admin/pendingSignups/{pendingId}");

await Assert.That(first.StatusCode).IsEqualTo(HttpStatusCode.NoContent);
await Assert.That(second.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
await Assert.That(await FindAsync(WebApplicationFactory, pendingId)).IsNull();
}

[Test]
public async Task PendingSignups_NotAnAdmin_IsRefused()
{
var user = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername("adminpendingnobody"), TestHelper.UniqueEmail("admin-pending-nobody"), Password);
using var client = TestHelper.CreateAuthenticatedClient(WebApplicationFactory, user.SessionToken);

var response = await client.GetAsync("/1/admin/pendingSignups");

await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Forbidden);
}

// The PendingSignups migration leaves a few unactivated accounts for a person to look at. Until an
// admin activates one it cannot sign in, and nothing else activates it.
[Test]
public async Task ActivateUser_AccountLeftUnactivated_CanSignInAfterwards()
{
var email = TestHelper.UniqueEmail("admin-activate");
var userId = await TestHelper.CreateUserInDb(WebApplicationFactory, TestHelper.UniqueUsername("adminactivate"), email, Password);
await using (var scope = WebApplicationFactory.Services.CreateAsyncScope())
{
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();
await db.Users.Where(u => u.Id == userId).ExecuteUpdateAsync(s => s.SetProperty(u => u.ActivatedAt, (DateTime?)null));
}

using var anonymous = WebApplicationFactory.CreateClient();
var before = await PostLoginAsync(anonymous, email, Password);
await Assert.That(before.StatusCode).IsEqualTo(HttpStatusCode.Unauthorized);
await Assert.That(await before.Content.ReadAsStringAsync()).Contains("Account.AccountNotActivated");

using var admin = await CreateAdminClient("adminactivator");
var activate = await admin.PutAsync($"/1/admin/users/{userId}/activate", null);
await Assert.That(activate.StatusCode).IsEqualTo(HttpStatusCode.OK);

var after = await PostLoginAsync(anonymous, email, Password);
await Assert.That(after.StatusCode).IsEqualTo(HttpStatusCode.OK);
}

[Test]
public async Task ActivateUser_UnknownUser_Returns404()
{
using var admin = await CreateAdminClient("adminactivatenobody");

var response = await admin.PutAsync($"/1/admin/users/{Guid.CreateVersion7()}/activate", null);

await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.NotFound);
}

private async Task<HttpClient> CreateAdminClient(string prefix)
{
var admin = await TestHelper.CreateAndLoginUser(WebApplicationFactory, TestHelper.UniqueUsername(prefix), TestHelper.UniqueEmail(prefix), Password);

await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();
await db.Users.Where(u => u.Id == admin.Id).ExecuteUpdateAsync(s => s.SetProperty(u => u.Roles, [RoleType.Admin]));

return TestHelper.CreateAuthenticatedClient(WebApplicationFactory, admin.SessionToken);
}
}
11 changes: 11 additions & 0 deletions API.IntegrationTests/Tests/AutomationTokenTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
using System.Net;
using System.Text.Json;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenShock.API.IntegrationTests.Helpers;
Expand Down Expand Up @@ -41,6 +42,16 @@ public async Task Signup_WithTurnstileToken_BypassesTurnstileAndLinksAccount()

await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK);

// The signup is linked to the token right away, and the account it becomes carries that over
// together with the audit entry for the use, whether or not the completing request has the token.
var pending = (await PendingSignupHelper.FindByEmailAsync(WebApplicationFactory, email)).Single();
await Assert.That(pending.CreatedByAutomationTokenId).IsEqualTo(tokenId);

var code = await PendingSignupHelper.MailCodeAsync(WebApplicationFactory, pending.Id);
using var browser = WebApplicationFactory.CreateClient(new WebApplicationFactoryClientOptions { HandleCookies = false });
var activated = await PendingSignupHelper.PostActivateAsync(browser, code, PendingSignupHelper.MintSignupBrowserCookie(WebApplicationFactory, pending.Id));
await Assert.That(activated.StatusCode).IsEqualTo(HttpStatusCode.OK);

await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();
var user = await db.Users.AsNoTracking().FirstAsync(u => u.Email == email);
Expand Down
Loading