Description
Putting request values directly into SQL passed to sequelize.query lets the caller change the search conditions or selected columns.
Potential impact
Depending on database privileges, altered queries may bypass access checks, expose, change or delete data, or disrupt service.
Remediation
- With
sequelize.query,replacementsescapes values and inserts them into the SQL text. Withbind, the database receives the values separately. Validate input format and length in either case. Avoid the MySQL-specificsqlstringpackage for PostgreSQL queries. - With
Model.findAllorfindOne, supply values throughwhere. Choose table names and the column names inattributesfrom a server-side allow-list.
Examples
Before
javascript
const express = require("express");
const { Sequelize } = require("sequelize");
const app = express();
const sequelize = new Sequelize("postgres://user:pass@localhost:5432/appdb");
// Before: concatenate user input directly into raw SQL.
app.get("/items", async (req, res) => {
const col = req.query.col; // Example: name
const term = req.query.term; // Example: a'
const sql = `SELECT ${col} FROM products WHERE name LIKE '%${term}%'`;
try {
const [rows] = await sequelize.query(sql);
res.json(rows);
} catch (e) {
res.status(500).send("error");
}
});
After
javascript
const express = require("express");
const { Sequelize, QueryTypes } = require("sequelize");
const app = express();
const sequelize = new Sequelize("postgres://user:pass@localhost:5432/appdb");
// After: use replacements for values and an allowlist for identifiers.
app.get("/items", async (req, res) => {
const allowedCols = new Set(["name", "price", "created_at"]);
const requested = String(req.query.col || "name");
if (!allowedCols.has(requested)) {
return res.status(400).send("invalid column");
}
const term = String(req.query.term || "");
// Pass values separately instead of concatenating them into SQL.
const sql = `SELECT ${requested} FROM products WHERE name ILIKE ?`;
try {
const rows = await sequelize.query(sql, {
replacements: [`%${term}%`],
type: QueryTypes.SELECT,
});
res.json(rows);
} catch (e) {
res.status(500).send("error");
}
});
// Alternative: use structured query options in the ORM API.
// Product.findAll({ attributes: [requested], where: { name: { [Op.iLike]: `%${term}%` } } });
The example permits three column names and passes the ILIKE search pattern as a replacements value for ?. This search ignores case, and % and _ in the pattern still act as wildcards.