feat(auth): add trusted-device 30-day 2FA skip (backend)

Adds a "trust this device" option to the 2FA challenge: on success, mints a
random token (only its SHA-256 hash is stored), sets it as a new httpOnly,
Secure, SameSite=Strict cookie, and records a TrustedDevice row. AuthController
checks that cookie for the exact signing-in user before gating on 2FA -- a
mismatched user, expired, or revoked device falls through to the normal 2FA
prompt, never errors. TwoFactorController also exposes list/revoke/revoke-all
endpoints for managing trusted devices, scoped to the owning user.

Schema added via the existing raw-SQL reconciler (SQLite + MySQL dialects),
not EF migrations, matching this repo's established pattern.
This commit is contained in:
cesnimda
2026-07-13 01:02:35 +02:00
parent b85dc1ffb7
commit b914630657
10 changed files with 554 additions and 9 deletions
@@ -6,6 +6,7 @@ using Microsoft.AspNetCore.DataProtection;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Moq;
using OtpNet;
using Xunit;
@@ -163,6 +164,104 @@ public sealed class TwoFactorControllerTests
Assert.IsType<UnauthorizedResult>(reuse);
}
[Fact]
public async Task Challenge_with_trust_device_true_creates_trusted_device_and_sets_cookie()
{
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com" };
var userManager = TestHostFactory.CreateUserManager();
userManager.Setup(x => x.CheckPasswordAsync(user, "correct-password")).ReturnsAsync(true);
userManager.Setup(x => x.UpdateAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(IdentityResult.Success);
userManager.Setup(x => x.FindByIdAsync("user-1")).ReturnsAsync(user);
var pending = new TwoFactorPendingTokenService(new Microsoft.Extensions.Caching.Memory.MemoryCache(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions()));
using var db = TestHostFactory.CreateInMemoryDb("user-1");
var controller = BuildController(userManager, db, pending, currentUser: user);
var setupResult = Assert.IsType<OkObjectResult>(await controller.Setup(new TwoFactorController.PasswordConfirmRequest("correct-password"), CancellationToken.None));
var setup = Assert.IsType<TwoFactorController.SetupResult>(setupResult.Value);
var code = new Totp(Base32Encoding.ToBytes(setup.ManualEntryKey)).ComputeTotp();
await controller.VerifySetup(new TwoFactorController.VerifySetupRequest(code), CancellationToken.None);
var pendingToken = pending.IssuePendingToken("user-1", rememberMe: false);
var challengeCode = new Totp(Base32Encoding.ToBytes(setup.ManualEntryKey)).ComputeTotp();
var challengeResult = Assert.IsType<OkObjectResult>(await controller.Challenge(new TwoFactorController.ChallengeRequest(pendingToken, challengeCode, TrustDevice: true), CancellationToken.None));
Assert.True(Assert.IsType<AuthController.AuthSessionResult>(challengeResult.Value).Authenticated);
var device = Assert.Single(db.TrustedDevices.IgnoreQueryFilters().Where(x => x.UserId == "user-1"));
Assert.NotNull(device.TokenHash);
var setCookieHeaders = controller.Response.Headers["Set-Cookie"];
var trustedDeviceCookie = Assert.Single(setCookieHeaders, h => h!.StartsWith($"{AuthSessionOptions.TrustedDeviceCookieName}=", StringComparison.Ordinal))!;
Assert.Contains("httponly", trustedDeviceCookie, StringComparison.OrdinalIgnoreCase);
Assert.Contains("samesite=strict", trustedDeviceCookie, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task Challenge_without_trust_device_does_not_create_trusted_device()
{
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com" };
var userManager = TestHostFactory.CreateUserManager();
userManager.Setup(x => x.CheckPasswordAsync(user, "correct-password")).ReturnsAsync(true);
userManager.Setup(x => x.UpdateAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(IdentityResult.Success);
userManager.Setup(x => x.FindByIdAsync("user-1")).ReturnsAsync(user);
var pending = new TwoFactorPendingTokenService(new Microsoft.Extensions.Caching.Memory.MemoryCache(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions()));
using var db = TestHostFactory.CreateInMemoryDb("user-1");
var controller = BuildController(userManager, db, pending, currentUser: user);
var setupResult = Assert.IsType<OkObjectResult>(await controller.Setup(new TwoFactorController.PasswordConfirmRequest("correct-password"), CancellationToken.None));
var setup = Assert.IsType<TwoFactorController.SetupResult>(setupResult.Value);
var code = new Totp(Base32Encoding.ToBytes(setup.ManualEntryKey)).ComputeTotp();
await controller.VerifySetup(new TwoFactorController.VerifySetupRequest(code), CancellationToken.None);
var pendingToken = pending.IssuePendingToken("user-1", rememberMe: false);
var challengeCode = new Totp(Base32Encoding.ToBytes(setup.ManualEntryKey)).ComputeTotp();
await controller.Challenge(new TwoFactorController.ChallengeRequest(pendingToken, challengeCode), CancellationToken.None);
Assert.Empty(db.TrustedDevices.IgnoreQueryFilters().Where(x => x.UserId == "user-1"));
}
[Fact]
public async Task Trusted_devices_can_be_listed_revoked_and_revoked_in_bulk_scoped_to_owner()
{
var user = new ApplicationUser { Id = "user-1", Email = "person@example.com", UserName = "person@example.com" };
var otherUser = new ApplicationUser { Id = "user-2", Email = "other@example.com", UserName = "other@example.com" };
var userManager = TestHostFactory.CreateUserManager();
using var db = TestHostFactory.CreateInMemoryDb("user-1");
db.TrustedDevices.Add(new TrustedDevice { UserId = "user-1", TokenHash = "hash-1", DeviceLabel = "Chrome on Windows", CreatedAtUtc = DateTimeOffset.UtcNow, LastSeenAtUtc = DateTimeOffset.UtcNow, ExpiresAtUtc = DateTimeOffset.UtcNow.AddDays(30) });
db.TrustedDevices.Add(new TrustedDevice { UserId = "user-1", TokenHash = "hash-2", DeviceLabel = "Safari on Mac", CreatedAtUtc = DateTimeOffset.UtcNow, LastSeenAtUtc = DateTimeOffset.UtcNow, ExpiresAtUtc = DateTimeOffset.UtcNow.AddDays(30) });
db.TrustedDevices.Add(new TrustedDevice { UserId = "user-2", TokenHash = "hash-3", DeviceLabel = "Someone else's device", CreatedAtUtc = DateTimeOffset.UtcNow, LastSeenAtUtc = DateTimeOffset.UtcNow, ExpiresAtUtc = DateTimeOffset.UtcNow.AddDays(30) });
db.SaveChanges();
var otherDeviceId = db.TrustedDevices.IgnoreQueryFilters().Single(x => x.UserId == "user-2").Id;
var controller = BuildController(userManager, db, currentUser: user);
var listResult = Assert.IsType<OkObjectResult>(await controller.ListTrustedDevices(CancellationToken.None));
var list = Assert.IsType<List<TwoFactorController.TrustedDeviceDto>>(listResult.Value);
Assert.Equal(2, list.Count);
// Can't revoke another user's device, even by guessing its id.
var revokeOther = await controller.RevokeTrustedDevice(otherDeviceId, CancellationToken.None);
Assert.IsType<NotFoundResult>(revokeOther);
Assert.NotNull(db.TrustedDevices.IgnoreQueryFilters().SingleOrDefault(x => x.Id == otherDeviceId));
var ownDeviceId = list[0].Id;
var revokeOwn = await controller.RevokeTrustedDevice(ownDeviceId, CancellationToken.None);
Assert.IsType<NoContentResult>(revokeOwn);
Assert.Null(db.TrustedDevices.IgnoreQueryFilters().SingleOrDefault(x => x.Id == ownDeviceId));
var revokeAll = await controller.RevokeAllTrustedDevices(CancellationToken.None);
Assert.IsType<NoContentResult>(revokeAll);
Assert.Empty(db.TrustedDevices.IgnoreQueryFilters().Where(x => x.UserId == "user-1"));
Assert.NotNull(db.TrustedDevices.IgnoreQueryFilters().SingleOrDefault(x => x.UserId == "user-2"));
}
[Fact]
public async Task Challenge_with_unknown_pending_token_is_rejected()
{