fix(payments): harden payment flow with idempotency keys, amount validation, and magic byte file validation

- Add dedicated idempotencyKey column with unique constraint (userId, provider, idempotencyKey) to prevent duplicate payments at DB level
- Add @Min(1) @Max(100B) validators on amountVND in CreatePaymentDto to reject invalid amounts at API boundary
- Replace read-check-write callback handler with atomic updateIfStatus to eliminate race condition on concurrent callbacks
- Add magic byte verification in FileValidationPipe to validate file content matches declared MIME type server-side

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Ho Ngoc Hai
2026-04-08 06:18:26 +07:00
parent be0deddeed
commit 9583d1cb66
9 changed files with 148 additions and 43 deletions

View File

@@ -48,50 +48,59 @@ export class HandleCallbackHandler implements ICommandHandler<HandleCallbackComm
});
}
// Find payment by orderId (which is the payment ID)
const payment = await this.paymentRepo.findById(result.orderId);
if (!payment) {
this.logger.warn(`Payment not found for orderId=${result.orderId}`);
throw new NotFoundException({
code: ErrorCode.NOT_FOUND,
message: 'Không tìm thấy thanh toán',
});
}
// Atomically transition payment status to prevent race conditions
// on concurrent callbacks. Only PENDING/PROCESSING payments can be updated.
const targetStatus = result.isSuccess ? 'COMPLETED' : 'FAILED';
const updated = await this.paymentRepo.updateIfStatus(
result.orderId,
['PENDING', 'PROCESSING'],
{
status: targetStatus as any,
callbackData: result.rawData,
},
);
// Idempotency: if already completed/failed, return current state
if (payment.status === 'COMPLETED' || payment.status === 'FAILED' || payment.status === 'REFUNDED') {
if (!updated) {
// Either payment doesn't exist or is already in a terminal state
const existing = await this.paymentRepo.findById(result.orderId);
if (!existing) {
this.logger.warn(`Payment not found for orderId=${result.orderId}`);
throw new NotFoundException({
code: ErrorCode.NOT_FOUND,
message: 'Không tìm thấy thanh toán',
});
}
// Already processed — return idempotent response
this.logger.log(
`Payment ${payment.id} already in terminal state: ${payment.status}`,
`Payment ${existing.id} already in terminal state: ${existing.status}`,
);
return {
paymentId: payment.id,
status: payment.status,
isSuccess: payment.status === 'COMPLETED',
paymentId: existing.id,
status: existing.status,
isSuccess: existing.status === 'COMPLETED',
};
}
// Update payment status
// Reconstruct domain entity and publish events
if (result.isSuccess) {
payment.markCompleted(result.rawData);
updated.emitCompleted();
} else {
payment.markFailed(result.rawData);
updated.emitFailed();
}
await this.paymentRepo.update(payment);
// Publish domain events
const events = payment.clearDomainEvents();
const events = updated.clearDomainEvents();
for (const event of events) {
this.eventBus.publish(event);
}
this.logger.log(
`Payment ${payment.id} callback processed: status=${payment.status}`,
`Payment ${updated.id} callback processed: status=${updated.status}`,
);
return {
paymentId: payment.id,
status: payment.status,
paymentId: updated.id,
status: updated.status,
isSuccess: result.isSuccess,
};
}

View File

@@ -115,6 +115,20 @@ export class PaymentEntity extends AggregateRoot<string> {
);
}
/** Emit completed event without modifying state (used when DB was already updated atomically). */
emitCompleted(): void {
this.addDomainEvent(
new PaymentCompletedEvent(this.id, this._userId, this._provider, this._amount.value),
);
}
/** Emit failed event without modifying state (used when DB was already updated atomically). */
emitFailed(): void {
this.addDomainEvent(
new PaymentFailedEvent(this.id, this._userId, this._provider),
);
}
markRefunded(): void {
if (this._status !== 'COMPLETED') {
throw new Error('Chỉ có thể hoàn tiền cho thanh toán đã hoàn tất');

View File

@@ -14,4 +14,6 @@ export interface IPaymentRepository {
}): Promise<{ items: PaymentEntity[]; total: number }>;
save(payment: PaymentEntity): Promise<void>;
update(payment: PaymentEntity): Promise<void>;
/** Atomically update payment status only if it is currently in one of the expected statuses. Returns null if no matching row. */
updateIfStatus(id: string, expectedStatuses: PaymentStatus[], data: { status: PaymentStatus; providerTxId?: string; callbackData?: unknown }): Promise<PaymentEntity | null>;
}

View File

@@ -1,6 +1,6 @@
import { Injectable } from '@nestjs/common';
import { PrismaService } from '@modules/shared/infrastructure/prisma.service';
import { type Payment as PrismaPayment, type PaymentStatus } from '@prisma/client';
import { Prisma, type Payment as PrismaPayment, type PaymentStatus } from '@prisma/client';
import { type IPaymentRepository } from '../../domain/repositories/payment.repository';
import { PaymentEntity, type PaymentProps } from '../../domain/entities/payment.entity';
import { Money } from '../../domain/value-objects/money.vo';
@@ -23,12 +23,7 @@ export class PrismaPaymentRepository implements IPaymentRepository {
async findByIdempotencyKey(key: string): Promise<PaymentEntity | null> {
const payment = await this.prisma.payment.findFirst({
where: {
callbackData: {
path: ['idempotencyKey'],
equals: key,
},
},
where: { idempotencyKey: key },
});
return payment ? this.toDomain(payment) : null;
}
@@ -70,6 +65,7 @@ export class PrismaPaymentRepository implements IPaymentRepository {
status: entity.status,
providerTxId: entity.providerTxId,
callbackData: entity.callbackData as any,
idempotencyKey: entity.idempotencyKey,
},
});
}
@@ -85,6 +81,33 @@ export class PrismaPaymentRepository implements IPaymentRepository {
});
}
async updateIfStatus(
id: string,
expectedStatuses: PaymentStatus[],
data: { status: PaymentStatus; providerTxId?: string; callbackData?: unknown },
): Promise<PaymentEntity | null> {
try {
const updated = await this.prisma.payment.update({
where: {
id,
status: { in: expectedStatuses },
},
data: {
status: data.status,
...(data.providerTxId !== undefined ? { providerTxId: data.providerTxId } : {}),
...(data.callbackData !== undefined ? { callbackData: data.callbackData as any } : {}),
},
});
return this.toDomain(updated);
} catch (error) {
// P2025: Record not found (status didn't match or ID doesn't exist)
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2025') {
return null;
}
throw error;
}
}
private toDomain(raw: PrismaPayment): PaymentEntity {
const amount = Money.create(raw.amountVND).unwrap();
@@ -97,7 +120,7 @@ export class PrismaPaymentRepository implements IPaymentRepository {
status: raw.status,
providerTxId: raw.providerTxId,
callbackData: raw.callbackData,
idempotencyKey: (raw.callbackData as any)?.idempotencyKey ?? null,
idempotencyKey: raw.idempotencyKey ?? null,
};
return new PaymentEntity(raw.id, props, raw.createdAt, raw.updatedAt);

View File

@@ -62,7 +62,7 @@ export class PaymentsController {
user.sub,
dto.provider,
dto.type,
dto.amountVND,
BigInt(dto.amountVND),
dto.description,
dto.returnUrl,
ip || '127.0.0.1',

View File

@@ -1,9 +1,12 @@
import {
IsEnum,
IsNotEmpty,
IsNumber,
IsOptional,
IsString,
IsUrl,
Max,
Min,
MinLength,
} from 'class-validator';
import { Transform } from 'class-transformer';
@@ -19,10 +22,17 @@ export class CreatePaymentDto {
@IsEnum(PaymentType)
type!: PaymentType;
@ApiProperty({ type: Number, description: 'Amount in VND', example: 500000 })
@ApiProperty({ type: Number, description: 'Amount in VND (1 100,000,000,000)', example: 500000 })
@IsNotEmpty()
@Transform(({ value }) => BigInt(value))
amountVND!: bigint;
@IsNumber()
@Min(1, { message: 'Số tiền phải lớn hơn 0' })
@Max(100_000_000_000, { message: 'Số tiền vượt quá giới hạn cho phép (100 tỷ VND)' })
@Transform(({ value }) => {
const num = Number(value);
if (!Number.isFinite(num) || !Number.isInteger(num)) return value;
return num;
}, { toClassOnly: true })
amountVND!: number;
@ApiProperty({ description: 'Payment description', example: 'Listing fee' })
@IsString()