Description
Using the length of a request-supplied object as the loop bound can make a handler iterate far beyond the number of items it needs to process.
Potential impact
A long loop blocks other requests on the event loop and can cause timeouts. Growing a collection inside the loop can also exhaust memory.
Remediation
Use Array.isArray and enforce MAX_ITEMS before copying or iterating. If the API also accepts array-like objects, require a finite, nonnegative integer length and apply the cap before conversion. Calling slice after Array.from still converts the entire input. Limit the request body size as well.
Examples
Before
const express = require("express");
const app = express();
app.use(express.json());
// Use an untrusted length directly as the loop bound
app.post("/sum", (req, res) => {
const list = req.body.items; // Fully controlled by the requester
let total = 0;
// BAD: { items: { length: 1e12 } } causes excessive iteration
for (let i = 0; i < list.length; i++) {
total += Number(list[i] || 0);
}
res.json({ total });
});
app.listen(3000);
After
const express = require("express");
const app = express();
app.use(express.json());
const MAX_ITEMS = 10000; // Choose a limit appropriate to the operation
// Validate the type and length before iterating over a bounded array
app.post("/sum", (req, res) => {
const list = req.body.items;
// 1) Require an actual array
if (!Array.isArray(list)) {
return res.status(400).json({ error: "items must be an array" });
}
// 2) Enforce the length limit before iteration or copying
if (list.length > MAX_ITEMS) {
return res.status(400).json({ error: "too many items" });
}
let total = 0;
for (const v of list) {
total += Number(v || 0);
}
res.json({ total });
});
app.listen(3000);
Given a parsed JSON object, the revised route returns 400 before summing if its items field is not an array or contains more than 10,000 items. Validate each item’s type and range before adding it. Number(v || 0) only converts the value.