Backend Validation Layers
Use this skill when building APIs, server actions, or processing form submissions to ensure robust data validation and security at the boundary layer.
Backend Validation Layers
Purpose
⚠IMPORTANT⚠This skill enforces boundary validation heuristics via mathematical schema definitions. It strictly prohibits propagating external input payloads into deeper execution layers without formal invariant checks.
When to Use This Skill
⚠NOTE⚠Use this skill whenever you are writing code that receives input from an external source (users, third-party APIs, webhooks).
What This Skill Prevents
This skill prevents:
- Boundary Trust Violation: Relying solely on client-side state AST constraints.
- Type Mutation Failure: Propagating unchecked schemas that trigger runtime execution halts on prototype methods (e.g.,
.toLowerCase()). - Mass Assignment Vulnerability: Direct insertion of unstripped
req.bodypayloads into ORM driver instances. - Obfuscated Exception States: Emitting generic HTTP 500 error strings for known $O(1)$ validation failures.
Core Principle
All external ingress payloads MUST be evaluated against deterministic schema ASTs. Invalid execution paths MUST return a structured HTTP 400 response and halt the request cycle before business logic is engaged.
Research-Backed Rules
- Schema Validation Vector: Formally declare expected data shapes using a strict schema engine (Zod, Pydantic). Untyped execution is prohibited.
- Early Return Heuristic: Evaluate schema as the absolute root step in the route handler logic. Failure MUST trigger an immediate
400 Bad Requesttermination sequence, skipping all underlying business logic execution. - Strict Parsing / Stripping Constraint: Enforce
.strip()(default) or.strict()constraints on schema resolution to purge unexpected payload keys. This is a mandatory invariant to prevent OWASP Mass Assignment vulnerabilities. - Error Obfuscation: Surface deterministic validation errors to the client parser. Suppress and sandbox internal database error strings.
Stack-Aware Guidance
Node / Express Guidance
Inject Zod schema constraints into middleware boundaries.
const schema = z.object({ email: z.string().email() });
// Inside middleware or controller
const parsed = schema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ errors: parsed.error.format() });
Next.js Server Actions Guidance
Apply Zod safeParse evaluation inside the use server abstraction. Intercept throws; return a structured boolean response { success: false, details: ... } to enable client-side error rendering.
'use server'
export async function createUser(data: FormData) {
const parsed = schema.safeParse(Object.fromEntries(data));
if (!parsed.success) return { error: "Validation failed", details: parsed.error.flatten() };
// proceed execution
}
FastAPI / Python Guidance
FastAPI executes Pydantic invariants natively. Define strict Pydantic topological models for incoming requests. FastAPI will automatically compile 422 Unprocessable Entity termination responses for invalid payloads.
Implementation Guidance
- Schema Definition: Instantiate validation graph for request payload, query scalars, and URL vectors.
- Schema Application: Execute
parseorsafeParseon the incoming vector. - Failure State Handling: Synthesize structured error response nodes (
400or422) on parse rejection. - Data Interpolation: Ensure downstream functions ONLY ingest the sanitized, parsed state object. Raw
req.bodyreferences are strictly prohibited beyond the parsing boundary.
Mathematical / Measurable Rules
- String Upper/Lower Bounds: Assert
.min()and.max()limits for all string arrays to prevent buffer exhaustion. - Numeric Bounds Constraint: Assert
.min()and.max()limits on all integer matrices to prevent $32$/$64$-bit overflow exploits in underlying database engines.
Quality Gates
Security Gate
- Confirmed strict server-side schema validation (client-side checks are considered null).
- Validated mass-assignment protections (unknown keys stripped from payload).
- Asserted maximum string boundary arrays.
Maintainability Gate
- Validation schema decoupled from route execution logic.
- Error messages synthesized in a consistent structured format.
Anti-Patterns to Avoid
- Manual Type Checking: Generating $O(N)$ string matching constraints (
if (typeof req.body.age !== 'number')) instead of utilizing a schema engine. - Direct DB Insertion: Executing
await db.user.create({ data: req.body })– A critical security vulnerability.
Agent Behavior Instructions
- Instantiate validation schema prior to database logic compilation.
- Ensure validation engine (e.g., Zod) is mapped to project dependencies.
- Maintain execution lock on business logic until
safeParsereturns a truthy validation node. - Synthesize error formatting for predictable client-side mapping.
Final Review Checklist
- Unvalidated backend inputs nullified.
-
req.bodymass assignment vector blocked. - Structured errors mapped.
- Fully agent-optimized deterministic rules.