diff --git a/EssentialCSharp.Web.Tests/Identity/AccountRecoveryHardeningTests.cs b/EssentialCSharp.Web.Tests/Identity/AccountRecoveryHardeningTests.cs new file mode 100644 index 00000000..de43b471 --- /dev/null +++ b/EssentialCSharp.Web.Tests/Identity/AccountRecoveryHardeningTests.cs @@ -0,0 +1,144 @@ +using System.Net; +using EssentialCSharp.Web.Areas.Identity.Data; +using EssentialCSharp.Web.Services; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; + +namespace EssentialCSharp.Web.Tests.Identity; + +/// +/// Regression tests for the smaller account findings: the RegisterConfirmation existence oracle, email links that +/// took their origin from the Host header, and lockout of accounts that have no password. +/// +public class AccountRecoveryHardeningTests : IntegrationTestBase +{ + [Test] + public async Task RegisterConfirmation_LooksTheSameForRegisteredAndUnknownEmails() + { + IdentityFlowHarness harness = new(Factory.Inner); + string registered = IdentityFlowHarness.UniqueEmail("registered"); + await harness.CreateConfirmedUserAsync(registered, IdentityFlowHarness.StrongPassword); + string unknown = IdentityFlowHarness.UniqueEmail("unknown"); + + using HttpResponseMessage forRegistered = await harness.NewBrowser().GetAsync($"/Identity/Account/RegisterConfirmation?email={Uri.EscapeDataString(registered)}"); + using HttpResponseMessage forUnknown = await harness.NewBrowser().GetAsync($"/Identity/Account/RegisterConfirmation?email={Uri.EscapeDataString(unknown)}"); + string registeredBody = await forRegistered.Content.ReadAsStringAsync(); + string unknownBody = await forUnknown.Content.ReadAsStringAsync(); + + using (Assert.Multiple()) + { + await Assert.That(forRegistered.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(forUnknown.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(registeredBody).Contains("Please check your email to confirm your account"); + await Assert.That(unknownBody).Contains("Please check your email to confirm your account"); + await Assert.That(unknownBody).DoesNotContain("Unable to load user"); + } + } + + [Test] + public async Task PasswordResetLink_UsesTheConfiguredSiteUrlEvenWithAForgedHostHeader() + { + IdentityFlowHarness harness = new(Factory.Inner, hostHeader: "attacker.example"); + string email = IdentityFlowHarness.UniqueEmail("victim"); + await harness.CreateConfirmedUserAsync(email, IdentityFlowHarness.StrongPassword); + string siteUrl = harness.Services.GetRequiredService>().Value.BaseUrl.TrimEnd('/'); + + using HttpResponseMessage forgot = await harness.NewBrowser().PostFormAsync("/Identity/Account/ForgotPassword", new() { ["Input.Email"] = email }); + string link = harness.LinkFromEmail(email, "Reset Password"); + + using (Assert.Multiple()) + { + await Assert.That(link).StartsWith($"{siteUrl}/Identity/Account/ResetPassword?", StringComparison.Ordinal); + await Assert.That(link).DoesNotContain("attacker.example"); + } + } + + [Test] + public async Task ConfirmationLink_UsesTheConfiguredSiteUrlEvenWithAForgedHostHeader() + { + IdentityFlowHarness harness = new(Factory.Inner, hostHeader: "attacker.example"); + string email = IdentityFlowHarness.UniqueEmail("reader"); + string siteUrl = harness.Services.GetRequiredService>().Value.BaseUrl.TrimEnd('/'); + + using HttpResponseMessage registered = await harness.NewBrowser().PostFormAsync("/Identity/Account/Register", new() + { + ["Input.UserName"] = $"user-{Guid.NewGuid():N}", + ["Input.FirstName"] = "Test", + ["Input.LastName"] = "User", + ["Input.Email"] = email, + ["Input.Password"] = IdentityFlowHarness.StrongPassword, + ["Input.ConfirmPassword"] = IdentityFlowHarness.StrongPassword, + }); + string link = harness.LinkFromEmail(email, "Confirm your email"); + + await Assert.That(link).StartsWith($"{siteUrl}/Identity/Account/ConfirmEmail?", StringComparison.Ordinal); + } + + [Test] + public async Task WrongPasswords_DoNotLockAnAccountThatHasNoPassword() + { + IdentityFlowHarness harness = new(Factory.Inner); + string email = IdentityFlowHarness.UniqueEmail("github-only"); + string userId = await harness.CreateConfirmedUserAsync(email, password: null); + await harness.InScopeAsync(async sp => + { + UserManager users = sp.GetRequiredService>(); + return await users.AddLoginAsync((await users.FindByIdAsync(userId))!, new UserLoginInfo("GitHub", "github-only-1", "GitHub")); + }); + + for (int attempt = 0; attempt < 5; attempt++) + { + await harness.NewBrowser().LogInWithPasswordAsync(email, IdentityFlowHarness.StrongPassword); + } + + Browser owner = harness.NewBrowser(); + owner.SetCookie(harness.CreateExternalLoginCookie("GitHub", "github-only-1")); + using HttpResponseMessage callback = await owner.GetAsync("/Identity/Account/ExternalLogin?handler=Callback"); + + EssentialCSharpWebUser user = (await harness.FindUserAsync(email))!; + using (Assert.Multiple()) + { + await Assert.That(user.AccessFailedCount).IsEqualTo(0); + await Assert.That(user.LockoutEnd).IsNull(); + await Assert.That(callback.Headers.Location?.OriginalString).IsEqualTo("/"); + await Assert.That(owner.HasCookie(IdentityFlowHarness.ApplicationCookieName)).IsTrue(); + } + } + + [Test] + public async Task WrongPasswords_StillLockAnAccountThatHasAPassword() + { + IdentityFlowHarness harness = new(Factory.Inner); + string email = IdentityFlowHarness.UniqueEmail("member"); + await harness.CreateConfirmedUserAsync(email, IdentityFlowHarness.StrongPassword); + + for (int attempt = 0; attempt < 3; attempt++) + { + await harness.NewBrowser().LogInWithPasswordAsync(email, IdentityFlowHarness.OtherStrongPassword); + } + + EssentialCSharpWebUser user = (await harness.FindUserAsync(email))!; + await Assert.That(user.LockoutEnd.GetValueOrDefault()).IsGreaterThan(DateTimeOffset.UtcNow); + } + + [Test] + public async Task PasswordReset_ClearsALockoutCausedByOtherPeoplesGuesses() + { + IdentityFlowHarness harness = new(Factory.Inner); + string email = IdentityFlowHarness.UniqueEmail("member"); + await harness.CreateConfirmedUserAsync(email, IdentityFlowHarness.StrongPassword); + for (int attempt = 0; attempt < 3; attempt++) + { + await harness.NewBrowser().LogInWithPasswordAsync(email, IdentityFlowHarness.OtherStrongPassword); + } + + await harness.ResetPasswordThroughPagesAsync(harness.NewBrowser(), email, IdentityFlowHarness.OtherStrongPassword); + + using (Assert.Multiple()) + { + await Assert.That((await harness.FindUserAsync(email))!.LockoutEnd).IsNull(); + await Assert.That(await harness.NewBrowser().LogInWithPasswordAsync(email, IdentityFlowHarness.OtherStrongPassword)).IsTrue(); + } + } +} diff --git a/EssentialCSharp.Web.Tests/Identity/ConfirmEmailChangeTests.cs b/EssentialCSharp.Web.Tests/Identity/ConfirmEmailChangeTests.cs new file mode 100644 index 00000000..2b201093 --- /dev/null +++ b/EssentialCSharp.Web.Tests/Identity/ConfirmEmailChangeTests.cs @@ -0,0 +1,94 @@ +using System.Net; +using EssentialCSharp.Web.Areas.Identity.Data; + +namespace EssentialCSharp.Web.Tests.Identity; + +/// +/// Regression tests for the email-change pre-account hijack: opening the change link must not attach the new +/// address to the requesting account unless the requester (not just the address owner) is the one confirming. +/// +public class ConfirmEmailChangeTests : IntegrationTestBase +{ + private static async Task<(IdentityFlowHarness Harness, Browser Requester, string RequesterEmail, string NewEmail, string Link)> RequestChangeAsync(Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory factory) + { + IdentityFlowHarness harness = new(factory); + string requesterEmail = IdentityFlowHarness.UniqueEmail("requester"); + string newEmail = IdentityFlowHarness.UniqueEmail("owner"); + await harness.CreateConfirmedUserAsync(requesterEmail, IdentityFlowHarness.StrongPassword); + Browser requester = harness.NewBrowser(); + if (!await requester.LogInWithPasswordAsync(requesterEmail, IdentityFlowHarness.StrongPassword)) + { + throw new InvalidOperationException("The requester could not log in."); + } + + using HttpResponseMessage change = await requester.PostFormAsync( + "/Identity/Account/Manage/Email?handler=ChangeEmail", + new() { ["Input.NewEmail"] = newEmail }, + getUrl: "/Identity/Account/Manage/Email"); + string link = IdentityFlowHarness.PathAndQuery(harness.LinkFromEmail(newEmail, "Confirm your email change")); + return (harness, requester, requesterEmail, newEmail, link); + } + + [Test] + public async Task ChangeEmailMessage_DescribesTheChangeRatherThanARegistration() + { + (IdentityFlowHarness harness, _, _, string newEmail, _) = await RequestChangeAsync(Factory.Inner); + + string body = harness.Email.Last(newEmail, "Confirm your email change").Body; + await Assert.That(body).Contains("change the email address"); + } + + [Test] + public async Task AnonymousClickOnTheChangeLink_DoesNotChangeTheEmail() + { + (IdentityFlowHarness harness, _, string requesterEmail, string newEmail, string link) = await RequestChangeAsync(Factory.Inner); + + using HttpResponseMessage click = await harness.NewBrowser().GetAsync(link); + + using (Assert.Multiple()) + { + await Assert.That(click.StatusCode).IsEqualTo(HttpStatusCode.Redirect); + await Assert.That(click.Headers.Location?.OriginalString).Contains("/Identity/Account/Login"); + await Assert.That(await harness.FindUserAsync(newEmail)).IsNull(); + await Assert.That(await harness.FindUserAsync(requesterEmail)).IsNotNull(); + } + } + + [Test] + public async Task ClickByADifferentSignedInUser_DoesNotChangeTheEmail() + { + (IdentityFlowHarness harness, _, string requesterEmail, string newEmail, string link) = await RequestChangeAsync(Factory.Inner); + string otherEmail = IdentityFlowHarness.UniqueEmail("other"); + await harness.CreateConfirmedUserAsync(otherEmail, IdentityFlowHarness.StrongPassword); + Browser other = harness.NewBrowser(); + await other.LogInWithPasswordAsync(otherEmail, IdentityFlowHarness.StrongPassword); + + using HttpResponseMessage click = await other.GetAsync(link); + string body = await click.Content.ReadAsStringAsync(); + + using (Assert.Multiple()) + { + await Assert.That(click.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(body).Contains("Error changing email"); + await Assert.That(await harness.FindUserAsync(newEmail)).IsNull(); + await Assert.That(await harness.FindUserAsync(requesterEmail)).IsNotNull(); + } + } + + [Test] + public async Task ClickByTheSignedInRequester_ChangesTheEmail() + { + (IdentityFlowHarness harness, Browser requester, string requesterEmail, string newEmail, string link) = await RequestChangeAsync(Factory.Inner); + + using HttpResponseMessage click = await requester.GetAsync(link); + string body = await click.Content.ReadAsStringAsync(); + + EssentialCSharpWebUser? changed = await harness.FindUserAsync(newEmail); + using (Assert.Multiple()) + { + await Assert.That(body).Contains("Thank you for confirming your email change."); + await Assert.That(changed).IsNotNull(); + await Assert.That(await harness.FindUserAsync(requesterEmail)).IsNull(); + } + } +} diff --git a/EssentialCSharp.Web.Tests/Identity/ExternalLoginAccountLinkingTests.cs b/EssentialCSharp.Web.Tests/Identity/ExternalLoginAccountLinkingTests.cs new file mode 100644 index 00000000..207dc415 --- /dev/null +++ b/EssentialCSharp.Web.Tests/Identity/ExternalLoginAccountLinkingTests.cs @@ -0,0 +1,207 @@ +using System.Net; +using EssentialCSharp.Web.Areas.Identity.Data; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; + +namespace EssentialCSharp.Web.Tests.Identity; + +/// +/// Regression tests for the external-login pre-account hijack: someone who signs in with their own GitHub or +/// Microsoft account must not be able to attach it to an account for an email address they don't control. +/// +public class ExternalLoginAccountLinkingTests : IntegrationTestBase +{ + private const string Provider = "GitHub"; + private const string CallbackUrl = "/Identity/Account/ExternalLogin?handler=Callback"; + private const string ConfirmationUrl = "/Identity/Account/ExternalLogin?handler=Confirmation"; + + private static async Task RegisterWithExternalLoginAsync(Browser browser, string email, string captchaResponse = "test-captcha-response") => + await browser.PostFormAsync(ConfirmationUrl, new() { ["Input.Email"] = email }, getUrl: CallbackUrl, captchaResponse: captchaResponse); + + private static Browser BrowserSignedInToProvider(IdentityFlowHarness harness, string providerKey) + { + Browser browser = harness.NewBrowser(); + browser.SetCookie(harness.CreateExternalLoginCookie(Provider, providerKey)); + return browser; + } + + [Test] + public async Task ConfirmationPost_DoesNotLinkTheExternalLoginBeforeTheEmailIsConfirmed() + { + IdentityFlowHarness harness = new(Factory.Inner); + string victimEmail = IdentityFlowHarness.UniqueEmail("victim"); + Browser attacker = BrowserSignedInToProvider(harness, "attacker-gh-1"); + + using HttpResponseMessage response = await RegisterWithExternalLoginAsync(attacker, victimEmail); + + EssentialCSharpWebUser? user = await harness.FindUserAsync(victimEmail); + using (Assert.Multiple()) + { + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Redirect); + await Assert.That(user).IsNotNull(); + await Assert.That(user!.EmailConfirmed).IsFalse(); + await Assert.That(await harness.GetLoginsAsync(victimEmail)).IsEmpty(); + } + } + + [Test] + public async Task PreRegisteredExternalLogin_DoesNotSignInAfterTheOwnerConfirmsAndResetsThePassword() + { + IdentityFlowHarness harness = new(Factory.Inner); + string victimEmail = IdentityFlowHarness.UniqueEmail("victim"); + Browser attacker = BrowserSignedInToProvider(harness, "attacker-gh-2"); + Browser owner = harness.NewBrowser(); + + using HttpResponseMessage registered = await RegisterWithExternalLoginAsync(attacker, victimEmail); + using HttpResponseMessage confirmed = await owner.GetAsync( + IdentityFlowHarness.PathAndQuery(harness.LinkFromEmail(victimEmail, "Confirm your email"))); + await harness.ResetPasswordThroughPagesAsync(owner, victimEmail, IdentityFlowHarness.StrongPassword); + + // The attacker replays the provider callback, as they would after the owner adopted the account. + Browser attackerAgain = BrowserSignedInToProvider(harness, "attacker-gh-2"); + using HttpResponseMessage callback = await attackerAgain.GetAsync(CallbackUrl); + + using (Assert.Multiple()) + { + await Assert.That(confirmed.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(callback.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(attackerAgain.HasCookie(IdentityFlowHarness.ApplicationCookieName)).IsFalse(); + await Assert.That(await harness.GetLoginsAsync(victimEmail)).IsEmpty(); + await Assert.That(await owner.LogInWithPasswordAsync(victimEmail, IdentityFlowHarness.StrongPassword)).IsTrue(); + } + } + + [Test] + public async Task ConfirmationLink_OpenedInTheBrowserHoldingTheExternalLogin_LinksItAndAllowsSignIn() + { + IdentityFlowHarness harness = new(Factory.Inner); + string email = IdentityFlowHarness.UniqueEmail("reader"); + Browser reader = BrowserSignedInToProvider(harness, "reader-gh-1"); + + using HttpResponseMessage registered = await RegisterWithExternalLoginAsync(reader, email); + string confirmLink = harness.LinkFromEmail(email, "Confirm your email"); + using HttpResponseMessage confirmed = await reader.GetAsync(IdentityFlowHarness.PathAndQuery(confirmLink)); + string confirmedBody = await confirmed.Content.ReadAsStringAsync(); + + Browser later = BrowserSignedInToProvider(harness, "reader-gh-1"); + using HttpResponseMessage callback = await later.GetAsync(CallbackUrl); + + IList logins = await harness.GetLoginsAsync(email); + using (Assert.Multiple()) + { + await Assert.That(confirmedBody).Contains("account is linked"); + await Assert.That(logins.Select(l => $"{l.LoginProvider}/{l.ProviderKey}")).IsEquivalentTo(["GitHub/reader-gh-1"]); + await Assert.That(callback.StatusCode).IsEqualTo(HttpStatusCode.Redirect); + await Assert.That(later.HasCookie(IdentityFlowHarness.ApplicationCookieName)).IsTrue(); + } + } + + [Test] + public async Task ConfirmationLink_OpenedWithADifferentExternalLogin_LinksNeither() + { + IdentityFlowHarness harness = new(Factory.Inner); + string victimEmail = IdentityFlowHarness.UniqueEmail("victim"); + Browser attacker = BrowserSignedInToProvider(harness, "attacker-gh-3"); + Browser owner = BrowserSignedInToProvider(harness, "owner-gh-3"); + + using HttpResponseMessage registered = await RegisterWithExternalLoginAsync(attacker, victimEmail); + using HttpResponseMessage confirmed = await owner.GetAsync( + IdentityFlowHarness.PathAndQuery(harness.LinkFromEmail(victimEmail, "Confirm your email"))); + + await Assert.That(await harness.GetLoginsAsync(victimEmail)).IsEmpty(); + } + + [Test] + public async Task ConfirmationLink_OpenedInAnotherBrowser_CanBeFinishedBySigningInAgain() + { + IdentityFlowHarness harness = new(Factory.Inner); + string email = IdentityFlowHarness.UniqueEmail("reader"); + Browser desktop = BrowserSignedInToProvider(harness, "reader-gh-4"); + Browser phone = harness.NewBrowser(); + + using HttpResponseMessage registered = await RegisterWithExternalLoginAsync(desktop, email); + using HttpResponseMessage confirmedOnPhone = await phone.GetAsync( + IdentityFlowHarness.PathAndQuery(harness.LinkFromEmail(email, "Confirm your email"))); + string phoneBody = await confirmedOnPhone.Content.ReadAsStringAsync(); + + // Signing in with the provider again and re-entering the email sends a fresh link for this browser. + Browser desktopAgain = BrowserSignedInToProvider(harness, "reader-gh-4"); + using HttpResponseMessage registeredAgain = await RegisterWithExternalLoginAsync(desktopAgain, email); + using HttpResponseMessage confirmedOnDesktop = await desktopAgain.GetAsync( + IdentityFlowHarness.PathAndQuery(harness.LinkFromEmail(email, "Confirm your email"))); + + using (Assert.Multiple()) + { + await Assert.That(phoneBody).Contains("log in with GitHub again"); + await Assert.That(harness.Email.CountTo(email)).IsEqualTo(2); + await Assert.That((await harness.GetLoginsAsync(email)).Select(l => l.ProviderKey)).IsEquivalentTo(["reader-gh-4"]); + } + } + + [Test] + public async Task ConfirmationPost_ForAConfirmedAccountThatCanSignIn_SendsNoLinkEmail() + { + IdentityFlowHarness harness = new(Factory.Inner); + string email = IdentityFlowHarness.UniqueEmail("member"); + await harness.CreateConfirmedUserAsync(email, IdentityFlowHarness.StrongPassword); + Browser attacker = BrowserSignedInToProvider(harness, "attacker-gh-5"); + + using HttpResponseMessage response = await RegisterWithExternalLoginAsync(attacker, email); + + using (Assert.Multiple()) + { + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(harness.Email.CountTo(email)).IsEqualTo(0); + await Assert.That(await harness.GetLoginsAsync(email)).IsEmpty(); + } + } + + [Test] + [Arguments("")] + [Arguments("invalid-captcha-test-token")] + public async Task ConfirmationPost_WithoutAValidCaptcha_CreatesNoAccountAndSendsNoEmail(string captchaResponse) + { + IdentityFlowHarness harness = new(Factory.Inner); + string email = IdentityFlowHarness.UniqueEmail("anyone"); + Browser browser = BrowserSignedInToProvider(harness, "bot-gh-1"); + + using HttpResponseMessage response = await RegisterWithExternalLoginAsync(browser, email, captchaResponse); + string body = await response.Content.ReadAsStringAsync(); + + using (Assert.Multiple()) + { + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(body).Contains("Human verification failed"); + await Assert.That(await harness.FindUserAsync(email)).IsNull(); + await Assert.That(harness.Email.CountTo(email)).IsEqualTo(0); + } + } + + [Test] + public async Task FirstConfirmation_RemovesExternalLoginsLinkedWhileTheEmailWasUnverified() + { + IdentityFlowHarness harness = new(Factory.Inner); + string victimEmail = IdentityFlowHarness.UniqueEmail("victim"); + // An account pre-linked before this fix shipped: unconfirmed, with someone's provider login on it. + string confirmLink = await harness.InScopeAsync(async sp => + { + UserManager users = sp.GetRequiredService>(); + EssentialCSharpWebUser user = new() { UserName = victimEmail, Email = victimEmail }; + await users.CreateAsync(user); + await users.AddLoginAsync(user, new UserLoginInfo(Provider, "attacker-gh-6", Provider)); + string code = await users.GenerateEmailConfirmationTokenAsync(user); + return $"/Identity/Account/ConfirmEmail?userId={user.Id}&code={Microsoft.AspNetCore.WebUtilities.WebEncoders.Base64UrlEncode(System.Text.Encoding.UTF8.GetBytes(code))}"; + }); + + using HttpResponseMessage confirmed = await harness.NewBrowser().GetAsync(confirmLink); + Browser attacker = BrowserSignedInToProvider(harness, "attacker-gh-6"); + using HttpResponseMessage callback = await attacker.GetAsync(CallbackUrl); + + using (Assert.Multiple()) + { + await Assert.That(confirmed.StatusCode).IsEqualTo(HttpStatusCode.OK); + await Assert.That(await harness.GetLoginsAsync(victimEmail)).IsEmpty(); + await Assert.That(attacker.HasCookie(IdentityFlowHarness.ApplicationCookieName)).IsFalse(); + } + } +} diff --git a/EssentialCSharp.Web.Tests/Identity/IdentityFlowHarness.cs b/EssentialCSharp.Web.Tests/Identity/IdentityFlowHarness.cs new file mode 100644 index 00000000..0bb60538 --- /dev/null +++ b/EssentialCSharp.Web.Tests/Identity/IdentityFlowHarness.cs @@ -0,0 +1,268 @@ +using System.Net; +using System.Security.Claims; +using System.Text; +using System.Text.RegularExpressions; +using EssentialCSharp.Web.Areas.Identity.Data; +using EssentialCSharp.Web.Services; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Authentication.Cookies; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Identity.UI.Services; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.AspNetCore.WebUtilities; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.DependencyInjection.Extensions; +using Microsoft.Extensions.Options; + +namespace EssentialCSharp.Web.Tests.Identity; + +/// +/// Drives the Identity pages over HTTP the way separate people in separate browsers would, with email captured +/// instead of sent. Used by the account-takeover regression tests. +/// +internal sealed class IdentityFlowHarness +{ + public const string ApplicationCookieName = ".AspNetCore.Identity.Application"; + + // Not in the bundled top-100,000 list, and the Have I Been Pwned lookup is stubbed out. + public const string StrongPassword = "Quiet-Harbor-Lantern-4821"; + public const string OtherStrongPassword = "Copper-Meadow-Violin-7305"; + + private readonly Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory _factory; + + public IdentityFlowHarness(Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory baseFactory, string? hostHeader = null) + { + _factory = baseFactory.WithWebHostBuilder(builder => builder.ConfigureServices(services => + { + services.RemoveAll(); + services.AddSingleton(Email); + services.AddHttpClient("HaveIBeenPwned").ConfigurePrimaryHttpMessageHandler(() => new NotPwnedHandler()); + })); + HostHeader = hostHeader; + } + + public RecordingEmailSender Email { get; } = new(); + + public IServiceProvider Services => _factory.Services; + + private string? HostHeader { get; } + + public static string UniqueEmail(string prefix) => $"{prefix}-{Guid.NewGuid():N}@example.test"; + + public Browser NewBrowser() => new( + _factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false, HandleCookies = false }), + HostHeader); + + public async Task InScopeAsync(Func> action) + { + using IServiceScope scope = Services.CreateScope(); + return await action(scope.ServiceProvider); + } + + public Task FindUserAsync(string email) => + InScopeAsync(sp => sp.GetRequiredService>().FindByEmailAsync(email)); + + public Task> GetLoginsAsync(string email) => InScopeAsync(async sp => + { + UserManager users = sp.GetRequiredService>(); + EssentialCSharpWebUser user = await users.FindByEmailAsync(email) ?? throw new InvalidOperationException($"No user {email}."); + return await users.GetLoginsAsync(user); + }); + + /// Creates a confirmed account directly, optionally with a password. + public Task CreateConfirmedUserAsync(string email, string? password) => InScopeAsync(async sp => + { + UserManager users = sp.GetRequiredService>(); + EssentialCSharpWebUser user = new() { UserName = email, Email = email, EmailConfirmed = true }; + IdentityResult result = password is null ? await users.CreateAsync(user) : await users.CreateAsync(user, password); + if (!result.Succeeded) + { + throw new InvalidOperationException(string.Join("; ", result.Errors.Select(e => e.Description))); + } + return user.Id; + }); + + /// + /// Builds the cookie the external-login middleware sets after a successful GitHub/Microsoft sign-in, standing in + /// for a real OAuth round trip. + /// + public (string Name, string Value) CreateExternalLoginCookie(string provider, string providerKey) + { + using IServiceScope scope = Services.CreateScope(); + CookieAuthenticationOptions options = scope.ServiceProvider + .GetRequiredService>() + .Get(IdentityConstants.ExternalScheme); + ClaimsIdentity identity = new( + [new Claim(ClaimTypes.NameIdentifier, providerKey), new Claim(ClaimTypes.Name, providerKey)], + provider); + AuthenticationProperties properties = new() + { + IssuedUtc = DateTimeOffset.UtcNow, + ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(5), + }; + properties.Items["LoginProvider"] = provider; + AuthenticationTicket ticket = new(new ClaimsPrincipal(identity), properties, IdentityConstants.ExternalScheme); + return (options.Cookie.Name!, options.TicketDataFormat.Protect(ticket)); + } + + /// Returns the path and query of the link in the last email with this subject sent to this address. + public string LinkFromEmail(string to, string subject) + { + string body = Email.Last(to, subject).Body; + Match match = Regex.Match(body, "href='([^']+)'"); + if (!match.Success) + { + throw new InvalidOperationException($"No link in '{subject}' email to {to}."); + } + return WebUtility.HtmlDecode(match.Groups[1].Value); + } + + public static string PathAndQuery(string absoluteLink) => new Uri(absoluteLink).PathAndQuery; + + /// Extracts and decodes the code query value of an emailed reset link. + public static string DecodeCode(string link) + { + string code = Regex.Match(link, "[?&]code=([^&]+)").Groups[1].Value; + return Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(WebUtility.UrlDecode(code))); + } + + /// Resets the password through the ForgotPassword and ResetPassword pages. + public async Task ResetPasswordThroughPagesAsync(Browser browser, string email, string newPassword) + { + using HttpResponseMessage forgot = await browser.PostFormAsync("/Identity/Account/ForgotPassword", new() { ["Input.Email"] = email }); + string resetLink = LinkFromEmail(email, "Reset Password"); + using HttpResponseMessage reset = await browser.PostFormAsync( + "/Identity/Account/ResetPassword", + new() + { + ["Input.Email"] = email, + ["Input.Password"] = newPassword, + ["Input.ConfirmPassword"] = newPassword, + ["Input.Code"] = DecodeCode(resetLink), + }, + getUrl: PathAndQuery(resetLink)); + if (reset.Headers.Location?.OriginalString.Contains("ResetPasswordConfirmation", StringComparison.Ordinal) != true) + { + throw new InvalidOperationException($"Password reset failed: {(int)reset.StatusCode} {reset.Headers.Location}"); + } + } + + internal sealed class RecordingEmailSender : IEmailSender + { + private readonly List<(string To, string Subject, string Body)> _Sent = []; + + public IReadOnlyList<(string To, string Subject, string Body)> Sent + { + get { lock (_Sent) { return [.. _Sent]; } } + } + + public Task SendEmailAsync(string email, string subject, string htmlMessage) + { + lock (_Sent) { _Sent.Add((email, subject, htmlMessage)); } + return Task.CompletedTask; + } + + public (string To, string Subject, string Body) Last(string to, string subject) => + Sent.Last(m => m.To == to && m.Subject == subject); + + public int CountTo(string to) => Sent.Count(m => m.To == to); + } + + private sealed class NotPwnedHandler : HttpMessageHandler + { + // The response is handed to the HttpClient pipeline; whoever made the request disposes it. + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) => + Task.FromResult(CreateNoMatchesResponse()); + + private static HttpResponseMessage CreateNoMatchesResponse() + { + HttpResponseMessage response = new(HttpStatusCode.OK); + response.Content = new StringContent(string.Empty); + return response; + } + } +} + +/// One person's browser: keeps its own cookies and fills in antiforgery and captcha fields. +internal sealed class Browser(HttpClient client, string? hostHeader) +{ + private readonly Dictionary _Cookies = new(StringComparer.Ordinal); + + public bool HasCookie(string name) => _Cookies.ContainsKey(name); + + public void SetCookie(string name, string value) => _Cookies[name] = value; + + public void SetCookie((string Name, string Value) cookie) => _Cookies[cookie.Name] = cookie.Value; + + public Task GetAsync(string url) => SendAsync(HttpMethod.Get, url); + + public async Task SendAsync(HttpMethod method, string url, Dictionary? form = null) + { + using HttpRequestMessage request = new(method, url); + if (hostHeader is not null) + { + request.Headers.Host = hostHeader; + } + if (_Cookies.Count > 0) + { + request.Headers.Add("Cookie", string.Join("; ", _Cookies.Select(kv => $"{kv.Key}={kv.Value}"))); + } + if (form is not null) + { + request.Content = new FormUrlEncodedContent(form); + } + + HttpResponseMessage response = await client.SendAsync(request); + if (response.Headers.TryGetValues("Set-Cookie", out IEnumerable? values)) + { + foreach (string header in values) + { + string pair = header.Split(';')[0]; + int separator = pair.IndexOf('=', StringComparison.Ordinal); + string name = pair[..separator]; + string value = pair[(separator + 1)..]; + bool deleted = value.Length == 0 || header.Contains("expires=Thu, 01 Jan 1970", StringComparison.OrdinalIgnoreCase); + if (deleted) + { + _Cookies.Remove(name); + } + else + { + _Cookies[name] = value; + } + } + } + return response; + } + + /// GETs the form page for its antiforgery token, then POSTs the form with a passing captcha response. + public async Task PostFormAsync( + string url, + Dictionary form, + string? getUrl = null, + string captchaResponse = "test-captcha-response") + { + using HttpResponseMessage page = await GetAsync(getUrl ?? url); + string html = await page.Content.ReadAsStringAsync(); + Match token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\""); + if (!token.Success) + { + throw new InvalidOperationException($"No antiforgery token on {getUrl ?? url} ({(int)page.StatusCode})."); + } + + Dictionary fields = new(form) + { + ["__RequestVerificationToken"] = token.Groups[1].Value, + [CaptchaOptions.HttpPostResponseKeyName] = captchaResponse, + }; + return await SendAsync(HttpMethod.Post, url, fields); + } + + public async Task LogInWithPasswordAsync(string email, string password) + { + using HttpResponseMessage response = await PostFormAsync( + "/Identity/Account/Login", + new() { ["Input.Email"] = email, ["Input.Password"] = password }); + return HasCookie(IdentityFlowHarness.ApplicationCookieName); + } +} diff --git a/EssentialCSharp.Web.Tests/Identity/RegisterAccountOwnershipTests.cs b/EssentialCSharp.Web.Tests/Identity/RegisterAccountOwnershipTests.cs new file mode 100644 index 00000000..45cceac8 --- /dev/null +++ b/EssentialCSharp.Web.Tests/Identity/RegisterAccountOwnershipTests.cs @@ -0,0 +1,135 @@ +using System.Net; +using EssentialCSharp.Web.Areas.Identity.Data; +using EssentialCSharp.Web.Services; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.DependencyInjection; + +namespace EssentialCSharp.Web.Tests.Identity; + +/// +/// Regression tests for the Register pre-account hijack and for what a password reset clears: a password, external +/// login or MCP token added by someone who never proved control of the email must not survive the owner taking +/// the account over. +/// +public class RegisterAccountOwnershipTests : IntegrationTestBase +{ + private static async Task RegisterAsync(Browser browser, string email, string password) => + await browser.PostFormAsync("/Identity/Account/Register", new() + { + ["Input.UserName"] = $"user-{Guid.NewGuid():N}", + ["Input.FirstName"] = "Test", + ["Input.LastName"] = "User", + ["Input.Email"] = email, + ["Input.Password"] = password, + ["Input.ConfirmPassword"] = password, + }); + + [Test] + public async Task SquattersPassword_StopsWorkingWhenTheOwnerConfirmsInTheirOwnBrowser() + { + IdentityFlowHarness harness = new(Factory.Inner); + string ownerEmail = IdentityFlowHarness.UniqueEmail("owner"); + Browser squatter = harness.NewBrowser(); + Browser owner = harness.NewBrowser(); + + using HttpResponseMessage registered = await RegisterAsync(squatter, ownerEmail, IdentityFlowHarness.StrongPassword); + using HttpResponseMessage confirmed = await owner.GetAsync( + IdentityFlowHarness.PathAndQuery(harness.LinkFromEmail(ownerEmail, "Confirm your email"))); + string confirmedBody = await confirmed.Content.ReadAsStringAsync(); + + EssentialCSharpWebUser? user = await harness.FindUserAsync(ownerEmail); + using (Assert.Multiple()) + { + await Assert.That(registered.StatusCode).IsEqualTo(HttpStatusCode.Redirect); + await Assert.That(user!.EmailConfirmed).IsTrue(); + await Assert.That(user.PasswordHash).IsNull(); + await Assert.That(confirmedBody).Contains("choose a password"); + await Assert.That(confirmedBody).Contains("id=\"set-password-link\""); + await Assert.That(await harness.NewBrowser().LogInWithPasswordAsync(ownerEmail, IdentityFlowHarness.StrongPassword)).IsFalse(); + } + } + + [Test] + public async Task OwnerCanChooseAPasswordFromTheConfirmationPage() + { + IdentityFlowHarness harness = new(Factory.Inner); + string ownerEmail = IdentityFlowHarness.UniqueEmail("owner"); + Browser owner = harness.NewBrowser(); + + using HttpResponseMessage registered = await RegisterAsync(harness.NewBrowser(), ownerEmail, IdentityFlowHarness.StrongPassword); + using HttpResponseMessage confirmed = await owner.GetAsync( + IdentityFlowHarness.PathAndQuery(harness.LinkFromEmail(ownerEmail, "Confirm your email"))); + string body = await confirmed.Content.ReadAsStringAsync(); + string setPasswordUrl = System.Net.WebUtility.HtmlDecode( + System.Text.RegularExpressions.Regex.Match(body, "id=\"set-password-link\"[^>]*href=\"([^\"]+)\"").Groups[1].Value); + + using HttpResponseMessage reset = await owner.PostFormAsync( + "/Identity/Account/ResetPassword", + new() + { + ["Input.Email"] = ownerEmail, + ["Input.Password"] = IdentityFlowHarness.OtherStrongPassword, + ["Input.ConfirmPassword"] = IdentityFlowHarness.OtherStrongPassword, + ["Input.Code"] = IdentityFlowHarness.DecodeCode(setPasswordUrl), + }, + getUrl: setPasswordUrl); + + using (Assert.Multiple()) + { + await Assert.That(reset.Headers.Location?.OriginalString).Contains("ResetPasswordConfirmation"); + await Assert.That(await harness.NewBrowser().LogInWithPasswordAsync(ownerEmail, IdentityFlowHarness.OtherStrongPassword)).IsTrue(); + await Assert.That(await harness.NewBrowser().LogInWithPasswordAsync(ownerEmail, IdentityFlowHarness.StrongPassword)).IsFalse(); + } + } + + [Test] + public async Task Registrant_ConfirmingInTheSameBrowser_KeepsTheirPassword() + { + IdentityFlowHarness harness = new(Factory.Inner); + string email = IdentityFlowHarness.UniqueEmail("reader"); + Browser reader = harness.NewBrowser(); + + using HttpResponseMessage registered = await RegisterAsync(reader, email, IdentityFlowHarness.StrongPassword); + using HttpResponseMessage confirmed = await reader.GetAsync( + IdentityFlowHarness.PathAndQuery(harness.LinkFromEmail(email, "Confirm your email"))); + string body = await confirmed.Content.ReadAsStringAsync(); + + using (Assert.Multiple()) + { + await Assert.That(body).Contains("Thank you for confirming your email."); + await Assert.That(body).DoesNotContain("set-password-link"); + await Assert.That(await reader.LogInWithPasswordAsync(email, IdentityFlowHarness.StrongPassword)).IsTrue(); + } + } + + [Test] + public async Task PasswordReset_RemovesExternalLoginsRevokesMcpTokensAndEndsSessions() + { + IdentityFlowHarness harness = new(Factory.Inner); + string email = IdentityFlowHarness.UniqueEmail("owner"); + string userId = await harness.CreateConfirmedUserAsync(email, IdentityFlowHarness.StrongPassword); + (string rawToken, string stampBefore) = await harness.InScopeAsync(async sp => + { + UserManager users = sp.GetRequiredService>(); + EssentialCSharpWebUser user = (await users.FindByIdAsync(userId))!; + await users.AddLoginAsync(user, new UserLoginInfo("GitHub", "someone-gh-1", "GitHub")); + (string token, _) = await sp.GetRequiredService().CreateTokenAsync(userId, "someone"); + return (token, (await users.FindByIdAsync(userId))!.SecurityStamp!); + }); + + await harness.ResetPasswordThroughPagesAsync(harness.NewBrowser(), email, IdentityFlowHarness.OtherStrongPassword); + + (bool tokenStillValid, string stampAfter) = await harness.InScopeAsync(async sp => + { + bool valid = await sp.GetRequiredService().ResolveValidTokenAsync(rawToken) is not null; + EssentialCSharpWebUser user = (await sp.GetRequiredService>().FindByIdAsync(userId))!; + return (valid, user.SecurityStamp!); + }); + using (Assert.Multiple()) + { + await Assert.That(await harness.GetLoginsAsync(email)).IsEmpty(); + await Assert.That(tokenStillValid).IsFalse(); + await Assert.That(stampAfter).IsNotEqualTo(stampBefore); + } + } +} diff --git a/EssentialCSharp.Web.Tests/IdentityEmailFailureTests.cs b/EssentialCSharp.Web.Tests/IdentityEmailFailureTests.cs index fa55c97e..e0432aac 100644 --- a/EssentialCSharp.Web.Tests/IdentityEmailFailureTests.cs +++ b/EssentialCSharp.Web.Tests/IdentityEmailFailureTests.cs @@ -2,12 +2,14 @@ using EssentialCSharp.Web.Areas.Identity.Data; using EssentialCSharp.Web.Areas.Identity.Pages.Account; using EssentialCSharp.Web.Areas.Identity.Pages.Account.Manage; +using EssentialCSharp.Web.Areas.Identity.Services; using EssentialCSharp.Web.Models; using EssentialCSharp.Web.Services; using EssentialCSharp.Web.Services.Referrals; using Mailjet.Client; using Mailjet.Client.Exceptions; using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; @@ -53,6 +55,7 @@ private static Mock> CreateUserManager() mock.Setup(m => m.GenerateEmailConfirmationTokenAsync(It.IsAny())).ReturnsAsync("token"); mock.Setup(m => m.GeneratePasswordResetTokenAsync(It.IsAny())).ReturnsAsync("token"); mock.Setup(m => m.GenerateChangeEmailTokenAsync(It.IsAny(), It.IsAny())).ReturnsAsync("token"); + mock.Setup(m => m.SetAuthenticationTokenAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(IdentityResult.Success); return mock; } @@ -81,6 +84,9 @@ private static Mock CreatePassingCaptcha() private static IOptions CaptchaOptionsAccessor() => Options.Create(new CaptchaOptions { SiteKey = "site", SecretKey = "secret" }); + private static IOptions SiteSettingsAccessor() => + Options.Create(new SiteSettings { BaseUrl = "https://example.test" }); + private static Mock CreateFailingSender() { Mock sender = new(); @@ -268,7 +274,9 @@ private static RegisterModel CreateRegisterModel(Mock>()); + Mock.Of>(), + SiteSettingsAccessor(), + new RegistrationBrowserBinding(new EphemeralDataProtectionProvider(), Options.Create(new DataProtectionTokenProviderOptions()))); model.Input = new RegisterModel.InputModel { UserName = "reader", @@ -335,7 +343,8 @@ private static ForgotPasswordModel CreateForgotPasswordModel(Mock.Instance); + logger ?? NullLogger.Instance, + SiteSettingsAccessor()); model.Input = new ForgotPasswordModel.InputModel { Email = UserEmail }; return model; } @@ -399,7 +408,8 @@ private static ResendEmailConfirmationModel CreateResendModel(Mock.Instance); + logger ?? NullLogger.Instance, + SiteSettingsAccessor()); model.Input = new ResendEmailConfirmationModel.InputModel { Email = UserEmail }; return model; } @@ -453,7 +463,7 @@ private static EmailModel CreateManageEmailModel(IEmailSender sender, ILogger> userManager = CreateUserManager(); userManager.Setup(m => m.GetUserAsync(It.IsAny())).ReturnsAsync(new EssentialCSharpWebUser()); userManager.Setup(m => m.GetEmailAsync(It.IsAny())).ReturnsAsync("old@example.com"); - return new EmailModel(userManager.Object, CreateSignInManager(userManager.Object).Object, sender, logger ?? NullLogger.Instance); + return new EmailModel(userManager.Object, CreateSignInManager(userManager.Object).Object, sender, logger ?? NullLogger.Instance, SiteSettingsAccessor()); } // ExternalLogin confirmation @@ -476,6 +486,8 @@ public async Task ExternalLogin_NewUser_WhenConfirmationEmailFails_RedirectsToRe await Assert.That(redirect.RouteValues?["email"]).IsEqualTo(UserEmail); await Assert.That(TempDataStatusMessage(model)).IsEqualTo(EmailFailureMessages.AccountCreatedConfirmationNotSent); } + // The typed email is unverified, so the external login must not be linked yet. + userManager.Verify(m => m.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never); } [Test] @@ -514,7 +526,12 @@ private static ExternalLoginModel CreateExternalLoginModel(Mock.Instance, sender, Mock.Of>(), - Mock.Of()); + Mock.Of(), + CreatePassingCaptcha().Object, + CaptchaOptionsAccessor(), + SiteSettingsAccessor(), + // The token service is not reached by the confirmation handler. + new AccountOwnershipService(userManager.Object, new McpApiTokenService(null!))); model.Input = new ExternalLoginModel.InputModel { Email = UserEmail }; return model; } diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ConfirmEmail.cshtml b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ConfirmEmail.cshtml index 2deb2e52..fb52e3fd 100644 --- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ConfirmEmail.cshtml +++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ConfirmEmail.cshtml @@ -6,3 +6,9 @@

@ViewData["Title"]

+@if (Model.SetPasswordUrl is not null) +{ +

+ Choose a password +

+} diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ConfirmEmail.cshtml.cs b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ConfirmEmail.cshtml.cs index a7fc8785..0e245afb 100644 --- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ConfirmEmail.cshtml.cs +++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ConfirmEmail.cshtml.cs @@ -1,5 +1,7 @@ using System.Text; using EssentialCSharp.Web.Areas.Identity.Data; +using EssentialCSharp.Web.Areas.Identity.Services; +using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; @@ -7,11 +9,19 @@ namespace EssentialCSharp.Web.Areas.Identity.Pages.Account; -public class ConfirmEmailModel(UserManager userManager) : PageModel +public class ConfirmEmailModel( + UserManager userManager, + SignInManager signInManager, + AccountOwnershipService accountOwnershipService, + RegistrationBrowserBinding registrationBrowserBinding) : PageModel { [TempData] public string StatusMessage { get; set; } = string.Empty; - public async Task OnGetAsync(string? userId, string? code) + + /// Set when the person confirming must choose a password before the account can be used. + public string? SetPasswordUrl { get; set; } + + public async Task OnGetAsync(string? userId, string? code, CancellationToken cancellationToken = default) { if (userId is null || code is null) { @@ -24,9 +34,61 @@ public async Task OnGetAsync(string? userId, string? code) return NotFound($"Unable to load user with ID '{userId}'."); } + bool wasConfirmed = user.EmailConfirmed; code = Encoding.UTF8.GetString(WebEncoders.Base64UrlDecode(code)); IdentityResult result = await userManager.ConfirmEmailAsync(user, code); - StatusMessage = result.Succeeded ? "Thank you for confirming your email." : "Error confirming your email."; + if (!result.Succeeded) + { + StatusMessage = "Error confirming your email."; + return Page(); + } + + StatusMessage = "Thank you for confirming your email."; + + if (!wasConfirmed) + { + // Opening the link proves control of the mailbox, and nothing else. Anything attached to the account + // before now may belong to whoever typed this address, so it does not survive confirmation. + await accountOwnershipService.RemoveCredentialsAddedBeforeOwnershipProofAsync(user, cancellationToken); + + if (await userManager.HasPasswordAsync(user)) + { + if (registrationBrowserBinding.IsBoundTo(HttpContext, user.Id)) + { + registrationBrowserBinding.Clear(HttpContext); + } + else + { + // The password was chosen by whoever registered, and this link was opened in another + // browser. Don't let that password unlock the account; have the mailbox owner choose one. + await userManager.RemovePasswordAsync(user); + string resetCode = await userManager.GeneratePasswordResetTokenAsync(user); + SetPasswordUrl = Url.Page( + "./ResetPassword", + pageHandler: null, + values: new { code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(resetCode)) }); + StatusMessage = "Thank you for confirming your email. To finish, choose a password for your account. " + + "(If you registered on another device, this keeps the account safe in case someone else chose your password.)"; + return Page(); + } + } + } + + // Link an external login that was waiting for this confirmation, but only if this browser holds it. + ExternalLoginInfo? externalLogin = await signInManager.GetExternalLoginInfoAsync(); + if (await accountOwnershipService.TryLinkPendingExternalLoginAsync(user, externalLogin)) + { + await HttpContext.SignOutAsync(IdentityConstants.ExternalScheme); + StatusMessage = $"Thank you for confirming your email. Your {externalLogin!.ProviderDisplayName ?? externalLogin.LoginProvider} account is linked, so you can now log in with it."; + } + else if (await accountOwnershipService.GetPendingExternalLoginDisplayNameAsync(user) is string pendingProvider + && !await userManager.HasPasswordAsync(user) + && (await userManager.GetLoginsAsync(user)).Count == 0) + { + StatusMessage = $"Thank you for confirming your email. To finish, log in with {pendingProvider} again and " + + "register with this email; then open the new link in that same browser."; + } + return Page(); } } diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ConfirmEmailChange.cshtml.cs b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ConfirmEmailChange.cshtml.cs index 9c86b055..e13052a7 100644 --- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ConfirmEmailChange.cshtml.cs +++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ConfirmEmailChange.cshtml.cs @@ -1,5 +1,6 @@ using System.Text; using EssentialCSharp.Web.Areas.Identity.Data; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; @@ -7,6 +8,10 @@ namespace EssentialCSharp.Web.Areas.Identity.Pages.Account; +// The link proves control of the new mailbox; being signed in as the account proves the change was requested by +// its owner. Requiring both stops someone attaching an address they don't own to their account (and keeping +// their own logins and tokens on it) just because the address owner clicked the link. +[Authorize] public class ConfirmEmailChangeModel(UserManager userManager, SignInManager signInManager) : PageModel { [TempData] @@ -19,6 +24,12 @@ public async Task OnGetAsync(string? userId, string? email, strin return RedirectToPage("/Index"); } + if (!string.Equals(userManager.GetUserId(User), userId, StringComparison.Ordinal)) + { + StatusMessage = "Error changing email. Log in to the account that requested the change, then open the link again."; + return Page(); + } + EssentialCSharpWebUser? user = await userManager.FindByIdAsync(userId); if (user is null) { diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ExternalLogin.cshtml b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ExternalLogin.cshtml index 15d8f352..c1e1ec54 100644 --- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ExternalLogin.cshtml +++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ExternalLogin.cshtml @@ -10,7 +10,8 @@

You've successfully authenticated with @Model.ProviderDisplayName. - Please enter an email address for this site below and click the Register button to finish + Please enter an email address for this site below and click the Register button. We'll email you a + confirmation link; open it in this browser to link your @Model.ProviderDisplayName account and finish logging in.

@@ -23,6 +24,9 @@ +
+ +
diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ExternalLogin.cshtml.cs b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ExternalLogin.cshtml.cs index d1938dd3..29e404e7 100644 --- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ExternalLogin.cshtml.cs +++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ExternalLogin.cshtml.cs @@ -3,6 +3,8 @@ using System.Text; using System.Text.Encodings.Web; using EssentialCSharp.Web.Areas.Identity.Data; +using EssentialCSharp.Web.Areas.Identity.Services; +using EssentialCSharp.Web.Extensions; using EssentialCSharp.Web.Services; using EssentialCSharp.Web.Services.Referrals; using Microsoft.AspNetCore.Authorization; @@ -11,6 +13,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.WebUtilities; +using Microsoft.Extensions.Options; namespace EssentialCSharp.Web.Areas.Identity.Pages.Account; @@ -22,7 +25,11 @@ public partial class ExternalLoginModel( ILogger logger, IEmailSender emailSender, IUserEmailStore emailStore, - IReferralService referralService) : PageModel + IReferralService referralService, + ICaptchaValidationService captchaValidationService, + IOptions captchaOptions, + IOptions siteSettings, + AccountOwnershipService accountOwnershipService) : PageModel { private InputModel? _Input; [BindProperty] @@ -32,6 +39,8 @@ public InputModel Input set => _Input = value ?? throw new ArgumentNullException(nameof(value)); } + public string CaptchaSiteKey { get; } = captchaOptions.Value.SiteKey ?? string.Empty; + public string? ProviderDisplayName { get; set; } public string? ReturnUrl { get; set; } @@ -110,7 +119,7 @@ public async Task OnGetCallbackAsync(string? returnUrl = null, st } } - public async Task OnPostConfirmationAsync(string? returnUrl = null) + public async Task OnPostConfirmationAsync(string? returnUrl = null, CancellationToken cancellationToken = default) { returnUrl ??= Url.Content("~/"); // Get the information about the user from the external login provider @@ -121,6 +130,21 @@ public async Task OnPostConfirmationAsync(string? returnUrl = nul return RedirectToPage("./Login", new { ReturnUrl = returnUrl }); } + ProviderDisplayName = info.ProviderDisplayName; + ReturnUrl = returnUrl; + + // This handler creates accounts and sends email, so it needs the same human check as Register. + string? captchaToken = Request.Form[CaptchaOptions.HttpPostResponseKeyName]; + CaptchaValidationResult captchaResult = await captchaValidationService.ValidateAsync( + captchaToken, + HttpContext.Connection.RemoteIpAddress?.ToString(), + cancellationToken); + if (!captchaResult.ShouldProceed) + { + ModelState.AddModelError(string.Empty, "Human verification failed. Please try again."); + return Page(); + } + if (ModelState.IsValid) { if (Input.Email is null) @@ -128,32 +152,41 @@ public async Task OnPostConfirmationAsync(string? returnUrl = nul ErrorMessage = "Error: Email may not be null."; return RedirectToPage("./Login", new { ReturnUrl = returnUrl }); } - EssentialCSharpWebUser user = CreateUser(); + // The typed email is unverified, so the external login is never linked here. It is recorded as + // pending, and ConfirmEmail links it only when the emailed link is opened in a browser that still + // holds this same external login: that proves one person controls both the mailbox and the login. EssentialCSharpWebUser? existingUser = await userManager.FindByEmailAsync(Input.Email).ConfigureAwait(false); if (existingUser is null) { - await userStore.SetUserNameAsync(user, Input.Email, CancellationToken.None); - await emailStore.SetEmailAsync(user, Input.Email, CancellationToken.None); + EssentialCSharpWebUser user = CreateUser(); + await userStore.SetUserNameAsync(user, Input.Email, cancellationToken); + await emailStore.SetEmailAsync(user, Input.Email, cancellationToken); IdentityResult result = await userManager.CreateAsync(user); if (result.Succeeded) { - result = await userManager.AddLoginAsync(user, info); - if (result.Succeeded) + result = await accountOwnershipService.SetPendingExternalLoginAsync(user, info); + if (!result.Succeeded) { - LogUserCreatedWithProvider(logger, info.LoginProvider); - try - { - return await SendConfirmationEmail(returnUrl, info, user); - } - catch (EmailSendException) - { - // The account and external login already exist; send the user to resend the email. - // Do not log the exception: its inner exception can contain the recipient address. EmailSender has logged the details. - LogConfirmationEmailNotSent(logger); - EmailFailureMessages.QueueAccountCreatedConfirmationNotSent(TempData); - return RedirectToPage("./ResendEmailConfirmation", new { email = Input.Email }); - } + // Creating the account and recording its login succeed or fail together, so a + // failure never leaves an account behind that nobody can finish setting up. + await userManager.DeleteAsync(user); + } + } + if (result.Succeeded) + { + LogUserCreatedWithProvider(logger, info.LoginProvider); + try + { + return await SendConfirmationEmail(returnUrl, info, user); + } + catch (EmailSendException) + { + // The account already exists; send the user to resend the email. + // Do not log the exception: its inner exception can contain the recipient address. EmailSender has logged the details. + LogConfirmationEmailNotSent(logger); + EmailFailureMessages.QueueAccountCreatedConfirmationNotSent(TempData); + return RedirectToPage("./ResendEmailConfirmation", new { email = Input.Email }); } } foreach (IdentityError error in result.Errors) @@ -161,30 +194,36 @@ public async Task OnPostConfirmationAsync(string? returnUrl = nul ModelState.AddModelError(string.Empty, error.Description); } } - else + else if (!existingUser.EmailConfirmed || await IsAwaitingExternalLoginAsync(existingUser)) { - if (!existingUser.EmailConfirmed) + // The account is unconfirmed, or it was created on this page and its login was never linked + // (for example, the link was opened in another browser). Proving the mailbox again from this + // browser links this login. Accounts that can already sign in link logins from Manage instead. + try { - try + IdentityResult pending = await accountOwnershipService.SetPendingExternalLoginAsync(existingUser, info); + if (pending.Succeeded) { await SendConfirmationEmail(returnUrl, info, existingUser); } - catch (EmailSendException) - { - // The email is only attempted when the address belongs to an existing account, so a visible - // error would reveal that. Log it and fall through to the same message shown on success. - LogConfirmationEmailNotSent(logger); - } + } + catch (EmailSendException) + { + // The email is only attempted when the address belongs to an existing account, so a visible + // error would reveal that. Log it and fall through to the same message shown on success. + LogConfirmationEmailNotSent(logger); } } } - ProviderDisplayName = info.ProviderDisplayName; - ReturnUrl = returnUrl; ModelState.AddModelError(string.Empty, "Please check confirmation email to complete registration."); return Page(); } + private async Task IsAwaitingExternalLoginAsync(EssentialCSharpWebUser user) => + !await userManager.HasPasswordAsync(user) + && (await userManager.GetLoginsAsync(user)).Count == 0; + private async Task SendConfirmationEmail(string returnUrl, ExternalLoginInfo info, EssentialCSharpWebUser user) { if (Input.Email is null) @@ -195,11 +234,10 @@ private async Task SendConfirmationEmail(string returnUrl, Extern string userId = await userManager.GetUserIdAsync(user); string code = await userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); - string? callbackUrl = Url.Page( + string? callbackUrl = Url.EmailPageLink( + siteSettings.Value, "/Account/ConfirmEmail", - pageHandler: null, - values: new { area = "Identity", userId = userId, code = code }, - protocol: Request.Scheme); + values: new { area = "Identity", userId = userId, code = code }); if (callbackUrl is null) { @@ -207,19 +245,13 @@ private async Task SendConfirmationEmail(string returnUrl, Extern return RedirectToPage("./Login", new { ReturnUrl = returnUrl }); } + string providerName = HtmlEncoder.Default.Encode(info.ProviderDisplayName ?? info.LoginProvider); await emailSender.SendEmailAsync(Input.Email, "Confirm your email", - $"Please confirm your account by clicking here."); - - // If account confirmation is required, we need to show the link if we don't have a real email sender - if (userManager.Options.SignIn.RequireConfirmedAccount) - { - return RedirectToPage("./RegisterConfirmation", new { Email = Input.Email }); - } + $"Please confirm your account by clicking here. " + + $"Open the link in the browser you used to sign in with {providerName} so that sign-in is linked to your account."); - // Ensure referral ID is set for the new user before signing in - await referralService.EnsureReferralIdAsync(user); - await signInManager.SignInAsync(user, isPersistent: false, info.LoginProvider); - return LocalRedirect(returnUrl); + // The account can't be used until its email is confirmed, and the external login is linked only then. + return RedirectToPage("./RegisterConfirmation", new { Email = Input.Email }); } private EssentialCSharpWebUser CreateUser() diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ForgotPassword.cshtml.cs b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ForgotPassword.cshtml.cs index a644e8b2..04bc2095 100644 --- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ForgotPassword.cshtml.cs +++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ForgotPassword.cshtml.cs @@ -2,6 +2,7 @@ using System.Text; using System.Text.Encodings.Web; using EssentialCSharp.Web.Areas.Identity.Data; +using EssentialCSharp.Web.Extensions; using EssentialCSharp.Web.Services; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; @@ -12,7 +13,7 @@ namespace EssentialCSharp.Web.Areas.Identity.Pages.Account; -public partial class ForgotPasswordModel(UserManager userManager, IEmailSender emailSender, ICaptchaValidationService captchaValidationService, IOptions optionsAccessor, ILogger logger) : PageModel +public partial class ForgotPasswordModel(UserManager userManager, IEmailSender emailSender, ICaptchaValidationService captchaValidationService, IOptions optionsAccessor, ILogger logger, IOptions siteSettings) : PageModel { private InputModel? _Input; [BindProperty] @@ -62,11 +63,12 @@ public async Task OnPostAsync(CancellationToken cancellationToken // visit https://go.microsoft.com/fwlink/?LinkID=532713 string code = await userManager.GeneratePasswordResetTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); - string? callbackUrl = Url.Page( + // Build the link from the configured site URL, not the request Host, so a forged Host header + // cannot send the reset token to another site. + string? callbackUrl = Url.EmailPageLink( + siteSettings.Value, "/Account/ResetPassword", - pageHandler: null, - values: new { area = "Identity", code }, - protocol: Request.Scheme); + values: new { area = "Identity", code }); if (callbackUrl is null) { diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/Login.cshtml.cs b/EssentialCSharp.Web/Areas/Identity/Pages/Account/Login.cshtml.cs index d537de31..b7fddd3a 100644 --- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/Login.cshtml.cs +++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/Login.cshtml.cs @@ -94,13 +94,16 @@ public async Task OnPostAsync(string? returnUrl = null, Cancellat } if (foundUser is not null) { - result = await signInManager.PasswordSignInAsync(foundUser, Input.Password, Input.RememberMe, lockoutOnFailure: true); + result = await signInManager.PasswordSignInAsync(foundUser, Input.Password, Input.RememberMe, lockoutOnFailure: await CanBeLockedOutByPasswordAsync(foundUser)); // Call the referral service to get the referral ID and set it onto the user claim _ = await referralService.EnsureReferralIdAsync(foundUser); } else { - result = await signInManager.PasswordSignInAsync(Input.Email, Input.Password, Input.RememberMe, lockoutOnFailure: true); + EssentialCSharpWebUser? userByName = await userManager.FindByNameAsync(Input.Email); + result = userByName is null + ? Microsoft.AspNetCore.Identity.SignInResult.Failed + : await signInManager.PasswordSignInAsync(userByName, Input.Password, Input.RememberMe, lockoutOnFailure: await CanBeLockedOutByPasswordAsync(userByName)); } if (result.Succeeded) { @@ -127,6 +130,10 @@ public async Task OnPostAsync(string? returnUrl = null, Cancellat return Page(); } + // An account without a password can't be guessed into, so wrong passwords must not lock it: otherwise anyone + // could lock an external-login-only account out of every sign-in method. + private Task CanBeLockedOutByPasswordAsync(EssentialCSharpWebUser user) => userManager.HasPasswordAsync(user); + [LoggerMessage(Level = LogLevel.Information, Message = "User logged in.")] private static partial void LogUserLoggedIn(ILogger logger); diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/Manage/Email.cshtml.cs b/EssentialCSharp.Web/Areas/Identity/Pages/Account/Manage/Email.cshtml.cs index 3163f877..0fb849df 100644 --- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/Manage/Email.cshtml.cs +++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/Manage/Email.cshtml.cs @@ -2,12 +2,14 @@ using System.Text; using System.Text.Encodings.Web; using EssentialCSharp.Web.Areas.Identity.Data; +using EssentialCSharp.Web.Extensions; using EssentialCSharp.Web.Services; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.WebUtilities; +using Microsoft.Extensions.Options; namespace EssentialCSharp.Web.Areas.Identity.Pages.Account.Manage; @@ -15,7 +17,8 @@ public partial class EmailModel( UserManager userManager, SignInManager signInManager, IEmailSender emailSender, - ILogger logger) : PageModel + ILogger logger, + IOptions siteSettings) : PageModel { private readonly UserManager _UserManager = userManager; private readonly SignInManager _SignInManager = signInManager; @@ -94,17 +97,21 @@ public async Task OnPostChangeEmailAsync() } string code = await _UserManager.GenerateChangeEmailTokenAsync(user, Input.NewEmail); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); - string? callbackUrl = Url.Page( + string? callbackUrl = Url.EmailPageLink( + siteSettings.Value, "/Account/ConfirmEmailChange", - pageHandler: null, - values: new { area = "Identity", userId = userId, email = Input.NewEmail, code = code }, - protocol: Request.Scheme); + values: new { area = "Identity", userId = userId, email = Input.NewEmail, code = code }); if (callbackUrl is null) { StatusMessage = "Error: callback url unexpectedly null."; return RedirectToPage(); } - if (!await TrySendConfirmationAsync(Input.NewEmail, callbackUrl)) + if (!await TrySendConfirmationAsync( + Input.NewEmail, + "Confirm your email change", + $"Someone asked to change the email address of an Essential C# account to this address. If that was you, " + + $"click here while logged in to that account to confirm the change. " + + "If it wasn't you, ignore this email: the address is not changed unless the link is opened by the account's owner.")) { return RedirectToPage(); } @@ -135,11 +142,10 @@ public async Task OnPostSendVerificationEmailAsync() string? email = await _UserManager.GetEmailAsync(user); string code = await _UserManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); - string? callbackUrl = Url.Page( + string? callbackUrl = Url.EmailPageLink( + siteSettings.Value, "/Account/ConfirmEmail", - pageHandler: null, - values: new { area = "Identity", userId = userId, code = code }, - protocol: Request.Scheme); + values: new { area = "Identity", userId = userId, code = code }); if (callbackUrl is null) { StatusMessage = "Error: callback url unexpectedly null."; @@ -149,7 +155,10 @@ public async Task OnPostSendVerificationEmailAsync() { return NotFound($"Unable to load user email with ID '{_UserManager.GetUserId(User)}'."); } - if (!await TrySendConfirmationAsync(email, callbackUrl)) + if (!await TrySendConfirmationAsync( + email, + "Confirm your email", + $"Please confirm your account by clicking here.")) { return RedirectToPage(); } @@ -159,14 +168,11 @@ public async Task OnPostSendVerificationEmailAsync() } /// Sends the confirmation link. On failure sets a friendly and returns false. - private async Task TrySendConfirmationAsync(string toEmail, string callbackUrl) + private async Task TrySendConfirmationAsync(string toEmail, string subject, string htmlMessage) { try { - await _EmailSender.SendEmailAsync( - toEmail, - "Confirm your email", - $"Please confirm your account by clicking here."); + await _EmailSender.SendEmailAsync(toEmail, subject, htmlMessage); return true; } catch (EmailSendException) diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/Register.cshtml.cs b/EssentialCSharp.Web/Areas/Identity/Pages/Account/Register.cshtml.cs index 6b537bcd..4d50cbea 100644 --- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/Register.cshtml.cs +++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/Register.cshtml.cs @@ -2,6 +2,8 @@ using System.Text; using System.Text.Encodings.Web; using EssentialCSharp.Web.Areas.Identity.Data; +using EssentialCSharp.Web.Areas.Identity.Services; +using EssentialCSharp.Web.Extensions; using EssentialCSharp.Web.Models; using EssentialCSharp.Web.Services; using Microsoft.AspNetCore.Authentication; @@ -22,7 +24,9 @@ public partial class RegisterModel( IEmailSender emailSender, ICaptchaValidationService captchaValidationService, IOptions optionsAccessor, - IUserEmailStore emailStore) : PageModel + IUserEmailStore emailStore, + IOptions siteSettings, + RegistrationBrowserBinding registrationBrowserBinding) : PageModel { public string CaptchaSiteKey { get; } = optionsAccessor.Value.SiteKey ?? string.Empty; @@ -118,13 +122,14 @@ public async Task OnPostAsync(string? returnUrl = null, Cancellat LogUserCreatedWithPassword(logger); string userId = await userManager.GetUserIdAsync(user); + // The password chosen here stays usable only if the confirmation link is opened in this browser. + registrationBrowserBinding.Issue(HttpContext, userId); string code = await userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); - string? callbackUrl = Url.Page( + string? callbackUrl = Url.EmailPageLink( + siteSettings.Value, "/Account/ConfirmEmail", - pageHandler: null, - values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl }, - protocol: Request.Scheme); + values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl }); if (callbackUrl is null) { diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/RegisterConfirmation.cshtml b/EssentialCSharp.Web/Areas/Identity/Pages/Account/RegisterConfirmation.cshtml index 48869443..f1f8c4f7 100644 --- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/RegisterConfirmation.cshtml +++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/RegisterConfirmation.cshtml @@ -5,19 +5,6 @@ }

@ViewData["Title"]

-@{ - if (@Model.DisplayConfirmAccountLink) -{ -

- This app does not currently have a real email sender registered, see these docs for how to configure a real email sender. - Normally this would be emailed: Click here to confirm your account -

- } -else -{

- Please check your email to confirm your account. If you can't find the email, please check your spam folder. + Please check your email to confirm your account. If you can't find the email, please check your spam folder.

- } -} - diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/RegisterConfirmation.cshtml.cs b/EssentialCSharp.Web/Areas/Identity/Pages/Account/RegisterConfirmation.cshtml.cs index 1f840a4f..72bb7d40 100644 --- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/RegisterConfirmation.cshtml.cs +++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/RegisterConfirmation.cshtml.cs @@ -1,61 +1,24 @@ -using System.Text; -using EssentialCSharp.Web.Areas.Identity.Data; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Identity; -using Microsoft.AspNetCore.Identity.UI.Services; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; -using Microsoft.AspNetCore.WebUtilities; namespace EssentialCSharp.Web.Areas.Identity.Pages.Account; [AllowAnonymous] public class RegisterConfirmationModel : PageModel { - private readonly UserManager _UserManager; - private readonly IEmailSender _Sender; - - public RegisterConfirmationModel(UserManager userManager, IEmailSender sender) - { - _UserManager = userManager; - _Sender = sender; - } - public string? Email { get; set; } - public bool DisplayConfirmAccountLink { get; set; } - - public string? EmailConfirmationUrl { get; set; } - - public async Task OnGetAsync(string? email, string? returnUrl = null) + // The page is the same whether or not an account exists for the email, so it can't be used to find out + // which addresses are registered. + public IActionResult OnGet(string? email) { if (email is null) { return RedirectToPage("/Index"); } - returnUrl ??= Url.Content("~/"); - - EssentialCSharpWebUser? user = await _UserManager.FindByEmailAsync(email); - if (user is null) - { - return NotFound($"Unable to load user with email '{email}'."); - } Email = email; - // Once you add a real email sender, you should remove this code that lets you confirm the account - DisplayConfirmAccountLink = false; - if (DisplayConfirmAccountLink) - { - string userId = await _UserManager.GetUserIdAsync(user); - string code = await _UserManager.GenerateEmailConfirmationTokenAsync(user); - code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); - EmailConfirmationUrl = Url.Page( - "/Account/ConfirmEmail", - pageHandler: null, - values: new { area = "Identity", userId = userId, code = code, returnUrl = returnUrl }, - protocol: Request.Scheme); - } - return Page(); } } diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResendEmailConfirmation.cshtml.cs b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResendEmailConfirmation.cshtml.cs index 9c66441b..e5dda833 100644 --- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResendEmailConfirmation.cshtml.cs +++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResendEmailConfirmation.cshtml.cs @@ -2,6 +2,7 @@ using System.Text; using System.Text.Encodings.Web; using EssentialCSharp.Web.Areas.Identity.Data; +using EssentialCSharp.Web.Extensions; using EssentialCSharp.Web.Services; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; @@ -14,7 +15,7 @@ namespace EssentialCSharp.Web.Areas.Identity.Pages.Account; [AllowAnonymous] -public partial class ResendEmailConfirmationModel(UserManager userManager, IEmailSender emailSender, ICaptchaValidationService captchaValidationService, IOptions optionsAccessor, ILogger logger) : PageModel +public partial class ResendEmailConfirmationModel(UserManager userManager, IEmailSender emailSender, ICaptchaValidationService captchaValidationService, IOptions optionsAccessor, ILogger logger, IOptions siteSettings) : PageModel { [TempData] public string? StatusMessage { get; set; } @@ -76,11 +77,10 @@ public async Task OnPostAsync(CancellationToken cancellationToken string userId = await userManager.GetUserIdAsync(user); string code = await userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); - string? callbackUrl = Url.Page( + string? callbackUrl = Url.EmailPageLink( + siteSettings.Value, "/Account/ConfirmEmail", - pageHandler: null, - values: new { userId = userId, code = code }, - protocol: Request.Scheme); + values: new { userId = userId, code = code }); if (callbackUrl is null) { diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResetPassword.cshtml.cs b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResetPassword.cshtml.cs index 19ebf68e..ada08142 100644 --- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResetPassword.cshtml.cs +++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResetPassword.cshtml.cs @@ -1,6 +1,7 @@ using System.ComponentModel.DataAnnotations; using System.Text; using EssentialCSharp.Web.Areas.Identity.Data; +using EssentialCSharp.Web.Areas.Identity.Services; using EssentialCSharp.Web.Services; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; @@ -10,7 +11,7 @@ namespace EssentialCSharp.Web.Areas.Identity.Pages.Account; -public class ResetPasswordModel(UserManager userManager, ICaptchaValidationService captchaValidationService, IOptions optionsAccessor) : PageModel +public class ResetPasswordModel(UserManager userManager, ICaptchaValidationService captchaValidationService, IOptions optionsAccessor, AccountOwnershipService accountOwnershipService) : PageModel { private InputModel? _Input; [BindProperty] @@ -103,6 +104,15 @@ public async Task OnPostAsync(CancellationToken cancellationToken IdentityResult result = await userManager.ResetPasswordAsync(user, Input.Code, Input.Password); if (result.Succeeded) { + // The reset token proves control of the mailbox. External logins and MCP tokens on the account + // may have been added by someone else before that, so they don't survive the reset. + await accountOwnershipService.RemoveCredentialsAddedBeforeOwnershipProofAsync(user, cancellationToken); + + // Failed password attempts by someone else shouldn't keep the owner locked out after they prove + // they own the account. + await userManager.SetLockoutEndDateAsync(user, null); + await userManager.ResetAccessFailedCountAsync(user); + return RedirectToPage("./ResetPasswordConfirmation"); } diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResetPasswordConfirmation.cshtml b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResetPasswordConfirmation.cshtml index c52552f3..9cf9c8b8 100644 --- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResetPasswordConfirmation.cshtml +++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/ResetPasswordConfirmation.cshtml @@ -8,3 +8,7 @@

Your password has been reset. Please click here to log in.

+

+ To keep your account safe, external logins (such as GitHub or Microsoft) and MCP tokens that were connected to + this account have been removed. After you log in, you can link them again from your account settings. +

diff --git a/EssentialCSharp.Web/Areas/Identity/Services/AccountOwnershipService.cs b/EssentialCSharp.Web/Areas/Identity/Services/AccountOwnershipService.cs new file mode 100644 index 00000000..9cfcffe6 --- /dev/null +++ b/EssentialCSharp.Web/Areas/Identity/Services/AccountOwnershipService.cs @@ -0,0 +1,118 @@ +using System.Text.Json; +using EssentialCSharp.Web.Areas.Identity.Data; +using EssentialCSharp.Web.Services; +using Microsoft.AspNetCore.Identity; + +namespace EssentialCSharp.Web.Areas.Identity.Services; + +/// +/// Keeps credentials off an account until the person adding them has proven they control the account's email +/// address, and clears anything attached before that proof. Without this, someone who registers (or links an +/// external login to) an address they don't own keeps a way in after the real owner confirms or resets it. +/// +public sealed class AccountOwnershipService( + UserManager userManager, + McpApiTokenService mcpApiTokenService) +{ + // Stored in AspNetUserTokens. The bracketed provider name cannot collide with a real external provider. + internal const string PendingExternalLoginTokenProvider = "[EssentialCSharpPendingExternalLogin]"; + internal const string PendingExternalLoginTokenName = "Login"; + + /// + /// Records the external login that asked to use this account. It is linked only by + /// , after the email is confirmed in a browser that still holds + /// the same external login. + /// + public Task SetPendingExternalLoginAsync(EssentialCSharpWebUser user, UserLoginInfo login) + { + ArgumentNullException.ThrowIfNull(login); + string value = JsonSerializer.Serialize(new PendingExternalLogin(login.LoginProvider, login.ProviderKey, login.ProviderDisplayName)); + return userManager.SetAuthenticationTokenAsync(user, PendingExternalLoginTokenProvider, PendingExternalLoginTokenName, value); + } + + /// Returns the display name of the provider whose login is waiting to be linked, if any. + public async Task GetPendingExternalLoginDisplayNameAsync(EssentialCSharpWebUser user) + { + PendingExternalLogin? pending = await GetPendingExternalLoginAsync(user); + return pending is null ? null : pending.ProviderDisplayName ?? pending.LoginProvider; + } + + /// + /// Links to only when it is the login recorded by + /// . Call it only after the caller has proven control of the email. + /// + /// when the login was linked. + public async Task TryLinkPendingExternalLoginAsync(EssentialCSharpWebUser user, UserLoginInfo? login) + { + if (login is null) + { + return false; + } + + PendingExternalLogin? pending = await GetPendingExternalLoginAsync(user); + if (pending is null + || !string.Equals(pending.LoginProvider, login.LoginProvider, StringComparison.Ordinal) + || !string.Equals(pending.ProviderKey, login.ProviderKey, StringComparison.Ordinal)) + { + return false; + } + + IdentityResult result = await userManager.AddLoginAsync(user, login); + if (!result.Succeeded) + { + return false; + } + + await userManager.RemoveAuthenticationTokenAsync(user, PendingExternalLoginTokenProvider, PendingExternalLoginTokenName); + return true; + } + + /// + /// Call when someone has just proven control of the account's email (first confirmation or a password reset). + /// Removes every external login and revokes every MCP token, because any of them may have been added by + /// someone else before that proof, then rotates the security stamp so existing sessions and tokens end. + /// + public async Task RemoveCredentialsAddedBeforeOwnershipProofAsync(EssentialCSharpWebUser user, CancellationToken cancellationToken = default) + { + ArgumentNullException.ThrowIfNull(user); + + foreach (UserLoginInfo login in await userManager.GetLoginsAsync(user)) + { + IdentityResult removed = await userManager.RemoveLoginAsync(user, login.LoginProvider, login.ProviderKey); + if (!removed.Succeeded) + { + throw new InvalidOperationException( + $"Could not remove the {login.LoginProvider} login: {string.Join("; ", removed.Errors.Select(e => e.Description))}"); + } + } + + await mcpApiTokenService.RevokeAllTokensAsync(user.Id, cancellationToken); + + IdentityResult stampResult = await userManager.UpdateSecurityStampAsync(user); + if (!stampResult.Succeeded) + { + throw new InvalidOperationException( + $"Could not rotate the security stamp: {string.Join("; ", stampResult.Errors.Select(e => e.Description))}"); + } + } + + private async Task GetPendingExternalLoginAsync(EssentialCSharpWebUser user) + { + string? value = await userManager.GetAuthenticationTokenAsync(user, PendingExternalLoginTokenProvider, PendingExternalLoginTokenName); + if (string.IsNullOrEmpty(value)) + { + return null; + } + + try + { + return JsonSerializer.Deserialize(value); + } + catch (JsonException) + { + return null; + } + } + + private sealed record PendingExternalLogin(string LoginProvider, string ProviderKey, string? ProviderDisplayName); +} diff --git a/EssentialCSharp.Web/Areas/Identity/Services/RegistrationBrowserBinding.cs b/EssentialCSharp.Web/Areas/Identity/Services/RegistrationBrowserBinding.cs new file mode 100644 index 00000000..efdd33e7 --- /dev/null +++ b/EssentialCSharp.Web/Areas/Identity/Services/RegistrationBrowserBinding.cs @@ -0,0 +1,74 @@ +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; + +namespace EssentialCSharp.Web.Areas.Identity.Services; + +/// +/// Remembers, in a protected cookie, which account this browser just registered. The first email confirmation +/// keeps the password chosen at registration only when the link is opened in that same browser; anywhere else, +/// the person clicking proved only that they own the mailbox, so they are asked to choose their own password. +/// +public sealed class RegistrationBrowserBinding( + IDataProtectionProvider dataProtectionProvider, + IOptions tokenOptions) +{ + internal const string CookieName = ".EssentialCSharp.RegistrationBinding"; + private const string CookiePath = "/Identity/Account"; + private const string Purpose = "EssentialCSharp.Web.RegistrationBrowserBinding.v1"; + + // Confirmation links are emailed with the default token provider, so the binding lasts as long as the link. + private TimeSpan Lifetime => tokenOptions.Value.TokenLifespan; + + private ITimeLimitedDataProtector Protector => + dataProtectionProvider.CreateProtector(Purpose).ToTimeLimitedDataProtector(); + + public void Issue(HttpContext httpContext, string userId) + { + ArgumentNullException.ThrowIfNull(httpContext); + ArgumentException.ThrowIfNullOrEmpty(userId); + + string value = Protector.Protect(userId, Lifetime); + httpContext.Response.Cookies.Append(CookieName, value, CreateCookieOptions(httpContext, DateTimeOffset.UtcNow.Add(Lifetime))); + } + + public bool IsBoundTo(HttpContext httpContext, string userId) + { + ArgumentNullException.ThrowIfNull(httpContext); + + if (!httpContext.Request.Cookies.TryGetValue(CookieName, out string? value) || string.IsNullOrEmpty(value)) + { + return false; + } + + try + { + return string.Equals(Protector.Unprotect(value), userId, StringComparison.Ordinal); + } + catch (System.Security.Cryptography.CryptographicException) + { + // Expired, tampered with or protected with a key that no longer exists. + return false; + } + } + + public void Clear(HttpContext httpContext) + { + ArgumentNullException.ThrowIfNull(httpContext); + if (httpContext.Request.Cookies.ContainsKey(CookieName)) + { + httpContext.Response.Cookies.Delete(CookieName, CreateCookieOptions(httpContext, expires: null)); + } + } + + private static CookieOptions CreateCookieOptions(HttpContext httpContext, DateTimeOffset? expires) => new() + { + HttpOnly = true, + Secure = httpContext.Request.IsHttps, + // Lax so the cookie is sent when the user follows the emailed link (a top-level GET navigation). + SameSite = SameSiteMode.Lax, + Path = CookiePath, + IsEssential = true, + Expires = expires, + }; +} diff --git a/EssentialCSharp.Web/Extensions/UrlHelperExtensions.cs b/EssentialCSharp.Web/Extensions/UrlHelperExtensions.cs new file mode 100644 index 00000000..5121b510 --- /dev/null +++ b/EssentialCSharp.Web/Extensions/UrlHelperExtensions.cs @@ -0,0 +1,43 @@ +using EssentialCSharp.Web.Services; +using Microsoft.AspNetCore.Mvc; + +namespace EssentialCSharp.Web.Extensions; + +public static class UrlHelperExtensions +{ + /// + /// Generates an absolute URL for a Razor page that is safe to put in an email. The origin comes from the + /// configured , never from the request's Host header, so a request + /// with a forged Host cannot make the app email a link (and its token) to another site. + /// + /// The absolute URL, or when the page cannot be resolved. + public static string? EmailPageLink(this IUrlHelper url, SiteSettings siteSettings, string pageName, object? values) + { + ArgumentNullException.ThrowIfNull(url); + ArgumentNullException.ThrowIfNull(siteSettings); + + string? link = url.Page(pageName, pageHandler: null, values); + if (link is null) + { + return null; + } + + if (!Uri.TryCreate(siteSettings.BaseUrl, UriKind.Absolute, out Uri? baseUri)) + { + throw new InvalidOperationException( + $"{SiteSettings.SectionName}:{nameof(SiteSettings.BaseUrl)} must be an absolute URL to generate email links."); + } + + // Keep only the path and query of whatever the URL helper produced, then attach the configured origin. + string pathAndQuery = Uri.TryCreate(link, UriKind.Absolute, out Uri? absolute) + && (absolute.Scheme == Uri.UriSchemeHttp || absolute.Scheme == Uri.UriSchemeHttps) + ? absolute.PathAndQuery + : link; + if (!pathAndQuery.StartsWith('/')) + { + pathAndQuery = "/" + pathAndQuery; + } + + return baseUri.GetLeftPart(UriPartial.Authority) + pathAndQuery; + } +} diff --git a/EssentialCSharp.Web/Program.cs b/EssentialCSharp.Web/Program.cs index 4fffe529..b456b6ad 100644 --- a/EssentialCSharp.Web/Program.cs +++ b/EssentialCSharp.Web/Program.cs @@ -4,6 +4,7 @@ using ModelContextProtocol.Protocol; using EssentialCSharp.Chat.Common.Extensions; using EssentialCSharp.Web.Areas.Identity.Data; +using EssentialCSharp.Web.Areas.Identity.Services; using EssentialCSharp.Web.Areas.Identity.Services.PasswordValidators; using EssentialCSharp.Web.Auth; using EssentialCSharp.Web.Data; @@ -193,6 +194,8 @@ private static void Main(string[] args) // MCP server — always enabled, authenticated via opaque DB-backed tokens. builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddMemoryCache(); builder.Services.AddSingleton(_ => new ResponseIdValidationService()); diff --git a/EssentialCSharp.Web/Services/McpApiTokenService.cs b/EssentialCSharp.Web/Services/McpApiTokenService.cs index 3cdc4ee1..9d7b1756 100644 --- a/EssentialCSharp.Web/Services/McpApiTokenService.cs +++ b/EssentialCSharp.Web/Services/McpApiTokenService.cs @@ -98,6 +98,14 @@ public async Task RevokeTokenAsync( return rows > 0; } + /// Revokes every token the user still has. Returns the number of tokens revoked. + public Task RevokeAllTokensAsync( + string userId, + CancellationToken cancellationToken = default) + => db.McpApiTokens + .Where(t => t.UserId == userId && t.RevokedAt == null) + .ExecuteUpdateAsync(s => s.SetProperty(t => t.RevokedAt, DateTime.UtcNow), cancellationToken); + /// Returns the count of active (non-revoked, non-expired) tokens for the specified user. public Task GetActiveTokenCountAsync( string userId,