[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
+15
View File
@@ -68,6 +68,21 @@ public enum ExceptionEnum
[Description("Aircraft not found or wrong role.")]
AircraftNotFound = 55,
[Description("MFA is already enabled for this user.")]
MfaAlreadyEnabled = 56,
[Description("MFA enrollment is not in progress for this user.")]
MfaNotEnrolling = 57,
[Description("MFA is not enabled for this user.")]
MfaNotEnabled = 58,
[Description("Invalid MFA code or recovery code.")]
InvalidMfaCode = 59,
[Description("MFA token is invalid or expired.")]
InvalidMfaToken = 61,
[Description("No file provided.")]
NoFileProvided = 60,
}
@@ -34,7 +34,12 @@ public static class AzaionDbSchemaHolder
.HasConversion(
v => v == null ? null : JsonConvert.SerializeObject(v),
p => string.IsNullOrEmpty(p) ? new UserConfig() : JsonConvert.DeserializeObject<UserConfig>(p))
.IsNullable();
.IsNullable()
// AZ-534 — mfa_recovery_codes is JSONB; tell the provider so Npgsql sends
// the JSON type oid instead of text (otherwise inserts fail with
// "column is of type jsonb but expression is of type text").
.Property(x => x.MfaRecoveryCodes)
.HasDataType(DataType.BinaryJson);
builder.Entity<DetectionClass>()
.HasTableName("detection_classes")
+11 -3
View File
@@ -12,7 +12,15 @@ public class AuditEvent
public static class AuditEventTypes
{
public const string LoginFailed = "login_failed";
public const string LoginLockout = "login_lockout";
public const string LoginSuccess = "login_success";
public const string LoginFailed = "login_failed";
public const string LoginLockout = "login_lockout";
public const string LoginSuccess = "login_success";
// AZ-534 — MFA lifecycle + login events.
public const string MfaEnroll = "mfa_enroll";
public const string MfaConfirm = "mfa_confirm";
public const string MfaDisable = "mfa_disable";
public const string MfaLoginSuccess = "mfa_login_success";
public const string MfaLoginFailed = "mfa_login_failed";
public const string MfaRecoveryUsed = "mfa_recovery_used";
}
+7
View File
@@ -43,6 +43,13 @@ public class Session
/// interactive sessions.
/// </summary>
public Guid? AircraftId { get; set; }
/// <summary>
/// AZ-534 — true iff the session was created via an MFA-validated /login/mfa
/// call. Refresh-token rotation reads this to keep the AMR claim stable across
/// the session lifetime.
/// </summary>
public bool MfaAuthenticated { get; set; }
}
public static class SessionRevokedReasons
+14
View File
@@ -20,6 +20,20 @@ public class User
public int FailedLoginCount { get; set; }
public DateTime? LockoutUntil { get; set; }
// AZ-534 — TOTP-based 2FA. mfa_secret is encrypted at rest; recovery codes are
// stored as a JSONB array of { hash, used_at } objects. mfa_last_used_window
// is the RFC 6238 time-step counter of the most recently accepted code,
// used to reject in-window replays.
[JsonIgnore]
public bool MfaEnabled { get; set; }
[JsonIgnore]
public string? MfaSecret { get; set; }
[JsonIgnore]
public string? MfaRecoveryCodes { get; set; }
public DateTime? MfaEnrolledAt { get; set; }
[JsonIgnore]
public long? MfaLastUsedWindow { get; set; }
public static string GetCacheKey(string email) =>
string.IsNullOrEmpty(email) ? "" : $"{nameof(User)}.{email}";
}
+43
View File
@@ -0,0 +1,43 @@
namespace Azaion.Common.Requests;
/// <summary>AZ-534 — body for <c>POST /users/me/mfa/enroll</c>.</summary>
public class MfaEnrollRequest
{
public string Password { get; set; } = null!;
}
/// <summary>AZ-534 — response of /enroll (also surfaces recovery codes ONCE; they are
/// hashed at rest and unrecoverable after this response).</summary>
public class MfaEnrollResponse
{
public string Secret { get; set; } = null!;
public string OtpAuthUrl { get; set; } = null!;
public string QrPngBase64 { get; set; } = null!;
public string[] RecoveryCodes { get; set; } = [];
}
public class MfaConfirmRequest
{
public string Code { get; set; } = null!;
}
public class MfaDisableRequest
{
public string Password { get; set; } = null!;
public string Code { get; set; } = null!;
}
/// <summary>AZ-534 AC-3 — response of step-1 /login when the user has MFA enabled.
/// The mfa_token is a short-lived JWT carried into <c>POST /login/mfa</c>.</summary>
public class MfaRequiredResponse
{
public bool MfaRequired { get; set; } = true;
public string MfaToken { get; set; } = null!;
public int ExpiresIn { get; set; }
}
public class MfaLoginRequest
{
public string MfaToken { get; set; } = null!;
public string Code { get; set; } = null!;
}