mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 00:20:07 +00:00
fix(db): store no NUL character on either engine
Postgres text cannot hold U+0000, so any write or filter carrying one (a request body, a query string, an import, a feed, a forwarded mail, a plugin's own SQL) answered a 500 on Postgres while SQLite stored it. Both engines now drop the character where every value leaves for the database (src/db/nul-free.ts): the MikroORM platforms when they inline a string or serialize a JSON value, the Kysely dialects for every parameter, a plugin's own SQLite file for its arguments, and the move from SQLite, which used to refuse such text. The same request now answers the same status and leaves the same row on both engines, so the places NUL suite runs on Postgres as well and leaves SQLITE_ONLY.
This commit is contained in:
@@ -1,13 +1,13 @@
|
||||
/**
|
||||
* M1 / program rule 22 (task-4-review.md): a NUL byte in a user string no
|
||||
* longer 500s on SQLite. The platform override restores the legacy raw bind's
|
||||
* byte-for-byte round-trip (base 94c6efbbc: 200/201; before that fix, every
|
||||
* ORM-converted statement 500'd on NUL).
|
||||
* A NUL character (U+0000) in a user string, on SQLite and on Postgres alike.
|
||||
*
|
||||
* Moved out of places.test.ts so the rest of that suite runs on both engines:
|
||||
* these two cases are about SQLite's value quoting, and Postgres text cannot
|
||||
* hold U+0000 at all (tests/postgres/lane.ts, SQLITE_ONLY). The control
|
||||
* characters 0x01-0x1F stay in places.test.ts, where they run on both.
|
||||
* Postgres text cannot hold it, so a write or a filter carrying one used to
|
||||
* answer a 500 there while SQLite stored it. TREK stores no NUL on either
|
||||
* engine now (src/db/nul-free.ts): every string a statement carries loses it,
|
||||
* so the same request answers the same status and leaves the same row on both
|
||||
* engines (M1 / program rule 22 first made it a 201 on SQLite). The control
|
||||
* characters 0x01-0x1F, which both engines store, are swept in
|
||||
* places.test.ts.
|
||||
*/
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { Places } from '../../src/db/entities/Places.entity';
|
||||
@@ -19,6 +19,7 @@ import { makeUser } from '../helpers/factories/users';
|
||||
import { resetDatabase } from '../helpers/reset-database';
|
||||
import { resetRateLimits } from '../helpers/test-db';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import type { AbstractSqlConnection } from '@mikro-orm/sql';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
|
||||
import type { Application } from 'express';
|
||||
@@ -44,34 +45,37 @@ afterAll(async () => {
|
||||
await nestApp.close();
|
||||
});
|
||||
|
||||
describe('M1 — NUL-safe value quoting on the SQLite platform (rule 22)', () => {
|
||||
it("GET ?search=%00 is 200, not 500 (status parity — SQLite's LIKE pattern matcher itself iterates its RHS as NUL-terminated, an independent SQLite limitation this platform fix does not touch, so a NUL search matches everything on BOTH trees, not nothing)", async () => {
|
||||
describe('a NUL character in a user string, on every engine', () => {
|
||||
it('GET ?search=%00 is 200 and matches as an empty search', async () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id);
|
||||
await makePlace(orm, trip.id, { name: 'Spot' });
|
||||
|
||||
// A raw, pre-encoded `%00` in the URL — the review's exact literal
|
||||
// request shape (`GET /api/trips/:id/places?search=%00`). `.query({...})`
|
||||
// goes through superagent's own `qs` encoder, which is not guaranteed to
|
||||
// round-trip a NUL character the same way; the literal query string is
|
||||
// what Express/the route actually receives in production.
|
||||
// A raw, pre-encoded `%00` in the URL: `.query({...})` goes through
|
||||
// superagent's own encoder, which need not round-trip a NUL the same way.
|
||||
const res = await request(app).get(`/api/trips/${trip.id}/places?search=%00`).set('Cookie', authCookie(user.id));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.places.map((p: { name: string }) => p.name)).toEqual(['Spot']);
|
||||
});
|
||||
|
||||
it('POST create with a NUL in the name is 201 and the name round-trips byte-for-byte', async () => {
|
||||
it('POST create with a NUL in the name is 201 and stores the name without it', async () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id);
|
||||
const name = 'nul\u0000name';
|
||||
|
||||
const res = await request(app)
|
||||
.post(`/api/trips/${trip.id}/places`)
|
||||
.set('Cookie', authCookie(user.id))
|
||||
.send({ name });
|
||||
.send({ name: 'nul\u0000name' });
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.place.name).toBe(name);
|
||||
expect(res.body.place.name).toBe('nulname');
|
||||
|
||||
const stored = await findRow(orm, Places, { id: res.body.place.id });
|
||||
expect(stored?.name).toBe(name);
|
||||
expect(stored?.name).toBe('nulname');
|
||||
});
|
||||
|
||||
it('a parameter of a Kysely statement loses its NUL too', async () => {
|
||||
const kysely = (orm.em.getConnection() as AbstractSqlConnection).getClient<object>();
|
||||
const row = await kysely.selectNoFrom((eb) => eb.val('a\u0000b').as('v')).executeTakeFirstOrThrow();
|
||||
expect(row.v).toBe('ab');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1304,8 +1304,8 @@ describe('A-H1 / A-M1 / B-H1 — verifyTripAccess parses once with toRowId (Task
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// M1 / program rule 22 (task-4-review.md) — control characters in a user
|
||||
// string round-trip on every engine. The NUL byte itself is SQLite's case and
|
||||
// lives in places-nul-sqlite.test.ts: Postgres text cannot hold U+0000.
|
||||
// string round-trip on every engine. The NUL byte, which neither engine
|
||||
// stores, has its own suite: places-nul.test.ts.
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('M1 — control characters in a place name (rule 22)', () => {
|
||||
@@ -1313,7 +1313,7 @@ describe('M1 — control characters in a place name (rule 22)', () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id);
|
||||
|
||||
// 0x00 is covered by places-nul-sqlite.test.ts; this sweeps the rest
|
||||
// 0x00 is covered by places-nul.test.ts; this sweeps the rest
|
||||
// of the control-character range the review's fuzz asked for.
|
||||
for (let code = 0x01; code <= 0x1f; code++) {
|
||||
const name = `ctrl${String.fromCharCode(code)}char`;
|
||||
|
||||
@@ -73,10 +73,6 @@ export const SQLITE_ONLY: Readonly<Record<string, string>> = {
|
||||
'tests/integration/legacy-upgrade-v205.test.ts': LEGACY_UPGRADE,
|
||||
'tests/integration/legacy-upgrade-v242.test.ts': LEGACY_UPGRADE,
|
||||
'tests/integration/legacy-upgrade-v244.test.ts': LEGACY_UPGRADE,
|
||||
'tests/integration/places-nul-sqlite.test.ts':
|
||||
'About SQLite value quoting of a NUL byte (U+0000) in a user string; Postgres text cannot hold that ' +
|
||||
'character, so the round-trip it asserts does not exist there. The other control characters run on ' +
|
||||
'both engines in places.test.ts.',
|
||||
};
|
||||
|
||||
const SNAPSHOT_BASELINE_FILE = path.join(__dirname, 'snapshot-suites-baseline.json');
|
||||
|
||||
@@ -80,14 +80,13 @@ describe('convertValue', () => {
|
||||
expect(convertValue('', 'float')).toMatchObject({ ok: false });
|
||||
});
|
||||
|
||||
it('MOVEVAL-005: text takes strings and numbers, and refuses a NUL Postgres cannot store or a BLOB', () => {
|
||||
it('MOVEVAL-005: text takes strings and numbers, drops a NUL as every write does, and refuses a BLOB', () => {
|
||||
expect(convertValue('Lisboa', 'text')).toEqual(ok('Lisboa'));
|
||||
expect(convertValue(7n, 'text')).toEqual(ok('7'));
|
||||
expect(convertValue(2.5, 'text')).toEqual(ok('2.5'));
|
||||
expect(convertValue('a\u0000b', 'text')).toMatchObject({
|
||||
ok: false,
|
||||
reason: expect.stringMatching(/NUL character/),
|
||||
});
|
||||
expect(convertValue('a\u0000b\u0000', 'text')).toEqual(ok('ab'));
|
||||
// The six characters of an escape are text like any other.
|
||||
expect(convertValue('a\\u0000b', 'text')).toEqual(ok('a\\u0000b'));
|
||||
expect(convertValue(new Uint8Array([0]), 'text')).toMatchObject({
|
||||
ok: false,
|
||||
reason: expect.stringMatching(/is not text/),
|
||||
@@ -98,17 +97,17 @@ describe('convertValue', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('MOVEVAL-006: JSON must parse and hold no NUL, escaped or not', () => {
|
||||
it('MOVEVAL-006: JSON must parse, and loses the NUL characters it escapes', () => {
|
||||
expect(convertValue('{"a":1}', 'json')).toEqual(ok('{"a":1}'));
|
||||
expect(convertValue(5n, 'json')).toEqual(ok('5'));
|
||||
expect(convertValue('{broken', 'json')).toMatchObject({
|
||||
ok: false,
|
||||
reason: expect.stringMatching(/is not valid JSON/),
|
||||
});
|
||||
expect(convertValue('"\\u0000"', 'json')).toMatchObject({
|
||||
ok: false,
|
||||
reason: expect.stringMatching(/jsonb cannot store/),
|
||||
});
|
||||
expect(convertValue('"\\u0000"', 'json')).toEqual(ok('""'));
|
||||
expect(convertValue('{"a\\u0000":["x\\u0000y",1]}', 'json')).toEqual(ok('{"a":["xy",1]}'));
|
||||
// A raw NUL is not valid JSON in the first place.
|
||||
expect(convertValue('"\u0000"', 'json')).toMatchObject({ ok: false, reason: expect.stringMatching(/valid JSON/) });
|
||||
expect(convertValue(new Uint8Array([1]), 'json')).toMatchObject({
|
||||
ok: false,
|
||||
reason: expect.stringMatching(/is not JSON text/),
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* TREK stores no NUL (U+0000) on either engine (src/db/nul-free.ts). These pin
|
||||
* the pieces every engine's write path runs through; the integration suite
|
||||
* tests/integration/places-nul.test.ts runs a write and a search through the
|
||||
* whole app on SQLite and on Postgres.
|
||||
*/
|
||||
import { extendedQuery, unmarkedValues } from '../../../src/db/engine/postgres/extended-query';
|
||||
import { TrekPostgreSqlPlatform } from '../../../src/db/engine/postgres/postgres-driver';
|
||||
import { nulFreeJson, nulFreeParameter, stripNul, withNulFreeParameters } from '../../../src/db/nul-free';
|
||||
|
||||
import {
|
||||
CompiledQuery,
|
||||
type DatabaseConnection,
|
||||
type Dialect,
|
||||
type Driver,
|
||||
type QueryResult,
|
||||
SqliteAdapter,
|
||||
SqliteIntrospector,
|
||||
SqliteQueryCompiler,
|
||||
} from 'kysely';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const RELEASE = Symbol('release');
|
||||
|
||||
/** A connection that records what it was sent and keeps a private release, like Kysely's Postgres one. */
|
||||
class RecordingConnection implements DatabaseConnection {
|
||||
readonly sent: CompiledQuery[] = [];
|
||||
released = false;
|
||||
#open = true;
|
||||
|
||||
async executeQuery<R>(query: CompiledQuery): Promise<QueryResult<R>> {
|
||||
if (!this.#open) throw new Error('closed');
|
||||
this.sent.push(query);
|
||||
return { rows: [] };
|
||||
}
|
||||
|
||||
async *streamQuery<R>(query: CompiledQuery): AsyncIterableIterator<QueryResult<R>> {
|
||||
this.sent.push(query);
|
||||
yield { rows: [] };
|
||||
}
|
||||
|
||||
[RELEASE](): void {
|
||||
this.released = this.#open;
|
||||
}
|
||||
}
|
||||
|
||||
function recordingDialect(connection: RecordingConnection): Dialect {
|
||||
const driver: Driver = {
|
||||
init: async () => undefined,
|
||||
acquireConnection: async () => connection,
|
||||
beginTransaction: async (c) => {
|
||||
await c.executeQuery(CompiledQuery.raw('begin'));
|
||||
},
|
||||
commitTransaction: async () => undefined,
|
||||
rollbackTransaction: async () => undefined,
|
||||
releaseConnection: async (c) => {
|
||||
(c as RecordingConnection)[RELEASE]();
|
||||
},
|
||||
destroy: async () => undefined,
|
||||
};
|
||||
return {
|
||||
createAdapter: () => new SqliteAdapter(),
|
||||
createDriver: () => driver,
|
||||
createIntrospector: (db) => new SqliteIntrospector(db),
|
||||
createQueryCompiler: () => new SqliteQueryCompiler(),
|
||||
};
|
||||
}
|
||||
|
||||
describe('NUL-free values', () => {
|
||||
it('NULFREE-001: strips NUL from a string, from the strings of an array, and nothing else', () => {
|
||||
expect(stripNul('a\u0000b\u0000')).toBe('ab');
|
||||
expect(stripNul('a\\u0000b')).toBe('a\\u0000b');
|
||||
const plain = 'no nul';
|
||||
expect(stripNul(plain)).toBe(plain);
|
||||
expect(nulFreeParameter(['x\u0000', 2])).toEqual(['x', 2]);
|
||||
const numbers = [1, 2];
|
||||
expect(nulFreeParameter(numbers)).toBe(numbers);
|
||||
const bytes = Buffer.from([0, 1]);
|
||||
expect(nulFreeParameter(bytes)).toBe(bytes);
|
||||
const marker = { trekExtendedProtocol: true };
|
||||
expect(nulFreeParameter(marker)).toBe(marker);
|
||||
expect(nulFreeParameter(null)).toBeNull();
|
||||
});
|
||||
|
||||
it('NULFREE-002: strips NUL from every string of a JSON value, keys included', () => {
|
||||
expect(nulFreeJson({ 'a\u0000': ['b\u0000', 1, null, { c: 'd\u0000' }] })).toEqual({
|
||||
a: ['b', 1, null, { c: 'd' }],
|
||||
});
|
||||
const date = new Date(0);
|
||||
expect(nulFreeJson(date)).toBe(date);
|
||||
});
|
||||
|
||||
it("NULFREE-003: a dialect's connections send every parameter without NUL and keep the rest of the query", async () => {
|
||||
const connection = new RecordingConnection();
|
||||
const driver = withNulFreeParameters(recordingDialect(connection)).createDriver();
|
||||
const acquired = await driver.acquireConnection();
|
||||
expect(await driver.acquireConnection()).toBe(acquired);
|
||||
|
||||
const clean = CompiledQuery.raw('select ?', ['clean']);
|
||||
await acquired.executeQuery(clean);
|
||||
expect(connection.sent[0]).toBe(clean);
|
||||
|
||||
await acquired.executeQuery(CompiledQuery.raw('insert into t values (?, ?, ?)', ['a\u0000b', 3, ['c\u0000']]));
|
||||
expect(connection.sent[1].sql).toBe('insert into t values (?, ?, ?)');
|
||||
expect(connection.sent[1].parameters).toEqual(['ab', 3, ['c']]);
|
||||
|
||||
for await (const chunk of acquired.streamQuery(CompiledQuery.raw('select ?', ['s\u0000']), 10)) {
|
||||
expect(chunk.rows).toEqual([]);
|
||||
}
|
||||
expect(connection.sent[2].parameters).toEqual(['s']);
|
||||
|
||||
// The extended-protocol marker survives by identity.
|
||||
await acquired.executeQuery(extendedQuery('select $1', ['m\u0000']));
|
||||
expect(unmarkedValues(connection.sent[3].parameters)).toEqual(['m']);
|
||||
|
||||
// The driver's own methods get the wrapped connection and still reach its private state.
|
||||
await driver.beginTransaction(acquired, {});
|
||||
expect(connection.sent[4].sql).toBe('begin');
|
||||
await driver.releaseConnection(acquired);
|
||||
expect(connection.released).toBe(true);
|
||||
});
|
||||
|
||||
it('NULFREE-004: the Postgres platform inlines strings and serializes JSON without NUL', () => {
|
||||
const platform = new TrekPostgreSqlPlatform();
|
||||
expect(platform.escape("o\u0000'k")).toBe("'o''k'");
|
||||
expect(platform.formatQuery('select ?', ['x\u0000y'])).toBe("select 'xy'");
|
||||
expect(platform.convertJsonToDatabaseValue({ k: 'v\u0000' })).toBe('{"k":"v"}');
|
||||
});
|
||||
});
|
||||
@@ -11,15 +11,15 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
/**
|
||||
* Plan 3c Task 4 review M1 / program rule 22: MikroORM 7 inlines every bound
|
||||
* value into the SQL text via `platform.quoteValue`/`escape` (see
|
||||
* `NulSafeSqlitePlatform`'s own docstring for the full mechanism). These
|
||||
* tests prove the override round-trips a NUL byte at every position SQLite
|
||||
* itself will accept, by handing the platform's own generated SQL literal to
|
||||
* a REAL `better-sqlite3` connection and reading the value back — not a
|
||||
* string-shape assertion, an actual SQLite round-trip.
|
||||
* `NulSafeSqlitePlatform`'s own docstring for the full mechanism). TREK stores
|
||||
* no NUL on either engine (`src/db/nul-free.ts`), so the platform drops it from
|
||||
* every string it inlines. These hand the platform's own SQL literal to a REAL
|
||||
* `better-sqlite3` connection and read the value back.
|
||||
*/
|
||||
describe('NulSafeSqlitePlatform', () => {
|
||||
const platform = new NulSafeSqlitePlatform();
|
||||
const db = new Database(':memory:');
|
||||
const withoutNul = (value: string) => value.replaceAll('\u0000', '');
|
||||
|
||||
function roundTrip(value: string): string {
|
||||
const literal = platform.escape(value);
|
||||
@@ -27,51 +27,29 @@ describe('NulSafeSqlitePlatform', () => {
|
||||
return row.v;
|
||||
}
|
||||
|
||||
it('round-trips a string with no NUL unchanged (baseline: unaffected by the override)', () => {
|
||||
it('round-trips a string with no NUL unchanged', () => {
|
||||
expect(roundTrip('plain string')).toBe('plain string');
|
||||
});
|
||||
|
||||
it('round-trips a NUL in the middle of a string', () => {
|
||||
const value = 'nul\u0000name';
|
||||
expect(roundTrip(value)).toBe(value);
|
||||
it('drops a NUL wherever it stands, and a string of NULs becomes empty', () => {
|
||||
expect(roundTrip('nul\u0000name')).toBe('nulname');
|
||||
expect(roundTrip('\u0000leading')).toBe('leading');
|
||||
expect(roundTrip('trailing\u0000')).toBe('trailing');
|
||||
expect(roundTrip('\u0000\u0000\u0000')).toBe('');
|
||||
});
|
||||
|
||||
it('round-trips a NUL at the very start of a string', () => {
|
||||
const value = '\u0000leading';
|
||||
expect(roundTrip(value)).toBe(value);
|
||||
it('keeps the quote and backslash handling of every other string next to a dropped NUL', () => {
|
||||
for (const value of ["o'brien\u0000's café", 'back\\slash\u0000end\\', "a'\u0000b\\\u0000c''\u0000\\\\d"]) {
|
||||
expect(roundTrip(value)).toBe(withoutNul(value));
|
||||
}
|
||||
});
|
||||
|
||||
it('round-trips a NUL at the very end of a string', () => {
|
||||
const value = 'trailing\u0000';
|
||||
expect(roundTrip(value)).toBe(value);
|
||||
});
|
||||
|
||||
it('round-trips a string made ENTIRELY of NUL bytes', () => {
|
||||
expect(roundTrip('\u0000')).toBe('\u0000');
|
||||
expect(roundTrip('\u0000\u0000\u0000')).toBe('\u0000\u0000\u0000');
|
||||
});
|
||||
|
||||
it('round-trips a NUL next to a single quote (the string-literal escape character)', () => {
|
||||
const value = "o'brien\u0000's café";
|
||||
expect(roundTrip(value)).toBe(value);
|
||||
});
|
||||
|
||||
it('round-trips a NUL next to a backslash (not special in a SQLite string literal)', () => {
|
||||
const value = 'back\\slash\u0000end\\';
|
||||
expect(roundTrip(value)).toBe(value);
|
||||
});
|
||||
|
||||
it('round-trips multiple NULs mixed with quotes and backslashes', () => {
|
||||
const value = "a'\u0000b\\\u0000c''\u0000\\\\d";
|
||||
expect(roundTrip(value)).toBe(value);
|
||||
});
|
||||
|
||||
it('fuzzes every 0x00-0x1F control character: none corrupt the round-trip and none throw', () => {
|
||||
it('fuzzes every 0x00-0x1F control character: only NUL is dropped and none throw', () => {
|
||||
for (let code = 0x00; code <= 0x1f; code++) {
|
||||
const ch = String.fromCharCode(code);
|
||||
const value = `before${ch}after`;
|
||||
expect(() => roundTrip(value)).not.toThrow();
|
||||
expect(roundTrip(value)).toBe(value);
|
||||
expect(roundTrip(value)).toBe(code === 0 ? 'beforeafter' : value);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -81,14 +59,19 @@ describe('NulSafeSqlitePlatform', () => {
|
||||
expect(platform.escape(true)).toBe('true');
|
||||
});
|
||||
|
||||
it('formatQuery (the real call path AbstractSqlConnection.execute uses: formatQuery -> quoteValue -> escape) inlines a NUL-safe literal for a bound `?`, matched via a real table', () => {
|
||||
it('formatQuery (the real call path AbstractSqlConnection.execute uses: formatQuery -> quoteValue -> escape) stores a value without its NUL and finds it by the same value', () => {
|
||||
db.exec('CREATE TABLE probe (name TEXT)');
|
||||
const value = 'search\u0000term';
|
||||
const insertSql = platform.formatQuery('insert into probe (name) values (?)', [value]);
|
||||
db.exec(insertSql);
|
||||
const selectSql = platform.formatQuery('select name from probe where name = ?', [value]);
|
||||
const row = db.prepare(selectSql).get() as { name: string } | undefined;
|
||||
expect(row?.name).toBe(value);
|
||||
db.exec(platform.formatQuery('insert into probe (name) values (?)', [value]));
|
||||
const row = db.prepare(platform.formatQuery('select name from probe where name = ?', [value])).get() as
|
||||
{ name: string } | undefined;
|
||||
expect(row?.name).toBe('searchterm');
|
||||
});
|
||||
|
||||
it('serializes a JSON value with every string in it, keys included, without NUL', () => {
|
||||
expect(platform.convertJsonToDatabaseValue({ 'k\u0000': ['a\u0000b', 1, { n: 'x\u0000' }] })).toBe(
|
||||
'{"k":["ab",1,{"n":"x"}]}',
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user