Skip to content

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

Merged
alumni merged 1 commit into
typeorm:v0.3from
smith-xyz:fix/validate-limit-input-v0.3
May 7, 2026
Merged

alumni merged 1 commit into
typeorm:v0.3from
smith-xyz:fix/validate-limit-input-v0.3

Conversation

@smith-xyz

Copy link
Copy Markdown
Collaborator

Description of change

Backport of #12436 to v0.3

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.

@smith-xyz
smith-xyz marked this pull request as draft May 7, 2026 18:07
@smith-xyz
smith-xyz changed the base branch from master to v0.3 May 7, 2026 18:08
@smith-xyz
smith-xyz marked this pull request as ready for review May 7, 2026 18:08
@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 (2) 📘 Rule violations (3)

Grey Divider


Action required

1. New test/github-issues tests 📘 Rule violation ⚙ Maintainability ⭐ New
Description
New tests were added under test/github-issues/10263 and test/github-issues/10999 instead of the
functional test suite. This conflicts with the guideline to keep issue fixes in test/functional
unless there is a clearly stated reason.
Code

test/github-issues/10263/issue-10263.test.ts[R1-37]

+import { expect } from "chai"
+import type { DataSource } from "../../../src"
+import {
+    closeTestingConnections,
+    createTestingConnections,
+} from "../../utils/test-utils"
+import { Space } from "./entity/Space"
+
+describe("github issues > #10263 closure table should inherit entity schema", () => {
+    let dataSources: DataSource[]
+
+    before(async () => {
+        dataSources = await createTestingConnections({
+            entities: [Space],
+            enabledDrivers: ["postgres"],
+            schemaCreate: false,
+            dropSchema: false,
+        })
+    })
+
+    after(() => closeTestingConnections(dataSources))
+
+    it("should set the same schema on the closure junction table as the parent entity", () => {
+        dataSources.forEach((dataSource) => {
+            const spaceMetadata = dataSource.getMetadata(Space)
+
+            expect(spaceMetadata.schema).to.equal("my_schema")
+            expect(spaceMetadata.closureJunctionTable).to.not.be.undefined
+            expect(spaceMetadata.closureJunctionTable.schema).to.equal(
+                "my_schema",
+            )
+            expect(spaceMetadata.closureJunctionTable.tablePath).to.contain(
+                "my_schema",
+            )
+        })
+    })
+})
Evidence
PR Compliance ID 3 requires issue-fix coverage to be added/updated in test/functional rather than
adding per-issue tests under test/github-issues without justification; this PR introduces new
per-issue tests in those directories.

Rule 3: Prefer functional tests over per-issue tests
test/github-issues/10263/issue-10263.test.ts[1-37]
test/github-issues/10999/issue-10999.test.ts[1-42]

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

## Issue description
New tests were added under `test/github-issues/...` rather than placing the coverage into `test/functional` (or documenting why a per-issue test is required).

## Issue Context
Compliance prefers functional tests for issue fixes to improve long-term maintainability.

## Fix Focus Areas
- test/github-issues/10263/issue-10263.test.ts[1-37]
- test/github-issues/10999/issue-10999.test.ts[1-42]

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


2. issue-10999 placeholder comment 📘 Rule violation ⚙ Maintainability ⭐ New
Description
The added line // you can add additional tests if needed is non-actionable boilerplate and
constitutes AI-like noise. This violates the requirement to avoid introducing extra/noisy comments.
Code

test/github-issues/10999/issue-10999.test.ts[41]

+    // you can add additional tests if needed
Evidence
PR Compliance ID 4 prohibits adding AI-generated noise and extra comments; the new placeholder
comment provides no value and should not be in merged code.

Rule 4: Remove AI-generated noise
test/github-issues/10999/issue-10999.test.ts[41-41]

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 non-actionable placeholder comment was added and should be removed.

## Issue Context
Compliance requires avoiding AI-like boilerplate/noise in code and tests.

## Fix Focus Areas
- test/github-issues/10999/issue-10999.test.ts[41-41]

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


3. Limit 0 dropped 🐞 Bug ≡ Correctness ⭐ New
Description
UpdateQueryBuilder.limit and SoftDeleteQueryBuilder.limit now normalize inputs via Number(), so a
caller-provided numeric string "0" becomes 0, but createLimitExpression uses a truthy check (if
(limit)) and omits LIMIT when the value is 0. This can turn an intended LIMIT 0 safety into an
unbounded UPDATE/SOFT DELETE affecting all matched rows.
Code

src/query-builder/UpdateQueryBuilder.ts[430]

+        this.expressionMap.limit = this.validateNumericInput("limit", limit)
Evidence
The PR changes UpdateQueryBuilder/SoftDeleteQueryBuilder to store a normalized numeric limit
(potentially 0) using validateNumericInput, which converts non-number inputs via Number(). Both
builders’ SQL generation still uses if (limit); when the normalized value is 0, the LIMIT clause
is skipped entirely.

src/query-builder/UpdateQueryBuilder.ts[426-432]
src/query-builder/SoftDeleteQueryBuilder.ts[395-401]
src/query-builder/QueryBuilder.ts[1742-1763]
src/query-builder/UpdateQueryBuilder.ts[755-773]
src/query-builder/SoftDeleteQueryBuilder.ts[557-572]

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` and `SoftDeleteQueryBuilder` now normalize `limit` using `validateNumericInput()`, which converts non-number inputs using `Number(...)`. This can produce a numeric `0` (e.g., caller passes the numeric string `"0"`).

Both builders generate SQL using `if (limit)` in `createLimitExpression()`, so `0` is treated as “not set” and the `LIMIT` clause is omitted, potentially leading to unbounded UPDATE / SOFT DELETE.

### Issue Context
This is especially risky because the new normalization makes it more likely that user input arrives as a real number (including `0`) rather than a truthy string.

### Fix Focus Areas
- src/query-builder/UpdateQueryBuilder.ts[758-773]
- src/query-builder/SoftDeleteQueryBuilder.ts[560-572]
- (optional for consistency) src/query-builder/UpdateQueryBuilder.ts[429-431]
- (optional for consistency) src/query-builder/SoftDeleteQueryBuilder.ts[398-400]

### Expected change
Update `createLimitExpression()` in both builders to treat `0` as a set limit, e.g.:
- `if (limit !== undefined && limit !== null)` instead of `if (limit)`

This preserves correct behavior for `limit=0` and avoids silently dropping LIMIT.

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


View more (2)
4. as any in injection tests 📘 Rule violation ⚙ Maintainability
Description
The new tests bypass typing by casting malicious string inputs to any when calling .limit().
This introduces prohibited type-safety bypass noise and can normalize using any instead of
exercising runtime validation via a typed-safe approach.
Code

test/other-issues/preventing-injection/preventing-injection.test.ts[R239-260]

+                    .limit("1; DROP TABLE post" as any)
+            }).to.throw(/not a number/)
+
+            expect(() => {
+                connection
+                    .createQueryBuilder()
+                    .update(Post)
+                    .set({ title: "test" })
+                    .limit(10)
+            }).to.not.throw()
+        })
+    })
+
+    it("should not allow non-numeric limit in SoftDeleteQueryBuilder", () => {
+        connections.forEach((connection) => {
+            expect(() => {
+                connection
+                    .createQueryBuilder()
+                    .softDelete()
+                    .from(Post)
+                    .limit("1; DROP TABLE post" as any)
+            }).to.throw(/not a number/)
Evidence
PR Compliance ID 4 forbids introducing any-casts to bypass type checks. The added tests explicitly
use "1; DROP TABLE post" as any in two new .limit(...) calls.

Rule 4: Remove AI-generated noise
test/other-issues/preventing-injection/preventing-injection.test.ts[239-240]
test/other-issues/preventing-injection/preventing-injection.test.ts[259-260]

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 tests use `as any` casts to pass invalid string values into `.limit()`, which violates the compliance rule against type-bypass noise.
## Issue Context
These tests can still validate runtime rejection of non-numeric limits without introducing `any` casts.
## Fix Focus Areas
- test/other-issues/preventing-injection/preventing-injection.test.ts[232-270]

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


5. Zero limit dropped 🐞 Bug ≡ Correctness
Description
UpdateQueryBuilder/SoftDeleteQueryBuilder now normalize limit via validateNumericInput(), so a
numeric string like "0" becomes the number 0. Their createLimitExpression() uses if (limit) and
will omit the LIMIT clause for 0, potentially turning an intended LIMIT 0 into an unbounded
update/soft-delete.
Code

src/query-builder/UpdateQueryBuilder.ts[R429-431]

   limit(limit?: number): this {
-        this.expressionMap.limit = limit
+        this.expressionMap.limit = this.validateNumericInput("limit", limit)
       return this
Evidence
validateNumericInput() calls normalizeNumber(), which converts non-number inputs using Number(...),
so "0" normalizes to 0. Both UpdateQueryBuilder and SoftDeleteQueryBuilder only append LIMIT when
limit is truthy, so a normalized 0 will not produce a LIMIT clause.

src/query-builder/QueryBuilder.ts[1742-1763]
src/query-builder/UpdateQueryBuilder.ts[758-773]
src/query-builder/SoftDeleteQueryBuilder.ts[560-572]

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

## Issue description
`createLimitExpression()` in both `UpdateQueryBuilder` and `SoftDeleteQueryBuilder` uses a truthiness check (`if (limit)`), which skips emitting `LIMIT` when the value is `0`. After this PR, `validateNumericInput()` normalizes numeric strings (e.g. "0") to `0`, making this bug easier to hit and potentially widening an intended no-op (`LIMIT 0`) into an unbounded UPDATE/SOFT DELETE.
### Issue Context
Other parts of the codebase (e.g. select pagination) treat `0` as a set value by checking `!== undefined && !== null` instead of truthiness.
### Fix Focus Areas
- src/query-builder/UpdateQueryBuilder.ts[758-773]
- src/query-builder/SoftDeleteQueryBuilder.ts[560-572]
- test/other-issues/preventing-injection/preventing-injection.test.ts[232-270]
### What to change
- Replace `if (limit)` with an explicit presence check like `if (limit !== undefined && limit !== null)` so `0` still emits `LIMIT 0`.
- Add/extend a test to cover `.limit("0" as any)` (and optionally `.limit(0)`) to ensure the LIMIT clause is not dropped (or at least that behavior is explicitly asserted for these builders).

ⓘ 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.

Qodo Logo

@alumni alumni changed the title Fix/validate limit input v0.3 fix(security): validate limit() in Update/SoftDelete query builders May 7, 2026
@alumni
alumni requested a review from michaelbromley May 7, 2026 18:15
@alumni

alumni commented May 7, 2026

Copy link
Copy Markdown
Collaborator

@michaelbromley let's publish 0.3.29 after this :)

@alumni
alumni merged commit 0d7991a into typeorm:v0.3 May 7, 2026
1 of 3 checks passed
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