lessons/basic-checks.md

Lesson 14 of 18

Basic checks: sign, zero, empty, null, NaN and bounds

The simplest checks are the ones reviewers skip. Each one below has caused a real incident.

Remember: For every value, ask: can it be negative, zero, empty, null, NaN, too large, or the wrong type? Then check that the code handles each answer on purpose.

A surprising share of security bugs are not clever. They are a value nobody checked: a negative amount, a zero divisor, an empty list, a missing header. You can learn to see them with one habit: for every input, list the values that break the meaning of the business, and check that each one is rejected or handled on purpose.

The checklist, in one line each

  • Sign: can the value be negative? A negative amount reverses a transfer or withdrawal.
  • Zero: is zero allowed? Zero is a divisor, an empty quantity, and often a sign of a bug.
  • Empty: an empty string, list or map. First and last elements do not exist.
  • Null or undefined: a lookup that finds nothing. In JavaScript, undefined == undefined is true.
  • NaN and Infinity: produced by bad number conversions. Every comparison with NaN is false.
  • Bounds: page 0, index -1, a page size of a billion, a length of 200 in a 16-byte buffer.
  • Type: a string where a number is expected, a float where an integer is needed for money.

Negative and zero, in three languages

if amount > account.balance:
raise InsufficientFunds()
account.balance -= amount
Vulnerable: a negative amount passes the balance check, and the subtraction adds money.
return total / transactions.Count;
Vulnerable: a zero count throws on every request for an empty customer.
const amount = Number(input);
if (amount <= 0) throw new Error("positive");
Vulnerable: NaN is not <= 0, so the guard lets it through.

Null, undefined and missing values

A missing value is not the same as a value that is wrong. In JavaScript, a request without a token has undefined, and a user without a reset token also has undefined; == says they match. The safe pattern is to reject missing input first, then compare with strict equality or a timing-safe function. Keep null checks next to the lookup that can return null, not far away.

Write the failing input first. Before you decide whether code is safe, type the worst value you can think of into the input and follow it: what does each line do with it?

Questions to ask yourself

  1. What is the smallest and largest value this input can have, and what does the code do with each?
  2. What does this code do when the list is empty, the lookup returns nothing, or the value is zero?
  3. Is the check on the meaning of the value, or only on its type?

Practise this