Files
admin/Azaion.Services/AuditLog.cs
T
Oleksandr Bezdieniezhnykh 1e1ded73f5
ci/woodpecker/push/01-test Pipeline failed
ci/woodpecker/push/02-build-push unknown status
[AZ-534] TOTP-based 2FA at credential login
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>
2026-05-14 06:21:28 +03:00

81 lines
3.7 KiB
C#

using Azaion.Common.Database;
using Azaion.Common.Entities;
using LinqToDB;
using Microsoft.AspNetCore.Http;
namespace Azaion.Services;
public interface IAuditLog
{
Task RecordLoginFailed (string email, CancellationToken ct = default);
Task RecordLoginLockout(string email, CancellationToken ct = default);
Task RecordLoginSuccess(string email, CancellationToken ct = default);
// AZ-534 — MFA lifecycle + login auth-event audit.
Task RecordMfaEnroll (string email, CancellationToken ct = default);
Task RecordMfaConfirm (string email, CancellationToken ct = default);
Task RecordMfaDisable (string email, CancellationToken ct = default);
Task RecordMfaLoginSuccess (string email, CancellationToken ct = default);
Task RecordMfaLoginFailed (string email, CancellationToken ct = default);
Task RecordMfaRecoveryUsed (string email, CancellationToken ct = default);
/// <summary>
/// Number of `login_failed` rows for the given email within the last <paramref name="windowSeconds"/>.
/// Used by the per-account sliding-window rate limit (AZ-537 AC-2).
/// </summary>
Task<int> CountRecentFailedLogins(string email, int windowSeconds, CancellationToken ct = default);
}
public class AuditLog(IDbFactory dbFactory, IHttpContextAccessor httpContextAccessor) : IAuditLog
{
public Task RecordLoginFailed (string email, CancellationToken ct = default)
=> Insert(AuditEventTypes.LoginFailed, email, ct);
public Task RecordLoginLockout(string email, CancellationToken ct = default)
=> Insert(AuditEventTypes.LoginLockout, email, ct);
public Task RecordLoginSuccess(string email, CancellationToken ct = default)
=> Insert(AuditEventTypes.LoginSuccess, email, ct);
public Task RecordMfaEnroll (string email, CancellationToken ct = default)
=> Insert(AuditEventTypes.MfaEnroll, email, ct);
public Task RecordMfaConfirm (string email, CancellationToken ct = default)
=> Insert(AuditEventTypes.MfaConfirm, email, ct);
public Task RecordMfaDisable (string email, CancellationToken ct = default)
=> Insert(AuditEventTypes.MfaDisable, email, ct);
public Task RecordMfaLoginSuccess (string email, CancellationToken ct = default)
=> Insert(AuditEventTypes.MfaLoginSuccess, email, ct);
public Task RecordMfaLoginFailed (string email, CancellationToken ct = default)
=> Insert(AuditEventTypes.MfaLoginFailed, email, ct);
public Task RecordMfaRecoveryUsed (string email, CancellationToken ct = default)
=> Insert(AuditEventTypes.MfaRecoveryUsed, email, ct);
public async Task<int> CountRecentFailedLogins(string email, int windowSeconds, CancellationToken ct = default)
{
var cutoff = DateTime.UtcNow.AddSeconds(-windowSeconds);
var normalised = email.ToLowerInvariant();
return await dbFactory.Run(async db =>
await db.AuditEvents
.Where(e => e.EventType == AuditEventTypes.LoginFailed
&& e.Email == normalised
&& e.OccurredAt >= cutoff)
.CountAsync(token: ct));
}
private async Task Insert(string eventType, string email, CancellationToken ct)
{
var ip = httpContextAccessor.HttpContext?.Connection.RemoteIpAddress?.ToString();
var normalised = email.ToLowerInvariant();
await dbFactory.RunAdmin(async db =>
{
await db.InsertAsync(new AuditEvent
{
EventType = eventType,
OccurredAt = DateTime.UtcNow,
Email = normalised,
Ip = ip
}, token: ct);
});
}
}