Skip to content

fix(security): validate limit() in Update/SoftDelete query builders - #12436

Merged
smith-xyz merged 1 commit into
typeorm:masterfrom
smith-xyz:fix/validate-limit-input
May 11, 2026
Merged

smith-xyz merged 1 commit into
typeorm:masterfrom
smith-xyz:fix/validate-limit-input

Conversation

@smith-xyz

Copy link
Copy Markdown
Collaborator

Description of change

  • Move normalizeNumber() from SelectQueryBuilder to base QueryBuilder
  • Add validateNumericInput() to base QueryBuilder to deduplicate the normalize + validate + throw pattern
  • Apply validation to limit() in UpdateQueryBuilder and SoftDeleteQueryBuilder
  • Consolidate SelectQueryBuilder's limit()/offset()/take()/skip() to use validateNumericInput()
  • Add tests for both builders

Pull-Request Checklist

  • Code is up-to-date with the master branch
  • This pull request links relevant issues as Fixes #00000
  • There are new or updated tests validating the change (tests/**.test.ts)
  • Documentation has been updated to reflect this change (docs/docs/**.md)

🛡️ Security fixes: Do not submit security fixes as public PRs — the diff exposes the vulnerability. Use GitHub Security Advisories instead.

@pkg-pr-new

pkg-pr-new Bot commented May 7, 2026 •

Copy link
Copy Markdown
  • typeorm-sql-js-example

    npm i https://pkg.pr.new/typeorm@12436
    

commit: 69ffef1

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

qodo-free-for-open-source-projects Bot commented May 7, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (3) 📘 Rule violations (2)

Grey Divider


Action required

1. Limit 0 ignored 🐞 Bug ≡ Correctness
Description
UpdateQueryBuilder/SoftDeleteQueryBuilder only apply LIMIT when expressionMap.limit is truthy
(if (limit)), so a normalized value of 0 is treated as “unset” and no LIMIT clause is emitted.
With this PR’s validateNumericInput() coercing inputs via Number(), JS callers passing "0" can
now unintentionally execute an unlimited update/soft-delete (and also bypass
LimitOnUpdateNotSupportedError on non-MySQL when limit is 0).
Code

src/query-builder/UpdateQueryBuilder.ts[R463-464]

   limit(limit?: number): this {
-        this.expressionMap.limit = limit
+        this.expressionMap.limit = this.validateNumericInput("limit", limit)
Evidence
This PR changes Update/SoftDelete .limit() to normalize inputs via validateNumericInput(), which
uses Number(...) conversion. The limit SQL generation still uses a truthy check (if (limit)), so
0 is treated as absent. Since QueryExpressionMap.limit is a number (0 is a valid number), this
can drop a user-provided limit after normalization (notably for string "0" inputs common from HTTP
query params).

src/query-builder/UpdateQueryBuilder.ts[463-466]
src/query-builder/SoftDeleteQueryBuilder.ts[430-433]
src/query-builder/QueryBuilder.ts[1726-1750]
src/query-builder/UpdateQueryBuilder.ts[796-810]
src/query-builder/SoftDeleteQueryBuilder.ts[598-610]
src/query-builder/QueryExpressionMap.ts[148-156]

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

## Issue description
`UpdateQueryBuilder.createLimitExpression()` and `SoftDeleteQueryBuilder.createLimitExpression()` use `if (limit)` to decide whether to emit a `LIMIT` clause. Because `0` is falsy, `limit(0)` is ignored. After this PR, `limit("0" as any)` can also normalize to numeric `0`, which is then ignored and results in an unbounded UPDATE/SOFT DELETE.
### Issue Context
- This PR intentionally normalizes user input through `Number(...)` via `validateNumericInput()`.
- `QueryExpressionMap.limit` is a `number | undefined`, so `0` is a valid value and should be handled explicitly.
### Fix Focus Areas
- src/query-builder/UpdateQueryBuilder.ts[796-810]
- src/query-builder/SoftDeleteQueryBuilder.ts[598-610]
- test/functional/query-builder/sql-injection/sql-injection.test.ts[360-422]
### Suggested fix
1. Replace `if (limit)` with an explicit presence check such as `if (limit !== undefined && limit !== null)` (or `typeof limit === "number"`) so `0` emits `LIMIT 0`.
2. Ensure the driver support check / `LimitOnUpdateNotSupportedError` path is still evaluated when `limit` is `0`.
3. Add regression tests for `limit(0)` and `limit("0" as any)` on UpdateQueryBuilder and SoftDeleteQueryBuilder to ensure LIMIT is not dropped.

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



Remediation recommended

2. Null leaks from validator 🐞 Bug ≡ Correctness ⭐ New
Description
validateNumericInput() can return null (via normalizeNumber()), despite its declared return
type being number | undefined, so callers can end up with `expressionMap.limit/offset/take/skip =
null without any error. Downstream logic often treats null` as “unset”, which can silently drop a
LIMIT/OFFSET/TABLE pagination constraint when null is passed at runtime (e.g., from JS or `as
any`).
Code

src/query-builder/QueryBuilder.ts[R1726-1750]

+    protected normalizeNumber(num: any) {
+        if (typeof num === "number" || num === undefined || num === null)
+            return num
+
+        return Number(num)
+    }
+
+    /**
+     * Normalizes and validates a numeric query parameter,
+     * throwing if the result is NaN.
+     *
+     * @param label
+     * @param num
+     */
+    protected validateNumericInput(
+        label: string,
+        num: number | undefined,
+    ): number | undefined {
+        const normalized = this.normalizeNumber(num)
+        if (normalized !== undefined && isNaN(normalized))
+            throw new TypeORMError(
+                `Provided "${label}" value is not a number. Please provide a numeric value.`,
+            )
+        return normalized
+    }
Evidence
normalizeNumber() explicitly returns null unchanged, and validateNumericInput() only guards
against undefined and NaN, so null passes through and is returned/assigned. Other parts of the
codebase already special-case null in expressionMap numeric fields, indicating it can appear at
runtime and needs consistent handling.

src/query-builder/QueryBuilder.ts[1726-1750]
src/query-builder/SelectQueryBuilder.ts[1915-1918]
src/query-builder/UpdateQueryBuilder.ts[796-811]
src/query-builder/SoftDeleteQueryBuilder.ts[598-610]

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

## Issue description
`validateNumericInput()` is declared to return `number | undefined`, but it can return `null` because `normalizeNumber()` returns `null` unchanged and `validateNumericInput()` doesn’t reject it. This violates the method contract and allows `expressionMap.*` numeric fields to become `null`, which downstream code treats differently from `undefined`.

## Issue Context
This helper is now shared across multiple builders (`SelectQueryBuilder`, `UpdateQueryBuilder`, `SoftDeleteQueryBuilder`), so the contract mismatch can propagate broadly.

## Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1726-1750]
- src/query-builder/UpdateQueryBuilder.ts[796-810]
- src/query-builder/SoftDeleteQueryBuilder.ts[598-610]

## Suggested fix
Pick one consistent policy and enforce it:
1) **Treat `null` as “unset”**: in `normalizeNumber`, convert `null` to `undefined` (or in `validateNumericInput`, explicitly `if (num === null) return undefined`).
2) **Reject `null`**: if `num === null`, throw a `TypeORMError` similar to the NaN path.
3) **Widen the contract** (least desirable): change return type to `number | undefined | null` and update all relevant downstream checks/types accordingly.

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


3. normalizeNumber() uses any 📘 Rule violation ⚙ Maintainability
Description
The newly added normalizeNumber(num: any) introduces an explicit any type, weakening type-safety
and contradicting the checklist requirement to avoid type-bypassing patterns. This increases the
chance of incorrect inputs flowing through without compile-time checks.
Code

src/query-builder/QueryBuilder.ts[R1726-1731]

+    protected normalizeNumber(num: any) {
+        if (typeof num === "number" || num === undefined || num === null)
+            return num
+
+        return Number(num)
+    }
Evidence
PR Compliance ID 4 prohibits introducing any usage that bypasses the type system; the new
normalizeNumber signature explicitly uses any in newly added production code.

Rule 4: Remove AI-generated noise
src/query-builder/QueryBuilder.ts[1726-1731]

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

## Issue description
`normalizeNumber()` was added with an explicit `any` parameter type (`normalizeNumber(num: any)`), which weakens type safety and violates the compliance guideline to avoid type-bypassing constructs.
## Issue Context
This method is used as a shared normalization helper in the base `QueryBuilder`, so its type signature influences multiple query builder APIs.
## Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1726-1731]
## Suggested direction
- Change `num: any` to `num: unknown`.
- Keep the existing runtime checks (`typeof num === "number"`, `undefined`, `null`) and only call `Number(num)` after narrowing, potentially restricting the accepted `unknown` values to those that safely convert (e.g., `string | number | null | undefined`).

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


4. limit() tests cast any 📘 Rule violation ⚙ Maintainability
Description
New tests pass malicious strings into limit() via as any, which is an explicit type-bypass cast
prohibited by the checklist. This can normalize unsafe typing practices in the codebase even if used
for testing.
Code

test/functional/query-builder/sql-injection/sql-injection.test.ts[R366-404]

+                    expect(() => {
+                        dataSource
+                            .createQueryBuilder()
+                            .update(Post)
+                            .set({ text: "updated" })
+                            .limit("1; DROP TABLE post" as any)
+                    }).to.throw(/not a number/)
+                }),
+            ))
+
+        it("should accept valid numeric limit", () =>
+            Promise.all(
+                dataSources.map(async (dataSource) => {
+                    if (!DriverUtils.isMySQLFamily(dataSource.driver)) return
+
+                    expect(() => {
+                        dataSource
+                            .createQueryBuilder()
+                            .update(Post)
+                            .set({ text: "updated" })
+                            .limit(10)
+                    }).to.not.throw()
+                }),
+            ))
+    })
+
+    describe("SoftDeleteQueryBuilder limit validation", () => {
+        it("should reject non-numeric limit", () =>
+            Promise.all(
+                dataSources.map(async (dataSource) => {
+                    if (!DriverUtils.isMySQLFamily(dataSource.driver)) return
+
+                    expect(() => {
+                        dataSource
+                            .createQueryBuilder()
+                            .softDelete()
+                            .from(Post)
+                            .limit("1; DROP TABLE post" as any)
+                    }).to.throw(/not a number/)
Evidence
PR Compliance ID 4 disallows introducing any-casts to bypass type checks; the added tests include
"1; DROP TABLE post" as any to force an invalid input into limit().

Rule 4: Remove AI-generated noise
test/functional/query-builder/sql-injection/sql-injection.test.ts[366-404]

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 new sql-injection tests use `as any` to pass a string into `limit()`. The compliance checklist flags newly introduced `any`-casts as type-bypass noise.
## Issue Context
These tests need to exercise runtime validation for invalid inputs without introducing `any` casts.
## Fix Focus Areas
- test/functional/query-builder/sql-injection/sql-injection.test.ts[366-404]
## Suggested direction
- Replace `as any` with a safer alternative like `as unknown as number` (avoids `any`), or refactor the test to call the underlying method through an untyped boundary (e.g., indexing) without using `any`.
- Keep the assertion that the call throws with `/not a number/`.

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



Advisory comments

5. Over-coercive numeric normalization 🐞 Bug ⛨ Security ⭐ New
Description
normalizeNumber() uses Number(num) for any non-number/undefined/null input, and
validateNumericInput() only rejects NaN, so some non-numeric runtime inputs can be silently
accepted after JS coercion. This weakens the intended “reject non-numeric” behavior for
LIMIT/OFFSET/TAKE/SKIP and can turn clearly invalid inputs into valid query modifiers without any
error.
Code

src/query-builder/QueryBuilder.ts[R1726-1749]

+    protected normalizeNumber(num: any) {
+        if (typeof num === "number" || num === undefined || num === null)
+            return num
+
+        return Number(num)
+    }
+
+    /**
+     * Normalizes and validates a numeric query parameter,
+     * throwing if the result is NaN.
+     *
+     * @param label
+     * @param num
+     */
+    protected validateNumericInput(
+        label: string,
+        num: number | undefined,
+    ): number | undefined {
+        const normalized = this.normalizeNumber(num)
+        if (normalized !== undefined && isNaN(normalized))
+            throw new TypeORMError(
+                `Provided "${label}" value is not a number. Please provide a numeric value.`,
+            )
+        return normalized
Evidence
The code path shows unconditional coercion via Number(num) for all non-number inputs, and the
validator only throws when the coerced result is NaN, meaning anything that coerces to a number will
be accepted.

src/query-builder/QueryBuilder.ts[1726-1749]

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 new shared normalization path accepts a very broad set of runtime inputs because it relies on `Number(...)` coercion and only checks for NaN. This can cause non-numeric values to be accepted as numeric query parameters.

## Issue Context
This helper is used for security-sensitive query modifiers (LIMIT/OFFSET/TAKE/SKIP) across multiple builders.

## Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1726-1750]

## Suggested fix
Make coercion strict and predictable:
- Allow only `number | undefined` (and optionally numeric `string`), and reject all other types.
- If supporting strings, require `typeof num === "string" && num.trim() !== ""` and then convert (and validate).
- Consider using `Number.isFinite(...)` and/or `Number.isInteger(...)` if these values must be safe for SQL LIMIT/OFFSET semantics.

ⓘ 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 69ffef1

Results up to commit bd29815


🐞 Bugs (1) 📘 Rule violations (2)


Action required
1. Limit 0 ignored 🐞 Bug ≡ Correctness
Description
UpdateQueryBuilder/SoftDeleteQueryBuilder only apply LIMIT when expressionMap.limit is truthy
(if (limit)), so a normalized value of 0 is treated as “unset” and no LIMIT clause is emitted.
With this PR’s validateNumericInput() coercing inputs via Number(), JS callers passing "0" can
now unintentionally execute an unlimited update/soft-delete (and also bypass
LimitOnUpdateNotSupportedError on non-MySQL when limit is 0).
Code

src/query-builder/UpdateQueryBuilder.ts[R463-464]

    limit(limit?: number): this {
-        this.expressionMap.limit = limit
+        this.expressionMap.limit = this.validateNumericInput("limit", limit)
Evidence
This PR changes Update/SoftDelete .limit() to normalize inputs via validateNumericInput(), which
uses Number(...) conversion. The limit SQL generation still uses a truthy check (if (limit)), so
0 is treated as absent. Since QueryExpressionMap.limit is a number (0 is a valid number), this
can drop a user-provided limit after normalization (notably for string "0" inputs common from HTTP
query params).

src/query-builder/UpdateQueryBuilder.ts[463-466]
src/query-builder/SoftDeleteQueryBuilder.ts[430-433]
src/query-builder/QueryBuilder.ts[1726-1750]
src/query-builder/UpdateQueryBuilder.ts[796-810]
src/query-builder/SoftDeleteQueryBuilder.ts[598-610]
src/query-builder/QueryExpressionMap.ts[148-156]

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

### Issue description
`UpdateQueryBuilder.createLimitExpression()` and `SoftDeleteQueryBuilder.createLimitExpression()` use `if (limit)` to decide whether to emit a `LIMIT` clause. Because `0` is falsy, `limit(0)` is ignored. After this PR, `limit("0" as any)` can also normalize to numeric `0`, which is then ignored and results in an unbounded UPDATE/SOFT DELETE.

### Issue Context
- This PR intentionally normalizes user input through `Number(...)` via `validateNumericInput()`.
- `QueryExpressionMap.limit` is a `number | undefined`, so `0` is a valid value and should be handled explicitly.

### Fix Focus Areas
- src/query-builder/UpdateQueryBuilder.ts[796-810]
- src/query-builder/SoftDeleteQueryBuilder.ts[598-610]
- test/functional/query-builder/sql-injection/sql-injection.test.ts[360-422]

### Suggested fix
1. Replace `if (limit)` with an explicit presence check such as `if (limit !== undefined && limit !== null)` (or `typeof limit === "number"`) so `0` emits `LIMIT 0`.
2. Ensure the driver support check / `LimitOnUpdateNotSupportedError` path is still evaluated when `limit` is `0`.
3. Add regression tests for `limit(0)` and `limit("0" as any)` on UpdateQueryBuilder and SoftDeleteQueryBuilder to ensure LIMIT is not dropped.

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



Remediation recommended
2. normalizeNumber() uses any 📘 Rule violation ⚙ Maintainability
Description
The newly added normalizeNumber(num: any) introduces an explicit any type, weakening type-safety
and contradicting the checklist requirement to avoid type-bypassing patterns. This increases the
chance of incorrect inputs flowing through without compile-time checks.
Code

src/query-builder/QueryBuilder.ts[R1726-1731]

+    protected normalizeNumber(num: any) {
+        if (typeof num === "number" || num === undefined || num === null)
+            return num
+
+        return Number(num)
+    }
Evidence
PR Compliance ID 4 prohibits introducing any usage that bypasses the type system; the new
normalizeNumber signature explicitly uses any in newly added production code.

Rule 4: Remove AI-generated noise
src/query-builder/QueryBuilder.ts[1726-1731]

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

## Issue description
`normalizeNumber()` was added with an explicit `any` parameter type (`normalizeNumber(num: any)`), which weakens type safety and violates the compliance guideline to avoid type-bypassing constructs.

## Issue Context
This method is used as a shared normalization helper in the base `QueryBuilder`, so its type signature influences multiple query builder APIs.

## Fix Focus Areas
- src/query-builder/QueryBuilder.ts[1726-1731]

## Suggested direction
- Change `num: any` to `num: unknown`.
- Keep the existing runtime checks (`typeof num === "number"`, `undefined`, `null`) and only call `Number(num)` after narrowing, potentially restricting the accepted `unknown` values to those that safely convert (e.g., `string | number | null | undefined`).

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


3. limit() tests cast any 📘 Rule violation ⚙ Maintainability
Description
New tests pass malicious strings into limit() via as any, which is an explicit type-bypass cast
prohibited by the checklist. This can normalize unsafe typing practices in the codebase even if used
for testing.
Code

test/functional/query-builder/sql-injection/sql-injection.test.ts[R366-404]

+                    expect(() => {
+                        dataSource
+                            .createQueryBuilder()
+                            .update(Post)
+                            .set({ text: "updated" })
+                            .limit("1; DROP TABLE post" as any)
+                    }).to.throw(/not a number/)
+                }),
+            ))
+
+        it("should accept valid numeric limit", () =>
+            Promise.all(
+                dataSources.map(async (dataSource) => {
+                    if (!DriverUtils.isMySQLFamily(dataSource.driver)) return
+
+                    expect(() => {
+                        dataSource
+                            .createQueryBuilder()
+                            .update(Post)
+                            .set({ text: "updated" })
+                            .limit(10)
+                    }).to.not.throw()
+                }),
+            ))
+    })
+
+    describe("SoftDeleteQueryBuilder limit validation", () => {
+        it("should reject non-numeric limit", () =>
+            Promise.all(
+                dataSources.map(async (dataSource) => {
+                    if (!DriverUtils.isMySQLFamily(dataSource.driver)) return
+
+                    expect(() => {
+                        dataSource
+                            .createQueryBuilder()
+                            .softDelete()
+                            .from(Post)
+                            .limit("1; DROP TABLE post" as any)
+                    }).to.throw(/not a number/)
Evidence
PR Compliance ID 4 disallows introducing any-casts to bypass type checks; the added tests include
"1; DROP TABLE post" as any to force an invalid input into limit().

Rule 4: Remove AI-generated noise
test/functional/query-builder/sql-injection/sql-injection.test.ts[366-404]

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 new sql-injection tests use `as any` to pass a string into `limit()`. The compliance checklist flags newly introduced `any`-casts as type-bypass noise.

## Issue Context
These tests need to exercise runtime validation for invalid inputs without introducing `any` casts.

## Fix Focus Areas
- test/functional/query-builder/sql-injection/sql-injection.test.ts[366-404]

## Suggested direction
- Replace `as any` with a safer alternative like `as unknown as number` (avoids `any`), or refactor the test to call the underlying method through an untyped boundary (e.g., indexing) without using `any`.
- Keep the assertion that the call throws with `/not a number/`.

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


Qodo Logo

@smith-xyz

smith-xyz commented May 7, 2026 •

Copy link
Copy Markdown
Collaborator Author

will skip qodo's review there - if you're passing in limit(0) ... please don't :)

its existing in any case, can be addressed in a separate PR

@smith-xyz
smith-xyz enabled auto-merge (squash) May 11, 2026 18:23
@smith-xyz
smith-xyz force-pushed the fix/validate-limit-input branch from bd29815 to 69ffef1 Compare May 11, 2026 18:24
@smith-xyz
smith-xyz merged commit 9284c16 into typeorm:master May 11, 2026
46 checks passed
@github-actions github-actions Bot added this to the 1.0 milestone May 11, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

3 participants