ORM wave: 24 defects patched across 10 ORMs (157 sites, 62 ecosystems)

Hibernate (5 HIGH): addColumn/addReferencedColumn/addIndex ArrayList→LinkedHashSet (19x)
  FK second-pass LinkedHashSet, orderHierarchy LinkedHashSet
MyBatis (1 MEDIUM): sortConstructorMappings indexOf→HashMap (12x)
EF Core (2 HIGH + 1 MEDIUM): FindGenerationProperty HashSet (250x),
  AddPrincipals HashSet (250x), FK discovery HashSet (6x)
Diesel (3 MEDIUM): SQLite/MySQL row position()→BTreeMap (51x)
SQLAlchemy (2 HIGH): _values_bindparam Set (500x), evaluated_keys Set (500x)
Peewee (1 MEDIUM): _SortedFieldList.index() bisect (42x)
Sequelize (2 HIGH): bulkInsert Set (50x), expandIncludeAll Set (250x)
TypeORM (3 HIGH): OrmUtils.uniq Map (500x), diffColumns Set (125x),
  updatedColumns Set (100x)
Doctrine ORM (1 HIGH + 2 MEDIUM): hydrator discriminator (26x),
  addSubClass (250x), SqlWalker partial (130x)
GORM (1 MEDIUM): sortCallbacks getRIndex→map (194x)
SQLite: SqliteTest unit proof 4/4 PASS (101x)

Unit tests: all PASS — Hibernate/MyBatis/EfCore/Diesel/SQLAlchemy/Peewee/
  Sequelize/TypeORM/Doctrine/GORM
Whitepaper: 157 sites, 62 ecosystems; PDF 752K
This commit is contained in:
russell@unturf.com 2026-03-27 13:34:26 -04:00
parent db2986ae44
commit d4ed2dff91
49 changed files with 4025 additions and 7 deletions

View file

@ -0,0 +1,20 @@
diff --git a/packages/core/src/abstract-dialect/query-generator.js b/packages/core/src/abstract-dialect/query-generator.js
--- a/packages/core/src/abstract-dialect/query-generator.js
+++ b/packages/core/src/abstract-dialect/query-generator.js
@@ -346,11 +346,13 @@ class AbstractQueryGenerator {
const tuples = [];
const serials = {};
- const allAttributes = [];
+ // CWE-407 fix: use a Set for O(1) membership test inside the double loop
+ // (for fieldValueHash -> forOwn key) to avoid O(rows * cols^2) complexity.
+ const allAttributesSet = new Set();
+ const allAttributes = [];
let onDuplicateKeyUpdate = '';
for (const fieldValueHash of fieldValueHashes) {
forOwn(fieldValueHash, (value, key) => {
- if (!allAttributes.includes(key)) {
+ if (!allAttributesSet.has(key)) {
+ allAttributesSet.add(key);
allAttributes.push(key);
}

View file

@ -0,0 +1,19 @@
diff --git a/packages/core/src/model.js b/packages/core/src/model.js
--- a/packages/core/src/model.js
+++ b/packages/core/src/model.js
@@ -515,9 +515,11 @@ class Model {
if (types !== true) {
// replace type placeholder e.g. 'One' with its constituent types
- // CWE-407: all.includes(type_) is O(|all|) inside a for loop = O(n^2)
all.splice(i, 1);
i--;
+ // CWE-407 fix: convert 'all' to a Set for O(1) membership check
+ const allSet = new Set(all);
for (const type_ of types) {
- if (!all.includes(type_)) {
+ if (!allSet.has(type_)) {
all.unshift(type_);
+ allSet.add(type_);
i++;
}
}

View file

@ -0,0 +1,120 @@
package unit;
import java.util.*;
/**
* SequelizeTest — sequelize-0001..0002
*
* Proves CWE-407 in Sequelize ORM:
* sequelize-0001: query-generator.js bulkInsertQuery — allAttributes.includes() O(C) in double loop
* O(rows × cols²) for bulk INSERT with many rows and columns
* sequelize-0002: model.js _expandIncludeAll — all.includes(type_) O(T) inside for-of loop
* O(T²) when expanding association types
*
* Run: javac -d . SequelizeTest.java && java -ea unit.SequelizeTest
*/
public class SequelizeTest {
// ── sequelize-0001: bulkInsertQuery allAttributes dedup ──────────────────
/**
* SLOW: allAttributes.includes(key) O(C) inside double loop (rows × cols).
* allAttributes grows incrementally; each new key requires O(C) scan.
* O(rows × cols × C) total where C = unique cols seen so far.
*/
static long bulkInsertSlow(int numRows, int numCols) {
List<String> allAttributes = new ArrayList<>();
long ops = 0;
for (int r = 0; r < numRows; r++) {
for (int c = 0; c < numCols; c++) {
String key = "col_" + c;
// allAttributes.includes(key)
boolean found = false;
for (String a : allAttributes) { ops++; if (a.equals(key)) { found = true; break; } }
if (!found) allAttributes.add(key);
}
}
return ops;
}
/** FAST: allAttributesSet.has(key) O(1) — shadow Set tracks already-seen cols. */
static long bulkInsertFast(int numRows, int numCols) {
Set<String> allAttributesSet = new HashSet<>();
List<String> allAttributes = new ArrayList<>();
long ops = 0;
for (int r = 0; r < numRows; r++) {
for (int c = 0; c < numCols; c++) {
String key = "col_" + c;
ops++; // O(1) set.has
if (allAttributesSet.add(key)) allAttributes.add(key);
}
}
return ops;
}
// ── sequelize-0002: _expandIncludeAll type dedup ─────────────────────────
/**
* SLOW: all.includes(type_) O(T) per expansion step.
* all grows as types are added; membership test is O(T) per type.
* O(T²) total for T association types.
*/
static long expandIncludeAllSlow(int numTypes) {
List<String> all = new ArrayList<>();
long ops = 0;
for (int i = 0; i < numTypes; i++) {
String type = "type_" + i;
// all.includes(type_)
boolean found = false;
for (String a : all) { ops++; if (a.equals(type)) { found = true; break; } }
if (!found) { all.add(0, type); } // unshift — O(T)
}
return ops;
}
/** FAST: allSet.has(type_) O(1) with shadow Set; O(T) total. */
static long expandIncludeAllFast(int numTypes) {
Set<String> allSet = new HashSet<>();
List<String> all = new ArrayList<>();
long ops = 0;
for (int i = 0; i < numTypes; i++) {
String type = "type_" + i;
ops++; // O(1)
if (allSet.add(type)) all.add(0, type);
}
return ops;
}
static void bench(String label, Runnable slow, Runnable fast, long sOps, long fOps) {
slow.run(); fast.run();
long t0 = System.nanoTime(); slow.run(); long sMs = (System.nanoTime()-t0)/1_000_000;
long t1 = System.nanoTime(); fast.run(); long fMs = (System.nanoTime()-t1)/1_000_000;
double r = fOps > 0 ? (double)sOps/fOps : 0;
System.out.printf(" %-52s slow:%4dms (%,d ops) fast:%4dms (%,d ops) speedup:%.0fx%n",
label, sMs, sOps, fMs, fOps, r);
}
public static void main(String[] args) {
System.out.println("=== UNIT sequelize-0001..0002: Sequelize CWE-407 ===");
System.out.println();
final int ROWS = 500, COLS = 100; // sequelize-0001
final int TYPES = 500; // sequelize-0002
long s0 = bulkInsertSlow(ROWS, COLS), f0 = bulkInsertFast(ROWS, COLS);
bench("sequelize-0001 bulkInsert allAttributes.includes()",
() -> bulkInsertSlow(ROWS, COLS), () -> bulkInsertFast(ROWS, COLS), s0, f0);
long s1 = expandIncludeAllSlow(TYPES), f1 = expandIncludeAllFast(TYPES);
bench("sequelize-0002 expandIncludeAll all.includes(type_)",
() -> expandIncludeAllSlow(TYPES), () -> expandIncludeAllFast(TYPES), s1, f1);
System.out.println();
int pass = 0;
assert s0 > f0 * 5 : "sequelize-0001 expected >5x"; pass++;
assert s1 > f1 * 5 : "sequelize-0002 expected >5x"; pass++;
System.out.printf("%d/2 PASS — sequelize-0001..0002: CWE-407 in Sequelize query builder/model%n", pass);
System.out.printf("Hotpaths: Model.bulkCreate() with many rows, Model.findAll() with include: 'all'%n");
}
}

View file

@ -0,0 +1,167 @@
/**
* CWE-407 unit tests for Sequelize.
*
* sequelize-0001: bulkInsertQuery allAttributes list → Set
* File: packages/core/src/abstract-dialect/query-generator.js line 351
* Pattern: `if (!allAttributes.includes(key)) allAttributes.push(key)`
* inside `for (fieldValueHash of fieldValueHashes) { forOwn(...) }` — the
* outer loop iterates rows, the inner iterates columns, and includes() scans
* allAttributes (which grows). O(rows * cols^2) total.
*
* sequelize-0002: _expandIncludeAllElement all.includes() inside nested for loop
* File: packages/core/src/model.js line 519
* Pattern: inner `for (type_ of types) { if (!all.includes(type_)) }`
* where `all` is the outer loop's array and grows as types are spliced in.
* O(|types| * |all|^2) worst case during include-type expansion.
*/
const { performance } = require('perf_hooks');
// ---------------------------------------------------------------------------
// sequelize-0001: bulkInsertQuery allAttributes dedup cost
// ---------------------------------------------------------------------------
function bulkInsertDedupDefective(nRows, nCols) {
// Simulate: for each row, for each key, check allAttributes.includes(key)
const allAttributes = [];
for (let r = 0; r < nRows; r++) {
for (let c = 0; c < nCols; c++) {
const key = `col_${c}`;
if (!allAttributes.includes(key)) {
allAttributes.push(key);
}
}
}
return allAttributes.length;
}
function bulkInsertDedupFixed(nRows, nCols) {
// Fixed: Set for O(1) membership
const allAttributesSet = new Set();
const allAttributes = [];
for (let r = 0; r < nRows; r++) {
for (let c = 0; c < nCols; c++) {
const key = `col_${c}`;
if (!allAttributesSet.has(key)) {
allAttributesSet.add(key);
allAttributes.push(key);
}
}
}
return allAttributes.length;
}
function testBulkInsertListSlowerThanSet() {
const nRows = 200;
const nCols = 300; // 200*300 = 60K inner iterations, includes() scans up to 300 each time
let t0 = performance.now();
for (let i = 0; i < 10; i++) bulkInsertDedupDefective(nRows, nCols);
const listTime = performance.now() - t0;
t0 = performance.now();
for (let i = 0; i < 10; i++) bulkInsertDedupFixed(nRows, nCols);
const setTime = performance.now() - t0;
const ratio = listTime / setTime;
if (ratio < 5) {
throw new Error(
`Expected defective (list) to be >=5x slower than fixed (set) at rows=${nRows} cols=${nCols}, ` +
`got ratio=${ratio.toFixed(1)} (list=${listTime.toFixed(1)}ms, set=${setTime.toFixed(1)}ms)`
);
}
console.log(`sequelize-0001 timing PASS ratio=${ratio.toFixed(1)}x (list=${listTime.toFixed(1)}ms set=${setTime.toFixed(1)}ms)`);
}
function testBulkInsertSameResult() {
for (const [nRows, nCols] of [[1, 1], [5, 10], [100, 50]]) {
const a = bulkInsertDedupDefective(nRows, nCols);
const b = bulkInsertDedupFixed(nRows, nCols);
if (a !== b) {
throw new Error(`Results differ at rows=${nRows} cols=${nCols}: defective=${a} fixed=${b}`);
}
}
console.log('sequelize-0001 correctness PASS');
}
// ---------------------------------------------------------------------------
// sequelize-0002: _expandIncludeAllElement all.includes() dedup
// ---------------------------------------------------------------------------
function expandIncludeAllDefective(nTypes) {
// all starts as ['One', 'Has', 'Many', ...] — simulate the expansion loop
// that splices type placeholders and does all.includes(type_) to dedup
let all = Array.from({ length: nTypes }, (_, i) => `TypeAlias_${i}`);
// Inner expansion: for each item, add expanded sub-types checking includes
const expanded = [];
for (let i = 0; i < all.length; i++) {
const subTypes = [`ConcreteA_${i}`, `ConcreteB_${i}`];
for (const type_ of subTypes) {
if (!all.includes(type_)) { // O(|all|) each time
all.unshift(type_);
i++;
expanded.push(type_);
}
}
}
return expanded.length;
}
function expandIncludeAllFixed(nTypes) {
let all = Array.from({ length: nTypes }, (_, i) => `TypeAlias_${i}`);
const allSet = new Set(all);
const expanded = [];
for (let i = 0; i < all.length; i++) {
const subTypes = [`ConcreteA_${i}`, `ConcreteB_${i}`];
for (const type_ of subTypes) {
if (!allSet.has(type_)) {
all.unshift(type_);
allSet.add(type_);
i++;
expanded.push(type_);
}
}
}
return expanded.length;
}
function testExpandIncludeAllListSlowerThanSet() {
const nTypes = 400;
let t0 = performance.now();
for (let i = 0; i < 20; i++) expandIncludeAllDefective(nTypes);
const listTime = performance.now() - t0;
t0 = performance.now();
for (let i = 0; i < 20; i++) expandIncludeAllFixed(nTypes);
const setTime = performance.now() - t0;
const ratio = listTime / setTime;
if (ratio < 3) {
throw new Error(
`Expected defective to be >=3x slower than fixed at nTypes=${nTypes}, ` +
`got ratio=${ratio.toFixed(1)} (list=${listTime.toFixed(1)}ms, set=${setTime.toFixed(1)}ms)`
);
}
console.log(`sequelize-0002 timing PASS ratio=${ratio.toFixed(1)}x (list=${listTime.toFixed(1)}ms set=${setTime.toFixed(1)}ms)`);
}
function testExpandIncludeAllSameResult() {
for (const n of [1, 5, 20, 50]) {
const a = expandIncludeAllDefective(n);
const b = expandIncludeAllFixed(n);
if (a !== b) {
throw new Error(`Results differ at nTypes=${n}: defective=${a} fixed=${b}`);
}
}
console.log('sequelize-0002 correctness PASS');
}
// ---------------------------------------------------------------------------
// Run
// ---------------------------------------------------------------------------
testBulkInsertListSlowerThanSet();
testBulkInsertSameResult();
testExpandIncludeAllListSlowerThanSet();
testExpandIncludeAllSameResult();