Repository navigation
fix(query-builder): reject empty where criteria on update and delete operations - #12629
Conversation
… __proto__ normalizeWhereCriteria() iterated any object whose criteria were being validated, including loaded entity class instances. An entity carries all its columns, so a nullable foreign key that happens to be null (or an unset undefined column) could be stripped or made to throw even though those columns are intentionally part of the WHERE condition. Add an isPlainObject early return so entity instances (and other non-plain objects) pass through unchanged; only plain FindOptionsWhere objects are normalized. Also skip the __proto__ key while iterating to avoid writing through the prototype. This is a pure safety/structural change: the default-throw behavior for the unconfigured case is unchanged and will be addressed separately. Refs #12578
commit: |
Code Review by Qodo
1. Docs: arrays not validated
|
Address review feedback on the new tests: - __proto__ guard test now asserts the returned object's own prototype is still Object.prototype (per-object prototype mutation), not only that the global Object.prototype is unpolluted — the prior check passed even without the guard. - Entity-instance passthrough test now asserts observable effects: a fully populated instance deletes its row, and an instance with a null nullable column does not throw and leaves the row in place (it renders as 'text = NULL', which matches nothing; IsNull() is required to match SQL NULL). This documents that passthrough never silently validates the instance and shows the actual query effect.
Thanks — this addresses both findings well.
No further concerns from my side. |
|
Noting one scope gap for #12578: this PR body says the unconfigured default behavior is intentionally untouched, and the new unit test currently asserts That means the original #12578 path still remains for unconfigured data sources: If the default-behavior follow-up lands separately, two edge cases from the duplicate PRs are worth carrying forward with it:
Happy to help turn those into a smaller follow-up patch if useful. |
normalizeWhereCriteria can reduce a non-empty criteria object to {} (e.g.
a "__proto__"-only object whose key is skipped by the pollution guard, or
all keys stripped under invalidWhereValuesBehavior: "ignore"). update/
delete/softDelete/restore validated emptiness only on the original criteria,
so the normalized {} reached .where(), rendered as "WHERE 1=1", and turned a
targeted write into a full-table one.
Re-check the normalized criteria via new OrmUtils.isNormalizedWhereCriteriaEmpty
(also rejects arrays that are empty or contain any empty OR-branch) and reject
with the existing "Empty criteria(s) are not allowed" error.
| * | ||
| * @param criteria | ||
| */ | ||
| public static isNormalizedWhereCriteriaEmpty( |
There was a problem hiding this comment.
isNormalizedWhereCriteriaEmpty looks like a duplicate of isCriteriaNullOrEmpty (with a bug in that function fixed).
| // normalization may have stripped every key (e.g. a "__proto__"-only | ||
| // object, or all keys removed under the "ignore" behavior); a now-empty | ||
| // criteria would render as "WHERE 1=1" and update the whole table. | ||
| if (OrmUtils.isNormalizedWhereCriteriaEmpty(normalizedCriteria)) { |
There was a problem hiding this comment.
I wonder what's the point of checking if the criteria is empty TWICE. We probably don't do it right the first time 😉 Or we don't do it at the right time 😉😉
|
He @naor, I had my custom review agent Nigel look at this and something was flagged that is worth checking to see if it is a legit concern, as it might contradict this earlier defense:
Nigel’s review findingsTypeORM lets you configure what happens when a null or undefined sneaks into a query's WHERE conditions. You set it once on your connection:invalidWhereValuesBehavior: { null: "throw", undefined: "throw" } "throw" means: "if someone tries to filter by a null/undefined value, stop and raise an error instead of silently building a broken query." This exists because column = NULL in SQL matches nothing (you have to write column IS NULL), so a stray null usually means a bug — better to shout than to silently return/delete the wrong rows. The trap: this rule is enforced in two separate places Here's the thing most people (including the PR author and the reviewer who approved it) didn't realise. There isn't one piece of code that enforces this setting. There are two completely separate copies, one for each family of operations: Two hand-written implementations of the same idea. They already had slightly different wording and logic before this PR ever showed up. What the PR changed The PR added an escape hatch to the write copy only (normalizeWhereCriteria). The new rule: "if the thing you're filtering by is a loaded entity object (not a plain {...}), skip all the null/undefined checking — pass it straight through untouched." // the new early-return in normalizeWhereCriteria
if (!OrmUtils.isPlainObject(criteria)) {
return criteria // entity instances bypass all validation
}The justification the author gave — and why it's wrong When a review bot flagged this, the author defended it (in the PR comments) by saying: ▎ "the passthrough is intentional and matches find() semantics: an entity class instance is not validated against invalidWhereValuesBehavior." In plain English: "Don't worry, the read side (find()) already ignores entities like this, so I'm just matching existing behaviour." That claim is false. I read the read-side code. Here's the actual loop from SelectQueryBuilder.buildWhere (SelectQueryBuilder.ts:4353-4398): for (const key in where) { // ← iterates EVERY key
let parameterValue = where[key]
...
if (parameterValue === undefined) {
... ?? "throw" ... // throws unless you opted out
}
if (parameterValue === null) {
... "throw" ... // throws unless you opted out
}
}There is no "is this a plain object or an entity?" check anywhere in here. The read side validates every key of whatever you pass it — plain object or loaded entity, it makes no difference. So find() does not have the behaviour the author claims to be matching. The concrete consequence Say you've got invalidWhereValuesBehavior: { null: "throw" } configured, and a loaded Post entity whose nullable text column happens to be null: const post = await repo.findOneBy({ id: 5 }) // post.text === null
// READ path — validated, so it throws loudly:
await repo.findBy(post) // ❌ throws "Null value encountered..."
// WRITE path AFTER this PR — bypassed, so it stays silent:
await repo.delete(post) // 😶 no error — builds `text = NULL`,
// matches zero rows, deletes nothingSame input, same setting, opposite behaviour depending on whether you're reading or writing. The whole point of a "throw" setting is that it fires consistently. After this PR it fires on reads but goes quiet on writes — and the person configured "throw" precisely because they wanted to be warned. Why this matters beyond the one bug The deeper issue Nigel is pointing at: the same rule living in two copies that are now actively drifting apart. Nobody reading normalizeWhereCriteria next to buildWhere will understand why the identical setting produces different results for the identical input — because the divergence isn't documented, it's accidental. What "fix" means here The minimum bar is honesty in the reasoning: the passthrough might be defensible as "this matches the low-level, unvalidated QueryBuilder.where() behaviour" — but not as "matches find()." Either correct that justification, or reconsider whether the bypass should exist at all. The cleaner long-term answer is one shared validation helper feeding both paths, so this class of "two copies drift" bug can't recur — but that's a bigger change worth its own follow-up. |
…lization Address review feedback: fold the array-aware emptiness logic into isCriteriaNullOrEmpty (an array is empty if it has no elements or any empty element) and drop the near-duplicate isNormalizedWhereCriteriaEmpty helper. Each of update/delete/softDelete/restore now normalizes first and checks emptiness once on the normalized criteria, instead of validating the original criteria and re-validating the normalized output. Behavior is unchanged for callers not using invalidWhereValuesBehavior (normalize is a passthrough).
Reduce duplication flagged by SonarCloud (new_duplicated_lines_density): the identical normalize + empty-check + reject block was copy-pasted across update/delete/softDelete/restore. Extract it into a single normalizeAndValidateWhereCriteria helper and make the four methods async so a thrown TypeORMError surfaces as a rejected promise, preserving the existing contract.
…ehavior - Strengthen the entity-instance passthrough test to assert DeleteResult.affected (1 for the populated instance, 0 for the null-column no-op) on drivers that report it, in addition to the existing row-existence checks. - Document in null-and-undefined-handling: write methods reject criteria that is empty after normalization (guards against WHERE 1=1), and entity class instances are passed through unchanged (not validated by invalidWhereValuesBehavior).
Deploying typeorm with
|
| Latest commit: |
073cb4b
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://753adab9.typeorm.pages.dev |
| Branch Preview URL: | https://fix-normalize-where-plain-ob.typeorm.pages.dev |
…ic arrays
The array branch recursively called isCriteriaNullOrEmpty on each element,
which stack-overflows (RangeError) on a self-referential array (const a=[];
a.push(a)) — reachable from EntityManager update/delete/softDelete/restore
criteria validation. Inspect array elements only one level deep with a
non-recursive emptiness check; this still catches every real empty shape
([], [{}], [null]) without recursing into nested/cyclic arrays.
…path Per maintainer review: the read path (SelectQueryBuilder.buildWhere) validates every key of the where criteria against invalidWhereValuesBehavior regardless of whether it was given a plain object or a loaded entity instance. The write path (update/delete/softDelete/restore) previously bypassed validation for entity instances via a !isPlainObject early-return in normalizeWhereCriteria, so the same input threw on find() but silently built `col = NULL` on delete(). Normalize entity instances the same as plain objects so both paths behave identically. Primitives and atomic value-types (Date, Buffer/Uint8Array) are still passed through untouched (delete-by-id and binary criteria unaffected), and unconfigured data sources are unchanged (early return when no options). Update tests and docs accordingly.
An array criteria element that is itself an empty array (e.g. [[]]) produces zero predicates and renders as an always-true `1=1` OR-branch, turning update/delete/softDelete/restore into unfiltered operations when invalidWhereValuesBehavior is unset (normalizeWhereCriteria passes criteria through untouched). Treat a zero-length array element as empty. This is a plain length check, not a recursive call, so cyclic arrays remain safe from unbounded recursion.
…elper doc Address two review findings: - Primitive id / id-array criteria (executed via whereInIds) was normalized and run through the OR-branch emptiness rules because validation ran before the isPrimitiveCriteria() branch. That could reject valid IN-lists (e.g. a string id list containing "") and needlessly mapped large id lists. Check isPrimitiveCriteria() first: primitive criteria is only rejected when wholly empty and returned untouched; object criteria is normalized and gets the per-element empty-OR-branch check. isCriteriaNullOrEmpty() reverts to a shallow whole-emptiness check (also removes any recursion concern). - Correct the normalizeAndValidateWhereCriteria doc comment: it validates entity class instances too, not only plain objects.
manager.findBy/delete take the entity target as the first argument; the example omitted it (manager.delete(post) -> manager.delete(Post, post)).
Move the authoritative description of invalidWhereValuesBehavior handling onto OrmUtils.normalizeWhereCriteria, trim the EntityManager helper comment to defer to it, and describe entity-instance validation in prose (removing the example code block). No behavior change.
…rn honestly The returned criteria is the raw id/id-array for the primitive (whereInIds) branch, not necessarily an object; type it as any so callers aren't misled into treating a primitive result as an object.
Guard update/delete/softDelete/restore at the point the WHERE is built: if a
WHERE was provided but renders empty ("1=1"), throw instead of emitting an
unfiltered statement. This closes the remaining full-table vector where criteria
look non-empty at the top level but expand to zero predicates — e.g. a relation
key whose value is a keyless object ({ category: new Category() }). Callers that
intend to affect all rows use updateAll()/deleteAll(), which set no WHERE.
When invalidWhereValuesBehavior is unset, the write path (update/delete/
softDelete/restore) passed null/undefined through unchanged (col = NULL), while
the read/find path and the documented default treat a missing behavior as
"throw". Default the option to {} so per-key resolution yields "throw",
aligning writes with reads. Configured behaviors (ignore/sql-null) are
unaffected.
The default-throw alignment broke a legitimate operation — TreeRepository
softDelete with { parentId: null } on an unconfigured data source
(tree-tables/materialized-path/soft-delete-parent). Changing the unconfigured
write default from passthrough to throw is a breaking change to established
behavior that existing (including internal tree) code relies on; it needs a
deliberate, separately-tested change rather than being bundled here. Keeps the
QueryBuilder empty-WHERE guard, which is unaffected.
smith-xyz
left a comment
There was a problem hiding this comment.
just some nits, lgtm!
| // the top level but expand to zero predicates (e.g. a relation key whose | ||
| // value is a keyless object). To affect all rows, use the dedicated | ||
| // updateAll()/deleteAll() methods, which set no WHERE. | ||
| const writeQueryTypes = ["update", "delete", "soft-delete", "restore"] |
There was a problem hiding this comment.
nit: this feels a little odd here - given that this is just building, surprised we don't store this as metadata as part of the object to denote what type of query it is
if anything maybe we could store this static list somewhere else outside of this protected member?
| // updateAll()/deleteAll() methods, which set no WHERE. | ||
| const writeQueryTypes = ["update", "delete", "soft-delete", "restore"] | ||
| if ( | ||
| writeQueryTypes.indexOf(this.expressionMap.queryType) !== -1 && |
There was a problem hiding this comment.
nit: could use .includes(), but I think this is consistent with other areas
| ) { | ||
| throw new TypeORMError( | ||
| `Empty criteria(s) are not allowed for the ${this.expressionMap.queryType} operation. ` + | ||
| `To affect all rows, use the dedicated updateAll/deleteAll methods.`, |
There was a problem hiding this comment.
minor nit: if soft-delete/restore, there is no equivalent to map to, so all actions are being told to go to updateAll/deleteAll.
There was a problem hiding this comment.
The type of criteria is no longer reflecting the real life type?
It should be any in real life, but it's incorrectly cast when we call this method.
| criteria === null || | ||
| typeof criteria !== "object" || | ||
| criteria instanceof Date || | ||
| isUint8Array(criteria) |
There was a problem hiding this comment.
Any code that requires a comment this long is probably doing something it shouldn't.
What would happen for other data types - I'm thinking maybe FindOperator or something like that? Or anything else you have not yet thought about?
Right know, we're iterating thought the Object entries for everything else that doesn't match all these things. But who knows what other values we could get here - last time we forgot about Buffer and Array (and BTW, we are forgetting about arrays here again!)
That's why we should ALWAYS check if it's the kind of value we'd like to work with before working with it (and not what it's not). So if we want to iterate through the Object.entries(criteria) we should make sure if makes sense to do that, e.g. it's a plain object criteria, not some instance of a class (like an entity or a FindOperator or an array which can be a sparse vector containing nulls).
A little bit below there's an if (OrmUtils.isPlainObject(value)) - since now the logic from all those functions in EntityManager was moved to this method, maybe it makes sense to bring it up here as well?
- normalizeWhereCriteria: guard the key iteration with a positive isPlainObject(criteria) check instead of enumerating value types to exclude. Entity/class instances, FindOperators, arrays, Date, Buffer and primitives are passed through untouched (deep entity validation needs metadata — out of scope). Type criteria as any and drop the casts at the call sites. - QueryBuilder empty-WHERE guard: hoist the write query-type list to a module-level const, use Array.includes, and reword the error since soft-delete/restore have no *All equivalent. - Update tests and docs to reflect plain-object-only normalization.
|
@naorpeled all review comments from @alumni and @smith-xyz are addressed in
Ready for release whenever you are 🙏 |
|
…operations (#12629) (cherry picked from commit 81b9466) Co-authored-by: Lucian Mocanu <[email protected]>
…operations (#12629) (cherry picked from commit 81b9466) Co-authored-by: Lucian Mocanu <[email protected]>
|
Hey, initial issue submitter here 👋 Just wanted to say thanks to all that worked on this, it obviously ended up being a bigger task than I initially thought. Appreciate the efforts! |
Thank you for opening the issue ❤️ |



Part of #12578
Problem
EntityManager.update/delete/softDelete/restorevalidate criteria for emptiness on the original input, then pass the normalized criteria toQueryBuilder.where(). Normalization can reduce a non‑empty criteria to an empty one, and an empty condition renders asWHERE 1=1— silently turning a targeted operation into a full‑table write/delete.Ways the criteria could collapse to empty (or otherwise produce no predicate):
__proto__‑only object, e.g.JSON.parse('{"__proto__": {"polluted": true}}')→{}invalidWhereValuesBehavior.null/undefined = "ignore", e.g.{ text: null }→{}[{}],[[]],[{ id: 1 }, {}][1, { id: 2 }](.where(1)has no predicate)new Post()(no set columns)Separately, the write path passed entity class instances through normalization untouched, so
invalidWhereValuesBehaviorwas not enforced for them — inconsistent with the read/find path (SelectQueryBuilder.buildWhere), which validates every key regardless of whether it was given a plain object or a loaded entity.Changes
Empty criteria(s) are not allowed …error, instead of emittingWHERE 1=1. Covers empty objects/arrays, empty OR‑branches, bare primitives in OR‑arrays, and keyless (empty) non‑plain objects such as empty entity instances.invalidWhereValuesBehavioron entity instances, exactly like plainFindOptionsWhereobjects, so reads and writes behave identically. Primitive id/id‑arrays keep usingwhereInIds(no over‑validation), and atomic value‑types (Date,Buffer/Uint8Array) pass through untouched.__proto__key while normalizing, so a crafted criteria key can't write through the object prototype.OrmUtils.isCriteriaNullOrEmptyis a shallow, cyclic‑safe check (no unbounded recursion on self‑referential arrays).normalizeAndValidateWhereCriteriahelper backsupdate/delete/softDelete/restore(no duplicated emptiness logic).Unconfigured data sources are unchanged. For intentional full‑table writes, use the dedicated
updateAll()/deleteAll()methods.Behavior (
invalidWhereValuesBehavior)throw,sql-null, andignoreall work as documented for plain objects, nested plain objects, arrays, and entity instances. Any criteria that normalizes to empty is rejected rather than silently matching every row.Tests & docs
test/unit/util/orm-utils.test.ts): shallow/cyclic‑safe emptiness check,__proto__guard, entity‑instance validation, value‑type passthrough.test/functional/null-undefined-handling/query-builders.test.ts):throw/sql-null/ignoreacross the shapes above; rejection of every empty/degenerate criteria (__proto__‑only, all‑keys‑stripped,[[]],[1, {id}], empty entity instance); entity instances validated consistently withfind(). Green across the full driver matrix.docs/docs/data-source/5-null-and-undefined-handling.mddocuments the empty‑criteria rejection and entity‑instance validation.