lessons/input-validation.md

Lesson 4 of 18

Validate values, not just types

A value can have the right type and still be wrong for the business.

Remember: Validate type, sign, range and meaning on the server, and prefer allowlists to blocklists.

A negative amount is still a number. But a transfer of -100 is a reversal the system never intended. Validation is about what a value means for the business, not only about its JavaScript or Python type.

  • Type: an integer, not a string or a float.
  • Sign and range: strictly positive, and below a per-transaction limit.
  • Format: IDs are UUIDs, currencies come from a fixed list.
  • Size: strings and arrays have maximum lengths.
  • Meaning: is the recipient allowed to receive? Is the account active?
const amount = body.amountMinor;
Vulnerable: used directly. Sign, type and size are never checked.
const TransferInput = z.object({
fromId: z.string().uuid(),
amountMinor: z.number().int().positive().max(5_000_000),
currency: z.enum(["EUR", "GBP", "USD"]),
});
const { amountMinor } = TransferInput.parse(await req.json());
Fixed: a schema rejects bad input before any business logic runs.

Allowlists over blocklists

A list of forbidden values always misses something. List what is allowed instead: allowed hosts, allowed columns, allowed currencies, allowed redirect paths.

Client-side validation is not a control

Validating in the form improves the user experience. It is not a security control, because any request can be sent straight to the API with curl or Burp.

Reject invalid input with a 400. Silently fixing the value (setting it to 0, or taking its absolute value) hides the problem and changes what the user asked for.

Questions to ask yourself

  1. Which fields does the business care about, and are they all validated?
  2. Which values would break an invariant: zero, negative, huge, empty?
  3. Is the rejection explicit (400), or a silent correction?

Practise this