Files
TREK/server/tests/unit/db/engine/postgres/session-search-path.test.ts
T
Maurice 861f6ba789 fix(db): run plugin SQL one statement at a time and search pg_temp last
The plugin SQL guard was the only thing between a plugin and TREK's tables
on Postgres, and two gaps in it were enough to leave the plugin schema.
Two layers now hold even when the guard is fooled.

A plugin write with no bound args went over the simple query protocol,
which runs every statement in its text. Plugin statements now go through
extendedQuery, which pg sends over the extended protocol whatever the
args, so a second statement is a syntax error instead of a statement that
runs. A marker parameter carries the request to the pool's clients, and a
client without the hook binds one value too many, so it fails closed.

pg_temp is searched before the search_path unless the path names it, and
a temporary table lives as long as its pooled connection, so one left
behind would stand in for users, sessions and every other table for the
next caller. Every connection of TREK's pool now puts pg_temp last on the
search_path the role configured, and a plugin transaction sets its schema
with pg_temp last.
2026-11-17 20:45:39 +01:00

40 lines
1.7 KiB
TypeScript

/**
* `pg_temp` last on the search_path of TREK's pool connections
* (src/db/engine/postgres/session-search-path.ts), without a database. That a
* temporary table then never stands in for TREK's own is PGPLUG-011 in the
* Postgres lane.
*/
import { putTempSchemaLast, searchPathWithTempLast } from '../../../../../src/db/engine/postgres/session-search-path';
import type { CompiledQuery, DatabaseConnection, QueryResult } from 'kysely';
import { describe, expect, it } from 'vitest';
describe('session search_path', () => {
it.each([
['"$user", public', '"$user", public, pg_temp'],
['trek', 'trek, pg_temp'],
['pg_temp, public', 'public, pg_temp'],
['PG_TEMP,public', 'public, pg_temp'],
['"pg_temp", "$user", public', '"$user", public, pg_temp'],
['"a, b", "c""d", public', '"a, b", "c""d", public, pg_temp'],
['', 'pg_temp'],
])('SPATH-001: %j keeps its schemas in order and gets pg_temp last: %j', (path, expected) => {
expect(searchPathWithTempLast(path)).toBe(expected);
});
it('SPATH-002: the connection hook reads the path and sets it for the session, the value bound', async () => {
const sent: Array<{ sql: string; parameters: readonly unknown[] }> = [];
const connection = {
executeQuery: async (query: CompiledQuery): Promise<QueryResult<unknown>> => {
sent.push({ sql: query.sql, parameters: query.parameters });
return { rows: query.sql === 'show search_path' ? [{ search_path: 'trek, public' }] : [] };
},
} as unknown as DatabaseConnection;
await putTempSchemaLast(connection);
expect(sent).toEqual([
{ sql: 'show search_path', parameters: [] },
{ sql: "select set_config('search_path', $1, false)", parameters: ['trek, public, pg_temp'] },
]);
});
});