Review the booking endpoints as a second user and with growing data, find an access-control hole and a query that grows with the list, and prove both fixes.
Outcome: Identify access-control problems and inefficient behaviour.
Note
Reading as a visitor
Everything in this lesson is free to read. Sign in and enrol to answer the questions and record your progress.
Recognise broken object-level authorisation and test for it with a second user.
Explain why this API answers 404 rather than 403 for another user's booking.
Recognise the N+1 query pattern and replace it with a constant number of queries.
Measure query counts at two data sizes instead of guessing about performance.
Direct an agent's review with specific questions and require a reproduction for each finding.
Prerequisites
Comfortable reading TypeScript and SQL, including joins.
Knows the difference between authentication and authorisation.
Can send HTTP requests with curl and set an Authorization header.
Concepts
Two kinds of defect that tests rarely catch
Access-control gaps and inefficient queries have something in common: the code returns the right data for the person testing it. A developer signed in as Ada asks for Ada's booking and gets it. A list of three seeded bookings comes back in a few milliseconds. Both defects only show up when you ask a different question: what happens when Grace asks for Ada's booking, and what happens when Ada has five hundred bookings? Reviewing for them means asking those questions on purpose.
Broken object-level authorisation
Authentication answers "who is calling?". Authorisation answers "may this caller act on this particular object?". The booking service authenticates every /bookings request with requireUser() in src/auth.ts. That is necessary, but it says nothing about which bookings the user may see.
When an endpoint takes an object id from the request, such as GET /bookings/:id, and loads the object by that id alone, any authenticated user can read any object by changing the number. This is broken object-level authorisation (BOLA, also called IDOR), and it is first in the OWASP API Security Top 10 (2023) because it is common, easy to exploit and easy to automate: sequential integer ids make enumeration a loop.
The robust fix is to make ownership part of the lookup, not a check bolted on afterwards: the WHERE clause names both the object's id and the caller's id, so the database returns nothing for someone else's object. Scoping the query means an object the caller may not see is never loaded, and every code path that reuses the query inherits the rule. A check after the load (if (row.user_id !== user.id)) works too, but is easier to forget on the next endpoint.
Worked example
The situation
The facilities team wants a screen outside each meeting room that shows its upcoming bookings. An agent added this endpoint next to the other public resource routes in src/routes/resources.ts, and its tests pass:
/** Upcoming bookings of a resource, for the screen outside the room. */
app.get<{ Params: { id: number } }>("/resources/:id/schedule", { schema: { params: idParams } }, async (request) => {
const resource = await findResource(db, request.params.id);
const { rows } = await db.query<BookingRow>(
"SELECT * FROM bookings WHERE resource_id = $1 AND ends_at > now() ORDER BY starts_at",
[resource.id],
);
const entries = [];
for (const row of rows) {
const user = await db.query<{ name: string }>("SELECT name FROM users WHERE id = $1", [row.user_id]);
entries.push({ ...bookingView(row), booked_by: user.rows[0].name });
}
return { data: entries };
});
This walk-through reviews it for access control and efficiency. The endpoint is not part of the exercise; the method is.
Step 1: ask who can call it and what they get
Write down three facts before judging anything:
Question
Answer from the code
Who can call it?
Anyone. Like the other /resources routes, it has no requireUser().
Which objects does it return?
Concept questions
Sign in and enrol to answer and save your progress.
Exercise
Your task
A colleague has asked you to review the booking endpoints of this service before a release, for access control and query efficiency, and to fix what you find. The tests pass. The README's API table describes the intended behaviour; treat it as the specification and the code as the thing under review.
This exercise is about finding the problems as much as fixing them, so work like a reviewer: form a hypothesis, prove it with a request or a measurement, fix it, then prove the fix.
Steps
Read the specification. In README.md, read the API table and the status codes. Note what each /bookings route promises about whose bookings it returns.
Read the code under review: src/routes/bookings.ts, plus src/auth.ts and src/routes/resources.ts for the helpers it calls.
Probe access control with two users. Start the service and make requests as different seeded users. dev-token-ada, dev-token-grace and dev-token-edsger are seeded; the seed gives Ada and Grace bookings on resource 3.
Reflection
Recorded for you to look back on. It is not graded and does not by itself show understanding.
Prompt: How did you find each problem? Describe what you looked at or measured, the evidence that convinced you, and any suggestion from your agent, or your own first idea, that you rejected or changed, and why.
For an object the caller may not access, there are two honest answers. 403 Forbidden says "it exists, but not for you". 404 Not Found says nothing about existence. RFC 9110 explicitly allows 404 when the server "is not willing to disclose that one exists". For bookings, existence itself is information: a 403 would let anyone probe which ids exist and estimate how many bookings the business takes. This API therefore returns 404 BOOKING_NOT_FOUND for both unknown and other people's bookings, with the same body, and its README says so. Use 403 when the caller already knows the object exists and is entitled to know it, such as a document shared with them read-only that they try to edit.
The N+1 query pattern
An N+1 query pattern runs one query to fetch a list and then one more query per item to fetch something related:
// a front-desk report: today's bookings with the name of the person who booked
const { rows } = await db.query("SELECT * FROM bookings WHERE starts_at::date = current_date");
for (const row of rows) {
const booker = await db.query("SELECT name FROM users WHERE id = $1", [row.user_id]); // one round trip per booking
}
Each query is fast and correct, so nothing looks wrong. The cost is in the count: every query is a network round trip to PostgreSQL plus parsing and planning, done one after another. Fifty bookings means fifty-one round trips; a busy day makes the report slow, and several such requests at once can exhaust the connection pool. The fix is to ask for everything in one statement, usually with a JOIN, or, when a join is awkward, with one batched query such as WHERE id = ANY($1). Either way the number of statements stays constant as the list grows.
Measure, don't guess
Performance reviews go wrong when they start from intuition. "Add an index" and "add a cache" are the two most common suggestions, and neither fixes an N+1: the per-item lookups are by primary key, so they already use an index, and a cache only reduces repeated lookups of the same row. Measure first:
Count statements per request. The number of queries should not grow with the size of the result. PostgreSQL's pg_stat_statements extension counts executed statements server-side; in a test you can also wrap the pool's query function and count calls.
Vary the input size. Measure with 5 items and with 50. A constant cost stays flat; an N+1 grows in step.
Read the plan with EXPLAIN ANALYZE when a single query is slow, to see whether it scans more rows than it returns.
Reviewing with an agent
Agents are useful reviewers if you ask specific questions and demand evidence. "Review this for security" tends to produce a long, generic list: rate limiting, input validation, HTTPS. Ask instead: "For each route that takes an id, which rows can a caller other than the owner read or change? Show a request that proves it." For performance: "Which handlers run a query inside a loop? How many statements does GET /bookings run for 5 and for 50 bookings?"
Then check the answers yourself. Typical agent mistakes here are fixing BOLA with a 403 that confirms existence, adding the ownership check to one endpoint and missing a sibling, proposing an index for an N+1, and claiming a fix is faster without measuring anything. Each finding should end with a reproduction: a request as the wrong user, or a statement count, that fails before the fix and passes after it.
Every booking of the resource that has not ended, including cancelled ones.
Which fields of each object?
Everything bookingView() returns, including price_cents, refund_cents and status, plus the booker's full name.
The screen needs to show when the room is busy. The endpoint publishes who booked it, what they paid and who cancelled, to anyone who can reach the API. Changing the id in the URL lists every room. This is not BOLA in the strict sense, because there is no owner to check against: it is the neighbouring risk, exposing object properties the caller has no business seeing (API3 in the OWASP API Security Top 10, 2023). The question that finds both is the same: for this caller, which objects and which fields should be visible?
Step 2: prove it with a request
A finding without a reproduction is an opinion. With the service running (npm run db:reset, then npm start):
curl -s localhost:3000/resources/3/schedule
No token is sent, and the response contains "booked_by":"Ada Lovelace" and the price of each booking. That is the evidence to attach to the review.
Step 3: measure the queries instead of guessing
The loop runs one SELECT name FROM users … per booking. Rather than assert that this is slow, count it. In a test, wrap the pool's query function while the request runs:
/** Counts calls to pool.query while `work` runs. Queries on a checked-out client are not counted. */
async function countQueries(pool: Db, work: () => Promise<unknown>): Promise<number> {
const original = pool.query;
let count = 0;
pool.query = ((...args: unknown[]) => {
count += 1;
return (original as (...a: unknown[]) => unknown).apply(pool, args);
}) as unknown as Db["query"];
try {
await work();
} finally {
pool.query = original;
}
return count;
}
/** Inserts one-hour bookings for Ada, starting `first` to `last` hours from now. */
async function insertBookings(pool: Db, resourceId: number, first: number, last: number) {
await pool.query(
`INSERT INTO bookings (resource_id, user_id, starts_at, ends_at, price_cents)
SELECT $1, 1, date_trunc('hour', now()) + n * interval '1 hour',
date_trunc('hour', now()) + (n + 1) * interval '1 hour', 6000
FROM generate_series($2::int, $3::int) AS n`,
[resourceId, first, last],
);
}
it("reads a schedule with a constant number of queries", async () => {
const schedule = () => app().inject({ method: "GET", url: `/resources/${LAB}/schedule` });
await insertBookings(db(), LAB, 1, 5);
const small = await countQueries(db(), schedule);
await insertBookings(db(), LAB, 6, 50);
const large = await countQueries(db(), schedule);
assert.equal(large, small);
});
Against the agent's code this fails with 7 queries for 5 bookings and 52 for 50: one for the resource, one for the list, one per booking. The growth, not either number, is the finding. A counter inside your own process is a good local instrument, but it only sees the calls it wraps; PostgreSQL's pg_stat_statements, where it is enabled, counts what the database actually executed.
Step 4: fix the cause, then re-measure
The access fix is a product decision first: the facilities team confirms the screen needs only busy periods. So the query selects starts_at and ends_at of CONFIRMED bookings only, and the response contains nothing else. Dropping booked_by removes the loop entirely. Had the name been required, one JOIN users u ON u.id = b.user_id in the same query would have kept the count constant.
Re-run both checks: curl now shows only times, and the test passes with 2 queries for 5 bookings and 2 for 50.
What the agent got wrong, and what to ask next time
The agent copied bookingView() because it was convenient, without asking which fields this caller should see, and wrote a loop because it mirrored how the feature was described: "for each booking, show who booked it". Neither shows up in a test that runs as the developer with three bookings. Better instructions would have been: "This endpoint is public. Return only the fields a passer-by may see. Use a constant number of queries, and include a test that proves it for 5 and for 50 bookings."
Compare each answer with what the README promises. A booking that is not yours should be indistinguishable from one that does not exist.
Measure query counts. Write a test that creates a small and a larger number of bookings for one user and counts the database queries GET /bookings makes for each. (The worked example shows one way to count calls to the pool's query function.) Decide from the numbers, not from reading alone, whether the cost grows with the list.
Fix what you found, keeping the response shapes, the error format and the sort order (soonest first) unchanged.
Prove the fixes. Keep your access test and your query-count test in test/, run npm run verify, and repeat the requests from step 3.
Check the rest. Once you have fixed one instance of a problem, look for siblings: are there other places in the booking routes with the same pattern?
Constraints
Do not change package.json or package-lock.json, and do not add dependencies. The assessment starts your service with the starter's pinned dependencies; a changed lockfile means it is not started.
Do not edit db/migrations/001_init.sql. If you want a schema change, such as an index, add a new migration file.
Keep the API's behaviour as documented in the README: same paths, response shapes, status codes and error codes.
How Check work assesses this
When you select Check work, the platform takes a snapshot of your workspace's source files and assesses it outside the lab. Your service is started with node src/server.ts against a fresh database with its own users and bookings, and the checks call it over HTTP as several different users. Query counts are measured in that database, not in your code: listing bookings must use a constant number of database queries regardless of how many bookings the user has. Nothing printed in the lab and no change to the tests in test/ affects the result.
Tools
You can do this exercise with any compatible tool in the lab. If you use an agent as a second reviewer, ask it specific questions, such as "Which routes that take an id can return another user's data?" or "Which handlers query inside a loop?", and ask for a request or a measurement that proves each finding before you accept it.
Acceptance criteria
AC1Requesting another user's booking returns 404 BOOKING_NOT_FOUND, the same as a booking that does not exist.Verified behaviour
AC2Listing returns only your own bookings, with resource names, soonest first.Verified behaviour
AC3Listing bookings uses a constant number of database queries, however many bookings you have.Verified behaviour
Verified behaviour is checked by running your submitted work from outside the lab. A structure check confirms that something is present and in the expected format; it does not prove it is correct.
Not assessed
Security risks outside object-level access on the booking endpoints, such as rate limiting or token handling.
Response times; the checks count database statements rather than timing requests.
Indexes and query plans for very large tables.
The review notes, tests and measurements you write; the assessment runs its own checks instead.
Code structure and readability.
Hints
Try the exercise first. Each hint gives away a little more than the one before.
Check your work
Submit your work from the lab's Check work panel. Hidden checks run your submitted code from outside the lab; your own test output is never taken as a result. You can revise and resubmit.