Gamify icon indicating copy to clipboard operation
Gamify copied to clipboard

[BUG]:Shop purchase endpoint has a race condition that allows overselling limited stock items

Open vedikathalkar opened this issue 5 months ago • 4 comments

In server/controllers/shopController.js, the purchaseItem function fetches the item with findById, checks item.stock === 0 to decide if it is out of stock, then later in the same function decrements item.stock and calls item.save().

These are separate steps with no locking between them, so under concurrent requests for the same item, multiple purchases can read the same stock value before any of them save their update. Each request individually passes the out of stock check and proceeds to debit points and create a purchase record, meaning a limited stock item with only one unit left can be sold to multiple users at once.

This is the same category of problem that debitPoints in server/services/pointService.js already solves correctly for point balances, using an atomic findOneAndUpdate with a points greater than or equal to amount condition so a user can never spend points they do not have even under concurrent requests. The shop stock check does not use the same pattern, so it remains vulnerable to overselling.

Suggested fix: change the stock check and decrement in purchaseItem to a single atomic operation, for example a findOneAndUpdate on ShopItem with a condition like stock greater than 0 or stock equal to negative 1 for unlimited items, combined with the decrement in the same call, mirroring the approach already used in debitPoints.

vedikathalkar avatar Jun 25 '26 11:06 vedikathalkar

Hi @DeadIndian, I'm a GSSoC 26 contributor and would like to work on this issue. I have a clear fix in mind that mirrors the atomic pattern already used in debitPoints. Could I get this assigned to me?

vedikathalkar avatar Jun 25 '26 11:06 vedikathalkar

Thank you for raising this issue!

We'll review it as soon as possible. We truly appreciate your contributions! ✨

Meanwhile make sure you've visited the README.md, CONTRIBUTING.md, and CODE_OF_CONDUCT.md before creating a PR for this. Also, please do NOT create a PR until this issue has been assigned to you. 😊

github-actions[bot] avatar Jun 25 '26 11:06 github-actions[bot]

Hi, I'd like to work on this issue. I'll fix the race condition in purchaseItem by replacing the read-then-write stock check with a single atomic findOneAndUpdate (stock > 0 or -1 for unlimited), mirroring the existing debitPoints pattern. Could you please assign it to me?

/assign /claim

anshul23102 avatar Jun 29 '26 07:06 anshul23102

Hi,could you assign this issue to me?

Keshavsspppp avatar Jul 03 '26 22:07 Keshavsspppp