Skip to content

Security ​

postgrelize builds SQL so that data from your users cannot change the meaning of a statement. This page lists every input that reaches SQL, how it is protected, and the few APIs that take raw SQL by design.

To report a vulnerability, see SECURITY.md.

How inputs are protected ​

MechanismMeaning
BoundSent to PostgreSQL as a $n parameter, never as SQL text
IdentifierQuoted as an identifier (" doubled): the value can only name a table, column, alias, channel, …
AllowlistChecked against a fixed set or a strict pattern; anything else throws before SQL is built
LiteralEscaped string literal ('', E'…' with doubled backslashes; NUL bytes rejected). In DDL, COPY TO and JSON_TABLE paths, where PostgreSQL does not accept parameters, and in replacements of sequelize.query and of the finders (ADR-036, ADR-037)
Raw by designSQL you write yourself. Not escaped. Never build it from user input
InputProtection
where values, Op.* values, in lists, JSON values, limit / offset, increment amounts, values of create / update / upsert / bulkCreate / insert / mergeBound
Op.similarTo / Op.jsonPathExists / trigram Op.* values, text of toTsQuery / plainToTsQuery / phraseToTsQuery / websearchToTsQuery / toTsVector, tsHeadline options string, jsonbPath path (as jsonpath) and vars (one jsonb parameter), trigramSimilarity / trigramDistance argumentsBound
sequelize.query bind ($1, $name)Bound
replacements (:name, ?) of sequelize.query and of the finders (findAll, findOne, findByPk, count, findAndCountAll, Model.reload, ...) for placeholders inside literal(): strings, numbers, booleans, dates, JSON, arrays for IN (:ids); written into the SQL text like v6, so one call can run several statementsLiteral
String arguments of fn() (fn('COUNT', '*'), fn('concat_ws', ' ', col('a'))) and the value of Op.is (null, booleans, literal(), or any value, as in v6; ADR-038)Literal
JSON paths in where keys ('meta.a.b', nested objects)Bound
Attribute and column names, where keys, order / group targets, aliases, as, table and schema names, CTE names, index and constraint names, LISTEN / NOTIFY channels, lock.ofIdentifier
HSTORE keys and values (serialized to one bound hstore text parameter), values of LTREE, MONEY, XML, BIT, TSQUERY, MACADDR8, TIMESTAMP columns, values of POINT, LINE, LSEG, BOX, PATH, POLYGON, CIRCLE columns (coordinates validated as finite numbers, then one bound text parameter), values of MULTIRANGE columns (bounds formatted into one bound multirange text parameter), values of GEOMETRY / GEOGRAPHY columns (GeoJSON type allowlisted, coordinates finite numbers, SRID digits only, sent as one bound hex EWKB parameter), values of COMPOSITE columns (fields quoted into one bound record text parameter, cast to the quoted type name in where)Bound
Values and conditions of insertStatement / updateStatement / deleteStatementBound
VALUES cells, function arguments, TABLESAMPLE percent and seed, JSON_TABLE documentBound
CTE search / cycle columns and added column names, from aliases, source column aliases, set-returning function names, JSON_TABLE column namesIdentifier
TABLESAMPLE method, CTE search mode, JSON_TABLE column typesAllowlist
JSON_TABLE jsonpath strings (PostgreSQL accepts only constants there)Literal
Operands of set operations (union(), intersect(), except()), source subqueries, the withTies fetch countBound
NOTIFY payloads, advisory-lock keys, transaction settings, statementTimeout (validated integer), bulkCreate unnest column arraysBound
order directions, Op operators, where(col, comparator, value) comparators, fn() names, Model.aggregate function names, cast() and 'attr::type' types, lock strengths, isolation levels, transaction deferrable (booleans only), onDelete / onUpdate, index using / operator classes, Deferrable, DataTypes parameters (STRING(n), DECIMAL(p, s), BIT(n), VARBIT(n), TIMESTAMP(p), …), timezone, COPY TO format optionsAllowlist
Text search configuration names (plain or schema-qualified identifier, bound as regconfig), setWeight labels (A–D), jsonbPath kinds, tsRank weights (four finite numbers) and normalization (integer 0–63)Allowlist
DDL defaults (an HSTORE or geometric default object is serialized, then escaped), table and column comments, ENUM values, partial-index and CHECK conditions, COPY TO filtersLiteral
COMPOSITE type and field names (quoted by createSql() and in column DDL; field types come from data types), extension, sequence names and schemas, ownedBy table and columnIdentifier
Extension versionLiteral
Sequence dataTypeAllowlist
Sequence start, increment, bounds, cache, restartWith, setval valuesAllowlist (whole numbers only)
nextval / setval sequence namesBound (as regclass text)
Policy names, policy rolesIdentifier
Policy command and kindAllowlist
Policy using / withCheck where-object valuesLiteral
View and materialized-view names, view column listsIdentifier
View checkOption, materialized-view using access methodAllowlist
Function names (strings), parameter and variable names, languagesAllowlist (identifier words)
Function names given as { name, schema }, trigger names, trigger tablesIdentifier
Function parameter and return typesAllowlist (strict type-name pattern)
Function parameter directions, function characteristic keywords, trigger timing, events and clauses (FOR EACH ROW, DEFERRABLE, REFERENCING)Allowlist
Trigger function arguments, variable defaultsLiteral
Table, schema and constraint names given to showIndex, showConstraint, getForeignKeysForTables and assertTableHasColumnBound
Database names given to createDatabase / dropDatabase, and everything given to quoteIdentifier / quoteIdentifiersIdentifier
Constraint names given to Deferrable.SET_DEFERRED / SET_IMMEDIATE (SET CONSTRAINTS); the deferrable option only accepts values made by DeferrableIdentifier
createDatabase options encoding, collate, ctype and templateLiteral
COPY FROM dataEscaped in the COPY text format
literal(), the SQL text of sequelize.query, string where / orderRaw by design
Index names, index columns, collate collationsIdentifier
Index and exclude using method, field operator classAllowlist
Constraint names, validateConstraint names, exclude element columnsIdentifier
exclude element with operatorsAllowlist (operator characters only)
Partition names, partition key columns and collationsIdentifier
Partition strategyAllowlist
Partition bound values (in, from, to), modulus, remainderLiteral (modulus and remainder: validated integer)
Index field nulls and orderAllowlist
Index, exclude and partition key expression, function body, trigger WHEN (...) clause, view and materialized-view query, policy using / withCheck stringsRaw by design (trusted SQL, not escaped)

The statementCache option sends no user data to PostgreSQL as a name: a prepared statement is named pgz_ plus a hash of the SQL text, and its max must be a positive integer. Values stay bound parameters.

Safe patterns ​

User values in model queries are always bound:

ts
// Values from users are always sent as bound parameters.
const byTitle = await Post.findAll({ where: { title: input['title'] } });
const searched = await Post.count({ where: { title: { [Op.iLike]: `%${input['search']}%` } } });

In raw SQL, pass user values through replacements (escaped into the SQL text, as in Sequelize v6) or bind (bound parameters):

ts
// Raw SQL: put user values in replacements or bind, never in the SQL text.
const rows = (await sequelize.query('SELECT title FROM "Posts" WHERE title = :title', {
  type: QueryTypes.SELECT,
  replacements: { title: input['title'] },
})) as { title: string }[];

Column names chosen by users (sorting, filtering by a field) are quoted, so they cannot inject SQL. But they can still name any column of the table. Map them through your own allowlist:

ts
// Column names from users: map them through your own allowlist.
const sortable = { rank: 'rank', title: 'title' } as const;
const column = sortable[input['sort'] as keyof typeof sortable] ?? 'rank';
const sorted = await Post.findAll({ order: [[column, 'DESC']] });

literal() inserts its text unchanged. Use it only for constant SQL written by you:

ts
// literal() is inserted as is: only constant SQL written by you.
const nullsLast = await Post.findAll({ order: [literal('"rank" DESC NULLS LAST')] });

Not injection, but worth knowing ​

  • Filtering on any column. Passing a request object straight in as where lets callers filter on any column, including ones you never show. Build where from the fields you allow.
  • Mass assignment. Model.update(values) and create(values) write every attribute present in values. Pass fields or pick the allowed attributes first.
  • LIKE patterns. Op.like, Op.startsWith, Op.substring and Op.endsWith keep LIKE semantics, as in Sequelize v6: %, _ and \ in the value act as wildcards. Escape them when users should match literally.

How this is verified ​

  • Every input above has tests on a real PostgreSQL in tests/integration/security/. The tests use a payload corpus: quote breakouts, backslash and E'' tricks, dollar quoting, U& escapes, comments, stacked statements, very long strings. They also run property-based tests with random strings, checking that values read back byte-for-byte and identifiers name exactly what was given. A canary table proves that no injected statement ran.
  • CodeQL (security-extended queries) scans every pull request.
  • Every input that reaches SQL must have a protection and tests before it is merged (ADR-020).

Released under the MIT License.