Access and authorization: BOLA/IDOR, tokens, mass assignment
BOLA/IDOR is when an authenticated user gets someone else's object by swapping its id, because the server checked the token but not who owns the resource. It is visible only with two accounts: B creates the resource and A requests it, covering every method and neighbouring address. Token revocation and mass assignment are checked the same way, by reading the state after the request, not just the status.
API · Typical bugs
The token is valid, and the server returned another user’s invoice. Which test catches it?
User A opens their own invoice GET /v1/invoices/10441, changes the number in the address to 10442 and gets user B’s invoice. The request is authenticated, the token is genuine, the status is 200. A test “a signed-in user sees an invoice” is green, while production leaks other people’s data. This class of bug is the most expensive because it hands out someone else’s data or extra rights, and it stays invisible until you use two users.
The lesson covers three bugs: access to someone else’s object (BOLA/IDOR), tokens that do not die, and mass assignment. For each: how it works, how to reproduce it, what to do next.
How it works
Authentication answers “who are you”, authorization answers “what are you allowed to do”. A server that checks only the token signature did the first half. In the OWASP API Security Top 10 (2023 edition) these are the top entries: API1 Broken Object Level Authorization (BOLA, called IDOR in older terminology), API2 Broken Authentication and API3 Broken Object Property Level Authorization, which absorbed mass assignment.
Why it happens. The owner check is not part of the protocol, it has to be written in every handler: “the resource belongs to the user from the token”. The framework does not know that. A developer adds it where security came to mind and forgets the neighbouring method, an export or a nested resource. So the bug lives in easy-to-miss places: PUT/DELETE while GET is protected, /invoices/{id}/pdf, /users/{id}/orders, ids in the body and query.
What the server checks in a request
Typical
Token only
The signature is valid, the token has not expired, the role allows the method. Whose invoice 10442 is, the server never asks.
Better
Token and owner
The same plus the condition “the resource belongs to the token’s subject” (or a role with rights over others). Otherwise 403 or 404.
Figure 1. The first check answers “who”, the second also “whose”. A BOLA bug is the missing second check.
Example: two accounts instead of one
The test needs two test users: B creates the resource and A accesses it. One account cannot reveal this bug by definition. We check all methods and neighbouring addresses, not only GET:
import { test, expect } from'@playwright/test';
// authA and authB hold the Authorization headers of two test accountstest('A cannot read, change or delete the invoice of B', async ({ request }) => {
const created = await request.post('/v1/invoices', {
headers: authB,
data: { amountMinor: 5000, currency: 'UAH' },
});
const { id } = await created.json();
const url = '/v1/invoices/' + id;
const attempts = [
await request.get(url, { headers: authA }),
await request.put(url, { headers: authA, data: { amountMinor: 1 } }),
await request.delete(url, { headers: authA }),
await request.get(url + '/pdf', { headers: authA }),
];
for (const res of attempts) expect([403, 404]).toContain(res.status());
const own = await request.get(url, { headers: authB });
expect((await own.json()).amountMinor).toBe(5000); // B's data is untouched
});
Both 403 and 404 are allowed: neither gives out foreign data. The last lines matter: if PUT returned 403 but still changed the amount, the status dresses up the bug, so B’s state is checked with a separate read.
403 or 404 for a foreign resource
403 Forbidden
Says honestly that access is denied. But it confirms that the resource exists, which helps id enumeration.
404 Not Found
Does not reveal that a foreign resource exists. Diagnosis is a little harder, but it is safer for private data.
Figure 2. Both responses are acceptable if the contract is the same for all endpoints. The bug is mixed behaviour and a 200.
A token that does not die
The second group: a session stays valid after logout, a password change or blocking. A short-lived JWT access token lives until it expires by design, that is not a bug. The defect is a TTL that is too long, a refresh token that survives logout, and a token that can be exchanged twice. Under refresh token rotation practice (OAuth 2.0 Security BCP), reuse of an already exchanged token should be treated as a sign of theft, and the server revokes the whole token “family”. Real systems often allow a short tolerance window, so the test repeats the request after a pause longer than the window, not in the same millisecond:
test('an exchanged refresh token cannot be used again', async ({ request }) => {
const { refreshToken } = awaitlogin(request, 'qa-a'); // helper of the suiteconst first = await request.post('/v1/auth/refresh', { data: { refreshToken } });
expect(first.status()).toBe(200); // rotation: a new pair is issuedawaitnewPromise((r) => setTimeout(r, GRACE_MS + 1000)); // wait past the reuse tolerance window (GRACE_MS from the API docs)const reuse = await request.post('/v1/auth/refresh', { data: { refreshToken } });
expect(reuse.status()).toBe(401); // the old token must be dead
});
Further cases: after logout the old refresh token does not work, after a password change other sessions are ended, after a role is removed the token does not grant the action (for a JWT it depends on whether the server checks the role from the token or from the database).
Mass assignment
The server maps the request body straight onto the model, and the client sets fields it should not: role, isAdmin, price, ownerId, status. A request from a regular user:
PATCH /v1/users/me HTTP/1.1
Authorization: Bearer <token of a regular user>
Content-Type: application/json
{ "displayName": "Olena", "role": "admin", "balanceMinor": 999999 }
The test does not stop at the status. 200 (field ignored), 400 or 422 (field rejected) are acceptable, only saving it is not. So we read the state after the request:
test('extra fields are rejected or ignored, never saved', async ({ request }) => {
const res = await request.patch('/v1/users/me', {
headers: authA,
data: { displayName: 'Olena', role: 'admin', balanceMinor: 999999 },
});
expect([200, 400, 422]).toContain(res.status());
const me = await (await request.get('/v1/users/me', { headers: authA })).json();
expect(me.role).toBe('user');
expect(me.balanceMinor).not.toBe(999999);
});
Extra fields come from GET responses (which fields a user sees) and from the documentation of privileged roles. The server-side fix is an allow list of fields, not a deny list of dangerous ones.
Limits and alternatives
An autotest with two accounts proves only the resources and methods it checked. Systematically this is covered by a “resource × method × role” matrix generated from the specification, or by a framework-level policy of “deny by default”.
Unpredictable ids (UUIDs) make enumeration harder but do not replace the owner check: ids leak through logs, emails and links.
A UI test on tokens catches little: signing out of the app may only make the browser forget the token while it stays valid on the server.
Do not enumerate other people’s ids in bulk and do not use rights you obtained. Two accounts of your own are enough as proof.
Common mistakes
Testing with one account. BOLA cannot be seen without another user’s resource.
Checking only GET. Change and delete often have separate handlers and a separate (missing) check.
Trusting the status, not the state. A 403 after the change was already saved leaves the hole open.
Treating token revocation as verified after a UI logout. The old token has to be replayed with a direct request.
Forgetting extra fields in PATCH and POST. A vulnerable server accepts privileged fields in the request body even when GET does not show them.
Check yourself
A request GET /orders/55 from A returned 403, while DELETE /orders/55 from A returned 204. What does it mean and what next?
Answer
The owner check exists only in the GET handler. Deleting another user’s order without a check is BOLA with critical impact. I reproduce with two of my own accounts, record requests and responses, check neighbouring methods and addresses, report it as critical and add a test “A does not change B’s resource” to the suite.
A PATCH with an extra field role: "admin" returned 200 with a body that has no role. A bug or not?
Answer
Unknown until the state is read. If the next GET shows role: "user", the field was ignored, which is acceptable. If it shows admin, it is mass assignment, and the response body just did not show the field.
Related lessons: “OWASP API Top 10: access and authentication”, “JWT traps”, “JWT and testing tokens”.
In an interview.Junior: BOLA is when a user sees someone else’s resource by substituting its id, even though their token is genuine. I check with two accounts: I open B’s resource with A’s token. Middle/Senior: Authentication does not give ownership: it is checked in every handler, so I test a resource × method × role matrix, including PUT, DELETE, exports and nested addresses, and I read the state after a refusal because the status can dress up a change. For tokens I check revocation (logout, password change) and reuse of an exchanged refresh token, and for mass assignment I read the state after extra fields and push for an allow list.
Money and repeated requests: races, idempotency, precision, partial failures
Races, repeated requests, precision errors and partial failures rarely show in one request, so tests check the state after a series of requests. Parallel charges are reproduced with N identical requests at once, checking the balance and record count. A repeated POST is protected by Idempotency-Key, money is tested with invariants in minor units, and partial failures by simulating a dependency outage at each step.
API · Typical bugs
One request works, while two parallel ones charge twice. How do you reproduce that in a test?
A user quickly clicked “Pay” twice, or a mobile client repeated a request after a timeout. A single request in a test works correctly, while the logs show two charges. The bugs of this lesson are invisible in one request: they appear with parallelism, repeats, calculations and the failure of a dependent service. They are caught by tests on the state after a series of requests, not on one response.
Four cases: a race, a non-idempotent repeat, money precision, a partial failure.
How it works
A race. The handler reads the balance, checks there is enough money and writes the new balance. There is a gap between the read and the write. Two requests that enter it simultaneously both see 10000 and both charge. The fix is not in the request code but in the database: a conditional update (UPDATE … WHERE balance >= amount), a row lock, a unique index or a transaction of a sufficient isolation level.
A repeat. HTTP does not guarantee that the client learns the outcome. The request may have been executed and the response got lost (a timeout, a 502 from the gateway). GET, PUT and DELETE are safe to repeat because they are idempotent by definition (RFC 9110). POST is not, so payments introduce the Idempotency-Key header: the server remembers the key together with the result and returns the same on a repeat without a new effect.
Two parallel charges of the whole balance
Typical
Read, then write
Both requests see 10000, both pass the check, the balance goes negative or two operations take one amount.
Better
An atomic condition in the database
The second request waits or is refused. One success, balance 0, it does not go negative.
Figure 1. The difference is not in the balance check code, but in whether the check and the write are atomic.
Example: reproducing the race
A race is non-deterministic: one run is not enough. The test sends N identical requests at once and looks at the state, not only at the responses. The idempotency key is deliberately different, to test the locking and not the key:
test('5 parallel transfers of the whole balance: only one passes', async ({ request }) => {
// precondition: account 42 holds 10000 minor unitsconst send = () =>
request.post('/v1/accounts/42/transfers', {
headers: { 'Idempotency-Key': crypto.randomUUID() }, // a new key each time
data: { toAccount: 'UA21...', amountMinor: 10000, currency: 'UAH' },
});
const results = awaitPromise.all(Array.from({ length: 5 }, send));
const passed = results.filter((r) => r.status() === 201).length;
expect(passed).toBe(1);
const acc = await (await request.get('/v1/accounts/42')).json();
expect(acc.balanceMinor).toBe(0); // never below zero
});
If the test is sometimes green, it does not mean there is no bug: repeat it 5-10 times and record the frequency (“3 of 10”). A regular Postman Runner run sends requests one by one (in parallel only in performance-test mode), so for races a script, k6 or curl with xargs -P is handier.
Example: a repeat and the idempotency key
The client got a timeout and repeated the POST. The correct behaviour: the same key and the same body give the same response without a new effect, while the same key with a different body gives an error. Under the IETF draft “The Idempotency-Key HTTP Header Field” that is 422, and a parallel request with the same key that is still running gets 409; take the exact codes from your API’s documentation:
test('same key and body: one effect; same key, other body: error', async ({ request }) => {
const key = crypto.randomUUID();
const body = { toAccount: 'UA21...', amountMinor: 500, currency: 'UAH' };
const post = (data: object) =>
request.post('/v1/accounts/42/transfers', {
headers: { 'Idempotency-Key': key },
data,
});
const first = awaitpost(body);
const replay = awaitpost(body);
expect(replay.status()).toBe(first.status());
expect((await replay.json()).id).toBe((await first.json()).id); // same transferconst other = awaitpost({ ...body, amountMinor: 900 });
expect(other.status()).toBeGreaterThanOrEqual(400); // key reused with other data
});
Repeating a POST after a timeout
Typical
No key
The first request was executed, the response got lost. The repeat creates a second payment, the money is charged twice.
Better
With Idempotency-Key
The server recognises the key and returns the stored response. One effect, the client gets the result.
Figure 2. A client timeout does not mean the server did nothing. The key turns a repeat from a risk into a safe operation.
Money precision
Floating-point numbers cannot store decimal fractions exactly: in JavaScript 0.1 + 0.2 gives 0.30000000000000004. If the JSON contains "total": 0.30000000000000004 or cents vanish on a discount, the money is calculated as a double. Safe representations are whole minor units (cents) or a decimal number in a string. The test checks invariants, not specific numbers: the sum of lines minus the discount equals the total, the total is an integer, rounding follows one policy. Handy boundaries: 2.675, percentage discounts on odd amounts, currencies with a different number of decimals (JPY has none, KWD has three):
test('order total equals the sum of its lines, in whole minor units', async ({ request }) => {
const res = await request.post('/v1/orders', {
data: {
items: [{ sku: 'a', priceMinor: 10, qty: 3 }, { sku: 'b', priceMinor: 20, qty: 3 }],
discountPercent: 15,
},
});
const order = await res.json();
const lines = order.lines.reduce((s: number, l: { totalMinor: number }) => s + l.totalMinor, 0);
expect(Number.isInteger(order.totalMinor)).toBe(true);
expect(lines - order.discountMinor).toBe(order.totalMinor);
});
A partial failure
The payment went through, the order was not created. The API answered 500, but part of the effects had already happened. The cause: several systems change without a shared transaction. The check: simulate a failure of the dependent service at every step (a stub, a stopped service, a timeout), look at the state in all systems, repeat the request. The fix is usually compensation (cancel the first step) or a transactional outbox with idempotent handlers. The test must check that no “orphaned” records remain after a failure and that a repeat completes the operation without a duplicate.
Limits and alternatives
A parallel test does not prove the absence of a race, it only finds an existing one. It is more reliable to add a code review (is there a condition in the UPDATE or a lock) and a database-level test.
A gateway or a load balancer may serialise requests, so the race disappears on a test environment but shows up in production with several replicas. Test on a configuration close to production.
Idempotency by key has a lifetime. A repeat after it expires is a new operation, which you need to know and verify in the documentation.
Decimal arithmetic in the test can also go wrong: calculate the expected value in whole minor units.
Common mistakes
Looking only at the responses of parallel requests. All of them may be 201, while the balance is right or wrong, which is visible only from the state.
One run of a race. A non-deterministic bug may not show up, so the test is repeated and the frequency recorded.
Checking the idempotency key only on a successful repeat. You also need a different body with the same key and an expired key.
Comparing money as toBe(0.3). The test itself fails on floating point, compare minor units.
Not checking the state of other systems after a 500. An “error” response does not say that no effects happened.
Check yourself
5 parallel requests to charge the whole balance returned five 201 responses. Which check do you add and what do you expect?
Answer
I read the state: the balance must not be negative and exactly one record must be created. If the balance covers one operation, I expect one 201 and four refusals (for example 409 or 422). Five 201 responses mean a race, a critical bug for money: I record the frequency and record ids and suggest a conditional update or a lock.
A client repeated POST /payments with the same Idempotency-Key but a different amount. What should the server do?
Answer
Do nothing and not silently return the old success: the same key with a different body is a client error. Under the IETF draft that is 422. If the server created a new payment or returned a response for the first amount, it is a bug, because the client will believe it paid a different amount.
Related lessons: “Timeouts, retries and idempotency keys”, “PUT vs PATCH and Idempotency-Key in fintech”, “Security and fintech”.
In an interview.Junior: A race is when two requests at once give a double effect, such as two charges. I check by sending several identical requests in parallel and comparing the balance. Middle/Senior: I look at the state, not at the responses, repeat the test 5-10 times and record the frequency. For repeats I check Idempotency-Key: the same key and body give the same response, a different body gives an error. I test money with invariants in minor units, and for partial failures I simulate a dependency failure at each step and look at the state of all systems.
Data: pagination, time zones, truncation, caching of private data
Pagination, time zones, silent truncation and caching of private data return 200 with a valid schema but wrong data, so data is compared, not status. Offset pagination on live data duplicates and loses records, so all pages are walked with an insert between requests. Time is tested around midnight in the user's zone, and the cache with two accounts on one URL.
API · Typical bugs
The response is 200 and looks fine, but records are missing from the list. Where did they go?
A client synchronises payments in pages of 100. Between the requests for page one and page two a new payment is created, and the last item of the first page appears again on the second. Another scenario: a report “for yesterday” does not contain an order created at 00:30 Kyiv time. There is no error, the status is 200, the schema is right, and the data is wrong. These bugs are the sneakiest because they cannot be seen without comparing against the expected state.
Four cases: pagination, time zones, silent truncation and encoding, caching of private data.
How it works
Pagination. In offset mode (?page=2&limit=100) the server skips the first 100 records and returns the next ones. If a record was added between requests, everything shifts by one: the last item of page 1 becomes the first on page 2. If a record was deleted, one disappears. Unstable sorting (equal created_at without a second key) also gives duplicates and gaps, because the order of equal records is not guaranteed. Cursor mode is tied to the value of the last returned key, not to a position number, so an insertion does not shift it.
A new record inserted between pages
Typical
Offset
Page 1 returned records 1-2, a new one was added at the start, page 2 returns records 2-3: record 2 twice.
Better
A cursor and a stable key
Page 2 starts after the last key of page 1. The new record does not shift what was already seen.
Figure 1. Offset counts positions, a cursor remembers a key. That is why offset duplicates or loses items on live data.
Example: walking all pages
The test collects ids from all pages and creates a record between requests. Duplicates and gaps are visible at once. Additionally check limit=0, the boundaries of the last page and whether total matches the real count:
test('walking all pages gives no duplicates and no gaps', async ({ request }) => {
const ids: string[] = [];
let url: string | null = '/v1/orders?limit=2';
let inserted = false;
while (url) {
const page = await (await request.get(url)).json();
ids.push(...page.items.map((i: { id: string }) => i.id));
if (!inserted) {
await request.post('/v1/orders', { data: { sku: 'new', qty: 1 } }); // between pages
inserted = true;
}
url = page.nextCursor ? '/v1/orders?limit=2&cursor=' + page.nextCursor : null;
}
expect(newSet(ids).size).toBe(ids.length); // no duplicates// and every order that existed before the walk must be in ids
});
Time zones and day boundaries
The server stores time in UTC, while a user wants a report “for 9 November” in their own zone. If day boundaries are computed in UTC, an order at 23:30 in Kyiv (UTC+2 in winter) is 21:30 UTC of the same day and may be counted, but at 00:30 Kyiv time it is still 22:30 UTC of the previous day, and the order ends up in the “yesterday” report. Check data around midnight in the user’s zone, not in UTC, month and year boundaries, a daylight saving change (a day of 23 or 25 hours) and the format: ISO 8601 / RFC 3339 with or without an offset. A time without an offset is interpreted by the server on its own assumption, which is a source of off-by-one-day errors:
// the user lives in Europe/Kyiv (UTC+2 in winter); 00:30 local is 22:30 UTC of the previous daytest('an order at 00:30 local belongs to that local day', async ({ request }) => {
const created = await request.post('/v1/orders', {
headers: { 'X-Timezone': 'Europe/Kyiv' },
data: { sku: 'a', qty: 1, createdAt: '2026-11-09T00:30:00+02:00' },
});
expect(created.status()).toBe(201);
const report = await request.get('/v1/reports/daily?date=2026-11-09&tz=Europe/Kyiv');
const ids = (await report.json()).orders.map((o: { id: string }) => o.id);
expect(ids).toContain((await created.json()).id);
});
The fix: store in UTC and compute day boundaries in the user’s zone.
Silent truncation and encoding
A name longer than 50 characters is stored truncated with no error, an emoji becomes ?, Cyrillic turns into mojibake (UTF-8 read as Windows-1251). The user sees no error but the data is already lost. Check length boundaries (the maximum and the maximum plus one), Unicode (Cyrillic, emoji, combining characters), Content-Type with charset, and the database column limit, which may be smaller than the API validation. The right behaviour is either to store everything or to reject with 400/422, but not to truncate silently:
const limit = 50; // the documented maximum of "name"for (const [label, name] of [
['max', 'a'.repeat(limit)],
['max + 1', 'a'.repeat(limit + 1)],
['cyrillic', 'Олена-Марія'],
['emoji', 'Team 🚀'],
]) {
test('name: ' + label, async ({ request }) => {
const res = await request.post('/v1/teams', { data: { name } });
if (res.status() === 201) {
const saved = (await (await request.get(res.headers()['location'])).json()).name;
expect(saved).toBe(name); // stored as sent, not silently cut or mangled
} else {
expect([400, 422]).toContain(res.status()); // or rejected with a clear error
}
});
}
Caching of private data
User B receives a response meant for A. The cause: a cache (CDN, gateway, reverse proxy) is keyed by URL and ignores the token. Under RFC 9111 a shared cache does not store a response to a request with Authorization unless the response explicitly allows it (public, s-maxage, must-revalidate), but a misconfigured gateway or public on a personal response bypasses that. Check with two accounts on one URL, the Cache-Control headers (private or no-store for personal data), Vary, and also Age and X-Cache (the format depends on the CDN):
test('a personal response is not served to another user from a cache', async ({ request }) => {
const a = await request.get('/v1/me/orders', { headers: authA });
const b = await request.get('/v1/me/orders', { headers: authB });
expect(await b.json()).not.toEqual(await a.json());
const cc = a.headers()['cache-control'] ?? '';
expect(cc).toMatch(/private|no-store/);
expect(a.headers()['age']).toBeUndefined(); // not served from a shared cache
});
One URL for two users through a shared cache
Typical
Cache-Control: public
The gateway stored A’s response under the URL. User B requests the same URL and gets A’s data.
Better
private or no-store
A shared cache does not store a personal response. Each user gets their own.
Figure 2. One wrong directive turns a personal response into one shared by everyone.
Limits and alternatives
A pagination test with an insertion catches a shift, but not all stability problems. For large sets also check that the sorting includes a unique key.
A time zone test depends on the current date for DST: fix the date in the test and do not rely on the system clock.
A cache test on a stage without a CDN proves nothing. Check where the gateway stands, as in production.
Silent truncation is sometimes documented as behaviour. Then the bug is in the documentation, not in the code, but the user still has to find out.
Common mistakes
Checking only the first page. Duplicates and gaps show up at page boundaries.
Testing time in UTC. The defect is visible only at the user’s day boundary.
Catching only errors. All four bugs return 200, so you compare data, not status.
Not repeating POST and then GET. Truncation is visible only if you compare what was stored with what was sent.
Checking the cache with one user. A leak shows up only with two.
Check yourself
A list of 5 records, limit=2. A record was added between the requests for pages 1 and 2. What will the client see with offset pagination?
Answer
The new record is added at the start (sorted by date descending) and everything shifts by one. Page 2 begins with the last record of page 1, so it appears twice. A cursor by key avoids that. The test collects the ids of all pages and checks for no duplicates and no gaps.
A response has Cache-Control: public, max-age=60 on /me/orders. What is dangerous about it?
Answer
A shared cache (CDN, gateway) may serve the stored response to anyone requesting this URL within 60 s. User B may receive A’s orders. For personal data I expect private or no-store. This is a critical leak, and I check it with two accounts.
Related lessons: “Pagination: offset vs cursor”, “ETag, 304 and Cache-Control”, “Request and response body: types, null and empty values”.
In an interview.Junior: These are bugs that give no error: the response is 200 but the data is wrong. For example, in pagination a record can appear twice, and time can shift a day. Middle/Senior: Offset duplicates and loses records on live data, so I walk all pages with an insertion between requests and recommend a cursor with a stable key. For time I take midnight in the user’s zone and a daylight saving change, for strings length boundaries and Unicode with a POST then GET check, and for the cache two accounts on one URL and a look at Cache-Control and Vary.
Contract and performance: breaking change, 200 with an error, N+1
A breaking change is a contract change after which an old client breaks: a renamed or removed field, a changed type, a new required request field. It is caught before release by comparing specifications and by contract tests. An error in the body with status 200 is invisible to clients and monitoring, so the first assert is on status, and N+1 is found by measuring time and SQL queries at growing volume.
API · Typical bugs
The dashboard shows 100% success, yet clients complain about errors. What went wrong?
After a release the mobile app shows an empty phone number: the backend renamed phone to phoneNumber. Monitoring is cheerful because the error is returned as 200 OK with {"status":"error"}. And a list endpoint with 10 records is fast until a client with 100,000 shows up in production. What these bugs share: they do not break a single request in a test, they break the agreement with clients or the behaviour under volume.
Three cases: a breaking contract change, 200 with an error in the body, N+1 and unbounded requests.
How it works
The contract. A client writes code for the shape of the response: field names, types, allowed enum values, error codes. Anything that changes this shape so that old code stops working is a breaking change: renaming or removing a field, changing a type ("id": 5 became "id": "5"), a new required field in a request, a new enum value the client does not know, narrowing a range. Adding an optional field to a response is usually safe. Mobile apps do not update instantly, so old versions live for months.
The status. Clients, caches, gateways and monitoring work with the status code, not with the body. 200 means “success”, and retries, caches and metrics behave accordingly. An error in the body under that status is invisible to the whole infrastructure.
The volume. N+1 happens when for a list of N records there is 1 query for the list and one more per item (its author, its status). The number of SQL queries grows with the response, and so does the time.
A failure that is seen and one that is not
Typical
200 and status: error in the body
Monitoring counts a success, a cache may store the response, an automatic retry considers the request done.
Better
422 or 5xx and Problem Details
Metrics show a failure, the cache does not store it, the client sees the reason in a standard format.
Figure 1. Only the client reads the error body, while everyone reads the status. So the error belongs in the status.
Example: a breaking change
The change can be found before the release by comparing specifications. The oasdiff tool (an OpenAPI CLI) has a breaking command that is put into CI. Take flag names from its documentation:
# compare the specification of the release candidate with production
oasdiff breaking https://prod.example.test/openapi.yaml ./openapi-next.yaml
# the CI job fails on a breaking change
oasdiff breaking prod.yaml next.yaml --fail-on ERR
A specification may not match the code, so add a test against a live response that checks what the old client relies on: names, types, enums.
test('the old client contract of GET /v1/users/{id} still holds', async ({ request }) => {
const user = await (await request.get('/v1/users/7')).json();
expect(typeof user.id).toBe('number'); // not "7"expect(typeof user.phone).toBe('string'); // not renamed to phoneNumberexpect(['active', 'blocked']).toContain(user.status); // no unknown enum value
});
The fix: return both fields for the migration period, add a version (/v2) and announce the support period of the old one. A contract test (consumer-driven, for example Pact) checks the consumers’ expectations in the provider’s CI before the release.
Example: 200 with an error
The error is visible only in a negative scenario: insufficient funds, invalid data, someone else’s resource. The response looks like this:
The test checks the status first, because clients may already parse the body (the fix will break them, so find the consumers). The body format is RFC 9457 Problem Details:
test('insufficient funds is an error status, not 200', async ({ request }) => {
const res = await request.post('/v1/accounts/42/transfers', {
headers: { 'Idempotency-Key': crypto.randomUUID() },
data: { toAccount: 'UA21...', amountMinor: 99999999, currency: 'UAH' },
});
expect(res.status()).toBe(422); // checked first, the body secondexpect(res.headers()['content-type']).toContain('problem+json');
});
Example: N+1 and an unbounded request
A sign of N+1: time grows linearly with the response size. The test measures time for 10, 50 and 100 records (100 is the maximum limit here) and tries a very large limit. The number of SQL queries per API request is best seen in logs or APM, and it must not grow with the response size:
for (const size of [10, 50, 100]) {
test('list time with ' + size + ' orders', async ({ request }) => {
awaitseedOrders(size); // helper that creates data for one test userconst t0 = performance.now();
const res = await request.get('/v1/orders?limit=' + size);
const ms = performance.now() - t0;
expect(res.status()).toBe(200);
console.log(size, 'rows:', Math.round(ms), 'ms'); // growth must be flat-ishexpect(ms).toBeLessThan(1500);
});
}
test('an absurd limit is capped or rejected', async ({ request }) => {
const res = await request.get('/v1/orders?limit=100000');
if (res.status() === 200) expect((await res.json()).items.length).toBeLessThanOrEqual(100);
elseexpect(res.status()).toBe(400);
});
A list of N records with their authors
Typical
N+1
1 query for the list and N for the authors: 1001 calls for 1000 records.
Better
A join or batch loading
1-2 queries for the list and all authors at once. The count does not depend on N.
Figure 2. The difference is the number of database queries. It is what turns a fast endpoint into a slow one as data grows.
The fix: eager loading or a join, pagination with an upper bound on limit, an index for filters and sorting.
Limits and alternatives
Comparing specifications catches only what is described. An undocumented change (the type of a field in a real response) requires a test on live responses or schema validation.
A timing test on a shared stage is noisy. Take a rough threshold and repeat it, and leave exact numbers to a load test with percentiles.
Not every field removal is breaking: if a field is marked deprecated and has no consumers, it can be removed under the versioning policy. But that is a team decision, not a tester’s.
When changing 200 to 4xx, remember the clients that parse the body. Agree on the transition.
Common mistakes
Treating adding a field as safe in all cases. A client with strict schema validation may fail on an unknown field.
Checking only the body of a negative response. A 200 status covers up the error, so the first assert must be on the status.
Measuring time on a small set. N+1 shows up only as the volume grows.
Not trying a large limit. An unbounded request is a way to bring the service down with one call.
Looking only at the specification. The code may drift from it, so a live-response check is needed too.
Check yourself
A new release returns "id": "5" instead of "id": 5. Tests that check toBeTruthy() are green. Why is this a problem and how do you catch it?
Answer
The field type changed, which is a breaking change: a client that compares the id as a number or passes it on breaks. A weak check does not notice. I catch it with typeof user.id === "number", JSON Schema validation or a specification comparison in CI.
A list endpoint answers in 80 ms with 10 records and in 12 s with 10,000. What do you do?
Answer
I suspect N+1 or a missing index or pagination. I measure time for 10, 100, 1000, look at the number of SQL queries per API request and the response size, and try a large limit. The report: request, volume, time, number of database queries. The fix: a join or eager loading, a limit, an index.
Related lessons: “Consumer-driven contracts and breaking changes”, “Error format: Problem Details and stable codes”, “A load test in practice: SLO, data, conclusions”.
In an interview.Junior: A breaking change is a response change that breaks an old client: a renamed field or a different type. An error inside a 200 is bad because the status says “success”. Middle/Senior: I catch a breaking change before release by comparing OpenAPI in CI and with contract tests on a live response, and fix it by adding a version and a migration period. I find an error in a 200 with negative scenarios and the status as the first assert. For N+1 I measure time on a growing volume and count SQL queries per API request, and I also cap the limit and add an index.
What to do when you find a critical API bug
On finding a critical API bug, the first rule is not to exploit it further: work with test accounts and do not enumerate other people's data. Then reproduce it with a minimal request, collect evidence without secrets, rate severity by impact, likelihood and difficulty of exploitation, and report through a security channel rather than a public ticket. After the fix, add a regression test to CI.
API · Typical bugs
You found that someone else’s invoice opens by id. What do you do in the first hour?
A critical API bug is a leak of other people’s data, money, privilege escalation or an unavailable service. You can go wrong not only in the bug itself but in the reaction: keep exploiting the vulnerability “to investigate”, lose the evidence, or write about it in a public ticket. A good reaction achieves one thing: the developer reproduces the bug on the first attempt and understands how serious it is.
The lesson gives a ten-step order, explains why it is this way and shows a report that can be handed over without any follow-up questions.
How it works
The order is built around two risks. The first: harm from the investigation itself, hence “do not dig deeper” at the start. The second: losing evidence and time, hence reproduction, evidence and severity come before the ticket, not after. Each step answers one question that a developer or the security team will ask:
Do not dig deeper. Do not exploit the bug, do not enumerate other people’s data, do not perform destructive actions. Work on test accounts and test data;
Reproduce minimally. The smallest set of steps, one request if possible (curl). Repeat 2-3 times. For races record the frequency (for example 7 of 10);
Isolate the layer. The same request without the UI, without the gateway or cache, by another user, on another environment. Find out when it appeared: the last release or long ago;
Collect evidence. The full request and response (no secrets in the clear), status, headers, a request or trace id, timestamps with a zone, version and environment, resource ids, a log fragment;
Estimate the scale without harm. Which methods, roles and resources are involved, one record or a whole class. Do not bulk-collect real data;
Severity. Impact × likelihood × difficulty of exploitation. A data leak, money or privilege escalation is critical. Report it immediately through the security channel or the on-call person, not in a public ticket;
The report in the template below;
A temporary mitigation. Suggest a workaround (disable the endpoint, a feature flag, a gateway rule). The team decides;
Verify the fix. The same case, neighbouring resources and methods, negative variants, on the environment where it was found and after the release in production;
Regression. An autotest in CI, a schema check, an item in the checklist. Ask why the bug was missed.
The reaction to a found leak
Typical
“I will see what else is there”
Enumerating other people’s ids, screenshots with real data in a chat, a public ticket. The harm grew, and there is no evidence in usable form.
Better
A minimal reproduction and the security channel
Two own accounts, one request, evidence without secrets, a message to the responsible people. The harm did not grow, the actions are clear.
Figure 1. The difference is not speed, but whether the evidence stayed intact and whether the harm shrank.
Example: from the finding to the report
Step 2 looks best as a single request that the developer can run themselves. Secrets are substituted via variables, and a request id helps find the trace in the logs:
# one request, two own accounts, nothing else
curl -i "$BASE/v1/invoices/10442" \
-H "Authorization: Bearer $TOKEN_QA_A" \
-H "X-Request-Id: bug-bola-001"
Next is isolation: the same request straight to the API (without the app), with another role, on another environment, and finding out since when the bug exists (from the release history). The report is assembled from the facts found. It must be complete without any follow-up questions:
Title: [Critical][API] GET /invoices/{id} returns another user's invoice (BOLA)
Environment: stage, build 2026.11.3, 2026-11-09 14:12 (UTC+2)
Steps:
1) Sign in as qa-a (id 77), get a token
2) GET /api/v1/invoices/10442 (invoice of qa-b, id 91) with qa-a's token
Expected: 403 or 404
Actual: 200, ownerId 91, the full invoice
Evidence: X-Request-Id 7f3a..., response attached (tokens redacted)
Impact: any user can read others' invoices; ids are sequential
Checked: PUT and DELETE on 10442 also work; /invoices/{id}/pdf too
Workaround: none; suggest closing /invoices/{id} at the gateway for now
Notes: reproduces 3 of 3; first build with the bug is 2026.11.1
Why it is like this. A title with the severity and the place gives triage in a second. “Expected” and “Actual” separate a bug from an opinion. The “Checked” block shows the scale without requiring enumeration of other people’s data. Evidence with redacted tokens (Bearer … cut off) does not create a new leak from the ticket itself.
Two starting severity levels
Critical
A leak of other people’s data, money, privilege escalation, full unavailability. Immediately, through a separate channel, with a suggested workaround.
High and below
Limited impact or difficult exploitation. A regular ticket, but with the same set of evidence.
Figure 2. The levels depend on team policy, but the criteria are the same: impact, likelihood, difficulty of exploitation.
Limits and alternatives
The order does not replace company policy. There are incident response processes, a channel for vulnerabilities and, in open projects, SECURITY.md or a bug bounty programme. Find them first.
In regulated fields (payments, healthcare) a leak has legal notification deadlines. The product owner or security does that, but the tester has to give them the facts quickly.
A temporary mitigation is not a fix. A workaround on the gateway closes the known path, not the cause, so the ticket stays open until the code is fixed.
Sometimes a minimal reproduction is impossible: the bug depends on data or a race. Then collect the frequency, conditions and logs, and do not invent deterministic steps.
Common mistakes
Investigating “a little more” on other people’s data. That is already access to data nobody allowed, even with good intentions.
Attaching a token or password in the clear. A ticket with a secret becomes a leak itself.
Writing severity “high” without explaining the impact. Without “who loses what”, triage guesses.
Opening a public ticket for a vulnerability. First the security channel or a responsible person, the ticket after a decision.
Closing the bug after the release without a regression test. Without an autotest it comes back.
Check yourself
You found BOLA and want to estimate the scale. How many other people’s ids may you enumerate as proof?
Answer
None. Two of your own accounts are enough as proof: A’s token reads B’s resource. I estimate the scale by methods, addresses and roles, not by the number of real records. There is no need to collect what you see in other people’s data, the fact that access exists is enough.
A developer says “It does not reproduce”. What was wrong with the report and what do you add?
Answer
The environment and build, the exact request, resource ids, time with a zone and a request id were missing. I add a single curl request with my two accounts, expected and actual results, the frequency (“3 of 3”) and the version where the bug appeared. If the bug depends on data or a race, I add the conditions and logs.
Related lessons: “Access and authorization: BOLA/IDOR, tokens, mass assignment”, “OWASP API Top 10: access and authentication”, “Information leaks: errors, URLs, logs and enumeration”.
In an interview.Junior: I found a critical bug: I do not exploit it further, I reproduce it on test data, collect the request, response and time, write a report with steps and tell the responsible people. Middle/Senior: First a minimal reproduction with one request and isolation of the layer, then evidence without secrets and severity by impact, likelihood and difficulty. A critical one goes through the security channel, not a public ticket, with a suggested workaround. After the fix I verify neighbouring methods and resources, add an autotest to CI and ask why the bug was missed at earlier stages.