← Study Notes Security


Security

Input Validation & Sanitization

The front door of application security: validate that input matches what you expect — type, shape, range, allow-list — and neutralise what you pass on: parameterised SQL, encoded HTML, safe paths. Injection attacks (SQLi, XSS, SSRF, traversal) are all failures to keep data and code apart. Validate at the boundary; encode at the point of use.


Purpose

Almost every injection class is one mistake wearing different costumes: untrusted input reaching an interpreter — SQL, HTML, a shell, a file path, a URL fetcher — still dressed as code. Validation and sanitisation are the two halves of the defence: validation rejects input that does not match expectations, at the boundary where it enters; sanitisation/encoding renders what remains inert for the specific context where it is used.

When to Use It

Every API body, query param, header, file upload, and webhook payload — anything an outsider can influence, including data that arrives "from the database" but was user-supplied last year. The counter-intuitive cases matter most: filenames used in paths (traversal), URLs the server fetches (SSRF), and rich text destined for other users' browsers (stored XSS).

Trade-offs

Over-strict validation rejects legitimate reality — names with apostrophes, addresses without postcodes, valid Unicode — so validate structure, not your assumptions about people. Sanitisation is context-specific: HTML-encoding does nothing against SQL injection, and one "sanitise everything" pass gives false confidence. And client-side validation is pure UX; the browser belongs to the attacker.

Implementation

Validate at the edge with a schema library (zod, Joi, JSON Schema): types, lengths, ranges, formats, and allow-lists over deny-lists — enumerate the good, don't blacklist the bad. Then use the context's safe primitive: parameterised queries for SQL, output encoding or a vetted sanitiser (DOMPurify) for HTML, allow-listed hosts for server-side fetches, and never string-concatenate into shells or paths.