237 lines
14 KiB
TypeScript
237 lines
14 KiB
TypeScript
// SPDX-License-Identifier: GPL-2.0-or-later
|
||
// Copyright (C) 2026 Bryan Joshua Pedini
|
||
|
||
import { test, expect, type World } from '../harness/fixtures';
|
||
import { up, type ApiClient, type ApiResult } from '../harness/api';
|
||
import { intEnv } from '../harness/env';
|
||
import { fuzzRecord, PAYLOADS, QUERY_KEYS, SCRIPT, soaBody, SQL_INJECTION } from '../harness/fuzz';
|
||
import { addAddress, address, checkZone, createZone, zoneInput } from '../harness/personas';
|
||
import { TYPES } from '../harness/records';
|
||
|
||
test.use({ group: 'fuzzer' });
|
||
|
||
function expectBounded(world: World, label: string, result: ApiResult): void {
|
||
if (result.status >= 400) {
|
||
expect(result.text.length, `${label}: bounded error body`).toBeLessThan(4096);
|
||
expect(result.json?.error, `${label}: error body`).toEqual(expect.any(String));
|
||
}
|
||
expect(world.secrets.findIn(result.text), `${label}: no secret`).toEqual([]);
|
||
expect(result.text, `${label}: no internal detail`).not.toMatch(/\$argon2id\$|runtime error:|SQLSTATE|password_hash|goroutine/);
|
||
}
|
||
|
||
async function send(world: World, api: ApiClient, method: string, path: string, options: Parameters<ApiClient['raw']>[2] = {}): Promise<ApiResult> {
|
||
world.recorder.fuzzCases.push({ method, path, ...options });
|
||
return api.raw(method, '/api/v1' + path, options);
|
||
}
|
||
|
||
test('seeded requests cover every API operation, path parameter, filter and DNS record type', async ({ world }) => {
|
||
test.setTimeout(360_000);
|
||
const admin = await world.bootstrapAdmin();
|
||
const api = await world.apiAs(admin);
|
||
const member = await world.createUser(api, 'user');
|
||
const u = up(member.username);
|
||
const zone = world.zoneName();
|
||
const z = await createZone(api, zone);
|
||
const r = await addAddress(api, z, 'initial', '192.0.2.30');
|
||
const rr = `${z}/records`;
|
||
const cases = [
|
||
['GET', '/account'], ['PUT', '/account/password'], ['GET', '/zones'], ['POST', '/zones'],
|
||
['GET', z], ['DELETE', z], ['GET', rr], ['POST', rr],
|
||
['PUT', `${rr}/${r.id}`], ['DELETE', `${rr}/${r.id}`], ['POST', `${rr}/delete`],
|
||
['PUT', `${z}/soa`], ['GET', `${z}/check`], ['GET', '/check'], ['GET', `${z}/export`],
|
||
['POST', `${z}/import/preview`], ['POST', `${z}/import/apply`],
|
||
['GET', `${z}/users`], ['PUT', z + u], ['DELETE', z + u],
|
||
['GET', '/users'], ['POST', '/users'], ['GET', u], ['PUT', `${u}/role`],
|
||
['PUT', `${u}/password`], ['DELETE', u], ['GET', '/audit'],
|
||
] as const;
|
||
const denied = new Set([400, 404, 409, 412, 413, 415, 422, 428]);
|
||
const values: unknown[] = [null, {}, [], 2 ** 40, 'bad value', '', '\u0000', '', ...PAYLOADS];
|
||
let mark = await world.db.auditMaxId();
|
||
const count = Math.max(cases.length, intEnv('E2E_FUZZ_CASES', 81));
|
||
for (let i = 0; i < count; i++) {
|
||
const [method, route] = cases[i < cases.length ? i : world.rng.int(0, cases.length - 1)];
|
||
const key = world.rng.pick(['name', 'type', 'ttl', 'confirm', 'role', 'password', 'data', 'content', 'zone', 'mode']);
|
||
const value = world.rng.pick(values);
|
||
const typo = world.rng.string(5);
|
||
const mutation = { [key]: value, [`unknown_${typo}`]: value };
|
||
const raw = world.rng.pick([JSON.stringify(mutation), JSON.stringify(value), '{"unfinished":', '[false]']);
|
||
const body = method === 'GET' || route === z + u || (method === 'DELETE' && route.startsWith(rr)) ? undefined : raw;
|
||
const query = method === 'GET' ? { [world.rng.pick([...QUERY_KEYS, 'filter'])]: String(value) } : undefined;
|
||
const result = await send(world, api, method, route, { raw: body, contentType: world.rng.pick(['text/plain', 'application/json', 'application/json']), query });
|
||
const maySucceed = method === 'GET' || route === z + u;
|
||
expect((maySucceed && result.status < 300) || denied.has(result.status), `${method} ${route}: ${result.status} ${result.text.slice(0, 250)}`).toBe(true);
|
||
expectBounded(world, `${method} ${route}`, result);
|
||
}
|
||
expect(await world.db.auditSince(mark)).toHaveLength(count);
|
||
expect(await world.db.records(zone)).toHaveLength(3);
|
||
|
||
mark = await world.db.auditMaxId();
|
||
let filters = 0;
|
||
for (const key of QUERY_KEYS) {
|
||
for (const payload of [SQL_INJECTION, SCRIPT, world.rng.pick(PAYLOADS)]) {
|
||
const route = key === 'deleted' ? '/users' : '/audit';
|
||
const result = await send(world, api, 'GET', route, { query: { [key]: payload } });
|
||
filters++;
|
||
expect([200, 400], `GET ${route}?${key}=${payload}: ${result.status} ${result.text.slice(0, 250)}`).toContain(result.status);
|
||
expectBounded(world, `GET ${route}?${key}`, result);
|
||
if (result.status === 200 && (key === 'zone' || key === 'actor')) expect(result.json.entries, `the ${key} filter matches the payload literally`).toEqual([]);
|
||
if (result.status === 200 && key === 'deleted') expect(result.json.users.map((x: { username: string }) => x.username)).toEqual(expect.arrayContaining([admin.username, member.username]));
|
||
}
|
||
}
|
||
expect(await world.db.auditSince(mark), 'one audit row per filter request').toHaveLength(filters);
|
||
|
||
const etag = `"${'0'.repeat(64)}"`;
|
||
const { name: _zoneName, extra_ns: _extra, ...soa } = zoneInput(zone);
|
||
const templates: Array<[string, string, unknown?]> = [
|
||
['GET', '/zones/{zone}'],
|
||
['DELETE', '/zones/{zone}', { confirm: zone }],
|
||
['GET', '/zones/{zone}/records'],
|
||
['POST', '/zones/{zone}/records', address('path', '192.0.2.77')],
|
||
['PUT', '/zones/{zone}/records/{id}', address('path', '192.0.2.77')],
|
||
['DELETE', '/zones/{zone}/records/{id}'],
|
||
['POST', '/zones/{zone}/records/delete', { records: [{ id: r.id, etag }] }],
|
||
['PUT', '/zones/{zone}/soa', soa],
|
||
['GET', '/zones/{zone}/check'],
|
||
['GET', '/zones/{zone}/export'],
|
||
['POST', '/zones/{zone}/import/preview', { mode: 'merge', content: 'path 300 IN A 192.0.2.77' }],
|
||
['POST', '/zones/{zone}/import/apply', { mode: 'merge', content: 'path 300 IN A 192.0.2.77', fingerprint: '0'.repeat(64) }],
|
||
['GET', '/zones/{zone}/users'],
|
||
['PUT', '/zones/{zone}/users/{username}'],
|
||
['DELETE', '/zones/{zone}/users/{username}'],
|
||
['GET', '/users/{username}'],
|
||
['PUT', '/users/{username}/role', { role: 'user' }],
|
||
['PUT', '/users/{username}/password', { password: world.password('fuzzed password') }],
|
||
['DELETE', '/users/{username}', { confirm: member.username }],
|
||
];
|
||
const actual: Record<string, string> = { zone, id: String(r.id), username: member.username };
|
||
const pathPayloads = [SQL_INJECTION, SCRIPT, world.rng.pick(PAYLOADS.slice(2)), world.rng.pick(['\u0000', '', 'bad value', '%', 'éxample.org'])];
|
||
mark = await world.db.auditMaxId();
|
||
let paths = 0;
|
||
for (const [method, template, body] of templates) {
|
||
for (const param of ['zone', 'id', 'username'].filter((p) => template.includes(`{${p}}`))) {
|
||
for (const payload of pathPayloads) {
|
||
const path = template.replace(/\{(zone|id|username)\}/g, (_m, p: string) => encodeURIComponent(p === param ? payload : actual[p]));
|
||
const ifMatch = /\/(records\/\{id\}|soa)$/.test(template) ? etag : undefined;
|
||
const result = await send(world, api, method, path, { body, ifMatch });
|
||
paths++;
|
||
expect([400, 403, 404, 422], `${method} ${template} with ${param}=${JSON.stringify(payload)}: ${result.status} ${result.text.slice(0, 250)}`).toContain(result.status);
|
||
expectBounded(world, `${method} ${template} ${param}`, result);
|
||
}
|
||
}
|
||
}
|
||
expect(await world.db.auditSince(mark), 'one audit row per path parameter request').toHaveLength(paths);
|
||
expect(await world.db.records(zone)).toHaveLength(3);
|
||
expect((await world.db.user(member.username))?.deleted_at).toBeNull();
|
||
|
||
const types = {
|
||
A: { ip: '192.0.2.42' },
|
||
AAAA: { ip: '2001:db8::42' },
|
||
CNAME: { host: `initial.${zone}` },
|
||
NS: { host: 'ns2.example.net.' },
|
||
MX: { host: '.', preference: 0 },
|
||
TXT: { text: 'random fixture' },
|
||
SRV: { priority: 0, weight: 0, port: 0, target: '.' },
|
||
CAA: { flag: 0, tag: 'issue', value: 'ca.example.net' },
|
||
SOA: { ns: 'ns.example.net.', MBox: 'hostmaster.example.net.', refresh: 3600, retry: 600, expire: 604800, minttl: 300 },
|
||
};
|
||
for (const [type, data] of Object.entries(types)) {
|
||
const owner = type === 'SOA' ? '@' : type === 'SRV' ? '_service._tcp' : world.rng.string(8).toLowerCase();
|
||
const ttl = world.rng.int(1, 86400);
|
||
const wrong = { name: owner, type, ttl: -ttl, data };
|
||
world.recorder.fuzzCases.push(wrong);
|
||
expect((await api.post(rr, wrong)).status).toBe(422);
|
||
if (type !== 'SOA') expect((await api.post(rr, { ...wrong, ttl })).status).toBe(201);
|
||
}
|
||
let rows = (await world.db.records(zone)).length;
|
||
|
||
const perType = intEnv('E2E_FUZZ_RECORDS', 8);
|
||
const accepted: Record<string, number> = {};
|
||
let seq = 0;
|
||
for (const type of TYPES) {
|
||
accepted[type] = 0;
|
||
for (let i = 0; i < perType; i++) {
|
||
const record = fuzzRecord(world.rng, zone, type, seq++, i > 0);
|
||
world.recorder.fuzzCases.push({ record });
|
||
const created = await api.post(rr, record);
|
||
const label = `POST ${type} ${JSON.stringify(record)}`;
|
||
expect([201, 422], `${label}: ${created.status} ${created.text.slice(0, 250)}`).toContain(created.status);
|
||
expectBounded(world, label, created);
|
||
if (type === 'SOA') expect(created.status, `${label}: the SOA is never created through the records route`).toBe(422);
|
||
if (type !== 'SOA' && i === 0) expect(created.status, `${label}: a valid record is accepted ${created.text}`).toBe(201);
|
||
if (created.status === 201) {
|
||
accepted[type]++;
|
||
rows++;
|
||
expect(created.json.record).toMatchObject({ type, id: expect.any(Number) });
|
||
}
|
||
if (type === 'SOA') {
|
||
const current = await api.get(z);
|
||
const updated = await api.put(`${z}/soa`, soaBody(record), { ifMatch: current.etag ?? etag });
|
||
const what = `PUT soa ${JSON.stringify(soaBody(record))}`;
|
||
expect([200, 422], `${what}: ${updated.status} ${updated.text.slice(0, 250)}`).toContain(updated.status);
|
||
expectBounded(world, what, updated);
|
||
if (i === 0) expect(updated.status, `${what}: a valid SOA is accepted ${updated.text}`).toBe(200);
|
||
if (updated.status === 200) accepted[type]++;
|
||
}
|
||
}
|
||
}
|
||
world.recorder.note(`accepted fuzzed records per type: ${JSON.stringify(accepted)}`);
|
||
expect(await world.db.records(zone), 'exactly the accepted records were stored').toHaveLength(rows);
|
||
const { name, extra_ns, ...updatedSoa } = zoneInput(zone);
|
||
expect((await api.put(`${z}/soa`, { ...updatedSoa, ttl: world.rng.int(1, 600) }, { ifMatch: (await api.get(z)).etag! })).status).toBe(200);
|
||
await checkZone(world, api, zone);
|
||
});
|
||
|
||
test('script payloads render as plain text in the audit diff and the import preview', async ({ world }) => {
|
||
test.setTimeout(180_000);
|
||
const admin = await world.bootstrapAdmin();
|
||
const api = await world.apiAs(admin);
|
||
const zone = world.zoneName('render-');
|
||
const z = await createZone(api, zone);
|
||
const literal = `<script>window.__pwned=1</script><img src=x onerror="window.__pwned=2">${SQL_INJECTION}`;
|
||
const foreign = JSON.stringify({ text: literal });
|
||
const foreignId = await world.db.insertRaw({ zone, name: 'foreign', ttl: 300, content: foreign, record_type: 'TXT' });
|
||
const native = await api.post(`${z}/records`, { name: 'native', type: 'TXT', ttl: 300, data: { text: literal } });
|
||
expect(native.status, native.text).toBe(201);
|
||
const nativeContent = (await world.db.recordById(native.json.record.id))?.content as string;
|
||
const ui = await world.uiAs(admin);
|
||
await ui.openZone(zone);
|
||
await ui.deleteRecord({ name: 'foreign', type: 'TXT' }, { expectStatus: 200 });
|
||
expect(await world.db.recordById(foreignId)).toBeUndefined();
|
||
|
||
const expectDiff = async (operation: string, side: 'Before' | 'After', id: number, content: string) => {
|
||
await ui.filterAudit({ zone, operation });
|
||
expect(await ui.auditRows()).toHaveLength(1);
|
||
const toggle = ui.page.locator('#audit-body button[aria-expanded]').first();
|
||
await toggle.click();
|
||
const diff = ui.page.locator('#audit-body tr.detail-row:not([hidden]) table.diff');
|
||
await expect(diff).toBeVisible();
|
||
const row = diff.locator('tbody tr').filter({ has: ui.page.locator('th', { hasText: new RegExp(`^(record ${id}\\.)?content$`) }) });
|
||
await expect(row).toHaveCount(1);
|
||
const marker = side === 'Before' ? '−' : '+';
|
||
const cell = row.getByRole('group', { name: side + ' content' });
|
||
await expect(cell).toHaveText(`${marker} Text: ${JSON.parse(content).text}`);
|
||
await expect(ui.page.locator('#app script, #app img')).toHaveCount(0);
|
||
};
|
||
const pwned = () => ui.page.evaluate(() => (window as unknown as { __pwned?: number }).__pwned);
|
||
await expectDiff('record_delete', 'Before', foreignId, foreign);
|
||
await expect(ui.page.locator('#audit-body').getByText('<script>window.__pwned=1</script><img src=x onerror=', { exact: false })).toBeVisible();
|
||
await expectDiff('record_create', 'After', native.json.record.id, nativeContent);
|
||
expect(await pwned(), 'no payload ran on the audit page').toBeUndefined();
|
||
|
||
const imported = `<script>window.__pwned=3</script><img src=x onerror=window.__pwned=4>${SQL_INJECTION}`;
|
||
const skipped = '<script>window.__pwned=5</script>';
|
||
const file = `imported 300 IN TXT "${imported}"\nlegacy 300 IN HINFO "${skipped}" "x"\n`;
|
||
const preview = await ui.importPreview(zone, file, 'merge');
|
||
expect(preview.status, JSON.stringify(preview.json)).toBe(200);
|
||
expect(preview.json.added).toHaveLength(1);
|
||
expect(preview.json.skipped).toHaveLength(1);
|
||
expect(preview.json.added[0].value).toContain(imported);
|
||
expect(preview.json.skipped[0].text).toContain(skipped);
|
||
const spaced = (text: string) => text.replace(/\s+/g, ' ');
|
||
await expect(ui.page.locator('#import-tables td.mono').filter({ hasText: imported })).toHaveText(spaced(preview.json.added[0].value));
|
||
await expect(ui.page.locator('#import-tables code').filter({ hasText: skipped })).toHaveText(spaced(preview.json.skipped[0].text));
|
||
await expect(ui.page.locator('#app script, #app img')).toHaveCount(0);
|
||
expect(await pwned(), 'no payload ran on the import page').toBeUndefined();
|
||
await checkZone(world, api, zone);
|
||
});
|