Business logic vulnerabilities: write the rules down as invariants, then try to break them
A business logic vulnerability is an application doing exactly what its code says, where the code does not say what the business means.
This guide explains why these flaws pass the checks a scanner makes, how to find the rules worth protecting, how to write each rule as an invariant a test can check, and where the enforcement belongs. It comes with a worked booking-and-refund state machine, eleven abuse cases played with two accounts, and a local lab with a regression test.
In this guide
Booking-and-refund state machine, abuse cases and lab
An illustration written for this page, not client code. Parts 1 to 4 are a booking-and-refund state machine for an invented tour operator, seven invariants written as checks on stored records, eleven abuse cases played with a customer and a staff approver (skipped steps, replayed approvals, limit changes, operations out of order and self-approval), each with its expected refusal, and the evidence to keep.
How to use itHide the instructions
Parts 5 to 8 hold a Node.js lab with nothing to install, its output recorded on Node.js 26.0.0, and a regression test that fails on the careless version and passes on the careful one.
business-logic-vulnerabilities.txt
BOOKING-AND-REFUND STATE MACHINE, INVARIANTS, ABUSE CASES AND LAB
Written for this page. Parts 1 to 4 work without the lab: a state machine for an invented tour operator's booking and refund flow, seven invariants, eleven abuse cases played with two accounts, and the evidence to keep. Rewrite them for your own flow before you use them. Parts 5 to 8 are the lab: an illustration that plays the same cases against a careless and a careful version of the invented service, on your own machine.
Use the cases only on an application you own, or one you are authorised in writing to test, with test accounts and test money, on staging where you can. Leave real customers' bookings, payments and cards out of it.
==== PART 1. THE STATE MACHINE ====
The invented business sells seats on a tour. An adult seat is 6000 cents and a child seat 3500 cents. A booking holds 1 to 8 seats, at least 1 of them an adult. Amounts are whole cents. Two roles: a customer, who owns their bookings, and a staff approver.
STATES
draft Created. Seats can still change.
payment_pending Checked out. The amount due is fixed.
paid The amount due has been captured.
confirmed The seats are confirmed.
refund_requested A refund has been asked for.
refund_approved A staff approver has approved it.
refunded Everything paid has been refunded.
cancelled Closed. No more money moves on it.
TRANSITIONS
Each line: the action, the states it may start from, the state it leads to, who may take it, and the rule checked before it runs.
create (new booking) -> draft. Customer. Seats in range.
edit draft -> draft. Customer. Seats in range.
checkout draft -> payment_pending. Customer. Fixes the amount due from the stored seats and the published seat prices.
pay payment_pending -> paid. Customer (see note). The payment equals the amount due, and the amount due still equals the seats' total.
confirm paid -> confirmed. Customer. Payments captured equal the total and the amount due.
requestRefund confirmed -> refund_requested. Customer, or staff on the customer's behalf. At least 1 cent, at most paid minus refunded.
approveRefund refund_requested -> refund_approved. Approver. The approver is not the requester. Creates an approval bound to one booking, one amount and one use.
claimRefund refund_approved -> refunded, or back to confirmed while part of the payment is still unrefunded. Customer. The approval was given for this booking, is unused, matches any amount sent, and is within paid minus refunded.
cancel draft, payment_pending or confirmed -> cancelled. Customer. Refunds whatever is left: paid minus refunded, from stored records.
Every other action, from every other state, is refused.
Note on pay: in the lab, the customer's pay request stands in for a captured card payment and moves no money anywhere. In your own service, take the capture from your payment provider's confirmation on the server, not from anything the browser sends.
==== PART 2. THE INVARIANTS ====
Each invariant is a sentence about stored records that a test can check after any request. "Corresponds to" names the WSTG v4.2 test or ASVS 5.0 requirement the rule follows, or says the rule is this page's own.
I1 Seat counts and amounts are whole numbers in range: at least 1 adult, 0 or more children, 8 seats at most, and every payment, refund request and refund at least 1 cent.
Check: every booking's seats; every payment, refund request and refund amount.
Corresponds to: WSTG-BUSL-01; ASVS 2.2.1 (Level 1).
I2 A booking is confirmed only when the payments captured before confirmation equal the total its seats come to.
Check: for each confirmed booking, the sum of payments recorded before confirmation, against seats times seat prices.
Corresponds to: WSTG-BUSL-06; ASVS 2.3.1 (Level 1).
I3 The total refunded on a booking never exceeds the total paid on it.
Check: sum of refunds against sum of payments, per booking, from the stored records.
Corresponds to: this page's own limit. ASVS 2.3.2 (Level 2) asks that business logic limits are implemented per the application's documentation.
I4 An approval is used once, and only for the booking and the amount it was given for.
Check: refunds per approval (at most 1); each refund's booking and amount against its approval's.
Corresponds to: WSTG-BUSL-05 for the single use. The binding to booking and amount is this page's own.
I5 The person who approves a refund is not the person who requested it.
Check: each approval's approver against its request's requester.
Corresponds to: ASVS 2.3.5 (Level 3), multi-user approval for high-value business logic flows.
I6 The amount read at checkout is the amount enforced at the end: once checkout has fixed the amount due, the seats still come to that amount.
Check: for each checked-out booking, seats times seat prices against the amount due fixed at checkout.
Corresponds to: WSTG-BUSL-03.
I7 A cancelled booking takes no further payments or refunds, and stays cancelled.
Check: no payment or refund recorded on a booking after its cancellation, and its state still cancelled.
Corresponds to: this page's own wording. WSTG-BUSL-06 covers steps taken out of order.
==== PART 3. THE ABUSE CASES ====
Two accounts: customer-1 (customer) and approver-1 (staff approver). Each case takes the normal flow to its starting point (setup), then sends the abuse requests straight to the API. After every case, check all seven invariants, not only the one the case attacks.
SKIPPED STEPS
A1 Request the last step directly.
Attacks I2. Corresponds to WSTG-BUSL-06; ASVS 2.3.1.
Start: customer-1 has draft booking b1, 2 adults.
Abuse: customer-1 POST /bookings/b1/confirm
Expected refusal: 409 on confirm. b1 stays a draft.
A2 Confirm without paying.
Attacks I2. Corresponds to WSTG-BUSL-06; ASVS 2.3.1.
Start: b1, 2 adults, checked out (payment_pending, 12000 cents due), nothing paid.
Abuse: customer-1 POST /bookings/b1/confirm
Expected refusal: 409 on confirm. b1 stays in payment_pending.
REPLAYED APPROVALS
A3 The same approval sent twice.
Attacks I4. Corresponds to WSTG-BUSL-05.
Start: b1 confirmed and paid (12000). Approval ap1 (3000) already claimed; a second request for 2000 approved as ap2.
Abuse: customer-1 POST /bookings/b1/refunds {"approvalId":"ap1"}
Expected refusal: 409, ap1 has already been used. One refund on ap1.
A4 An approval for one booking used on another.
Attacks I4. This page's own case.
Start: b1 and b2 confirmed and paid. ap1 approves 3000 on b1; ap2 approves 1000 on b2.
Abuse: customer-1 POST /bookings/b2/refunds {"approvalId":"ap1"}
Expected refusal: 409, ap1 was given for b1. No refund on b2 from ap1.
LIMIT CHANGES
A5 The amount edited after approval.
Attacks I4. Corresponds to WSTG-BUSL-03.
Start: b1 confirmed and paid (12000). ap1 approves 3000.
Abuse: customer-1 POST /bookings/b1/refunds {"approvalId":"ap1","amountCents":12000}
Expected refusal: 409, ap1 is for 3000. Nothing refunded.
A6 A zero or negative value.
Attacks I1. Corresponds to WSTG-BUSL-01; ASVS 2.2.1.
Start: no bookings.
Abuse: customer-1 POST /bookings {"adults":0,"children":0}, then {"adults":3,"children":-2}, then checkout, pay and confirm on the second.
Expected refusal: 422 on both bookings. Nothing else exists to pay for.
A7 A limit changed mid-flow: seats changed after checkout.
Attacks I6. Corresponds to WSTG-BUSL-03.
Start: b1, 2 adults, checked out with 12000 due.
Abuse: customer-1 PATCH /bookings/b1 {"adults":6,"children":0}, then pay 12000, then confirm.
Expected refusal: 409 on the change. b1 is then paid and confirmed for 2 adults.
OPERATIONS OUT OF ORDER
A8 Refund before capture.
Attacks I3. Corresponds to WSTG-BUSL-06; ASVS 2.3.1.
Start: b1 checked out, nothing paid.
Abuse: customer-1 asks for a 12000 refund, approver-1 approves r1, customer-1 claims ap1.
Expected refusal: 409 on the refund request. Nothing refunded.
A9 Cancel after refund.
Attacks I3. Corresponds to WSTG-BUSL-06; ASVS 2.3.1.
Start: b1 paid 12000, then refunded 12000 through an approval.
Abuse: customer-1 POST /bookings/b1/cancel
Expected refusal: 409 on cancel. Refunded stays at 12000.
A10 Pay after cancel.
Attacks I7. Corresponds to WSTG-BUSL-06; ASVS 2.3.1.
Start: b1 checked out, then cancelled with nothing paid.
Abuse: customer-1 POST /bookings/b1/pay {"amountCents":12000}, then POST /bookings/b1/confirm
Expected refusal: 409 on pay and on confirm. b1 stays cancelled with nothing paid.
ROLE CONFUSION INSIDE THE FLOW
A11 The requester approves their own refund.
Attacks I5. Corresponds to ASVS 2.3.5.
Start: b1 confirmed and paid (12000).
Abuse: approver-1 raises a 12000 refund request on b1 for the customer, approver-1 approves r1, customer-1 claims ap1.
Expected refusal: 403 on the approval. Nothing refunded.
==== PART 4. EVIDENCE TO KEEP FOR EVERY CASE, PASS OR FAIL ====
- The build or commit, the environment and the date.
- The account label for each request, such as customer-1. Not the session token.
- Each request: method, path and body.
- Each response: status and body.
- The state before and after of every record the case touched, read from the database rather than the screen: the booking's state and seats, the amount due, the sum of payments, the sum of refunds, and each approval with whether it has been used.
- Which invariants held after the case and which broke, with the record ids.
- The log entry the service wrote for each refused step.
- What the case created, and how it was cleaned up.
==== PART 5. THE LAB (AN ILLUSTRATION) ====
The tour operator, its two accounts, its bookings and its money are invented. All money is counted in whole cents and held in memory, and nothing is charged or paid anywhere. The lab shows the pattern. It does not model any real payment provider's behaviour.
The service runs as its own process. It listens only on 127.0.0.1, on a port the operating system assigns because the lab asks for port 0, and the runner stops it by its process id when a run ends. The lab imports only node:child_process, node:crypto, node:http, node:url, node:assert/strict and node:test, and installs no packages.
Written and run on: Node.js 26.0.0 on macOS. Every output below was copied from that run's captured output by a script. Test timings will differ on your machine.
Setup: create an empty folder, save the seven files below into it under the names shown, and open a terminal in it.
Both versions share service.mjs, which checks who is signed in, which role may call each endpoint, and which bookings a customer owns. They differ only in the business rules:
careless.mjs Each endpoint checks its own inputs: whole numbers, positive amounts, a refund no larger than the booking's total, an approval that exists. Cancelling refunds a running total of payments that never goes down.
careful.mjs Every endpoint that acts on an existing booking goes through runTransition: the state check from TRANSITIONS, then that action's guard, then a log entry, and only then the change. Creating a booking runs the seat guard and writes its log entry directly. A guard that needs a total recomputes it from the stored seats, payments and refunds. Approvals are bound to one booking, one amount and one use.
================================================================
FILE 1 OF 7: booking-rules.mjs
================================================================
// booking-rules.mjs: the invented tour operator's prices and limits, the
// records both versions of the service store, and the seven invariants as code.
// Illustration only. All money is invented, counted in whole cents and held in
// memory. The lab imitates no real payment provider.
export const PRICES = { adultCents: 6000, childCents: 3500 }
export const MAX_SEATS = 8
// The two invented accounts: one customer and one staff approver.
export const ACCOUNTS = {
'customer-1': { id: 'customer-1', role: 'customer' },
'approver-1': { id: 'approver-1', role: 'approver' },
}
// Each payment and refund carries a sequence number, and a booking records
// the number at which it was confirmed and at which it was cancelled, so the
// invariants can tell what was paid before a confirmation and what money
// moved after a cancellation.
export function createStore() {
return { nextSeq: 1, counters: {}, bookings: [], payments: [], refundRequests: [], approvals: [], refunds: [], log: [] }
}
export function nextId(store, prefix) {
store.counters[prefix] = (store.counters[prefix] || 0) + 1
return prefix + store.counters[prefix]
}
export function nextSeq(store) {
const seq = store.nextSeq
store.nextSeq = seq + 1
return seq
}
export function findById(list, id) {
return list.find((item) => item.id === id) || null
}
export function isWholeNumber(value) {
return Number.isInteger(value)
}
export function totalCents(booking) {
return booking.adults * PRICES.adultCents + booking.children * PRICES.childCents
}
function sumFor(list, bookingId) {
let sum = 0
for (const entry of list) {
if (entry.bookingId === bookingId) sum += entry.amountCents
}
return sum
}
// The paid and refunded totals for a booking, added up from the stored
// payments and refunds on every call.
export function paidCents(store, bookingId) {
return sumFor(store.payments, bookingId)
}
export function refundedCents(store, bookingId) {
return sumFor(store.refunds, bookingId)
}
// What the service sends back about a booking.
export function viewBooking(booking) {
return {
id: booking.id,
state: booking.state,
adults: booking.adults,
children: booking.children,
totalCents: totalCents(booking),
amountDueCents: booking.amountDueCents,
}
}
export function refuse(status, message) {
return { status: status, body: { error: message } }
}
export function describeBooking(store, booking) {
const due = booking.amountDueCents === null ? 'none' : String(booking.amountDueCents)
return booking.id + ': ' + booking.state + ', ' + booking.adults + ' adults ' + booking.children + ' children, total ' +
totalCents(booking) + ', due ' + due + ', paid ' + paidCents(store, booking.id) + ', refunded ' + refundedCents(store, booking.id)
}
// ---------------------------------------------------------------------------
// The invariants. Each check reads only stored records and returns a list of
// problems; an empty list means the invariant holds.
// ---------------------------------------------------------------------------
function checkRanges(store) {
const problems = []
for (const booking of store.bookings) {
const seats = booking.adults + booking.children
const isValid = isWholeNumber(booking.adults) && isWholeNumber(booking.children) &&
booking.adults >= 1 && booking.children >= 0 && seats <= MAX_SEATS
if (!isValid) problems.push(booking.id + ' has ' + booking.adults + ' adults and ' + booking.children + ' children')
}
for (const list of [store.payments, store.refundRequests, store.refunds]) {
for (const entry of list) {
if (!isWholeNumber(entry.amountCents) || entry.amountCents < 1) problems.push(entry.id + ' is for ' + entry.amountCents + ' cents')
}
}
return problems
}
function checkConfirmedPaid(store) {
const problems = []
for (const booking of store.bookings) {
if (booking.confirmedSeq === null) continue
let captured = 0
for (const payment of store.payments) {
if (payment.bookingId === booking.id && payment.seq < booking.confirmedSeq) captured += payment.amountCents
}
if (captured !== totalCents(booking)) {
problems.push(booking.id + ' was confirmed with ' + captured + ' of ' + totalCents(booking) + ' cents captured')
}
}
return problems
}
function checkRefundsCovered(store) {
const problems = []
for (const booking of store.bookings) {
const paid = paidCents(store, booking.id)
const refunded = refundedCents(store, booking.id)
if (refunded > paid) problems.push(booking.id + ' has ' + refunded + ' cents refunded against ' + paid + ' paid')
}
return problems
}
function checkApprovalUse(store) {
const problems = []
for (const approval of store.approvals) {
const uses = store.refunds.filter((refund) => refund.approvalId === approval.id)
if (uses.length > 1) problems.push(approval.id + ' was used ' + uses.length + ' times')
for (const refund of uses) {
if (refund.bookingId !== approval.bookingId) {
problems.push(refund.id + ' on ' + refund.bookingId + ' used ' + approval.id + ', given for ' + approval.bookingId)
}
if (refund.amountCents !== approval.amountCents) {
problems.push(refund.id + ' paid ' + refund.amountCents + ' cents on ' + approval.id + ', approved for ' + approval.amountCents)
}
}
}
return problems
}
function checkSeparateApprover(store) {
const problems = []
for (const approval of store.approvals) {
const request = findById(store.refundRequests, approval.requestId)
if (request && request.requestedBy === approval.approvedBy) {
problems.push(approval.id + ' was approved by ' + approval.approvedBy + ', who requested ' + request.id)
}
}
return problems
}
function checkCheckoutAmountKept(store) {
const problems = []
for (const booking of store.bookings) {
if (booking.amountDueCents === null) continue
if (totalCents(booking) !== booking.amountDueCents) {
problems.push(booking.id + ' holds seats worth ' + totalCents(booking) + ' cents; checkout fixed ' + booking.amountDueCents)
}
}
return problems
}
function checkCancelledClosed(store) {
const problems = []
for (const booking of store.bookings) {
if (booking.cancelledSeq === null) continue
if (booking.state !== 'cancelled') problems.push(booking.id + ' was cancelled and is now ' + booking.state)
for (const entry of store.payments.concat(store.refunds)) {
if (entry.bookingId === booking.id && entry.seq > booking.cancelledSeq) problems.push(entry.id + ' moved money on ' + booking.id + ' after it was cancelled')
}
}
return problems
}
export const INVARIANTS = [
{
id: 'I1',
text: 'Seat counts and amounts are whole numbers in range: at least 1 adult, 0 or more children, 8 seats at most, and every payment, refund request and refund at least 1 cent.',
check: checkRanges,
},
{ id: 'I2', text: 'A booking is confirmed only when the payments captured before confirmation equal the total its seats come to.', check: checkConfirmedPaid },
{ id: 'I3', text: 'The total refunded on a booking never exceeds the total paid on it.', check: checkRefundsCovered },
{ id: 'I4', text: 'An approval is used once, and only for the booking and the amount it was given for.', check: checkApprovalUse },
{ id: 'I5', text: 'The person who approves a refund is not the person who requested it.', check: checkSeparateApprover },
{
id: 'I6',
text: 'The amount read at checkout is the amount enforced at the end: once checkout has fixed the amount due, the seats still come to that amount.',
check: checkCheckoutAmountKept,
},
{ id: 'I7', text: 'A cancelled booking takes no further payments or refunds, and stays cancelled.', check: checkCancelledClosed },
]
export function checkInvariants(store) {
const results = {}
for (const invariant of INVARIANTS) results[invariant.id] = invariant.check(store)
return results
}
================================================================
FILE 2 OF 7: careless.mjs
================================================================
// careless.mjs: the booking service written one endpoint at a time. Each
// endpoint checks its own inputs (the service has already checked who is
// calling, that their role may call it and, for a customer, that the booking
// is theirs) and then does its job. None of them asks where the booking is in
// its flow, whether an approval still fits, or what the stored payments and
// refunds add up to.
import { findById, isWholeNumber, nextId, nextSeq, refuse, totalCents, viewBooking } from './booking-rules.mjs'
function isPositiveAmount(value) {
return isWholeNumber(value) && value >= 1
}
export const careless = {
createBooking({ user, store, body }) {
if (!isWholeNumber(body.adults) || !isWholeNumber(body.children)) return refuse(422, 'adults and children must be whole numbers')
const booking = {
id: nextId(store, 'b'),
ownerId: user.id,
adults: body.adults,
children: body.children,
state: 'draft',
amountDueCents: null,
paidCents: 0,
confirmedSeq: null,
cancelledSeq: null,
}
store.bookings.push(booking)
return { status: 201, body: viewBooking(booking) }
},
editBooking({ booking, body }) {
if (!isWholeNumber(body.adults) || !isWholeNumber(body.children)) return refuse(422, 'adults and children must be whole numbers')
booking.adults = body.adults
booking.children = body.children
return { status: 200, body: viewBooking(booking) }
},
checkout({ booking }) {
booking.amountDueCents = totalCents(booking)
booking.state = 'payment_pending'
return { status: 200, body: viewBooking(booking) }
},
// The lab's stand-in for a captured card payment.
pay({ store, booking, body }) {
if (!isPositiveAmount(body.amountCents)) return refuse(422, 'amountCents must be a whole number of cents')
const payment = { id: nextId(store, 'pay'), bookingId: booking.id, amountCents: body.amountCents, seq: nextSeq(store) }
store.payments.push(payment)
booking.paidCents += body.amountCents
booking.state = 'paid'
return { status: 200, body: viewBooking(booking) }
},
confirm({ store, booking }) {
booking.state = 'confirmed'
booking.confirmedSeq = nextSeq(store)
return { status: 200, body: viewBooking(booking) }
},
// A refund may not be larger than the booking: checked against its total.
requestRefund({ user, store, booking, body }) {
if (!isPositiveAmount(body.amountCents)) return refuse(422, 'amountCents must be a whole number of cents')
if (body.amountCents > totalCents(booking)) return refuse(422, 'a refund cannot be larger than the booking')
const refundRequest = { id: nextId(store, 'r'), bookingId: booking.id, amountCents: body.amountCents, requestedBy: user.id, status: 'requested' }
store.refundRequests.push(refundRequest)
booking.state = 'refund_requested'
return { status: 201, body: refundRequest }
},
approveRefund({ user, store, booking, refundRequest }) {
const approval = {
id: nextId(store, 'ap'),
requestId: refundRequest.id,
bookingId: refundRequest.bookingId,
amountCents: refundRequest.amountCents,
approvedBy: user.id,
}
store.approvals.push(approval)
refundRequest.status = 'approved'
booking.state = 'refund_approved'
return { status: 201, body: approval }
},
// Takes the approval id and, when the request sends one, the amount to
// refund, as a refund screen might send back the amount it shows.
claimRefund({ store, booking, body }) {
const approval = findById(store.approvals, body.approvalId)
if (!approval) return refuse(404, 'approval not found')
const amountCents = body.amountCents === undefined ? approval.amountCents : body.amountCents
if (!isPositiveAmount(amountCents)) return refuse(422, 'amountCents must be a whole number of cents')
const refund = { id: nextId(store, 'ref'), bookingId: booking.id, amountCents: amountCents, approvalId: approval.id, seq: nextSeq(store) }
store.refunds.push(refund)
booking.state = 'refunded'
return { status: 201, body: { id: refund.id, bookingId: refund.bookingId, amountCents: refund.amountCents, approvalId: refund.approvalId } }
},
// Cancelling refunds what was paid, read from the running total on the booking.
cancel({ store, booking }) {
if (booking.paidCents > 0) {
const refund = { id: nextId(store, 'ref'), bookingId: booking.id, amountCents: booking.paidCents, approvalId: null, seq: nextSeq(store) }
store.refunds.push(refund)
}
booking.state = 'cancelled'
booking.cancelledSeq = nextSeq(store)
return { status: 200, body: viewBooking(booking) }
},
}
================================================================
FILE 3 OF 7: careful.mjs
================================================================
// careful.mjs: the same endpoints. Each one that acts on an existing booking
// is a thin call into one transition function, runTransition. A transition
// lists the states it may start from, a guard for its business rule and the
// change to make. A guard that needs a total recomputes it from the stored
// seats, payments and refunds, and an approval is bound to one booking, one
// amount and one use. checkout and cancel have no guard beyond the state
// check. createBooking has no starting state, so it runs the seat guard and
// writes its log entry itself. Every call to these endpoints, allowed or
// refused, is logged with who asked, what, on which booking, from which state
// and, for a refusal, why.
import {
MAX_SEATS,
findById,
isWholeNumber,
nextId,
nextSeq,
paidCents,
refundedCents,
refuse,
totalCents,
viewBooking,
} from './booking-rules.mjs'
function balanceCents(store, bookingId) {
return paidCents(store, bookingId) - refundedCents(store, bookingId)
}
// ---------------------------------------------------------------------------
// Guards: each returns null when the rule holds, or the refusal to send.
// ---------------------------------------------------------------------------
function guardSeats({ body }) {
const seats = body.adults + body.children
const isValid = isWholeNumber(body.adults) && isWholeNumber(body.children) &&
body.adults >= 1 && body.children >= 0 && seats <= MAX_SEATS
return isValid ? null : refuse(422, 'a booking needs whole numbers: at least 1 adult, 0 or more children, 8 seats at most')
}
function noGuard() {
return null
}
function guardPayment({ booking, body }) {
const due = booking.amountDueCents
if (body.amountCents === due && due === totalCents(booking)) return null
return refuse(409, 'a payment of ' + body.amountCents + ' cents does not match the ' + due + ' cents due')
}
function guardFullyPaid({ store, booking }) {
const captured = paidCents(store, booking.id)
if (captured === totalCents(booking) && captured === booking.amountDueCents) return null
return refuse(409, 'only ' + captured + ' of ' + totalCents(booking) + ' cents captured')
}
function guardRefundAmount({ store, booking, body }) {
const balance = balanceCents(store, booking.id)
if (!isWholeNumber(body.amountCents) || body.amountCents < 1) return refuse(422, 'a refund must be a whole number of cents, at least 1')
if (body.amountCents > balance) return refuse(409, 'a refund of ' + body.amountCents + ' cents is more than the ' + balance + ' cents left to refund')
return null
}
function guardApprover({ user, refundRequest }) {
if (refundRequest.requestedBy === user.id) return refuse(403, user.id + ' requested ' + refundRequest.id + ' and cannot also approve it')
if (refundRequest.status !== 'requested') return refuse(409, refundRequest.id + ' is already ' + refundRequest.status)
return null
}
function guardApproval({ store, booking, body }) {
const approval = findById(store.approvals, body.approvalId)
if (!approval) return refuse(409, 'there is no approval ' + body.approvalId)
if (approval.bookingId !== booking.id) return refuse(409, 'approval ' + approval.id + ' was given for ' + approval.bookingId + ', not ' + booking.id)
if (approval.usedSeq !== null) return refuse(409, 'approval ' + approval.id + ' has already been used')
if (body.amountCents !== undefined && body.amountCents !== approval.amountCents) {
return refuse(409, 'approval ' + approval.id + ' is for ' + approval.amountCents + ' cents, not ' + body.amountCents)
}
const balance = balanceCents(store, booking.id)
if (approval.amountCents > balance) return refuse(409, 'approval ' + approval.id + ' is for more than the ' + balance + ' cents left to refund')
return null
}
// ---------------------------------------------------------------------------
// Effects: run only after the state check and the guard have passed.
// ---------------------------------------------------------------------------
function applyEdit({ booking, body }) {
booking.adults = body.adults
booking.children = body.children
return { status: 200, body: viewBooking(booking) }
}
function applyCheckout({ booking }) {
booking.amountDueCents = totalCents(booking)
booking.state = 'payment_pending'
return { status: 200, body: viewBooking(booking) }
}
function applyPayment({ store, booking }) {
store.payments.push({ id: nextId(store, 'pay'), bookingId: booking.id, amountCents: booking.amountDueCents, seq: nextSeq(store) })
booking.state = 'paid'
return { status: 200, body: viewBooking(booking) }
}
function applyConfirm({ store, booking }) {
booking.state = 'confirmed'
booking.confirmedSeq = nextSeq(store)
return { status: 200, body: viewBooking(booking) }
}
function applyRefundRequest({ user, store, booking, body }) {
const refundRequest = { id: nextId(store, 'r'), bookingId: booking.id, amountCents: body.amountCents, requestedBy: user.id, status: 'requested' }
store.refundRequests.push(refundRequest)
booking.state = 'refund_requested'
return { status: 201, body: refundRequest }
}
function applyApproval({ user, store, booking, refundRequest }) {
const approval = {
id: nextId(store, 'ap'),
requestId: refundRequest.id,
bookingId: refundRequest.bookingId,
amountCents: refundRequest.amountCents,
approvedBy: user.id,
usedSeq: null,
}
store.approvals.push(approval)
refundRequest.status = 'approved'
booking.state = 'refund_approved'
return { status: 201, body: { id: approval.id, requestId: approval.requestId, bookingId: approval.bookingId, amountCents: approval.amountCents, approvedBy: approval.approvedBy } }
}
function applyRefund({ store, booking, body }) {
const approval = findById(store.approvals, body.approvalId)
const refund = { id: nextId(store, 'ref'), bookingId: booking.id, amountCents: approval.amountCents, approvalId: approval.id, seq: nextSeq(store) }
store.refunds.push(refund)
approval.usedSeq = refund.seq
findById(store.refundRequests, approval.requestId).status = 'refunded'
booking.state = balanceCents(store, booking.id) === 0 ? 'refunded' : 'confirmed'
return { status: 201, body: { id: refund.id, bookingId: refund.bookingId, amountCents: refund.amountCents, approvalId: refund.approvalId } }
}
// Cancelling refunds what is left: paid minus refunded, from stored records.
function applyCancel({ store, booking }) {
const balance = balanceCents(store, booking.id)
if (balance > 0) store.refunds.push({ id: nextId(store, 'ref'), bookingId: booking.id, amountCents: balance, approvalId: null, seq: nextSeq(store) })
booking.state = 'cancelled'
booking.cancelledSeq = nextSeq(store)
return { status: 200, body: viewBooking(booking) }
}
// ---------------------------------------------------------------------------
// The state machine, and the one function every endpoint that acts on an
// existing booking goes through.
// ---------------------------------------------------------------------------
export const TRANSITIONS = {
edit: { from: ['draft'], guard: guardSeats, apply: applyEdit },
checkout: { from: ['draft'], guard: noGuard, apply: applyCheckout },
pay: { from: ['payment_pending'], guard: guardPayment, apply: applyPayment },
confirm: { from: ['paid'], guard: guardFullyPaid, apply: applyConfirm },
requestRefund: { from: ['confirmed'], guard: guardRefundAmount, apply: applyRefundRequest },
approveRefund: { from: ['refund_requested'], guard: guardApprover, apply: applyApproval },
claimRefund: { from: ['refund_approved'], guard: guardApproval, apply: applyRefund },
cancel: { from: ['draft', 'payment_pending', 'confirmed'], guard: noGuard, apply: applyCancel },
}
function writeLog(context, action, fromState, refusal) {
const entry = {
seq: nextSeq(context.store),
actor: context.user.id,
action: action,
bookingId: context.booking ? context.booking.id : null,
fromState: fromState,
outcome: refusal ? 'refused' : 'allowed',
reason: refusal ? refusal.body.error : '',
}
context.store.log.push(entry)
}
function runTransition(action, context) {
const transition = TRANSITIONS[action]
const fromState = context.booking.state
let refusal = null
if (!transition.from.includes(fromState)) refusal = refuse(409, action + ' is not allowed from ' + fromState)
if (!refusal) refusal = transition.guard(context)
writeLog(context, action, fromState, refusal)
return refusal || transition.apply(context)
}
export const careful = {
createBooking(context) {
const refusal = guardSeats(context)
writeLog(context, 'createBooking', 'none', refusal)
if (refusal) return refusal
const { user, store, body } = context
const booking = {
id: nextId(store, 'b'),
ownerId: user.id,
adults: body.adults,
children: body.children,
state: 'draft',
amountDueCents: null,
confirmedSeq: null,
cancelledSeq: null,
}
store.bookings.push(booking)
return { status: 201, body: viewBooking(booking) }
},
editBooking: (context) => runTransition('edit', context),
checkout: (context) => runTransition('checkout', context),
pay: (context) => runTransition('pay', context),
confirm: (context) => runTransition('confirm', context),
requestRefund: (context) => runTransition('requestRefund', context),
approveRefund: (context) => runTransition('approveRefund', context),
claimRefund: (context) => runTransition('claimRefund', context),
cancel: (context) => runTransition('cancel', context),
}
================================================================
FILE 4 OF 7: service.mjs
================================================================
// service.mjs: the booking service over HTTP, in the version named on the
// command line (careless or careful). It listens on 127.0.0.1 only, on a port
// the operating system picks, and is started and stopped by abuse-cases.mjs.
// Both versions share everything in this file, including the checks on who is
// signed in, which role may call which endpoint and which bookings a customer
// owns, so the two differ only in their business rules.
import { randomBytes } from 'node:crypto'
import { createServer } from 'node:http'
import { ACCOUNTS, createStore, findById, refuse } from './booking-rules.mjs'
import { careful } from './careful.mjs'
import { careless } from './careless.mjs'
const VERSIONS = { careless: careless, careful: careful }
const version = process.argv[2]
const handlers = VERSIONS[version]
if (!handlers) throw new Error('Name a version: careless or careful')
const ROUTES = [
['POST', '/bookings', 'createBooking'],
['PATCH', '/bookings/:id', 'editBooking'],
['POST', '/bookings/:id/checkout', 'checkout'],
['POST', '/bookings/:id/pay', 'pay'],
['POST', '/bookings/:id/confirm', 'confirm'],
['POST', '/bookings/:id/refund-requests', 'requestRefund'],
['POST', '/refund-requests/:id/approve', 'approveRefund'],
['POST', '/bookings/:id/refunds', 'claimRefund'],
['POST', '/bookings/:id/cancel', 'cancel'],
]
// Which role may call each endpoint. Staff may raise a refund request on a
// customer's behalf; only staff approve.
const ROLES = {
createBooking: ['customer'],
editBooking: ['customer'],
checkout: ['customer'],
pay: ['customer'],
confirm: ['customer'],
requestRefund: ['customer', 'approver'],
approveRefund: ['approver'],
claimRefund: ['customer'],
cancel: ['customer'],
}
let store = createStore()
// Random session tokens, sent back by the client in a cookie named session.
const userIdByToken = new Map()
const tokenByUserId = {}
for (const userId of Object.keys(ACCOUNTS)) {
const token = randomBytes(16).toString('hex')
userIdByToken.set(token, userId)
tokenByUserId[userId] = token
}
function readUser(request) {
for (const cookie of (request.headers.cookie || '').split(';')) {
const parts = cookie.trim().split('=')
if (parts[0] === 'session') return ACCOUNTS[userIdByToken.get(parts[1])] || null
}
return null
}
function matchRoute(method, pathname) {
const pathParts = pathname.split('/')
for (const [routeMethod, pattern, action] of ROUTES) {
const patternParts = pattern.split('/')
if (routeMethod !== method || patternParts.length !== pathParts.length) continue
let id = null
const isMatch = patternParts.every((part, index) => {
if (part === ':id') {
id = pathParts[index]
return true
}
return part === pathParts[index]
})
if (isMatch) return { action: action, id: id }
}
return null
}
function readBody(request) {
return new Promise((resolve) => {
let text = ''
request.on('data', (chunk) => {
text += chunk
})
request.on('end', () => {
try {
resolve(text ? JSON.parse(text) : {})
} catch {
resolve({})
}
})
})
}
// Finds the booking an HTTP request is about, through the refund request for
// an approval. The check that a customer reaches only their own is in answer().
function findTarget(route) {
if (route.action === 'createBooking') return { booking: null, refundRequest: null }
let refundRequest = null
let bookingId = route.id
if (route.action === 'approveRefund') {
refundRequest = findById(store.refundRequests, route.id)
if (!refundRequest) return null
bookingId = refundRequest.bookingId
}
const booking = findById(store.bookings, bookingId)
return booking ? { booking: booking, refundRequest: refundRequest } : null
}
async function answer(request) {
const route = matchRoute(request.method, new URL(request.url, 'http://127.0.0.1').pathname)
if (!route) return refuse(404, 'not found')
const user = readUser(request)
if (!user) return refuse(401, 'not signed in')
if (!ROLES[route.action].includes(user.role)) return refuse(403, 'a ' + user.role + ' cannot call ' + route.action)
const target = findTarget(route)
if (!target) return refuse(404, 'not found')
if (target.booking && user.role === 'customer' && target.booking.ownerId !== user.id) return refuse(404, 'not found')
const body = await readBody(request)
const context = { user: user, store: store, body: body, booking: target.booking, refundRequest: target.refundRequest }
return handlers[route.action](context)
}
const server = createServer(async (request, response) => {
const result = await answer(request)
response.writeHead(result.status, { 'content-type': 'application/json' })
response.end(JSON.stringify(result.body))
})
// Lab-only channel to the process that started this one: a fresh set of
// records before each case, and a copy of the stored records to check the
// invariants against. A real service has neither; you would read your database.
process.on('message', (message) => {
if (message.type === 'reset') {
store = createStore()
process.send({ type: 'reset' })
}
if (message.type === 'snapshot') process.send({ type: 'snapshot', store: store })
})
// Port 0 asks the operating system for any unused port.
server.listen(0, '127.0.0.1', () => {
process.send({ type: 'ready', port: server.address().port, tokens: tokenByUserId })
})
================================================================
FILE 5 OF 7: abuse-cases.mjs
================================================================
// abuse-cases.mjs: the abuse cases as data, and the code that plays them
// against one version of the service. The service runs as its own process,
// started here and stopped by its process id when the run ends. Every case
// starts from fresh records, takes the normal flow to its starting state
// (setup), then sends the abuse requests.
import { fork } from 'node:child_process'
import { request as httpRequest } from 'node:http'
import { fileURLToPath } from 'node:url'
import { checkInvariants } from './booking-rules.mjs'
const CUSTOMER = 'customer-1'
const APPROVER = 'approver-1'
function step(as, method, path, body) {
return { as: as, method: method, path: path, body: body }
}
// The normal flow to a confirmed booking for 2 adults, fully paid (12000 cents).
function confirmedBooking(bookingId) {
return [
step(CUSTOMER, 'POST', '/bookings', { adults: 2, children: 0 }),
step(CUSTOMER, 'POST', '/bookings/' + bookingId + '/checkout', {}),
step(CUSTOMER, 'POST', '/bookings/' + bookingId + '/pay', { amountCents: 12000 }),
step(CUSTOMER, 'POST', '/bookings/' + bookingId + '/confirm', {}),
]
}
// The customer asks for a refund and the approver approves it.
function approvedRefund(bookingId, requestId, amountCents) {
return [
step(CUSTOMER, 'POST', '/bookings/' + bookingId + '/refund-requests', { amountCents: amountCents }),
step(APPROVER, 'POST', '/refund-requests/' + requestId + '/approve', {}),
]
}
function claim(bookingId, body) {
return step(CUSTOMER, 'POST', '/bookings/' + bookingId + '/refunds', body)
}
export const CASES = [
{
id: 'A1',
title: 'Skipped step: request the last step directly. Confirm a booking that was never checked out or paid.',
attacks: 'I2',
mapsTo: 'WSTG-BUSL-06; ASVS 2.3.1',
expected: '409 on confirm; b1 stays a draft.',
setup: [step(CUSTOMER, 'POST', '/bookings', { adults: 2, children: 0 })],
abuse: [step(CUSTOMER, 'POST', '/bookings/b1/confirm', {})],
},
{
id: 'A2',
title: 'Skipped step: confirm without paying. Check out, then confirm with no payment captured.',
attacks: 'I2',
mapsTo: 'WSTG-BUSL-06; ASVS 2.3.1',
expected: '409 on confirm; b1 stays in payment_pending.',
setup: [step(CUSTOMER, 'POST', '/bookings', { adults: 2, children: 0 }), step(CUSTOMER, 'POST', '/bookings/b1/checkout', {})],
abuse: [step(CUSTOMER, 'POST', '/bookings/b1/confirm', {})],
},
{
id: 'A3',
title: 'Replayed approval: the same approval sent twice. After ap1 has paid out, claim it again while a smaller approval, ap2, is waiting.',
attacks: 'I4',
mapsTo: 'WSTG-BUSL-05',
expected: '409 on the second claim of ap1; one refund on ap1.',
setup: confirmedBooking('b1').concat(approvedRefund('b1', 'r1', 3000), [claim('b1', { approvalId: 'ap1' })], approvedRefund('b1', 'r2', 2000)),
abuse: [claim('b1', { approvalId: 'ap1' })],
},
{
id: 'A4',
title: 'Replayed approval: an approval for one booking used on another. Claim on b2 with the larger approval given for b1.',
attacks: 'I4',
mapsTo: "this page's own case: an approval bound to its booking",
expected: '409 on the claim; no refund on b2 from ap1.',
setup: confirmedBooking('b1').concat(confirmedBooking('b2'), approvedRefund('b1', 'r1', 3000), approvedRefund('b2', 'r2', 1000)),
abuse: [claim('b2', { approvalId: 'ap1' })],
},
{
id: 'A5',
title: 'Limit change: the amount edited after approval. Claim ap1, approved for 3000 cents, with 12000 in the body.',
attacks: 'I4',
mapsTo: 'WSTG-BUSL-03',
expected: '409 on the claim; nothing refunded.',
setup: confirmedBooking('b1').concat(approvedRefund('b1', 'r1', 3000)),
abuse: [claim('b1', { approvalId: 'ap1', amountCents: 12000 })],
},
{
id: 'A6',
title: 'Limit change: a zero or negative value. Book 0 seats, then 3 adults and -2 children, and pay for that.',
attacks: 'I1',
mapsTo: 'WSTG-BUSL-01; ASVS 2.2.1',
expected: '422 on both bookings; nothing else exists to pay for.',
setup: [],
abuse: [
step(CUSTOMER, 'POST', '/bookings', { adults: 0, children: 0 }),
step(CUSTOMER, 'POST', '/bookings', { adults: 3, children: -2 }),
step(CUSTOMER, 'POST', '/bookings/b2/checkout', {}),
step(CUSTOMER, 'POST', '/bookings/b2/pay', { amountCents: 11000 }),
step(CUSTOMER, 'POST', '/bookings/b2/confirm', {}),
],
},
{
id: 'A7',
title: 'Limit change mid-flow: seats changed after checkout. Check out 2 adults, change to 6, pay the amount due for 2, confirm.',
attacks: 'I6',
mapsTo: 'WSTG-BUSL-03',
expected: '409 on the change; b1 is paid and confirmed for 2 adults.',
setup: [step(CUSTOMER, 'POST', '/bookings', { adults: 2, children: 0 }), step(CUSTOMER, 'POST', '/bookings/b1/checkout', {})],
abuse: [
step(CUSTOMER, 'PATCH', '/bookings/b1', { adults: 6, children: 0 }),
step(CUSTOMER, 'POST', '/bookings/b1/pay', { amountCents: 12000 }),
step(CUSTOMER, 'POST', '/bookings/b1/confirm', {}),
],
},
{
id: 'A8',
title: 'Out of order: refund before capture. Ask for a refund on a booking that is checked out but not paid.',
attacks: 'I3',
mapsTo: 'WSTG-BUSL-06; ASVS 2.3.1',
expected: '409 on the refund request; nothing refunded.',
setup: [step(CUSTOMER, 'POST', '/bookings', { adults: 2, children: 0 }), step(CUSTOMER, 'POST', '/bookings/b1/checkout', {})],
abuse: [
step(CUSTOMER, 'POST', '/bookings/b1/refund-requests', { amountCents: 12000 }),
step(APPROVER, 'POST', '/refund-requests/r1/approve', {}),
claim('b1', { approvalId: 'ap1' }),
],
},
{
id: 'A9',
title: 'Out of order: cancel after refund. Cancel a booking that has already been refunded in full.',
attacks: 'I3',
mapsTo: 'WSTG-BUSL-06; ASVS 2.3.1',
expected: '409 on cancel; refunded stays at 12000.',
setup: confirmedBooking('b1').concat(approvedRefund('b1', 'r1', 12000), [claim('b1', { approvalId: 'ap1' })]),
abuse: [step(CUSTOMER, 'POST', '/bookings/b1/cancel', {})],
},
{
id: 'A10',
title: 'Out of order: pay after cancel. Cancel a checked-out booking, then pay and confirm it.',
attacks: 'I7',
mapsTo: 'WSTG-BUSL-06; ASVS 2.3.1',
expected: '409 on pay and on confirm; b1 stays cancelled with nothing paid.',
setup: [
step(CUSTOMER, 'POST', '/bookings', { adults: 2, children: 0 }),
step(CUSTOMER, 'POST', '/bookings/b1/checkout', {}),
step(CUSTOMER, 'POST', '/bookings/b1/cancel', {}),
],
abuse: [step(CUSTOMER, 'POST', '/bookings/b1/pay', { amountCents: 12000 }), step(CUSTOMER, 'POST', '/bookings/b1/confirm', {})],
},
{
id: 'A11',
title: "Role confusion: the requester approves their own refund. The approver raises a refund on the customer's booking, then approves it.",
attacks: 'I5',
mapsTo: 'ASVS 2.3.5',
expected: '403 on the approval; nothing refunded.',
setup: confirmedBooking('b1'),
abuse: [
step(APPROVER, 'POST', '/bookings/b1/refund-requests', { amountCents: 12000 }),
step(APPROVER, 'POST', '/refund-requests/r1/approve', {}),
claim('b1', { approvalId: 'ap1' }),
],
},
]
// ---------------------------------------------------------------------------
// Starting, asking and stopping the service process.
// ---------------------------------------------------------------------------
function startService(version) {
const child = fork(fileURLToPath(new URL('./service.mjs', import.meta.url)), [version])
return new Promise((resolve, reject) => {
child.once('message', (message) => resolve({ child: child, port: message.port, tokens: message.tokens }))
child.once('error', reject)
})
}
function stopService(service) {
return new Promise((resolve) => {
service.child.once('exit', () => resolve())
process.kill(service.child.pid, 'SIGTERM')
})
}
function askService(service, type) {
return new Promise((resolve) => {
const onMessage = (message) => {
if (message.type !== type) return
service.child.off('message', onMessage)
resolve(message)
}
service.child.on('message', onMessage)
service.child.send({ type: type })
})
}
function send(service, request) {
const payload = JSON.stringify(request.body || {})
const options = {
host: '127.0.0.1',
port: service.port,
method: request.method,
path: request.path,
agent: false,
headers: {
'content-type': 'application/json',
'content-length': Buffer.byteLength(payload),
cookie: 'session=' + service.tokens[request.as],
},
}
return new Promise((resolve, reject) => {
const outgoing = httpRequest(options, (response) => {
let text = ''
response.on('data', (chunk) => {
text += chunk
})
response.on('end', () => resolve({ status: response.statusCode, body: JSON.parse(text) }))
})
outgoing.on('error', reject)
outgoing.end(payload)
})
}
async function sendAll(service, requests) {
const exchanges = []
for (const request of requests) exchanges.push({ request: request, response: await send(service, request) })
return exchanges
}
async function runCase(service, abuseCase) {
await askService(service, 'reset')
const setup = await sendAll(service, abuseCase.setup)
const before = (await askService(service, 'snapshot')).store
const abuse = await sendAll(service, abuseCase.abuse)
const after = (await askService(service, 'snapshot')).store
const refusalsLogged = after.log.filter((entry) => entry.seq >= before.nextSeq && entry.outcome === 'refused')
return { abuseCase: abuseCase, setup: setup, before: before, abuse: abuse, after: after, invariants: checkInvariants(after), refusalsLogged: refusalsLogged }
}
export async function runAllCases(version) {
const service = await startService(version)
const results = []
try {
for (const abuseCase of CASES) results.push(await runCase(service, abuseCase))
} finally {
await stopService(service)
}
return results
}
================================================================
FILE 6 OF 7: run-cases.mjs
================================================================
// run-cases.mjs: plays every abuse case against both versions and prints the
// evidence for each: the statuses the setup requests got, each abuse request
// and its response, the bookings before and after, which invariants hold and
// which are broken, and each refusal the careful version logged for the abuse
// requests.
// Run: node run-cases.mjs
import { INVARIANTS, describeBooking } from './booking-rules.mjs'
import { CASES, runAllCases } from './abuse-cases.mjs'
const VERSIONS = ['careless', 'careful']
const LINE = '================================================================'
function describeState(store) {
if (store.bookings.length === 0) return ['no bookings']
return store.bookings.map((booking) => describeBooking(store, booking))
}
function describeExchange(exchange) {
const request = exchange.request
return request.as + ' ' + request.method + ' ' + request.path + ' ' + JSON.stringify(request.body) +
' -> ' + exchange.response.status + ' ' + JSON.stringify(exchange.response.body)
}
function printInvariants(invariants) {
const holding = []
for (const invariant of INVARIANTS) {
const problems = invariants[invariant.id]
if (problems.length === 0) holding.push(invariant.id)
for (const problem of problems) console.log(' BROKEN ' + invariant.id + ': ' + problem)
}
console.log(' holds: ' + (holding.length ? holding.join(' ') : 'none'))
}
function describeSetup(setup) {
if (setup.length === 0) return 'none'
const statuses = setup.map((exchange) => exchange.response.status).join(' ')
const count = setup.length === 1 ? '1 request' : setup.length + ' requests'
return count + ' in the normal flow, answered ' + statuses
}
function describeRefusal(entry) {
const target = entry.bookingId === null ? 'a new booking' : entry.bookingId + ' from ' + entry.fromState
return entry.actor + ' ' + entry.action + ' on ' + target + ': ' + entry.reason
}
function printVersion(version, result) {
console.log(' ' + version)
console.log(' setup: ' + describeSetup(result.setup))
for (const line of describeState(result.before)) console.log(' before ' + line)
for (const exchange of result.abuse) console.log(' abuse ' + describeExchange(exchange))
for (const line of describeState(result.after)) console.log(' after ' + line)
printInvariants(result.invariants)
for (const entry of result.refusalsLogged) console.log(' logged refusal: ' + describeRefusal(entry))
}
function countBroken(results) {
return results.filter((result) => INVARIANTS.some((invariant) => result.invariants[invariant.id].length > 0)).length
}
const resultsByVersion = {}
for (const version of VERSIONS) resultsByVersion[version] = await runAllCases(version)
console.log('Run on Node.js ' + process.version)
CASES.forEach((abuseCase, index) => {
console.log(LINE)
console.log(abuseCase.id + ' ' + abuseCase.title)
console.log(' attacks ' + abuseCase.attacks + '; corresponds to ' + abuseCase.mapsTo)
console.log(' expected refusal: ' + abuseCase.expected)
for (const version of VERSIONS) printVersion(version, resultsByVersion[version][index])
})
console.log(LINE)
for (const version of VERSIONS) {
console.log(version + ': invariants broken after ' + countBroken(resultsByVersion[version]) + ' of ' + CASES.length + ' cases')
}
================================================================
FILE 7 OF 7: invariants.test.mjs
================================================================
// invariants.test.mjs: every abuse case is played once against one version, then
// one test per invariant fails while any case has left that invariant broken.
// Run: node invariants.test.mjs careless (expect 7 failures)
// node invariants.test.mjs careful (expect 7 passes)
// With no argument it tests the careful version, which is what node --test runs.
import assert from 'node:assert/strict'
import { test } from 'node:test'
import { INVARIANTS } from './booking-rules.mjs'
import { runAllCases } from './abuse-cases.mjs'
const version = process.argv[2] || 'careful'
const results = await runAllCases(version)
for (const invariant of INVARIANTS) {
test(version + ': ' + invariant.id + ' ' + invariant.text, () => {
const problems = []
for (const result of results) {
for (const problem of result.invariants[invariant.id]) problems.push(result.abuseCase.id + ': ' + problem)
}
assert.deepEqual(problems, [])
})
}
==== PART 6. STEP 1: PLAY EVERY CASE AGAINST BOTH VERSIONS ====
Command: node run-cases.mjs
Run on Node.js v26.0.0
================================================================
A1 Skipped step: request the last step directly. Confirm a booking that was never checked out or paid.
attacks I2; corresponds to WSTG-BUSL-06; ASVS 2.3.1
expected refusal: 409 on confirm; b1 stays a draft.
careless
setup: 1 request in the normal flow, answered 201
before b1: draft, 2 adults 0 children, total 12000, due none, paid 0, refunded 0
abuse customer-1 POST /bookings/b1/confirm {} -> 200 {"id":"b1","state":"confirmed","adults":2,"children":0,"totalCents":12000,"amountDueCents":null}
after b1: confirmed, 2 adults 0 children, total 12000, due none, paid 0, refunded 0
BROKEN I2: b1 was confirmed with 0 of 12000 cents captured
holds: I1 I3 I4 I5 I6 I7
careful
setup: 1 request in the normal flow, answered 201
before b1: draft, 2 adults 0 children, total 12000, due none, paid 0, refunded 0
abuse customer-1 POST /bookings/b1/confirm {} -> 409 {"error":"confirm is not allowed from draft"}
after b1: draft, 2 adults 0 children, total 12000, due none, paid 0, refunded 0
holds: I1 I2 I3 I4 I5 I6 I7
logged refusal: customer-1 confirm on b1 from draft: confirm is not allowed from draft
================================================================
A2 Skipped step: confirm without paying. Check out, then confirm with no payment captured.
attacks I2; corresponds to WSTG-BUSL-06; ASVS 2.3.1
expected refusal: 409 on confirm; b1 stays in payment_pending.
careless
setup: 2 requests in the normal flow, answered 201 200
before b1: payment_pending, 2 adults 0 children, total 12000, due 12000, paid 0, refunded 0
abuse customer-1 POST /bookings/b1/confirm {} -> 200 {"id":"b1","state":"confirmed","adults":2,"children":0,"totalCents":12000,"amountDueCents":12000}
after b1: confirmed, 2 adults 0 children, total 12000, due 12000, paid 0, refunded 0
BROKEN I2: b1 was confirmed with 0 of 12000 cents captured
holds: I1 I3 I4 I5 I6 I7
careful
setup: 2 requests in the normal flow, answered 201 200
before b1: payment_pending, 2 adults 0 children, total 12000, due 12000, paid 0, refunded 0
abuse customer-1 POST /bookings/b1/confirm {} -> 409 {"error":"confirm is not allowed from payment_pending"}
after b1: payment_pending, 2 adults 0 children, total 12000, due 12000, paid 0, refunded 0
holds: I1 I2 I3 I4 I5 I6 I7
logged refusal: customer-1 confirm on b1 from payment_pending: confirm is not allowed from payment_pending
================================================================
A3 Replayed approval: the same approval sent twice. After ap1 has paid out, claim it again while a smaller approval, ap2, is waiting.
attacks I4; corresponds to WSTG-BUSL-05
expected refusal: 409 on the second claim of ap1; one refund on ap1.
careless
setup: 9 requests in the normal flow, answered 201 200 200 200 201 201 201 201 201
before b1: refund_approved, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 3000
abuse customer-1 POST /bookings/b1/refunds {"approvalId":"ap1"} -> 201 {"id":"ref2","bookingId":"b1","amountCents":3000,"approvalId":"ap1"}
after b1: refunded, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 6000
BROKEN I4: ap1 was used 2 times
holds: I1 I2 I3 I5 I6 I7
careful
setup: 9 requests in the normal flow, answered 201 200 200 200 201 201 201 201 201
before b1: refund_approved, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 3000
abuse customer-1 POST /bookings/b1/refunds {"approvalId":"ap1"} -> 409 {"error":"approval ap1 has already been used"}
after b1: refund_approved, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 3000
holds: I1 I2 I3 I4 I5 I6 I7
logged refusal: customer-1 claimRefund on b1 from refund_approved: approval ap1 has already been used
================================================================
A4 Replayed approval: an approval for one booking used on another. Claim on b2 with the larger approval given for b1.
attacks I4; corresponds to this page's own case: an approval bound to its booking
expected refusal: 409 on the claim; no refund on b2 from ap1.
careless
setup: 12 requests in the normal flow, answered 201 200 200 200 201 200 200 200 201 201 201 201
before b1: refund_approved, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 0
before b2: refund_approved, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 0
abuse customer-1 POST /bookings/b2/refunds {"approvalId":"ap1"} -> 201 {"id":"ref1","bookingId":"b2","amountCents":3000,"approvalId":"ap1"}
after b1: refund_approved, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 0
after b2: refunded, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 3000
BROKEN I4: ref1 on b2 used ap1, given for b1
holds: I1 I2 I3 I5 I6 I7
careful
setup: 12 requests in the normal flow, answered 201 200 200 200 201 200 200 200 201 201 201 201
before b1: refund_approved, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 0
before b2: refund_approved, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 0
abuse customer-1 POST /bookings/b2/refunds {"approvalId":"ap1"} -> 409 {"error":"approval ap1 was given for b1, not b2"}
after b1: refund_approved, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 0
after b2: refund_approved, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 0
holds: I1 I2 I3 I4 I5 I6 I7
logged refusal: customer-1 claimRefund on b2 from refund_approved: approval ap1 was given for b1, not b2
================================================================
A5 Limit change: the amount edited after approval. Claim ap1, approved for 3000 cents, with 12000 in the body.
attacks I4; corresponds to WSTG-BUSL-03
expected refusal: 409 on the claim; nothing refunded.
careless
setup: 6 requests in the normal flow, answered 201 200 200 200 201 201
before b1: refund_approved, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 0
abuse customer-1 POST /bookings/b1/refunds {"approvalId":"ap1","amountCents":12000} -> 201 {"id":"ref1","bookingId":"b1","amountCents":12000,"approvalId":"ap1"}
after b1: refunded, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 12000
BROKEN I4: ref1 paid 12000 cents on ap1, approved for 3000
holds: I1 I2 I3 I5 I6 I7
careful
setup: 6 requests in the normal flow, answered 201 200 200 200 201 201
before b1: refund_approved, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 0
abuse customer-1 POST /bookings/b1/refunds {"approvalId":"ap1","amountCents":12000} -> 409 {"error":"approval ap1 is for 3000 cents, not 12000"}
after b1: refund_approved, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 0
holds: I1 I2 I3 I4 I5 I6 I7
logged refusal: customer-1 claimRefund on b1 from refund_approved: approval ap1 is for 3000 cents, not 12000
================================================================
A6 Limit change: a zero or negative value. Book 0 seats, then 3 adults and -2 children, and pay for that.
attacks I1; corresponds to WSTG-BUSL-01; ASVS 2.2.1
expected refusal: 422 on both bookings; nothing else exists to pay for.
careless
setup: none
before no bookings
abuse customer-1 POST /bookings {"adults":0,"children":0} -> 201 {"id":"b1","state":"draft","adults":0,"children":0,"totalCents":0,"amountDueCents":null}
abuse customer-1 POST /bookings {"adults":3,"children":-2} -> 201 {"id":"b2","state":"draft","adults":3,"children":-2,"totalCents":11000,"amountDueCents":null}
abuse customer-1 POST /bookings/b2/checkout {} -> 200 {"id":"b2","state":"payment_pending","adults":3,"children":-2,"totalCents":11000,"amountDueCents":11000}
abuse customer-1 POST /bookings/b2/pay {"amountCents":11000} -> 200 {"id":"b2","state":"paid","adults":3,"children":-2,"totalCents":11000,"amountDueCents":11000}
abuse customer-1 POST /bookings/b2/confirm {} -> 200 {"id":"b2","state":"confirmed","adults":3,"children":-2,"totalCents":11000,"amountDueCents":11000}
after b1: draft, 0 adults 0 children, total 0, due none, paid 0, refunded 0
after b2: confirmed, 3 adults -2 children, total 11000, due 11000, paid 11000, refunded 0
BROKEN I1: b1 has 0 adults and 0 children
BROKEN I1: b2 has 3 adults and -2 children
holds: I2 I3 I4 I5 I6 I7
careful
setup: none
before no bookings
abuse customer-1 POST /bookings {"adults":0,"children":0} -> 422 {"error":"a booking needs whole numbers: at least 1 adult, 0 or more children, 8 seats at most"}
abuse customer-1 POST /bookings {"adults":3,"children":-2} -> 422 {"error":"a booking needs whole numbers: at least 1 adult, 0 or more children, 8 seats at most"}
abuse customer-1 POST /bookings/b2/checkout {} -> 404 {"error":"not found"}
abuse customer-1 POST /bookings/b2/pay {"amountCents":11000} -> 404 {"error":"not found"}
abuse customer-1 POST /bookings/b2/confirm {} -> 404 {"error":"not found"}
after no bookings
holds: I1 I2 I3 I4 I5 I6 I7
logged refusal: customer-1 createBooking on a new booking: a booking needs whole numbers: at least 1 adult, 0 or more children, 8 seats at most
logged refusal: customer-1 createBooking on a new booking: a booking needs whole numbers: at least 1 adult, 0 or more children, 8 seats at most
================================================================
A7 Limit change mid-flow: seats changed after checkout. Check out 2 adults, change to 6, pay the amount due for 2, confirm.
attacks I6; corresponds to WSTG-BUSL-03
expected refusal: 409 on the change; b1 is paid and confirmed for 2 adults.
careless
setup: 2 requests in the normal flow, answered 201 200
before b1: payment_pending, 2 adults 0 children, total 12000, due 12000, paid 0, refunded 0
abuse customer-1 PATCH /bookings/b1 {"adults":6,"children":0} -> 200 {"id":"b1","state":"payment_pending","adults":6,"children":0,"totalCents":36000,"amountDueCents":12000}
abuse customer-1 POST /bookings/b1/pay {"amountCents":12000} -> 200 {"id":"b1","state":"paid","adults":6,"children":0,"totalCents":36000,"amountDueCents":12000}
abuse customer-1 POST /bookings/b1/confirm {} -> 200 {"id":"b1","state":"confirmed","adults":6,"children":0,"totalCents":36000,"amountDueCents":12000}
after b1: confirmed, 6 adults 0 children, total 36000, due 12000, paid 12000, refunded 0
BROKEN I2: b1 was confirmed with 12000 of 36000 cents captured
BROKEN I6: b1 holds seats worth 36000 cents; checkout fixed 12000
holds: I1 I3 I4 I5 I7
careful
setup: 2 requests in the normal flow, answered 201 200
before b1: payment_pending, 2 adults 0 children, total 12000, due 12000, paid 0, refunded 0
abuse customer-1 PATCH /bookings/b1 {"adults":6,"children":0} -> 409 {"error":"edit is not allowed from payment_pending"}
abuse customer-1 POST /bookings/b1/pay {"amountCents":12000} -> 200 {"id":"b1","state":"paid","adults":2,"children":0,"totalCents":12000,"amountDueCents":12000}
abuse customer-1 POST /bookings/b1/confirm {} -> 200 {"id":"b1","state":"confirmed","adults":2,"children":0,"totalCents":12000,"amountDueCents":12000}
after b1: confirmed, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 0
holds: I1 I2 I3 I4 I5 I6 I7
logged refusal: customer-1 edit on b1 from payment_pending: edit is not allowed from payment_pending
================================================================
A8 Out of order: refund before capture. Ask for a refund on a booking that is checked out but not paid.
attacks I3; corresponds to WSTG-BUSL-06; ASVS 2.3.1
expected refusal: 409 on the refund request; nothing refunded.
careless
setup: 2 requests in the normal flow, answered 201 200
before b1: payment_pending, 2 adults 0 children, total 12000, due 12000, paid 0, refunded 0
abuse customer-1 POST /bookings/b1/refund-requests {"amountCents":12000} -> 201 {"id":"r1","bookingId":"b1","amountCents":12000,"requestedBy":"customer-1","status":"requested"}
abuse approver-1 POST /refund-requests/r1/approve {} -> 201 {"id":"ap1","requestId":"r1","bookingId":"b1","amountCents":12000,"approvedBy":"approver-1"}
abuse customer-1 POST /bookings/b1/refunds {"approvalId":"ap1"} -> 201 {"id":"ref1","bookingId":"b1","amountCents":12000,"approvalId":"ap1"}
after b1: refunded, 2 adults 0 children, total 12000, due 12000, paid 0, refunded 12000
BROKEN I3: b1 has 12000 cents refunded against 0 paid
holds: I1 I2 I4 I5 I6 I7
careful
setup: 2 requests in the normal flow, answered 201 200
before b1: payment_pending, 2 adults 0 children, total 12000, due 12000, paid 0, refunded 0
abuse customer-1 POST /bookings/b1/refund-requests {"amountCents":12000} -> 409 {"error":"requestRefund is not allowed from payment_pending"}
abuse approver-1 POST /refund-requests/r1/approve {} -> 404 {"error":"not found"}
abuse customer-1 POST /bookings/b1/refunds {"approvalId":"ap1"} -> 409 {"error":"claimRefund is not allowed from payment_pending"}
after b1: payment_pending, 2 adults 0 children, total 12000, due 12000, paid 0, refunded 0
holds: I1 I2 I3 I4 I5 I6 I7
logged refusal: customer-1 requestRefund on b1 from payment_pending: requestRefund is not allowed from payment_pending
logged refusal: customer-1 claimRefund on b1 from payment_pending: claimRefund is not allowed from payment_pending
================================================================
A9 Out of order: cancel after refund. Cancel a booking that has already been refunded in full.
attacks I3; corresponds to WSTG-BUSL-06; ASVS 2.3.1
expected refusal: 409 on cancel; refunded stays at 12000.
careless
setup: 7 requests in the normal flow, answered 201 200 200 200 201 201 201
before b1: refunded, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 12000
abuse customer-1 POST /bookings/b1/cancel {} -> 200 {"id":"b1","state":"cancelled","adults":2,"children":0,"totalCents":12000,"amountDueCents":12000}
after b1: cancelled, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 24000
BROKEN I3: b1 has 24000 cents refunded against 12000 paid
holds: I1 I2 I4 I5 I6 I7
careful
setup: 7 requests in the normal flow, answered 201 200 200 200 201 201 201
before b1: refunded, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 12000
abuse customer-1 POST /bookings/b1/cancel {} -> 409 {"error":"cancel is not allowed from refunded"}
after b1: refunded, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 12000
holds: I1 I2 I3 I4 I5 I6 I7
logged refusal: customer-1 cancel on b1 from refunded: cancel is not allowed from refunded
================================================================
A10 Out of order: pay after cancel. Cancel a checked-out booking, then pay and confirm it.
attacks I7; corresponds to WSTG-BUSL-06; ASVS 2.3.1
expected refusal: 409 on pay and on confirm; b1 stays cancelled with nothing paid.
careless
setup: 3 requests in the normal flow, answered 201 200 200
before b1: cancelled, 2 adults 0 children, total 12000, due 12000, paid 0, refunded 0
abuse customer-1 POST /bookings/b1/pay {"amountCents":12000} -> 200 {"id":"b1","state":"paid","adults":2,"children":0,"totalCents":12000,"amountDueCents":12000}
abuse customer-1 POST /bookings/b1/confirm {} -> 200 {"id":"b1","state":"confirmed","adults":2,"children":0,"totalCents":12000,"amountDueCents":12000}
after b1: confirmed, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 0
BROKEN I7: b1 was cancelled and is now confirmed
BROKEN I7: pay1 moved money on b1 after it was cancelled
holds: I1 I2 I3 I4 I5 I6
careful
setup: 3 requests in the normal flow, answered 201 200 200
before b1: cancelled, 2 adults 0 children, total 12000, due 12000, paid 0, refunded 0
abuse customer-1 POST /bookings/b1/pay {"amountCents":12000} -> 409 {"error":"pay is not allowed from cancelled"}
abuse customer-1 POST /bookings/b1/confirm {} -> 409 {"error":"confirm is not allowed from cancelled"}
after b1: cancelled, 2 adults 0 children, total 12000, due 12000, paid 0, refunded 0
holds: I1 I2 I3 I4 I5 I6 I7
logged refusal: customer-1 pay on b1 from cancelled: pay is not allowed from cancelled
logged refusal: customer-1 confirm on b1 from cancelled: confirm is not allowed from cancelled
================================================================
A11 Role confusion: the requester approves their own refund. The approver raises a refund on the customer's booking, then approves it.
attacks I5; corresponds to ASVS 2.3.5
expected refusal: 403 on the approval; nothing refunded.
careless
setup: 4 requests in the normal flow, answered 201 200 200 200
before b1: confirmed, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 0
abuse approver-1 POST /bookings/b1/refund-requests {"amountCents":12000} -> 201 {"id":"r1","bookingId":"b1","amountCents":12000,"requestedBy":"approver-1","status":"requested"}
abuse approver-1 POST /refund-requests/r1/approve {} -> 201 {"id":"ap1","requestId":"r1","bookingId":"b1","amountCents":12000,"approvedBy":"approver-1"}
abuse customer-1 POST /bookings/b1/refunds {"approvalId":"ap1"} -> 201 {"id":"ref1","bookingId":"b1","amountCents":12000,"approvalId":"ap1"}
after b1: refunded, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 12000
BROKEN I5: ap1 was approved by approver-1, who requested r1
holds: I1 I2 I3 I4 I6 I7
careful
setup: 4 requests in the normal flow, answered 201 200 200 200
before b1: confirmed, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 0
abuse approver-1 POST /bookings/b1/refund-requests {"amountCents":12000} -> 201 {"id":"r1","bookingId":"b1","amountCents":12000,"requestedBy":"approver-1","status":"requested"}
abuse approver-1 POST /refund-requests/r1/approve {} -> 403 {"error":"approver-1 requested r1 and cannot also approve it"}
abuse customer-1 POST /bookings/b1/refunds {"approvalId":"ap1"} -> 409 {"error":"claimRefund is not allowed from refund_requested"}
after b1: refund_requested, 2 adults 0 children, total 12000, due 12000, paid 12000, refunded 0
holds: I1 I2 I3 I4 I5 I6 I7
logged refusal: approver-1 approveRefund on b1 from refund_requested: approver-1 requested r1 and cannot also approve it
logged refusal: customer-1 claimRefund on b1 from refund_requested: claimRefund is not allowed from refund_requested
================================================================
careless: invariants broken after 11 of 11 cases
careful: invariants broken after 0 of 11 cases
Reading the output
setup How many normal-flow requests brought the case to its starting point, and the status each got.
before Each booking after setup, from the stored records: state, seats, total, amount due, paid and refunded, in cents.
abuse Each abuse request as account, method, path and body, then the status and body that came back.
after Each booking once the abuse requests had run, described the same way.
BROKEN An invariant that no longer holds, with the records that break it. "holds" lists the ones that do.
logged refusal The careful version's log entry for each abuse request it refused: who, which action, which booking, from which state, and why.
What the run shows
The careless version answered every abuse request in every case with 200 or 201 and well-formed JSON, and left at least one invariant broken after all 11 cases. Every one of the seven invariants was broken by at least one case.
The careful version refused each case at the step Part 3 expects, and all seven invariants held after all 11 cases.
A7 aimed at I6 and broke I2 as well, which is why every invariant is checked after every case.
A9 shows why totals are recomputed: the careless cancel refunded its running total of payments, 12000, on top of the 12000 already refunded.
==== PART 7. STEPS 2 AND 3: THE REGRESSION TEST ====
Command: node invariants.test.mjs careless
✖ careless: I1 Seat counts and amounts are whole numbers in range: at least 1 adult, 0 or more children, 8 seats at most, and every payment, refund request and refund at least 1 cent. (2.302167ms)
✖ careless: I2 A booking is confirmed only when the payments captured before confirmation equal the total its seats come to. (0.13625ms)
✖ careless: I3 The total refunded on a booking never exceeds the total paid on it. (0.090625ms)
✖ careless: I4 An approval is used once, and only for the booking and the amount it was given for. (0.083542ms)
✖ careless: I5 The person who approves a refund is not the person who requested it. (0.07775ms)
✖ careless: I6 The amount read at checkout is the amount enforced at the end: once checkout has fixed the amount due, the seats still come to that amount. (0.073792ms)
✖ careless: I7 A cancelled booking takes no further payments or refunds, and stays cancelled. (0.062667ms)
ℹ tests 7
ℹ suites 0
ℹ pass 0
ℹ fail 7
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 5.852416
✖ failing tests:
test at invariants.test.mjs:15:3
✖ careless: I1 Seat counts and amounts are whole numbers in range: at least 1 adult, 0 or more children, 8 seats at most, and every payment, refund request and refund at least 1 cent. (2.302167ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
+ [
+ 'A6: b1 has 0 adults and 0 children',
+ 'A6: b2 has 3 adults and -2 children'
+ ]
- []
(cut here: the stack trace, which shows local file paths, and the error object fields)
test at invariants.test.mjs:15:3
✖ careless: I2 A booking is confirmed only when the payments captured before confirmation equal the total its seats come to. (0.13625ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
+ [
+ 'A1: b1 was confirmed with 0 of 12000 cents captured',
+ 'A2: b1 was confirmed with 0 of 12000 cents captured',
+ 'A7: b1 was confirmed with 12000 of 36000 cents captured'
+ ]
- []
(cut here: the stack trace, which shows local file paths, and the error object fields)
test at invariants.test.mjs:15:3
✖ careless: I3 The total refunded on a booking never exceeds the total paid on it. (0.090625ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
+ [
+ 'A8: b1 has 12000 cents refunded against 0 paid',
+ 'A9: b1 has 24000 cents refunded against 12000 paid'
+ ]
- []
(cut here: the stack trace, which shows local file paths, and the error object fields)
test at invariants.test.mjs:15:3
✖ careless: I4 An approval is used once, and only for the booking and the amount it was given for. (0.083542ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
+ [
+ 'A3: ap1 was used 2 times',
+ 'A4: ref1 on b2 used ap1, given for b1',
+ 'A5: ref1 paid 12000 cents on ap1, approved for 3000'
+ ]
- []
(cut here: the stack trace, which shows local file paths, and the error object fields)
test at invariants.test.mjs:15:3
✖ careless: I5 The person who approves a refund is not the person who requested it. (0.07775ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
+ [
+ 'A11: ap1 was approved by approver-1, who requested r1'
+ ]
- []
(cut here: the stack trace, which shows local file paths, and the error object fields)
test at invariants.test.mjs:15:3
✖ careless: I6 The amount read at checkout is the amount enforced at the end: once checkout has fixed the amount due, the seats still come to that amount. (0.073792ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
+ [
+ 'A7: b1 holds seats worth 36000 cents; checkout fixed 12000'
+ ]
- []
(cut here: the stack trace, which shows local file paths, and the error object fields)
test at invariants.test.mjs:15:3
✖ careless: I7 A cancelled booking takes no further payments or refunds, and stays cancelled. (0.062667ms)
AssertionError [ERR_ASSERTION]: Expected values to be strictly deep-equal:
+ actual - expected
+ [
+ 'A10: b1 was cancelled and is now confirmed',
+ 'A10: pay1 moved money on b1 after it was cancelled'
+ ]
- []
(cut here: the stack trace, which shows local file paths, and the error object fields)
Command: node invariants.test.mjs careful
✔ careful: I1 Seat counts and amounts are whole numbers in range: at least 1 adult, 0 or more children, 8 seats at most, and every payment, refund request and refund at least 1 cent. (1.187041ms)
✔ careful: I2 A booking is confirmed only when the payments captured before confirmation equal the total its seats come to. (0.049333ms)
✔ careful: I3 The total refunded on a booking never exceeds the total paid on it. (0.036208ms)
✔ careful: I4 An approval is used once, and only for the booking and the amount it was given for. (0.033167ms)
✔ careful: I5 The person who approves a refund is not the person who requested it. (0.041125ms)
✔ careful: I6 The amount read at checkout is the amount enforced at the end: once checkout has fixed the amount due, the seats still come to that amount. (0.033333ms)
✔ careful: I7 A cancelled booking takes no further payments or refunds, and stays cancelled. (0.037625ms)
ℹ tests 7
ℹ suites 0
ℹ pass 7
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 4.16075
Exit codes, as the shell reported them after each command (node --test, run in the same folder, finds invariants.test.mjs by its name and tests the careful version):
node run-cases.mjs: exit code 0
node invariants.test.mjs careless: exit code 1
node invariants.test.mjs careful: exit code 0
node --test: exit code 0
==== PART 8. USING IT ON YOUR OWN SERVICE ====
1. Rewrite Part 1 for your own flow: your states, your actions, who may take each, and the rule checked before each runs. Ask the business, not the code, what each rule is.
2. Rewrite the invariants in Part 2 as checks against your own database tables, and keep each one's name, so a failing test, a log line and a finding all point at the same rule.
3. Rewrite the cases in abuse-cases.mjs for your own routes, with a test account in each role your flow needs, and point the runner at staging seeded with test data and test money.
4. Keep the reset between cases: restore the seeded records so one case's leftovers cannot change the next.
5. Run invariants.test.mjs on every build, as a check that has to pass before a change merges.What a business logic flaw is
An injection flaw involves a request the application should not have accepted: a script in a comment field, a quote mark in a search box.
A business logic flaw can involve requests that are each perfectly ordinary: well formed, sent from a signed-in account allowed to make that request, and answered with a success. The flaw is in the outcome: a booking confirmed with nothing paid, one approval paid out twice, three adult seats sold for less than two. The application did exactly what its code says. The code does not say what the business means.
MITRE's Common Weakness Enumeration groups these weaknesses under CWE-840, Business Logic Errors. Its terminology note says the term is generally used for issues that require domain-specific knowledge or "business rules" to determine if they are weaknesses or vulnerabilities, instead of legitimate behaviour, and that many such issues can be understood as instances of other weaknesses, such as input validation, access control, numeric computation and order of operations, among others.
In CWE version 5.0, MITRE lists CWE-840 as a grouping, not a weakness, and marks its ID as one that must not be used to map real-world vulnerabilities.
Its comments say to perform root cause analysis and consult the member weaknesses, which include CWE-837, Improper Enforcement of a Single, Unique Action, and CWE-841, the entry for improper enforcement of behavioural workflow.
OWASP's Top 10:2025 covers the same ground in A06, Insecure Design. OWASP describes the category as a broad one representing different weaknesses, expressed as missing or ineffective control design, and says it includes flaws in the business logic of an application, such as the lack of defining unwanted or unexpected state changes inside an application.
It also says an insecure design cannot be fixed by a perfect implementation, as the needed security controls were never created to defend against specific attacks. CWE-841 is among the CWEs A06 maps to the category.
OWASP's point that an insecure design cannot be fixed by a perfect implementation is why this guide starts from the rules rather than from the code. An endpoint written to a specification that never said "refund at most what was paid" can refund more than was paid, however carefully the endpoint itself is written.
Why these flaws pass the checks a scanner makes
NIST IR 8397, NIST's guidelines on minimum standards for developer verification of software, describes web application scanners as tools that create inputs as they run and monitor for general unusual behaviour, and describes dynamic testing tools monitoring for subtle hints of problems, such as an internal table name in an error message.
A business logic flaw gives no such hint. In the lab on this page, the careless version answered every one of its 22 abuse requests with a 200 or a 201 and well-formed JSON. Nothing in any single response says the booking it just confirmed was never paid for.
The WSTG and MITRE say this in their own words. The WSTG v4.2 introduction to business logic testing says this type of vulnerability cannot be detected by a vulnerability scanner and relies upon the skills and creativity of the penetration tester, and that automated tools find it hard to understand context.
MITRE's CWE-840 says business logic errors can be difficult to find automatically, since they typically involve legitimate use of the application's functionality, and that such issues might not be easily detectable via automatic code analysis, because the associated operations do not produce clear errors or undefined behaviour at the code level.
NIST IR 8397 does not mention business logic, but two of its general points bear on the subject. Its section 3.7 says static analysis tools scan for many properties and potential problems, and that some properties are poorly suited to computerised recognition, and hence may warrant human examination.
Its section 3.8 says additional test cases may be based on five principles, one of which is general security principles: find security vulnerabilities, such as failure to check credentials, since these often do not cause operational failures (crashes or incorrect output).
Other passages leave more room for tools. MITRE's entry for CWE-841 says automated static analysis can find some instances of that weakness, and NIST IR 8397 lists improving automated web application security assessment tools with respect to logical flow among the nearer-term advances that may add to security assurance.
The practical reading is narrower than "tools are useless here". A scanner does not know your rules, so it cannot tell that a successful response broke one. A test that does know them can, which is what the rest of this guide builds.
Finding the rules worth protecting: follow the money and the stock
Under Business Limits and Restrictions, the WSTG introduction says to consider the rules for the business function the application provides, asks whether there are any limits or restrictions on people's behaviour, and then says to consider whether the application enforces those rules.
It says that if you are a third-party tester, you will have to use your common sense and ask the business whether different operations should be allowed by the application. Either way, the rules come from the business. The code can only tell you what was built.
A practical way to find those limits and restrictions is to follow the money and the stock. List every place where money moves: a payment captured, a refund paid, a credit issued, a voucher redeemed, a payout to a supplier.
Then list every place where something limited changes hands: a seat, a time slot, an item of stock, a free trial, a referral reward. Each of those is a step where someone gains if a rule is skipped, so each needs its rules written down: who may trigger it, from which states, for what amount, how many times, and what has to be true before and after.
ASVS 5.0 asks for limits to be written down. Requirement 2.1.3, at Level 2, asks that expectations for business logic limits and validations are documented, including both per-user and globally across the application. Requirement 2.3.2, also at Level 2, asks that business logic limits are implemented per the application's documentation to avoid business logic flaws being exploited.
OWASP's A06 gives an example of such a limit: a cinema chain that allows group booking discounts and has a maximum of fifteen attendees before requiring a deposit.
OWASP says attackers could threat model this flow and test if they can find an attack vector in the business logic of the application, for example booking six hundred seats and all cinemas at once in a few requests.
Some flows are sensitive for a different reason: each use follows the rules, and the harm comes from using them too much. OWASP's API Security Top 10 2023 entry API6, Unrestricted Access to Sensitive Business Flows, says an API endpoint is vulnerable if it exposes a sensitive business flow without appropriately restricting the access to it, and gives making a reservation, where an attacker can reserve all the available time slots and prevent other users from using the system, among its common examples.
How often a flow may be used belongs with the rate limiting guide in this library. This guide deals with whether each single use keeps the rules.
Writing each rule as an invariant a test can check
An invariant is a sentence about stored records that should be true after every request, whatever requests came before.
"Refunds need approval" is a policy. "The total refunded on a booking never exceeds the total paid on it" is an invariant, because a test can add up two sets of records and compare them.
Three habits make an invariant checkable. Write it about records, not screens: "the person who approves a refund is not the person who requested it" can be checked against stored approvals, where "only staff see the Approve button" cannot be checked at all. Recompute what it compares from the stored records each time, rather than trusting a running total, because a running total is one more value a careless step can leave wrong.
And give every invariant a short name, so a failing test, a log line and a finding in a report can all point at the same rule.
The WSTG introduction says testing for business logic flaws is similar to the test types used by functional testers that focus on logical or finite state testing, and that these types of tests require security professionals to think a bit differently, develop abuse and misuse cases and use many of the testing techniques embraced by functional testers.
OWASP's A06 recommends writing unit and integration tests that validate all critical flows are resistant to the threat model, and compiling use-cases and misuse-cases for each tier of the application. An invariant is what turns a misuse case into a pass or a fail.
A worked state machine for an invented booking service
The lab on this page uses an invented tour operator. An adult seat is 6000 cents and a child seat 3500 cents, a booking holds 1 to 8 seats with at least one adult, and there are two roles: a customer, who owns their bookings, and a staff approver.
A booking moves through eight states: draft, payment pending, paid, confirmed, refund requested, refund approved, refunded and cancelled. The transitions, with who may take each one and the rule checked before it runs:
- Customer: create a booking and edit its seats, while it is a draft.
- Customer: check out, which moves a draft to payment pending and fixes the amount due from the stored seats.
- Customer: pay, which moves payment pending to paid, for exactly the amount due. In the lab this stands in for a captured card payment.
- Customer: confirm, which moves paid to confirmed, only when the payments captured equal the total.
- Customer, or staff on the customer's behalf: request a refund on a confirmed booking, for at least 1 cent and at most what has been paid and not yet refunded.
- Approver: approve the request, if they did not raise it. The approval is bound to one booking, one amount and one use.
- Customer: claim the approved refund, which moves the booking to refunded, or back to confirmed while part of the payment is still unrefunded.
- Customer: cancel a draft, a booking awaiting payment or a confirmed booking. Cancelling refunds whatever is left: paid minus refunded.
- Every other action from every other state is refused.
The seven invariants
Each one below is a function in the lab that reads only stored records and lists the records that break it. The asset maps each to the WSTG test or ASVS requirement it follows, or marks it as this page's own.
- I1:seat counts and amounts are whole numbers in range: at least 1 adult, 0 or more children, 8 seats at most, and every payment, refund request and refund at least 1 cent.
- I2:a booking is confirmed only when the payments captured before confirmation equal the total its seats come to.
- I3:the total refunded on a booking never exceeds the total paid on it.
- I4:an approval is used once, and only for the booking and the amount it was given for.
- I5:the person who approves a refund is not the person who requested it.
- I6:the amount read at checkout is the amount enforced at the end: once checkout has fixed the amount due, the seats still come to that amount.
- I7:a cancelled booking takes no further payments or refunds, and stays cancelled.
Why each endpoint checking its own inputs is not the flow being enforced
The careless version in the lab is not sloppy code.
Each endpoint checks its own inputs: seat counts are whole numbers, amounts are positive, a refund is no larger than the booking, an approval exists. The shared service code checks who is signed in, which role may call the endpoint and, for a customer, that the booking is theirs.
A reviewer reading any one handler would find little to object to. Across the eleven cases it still left every one of the seven invariants broken at least once, because no endpoint asks the question that spans them: where is this booking in its flow, and what has already happened to it?
MITRE's CWE-841 describes the weakness: the product supports a session in which more than one behaviour must be performed by an actor, but it does not properly ensure that the actor performs the behaviours in the required sequence or timeframe.
It says workflow-related behaviours include: steps are performed in the expected order, required steps are not omitted, steps are not interrupted, and steps are performed in a timely fashion.
It adds that by performing actions in an unexpected order, or by omitting steps, an attacker could manipulate the business logic of the product or cause it to enter an invalid state.
WSTG-BUSL-06, Testing for the Circumvention of Work Flows, says the application's business logic must require that the user complete specific steps in the correct order, and that if the workflow is terminated without correctly completing, all actions and spawned actions are rolled back or cancelled.
Its first example is a loyalty scheme where, after points have been added to their account, a customer cancels out of the transaction or removes items from their basket and tenders, and it says the system should either not apply the points until the sale is tendered, or roll them back if they do not match the final tender.
Case A7 in the lab shows how valid inputs add up to a broken flow. Checkout fixes an amount due of 12000 cents for two adults. The careless edit endpoint then accepts six adults, because six is a valid whole number. The careless payment endpoint accepts 12000 cents, because that is a positive amount, and the careless confirm endpoint confirms the booking it is given.
Every check passed, and the booking ended up confirmed for six adults with 12000 of 36000 cents captured.
Where the enforcement belongs
On the server.
ASVS 5.0 requirement 2.2.2, at Level 1, asks that the application is designed to enforce input validation at a trusted service layer, and says that while client-side validation improves usability and should be encouraged, it must not be relied upon as a security control.
WSTG-BUSL-03, Test Integrity Checks, says the application must not depend on non-editable controls, drop-down menus or hidden fields for business logic processing, because these fields remain non-editable only in the context of the browser, and that if it exposes values related to business rules, such as quantity, as non-editable fields, it must maintain a copy on the server side and use that copy for business logic processing.
In one place. The lab's careful version keeps a single transition table: for each action on an existing booking, the states it may start from and a guard for its business rule. Every endpoint that acts on an existing booking is a thin call into one function, runTransition, which refuses the action if the booking is in the wrong state, runs the guard, writes a log entry and only then applies the change.
Creating a booking has no starting state, so that endpoint runs the seat guard and writes the same kind of log entry itself.
Adding an action on an existing booking means adding a row to that table, where its starting states and its guard sit beside those of every other row.
Next to the data. In the careful version an approval records the booking, the amount and the request it came from, and is marked used in the same step that pays it out. A claim is refused if the booking or the amount does not match, or if the approval has been used.
Totals are recomputed from the stored payments and refunds every time, never read from a running total or from the request. WSTG-BUSL-05's remediation says the application should set hard controls to prevent limit abuse, and that this can be achieved by setting a coupon to be no longer valid on the database level, or by setting a counter limit per user on the back end or database level, whichever is better for the business requirement.
All or nothing. ASVS 5.0 requirement 2.3.3, at Level 2, asks that transactions are used at the business logic level, so that a business logic operation either succeeds in its entirety or is rolled back to the previous correct state. In a real database, the state check, the guard and the write belong inside one transaction.
The lab sends its requests one after another and keeps its records in memory, so it shows the order of the checks, not the locking. Two requests arriving at the same moment are the subject of the race conditions guide in this library.
Five families of abuse case, played with two accounts
Each case in the asset takes the normal flow to a starting point with two invented accounts, customer-1 and approver-1, then sends the requests that try to break one invariant straight to the API.
The asset gives every case in full, with its expected refusal and the evidence to keep. Here is what each family tests and what the lab showed.
WSTG-BUSL-06's objectives are to review the project documentation for methods to skip steps in the application process, or go through them in a different order from the intended business logic flow, and to develop a misuse case and try to circumvent every logic flow identified.
ASVS 5.0 requirement 2.3.1, at Level 1, asks that the application only processes business logic flows for the same user in the expected sequential step order and without skipping steps. Case A1 sends the last step first, confirming a draft that was never checked out.
Case A2 checks out and then confirms with nothing paid. The careless version confirmed both. The careful version answered 409 in both, because confirm is allowed only from paid.
MITRE's CWE-837 is the weakness where the product requires that an actor should only be able to perform an action once, or to have only one unique action, but does not enforce or incorrectly enforces this restriction. WSTG-BUSL-05's objectives are to identify functions that must limit the number of times they can be called and assess whether that limit is set and properly validated.
Case A3 claims approval ap1 a second time, after it has paid out, while a smaller approval waits on the same booking. Case A4, this page's own, claims a refund on booking b2 with the larger approval given for b1.
The careless version paid out both times. The careful version refused with 409, once because ap1 had already been used and once because it was given for b1, not b2.
WSTG-BUSL-01 has the tester insert logically invalid data into the application to verify that the server does not accept it. ASVS 5.0 requirement 2.2.1, at Level 1, asks that input is validated to enforce business or functional expectations, either against an allow list of values, patterns and ranges or against an expected structure and logical limits according to predefined rules, and says that at Level 1 this can focus on input used to make specific business or security decisions.
WSTG-BUSL-03 adds that where users are able to make changes, they should only be able to write or update specific artefacts at specific times per the business process logic.
Case A5 claims an approval for 3000 cents with 12000 in the request body, and the careless version refunded 12000. Case A6 books zero seats, then three adults and minus two children, and the careless version confirmed three adult seats for 11000 cents, less than two adults come to.
Case A7 changes the seats after checkout. The careful version answered 409, 422 and 409, and confirmed A7's booking for the two adults that checkout fixed.
Each of these cases sends a real step at the wrong moment, the kind of unexpected order CWE-841 says can put a product into an invalid state. Case A8 asks for a refund on a booking that is checked out but not paid, and the careless version refunded 12000 cents against nothing paid.
Case A9 cancels a booking that has already been refunded in full, and the careless cancel refunded its running total of payments again, leaving 24000 refunded against 12000 paid.
Case A10 pays for and confirms a booking that was already cancelled. The careful version refused all three with 409, at the first step that was out of order.
In A8 the approver approved a refund on a booking with nothing paid. The lab scripts that request, and it stands for a person who expects the approval queue to hold only requests the system has already checked. An approval adds a second person's judgement; it does not replace the state check that should have refused the request first.
ASVS 5.0 requirement 2.3.5, at Level 3, asks that high-value business logic flows require multi-user approval to prevent unauthorised or accidental actions, and says this could include, but is not limited to, large monetary transfers, contract approvals, access to classified information or safety overrides in manufacturing. Multi-user approval means something only when the second user is a different person, which is invariant I5.
In case A11 the approver raises a refund request on a customer's booking, which staff are allowed to do, and then approves it. The careless version let the approval through; the careful version answered 403.
A customer reaching the approve endpoint at all would be a vertical access control failure, which the broken access control guide covers. Both versions of the lab share a role table that lets only the approver role call approve. The case here is the right role in the wrong position in the flow.
What to log so that a broken rule is noticed
ASVS 5.0 requirement 16.3.3, at Level 2, asks that the application logs the security events defined in its documentation and also logs attempts to bypass the security controls, such as input validation, business logic and anti-automation.
WSTG-BUSL-07, Test Defenses Against Application Misuse, lists kinds of misuse that often have no defence, among them accessing a multi-stage business process in the wrong order, and multiple input validation or business logic verification failures with values that cannot be the result of user mistakes or typos.
A refused transition is the event to log, with enough detail to read it later without the code: who asked, which action, on which booking, from which state, and the rule that refused it. The careful version logs every attempt that reaches its rules in that form, and its refusal in case A11 reads: "approver-1 approveRefund on b1 from refund_requested: approver-1 requested r1 and cannot also approve it".
Four requests in its captured run, three in case A6 and one in A8, never reached those rules, because the shared service answered 404 for a booking or a refund request that did not exist, and they have no log entry.
One account collecting refusals for confirm, claim and cancel on the same booking resembles the misuse WSTG-BUSL-07 lists. That pattern is worth an alert.
Log the money movements that were allowed as well: each payment, each approval with who gave it, and each refund with the approval it used. OWASP's A09:2025, Security Logging and Alerting Failures, counts high-value transactions not being logged among its failures, and recommends giving transactions an audit trail with integrity controls to prevent tampering or deletion.
That trail is what answers "who approved this?" after the fact, and it is what the invariant checks run against. Keep card details out of it: ASVS 5.0 requirement 16.2.5, at Level 2, gives credentials and payment details as examples of data it may not be allowed to log.
Alert thresholds, retention and where the logs are sent belong in the security logging and monitoring guide planned for this library.
Testing a flow on your own application with two accounts
Run these tests only on an application you own, or one you are authorised in writing to test, on staging where you can, with test accounts and test money.
Leave real customers' bookings, payments and cards out of it.
- Write the state machine and the invariants first, from what the business says each rule is, not from what the code does.
- Create an account for each role the flow needs. For a refund flow that means a customer and a staff approver, and if staff can raise requests on a customer's behalf, give the approver that ability too, so the self-approval case can run.
- For each case, take the normal flow to the starting point, then send the abuse requests straight to the API rather than through the screens. WSTG-BUSL-02 describes forging requests as going around the front end to submit information directly for back end processing, with data values the business logic does not support, guard against or expect.
- Keep the evidence: every request with its account, method, path and body; every response with its status and body; and the state before and after of every record the case touched, read from the database rather than from the screen.
- Check every invariant after every case, not only the one the case attacks. In the lab, case A7 aimed at I6 and broke I2 as well.
- Reset the records between cases, so one case's leftovers cannot change the next.
- Keep the cases as a regression test that runs on every build.
Keeping the cases as a regression test
NIST IR 8397 says some test cases are created specifically to show the presence, and later the absence, of a bug, and that these are sometimes called regression tests. The lab's invariants.test.mjs runs one test per invariant on the Node.js test runner (node:test), which the Node.js documentation says sets the process exit code to 1 if any test fails. A pipeline step that runs it therefore fails while any case leaves an invariant broken.
The lab: one booking service, careless and careful
The lab is an illustration written for this page, not client code.
The tour operator, its two accounts, its bookings and its money are invented. All money is counted in whole cents and held in memory, and the pay endpoint stands in for a captured card payment without charging anything. It shows the pattern, not the behaviour of any real payment provider.
It is seven files. booking-rules.mjs holds the seat prices, the stored records and the seven invariants as code. careless.mjs and careful.mjs are the two versions. service.mjs serves either version over HTTP and holds the checks both share. abuse-cases.mjs holds the eleven cases as data and plays them. run-cases.mjs prints the evidence, and invariants.test.mjs is the regression test. The lab imports only node:child_process, node:crypto, node:http, node:url, node:assert/strict and node:test, and installs no packages.
The service runs as its own process, listening only on 127.0.0.1 and asking for port 0. The Node.js documentation says that when the port is 0 the operating system assigns an arbitrary unused port. The runner starts the service, plays every case with the two invented accounts, and stops the service by its process id when the run ends.
On Node.js 26.0.0 on macOS, the careless version left at least one invariant broken after all 11 cases, and each of the seven invariants was broken by at least one case. The careful version refused each case at the step the asset expects, and all seven invariants held after all 11.
The regression test failed all 7 of its tests on the careless version, with exit code 1, and passed all 7 on the careful version, with exit code 0.
What this guide leaves to other guides
Business logic sits beside several neighbouring topics, each with a guide of its own in this library:
- Broken access control and IDOR: whether an account may reach a record or a function at all, where this guide assumes it may and asks whether it may do this now, for this amount, or again.
- Race conditions: two requests arriving at the same moment, so that a check and the write after it are separated by someone else's write.
- Rate limiting: how many times a flow may be used per account, address or window, one defence for flows that do harm in bulk.
- Security logging and monitoring, a guide planned for this library: where the refusals and money movements described here are kept, for how long, and what raises an alert.
- Methodology: how a Clever Ops web application test runs, from scope to retest, including the business-logic checkpoints in its coverage matrix.
Where an outside test fits
Your own invariants cover the rules you wrote down.
In a Clever Ops web application and API penetration test, business logic tests hold the application to the rules list in the scope, using two test accounts in each role. A business-logic flaw is only a flaw against a rule, so the scope asks for your key rules in writing, and a state machine and invariant list like the ones on this page set those rules out.
Destructive actions are off by default for real people's accounts and records that existed before the test, and reset, lockout and deletion checks run only on test accounts and test records where the rules of engagement allow them. Payment checks run against a staging copy linked to a non-live payment account wherever one is available, so no real card is charged.
The report gives each finding with redacted evidence, its business impact, a fix and the criteria the retest will use.
Very logic-heavy products, such as marketplaces, lending platforms and multi-tenant billing, are scoped individually or referred to a larger firm. If Clever Ops built or hosts your application, the work is a security review rather than an independent test, and the report says who built it and who hosts it.
Frequently asked questions
A flaw in the rules an application enforces rather than in how it handles input. Each request is valid on its own, and the order, the values or the person sending them break a rule the business relies on, such as confirming a booking with nothing paid or refunding more than was paid. MITRE groups these under CWE-840, Business Logic Errors, and OWASP's Top 10:2025 covers business logic flaws in A06, Insecure Design.
The WSTG v4.2 says this type of vulnerability cannot be detected by a vulnerability scanner, and MITRE says business logic errors can be difficult to find automatically because they typically involve legitimate use of the application's functionality. A scanner does not know your rules, so a success response that breaks one looks like any other success. Tests written from your own invariants can check those rules on every build.
Testing whether an application enforces the rules of the business: steps happen in order, one-time actions happen once, amounts and limits add up, and approvals come from someone other than the requester. The WSTG v4.2 covers it in its business logic testing section, which runs from WSTG-BUSL-01 to WSTG-BUSL-09. The method on this page writes each rule as an invariant and plays abuse cases with two accounts against it.
Using an application's steps in an order or combination its designers did not intend: confirming without paying, cancelling after a refund to be refunded again, or paying for a booking that was already cancelled. MITRE's CWE-841 describes the weakness behind it as a product that does not properly ensure an actor performs the required behaviours in the required sequence or timeframe.
Write the limit as an invariant about stored records, such as "the total refunded never exceeds the total paid", then try to break it: change the amount after it was checked or approved, send zero or a negative value, change the quantity after checkout, and reuse an approval. Check the stored totals after each attempt, not only the response. Do this on an application you own or are authorised in writing to test, with test accounts and test money.
Access control decides whether an account may reach a record or a function at all. Business logic decides whether an account that may reach it can do this now, in this order, for this amount, or again. A customer reading another customer's booking is an access control failure. A customer claiming their own approved refund twice is a business logic flaw.
Scope the right test for your application
Tell us what you have built, who uses it and when it needs to launch. You will get a plain-English recommendation: a website audit, a web application test or a referral to a specialist.