chore: update project documentation, audit reports, and initialize IDE configuration files
Some checks failed
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 29s
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 2m42s
Deploy / Build Web Image (push) Failing after 27s
Deploy / Build AI Services Image (push) Failing after 29s
E2E Tests / Playwright E2E (push) Failing after 43s
Deploy / Build API Image (push) Failing after 1m31s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 6s
Security Scanning / Trivy Scan — API Image (push) Failing after 5m35s
Security Scanning / Trivy Scan — AI Services Image (push) Failing after 3m45s
Deploy / Deploy to Staging (push) Has been skipped
Deploy / Smoke Test Staging (push) Has been skipped
Deploy / Deploy to Production (push) Has been skipped
Deploy / Smoke Test Production (push) Has been skipped
Deploy / Rollback Staging (push) Has been skipped
Deploy / Rollback Production (push) Has been skipped
Security Scanning / Trivy Scan — Web Image (push) Failing after 13m51s
Security Scanning / Trivy Filesystem Scan (push) Failing after 14m46s
Security Scanning / Security Gate (push) Has been cancelled
Some checks failed
CI / Lint → Typecheck → Test → Build (22) (push) Failing after 29s
CI / E2E Tests (push) Has been skipped
CodeQL Analysis / CodeQL (javascript-typescript) (push) Failing after 2m42s
Deploy / Build Web Image (push) Failing after 27s
Deploy / Build AI Services Image (push) Failing after 29s
E2E Tests / Playwright E2E (push) Failing after 43s
Deploy / Build API Image (push) Failing after 1m31s
Security Scanning / Dependency Audit (pnpm) (push) Failing after 6s
Security Scanning / Trivy Scan — API Image (push) Failing after 5m35s
Security Scanning / Trivy Scan — AI Services Image (push) Failing after 3m45s
Deploy / Deploy to Staging (push) Has been skipped
Deploy / Smoke Test Staging (push) Has been skipped
Deploy / Deploy to Production (push) Has been skipped
Deploy / Smoke Test Production (push) Has been skipped
Deploy / Rollback Staging (push) Has been skipped
Deploy / Rollback Production (push) Has been skipped
Security Scanning / Trivy Scan — Web Image (push) Failing after 13m51s
Security Scanning / Trivy Filesystem Scan (push) Failing after 14m46s
Security Scanning / Security Gate (push) Has been cancelled
This commit is contained in:
@@ -1,224 +1,223 @@
|
||||
# GoodGo Platform Payment Module - Security Review File Inventory
|
||||
# Kiểm Tra Bảo Mật Module Thanh Toán GoodGo Platform - Danh Sách File
|
||||
|
||||
## Overview
|
||||
Comprehensive file listing for the Order & Escrow entities security review in the payments module.
|
||||
Location: `/Users/velikho/Desktop/WORKING/goodgo-platform-ai/apps/api/src/modules/payments/`
|
||||
## Tổng Quan
|
||||
Danh sách file toàn diện cho đợt kiểm tra bảo mật các thực thể Order & Escrow trong module thanh toán.
|
||||
Vị trí: `/Users/velikho/Desktop/WORKING/goodgo-platform-ai/apps/api/src/modules/payments/`
|
||||
|
||||
---
|
||||
|
||||
## 1. DOMAIN LAYER - ENTITIES
|
||||
## 1. TẦNG DOMAIN - CÁC THỰC THỂ
|
||||
|
||||
### Core Entities
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `domain/entities/order.entity.ts` | **ORDER ENTITY** - Manages order lifecycle with state machine (CREATED→PAYMENT_PENDING→PAYMENT_CONFIRMED→ESCROW_HELD→SHIPPED→DELIVERED→ESCROW_RELEASED→COMPLETED). Validates transitions. Emits events: OrderCreatedEvent, OrderPaidEvent, OrderCancelledEvent. Critical fields: buyerId, sellerId, listingId, amount (Money VO), platformFee, sellerPayout. |
|
||||
| `domain/entities/escrow.entity.ts` | **ESCROW ENTITY** - Manages escrow lifecycle (PENDING→HELD→RELEASED/DISPUTED/REFUNDED). Stores escrow amount, fee, and calculated netPayout. Emits: EscrowHeldEvent, EscrowReleasedEvent, EscrowDisputedEvent. Validates state transitions. |
|
||||
| `domain/entities/payment.entity.ts` | **PAYMENT ENTITY** - Manages payment transactions (PENDING→PROCESSING→COMPLETED/FAILED/REFUNDED). Stores userId, provider (VNPAY/MOMO/ZALOPAY), type, amount, callbackData, idempotencyKey. Emits: PaymentCreatedEvent, PaymentCompletedEvent, PaymentFailedEvent, PaymentRefundedEvent. |
|
||||
### Các Thực Thể Cốt Lõi
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `domain/entities/order.entity.ts` | **THỰC THỂ ORDER** - Quản lý vòng đời đơn hàng với máy trạng thái (CREATED→PAYMENT_PENDING→PAYMENT_CONFIRMED→ESCROW_HELD→SHIPPED→DELIVERED→ESCROW_RELEASED→COMPLETED). Xác thực các chuyển trạng thái. Phát sự kiện: OrderCreatedEvent, OrderPaidEvent, OrderCancelledEvent. Các trường quan trọng: buyerId, sellerId, listingId, amount (Money VO), platformFee, sellerPayout. |
|
||||
| `domain/entities/escrow.entity.ts` | **THỰC THỂ ESCROW** - Quản lý vòng đời escrow (PENDING→HELD→RELEASED/DISPUTED/REFUNDED). Lưu trữ số tiền escrow, phí và netPayout đã tính. Phát: EscrowHeldEvent, EscrowReleasedEvent, EscrowDisputedEvent. Xác thực chuyển trạng thái. |
|
||||
| `domain/entities/payment.entity.ts` | **THỰC THỂ PAYMENT** - Quản lý giao dịch thanh toán (PENDING→PROCESSING→COMPLETED/FAILED/REFUNDED). Lưu trữ userId, provider (VNPAY/MOMO/ZALOPAY), type, amount, callbackData, idempotencyKey. Phát: PaymentCreatedEvent, PaymentCompletedEvent, PaymentFailedEvent, PaymentRefundedEvent. |
|
||||
|
||||
### Value Objects
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `domain/value-objects/money.vo.ts` | **MONEY VALUE OBJECT** - Wraps amounts as bigint in VND. Validates: amount > 0, max limit 999_999_999_999. Used for all financial amounts. |
|
||||
| `domain/value-objects/platform-fee.vo.ts` | **PLATFORM FEE VALUE OBJECT** - Calculates 5% platform fee. Methods: `fromOrderAmount()` (auto-calc 5%), `create()` (explicit amount). Validates fee >= 0. |
|
||||
### Các Value Object
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `domain/value-objects/money.vo.ts` | **VALUE OBJECT MONEY** - Bọc các số tiền dưới dạng bigint theo VND. Xác thực: amount > 0, giới hạn tối đa 999_999_999_999. Dùng cho tất cả các số tiền tài chính. |
|
||||
| `domain/value-objects/platform-fee.vo.ts` | **VALUE OBJECT PHÍ NỀN TẢNG** - Tính phí nền tảng 5%. Các phương thức: `fromOrderAmount()` (tự động tính 5%), `create()` (số tiền tường minh). Xác thực fee >= 0. |
|
||||
|
||||
---
|
||||
|
||||
## 2. DOMAIN LAYER - REPOSITORIES (Interfaces)
|
||||
## 2. TẦNG DOMAIN - REPOSITORY (Giao Diện)
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `domain/repositories/order.repository.ts` | **ORDER REPOSITORY INTERFACE** - Defines CRUD + query methods: findById, findByIdempotencyKey, findByBuyerId, findBySellerId, save, update. Idempotency protection. |
|
||||
| `domain/repositories/escrow.repository.ts` | **ESCROW REPOSITORY INTERFACE** - Defines: findById, findByOrderId, save, update. One escrow per order relationship. |
|
||||
| `domain/repositories/payment.repository.ts` | **PAYMENT REPOSITORY INTERFACE** - Defines: findById, findByProviderTxId, findByIdempotencyKey, findByUserId, save, update, **updateIfStatus** (atomic conditional update for race condition handling). |
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `domain/repositories/order.repository.ts` | **GIAO DIỆN ORDER REPOSITORY** - Định nghĩa các phương thức CRUD + truy vấn: findById, findByIdempotencyKey, findByBuyerId, findBySellerId, save, update. Bảo vệ idempotency. |
|
||||
| `domain/repositories/escrow.repository.ts` | **GIAO DIỆN ESCROW REPOSITORY** - Định nghĩa: findById, findByOrderId, save, update. Quan hệ một escrow trên một order. |
|
||||
| `domain/repositories/payment.repository.ts` | **GIAO DIỆN PAYMENT REPOSITORY** - Định nghĩa: findById, findByProviderTxId, findByIdempotencyKey, findByUserId, save, update, **updateIfStatus** (cập nhật có điều kiện nguyên tử để xử lý race condition). |
|
||||
|
||||
---
|
||||
|
||||
## 3. DOMAIN LAYER - EVENTS
|
||||
## 3. TẦNG DOMAIN - SỰ KIỆN
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `domain/events/order-created.event.ts` | Emitted when order created - contains orderId, buyerId, sellerId, listingId, amount |
|
||||
| `domain/events/order-paid.event.ts` | Emitted when payment confirmed - contains orderId, buyerId, amount |
|
||||
| `domain/events/order-cancelled.event.ts` | Emitted when order cancelled - contains orderId, buyerId, sellerId |
|
||||
| `domain/events/escrow-held.event.ts` | Emitted when escrow held - contains escrowId, orderId, amount |
|
||||
| `domain/events/escrow-released.event.ts` | Emitted when escrow released - contains escrowId, orderId, netPayout |
|
||||
| `domain/events/escrow-disputed.event.ts` | Emitted when escrow disputed - contains escrowId, orderId, reason |
|
||||
| `domain/events/payment-created.event.ts` | Emitted when payment created - contains paymentId, userId, provider, amount |
|
||||
| `domain/events/payment-completed.event.ts` | Emitted when payment completes - contains paymentId, userId, provider |
|
||||
| `domain/events/payment-failed.event.ts` | Emitted when payment fails - contains paymentId, userId, provider |
|
||||
| `domain/events/payment-refunded.event.ts` | Emitted when payment refunded - contains paymentId, userId, provider, amount |
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `domain/events/order-created.event.ts` | Phát khi tạo order - chứa orderId, buyerId, sellerId, listingId, amount |
|
||||
| `domain/events/order-paid.event.ts` | Phát khi thanh toán được xác nhận - chứa orderId, buyerId, amount |
|
||||
| `domain/events/order-cancelled.event.ts` | Phát khi order bị hủy - chứa orderId, buyerId, sellerId |
|
||||
| `domain/events/escrow-held.event.ts` | Phát khi escrow được giữ - chứa escrowId, orderId, amount |
|
||||
| `domain/events/escrow-released.event.ts` | Phát khi escrow được giải phóng - chứa escrowId, orderId, netPayout |
|
||||
| `domain/events/escrow-disputed.event.ts` | Phát khi escrow bị tranh chấp - chứa escrowId, orderId, reason |
|
||||
| `domain/events/payment-created.event.ts` | Phát khi tạo thanh toán - chứa paymentId, userId, provider, amount |
|
||||
| `domain/events/payment-completed.event.ts` | Phát khi thanh toán hoàn tất - chứa paymentId, userId, provider |
|
||||
| `domain/events/payment-failed.event.ts` | Phát khi thanh toán thất bại - chứa paymentId, userId, provider |
|
||||
| `domain/events/payment-refunded.event.ts` | Phát khi thanh toán được hoàn tiền - chứa paymentId, userId, provider, amount |
|
||||
|
||||
---
|
||||
|
||||
## 4. INFRASTRUCTURE LAYER - REPOSITORIES (Implementations)
|
||||
## 4. TẦNG CƠ SỞ HẠ TẦNG - REPOSITORY (Triển Khai)
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `infrastructure/repositories/prisma-order.repository.ts` | **ORDER REPOSITORY IMPL** - Prisma ORM implementation. Stores: id, buyerId, sellerId, listingId, status, amountVND, platformFeeVND, sellerPayoutVND, idempotencyKey, metadata. Handles order persistence. |
|
||||
| `infrastructure/repositories/prisma-escrow.repository.ts` | **ESCROW REPOSITORY IMPL** - Prisma ORM implementation. Stores: id, orderId, amountVND, feeVND, status, heldAt, releasedAt, disputeReason, disputedAt. Handles escrow persistence. |
|
||||
| `infrastructure/repositories/prisma-payment.repository.ts` | **PAYMENT REPOSITORY IMPL** - Prisma ORM. Stores: id, userId, transactionId, provider, type, amountVND, status, providerTxId, callbackData, idempotencyKey. **CRITICAL: `updateIfStatus()` uses conditional WHERE clause for atomic race condition prevention** (Line 84-109). |
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `infrastructure/repositories/prisma-order.repository.ts` | **TRIỂN KHAI ORDER REPOSITORY** - Triển khai Prisma ORM. Lưu trữ: id, buyerId, sellerId, listingId, status, amountVND, platformFeeVND, sellerPayoutVND, idempotencyKey, metadata. Xử lý lưu trữ order. |
|
||||
| `infrastructure/repositories/prisma-escrow.repository.ts` | **TRIỂN KHAI ESCROW REPOSITORY** - Triển khai Prisma ORM. Lưu trữ: id, orderId, amountVND, feeVND, status, heldAt, releasedAt, disputeReason, disputedAt. Xử lý lưu trữ escrow. |
|
||||
| `infrastructure/repositories/prisma-payment.repository.ts` | **TRIỂN KHAI PAYMENT REPOSITORY** - Prisma ORM. Lưu trữ: id, userId, transactionId, provider, type, amountVND, status, providerTxId, callbackData, idempotencyKey. **QUAN TRỌNG: `updateIfStatus()` sử dụng mệnh đề WHERE có điều kiện để ngăn race condition nguyên tử** (Dòng 84-109). |
|
||||
|
||||
---
|
||||
|
||||
## 5. INFRASTRUCTURE LAYER - PAYMENT GATEWAY SERVICES
|
||||
## 5. TẦNG CƠ SỞ HẠ TẦNG - DỊCH VỤ CỔNG THANH TOÁN
|
||||
|
||||
### Payment Gateway Interface
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `infrastructure/services/payment-gateway.interface.ts` | **GATEWAY INTERFACE** - Defines IPaymentGateway contract: createPaymentUrl(), verifyCallback(), refund(). CallbackVerifyResult includes: isValid, orderId, providerTxId, isSuccess, rawData. Sensitive for security. |
|
||||
### Giao Diện Cổng Thanh Toán
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `infrastructure/services/payment-gateway.interface.ts` | **GIAO DIỆN GATEWAY** - Định nghĩa hợp đồng IPaymentGateway: createPaymentUrl(), verifyCallback(), refund(). CallbackVerifyResult bao gồm: isValid, orderId, providerTxId, isSuccess, rawData. Nhạy cảm về bảo mật. |
|
||||
|
||||
### VNPay Service
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `infrastructure/services/vnpay.service.ts` | **VNPAY PAYMENT GATEWAY** - Implements IPaymentGateway. **CALLBACK VERIFICATION (Line 72-105)**: Extracts secure hash, removes it from data, sorts params, generates HMAC-SHA512, uses crypto.timingSafeEqual() for constant-time comparison. Amount multiplied by 100 for VND cents. Returns isValid, orderId (vnp_TxnRef), providerTxId (vnp_TransactionNo), isSuccess (responseCode === '00'). Refund support. |
|
||||
### Dịch Vụ VNPay
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `infrastructure/services/vnpay.service.ts` | **CỔNG THANH TOÁN VNPAY** - Triển khai IPaymentGateway. **XÁC MINH CALLBACK (Dòng 72-105)**: Trích xuất secure hash, loại bỏ khỏi dữ liệu, sắp xếp các tham số, tạo HMAC-SHA512, dùng crypto.timingSafeEqual() để so sánh thời gian cố định. Số tiền nhân 100 cho VND cents. Trả về isValid, orderId (vnp_TxnRef), providerTxId (vnp_TransactionNo), isSuccess (responseCode === '00'). Hỗ trợ hoàn tiền. |
|
||||
|
||||
### MoMo Service
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `infrastructure/services/momo.service.ts` | **MOMO PAYMENT GATEWAY** - Implements IPaymentGateway. **CALLBACK VERIFICATION (Line 102-147)**: Extracts signature from data, rebuilds raw signature with accessKey, amount, extraData, IPN/redirect URLs, orderId, etc. Uses HMAC-SHA256, constant-time comparison via crypto.timingSafeEqual(). Success check: resultCode === '0'. Refund support. Amount as Number (not bigint in API). |
|
||||
### Dịch Vụ MoMo
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `infrastructure/services/momo.service.ts` | **CỔNG THANH TOÁN MOMO** - Triển khai IPaymentGateway. **XÁC MINH CALLBACK (Dòng 102-147)**: Trích xuất chữ ký từ dữ liệu, xây dựng lại chữ ký thô với accessKey, amount, extraData, IPN/redirect URLs, orderId, v.v. Dùng HMAC-SHA256, so sánh thời gian cố định qua crypto.timingSafeEqual(). Kiểm tra thành công: resultCode === '0'. Hỗ trợ hoàn tiền. Amount dưới dạng Number (không phải bigint trong API). |
|
||||
|
||||
### ZaloPay Service
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `infrastructure/services/zalopay.service.ts` | **ZALOPAY PAYMENT GATEWAY** - Implements IPaymentGateway. **CALLBACK VERIFICATION (Line 98-144)**: Data passed as JSON string in 'data' field. MAC verified via HMAC-SHA256 with key2. Parses JSON data to extract app_trans_id and zp_trans_id. **SECURITY NOTE**: Catches JSON parse errors gracefully. Uses constant-time comparison. Refund support (key1). |
|
||||
### Dịch Vụ ZaloPay
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `infrastructure/services/zalopay.service.ts` | **CỔNG THANH TOÁN ZALOPAY** - Triển khai IPaymentGateway. **XÁC MINH CALLBACK (Dòng 98-144)**: Dữ liệu được truyền dưới dạng chuỗi JSON trong trường 'data'. MAC được xác minh qua HMAC-SHA256 với key2. Phân tích dữ liệu JSON để trích xuất app_trans_id và zp_trans_id. **LƯU Ý BẢO MẬT**: Xử lý lỗi phân tích JSON một cách duyên dáng. Dùng so sánh thời gian cố định. Hỗ trợ hoàn tiền (key1). |
|
||||
|
||||
### Payment Gateway Factory
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `infrastructure/services/payment-gateway.factory.ts` | **GATEWAY FACTORY** - Returns appropriate gateway instance (VNPay/MoMo/ZaloPay) based on provider enum. |
|
||||
### Factory Cổng Thanh Toán
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `infrastructure/services/payment-gateway.factory.ts` | **GATEWAY FACTORY** - Trả về instance gateway phù hợp (VNPay/MoMo/ZaloPay) dựa trên enum provider. |
|
||||
|
||||
---
|
||||
|
||||
## 6. APPLICATION LAYER - COMMANDS
|
||||
## 6. TẦNG ỨNG DỤNG - COMMAND
|
||||
|
||||
### Order Commands
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `application/commands/create-order/create-order.command.ts` | **CREATE ORDER COMMAND** - Input: buyerId, sellerId, listingId, amountVND, idempotencyKey. Payload object. |
|
||||
| `application/commands/create-order/create-order.handler.ts` | **CREATE ORDER HANDLER** - Idempotency check via findByIdempotencyKey. Validates amount (Money VO). Calculates platform fee (5%) and seller payout. Creates OrderEntity + EscrowEntity (PENDING status). Saves both. Emits events. |
|
||||
| `application/commands/cancel-order/cancel-order.command.ts` | **CANCEL ORDER COMMAND** - Input: orderId, userId, reason. |
|
||||
| `application/commands/cancel-order/cancel-order.handler.ts` | **CANCEL ORDER HANDLER** - Verifies user owns order, validates state transition via entity.markCancelled(), saves, emits events. |
|
||||
### Các Order Command
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `application/commands/create-order/create-order.command.ts` | **CREATE ORDER COMMAND** - Đầu vào: buyerId, sellerId, listingId, amountVND, idempotencyKey. Đối tượng payload. |
|
||||
| `application/commands/create-order/create-order.handler.ts` | **CREATE ORDER HANDLER** - Kiểm tra idempotency qua findByIdempotencyKey. Xác thực amount (Money VO). Tính phí nền tảng (5%) và seller payout. Tạo OrderEntity + EscrowEntity (trạng thái PENDING). Lưu cả hai. Phát sự kiện. |
|
||||
| `application/commands/cancel-order/cancel-order.command.ts` | **CANCEL ORDER COMMAND** - Đầu vào: orderId, userId, reason. |
|
||||
| `application/commands/cancel-order/cancel-order.handler.ts` | **CANCEL ORDER HANDLER** - Xác minh người dùng sở hữu order, xác thực chuyển trạng thái qua entity.markCancelled(), lưu, phát sự kiện. |
|
||||
|
||||
### Escrow Commands
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `application/commands/hold-escrow/hold-escrow.command.ts` | **HOLD ESCROW COMMAND** - Input: orderId. Admin-only operation. |
|
||||
| `application/commands/hold-escrow/hold-escrow.handler.ts` | **HOLD ESCROW HANDLER (Line 23-67)** - Fetches order + escrow by orderId. Calls escrow.hold() state transition. Updates both entities. Emits EscrowHeldEvent. **SECURITY NOTE**: No Redis lock - potential race condition if multiple concurrent requests. |
|
||||
| `application/commands/release-escrow/release-escrow.command.ts` | **RELEASE ESCROW COMMAND** - Input: orderId. Admin-only operation. |
|
||||
| `application/commands/release-escrow/release-escrow.handler.ts` | **RELEASE ESCROW HANDLER (Line 24-45)** - Fetches order + escrow by orderId. Calls escrow.release() state transition. Updates both entities. Emits EscrowReleasedEvent with netPayout. **SECURITY NOTE**: No Redis lock - potential race condition. |
|
||||
### Các Escrow Command
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `application/commands/hold-escrow/hold-escrow.command.ts` | **HOLD ESCROW COMMAND** - Đầu vào: orderId. Chỉ dành cho Admin. |
|
||||
| `application/commands/hold-escrow/hold-escrow.handler.ts` | **HOLD ESCROW HANDLER (Dòng 23-67)** - Lấy order + escrow theo orderId. Gọi escrow.hold() để chuyển trạng thái. Cập nhật cả hai thực thể. Phát EscrowHeldEvent. **LƯU Ý BẢO MẬT**: Không có Redis lock - tiềm ẩn race condition nếu có nhiều yêu cầu đồng thời. |
|
||||
| `application/commands/release-escrow/release-escrow.command.ts` | **RELEASE ESCROW COMMAND** - Đầu vào: orderId. Chỉ dành cho Admin. |
|
||||
| `application/commands/release-escrow/release-escrow.handler.ts` | **RELEASE ESCROW HANDLER (Dòng 24-45)** - Lấy order + escrow theo orderId. Gọi escrow.release() để chuyển trạng thái. Cập nhật cả hai thực thể. Phát EscrowReleasedEvent với netPayout. **LƯU Ý BẢO MẬT**: Không có Redis lock - tiềm ẩn race condition. |
|
||||
|
||||
### Payment Commands
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `application/commands/create-payment/create-payment.command.ts` | **CREATE PAYMENT COMMAND** - Input: userId, provider, type, amountVND, description, returnUrl, ipAddress, transactionId, idempotencyKey. |
|
||||
| `application/commands/create-payment/create-payment.handler.ts` | **CREATE PAYMENT HANDLER** - Idempotency check. Validates amount (Money VO). Gets payment gateway. Calls createPaymentUrl(). Creates PaymentEntity (PENDING status). Saves. Emits PaymentCreatedEvent. Returns paymentUrl for frontend redirect. |
|
||||
| `application/commands/refund-payment/refund-payment.command.ts` | **REFUND PAYMENT COMMAND** - Input: paymentId, reason, userId. Admin command. |
|
||||
| `application/commands/refund-payment/refund-payment.handler.ts` | **REFUND PAYMENT HANDLER** - Verifies payment exists, calls gateway.refund() with provider-specific args, updates payment status to REFUNDED, emits PaymentRefundedEvent. |
|
||||
### Các Payment Command
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `application/commands/create-payment/create-payment.command.ts` | **CREATE PAYMENT COMMAND** - Đầu vào: userId, provider, type, amountVND, description, returnUrl, ipAddress, transactionId, idempotencyKey. |
|
||||
| `application/commands/create-payment/create-payment.handler.ts` | **CREATE PAYMENT HANDLER** - Kiểm tra idempotency. Xác thực amount (Money VO). Lấy payment gateway. Gọi createPaymentUrl(). Tạo PaymentEntity (trạng thái PENDING). Lưu. Phát PaymentCreatedEvent. Trả về paymentUrl để frontend chuyển hướng. |
|
||||
| `application/commands/refund-payment/refund-payment.command.ts` | **REFUND PAYMENT COMMAND** - Đầu vào: paymentId, reason, userId. Lệnh dành cho Admin. |
|
||||
| `application/commands/refund-payment/refund-payment.handler.ts` | **REFUND PAYMENT HANDLER** - Xác minh thanh toán tồn tại, gọi gateway.refund() với các tham số đặc thù nhà cung cấp, cập nhật trạng thái thanh toán thành REFUNDED, phát PaymentRefundedEvent. |
|
||||
|
||||
### Callback Handler (CRITICAL)
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `application/commands/handle-callback/handle-callback.command.ts` | **HANDLE CALLBACK COMMAND** - Input: provider (PaymentProvider enum), callbackData (Record<string, string>). |
|
||||
| `application/commands/handle-callback/handle-callback.handler.ts` | **HANDLE CALLBACK HANDLER (Line 32-110)** - **CRITICAL SECURITY FILE**. Gets gateway, calls verifyCallback() (validates signature). If invalid: throws ValidationException. If valid: **Uses `paymentRepo.updateIfStatus()` with conditional WHERE ['PENDING', 'PROCESSING']** (Line 48-55) - atomic update to prevent duplicate processing. If update returns null: checks if payment exists (already processed - idempotent response). If success: calls payment.emitCompleted(), else payment.emitFailed(). Publishes events. **STRONG RACE CONDITION PROTECTION via conditional update**. |
|
||||
### Handler Callback (QUAN TRỌNG)
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `application/commands/handle-callback/handle-callback.command.ts` | **HANDLE CALLBACK COMMAND** - Đầu vào: provider (enum PaymentProvider), callbackData (Record<string, string>). |
|
||||
| `application/commands/handle-callback/handle-callback.handler.ts` | **HANDLE CALLBACK HANDLER (Dòng 32-110)** - **FILE BẢO MẬT QUAN TRỌNG**. Lấy gateway, gọi verifyCallback() (xác thực chữ ký). Nếu không hợp lệ: ném ValidationException. Nếu hợp lệ: **Dùng `paymentRepo.updateIfStatus()` với WHERE có điều kiện ['PENDING', 'PROCESSING']** (Dòng 48-55) - cập nhật nguyên tử để ngăn xử lý trùng lặp. Nếu cập nhật trả về null: kiểm tra xem thanh toán có tồn tại không (đã xử lý - phản hồi idempotent). Nếu thành công: gọi payment.emitCompleted(), ngược lại payment.emitFailed(). Phát sự kiện. **BẢO VỆ RACE CONDITION MẠNH qua cập nhật có điều kiện**. |
|
||||
|
||||
---
|
||||
|
||||
## 7. APPLICATION LAYER - QUERIES
|
||||
## 7. TẦNG ỨNG DỤNG - QUERY
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `application/queries/get-order-status/get-order-status.query.ts` | Query: Input orderId, userId (for authorization). |
|
||||
| `application/queries/get-order-status/get-order-status.handler.ts` | Fetches order, verifies ownership (buyer/seller), returns status + details. |
|
||||
| `application/queries/get-payment-status/get-payment-status.query.ts` | Query: Input paymentId, userId. |
|
||||
| `application/queries/get-payment-status/get-payment-status.handler.ts` | Fetches payment, verifies ownership, returns status + details. |
|
||||
| `application/queries/list-transactions/list-transactions.query.ts` | Query: Input userId, status (optional), limit, offset. |
|
||||
| `application/queries/list-transactions/list-transactions.handler.ts` | Lists payments for user with pagination, filters by status if provided. |
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `application/queries/get-order-status/get-order-status.query.ts` | Query: Đầu vào orderId, userId (để phân quyền). |
|
||||
| `application/queries/get-order-status/get-order-status.handler.ts` | Lấy order, xác minh quyền sở hữu (buyer/seller), trả về trạng thái + chi tiết. |
|
||||
| `application/queries/get-payment-status/get-payment-status.query.ts` | Query: Đầu vào paymentId, userId. |
|
||||
| `application/queries/get-payment-status/get-payment-status.handler.ts` | Lấy thanh toán, xác minh quyền sở hữu, trả về trạng thái + chi tiết. |
|
||||
| `application/queries/list-transactions/list-transactions.query.ts` | Query: Đầu vào userId, status (tùy chọn), limit, offset. |
|
||||
| `application/queries/list-transactions/list-transactions.handler.ts` | Liệt kê các thanh toán của người dùng với phân trang, lọc theo status nếu được cung cấp. |
|
||||
|
||||
---
|
||||
|
||||
## 8. PRESENTATION LAYER - CONTROLLERS
|
||||
## 8. TẦNG TRÌNH BÀY - CONTROLLER
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `presentation/controllers/orders.controller.ts` | **ORDERS CONTROLLER** - Routes: POST / (create order), GET /:id (status), POST /:id/cancel (cancel), POST /:id/escrow/hold (admin), POST /:id/escrow/release (admin). Auth: JwtAuthGuard, RolesGuard for admin ops. Converts DTO to commands. |
|
||||
| `presentation/controllers/payments.controller.ts` | **PAYMENTS CONTROLLER** - Routes: POST / (create payment), POST /callback/:provider (webhook - **Throttle + EndpointRateLimit**), GET /:id (status), GET (list), POST /:id/refund (admin refund). **CRITICAL: Callback endpoint has rate limiting (Throttle + EndpointRateLimitGuard)** - prevents callback flooding. |
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `presentation/controllers/orders.controller.ts` | **ORDERS CONTROLLER** - Các route: POST / (tạo order), GET /:id (trạng thái), POST /:id/cancel (hủy), POST /:id/escrow/hold (admin), POST /:id/escrow/release (admin). Xác thực: JwtAuthGuard, RolesGuard cho các thao tác admin. Chuyển đổi DTO thành command. |
|
||||
| `presentation/controllers/payments.controller.ts` | **PAYMENTS CONTROLLER** - Các route: POST / (tạo thanh toán), POST /callback/:provider (webhook - **Throttle + EndpointRateLimit**), GET /:id (trạng thái), GET (danh sách), POST /:id/refund (admin hoàn tiền). **QUAN TRỌNG: Endpoint callback có giới hạn tốc độ (Throttle + EndpointRateLimitGuard)** - ngăn chặn lũ lụt callback. |
|
||||
|
||||
---
|
||||
|
||||
## 9. PRESENTATION LAYER - DTOs
|
||||
## 9. TẦNG TRÌNH BÀY - DTO
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `presentation/dto/create-order.dto.ts` | DTO: sellerId, listingId, amountVND (string), idempotencyKey (optional). |
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `presentation/dto/create-order.dto.ts` | DTO: sellerId, listingId, amountVND (string), idempotencyKey (tùy chọn). |
|
||||
| `presentation/dto/cancel-order.dto.ts` | DTO: reason (string). |
|
||||
| `presentation/dto/create-payment.dto.ts` | DTO: provider (enum), type (enum), amountVND (string), description, returnUrl, transactionId (optional), idempotencyKey (optional). |
|
||||
| `presentation/dto/create-payment.dto.ts` | DTO: provider (enum), type (enum), amountVND (string), description, returnUrl, transactionId (tùy chọn), idempotencyKey (tùy chọn). |
|
||||
| `presentation/dto/refund-payment.dto.ts` | DTO: reason (string). |
|
||||
| `presentation/dto/list-transactions.dto.ts` | DTO: status (optional), limit, offset. |
|
||||
| `presentation/dto/list-transactions.dto.ts` | DTO: status (tùy chọn), limit, offset. |
|
||||
|
||||
---
|
||||
|
||||
## 10. MODULE & TEST FILES
|
||||
## 10. MODULE & CÁC FILE KIỂM THỬ
|
||||
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `payments.module.ts` | **MODULE SETUP** - Registers repositories, services, handlers, controllers. |
|
||||
| `index.ts` (module level) | Exports public API. |
|
||||
| `infrastructure/repositories/index.ts` | Exports repository implementations. |
|
||||
| `infrastructure/services/index.ts` | Exports gateway services. |
|
||||
| `application/index.ts` | Exports command/query handlers. |
|
||||
| `domain/repositories/index.ts` | Exports repository interfaces. |
|
||||
| `domain/entities/index.ts` | Exports entities. |
|
||||
| `domain/value-objects/index.ts` | Exports VOs. |
|
||||
| `domain/events/index.ts` | Exports domain events. |
|
||||
| `presentation/controllers/index.ts` | Exports controllers. |
|
||||
| `presentation/dto/index.ts` | Exports DTOs. |
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `payments.module.ts` | **CÀI ĐẶT MODULE** - Đăng ký các repository, service, handler, controller. |
|
||||
| `index.ts` (cấp module) | Xuất API công khai. |
|
||||
| `infrastructure/repositories/index.ts` | Xuất các triển khai repository. |
|
||||
| `infrastructure/services/index.ts` | Xuất các dịch vụ gateway. |
|
||||
| `application/index.ts` | Xuất các handler command/query. |
|
||||
| `domain/repositories/index.ts` | Xuất các giao diện repository. |
|
||||
| `domain/entities/index.ts` | Xuất các thực thể. |
|
||||
| `domain/value-objects/index.ts` | Xuất các VO. |
|
||||
| `domain/events/index.ts` | Xuất các sự kiện domain. |
|
||||
| `presentation/controllers/index.ts` | Xuất các controller. |
|
||||
| `presentation/dto/index.ts` | Xuất các DTO. |
|
||||
|
||||
### Test Files
|
||||
| File | Description |
|
||||
|------|-------------|
|
||||
| `domain/__tests__/order.entity.spec.ts` | Order entity unit tests - state machine, transitions |
|
||||
| `domain/__tests__/escrow.entity.spec.ts` | Escrow entity unit tests - hold, release, dispute, refund |
|
||||
| `domain/__tests__/payment.entity.spec.ts` | Payment entity unit tests |
|
||||
| `domain/__tests__/money.vo.spec.ts` | Money VO validation tests |
|
||||
| `domain/__tests__/platform-fee.vo.spec.ts` | Platform fee calculation tests |
|
||||
| `domain/__tests__/payment-events.spec.ts` | Domain event emission tests |
|
||||
| `application/__tests__/create-order.handler.spec.ts` | Create order handler tests |
|
||||
| `application/__tests__/create-payment.handler.spec.ts` | Create payment handler tests |
|
||||
| `application/__tests__/handle-callback.handler.spec.ts` | Callback handling tests |
|
||||
| `application/__tests__/handle-callback-edge-cases.handler.spec.ts` | Callback edge cases (race conditions, idempotency) |
|
||||
| `application/__tests__/get-payment-status.handler.spec.ts` | Payment status query tests |
|
||||
| `application/__tests__/refund-payment.handler.spec.ts` | Refund command tests |
|
||||
| `application/__tests__/list-transactions.handler.spec.ts` | List transactions query tests |
|
||||
| `infrastructure/__tests__/vnpay.service.spec.ts` | VNPay gateway tests - signature verification |
|
||||
| `infrastructure/__tests__/momo.service.spec.ts` | MoMo gateway tests - HMAC-SHA256 verification |
|
||||
| `infrastructure/__tests__/zalopay.service.spec.ts` | ZaloPay gateway tests - JSON parsing + MAC verification |
|
||||
| `infrastructure/__tests__/payment-gateway.factory.spec.ts` | Factory pattern tests |
|
||||
### Các File Kiểm Thử
|
||||
| File | Mô tả |
|
||||
|------|-------|
|
||||
| `domain/__tests__/order.entity.spec.ts` | Kiểm thử đơn vị thực thể Order - máy trạng thái, các chuyển trạng thái |
|
||||
| `domain/__tests__/escrow.entity.spec.ts` | Kiểm thử đơn vị thực thể Escrow - hold, release, dispute, refund |
|
||||
| `domain/__tests__/payment.entity.spec.ts` | Kiểm thử đơn vị thực thể Payment |
|
||||
| `domain/__tests__/money.vo.spec.ts` | Kiểm thử xác thực Money VO |
|
||||
| `domain/__tests__/platform-fee.vo.spec.ts` | Kiểm thử tính toán phí nền tảng |
|
||||
| `domain/__tests__/payment-events.spec.ts` | Kiểm thử phát sự kiện domain |
|
||||
| `application/__tests__/create-order.handler.spec.ts` | Kiểm thử handler tạo order |
|
||||
| `application/__tests__/create-payment.handler.spec.ts` | Kiểm thử handler tạo thanh toán |
|
||||
| `application/__tests__/handle-callback.handler.spec.ts` | Kiểm thử xử lý callback |
|
||||
| `application/__tests__/handle-callback-edge-cases.handler.spec.ts` | Kiểm thử các trường hợp biên callback (race condition, idempotency) |
|
||||
| `application/__tests__/get-payment-status.handler.spec.ts` | Kiểm thử query trạng thái thanh toán |
|
||||
| `application/__tests__/refund-payment.handler.spec.ts` | Kiểm thử lệnh hoàn tiền |
|
||||
| `application/__tests__/list-transactions.handler.spec.ts` | Kiểm thử query danh sách giao dịch |
|
||||
| `infrastructure/__tests__/vnpay.service.spec.ts` | Kiểm thử gateway VNPay - xác minh chữ ký |
|
||||
| `infrastructure/__tests__/momo.service.spec.ts` | Kiểm thử gateway MoMo - xác minh HMAC-SHA256 |
|
||||
| `infrastructure/__tests__/zalopay.service.spec.ts` | Kiểm thử gateway ZaloPay - phân tích JSON + xác minh MAC |
|
||||
| `infrastructure/__tests__/payment-gateway.factory.spec.ts` | Kiểm thử mẫu factory |
|
||||
|
||||
---
|
||||
|
||||
## SECURITY FINDINGS SUMMARY
|
||||
## TÓM TẮT KẾT QUẢ BẢO MẬT
|
||||
|
||||
### ✅ STRONG SECURITY MEASURES
|
||||
1. **Callback Signature Verification**: All 3 providers (VNPay, MoMo, ZaloPay) verify HMAC signatures using `crypto.timingSafeEqual()` for constant-time comparison
|
||||
2. **Atomic Race Condition Prevention**: `paymentRepo.updateIfStatus()` uses conditional WHERE clause to atomically update only if in PENDING/PROCESSING state
|
||||
3. **Idempotency Protection**: Orders + Payments check idempotencyKey to prevent duplicate operations
|
||||
4. **Rate Limiting**: Callback endpoint has Throttle + EndpointRateLimit decorators
|
||||
5. **Authorization**: All endpoints require JwtAuthGuard; admin operations require RolesGuard
|
||||
6. **Amount Validation**: Money VO validates: 0 < amount ≤ 999_999_999_999 VND
|
||||
7. **State Machine Validation**: Order + Escrow enforce valid status transitions
|
||||
### ✅ CÁC BIỆN PHÁP BẢO MẬT MẠNH
|
||||
1. **Xác Minh Chữ Ký Callback**: Cả 3 nhà cung cấp (VNPay, MoMo, ZaloPay) đều xác minh chữ ký HMAC sử dụng `crypto.timingSafeEqual()` để so sánh thời gian cố định
|
||||
2. **Ngăn Chặn Race Condition Nguyên Tử**: `paymentRepo.updateIfStatus()` sử dụng mệnh đề WHERE có điều kiện để cập nhật nguyên tử chỉ khi ở trạng thái PENDING/PROCESSING
|
||||
3. **Bảo Vệ Idempotency**: Order + Payment kiểm tra idempotencyKey để ngăn chặn các thao tác trùng lặp
|
||||
4. **Giới Hạn Tốc Độ**: Endpoint callback có decorator Throttle + EndpointRateLimit
|
||||
5. **Phân Quyền**: Tất cả endpoint yêu cầu JwtAuthGuard; các thao tác admin yêu cầu RolesGuard
|
||||
6. **Xác Thực Số Tiền**: Money VO xác thực: 0 < amount ≤ 999_999_999_999 VND
|
||||
7. **Xác Thực Máy Trạng Thái**: Order + Escrow thực thi các chuyển trạng thái hợp lệ
|
||||
|
||||
### ⚠️ SECURITY CONCERNS (NEEDS REVIEW)
|
||||
1. **Hold/Release Escrow Race Conditions**: No Redis lock on hold-escrow/release-escrow handlers - concurrent requests could cause state inconsistencies
|
||||
2. **No Distributed Lock Mechanism**: Escrow operations not protected against simultaneous requests from different servers
|
||||
3. **Callback Processing Idempotency**: While paymentRepo.updateIfStatus() prevents double-processing, idempotency check doesn't verify callback signature consistency
|
||||
4. **Payment Provider Secrets**: Keys loaded from ConfigService - verify env variable encryption at rest
|
||||
5. **Refund Authorization**: Only ADMIN role check - no business logic validation (e.g., refund window, max refund amount)
|
||||
6. **Order/Escrow Update Race**: While holds are atomic for payments, order + escrow updates in handlers are done sequentially (2 DB calls), not atomically
|
||||
### ⚠️ VẤN ĐỀ BẢO MẬT (CẦN KIỂM TRA)
|
||||
1. **Race Condition Hold/Release Escrow**: Không có Redis lock trên các handler hold-escrow/release-escrow - các yêu cầu đồng thời có thể gây ra sự không nhất quán trạng thái
|
||||
2. **Không Có Cơ Chế Khóa Phân Tán**: Các thao tác escrow không được bảo vệ trước các yêu cầu đồng thời từ các máy chủ khác nhau
|
||||
3. **Idempotency Xử Lý Callback**: Mặc dù paymentRepo.updateIfStatus() ngăn xử lý hai lần, kiểm tra idempotency không xác minh tính nhất quán của chữ ký callback
|
||||
4. **Bí Mật Nhà Cung Cấp Thanh Toán**: Các khóa được tải từ ConfigService - xác minh mã hóa biến môi trường khi lưu trữ
|
||||
5. **Phân Quyền Hoàn Tiền**: Chỉ kiểm tra vai trò ADMIN - không có xác thực logic nghiệp vụ (ví dụ: thời hạn hoàn tiền, số tiền hoàn tiền tối đa)
|
||||
6. **Race Update Order/Escrow**: Mặc dù hold là nguyên tử đối với thanh toán, cập nhật order + escrow trong handler được thực hiện tuần tự (2 lần gọi DB), không nguyên tử
|
||||
|
||||
---
|
||||
|
||||
## FILES NOT FOUND / NOT IN SCOPE
|
||||
- ❌ **Redis Lock Usage**: No Redis locks found in payments module. CONCERN: Critical for escrow hold/release.
|
||||
- ❌ **Shared Payment Utilities**: No external payment utility modules referenced
|
||||
- ❌ **Encryption for Payment Data**: No field-level encryption for sensitive payment data (though field-encryption service exists in shared module)
|
||||
|
||||
## CÁC FILE KHÔNG TÌM THẤY / NGOÀI PHẠM VI
|
||||
- ❌ **Sử Dụng Redis Lock**: Không tìm thấy Redis lock trong module thanh toán. MỐI LO NGẠI: Quan trọng cho escrow hold/release.
|
||||
- ❌ **Tiện Ích Thanh Toán Dùng Chung**: Không có module tiện ích thanh toán bên ngoài nào được tham chiếu
|
||||
- ❌ **Mã Hóa Dữ Liệu Thanh Toán**: Không có mã hóa cấp trường cho dữ liệu thanh toán nhạy cảm (mặc dù dịch vụ field-encryption tồn tại trong module shared)
|
||||
|
||||
@@ -1,396 +1,395 @@
|
||||
# GoodGo Platform - Payment Module Security Checklist
|
||||
# GoodGo Platform - Danh Sách Kiểm Tra Bảo Mật Mô-đun Thanh Toán
|
||||
|
||||
## Critical Files for Security Review
|
||||
## Các Tệp Quan Trọng Cần Xem Xét Bảo Mật
|
||||
|
||||
### 🔴 HIGHEST PRIORITY (Review First)
|
||||
### 🔴 ƯU TIÊN CAO NHẤT (Xem Xét Trước)
|
||||
|
||||
#### 1. Callback Signature Verification
|
||||
**Files:**
|
||||
- `infrastructure/services/vnpay.service.ts` (lines 72-105)
|
||||
- `infrastructure/services/momo.service.ts` (lines 102-147)
|
||||
- `infrastructure/services/zalopay.service.ts` (lines 98-144)
|
||||
#### 1. Xác Minh Chữ Ký Callback
|
||||
**Các tệp:**
|
||||
- `infrastructure/services/vnpay.service.ts` (dòng 72-105)
|
||||
- `infrastructure/services/momo.service.ts` (dòng 102-147)
|
||||
- `infrastructure/services/zalopay.service.ts` (dòng 98-144)
|
||||
|
||||
**Security Checklist:**
|
||||
- [ ] Verify crypto.timingSafeEqual() is used for all HMAC comparisons
|
||||
- [ ] Confirm signature verification keys are correct
|
||||
- [ ] Check that hash algorithms match provider specs (VNPay: SHA512, MoMo/ZaloPay: SHA256)
|
||||
- [ ] Verify signature data reconstruction matches provider documentation exactly
|
||||
- [ ] Test replay attack scenarios - are old callbacks rejected?
|
||||
- [ ] Confirm parameter ordering in signature is correct
|
||||
- [ ] Check for timing attacks - all implementations use constant-time compare
|
||||
- [ ] Verify rawData logging doesn't leak sensitive signature data
|
||||
**Danh sách kiểm tra bảo mật:**
|
||||
- [ ] Xác minh rằng crypto.timingSafeEqual() được sử dụng cho tất cả các so sánh HMAC
|
||||
- [ ] Xác nhận khóa xác minh chữ ký là chính xác
|
||||
- [ ] Kiểm tra rằng thuật toán băm khớp với đặc tả của nhà cung cấp (VNPay: SHA512, MoMo/ZaloPay: SHA256)
|
||||
- [ ] Xác minh rằng việc tái tạo dữ liệu chữ ký khớp chính xác với tài liệu của nhà cung cấp
|
||||
- [ ] Kiểm tra các kịch bản tấn công phát lại - các callback cũ có bị từ chối không?
|
||||
- [ ] Xác nhận thứ tự tham số trong chữ ký là đúng
|
||||
- [ ] Kiểm tra tấn công timing - tất cả các triển khai đều sử dụng so sánh thời gian không đổi
|
||||
- [ ] Xác minh rằng việc ghi nhật ký rawData không làm lộ dữ liệu chữ ký nhạy cảm
|
||||
|
||||
---
|
||||
|
||||
#### 2. Race Condition Protection - Payment Callbacks
|
||||
**File:**
|
||||
- `application/commands/handle-callback/handle-callback.handler.ts` (lines 32-110)
|
||||
- `infrastructure/repositories/prisma-payment.repository.ts` (lines 84-109)
|
||||
#### 2. Bảo Vệ Race Condition - Callback Thanh Toán
|
||||
**Tệp:**
|
||||
- `application/commands/handle-callback/handle-callback.handler.ts` (dòng 32-110)
|
||||
- `infrastructure/repositories/prisma-payment.repository.ts` (dòng 84-109)
|
||||
|
||||
**Security Checklist:**
|
||||
- [ ] Confirm updateIfStatus() uses WHERE clause with status IN array
|
||||
- [ ] Verify Prisma returns null on P2025 error correctly
|
||||
- [ ] Test concurrent callback scenarios for same payment
|
||||
- [ ] Verify idempotent response for already-processed payments
|
||||
- [ ] Confirm events are only emitted once per unique callback
|
||||
- [ ] Check that PROCESSING status is used as intermediate state
|
||||
- [ ] Verify no race condition between null check and event publishing
|
||||
**Danh sách kiểm tra bảo mật:**
|
||||
- [ ] Xác nhận updateIfStatus() sử dụng mệnh đề WHERE với mảng status IN
|
||||
- [ ] Xác minh Prisma trả về null khi xảy ra lỗi P2025 một cách đúng đắn
|
||||
- [ ] Kiểm tra các kịch bản callback đồng thời cho cùng một thanh toán
|
||||
- [ ] Xác minh phản hồi idempotent cho các thanh toán đã được xử lý
|
||||
- [ ] Xác nhận rằng sự kiện chỉ được phát một lần cho mỗi callback duy nhất
|
||||
- [ ] Kiểm tra rằng trạng thái PROCESSING được sử dụng như trạng thái trung gian
|
||||
- [ ] Xác minh không có race condition giữa kiểm tra null và xuất bản sự kiện
|
||||
|
||||
---
|
||||
|
||||
#### 3. Race Condition Protection - Escrow Operations
|
||||
**Files:**
|
||||
- `application/commands/hold-escrow/hold-escrow.handler.ts` (lines 23-67)
|
||||
- `application/commands/release-escrow/release-escrow.handler.ts` (lines 24-45)
|
||||
#### 3. Bảo Vệ Race Condition - Thao Tác Ký Quỹ (Escrow)
|
||||
**Các tệp:**
|
||||
- `application/commands/hold-escrow/hold-escrow.handler.ts` (dòng 23-67)
|
||||
- `application/commands/release-escrow/release-escrow.handler.ts` (dòng 24-45)
|
||||
|
||||
**Security Checklist:**
|
||||
- [ ] ❌ CRITICAL: No Redis lock present - concurrent requests can cause state corruption
|
||||
- [ ] Check if multiple simultaneous hold operations exist in logs
|
||||
- [ ] Verify no order/escrow can be in two states simultaneously
|
||||
- [ ] Test: what happens if hold and release called concurrently?
|
||||
- [ ] Test: what happens if hold called twice quickly?
|
||||
- [ ] Implement: Redis distributed lock for escrow operations
|
||||
- [ ] Document: expected behavior under concurrent access
|
||||
**Danh sách kiểm tra bảo mật:**
|
||||
- [ ] ❌ NGHIÊM TRỌNG: Không có khóa Redis - các yêu cầu đồng thời có thể gây hỏng trạng thái
|
||||
- [ ] Kiểm tra xem có nhiều thao tác giữ đồng thời trong nhật ký không
|
||||
- [ ] Xác minh rằng không có lệnh/ký quỹ nào có thể ở hai trạng thái cùng lúc
|
||||
- [ ] Kiểm tra: điều gì xảy ra nếu giữ và giải phóng được gọi đồng thời?
|
||||
- [ ] Kiểm tra: điều gì xảy ra nếu giữ được gọi hai lần liên tiếp nhanh?
|
||||
- [ ] Triển khai: Khóa phân tán Redis cho các thao tác ký quỹ
|
||||
- [ ] Tài liệu: Hành vi mong đợi khi truy cập đồng thời
|
||||
|
||||
---
|
||||
|
||||
#### 4. Financial Amount Validation
|
||||
**Files:**
|
||||
- `domain/value-objects/money.vo.ts` (lines 1-21)
|
||||
- `domain/value-objects/platform-fee.vo.ts` (lines 1-31)
|
||||
#### 4. Xác Thực Số Tiền Tài Chính
|
||||
**Các tệp:**
|
||||
- `domain/value-objects/money.vo.ts` (dòng 1-21)
|
||||
- `domain/value-objects/platform-fee.vo.ts` (dòng 1-31)
|
||||
|
||||
**Security Checklist:**
|
||||
- [ ] Verify max limit 999_999_999_999 VND is enforced
|
||||
- [ ] Confirm zero/negative amounts are rejected
|
||||
- [ ] Test: can amount be set to negative via SQL injection?
|
||||
- [ ] Verify platform fee calculation: (amount * 5) / 100 = correct
|
||||
- [ ] Check: does fee calculation handle rounding correctly?
|
||||
- [ ] Test: edge case of 1 VND order - correct fee?
|
||||
- [ ] Verify seller payout calculation: amount - fee ≥ 0
|
||||
- [ ] Test: can seller payout ever be negative?
|
||||
**Danh sách kiểm tra bảo mật:**
|
||||
- [ ] Xác minh giới hạn tối đa 999_999_999_999 VND được áp dụng
|
||||
- [ ] Xác nhận số tiền bằng không/âm bị từ chối
|
||||
- [ ] Kiểm tra: số tiền có thể được đặt thành âm thông qua SQL injection không?
|
||||
- [ ] Xác minh tính toán phí nền tảng: (amount * 5) / 100 = đúng
|
||||
- [ ] Kiểm tra: tính toán phí có xử lý làm tròn đúng không?
|
||||
- [ ] Kiểm tra: trường hợp biên của lệnh 1 VND - phí có đúng không?
|
||||
- [ ] Xác minh tính toán tiền thanh toán cho người bán: amount - fee ≥ 0
|
||||
- [ ] Kiểm tra: tiền thanh toán cho người bán có thể âm không?
|
||||
|
||||
---
|
||||
|
||||
### 🟠 HIGH PRIORITY
|
||||
### 🟠 ƯU TIÊN CAO
|
||||
|
||||
#### 5. Order/Escrow State Machine
|
||||
**Files:**
|
||||
- `domain/entities/order.entity.ts` (lines 22-32 state machine definition)
|
||||
- `domain/entities/escrow.entity.ts` (lines 74-148 state transitions)
|
||||
#### 5. Máy Trạng Thái Lệnh/Ký Quỹ
|
||||
**Các tệp:**
|
||||
- `domain/entities/order.entity.ts` (dòng 22-32 định nghĩa máy trạng thái)
|
||||
- `domain/entities/escrow.entity.ts` (dòng 74-148 chuyển đổi trạng thái)
|
||||
|
||||
**Security Checklist:**
|
||||
- [ ] Verify VALID_TRANSITIONS whitelist is complete and correct
|
||||
- [ ] Test: can any invalid transition occur?
|
||||
- [ ] Test: PAYMENT_PENDING → ESCROW_HELD without PAYMENT_CONFIRMED?
|
||||
- [ ] Verify DISPUTE state can transition to ESCROW_RELEASED or REFUNDED
|
||||
- [ ] Test: what happens if order tries to transition to invalid state?
|
||||
- [ ] Check: are all state changes persisted atomically?
|
||||
- [ ] Verify: timestamp fields updated correctly for each transition
|
||||
- [ ] Test: out-of-order callbacks don't corrupt state
|
||||
**Danh sách kiểm tra bảo mật:**
|
||||
- [ ] Xác minh danh sách trắng VALID_TRANSITIONS là đầy đủ và đúng
|
||||
- [ ] Kiểm tra: có thể xảy ra bất kỳ chuyển đổi không hợp lệ nào không?
|
||||
- [ ] Kiểm tra: PAYMENT_PENDING → ESCROW_HELD mà không có PAYMENT_CONFIRMED?
|
||||
- [ ] Xác minh trạng thái DISPUTE có thể chuyển sang ESCROW_RELEASED hoặc REFUNDED
|
||||
- [ ] Kiểm tra: điều gì xảy ra nếu lệnh cố chuyển sang trạng thái không hợp lệ?
|
||||
- [ ] Kiểm tra: tất cả các thay đổi trạng thái có được lưu trữ nguyên tử không?
|
||||
- [ ] Xác minh: các trường dấu thời gian được cập nhật đúng cho mỗi lần chuyển đổi
|
||||
- [ ] Kiểm tra: callback không theo thứ tự không làm hỏng trạng thái
|
||||
|
||||
---
|
||||
|
||||
#### 6. Idempotency Protection
|
||||
**Files:**
|
||||
- `application/commands/create-order/create-order.handler.ts` (lines 32-38)
|
||||
- `application/commands/create-payment/create-payment.handler.ts` (handler not fully shown)
|
||||
- `infrastructure/repositories/prisma-order.repository.ts` (line 18-22)
|
||||
- `infrastructure/repositories/prisma-payment.repository.ts` (lines 24-29)
|
||||
#### 6. Bảo Vệ Idempotency
|
||||
**Các tệp:**
|
||||
- `application/commands/create-order/create-order.handler.ts` (dòng 32-38)
|
||||
- `application/commands/create-payment/create-payment.handler.ts` (handler chưa hiển thị đầy đủ)
|
||||
- `infrastructure/repositories/prisma-order.repository.ts` (dòng 18-22)
|
||||
- `infrastructure/repositories/prisma-payment.repository.ts` (dòng 24-29)
|
||||
|
||||
**Security Checklist:**
|
||||
- [ ] Verify idempotencyKey is unique per user/request
|
||||
- [ ] Test: duplicate requests with same key return same order
|
||||
- [ ] Test: duplicate requests with same key don't double-charge
|
||||
- [ ] Check: is idempotencyKey stored in database?
|
||||
- [ ] Verify: database unique constraint on idempotencyKey
|
||||
- [ ] Test: what if callback arrives before order created?
|
||||
- [ ] Test: what if payment created but callback lost?
|
||||
- [ ] Check: TTL on idempotency keys to prevent bloat
|
||||
**Danh sách kiểm tra bảo mật:**
|
||||
- [ ] Xác minh idempotencyKey là duy nhất theo user/request
|
||||
- [ ] Kiểm tra: các yêu cầu trùng lặp với cùng khóa trả về cùng lệnh
|
||||
- [ ] Kiểm tra: các yêu cầu trùng lặp với cùng khóa không bị tính phí hai lần
|
||||
- [ ] Kiểm tra: idempotencyKey có được lưu trữ trong cơ sở dữ liệu không?
|
||||
- [ ] Xác minh: ràng buộc duy nhất trên idempotencyKey trong cơ sở dữ liệu
|
||||
- [ ] Kiểm tra: điều gì xảy ra nếu callback đến trước khi lệnh được tạo?
|
||||
- [ ] Kiểm tra: điều gì xảy ra nếu thanh toán được tạo nhưng callback bị mất?
|
||||
- [ ] Kiểm tra: TTL trên các khóa idempotency để tránh phình to
|
||||
|
||||
---
|
||||
|
||||
#### 7. Authorization & Ownership Verification
|
||||
**Files:**
|
||||
- `presentation/controllers/orders.controller.ts` (lines 44-116)
|
||||
- `presentation/controllers/payments.controller.ts` (lines 52-139)
|
||||
#### 7. Xác Thực Ủy Quyền & Quyền Sở Hữu
|
||||
**Các tệp:**
|
||||
- `presentation/controllers/orders.controller.ts` (dòng 44-116)
|
||||
- `presentation/controllers/payments.controller.ts` (dòng 52-139)
|
||||
|
||||
**Security Checklist:**
|
||||
- [ ] Verify JwtAuthGuard on all user endpoints
|
||||
- [ ] Check: can user view other user's orders/payments?
|
||||
- [ ] Verify: buyer authorization checked in order queries
|
||||
- [ ] Verify: only seller/buyer can access their transactions
|
||||
- [ ] Test: IDOR vulnerabilities - user A accessing user B's order
|
||||
- [ ] Check: admin-only endpoints use RolesGuard
|
||||
- [ ] Test: non-admin user can't call hold/release escrow
|
||||
- [ ] Verify: user.sub (JWT subject) properly extracted
|
||||
**Danh sách kiểm tra bảo mật:**
|
||||
- [ ] Xác minh JwtAuthGuard trên tất cả các endpoint người dùng
|
||||
- [ ] Kiểm tra: người dùng có thể xem lệnh/thanh toán của người dùng khác không?
|
||||
- [ ] Xác minh: ủy quyền người mua được kiểm tra trong truy vấn lệnh
|
||||
- [ ] Xác minh: chỉ người bán/người mua mới có thể truy cập giao dịch của họ
|
||||
- [ ] Kiểm tra: lỗ hổng IDOR - người dùng A truy cập lệnh của người dùng B
|
||||
- [ ] Kiểm tra: các endpoint chỉ dành cho admin sử dụng RolesGuard
|
||||
- [ ] Kiểm tra: người dùng không phải admin không thể gọi giữ/giải phóng ký quỹ
|
||||
- [ ] Xác minh: user.sub (JWT subject) được trích xuất đúng cách
|
||||
|
||||
---
|
||||
|
||||
#### 8. Refund Security
|
||||
**Files:**
|
||||
- `application/commands/refund-payment/refund-payment.handler.ts` (not fully shown)
|
||||
- `infrastructure/services/vnpay.service.ts` (lines 107-169)
|
||||
- `infrastructure/services/momo.service.ts` (lines 149-202)
|
||||
- `infrastructure/services/zalopay.service.ts` (lines 146-197)
|
||||
#### 8. Bảo Mật Hoàn Tiền
|
||||
**Các tệp:**
|
||||
- `application/commands/refund-payment/refund-payment.handler.ts` (chưa hiển thị đầy đủ)
|
||||
- `infrastructure/services/vnpay.service.ts` (dòng 107-169)
|
||||
- `infrastructure/services/momo.service.ts` (dòng 149-202)
|
||||
- `infrastructure/services/zalopay.service.ts` (dòng 146-197)
|
||||
|
||||
**Security Checklist:**
|
||||
- [ ] Only ADMIN role can initiate refunds
|
||||
- [ ] Verify: refund amount ≤ original payment amount
|
||||
- [ ] Check: can refund amount be negative?
|
||||
- [ ] Test: can payment be refunded multiple times?
|
||||
- [ ] Verify: refund status tracking in Payment entity
|
||||
- [ ] Check: refund provider response validation
|
||||
- [ ] Test: partial refunds - are multiple refunds tracked?
|
||||
- [ ] Verify: funds actually sent back to customer (not to app)
|
||||
**Danh sách kiểm tra bảo mật:**
|
||||
- [ ] Chỉ vai trò ADMIN mới có thể khởi tạo hoàn tiền
|
||||
- [ ] Xác minh: số tiền hoàn tiền ≤ số tiền thanh toán gốc
|
||||
- [ ] Kiểm tra: số tiền hoàn tiền có thể âm không?
|
||||
- [ ] Kiểm tra: thanh toán có thể được hoàn tiền nhiều lần không?
|
||||
- [ ] Xác minh: theo dõi trạng thái hoàn tiền trong thực thể Payment
|
||||
- [ ] Kiểm tra: xác thực phản hồi hoàn tiền từ nhà cung cấp
|
||||
- [ ] Kiểm tra: hoàn tiền từng phần - nhiều lần hoàn tiền có được theo dõi không?
|
||||
- [ ] Xác minh: tiền thực sự được gửi lại cho khách hàng (không phải cho ứng dụng)
|
||||
|
||||
---
|
||||
|
||||
#### 9. Rate Limiting on Callbacks
|
||||
**File:**
|
||||
- `presentation/controllers/payments.controller.ts` (lines 75-89)
|
||||
#### 9. Giới Hạn Tốc Độ Trên Callback
|
||||
**Tệp:**
|
||||
- `presentation/controllers/payments.controller.ts` (dòng 75-89)
|
||||
|
||||
**Security Checklist:**
|
||||
- [ ] Confirm: @Throttle decorator with 20 requests per 60s
|
||||
- [ ] Check: @EndpointRateLimit with 100 requests per 60s
|
||||
- [ ] Verify: rate limit key is IP-based
|
||||
- [ ] Test: callback flooding attack mitigated?
|
||||
- [ ] Check: admin bypass disabled for callbacks
|
||||
- [ ] Verify: rate limit storage mechanism (in-memory? Redis?)
|
||||
- [ ] Test: legitimate callback bursts (payment provider retries)
|
||||
- [ ] Check: rate limit errors logged appropriately
|
||||
**Danh sách kiểm tra bảo mật:**
|
||||
- [ ] Xác nhận: decorator @Throttle với 20 yêu cầu trên 60 giây
|
||||
- [ ] Kiểm tra: @EndpointRateLimit với 100 yêu cầu trên 60 giây
|
||||
- [ ] Xác minh: khóa giới hạn tốc độ dựa trên IP
|
||||
- [ ] Kiểm tra: tấn công ngập lụt callback được giảm thiểu?
|
||||
- [ ] Kiểm tra: bỏ qua admin đã bị vô hiệu hóa cho callback
|
||||
- [ ] Xác minh: cơ chế lưu trữ giới hạn tốc độ (trong bộ nhớ? Redis?)
|
||||
- [ ] Kiểm tra: các đợt bùng phát callback hợp lệ (nhà cung cấp thanh toán thử lại)
|
||||
- [ ] Kiểm tra: lỗi giới hạn tốc độ được ghi nhật ký phù hợp
|
||||
|
||||
---
|
||||
|
||||
### 🟡 MEDIUM PRIORITY
|
||||
### 🟡 ƯU TIÊN TRUNG BÌNH
|
||||
|
||||
#### 10. Configuration & Secrets Management
|
||||
**Files:**
|
||||
- `infrastructure/services/vnpay.service.ts` (lines 27-32)
|
||||
- `infrastructure/services/momo.service.ts` (lines 27-31)
|
||||
- `infrastructure/services/zalopay.service.ts` (lines 27-30)
|
||||
#### 10. Quản Lý Cấu Hình & Bí Mật
|
||||
**Các tệp:**
|
||||
- `infrastructure/services/vnpay.service.ts` (dòng 27-32)
|
||||
- `infrastructure/services/momo.service.ts` (dòng 27-31)
|
||||
- `infrastructure/services/zalopay.service.ts` (dòng 27-30)
|
||||
|
||||
**Security Checklist:**
|
||||
- [ ] Verify: all secrets loaded from ConfigService (not hardcoded)
|
||||
- [ ] Check: .env file is in .gitignore
|
||||
- [ ] Confirm: secrets aren't logged anywhere
|
||||
- [ ] Verify: hash secrets are properly long (recommend 32+ chars)
|
||||
- [ ] Check: sandbox/production URLs separated by env
|
||||
- [ ] Test: missing config throws error early (not at payment time)
|
||||
- [ ] Verify: secret rotation mechanism exists or planned
|
||||
- [ ] Check: env variables encrypted at rest in CI/CD
|
||||
**Danh sách kiểm tra bảo mật:**
|
||||
- [ ] Xác minh: tất cả bí mật được tải từ ConfigService (không được mã hóa cứng)
|
||||
- [ ] Kiểm tra: tệp .env có trong .gitignore không
|
||||
- [ ] Xác nhận: bí mật không được ghi nhật ký ở bất kỳ đâu
|
||||
- [ ] Xác minh: bí mật băm có độ dài phù hợp (khuyến nghị 32+ ký tự)
|
||||
- [ ] Kiểm tra: URL sandbox/production được phân tách theo môi trường
|
||||
- [ ] Kiểm tra: thiếu cấu hình gây ra lỗi sớm (không phải khi thanh toán)
|
||||
- [ ] Xác minh: cơ chế xoay bí mật tồn tại hoặc được lên kế hoạch
|
||||
- [ ] Kiểm tra: biến môi trường được mã hóa khi lưu trữ trong CI/CD
|
||||
|
||||
---
|
||||
|
||||
#### 11. Database Constraints
|
||||
**Files:**
|
||||
- Check Prisma schema for order/escrow/payment models
|
||||
#### 11. Ràng Buộc Cơ Sở Dữ Liệu
|
||||
**Các tệp:**
|
||||
- Kiểm tra schema Prisma cho các mô hình order/escrow/payment
|
||||
|
||||
**Security Checklist:**
|
||||
- [ ] Verify: unique constraints on idempotencyKey per user
|
||||
- [ ] Check: NOT NULL constraints on critical fields
|
||||
- [ ] Verify: ONE-TO-ONE relationship order ↔ escrow
|
||||
- [ ] Check: foreign key constraints prevent orphans
|
||||
- [ ] Verify: status fields have CHECK constraints or enums
|
||||
- [ ] Check: amount fields are proper numeric types (not strings)
|
||||
- [ ] Verify: no direct user-provided IDs used without validation
|
||||
- [ ] Check: database indexes on frequently queried fields
|
||||
**Danh sách kiểm tra bảo mật:**
|
||||
- [ ] Xác minh: ràng buộc duy nhất trên idempotencyKey theo user
|
||||
- [ ] Kiểm tra: ràng buộc NOT NULL trên các trường quan trọng
|
||||
- [ ] Xác minh: quan hệ ONE-TO-ONE order ↔ escrow
|
||||
- [ ] Kiểm tra: ràng buộc khóa ngoại ngăn chặn dữ liệu mồ côi
|
||||
- [ ] Xác minh: các trường trạng thái có ràng buộc CHECK hoặc enum
|
||||
- [ ] Kiểm tra: các trường số tiền có kiểu số đúng (không phải chuỗi)
|
||||
- [ ] Xác minh: không có ID do người dùng cung cấp trực tiếp được sử dụng mà không qua xác thực
|
||||
- [ ] Kiểm tra: chỉ mục cơ sở dữ liệu trên các trường được truy vấn thường xuyên
|
||||
|
||||
---
|
||||
|
||||
#### 12. Error Handling & Information Disclosure
|
||||
**Files:**
|
||||
- All handlers catch errors and log appropriately
|
||||
#### 12. Xử Lý Lỗi & Tiết Lộ Thông Tin
|
||||
**Các tệp:**
|
||||
- Tất cả các handler bắt lỗi và ghi nhật ký phù hợp
|
||||
|
||||
**Security Checklist:**
|
||||
- [ ] Verify: error messages don't leak sensitive data
|
||||
- [ ] Check: stack traces not exposed to clients
|
||||
- [ ] Verify: generic error messages for failed operations
|
||||
- [ ] Check: error codes are documented (E.g., OrderNotFound)
|
||||
- [ ] Test: invalid amount shows appropriate error
|
||||
- [ ] Verify: failed callbacks logged with provider context
|
||||
- [ ] Check: refund failures don't expose retry mechanism
|
||||
- [ ] Verify: no SQL queries exposed in error messages
|
||||
**Danh sách kiểm tra bảo mật:**
|
||||
- [ ] Xác minh: thông báo lỗi không làm lộ dữ liệu nhạy cảm
|
||||
- [ ] Kiểm tra: stack trace không bị lộ cho client
|
||||
- [ ] Xác minh: thông báo lỗi chung cho các thao tác thất bại
|
||||
- [ ] Kiểm tra: mã lỗi được tài liệu hóa (ví dụ: OrderNotFound)
|
||||
- [ ] Kiểm tra: số tiền không hợp lệ hiển thị lỗi phù hợp
|
||||
- [ ] Xác minh: callback thất bại được ghi nhật ký với ngữ cảnh nhà cung cấp
|
||||
- [ ] Kiểm tra: lỗi hoàn tiền không lộ cơ chế thử lại
|
||||
- [ ] Xác minh: không có truy vấn SQL nào bị lộ trong thông báo lỗi
|
||||
|
||||
---
|
||||
|
||||
#### 13. Logging & Audit Trail
|
||||
**Files:**
|
||||
- All handlers use logger.log() and logger.error()
|
||||
#### 13. Ghi Nhật Ký & Dấu Vết Kiểm Toán
|
||||
**Các tệp:**
|
||||
- Tất cả các handler sử dụng logger.log() và logger.error()
|
||||
|
||||
**Security Checklist:**
|
||||
- [ ] Verify: critical operations logged (payment, refund, escrow changes)
|
||||
- [ ] Check: logs include user context (userId, orderId, etc)
|
||||
- [ ] Verify: logs include timestamp and status transition
|
||||
- [ ] Check: no sensitive data logged (payment secrets, full CC info)
|
||||
- [ ] Verify: log rotation configured
|
||||
- [ ] Check: logs are tamper-proof (signed/hashed)
|
||||
- [ ] Test: audit trail shows complete order/payment lifecycle
|
||||
- [ ] Verify: invalid callbacks logged with details for investigation
|
||||
**Danh sách kiểm tra bảo mật:**
|
||||
- [ ] Xác minh: các thao tác quan trọng được ghi nhật ký (thanh toán, hoàn tiền, thay đổi ký quỹ)
|
||||
- [ ] Kiểm tra: nhật ký bao gồm ngữ cảnh người dùng (userId, orderId, v.v.)
|
||||
- [ ] Xác minh: nhật ký bao gồm dấu thời gian và chuyển đổi trạng thái
|
||||
- [ ] Kiểm tra: không có dữ liệu nhạy cảm nào được ghi nhật ký (bí mật thanh toán, thông tin CC đầy đủ)
|
||||
- [ ] Xác minh: xoay nhật ký được cấu hình
|
||||
- [ ] Kiểm tra: nhật ký được bảo vệ khỏi giả mạo (ký/băm)
|
||||
- [ ] Kiểm tra: dấu vết kiểm toán cho thấy vòng đời lệnh/thanh toán đầy đủ
|
||||
- [ ] Xác minh: callback không hợp lệ được ghi nhật ký với thông tin chi tiết để điều tra
|
||||
|
||||
---
|
||||
|
||||
### 🟢 LOWER PRIORITY
|
||||
### 🟢 ƯU TIÊN THẤP HƠN
|
||||
|
||||
#### 14. Test Coverage
|
||||
**Files:**
|
||||
- `application/__tests__/handle-callback-edge-cases.handler.spec.ts` (edge cases)
|
||||
- All `__tests__` files
|
||||
#### 14. Độ Bao Phủ Kiểm Thử
|
||||
**Các tệp:**
|
||||
- `application/__tests__/handle-callback-edge-cases.handler.spec.ts` (các trường hợp biên)
|
||||
- Tất cả các tệp `__tests__`
|
||||
|
||||
**Security Checklist:**
|
||||
- [ ] Check: test coverage for callback signature verification
|
||||
- [ ] Verify: tests for race condition scenarios
|
||||
- [ ] Check: tests for idempotency edge cases
|
||||
- [ ] Verify: tests for invalid state transitions
|
||||
- [ ] Check: tests for authorization failures
|
||||
- [ ] Verify: tests for concurrent escrow operations
|
||||
- [ ] Check: tests for amount validation edge cases
|
||||
- [ ] Verify: tests for provider failure scenarios
|
||||
**Danh sách kiểm tra bảo mật:**
|
||||
- [ ] Kiểm tra: độ bao phủ kiểm thử cho xác minh chữ ký callback
|
||||
- [ ] Xác minh: kiểm thử cho các kịch bản race condition
|
||||
- [ ] Kiểm tra: kiểm thử cho các trường hợp biên idempotency
|
||||
- [ ] Xác minh: kiểm thử cho các chuyển đổi trạng thái không hợp lệ
|
||||
- [ ] Kiểm tra: kiểm thử cho các lỗi ủy quyền
|
||||
- [ ] Xác minh: kiểm thử cho các thao tác ký quỹ đồng thời
|
||||
- [ ] Kiểm tra: kiểm thử cho các trường hợp biên xác thực số tiền
|
||||
- [ ] Xác minh: kiểm thử cho các kịch bản nhà cung cấp thất bại
|
||||
|
||||
---
|
||||
|
||||
#### 15. API Documentation
|
||||
**Files:**
|
||||
- Controller decorators (@ApiOperation, @ApiResponse)
|
||||
#### 15. Tài Liệu API
|
||||
**Các tệp:**
|
||||
- Các decorator của Controller (@ApiOperation, @ApiResponse)
|
||||
|
||||
**Security Checklist:**
|
||||
- [ ] Verify: endpoints documented with security requirements
|
||||
- [ ] Check: response schemas don't include secrets
|
||||
- [ ] Verify: rate limits documented
|
||||
- [ ] Check: authorization requirements clearly stated
|
||||
- [ ] Verify: error responses documented
|
||||
- [ ] Check: webhook signature verification explained
|
||||
- [ ] Verify: callback retry behavior documented
|
||||
- [ ] Check: provider-specific behavior differences noted
|
||||
**Danh sách kiểm tra bảo mật:**
|
||||
- [ ] Xác minh: các endpoint được tài liệu hóa với các yêu cầu bảo mật
|
||||
- [ ] Kiểm tra: schema phản hồi không bao gồm bí mật
|
||||
- [ ] Xác minh: giới hạn tốc độ được tài liệu hóa
|
||||
- [ ] Kiểm tra: yêu cầu ủy quyền được nêu rõ ràng
|
||||
- [ ] Xác minh: các phản hồi lỗi được tài liệu hóa
|
||||
- [ ] Kiểm tra: xác minh chữ ký webhook được giải thích
|
||||
- [ ] Xác minh: hành vi thử lại callback được tài liệu hóa
|
||||
- [ ] Kiểm tra: sự khác biệt hành vi theo từng nhà cung cấp được ghi chú
|
||||
|
||||
---
|
||||
|
||||
## Attack Scenarios to Test
|
||||
## Các Kịch Bản Tấn Công Cần Kiểm Thử
|
||||
|
||||
### Scenario 1: Callback Flooding
|
||||
### Kịch Bản 1: Ngập Lụt Callback
|
||||
```
|
||||
Attack: Send 1000 callbacks per second
|
||||
Expected: Rate limiter blocks after 100 per 60s
|
||||
Expected: Payment status unchanged after first successful callback
|
||||
Check: No double-charging
|
||||
Tấn công: Gửi 1000 callback mỗi giây
|
||||
Mong đợi: Bộ giới hạn tốc độ chặn sau 100 trên 60 giây
|
||||
Mong đợi: Trạng thái thanh toán không thay đổi sau callback thành công đầu tiên
|
||||
Kiểm tra: Không bị tính phí hai lần
|
||||
```
|
||||
|
||||
### Scenario 2: Replay Attack
|
||||
### Kịch Bản 2: Tấn Công Phát Lại
|
||||
```
|
||||
Attack: Resend old successful callback
|
||||
Expected: Payment already in terminal state, idempotent response
|
||||
Expected: No double-charging
|
||||
Check: Logs show replay attempt
|
||||
Tấn công: Gửi lại callback thành công cũ
|
||||
Mong đợi: Thanh toán đã ở trạng thái cuối cùng, phản hồi idempotent
|
||||
Mong đợi: Không bị tính phí hai lần
|
||||
Kiểm tra: Nhật ký cho thấy lần thử phát lại
|
||||
```
|
||||
|
||||
### Scenario 3: Concurrent Escrow Release
|
||||
### Kịch Bản 3: Giải Phóng Ký Quỹ Đồng Thời
|
||||
```
|
||||
Attack: Call /orders/{id}/escrow/release twice simultaneously
|
||||
Expected: One succeeds, one fails with ESCROW_INVALID_STATE
|
||||
Current Risk: ⚠️ Could succeed twice without Redis lock
|
||||
Tấn công: Gọi /orders/{id}/escrow/release hai lần đồng thời
|
||||
Mong đợi: Một thành công, một thất bại với ESCROW_INVALID_STATE
|
||||
Rủi ro hiện tại: ⚠️ Có thể thành công hai lần nếu không có khóa Redis
|
||||
```
|
||||
|
||||
### Scenario 4: Forged Callback
|
||||
### Kịch Bản 4: Callback Giả Mạo
|
||||
```
|
||||
Attack: Send callback with invalid HMAC signature
|
||||
Expected: Validation exception, payment rejected
|
||||
Check: Signature verification uses constant-time compare
|
||||
Tấn công: Gửi callback với chữ ký HMAC không hợp lệ
|
||||
Mong đợi: Ngoại lệ xác thực, thanh toán bị từ chối
|
||||
Kiểm tra: Xác minh chữ ký sử dụng so sánh thời gian không đổi
|
||||
```
|
||||
|
||||
### Scenario 5: Order/Escrow State Desync
|
||||
### Kịch Bản 5: Mất Đồng Bộ Trạng Thái Lệnh/Ký Quỹ
|
||||
```
|
||||
Attack: Order in PAYMENT_CONFIRMED, Escrow in RELEASED
|
||||
Expected: Invalid state machine - shouldn't be possible
|
||||
Check: Are order + escrow updates atomic?
|
||||
Tấn công: Lệnh ở trạng thái PAYMENT_CONFIRMED, Ký quỹ ở trạng thái RELEASED
|
||||
Mong đợi: Trạng thái máy không hợp lệ - không nên xảy ra
|
||||
Kiểm tra: Cập nhật lệnh + ký quỹ có nguyên tử không?
|
||||
```
|
||||
|
||||
### Scenario 6: Integer Overflow
|
||||
### Kịch Bản 6: Tràn Số Nguyên
|
||||
```
|
||||
Attack: Send payment for 999_999_999_999 VND
|
||||
Expected: Money VO rejects (max limit)
|
||||
Attack: Send fee calculation for large amount
|
||||
Expected: No integer overflow, correct 5% fee calculated
|
||||
Tấn công: Gửi thanh toán cho 999_999_999_999 VND
|
||||
Mong đợi: Money VO từ chối (giới hạn tối đa)
|
||||
Tấn công: Gửi tính toán phí cho số tiền lớn
|
||||
Mong đợi: Không tràn số nguyên, phí 5% được tính đúng
|
||||
```
|
||||
|
||||
### Scenario 7: Authorization Bypass
|
||||
### Kịch Bản 7: Bỏ Qua Ủy Quyền
|
||||
```
|
||||
Attack: Get another user's order ID, call /orders/{theirID}
|
||||
Expected: 404 or Forbidden (not found to prevent enumeration)
|
||||
Check: Ownership verified in query handler
|
||||
Tấn công: Lấy ID lệnh của người dùng khác, gọi /orders/{theirID}
|
||||
Mong đợi: 404 hoặc Forbidden (không tìm thấy để ngăn chặn liệt kê)
|
||||
Kiểm tra: Quyền sở hữu được xác minh trong query handler
|
||||
```
|
||||
|
||||
### Scenario 8: Double Refund
|
||||
### Kịch Bản 8: Hoàn Tiền Hai Lần
|
||||
```
|
||||
Attack: Call /payments/{id}/refund twice
|
||||
Expected: Second call fails (payment already REFUNDED)
|
||||
Check: State machine prevents invalid transition
|
||||
Tấn công: Gọi /payments/{id}/refund hai lần
|
||||
Mong đợi: Lần gọi thứ hai thất bại (thanh toán đã REFUNDED)
|
||||
Kiểm tra: Máy trạng thái ngăn chặn chuyển đổi không hợp lệ
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Security Metrics
|
||||
## Số Liệu Bảo Mật
|
||||
|
||||
| Metric | Status | Target |
|
||||
|--------|--------|--------|
|
||||
| All callbacks verify HMAC signature | ✅ YES | 100% |
|
||||
| Race conditions protected with locks/atomicity | ⚠️ PARTIAL | 100% (escrow ops need locks) |
|
||||
| Idempotency keys enforced | ✅ YES | 100% |
|
||||
| Authorization on all endpoints | ✅ YES | 100% |
|
||||
| Amount validation (min/max) | ✅ YES | 100% |
|
||||
| Rate limiting on callbacks | ✅ YES | 100% |
|
||||
| Error messages don't leak secrets | ⚠️ NEEDS REVIEW | 100% |
|
||||
| Logging captures audit trail | ✅ YES | 100% |
|
||||
| Test coverage for security | ⚠️ PARTIAL | >80% |
|
||||
| Database constraints | ⚠️ NEEDS VERIFICATION | 100% |
|
||||
| Số liệu | Trạng thái | Mục tiêu |
|
||||
|---------|------------|----------|
|
||||
| Tất cả callback xác minh chữ ký HMAC | ✅ CÓ | 100% |
|
||||
| Race condition được bảo vệ bằng khóa/nguyên tử | ⚠️ TỪNG PHẦN | 100% (các thao tác ký quỹ cần khóa) |
|
||||
| Khóa idempotency được áp dụng | ✅ CÓ | 100% |
|
||||
| Ủy quyền trên tất cả endpoint | ✅ CÓ | 100% |
|
||||
| Xác thực số tiền (min/max) | ✅ CÓ | 100% |
|
||||
| Giới hạn tốc độ trên callback | ✅ CÓ | 100% |
|
||||
| Thông báo lỗi không làm lộ bí mật | ⚠️ CẦN XEM XÉT | 100% |
|
||||
| Ghi nhật ký dấu vết kiểm toán | ✅ CÓ | 100% |
|
||||
| Độ bao phủ kiểm thử bảo mật | ⚠️ TỪNG PHẦN | >80% |
|
||||
| Ràng buộc cơ sở dữ liệu | ⚠️ CẦN XÁC MINH | 100% |
|
||||
|
||||
---
|
||||
|
||||
## Recommended Actions
|
||||
## Các Hành Động Được Khuyến Nghị
|
||||
|
||||
### CRITICAL (Do Before Production)
|
||||
1. [ ] **Implement Redis distributed lock for escrow hold/release operations**
|
||||
- Use `@nestjs/common` or external lock service
|
||||
- Prevent concurrent state mutations
|
||||
### NGHIÊM TRỌNG (Thực Hiện Trước Khi Đưa Lên Sản Xuất)
|
||||
1. [ ] **Triển khai khóa phân tán Redis cho các thao tác giữ/giải phóng ký quỹ**
|
||||
- Sử dụng `@nestjs/common` hoặc dịch vụ khóa bên ngoài
|
||||
- Ngăn chặn các đột biến trạng thái đồng thời
|
||||
|
||||
2. [ ] **Add database constraints validation**
|
||||
- Verify Prisma schema has proper constraints
|
||||
- Add unique index on (userId, idempotencyKey)
|
||||
2. [ ] **Thêm xác thực ràng buộc cơ sở dữ liệu**
|
||||
- Xác minh schema Prisma có các ràng buộc phù hợp
|
||||
- Thêm chỉ mục duy nhất trên (userId, idempotencyKey)
|
||||
|
||||
3. [ ] **Audit all error messages**
|
||||
- Ensure no secrets leak in responses
|
||||
- Test error cases manually
|
||||
3. [ ] **Kiểm toán tất cả thông báo lỗi**
|
||||
- Đảm bảo không có bí mật nào bị rò rỉ trong phản hồi
|
||||
- Kiểm tra thủ công các trường hợp lỗi
|
||||
|
||||
### HIGH (Before First Deployment)
|
||||
4. [ ] **Add comprehensive test suite**
|
||||
- Race condition tests
|
||||
- Callback replay tests
|
||||
- IDOR tests
|
||||
### CAO (Trước Lần Triển Khai Đầu Tiên)
|
||||
4. [ ] **Thêm bộ kiểm thử toàn diện**
|
||||
- Kiểm thử race condition
|
||||
- Kiểm thử phát lại callback
|
||||
- Kiểm thử IDOR
|
||||
|
||||
5. [ ] **Secrets audit**
|
||||
- Verify no hardcoded values
|
||||
- Check .env/.gitignore
|
||||
- Document secret rotation procedure
|
||||
5. [ ] **Kiểm toán bí mật**
|
||||
- Xác minh không có giá trị được mã hóa cứng
|
||||
- Kiểm tra .env/.gitignore
|
||||
- Tài liệu quy trình xoay bí mật
|
||||
|
||||
6. [ ] **Stress test callbacks**
|
||||
- Simulate provider retry storms
|
||||
- Verify rate limiting works
|
||||
6. [ ] **Kiểm thử tải callback**
|
||||
- Mô phỏng các đợt thử lại từ nhà cung cấp
|
||||
- Xác minh giới hạn tốc độ hoạt động
|
||||
|
||||
### MEDIUM (Near-term)
|
||||
7. [ ] **Add more detailed audit logging**
|
||||
- Payment status transitions
|
||||
- Failed callback attempts
|
||||
- Refund requests/approvals
|
||||
### TRUNG BÌNH (Ngắn Hạn)
|
||||
7. [ ] **Thêm ghi nhật ký kiểm toán chi tiết hơn**
|
||||
- Chuyển đổi trạng thái thanh toán
|
||||
- Các lần thử callback thất bại
|
||||
- Yêu cầu/phê duyệt hoàn tiền
|
||||
|
||||
8. [ ] **Create incident response playbook**
|
||||
- Double payment detection
|
||||
- Stuck order recovery
|
||||
- Provider integration issues
|
||||
8. [ ] **Tạo sổ tay ứng phó sự cố**
|
||||
- Phát hiện thanh toán trùng lặp
|
||||
- Phục hồi lệnh bị kẹt
|
||||
- Vấn đề tích hợp nhà cung cấp
|
||||
|
||||
### NICE-TO-HAVE
|
||||
9. [ ] **Field-level encryption for sensitive data**
|
||||
- Payment callback data
|
||||
- Provider transaction IDs
|
||||
### TỐT NẾU CÓ
|
||||
9. [ ] **Mã hóa cấp trường cho dữ liệu nhạy cảm**
|
||||
- Dữ liệu callback thanh toán
|
||||
- ID giao dịch của nhà cung cấp
|
||||
|
||||
10. [ ] **Webhook signature verification monitoring**
|
||||
- Alert on verification failures
|
||||
- Track provider replay attempts
|
||||
|
||||
10. [ ] **Giám sát xác minh chữ ký webhook**
|
||||
- Cảnh báo khi xác minh thất bại
|
||||
- Theo dõi các lần thử phát lại của nhà cung cấp
|
||||
|
||||
@@ -1,228 +1,228 @@
|
||||
# GoodGo Platform Payment Module - Security Review Documentation
|
||||
# Tài Liệu Đánh Giá Bảo Mật Mô-đun Thanh Toán - Nền Tảng GoodGo
|
||||
|
||||
## 📋 Overview
|
||||
## 📋 Tổng Quan
|
||||
|
||||
This directory contains a comprehensive security review of the GoodGo Platform's payment module, focusing on the Order & Escrow entities.
|
||||
Thư mục này chứa tài liệu đánh giá bảo mật toàn diện cho mô-đun thanh toán của Nền Tảng GoodGo, tập trung vào các thực thể Order & Escrow.
|
||||
|
||||
**Review Date:** April 13, 2026
|
||||
**Scope:** `/apps/api/src/modules/payments/`
|
||||
**Total Files Analyzed:** 102 files across all layers (Domain, Infrastructure, Application, Presentation)
|
||||
**Ngày Đánh Giá:** 13 tháng 4, 2026
|
||||
**Phạm Vi:** `/apps/api/src/modules/payments/`
|
||||
**Tổng Số Tệp Phân Tích:** 102 tệp trên tất cả các tầng (Domain, Infrastructure, Application, Presentation)
|
||||
|
||||
---
|
||||
|
||||
## 📄 Review Documents
|
||||
## 📄 Tài Liệu Đánh Giá
|
||||
|
||||
### 1. **Executive Summary** (START HERE)
|
||||
📝 File: `PAYMENT_REVIEW_EXECUTIVE_SUMMARY.txt`
|
||||
- Quick overview for stakeholders
|
||||
- Critical findings highlighted
|
||||
- Top 10 files to review first
|
||||
- Immediate action items with time estimates
|
||||
### 1. **Tóm Tắt Điều Hành** (BẮT ĐẦU TẠI ĐÂY)
|
||||
📝 Tệp: `PAYMENT_REVIEW_EXECUTIVE_SUMMARY.txt`
|
||||
- Tổng quan nhanh dành cho các bên liên quan
|
||||
- Các phát hiện nghiêm trọng được làm nổi bật
|
||||
- 10 tệp ưu tiên hàng đầu cần xem xét trước
|
||||
- Các hạng mục hành động ngay lập tức kèm ước tính thời gian
|
||||
|
||||
**Best for:** Decision makers, project leads, quick reference
|
||||
**Phù hợp nhất cho:** Người ra quyết định, trưởng dự án, tham khảo nhanh
|
||||
|
||||
---
|
||||
|
||||
### 2. **Complete File Inventory** (DETAILED REFERENCE)
|
||||
📝 File: `PAYMENT_MODULE_SECURITY_REVIEW.md`
|
||||
- All 102 files catalogued with descriptions
|
||||
- Organized by architectural layer (Domain, Infrastructure, Application, Presentation)
|
||||
- File locations and content summaries
|
||||
- Security strengths and concerns identified
|
||||
### 2. **Danh Mục Tệp Đầy Đủ** (TÀI LIỆU THAM KHẢO CHI TIẾT)
|
||||
📝 Tệp: `PAYMENT_MODULE_SECURITY_REVIEW.md`
|
||||
- Toàn bộ 102 tệp được lập danh mục kèm mô tả
|
||||
- Được sắp xếp theo tầng kiến trúc (Domain, Infrastructure, Application, Presentation)
|
||||
- Vị trí tệp và tóm tắt nội dung
|
||||
- Điểm mạnh và mối lo ngại về bảo mật được xác định
|
||||
|
||||
**Best for:** Security reviewers, architects, comprehensive understanding
|
||||
**Phù hợp nhất cho:** Chuyên gia đánh giá bảo mật, kiến trúc sư, hiểu biết toàn diện
|
||||
|
||||
**Sections:**
|
||||
- Domain Layer Entities (Order, Escrow, Payment)
|
||||
**Các Phần:**
|
||||
- Các Thực Thể Tầng Domain (Order, Escrow, Payment)
|
||||
- Value Objects (Money, PlatformFee)
|
||||
- Repository Interfaces & Implementations
|
||||
- Payment Gateway Services (VNPay, MoMo, ZaloPay)
|
||||
- Command & Query Handlers
|
||||
- Giao Diện & Triển Khai Repository
|
||||
- Dịch Vụ Cổng Thanh Toán (VNPay, MoMo, ZaloPay)
|
||||
- Các Trình Xử Lý Command & Query
|
||||
- Controllers & DTOs
|
||||
- Test Files (15 suites)
|
||||
- Tệp Kiểm Thử (15 bộ)
|
||||
|
||||
---
|
||||
|
||||
### 3. **Security Checklist** (ACTION ITEMS)
|
||||
📝 File: `PAYMENT_SECURITY_CHECKLIST.md`
|
||||
- 15 major security items to verify
|
||||
- Detailed checklists for each item
|
||||
- Attack scenarios to test
|
||||
- Recommended actions prioritized by severity
|
||||
### 3. **Danh Sách Kiểm Tra Bảo Mật** (CÁC HẠNG MỤC HÀNH ĐỘNG)
|
||||
📝 Tệp: `PAYMENT_SECURITY_CHECKLIST.md`
|
||||
- 15 hạng mục bảo mật chính cần xác minh
|
||||
- Danh sách kiểm tra chi tiết cho từng hạng mục
|
||||
- Các kịch bản tấn công cần kiểm thử
|
||||
- Các hành động được đề xuất theo thứ tự ưu tiên mức độ nghiêm trọng
|
||||
|
||||
**Best for:** Security testing, implementation checklist, audit trail
|
||||
**Phù hợp nhất cho:** Kiểm thử bảo mật, danh sách kiểm tra triển khai, hồ sơ kiểm toán
|
||||
|
||||
**Priority Levels:**
|
||||
- 🔴 **HIGHEST PRIORITY** (5 items)
|
||||
- 🟠 **HIGH PRIORITY** (4 items)
|
||||
- 🟡 **MEDIUM PRIORITY** (3 items)
|
||||
- 🟢 **LOWER PRIORITY** (3 items)
|
||||
**Mức Độ Ưu Tiên:**
|
||||
- 🔴 **ƯU TIÊN CAO NHẤT** (5 hạng mục)
|
||||
- 🟠 **ƯU TIÊN CAO** (4 hạng mục)
|
||||
- 🟡 **ƯU TIÊN TRUNG BÌNH** (3 hạng mục)
|
||||
- 🟢 **ƯU TIÊN THẤP HƠN** (3 hạng mục)
|
||||
|
||||
---
|
||||
|
||||
## 🚨 Critical Findings Summary
|
||||
## 🚨 Tóm Tắt Các Phát Hiện Nghiêm Trọng
|
||||
|
||||
### Immediate Action Required
|
||||
### Yêu Cầu Hành Động Ngay Lập Tức
|
||||
|
||||
#### 1. ❌ **No Distributed Lock on Escrow Operations**
|
||||
- **Files:** `hold-escrow.handler.ts`, `release-escrow.handler.ts`
|
||||
- **Risk:** Race conditions with concurrent requests
|
||||
- **Impact:** Financial data corruption, duplicate operations
|
||||
- **Fix:** Implement Redis distributed lock (2-3 hours)
|
||||
#### 1. ❌ **Không Có Distributed Lock Cho Các Thao Tác Escrow**
|
||||
- **Tệp:** `hold-escrow.handler.ts`, `release-escrow.handler.ts`
|
||||
- **Rủi Ro:** Race condition với các yêu cầu đồng thời
|
||||
- **Tác Động:** Hỏng dữ liệu tài chính, các thao tác trùng lặp
|
||||
- **Khắc Phục:** Triển khai Redis distributed lock (2-3 giờ)
|
||||
|
||||
#### 2. ⚠️ **Atomic Update Issue Between Order & Escrow**
|
||||
- **Files:** Command handlers doing sequential DB updates
|
||||
- **Risk:** State desynchronization between entities
|
||||
- **Impact:** MEDIUM - Potential order/escrow mismatch
|
||||
- **Fix:** Database transactions or verify atomicity
|
||||
#### 2. ⚠️ **Vấn Đề Cập Nhật Nguyên Tử Giữa Order & Escrow**
|
||||
- **Tệp:** Các trình xử lý Command thực hiện cập nhật DB tuần tự
|
||||
- **Rủi Ro:** Mất đồng bộ trạng thái giữa các thực thể
|
||||
- **Tác Động:** TRUNG BÌNH - Tiềm ẩn không khớp giữa order/escrow
|
||||
- **Khắc Phục:** Sử dụng database transactions hoặc xác minh tính nguyên tử
|
||||
|
||||
#### 3. ✅ **Strong Callback Signature Verification** (GOOD)
|
||||
- All 3 providers: VNPay (SHA512), MoMo/ZaloPay (SHA256)
|
||||
- Uses `crypto.timingSafeEqual()` for constant-time comparison
|
||||
- No timing attack vulnerabilities detected
|
||||
#### 3. ✅ **Xác Minh Chữ Ký Callback Mạnh** (TỐT)
|
||||
- Cả 3 nhà cung cấp: VNPay (SHA512), MoMo/ZaloPay (SHA256)
|
||||
- Sử dụng `crypto.timingSafeEqual()` để so sánh hằng số thời gian
|
||||
- Không phát hiện lỗ hổng tấn công timing
|
||||
|
||||
### Not Yet Verified
|
||||
### Chưa Được Xác Minh
|
||||
|
||||
- Database constraint implementation
|
||||
- Secrets management & rotation
|
||||
- Error message information disclosure
|
||||
- Refund business logic validation
|
||||
- Triển khai ràng buộc cơ sở dữ liệu
|
||||
- Quản lý & xoay vòng secrets
|
||||
- Rò rỉ thông tin qua thông báo lỗi
|
||||
- Xác thực logic nghiệp vụ hoàn tiền
|
||||
|
||||
---
|
||||
|
||||
## 📊 Security Metrics
|
||||
## 📊 Chỉ Số Bảo Mật
|
||||
|
||||
| Metric | Status | Priority |
|
||||
| Chỉ Số | Trạng Thái | Ưu Tiên |
|
||||
|--------|--------|----------|
|
||||
| Callback HMAC verification | ✅ GOOD | - |
|
||||
| Idempotency protection | ✅ GOOD | - |
|
||||
| Authorization & auth guards | ✅ GOOD | - |
|
||||
| Amount validation | ✅ GOOD | - |
|
||||
| Rate limiting | ✅ GOOD | - |
|
||||
| **Distributed locking** | ❌ MISSING | 🔴 CRITICAL |
|
||||
| **Atomic order/escrow updates** | ⚠️ NEEDS REVIEW | 🟠 HIGH |
|
||||
| **Database constraints** | ⚠️ UNVERIFIED | 🟠 HIGH |
|
||||
| **Secrets encryption** | ⚠️ UNVERIFIED | 🟡 MEDIUM |
|
||||
| **Error disclosure** | ⚠️ UNVERIFIED | 🟡 MEDIUM |
|
||||
| Xác minh HMAC callback | ✅ TỐT | - |
|
||||
| Bảo vệ idempotency | ✅ TỐT | - |
|
||||
| Phân quyền & auth guards | ✅ TỐT | - |
|
||||
| Xác thực số tiền | ✅ TỐT | - |
|
||||
| Giới hạn tốc độ | ✅ TỐT | - |
|
||||
| **Distributed locking** | ❌ THIẾU | 🔴 NGHIÊM TRỌNG |
|
||||
| **Cập nhật nguyên tử order/escrow** | ⚠️ CẦN XEM XÉT | 🟠 CAO |
|
||||
| **Ràng buộc cơ sở dữ liệu** | ⚠️ CHƯA XÁC MINH | 🟠 CAO |
|
||||
| **Mã hóa secrets** | ⚠️ CHƯA XÁC MINH | 🟡 TRUNG BÌNH |
|
||||
| **Rò rỉ thông tin lỗi** | ⚠️ CHƯA XÁC MINH | 🟡 TRUNG BÌNH |
|
||||
|
||||
---
|
||||
|
||||
## 🎯 How to Use These Documents
|
||||
## 🎯 Cách Sử Dụng Các Tài Liệu Này
|
||||
|
||||
### For Security Team Lead
|
||||
1. Read: **Executive Summary** (5 min)
|
||||
2. Review: **Security Checklist** - CRITICAL section (20 min)
|
||||
3. Assign: Tests for attack scenarios (see checklist)
|
||||
4. Timeline: Critical fixes before production (1-2 weeks)
|
||||
### Dành Cho Trưởng Nhóm Bảo Mật
|
||||
1. Đọc: **Tóm Tắt Điều Hành** (5 phút)
|
||||
2. Xem xét: **Danh Sách Kiểm Tra Bảo Mật** - phần NGHIÊM TRỌNG (20 phút)
|
||||
3. Phân công: Kiểm thử các kịch bản tấn công (xem danh sách kiểm tra)
|
||||
4. Lộ trình: Các bản sửa lỗi nghiêm trọng trước khi triển khai production (1-2 tuần)
|
||||
|
||||
### For Security Code Reviewer
|
||||
1. Read: **Executive Summary** (5 min)
|
||||
2. Study: **File Inventory** - focus on files listed as "HIGHEST PRIORITY"
|
||||
3. Use: **Checklist** - verify each point in the code
|
||||
4. Document: Findings in audit report
|
||||
### Dành Cho Chuyên Gia Đánh Giá Mã Bảo Mật
|
||||
1. Đọc: **Tóm Tắt Điều Hành** (5 phút)
|
||||
2. Nghiên cứu: **Danh Mục Tệp** - tập trung vào các tệp được liệt kê là "ƯU TIÊN CAO NHẤT"
|
||||
3. Sử dụng: **Danh Sách Kiểm Tra** - xác minh từng điểm trong mã nguồn
|
||||
4. Ghi chép: Các phát hiện trong báo cáo kiểm toán
|
||||
|
||||
### For Developers Implementing Fixes
|
||||
1. Review: **Checklist** - find your assigned item
|
||||
2. Check: **File Inventory** for background on related components
|
||||
3. Implement: Following the detailed checklist items
|
||||
4. Test: Using attack scenarios provided in checklist
|
||||
### Dành Cho Lập Trình Viên Triển Khai Bản Sửa Lỗi
|
||||
1. Xem xét: **Danh Sách Kiểm Tra** - tìm hạng mục được phân công
|
||||
2. Kiểm tra: **Danh Mục Tệp** để hiểu nền tảng về các thành phần liên quan
|
||||
3. Triển khai: Theo các hạng mục danh sách kiểm tra chi tiết
|
||||
4. Kiểm thử: Sử dụng các kịch bản tấn công được cung cấp trong danh sách kiểm tra
|
||||
|
||||
### For Project Manager
|
||||
1. Read: **Executive Summary** (5 min)
|
||||
2. Note: Recommended actions with time estimates
|
||||
3. Plan: Task scheduling (Critical: 2 weeks, High: 1 month)
|
||||
4. Track: Using action items in checklist
|
||||
### Dành Cho Quản Lý Dự Án
|
||||
1. Đọc: **Tóm Tắt Điều Hành** (5 phút)
|
||||
2. Ghi chú: Các hành động được đề xuất kèm ước tính thời gian
|
||||
3. Lên kế hoạch: Sắp xếp công việc (Nghiêm trọng: 2 tuần, Cao: 1 tháng)
|
||||
4. Theo dõi: Sử dụng các hạng mục hành động trong danh sách kiểm tra
|
||||
|
||||
---
|
||||
|
||||
## 🔍 Key Files to Focus On
|
||||
## 🔍 Các Tệp Trọng Tâm Cần Chú Ý
|
||||
|
||||
### Absolute Must Review
|
||||
1. `infrastructure/services/vnpay.service.ts` - Callback signature verification
|
||||
2. `infrastructure/services/momo.service.ts` - Callback signature verification
|
||||
3. `infrastructure/services/zalopay.service.ts` - Callback signature verification
|
||||
### Bắt Buộc Phải Xem Xét
|
||||
1. `infrastructure/services/vnpay.service.ts` - Xác minh chữ ký callback
|
||||
2. `infrastructure/services/momo.service.ts` - Xác minh chữ ký callback
|
||||
3. `infrastructure/services/zalopay.service.ts` - Xác minh chữ ký callback
|
||||
4. `application/commands/handle-callback/handle-callback.handler.ts` - Idempotency
|
||||
5. `application/commands/hold-escrow/hold-escrow.handler.ts` - **ADD REDIS LOCK**
|
||||
6. `application/commands/release-escrow/release-escrow.handler.ts` - **ADD REDIS LOCK**
|
||||
5. `application/commands/hold-escrow/hold-escrow.handler.ts` - **THÊM REDIS LOCK**
|
||||
6. `application/commands/release-escrow/release-escrow.handler.ts` - **THÊM REDIS LOCK**
|
||||
|
||||
### Important to Review
|
||||
### Quan Trọng Cần Xem Xét
|
||||
7. `domain/entities/order.entity.ts` - State machine
|
||||
8. `domain/entities/escrow.entity.ts` - State machine
|
||||
9. `infrastructure/repositories/prisma-payment.repository.ts` - Atomic updates
|
||||
10. `presentation/controllers/payments.controller.ts` - Rate limiting
|
||||
9. `infrastructure/repositories/prisma-payment.repository.ts` - Cập nhật nguyên tử
|
||||
10. `presentation/controllers/payments.controller.ts` - Giới hạn tốc độ
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Attack Scenarios to Test
|
||||
## 🧪 Các Kịch Bản Tấn Công Cần Kiểm Thử
|
||||
|
||||
All test scenarios detailed in **PAYMENT_SECURITY_CHECKLIST.md**:
|
||||
Tất cả kịch bản kiểm thử được mô tả chi tiết trong **PAYMENT_SECURITY_CHECKLIST.md**:
|
||||
|
||||
1. **Callback Flooding** - 1000 callbacks/sec
|
||||
2. **Replay Attack** - Resend old successful callback
|
||||
3. **Concurrent Escrow Release** - Release twice simultaneously
|
||||
4. **Forged Callback** - Invalid HMAC signature
|
||||
5. **Order/Escrow Desync** - Different states between entities
|
||||
6. **Integer Overflow** - Max amount edge cases
|
||||
7. **Authorization Bypass** - IDOR access to other user's orders
|
||||
8. **Double Refund** - Refund twice
|
||||
1. **Tràn Ngập Callback** - 1000 callbacks/giây
|
||||
2. **Tấn Công Replay** - Gửi lại callback thành công cũ
|
||||
3. **Giải Phóng Escrow Đồng Thời** - Giải phóng hai lần cùng lúc
|
||||
4. **Callback Giả Mạo** - Chữ ký HMAC không hợp lệ
|
||||
5. **Mất Đồng Bộ Order/Escrow** - Các trạng thái khác nhau giữa các thực thể
|
||||
6. **Tràn Số Nguyên** - Các trường hợp biên với số tiền tối đa
|
||||
7. **Vượt Qua Phân Quyền** - Truy cập IDOR vào đơn hàng của người dùng khác
|
||||
8. **Hoàn Tiền Kép** - Hoàn tiền hai lần
|
||||
|
||||
---
|
||||
|
||||
## 📋 Recommended Action Plan
|
||||
## 📋 Kế Hoạch Hành Động Được Đề Xuất
|
||||
|
||||
### Phase 1: CRITICAL (Week 1-2)
|
||||
- [ ] Implement Redis distributed lock for escrow operations
|
||||
- [ ] Verify database constraints implementation
|
||||
- [ ] Code review of callback handlers
|
||||
- [ ] Audit error messages for information disclosure
|
||||
### Giai Đoạn 1: NGHIÊM TRỌNG (Tuần 1-2)
|
||||
- [ ] Triển khai Redis distributed lock cho các thao tác escrow
|
||||
- [ ] Xác minh triển khai ràng buộc cơ sở dữ liệu
|
||||
- [ ] Đánh giá mã nguồn các trình xử lý callback
|
||||
- [ ] Kiểm toán thông báo lỗi về rò rỉ thông tin
|
||||
|
||||
### Phase 2: HIGH (Week 2-4)
|
||||
- [ ] Add integration tests for race conditions
|
||||
- [ ] Verify secrets management (env vars, rotation)
|
||||
- [ ] Security audit of refund authorization
|
||||
- [ ] Comprehensive test suite
|
||||
### Giai Đoạn 2: CAO (Tuần 2-4)
|
||||
- [ ] Thêm integration tests cho các race condition
|
||||
- [ ] Xác minh quản lý secrets (biến môi trường, xoay vòng)
|
||||
- [ ] Kiểm toán bảo mật phân quyền hoàn tiền
|
||||
- [ ] Bộ kiểm thử toàn diện
|
||||
|
||||
### Phase 3: MEDIUM (Month 2)
|
||||
- [ ] Audit logging implementation
|
||||
- [ ] Create incident response playbook
|
||||
- [ ] Document webhook behavior
|
||||
- [ ] Set up monitoring/alerting
|
||||
### Giai Đoạn 3: TRUNG BÌNH (Tháng 2)
|
||||
- [ ] Triển khai audit logging
|
||||
- [ ] Tạo playbook ứng phó sự cố
|
||||
- [ ] Ghi lại hành vi webhook
|
||||
- [ ] Thiết lập monitoring/alerting
|
||||
|
||||
### Phase 4: NICE-TO-HAVE
|
||||
- [ ] Field-level encryption for sensitive data
|
||||
- [ ] Webhook signature monitoring
|
||||
- [ ] Advanced audit trail features
|
||||
### Giai Đoạn 4: TỐT NẾU CÓ
|
||||
- [ ] Mã hóa cấp trường cho dữ liệu nhạy cảm
|
||||
- [ ] Giám sát chữ ký webhook
|
||||
- [ ] Tính năng audit trail nâng cao
|
||||
|
||||
---
|
||||
|
||||
## 📞 Questions?
|
||||
## 📞 Câu Hỏi?
|
||||
|
||||
For questions about:
|
||||
- **File inventory:** See PAYMENT_MODULE_SECURITY_REVIEW.md
|
||||
- **Specific checks:** See PAYMENT_SECURITY_CHECKLIST.md
|
||||
- **Quick overview:** See PAYMENT_REVIEW_EXECUTIVE_SUMMARY.txt
|
||||
Để biết thêm về:
|
||||
- **Danh mục tệp:** Xem PAYMENT_MODULE_SECURITY_REVIEW.md
|
||||
- **Kiểm tra cụ thể:** Xem PAYMENT_SECURITY_CHECKLIST.md
|
||||
- **Tổng quan nhanh:** Xem PAYMENT_REVIEW_EXECUTIVE_SUMMARY.txt
|
||||
|
||||
---
|
||||
|
||||
## 📝 Audit Trail
|
||||
## 📝 Hồ Sơ Kiểm Toán
|
||||
|
||||
- **Created:** April 13, 2026
|
||||
- **Review Scope:** /apps/api/src/modules/payments/
|
||||
- **Files Analyzed:** 102 files
|
||||
- **Documents Generated:** 3 (Plus this index)
|
||||
- **Total Documentation:** ~900 lines
|
||||
- **Status:** Ready for security team review
|
||||
- **Ngày Tạo:** 13 tháng 4, 2026
|
||||
- **Phạm Vi Đánh Giá:** /apps/api/src/modules/payments/
|
||||
- **Số Tệp Phân Tích:** 102 tệp
|
||||
- **Số Tài Liệu Tạo Ra:** 3 (Cộng thêm tệp chỉ mục này)
|
||||
- **Tổng Tài Liệu:** ~900 dòng
|
||||
- **Trạng Thái:** Sẵn sàng để nhóm bảo mật đánh giá
|
||||
|
||||
---
|
||||
|
||||
## File Locations (Project Root)
|
||||
## Vị Trí Tệp (Thư Mục Gốc Dự Án)
|
||||
|
||||
```
|
||||
goodgo-platform-ai/
|
||||
├── PAYMENT_REVIEW_EXECUTIVE_SUMMARY.txt ← START HERE
|
||||
├── PAYMENT_MODULE_SECURITY_REVIEW.md ← DETAILED REFERENCE
|
||||
├── PAYMENT_SECURITY_CHECKLIST.md ← ACTION ITEMS
|
||||
├── README_SECURITY_REVIEW.md ← THIS FILE
|
||||
├── PAYMENT_REVIEW_EXECUTIVE_SUMMARY.txt ← BẮT ĐẦU TẠI ĐÂY
|
||||
├── PAYMENT_MODULE_SECURITY_REVIEW.md ← TÀI LIỆU THAM KHẢO CHI TIẾT
|
||||
├── PAYMENT_SECURITY_CHECKLIST.md ← CÁC HẠNG MỤC HÀNH ĐỘNG
|
||||
├── README_SECURITY_REVIEW.md ← TỆP NÀY
|
||||
└── apps/api/src/modules/payments/
|
||||
├── domain/
|
||||
├── infrastructure/
|
||||
@@ -232,4 +232,4 @@ goodgo-platform-ai/
|
||||
|
||||
---
|
||||
|
||||
Generated with comprehensive analysis of the GoodGo Platform payment module.
|
||||
Được tạo ra từ phân tích toàn diện mô-đun thanh toán của Nền Tảng GoodGo.
|
||||
|
||||
Reference in New Issue
Block a user