Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 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
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);
}
}
161 changes: 161 additions & 0 deletions API.IntegrationTests/Helpers/PendingSignupHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
using Microsoft.AspNetCore.DataProtection;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using OpenShock.Common.Authentication;
using OpenShock.Common.Constants;
using OpenShock.Common.OpenShockDb;
using OpenShock.Common.Utils;

namespace OpenShock.API.IntegrationTests.Helpers;

/// <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);
}

public static Task<HttpResponseMessage> PostLoginAsync(HttpClient client, string usernameOrEmail, string password, string? cookie = null)
{
var request = new HttpRequestMessage(HttpMethod.Post, "/2/account/login")
{
Content = TestHelper.JsonContent(new
{
usernameOrEmail,
password,
turnstileResponse = "valid-token"
})
};
if (cookie is not null) request.Headers.Add("Cookie", cookie);
return client.SendAsync(request);
}
}
4 changes: 2 additions & 2 deletions API.IntegrationTests/Helpers/TestHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ public static StringContent JsonContent(object obj)
/// </summary>
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";
}

Expand All @@ -189,7 +189,7 @@ public static string UniqueEmail(string prefix)
/// </summary>
public static string UniqueUsername(string prefix)
{
var suffix = Guid.CreateVersion7().ToString("N")[..8];
var suffix = Guid.NewGuid().ToString("N")[..8];
return ($"{prefix}{suffix}").ToLowerInvariant();
}
}
Expand Down
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
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
8 changes: 3 additions & 5 deletions API.IntegrationTests/Tests/MailDisabledTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
namespace OpenShock.API.IntegrationTests.Tests;

/// <summary>
/// With no mail provider configured no activation link can ever be delivered, so signup must activate
/// With no mail provider configured no activation code can ever be delivered, so signup must activate
/// the account outright instead of parking it behind an activation flow it can never complete.
/// </summary>
public sealed class MailDisabledTests
Expand All @@ -35,13 +35,11 @@ public async Task V2Signup_MailDisabled_ActivatesAccountAndEnqueuesNoEmail()
await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();

var user = await db.Users
.Include(u => u.UserActivationRequest)
.FirstOrDefaultAsync(u => u.Email == email);
var user = await db.Users.FirstOrDefaultAsync(u => u.Email == email);

await Assert.That(user).IsNotNull();
await Assert.That(user!.ActivatedAt).IsNotNull();
await Assert.That(user.UserActivationRequest).IsNull();
await Assert.That(await db.PendingSignups.AnyAsync(p => p.Email == email)).IsFalse();

var activationMails = await db.EmailOutbox
.CountAsync(m => m.Recipient == email && m.Type == EmailType.AccountActivation);
Expand Down
Loading