Audit playbook for business logic flaws (workflow bypass, price tampering) and race conditions (TOCTOU, double-execution) across languages and frameworks. Provides reproduction recipes, evidence, and fixes.
Ships in Aegis Skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Audit the target repository for flaws where the application trusts the client's data, ordering, or timing instead of enforcing its own rules: checkout steps that can be skipped, totals that arrive precomputed, balances debited through unsynchronized read-modify-write sequences, trials extended by client clocks, limits counted on the wrong field, approvals signed by their own requester. For every finding produce file:line evidence, a static-first reproduction recipe, a severity with rationale, and a stack-correct fix built around transactions, row locks, atomic conditional updates, idempotency keys, or server-side transition guards.
| Class | Typical finding | Primary CWE |
|---|---|---|
| Workflow / state-machine bypass | Direct call to the order-creation endpoint skipping payment; UI-only email-verification gate; password change without old password; step tokens accepted unsigned or unvalidated | CWE-20 (where a client-set field drives the transition) |
| Price / quantity / amount tampering | Client-computed total persisted as-is; negative quantities minting store credit; coupon stacking without validation; unlimited discount-code reuse; floating-point money | CWE-20 |
| Race conditions (check-then-act) | Balance check then debit; stock decrement; voucher single-use enforcement; rate-limit counters themselves; uniqueness at signup | CWE-362 |
| TOCTOU on resources | Upload published before or during malware scan; expiry checked at render but not at action; permission revocation vs live sessions | CWE-367 |
| Double execution | Double-spend, double-vote, double-refund; missing idempotency keys on payment endpoints; webhook replay | CWE-362 |
| Limit / counting logic | Check on one field, increment on another; per-request vs per-day windows; soft-delete resurrecting quotas | CWE-362 |
| Approval / multi-party flows | Self-approval, unenforced approval order, circular delegation chains, four-eyes claimed but single-principal path exists | Design finding (CWE-20 when client-set status drives it) |
| Referral / cashback / gift systems | Self-referral loops, gift-card brute force, negative-amount transfers crediting both sides | CWE-20 |
| Cross-user enumeration inside business flows | Pagination walking others' orders, invoices, vouchers to farm codes or balances | CWE-639 |
Workflow bypasses with no client-set field map to OWASP A04:2021 (design weakness) rather than a single code-level CWE; document them as design findings with the transition table as evidence.
status, price, or balance field found there becomes a workflow or tampering candidate here.Read-only repository access; no running instance guaranteed. Static confirmation grounded in documented framework semantics (transaction scopes, lock modes, database constraint behavior) is sufficient evidence for reporting. Dynamic reproduction only against explicitly authorized environments; the concurrent-request recipes in this module assume written authorization.
Zero-background primer: the terms this module uses, one line each. Deeper plain-language explanations for every class live in the repository GUIDE.md glossary.
An order moves CART -> SUBMITTED -> PAID -> SHIPPED. A voucher moves ACTIVE -> REDEEMED. A withdrawal is a transition on a balance. Screens, buttons, wizard steps, and disabled controls are presentation; the only real machine is the set of legal transitions the server enforces. Findings appear wherever the server lets a caller choose a transition directly (skip), repeat a transition (replay or race), or supply the operands of the transition (tamper). Start every audit by locating the machines: enumerate entities carrying lifecycle columns (status, state, stage) and enumerate every handler that mutates them.
For every business-critical transition, ask and answer in writing:
if guarding the write; determine whether anything (an await, a network call, a second statement) sits between check and write, and whether the pair shares one transaction with a lock.Map answer patterns to finding classes:
| Answer pattern | Finding class |
|---|---|
| Q1: later step reachable out of order | Workflow bypass |
| Q2: yes | Tampering (price, quantity, state, time) |
| Q3: unprotected gap | TOCTOU race (CWE-362 / CWE-367) |
| Q4: twice is profitable | Double-spend / replay |
| Q4: zero times achievable | Precondition bypass (forced-error state) |
| Q5: no | Payment and webhook replay risk |
Family one, trusted data: the server executes correct logic on attacker-chosen operands (totals, currencies, quantities, statuses, timestamps, step tokens). Family two, trusted ordering and timing: the server executes correct logic assuming each operation happens once, in sequence, alone; concurrency, retries, and direct calls violate each assumption. Grep differently per family: the data family greps for assignments sourced from request objects; the ordering family greps for read-modify-write pairs and for the absence of transaction vocabulary around money writes.
Balances, credits, points, stock, quota, vote tallies, redemption counters: each is a counter whose integrity equals financial or entitlement integrity. A counter updated by application-side arithmetic (read x.balance, subtract in code, save) is a race waiting for its first concurrent pair. Demand atomic shapes everywhere: a single conditional UPDATE, a filtered $inc, an INCRBY inside Lua, or a row-locked transactional decrement. Anything less is a finding.
Payment webhooks, mobile clients on flaky links, orchestrator retries, browser double-clicks, and proxy retransmits guarantee every mutating endpoint eventually receives duplicates. The absence of idempotency protection on charge, refund, transfer, payout, and provisioning endpoints is a finding on its own, even before any race exists.
Any gap between check and write widens under load and is trivially weaponized by firing tens of parallel requests; once scripted, attack complexity is Low. In-process locks (Python threading.Lock, Java synchronized, Go sync.Mutex) exclude competitors within one process only; production deployments run many workers and replicas. Real exclusion lives in the shared datastore: row locks, atomic statements, unique indexes, and serialized queues. Treat every in-process guard around money as decorative until the database agrees.
order.status == PAID), never from trusting an echoed step token or hidden-field value.routes.js, App.tsx, Angular canActivate, React ProtectedRoute, Vue beforeEnter, Next.js middleware). A guard existing only in the router is UI-only; confirm the paired API handler enforces the same predicate.status, state, step, verified, approved, is_paid read from body/query/form. Each hit is a transition the client can drive.step_token, checkout_session, flow_id values must be checked against server session state and bound to one user and one next state. Unsigned, globally guessable, or reusable tokens fail.new_password is a finding (session theft escalates to permanent takeover).onboarding_complete-style predicate and verify every downstream endpoint enforces it, not just the dashboard redirect.total, subtotal, grand_total assignments. If the value originates from the request body, or the server persists whatever arrives, record the endpoint: totals must be recomputed at write time from catalog data.unit_price: legitimate clients may echo prices, but the server must ignore them and join catalog prices itself. Confirm in the persistence path, not the DTO.currency. Flag client-selected currency applied to fixed-price catalog items (JPY-priced item paid as nominal USD), missing currency on money columns, and any float/double holding money (float price, JS arithmetic on cents). Demand integer minor units or DECIMAL.-1 quantities, -100 refund/transfer/top-up amounts, zero-cost orders. Verify validation (@Positive, @Min(0), schema minimum) actually executes on every write path including admin panels, importers, GraphQL resolvers, and queue consumers.findOne, get, SELECT) -> CONDITION (if balance >= x) -> WRITE (save, UPDATE, decrement). Record file:line for both READ and WRITE. Absent a single transaction containing a row lock, or replacement by one conditional atomic statement, log a CWE-362 candidate.UNIQUE(voucher_id) (or (voucher_id, user_id)), or an atomic conditional UPDATE checking affected rows. A boolean flip via read-modify-write fails under concurrency.exists() probe; duplicate-key errors should surface as friendly conflicts.INCR/INCRBY with expiry or a Lua script.trial_end / trial_ends_at is computed. Flag derivation from client-supplied timestamps (body started_at, header dates, client-asserted JWT claims). Deadlines derive from the server clock at creation and compare against the server clock at use.now(). Render-time-only checks leave action endpoints usable past expiry.Carbon::now() vs DB NOW() vs JS Date). "23:59 local" evaluated in UTC opens bypass windows; recurring jobs during DST fall-back can execute twice.exp/nbf against server clock with small skew tolerance. Flag client-asserted iat or custom claims feeding trial or cooldown math.MAX_*, max_uses, daily_limit) with the field incremented at consumption. Mismatches (check usage_count, increment uses; check per-user, increment global) produce either permanent blockage or infinite allowance.WHERE deleted_at IS NULL) while the limit intends lifetime totals, purging history resurrects quota. Compare count-query filters against business intent.approved_by accepted from the payload is a self-approval primitive.created_by == approver_id refused) wherever four-eyes is claimed.SUBMITTED -> APPROVED legal; approve-before-submit or approve-after-cancel illegal).referred_by with immediate credit equals an infinite money loop given disposable identities; document the economics.updated_at guard) before any state mutation.Build the audit surface with filename and symbol searches (adapt to repo layout):
| Domain | Path/name keywords | Entity/symbol keywords |
|---|---|---|
| Orders/checkout | checkout, cart, order, basket | Order, Cart, LineItem, place_order, submitOrder |
| Payments/ledger | payment, billing, ledger, wallet, invoice | Charge, Refund, Balance, LedgerEntry |
| Promotions | coupon, promo, discount, voucher, gift | Coupon, Redemption, GiftCard |
| Entitlements | plan, subscription, trial, quota, entitlement | Subscription, Usage, Allowance |
| Trust transitions | verify, kyc, onboard, approve, review | Verification, Approval, KYCStatus |
| Movement | transfer, withdraw, payout, topup, cashback, referral | Transfer, Withdrawal, Reward |
| Scarce goods | inventory, stock, seat, slot, reservation | StockItem, Reservation |
migrations/, db/schema.rb, prisma/schema.prisma, JPA @Entity classes, Django models.py): constraints here are ground truth. For each money/state column record: type (DECIMAL or bigint minor units vs float), NULLability, defaults, UNIQUE indexes, CHECK constraints, foreign keys.ProtectedRoute, canActivate, beforeRouteEnter, stepper libraries), disabled buttons, hidden form sections. Each corresponds to a server-side check that must exist independently of the client.Run all regexes from the repo root with ripgrep; expect noise, then triage by opening hits. Keep patterns single-line (no lookarounds, no cross-line matching) for ripgrep compatibility.
\b(findOne|findById|findFirst|firstOrFail|get_object_or_404|objects\.get)\b.{0,60}\b(account|wallet|balance|stock|inventory|quota|coupon|voucher|credit|points)\b
\.(balance|stock|quantity|credits|points|uses|usage_count)\s*=\s*[^=]
\b(save|persist|updateOne|updateMany|update\(|SaveChangesAsync|flush)\(
\b(INCR|DECR|INCRBY|DECRBY|increment|decrement|incrBy)\(
A hit pairing line one (READ), line two (in-place assignment), and line three (WRITE) inside one handler is the canonical race shape; capture all three file:line references as evidence.
if\s*\(?\s*[\w.]*\b(balance|stock|remaining|available|slots|seats|credits|quota|uses_left|max_uses)\b\s*(>=?|<=?|==|!=)
\bexists\(|\bexists\?\(|\.Exists\(|countDocuments
\b(count\(\)|COUNT\(\*\)|count\(\*\))\b.{0,40}(<|>|<=|>=)
/(pay|charge|refund|withdraw|deposit|transfer|redeem|payout|topup|purchase|subscribe|cashback|reward)s?
Search within roughly +/- 40 lines of each money-mutating handler body. These keywords are the expected companions of safe writes:
select_for_update|with_for_update|FOR UPDATE|LOCK IN SHARE MODE|with_lock|lock!|lockForUpdate
PESSIMISTIC_WRITE|LockModeType|SERIALIZABLE|Isolation\.
DB::transaction|TransactionScope|BeginTx|begin_transaction|withTransaction|startSession
WATCH|\bMULTI\b|\bEVAL\b|evalsha|redis\.Lua|atomic\(|F\("balance"\)|F\('balance'\)
Absence-marker judgment rule: absence of this vocabulary near a money write is a lead, never proof. Before reporting: check global wrappers (Django ATOMIC_REQUESTS = True in settings, base-controller transactions, ORM unit-of-work behavior); note that atomicity wrappers give rollback, not mutual exclusion, so a globally-atomic request can still race its reads. Report the specific unlocked READ/CONDITION/WRITE lines with file:line, not "missing keyword". Conversely, if a lock or atomic statement does exist up the call chain, drop the candidate.
req\.body\.(status|state|step|stage|verified|approved|is_paid|role)
["'](status|state|step|verified|approved|is_paid)["']\s*:
request\.data\.get\(["'](status|state|step|approved|verified)
\$_(POST|GET|REQUEST)\[["'](status|state|step|approved|verified)["']\]
["']?(total|grand_total|amount_due|final_total|unit_price|price|amount|discount_value|currency)["']?\s*[:=]\s*-?[0-9"']
(float|double|Float|Double)\s+(price|amount|total|balance|fee)
Math\.round\(.{0,30}(price|amount|total)|toFixed\(2\)
Date\.now\(\)|new Date\(\)|datetime\.now\(\)|time\.Now\(\)|Time\.now|Carbon::now|LocalDateTime\.now|Instant\.now\(\)
\biat\b|\bexp\b|\bnbf\b|claims\[.(iat|exp|nbf).\]|issuedAt|expiration
trial_(start|end|days)|trialStart|trialEnd|expiresAt|expires_at|valid_until|reset_at|period_start
max_uses|usage_limit|usage_count|times_used|redemption_count|daily_limit|per_day|monthly_quota|[A-Z_]*MAX_[A-Z_]+
window_start|next_reset|rolling|fixed_window
page_size|pageSize|\boffset\b|cursor=
(approved_by|approver|reviewer_id|rejected_by|delegated_to|four_?eyes)
(created_by|author_id|requester).{0,30}(==|!=|equals).{0,30}(approver|user_id|current_user)
status\s*(===?|==)\s*["'](APPROVED|Approved|PAID|SHIPPED)["']
Idempotency[-_ ]?Key|idempotency_key|idempoten[a-z]*|event_id|eventId|dedup[a-z]*|\bnonce\b|replay
Zero hits across a repo containing payment endpoints is itself a high-priority lead.
| Stack | Required primitive for counter safety |
|---|---|
| Python/Django | select_for_update() inside transaction.atomic(); F() expressions for single-column deltas |
| Python/SQLAlchemy | with_for_update() on the SELECT within one session.begin() |
| Java/JPA | LockModeType.PESSIMISTIC_WRITE or @Version columns inside @Transactional |
| C#/EF Core | [Timestamp] RowVersion concurrency token or guarded ExecuteUpdate; explicit TransactionScope |
| Node/Mongo | findOneAndUpdate({_id, balance: {$gte: amt}}, {$inc: {...}}); multi-document work via session withTransaction (replica set required) |
| Node/Redis | Lua script (check+write atomically) over WATCH/MULTI/EXEC retries |
| Go | database/sql BeginTx plus SELECT ... FOR UPDATE; never sync.Mutex across replicas |
| Ruby/Rails | ActiveRecord::Base.transaction with .lock / with_lock; SQL-side deltas |
| PHP/Laravel | DB::transaction(fn) plus lockForUpdate(); decrement() compiles to atomic SQL |
| SQL itself | UPDATE ... SET col = col - :x WHERE ... AND col >= :x plus UNIQUE indexes as final backstop |
| Source | Trust level | Handling rule |
|---|---|---|
Body/query fields (price, total, qty, currency, status, step, approved_by) | Attacker-controlled | Never drive money or state transitions directly; recompute or reject |
Headers (Idempotency-Key, client dates) | Semi-controlled | Key: opaque dedupe token bound to user plus request hash. Dates: never feed expiry math |
| JWT/session claims | Trusted only if server-signed and server-issued | Client-asserted iat or custom trial_start claims are attacker-controlled |
| Webhook payloads | Attacker-influenceable | Verify signature first, de-duplicate event id second, mutate third |
| Catalog/database-derived values | Trusted | The only legitimate operands for totals and pricing |
items[] loops multiply tampering (one legitimate line item hides one negative-quantity item). Trace per-element handling and per-element validation.Treat as sinks: writes to balance, credits, points, stock, usage_count, lifecycle status/state columns, expires_at/trial_end fields, reward or grant inserts, role/permission grants, and any third-party money API call (stripe.Charge.create, payout SDKs, bank transfer APIs). A tainted operand reaching a sink is a candidate finding. A tainted operand reaching only a comparison (if body.total == computed.total) is a weak guard at best: equality still leaks an oracle, and the computed side may itself consume tainted inputs.
Execute dynamic reproduction only against environments you are explicitly authorized to test. When no instance exists, deliver the static trace (see Static-Only Confirmation Protocol) as the reproduction of record.
BASE="https://target.example"
TOKEN="eyJ..." # authenticated low-privilege test session
for i in $(seq 1 10); do
curl -s -o "resp_$i.json" -w "%{http_code} " \
-X POST "$BASE/api/vouchers/redeem" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{"code":"WELCOME50"}' &
done
wait; echo
grep -h -o '"success":[a-z]*' resp_*.json | sort | uniq -c
Equivalent xargs form:
printf '%s\n' $(seq 1 10) | xargs -P10 -I{} curl -s -X POST "$BASE/api/vouchers/redeem" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{"code":"WELCOME50"}' -o "resp_{}.json"
grep -l 'success.:true' resp_*.json | wc -l
"success":true / HTTP 200 for one voucher; account credited multiple times. Patched behavior: exactly one success, remainder 409/422.for i in $(seq 1 2); do
curl -s -X POST "$BASE/api/wallet/withdraw" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{"amount":100.00,"destination":"ext-test-acc-1"}' &
done
wait
curl -s "$BASE/api/wallet/balance" -H "Authorization: Bearer $TOKEN"
(balance / N) + 1 each.Checkout-without-payment sequence:
# 1. Create cart through the normal entry point.
CART_ID=$(curl -s -X POST "$BASE/api/cart" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d '{"items":[{"sku":"SKU-1","qty":1}]}' | grep -o '"id":"[^"]*"' | head -1)
# 2. Jump directly to order creation, skipping POST /api/payments entirely,
# supplying the status field the payment step would have set.
curl -s -X POST "$BASE/api/orders" \
-H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
-d "{\"cart_id\":\"$CART_ID\",\"status\":\"SUBMITTED\",\"payment_id\":null}"
Expected observable when vulnerable: 200/201 returning an order in SUBMITTED or PAID state despite zero payment records; contrast against the UI-enforced sequence cart -> pay -> order.
Further bypass probes:
curl -s -X POST "$BASE/api/user/password" -d '{"new_password":"New123!"}' succeeding without current-password or session re-authentication equals finding.Capture a legitimate checkout body from the browser devtools, then send its tampered twin:
{"cart_id":"c-123","items":[{"sku":"SKU-1","qty":1,"unit_price":49.90}]}
{"cart_id":"c-123","items":[{"sku":"SKU-1","qty":1,"unit_price":0.01}],"total":0.01,"currency":"USD"}
Negative-quantity credit variant:
{"items":[{"sku":"SKU-1","qty":-3,"unit_price":49.90}]}
Expected observable when vulnerable: stored order reflects attacker values (0.01 charged, or wallet/store credit increased by 149.70 through refund-on-negative-purchase logic). Currency variant: identical numeric total posted under USD where the catalog priced the item in JPY. Compare persisted order rows (admin view, order confirmation endpoint) against catalog prices as evidence.
When no test instance is authorized:
ATOMIC_REQUESTS), base-controller transactions, ORM unit-of-work autoflush, queue serialization ahead of the endpoint. Remember atomicity wrappers prevent partial failure, not interleaved reads.Apply fixes in layers, strongest first: constrain the database, atomize the write, serialize structurally hot paths, then harden the protocol with idempotency keys, state machines, and server-side recomputation. One layer alone is brittle; ship at least a database backstop plus an atomic write for every invariant.
Single-statement mutation carrying its own guard; affected-rows = 0 signals rejection. Every stack below maps onto this shape:
-- FIXED: atomic guarded debit; no separate SELECT, no application-side branch
UPDATE accounts
SET balance = balance - :amount
WHERE id = :account_id
AND balance >= :amount;
-- application checks rowCount(): 0 -> insufficient funds
Redemption as insert-only fact with a database-enforced cap:
-- FIXED: single use enforced by UNIQUE; second insert raises duplicate-key
CREATE TABLE voucher_redemptions (
voucher_id BIGINT NOT NULL,
user_id BIGINT NOT NULL,
redeemed_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (voucher_id)
);
Last-line constraints for every invariant named in this module:
ALTER TABLE accounts ADD CONSTRAINT chk_balance_nonneg CHECK (balance >= 0);
ALTER TABLE order_items ADD CONSTRAINT chk_qty_positive CHECK (qty > 0);
ALTER TABLE users ADD CONSTRAINT uq_users_email UNIQUE (email);
ALTER TABLE coupons_used ADD CONSTRAINT uq_coupon_user UNIQUE (coupon_id, user_id);
Money columns: DECIMAL(19,4) or bigint minor units, NOT NULL, never float/double.
# VULNERABLE: check-then-act; gap spans two queries and all intervening logic
acct = Account.objects.get(pk=account_id)
if acct.balance >= amount:
acct.balance -= amount
acct.save()
# FIXED: row lock + atomic delta inside one transaction
from django.db import transaction
from django.db.models import F
with transaction.atomic():
acct = Account.objects.select_for_update().get(pk=account_id)
if acct.balance < amount:
raise InsufficientFunds()
acct.balance = F("balance") - amount
acct.save(update_fields=["balance"])
asyncio note: a coroutine that awaits between check and write yields the event loop and interleaves other coroutines; single-process asyncio provides zero mutual exclusion. Multi-worker deployments (gunicorn, uvicorn workers, celery processes) share nothing in memory; only database locks and atomic statements serialize across them. Celery note: tasks redeliver after broker visibility timeouts, so handlers must be idempotent; key side effects on task/entity ids and record them in a unique-constrained journal table before executing.
SQLAlchemy equivalent: session.execute(select(Account).where(...).with_for_update()) inside one explicit session.begin() block.
// VULNERABLE: plain find + setter; two transactions read the same balance
Account a = em.find(Account.class, id);
if (a.getBalance().compareTo(amount) >= 0) {
a.setBalance(a.getBalance().subtract(amount));
}
// FIXED: pessimistic row lock inside an explicit transaction boundary
@Transactional(isolation = Isolation.READ_COMMITTED)
public void withdraw(Long id, BigDecimal amount) {
Account a = em.find(Account.class, id, LockModeType.PESSIMISTIC_WRITE);
if (a.getBalance().compareTo(amount) < 0) throw new InsufficientFunds();
a.setBalance(a.getBalance().subtract(amount));
}
Isolation notes: REPEATABLE_READ or snapshot isolation does not stop two writers from both passing a balance guard (write skew); either take the pessimistic row lock as shown, run the guarded path SERIALIZABLE, or translate to the conditional-UPDATE shape. Optimistic alternative: annotate @Version Long version; and retry on OptimisticLockException.
// VULNERABLE
var acct = db.Accounts.Find(id);
if (acct.Balance >= amount) { acct.Balance -= amount; }
await db.SaveChangesAsync();
// FIXED: RowVersion concurrency token + explicit transaction scope
public byte[] RowVersion { get; set; } // [Timestamp] on the entity class
using var scope = new TransactionScope(TransactionScopeOption.Required,
new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted },
TransactionScopeAsyncFlowOption.Enabled);
var acct = db.Accounts.Single(x => x.Id == id);
if (acct.Balance < amount) throw new InsufficientFunds();
acct.Balance -= amount;
await db.SaveChangesAsync(); // DbUpdateConcurrencyException on lost update
scope.Complete();
Where EF Core 7+ is available, prefer translating guard and write into one statement (ExecuteUpdate with a WHERE Balance >= amount predicate) so no interleaving point exists at all.
No native transaction spans awaits; correctness comes from conditional atomic operations, Mongo transactions on replica sets, or Redis Lua.
// VULNERABLE: await gap between check and write; concurrent requests interleave here
const acct = await accounts.findOne({ _id });
if (acct.balance >= amount) {
await accounts.updateOne({ _id }, { $set: { balance: acct.balance - amount } });
}
// FIXED (single document): conditional atomic update; matchedCount 0 => insufficient
const r = await accounts.updateOne(
{ _id, balance: { $gte: amount } },
{ $inc: { balance: -amount } }
);
if (r.matchedCount === 0) throw new InsufficientFunds();
Multi-document work requires a replica set and a session:
// FIXED (multi-document): Mongo transaction
const session = client.startSession();
try {
await session.withTransaction(async () => {
const acct = await accounts.findOne({ _id }, { session });
if (acct.balance < amount) throw new InsufficientFunds();
await accounts.updateOne({ _id }, { $inc: { balance: -amount } }, { session });
await ledgers.insertOne({ accountId: _id, delta: -amount }, { session });
});
} finally { await session.endSession(); }
Redis counters: never GET-then-DECR blindly; make check+write one atomic script.
-- FIXED: returns remaining balance, or -1 when funds are insufficient
local bal = tonumber(redis.call('GET', KEYS[1]) or '0')
if bal < tonumber(ARGV[1]) then return -1 end
return redis.call('DECRBY', KEYS[1], ARGV[1])
// VULNERABLE: two bare statements; sync.Mutex would only guard one process
var bal int64
db.QueryRowContext(ctx, `SELECT balance FROM accounts WHERE id=$1`, id).Scan(&bal)
if bal >= amount {
db.ExecContext(ctx, `UPDATE accounts SET balance=$1 WHERE id=$2`, bal-amount, id)
}
// FIXED: single Tx holding the row lock until commit
tx, err := db.BeginTx(ctx, nil)
if err != nil { return err }
defer tx.Rollback()
var bal int64
err = tx.QueryRowContext(ctx,
`SELECT balance FROM accounts WHERE id=$1 FOR UPDATE`, id).Scan(&bal)
if err != nil { return err }
if bal < amount { return ErrInsufficientFunds }
_, err = tx.ExecContext(ctx,
`UPDATE accounts SET balance = balance - $1 WHERE id = $2`, amount, id)
if err != nil { return err }
return tx.Commit()
sync.Mutex scope warning: it excludes goroutines within one binary only; replicas bypass it entirely. Reserve mutexes for in-process caches, never for money.
# VULNERABLE
acct = Account.find(id)
acct.update!(balance: acct.balance - amount) if acct.balance >= amount
# FIXED
Account.transaction do
acct = Account.lock.find(id) # SELECT ... FOR UPDATE
raise InsufficientFunds if acct.balance < amount
acct.balance -= amount # or express as SQL delta
acct.save!
end
# equivalent shorthand: acct.with_lock { ... }
Outside a held lock, never assign a money field from a previously-read value; prefer SQL-side deltas so the arithmetic executes next to the row.
// VULNERABLE
$acct = Account::find($id);
if ($acct->balance >= $amount) {
$acct->balance -= $amount;
$acct->save();
}
// FIXED
use Illuminate\Support\Facades\DB;
DB::transaction(function () use ($id, $amount) {
$acct = DB::table('accounts')->where('id', $id)->lockForUpdate()->first();
if ($acct->balance < $amount) {
throw new InsufficientFunds();
}
DB::table('accounts')->where('id', $id)->decrement('balance', $amount);
});
decrement() compiles to atomic SET balance = balance - ?; combine it with a guarded WHERE clause for check-free safety where business rules allow.
CREATE TABLE idempotency_keys (
key VARCHAR(255) PRIMARY KEY,
user_id BIGINT NOT NULL,
request_hash CHAR(64) NOT NULL,
response_status SMALLINT,
response_body JSONB,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
UNIQUE (key)
);
Handling pattern (stack-independent):
user_id.INSERT ... ON CONFLICT DO NOTHING. Zero inserted rows means duplicate: SELECT the stored response and replay it verbatim without re-executing side effects. For simultaneous duplicates of an in-flight request, take a row lock on the key row and wait or return 409.request_hash (422): prevents collision smuggling of a second payload under a paid key.Model lifecycles explicitly and route every mutation through the guard:
# FIXED: closed transition table; anything unlisted is rejected
from enum import Enum
class OrderStatus(Enum):
CART = "CART"; SUBMITTED = "SUBMITTED"; PAID = "PAID"
SHIPPED = "SHIPPED"; DELIVERED = "DELIVERED"; CANCELLED = "CANCELLED"; REFUNDED = "REFUNDED"
TRANSITIONS = {
OrderStatus.CART: frozenset({OrderStatus.SUBMITTED}),
OrderStatus.SUBMITTED: frozenset({OrderStatus.PAID, OrderStatus.CANCELLED}),
OrderStatus.PAID: frozenset({OrderStatus.SHIPPED, OrderStatus.REFUNDED}),
OrderStatus.SHIPPED: frozenset({OrderStatus.DELIVERED}),
}
def transition(entity, target, actor):
if target not in TRANSITIONS.get(entity.status, frozenset()):
raise IllegalTransition(f"{entity.status} -> {target}")
entity.status = target
entity.save(update_fields=["status"]) # persist inside a transaction
Rules: lifecycle columns hold enums and are non-null; direct status= assignments outside the guard are banned by review and grep; payment-driven transitions fire only from verified provider callbacks whose event ids passed de-duplication; step/flow tokens bind server-side to (user, session, next_state) and are consumed single-use.
Compute totals, taxes, discounts, and currency conversion at write time from server-owned data (catalog tables, pricing service, FX rates). The client-supplied total is at most an integrity hint: recompute server-side and, on mismatch, reject or accept-and-flag per product policy; never silently persist the client figure. Validate quantity positivity on every path. Clamp coupon discounts to order subtotal; apply single-coupon semantics unless stacking is explicitly modeled with precedence and cap rules.
When contention is structural (one inventory row during flash sales), funnel every mutation for the resource through a single ordered channel: message-broker partition keyed by account_id/sku_id consumed by exactly one worker, or a DB-backed job table polled per resource shard. Producers receive 202 plus job id; consumers perform locked transactions and publish results. This trades latency for the impossibility of interleaving.
Low-contention tables: add version INT NOT NULL DEFAULT 0; every update runs ... WHERE id = :id AND version = :expected_version setting version = version + 1; zero affected rows means concurrent modification: retry or 409. Native support: JPA @Version, EF [Timestamp], Rails lock_version. Combine with CHECK constraints so even a lost-update bug cannot mint negative balances.
Store expiry and trial deadlines server-side at creation; compare against the server clock at every use; ignore client timestamps everywhere. Implement resets as idempotent "set current window start" operations rather than additive grants. Pin scheduled jobs to UTC and handle DST transitions explicitly in window math.
Port the template below to pytest, JUnit, xUnit, or go test as available. Require a real database (testcontainers or CI service container); in-memory fakes hide exactly this defect class.
GIVEN an account with balance 100
AND endpoint POST /wallet/withdraw accepting {"amount": 100}
WHEN 10 threads simultaneously POST /wallet/withdraw
THEN exactly 1 response is success (2xx)
AND final stored balance == 0
AND no ledger row implies a negative balance
GIVEN an account with balance 900
WHEN 10 threads each withdraw 100 concurrently
THEN exactly 9 succeed
AND final balance == 0
GIVEN single-use voucher V
WHEN 20 threads redeem V concurrently
THEN exactly 1 redemption row exists
AND the other 19 responses are 409/422
FINALLY rerun each scenario at parallelism 2, 10, and 50; outcomes must not vary
Worker-pool sketch for the harness:
barrier = Barrier(N)
results = parallel_map(range(N),
lambda i: (barrier.wait(), http_post(WITHDRAW_ENDPOINT, body))[1])
assert count_2xx(results) == expected_successes
assert stored_balance_after == expected_final_balance
Confirm fixes landed and no sibling regressed:
rg -n "select_for_update|lockForUpdate|PESSIMISTIC_WRITE|with_lock|FOR UPDATE" app/
rg -ni "Idempotency-Key|idempotency_key" app/
rg -n "CHECK \\\(balance|UNIQUE \\\(voucher" migrations/
rg -n "req\.body\.(total|price|amount|status|qty)" app/
Expected: transaction vocabulary adjacent to every money handler; zero request-sourced totals reaching persistence (or a recompute call at each); constraint migrations present.
Score with the official CVSS v3.1 calculator against the specific asset; vectors below are starting points.
| Finding class | Primary CWE | Illustrative vector | Default rating |
|---|---|---|---|
| Money creation: double-spend, negative-transfer credit, unlimited coupon/referral loops | CWE-362 / CWE-20 | CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:H/A:L (~7.1) | Critical |
| Workflow bypass reaching privileged outcome (unpaid fulfillment, unverified account performing KYC-gated actions, self-approved payouts) | CWE-20 (A04 design) | CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N | High to Critical by blast radius |
| Bounded race: one voucher reused, oversell of limited units | CWE-362 | CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:L/A:L | High |
| Quota/free-tier abuse or discount stacking without direct loss | CWE-20 | CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:N/I:L/A:N | Medium |
| Revocation latency (banned user retains access minutes-to-hours) | CWE-367 | CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:L/I:L/A:N | Medium |
| Cosmetic state inconsistency without economic effect | CWE-362 | CVSS:3.1/AV:N/AC:H/PR:L/UI:N/S:U/C:N/I:N/A:L | Low |
Attack complexity stays Low for races once a parallel script exists (Repro A/B are reliable by construction); some programs argue AC:H pre-automation. Resolve via program policy and let the rubric band, not the decimal, carry the message.
Rubric anchors:
Assign CWE-362 for unsynchronized concurrent access; CWE-367 specifically where a check's validity expires before its dependent use (upload scan vs publish, revocation vs live session). Assign CWE-20 for tampered operands (totals, negative quantities, client-driven statuses). Assign CWE-639 when the flaw reduces to user-controlled keys addressing others' objects, cross-referencing the AUTHZ module. Do not assign CWE-840: it survives only as a deprecated Category alias, not an assignable weakness; map findings to the root-cause weaknesses above and tag the report OWASP A04:2021.
updateOne({_id, balance: {$gte: amt}}, {$inc: ...}) resembles read-modify-write but is safe when matchedCount is checked.What SKILL.md sets; muted values are Claude Code's defaults
/aegis:aegis-business-logic-racesfrom Aegis Skills
npx claudepluginhub as-foss/aegis-skills --plugin aegis40 skills in this plugin
/aegis-api-securityAudit playbook module for API-specific security failures covering mass assignment, missing rate limits and pagination caps, GraphQL/gRPC misconfiguration, REST hygiene gaps, API key mishandling, and WebSocket/SSE access-control defects across all mainstream web frameworks./aegis-api-token-securityAudits the full lifecycle of bearer/API tokens protecting an internet-exposed HTTP API — minting entropy and format, hash-only server storage, transport rules, scoping, expiry and rotation, revocation, per-key rate limits, and log hygiene — with read-only evidence commands and hardened reference implementations./aegis-authn-sessionDetect authentication and session management failures across login, password storage, password reset, MFA, session lifecycle, JWT/OAuth/API-key handling, remember-me, and session storage./aegis-authz-access-controlDetects broken function-level and object-level authorization (BFLA/BOLA), vertical and horizontal privilege escalation, tenant-isolation failures, path/header bypasses, and unsafe delegation across mainstream web frameworks and APIs./aegis-baas-platformAudits Backend-as-a-Service and managed-platform configuration - Supabase RLS, Firebase security rules, connection-string databases, serverless host exposure, payment-webhook integrity, and managed CMS posture - for broken-access-control footguns that expose or corrupt production data./aegis-backup-drAudits backup hygiene and disaster-recovery readiness for Linux hosts — job inventory and coverage-gap analysis, destination tiering against the 3-2-1-1-0 pattern, encryption and key-custody posture, restore documentation and drill evidence, and ransomware resilience — using read-only discovery sweeps, fill-in RTO/RPO and recovery-order worksheets, and remediation skeletons.Other plugins' skills for the same job