Repository navigation
fix:Security fixes, Implement idempotency handling and database constraints for orders - #14
Merged
Merged
Conversation
…nts for orders and transactions
KhaledSayed04
requested changes
Oct 20, 2026
KhaledSayed04
left a comment
Collaborator
There was a problem hiding this comment.
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)
- P2002 retry runs on the aborted transaction — never fires in prod, so races return 500 instead of
alreadyProcessed: true. - Cross-op key reuse returns false success. Two fixes proposed — schema-level composite or code-level
expectedCategory. Your call.
Inline fixes
orderService.js—cancelOrderrefund key not scoped to order.orderController.js— P2004 message now covers wallet constraints too.authController.js— revert force-Buyer; master'ssafeRolealready 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.
…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)
Collaborator
Author
|
Thanks for the great feedback, @KhaledSayed04! All comments have been addressed. The PR has been updated and is ready for another look! |
…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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR addresses ** Immediate Security Fixes**, closing critical exploitable vulnerabilities in the current
mainbranch 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):
authController.js): Theregisterhandler now hardcodesrole: 'Buyer'into thesafeUserDataobject before passing it to the service. Any incomingrolefield from the request body is completely ignored.authService.js):createNewUserindependently forcesrole: 'Buyer'inside thedatablock passed to Prisma, making the fix hold even if the controller is bypassed or called directly.Regression tests added (
authService.test.js):POST /auth/registerwith"role": "Admin"→ created user hasrole: 'Buyer'✅createNewUser({ role: 'Admin' })→ stored role is'Buyer'✅2. Enforce
isActiveon Login — FixedProblem: Soft-deleted users (where
isActive === false) could still log in successfully, bypassing soft-deletion entirely.Fix (
authService.js—loginUser):The same generic
INVALID_CREDENTIALSerror 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):isActive: false) cannot log in → receives401 Invalid email or password✅401response (no info leak) ✅3. Database Migration — Wallet CHECK Constraints & FK Indexes
Migration file:
20261019081851_add_fk_indexes_and_wallet_check_constraintsCHECK Constraints
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
All FK columns that are frequently used in
WHEREclauses now have indexes, preventing full-table scans on joins and filters.Prisma Schema: Added matching
@@indexdecorators 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
walletServiceandorderService, with no protection against race conditions.Solution: A single reusable wrapper that:
idempotencyKeybefore executing.fn()inside the provided Prisma transaction.P2002(unique constraint violation) — the race-condition signal — and re-fetches the winning record instead of throwing, returningalreadyProcessed: true.validateExistinghook for caller-specific checks on replayed responses.walletService.jsandorderService.jswere fully refactored to usewithIdempotency, removing ~250 lines of duplicated, fragile logic.Concurrent race-condition test (
wallet.test.js):P2002collision during a concurrent deposit → returnsalreadyProcessed: truewith the winning record's balance5. New & Expanded Test Suite
authService.test.jsisActiveenforcement, inactive user login, wrong password, JWT signingwallet.test.jsorderService.test.jsproductService.test.jsTotal tests: 63 passing, 0 failing ✅
Checklist
CHECKconstraints prevent negative balancesP2002) handled gracefully