Skip to content
mentoor

Topic 4 of 5 · 5 min read

Validating input and encoding output

Goal: Spot injection, path traversal or SSRF in generated handler code and choose the defence that fits each.

Treat every value that crosses your boundary as hostile text: validate its shape on the way in, keep it as data when you use it, and encode it on the way out. Most injection flaws come from one move: building a command or a query by gluing strings together.

Check yourself · 1 of 3

What is the best defence against SQL injection?

Choose one answer

Why it matters

A model has seen thousands of examples that concatenate strings into SQL or paths, because tutorials do. It reproduces the pattern when it is the shortest way to a working answer. The code passes tests with friendly input and fails when the input is not friendly.

The four defences

  1. Validate at the boundary. Use a schema library (Zod, Pydantic, JSON Schema) to check type, length, range and allowed values. Reject early. Prefer allowlists to blocklists.
  2. Parameterise. Pass values separately from the query: db.query("SELECT * FROM users WHERE email = $1", [email]). The same idea applies to shell commands: pass an argument array, not one string.
  3. Encode output for its context. HTML, URL, SQL and shell each need different escaping. Use the framework's templating, which escapes by default, and avoid innerHTML and dangerouslySetInnerHTML with user text.
  4. Constrain where the input points. For file paths, resolve the full path and check it stays inside the intended folder. For URLs the server fetches, check the host against an allowlist.

Three patterns to know

  • Injection: "SELECT ... WHERE id = " + id lets 1 OR 1=1 change the query.
  • Path traversal: fs.readFile("./uploads/" + name) lets ../../etc/passwd escape the folder.
  • Server-side request forgery (SSRF): fetch(req.body.url) lets a caller make your server call internal addresses such as a cloud metadata service.

Before and after

// Before
const file = await fs.readFile(path.join(UPLOADS, req.query.name));

// After
const full = path.resolve(UPLOADS, req.query.name);
if (!full.startsWith(path.resolve(UPLOADS) + path.sep)) return res.status(400).end();
const file = await fs.readFile(full);

What goes wrong

  • Escaping by hand instead of using parameters, then missing one case.
  • Validating only on the client. The caller can skip the browser.
  • Blocklisting. Filtering .. or localhost misses encoded and alternative forms; allowlist instead.

Examples

An SSRF in a preview feature

@app.post('/preview')
def preview():
    return requests.get(request.json['url']).text

A caller sends http://169.254.169.254/ and the server returns data from the cloud metadata service. Fix: parse the URL, allow only https and a short list of approved hosts, and set a timeout and size limit.

Key points

  • Validate type, length and allowed values at the boundary and reject bad input early.
  • Use parameterised queries and argument arrays, never string concatenation, for SQL and shell commands.
  • Encode output for its context and prefer templating that escapes by default.
  • For file paths, resolve the full path and confirm it stays inside the intended directory.
  • For server-side fetches of user-supplied URLs, allow only known hosts instead of trying to block bad ones.

Common mistakes

  • Building SQL or shell commands from strings because the output looks clear and works in tests.
  • Relying on client-side validation alone.
  • Using a blocklist of bad characters or hosts instead of an allowlist.
  • Using innerHTML with text that came from a user.

Check yourself · 2 of 3

A handler runs fs.readFile('./uploads/' + name) where name comes from the URL. What risk does this carry?

Choose one answer

Check yourself · 3 of 3

A feature fetches any URL the user types. Which defence fits best?

Choose one answer

Practice items, not counted towards your mastery.

Start here

More for this topic