How-To Guide

How to Validate Input at the Trust Boundary

Validate all input at the system boundary: parse before you trust, reject invalid shapes early, and keep validation out of business logic.

On this page

  1. Introduction
  2. Name the boundary explicitly
  3. Parse into a typed value once
  4. Reject rather than coerce
  5. Carry the guarantee inward
  6. Test with hostile inputs
  7. Common pitfalls
  8. Conclusion

Introduction

Every system has a boundary where data it did not create enters: an HTTP body, a query parameter, a message from a queue, a file, a CLI argument. Data from beyond that boundary is untrusted until it has been checked. Systems that validate inside business logic spread the check across many places and inevitably miss one. Validating at the boundary, once, converts raw input into a trusted value that everything inward can rely on.

This tutorial covers identifying the boundary, parsing untrusted input into a typed value, rejecting invalid input rather than coercing it, and testing with hostile inputs. The examples use TypeScript with a schema library, but the discipline applies to any language: parse at the edge, trust inward.

Name the boundary explicitly

The first step is to be explicit about where the boundary is. In a web service, it is the handler that receives the request; everything the request carries — path, query, headers, body, cookies — is untrusted. In a worker, it is the message that arrives from the queue. In a CLI, it is argv and the environment. Each of these points is where validation belongs, and nowhere else should be inventing raw values.

Make the boundary a narrow choke point. If every handler parses its own input, some will forget a field. Where the framework allows, centralize the parse in a middleware or a decorator so a handler receives an already-typed value. The further the raw input travels before it is validated, the more code exists that could use it unsafely.

Parse into a typed value once

Parsing is validation plus conversion: it checks the shape and produces a value of a known type. A schema describes the expected fields, their types, and their constraints, and the parser either returns a strongly-typed object or an error. From that point the code holds a trusted value, and the type system carries the guarantee into the rest of the program.

Use a schema that rejects unknown fields by default, so a caller cannot smuggle an extra property into an object that downstream code spreads into another, such as a database insert. This ‘strict’ parsing prevents mass assignment, where an unexpected field like role or isAdmin silently takes effect. Define the schema next to the endpoint so the contract is visible, and derive the TypeScript type from the schema so the type and the runtime check cannot drift.

import { z } from 'zod';

const CreateOrder = z.object({
  customerId: z.number().int().positive(),
  items: z.array(z.object({
    sku: z.string().min(1),
    qty: z.number().int().positive().max(1000),
  })).min(1),
  note: z.string().max(500).optional(),
}).strict(); // reject unknown fields: blocks mass assignment

type CreateOrder = z.infer<typeof CreateOrder>;

function parseOrder(raw: unknown): CreateOrder {
  return CreateOrder.parse(raw); // throws a typed error on invalid input
}

Reject rather than coerce

When input is invalid, reject it with a clear error instead of coercing it into something plausible. Coercion turns a caller’s mistake into data: a string ‘1’ parsed into the number 1 for a field that should never accept a string, or a missing field defaulted to an empty value, hides the defect until it surfaces elsewhere. A clear rejection at the boundary tells the caller exactly what was wrong.

Return 400 or 422 with a machine-readable description of the failed fields, and never echo the raw input back in the error, which can reflect content into responses. Avoid leaking internal schema details that help an attacker, but do give a developer enough to fix the request. Keep the error shape consistent so clients can parse it.

function toProblem(err) {
  const issues = err.issues.map((i) => ({ path: i.path.join('.'), message: i.message }));
  return { status: 422, body: { type: 'validation', issues } };
}
// handler: try parseOrder(req.body) catch (e) => send toProblem(e)

Carry the guarantee inward

The value of boundary validation is that downstream code does not re-check the same thing. Use types that make the invariant explicit: a branded type for a validated email, so a function that takes an Email cannot be called with an arbitrary string. Then the compiler enforces that only a validated value reaches the sensitive function, and re-validating inside every layer becomes unnecessary.

Distinguish the validated type from the raw one at the type level so a mistake is a compile error. A function that takes an UntrustedInput and returns a ValidatedInput documents the boundary and prevents passing raw data where validated data is expected. This shifts the guarantee from runtime checks scattered in code to the type system, which is harder to forget.

declare const brand: unique symbol;
type Email = string & { readonly [brand]: 'Email' };

function asEmail(value: string): Email {
  if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(value)) throw new Error('invalid email');
  return value as Email;
}

function sendReceipt(to: Email) { /* only validated emails reach here */ }

Test with hostile inputs

Treat the boundary as the target of adversarial tests. Send a body with a missing required field, a wrong type, an extra unknown field, an oversized string, and deeply nested input, and assert each is rejected at the boundary with the right status rather than failing deeper or being accepted. Assert the error does not echo the raw input or reveal internal field names that are not part of the contract.

# wrong type -> 422 at the boundary
curl -s -o /dev/null -w '%{http_code}\n' -X POST -H 'content-type: application/json' -d '{"customerId":"x","items":[]}' http://localhost:3000/orders
# unknown field -> rejected by .strict()
curl -s -o /dev/null -w '%{http_code}\n' -X POST -H 'content-type: application/json' -d '{"customerId":1,"items":[{"sku":"a","qty":1}],"isAdmin":true}' http://localhost:3000/orders

Common pitfalls

Validating inside business logic where a path can miss the check, coercing invalid input instead of rejecting it, allowing unknown fields so mass assignment becomes possible, echoing raw input in errors, and re-validating the same value at every internal layer are the recurring mistakes. A single boundary parse, rejection, strict schemas, safe errors, and branded types address them.

Conclusion

Validate input once, at the trust boundary. Name the boundary, parse raw input into a typed value with a strict schema, reject invalid input instead of coercing it, carry the guarantee inward with types, and test with hostile inputs. Self-check by sending malformed and unknown-field payloads and asserting each is rejected at the boundary. When the boundary is the only place raw input exists, the rest of the system is free of untrusted data.

Sources: OWASP: Input validation cheat sheet, OWASP: Validate input, avoid injection, MDN: MIME types and data validation.

FAQ

Validate once or at every layer?
Validate the shape once at the boundary and convert it to a trusted type. Re-validating the same thing at every internal layer adds noise; instead, use types that make the validated invariant explicit so downstream code does not need to re-check.
Should I coerce or reject?
Reject. Silent coercion hides a caller's mistake and can turn an attack into data. If '1' is not a number for a numeric field, return an error rather than parsing it, unless the field is genuinely stringly-typed by contract.

Related Examples