--- name: code-sanitization description: Use when writing any code that handles external input (user input, API responses, file uploads, database queries, shell commands). Framework-agnostic injection-prevention baseline. --- # Code Sanitization Framework-agnostic baseline for handling untrusted input safely. Applies regardless of language — the specific function names differ, the principle doesn't. ## The core rule: sanitize on input, escape on output, separately These are two different concerns, both required: - **Sanitize/validate on input**: reject or normalize data that doesn't match the expected shape, as early as possible (at the point you first receive it). - **Escape on output**: transform data for the specific context it's being placed into (HTML, a SQL query, a shell command, a URL, JSON) — every different output context needs its OWN escaping, applied at the point of output, not once globally. A common real mistake: sanitizing once on input and assuming that's sufficient for every later output context. It isn't — data that's safe to store isn't automatically safe to interpolate into HTML, and separately isn't automatically safe to interpolate into a shell command. ## SQL injection **Parameterized queries / prepared statements, always, no exceptions.** Never build a SQL string via concatenation or interpolation with a variable in it, even if you're "sure" the variable is safe (a value that was safe when the code was written is not guaranteed to stay safe as the codebase evolves and new call sites appear). ## Cross-site scripting (XSS) Escape for the exact context: - HTML body text: HTML-entity-escape (`<`, `>`, `&`, `"`, `'`). - HTML attribute: attribute-escape (stricter than body-text escaping). - JavaScript string embedded in a `