[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
+26
View File
@@ -241,6 +241,32 @@ public sealed class DbHelper
rd.IsDBNull(2) ? null : rd.GetGuid(2));
}
/// <summary>
/// AZ-534 — read mfa_secret raw to assert it's encrypted at rest.
/// </summary>
public async Task<string?> GetMfaSecretRaw(string email, CancellationToken ct = default)
{
await using var conn = await OpenAsync(ct);
await using var cmd = new NpgsqlCommand(
"SELECT mfa_secret FROM public.users WHERE email = @e", conn);
cmd.Parameters.AddWithValue("e", email);
var raw = await cmd.ExecuteScalarAsync(ct);
return raw is null or DBNull ? null : (string)raw;
}
/// <summary>
/// AZ-534 — read mfa_enabled flag.
/// </summary>
public async Task<bool> GetMfaEnabled(string email, CancellationToken ct = default)
{
await using var conn = await OpenAsync(ct);
await using var cmd = new NpgsqlCommand(
"SELECT mfa_enabled FROM public.users WHERE email = @e", conn);
cmd.Parameters.AddWithValue("e", email);
var raw = await cmd.ExecuteScalarAsync(ct);
return raw is bool b && b;
}
/// <summary>
/// AZ-535 — promote a user to <c>Service</c> role so they can read /sessions/revoked.
/// </summary>