progmaweb
The site and account service of Progmasoft: a Next.js frontend and an ASP.NET Core API.
Clonegit clone https://git.progmasoft.com/progmaweb
Prevent Google account pre-hijacking and unsafe email-based identity merging by persisting the provider subject, indexing it independently, rejecting unverified password-account collisions and email races, reconciling only identical Google identities, and covering both service-level concurrency and the protected external-auth callback path.
- Commit
2e222079630adf07c0e14a1827283b0a26897149- Author
- Leitwolf11 ·
- Parents
3f84eee09b08
Changes
apps/api-tests/AccountEndpointTests.cs | 43 ++++++++ apps/api-tests/AccountServiceTests.cs | 173 ++++++++++++++++++++++++++++++ apps/api/Accounts/AccountContracts.cs | 5 +- apps/api/Accounts/AccountEndpoints.cs | 3 +- apps/api/Accounts/AccountRecord.cs | 1 + apps/api/Accounts/AccountService.cs | 29 ++++- apps/api/Accounts/IAccountStore.cs | 1 + apps/api/Accounts/InMemoryAccountStore.cs | 22 ++++ apps/api/Progmaweb.Api.csproj | 3 + 9 files changed, 273 insertions(+), 7 deletions(-) diff --git a/apps/api-tests/AccountEndpointTests.cs b/apps/api-tests/AccountEndpointTests.cs index cd73c71..8453824 100644 --- a/apps/api-tests/AccountEndpointTests.cs +++ b/apps/api-tests/AccountEndpointTests.cs @@ -3,7 +3,13 @@ using System.Net; using System.Net.Http.Json; +using System.Security.Claims; using System.Text.Json; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Progmasoft.Progmaweb.Api.Accounts; namespace Progmasoft.Progmaweb.Api.Tests; @@ -41,6 +47,43 @@ public sealed class AccountEndpointTests Assert.Equal("/register?google=invalid-account-name", response.Headers.Location?.OriginalString); } + [Fact] + public async Task GoogleCompleteDoesNotIssueASessionForAnExistingPasswordAccountWithTheSameEmail() + { + await using AccountApiFactory factory = new(); + using HttpClient registrationClient = factory.CreateAccountClient(); + HttpResponseMessage registration = + await RegisterAsync(registrationClient, "PasswordUser", "victim@example.com"); + Assert.Equal(HttpStatusCode.Created, registration.StatusCode); + + IOptionsMonitor<CookieAuthenticationOptions> cookieOptions = + factory.Services.GetRequiredService<IOptionsMonitor<CookieAuthenticationOptions>>(); + CookieAuthenticationOptions externalOptions = cookieOptions.Get(AccountEndpoints.ExternalCookieScheme); + ClaimsPrincipal googlePrincipal = new(new ClaimsIdentity( + [ + new Claim(ClaimTypes.NameIdentifier, "google-subject-victim"), + new Claim(ClaimTypes.Email, "victim@example.com") + ], + "Google")); + AuthenticationTicket googleTicket = new( + googlePrincipal, + new AuthenticationProperties(), + AccountEndpoints.ExternalCookieScheme); + string protectedTicket = externalOptions.TicketDataFormat.Protect(googleTicket); + + using HttpClient googleClient = factory.CreateAccountClient(handleCookies: false); + using HttpRequestMessage request = new(HttpMethod.Get, "/api/v1/accounts/oauth/google/complete"); + request.Headers.Add("Cookie", $"{externalOptions.Cookie.Name}={protectedTicket}"); + HttpResponseMessage response = + await googleClient.SendAsync(request, TestContext.Current.CancellationToken); + + Assert.Equal(HttpStatusCode.Redirect, response.StatusCode); + Assert.Equal("/login?google=failed", response.Headers.Location?.OriginalString); + Assert.DoesNotContain( + response.Headers.GetValues("Set-Cookie"), + value => value.StartsWith("__Host-ProgmasoftSession=", StringComparison.Ordinal)); + } + [Fact] public async Task RegisterCreatesSessionAndMeReturnsAccount() { diff --git a/apps/api-tests/AccountServiceTests.cs b/apps/api-tests/AccountServiceTests.cs new file mode 100644 index 0000000..c2a9a46 --- /dev/null +++ b/apps/api-tests/AccountServiceTests.cs @@ -0,0 +1,173 @@ +// SPDX-FileCopyrightText: 2026 Progmasoft <support@progmasoft.com> +// SPDX-License-Identifier: AGPL-3.0-or-later WITH AdditionRef-Progmasoft-Patent-Grant-1.1 + +using Microsoft.Extensions.Options; +using Progmasoft.Progmaweb.Api.Accounts; + +namespace Progmasoft.Progmaweb.Api.Tests; + +public sealed class AccountServiceTests +{ + [Fact] + public async Task GoogleAuthenticationRejectsAnEmailWithoutAProviderSubject() + { + InMemoryAccountStore store = new(); + AccountService accounts = new(store, TimeProvider.System); + SessionService sessions = new( + store, + TimeProvider.System, + Options.Create(new AccountSessionOptions())); + + (AuthenticatedAccount? authentication, GoogleAccountFailure failure) = + await accounts.AuthenticateGoogleAsync( + null, + "google@example.com", + "GoogleUser", + sessions, + TestContext.Current.CancellationToken); + + Assert.Null(authentication); + Assert.Equal(GoogleAccountFailure.ProviderRejected, failure); + } + + [Fact] + public async Task GoogleAuthenticationDoesNotLinkAnUnverifiedPasswordAccountByEmail() + { + InMemoryAccountStore store = new(); + AccountService accounts = new(store, TimeProvider.System); + SessionService sessions = new( + store, + TimeProvider.System, + Options.Create(new AccountSessionOptions())); + + (AuthenticatedAccount? registration, _) = await accounts.RegisterAsync( + new RegisterAccountRequest( + "PasswordUser", + "unverified@example.com", + "a-long-development-password"), + sessions, + TestContext.Current.CancellationToken); + Assert.NotNull(registration); + + (AuthenticatedAccount? authentication, GoogleAccountFailure failure) = + await accounts.AuthenticateGoogleAsync( + "google-subject-victim", + "unverified@example.com", + null, + sessions, + TestContext.Current.CancellationToken); + + Assert.Null(authentication); + Assert.Equal(GoogleAccountFailure.ProviderRejected, failure); + } + + [Fact] + public async Task GoogleAuthenticationDoesNotLinkAConcurrentPasswordAccountByEmail() + { + AccountRecord passwordAccount = new( + Guid.NewGuid(), + "PasswordUser", + "PASSWORDUSER", + "race@example.com", + "RACE@EXAMPLE.COM", + null, + "password-hash", + DateTimeOffset.UtcNow); + ConcurrentPasswordRegistrationStore store = new(passwordAccount); + AccountService accounts = new(store, TimeProvider.System); + SessionService sessions = new( + store, + TimeProvider.System, + Options.Create(new AccountSessionOptions())); + + (AuthenticatedAccount? authentication, GoogleAccountFailure failure) = + await accounts.AuthenticateGoogleAsync( + "google-subject-race", + "race@example.com", + "GoogleUser", + sessions, + TestContext.Current.CancellationToken); + + Assert.Null(authentication); + Assert.Equal(GoogleAccountFailure.ProviderRejected, failure); + Assert.Equal(0, store.StoredSessionCount); + } + + [Fact] + public async Task GoogleAuthenticationReusesAnExistingGoogleOnlyAccount() + { + InMemoryAccountStore store = new(); + AccountService accounts = new(store, TimeProvider.System); + SessionService sessions = new( + store, + TimeProvider.System, + Options.Create(new AccountSessionOptions())); + (AuthenticatedAccount? first, GoogleAccountFailure firstFailure) = + await accounts.AuthenticateGoogleAsync( + "google-subject-stable", + "google@example.com", + "GoogleUser", + sessions, + TestContext.Current.CancellationToken); + + (AuthenticatedAccount? second, GoogleAccountFailure secondFailure) = + await accounts.AuthenticateGoogleAsync( + "google-subject-stable", + "changed@example.com", + null, + sessions, + TestContext.Current.CancellationToken); + + Assert.NotNull(first); + Assert.Equal(GoogleAccountFailure.None, firstFailure); + Assert.NotNull(second); + Assert.Equal(GoogleAccountFailure.None, secondFailure); + Assert.Equal(first.Account.Id, second.Account.Id); + } + + private sealed class ConcurrentPasswordRegistrationStore(AccountRecord passwordAccount) : IAccountStore + { + private bool createAttempted; + + public int StoredSessionCount { get; private set; } + + public ValueTask<CreateAccountResult> CreateAsync( + AccountRecord account, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + createAttempted = true; + return ValueTask.FromResult(CreateAccountResult.EmailUnavailable()); + } + + public ValueTask<AccountRecord?> FindByEmailAsync( + string normalizedEmail, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + return ValueTask.FromResult<AccountRecord?>(createAttempted ? passwordAccount : null); + } + + public ValueTask<AccountRecord?> FindByIdAsync(Guid id, CancellationToken cancellationToken) => + ValueTask.FromResult<AccountRecord?>(passwordAccount.Id == id ? passwordAccount : null); + + public ValueTask<AccountRecord?> FindByGoogleSubjectAsync( + string googleSubject, + CancellationToken cancellationToken) => + ValueTask.FromResult<AccountRecord?>(null); + + public ValueTask StoreSessionAsync(SessionRecord session, CancellationToken cancellationToken) + { + StoredSessionCount++; + return ValueTask.CompletedTask; + } + + public ValueTask<SessionRecord?> FindSessionAsync( + byte[] tokenDigest, + CancellationToken cancellationToken) => + ValueTask.FromResult<SessionRecord?>(null); + + public ValueTask RevokeSessionAsync(byte[] tokenDigest, CancellationToken cancellationToken) => + ValueTask.CompletedTask; + } +} diff --git a/apps/api/Accounts/AccountContracts.cs b/apps/api/Accounts/AccountContracts.cs index 6f73c38..ca7ddb1 100644 --- a/apps/api/Accounts/AccountContracts.cs +++ b/apps/api/Accounts/AccountContracts.cs @@ -15,7 +15,8 @@ internal enum CreateAccountStatus { Created, AccountNameUnavailable, - EmailUnavailable + EmailUnavailable, + GoogleSubjectUnavailable } internal sealed record CreateAccountResult(CreateAccountStatus Status, AccountRecord? Account) @@ -23,5 +24,7 @@ internal sealed record CreateAccountResult(CreateAccountStatus Status, AccountRe public static CreateAccountResult Created(AccountRecord account) => new(CreateAccountStatus.Created, account); public static CreateAccountResult AccountNameUnavailable() => new(CreateAccountStatus.AccountNameUnavailable, null); public static CreateAccountResult EmailUnavailable() => new(CreateAccountStatus.EmailUnavailable, null); + public static CreateAccountResult GoogleSubjectUnavailable() => + new(CreateAccountStatus.GoogleSubjectUnavailable, null); } diff --git a/apps/api/Accounts/AccountEndpoints.cs b/apps/api/Accounts/AccountEndpoints.cs index f543c3f..06f4997 100644 --- a/apps/api/Accounts/AccountEndpoints.cs +++ b/apps/api/Accounts/AccountEndpoints.cs @@ -67,10 +67,11 @@ internal static class AccountEndpoints } string? email = external.Principal.FindFirstValue(ClaimTypes.Email); + string? subject = external.Principal.FindFirstValue(ClaimTypes.NameIdentifier); string? accountName = null; external.Properties?.Items.TryGetValue("accountName", out accountName); (AuthenticatedAccount? authentication, GoogleAccountFailure failure) = - await accounts.AuthenticateGoogleAsync(email, accountName, sessions, cancellationToken); + await accounts.AuthenticateGoogleAsync(subject, email, accountName, sessions, cancellationToken); await context.SignOutAsync(ExternalCookieScheme); if (authentication is null) diff --git a/apps/api/Accounts/AccountRecord.cs b/apps/api/Accounts/AccountRecord.cs index 1e38aeb..7625168 100644 --- a/apps/api/Accounts/AccountRecord.cs +++ b/apps/api/Accounts/AccountRecord.cs @@ -9,6 +9,7 @@ internal sealed record AccountRecord( string NormalizedAccountName, string Email, string NormalizedEmail, + string? GoogleSubject, string? PasswordHash, DateTimeOffset CreatedAt); diff --git a/apps/api/Accounts/AccountService.cs b/apps/api/Accounts/AccountService.cs index 03208af..2126f2b 100644 --- a/apps/api/Accounts/AccountService.cs +++ b/apps/api/Accounts/AccountService.cs @@ -29,6 +29,7 @@ internal sealed class AccountService( AccountNamePolicy.NormalizeForLookup(accountName), email, normalizedEmail, + null, string.Empty, timeProvider.GetUtcNow()); @@ -66,7 +67,7 @@ internal sealed class AccountService( { // A fixed dummy record keeps the missing-account path on the same password-hashing primitive. AccountRecord dummyBase = new(Guid.Empty, "Missing00", "MISSING00", "missing@example.invalid", - "MISSING@EXAMPLE.INVALID", string.Empty, DateTimeOffset.UnixEpoch); + "MISSING@EXAMPLE.INVALID", null, string.Empty, DateTimeOffset.UnixEpoch); AccountRecord dummy = dummyBase with { PasswordHash = passwordHasher.HashPassword(dummyBase, "not-the-provided-password") @@ -87,20 +88,32 @@ internal sealed class AccountService( public async ValueTask<(AuthenticatedAccount? Authentication, GoogleAccountFailure Failure)> AuthenticateGoogleAsync( + string? providerSubject, string? providerEmail, string? requestedAccountName, SessionService sessions, CancellationToken cancellationToken) { - if (!EmailAddressPolicy.TryNormalize(providerEmail, out string email, out string normalizedEmail, out _)) + if (string.IsNullOrWhiteSpace(providerSubject) || + !EmailAddressPolicy.TryNormalize(providerEmail, out string email, out string normalizedEmail, out _)) { return (null, GoogleAccountFailure.ProviderRejected); } + AccountRecord? knownGoogleAccount = + await store.FindByGoogleSubjectAsync(providerSubject, cancellationToken); + if (knownGoogleAccount is not null) + { + return (await sessions.CreateAsync(knownGoogleAccount, cancellationToken), GoogleAccountFailure.None); + } + AccountRecord? existing = await store.FindByEmailAsync(normalizedEmail, cancellationToken); if (existing is not null) { - return (await sessions.CreateAsync(existing, cancellationToken), GoogleAccountFailure.None); + // Password registrations do not verify ownership of the supplied email address yet. Automatically + // linking a verified Google identity by email would therefore let two unrelated people share an + // account (and any already-issued sessions) when one of them registered the other's address. + return (null, GoogleAccountFailure.ProviderRejected); } if (requestedAccountName is null) @@ -119,6 +132,7 @@ internal sealed class AccountService( AccountNamePolicy.NormalizeForLookup(accountName), email, normalizedEmail, + providerSubject, null, timeProvider.GetUtcNow()); CreateAccountResult result = await store.CreateAsync(account, cancellationToken); @@ -130,8 +144,13 @@ internal sealed class AccountService( if (result.Status is CreateAccountStatus.EmailUnavailable) { - // A concurrent callback may have created the same verified Google identity. - AccountRecord? concurrent = await store.FindByEmailAsync(normalizedEmail, cancellationToken); + // Any different identity can win the email race, including an unverified password registration. + return (null, GoogleAccountFailure.ProviderRejected); + } + + if (result.Status is CreateAccountStatus.GoogleSubjectUnavailable) + { + AccountRecord? concurrent = await store.FindByGoogleSubjectAsync(providerSubject, cancellationToken); return concurrent is null ? (null, GoogleAccountFailure.ProviderRejected) : (await sessions.CreateAsync(concurrent, cancellationToken), GoogleAccountFailure.None); diff --git a/apps/api/Accounts/IAccountStore.cs b/apps/api/Accounts/IAccountStore.cs index 625d4f9..6bb2955 100644 --- a/apps/api/Accounts/IAccountStore.cs +++ b/apps/api/Accounts/IAccountStore.cs @@ -7,6 +7,7 @@ internal interface IAccountStore { ValueTask<CreateAccountResult> CreateAsync(AccountRecord account, CancellationToken cancellationToken); ValueTask<AccountRecord?> FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken); + ValueTask<AccountRecord?> FindByGoogleSubjectAsync(string googleSubject, CancellationToken cancellationToken); ValueTask<AccountRecord?> FindByIdAsync(Guid id, CancellationToken cancellationToken); ValueTask StoreSessionAsync(SessionRecord session, CancellationToken cancellationToken); ValueTask<SessionRecord?> FindSessionAsync(byte[] tokenDigest, CancellationToken cancellationToken); diff --git a/apps/api/Accounts/InMemoryAccountStore.cs b/apps/api/Accounts/InMemoryAccountStore.cs index 51c19f2..9f183e7 100644 --- a/apps/api/Accounts/InMemoryAccountStore.cs +++ b/apps/api/Accounts/InMemoryAccountStore.cs @@ -10,6 +10,7 @@ internal sealed class InMemoryAccountStore : IAccountStore private readonly Lock gate = new(); private readonly Dictionary<Guid, AccountRecord> accountsById = []; private readonly Dictionary<string, Guid> accountIdsByEmail = new(StringComparer.Ordinal); + private readonly Dictionary<string, Guid> accountIdsByGoogleSubject = new(StringComparer.Ordinal); private readonly Dictionary<string, Guid> accountIdsByName = new(StringComparer.Ordinal); private readonly Dictionary<string, SessionRecord> sessionsByDigest = new(StringComparer.Ordinal); @@ -19,6 +20,11 @@ internal sealed class InMemoryAccountStore : IAccountStore lock (gate) { + if (account.GoogleSubject is not null && accountIdsByGoogleSubject.ContainsKey(account.GoogleSubject)) + { + return ValueTask.FromResult(CreateAccountResult.GoogleSubjectUnavailable()); + } + if (accountIdsByName.ContainsKey(account.NormalizedAccountName)) { return ValueTask.FromResult(CreateAccountResult.AccountNameUnavailable()); @@ -32,10 +38,26 @@ internal sealed class InMemoryAccountStore : IAccountStore accountsById.Add(account.Id, account); accountIdsByName.Add(account.NormalizedAccountName, account.Id); accountIdsByEmail.Add(account.NormalizedEmail, account.Id); + if (account.GoogleSubject is not null) + { + accountIdsByGoogleSubject.Add(account.GoogleSubject, account.Id); + } return ValueTask.FromResult(CreateAccountResult.Created(account)); } } + public ValueTask<AccountRecord?> FindByGoogleSubjectAsync( + string googleSubject, + CancellationToken cancellationToken) + { + cancellationToken.ThrowIfCancellationRequested(); + lock (gate) + { + return ValueTask.FromResult( + accountIdsByGoogleSubject.TryGetValue(googleSubject, out Guid id) ? accountsById[id] : null); + } + } + public ValueTask<AccountRecord?> FindByEmailAsync(string normalizedEmail, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); diff --git a/apps/api/Progmaweb.Api.csproj b/apps/api/Progmaweb.Api.csproj index 62f8768..c633ca7 100644 --- a/apps/api/Progmaweb.Api.csproj +++ b/apps/api/Progmaweb.Api.csproj @@ -11,4 +11,7 @@ <ItemGroup> <PackageReference Include="Microsoft.AspNetCore.Authentication.Google" Version="10.0.11" /> </ItemGroup> + <ItemGroup> + <InternalsVisibleTo Include="Progmaweb.Api.Tests" /> + </ItemGroup> </Project>