← All tracks
FoundationsBusiness Logic10 labsIntermediate6h practice

Business Logic: The Bug in the Rule

Security is also the set of invariants the business promises.

“Every line of code was correct. The business rule was not.”

CWE-840OWASP Top 10 A04:2021OWASP ASVS 5.1
The mental model
A workflow is a story with invariants: a price cannot go negative, a coupon is used once, a refund cannot exceed a payment. The attacker changes the story, not the syntax.

The server trusts a client-supplied price, quantity, currency or status. It checks each step in isolation but not the sequence or the final invariant. Negative values, replay and skipped steps turn a valid workflow into a loss.

We test inputs, not the story the workflow tells. Attackers ask what happens if the story takes a different path.

Threat model

What is actually at stake?

Before touching a payload, map the assets, the actors and the boundary that is supposed to protect them. A finding only becomes a vulnerability when you can connect the failed boundary to a real asset.

Assets

  • Money, credits and gift balances
  • Inventory and reservation capacity
  • Discounts, refunds and subscription state
  • Approval and shipping workflows

Actors

  • Customer seeking an unintended discount
  • Organized abuser running many accounts
  • Insider who knows workflow edge cases
  • Automated client replaying requests

Trust boundaries

  • Client price to server price
  • Cart state to order state
  • One-time action to repeated action
  • Currency and unit conversion
  • Approval threshold to approval authority

Abuse cases

  • Submit a negative quantity so the total reverses
  • Reuse a one-time coupon without an atomic redemption
  • Race two refunds before the balance updates
  • Exploit rounding or currency confusion
  • Skip a required state transition
PrerequisitesBasic commerce and account workflowsState machines and invariantsReading a request body and server response
Request anatomy

Follow the decision, not the payload

Every family has a moment where trusted data becomes an authorization, parsing or state decision. Learn to point at that moment in the request path.

  1. 01

    Model the workflow

    List states, allowed transitions, actors and invariants. A business rule is a property of the system, not a field validator.

  2. 02

    Accept input

    Receive quantities, prices, coupons and identifiers, but treat every client value as a proposal.

  3. 03

    Recompute

    Derive prices, totals, eligibility and limits on the server from trusted data.

  4. 04

    Commit atomically

    Check and consume one-time resources in a transaction so concurrent requests cannot both win.

  5. 05

    Reconcile

    Record the economic event and monitor for impossible states such as negative balances or duplicate redemptions.

Case study

The gift card that could be spent twice

Composite case study from public business-logic disclosures
Context

A composite case based on a common retail pattern: a gift card balance was checked, then debited in a separate step, with no row lock or idempotency key.

Discovery

A tester sent two redemption requests in parallel. Both read the same available balance before either wrote the debit, and both orders were accepted.

Impact

The customer received goods worth more than the card balance. At scale, the same pattern becomes a direct financial loss and a reconciliation failure.

Root cause

The check and the debit were not atomic, and the endpoint had no idempotency key. The application validated each request in isolation but not the concurrent history.

Fix

Perform the balance check and debit in one transaction with a conditional update or row lock, require an idempotency key, and reconcile ledger entries continuously.

Read it as a chain: discovery → failed decision → impact → fix. Then ask which link would have broken earliest.

Attacker lens

A repeatable testing sequence

  1. Map the happy path and every value the client can change.
  2. Try negative, zero, huge and fractional values.
  3. Replay one-time actions and skip or reorder steps.
  4. Look for the invariant the server never re-checks.

Where smart people get fooled

  • Valid input syntax does not mean a valid business state.
  • The UI disables a button; the API does not.
  • A single request test misses replay and race cases.
Detection engineering

What would the logs show?

A control is stronger when someone can see it fail. These signals are starting points for a detection rule, not a complete SIEM use case.

  • Orders or refunds with negative, zero or unusually large values
  • The same coupon, gift card or idempotency key used more than once
  • Multiple requests for one workflow arriving within milliseconds
  • Balances or inventory below zero
  • State transitions that skip a required approval or payment step
Starter query
index=payments sourcetype=ledger | stats count sum(amount) by account_id, idempotency_key | where count > 1 OR sum(amount) < 0 | join account_id [search index=accounts sourcetype=balances | where balance < 0]
The defender's move

Fix the decision, then prove it stays fixed

  • Enforce invariants server-side at the final commit.
  • Use state machines, idempotency keys and explicit limits.
  • Recompute prices and permissions from trusted data, never from the client.
Vulnerable patternsql
SELECT balance FROM gift_cards WHERE code = ?;
-- application checks balance, then later:
UPDATE gift_cards SET balance = balance - ? WHERE code = ?;
Safer patternsql
UPDATE gift_cards
SET balance = balance - :amount
WHERE code = :code AND balance >= :amount
RETURNING balance;
-- zero rows means insufficient funds; commit once

Make the invariant part of the write. A conditional update is atomic; a read followed by a separate write is a race waiting to happen.

Regression tests a reviewer would ask for

Negative value

GivenA checkout accepts quantity and price

WhenQuantity is -1 or price is 0

ThenThe server rejects the request or recomputes a valid non-negative total

Parallel redemption

GivenA one-time coupon has one remaining use

WhenTwo requests redeem it simultaneously

ThenExactly one succeeds and the other receives a deterministic failure

Currency and rounding

GivenThe client can submit an amount and currency

WhenThe amount is in the wrong unit or uses a different currency

ThenThe server normalizes to minor units and rejects mismatches

State transition

GivenAn order must be paid before it can ship

WhenA client calls the shipping transition directly

ThenThe transition is refused and the order state is unchanged

False positives

What this finding is not

Strong testers kill their own findings before someone else does. These are the shortcuts that turn a real bug into a weak report — or a false alarm into a wasted escalation.

  • The form rejects negative numbers: test the API directly and try zero, fractional, very large and replayed values.
  • The total looks correct in the UI: the server may trust a hidden price or discount field.
  • The coupon fails on the second attempt: test two parallel attempts, not two sequential ones.
  • A refund is capped: test multiple partial refunds and different currencies or units.
Working vocabulary

Terms you should be able to use precisely

Invariant
A property that must remain true across every valid state, such as a balance never going below zero.
Idempotency key
A client-supplied identifier that lets the server recognize and deduplicate a repeated operation.
TOCTOU
Time-of-check to time-of-use: a condition changes between the check and the action.
State machine
An explicit model of allowed states and transitions for a workflow.
Reconciliation
Comparing independent records, such as orders and ledger entries, to detect impossible or missing events.
Economic denial of service
Abuse that creates cost or loss without necessarily stealing data, such as unlimited refunds or resource consumption.
Interview drill

Answer these without reciting a payload

Why can't business-logic abuse be fixed by a WAF?

The requests are syntactically valid and often use legitimate endpoints in an unexpected order or combination. The defense must understand the workflow invariants and enforce them atomically.

How do you test for a race in a one-time action?

Send multiple equivalent requests in parallel, then inspect the final state and ledger. Sequential retries do not exercise the same window.

What is the difference between validation and an invariant?

Validation checks one input against a rule. An invariant is a property the whole system must preserve across all transitions, including concurrent ones.

Knowledge check

Can you separate the mechanism from the payload?

Four questions, graded on the server. Answers and explanations are released only after you submit, and signed-in learners keep a best score.

4 questions
01A checkout accepts quantity=-1 and credits the account. What is the root cause?
02Which control best prevents double-spending a gift card?
03Why is testing a coupon twice sequentially insufficient?
04What is the strongest regression test for a refund workflow?
الخلاصة الموسّعة
لماذا هذا مهم؟

ثغرات منطق العمل لا تُكسر بمدخل غريب فقط، بل بترتيب أو تكرار أو قيمة تجعل النظام يصل إلى حالة كان يجب أن تكون مستحيلة.

لا تثق بالسعر أو الكمية أو حالة السلة القادمة من العميل؛ أعد حسابها على الخادم. واجعل العمليات المالية ذرّية: التحقق والخصم في خطوة واحدة، مع مفتاح تكرار يمنع التنفيذ المزدوج. راقب الحالات المستحيلة مثل رصيد سالب أو كوبون استُخدم مرتين.

What must always be true after this step, regardless of input order?