Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 144 additions & 0 deletions EssentialCSharp.Web.Tests/Identity/AccountRecoveryHardeningTests.cs
Original file line number Diff line number Diff line change
@@ -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;

/// <summary>
/// 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.
/// </summary>
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<IOptions<SiteSettings>>().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<IOptions<SiteSettings>>().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<EssentialCSharpWebUser> users = sp.GetRequiredService<UserManager<EssentialCSharpWebUser>>();
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();
}
}
}
94 changes: 94 additions & 0 deletions EssentialCSharp.Web.Tests/Identity/ConfirmEmailChangeTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
using System.Net;
using EssentialCSharp.Web.Areas.Identity.Data;

namespace EssentialCSharp.Web.Tests.Identity;

/// <summary>
/// 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.
/// </summary>
public class ConfirmEmailChangeTests : IntegrationTestBase
{
private static async Task<(IdentityFlowHarness Harness, Browser Requester, string RequesterEmail, string NewEmail, string Link)> RequestChangeAsync(Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory<Program> 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();
}
}
}
Loading
Loading