Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 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
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);
}
}
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
634 changes: 634 additions & 0 deletions API.IntegrationTests/Tests/MailTests.cs

Large diffs are not rendered by default.

432 changes: 432 additions & 0 deletions API.IntegrationTests/Tests/OAuthFlowTests.cs

Large diffs are not rendered by default.

150 changes: 150 additions & 0 deletions API.IntegrationTests/Tests/SignupBrowserCookieCountryTests.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// The signup browser cookie only stands in for the account's credential when it comes back from the
/// country the signup was made in.
/// </summary>
// 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<GeoLocatedWebApplicationFactory>(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<IDataProtectionProvider>();
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
});

/// <summary>Signs up through the API, and stands in for the Cron job that mails the activation link.</summary>
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<OpenShockContext>();
userId = await db.Users.AsNoTracking().Where(u => u.Email == email).Select(u => u.Id).SingleAsync();
}

return (userId, await SeedActivationTokenAsync(userId), cookie);
}

private async Task<string> 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<OpenShockContext>();
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<HttpResponseMessage> 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<bool> IsActivatedAsync(Guid userId)
{
await using var scope = WebApplicationFactory.Services.CreateAsyncScope();
var db = scope.ServiceProvider.GetRequiredService<OpenShockContext>();
return await db.Users.AsNoTracking().Where(u => u.Id == userId).Select(u => u.ActivatedAt != null).SingleAsync();
}
}
5 changes: 5 additions & 0 deletions API.IntegrationTests/WebApplicationFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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" },

Expand Down
42 changes: 37 additions & 5 deletions API/Controller/Account/Activate.cs
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -11,14 +16,41 @@ public sealed partial class AccountController
/// <summary>
/// Activate account
/// </summary>
/// <remarks>
/// 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 <c>activationToken</c>.
/// </remarks>
/// <response code="200">Account activated</response>
/// <response code="400">No pending activation matches the token</response>
/// <response code="403">The token is valid, but the account's password or linked sign-in is also required</response>
[HttpPost("activate")]
[ApiVersion(1)]
[EnableRateLimiting("auth")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType<OpenShockProblem>(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)]
public async Task<IActionResult> Activate([FromQuery(Name = "token")] string token, CancellationToken cancellationToken)
[ProducesResponseType<OpenShockProblem>(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] // AccountActivationNotFound
[ProducesResponseType<OpenShockProblem>(StatusCodes.Status403Forbidden, MediaTypeNames.Application.ProblemJson)] // AccountActivationCredentialRequired
public async Task<IActionResult> 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
{
/// <summary>The account's password. Only needed when activating from a browser other than the one that signed up.</summary>
public string? Password { get; init; }
}
}
2 changes: 1 addition & 1 deletion API/Controller/Account/Authenticated/ChangePassword.cs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ public sealed partial class AuthenticatedAccountController
public async Task<IActionResult> 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);
Expand Down
20 changes: 14 additions & 6 deletions API/Controller/Account/Authenticated/OAuthConnectionRemove.cs
Original file line number Diff line number Diff line change
@@ -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;

Expand All @@ -14,17 +18,21 @@ public sealed partial class AuthenticatedAccountController
/// <param name="cancellationToken"></param>
/// <response code="204">Connection removed.</response>
/// <response code="404">No connection found for this provider.</response>
/// <response code="409">The connection is the account's only way to sign in.</response>
[HttpDelete("connections/{provider}")]
[ApiVersion(1)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[ProducesResponseType<OpenShockProblem>(StatusCodes.Status409Conflict, MediaTypeNames.Application.ProblemJson)] // LastLoginMethod
public async Task<IActionResult> 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()
};
}
}
44 changes: 44 additions & 0 deletions API/Controller/Account/Authenticated/VerifyEmailChange.cs
Original file line number Diff line number Diff line change
@@ -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
{
/// <summary>
/// Verify a pending email change of the current user using the token from the verification email.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
/// <response code="200">Email change verified and applied</response>
/// <response code="400">Token is invalid, already used, expired, or belongs to another account</response>
/// <response code="409">The new email address was claimed by another account before verification completed</response>
[HttpPost("email-change/verify")]
[ApiVersion(1)]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType<OpenShockProblem>(StatusCodes.Status400BadRequest, MediaTypeNames.Application.ProblemJson)] // EmailChangeNotFound
[ProducesResponseType<OpenShockProblem>(StatusCodes.Status409Conflict, MediaTypeNames.Application.ProblemJson)] // EmailChangeAlreadyInUse
public async Task<IActionResult> 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()
};
}
}
5 changes: 4 additions & 1 deletion API/Controller/Account/LoginV2.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,10 @@ async Task<IActionResult> 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));
}
Expand Down
Loading