Skip to content

fix: apply default invalid where behavior when options are omitted - #12595

Closed
belljinwo-jpg wants to merge 4 commits into
typeorm:masterfrom
belljinwo-jpg:fix/12578-default-invalid-where-behavior
Closed

belljinwo-jpg wants to merge 4 commits into
typeorm:masterfrom
belljinwo-jpg:fix/12578-default-invalid-where-behavior

Conversation

@belljinwo-jpg

@belljinwo-jpg belljinwo-jpg commented Jun 19, 2026 •

Copy link
Copy Markdown

fix: apply default invalid where behavior when options are omitted

Closes #12578.

What changed

OrmUtils.normalizeWhereCriteria() now applies the documented default behavior when invalidWhereValuesBehavior is omitted: both null and undefined values throw in high-level mutation criteria.

The implementation also preserves the historical passthrough for entity-instance criteria only when the options argument is omitted. When a DataSource explicitly configures invalid-value behavior, entity instances are normalized and the configured behavior is honored.

Normalized criteria use a null-prototype accumulator so keys such as __proto__ remain ordinary own WHERE keys without mutating the result prototype.

Functional regression coverage

  • default throws for top-level undefined and null
  • nested and array criteria report the full property path
  • explicit { undefined: "ignore" } behavior remains supported
  • entity instances keep historical behavior when options are omitted
  • explicit invalid-value behavior is honored for entity instances
  • __proto__ remains an own criteria key without prototype mutation

Verification

  • TypeScript compilation: passed
  • focused functional suite: 24 passing
  • complete SQL.js suite: 2,965 passing, 179 pending, 0 failing
  • semantic PR check: passed

Opire

This PR targets the USD 300 Opire reward attached to issue #12578.

@github-actions github-actions Bot added linked-issue PR references an issue possible-duplicate PR may duplicate an existing open PR labels Jun 19, 2026
@github-actions

Copy link
Copy Markdown

Other open PRs also reference #12578: #12579,#12594. Maintainers may want to coordinate.

@belljinwo-jpg

Copy link
Copy Markdown
Author

/claim #12578

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Jun 19, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (0) 📘 Rule violations (1) 📜 Skill insights (0)

Grey Divider


Action required

1. Entity criteria bypass validation ✓ Resolved 🐞 Bug ≡ Correctness
Description
normalizeWhereCriteria() now returns non-plain-object criteria (e.g., entity instances) without
applying invalidWhereValuesBehavior, even when the behavior is explicitly configured on the
DataSource. This makes EntityManager.update/delete/softDelete/restore silently fall back to
QueryBuilder.where() semantics for those criteria, contradicting the documented behavior and
allowing null/undefined to pass through unvalidated/transformed.
Code

src/util/OrmUtils.ts[R680-684]

+        // Entity instances can contain nullable fields that are not intended
+        // to participate in the WHERE clause. Preserve their existing behavior.
+        if (!OrmUtils.isPlainObject(criteria)) {
+            return criteria
+        }
Evidence
EntityManager mutation methods always funnel non-primitive criteria through normalizeWhereCriteria()
and then into QueryBuilder.where(). With the new non-plain-object early return, entity instances
skip normalization and therefore skip invalidWhereValuesBehavior handling, even though docs state
the setting applies to these high-level methods and that QueryBuilder.where() is not affected by the
setting.

src/util/OrmUtils.ts[660-688]
src/entity-manager/EntityManager.ts[837-887]
docs/docs/data-source/5-null-and-undefined-handling.md[198-253]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`OrmUtils.normalizeWhereCriteria()` now returns early for any non-plain object criteria (e.g. entity instances). This means `invalidWhereValuesBehavior` is not applied for those criteria, even when the behavior is explicitly configured on the `DataSource`, and the criteria then flow into `QueryBuilder.where()` unvalidated.
### Issue Context
The TypeORM docs state `invalidWhereValuesBehavior` applies to high-level operations (including EntityManager update/delete/softDelete/restore) and does *not* affect QueryBuilder `.where()` directly. With the new early return, passing an entity instance as criteria (e.g. `manager.update(Post, Object.assign(new Post(), { text: null }), {...})`) will bypass the configured behavior.
### Fix Focus Areas
- Only preserve “entity instance passthrough” when the behavior is truly omitted (the historical case), but **do not** bypass validation when the behavior is explicitly configured.
- Implement by tracking whether `options` was omitted before defaulting it, e.g.:
- `const optionsOmitted = options == null; options ??= {}; if (optionsOmitted && !isPlainObject(criteria)) return criteria;`
- This keeps the narrow regression-avoidance for omitted options, while honoring explicit configuration.
### Fix Focus Areas (code pointers)
- src/util/OrmUtils.ts[660-688]
- src/entity-manager/EntityManager.ts[837-887]
- docs/docs/data-source/5-null-and-undefined-handling.md[198-253]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. __proto__ criteria injection ✓ Resolved 🐞 Bug ⛨ Security
Description
normalizeWhereCriteria() copies user-controlled keys into a fresh {} without filtering special
keys (e.g. __proto__), which can mutate the prototype of the normalized criteria object. With the
new options ??= {} change, this normalization now runs even when options are omitted, and a
crafted criteria can cause predicates to be lost (e.g. normalized object has no own keys), risking
unbounded update/delete WHERE generation.
Code

src/util/OrmUtils.ts[R665-669]

+        // Resolve omitted behavior once so the documented defaults below apply.
+        options ??= {}
  // multiple criteria are possible at the top level
  if (!path && Array.isArray(criteria)) {
Evidence
normalizeWhereCriteria now always resolves omitted options and then copies entries into a new object
via result[key] = ... without filtering special keys; assigning __proto__ can mutate the
prototype of result and remove expected own-properties. The codebase already skips __proto__ in
OrmUtils.merge(), indicating this is a known hazard, and query-builder predicate generation relies
on Object.keys(entity), so losing own keys can lead to missing predicates.

src/util/OrmUtils.ts[660-723]
src/util/OrmUtils.ts[633-642]
src/entity-manager/EntityManager.ts[861-881]
src/query-builder/QueryBuilder.ts[1386-1405]
src/query-builder/QueryBuilder.ts[1624-1687]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`OrmUtils.normalizeWhereCriteria()` builds a new plain object (`{}`) and assigns `result[key] = ...` for every key from user-provided criteria. If the input contains special keys like `"__proto__"`, this assignment can invoke the `__proto__` setter and change the prototype of `result`, potentially dropping own keys and/or causing downstream query building to behave unexpectedly (including generating a WHERE-less UPDATE/DELETE).
Because this PR changes behavior to always normalize when options are omitted (`options ??= {}`), this risk becomes reachable in the default configuration.
## Issue Context
TypeORM already treats `__proto__` as dangerous in similar object-copying code (see `OrmUtils.merge()`), but `normalizeWhereCriteria()` does not apply the same protection.
## Fix Focus Areas
- src/util/OrmUtils.ts[660-723]
### Suggested fix approach
Implement one (or both) of the following in `normalizeWhereCriteria()`:
1. Skip dangerous keys:
- `if (key === "__proto__" || key === "constructor" || key === "prototype") continue`
2. Create the accumulator with a null prototype:
- `const result: ObjectLiteral = Object.create(null)`
If you skip keys, consider whether you should throw a `TypeORMError` for these keys (safer for update/delete), rather than silently dropping them.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

3. normalizeWhereCriteria tests not functional ✓ Resolved 📘 Rule violation ☼ Reliability
Description
This issue fix adds coverage in test/unit/util/orm-utils.test.ts instead of the functional test
suite (test/functional), which does not meet the checklist requirement for issue fixes. Keeping
the regression test in functional tests (with an issue reference comment) helps ensure the behavior
is covered through end-to-end library usage patterns.
Code

test/unit/util/orm-utils.test.ts[R274-335]

+    describe("normalizeWhereCriteria", () => {
+        it("uses the default throw behavior when options are omitted", () => {
+            expect(() =>
+                OrmUtils.normalizeWhereCriteria({ id: undefined }),
+            ).to.throw("Undefined value encountered in property 'id'")
+
+            expect(() =>
+                OrmUtils.normalizeWhereCriteria({ id: null }),
+            ).to.throw("Null value encountered in property 'id'")
+        })
+
+        it("applies defaults recursively to nested and array criteria", () => {
+            expect(() =>
+                OrmUtils.normalizeWhereCriteria({ user: { id: undefined } }),
+            ).to.throw("Undefined value encountered in property 'user.id'")
+
+            expect(() =>
+                OrmUtils.normalizeWhereCriteria([
+                    { id: 1 },
+                    { user: { id: null } },
+                ]),
+            ).to.throw("Null value encountered in property '1.user.id'")
+        })
+
+        it("preserves explicitly configured behavior", () => {
+            expect(
+                OrmUtils.normalizeWhereCriteria(
+                    { id: undefined, name: "Ada" },
+                    { undefined: "ignore" },
+                ),
+            ).to.deep.equal({ name: "Ada" })
+        })
+
+        it("preserves entity instances and arrays containing them", () => {
+            class User {
+                id = 1
+                parentId: number | null = null
+            }
+
+            const entity = new User()
+
+            expect(OrmUtils.normalizeWhereCriteria(entity)).to.equal(entity)
+            expect(OrmUtils.normalizeWhereCriteria([entity])).to.deep.equal([
+                entity,
+            ])
+        })
+
+        it("preserves __proto__ criteria without changing the result prototype", () => {
+            const criteria = JSON.parse(
+                '{"__proto__":{"admin":true},"id":1}',
+            )
+
+            const normalized = OrmUtils.normalizeWhereCriteria(
+                criteria,
+            ) as Record<string, any>
+
+            expect(Object.getPrototypeOf(normalized)).to.equal(null)
+            expect(Object.hasOwn(normalized, "__proto__")).to.equal(true)
+            expect(normalized.id).to.equal(1)
+            expect(normalized.__proto__.admin).to.equal(true)
+        })
+    })
Evidence
PR Compliance ID 3 requires issue-fix coverage to be added/updated in test/functional. The PR adds
new tests for normalizeWhereCriteria under test/unit/util/orm-utils.test.ts, so the fix is not
covered in the functional suite per the checklist.

Rule 3: Prefer functional tests over per-issue tests
test/unit/util/orm-utils.test.ts[274-335]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The regression coverage for this issue fix was added under `test/unit`, but the checklist requires issue fixes to live in the functional suite (`test/functional`) and include an issue reference comment when applicable.
## Issue Context
This PR is explicitly an issue fix (Closes #12578), and it adds a new `describe("normalizeWhereCriteria")` block under unit tests.
## Fix Focus Areas
- test/unit/util/orm-utils.test.ts[274-335]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. any cast in test 📘 Rule violation ⚙ Maintainability
Description
The added test uses an any-typed cast (as Record), which introduces type-bypassing noise and
weakens type safety. This violates the checklist’s requirement to avoid any casts used to bypass
type issues.
Code

test/unit/util/orm-utils.test.ts[R326-329]

+            const normalized = OrmUtils.normalizeWhereCriteria(
+                criteria,
+            ) as Record<string, any>
+
Evidence
PR Compliance ID 4 forbids introducing AI-like noise such as any casts to bypass type checking.
The new test explicitly casts the normalized output to Record.

Rule 4: Remove AI-generated noise
test/unit/util/orm-utils.test.ts[326-329]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A new test uses `as Record<string, any>`, which is an explicit `any` cast to bypass typing.
## Issue Context
This appears to be used only to access and assert on the `"__proto__"` key of the normalized object.
## Fix Focus Areas
- test/unit/util/orm-utils.test.ts[326-334]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

  • Author self-review: I have reviewed the code review findings, and addressed the relevant ones.

Previous review results

Review updated until commit 1e5829b

Results up to commit ee6661a


🐞 Bugs (1) 📘 Rule violations (1) 📜 Skill insights (0)


Action required
1. Entity criteria bypass validation 🐞 Bug ≡ Correctness ⭐ New
Description
normalizeWhereCriteria() now returns non-plain-object criteria (e.g., entity instances) without
applying invalidWhereValuesBehavior, even when the behavior is explicitly configured on the
DataSource. This makes EntityManager.update/delete/softDelete/restore silently fall back to
QueryBuilder.where() semantics for those criteria, contradicting the documented behavior and
allowing null/undefined to pass through unvalidated/transformed.
Code

src/util/OrmUtils.ts[R680-684]

+        // Entity instances can contain nullable fields that are not intended
+        // to participate in the WHERE clause. Preserve their existing behavior.
+        if (!OrmUtils.isPlainObject(criteria)) {
+            return criteria
+        }
Evidence
EntityManager mutation methods always funnel non-primitive criteria through normalizeWhereCriteria()
and then into QueryBuilder.where(). With the new non-plain-object early return, entity instances
skip normalization and therefore skip invalidWhereValuesBehavior handling, even though docs state
the setting applies to these high-level methods and that QueryBuilder.where() is not affected by the
setting.

src/util/OrmUtils.ts[660-688]
src/entity-manager/EntityManager.ts[837-887]
docs/docs/data-source/5-null-and-undefined-handling.md[198-253]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`OrmUtils.normalizeWhereCriteria()` now returns early for any non-plain object criteria (e.g. entity instances). This means `invalidWhereValuesBehavior` is not applied for those criteria, even when the behavior is explicitly configured on the `DataSource`, and the criteria then flow into `QueryBuilder.where()` unvalidated.

### Issue Context
The TypeORM docs state `invalidWhereValuesBehavior` applies to high-level operations (including EntityManager update/delete/softDelete/restore) and does *not* affect QueryBuilder `.where()` directly. With the new early return, passing an entity instance as criteria (e.g. `manager.update(Post, Object.assign(new Post(), { text: null }), {...})`) will bypass the configured behavior.

### Fix Focus Areas
- Only preserve “entity instance passthrough” when the behavior is truly omitted (the historical case), but **do not** bypass validation when the behavior is explicitly configured.
- Implement by tracking whether `options` was omitted before defaulting it, e.g.:
 - `const optionsOmitted = options == null; options ??= {}; if (optionsOmitted && !isPlainObject(criteria)) return criteria;`
 - This keeps the narrow regression-avoidance for omitted options, while honoring explicit configuration.

### Fix Focus Areas (code pointers)
- src/util/OrmUtils.ts[660-688]
- src/entity-manager/EntityManager.ts[837-887]
- docs/docs/data-source/5-null-and-undefined-handling.md[198-253]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. __proto__ criteria injection ✓ Resolved 🐞 Bug ⛨ Security
Description
normalizeWhereCriteria() copies user-controlled keys into a fresh {} without filtering special
keys (e.g. __proto__), which can mutate the prototype of the normalized criteria object. With the
new options ??= {} change, this normalization now runs even when options are omitted, and a
crafted criteria can cause predicates to be lost (e.g. normalized object has no own keys), risking
unbounded update/delete WHERE generation.
Code

src/util/OrmUtils.ts[R665-669]

+        // Resolve omitted behavior once so the documented defaults below apply.
+        options ??= {}
    // multiple criteria are possible at the top level
    if (!path && Array.isArray(criteria)) {
Evidence
normalizeWhereCriteria now always resolves omitted options and then copies entries into a new object
via result[key] = ... without filtering special keys; assigning __proto__ can mutate the
prototype of result and remove expected own-properties. The codebase already skips __proto__ in
OrmUtils.merge(), indicating this is a known hazard, and query-builder predicate generation relies
on Object.keys(entity), so losing own keys can lead to missing predicates.

src/util/OrmUtils.ts[660-723]
src/util/OrmUtils.ts[633-642]
src/entity-manager/EntityManager.ts[861-881]
src/query-builder/QueryBuilder.ts[1386-1405]
src/query-builder/QueryBuilder.ts[1624-1687]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`OrmUtils.normalizeWhereCriteria()` builds a new plain object (`{}`) and assigns `result[key] = ...` for every key from user-provided criteria. If the input contains special keys like `"__proto__"`, this assignment can invoke the `__proto__` setter and change the prototype of `result`, potentially dropping own keys and/or causing downstream query building to behave unexpectedly (including generating a WHERE-less UPDATE/DELETE).
Because this PR changes behavior to always normalize when options are omitted (`options ??= {}`), this risk becomes reachable in the default configuration.
## Issue Context
TypeORM already treats `__proto__` as dangerous in similar object-copying code (see `OrmUtils.merge()`), but `normalizeWhereCriteria()` does not apply the same protection.
## Fix Focus Areas
- src/util/OrmUtils.ts[660-723]
### Suggested fix approach
Implement one (or both) of the following in `normalizeWhereCriteria()`:
1. Skip dangerous keys:
- `if (key === "__proto__" || key === "constructor" || key === "prototype") continue`
2. Create the accumulator with a null prototype:
- `const result: ObjectLiteral = Object.create(null)`
If you skip keys, consider whether you should throw a `TypeORMError` for these keys (safer for update/delete), rather than silently dropping them.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended
3. normalizeWhereCriteria tests not functional ✓ Resolved 📘 Rule violation ☼ Reliability
Description
This issue fix adds coverage in test/unit/util/orm-utils.test.ts instead of the functional test
suite (test/functional), which does not meet the checklist requirement for issue fixes. Keeping
the regression test in functional tests (with an issue reference comment) helps ensure the behavior
is covered through end-to-end library usage patterns.
Code

test/unit/util/orm-utils.test.ts[R274-335]

+    describe("normalizeWhereCriteria", () => {
+        it("uses the default throw behavior when options are omitted", () => {
+            expect(() =>
+                OrmUtils.normalizeWhereCriteria({ id: undefined }),
+            ).to.throw("Undefined value encountered in property 'id'")
+
+            expect(() =>
+                OrmUtils.normalizeWhereCriteria({ id: null }),
+            ).to.throw("Null value encountered in property 'id'")
+        })
+
+        it("applies defaults recursively to nested and array criteria", () => {
+            expect(() =>
+                OrmUtils.normalizeWhereCriteria({ user: { id: undefined } }),
+            ).to.throw("Undefined value encountered in property 'user.id'")
+
+            expect(() =>
+                OrmUtils.normalizeWhereCriteria([
+                    { id: 1 },
+                    { user: { id: null } },
+                ]),
+            ).to.throw("Null value encountered in property '1.user.id'")
+        })
+
+        it("preserves explicitly configured behavior", () => {
+            expect(
+                OrmUtils.normalizeWhereCriteria(
+                    { id: undefined, name: "Ada" },
+                    { undefined: "ignore" },
+                ),
+            ).to.deep.equal({ name: "Ada" })
+        })
+
+        it("preserves entity instances and arrays containing them", () => {
+            class User {
+                id = 1
+                parentId: number | null = null
+            }
+
+            const entity = new User()
+
+            expect(OrmUtils.normalizeWhereCriteria(entity)).to.equal(entity)
+            expect(OrmUtils.normalizeWhereCriteria([entity])).to.deep.equal([
+                entity,
+            ])
+        })
+
+        it("preserves __proto__ criteria without changing the result prototype", () => {
+            const criteria = JSON.parse(
+                '{"__proto__":{"admin":true},"id":1}',
+            )
+
+            const normalized = OrmUtils.normalizeWhereCriteria(
+                criteria,
+            ) as Record<string, any>
+
+            expect(Object.getPrototypeOf(normalized)).to.equal(null)
+            expect(Object.hasOwn(normalized, "__proto__")).to.equal(true)
+            expect(normalized.id).to.equal(1)
+            expect(normalized.__proto__.admin).to.equal(true)
+        })
+    })
Evidence
PR Compliance ID 3 requires issue-fix coverage to be added/updated in test/functional. The PR adds
new tests for normalizeWhereCriteria under test/unit/util/orm-utils.test.ts, so the fix is not
covered in the functional suite per the checklist.

Rule 3: Prefer functional tests over per-issue tests
test/unit/util/orm-utils.test.ts[274-335]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The regression coverage for this issue fix was added under `test/unit`, but the checklist requires issue fixes to live in the functional suite (`test/functional`) and include an issue reference comment when applicable.
## Issue Context
This PR is explicitly an issue fix (Closes #12578), and it adds a new `describe("normalizeWhereCriteria")` block under unit tests.
## Fix Focus Areas
- test/unit/util/orm-utils.test.ts[274-335]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


4. any cast in test 📘 Rule violation ⚙ Maintainability
Description
The added test uses an any-typed cast (as Record), which introduces type-bypassing noise and
weakens type safety. This violates the checklist’s requirement to avoid any casts used to bypass
type issues.
Code

test/unit/util/orm-utils.test.ts[R326-329]

+            const normalized = OrmUtils.normalizeWhereCriteria(
+                criteria,
+            ) as Record<string, any>
+
Evidence
PR Compliance ID 4 forbids introducing AI-like noise such as any casts to bypass type checking.
The new test explicitly casts the normalized output to Record.

Rule 4: Remove AI-generated noise
test/unit/util/orm-utils.test.ts[326-329]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A new test uses `as Record<string, any>`, which is an explicit `any` cast to bypass typing.
## Issue Context
This appears to be used only to access and assert on the `"__proto__"` key of the normalized object.
## Fix Focus Areas
- test/unit/util/orm-utils.test.ts[326-334]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Results up to commit cf7b4ef


🐞 Bugs (0) 📘 Rule violations (2) 📜 Skill insights (0)


Action required
1. __proto__ criteria injection ✓ Resolved 🐞 Bug ⛨ Security
Description
normalizeWhereCriteria() copies user-controlled keys into a fresh {} without filtering special
keys (e.g. __proto__), which can mutate the prototype of the normalized criteria object. With the
new options ??= {} change, this normalization now runs even when options are omitted, and a
crafted criteria can cause predicates to be lost (e.g. normalized object has no own keys), risking
unbounded update/delete WHERE generation.
Code

src/util/OrmUtils.ts[R665-669]

+        // Resolve omitted behavior once so the documented defaults below apply.
+        options ??= {}
      // multiple criteria are possible at the top level
      if (!path && Array.isArray(criteria)) {
Evidence
normalizeWhereCriteria now always resolves omitted options and then copies entries into a new object
via result[key] = ... without filtering special keys; assigning __proto__ can mutate the
prototype of result and remove expected own-properties. The codebase already skips __proto__ in
OrmUtils.merge(), indicating this is a known hazard, and query-builder predicate generation relies
on Object.keys(entity), so losing own keys can lead to missing predicates.

src/util/OrmUtils.ts[660-723]
src/util/OrmUtils.ts[633-642]
src/entity-manager/EntityManager.ts[861-881]
src/query-builder/QueryBuilder.ts[1386-1405]
src/query-builder/QueryBuilder.ts[1624-1687]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`OrmUtils.normalizeWhereCriteria()` builds a new plain object (`{}`) and assigns `result[key] = ...` for every key from user-provided criteria. If the input contains special keys like `"__proto__"`, this assignment can invoke the `__proto__` setter and change the prototype of `result`, potentially dropping own keys and/or causing downstream query building to behave unexpectedly (including generating a WHERE-less UPDATE/DELETE).
Because this PR changes behavior to always normalize when options are omitted (`options ??= {}`), this risk becomes reachable in the default configuration.
## Issue Context
TypeORM already treats `__proto__` as dangerous in similar object-copying code (see `OrmUtils.merge()`), but `normalizeWhereCriteria()` does not apply the same protection.
## Fix Focus Areas
- src/util/OrmUtils.ts[660-723]
### Suggested fix approach
Implement one (or both) of the following in `normalizeWhereCriteria()`:
1. Skip dangerous keys:
- `if (key === "__proto__" || key === "constructor" || key === "prototype") continue`
2. Create the accumulator with a null prototype:
- `const result: ObjectLiteral = Object.create(null)`
If you skip keys, consider whether you should throw a `TypeORMError` for these keys (safer for update/delete), rather than silently dropping them.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended
2. normalizeWhereCriteria tests not functional 📘 Rule violation ☼ Reliability ⭐ New
Description
This issue fix adds coverage in test/unit/util/orm-utils.test.ts instead of the functional test
suite (test/functional), which does not meet the checklist requirement for issue fixes. Keeping
the regression test in functional tests (with an issue reference comment) helps ensure the behavior
is covered through end-to-end library usage patterns.
Code

test/unit/util/orm-utils.test.ts[R274-335]

+    describe("normalizeWhereCriteria", () => {
+        it("uses the default throw behavior when options are omitted", () => {
+            expect(() =>
+                OrmUtils.normalizeWhereCriteria({ id: undefined }),
+            ).to.throw("Undefined value encountered in property 'id'")
+
+            expect(() =>
+                OrmUtils.normalizeWhereCriteria({ id: null }),
+            ).to.throw("Null value encountered in property 'id'")
+        })
+
+        it("applies defaults recursively to nested and array criteria", () => {
+            expect(() =>
+                OrmUtils.normalizeWhereCriteria({ user: { id: undefined } }),
+            ).to.throw("Undefined value encountered in property 'user.id'")
+
+            expect(() =>
+                OrmUtils.normalizeWhereCriteria([
+                    { id: 1 },
+                    { user: { id: null } },
+                ]),
+            ).to.throw("Null value encountered in property '1.user.id'")
+        })
+
+        it("preserves explicitly configured behavior", () => {
+            expect(
+                OrmUtils.normalizeWhereCriteria(
+                    { id: undefined, name: "Ada" },
+                    { undefined: "ignore" },
+                ),
+            ).to.deep.equal({ name: "Ada" })
+        })
+
+        it("preserves entity instances and arrays containing them", () => {
+            class User {
+                id = 1
+                parentId: number | null = null
+            }
+
+            const entity = new User()
+
+            expect(OrmUtils.normalizeWhereCriteria(entity)).to.equal(entity)
+            expect(OrmUtils.normalizeWhereCriteria([entity])).to.deep.equal([
+                entity,
+            ])
+        })
+
+        it("preserves __proto__ criteria without changing the result prototype", () => {
+            const criteria = JSON.parse(
+                '{"__proto__":{"admin":true},"id":1}',
+            )
+
+            const normalized = OrmUtils.normalizeWhereCriteria(
+                criteria,
+            ) as Record<string, any>
+
+            expect(Object.getPrototypeOf(normalized)).to.equal(null)
+            expect(Object.hasOwn(normalized, "__proto__")).to.equal(true)
+            expect(normalized.id).to.equal(1)
+            expect(normalized.__proto__.admin).to.equal(true)
+        })
+    })
Evidence
PR Compliance ID 3 requires issue-fix coverage to be added/updated in test/functional. The PR adds
new tests for normalizeWhereCriteria under test/unit/util/orm-utils.test.ts, so the fix is not
covered in the functional suite per the checklist.

Rule 3: Prefer functional tests over per-issue tests
test/unit/util/orm-utils.test.ts[274-335]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The regression coverage for this issue fix was added under `test/unit`, but the checklist requires issue fixes to live in the functional suite (`test/functional`) and include an issue reference comment when applicable.

## Issue Context
This PR is explicitly an issue fix (Closes #12578), and it adds a new `describe("normalizeWhereCriteria")` block under unit tests.

## Fix Focus Areas
- test/unit/util/orm-utils.test.ts[274-335]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. any cast in test 📘 Rule violation ⚙ Maintainability ⭐ New
Description
The added test uses an any-typed cast (as Record<string, any>), which introduces type-bypassing
noise and weakens type safety. This violates the checklist’s requirement to avoid any casts used
to bypass type issues.
Code

test/unit/util/orm-utils.test.ts[R326-329]

+            const normalized = OrmUtils.normalizeWhereCriteria(
+                criteria,
+            ) as Record<string, any>
+
Evidence
PR Compliance ID 4 forbids introducing AI-like noise such as any casts to bypass type checking.
The new test explicitly casts the normalized output to Record<string, any>.

Rule 4: Remove AI-generated noise
test/unit/util/orm-utils.test.ts[326-329]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
A new test uses `as Record<string, any>`, which is an explicit `any` cast to bypass typing.

## Issue Context
This appears to be used only to access and assert on the `"__proto__"` key of the normalized object.

## Fix Focus Areas
- test/unit/util/orm-utils.test.ts[326-334]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Results up to commit cff961b


🐞 Bugs (1) 📘 Rule violations (0) 📜 Skill insights (0)


Action required
1. __proto__ criteria injection 🐞 Bug ⛨ Security
Description
normalizeWhereCriteria() copies user-controlled keys into a fresh {} without filtering special
keys (e.g. __proto__), which can mutate the prototype of the normalized criteria object. With the
new options ??= {} change, this normalization now runs even when options are omitted, and a
crafted criteria can cause predicates to be lost (e.g. normalized object has no own keys), risking
unbounded update/delete WHERE generation.
Code

src/util/OrmUtils.ts[R665-669]

+        // Resolve omitted behavior once so the documented defaults below apply.
+        options ??= {}

        // multiple criteria are possible at the top level
        if (!path && Array.isArray(criteria)) {
Evidence
normalizeWhereCriteria now always resolves omitted options and then copies entries into a new object
via result[key] = ... without filtering special keys; assigning __proto__ can mutate the
prototype of result and remove expected own-properties. The codebase already skips __proto__ in
OrmUtils.merge(), indicating this is a known hazard, and query-builder predicate generation relies
on Object.keys(entity), so losing own keys can lead to missing predicates.

src/util/OrmUtils.ts[660-723]
src/util/OrmUtils.ts[633-642]
src/entity-manager/EntityManager.ts[861-881]
src/query-builder/QueryBuilder.ts[1386-1405]
src/query-builder/QueryBuilder.ts[1624-1687]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`OrmUtils.normalizeWhereCriteria()` builds a new plain object (`{}`) and assigns `result[key] = ...` for every key from user-provided criteria. If the input contains special keys like `"__proto__"`, this assignment can invoke the `__proto__` setter and change the prototype of `result`, potentially dropping own keys and/or causing downstream query building to behave unexpectedly (including generating a WHERE-less UPDATE/DELETE).

Because this PR changes behavior to always normalize when options are omitted (`options ??= {}`), this risk becomes reachable in the default configuration.

## Issue Context
TypeORM already treats `__proto__` as dangerous in similar object-copying code (see `OrmUtils.merge()`), but `normalizeWhereCriteria()` does not apply the same protection.

## Fix Focus Areas
- src/util/OrmUtils.ts[660-723]

### Suggested fix approach
Implement one (or both) of the following in `normalizeWhereCriteria()`:
1. Skip dangerous keys:
  - `if (key === "__proto__" || key === "constructor" || key === "prototype") continue`
2. Create the accumulator with a null prototype:
  - `const result: ObjectLiteral = Object.create(null)`

If you skip keys, consider whether you should throw a `TypeORMError` for these keys (safer for update/delete), rather than silently dropping them.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Qodo Logo

@belljinwo-jpg

Copy link
Copy Markdown
Author

Addressed the automated security finding in cf7b4ef: normalized criteria now use a null-prototype accumulator, so special keys such as `proto` remain own WHERE keys without invoking Object.prototype setters. Added a regression test using JSON-parsed criteria. Verification: TypeScript compilation passed; focused suite 19 passing; complete SQL.js suite 2,966 passing, 179 pending, 0 failing.

@belljinwo-jpg

Copy link
Copy Markdown
Author

Addressed both remaining review recommendations in ee6661a. The issue regression now lives in the functional write-path suite and covers default null/undefined behavior for EntityManager.update/delete. The prototype-key regression is also exercised through an actual update and verifies the row remains unchanged. The unit-only block and its `any` cast were removed. Verification: TypeScript compilation passed; focused functional suite 23 passing; complete SQL.js suite 2,964 passing, 179 pending, 0 failing.

@belljinwo-jpg

Copy link
Copy Markdown
Author

Addressed the new entity-criteria finding in 1e5829b. Entity instances retain historical passthrough only when invalidWhereValuesBehavior is omitted; explicitly configured behavior now validates them. Added functional coverage for entity-instance criteria under explicit throw configuration. Verification: TypeScript compilation passed; focused functional suite 24 passing; complete SQL.js suite 2,965 passing, 179 pending, 0 failing.

@naorpeled

Copy link
Copy Markdown
Member

Closing as this is a duplicate of #12579

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

linked-issue PR references an issue possible-duplicate PR may duplicate an existing open PR

Development

Successfully merging this pull request may close these issues.

OrmUtils.normalizeWhereCriteria() does not implement described default behaviour for invalidWhereValuesBehavior

2 participants