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:
Maurice
2026-11-17 21:24:00 +01:00
parent 685506d067
commit 5ff5e76603
12 changed files with 374 additions and 157 deletions
@@ -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/),
+129
View File
@@ -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"}]}',
);
});
/**