From 1cafcc759e66e0f2912f7fd4d7f5962c0f8a4b8b Mon Sep 17 00:00:00 2001 From: Bryan Joshua Pedini Date: Thu, 19 Nov 2026 14:40:08 +0100 Subject: [PATCH] test(e2e): set a user password and revoke a delegation from the web ui - test(e2e): set a user password and revoke a delegation from the web ui - test(e2e): switch a dynamic soa serial to a managed one through the ui - test(e2e): match audit ledger routes on the decoded api path - test(e2e): fuzz injection payloads in paths, filters and record data --- README.md | 2 +- e2e/compose.yaml | 1 + e2e/harness/fuzz.ts | 124 +++++++++++++++++++++++++ e2e/harness/ledger.ts | 14 +-- e2e/tests/core.spec.ts | 126 ++++++++++++++++++++++++- e2e/tests/fuzzer.spec.ts | 189 ++++++++++++++++++++++++++++++++++---- e2e/tests/harness.spec.ts | 5 +- 7 files changed, 433 insertions(+), 28 deletions(-) create mode 100644 e2e/harness/fuzz.ts diff --git a/README.md b/README.md index 9bc25df..bd46ace 100644 --- a/README.md +++ b/README.md @@ -429,7 +429,7 @@ docker run --rm -v "$PWD":/src -w /src -v coredns-web-ui-gomod:/go/pkg/mod -e GO Prerequisites: Docker with the Compose plugin, access to the Docker socket (the runner mounts `E2E_DOCKER_SOCKET`, default `/var/run/docker.sock`, to restart application containers), network access to pull the missing images and to build the runner (`apt` and `npm ci`), and about 2 GiB of memory for the MySQL tmpfs. The application image must already exist (`make docker`; `make test-e2e` builds it). Images the script had to pull are removed again at the end. -Optional environment variables: `E2E_RUN_ID` (lowercase letters, digits and hyphens; default random), `E2E_SEED` (reproduces a failing seed), `E2E_WORKERS` (default 4), `E2E_FUZZ_CASES`, `E2E_OPERATOR_ACTIONS` and `E2E_ARGS` (extra `playwright test` arguments). Resources are named `cdwu-e2e-`, are removed at exit, and the script fails when a run leaves any behind. Reports, screenshots and failing seeds are copied to `e2e/reports/cdwu-e2e-/`. +Optional environment variables: `E2E_RUN_ID` (lowercase letters, digits and hyphens; default random), `E2E_SEED` (reproduces a failing seed), `E2E_WORKERS` (default 4), `E2E_FUZZ_CASES`, `E2E_FUZZ_RECORDS` (fuzzed records per type, default 8), `E2E_OPERATOR_ACTIONS` and `E2E_ARGS` (extra `playwright test` arguments). Resources are named `cdwu-e2e-`, are removed at exit, and the script fails when a run leaves any behind. Reports, screenshots and failing seeds are copied to `e2e/reports/cdwu-e2e-/`. ### Continuous integration diff --git a/e2e/compose.yaml b/e2e/compose.yaml index cca38a8..7ebd05c 100644 --- a/e2e/compose.yaml +++ b/e2e/compose.yaml @@ -264,6 +264,7 @@ services: E2E_SEED: ${E2E_SEED:-} E2E_WORKERS: ${E2E_WORKERS:-4} E2E_FUZZ_CASES: ${E2E_FUZZ_CASES:-} + E2E_FUZZ_RECORDS: ${E2E_FUZZ_RECORDS:-} E2E_OPERATOR_ACTIONS: ${E2E_OPERATOR_ACTIONS:-} E2E_ARGS: ${E2E_ARGS:-} command: ["sh", "-c", "npx tsc --noEmit && exec npx playwright test $$E2E_ARGS"] diff --git a/e2e/harness/fuzz.ts b/e2e/harness/fuzz.ts new file mode 100644 index 0000000..019612c --- /dev/null +++ b/e2e/harness/fuzz.ts @@ -0,0 +1,124 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import type { RecordType } from './records'; +import type { Rng } from './rng'; + +export const SQL_INJECTION = "' OR '1'='1' -- "; +export const SCRIPT = ''; + +export const PAYLOADS = [ + SQL_INJECTION, + SCRIPT, + `${SCRIPT}${SQL_INJECTION}`, + "x'); DROP TABLE users; --", + '" OR ""="', + '">', + "admin'--", + '1 UNION SELECT username FROM users', +] as const; + +export const AUDIT_FILTER_KEYS = ['zone', 'actor', 'operation', 'kind', 'outcome', 'before_id', 'limit'] as const; +export const QUERY_KEYS = [...AUDIT_FILTER_KEYS, 'deleted'] as const; + +export interface FuzzRecord { + name: unknown; + type: RecordType; + ttl: unknown; + data: Record; +} + +interface Field { + valid: readonly unknown[]; + hostile: readonly unknown[]; +} + +const INTEGERS_HOSTILE: readonly unknown[] = [65536, 2147483648, -1, '10', 1.5, null, SQL_INJECTION]; +const U16: Field = { valid: [0, 1, 10, 65535], hostile: INTEGERS_HOSTILE }; +const TTL: Field = { valid: [0, 1, 300, 86400, 2147483647], hostile: [2147483648, -1, '300', 1.5, null, SQL_INJECTION] }; +const TEXT: Field = { + valid: ["it's", 'a;b;c', 'bold', 'say "hi"', SQL_INJECTION, SCRIPT, 'plain text', 'x'.repeat(300), '">'], + hostile: ['', 'back\\slash', 'tab\there', 'café', 'nul\u0000byte', 'x'.repeat(4097), 7, null], +}; +const IPV4: Field = { valid: ['192.0.2.55', '198.51.100.7', '203.0.113.200'], hostile: ['2001:db8::55', '256.0.0.1', '192.0.2.055', '::ffff:192.0.2.1', SQL_INJECTION, SCRIPT, '', 3221225985] }; +const IPV6: Field = { valid: ['2001:db8::55', '2001:db8:0:0:0:0:0:56', '2001:DB8::57'], hostile: ['192.0.2.55', '::ffff:192.0.2.1', '2001:db8::g', SQL_INJECTION, SCRIPT, '', 1] }; +const CAA_TAG: Field = { valid: ['issue', 'issuewild', 'iodef'], hostile: ['bad tag', SCRIPT, SQL_INJECTION, '', 'x'.repeat(256), 1] }; +const CAA_FLAG: Field = { valid: [0, 128], hostile: [256, -1, '0', SQL_INJECTION, null] }; +const SOA_TIMER: Field = { valid: [60, 3600, 604800, 2147483647], hostile: [0, -1, 2147483648, 4294967296, '3600', null, SQL_INJECTION] }; + +function hosts(zone: string): Field { + return { + valid: ['target.example.net.', `www.${zone}`, 'mail.example.net'], + hostile: ['single-label', SQL_INJECTION, SCRIPT, '-bad-.example.net.', 'a..b.example.net.', '', `${'x'.repeat(64)}.example.net.`, 'under score!.example.net.', 5], + }; +} + +function fields(zone: string, type: RecordType): Record { + const host = hosts(zone); + switch (type) { + case 'A': + return { ip: IPV4 }; + case 'AAAA': + return { ip: IPV6 }; + case 'CNAME': + case 'NS': + return { host }; + case 'MX': + return { host: { valid: ['mail.example.net.', `mx.${zone}`], hostile: host.hostile }, preference: U16 }; + case 'TXT': + return { text: TEXT }; + case 'SRV': + return { priority: U16, weight: U16, port: U16, target: { valid: ['sip.example.net.', '.'], hostile: host.hostile } }; + case 'CAA': + return { flag: CAA_FLAG, tag: CAA_TAG, value: { valid: TEXT.valid.filter((t) => t !== '' && String(t).length < 256), hostile: TEXT.hostile } }; + case 'SOA': + return { + ns: { valid: ['ns1.example.net.', `ns1.${zone}`], hostile: host.hostile }, + MBox: { valid: ['hostmaster.example.net.', `hostmaster.${zone}`], hostile: [...host.hostile, 'host@master@example.net'] }, + refresh: SOA_TIMER, + retry: SOA_TIMER, + expire: SOA_TIMER, + minttl: SOA_TIMER, + }; + } +} + +function freshName(rng: Rng, type: RecordType, seq: number): string { + const label = `f${seq}${rng.string(5)}`; + const choices = type === 'SRV' ? [`_${label}._tcp`, `_${label}._udp`] : [label, `${label}.sub`, label.toUpperCase()]; + if (type !== 'NS' && type !== 'SRV') choices.push(`*.${label}`); + if (type === 'NS' || type === 'MX' || type === 'TXT' || type === 'CAA') choices.push('@'); + return rng.pick(choices); +} + +const NAME_HOSTILE: readonly unknown[] = [SQL_INJECTION, SCRIPT, '', 'bad name', 'x'.repeat(64), '*bad', 'nul\u0000', 7, null]; + +export function fuzzRecord(rng: Rng, zone: string, type: RecordType, seq: number, mutate: boolean): FuzzRecord { + const spec = fields(zone, type); + const data: Record = {}; + for (const [key, field] of Object.entries(spec)) data[key] = rng.pick(field.valid); + const record: FuzzRecord = { name: type === 'SOA' ? '@' : freshName(rng, type, seq), type, ttl: rng.pick(TTL.valid), data }; + if (!mutate) return record; + const keys = Object.keys(spec); + const target = rng.weighted([ + ['name', 2], + ['ttl', 2], + ['data', 6], + ['missing', 1], + ['extra', 1], + ]); + if (target === 'name') record.name = rng.pick(NAME_HOSTILE); + else if (target === 'ttl') record.ttl = rng.pick(TTL.hostile); + else if (target === 'missing') delete data[rng.pick(keys)]; + else if (target === 'extra') data[rng.pick(['serial', 'Ttl', 'comment', 'ip', 'host'])] = rng.pick(PAYLOADS); + else { + const key = rng.pick(keys); + data[key] = rng.pick(spec[key].hostile); + } + return record; +} + +export function soaBody(record: FuzzRecord): Record { + const d = record.data; + return { ns: d.ns, mbox: d.MBox, ttl: record.ttl, refresh: d.refresh, retry: d.retry, expire: d.expire, minttl: d.minttl }; +} diff --git a/e2e/harness/ledger.ts b/e2e/harness/ledger.ts index 9cb03c3..df49c92 100644 --- a/e2e/harness/ledger.ts +++ b/e2e/harness/ledger.ts @@ -81,11 +81,12 @@ export interface RouteMatch { targetUser: string | null; } -function decode(segment: string): string | null { +export function decodedApiPath(path: string): string { + const raw = path.slice('/api/v1'.length).split('?')[0]; try { - return decodeURIComponent(segment); + return decodeURIComponent(raw); } catch { - return null; + return raw; } } @@ -102,11 +103,11 @@ export function matchRoute(method: string, apiPath: string): RouteMatch | null { if (m !== method.toUpperCase()) continue; const match = re.exec(apiPath); if (!match) continue; - const groups = match.slice(1).map((s) => decode(s)); + const groups = match.slice(1); const out: RouteMatch = { operation, zone: null, recordId: null, targetUser: null }; targets.forEach((t, i) => { const v = groups[i]; - if (v === null || v === undefined) return; + if (v === undefined) return; if (t === 'zone') out.zone = normalizeZoneParam(v); if (t === 'record' && /^\+?[0-9]+$/.test(v)) { const id = Number(v); @@ -204,8 +205,7 @@ export class AuditLedger { api(x: ApiExchange): void { if (!x.path.startsWith('/api/v1/') && x.path !== '/api/v1') return; - const apiPath = x.path.slice('/api/v1'.length).split('?')[0]; - const route = matchRoute(x.method, apiPath); + const route = matchRoute(x.method, decodedApiPath(x.path)); if (!x.sessionValid || x.status === 401 || x.crossOrigin) { this.skipped++; return; diff --git a/e2e/tests/core.spec.ts b/e2e/tests/core.spec.ts index e96c13e..90e9dc9 100644 --- a/e2e/tests/core.spec.ts +++ b/e2e/tests/core.spec.ts @@ -5,7 +5,7 @@ import { test, expect, type Account } from '../harness/fixtures'; import type { ApiClient } from '../harness/api'; import { zp, up } from '../harness/api'; import { parseTable, USAGE_TEXT } from '../harness/cli'; -import { waitForZone, waitForZoneGone } from '../harness/dig'; +import { servedSerial, waitForZone, waitForZoneGone } from '../harness/dig'; import { runnerAddress, SESSION_COOKIE } from '../harness/env'; import { bulkDeleteBody, expectCheckErrorRowsCarryRaw, expectZoneCreateWarnings, importApplyBody, UNKNOWN_API_OPERATION, ZONE_CREATE_DELEGATIONS_IN } from '../harness/decisions'; import { READ_OPERATIONS } from '../harness/ledger'; @@ -660,6 +660,79 @@ test.describe('core flow', () => { await servedZone(world, zone); }); + test('a dynamic SOA serial is shown, served as Unix time and replaced by a managed serial through the UI', async ({ world }) => { + test.setTimeout(180_000); + const ui = adminUi; + const dz = world.zoneName('dynamic-'); + expect((await adminApi.post('/zones', { name: dz, ns: `ns1.${dz}`, mbox: `hostmaster@${dz}`, extra_ns: [], refresh: 3600, retry: 600, expire: 604800, minttl: 300, ttl: 3600 })).status).toBe(201); + await waitForZone(world.g, dz, { recorder: world.recorder }); + const managedSoa = (await world.db.records(dz)).find((r) => r.record_type === 'SOA')!; + const { serial: createdSerial, ...timers } = JSON.parse(managedSoa.content!) as Record; + expect(createdSerial).toEqual(expect.any(Number)); + await world.db.updateRaw(managedSoa.id, { content: JSON.stringify(timers) }); + expect(await world.db.soaSerial(dz), 'the SOA has no serial key').toBeNull(); + + await ui.openZone(dz); + expect((await ui.soaSummary()).Serial).toBe('dynamic (Unix time)'); + await expect(ui.page.locator('#soa-managed')).toBeVisible(); + await ui.expectRow({ name: '@', type: 'SOA', value: uiValue('SOA', { ...timers, serial: 'dynamic (Unix time)' }) }); + expect(await ui.problems()).toContainEqual({ severity: 'warning', code: 'soa_dynamic_serial', where: '(@ SOA)' }); + expect((await adminApi.get(`${zp(dz)}/check`)).json.problems).toContainEqual(expect.objectContaining({ severity: 'warning', code: 'soa_dynamic_serial', id: managedSoa.id, name: '', type: 'SOA' })); + await ui.goto('/'); + expect(await ui.zonesTable()).toContainEqual(expect.objectContaining({ zone: dz, serial: 'dynamic' })); + const before = Math.floor(Date.now() / 1000); + const unixSerial = await servedSerial(world.g, dz, { recorder: world.recorder }); + const after = Math.floor(Date.now() / 1000); + expect(unixSerial, 'CoreDNS serves the Unix time as the dynamic serial').toBeGreaterThanOrEqual(before - 5); + expect(unixSerial).toBeLessThanOrEqual(after + 5); + await served(world, dz, dz, 'SOA', 'dynamic serial'); + + await ui.openZone(dz); + const rowsBefore = await world.db.records(dz); + const mark = await world.db.auditMaxId(); + const t0 = new Date(); + const done = ui.page.waitForResponse((r) => new URL(r.url()).pathname.endsWith('/soa') && r.request().method() === 'PUT'); + await ui.page.click('#soa-managed'); + expect((await done).status()).toBe(200); + await ui.settle(); + await ui.expectToast('The zone now uses a managed serial.'); + const serial = (await world.db.soaSerial(dz)) as number; + expect([utcDay(t0), utcDay(new Date())], 'the managed serial is YYYYMMDD00 of today').toContain(serial); + const soaRow = await storedRow(world, dz, { name: '', type: 'SOA', ttl: managedSoa.ttl as number, data: { ...timers, serial } }); + expect(soaRow.id).toBe(managedSoa.id); + for (const r of rowsBefore.filter((x) => x.id !== managedSoa.id)) expect(await world.db.recordById(r.id)).toEqual(r); + await expect.poll(async () => (await ui.soaSummary()).Serial).toBe(String(serial)); + await expect(ui.page.locator('#soa-managed')).toBeHidden(); + await ui.expectRow({ name: '@', type: 'SOA', value: uiValue('SOA', { ...timers, serial }) }); + expect((await ui.problems()).some((p) => p.code === 'soa_dynamic_serial')).toBe(false); + await served(world, dz, dz, 'SOA', 'managed serial in the answer'); + await served(world, dz, `missing.${dz}`, 'TXT', 'managed serial in the authority section'); + expect(await servedSerial(world.g, dz, { recorder: world.recorder })).toBe(serial); + const audits = (await auditSince(world, mark)).filter((r) => r.operation === 'soa_update'); + expect(audits, 'exactly one soa_update audit row').toHaveLength(1); + expect(audits[0]).toMatchObject({ actor: admin.username, status: 200, error: null, zone: dz, record_id: managedSoa.id, target_user_id: null }); + const dynamicRow = rowsBefore.find((r) => r.id === managedSoa.id)!; + expectAuditRecord(parsedJson(audits[0].before_value), dynamicRow, 'soa_update before'); + expectAuditRecord(parsedJson(audits[0].after_value), soaRow, 'soa_update after'); + const contentOf = (v: unknown) => { + const c = (parsedJson(v) as { content: unknown }).content; + return (typeof c === 'string' ? JSON.parse(c) : c) as Record; + }; + expect(contentOf(audits[0].before_value)).not.toHaveProperty('serial'); + expect(contentOf(audits[0].after_value)).toHaveProperty('serial', serial); + + const rec: Rec = { name: 'after-managed', type: 'TXT', ttl: 300, data: { text: 'managed serial bump' } }; + const change = await begin(world, dz); + await ui.addRecord({ name: rec.name, type: 'TXT', ttl: '300', fields: { text: 'managed serial bump' } }, { expectStatus: 201 }); + await threeWay(world, ui, dz, rec, change, 'the first change after the managed serial'); + const next = (await world.db.soaSerial(dz)) as number; + if (utcDay(new Date()) === serial) expect(next, 'the next change of the day is YYYYMMDD01').toBe(serial + 1); + expect(await servedSerial(world.g, dz, { recorder: world.recorder })).toBe(next); + await expect.poll(async () => (await ui.soaSummary()).Serial).toBe(String(next)); + expect((await adminApi.get(`${zp(dz)}/check`)).json.problems.filter((p: { severity: string }) => p.severity === 'error')).toEqual([]); + await servedZone(world, dz); + }); + test('7. users and delegation: roles, zone visibility, revocation, promotion, deletion and the last active admin', async ({ world }) => { test.setTimeout(600_000); zoneB = `${world.unique('second-')}.core.test.`; @@ -811,6 +884,57 @@ test.describe('core flow', () => { expect((await adminUi.setRoleUi('user')).status).toBe(204); expect((await u1api.get(zp(zone))).status, 'the delegation applies again after the demotion').toBe(200); + const u2id = (await world.db.user(user2.username))?.id as number; + const hashBefore = (await world.db.user(user2.username))?.password_hash; + expect((await u2api.get('/account')).status, 'the API session of the user is open').toBe(200); + expect((await world.db.sessions(u2id)).length, 'the user has an API and a browser session').toBe(2); + const setPassword = world.password('password of bob set by an admin'); + await adminUi.openUser(user2.username); + const pwMark = await world.db.auditMaxId(); + const pwSet = await adminUi.setPasswordUi(setPassword); + expect(pwSet.status, JSON.stringify(pwSet.json)).toBe(204); + await adminUi.expectToast(`Password set. The sessions of ${user2.username} ended.`); + const pwAudits = (await auditSince(world, pwMark)).filter((r) => r.operation === 'user_password'); + expect(pwAudits, 'exactly one user_password audit row').toHaveLength(1); + const pwAudit = pwAudits[0]; + expect(pwAudit).toMatchObject({ user_id: rootId, actor: admin.username, origin: runnerAddress(), status: 204, error: null, zone: null, record_id: null, target_user_id: u2id }); + for (const value of [pwAudit.before_value, pwAudit.after_value]) { + const snapshot = parsedJson(value) as Record; + expect(Object.keys(snapshot).sort()).toEqual(['created_at', 'deleted_at', 'id', 'role', 'username']); + expect(snapshot).toMatchObject({ id: u2id, username: user2.username, role: 'user', deleted_at: null }); + } + expect(JSON.stringify(pwAudit)).not.toMatch(/argon2|password_hash/); + expect(JSON.stringify(pwAudit)).not.toContain(setPassword); + expect(await world.db.sessions(u2id), 'setting a password ends every session of the user').toEqual([]); + const u2row = await world.db.user(user2.username); + expect(u2row?.password_hash).toMatch(/^\$argon2id\$v=19\$m=65536,t=3,p=2\$/); + expect(u2row?.password_hash, 'the stored hash changed').not.toBe(hashBefore); + expect((await u2api.get('/account')).status, 'the open API session of the user ended').toBe(401); + u2api.forgetSession(); + await u2ui.page.reload(); + await expect(u2ui.page).toHaveURL(/\/login/); + u2ui.sessionEnded(); + const oldPassword = await (await world.api()).login(user2.username, user2.password); + expect(oldPassword.status, 'the previous password is refused').toBe(401); + user2 = { ...user2, password: setPassword }; + const u2next = await world.apiAs(user2); + expect((await u2next.get('/account')).status, 'the password set by the admin works').toBe(200); + + await adminUi.openZone(zoneB); + expect((await adminUi.delegateFromZonePage(user2.username)).status).toBe(204); + await expect.poll(() => adminUi.zoneUsers()).toEqual([user2.username]); + expect((await u2next.get(zp(zoneB))).status, 'the delegation from the zone page applies').toBe(200); + const revokeMark = await world.db.auditMaxId(); + expect((await adminUi.revokeFromZonePage(user2.username)).status).toBe(204); + await expect.poll(() => adminUi.zoneUsers()).toEqual([]); + const revokes = (await auditSince(world, revokeMark)).filter((r) => r.operation === 'delegation_revoke'); + expect(revokes, 'exactly one delegation_revoke audit row').toHaveLength(1); + expect(revokes[0]).toMatchObject({ user_id: rootId, actor: admin.username, status: 204, error: null, zone: zoneB, record_id: null, target_user_id: u2id }); + expect(parsedJson(revokes[0].before_value)).toEqual({ zone: zoneB, username: user2.username }); + expect(revokes[0].after_value).toBeNull(); + expect((await world.db.delegations()).filter((d) => d.zone === zoneB && d.user_id === u2id), 'the delegation row is gone').toEqual([]); + expect((await u2next.get(zp(zoneB))).status, 'a revocation from the zone page takes effect on the next request').toBe(404); + await adminUi.openUser(admin.username); await expect(adminUi.page.locator('#user-self')).toBeVisible(); await expect(adminUi.page.locator('#role-form')).toHaveCount(0); diff --git a/e2e/tests/fuzzer.spec.ts b/e2e/tests/fuzzer.spec.ts index 774d4ff..3c1a9bb 100644 --- a/e2e/tests/fuzzer.spec.ts +++ b/e2e/tests/fuzzer.spec.ts @@ -1,15 +1,31 @@ // SPDX-License-Identifier: GPL-2.0-or-later // Copyright (C) 2026 Bryan Joshua Pedini -import { test, expect } from '../harness/fixtures'; -import { up } from '../harness/api'; +import { test, expect, type World } from '../harness/fixtures'; +import { up, type ApiClient, type ApiResult } from '../harness/api'; import { intEnv } from '../harness/env'; -import { addAddress, checkZone, createZone, zoneInput } from '../harness/personas'; +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' }); -test('seeded requests cover every API operation and DNS record type', async ({ world }) => { - test.setTimeout(240_000); +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[2] = {}): Promise { + 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'); @@ -29,33 +45,84 @@ test('seeded requests cover every API operation and DNS record type', async ({ w ['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', '\u200b']; - const mark = await world.db.auditMaxId(); + 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']); + 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(['limit', 'before_id', 'kind', 'actor', 'filter', 'deleted'])]: String(value) } : undefined; - const options = { raw: body, contentType: world.rng.pick(['text/plain', 'application/json', 'application/json']), query }; - world.recorder.fuzzCases.push({ method, route, ...options }); - const result = await api.raw(method, '/api/v1' + route, options); + 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); - if (result.status >= 400) { - expect(result.text.length).toBeLessThan(4096); - expect(result.json.error).toEqual(expect.any(String)); - } - expect(world.secrets.findIn(result.text)).toEqual([]); - expect(result.text).not.toMatch(/\$argon2id\$|runtime error:|SQLSTATE/); + 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 = { 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' }, @@ -75,7 +142,93 @@ test('seeded requests cover every API operation and DNS record type', async ({ w 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 = {}; + 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 = `${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); + await expect(row.locator('td').nth(side === 'Before' ? 0 : 1)).toHaveText(JSON.stringify(content).replace(/\s+/g, ' ')); + 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('window.__pwned=3${SQL_INJECTION}`; + const skipped = ''; + 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); +}); diff --git a/e2e/tests/harness.spec.ts b/e2e/tests/harness.spec.ts index 43eb09b..b59b3b0 100644 --- a/e2e/tests/harness.spec.ts +++ b/e2e/tests/harness.spec.ts @@ -6,7 +6,7 @@ import { run } from '../harness/proc'; import { docker } from '../harness/docker'; import { parseDig } from '../harness/dig'; import { containerName, GROUPS, project, RUN_LABEL } from '../harness/env'; -import { matchRoute, sanitizeActor } from '../harness/ledger'; +import { decodedApiPath, matchRoute, sanitizeActor } from '../harness/ledger'; import { parseTable, USAGE_TEXT } from '../harness/cli'; import { rawRecord, sqlZone, canonicalContent, digData, bumpSerial, utcDay, type RawRecordInput } from '../harness/records'; import { Rng, testSeed } from '../harness/rng'; @@ -87,6 +87,9 @@ test.describe('harness self-checks', () => { expect(matchRoute('PUT', '/zones/example.org/records/12')).toEqual({ operation: 'record_update', zone: 'example.org.', recordId: 12, targetUser: null }); expect(matchRoute('DELETE', '/zones/Example.ORG./users/bob')).toEqual({ operation: 'delegation_revoke', zone: 'example.org.', recordId: null, targetUser: 'bob' }); expect(matchRoute('POST', '/zones/x.org/records/delete')?.operation).toBe('record_bulk_delete'); + expect(decodedApiPath('/api/v1/zones/a%20b.org/records?limit=1')).toBe('/zones/a b.org/records'); + expect(matchRoute('GET', decodedApiPath('/api/v1/users/%3Cscript%3Ex%3C%2Fscript%3E'))).toBeNull(); + expect(matchRoute('PUT', decodedApiPath('/api/v1/zones/x.org/users/%27%20OR%20%271%27'))).toEqual({ operation: 'delegation_grant', zone: 'x.org.', recordId: null, targetUser: "' OR '1'" }); expect(sanitizeActor('a\u0000b\u0007c')).toBe('a b c'); expect(sanitizeActor('x'.repeat(100))).toHaveLength(64); });