From 03639b958957ae2144cf3a666ce2be9a584a0806 Mon Sep 17 00:00:00 2001 From: Daniel Salazar Date: Thu, 19 Nov 2026 13:48:09 -0700 Subject: [PATCH] fix(db): bound parameters must be scalars; text lookups match only strings (#4706) Every database client refuses an array, object or function parameter with a 400 before it reaches the driver. Strings, numbers, bigints, booleans, null, dates and buffers still bind. tryHardReadAll checks the whole batch first. Store lookups on text columns return null for a value that is not a string: users (only id takes a number), apps (also existsByName and uidExistsOnPrimary), fsentries by uuid, subdomains by uuid, sessions by uuid, shares and notifications by uid, notifications by send key. OIDC links still look up a numeric provider sub. --- .../clients/database/DatabaseClient.test.ts | 12 ++++ .../clients/database/DatabaseClient.ts | 4 ++ .../database/MySQLDatabaseClient.test.ts | 55 +++++++++++++++++ .../clients/database/MySQLDatabaseClient.ts | 7 +++ .../database/PostgresDatabaseClient.test.ts | 18 ++++++ .../database/PostgresDatabaseClient.ts | 2 + .../database/SqliteDatabaseClient.test.ts | 25 ++++++++ .../clients/database/SqliteDatabaseClient.ts | 14 +++-- .../clients/database/bindableParams.ts | 59 +++++++++++++++++++ src/backend/stores/app/AppStore.js | 11 +++- src/backend/stores/app/AppStore.test.js | 24 ++++++++ src/backend/stores/fs/FSEntryStore.test.ts | 23 ++++++++ src/backend/stores/fs/FSEntryStore.ts | 2 + .../stores/notification/NotificationStore.js | 2 + .../notification/NotificationStore.test.js | 23 ++++++++ src/backend/stores/oidc/OIDCStore.js | 3 + src/backend/stores/oidc/OIDCStore.test.ts | 21 +++++++ src/backend/stores/session/SessionStore.js | 2 +- .../stores/session/SessionStore.test.ts | 22 +++++++ src/backend/stores/share/ShareStore.js | 1 + src/backend/stores/share/ShareStore.test.js | 22 +++++++ .../stores/subdomain/SubdomainStore.test.ts | 22 +++++++ .../stores/subdomain/SubdomainStore.ts | 1 + src/backend/stores/user/UserStore.test.ts | 20 ++++++- src/backend/stores/user/UserStore.ts | 10 +++- 25 files changed, 393 insertions(+), 12 deletions(-) create mode 100644 src/backend/clients/database/bindableParams.ts diff --git a/src/backend/clients/database/DatabaseClient.test.ts b/src/backend/clients/database/DatabaseClient.test.ts index 4b10f7aee..01156544a 100644 --- a/src/backend/clients/database/DatabaseClient.test.ts +++ b/src/backend/clients/database/DatabaseClient.test.ts @@ -192,6 +192,18 @@ describe('AbstractDatabaseClient — replica-aware reads', () => { }, ); + it('refuses a batch with an array parameter before any read', async () => { + const client = new FixtureDatabaseClient([{ id: 1 }], [{ id: 2 }]); + await expect( + client.tryHardReadAll([ + { query: 'SELECT 1', params: ['a'] }, + { query: 'SELECT 2', params: [['a', 'b']] }, + ]), + ).rejects.toMatchObject({ statusCode: 400 }); + expect(client.reads).toEqual([]); + expect(client.preads).toEqual([]); + }); + it('issues one read per query when there is no replica', async () => { const client = new FixtureDatabaseClient([], [{ id: 2 }], false); expect(await client.tryHardReadAll(reads)).toEqual([[], []]); diff --git a/src/backend/clients/database/DatabaseClient.ts b/src/backend/clients/database/DatabaseClient.ts index 3aa933906..39fb501f0 100644 --- a/src/backend/clients/database/DatabaseClient.ts +++ b/src/backend/clients/database/DatabaseClient.ts @@ -22,6 +22,7 @@ import { isAbsolute, resolve as resolvePath } from 'path'; import type { IConfig } from '../../types'; import { Span } from '../../util/span.js'; import { PuterClient } from '../types'; +import { assertBindableParams } from './bindableParams.js'; import { compareMigrationFilenames } from './migrationFilenames.js'; export interface WriteResult { @@ -179,6 +180,9 @@ export class AbstractDatabaseClient extends PuterClient { async tryHardReadAll( reads: { query: string; params?: unknown[] }[], ): Promise[][]> { + // A failed replica read counts as a miss below, so refuse up front. + for (const { query, params } of reads) + assertBindableParams(query, params); if (!this.hasReadReplica()) { return Promise.all( reads.map(({ query, params = [] }) => this.read(query, params)), diff --git a/src/backend/clients/database/MySQLDatabaseClient.test.ts b/src/backend/clients/database/MySQLDatabaseClient.test.ts index 6b20e04e0..9752b44ee 100644 --- a/src/backend/clients/database/MySQLDatabaseClient.test.ts +++ b/src/backend/clients/database/MySQLDatabaseClient.test.ts @@ -615,6 +615,61 @@ describe('MySQLDatabaseClient — query interface', () => { }); }); +describe('MySQLDatabaseClient — non-scalar parameters', () => { + // The driver formats in the client: an array becomes a value list and an + // object becomes `col = val` pairs, so neither may reach it. + it.each([ + ['an array', ['a', 'b']], + ['an object', { username: 1 }], + ['a function', () => 1], + ])('refuses %s with a 400 before any query is sent', async (_, value) => { + const client = await startClient({ replica: { host: 'replica' } }); + const sql = 'SELECT * FROM `user` WHERE `username` = ?'; + for (const call of [ + () => client.read(sql, [value]), + () => client.pread(sql, [value]), + () => client.tryHardRead(sql, [value]), + () => client.write('DELETE FROM `user` WHERE `uuid` = ?', [value]), + () => + client.batchWrite([ + { statement: 'UPDATE `user` SET `x` = ?', values: [1] }, + { + statement: 'DELETE FROM `user` WHERE `uuid` = ?', + values: [value], + }, + ]), + ]) { + await expect(call()).rejects.toMatchObject({ statusCode: 400 }); + } + for (const pool of createdPools) { + expect(pool.calls).toEqual([]); + expect(pool.connections).toEqual([]); + } + }); + + it('binds scalars, null, dates and buffers', async () => { + const client = await startClient(); + const pool = createdPools[0]; + pool.respond = () => rowSets([]); + const values = [ + 'a', + 1, + 10n, + true, + null, + undefined, + new Date(0), + Buffer.from('x'), + ]; + + await client.read( + `SELECT 1 WHERE ${values.map(() => '?').join(' AND ')}`, + values, + ); + expect(pool.calls[0].values).toEqual(values); + }); +}); + describe('MySQLDatabaseClient — batchWrite transactions', () => { it('runs every statement on one connection inside a transaction', async () => { const client = await startClient(); diff --git a/src/backend/clients/database/MySQLDatabaseClient.ts b/src/backend/clients/database/MySQLDatabaseClient.ts index 3f9074e57..230b55a79 100644 --- a/src/backend/clients/database/MySQLDatabaseClient.ts +++ b/src/backend/clients/database/MySQLDatabaseClient.ts @@ -20,6 +20,7 @@ import { metrics } from '@opentelemetry/api'; import { createPool, ExecuteValues, type Pool } from 'mysql2'; import { Span } from '../../util/span.js'; +import { assertBindableParams } from './bindableParams.js'; import { AbstractDatabaseClient, type WriteResult } from './DatabaseClient'; import { SQLBatcher } from './SQLBatcher.js'; import { isRetriableError } from './retriableErrors.js'; @@ -134,6 +135,7 @@ export class MySQLDatabaseClient extends AbstractDatabaseClient { query: string, params: unknown[] = [], ): Promise[]> { + assertBindableParams(query, params); let result; try { result = await this.dbReplica.execute(query, params); @@ -160,6 +162,7 @@ export class MySQLDatabaseClient extends AbstractDatabaseClient { query: string, params: unknown[] = [], ): Promise[]> { + assertBindableParams(query, params); const result = await this.dbPrimaryRead.execute(query, params); if (!result) return []; return (result[0] as Record[]) ?? []; @@ -170,6 +173,7 @@ export class MySQLDatabaseClient extends AbstractDatabaseClient { query: string, params: unknown[] = [], ): Promise { + assertBindableParams(query, params); const result = await this.db.execute(query, params); const header = result[0] as { insertId?: number; @@ -192,6 +196,8 @@ export class MySQLDatabaseClient extends AbstractDatabaseClient { entries: { statement: string; values: unknown[] }[], ): Promise { if (entries.length === 0) return; + for (const { statement, values } of entries) + assertBindableParams(statement, values); // Bypass the SQLBatcher: it coalesces queries from unrelated callers // into a single multi-statement string, which is incompatible with // wrapping a transaction around just *our* statements. Acquire a @@ -223,6 +229,7 @@ export class MySQLDatabaseClient extends AbstractDatabaseClient { query: string, params: unknown[], ): Promise[]> { + assertBindableParams(query, params); const result = await this.dbReplica.execute(query, params); if (!result) return []; return (result[0] as Record[]) ?? []; diff --git a/src/backend/clients/database/PostgresDatabaseClient.test.ts b/src/backend/clients/database/PostgresDatabaseClient.test.ts index 380a47691..b47970cc6 100644 --- a/src/backend/clients/database/PostgresDatabaseClient.test.ts +++ b/src/backend/clients/database/PostgresDatabaseClient.test.ts @@ -325,6 +325,24 @@ describe('PostgresDatabaseClient', () => { ).resolves.toEqual([{ created_at: 3 }]); }); + it('refuses an array or object parameter with a 400', async () => { + const pool = new RecordingPool(); + const client = new PostgresDatabaseClient(postgresConfig(), () => pool); + await client.onServerStart(); + const before = pool.calls.length; + const query = 'SELECT `name` FROM `apps` WHERE `uid` = ?'; + + for (const value of [['a', 'b'], { uid: 'a' }]) { + await expect(client.read(query, [value])).rejects.toMatchObject({ + statusCode: 400, + }); + await expect(client.write(query, [value])).rejects.toMatchObject({ + statusCode: 400, + }); + } + expect(pool.calls.length).toBe(before); + }); + it('runs batch writes in order and commits', async () => { const conn = new RecordingPoolClient(); const client = new PostgresDatabaseClient( diff --git a/src/backend/clients/database/PostgresDatabaseClient.ts b/src/backend/clients/database/PostgresDatabaseClient.ts index 235db418c..0c4ec11dc 100644 --- a/src/backend/clients/database/PostgresDatabaseClient.ts +++ b/src/backend/clients/database/PostgresDatabaseClient.ts @@ -25,6 +25,7 @@ import { type BatchEntry, type WriteResult, } from './DatabaseClient'; +import { assertBindableParams } from './bindableParams.js'; import { preparePostgresSql } from './preparePostgresSql.js'; import { splitPostgresStatements } from './splitPostgresStatements.js'; import type { IConfig } from '../../types'; @@ -283,6 +284,7 @@ export class PostgresDatabaseClient extends AbstractDatabaseClient { query: string, params: unknown[] = [], ): Promise { + assertBindableParams(query, params); let text = this.preparedSql.get(query); if (text === undefined) { text = preparePostgresSql(query).text; diff --git a/src/backend/clients/database/SqliteDatabaseClient.test.ts b/src/backend/clients/database/SqliteDatabaseClient.test.ts index bd0f338c9..f5db7953d 100644 --- a/src/backend/clients/database/SqliteDatabaseClient.test.ts +++ b/src/backend/clients/database/SqliteDatabaseClient.test.ts @@ -1211,6 +1211,31 @@ describe('SqliteDatabaseClient — query interface', () => { ); }); + it('refuses an array or object parameter with a 400', async () => { + await client.write('INSERT INTO `widget` (`name`) VALUES (?)', ['a']); + for (const value of [['a'], { name: 'a' }]) { + await expect( + client.read('SELECT * FROM `widget` WHERE `name` = ?', [ + value, + ]), + ).rejects.toMatchObject({ statusCode: 400 }); + await expect( + client.write('DELETE FROM `widget` WHERE `name` = ?', [value]), + ).rejects.toMatchObject({ statusCode: 400 }); + await expect( + client.batchWrite([ + { + statement: 'DELETE FROM `widget` WHERE `name` = ?', + values: [value], + }, + ]), + ).rejects.toMatchObject({ statusCode: 400 }); + } + expect(await client.read('SELECT `name` FROM `widget`')).toEqual([ + { name: 'a' }, + ]); + }); + it('closes the database on shutdown', async () => { const closable = await bootClient(); closable.onServerShutdown(); diff --git a/src/backend/clients/database/SqliteDatabaseClient.ts b/src/backend/clients/database/SqliteDatabaseClient.ts index 54d2af100..6b9dc3ad1 100644 --- a/src/backend/clients/database/SqliteDatabaseClient.ts +++ b/src/backend/clients/database/SqliteDatabaseClient.ts @@ -23,6 +23,7 @@ import { createContext, runInContext } from 'vm'; import type { IConfig } from '../../types'; import { BoundedTtlMap } from '../../util/boundedTtlMap.js'; import { Span } from '../../util/span.js'; +import { assertBindableParams } from './bindableParams.js'; import { AbstractDatabaseClient, type WriteResult } from './DatabaseClient'; const MIGRATIONS_DIR = resolve(__dirname, './migrations/sqlite'); @@ -195,7 +196,7 @@ export class SqliteDatabaseClient extends AbstractDatabaseClient { params: unknown[] = [], ): Promise[]> { return this.prepare(query).all( - ...this.transformParams(params), + ...this.transformParams(query, params), ) as Record[]; } @@ -212,7 +213,9 @@ export class SqliteDatabaseClient extends AbstractDatabaseClient { query: string, params: unknown[] = [], ): Promise { - const info = this.prepare(query).run(...this.transformParams(params)); + const info = this.prepare(query).run( + ...this.transformParams(query, params), + ); return { insertId: info.lastInsertRowid, @@ -232,7 +235,9 @@ export class SqliteDatabaseClient extends AbstractDatabaseClient { ): Promise { this.db.transaction(() => { for (const { statement, values } of entries) { - this.prepare(statement).run(...this.transformParams(values)); + this.prepare(statement).run( + ...this.transformParams(statement, values), + ); } })(); } @@ -254,7 +259,8 @@ export class SqliteDatabaseClient extends AbstractDatabaseClient { return query.replace(/now\(\)/gi, "datetime('now')"); } - private transformParams(params: unknown[]): unknown[] { + private transformParams(query: string, params: unknown[]): unknown[] { + assertBindableParams(query, params); return params.map((p) => { if (typeof p === 'boolean') return p ? 1 : 0; return p; diff --git a/src/backend/clients/database/bindableParams.ts b/src/backend/clients/database/bindableParams.ts new file mode 100644 index 000000000..027bc342d --- /dev/null +++ b/src/backend/clients/database/bindableParams.ts @@ -0,0 +1,59 @@ +/* + * Copyright (C) 2024-present Puter Technologies Inc. + * + * This file is part of Puter. + * + * Puter is free software: you can redistribute it and/or modify + * it under the terms of the GNU Affero General Public License as published + * by the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU Affero General Public License for more details. + * + * You should have received a copy of the GNU Affero General Public License + * along with this program. If not, see . + */ + +import { HttpError } from '../../core/http/HttpError.js'; + +const isBindable = (value: unknown): boolean => { + if (value === null || value === undefined) return true; + switch (typeof value) { + case 'string': + case 'number': + case 'bigint': + case 'boolean': + return true; + case 'object': + // Buffer is a Uint8Array. + return value instanceof Date || value instanceof Uint8Array; + default: + return false; + } +}; + +/** + * Refuses a bound value that isn't a scalar. mysql formats queries in the + * client and expands an array into a value list and an object into `col = val` + * pairs, so a request value of the wrong shape would change the statement + * instead of failing to match. `IN` lists bind one `?` per item. + */ +export const assertBindableParams = ( + statement: string, + params: readonly unknown[] | undefined, +): void => { + if (!params) return; + for (const value of params) { + if (isBindable(value)) continue; + console.warn( + `[db] refused a ${Array.isArray(value) ? 'array' : typeof value} parameter:`, + statement.slice(0, 200), + ); + throw new HttpError(400, 'Invalid parameter.', { + legacyCode: 'bad_request', + }); + } +}; diff --git a/src/backend/stores/app/AppStore.js b/src/backend/stores/app/AppStore.js index 3452f28fb..6f6e1b4fe 100644 --- a/src/backend/stores/app/AppStore.js +++ b/src/backend/stores/app/AppStore.js @@ -274,7 +274,7 @@ export class AppStore extends PuterStore { * extensions. */ async uidExistsOnPrimary(uid) { - if (!uid) return false; + if (!uid || typeof uid !== 'string') return false; const rows = await this.clients.db.pread( 'SELECT `id` FROM `apps` WHERE `uid` = ? LIMIT 1', [uid], @@ -352,6 +352,7 @@ export class AppStore extends PuterStore { } async existsByName(name) { + if (typeof name !== 'string') return false; const rows = await this.clients.db.read( 'SELECT `id` FROM `apps` WHERE `name` = ? LIMIT 1', [name], @@ -1276,7 +1277,13 @@ export class AppStore extends PuterStore { // -- Internals ---------------------------------------------------- async #getByProperty(prop, value) { - if (value === undefined || value === null) return null; + // A text column compared with a number casts the column, so only `id` + // takes a number. + if ( + typeof value !== 'string' && + !(prop === 'id' && typeof value === 'number') + ) + return null; return this.#cache.get( this.#cache.key(prop, value), async (primary) => { diff --git a/src/backend/stores/app/AppStore.test.js b/src/backend/stores/app/AppStore.test.js index f826c0b2b..7e1241d41 100644 --- a/src/backend/stores/app/AppStore.test.js +++ b/src/backend/stores/app/AppStore.test.js @@ -342,6 +342,30 @@ describe('AppStore batched lookups', () => { expect((await appStore.getByUids(null)).size).toBe(0); }); + it('text lookups match no row for a value that is not a string', async () => { + const a = await createApp('Alpha'); + // MySQL would cast the column for a number, so none may reach it. + const db = server.clients.db; + const reads = [ + vi.spyOn(db, 'read'), + vi.spyOn(db, 'pread'), + vi.spyOn(db, 'tryHardRead'), + ]; + for (const value of [0, 1, true, ['x'], { uid: a.uid }]) { + expect(await appStore.getByUid(value)).toBeNull(); + expect(await appStore.getByName(value)).toBeNull(); + expect(await appStore.resolveApp(value)).toBeNull(); + expect(await appStore.existsByName(value)).toBe(false); + expect(await appStore.uidExistsOnPrimary(value)).toBe(false); + } + for (const spy of reads) { + expect(spy).not.toHaveBeenCalled(); + spy.mockRestore(); + } + expect((await appStore.getById(a.id))?.uid).toBe(a.uid); + expect((await appStore.getByUid(a.uid))?.id).toBe(a.id); + }); + it('getByIds still resolves id-keyed lookups off the shared engine', async () => { const a = await createApp('Alpha'); diff --git a/src/backend/stores/fs/FSEntryStore.test.ts b/src/backend/stores/fs/FSEntryStore.test.ts index 5e8be9c7e..106e61ecc 100644 --- a/src/backend/stores/fs/FSEntryStore.test.ts +++ b/src/backend/stores/fs/FSEntryStore.test.ts @@ -4538,3 +4538,26 @@ describe('FSEntryStore lineage backfill under a lenient collation', () => { ); }); }); + +describe('FSEntryStore lookups by a value that is not a string', () => { + let lookupServer: PuterServer; + + beforeAll(async () => { + lookupServer = await setupTestServer(); + }); + + afterAll(async () => { + await lookupServer?.shutdown(); + }); + + it('match no row', async () => { + const stores = lookupServer.stores; + for (const value of [0, 1, true, ['x'], { uid: 'x' }]) { + for (const row of [ + await stores.fsEntry.getEntryByUuid(value as never), + await stores.fsEntry.getEntryByUuidFromPrimary(value as never), + ]) + expect(row).toBeNull(); + } + }); +}); diff --git a/src/backend/stores/fs/FSEntryStore.ts b/src/backend/stores/fs/FSEntryStore.ts index d968740a1..166197c0b 100644 --- a/src/backend/stores/fs/FSEntryStore.ts +++ b/src/backend/stores/fs/FSEntryStore.ts @@ -1652,11 +1652,13 @@ export class FSEntryStore extends PuterStore { } async getEntryByUuid(uuid: string): Promise { + if (typeof uuid !== 'string') return null; return this.#getEntryBy('uuid', uuid); } /** Uncached primary read, for decisions a stale row must not make. */ async getEntryByUuidFromPrimary(uuid: string): Promise { + if (typeof uuid !== 'string') return null; const rows = (await this.clients.db.pread( `SELECT ${this.#selectFsentriesColumns()} FROM fsentries WHERE uuid = ? LIMIT 1`, [uuid], diff --git a/src/backend/stores/notification/NotificationStore.js b/src/backend/stores/notification/NotificationStore.js index 9aca8e0d8..ad0a8f260 100644 --- a/src/backend/stores/notification/NotificationStore.js +++ b/src/backend/stores/notification/NotificationStore.js @@ -120,6 +120,7 @@ export class NotificationStore extends PuterStore { * @param {{ userId?: number; primary?: boolean }} [opts] */ async getByUid(uid, { userId, primary = false } = {}) { + if (typeof uid !== 'string') return null; const where = userId !== undefined ? 'WHERE `uid` = ? AND `user_id` = ?' @@ -139,6 +140,7 @@ export class NotificationStore extends PuterStore { * @param {string} sendKey */ async getBySendKey(sendKey) { + if (typeof sendKey !== 'string') return null; const rows = await this.clients.db.pread( 'SELECT * FROM `notification` WHERE `send_key` = ? LIMIT 1', [sendKey], diff --git a/src/backend/stores/notification/NotificationStore.test.js b/src/backend/stores/notification/NotificationStore.test.js index 83dd1510b..367119044 100644 --- a/src/backend/stores/notification/NotificationStore.test.js +++ b/src/backend/stores/notification/NotificationStore.test.js @@ -713,3 +713,26 @@ describe('NotificationStore', () => { expect(await store.getByUid(n.uid)).toBeNull(); }); }); + +describe('NotificationStore lookups by a value that is not a string', () => { + let lookupServer; + + beforeAll(async () => { + lookupServer = await setupTestServer(); + }); + + afterAll(async () => { + await lookupServer?.shutdown(); + }); + + it('match no row', async () => { + const stores = lookupServer.stores; + for (const value of [0, 1, true, ['x'], { uid: 'x' }]) { + for (const row of [ + await stores.notification.getByUid(value), + await stores.notification.getBySendKey(value), + ]) + expect(row).toBeNull(); + } + }); +}); diff --git a/src/backend/stores/oidc/OIDCStore.js b/src/backend/stores/oidc/OIDCStore.js index 5ab6bcd93..06660f211 100644 --- a/src/backend/stores/oidc/OIDCStore.js +++ b/src/backend/stores/oidc/OIDCStore.js @@ -32,6 +32,9 @@ export class OIDCStore extends PuterStore { /** Pass `primary` when the row may be newer than the replica. */ async getByProviderSub(provider, providerSub, { primary = false } = {}) { + // Some providers send a numeric `sub`, and links were stored from it. + if (typeof providerSub !== 'string' && typeof providerSub !== 'number') + return null; // Ordered so a sub that predates the UNIQUE index (two callbacks for the // same new identity used to be able to both insert) always resolves to // the same link, instead of bouncing the user between two accounts. diff --git a/src/backend/stores/oidc/OIDCStore.test.ts b/src/backend/stores/oidc/OIDCStore.test.ts index d75ae05fe..64196926a 100644 --- a/src/backend/stores/oidc/OIDCStore.test.ts +++ b/src/backend/stores/oidc/OIDCStore.test.ts @@ -42,6 +42,27 @@ const createStore = (rows: readonly OidcRow[]) => { }; describe('OIDCStore', () => { + it('looks up a string or numeric sub and refuses other shapes', async () => { + const row = { user_id: 1, provider: 'p', provider_sub: '42' }; + const { db, store } = createStore([row]); + + await expect( + store.getByProviderSub('p', 42, { primary: true }), + ).resolves.toEqual(row); + expect(db.pread).toHaveBeenLastCalledWith(expect.any(String), [ + 'p', + 42, + ]); + + db.pread.mockClear(); + for (const sub of [true, ['42'], { sub: '42' }, null]) { + await expect( + store.getByProviderSub('p', sub, { primary: true }), + ).resolves.toBeNull(); + } + expect(db.pread).not.toHaveBeenCalled(); + }); + it('treats a Postgres unique violation as idempotent for an existing same-user link', async () => { const { db, store } = createStore([ { diff --git a/src/backend/stores/session/SessionStore.js b/src/backend/stores/session/SessionStore.js index fe956dd17..9ec6cb915 100644 --- a/src/backend/stores/session/SessionStore.js +++ b/src/backend/stores/session/SessionStore.js @@ -162,7 +162,7 @@ export class SessionStore extends PuterStore { } async getByUuidAny(uuid) { - if (!uuid) return null; + if (!uuid || typeof uuid !== 'string') return null; const cached = await this.#readCache(uuid); if (cached) return cached; diff --git a/src/backend/stores/session/SessionStore.test.ts b/src/backend/stores/session/SessionStore.test.ts index e6d4bb946..acef2eca8 100644 --- a/src/backend/stores/session/SessionStore.test.ts +++ b/src/backend/stores/session/SessionStore.test.ts @@ -2214,3 +2214,25 @@ describe('SessionStore', () => { }); }); }); + +describe('SessionStore lookups by a value that is not a string', () => { + let lookupServer: PuterServer; + + beforeAll(async () => { + lookupServer = await setupTestServer(); + }); + + afterAll(async () => { + await lookupServer?.shutdown(); + }); + + it('match no row', async () => { + const stores = lookupServer.stores; + for (const value of [0, 1, true, ['x'], { uid: 'x' }]) { + for (const row of [ + await stores.session.getByUuidAny(value as never), + ]) + expect(row).toBeNull(); + } + }); +}); diff --git a/src/backend/stores/share/ShareStore.js b/src/backend/stores/share/ShareStore.js index 8730428d0..4569b6557 100644 --- a/src/backend/stores/share/ShareStore.js +++ b/src/backend/stores/share/ShareStore.js @@ -79,6 +79,7 @@ export class ShareStore extends PuterStore { /** Pass `primary` to read back a row just written; a replica may lag. */ async getByUid(uid, { primary = false } = {}) { + if (typeof uid !== 'string') return null; const rows = await this.#select( 'SELECT * FROM `share` WHERE `uid` = ? LIMIT 1', [uid], diff --git a/src/backend/stores/share/ShareStore.test.js b/src/backend/stores/share/ShareStore.test.js index cb6b983c9..63b8e2b8b 100644 --- a/src/backend/stores/share/ShareStore.test.js +++ b/src/backend/stores/share/ShareStore.test.js @@ -1645,3 +1645,25 @@ describe('ShareStore', () => { expect(Number(after[0].n)).toBe(Number(before[0].n)); }); }); + +describe('ShareStore lookups by a value that is not a string', () => { + let lookupServer; + + beforeAll(async () => { + lookupServer = await setupTestServer(); + }); + + afterAll(async () => { + await lookupServer?.shutdown(); + }); + + it('match no row', async () => { + const stores = lookupServer.stores; + for (const value of [0, 1, true, ['x'], { uid: 'x' }]) { + for (const row of [ + await stores.share.getByUid(value), + ]) + expect(row).toBeNull(); + } + }); +}); diff --git a/src/backend/stores/subdomain/SubdomainStore.test.ts b/src/backend/stores/subdomain/SubdomainStore.test.ts index c2003b407..583763f40 100644 --- a/src/backend/stores/subdomain/SubdomainStore.test.ts +++ b/src/backend/stores/subdomain/SubdomainStore.test.ts @@ -1210,3 +1210,25 @@ describe('SubdomainStore.trashedRootDirIds', () => { } }); }); + +describe('SubdomainStore lookups by a value that is not a string', () => { + let lookupServer: PuterServer; + + beforeAll(async () => { + lookupServer = await setupTestServer(); + }); + + afterAll(async () => { + await lookupServer?.shutdown(); + }); + + it('match no row', async () => { + const stores = lookupServer.stores; + for (const value of [0, 1, true, ['x'], { uid: 'x' }]) { + for (const row of [ + await stores.subdomain.getByUuid(value as never), + ]) + expect(row).toBeNull(); + } + }); +}); diff --git a/src/backend/stores/subdomain/SubdomainStore.ts b/src/backend/stores/subdomain/SubdomainStore.ts index 03a641196..01f4eeae3 100644 --- a/src/backend/stores/subdomain/SubdomainStore.ts +++ b/src/backend/stores/subdomain/SubdomainStore.ts @@ -145,6 +145,7 @@ export class SubdomainStore extends PuterStore { primary?: boolean; } = {}, ): Promise { + if (typeof uuid !== 'string') return null; const where = userId !== undefined ? 'WHERE `uuid` = ? AND `user_id` = ?' diff --git a/src/backend/stores/user/UserStore.test.ts b/src/backend/stores/user/UserStore.test.ts index 5481fd212..13c8afddf 100644 --- a/src/backend/stores/user/UserStore.test.ts +++ b/src/backend/stores/user/UserStore.test.ts @@ -512,7 +512,7 @@ describe('UserStore batched and uncached lookups', () => { ).toBeNull(); }); - it('matches no row for a lookup value that is not a string or number', async () => { + it('matches no row on a text column for a value that is not a string', async () => { const user = await makeUser(); const lookups: unknown[] = [ ['a', 'b'], @@ -522,6 +522,15 @@ describe('UserStore batched and uncached lookups', () => { null, undefined, true, + 0, + 1, + ]; + // MySQL would cast the column for a number, so none may reach it. + const db = server.clients.db; + const reads = [ + vi.spyOn(db, 'read'), + vi.spyOn(db, 'pread'), + vi.spyOn(db, 'tryHardRead'), ]; for (const value of lookups) { expect( @@ -534,10 +543,17 @@ describe('UserStore batched and uncached lookups', () => { await server.stores.user.getByProperty('uuid', value), ).toBeNull(); } - // A real lookup still resolves. + for (const spy of reads) { + expect(spy).not.toHaveBeenCalled(); + spy.mockRestore(); + } + // Real lookups still resolve, `id` by number. expect( (await server.stores.user.getByUsername(user.username))?.id, ).toBe(user.id); + expect((await server.stores.user.getById(user.id))?.uuid).toBe( + user.uuid, + ); }); it('refuses to write a non-latin1 value into a latin1 column', async () => { diff --git a/src/backend/stores/user/UserStore.ts b/src/backend/stores/user/UserStore.ts index 38ca31e37..073a6b681 100644 --- a/src/backend/stores/user/UserStore.ts +++ b/src/backend/stores/user/UserStore.ts @@ -425,9 +425,13 @@ export class UserStore extends PuterStore { const cached = options.cached ?? true; const force = options.force ?? false; - // Only a string or number can equal a stored value. The driver expands - // an array or object into SQL of its own. - if (typeof value !== 'string' && typeof value !== 'number') return null; + // A text column compared with a number casts the column, so `0` or + // `true` would match unrelated rows. Only `id` takes a number. + if ( + typeof value !== 'string' && + !(prop === 'id' && typeof value === 'number') + ) + return null; // Reject lookup values that can't exist in a latin1 column before // the driver turns them into a collation-mix error at MySQL.