Advanced Web Applications Development

Labs · Lab

Lab B — add a fare, and refuse a bad one

Accept a new fare, say no clearly when the request is wrong, and see what an unparameterised query hands an attacker.

In this lab

  • Validating a request before it reaches the database
  • Choosing between 201, 400 and 404
  • What an unparameterised query hands an attacker
Time
30 min
Start from
checkpoint/lab-a-done
Finish at
checkpoint/lab-b-done

Reading fares is the easy half. The moment anyone can write one, two questions arrive that reading never asked: is this request sane, and can I trust what is inside it?

This lab is less guided than Lab A. The steps say what to build, not every line to type.

Catch up

git checkout checkpoint/lab-a-done
npm run reset

The idea

A bursar sends a fare. Three things can be true:

  • The request is fine → 201, and the fare exists now.
  • The request is malformed — no amount, no source, a negative number → 400. Their mistake, and they can fix it.
  • The route does not exist → 404. Nothing is wrong with the request; the thing it points at is missing.

Those are different sentences, and collapsing them into one is how an API becomes impossible to debug from the outside.

Steps

1. Validate before you touch the database. Write a validateFare(body) function above the handler that collects all the problems into an array rather than returning on the first one. A bursar fixing four mistakes one round-trip at a time will stop using your software.

Check at least: from and to are stop ids, amountDalasi is a whole number above zero, effectiveFrom parses as a date, and source is present. The amount is also worth a sanity ceiling — a fare over D5000 is a typo, not a bus.

2. Write the handler. Validation first, then look up the route, then create:

router.post('/', async (req, res) => {
  const { problems, from, to, amountDalasi, effectiveFrom, source } =
    validateFare(req.body ?? {});

  if (problems.length > 0) {
    return res.status(400).json({ error: 'That fare was not accepted', problems });
  }

  const route = await db.route.findFirst({
    where: { originId: from, destinationId: to },
    include: { origin: true, destination: true },
  });

  if (!route) {
    return res.status(404).json({ error: 'No route between those two stops' });
  }

  // TODO: create the fare and answer 201
});

3. Create it, and mark it as real. The seeded fares are guesses with status: 'sample'. Yours was actually paid, so it is 'verified'. Answer with 201 and a Location header pointing at where the new fare can be read.

4. Add the fare you paid this week. Use your own trip, your own amount, and say in source where it came from:

curl -X POST localhost:3000/api/fares \
  -H 'Content-Type: application/json' \
  -d '{"from":1,"to":8,"amountDalasi":50,"effectiveFrom":"2026-11-18","source":"paid it on Tuesday"}'

5. Commit and push.

git add -A
git commit -m "Lab B: add a fare with validation"
git push

Checkpoint

A valid fare returns 201 and the row it made:

{"id":41,"from":"Westfield","to":"Brikama","amountDalasi":50,"effectiveFrom":"2026-11-18T00:00:00.000Z","source":"paid it on Tuesday","status":"verified"}

Now search that route again in the browser. It says D50, and the badge reads verified rather than sample — because your fare’s date is later than April’s, and Lab A already asks for the newest one that has started. You wrote no new search code, and the search changed its answer.

A bad body returns 400 and every problem at once:

{"error":"That fare was not accepted","problems":["amountDalasi must be a whole number of dalasi above zero","source is required — say where this fare came from"]}

A missing route returns 404:

{"error":"No route between those two stops"}

The part worth stopping on

Lab A said Prisma sends values separately from the query, so a stop id can never be read as a command. Here is what it costs when that is not true.

On the demo/injection branch there is a stop search built by gluing the input into the SQL. That branch exists only to be attacked — it is never merged into main, and no pull request is opened from it. If you reuse this repository with your own students, keep it that way: the one thing worse than no demo is a demo that quietly ships.

const rows = await db.$queryRawUnsafe(
  `SELECT id, name, region FROM stops WHERE name = '${name}'`
);

Searching for Westfield behaves:

[{"id":1,"name":"Westfield","region":"Kanifing"}]

Now search for ' OR '1'='1 instead:

curl -G localhost:3000/api/fares/unsafe-search --data-urlencode "name=' OR '1'='1"

All twelve stops come back. The quote closed the string, OR '1'='1' is always true, and the query stopped being the one that was written. Nobody had to guess a password. The input was simply read as instructions.

The fix is not better escaping. It is never building the sentence by gluing:

const rows = await db.$queryRaw`
  SELECT id, name, region FROM stops WHERE name = ${name}
`;

That looks almost identical — it is a tagged template, not a string — and the same attack now returns:

[]

The value went to the database as a value. There is no stop literally named ' OR '1'='1, so nothing matches. Which is the correct answer.

Everything you wrote in Lab A and Lab B already works this way. The lesson is what the shortcut costs on the day someone reaches for it.

If it breaks

req.body is undefined — the request had no Content-Type: application/json header, so nothing parsed it. Check the curl command.

201 but the fare never appears in search — you set effectiveFrom in the future. Lab A’s query only returns fares that have started.

Every request returns 400 — your validator is pushing a problem even when the value is fine. Log req.body and read what actually arrived.

“Unique constraint failed” — you created a route rather than a fare, and that pair already exists.

The finished code

Both pieces, as they stand on checkpoint/lab-b-done. This lab asked you to design the validator yourself, so expect yours to differ — what matters is that it collects every problem instead of returning on the first one.

// ... the GET handler you wrote in Lab A, unchanged

// Everything the body must get right, in one place, so the handler below
// reads as a list of decisions rather than a thicket of ifs.
function validateFare(body) {
  const problems = [];

  const from = Number(body.from);
  const to = Number(body.to);
  const amountDalasi = Number(body.amountDalasi);

  if (!Number.isInteger(from) || !Number.isInteger(to)) {
    problems.push('from and to must both be stop ids');
  }

  if (!Number.isInteger(amountDalasi) || amountDalasi <= 0) {
    problems.push('amountDalasi must be a whole number of dalasi above zero');
  }

  if (amountDalasi > 5000) {
    problems.push('amountDalasi looks like a typo — over D5000');
  }

  const effectiveFrom = new Date(body.effectiveFrom ?? Date.now());

  if (Number.isNaN(effectiveFrom.getTime())) {
    problems.push('effectiveFrom must be a date like 2026-11-20');
  }

  if (!body.source || String(body.source).trim().length < 3) {
    problems.push('source is required — say where this fare came from');
  }

  return {
    problems,
    from,
    to,
    amountDalasi,
    effectiveFrom,
    source: String(body.source ?? '').trim(),
  };
}

// POST /api/fares
router.post('/', async (req, res) => {
  const { problems, from, to, amountDalasi, effectiveFrom, source } = validateFare(
    req.body ?? {}
  );

  // 400 means "you sent something wrong and can fix it".
  if (problems.length > 0) {
    return res.status(400).json({ error: 'That fare was not accepted', problems });
  }

  const route = await db.route.findFirst({
    where: { originId: from, destinationId: to },
    include: { origin: true, destination: true },
  });

  // 404 means "what you asked for is not here", which is a different fix.
  if (!route) {
    return res.status(404).json({ error: 'No route between those two stops' });
  }

  const fare = await db.fare.create({
    data: {
      routeId: route.id,
      amountDalasi,
      effectiveFrom,
      source,
      // Someone actually paid this one, unlike the seeded guesses.
      status: 'verified',
    },
  });

  // 201 means "I made something", and Location says where it lives.
  res
    .status(201)
    .location(`/api/fares?from=${route.originId}&to=${route.destinationId}`)
    .json({
      id: fare.id,
      from: route.origin.name,
      to: route.destination.name,
      amountDalasi: fare.amountDalasi,
      effectiveFrom: fare.effectiveFrom,
      source: fare.source,
      status: fare.status,
    });
});

export default router;

Stretch

  1. Reject a duplicate. Refuse a fare whose route and effectiveFrom already exist, with 409 Conflict. Which is right: refuse, or replace?
  2. Make the web page do it. Add a small form that POSTs a fare, so the bursar never touches curl.

For trainers

  1. Where would your students get stuck first?
  2. What would you cut if you had twenty minutes instead of thirty?
  3. What would you add that is missing here?
Saved in this browser only.