[AZ-534] TOTP-based 2FA at credential login
ci/woodpecker/push/01-test Pipeline failed
ci/woodpecker/push/02-build-push unknown status

Add RFC 6238 TOTP enrollment, two-step /login flow, recovery codes, and
the amr=["pwd","mfa"] claim that propagates through refresh-token rotation.

- New endpoints: /users/me/mfa/{enroll,confirm,disable} and /login/mfa.
- /login short-circuits to a 5-min ES256 step-1 token (audience-pinned
  azaion-mfa-step2) when the user has MFA enabled; real access+refresh
  pair is minted only after /login/mfa.
- mfa_secret encrypted at rest via ASP.NET Core IDataProtector
  (purpose=Azaion.Mfa.Secret.v1; key folder configurable via
  DataProtection:KeysFolder for production persistence).
- Recovery codes (10 single-use, base32, ~80-bit entropy) hashed with
  SHA-256 and stored as JSONB; constant-time compare on lookup.
- RFC 6238 §5.2 replay defense via mfa_last_used_window per user.
- Sessions carry mfa_authenticated so /token/refresh re-stamps the
  amr claim correctly across the entire 30-day refresh window.
- New audit events: enroll, confirm, disable, login-success/failed,
  recovery-used.
- Schema: env/db/10_users_mfa.sql adds users.mfa_* columns and
  sessions.mfa_authenticated; mfa_recovery_codes mapped as BinaryJson
  in AzaionDbSchemaHolder; disable path uses raw parameterised SQL to
  avoid LinqToDB null-literal type-inference on jsonb columns.

E2E: 6 new tests in MfaLoginTests cover all six AC; full suite
82 passed / 0 failed / 3 intentional skips.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
Oleksandr Bezdieniezhnykh
2026-05-14 06:21:28 +03:00
parent 8e7c602f51
commit 1e1ded73f5
24 changed files with 1188 additions and 57 deletions
+23 -20
View File
@@ -18,9 +18,10 @@ public interface IRefreshTokenService
/// <summary>
/// Mint a fresh refresh token at login; starts a new session family. Returns
/// the opaque token (NEVER persisted; only its sha256 lands in the DB) and
/// the session row that backs it.
/// the session row that backs it. <paramref name="mfaAuthenticated"/> is pinned
/// to the session so refresh-token rotation inherits the original AMR strength.
/// </summary>
Task<(string OpaqueToken, Session Session)> IssueForNewLogin(Guid userId, CancellationToken ct = default);
Task<(string OpaqueToken, Session Session)> IssueForNewLogin(Guid userId, bool mfaAuthenticated = false, CancellationToken ct = default);
/// <summary>
/// Rotate <paramref name="opaqueToken"/>. On success returns the new token +
@@ -37,20 +38,21 @@ public class RefreshTokenService(IDbFactory dbFactory, IOptions<SessionConfig> s
private readonly SessionConfig _cfg = sessionConfig.Value;
public async Task<(string OpaqueToken, Session Session)> IssueForNewLogin(Guid userId, CancellationToken ct = default)
public async Task<(string OpaqueToken, Session Session)> IssueForNewLogin(Guid userId, bool mfaAuthenticated = false, CancellationToken ct = default)
{
var (opaque, hash) = GenerateToken();
var now = DateTime.UtcNow;
var session = new Session
{
Id = Guid.NewGuid(),
UserId = userId,
RefreshHash = hash,
FamilyId = Guid.NewGuid(), // self-rooted family
IssuedAt = now,
LastUsedAt = now,
ExpiresAt = now.AddHours(_cfg.RefreshSlidingHours),
FamilyStartedAt = now,
Id = Guid.NewGuid(),
UserId = userId,
RefreshHash = hash,
FamilyId = Guid.NewGuid(), // self-rooted family
IssuedAt = now,
LastUsedAt = now,
ExpiresAt = now.AddHours(_cfg.RefreshSlidingHours),
FamilyStartedAt = now,
MfaAuthenticated = mfaAuthenticated,
};
// family_id should equal id for the root row so SELECT family_id from
// any row returns a stable handle even if id is renamed later.
@@ -104,15 +106,16 @@ public class RefreshTokenService(IDbFactory dbFactory, IOptions<SessionConfig> s
var (newOpaque, newHash) = GenerateToken();
var newSession = new Session
{
Id = Guid.NewGuid(),
UserId = current.UserId,
RefreshHash = newHash,
FamilyId = current.FamilyId,
IssuedAt = now,
LastUsedAt = now,
ExpiresAt = now.AddHours(_cfg.RefreshSlidingHours),
FamilyStartedAt = current.FamilyStartedAt,
ParentSessionId = current.Id,
Id = Guid.NewGuid(),
UserId = current.UserId,
RefreshHash = newHash,
FamilyId = current.FamilyId,
IssuedAt = now,
LastUsedAt = now,
ExpiresAt = now.AddHours(_cfg.RefreshSlidingHours),
FamilyStartedAt = current.FamilyStartedAt,
ParentSessionId = current.Id,
MfaAuthenticated = current.MfaAuthenticated,
};
await db.Sessions