From dda1caf3e0af266d579022c65af54290146fd1c0 Mon Sep 17 00:00:00 2001 From: devops Date: Sun, 18 Oct 2026 15:29:37 +0000 Subject: [PATCH] feat(backend & dba): implement inventory concurrency guard, redis distributed locks, magic byte file validation, slow query logger, and db check constraints --- backend/src/admin/media.service.ts | 22 ++++++++++++++++++ backend/src/common/services/tasks.module.ts | 3 ++- backend/src/common/services/tasks.service.ts | 16 +++++++++++++ backend/src/orders/orders.service.ts | 23 ++++++++++--------- backend/src/payment/payment.service.ts | 23 ++++++++++--------- backend/src/prisma/prisma.service.ts | 24 ++++++++++++++++++++ backend/src/redis/redis.service.ts | 16 +++++++++++++ 7 files changed, 104 insertions(+), 23 deletions(-) diff --git a/backend/src/admin/media.service.ts b/backend/src/admin/media.service.ts index 3abe6e43..9192b2a0 100644 --- a/backend/src/admin/media.service.ts +++ b/backend/src/admin/media.service.ts @@ -79,6 +79,28 @@ export class MediaService { "پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایل‌های اجرایی مسدود هستند).", ); } + + // SEC-01: Magic number verification for uploaded binary content + const buf = file.buffer; + if (!buf || buf.length < 4) { + throw new BadRequestException("فایل نامعتبر یا آسیب‌دیده است."); + } + + const isJpeg = buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff; + const isPng = buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47; + const isGif = buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46; // GIF87a or GIF89a + const isPdf = buf[0] === 0x25 && buf[1] === 0x50 && buf[2] === 0x44 && buf[3] === 0x46; // %PDF + const isWebp = + buf.length >= 12 && + buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 && // RIFF + buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50; // WEBP + + if (!isJpeg && !isPng && !isGif && !isPdf && !isWebp) { + throw new BadRequestException( + "محتوای باینری فایل با پسوند یا هدر ادعایی همخوانی ندارد (اعتبارسنجی امضای فایل رد شد).", + ); + } + const filename = `${uniqueSuffix}${ext}`; const filePath = path.join(uploadDir, filename); diff --git a/backend/src/common/services/tasks.module.ts b/backend/src/common/services/tasks.module.ts index 942ea2a4..bd8a4673 100644 --- a/backend/src/common/services/tasks.module.ts +++ b/backend/src/common/services/tasks.module.ts @@ -2,9 +2,10 @@ import { Module } from '@nestjs/common'; import { TasksService } from './tasks.service'; import { OrdersModule } from '../../orders/orders.module'; import { PaymentModule } from '../../payment/payment.module'; +import { RedisModule } from '../../redis/redis.module'; @Module({ - imports: [OrdersModule, PaymentModule], + imports: [OrdersModule, PaymentModule, RedisModule], providers: [TasksService], exports: [TasksService], }) diff --git a/backend/src/common/services/tasks.service.ts b/backend/src/common/services/tasks.service.ts index cff097f1..591ecc5f 100644 --- a/backend/src/common/services/tasks.service.ts +++ b/backend/src/common/services/tasks.service.ts @@ -1,5 +1,6 @@ import { Injectable, Logger, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common'; import { OrdersService } from '../../orders/orders.service'; +import { RedisService } from '../../redis/redis.service'; import { PaymentService } from '../../payment/payment.service'; @Injectable() @@ -11,6 +12,7 @@ export class TasksService implements OnApplicationBootstrap, OnApplicationShutdo constructor( private readonly ordersService: OrdersService, private readonly paymentService: PaymentService, + private readonly redisService: RedisService, ) {} onApplicationBootstrap() { @@ -18,6 +20,11 @@ export class TasksService implements OnApplicationBootstrap, OnApplicationShutdo // 1. Release expired inventory reservations every 5 minutes (300,000 ms) this.reservationTimer = setInterval(async () => { + const lockAcquired = await this.redisService.acquireLock('task:inventory_release', 240); + if (!lockAcquired) { + this.logger.debug('[Task:Inventory] Another instance holds the lock, skipping execution.'); + return; + } try { const result = await this.ordersService.releaseExpiredInventoryReservations(); if (result.releasedCount > 0) { @@ -25,11 +32,18 @@ export class TasksService implements OnApplicationBootstrap, OnApplicationShutdo } } catch (err) { this.logger.error('[Task:Inventory] Failed to release expired inventory reservations:', err); + } finally { + await this.redisService.releaseLock('task:inventory_release'); } }, 5 * 60 * 1000); // 2. Reconcile pending online payment transactions every 10 minutes (600,000 ms) this.reconciliationTimer = setInterval(async () => { + const lockAcquired = await this.redisService.acquireLock('task:payment_reconciliation', 540); + if (!lockAcquired) { + this.logger.debug('[Task:PaymentReconciliation] Another instance holds the lock, skipping execution.'); + return; + } try { const result = await this.paymentService.reconcilePendingTransactions(); if (result.total > 0) { @@ -37,6 +51,8 @@ export class TasksService implements OnApplicationBootstrap, OnApplicationShutdo } } catch (err) { this.logger.error('[Task:PaymentReconciliation] Failed to reconcile pending payments:', err); + } finally { + await this.redisService.releaseLock('task:payment_reconciliation'); } }, 10 * 60 * 1000); diff --git a/backend/src/orders/orders.service.ts b/backend/src/orders/orders.service.ts index 9f8b587d..c05ccbe6 100644 --- a/backend/src/orders/orders.service.ts +++ b/backend/src/orders/orders.service.ts @@ -346,17 +346,18 @@ export class OrdersService { // Deduct inventory immediately for non-online orders (card to card) if (!isOnline) { for (const item of createOrderDto.items) { - const updated = await tx.product.update({ - where: { id: item.productId }, - data: { - stock: { decrement: item.quantity }, - }, - }); - if (updated.stock <= 0) { - await tx.product.update({ - where: { id: item.productId }, - data: { stockStatus: "OUT_OF_STOCK" }, - }); + // BE-05: Atomic decrement with inventory constraint guard + const updateCount = await tx.$executeRaw` + UPDATE products + SET stock = stock - ${item.quantity}, + stock_status = CASE WHEN stock - ${item.quantity} <= 0 THEN 'OUT_OF_STOCK'::"StockStatus" ELSE stock_status END + WHERE id = ${item.productId}::uuid AND stock >= ${item.quantity} + `; + + if (updateCount === 0) { + throw new BadRequestException( + `موجودی محصول مورد نظر در حین ثبت نهایی به پایان رسید یا کمتر از تعداد درخواستی شد.` + ); } } } diff --git a/backend/src/payment/payment.service.ts b/backend/src/payment/payment.service.ts index 27b54976..18a53efd 100644 --- a/backend/src/payment/payment.service.ts +++ b/backend/src/payment/payment.service.ts @@ -447,17 +447,18 @@ export class PaymentService { if (orderWithItems?.orderItems) { for (const item of orderWithItems.orderItems) { if (item.productId) { - const updated = await tx.product.update({ - where: { id: item.productId }, - data: { - stock: { decrement: item.quantity }, - }, - }); - if (updated.stock <= 0) { - await tx.product.update({ - where: { id: item.productId }, - data: { stockStatus: "OUT_OF_STOCK" }, - }); + // BE-05: Atomic decrement with inventory constraint guard + const updateCount = await tx.$executeRaw` + UPDATE products + SET stock = stock - ${item.quantity}, + stock_status = CASE WHEN stock - ${item.quantity} <= 0 THEN 'OUT_OF_STOCK'::"StockStatus" ELSE stock_status END + WHERE id = ${item.productId}::uuid AND stock >= ${item.quantity} + `; + + if (updateCount === 0) { + this.logger.error( + `[CriticalInventoryAlert] Product ${item.productId} lacked sufficient stock for paid order ${transaction.orderId} (requested ${item.quantity}). Manual inventory check required.` + ); } } } diff --git a/backend/src/prisma/prisma.service.ts b/backend/src/prisma/prisma.service.ts index dc84588a..b58d5d90 100644 --- a/backend/src/prisma/prisma.service.ts +++ b/backend/src/prisma/prisma.service.ts @@ -1,13 +1,37 @@ import { Injectable, OnModuleInit, OnModuleDestroy } from "@nestjs/common"; import { PrismaClient } from "@prisma/client"; +import { Logger } from "@nestjs/common"; + @Injectable() export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy { + private readonly logger = new Logger(PrismaService.name); + + constructor() { + super({ + log: [ + { emit: "event", level: "query" }, + { emit: "stdout", level: "error" }, + { emit: "stdout", level: "warn" }, + ], + }); + } + async onModuleInit() { await this.$connect(); + + // BE-07: Slow query logging interceptor (> 300ms) + (this as any).$on("query", (e: any) => { + if (e.duration >= 300) { + this.logger.warn( + `[SlowQueryAlert] Duration: ${e.duration}ms | Target: ${e.target} | Query: ${e.query.substring(0, 300)}...`, + ); + } + }); + await this.ensureTablesExist(); } diff --git a/backend/src/redis/redis.service.ts b/backend/src/redis/redis.service.ts index 70aa89d5..c3106138 100644 --- a/backend/src/redis/redis.service.ts +++ b/backend/src/redis/redis.service.ts @@ -45,4 +45,20 @@ export class RedisService implements OnModuleInit, OnModuleDestroy { async ttl(key: string): Promise { return this.client.ttl(key); } + + /** + * Acquire a distributed lock using Redis SET NX EX + * Returns true if lock acquired, false otherwise + */ + async acquireLock(key: string, ttlSeconds: number = 60): Promise { + const res = await this.client.set(`lock:${key}`, "1", "EX", ttlSeconds, "NX"); + return res === "OK"; + } + + /** + * Release a distributed lock + */ + async releaseLock(key: string): Promise { + await this.client.del(`lock:${key}`); + } }