EXERCISE 1 — "Encode on output, for the context" + why not at input ==================================================================== "ENCODE ON OUTPUT, FOR THE CONTEXT" MEANS: - ON OUTPUT: apply the encoding at the exact moment you INSERT the untrusted value into the page (or response), not when you first receive/store it. - FOR THE CONTEXT: choose the encoder that matches WHERE the value lands -- HTML body, HTML attribute, JavaScript string, URL, or CSS -- because each context has different breakout characters (Chapter 3). The encoding turns those breakout characters into inert equivalents the browser displays literally. TWO CONCRETE REASONS OUTPUT-TIME BEATS INPUT-TIME ENCODING: REASON 1 -- the CONTEXT IS UNKNOWN at input time. - When data arrives (e.g. a username), you don't yet know where it will be rendered later. The SAME value may appear in an HTML body on one page, inside a quoted attribute on another, in a URL, in a JSON/JS block, or in an email. Each needs a DIFFERENT encoding. - If you encode once at input, you can only pick ONE encoding -- which will be wrong (and unsafe, or broken) for the other contexts. Encoding at each OUTPUT site lets you apply the correct encoder per destination. REASON 2 -- DOUBLE-ENCODING / DATA CORRUPTION. - If you HTML-encode at input and store "<b>", then any output step that ALSO encodes produces "<b>" -- the user sees mangled text (double-encoding bug). - Stored-encoded data also corrupts NON-HTML uses: an email, a PDF, a CSV export, an API response, or a length/format validation now operate on "<b>" instead of the real "". The stored value is no longer the user's actual data. - Storing RAW and encoding late keeps the database holding the true value, and each consumer encodes appropriately (or not at all, for non-HTML uses). One source of truth; presentation handled at presentation time. THE BEST-PRACTICE RULE: - STORE THE RAW, ORIGINAL INPUT. ENCODE AT EACH OUTPUT SITE FOR THAT SITE'S CONTEXT. - Input VALIDATION still has value (reject obviously invalid data, enforce formats -- Chapter 7), but it is NOT the XSS defence and must not replace output encoding. Validation reduces bad data; encoding makes output safe.