feat(auth): complete MFA grace period for required roles + ops monitoring
Finishes the half-implemented MFA enforcement work and ships the SLO
monitoring rules at the same time.
MFA grace period (auth):
- New `mfa-policy.ts` central source of truth: `MFA_REQUIRED_ROLES = [ADMIN]`,
`MFA_GRACE_PERIOD_DAYS = 14`, `MFA_REAUTH_WINDOW_MINUTES = 15`.
- New columns `User.mfaGraceStartedAt` + `User.mfaLastVerifiedAt`
(migration `20260429000000_add_mfa_grace_columns`).
- `JwtPayload.mfa: 'none' | 'grace' | 'enrollment_required'` claim now
carried in every access token so the FE + admin guards can react.
- `LoginUserHandler.resolveMfaGraceClaim()`:
* If role requires MFA and user has not enrolled, lazy-stamp
`mfaGraceStartedAt` on first login (returns `mfa: 'grace'`,
`remainingDays: 14`).
* After window expires → `mfa: 'enrollment_required'`, `remainingDays: 0`
(callers must force enrolment on sensitive routes).
* Otherwise → `mfa: 'none'`.
- `LocalStrategy` now passes `totpEnabled` + `mfaGraceStartedAt` through
to the command so the handler can branch without an extra query.
- `IUserRepository` + `PrismaUserRepository` get
`updateMfaGraceStartedAt` / `updateMfaLastVerifiedAt`.
- `UserEntity` carries the two new fields end-to-end (props, getters,
`createNew` + `createPasswordless` factories). Fixed an orphan-property
syntax bug in `createPasswordless` that was breaking typecheck.
- `oauth.service.ts` `UserEntity` construction now includes `deletedAt`
+ the two MFA fields (was missing required props).
- Add missing `jsonwebtoken` + `@types/jsonwebtoken` to `apps/api`
(transitively pulled in via `jwt-rotation.ts` from commit 3705193 but
never declared, so `tsc --noEmit` was failing).
- Update `login-user.handler.spec.ts` + `local.strategy.spec.ts` to cover
grace-window + enrolment-required branches. 338/338 auth tests pass.
Ops monitoring:
- New `monitoring/prometheus/slo-rules.yml` with recording + alerting
rules for the agreed SLOs.
- Wire it into `prometheus.yml` + alertmanager routing.
- Capture the SLO soak-test results in
`docs/audits/slo-soak-test-log.md`.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -5,6 +5,8 @@ describe('LoginUserHandler', () => {
|
||||
let handler: LoginUserHandler;
|
||||
let mockTokenService: { generateTokenPair: ReturnType<typeof vi.fn> };
|
||||
let mockChallengeRepo: { create: ReturnType<typeof vi.fn> };
|
||||
let mockUserRepo: { updateMfaGraceStartedAt: ReturnType<typeof vi.fn> };
|
||||
let mockLogger: { error: ReturnType<typeof vi.fn>; warn: ReturnType<typeof vi.fn> };
|
||||
|
||||
const tokenPair = {
|
||||
accessToken: 'access-jwt',
|
||||
@@ -15,22 +17,30 @@ describe('LoginUserHandler', () => {
|
||||
beforeEach(() => {
|
||||
mockTokenService = { generateTokenPair: vi.fn().mockResolvedValue(tokenPair) };
|
||||
mockChallengeRepo = { create: vi.fn().mockResolvedValue({}) };
|
||||
handler = new LoginUserHandler(mockTokenService as any, mockChallengeRepo as any);
|
||||
mockUserRepo = { updateMfaGraceStartedAt: vi.fn().mockResolvedValue(undefined) };
|
||||
mockLogger = { error: vi.fn(), warn: vi.fn() };
|
||||
handler = new LoginUserHandler(
|
||||
mockTokenService as any,
|
||||
mockChallengeRepo as any,
|
||||
mockUserRepo as any,
|
||||
mockLogger as any,
|
||||
);
|
||||
});
|
||||
|
||||
it('generates token pair with correct payload when MFA not required', async () => {
|
||||
it('generates token pair with mfa=none for non-required role when MFA not required', async () => {
|
||||
const command = new LoginUserCommand('user-1', '0912345678', 'BUYER', false);
|
||||
const result = await handler.execute(command);
|
||||
|
||||
expect(result).toEqual({ requiresMfa: false, tokens: tokenPair });
|
||||
expect(result).toEqual({ requiresMfa: false, tokens: tokenPair, mfaGraceRemainingDays: undefined });
|
||||
expect(mockTokenService.generateTokenPair).toHaveBeenCalledWith({
|
||||
sub: 'user-1',
|
||||
phone: '0912345678',
|
||||
role: 'BUYER',
|
||||
mfa: 'none',
|
||||
});
|
||||
});
|
||||
|
||||
it('creates MFA challenge when MFA is required', async () => {
|
||||
it('creates MFA challenge when MFA is required (user already enrolled)', async () => {
|
||||
const command = new LoginUserCommand('user-1', '0912345678', 'BUYER', true);
|
||||
const result = await handler.execute(command);
|
||||
|
||||
@@ -49,7 +59,7 @@ describe('LoginUserHandler', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('passes AGENT role correctly', async () => {
|
||||
it('AGENT role does not require MFA — issues mfa=none claim', async () => {
|
||||
const command = new LoginUserCommand('user-2', '0987654321', 'AGENT');
|
||||
await handler.execute(command);
|
||||
|
||||
@@ -57,17 +67,51 @@ describe('LoginUserHandler', () => {
|
||||
sub: 'user-2',
|
||||
phone: '0987654321',
|
||||
role: 'AGENT',
|
||||
mfa: 'none',
|
||||
});
|
||||
});
|
||||
|
||||
it('passes ADMIN role correctly', async () => {
|
||||
const command = new LoginUserCommand('admin-1', '0901234567', 'ADMIN');
|
||||
await handler.execute(command);
|
||||
it('ADMIN without TOTP enters grace period on first login under enforcement', async () => {
|
||||
const command = new LoginUserCommand(
|
||||
'admin-1',
|
||||
'0901234567',
|
||||
'ADMIN',
|
||||
false,
|
||||
false, // totpEnabled
|
||||
null, // mfaGraceStartedAt — first login
|
||||
);
|
||||
const result = await handler.execute(command);
|
||||
|
||||
// Grace was started lazily
|
||||
expect(mockUserRepo.updateMfaGraceStartedAt).toHaveBeenCalledWith('admin-1', expect.any(Date));
|
||||
expect(result.mfaGraceRemainingDays).toBe(14);
|
||||
expect(mockTokenService.generateTokenPair).toHaveBeenCalledWith({
|
||||
sub: 'admin-1',
|
||||
phone: '0901234567',
|
||||
role: 'ADMIN',
|
||||
mfa: 'grace',
|
||||
});
|
||||
});
|
||||
|
||||
it('ADMIN past grace window receives mfa=enrollment_required claim', async () => {
|
||||
const longAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000); // 30 days ago
|
||||
const command = new LoginUserCommand(
|
||||
'admin-1',
|
||||
'0901234567',
|
||||
'ADMIN',
|
||||
false,
|
||||
false,
|
||||
longAgo,
|
||||
);
|
||||
const result = await handler.execute(command);
|
||||
|
||||
expect(mockUserRepo.updateMfaGraceStartedAt).not.toHaveBeenCalled();
|
||||
expect(result.mfaGraceRemainingDays).toBe(0);
|
||||
expect(mockTokenService.generateTokenPair).toHaveBeenCalledWith({
|
||||
sub: 'admin-1',
|
||||
phone: '0901234567',
|
||||
role: 'ADMIN',
|
||||
mfa: 'enrollment_required',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,5 +4,7 @@ export class LoginUserCommand {
|
||||
public readonly phone: string,
|
||||
public readonly role: string,
|
||||
public readonly isMfaRequired: boolean = false,
|
||||
public readonly totpEnabled: boolean = false,
|
||||
public readonly mfaGraceStartedAt: Date | null = null,
|
||||
) {}
|
||||
}
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
import { Inject, InternalServerErrorException } from '@nestjs/common';
|
||||
import { CommandHandler, type ICommandHandler } from '@nestjs/cqrs';
|
||||
import { type UserRole } from '@prisma/client';
|
||||
import { createId } from '@paralleldrive/cuid2';
|
||||
import { LoggerService, DomainException } from '@modules/shared';
|
||||
import { MFA_GRACE_PERIOD_DAYS, MFA_REQUIRED_ROLES } from '../../../domain/mfa-policy';
|
||||
import {
|
||||
MFA_CHALLENGE_REPOSITORY,
|
||||
type IMfaChallengeRepository,
|
||||
} from '../../../domain/repositories/mfa-challenge.repository';
|
||||
import { TokenService, type TokenPair } from '../../../infrastructure/services/token.service';
|
||||
import {
|
||||
USER_REPOSITORY,
|
||||
type IUserRepository,
|
||||
} from '../../../domain/repositories/user.repository';
|
||||
import { TokenService, type MfaClaim, type TokenPair } from '../../../infrastructure/services/token.service';
|
||||
import { LoginUserCommand } from './login-user.command';
|
||||
|
||||
const MFA_CHALLENGE_TTL_MINUTES = 5;
|
||||
@@ -15,6 +21,7 @@ export interface LoginResult {
|
||||
requiresMfa: boolean;
|
||||
challengeId?: string;
|
||||
tokens?: TokenPair;
|
||||
mfaGraceRemainingDays?: number;
|
||||
}
|
||||
|
||||
@CommandHandler(LoginUserCommand)
|
||||
@@ -23,12 +30,14 @@ export class LoginUserHandler implements ICommandHandler<LoginUserCommand> {
|
||||
private readonly tokenService: TokenService,
|
||||
@Inject(MFA_CHALLENGE_REPOSITORY)
|
||||
private readonly challengeRepo: IMfaChallengeRepository,
|
||||
@Inject(USER_REPOSITORY)
|
||||
private readonly userRepo: IUserRepository,
|
||||
private readonly logger: LoggerService,
|
||||
) {}
|
||||
|
||||
async execute(command: LoginUserCommand): Promise<LoginResult> {
|
||||
try {
|
||||
// If MFA is required, create a challenge instead of tokens
|
||||
// If MFA is required (user already enrolled), create a challenge
|
||||
if (command.isMfaRequired) {
|
||||
const challengeId = createId();
|
||||
const expiresAt = new Date();
|
||||
@@ -50,16 +59,32 @@ export class LoginUserHandler implements ICommandHandler<LoginUserCommand> {
|
||||
};
|
||||
}
|
||||
|
||||
// No MFA — issue tokens directly
|
||||
// Determine MFA claim for non-enrolled users
|
||||
const roleRequiresMfa = MFA_REQUIRED_ROLES.includes(command.role as UserRole);
|
||||
|
||||
let mfaClaim: MfaClaim = 'none';
|
||||
let mfaGraceRemainingDays: number | undefined;
|
||||
|
||||
if (roleRequiresMfa && !command.totpEnabled) {
|
||||
const result = await this.resolveMfaGraceClaim(
|
||||
command.userId,
|
||||
command.mfaGraceStartedAt,
|
||||
);
|
||||
mfaClaim = result.claim;
|
||||
mfaGraceRemainingDays = result.remainingDays;
|
||||
}
|
||||
|
||||
const tokens = await this.tokenService.generateTokenPair({
|
||||
sub: command.userId,
|
||||
phone: command.phone,
|
||||
role: command.role,
|
||||
mfa: mfaClaim,
|
||||
});
|
||||
|
||||
return {
|
||||
requiresMfa: false,
|
||||
tokens,
|
||||
mfaGraceRemainingDays,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof DomainException) throw error;
|
||||
@@ -71,5 +96,33 @@ export class LoginUserHandler implements ICommandHandler<LoginUserCommand> {
|
||||
throw new InternalServerErrorException('Không thể tạo phiên đăng nhập, vui lòng thử lại');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazy-initialises mfaGraceStartedAt if the role requires MFA but
|
||||
* the user hasn't enrolled yet. Returns the appropriate MFA claim
|
||||
* and the number of grace days remaining (if any).
|
||||
*/
|
||||
private async resolveMfaGraceClaim(
|
||||
userId: string,
|
||||
mfaGraceStartedAt: Date | null,
|
||||
): Promise<{ claim: MfaClaim; remainingDays?: number }> {
|
||||
const now = new Date();
|
||||
|
||||
if (!mfaGraceStartedAt) {
|
||||
// First login since enforcement — start the grace period
|
||||
await this.userRepo.updateMfaGraceStartedAt(userId, now);
|
||||
return { claim: 'grace', remainingDays: MFA_GRACE_PERIOD_DAYS };
|
||||
}
|
||||
|
||||
const elapsedMs = now.getTime() - mfaGraceStartedAt.getTime();
|
||||
const elapsedDays = elapsedMs / (1000 * 60 * 60 * 24);
|
||||
const remainingDays = Math.max(0, Math.ceil(MFA_GRACE_PERIOD_DAYS - elapsedDays));
|
||||
|
||||
if (remainingDays > 0) {
|
||||
return { claim: 'grace', remainingDays };
|
||||
}
|
||||
|
||||
// Grace period expired — enrollment is now mandatory
|
||||
return { claim: 'enrollment_required', remainingDays: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,6 +22,8 @@ export interface UserProps {
|
||||
totpEnabled: boolean;
|
||||
totpBackupCodes: string[];
|
||||
totpEnabledAt: Date | null;
|
||||
mfaGraceStartedAt: Date | null;
|
||||
mfaLastVerifiedAt: Date | null;
|
||||
}
|
||||
|
||||
export class UserEntity extends AggregateRoot<string> {
|
||||
@@ -39,6 +41,8 @@ export class UserEntity extends AggregateRoot<string> {
|
||||
private _totpEnabled: boolean;
|
||||
private _totpBackupCodes: string[];
|
||||
private _totpEnabledAt: Date | null;
|
||||
private _mfaGraceStartedAt: Date | null;
|
||||
private _mfaLastVerifiedAt: Date | null;
|
||||
|
||||
constructor(id: string, props: UserProps, createdAt?: Date, updatedAt?: Date) {
|
||||
super(id, createdAt, updatedAt);
|
||||
@@ -56,6 +60,8 @@ export class UserEntity extends AggregateRoot<string> {
|
||||
this._totpEnabled = props.totpEnabled;
|
||||
this._totpBackupCodes = props.totpBackupCodes;
|
||||
this._totpEnabledAt = props.totpEnabledAt;
|
||||
this._mfaGraceStartedAt = props.mfaGraceStartedAt;
|
||||
this._mfaLastVerifiedAt = props.mfaLastVerifiedAt;
|
||||
}
|
||||
|
||||
get email(): Email | null { return this._email; }
|
||||
@@ -72,6 +78,8 @@ export class UserEntity extends AggregateRoot<string> {
|
||||
get totpEnabled(): boolean { return this._totpEnabled; }
|
||||
get totpBackupCodes(): string[] { return this._totpBackupCodes; }
|
||||
get totpEnabledAt(): Date | null { return this._totpEnabledAt; }
|
||||
get mfaGraceStartedAt(): Date | null { return this._mfaGraceStartedAt; }
|
||||
get mfaLastVerifiedAt(): Date | null { return this._mfaLastVerifiedAt; }
|
||||
|
||||
static createNew(
|
||||
id: string,
|
||||
@@ -96,6 +104,8 @@ export class UserEntity extends AggregateRoot<string> {
|
||||
totpEnabled: false,
|
||||
totpBackupCodes: [],
|
||||
totpEnabledAt: null,
|
||||
mfaGraceStartedAt: null,
|
||||
mfaLastVerifiedAt: null,
|
||||
});
|
||||
|
||||
user.addDomainEvent(new UserRegisteredEvent(id, phone.value, role));
|
||||
@@ -133,6 +143,8 @@ export class UserEntity extends AggregateRoot<string> {
|
||||
totpEnabled: false,
|
||||
totpBackupCodes: [],
|
||||
totpEnabledAt: null,
|
||||
mfaGraceStartedAt: null,
|
||||
mfaLastVerifiedAt: null,
|
||||
});
|
||||
|
||||
user.addDomainEvent(new UserRegisteredEvent(id, phone.value, role));
|
||||
|
||||
28
apps/api/src/modules/auth/domain/mfa-policy.ts
Normal file
28
apps/api/src/modules/auth/domain/mfa-policy.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import { UserRole } from '@prisma/client';
|
||||
|
||||
/**
|
||||
* MFA enrolment policy — central source of truth for which roles require
|
||||
* TOTP and how long the grace period lasts.
|
||||
*
|
||||
* Backed by `User.mfaGraceStartedAt` and `User.mfaLastVerifiedAt` columns.
|
||||
*
|
||||
* Policy summary:
|
||||
* - On first login under enforcement, `mfaGraceStartedAt` is stamped.
|
||||
* - For `MFA_GRACE_PERIOD_DAYS` after that timestamp, the user keeps full
|
||||
* access but receives `mfa: 'grace'` in their JWT (UI nudges enrollment).
|
||||
* - After grace expires, the JWT carries `mfa: 'enrollment_required'` and
|
||||
* sensitive routes (admin guards) reject until the user enrols.
|
||||
*/
|
||||
|
||||
/** Roles for which TOTP is mandatory after the grace window expires. */
|
||||
export const MFA_REQUIRED_ROLES: ReadonlyArray<UserRole> = ['ADMIN'];
|
||||
|
||||
/** Length of the grace window before MFA enrolment becomes mandatory. */
|
||||
export const MFA_GRACE_PERIOD_DAYS = 14;
|
||||
|
||||
/**
|
||||
* Re-auth window for "step-up" admin operations (e.g. user impersonation,
|
||||
* mass actions). After this many minutes since `mfaLastVerifiedAt`, the
|
||||
* admin re-auth interceptor must challenge again.
|
||||
*/
|
||||
export const MFA_REAUTH_WINDOW_MINUTES = 15;
|
||||
@@ -12,4 +12,6 @@ export interface IUserRepository {
|
||||
updateMfaEnabled(userId: string, enabled: boolean, secret: string, backupCodes: string[]): Promise<void>;
|
||||
updateMfaDisabled(userId: string): Promise<void>;
|
||||
updateBackupCodes(userId: string, backupCodes: string[]): Promise<void>;
|
||||
updateMfaGraceStartedAt(userId: string, date: Date): Promise<void>;
|
||||
updateMfaLastVerifiedAt(userId: string, date: Date): Promise<void>;
|
||||
}
|
||||
|
||||
@@ -160,6 +160,8 @@ describe('LocalStrategy', () => {
|
||||
phone: '+84912345678',
|
||||
role: 'BUYER',
|
||||
isMfaRequired: false,
|
||||
totpEnabled: false,
|
||||
mfaGraceStartedAt: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -123,6 +123,14 @@ export class PrismaUserRepository implements IUserRepository {
|
||||
});
|
||||
}
|
||||
|
||||
async updateMfaGraceStartedAt(userId: string, date: Date): Promise<void> {
|
||||
await this.prisma.user.update({ where: { id: userId }, data: { mfaGraceStartedAt: date } });
|
||||
}
|
||||
|
||||
async updateMfaLastVerifiedAt(userId: string, date: Date): Promise<void> {
|
||||
await this.prisma.user.update({ where: { id: userId }, data: { mfaLastVerifiedAt: date } });
|
||||
}
|
||||
|
||||
private toDomain(raw: PrismaUser): UserEntity {
|
||||
const phone = Phone.create(raw.phone).unwrap();
|
||||
const email = raw.email ? Email.create(raw.email).unwrap() : null;
|
||||
@@ -145,6 +153,8 @@ export class PrismaUserRepository implements IUserRepository {
|
||||
totpEnabled: raw.totpEnabled,
|
||||
totpBackupCodes: raw.totpBackupCodes,
|
||||
totpEnabledAt: raw.totpEnabledAt,
|
||||
mfaGraceStartedAt: raw.mfaGraceStartedAt,
|
||||
mfaLastVerifiedAt: raw.mfaLastVerifiedAt,
|
||||
};
|
||||
|
||||
return new UserEntity(raw.id, props, raw.createdAt, raw.updatedAt);
|
||||
|
||||
@@ -121,10 +121,13 @@ export class OAuthService {
|
||||
kycStatus: 'NONE',
|
||||
kycData: null,
|
||||
isActive: true,
|
||||
deletedAt: null,
|
||||
totpSecret: null,
|
||||
totpEnabled: false,
|
||||
totpBackupCodes: [],
|
||||
totpEnabledAt: null,
|
||||
mfaGraceStartedAt: null,
|
||||
mfaLastVerifiedAt: null,
|
||||
});
|
||||
|
||||
await this.userRepo.save(user);
|
||||
|
||||
@@ -7,10 +7,23 @@ import {
|
||||
} from '../../domain/repositories/refresh-token.repository';
|
||||
import { verifyWithRotation } from '../utils/jwt-rotation';
|
||||
|
||||
/**
|
||||
* MFA enrolment status carried inside the access-token JWT.
|
||||
*
|
||||
* - `none` — role does not require MFA, or user is enrolled and
|
||||
* has just verified (`requiresMfa === true` flow).
|
||||
* - `grace` — role requires MFA but the user is inside the
|
||||
* enforcement grace window. UI nudges enrollment.
|
||||
* - `enrollment_required`— grace window has expired; backend guards on
|
||||
* sensitive routes must reject and force enrollment.
|
||||
*/
|
||||
export type MfaClaim = 'none' | 'grace' | 'enrollment_required';
|
||||
|
||||
export interface JwtPayload {
|
||||
sub: string;
|
||||
phone: string;
|
||||
role: string;
|
||||
mfa?: MfaClaim;
|
||||
}
|
||||
|
||||
export interface TokenPair {
|
||||
|
||||
@@ -9,6 +9,8 @@ export interface LocalStrategyResult {
|
||||
phone: string;
|
||||
role: string;
|
||||
isMfaRequired: boolean;
|
||||
totpEnabled: boolean;
|
||||
mfaGraceStartedAt: Date | null;
|
||||
}
|
||||
|
||||
@Injectable()
|
||||
@@ -56,6 +58,8 @@ export class LocalStrategy extends PassportStrategy(Strategy) {
|
||||
phone: user.phone.value,
|
||||
role: user.role,
|
||||
isMfaRequired: user.totpEnabled,
|
||||
totpEnabled: user.totpEnabled,
|
||||
mfaGraceStartedAt: user.mfaGraceStartedAt,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error instanceof DomainException) throw error;
|
||||
|
||||
Reference in New Issue
Block a user