API Security, Mass Assignment, Business Logic, and Race Conditions
Audit REST and GraphQL APIs for property-level flaws, broken function authorisation, resource abuse, and the business-rule and concurrency bugs that scanners never find.
By the end, you’ll be able to…
- Inventory REST and GraphQL endpoints and test object-, function-, and property-level authorisation.
- Recognise mass assignment, excessive data exposure, rate-limit bypass, and pagination abuse.
- Break business rules with negative quantities, coupon reuse, refund loops, and workflow skipping in a lab.
- Exploit and fix race conditions with transactions, atomic updates, unique constraints, and idempotency keys.
01Mapping the API Surface
Modern applications are mostly API. A web front end, a mobile app, a partner integration, and a support tool may all call the same endpoints with different expectations. REST exposes resources under predictable paths; GraphQL exposes one endpoint with a schema; older versions linger after a rewrite. The first testing problem is inventory: which endpoints exist, which versions are still routed, and which are reachable only from a mobile client or an internal service.
Discover endpoints from JavaScript bundles, mobile traffic, OpenAPI documents, GraphQL introspection, error messages, and response headers. Try OPTIONS and HEAD, compare trailing slashes and version prefixes, and check whether old versions still accept the same token. Build a matrix of endpoint, method, role, object owner, and expected result. The matrix is the test plan; without it, API testing becomes a random walk through JSON.
Authentication and authorisation are separate questions at every layer. An API key identifies a client, not a user, and a valid key does not prove that the caller may read a specific invoice. Gateways can enforce coarse rules such as requiring a token, but object-level checks must live in the service that owns the data. Assume internal callers and background jobs can reach the same code paths; test the service directly where the lab allows it, not only through the gateway.
02Mass Assignment and Excessive Data Exposure
Mass assignment happens when a framework binds a JSON or form body directly to a model and the developer does not restrict which fields may be written. The UI sends displayName and email, but the model also has role, tenantId, credit, and verified. An attacker adds those fields and the framework sets them. The result can be privilege escalation, tenant movement, or free credit. The bug is not in the framework; it is in using a database model as the public request schema.
Excessive data exposure is the read-side twin. An endpoint returns the whole ORM entity, including password hashes, internal notes, moderation flags, other users' identifiers, and fields the current role should not see. Clients may ignore those fields, but an attacker reads the raw JSON. Field-level authorisation means the response is built from an explicit view for the caller's role, not filtered in the browser. Hiding a field in the UI is not redaction.
Defend with explicit request and response models. A customer profile DTO contains only the fields a customer may change; an admin DTO is separate and individually authorised. Reject unknown fields or strip them before binding. Serialise through a view layer that selects fields by role and relationship. Add tests that send role, tenantId, isAdmin, and credit in every update request and assert they are ignored or rejected, and tests that inspect the raw response for sensitive keys.
### Mass assignment: try to grant authorityPATCH /api/v1/users/me HTTP/1.1Host: api.lab.testAuthorization: Bearer <user-token>Content-Type: application/json{"displayName":"Student","role":"admin","tenantId":"tenant-two","credit":99999}### Expected: only displayName changes; the other fields are rejected### or ignored, and the response does not echo them as accepted.### Excessive data exposure: read your own profileGET /api/v1/users/me HTTP/1.1Host: api.lab.testAuthorization: Bearer <user-token>### Inspect the raw JSON for password_hash, internal_notes, role,### tenant_id, moderation flags, and other users' identifiers.### Pagination and resource consumptionGET /api/v1/orders?limit=100000&offset=0 HTTP/1.1Host: api.lab.testAuthorization: Bearer <user-token>### Expected: server-side maximum page size, 400 for an invalid limit,### and the same authorisation predicate on rows and counts.03Function-Level Authorisation, Rate Limits, and Pagination
Broken function-level authorisation is the vertical version of IDOR: a customer reaches an administrative function. The route may be hidden, undocumented, or exposed only in an older API version. Test every role against every function, including report exports, user management, configuration, refunds, and feature flags. Try method changes: a GET-only admin route may still accept POST. Try path normalisation: /admin, /Admin, /admin/, /api/v1/admin, and an internal host header. A gateway rule that blocks /admin may not block the service's alternate route.
Rate limits protect credentials, money, and availability. Key them by the identity that matters: account, token, route, and source address together, not source address alone. A limit of one hundred login attempts per hour per IP is useless behind a botnet and harmful behind a shared office NAT. Apply stricter limits to login, OTP verification, password reset, coupon redemption, search, export, and payment. Return 429 with Retry-After, log the decision, and alert on sustained abuse without locking out legitimate users.
Pagination and filtering are resource-consumption controls. A limit parameter that accepts 100000 turns a list endpoint into a bulk export. Negative offsets, cursor tampering, and filters that reveal other tenants are common. Enforce a maximum page size, reject invalid values instead of clamping silently, use opaque cursors, and apply the same authorisation predicate to the count query. Test with a normal account, a large limit, a negative offset, a cursor from another user, and a filter that targets a tenant the account does not belong to.
RATE-LIMIT BYPASS ATTEMPTS (lab only, low volume) - Rotate X-Forwarded-For and X-Real-IP values. - Change header case or add duplicate headers. - Add a trailing slash, a semicolon, or a different API version. - Switch between JSON, form, and multipart content types. - Use several API keys that belong to the same tenant. - Spread attempts across accounts that share a victim identifier. - Use HTTP/2 multiplexing to send requests in one packet.WHAT TO VERIFY - The limit is keyed by account and route, not just by IP. - 429 responses include Retry-After and do not leak account existence. - Successful and failed attempts are counted separately where appropriate. - Lockouts are temporary and do not let an attacker deny service. - Alerts fire on sustained attempts across rotating addresses.04GraphQL: Introspection, Depth, and Field-Level Authorization
GraphQL exposes a typed schema and usually a single endpoint. Introspection lets a client discover types, fields, arguments, and mutations, which is excellent for developers and also excellent for testers. Disabling introspection in production raises the effort for an attacker but is not an authorisation control; the schema can still be inferred from errors and field guessing. Treat the schema as public and enforce authorisation on every field and mutation.
GraphQL-specific abuse includes deep nested queries that expand exponentially, aliases that run the same mutation many times in one request, batched operations, and fragments that bypass naive query-string filters. A query depth limit and a cost analysis based on resolved fields, not string length, are necessary. Rate limiting should count operations and complexity, not just HTTP requests. Mutations need the same CSRF and authorisation checks as REST state changes, and persisted queries or an operation allowlist reduce the attack surface for production clients.
Field-level authorisation is the subtle part. A resolver for User.posts may check that the caller can read the user, but the posts resolver may return private drafts because it only checks that a post exists. Nested resolvers must each enforce the caller's relationship to the object. Test by querying another user's node through every path: direct ID, nested under an organisation, through a search result, and through a mutation response. A single missing resolver check is enough to leak data even when the top-level query is protected.
# Schema discovery in a lab.{ __schema { types { name fields { name } } } }# Depth and alias amplification (send at low volume in a lab).{ a: user(id: 1) { posts { author { posts { author { id } } } } } }{ a: login(email: "a@lab.test", password: "x") { token } }# Field-level authorisation test: ask for a private field.{ user(id: 1042) { email role internalNotes posts { draftTitle } } }# Controls to verify:# 1. Every resolver checks the caller against the object it returns.# 2. Query depth and cost are capped before execution.# 3. Aliases and batched operations count toward the limit.# 4. Mutations require the same CSRF and role checks as REST.# 5. Errors do not reveal internal fields or stack traces.05Business Logic: Rules the Scanner Cannot See
Business logic flaws are violations of the application's own rules, not memory-safety or injection bugs. A shop must not sell a negative quantity, a coupon must be used once per customer, a refund must not exceed the amount paid, and an approval must come from someone other than the requester. These rules live in code and process, and a scanner that does not understand the business cannot test them. The tester must learn the intended workflow and then try to break it in ways the designer did not consider.
Common patterns include negative quantities that turn a charge into a credit, price fields supplied by the client, coupon stacking or reuse across accounts, refund loops that return more than the original payment, and workflow steps that can be skipped by calling a later endpoint directly. Currency rounding can create or destroy value when amounts are converted repeatedly. Trials and referrals can be abused with disposable accounts or self-referral. Inventory can be oversold when two checkouts read the same stock count.
Test business logic by writing the invariants first. For each workflow, state what must always be true: total equals the sum of line items, refunded amount never exceeds captured amount, a coupon's redemption count never exceeds its limit, an approver is not the requester. Then try boundary values, negative numbers, zero, very large numbers, repeated steps, out-of-order steps, and parallel requests. A finding is a sequence that produces a state the business says is impossible, with the exact requests and the resulting balance or order state.
# Checkout and Refund Invariants## Cart and pricing- Quantity is an integer greater than zero and less than the stock limit.- Unit price comes from the server catalogue, never from the request body.- Discounts cannot exceed the subtotal.- Currency conversion uses one documented rounding rule.## Coupons- A coupon is redeemed at most max_uses times in total.- A customer can use a coupon at most once unless explicitly allowed.- Expired, disabled, and other-tenant coupons are rejected.- Stacking is allowed only for documented combinations.## Payment and refund- Captured amount equals the order total.- Refunded amount never exceeds captured amount.- A refund is idempotent: retrying the request does not refund twice.- Only the payment owner or an authorised support role can refund.## Workflow- Payment cannot complete before stock is reserved.- An order cannot ship before payment is captured.- An approver cannot approve their own request.## Test sequences- Negative quantity, zero quantity, fractional quantity.- Two concurrent checkouts for the last item.- Coupon redemption in parallel from two sessions.- Refund, then refund again with the same idempotency key and a new one.- Call the shipping endpoint before payment.06Race Conditions: When Two Requests Arrive Together
A race condition occurs when correctness depends on the timing of concurrent operations. The classic pattern is check-then-act: read the coupon's use count, decide it is below the limit, then increment it. Two requests can both read the same count before either writes, so both succeed. The same pattern enables double-spending a wallet, overselling the last item, redeeming a gift card twice, and approving two conflicting changes. The window may be milliseconds, but an attacker can widen it with parallel requests or a single-packet attack that delivers many HTTP/2 requests together.
The fix is to make the check and the update one atomic operation in the data store. A transaction with a row lock (SELECT ... FOR UPDATE) serialises the critical section. A conditional update (UPDATE ... WHERE uses < max_uses) lets the database decide, and the affected-row count tells the application whether it won. A unique constraint prevents duplicate redemptions even if application logic is wrong. For distributed workflows, use an idempotency key stored with the result, a queue that processes one job per aggregate, or optimistic concurrency with a version column and retry.
Test race conditions with a lab harness that sends many requests at the same moment, then repeat the experiment several times. Measure the final state, not just the status codes: count redemptions, check the balance, and inspect the stock level. A single 200 is not proof; two successes beyond the limit are. Document the exact concurrency, the observed state, and the control that should have prevented it. Then verify the fix under the same load, including retries and duplicate idempotency keys.
-- Vulnerable pattern in application code:-- 1. SELECT uses FROM coupons WHERE code = 'WELCOME10';-- 2. if uses < max_uses then UPDATE coupons SET uses = uses + 1;-- Two requests can both pass step 2 before either writes.-- Fix A: serialise the critical section with a row lock.BEGIN;SELECT uses, max_uses FROM coupons WHERE code = 'WELCOME10' FOR UPDATE;-- Application checks the limit while holding the lock.UPDATE coupons SET uses = uses + 1 WHERE code = 'WELCOME10';COMMIT;-- Fix B: make the check part of the update.UPDATE couponsSET uses = uses + 1WHERE code = 'WELCOME10' AND uses < max_uses;-- affected rows = 1 means this request won; 0 means the limit was reached.-- Fix C: enforce uniqueness per customer.CREATE UNIQUE INDEX one_redemption_per_customer ON coupon_redemptions (coupon_id, customer_id);07Testing and Defending the API and Business Layer
A practical API test combines three lenses. The schema lens asks what fields and operations exist. The authorisation lens asks who may do what to which object, including nested and bulk operations. The business lens asks which sequences should be impossible. Use the same two-account, two-tenant setup for every test, and include an administrator and an anonymous caller. Automate the repetitive matrix, but inspect response bodies by hand because a 200 with an empty array can hide a filter that is doing the wrong thing.
Defences are explicit models, server-side invariants, and transactional controls. Request DTOs allowlist writable fields; response DTOs select fields by role. Authorisation lives in the service, not only in the gateway, and each resolver or handler checks the object relationship. Business rules are enforced in one place, with tests for boundaries and sequences. Money and inventory use atomic database operations, idempotency keys, and unique constraints. Limits are keyed by account and route, with monitoring for abuse.
Finally, log the decisions that matter: denied authorisation, rate-limit events, refunds, coupon redemptions, role changes, and admin actions. Include the subject, the object, the action, the result, and a correlation ID, but never the secret itself. A business logic bug that is invisible in logs is much harder to contain. Detection turns a one-off logic error into an incident you can scope and fix.
The ideas worth keeping.
- APIs need object-, function-, and field-level authorisation in the service, not just at the gateway.
- Mass assignment and excessive data exposure are schema design failures; explicit DTOs fix both directions.
- Business logic testing starts from invariants and sequences, including negative values, skipped steps, and retries.
- Race conditions are fixed in the data store with atomic updates, locks, unique constraints, and idempotency keys.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Exercise 1: Break a coupon and refund flow
A lab shop allows one use of coupon WELCOME10 per customer and refunds up to the captured amount. Design a test plan that checks the rules, including concurrency and retries, and state the evidence you would record.
Explore a worked solution
State the invariants: total redemptions never exceed max_uses, one redemption per customer, discount never exceeds the subtotal, refunded amount never exceeds captured, and a retried refund does not pay twice. Test a normal redemption, a second redemption by the same customer, a redemption by a second account, an expired coupon, a coupon from another tenant, and a stacked discount. Submit a negative quantity and a client-supplied price. For concurrency, send many simultaneous redemptions and refunds with the same idempotency key and with new keys. Record the request sequence, status codes, final redemption count, order balance, and ledger entries. Evidence is two successful redemptions beyond the limit or a refund total above the captured amount.Business logic testing needs a stated invariant and a final-state check. Status codes alone can look correct while the ledger is wrong.
Exercise 2: Prove and fix a double-spend
A wallet endpoint reads the balance, checks that it is at least the transfer amount, then writes the new balance. Explain how two concurrent requests can overdraw the wallet, how you would demonstrate it in a lab, and how to fix it.
Explore a worked solution
Two requests read the same balance before either writes, so both pass the check and both write a new balance that does not account for the other transfer. In a lab, send many simultaneous transfer requests from the same wallet with just enough funds for one, then sum the successful transfers and compare with the opening balance. Fix with an atomic conditional update: UPDATE wallets SET balance = balance - :amount WHERE id = :id AND balance >= :amount, and treat zero affected rows as insufficient funds. Alternatively use a transaction with SELECT ... FOR UPDATE, or optimistic concurrency with a version column. Add an idempotency key for retries, a ledger with a unique constraint per transfer, and a test that runs the same concurrency harness against the fixed code.The database must arbitrate the race. Reading in the application and writing later is a check-then-act window that concurrency will eventually hit.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Keep exploring.
The official references behind this lesson, when you want a second angle or the full details.
One lesson closer.
Reading is a start. Trying it yourself makes the connection.