Business Logic Security

Scanners can't find these bugs, because the code "works". The flaw is in the logic.

Common flaws

FlawExample
Trusting client pricesClient sends { price: 1 } for a ₹50,000 phone
Negative valuesTransfer -1000 → money moves the wrong way
Race conditionsUse one coupon 10 times with parallel requests
Skipping stepsCall /checkout/confirm without paying
Double chargingThe user double-clicks or the network retries the request
Unlimited actionsUnlimited free trials with new emails, referral abuse

Packages

PackageUse
redlock / ioredisDistributed locks
DB transactions (prisma.$transaction, pg BEGIN)Atomic changes
decimal.js / integer paiseMoney math without float errors

❌ Vulnerable

app.post('/order', async (req, res) => {
  await Order.create({ items: req.body.items, total: req.body.total }); // trusts the client
});

// Race: two requests both pass the check before either one updates
if (coupon.used < coupon.limit) { await useCoupon(); coupon.used++; await coupon.save(); }

✅ Secure

// Recalculate everything on the server
const products = await Product.find({ _id: { $in: req.body.items.map(i => i.id) } });
const total = req.body.items.reduce((sum, i) => {
  const p = products.find(p => p.id === i.id);
  if (!p || !Number.isInteger(i.qty) || i.qty < 1 || i.qty > 10) throw badRequest();
  return sum + p.pricePaise * i.qty; // integer paise, no floats
}, 0);

// Atomic check-and-update (no race)
const r = await db.query(
  'UPDATE coupons SET used = used + 1 WHERE code = $1 AND used < max_uses RETURNING id',
  [code]
);
if (r.rowCount === 0) return res.status(409).json({ error: 'Coupon not valid' });

Idempotency keys (payments, orders)

// The client sends a unique Idempotency-Key header per action
const key = req.get('Idempotency-Key');
const existing = await Idem.findOne({ key, userId: req.user.id });
if (existing) return res.status(existing.status).json(existing.body); // replay the saved response
// ...process, then save { key, userId, status, body } with a UNIQUE index on (key, userId)

Checklist

  • The server computes prices, totals, discounts and permissions
  • Validate ranges (no negative amounts or quantities)
  • Atomic updates / transactions / locks for counters and balances
  • Idempotency keys on payment and order endpoints
  • A state machine for multi-step flows (each step checks the previous one)
  • Verify payment webhooks by signature and amount, not by a client redirect