Skip to content

fix:Security fixes, Implement idempotency handling and database constraints for orders - #14

Merged
SH-AHD merged 3 commits into
masterfrom
fix/security-fixes-and-idempotency
Nov 1, 2026
Merged

SH-AHD merged 3 commits into
masterfrom
fix/security-fixes-and-idempotency

Conversation

@SH-AHD

@SH-AHD SH-AHD commented Oct 20, 2026

Copy link
Copy Markdown
Collaborator

This PR addresses ** Immediate Security Fixes**, closing critical exploitable vulnerabilities in the current main branch and hardening the backend before any new features are added. Changes span authentication, database constraints, idempotency guarantees, schema indexes, and a comprehensive new test suite.


1. Registration Role Injection — Fixed

Problem: The previous implementation allowed a client to pass "role": "Admin" in the registration body and get an Admin account created — a classic privilege escalation vulnerability.

Fix (two-layer defence):

  • Controller (authController.js): The register handler now hardcodes role: 'Buyer' into the safeUserData object before passing it to the service. Any incoming role field from the request body is completely ignored.
  • Service (authService.js): createNewUser independently forces role: 'Buyer' inside the data block passed to Prisma, making the fix hold even if the controller is bypassed or called directly.

Regression tests added (authService.test.js):

  • POST /auth/register with "role": "Admin" → created user has role: 'Buyer' ✅
  • Service-level test: createNewUser({ role: 'Admin' }) → stored role is 'Buyer' ✅

2. Enforce isActive on Login — Fixed

Problem: Soft-deleted users (where isActive === false) could still log in successfully, bypassing soft-deletion entirely.

Fix (authService.js — loginUser):

// Before
if (!user) throw new Error('INVALID_CREDENTIALS');

// After
if (!user || user.isActive === false) throw new Error('INVALID_CREDENTIALS');

The same generic INVALID_CREDENTIALS error is thrown in both cases to prevent account-state leakage (i.e., an attacker cannot distinguish between "wrong email" and "account disabled").

Tests added (authService.test.js):

  • Soft-deleted user (isActive: false) cannot log in → receives 401 Invalid email or password ✅
  • Active user with wrong password → same 401 response (no info leak) ✅

3. Database Migration — Wallet CHECK Constraints & FK Indexes

Migration file: 20261019081851_add_fk_indexes_and_wallet_check_constraints

CHECK Constraints

ALTER TABLE "wallets" ADD CONSTRAINT "real_balance_non_negative" CHECK ("real_balance" >= 0);
ALTER TABLE "wallets" ADD CONSTRAINT "promo_balance_non_negative" CHECK ("promo_balance" >= 0);

The database now enforces that wallet balances can never go negative, acting as a last-resort safety net even if application logic has a bug.

Foreign-Key Indexes

CREATE INDEX "notifications_user_id_idx"    ON "notifications"("user_id");
CREATE INDEX "order_items_order_id_idx"     ON "order_items"("order_id");
CREATE INDEX "order_items_product_id_idx"   ON "order_items"("product_id");
CREATE INDEX "orders_buyer_id_idx"          ON "orders"("buyer_id");
CREATE INDEX "products_seller_id_idx"       ON "products"("seller_id");
CREATE INDEX "transactions_wallet_id_idx"   ON "transactions"("wallet_id");

All FK columns that are frequently used in WHERE clauses now have indexes, preventing full-table scans on joins and filters.

Prisma Schema: Added matching @@index decorators to keep the schema in sync with the migration.


4. Idempotency Utility — Extracted & Hardened

New file: src/utils/idempotency.js — withIdempotency(tx, key, fn, options)

Problem: Idempotency logic was duplicated and inconsistent across walletService and orderService, with no protection against race conditions.

Solution: A single reusable wrapper that:

  1. Checks for an existing transaction record by idempotencyKey before executing.
  2. Runs fn() inside the provided Prisma transaction.
  3. Catches Prisma P2002 (unique constraint violation) — the race-condition signal — and re-fetches the winning record instead of throwing, returning alreadyProcessed: true.
  4. Supports an optional validateExisting hook for caller-specific checks on replayed responses.

walletService.js and orderService.js were fully refactored to use withIdempotency, removing ~250 lines of duplicated, fragile logic.

Concurrent race-condition test (wallet.test.js):

  • Simulates a P2002 collision during a concurrent deposit → returns alreadyProcessed: true with the winning record's balance

5. New & Expanded Test Suite

Test File What's Covered
authService.test.js Role injection prevention (controller + service level), isActive enforcement, inactive user login, wrong password, JWT signing
wallet.test.js P2002 race-condition idempotency collision test
orderService.test.js Idempotency replay, duplicate order prevention
productService.test.js Product service edge-cases post-refactor

Total tests: 63 passing, 0 failing ✅


Checklist

  • Role injection blocked at controller and service layer
  • Soft-deleted users cannot log in (same error message — no state leakage)
  • DB-level CHECK constraints prevent negative balances
  • FK indexes added for query performance
  • Idempotency race condition (P2002) handled gracefully
  • All changes covered by unit tests
  • 63/63 tests passing

@SH-AHD
SH-AHD requested a review from KhaledSayed04 October 20, 2026 06:55

@KhaledSayed04 KhaledSayed04 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Summary
Solid PR — migration is clean, isActive and zero-value validation are correct, tests cover the right behaviors. Two blockers, three inline fixes, one deferral.

Blockers (both in idempotency.js)

  1. P2002 retry runs on the aborted transaction — never fires in prod, so races return 500 instead of alreadyProcessed: true.
  2. Cross-op key reuse returns false success. Two fixes proposed — schema-level composite or code-level expectedCategory. Your call.

Inline fixes

  • orderService.js — cancelOrder refund key not scoped to order.
  • orderController.js — P2004 message now covers wallet constraints too.
  • authController.js — revert force-Buyer; master's safeRole already blocks Admin injection and preserves the seller path.

Deferred
isActive not enforced on token validation — deactivated users with a live token can act until expiry (1h). Resolves in Phase 4.

Comment thread Backend/src/utils/idempotency.js Resolved
Comment thread Backend/src/utils/idempotency.js Resolved
Comment thread Backend/src/services/orderService.js Resolved
Comment thread Backend/tests/orderService.test.js Resolved
…straint, scoped refund key, error handling cleanup

- fix(idempotency): move $transaction inside withIdempotency so P2002 retry
  runs on a fresh prisma connection, not the aborted tx
- fix(idempotency): add `category` param + @@unique([idempotencyKey, category])
  to prevent cross-op key reuse returning false success
- fix(orderService): scope refund idempotency key to orderId to prevent
  cancel(order5) colliding with cancel(order7) using same base key
- fix(orderController): simplify P2004/P2010 to single honest message;
  add typed INSUFFICIENT_BALANCE error for stable wallet-specific UX
- fix(authController): revert force-Buyer to safeRole to preserve Seller path
- test(orderService): update mock strategy — fetchExisting() now targets
  top-level prisma mock, not tx mock; update P2002 meta for composite constraint
- chore: remove dead validateExisting option from processOrder (covered by category scoping)
@SH-AHD

SH-AHD commented Oct 22, 2026

Copy link
Copy Markdown
Collaborator Author

Thanks for the great feedback, @KhaledSayed04! All comments have been addressed. The PR has been updated and is ready for another look!

@SH-AHD
SH-AHD requested a review from KhaledSayed04 October 22, 2026 09:27
…ected errors

- authService.createNewUser: pass through controller-sanitized role instead of
  forcing 'Buyer', unblocking Seller registration
- orderController: drop dead INSUFFICIENT_BALANCE branch and 400-everything
  fallthrough; match known business errors, log and return 500 for the rest
- walletController.getAllWalletsForAdmin: empty list returns 200 with count 0
  instead of 404; log unexpected errors in catch for observability
- authService.test: replace service-level force-Buyer test with controller-level
  preserve-Seller test; policy is controller-only now

@KhaledSayed04 KhaledSayed04 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!

@SH-AHD
SH-AHD merged commit a65606b into master Nov 1, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants