mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-25 22:27:32 +00:00
fix(db): drop NUL from every request value before any logic runs
The database stores no NUL on either engine, but the application still held the value a client sent. A key or a check made from it was then a different value from the one the database compared: `victim@x.test` followed by NUL was a fresh key for the per-email password-reset throttle while the lookup found the victim's row, so every spelling mailed a new link and voided the last one. Every input now loses its NUL where it enters TREK: the nulFreeRequest middleware after the body parsers (path, query string, body, cookies), the first global pipe for what a route parses itself (a multipart body), the websocket adapter for every frame, and the MCP registry through a new host-supplied input mapper, since /mcp keeps its raw body. Headers need nothing: Node refuses a NUL in one with a 400. A string under a key naming a password stays as sent: it is only ever hashed, and stripping it would lock out an account whose password was set with one. The stripping in the database layer stays as the backstop for what does not come from a request.
This commit is contained in:
@@ -5,7 +5,7 @@
|
||||
* whole app on SQLite and on Postgres.
|
||||
*/
|
||||
import { TrekPostgreSqlPlatform } from '../../../src/db/engine/postgres/postgres-driver';
|
||||
import { nulFreeJson, nulFreeParameter, stripNul, withNulFreeParameters } from '../../../src/db/nul-free';
|
||||
import { nulFreeInput, nulFreeJson, nulFreeParameter, stripNul, withNulFreeParameters } from '../../../src/db/nul-free';
|
||||
|
||||
import {
|
||||
type AbortableOperationOptions,
|
||||
@@ -143,3 +143,69 @@ describe('NUL-free values', () => {
|
||||
expect(platform.convertJsonToDatabaseValue({ k: 'v\u0000' })).toBe('{"k":"v"}');
|
||||
});
|
||||
});
|
||||
|
||||
describe('nulFreeInput: a request value as the application handles it', () => {
|
||||
it('drops NUL from every string and key, in arrays and nested objects', () => {
|
||||
expect(nulFreeInput('victim@x.test\u0000')).toBe('victim@x.test');
|
||||
expect(nulFreeInput({ 'na\u0000me': ['a\u0000', { deep: 'b\u0000c' }], n: 1, ok: true, none: null })).toEqual({
|
||||
name: ['a', { deep: 'bc' }],
|
||||
n: 1,
|
||||
ok: true,
|
||||
none: null,
|
||||
});
|
||||
});
|
||||
|
||||
it('returns the very same value when nothing holds a NUL', () => {
|
||||
const body = { email: 'a@b.c', tags: ['x', 'y'], nested: { k: 'v' } };
|
||||
expect(nulFreeInput(body)).toBe(body);
|
||||
const list = ['a', 'b'];
|
||||
expect(nulFreeInput(list)).toBe(list);
|
||||
});
|
||||
|
||||
it('leaves a password exactly as sent, under any key that names one', () => {
|
||||
const body = {
|
||||
email: 'a@b.c\u0000',
|
||||
password: 'pa\u0000ss',
|
||||
new_password: 'n\u0000ew',
|
||||
current_password: 'c\u0000ur',
|
||||
user: { synology_password: 's\u0000y' },
|
||||
};
|
||||
expect(nulFreeInput(body)).toEqual({
|
||||
email: 'a@b.c',
|
||||
password: 'pa\u0000ss',
|
||||
new_password: 'n\u0000ew',
|
||||
current_password: 'c\u0000ur',
|
||||
user: { synology_password: 's\u0000y' },
|
||||
});
|
||||
});
|
||||
|
||||
it('still walks an object under a password key, only its strings stay as sent', () => {
|
||||
expect(nulFreeInput({ passwordReset: { note: 'x\u0000' } })).toEqual({ passwordReset: { note: 'x' } });
|
||||
});
|
||||
|
||||
it('keeps a null prototype, and a `__proto__` key stays a plain property', () => {
|
||||
const fields = Object.create(null) as Record<string, unknown>;
|
||||
fields.title = 't\u0000';
|
||||
const cleaned = nulFreeInput(fields) as Record<string, unknown>;
|
||||
expect(Object.getPrototypeOf(cleaned)).toBeNull();
|
||||
expect(cleaned.title).toBe('t');
|
||||
|
||||
const hostile = JSON.parse('{"__proto__": {"polluted": "y\\u0000"}, "a": "b\\u0000"}') as object;
|
||||
const out = nulFreeInput(hostile) as Record<string, unknown>;
|
||||
expect(Object.getPrototypeOf(out)).toBe(Object.prototype);
|
||||
expect(Object.prototype.hasOwnProperty.call(out, '__proto__')).toBe(true);
|
||||
expect(({} as Record<string, unknown>).polluted).toBeUndefined();
|
||||
expect(out.a).toBe('b');
|
||||
});
|
||||
|
||||
it('leaves anything that is not a string, an array or a plain object alone', () => {
|
||||
const buffer = Buffer.from('a\u0000b');
|
||||
const date = new Date(0);
|
||||
expect(nulFreeInput(buffer)).toBe(buffer);
|
||||
expect(nulFreeInput(date)).toBe(date);
|
||||
expect(nulFreeInput(5)).toBe(5);
|
||||
expect(nulFreeInput(undefined)).toBeUndefined();
|
||||
const file = { originalname: 'pho\u0000to.jpg', buffer };
|
||||
expect(nulFreeInput(file)).toEqual({ originalname: 'photo.jpg', buffer });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -233,6 +233,23 @@ describe('McpRegistry.attach', () => {
|
||||
expect(JSON.parse(textOf(result))).toEqual({ args: {}, userId: 42 });
|
||||
});
|
||||
|
||||
it('hands every tool, prompt and resource template input through the input mapper first', async () => {
|
||||
const mapped: unknown[] = [];
|
||||
const inputMapper = (input: unknown) => {
|
||||
mapped.push(input);
|
||||
return JSON.parse(JSON.stringify(input).replaceAll('!', '')) as unknown;
|
||||
};
|
||||
const registry = createTestRegistry([new FixtureMcp(new Greeter())], { accessPolicy: policy, inputMapper });
|
||||
harness = await createAttachHarness(registry, { userId: 5, canRead: true });
|
||||
const tool = await harness.client.callTool({ name: 'loose_tool', arguments: { name: 'tr!ek' } });
|
||||
expect(JSON.parse(textOf(tool))).toEqual({ args: { name: 'trek' }, userId: 5 });
|
||||
const prompt = await harness.client.getPrompt({ name: 'fixture_prompt', arguments: { topic: 'pack!ing' } });
|
||||
expect(prompt.messages[0]?.content).toMatchObject({ text: 'packing for 5' });
|
||||
const item = await harness.client.readResource({ uri: 'test://item/4!2' });
|
||||
expect(item.contents[0]).toMatchObject({ text: 'item 42 for 5' });
|
||||
expect(mapped).toEqual([{ name: 'tr!ek' }, { topic: 'pack!ing' }, { id: '4!2' }]);
|
||||
});
|
||||
|
||||
it('serves fixed resources with (uri, ctx)', async () => {
|
||||
harness = await createAttachHarness(buildRegistry(), { userId: 9, canRead: true });
|
||||
const result = await harness.client.readResource({ uri: 'test://doc' });
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
/**
|
||||
* The HTTP edge of the NUL rule (src/nest/common/nul-free-input.ts): what a
|
||||
* request carries loses its NUL characters before any guard or controller
|
||||
* reads it. tests/integration/nul-free-input.test.ts drives the same rule
|
||||
* through the whole app on SQLite and on Postgres.
|
||||
*/
|
||||
import { NulFreeInputPipe, nulFreeRequest, withoutEncodedNul } from '../../../../src/nest/common/nul-free-input';
|
||||
|
||||
import type { Request, Response } from 'express';
|
||||
import nodeHttp from 'node:http';
|
||||
import net from 'node:net';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
function run(req: Partial<Request> & { cookies?: unknown; signedCookies?: unknown }) {
|
||||
const next = vi.fn();
|
||||
nulFreeRequest(req as Request, {} as Response, next);
|
||||
expect(next).toHaveBeenCalledWith();
|
||||
return req;
|
||||
}
|
||||
|
||||
describe('withoutEncodedNul', () => {
|
||||
it('drops every %00 from the path and the query string', () => {
|
||||
expect(withoutEncodedNul('/api/trips/7%00/places?search=a%00b&x=%00')).toBe('/api/trips/7/places?search=ab&x=');
|
||||
});
|
||||
|
||||
it('cannot be tricked into leaving one behind', () => {
|
||||
expect(withoutEncodedNul('/a?q=%%0000')).toBe('/a?q=');
|
||||
expect(withoutEncodedNul('/a?q=%%%000000')).toBe('/a?q=');
|
||||
});
|
||||
|
||||
it('keeps an encoded percent sign followed by 00, which decodes to the text %00', () => {
|
||||
expect(withoutEncodedNul('/a?q=%2500')).toBe('/a?q=%2500');
|
||||
});
|
||||
});
|
||||
|
||||
describe('nulFreeRequest', () => {
|
||||
it('cleans the url, the body and both cookie jars', () => {
|
||||
const req = run({
|
||||
url: '/api/auth/x%00?e=a%00',
|
||||
body: { email: 'victim@x.test\u0000', password: 'pa\u0000ss' },
|
||||
cookies: { trek_session: 'tok\u0000en' },
|
||||
signedCookies: { s: 'v\u0000' },
|
||||
});
|
||||
expect(req.url).toBe('/api/auth/x?e=a');
|
||||
expect(req.body).toEqual({ email: 'victim@x.test', password: 'pa\u0000ss' });
|
||||
expect(req.cookies).toEqual({ trek_session: 'token' });
|
||||
expect(req.signedCookies).toEqual({ s: 'v' });
|
||||
});
|
||||
|
||||
it('leaves a request without a body or cookies as it is', () => {
|
||||
const req = run({ url: '/api/health' });
|
||||
expect(req).toEqual({ url: '/api/health' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('NulFreeInputPipe', () => {
|
||||
it('cleans what a route parsed itself, a multipart body and its file name', () => {
|
||||
const fields = Object.create(null) as Record<string, unknown>;
|
||||
fields.description = 'a\u0000b';
|
||||
const pipe = new NulFreeInputPipe();
|
||||
expect({ ...(pipe.transform(fields) as object) }).toEqual({ description: 'ab' });
|
||||
expect(pipe.transform({ originalname: 'x\u0000.jpg' })).toEqual({ originalname: 'x.jpg' });
|
||||
expect(pipe.transform('7\u0000')).toBe('7');
|
||||
expect(pipe.transform(7)).toBe(7);
|
||||
});
|
||||
});
|
||||
|
||||
describe('headers', () => {
|
||||
it('never reach TREK with a NUL: Node answers 400 before any middleware runs', async () => {
|
||||
const seen = vi.fn();
|
||||
const server = nodeHttp.createServer((_req, res) => {
|
||||
seen();
|
||||
res.end('ok');
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
|
||||
try {
|
||||
const { port } = server.address() as net.AddressInfo;
|
||||
const status = await new Promise<string>((resolve, reject) => {
|
||||
const socket = net.connect(port, '127.0.0.1', () => {
|
||||
socket.write('GET / HTTP/1.1\r\nHost: x\r\nX-Email: a\u0000b\r\nConnection: close\r\n\r\n');
|
||||
});
|
||||
let raw = '';
|
||||
socket.on('data', (chunk: Buffer) => {
|
||||
raw += chunk.toString();
|
||||
});
|
||||
socket.on('end', () => resolve(raw.split('\r\n')[0]));
|
||||
socket.on('error', reject);
|
||||
});
|
||||
expect(status).toBe('HTTP/1.1 400 Bad Request');
|
||||
expect(seen).not.toHaveBeenCalled();
|
||||
} finally {
|
||||
await new Promise((resolve) => server.close(resolve));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -138,6 +138,15 @@ describe('TrekWsAdapter wire protocol', () => {
|
||||
expect(socket.sent).toHaveLength(0); // the answer went nowhere
|
||||
});
|
||||
|
||||
it('WSAD-001c: a frame reaches its handler without NUL characters, its type included', () => {
|
||||
// The same rule as every HTTP request (src/nest/common/nul-free-input.ts):
|
||||
// a handler never holds a value the database would store differently.
|
||||
const socket = fakeSocket();
|
||||
adapter.bindMessageHandlers(socket as never, handlers as never, transform);
|
||||
socket.emit('message', frame({ type: 'jo\u0000in', tripId: 7, note: 'a\u0000b', 'k\u0000': ['c\u0000'] }));
|
||||
expect(handled).toEqual([{ type: 'join', tripId: 7, note: 'ab', k: ['c'] }]);
|
||||
});
|
||||
|
||||
it('WSAD-002: a handler that answers undefined sends nothing', () => {
|
||||
const socket = fakeSocket();
|
||||
adapter.bindMessageHandlers(socket as never, handlers as never, transform);
|
||||
|
||||
Reference in New Issue
Block a user