Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/select-alias-prototype-pollution.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/db': patch
---

Fix prototype pollution via `select()` alias paths. Aliases were split on `.` and walked into the result object without sanitization, so a query like `select(() => ({ ['__proto__.polluted']: ... }))` (or any segment matching `__proto__`, `prototype`, or `constructor`) could mutate `Object.prototype`. The select compiler now rejects unsafe alias path segments with a new `UnsafeAliasPathError`. Fixes #1584.
10 changes: 10 additions & 0 deletions packages/db/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -442,6 +442,16 @@ export class QueryCompilationError extends TanStackDBError {
}
}

export class UnsafeAliasPathError extends QueryCompilationError {
constructor(segment: string) {
super(
`Unsafe alias path segment "${segment}" is not allowed in .select(). ` +
`Aliases must not contain "__proto__", "prototype", or "constructor".`,
)
this.name = `UnsafeAliasPathError`
}
}

export class DistinctRequiresSelectError extends QueryCompilationError {
constructor() {
super(`DISTINCT requires a SELECT clause.`)
Expand Down
20 changes: 19 additions & 1 deletion packages/db/src/query/compiler/select.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@ import {
Value as ValClass,
isExpressionLike,
} from '../ir.js'
import { AggregateNotSupportedError } from '../../errors.js'
import {
AggregateNotSupportedError,
UnsafeAliasPathError,
} from '../../errors.js'
import { compileExpression, isCaseWhenConditionTrue } from './evaluators.js'
import { containsAggregate } from './group-by.js'
import type {
Expand Down Expand Up @@ -39,6 +42,16 @@ function unwrapVal(input: any): any {
return input
}

const UNSAFE_ALIAS_SEGMENTS = new Set([`__proto__`, `prototype`, `constructor`])

function assertSafeAliasSegments(segments: ReadonlyArray<string>): void {
for (const seg of segments) {
if (UNSAFE_ALIAS_SEGMENTS.has(seg)) {
throw new UnsafeAliasPathError(seg)
}
}
}

/**
* Processes a merge operation by merging source values into the target path
*/
Expand All @@ -47,6 +60,7 @@ function processMerge(
namespacedRow: NamespacedRow,
selectResults: Record<string, any>,
): void {
assertSafeAliasSegments(op.targetPath)
const value = op.source(namespacedRow)
if (value && typeof value === `object`) {
// Ensure target object exists
Expand Down Expand Up @@ -89,6 +103,7 @@ function processNonMergeOp(
): void {
// Support nested alias paths like "meta.author.name"
const path = op.alias.split(`.`)
assertSafeAliasSegments(path)
if (path.length === 1) {
selectResults[op.alias] = op.compiled(namespacedRow)
} else {
Expand Down Expand Up @@ -283,6 +298,9 @@ function addFromObject(
ops: Array<SelectOp>,
) {
for (const [key, value] of Object.entries(obj)) {
if (!key.startsWith(`__SPREAD_SENTINEL__`)) {
assertSafeAliasSegments(key.split(`.`))
}
if (key.startsWith(`__SPREAD_SENTINEL__`)) {
const rest = key.slice(`__SPREAD_SENTINEL__`.length)
const splitIndex = rest.lastIndexOf(`__`)
Expand Down
60 changes: 60 additions & 0 deletions packages/db/tests/query/select-prototype-pollution.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { describe, expect, it } from 'vitest'
import { createCollection } from '../../src/collection/index.js'
import { queryOnce } from '../../src/query/index.js'
import { UnsafeAliasPathError } from '../../src/errors.js'
import { mockSyncCollectionOptions } from '../utils.js'

type User = { id: number; name: string }

const sampleUsers: Array<User> = [
{ id: 1, name: `Alice` },
{ id: 2, name: `Bob` },
]

function makeCollection() {
return createCollection(
mockSyncCollectionOptions<User>({
id: `proto-pollution-users`,
getKey: (u) => u.id,
initialData: sampleUsers,
}),
)
}

function prototypeHasOwn(prop: string): boolean {
return Object.prototype.hasOwnProperty.call(Object.prototype, prop)
}

describe(`select() alias prototype pollution (issue #1584)`, () => {
it(`should reject __proto__ in alias path and not pollute Object.prototype`, async () => {
const users = makeCollection()
const hadBefore = prototypeHasOwn(`polluted`)

await expect(
queryOnce((q) =>
q.from({ user: users }).select(({ user }) => ({
[`__proto__.polluted`]: user.name,
})),
),
).rejects.toThrow(UnsafeAliasPathError)

Comment thread
coderabbitai[bot] marked this conversation as resolved.
expect(prototypeHasOwn(`polluted`)).toBe(hadBefore)
expect(prototypeHasOwn(`polluted`)).toBe(false)
})

it(`should reject constructor in alias path and not pollute Object.prototype`, async () => {
const users = makeCollection()
const hadBefore = prototypeHasOwn(`polluted`)

await expect(
queryOnce((q) =>
q.from({ user: users }).select(({ user }) => ({
[`constructor.prototype.polluted`]: user.name,
})),
),
).rejects.toThrow(UnsafeAliasPathError)

expect(prototypeHasOwn(`polluted`)).toBe(hadBefore)
expect(prototypeHasOwn(`polluted`)).toBe(false)
})
})
Loading