Resource exhaustion with Ajv allErrors:true

Resource exhaustion from collecting all Ajv validation errors

Description

With allErrors: true, Ajv keeps collecting errors after a validation failure, increasing CPU and memory use per request.

Potential impact

Large error lists can slow responses or exhaust memory. Logging every error can also fill monitoring logs.

Remediation

Keep allErrors at its default of false in production. Use trusted schemas and avoid unnecessary combinations of oneOf or anyOf. Limit body size, connection time, array items (maxItems) and object properties (maxProperties). Use rate limits and circuit breakers to manage bursts.

Examples

Before

javascript
import express from "express";
import Ajv from "ajv";

const app = express();
app.use(express.json({ limit: "1mb" }));

// BAD: use allErrors:true in production (collect all errors)
const ajv = new Ajv({ allErrors: true });

const userSchema = {
  type: "object",
  additionalProperties: false,
  properties: {
    name: { type: "string" },
    tags: { type: "array", items: { type: "string" } },
  },
  required: ["name", "tags"],
};

const validateUser = ajv.compile(userSchema);

app.post("/users", (req, res) => {
  const valid = validateUser(req.body);
  if (!valid) {
    // Generating and returning many errors consumes CPU and memory
    return res.status(400).json({ errors: validateUser.errors });
  }
  res.send("ok");
});

app.listen(3000);

After

javascript
import express from "express";
import Ajv from "ajv";

const app = express();
// Set a request size limit and timeout
app.use(express.json({ limit: "512kb" }));
app.use((req, res, next) => {
  req.setTimeout(5000);
  next();
});

// GOOD: default fail-fast behavior; enable allErrors only for development
const enableAllErrors = process.env.NODE_ENV === "development" && process.env.DEBUG_VALIDATE === "1";
const ajv = new Ajv({ allErrors: enableAllErrors });

const userSchema = {
  type: "object",
  additionalProperties: false,
  properties: {
    name: { type: "string" },
    tags: {
      type: "array",
      maxItems: 50,
      items: { type: "string", maxLength: 64 },
    },
  },
  required: ["name", "tags"],
};

const validateUser = ajv.compile(userSchema);

app.post("/users", (req, res) => {
  const valid = validateUser(req.body);
  if (!valid) {
    // Return a summary instead of exposing many error objects
    return res.status(400).json({ message: "Invalid payload" });
  }
  res.send("ok");
});

app.listen(3000);

The revised route collects all errors only in development with DEBUG_VALIDATE=1. It caps the JSON body at 512kb, accepts up to 50 tags of at most 64 characters each, and returns a short error. The socket inactivity timeout req.setTimeout(5000) runs after the body parser. It cannot limit body receipt or parsing, or interrupt synchronous validation.

References