mirror of
https://github.com/HeyPuter/puter.git
synced 2026-11-25 15:17:23 +00:00
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.
This commit is contained in:
1 parent
31d9f2a89c
commit
03639b9589
25 files changed
+393
-12
No files matched your search
@@ -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([[], []]);
|
||||
|
||||
@@ -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<Record<string, unknown>[][]> {
|
||||
// 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)),
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<Record<string, unknown>[]> {
|
||||
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<Record<string, unknown>[]> {
|
||||
assertBindableParams(query, params);
|
||||
const result = await this.dbPrimaryRead.execute(query, params);
|
||||
if (!result) return [];
|
||||
return (result[0] as Record<string, unknown>[]) ?? [];
|
||||
@@ -170,6 +173,7 @@ export class MySQLDatabaseClient extends AbstractDatabaseClient {
|
||||
query: string,
|
||||
params: unknown[] = [],
|
||||
): Promise<WriteResult> {
|
||||
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<void> {
|
||||
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<Record<string, unknown>[]> {
|
||||
assertBindableParams(query, params);
|
||||
const result = await this.dbReplica.execute(query, params);
|
||||
if (!result) return [];
|
||||
return (result[0] as Record<string, unknown>[]) ?? [];
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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<QueryResult> {
|
||||
assertBindableParams(query, params);
|
||||
let text = this.preparedSql.get(query);
|
||||
if (text === undefined) {
|
||||
text = preparePostgresSql(query).text;
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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<Record<string, unknown>[]> {
|
||||
return this.prepare(query).all(
|
||||
...this.transformParams(params),
|
||||
...this.transformParams(query, params),
|
||||
) as Record<string, unknown>[];
|
||||
}
|
||||
|
||||
@@ -212,7 +213,9 @@ export class SqliteDatabaseClient extends AbstractDatabaseClient {
|
||||
query: string,
|
||||
params: unknown[] = [],
|
||||
): Promise<WriteResult> {
|
||||
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<void> {
|
||||
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;
|
||||
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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',
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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');
|
||||
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1652,11 +1652,13 @@ export class FSEntryStore extends PuterStore {
|
||||
}
|
||||
|
||||
async getEntryByUuid(uuid: string): Promise<FSEntry | null> {
|
||||
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<FSEntry | null> {
|
||||
if (typeof uuid !== 'string') return null;
|
||||
const rows = (await this.clients.db.pread(
|
||||
`SELECT ${this.#selectFsentriesColumns()} FROM fsentries WHERE uuid = ? LIMIT 1`,
|
||||
[uuid],
|
||||
|
||||
@@ -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],
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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.
|
||||
|
||||
@@ -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([
|
||||
{
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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],
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -145,6 +145,7 @@ export class SubdomainStore extends PuterStore {
|
||||
primary?: boolean;
|
||||
} = {},
|
||||
): Promise<SubdomainRow | null> {
|
||||
if (typeof uuid !== 'string') return null;
|
||||
const where =
|
||||
userId !== undefined
|
||||
? 'WHERE `uuid` = ? AND `user_id` = ?'
|
||||
|
||||
@@ -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 () => {
|
||||
|
||||
@@ -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.
|
||||
|
||||
Reference in new issue
Block a user