diff --git a/.gitignore b/.gitignore index a43f6d9..5b8cf81 100644 --- a/.gitignore +++ b/.gitignore @@ -7,3 +7,4 @@ e2e/node_modules/ e2e/test-results/ e2e/playwright-report/ +e2e/reports/ diff --git a/e2e/.dockerignore b/e2e/.dockerignore new file mode 100644 index 0000000..6aa3850 --- /dev/null +++ b/e2e/.dockerignore @@ -0,0 +1,4 @@ +node_modules +reports +test-results +playwright-report diff --git a/e2e/compose.yaml b/e2e/compose.yaml new file mode 100644 index 0000000..f7bee2f --- /dev/null +++ b/e2e/compose.yaml @@ -0,0 +1,270 @@ +name: ${E2E_PROJECT:?E2E_PROJECT is required} + +x-labels: &labels + cdwu.e2e.run: ${E2E_PROJECT} + +x-app-env: &app-env + DB_HOST: mysql + DB_PORT: "3306" + DB_TLS: "false" + DB_TABLE_PREFIX: coredns_ + HTTP_ADDR: 0.0.0.0 + HTTP_PORT: "8080" + LOG_LEVEL: DEBUG + APP_NAME: CoreDNS Web UI + COOKIE_SECURE: "false" + SESSION_IDLE_TIMEOUT: 1h + SESSION_MAX_AGE: 12h + TRUSTED_PROXIES: "" + +x-app: &app + image: ${E2E_APP_IMAGE:?E2E_APP_IMAGE is required} + labels: *labels + networks: [e2e] + restart: "no" + stop_grace_period: 30s + healthcheck: + test: ["CMD", "/app", "healthcheck"] + interval: 2s + timeout: 3s + retries: 45 + start_period: 90s + start_interval: 1s + +configs: + corefile: + content: | + .:5300 { + mysql { + dsn dns_harness:dns-harness-e2e-pass@tcp(mysql:3306)/e2e_harness + table_prefix coredns_ + zone_update_interval 1s + } + errors + } + .:5301 { + mysql { + dsn dns_core:dns-core-e2e-pass@tcp(mysql:3306)/e2e_core + table_prefix coredns_ + zone_update_interval 1s + } + errors + } + .:5302 { + mysql { + dsn dns_session:dns-session-e2e-pass@tcp(mysql:3306)/e2e_session + table_prefix coredns_ + zone_update_interval 1s + } + errors + } + .:5303 { + mysql { + dsn dns_power:dns-power-e2e-pass@tcp(mysql:3306)/e2e_power + table_prefix coredns_ + zone_update_interval 1s + } + errors + } + .:5304 { + mysql { + dsn dns_stupid:dns-stupid-e2e-pass@tcp(mysql:3306)/e2e_stupid + table_prefix coredns_ + zone_update_interval 1s + } + errors + } + .:5305 { + mysql { + dsn dns_malicious:dns-malicious-e2e-pass@tcp(mysql:3306)/e2e_malicious + table_prefix e2e_ + zone_update_interval 1s + } + errors + } + .:5306 { + mysql { + dsn dns_fuzzer:dns-fuzzer-e2e-pass@tcp(mysql:3306)/e2e_fuzzer + table_prefix coredns_ + zone_update_interval 1s + } + errors + } + .:5307 { + mysql { + dsn dns_operator:dns-operator-e2e-pass@tcp(mysql:3306)/e2e_operator + table_prefix coredns_ + zone_update_interval 1s + } + errors + } + .:5308 { + mysql { + dsn dns_a11y:dns-a11y-e2e-pass@tcp(mysql:3306)/e2e_a11y + table_prefix coredns_ + zone_update_interval 1s + } + errors + } + +networks: + e2e: + name: ${E2E_PROJECT}-net + internal: true + labels: *labels + +services: + mysql: + image: ${E2E_MYSQL_IMAGE:-mysql:8.4} + container_name: ${E2E_PROJECT}-mysql + labels: *labels + networks: [e2e] + restart: "no" + environment: + MYSQL_ROOT_PASSWORD: ${E2E_MYSQL_ROOT_PASSWORD:?E2E_MYSQL_ROOT_PASSWORD is required} + tmpfs: + - /var/lib/mysql:size=2g + healthcheck: + test: ["CMD-SHELL", "MYSQL_PWD=\"$$MYSQL_ROOT_PASSWORD\" mysqladmin ping --host=127.0.0.1 --user=root --silent"] + interval: 2s + timeout: 5s + retries: 90 + start_period: 120s + start_interval: 1s + + coredns: + image: ${E2E_COREDNS_IMAGE:-git.bjphoster.com/docker/coredns-mysql:latest} + container_name: ${E2E_PROJECT}-coredns + labels: *labels + networks: [e2e] + restart: "no" + command: ["-conf", "/Corefile"] + configs: + - source: corefile + target: /Corefile + + origin2: + image: ${E2E_RUNNER_IMAGE:?E2E_RUNNER_IMAGE is required} + container_name: ${E2E_PROJECT}-origin2 + labels: *labels + networks: [e2e] + restart: "no" + working_dir: /e2e + command: ["node", "stack/origin2.mjs"] + environment: + ORIGIN2_PORT: "8081" + + app-harness: + <<: *app + container_name: ${E2E_PROJECT}-app-harness + environment: + <<: *app-env + DB_USER: webui_harness + DB_PASSWORD: webui-harness-e2e-pass + DB_NAME: e2e_harness + + app-core: + <<: *app + container_name: ${E2E_PROJECT}-app-core + environment: + <<: *app-env + DB_USER: webui_core + DB_PASSWORD: webui-core-e2e-pass + DB_NAME: e2e_core + + app-session: + <<: *app + container_name: ${E2E_PROJECT}-app-session + environment: + <<: *app-env + DB_USER: webui_session + DB_PASSWORD: webui-session-e2e-pass + DB_NAME: e2e_session + SESSION_IDLE_TIMEOUT: 1m + SESSION_MAX_AGE: 3m + + app-power: + <<: *app + container_name: ${E2E_PROJECT}-app-power + environment: + <<: *app-env + DB_USER: webui_power + DB_PASSWORD: webui-power-e2e-pass + DB_NAME: e2e_power + + app-stupid: + <<: *app + container_name: ${E2E_PROJECT}-app-stupid + environment: + <<: *app-env + DB_USER: webui_stupid + DB_PASSWORD: webui-stupid-e2e-pass + DB_NAME: e2e_stupid + + app-malicious: + <<: *app + container_name: ${E2E_PROJECT}-app-malicious + environment: + <<: *app-env + DB_USER: webui_malicious + DB_PASSWORD: webui-malicious-e2e-pass + DB_NAME: e2e_malicious + DB_TABLE_PREFIX: e2e_ + LOG_LEVEL: TRACE + TRUSTED_PROXIES: 192.0.2.0/24 + + app-fuzzer: + <<: *app + container_name: ${E2E_PROJECT}-app-fuzzer + environment: + <<: *app-env + DB_USER: webui_fuzzer + DB_PASSWORD: webui-fuzzer-e2e-pass + DB_NAME: e2e_fuzzer + LOG_LEVEL: TRACE + + app-operator: + <<: *app + container_name: ${E2E_PROJECT}-app-operator + environment: + <<: *app-env + DB_USER: webui_operator + DB_PASSWORD: webui-operator-e2e-pass + DB_NAME: e2e_operator + + app-a11y: + <<: *app + container_name: ${E2E_PROJECT}-app-a11y + environment: + <<: *app-env + DB_USER: webui_a11y + DB_PASSWORD: webui-a11y-e2e-pass + DB_NAME: e2e_a11y + + runner: + image: ${E2E_RUNNER_IMAGE} + profiles: [runner] + labels: *labels + networks: [e2e] + restart: "no" + working_dir: /e2e + shm_size: 2gb + init: true + volumes: + - ${E2E_DOCKER_SOCKET:-/var/run/docker.sock}:/var/run/docker.sock + environment: + E2E_PROJECT: ${E2E_PROJECT} + E2E_DOCKER_SOCKET: ${E2E_DOCKER_SOCKET:-/var/run/docker.sock} + COMPOSE_PROJECT_NAME: ${E2E_PROJECT} + E2E_APP_IMAGE: ${E2E_APP_IMAGE} + E2E_RUNNER_IMAGE: ${E2E_RUNNER_IMAGE} + E2E_MYSQL_IMAGE: ${E2E_MYSQL_IMAGE:-mysql:8.4} + E2E_COREDNS_IMAGE: ${E2E_COREDNS_IMAGE:-git.bjphoster.com/docker/coredns-mysql:latest} + E2E_MYSQL_ROOT_PASSWORD: ${E2E_MYSQL_ROOT_PASSWORD} + E2E_SEED: ${E2E_SEED:-} + E2E_WORKERS: ${E2E_WORKERS:-4} + E2E_FUZZ_CASES: ${E2E_FUZZ_CASES:-} + E2E_OPERATOR_ACTIONS: ${E2E_OPERATOR_ACTIONS:-} + E2E_ARGS: ${E2E_ARGS:-} + E2E_REVIEW_FIXES: ${E2E_REVIEW_FIXES:-} + command: ["sh", "-c", "npx tsc --noEmit && exec npx playwright test $$E2E_ARGS"] diff --git a/e2e/dockerfile b/e2e/dockerfile new file mode 100644 index 0000000..e50317e --- /dev/null +++ b/e2e/dockerfile @@ -0,0 +1,21 @@ +# SPDX-License-Identifier: GPL-2.0-or-later +# Copyright (C) 2026 Bryan Joshua Pedini + +ARG PLAYWRIGHT_IMAGE=mcr.microsoft.com/playwright:v1.56.1-noble +FROM ${PLAYWRIGHT_IMAGE} +RUN apt-get update \ + && apt-get install -y --no-install-recommends ca-certificates curl dnsutils gnupg \ + && install -m 0755 -d /etc/apt/keyrings \ + && curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc \ + && chmod a+r /etc/apt/keyrings/docker.asc \ + && . /etc/os-release \ + && echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu ${VERSION_CODENAME} stable" > /etc/apt/sources.list.d/docker.list \ + && apt-get update \ + && apt-get install -y --no-install-recommends docker-ce-cli docker-compose-plugin \ + && rm -rf /var/lib/apt/lists/* +WORKDIR /e2e +ENV CI=1 NODE_ENV=test +COPY package.json package-lock.json ./ +RUN npm ci --no-audit --no-fund +COPY . . +CMD ["npx", "playwright", "test"] diff --git a/e2e/harness/api.ts b/e2e/harness/api.ts new file mode 100644 index 0000000..1b08a97 --- /dev/null +++ b/e2e/harness/api.ts @@ -0,0 +1,237 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { request, type APIRequestContext, type APIResponse } from '@playwright/test'; +import { runnerAddress, SESSION_COOKIE, type GroupConfig } from './env'; +import type { AuditLedger } from './ledger'; +import type { Recorder } from './recorder'; +import type { SecretRegistry } from './secrets'; + +export interface ApiResult { + status: number; + headers: Record; + text: string; + json: any; + etag: string | null; + durationMs: number; + setCookie: string; +} + +export interface RequestOptions { + body?: unknown; + raw?: string | Buffer; + contentType?: string | null; + headers?: Record; + query?: Record; + ifMatch?: string; + origin?: 'same' | 'none' | string; + audit?: 'auto' | 'none' | 'optional'; + timeoutMs?: number; +} + +export interface LoginHooks { + beforeLogin(username: string): Promise; + afterLogin(username: string, status: number): void; +} + +export interface ApiDeps { + recorder: Recorder; + secrets: SecretRegistry; + ledger?: AuditLedger; + hooks?: LoginHooks; +} + +const UNSAFE = new Set(['POST', 'PUT', 'DELETE', 'PATCH']); + +export class ApiClient { + username = ''; + private disposed = false; + + private constructor( + readonly group: GroupConfig, + public ctx: APIRequestContext, + private readonly deps: ApiDeps, + ) {} + + static async create(group: GroupConfig, deps: ApiDeps): Promise { + const ctx = await request.newContext({ baseURL: group.baseURL, extraHTTPHeaders: { Accept: 'application/json' }, timeout: 90_000 }); + return new ApiClient(group, ctx, deps); + } + + get origin(): string { + return new URL(this.group.baseURL).origin; + } + + async cookie(): Promise { + const state = await this.ctx.storageState(); + return state.cookies.find((c) => c.name === SESSION_COOKIE)?.value; + } + + async cookieAttributes(): Promise<{ httpOnly: boolean; sameSite: string; path: string; secure: boolean } | undefined> { + const state = await this.ctx.storageState(); + const c = state.cookies.find((x) => x.name === SESSION_COOKIE); + return c ? { httpOnly: c.httpOnly, sameSite: c.sameSite, path: c.path, secure: c.secure } : undefined; + } + + async setCookie(value: string | null): Promise { + const host = new URL(this.group.baseURL).hostname; + const state = await this.ctx.storageState(); + const others = state.cookies.filter((c) => c.name !== SESSION_COOKIE); + const cookies = + value === null ? others : [...others, { name: SESSION_COOKIE, value, domain: host, path: '/', expires: -1, httpOnly: true, secure: false, sameSite: 'Strict' as const }]; + const fresh = await request.newContext({ + baseURL: this.group.baseURL, + extraHTTPHeaders: { Accept: 'application/json' }, + timeout: 90_000, + storageState: { cookies, origins: [] }, + }); + await this.ctx.dispose(); + this.ctx = fresh; + } + + async login(username: string, password: string, opts: { next?: string; headers?: Record; expectStatus?: number; preserveRateLimit?: boolean } = {}): Promise { + this.deps.secrets.register(password, `password of ${username}`); + if (!opts.preserveRateLimit) await this.deps.hooks?.beforeLogin(username); + const started = Date.now(); + const res = await this.ctx.post('/login', { + form: { username, password, next: opts.next ?? '/' }, + headers: { Origin: this.origin, Accept: 'text/html', ...(opts.headers ?? {}) }, + maxRedirects: 0, + }); + const result = await this.wrap(res, started); + this.recordHttp('POST', '/login', { 'content-type': 'application/x-www-form-urlencoded' }, 0, result, username); + this.deps.ledger?.login(username, result.status, runnerAddress(), `api login ${username}`); + this.deps.hooks?.afterLogin(username, result.status); + if (result.status === 303) { + this.username = username; + const c = await this.cookie(); + if (c) this.deps.secrets.register(c, `session cookie of ${username}`); + } + return result; + } + + async logout(opts: { sessionValid?: boolean } = {}): Promise { + const started = Date.now(); + const res = await this.ctx.post('/logout', { headers: { Origin: this.origin, Accept: 'text/html' }, maxRedirects: 0 }); + const result = await this.wrap(res, started); + this.recordHttp('POST', '/logout', {}, 0, result, this.username); + this.deps.ledger?.logout(this.username, result.status, runnerAddress(), opts.sessionValid ?? true, `api logout ${this.username}`); + this.username = ''; + return result; + } + + async page(path: string, opts: RequestOptions = {}): Promise { + return this.raw('GET', path, { ...opts, audit: 'none' }); + } + + async raw(method: string, path: string, opts: RequestOptions = {}): Promise { + const headers: Record = { ...(opts.headers ?? {}) }; + const origin = opts.origin ?? 'same'; + if (UNSAFE.has(method.toUpperCase()) && origin !== 'none') headers.Origin = origin === 'same' ? this.origin : origin; + if (opts.ifMatch !== undefined) headers['If-Match'] = opts.ifMatch; + let data: string | Buffer | undefined; + if (opts.raw !== undefined) { + data = opts.raw; + if (opts.contentType !== null) headers['Content-Type'] = opts.contentType ?? 'application/json'; + } else if (opts.body !== undefined) { + data = JSON.stringify(opts.body); + if (opts.contentType !== null) headers['Content-Type'] = opts.contentType ?? 'application/json'; + } + let url = path; + if (opts.query) { + const params = new URLSearchParams(); + for (const [k, v] of Object.entries(opts.query)) if (v !== undefined) params.set(k, String(v)); + const qs = params.toString(); + if (qs) url += (url.includes('?') ? '&' : '?') + qs; + } + const started = Date.now(); + const res = await this.ctx.fetch(url, { method, headers, data, maxRedirects: 0, timeout: opts.timeoutMs ?? 90_000 }); + const result = await this.wrap(res, started); + const bodyBytes = data === undefined ? 0 : Buffer.byteLength(data); + this.recordHttp(method, url, headers, bodyBytes, result, this.username); + const audit = opts.audit ?? 'auto'; + if (audit !== 'none' && this.deps.ledger) { + const crossOrigin = origin !== 'same' && origin !== 'none' && UNSAFE.has(method.toUpperCase()); + const fetchSite = Object.entries(headers).find(([k]) => k.toLowerCase() === 'sec-fetch-site')?.[1]; + this.deps.ledger.api({ + method, + path: url, + status: result.status, + actor: this.username, + origin: runnerAddress(), + body: result.text, + sessionValid: this.username !== '' && result.status !== 401, + crossOrigin: crossOrigin || (fetchSite !== undefined && fetchSite !== 'same-origin' && fetchSite !== 'none' && UNSAFE.has(method.toUpperCase())), + optional: audit === 'optional', + source: `api ${method} ${url} as ${this.username || '(no session)'}`, + }); + } + return result; + } + + get(path: string, opts: RequestOptions = {}): Promise { + return this.raw('GET', `/api/v1${path}`, opts); + } + + post(path: string, body?: unknown, opts: RequestOptions = {}): Promise { + return this.raw('POST', `/api/v1${path}`, { body, ...opts }); + } + + put(path: string, body?: unknown, opts: RequestOptions = {}): Promise { + return this.raw('PUT', `/api/v1${path}`, { body, ...opts }); + } + + delete(path: string, body?: unknown, opts: RequestOptions = {}): Promise { + return this.raw('DELETE', `/api/v1${path}`, { body, ...opts }); + } + + forgetSession(): void { + this.username = ''; + } + + private async wrap(res: APIResponse, started: number): Promise { + const text = await res.text().catch(() => ''); + let json: any = undefined; + try { + json = text ? JSON.parse(text) : undefined; + } catch { + json = undefined; + } + const headers = res.headers(); + const setCookie = res + .headersArray() + .filter((h) => h.name.toLowerCase() === 'set-cookie') + .map((h) => h.value) + .join('\n'); + return { status: res.status(), headers, text, json, etag: headers['etag'] ?? null, durationMs: Date.now() - started, setCookie }; + } + + private recordHttp(method: string, url: string, headers: Record, bodyBytes: number, r: ApiResult, actor: string): void { + this.deps.recorder.addHttp({ + client: 'api', + actor, + method, + url, + requestHeaders: this.deps.secrets.redactValue(headers), + requestBodyBytes: bodyBytes, + status: r.status, + responseHeaders: this.deps.secrets.redactValue(r.headers), + bodyPreview: this.deps.secrets.redact(r.text), + durationMs: r.durationMs, + }); + } + + async dispose(): Promise { + if (this.disposed) return; + this.disposed = true; + await this.ctx.dispose(); + } +} + +export function zp(zone: string): string { + return `/zones/${encodeURIComponent(zone)}`; +} + +export function up(username: string): string { + return `/users/${encodeURIComponent(username)}`; +} diff --git a/e2e/harness/cli.ts b/e2e/harness/cli.ts new file mode 100644 index 0000000..2c1bffa --- /dev/null +++ b/e2e/harness/cli.ts @@ -0,0 +1,105 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { containerName, type GroupConfig } from './env'; +import type { AuditLedger } from './ledger'; +import { run } from './proc'; +import type { Recorder } from './recorder'; +import type { SecretRegistry } from './secrets'; + +export interface CliResult { + code: number | null; + stdout: string; + stderr: string; +} + +export const USAGE_TEXT = `usage: + coredns-web-ui start the HTTP server + coredns-web-ui help print this usage text + coredns-web-ui version print the version and commit + coredns-web-ui healthcheck query the local /health endpoint + coredns-web-ui user list [all] list the active users, or every user with all + coredns-web-ui user add create a user with role admin or user, reading the password from stdin + coredns-web-ui user passwd set the password of a user, reading it from stdin + coredns-web-ui user role set the role of a user to admin or user + coredns-web-ui user delete mark a user as deleted and end their sessions + coredns-web-ui check [zone] report the rows the plugin cannot serve correctly + coredns-web-ui audit [n] print the latest n audit rows (default 20) +`; + +export function parseTable(stdout: string): { header: string[]; rows: string[][] } { + const lines = stdout.split('\n').filter((l) => l.trim() !== ''); + if (lines.length === 0) return { header: [], rows: [] }; + const headerLine = lines[0]; + const starts: number[] = []; + const re = /\S+/g; + let m: RegExpExecArray | null; + while ((m = re.exec(headerLine))) starts.push(m.index); + const header = starts.map((s, i) => headerLine.slice(s, i + 1 < starts.length ? starts[i + 1] : undefined).trim()); + const rows = lines.slice(1).map((line) => starts.map((s, i) => line.slice(s, i + 1 < starts.length ? starts[i + 1] : undefined).trim())); + return { header, rows }; +} + +export class Cli { + constructor( + readonly group: GroupConfig, + private readonly recorder: Recorder, + private readonly secrets: SecretRegistry, + private readonly ledger?: AuditLedger, + ) {} + + get container(): string { + return containerName(this.group.service); + } + + async run(args: string[], stdin?: string): Promise { + const dockerArgs = ['exec', ...(stdin !== undefined ? ['-i'] : []), this.container, '/app', ...args]; + const r = await run('docker', dockerArgs, { input: stdin, timeoutMs: 120_000 }); + this.recorder.addCli({ + container: this.container, + args, + stdinBytes: stdin === undefined ? 0 : Buffer.byteLength(stdin), + exitCode: r.code, + durationMs: r.durationMs, + stdout: this.secrets.redact(r.stdout), + stderr: this.secrets.redact(r.stderr), + }); + return { code: r.code, stdout: r.stdout, stderr: r.stderr }; + } + + private async change(operation: string, target: string, args: string[], stdin?: string): Promise { + const r = await this.run(args, stdin); + if (r.code === 0) this.ledger?.cli(operation, target, `cli ${args.join(' ')}`); + return r; + } + + userAdd(username: string, role: string, password: string): Promise { + this.secrets.register(password, `password of ${username}`); + return this.change('user_create', username, ['user', 'add', username, role], `${password}\n`); + } + + userPasswd(username: string, password: string): Promise { + this.secrets.register(password, `password of ${username}`); + return this.change('user_password', username, ['user', 'passwd', username], `${password}\n`); + } + + userRole(username: string, role: string): Promise { + return this.change('user_role', username, ['user', 'role', username, role]); + } + + userDelete(username: string): Promise { + return this.change('user_delete', username, ['user', 'delete', username]); + } + + userList(all = false): Promise { + return this.run(all ? ['user', 'list', 'all'] : ['user', 'list']); + } + + check(zone?: string): Promise { + return this.run(zone === undefined ? ['check'] : ['check', zone]); + } + + audit(n?: number | string): Promise { + return this.run(n === undefined ? ['audit'] : ['audit', String(n)]); + } +} diff --git a/e2e/harness/decisions.ts b/e2e/harness/decisions.ts new file mode 100644 index 0000000..3607bc8 --- /dev/null +++ b/e2e/harness/decisions.ts @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { expect } from '@playwright/test'; + +export const REVIEW_FIXES: boolean = process.env.E2E_REVIEW_FIXES === 'enabled'; + +export const UNKNOWN_API_OPERATION = 'api_unknown'; +export const UNKNOWN_API_ROW_COUNT = REVIEW_FIXES ? 1 : 0; +export const RECORD_DELETE_STATUS = REVIEW_FIXES ? 200 : 204; +export const ZONE_CREATE_DELEGATIONS_IN = REVIEW_FIXES ? 'before' : 'any'; + +export function expectRecordDeleteBody(json: unknown, what: string): void { + if (REVIEW_FIXES) expect(json, `${what}: record delete answers its warnings`).toEqual({ warnings: expect.any(Array) }); +} + +export function bulkDeleteBody(deleted: number): Record { + return expect.objectContaining({ deleted }); +} + +export function importApplyBody(added: number, updated: number, deleted: number): Record { + return expect.objectContaining({ added, updated, deleted }); +} + +export function expectZoneCreateWarnings(json: unknown): void { + if (REVIEW_FIXES) expect((json as { warnings?: unknown }).warnings, 'zone create answers its warnings').toEqual(expect.any(Array)); +} + +export function expectCheckErrorRowsCarryRaw(rows: Array<{ data: unknown; raw: string | null; problems: Array<{ severity: string }> }>, contentOf: (index: number) => string | null): void { + if (!REVIEW_FIXES) return; + rows.forEach((r, i) => { + if (r.problems.some((p) => p.severity === 'error')) expect(r.raw, 'a row with a check error carries its stored content in raw').toBe(contentOf(i)); + }); +} diff --git a/e2e/harness/dig.ts b/e2e/harness/dig.ts new file mode 100644 index 0000000..c56d451 --- /dev/null +++ b/e2e/harness/dig.ts @@ -0,0 +1,115 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { COREDNS_HOST, type GroupConfig } from './env'; +import { HarnessError } from './errors'; +import { run, sleep } from './proc'; +import type { Recorder } from './recorder'; + +export interface DigRR { + name: string; + ttl: number; + class: string; + type: string; + data: string; +} + +export interface DigResult { + rcode: string; + flags: string[]; + answer: DigRR[]; + authority: DigRR[]; + additional: DigRR[]; + raw: string; +} + +export function parseRR(line: string): DigRR { + const m = /^(\S+)\s+(\d+)\s+(\S+)\s+(\S+)\s*(.*)$/.exec(line.trim()); + if (!m) throw new HarnessError('protocol', `cannot parse dig record line: ${line}`); + return { name: m[1].toLowerCase(), ttl: Number(m[2]), class: m[3], type: m[4], data: m[5].trim() }; +} + +export function parseDig(text: string): DigResult { + const header = /->>HEADER<<-\s+opcode:\s*\S+,\s*status:\s*([A-Z]+),/.exec(text); + if (!header) throw new HarnessError('protocol', `dig output without a header: ${text.slice(0, 500)}`); + const flagsMatch = /;; flags:([^;]*);/.exec(text); + const result: DigResult = { + rcode: header[1], + flags: flagsMatch ? flagsMatch[1].trim().split(/\s+/).filter(Boolean) : [], + answer: [], + authority: [], + additional: [], + raw: text, + }; + let section: 'answer' | 'authority' | 'additional' | null = null; + for (const line of text.split('\n')) { + const t = line.trim(); + const head = /^;; ([A-Z ]+?)\s*(?:PSEUDO)?SECTION:$/.exec(t); + if (head) { + const name = head[1].trim().toLowerCase(); + section = name === 'answer' || name === 'authority' || name === 'additional' ? name : null; + continue; + } + if (t === '' || t.startsWith(';')) continue; + if (section) result[section].push(parseRR(t)); + } + return result; +} + +export interface DigOptions { + tcp?: boolean; + recorder?: Recorder; +} + +export async function dig(group: GroupConfig, name: string, type: string, opts: DigOptions = {}): Promise { + const args = [`@${COREDNS_HOST}`, '-p', String(group.dnsPort), '+norecurse', '+nocookie', '+time=3', '+tries=2', '+noall', '+comments', '+answer', '+authority', '+additional']; + if (opts.tcp) args.push('+tcp'); + args.push('-t', type, '-q', name); + let last = ''; + for (let attempt = 0; attempt < 3; attempt++) { + const r = await run('dig', args, { timeoutMs: 20_000 }); + last = r.stdout + r.stderr; + opts.recorder?.addDig(args, last); + if (r.code === 0 && /->>HEADER<<-/.test(r.stdout)) return parseDig(r.stdout); + await sleep(300); + } + throw new HarnessError('transport', `dig ${name} ${type} on port ${group.dnsPort} failed: ${last.slice(0, 500)}`); +} + +export function fqdn(name: string, zone: string): string { + return name === '' ? zone : `${name}.${zone}`; +} + +export async function waitForZone(group: GroupConfig, zone: string, opts: DigOptions = {}, timeoutMs = 20_000): Promise { + const deadline = Date.now() + timeoutMs; + let last: DigResult | undefined; + for (;;) { + last = await dig(group, zone, 'SOA', opts); + if (last.rcode === 'NOERROR' && last.flags.includes('aa') && last.answer.some((rr) => rr.type === 'SOA')) return last; + if (Date.now() > deadline) throw new HarnessError('timeout', `zone ${zone} not served on port ${group.dnsPort} within ${timeoutMs} ms: ${last.raw.slice(0, 800)}`); + await sleep(250); + } +} + +export async function waitForZoneGone(group: GroupConfig, zone: string, opts: DigOptions = {}, timeoutMs = 20_000): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + const r = await dig(group, zone, 'SOA', opts); + if (!r.flags.includes('aa') && !r.answer.some((rr) => rr.type === 'SOA')) return r; + if (Date.now() > deadline) throw new HarnessError('timeout', `zone ${zone} still served on port ${group.dnsPort} after ${timeoutMs} ms`); + await sleep(250); + } +} + +export function soaSerialOf(rr: DigRR): number { + const parts = rr.data.split(/\s+/); + if (rr.type !== 'SOA' || parts.length !== 7) throw new HarnessError('protocol', `not an SOA record: ${rr.type} ${rr.data}`); + return Number(parts[2]); +} + +export async function servedSerial(group: GroupConfig, zone: string, opts: DigOptions = {}): Promise { + const r = await dig(group, zone, 'SOA', opts); + const soa = r.answer.find((rr) => rr.type === 'SOA'); + if (!soa) throw new HarnessError('protocol', `no SOA answer for ${zone}: ${r.raw.slice(0, 500)}`); + return soaSerialOf(soa); +} diff --git a/e2e/harness/docker.ts b/e2e/harness/docker.ts new file mode 100644 index 0000000..59c2538 --- /dev/null +++ b/e2e/harness/docker.ts @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { COMPOSE_FILE, containerName, project, RESOURCE_PREFIX, RUN_LABEL } from './env'; +import { run, runOk, type ProcOptions, type ProcResult } from './proc'; + +export function docker(args: readonly string[], opts: ProcOptions = {}): Promise { + return run('docker', args, opts); +} + +export function dockerOk(args: readonly string[], opts: ProcOptions = {}): Promise { + return runOk('docker', args, opts); +} + +export function compose(args: readonly string[], opts: ProcOptions = {}): Promise { + return runOk('docker', ['compose', '--project-name', project(), '--file', COMPOSE_FILE, ...args], opts); +} + +export function runnerContainer(): string { + return containerName('runner'); +} + +function lines(s: string): string[] { + return s + .split('\n') + .map((l) => l.trim()) + .filter(Boolean); +} + +export interface ProjectResources { + containers: string[]; + volumes: string[]; + networks: string[]; +} + +export async function projectResources(): Promise { + const p = project(); + const byLabel = await dockerOk(['ps', '-a', '--filter', `label=${RUN_LABEL}=${p}`, '--format', '{{.Names}}']); + const byName = await dockerOk(['ps', '-a', '--filter', `name=^${p}`, '--format', '{{.Names}}']); + const byCompose = await dockerOk(['ps', '-a', '--filter', `label=com.docker.compose.project=${p}`, '--format', '{{.Names}}']); + const self = new Set([runnerContainer()]); + const containers = [...new Set([...lines(byLabel.stdout), ...lines(byName.stdout), ...lines(byCompose.stdout)])].filter( + (n) => !self.has(n) && !/^.+-runner-run-[0-9a-f]+$/.test(n), + ); + const volumes = new Set(); + for (const filter of [`label=${RUN_LABEL}=${p}`, `label=com.docker.compose.project=${p}`, `name=${p}`]) { + const r = await dockerOk(['volume', 'ls', '-q', '--filter', filter]); + for (const v of lines(r.stdout)) volumes.add(v); + } + const networks = new Set(); + for (const filter of [`label=${RUN_LABEL}=${p}`, `name=${p}`]) { + const r = await dockerOk(['network', 'ls', '--format', '{{.Name}}', '--filter', filter]); + for (const n of lines(r.stdout)) networks.add(n); + } + return { containers, volumes: [...volumes], networks: [...networks] }; +} + +export function isOwnedName(name: string): boolean { + return name.startsWith(RESOURCE_PREFIX); +} diff --git a/e2e/harness/env.ts b/e2e/harness/env.ts new file mode 100644 index 0000000..15cc566 --- /dev/null +++ b/e2e/harness/env.ts @@ -0,0 +1,120 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import os from 'node:os'; +import path from 'node:path'; +import { HarnessError } from './errors'; + +export const RESOURCE_PREFIX = 'cdwu-e2e-'; +export const RUN_LABEL = 'cdwu.e2e.run'; +export const COMPOSE_FILE = path.resolve(process.cwd(), 'compose.yaml'); +export const REPORTS_DIR = path.resolve(process.cwd(), 'reports'); +export const SCREENSHOTS_DIR = path.join(REPORTS_DIR, 'screenshots'); +export const SEEDS_DIR = path.join(REPORTS_DIR, 'failing-seeds'); +export const DEFAULT_SEED = 'cdwu-e2e-default-seed-1'; +export const MYSQL_HOST = 'mysql'; +export const COREDNS_HOST = 'coredns'; +export const ORIGIN2_URL = 'http://origin2:8081'; +export const SESSION_COOKIE = 'coredns_webui_session'; + +export type GroupName = 'harness' | 'core' | 'session' | 'power' | 'stupid' | 'malicious' | 'fuzzer' | 'operator' | 'a11y'; + +export interface GroupConfig { + name: GroupName; + service: string; + database: string; + prefix: string; + appUser: string; + appPassword: string; + dnsUser: string; + dnsPassword: string; + dnsPort: number; + baseURL: string; + idleTimeoutMs: number; + maxAgeMs: number; + trustedProxies: string; + logLevel: string; +} + +function group(name: GroupName, dnsPort: number, extra: Partial = {}): GroupConfig { + return { + name, + service: `app-${name}`, + database: `e2e_${name}`, + prefix: 'coredns_', + appUser: `webui_${name}`, + appPassword: `webui-${name}-e2e-pass`, + dnsUser: `dns_${name}`, + dnsPassword: `dns-${name}-e2e-pass`, + dnsPort, + baseURL: `http://app-${name}:8080`, + idleTimeoutMs: 3600_000, + maxAgeMs: 12 * 3600_000, + trustedProxies: '', + logLevel: 'DEBUG', + ...extra, + }; +} + +export const GROUPS: Readonly> = { + harness: group('harness', 5300), + core: group('core', 5301), + session: group('session', 5302, { idleTimeoutMs: 60_000, maxAgeMs: 180_000 }), + power: group('power', 5303), + stupid: group('stupid', 5304), + malicious: group('malicious', 5305, { prefix: 'e2e_', logLevel: 'TRACE', trustedProxies: '192.0.2.0/24' }), + fuzzer: group('fuzzer', 5306, { logLevel: 'TRACE' }), + operator: group('operator', 5307), + a11y: group('a11y', 5308), +}; + +export const GROUP_NAMES = Object.keys(GROUPS) as GroupName[]; + +export function requireEnv(name: string): string { + const value = process.env[name]; + if (!value) throw new HarnessError('prerequisite', `environment variable ${name} is required (run the suite through scripts/test-e2e.sh)`); + return value; +} + +export function project(): string { + const p = requireEnv('E2E_PROJECT'); + if (!p.startsWith(RESOURCE_PREFIX) || !/^[a-z0-9][a-z0-9_-]*$/.test(p)) { + throw new HarnessError('prerequisite', `E2E_PROJECT must start with ${RESOURCE_PREFIX} and be a valid compose project name`); + } + return p; +} + +export function containerName(service: string): string { + return `${project()}-${service}`; +} + +export function runSeed(): string { + return process.env.E2E_SEED || DEFAULT_SEED; +} + +export function runDir(): string { + return path.join(os.tmpdir(), `${project()}-run`); +} + +export function secretsDir(): string { + return path.join(runDir(), 'secrets'); +} + +export function intEnv(name: string, fallback: number): number { + const v = process.env[name]; + if (!v) return fallback; + const n = Number(v); + if (!Number.isInteger(n) || n < 1) throw new HarnessError('prerequisite', `${name} must be a positive integer`); + return n; +} + +export function runnerAddress(): string { + const fromEnv = process.env.E2E_RUNNER_IP; + if (fromEnv) return fromEnv; + for (const list of Object.values(os.networkInterfaces())) { + for (const addr of list ?? []) { + if (addr.family === 'IPv4' && !addr.internal) return addr.address; + } + } + throw new HarnessError('prerequisite', 'cannot determine the runner address on the stack network'); +} diff --git a/e2e/harness/errors.ts b/e2e/harness/errors.ts new file mode 100644 index 0000000..626752e --- /dev/null +++ b/e2e/harness/errors.ts @@ -0,0 +1,20 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +export type HarnessErrorKind = 'timeout' | 'spawn' | 'prerequisite' | 'protocol' | 'transport' | 'leak' | 'infrastructure'; + +export class HarnessError extends Error { + readonly kind: HarnessErrorKind; + readonly details?: unknown; + + constructor(kind: HarnessErrorKind, message: string, details?: unknown) { + super(`[harness:${kind}] ${message}`); + this.name = 'HarnessError'; + this.kind = kind; + this.details = details; + } +} + +export function isHarnessError(e: unknown): e is HarnessError { + return e instanceof HarnessError; +} diff --git a/e2e/harness/fixtures.ts b/e2e/harness/fixtures.ts new file mode 100644 index 0000000..39bc4dc --- /dev/null +++ b/e2e/harness/fixtures.ts @@ -0,0 +1,264 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import fs from 'node:fs'; +import path from 'node:path'; +import { test as base, expect, type Browser, type TestInfo } from '@playwright/test'; +import { ApiClient, type LoginHooks } from './api'; +import { Cli } from './cli'; +import { docker } from './docker'; +import { containerName, GROUPS, runSeed, secretsDir, SEEDS_DIR, type GroupConfig, type GroupName } from './env'; +import { AuditLedger } from './ledger'; +import { Db } from './mysql'; +import { Recorder } from './recorder'; +import { Rng, testSeed } from './rng'; +import { redactText, SecretRegistry } from './secrets'; +import { restartApp } from './stack'; +import { Ui, type UiOpenOptions } from './ui'; + +export interface Account { + username: string; + password: string; + role: 'admin' | 'user'; +} + +export class World implements LoginHooks { + readonly db: Db; + readonly secrets: SecretRegistry; + readonly recorder = new Recorder(); + readonly ledger: AuditLedger; + readonly cli: Cli; + rng: Rng; + testInfo: TestInfo | null = null; + auditCheck = true; + private originFailures = 0; + private readonly usernameFailures = new Map(); + private readonly testClients = new Set(); + private readonly testUis = new Set(); + private readonly keptClients = new Set(); + private readonly keptUis = new Set(); + private seq = 0; + + constructor( + readonly g: GroupConfig, + readonly browser: Browser, + ) { + this.db = new Db(g); + this.secrets = new SecretRegistry(path.join(secretsDir(), `${g.name}-${process.pid}.jsonl`)); + this.secrets.register(g.appPassword, 'mysql password of the application'); + this.secrets.register(g.dnsPassword, 'mysql password of coredns'); + if (process.env.E2E_MYSQL_ROOT_PASSWORD) this.secrets.register(process.env.E2E_MYSQL_ROOT_PASSWORD, 'mysql root password'); + this.ledger = new AuditLedger(this.db, this.secrets); + this.cli = new Cli(g, this.recorder, this.secrets, this.ledger); + this.rng = new Rng(`${runSeed()}::${g.name}`); + } + + async beforeLogin(username: string): Promise { + if (this.originFailures >= 4 || (this.usernameFailures.get(username) ?? 0) >= 4) await this.resetRateLimits(); + } + + afterLogin(username: string, status: number): void { + if (status === 303) { + this.usernameFailures.delete(username); + return; + } + if (status === 401 || status === 429) { + this.originFailures++; + this.usernameFailures.set(username, (this.usernameFailures.get(username) ?? 0) + 1); + } + } + + async resetRateLimits(): Promise { + this.recorder.note(`restarting ${this.g.service} to reset the in-memory login rate limits`); + await this.ledger.settle(); + await restartApp(this.g); + this.originFailures = 0; + this.usernameFailures.clear(); + } + + async restart(): Promise { + await this.ledger.settle(); + await restartApp(this.g); + this.originFailures = 0; + this.usernameFailures.clear(); + } + + unique(prefix: string): string { + this.seq++; + return `${prefix}${this.rng.string(5)}${this.seq}`; + } + + zoneName(prefix = 'z'): string { + return `${this.unique(prefix)}.${this.g.name}.test.`; + } + + password(label = 'password'): string { + const pw = `Pw-${this.rng.string(10, 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')}-${this.rng.string(8)}`; + return this.secrets.register(pw, label); + } + + async api(opts: { keep?: boolean } = {}): Promise { + const c = await ApiClient.create(this.g, { recorder: this.recorder, secrets: this.secrets, ledger: this.ledger, hooks: this }); + (opts.keep ? this.keptClients : this.testClients).add(c); + return c; + } + + async ui(opts: UiOpenOptions & { keep?: boolean } = {}): Promise { + const u = await Ui.open(this.browser, { group: this.g, ledger: this.ledger, recorder: this.recorder, secrets: this.secrets, hooks: this }, opts); + (opts.keep ? this.keptUis : this.testUis).add(u); + return u; + } + + async apiAs(account: Account, opts: { keep?: boolean } = {}): Promise { + const c = await this.api(opts); + const r = await c.login(account.username, account.password); + expect(r.status, `login of ${account.username}`).toBe(303); + return c; + } + + async uiAs(account: Account, opts: UiOpenOptions & { keep?: boolean } = {}): Promise { + const u = await this.ui(opts); + await u.login(account.username, account.password); + return u; + } + + async bootstrapAdmin(username = this.unique('root')): Promise { + const password = this.password(`password of ${username}`); + const r = await this.cli.userAdd(username, 'admin', password); + expect(r.code, `user add ${username} admin: ${this.secrets.redact(r.stderr)}`).toBe(0); + return { username, password, role: 'admin' }; + } + + async createUser(admin: ApiClient, role: 'admin' | 'user', username = this.unique(role === 'admin' ? 'adm' : 'usr')): Promise { + const password = this.password(`password of ${username}`); + const r = await admin.post('/users', { username, role, password }); + expect(r.status, `create user ${username}: ${r.text}`).toBe(201); + return { username, password, role }; + } + + async closeTestResources(): Promise { + for (const u of this.testUis) await u.close().catch(() => undefined); + for (const c of this.testClients) await c.dispose().catch(() => undefined); + this.testUis.clear(); + this.testClients.clear(); + } + + async dispose(): Promise { + await this.closeTestResources(); + for (const u of this.keptUis) await u.close().catch(() => undefined); + for (const c of this.keptClients) await c.dispose().catch(() => undefined); + await this.db.close().catch(() => undefined); + } +} + +let currentSecrets: SecretRegistry | undefined; +let stdioWrapped = false; + +function installStdioRedaction(): void { + if (stdioWrapped) return; + stdioWrapped = true; + for (const stream of [process.stdout, process.stderr]) { + const original = stream.write.bind(stream) as (...a: unknown[]) => boolean; + stream.write = ((chunk: unknown, ...rest: unknown[]) => { + const text = typeof chunk === 'string' ? chunk : chunk instanceof Uint8Array ? Buffer.from(chunk).toString('utf8') : undefined; + return original(text === undefined ? chunk : redactText(text, currentSecrets?.all() ?? []), ...rest); + }) as typeof stream.write; + } +} + +function slug(s: string): string { + return s.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 120) || 'test'; +} + +async function attachFailure(w: World, info: TestInfo, seed: string): Promise { + const red = (v: T) => w.secrets.redactValue(v); + await info.attach('http.json', { body: JSON.stringify(red(w.recorder.http), null, 2), contentType: 'application/json' }); + await info.attach('cli.json', { body: JSON.stringify(red(w.recorder.cli), null, 2), contentType: 'application/json' }); + await info.attach('dig.json', { body: JSON.stringify(w.recorder.dig, null, 2), contentType: 'application/json' }); + await info.attach('notes.txt', { body: w.secrets.redact(w.recorder.notes.join('\n')), contentType: 'text/plain' }); + const snapshot = await w.db.snapshot().catch((e) => `snapshot failed: ${(e as Error).message}`); + await info.attach('database.json', { body: w.secrets.redact(snapshot), contentType: 'application/json' }); + const logs = await docker(['logs', '--tail', '400', containerName(w.g.service)], { timeoutMs: 60_000 }).catch(() => null); + if (logs) await info.attach('app.log', { body: w.secrets.redact(logs.stdout + logs.stderr), contentType: 'text/plain' }); + const failing = { seed, runSeed: runSeed(), group: w.g.name, title: info.titlePath.join(' > '), reproduce: `E2E_SEED=${JSON.stringify(runSeed())}`, fuzzCases: red(w.recorder.fuzzCases) }; + await info.attach('seed.json', { body: JSON.stringify(failing, null, 2), contentType: 'application/json' }); + fs.mkdirSync(SEEDS_DIR, { recursive: true }); + fs.writeFileSync(path.join(SEEDS_DIR, `${slug(info.titlePath.slice(1).join(' '))}.json`), JSON.stringify(failing, null, 2)); +} + +async function scanLogs(w: World, since: Date): Promise { + const r = await docker(['logs', '--since', since.toISOString(), containerName(w.g.service)], { timeoutMs: 60_000 }); + const text = r.stdout + r.stderr; + const found = w.secrets.findIn(text); + if (/\$argon2id\$/.test(text)) found.push('a password hash'); + if (/coredns_webui_session=/.test(text)) found.push('a session cookie'); + return found; +} + +export interface Options { + group: GroupName; +} + +export interface Fixtures { + world: World; + seed: string; +} + +export interface WorkerFixtures { + worlds: Map; +} + +export const test = base.extend({ + group: ['harness', { option: true }], + + worlds: [ + async ({}, use) => { + installStdioRedaction(); + const m = new Map(); + await use(m); + for (const w of m.values()) await w.dispose(); + }, + { scope: 'worker' }, + ], + + seed: async ({}, use, info) => { + await use(testSeed(runSeed(), info.titlePath)); + }, + + world: async ({ group, browser, worlds, seed }, use, info) => { + let w = worlds.get(group); + if (!w || w.browser !== browser) { + w = new World(GROUPS[group], browser); + worlds.set(group, w); + } + currentSecrets = w.secrets; + w.testInfo = info; + w.rng = new Rng(seed); + w.auditCheck = true; + info.annotations.push({ type: 'seed', description: seed }); + const started = new Date(Date.now() - 1000); + await w.ledger.start(); + let failure: unknown; + try { + await use(w); + } finally { + try { + await w.ledger.settle(); + if (info.status === info.expectedStatus) { + if (w.auditCheck) await w.ledger.verify(`every operation of "${info.title}" has exactly one audit row`); + const leaks = await scanLogs(w, started); + expect(leaks, 'secrets in the application log').toEqual([]); + } + } catch (e) { + failure = e; + } + await w.closeTestResources(); + if (info.status !== info.expectedStatus || failure) await attachFailure(w, info, seed).catch(() => undefined); + w.recorder.clear(); + w.testInfo = null; + } + if (failure) throw failure; + }, +}); + +export { expect }; diff --git a/e2e/harness/global-setup.ts b/e2e/harness/global-setup.ts new file mode 100644 index 0000000..ea8c25e --- /dev/null +++ b/e2e/harness/global-setup.ts @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import fs from 'node:fs'; +import path from 'node:path'; +import { project, REPORTS_DIR, runDir, runSeed, SCREENSHOTS_DIR, secretsDir, SEEDS_DIR } from './env'; +import { HarnessError } from './errors'; +import { stackDown, stackUp } from './stack'; +import { run } from './proc'; + +export default async function globalSetup(): Promise { + const p = project(); + const docker = await run('docker', ['version', '--format', '{{.Server.Version}}'], { timeoutMs: 30_000 }).catch(() => null); + if (!docker || docker.code !== 0) throw new HarnessError('prerequisite', 'the Docker socket is not reachable from the runner'); + const compose = await run('docker', ['compose', 'version'], { timeoutMs: 30_000 }).catch(() => null); + if (!compose || compose.code !== 0) throw new HarnessError('prerequisite', 'docker compose is not available in the runner'); + const dig = await run('dig', ['-v'], { timeoutMs: 30_000 }).catch(() => null); + if (!dig || dig.code !== 0) throw new HarnessError('prerequisite', 'dig is not available in the runner'); + fs.rmSync(runDir(), { recursive: true, force: true }); + fs.mkdirSync(secretsDir(), { recursive: true, mode: 0o700 }); + for (const dir of [REPORTS_DIR, SCREENSHOTS_DIR, SEEDS_DIR]) fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync( + path.join(REPORTS_DIR, 'run.json'), + JSON.stringify({ project: p, seed: runSeed(), appImage: process.env.E2E_APP_IMAGE ?? null, startedAt: new Date().toISOString() }, null, 2), + ); + console.log(`[cdwu-e2e] run ${p} seed ${JSON.stringify(runSeed())} (reproduce with E2E_SEED)`); + try { + await stackUp((line) => console.log(`[cdwu-e2e] ${line}`)); + } catch (e) { + await stackDown().catch(() => undefined); + throw e; + } +} diff --git a/e2e/harness/global-teardown.ts b/e2e/harness/global-teardown.ts new file mode 100644 index 0000000..8893fe6 --- /dev/null +++ b/e2e/harness/global-teardown.ts @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import fs from 'node:fs'; +import { docker, projectResources, runnerContainer } from './docker'; +import { project, runDir } from './env'; +import { stackDown } from './stack'; + +export async function detectLeaks(allowed: ReadonlySet = new Set()): Promise { + const leaks: string[] = []; + const resources = await projectResources(); + const self = runnerContainer(); + const runnerNetworks = new Set(); + const inspect = await docker(['inspect', '--format', '{{range $k, $v := .NetworkSettings.Networks}}{{$k}} {{end}}', self]); + if (inspect.code === 0) for (const n of inspect.stdout.trim().split(/\s+/).filter(Boolean)) runnerNetworks.add(n); + const containers = resources.containers.filter((c) => c !== self && !allowed.has(c)); + if (containers.length > 0) { + leaks.push(`containers left behind: ${containers.join(', ')}`); + await docker(['rm', '--force', '--volumes', ...containers]); + } + const volumes = resources.volumes.filter((v) => !allowed.has(v)); + if (volumes.length > 0) { + leaks.push(`volumes left behind: ${volumes.join(', ')}`); + await docker(['volume', 'rm', '--force', ...volumes]); + } + const networks = resources.networks.filter((n) => !runnerNetworks.has(n) && !allowed.has(n)); + if (networks.length > 0) { + leaks.push(`networks left behind: ${networks.join(', ')}`); + await docker(['network', 'rm', ...networks]); + } + return leaks; +} + +export default async function globalTeardown(): Promise { + const p = project(); + const problems: string[] = []; + try { + await stackDown(); + } catch (e) { + problems.push(`stack teardown failed: ${(e as Error).message}`); + } + try { + problems.push(...(await detectLeaks())); + } catch (e) { + problems.push(`leak detection failed: ${(e as Error).message}`); + } + fs.rmSync(runDir(), { recursive: true, force: true }); + if (problems.length > 0) { + throw new Error(`[cdwu-e2e] resource leaks detected for run ${p} (cleaned up, failing the run):\n- ${problems.join('\n- ')}`); + } + console.log(`[cdwu-e2e] run ${p}: stack removed, no leaked containers, volumes or networks`); +} diff --git a/e2e/harness/ledger.ts b/e2e/harness/ledger.ts new file mode 100644 index 0000000..0e6b226 --- /dev/null +++ b/e2e/harness/ledger.ts @@ -0,0 +1,310 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { expect } from '@playwright/test'; +import type { AuditRow, Db } from './mysql'; +import { REVIEW_FIXES, UNKNOWN_API_OPERATION } from './decisions'; +import type { SecretRegistry } from './secrets'; + +export const READ_OPERATIONS = new Set([ + 'account_read', + 'zone_list', + 'zone_read', + 'record_list', + 'zone_check', + 'check_all', + 'zone_export', + 'zone_import_preview', + 'delegation_list', + 'user_list', + 'user_read', + 'audit_read', + UNKNOWN_API_OPERATION, +]); + +export const CHANGE_OPERATIONS = new Set([ + 'login', + 'logout', + 'password_change', + 'zone_create', + 'zone_delete', + 'record_create', + 'record_update', + 'record_delete', + 'record_bulk_delete', + 'soa_update', + 'zone_import', + 'delegation_grant', + 'delegation_revoke', + 'user_create', + 'user_role', + 'user_password', + 'user_delete', +]); + +type Target = 'zone' | 'record' | 'user' | 'delegation'; + +const ROUTES: ReadonlyArray = [ + ['GET', /^\/account$/, 'account_read', []], + ['PUT', /^\/account\/password$/, 'password_change', []], + ['GET', /^\/zones$/, 'zone_list', []], + ['POST', /^\/zones$/, 'zone_create', []], + ['GET', /^\/zones\/([^/]+)$/, 'zone_read', ['zone']], + ['DELETE', /^\/zones\/([^/]+)$/, 'zone_delete', ['zone']], + ['GET', /^\/zones\/([^/]+)\/records$/, 'record_list', ['zone']], + ['POST', /^\/zones\/([^/]+)\/records$/, 'record_create', ['zone']], + ['POST', /^\/zones\/([^/]+)\/records\/delete$/, 'record_bulk_delete', ['zone']], + ['PUT', /^\/zones\/([^/]+)\/records\/([^/]+)$/, 'record_update', ['zone', 'record']], + ['DELETE', /^\/zones\/([^/]+)\/records\/([^/]+)$/, 'record_delete', ['zone', 'record']], + ['PUT', /^\/zones\/([^/]+)\/soa$/, 'soa_update', ['zone']], + ['GET', /^\/zones\/([^/]+)\/check$/, 'zone_check', ['zone']], + ['GET', /^\/check$/, 'check_all', []], + ['GET', /^\/zones\/([^/]+)\/export$/, 'zone_export', ['zone']], + ['POST', /^\/zones\/([^/]+)\/import\/preview$/, 'zone_import_preview', ['zone']], + ['POST', /^\/zones\/([^/]+)\/import\/apply$/, 'zone_import', ['zone']], + ['GET', /^\/zones\/([^/]+)\/users$/, 'delegation_list', ['zone']], + ['PUT', /^\/zones\/([^/]+)\/users\/([^/]+)$/, 'delegation_grant', ['zone', 'delegation']], + ['DELETE', /^\/zones\/([^/]+)\/users\/([^/]+)$/, 'delegation_revoke', ['zone', 'delegation']], + ['GET', /^\/users$/, 'user_list', []], + ['POST', /^\/users$/, 'user_create', []], + ['GET', /^\/users\/([^/]+)$/, 'user_read', ['user']], + ['PUT', /^\/users\/([^/]+)\/role$/, 'user_role', ['user']], + ['PUT', /^\/users\/([^/]+)\/password$/, 'user_password', ['user']], + ['DELETE', /^\/users\/([^/]+)$/, 'user_delete', ['user']], + ['GET', /^\/audit$/, 'audit_read', []], +]; + +export interface RouteMatch { + operation: string; + zone: string | null; + recordId: number | null; + targetUser: string | null; +} + +function decode(segment: string): string | null { + try { + return decodeURIComponent(segment); + } catch { + return null; + } +} + +const ZONE_RE = /^(?=.{1,254}$)([a-z0-9_]([a-z0-9_-]{0,61}[a-z0-9_])?\.)+$/; + +export function normalizeZoneParam(raw: string): string | null { + const z = raw.toLowerCase(); + const withDot = z.endsWith('.') ? z : `${z}.`; + return ZONE_RE.test(withDot) ? withDot : null; +} + +export function matchRoute(method: string, apiPath: string): RouteMatch | null { + for (const [m, re, operation, targets] of ROUTES) { + if (m !== method.toUpperCase()) continue; + const match = re.exec(apiPath); + if (!match) continue; + const groups = match.slice(1).map((s) => decode(s)); + 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 (t === 'zone') out.zone = normalizeZoneParam(v); + if (t === 'record') out.recordId = /^[0-9]{1,9}$/.test(v) ? Number(v) : null; + if (t === 'user' || t === 'delegation') out.targetUser = v; + }); + return out; + } + return null; +} + +export function sanitizeActor(s: string): string { + return [...s] + .map((ch) => (ch === ' ' || /[\p{L}\p{M}\p{N}\p{P}\p{S}]/u.test(ch) ? ch : ' ')) + .slice(0, 64) + .join(''); +} + +export interface ExpectedAudit { + operation: string; + status: number | null; + anyStatus?: boolean; + actor: string; + origin: string; + userIsActor: boolean | null; + error?: string | null; + zone?: string | null; + recordId?: number | null; + targetUser?: string | null; + optional: boolean; + source: string; +} + +export interface ApiExchange { + method: string; + path: string; + status: number; + actor: string; + origin: string; + body: string; + sessionValid: boolean; + crossOrigin?: boolean; + optional?: boolean; + source: string; +} + +function errorOf(body: string): string | null { + try { + const parsed = JSON.parse(body) as { error?: unknown }; + return typeof parsed.error === 'string' ? parsed.error : null; + } catch { + return null; + } +} + +export class AuditLedger { + private expected: ExpectedAudit[] = []; + private mark = 0; + private pending = new Set>(); + private skipped = 0; + + constructor( + private readonly db: Db, + private readonly secrets: SecretRegistry, + ) {} + + async start(): Promise { + await this.settle(); + this.mark = await this.db.auditMaxId(); + this.expected = []; + } + + track(p: Promise): Promise { + this.pending.add(p); + p.finally(() => this.pending.delete(p)).catch(() => undefined); + return p; + } + + async settle(): Promise { + while (this.pending.size > 0) await Promise.allSettled([...this.pending]); + } + + get expectedCount(): number { + return this.expected.length; + } + + get skippedCount(): number { + return this.skipped; + } + + add(e: ExpectedAudit): void { + this.expected.push(e); + } + + 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); + if (!x.sessionValid || x.status === 401 || x.crossOrigin) { + this.skipped++; + return; + } + if (!route || x.status === 405) { + this.add( + REVIEW_FIXES + ? { operation: UNKNOWN_API_OPERATION, status: x.status, actor: x.actor, origin: x.origin, userIsActor: true, error: errorOf(x.body) ?? undefined, optional: false, source: x.source } + : { operation: '*', status: x.status, actor: x.actor, origin: x.origin, userIsActor: true, optional: true, source: x.source }, + ); + return; + } + const ok = x.status < 400; + this.add({ + operation: route.operation, + status: x.status, + actor: x.actor, + origin: x.origin, + userIsActor: true, + error: ok ? null : errorOf(x.body), + zone: ok ? route.zone : undefined, + recordId: ok && route.recordId !== null ? route.recordId : undefined, + targetUser: ok ? route.targetUser : undefined, + optional: x.optional ?? false, + source: x.source, + }); + } + + login(submitted: string, status: number, origin: string, source: string): void { + this.add({ + operation: 'login', + status, + actor: sanitizeActor(submitted), + origin, + userIsActor: status === 303 ? true : null, + optional: false, + source, + }); + } + + logout(actor: string, status: number, origin: string, sessionValid: boolean, source: string): void { + if (!sessionValid) { + this.skipped++; + return; + } + this.add({ operation: 'logout', status, actor, origin, userIsActor: true, optional: false, source }); + } + + cli(operation: string, targetUser: string, source: string): void { + this.add({ operation, status: null, actor: 'cli', origin: 'local', userIsActor: false, targetUser, error: null, optional: false, source }); + } + + async verify(label = 'audit rows match the operations performed'): Promise { + await this.settle(); + await new Promise((r) => setTimeout(r, 150)); + await this.settle(); + const rows = await this.db.auditSince(this.mark); + const userIds = new Map(); + for (const r of rows) { + for (const id of [r.user_id, r.target_user_id]) { + if (id !== null && !userIds.has(id)) userIds.set(id, (await this.db.usernameById(id)) ?? `#${id}`); + } + } + const used = new Set(); + const problems: string[] = []; + const describe = (r: AuditRow) => + `#${r.id} ${r.operation} ${r.status} actor=${JSON.stringify(r.actor)} origin=${r.origin} zone=${r.zone} record=${r.record_id} target=${r.target_user_id === null ? null : userIds.get(r.target_user_id)} error=${JSON.stringify(r.error)}`; + const matches = (e: ExpectedAudit, r: AuditRow): boolean => { + if (e.operation !== '*' && r.operation !== e.operation) return false; + if (!e.anyStatus && r.status !== e.status) return false; + if (r.actor !== e.actor) return false; + if (r.origin !== e.origin) return false; + if (e.userIsActor === true && (r.user_id === null || userIds.get(r.user_id) !== e.actor)) return false; + if (e.userIsActor === false && r.user_id !== null) return false; + if (e.error !== undefined && e.error !== null && r.error !== e.error) return false; + if (e.error === null && r.error !== null) return false; + if (e.zone !== undefined && e.zone !== null && r.zone !== e.zone) return false; + if (e.recordId !== undefined && e.recordId !== null && r.record_id !== e.recordId) return false; + if (e.targetUser !== undefined && e.targetUser !== null && (r.target_user_id === null || userIds.get(r.target_user_id) !== e.targetUser)) return false; + return true; + }; + const ordered = [...this.expected.filter((e) => !e.optional), ...this.expected.filter((e) => e.optional)]; + for (const e of ordered) { + const idx = rows.findIndex((r, i) => !used.has(i) && matches(e, r)); + if (idx >= 0) used.add(idx); + else if (!e.optional) problems.push(`missing: ${e.operation} ${e.status} actor=${JSON.stringify(e.actor)} zone=${e.zone ?? '-'} error=${JSON.stringify(e.error ?? '-')} (${e.source})`); + } + rows.forEach((r, i) => { + if (!used.has(i)) problems.push(`unexpected: ${describe(r)}`); + }); + for (const r of rows) { + if (r.status !== null && r.status >= 400 && (r.error === null || r.error === '')) problems.push(`row without error message: ${describe(r)}`); + if (r.status !== null && r.status < 400 && r.error !== null) problems.push(`successful row with error: ${describe(r)}`); + if (READ_OPERATIONS.has(r.operation) && (r.before_value !== null || r.after_value !== null)) problems.push(`read row with values: ${describe(r)}`); + if (r.status !== null && r.status >= 400 && (r.before_value !== null || r.after_value !== null)) problems.push(`failed row with values: ${describe(r)}`); + const text = JSON.stringify(r); + if (/password_hash|\$argon2id\$/i.test(text)) problems.push(`row with a password hash: ${describe(r)}`); + for (const leak of this.secrets.findIn(text)) problems.push(`row with a secret (${leak}): ${describe(r)}`); + } + expect(problems, label).toEqual([]); + if (rows.length > 0) this.mark = rows[rows.length - 1].id; + this.expected = []; + return rows; + } +} diff --git a/e2e/harness/mysql.ts b/e2e/harness/mysql.ts new file mode 100644 index 0000000..06794b1 --- /dev/null +++ b/e2e/harness/mysql.ts @@ -0,0 +1,312 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import fs from 'node:fs'; +import path from 'node:path'; +import mysql from 'mysql2/promise'; +import { GROUP_NAMES, GROUPS, MYSQL_HOST, requireEnv, type GroupConfig } from './env'; +import { HarnessError } from './errors'; + +export interface RecordRow { + id: number; + zone: string; + name: string; + ttl: number | null; + content: string | null; + record_type: string; +} + +export interface UserRow { + id: number; + username: string; + role: string; + password_hash: string; + created_at: string; + updated_at: string; + last_login_at: string | null; + deleted_at: string | null; +} + +export interface AuditRow { + id: number; + time: string; + user_id: number | null; + actor: string; + origin: string; + operation: string; + status: number | null; + error: string | null; + zone: string | null; + record_id: number | null; + target_user_id: number | null; + before_value: unknown; + after_value: unknown; +} + +export interface DelegationRow { + zone: string; + user_id: number; + username: string; + created_at: string; + created_by: number; +} + +export interface SessionRow { + user_id: number; + created_at: string; + last_seen_at: string; + expires_at: string; + origin: string; + user_agent: string; +} + +export type RawRecord = { zone: string; name: string; ttl: number | null; content: string | null; record_type: string }; + +const INIT_TEMPLATE = path.resolve(process.cwd(), 'stack', 'mysql-init.sql'); + +function connectionOptions(database?: string): mysql.ConnectionOptions { + return { + host: MYSQL_HOST, + port: 3306, + user: 'root', + password: requireEnv('E2E_MYSQL_ROOT_PASSWORD'), + database, + timezone: 'Z', + dateStrings: true, + supportBigNumbers: true, + bigNumberStrings: false, + charset: 'utf8mb4_0900_ai_ci', + connectTimeout: 10_000, + }; +} + +function q(identifier: string): string { + if (!/^[A-Za-z0-9_]+$/.test(identifier)) throw new HarnessError('infrastructure', `unsafe identifier ${identifier}`); + return '`' + identifier + '`'; +} + +export function initSql(g: GroupConfig): string { + const template = fs.readFileSync(INIT_TEMPLATE, 'utf8'); + const values: Record = { + DATABASE: g.database, + PREFIX: g.prefix, + DNS_USER: g.dnsUser, + DNS_PASSWORD: g.dnsPassword, + APP_USER: g.appUser, + APP_PASSWORD: g.appPassword, + }; + return template + .split('\n') + .filter((l) => !l.startsWith('--')) + .join('\n') + .replace(/\{\{([A-Z_]+)\}\}/g, (_m, k: string) => { + const v = values[k]; + if (v === undefined || !/^[A-Za-z0-9_-]+$/.test(v)) throw new HarnessError('infrastructure', `bad template value ${k}`); + return v; + }); +} + +export async function initDatabases(): Promise { + const conn = await mysql.createConnection({ ...connectionOptions(), multipleStatements: true }); + try { + for (const name of GROUP_NAMES) { + const [rows] = await conn.query('SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = ?', [GROUPS[name].database]); + if (rows.length > 0) continue; + await conn.query(initSql(GROUPS[name])); + } + } finally { + await conn.end(); + } +} + +export async function waitForMysql(timeoutMs = 120_000): Promise { + const deadline = Date.now() + timeoutMs; + for (;;) { + try { + const conn = await mysql.createConnection(connectionOptions()); + await conn.query('SELECT 1'); + await conn.end(); + return; + } catch (e) { + if (Date.now() > deadline) throw new HarnessError('timeout', `mysql not reachable: ${(e as Error).message}`); + await new Promise((r) => setTimeout(r, 500)); + } + } +} + +export class Db { + private readonly pool: mysql.Pool; + readonly t: { records: string; users: string; sessions: string; delegations: string; audit: string; schema: string }; + + constructor(readonly group: GroupConfig) { + this.pool = mysql.createPool({ ...connectionOptions(group.database), connectionLimit: 4 }); + const p = group.prefix; + this.t = { + records: q(`${p}records`), + users: q(`${p}webui_users`), + sessions: q(`${p}webui_sessions`), + delegations: q(`${p}webui_zone_delegations`), + audit: q(`${p}webui_audit`), + schema: q(`${p}webui_schema`), + }; + } + + async query(sql: string, params: unknown[] = []): Promise { + const [rows] = await this.pool.query(sql, params); + return rows as T[]; + } + + async exec(sql: string, params: unknown[] = []): Promise { + const [r] = await this.pool.query(sql, params); + return r; + } + + async records(zone?: string): Promise { + const where = zone === undefined ? '' : 'WHERE `zone` = BINARY ?'; + return this.query(`SELECT id, zone, name, ttl, content, record_type FROM ${this.t.records} ${where} ORDER BY id`, zone === undefined ? [] : [zone]); + } + + async recordById(id: number): Promise { + const rows = await this.query(`SELECT id, zone, name, ttl, content, record_type FROM ${this.t.records} WHERE id = ?`, [id]); + return rows[0]; + } + + async zones(): Promise { + const rows = await this.query<{ zone: string }>(`SELECT DISTINCT zone FROM ${this.t.records} ORDER BY zone`); + return rows.map((r) => r.zone); + } + + async recordCount(): Promise { + const rows = await this.query<{ n: number }>(`SELECT COUNT(*) AS n FROM ${this.t.records}`); + return Number(rows[0].n); + } + + async insertRaw(r: RawRecord): Promise { + const res = await this.exec(`INSERT INTO ${this.t.records} (zone, name, ttl, content, record_type) VALUES (?, ?, ?, ?, ?)`, [r.zone, r.name, r.ttl, r.content, r.record_type]); + return res.insertId; + } + + async insertMany(rows: RawRecord[]): Promise { + for (let i = 0; i < rows.length; i += 1000) { + const chunk = rows.slice(i, i + 1000); + await this.exec( + `INSERT INTO ${this.t.records} (zone, name, ttl, content, record_type) VALUES ${chunk.map(() => '(?, ?, ?, ?, ?)').join(', ')}`, + chunk.flatMap((r) => [r.zone, r.name, r.ttl, r.content, r.record_type]), + ); + } + } + + async updateRaw(id: number, fields: Partial): Promise { + const keys = Object.keys(fields) as Array; + if (keys.length === 0) return; + await this.exec(`UPDATE ${this.t.records} SET ${keys.map((k) => `${q(k)} = ?`).join(', ')} WHERE id = ?`, [...keys.map((k) => fields[k]), id]); + } + + async deleteZoneRaw(zone: string): Promise { + await this.exec(`DELETE FROM ${this.t.records} WHERE zone = BINARY ?`, [zone]); + } + + async soaContent(zone: string): Promise | null> { + const rows = await this.query(`SELECT id, zone, name, ttl, content, record_type FROM ${this.t.records} WHERE zone = BINARY ? AND name = '' AND record_type = 'SOA'`, [zone]); + if (rows.length !== 1 || rows[0].content === null) return null; + return JSON.parse(rows[0].content) as Record; + } + + async soaSerial(zone: string): Promise { + const soa = await this.soaContent(zone); + return soa && typeof soa.serial === 'number' ? soa.serial : null; + } + + async users(): Promise { + return this.query(`SELECT id, username, role, password_hash, created_at, updated_at, last_login_at, deleted_at FROM ${this.t.users} ORDER BY id`); + } + + async user(username: string): Promise { + const rows = await this.query( + `SELECT id, username, role, password_hash, created_at, updated_at, last_login_at, deleted_at FROM ${this.t.users} WHERE username = ?`, + [username], + ); + return rows[0]; + } + + async userId(username: string): Promise { + return (await this.user(username))?.id ?? null; + } + + async usernameById(id: number): Promise { + const rows = await this.query<{ username: string }>(`SELECT username FROM ${this.t.users} WHERE id = ?`, [id]); + return rows[0]?.username ?? null; + } + + async delegations(): Promise { + return this.query( + `SELECT d.zone, d.user_id, u.username, d.created_at, d.created_by FROM ${this.t.delegations} d JOIN ${this.t.users} u ON u.id = d.user_id ORDER BY d.zone, u.username`, + ); + } + + async sessions(userId?: number): Promise { + const where = userId === undefined ? '' : 'WHERE user_id = ?'; + return this.query(`SELECT user_id, created_at, last_seen_at, expires_at, origin, user_agent FROM ${this.t.sessions} ${where}`, userId === undefined ? [] : [userId]); + } + + async sessionExists(hash: Buffer): Promise { + const [row] = await this.query<{ n: number }>(`SELECT COUNT(*) AS n FROM ${this.t.sessions} WHERE token_hash = ?`, [hash]); + return Number(row.n) === 1; + } + + async deleteSessions(userId: number): Promise { + await this.exec(`DELETE FROM ${this.t.sessions} WHERE user_id = ?`, [userId]); + } + + async auditMaxId(): Promise { + const rows = await this.query<{ id: number | null }>(`SELECT MAX(id) AS id FROM ${this.t.audit}`); + return Number(rows[0].id ?? 0); + } + + async auditSince(id: number): Promise { + return this.query( + `SELECT id, DATE_FORMAT(time, '%Y-%m-%dT%H:%i:%s.%fZ') AS time, user_id, actor, origin, operation, status, error, zone, record_id, target_user_id, before_value, after_value FROM ${this.t.audit} WHERE id > ? ORDER BY id`, + [id], + ); + } + + async auditTail(n: number): Promise { + const rows = await this.query( + `SELECT id, DATE_FORMAT(time, '%Y-%m-%dT%H:%i:%s.%fZ') AS time, user_id, actor, origin, operation, status, error, zone, record_id, target_user_id, before_value, after_value FROM ${this.t.audit} ORDER BY id DESC LIMIT ?`, + [n], + ); + return rows.reverse(); + } + + async auditCount(where = '1 = 1', params: unknown[] = []): Promise { + const rows = await this.query<{ n: number }>(`SELECT COUNT(*) AS n FROM ${this.t.audit} WHERE ${where}`, params); + return Number(rows[0].n); + } + + async tableExists(name: string): Promise { + const rows = await this.query<{ n: number }>('SELECT COUNT(*) AS n FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', [name]); + return Number(rows[0].n) === 1; + } + + async snapshot(): Promise { + const records = await this.records().catch(() => []); + const audit = await this.auditTail(60).catch(() => []); + const users = await this.users().catch(() => []); + const delegations = await this.delegations().catch(() => []); + return JSON.stringify( + { + records: records.slice(-300), + recordCount: records.length, + users: users.map((u) => ({ ...u, password_hash: u.password_hash ? '[hash]' : '' })), + delegations, + audit, + }, + null, + 2, + ); + } + + async close(): Promise { + await this.pool.end(); + } +} diff --git a/e2e/harness/personas.ts b/e2e/harness/personas.ts new file mode 100644 index 0000000..004d501 --- /dev/null +++ b/e2e/harness/personas.ts @@ -0,0 +1,48 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { createHash } from 'node:crypto'; +import { expect, type World } from './fixtures'; +import { zp, type ApiClient } from './api'; +import { waitForZone } from './dig'; +import { servedZone } from './verify'; +import type { Ui } from './ui'; + +export function zoneInput(zone: string) { + return { name: zone, ns: 'ns.example.net.', mbox: 'hostmaster.example.net.', extra_ns: [], ttl: 300, refresh: 3600, retry: 600, expire: 604800, minttl: 300 }; +} + +export async function createZone(client: ApiClient, zone: string): Promise { + const response = await client.post('/zones', zoneInput(zone)); + expect(response.status, response.text).toBe(201); + return zp(zone); +} + +export async function checkZone(world: World, client: ApiClient, zone: string): Promise { + const response = await client.get(`${zp(zone)}/check`); + expect(response.status).toBe(200); + expect(response.json.problems.filter((p: { severity: string }) => p.severity === 'error')).toEqual([]); + await waitForZone(world.g, zone, { recorder: world.recorder }); + await servedZone(world, zone); +} + +export function address(name: string, ip: string, ttl = 300) { + return { name, type: 'A' as const, ttl, data: { ip } }; +} + +export async function addAddress(client: ApiClient, zonePath: string, name: string, ip: string) { + const response = await client.post(`${zonePath}/records`, address(name, ip)); + expect(response.status, response.text).toBe(201); + return response.json.record; +} + +export async function restartWithSessions(world: World, ...browsers: Ui[]): Promise { + const cookies = await Promise.all(browsers.map((browser) => browser.cookie())); + await world.restart(); + for (let i = 0; i < browsers.length; i++) { + const cookie = cookies[i]; + expect(Boolean(cookie && cookie === await browsers[i].cookie()), 'browser cookie survives app restart').toBe(true); + const hash = createHash('sha256').update(cookie!).digest(); + expect(await world.db.sessionExists(hash), 'the stored SHA-256 session survives app restart').toBe(true); + } +} diff --git a/e2e/harness/proc.ts b/e2e/harness/proc.ts new file mode 100644 index 0000000..e695d3d --- /dev/null +++ b/e2e/harness/proc.ts @@ -0,0 +1,93 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { spawn } from 'node:child_process'; +import { HarnessError } from './errors'; + +export interface ProcResult { + code: number | null; + signal: string | null; + stdout: string; + stderr: string; + durationMs: number; +} + +export interface ProcOptions { + input?: string | Buffer; + timeoutMs?: number; + env?: NodeJS.ProcessEnv; +} + +export function run(command: string, args: readonly string[], opts: ProcOptions = {}): Promise { + const timeoutMs = opts.timeoutMs ?? 120_000; + const started = Date.now(); + return new Promise((resolve, reject) => { + let child; + try { + child = spawn(command, [...args], { env: opts.env ?? process.env, stdio: ['pipe', 'pipe', 'pipe'] }); + } catch (e) { + reject(new HarnessError('spawn', `cannot start ${command}: ${(e as Error).message}`)); + return; + } + const out: Buffer[] = []; + const err: Buffer[] = []; + let timedOut = false; + const timer = setTimeout(() => { + timedOut = true; + child.kill('SIGKILL'); + }, timeoutMs); + child.stdout.on('data', (b: Buffer) => out.push(b)); + child.stderr.on('data', (b: Buffer) => err.push(b)); + child.on('error', (e) => { + clearTimeout(timer); + reject(new HarnessError('spawn', `cannot start ${command}: ${e.message}`)); + }); + child.on('close', (code, signal) => { + clearTimeout(timer); + const result: ProcResult = { + code, + signal, + stdout: Buffer.concat(out).toString('utf8'), + stderr: Buffer.concat(err).toString('utf8'), + durationMs: Date.now() - started, + }; + if (timedOut) { + reject(new HarnessError('timeout', `${command} ${args.slice(0, 4).join(' ')} did not finish within ${timeoutMs} ms`, result)); + return; + } + resolve(result); + }); + child.stdin.on('error', () => undefined); + if (opts.input !== undefined) child.stdin.end(opts.input); + else child.stdin.end(); + }); +} + +export async function runOk(command: string, args: readonly string[], opts: ProcOptions = {}): Promise { + const r = await run(command, args, opts); + if (r.code !== 0) { + throw new HarnessError('infrastructure', `${command} ${args.join(' ')} exited with ${r.code}: ${r.stderr.trim().slice(-2000)}`, r); + } + return r; +} + +export function sleep(ms: number): Promise { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +export async function pollUntil(what: string, fn: () => Promise, timeoutMs = 30_000, intervalMs = 250): Promise { + const deadline = Date.now() + timeoutMs; + let lastError: unknown; + for (;;) { + try { + const v = await fn(); + if (v !== undefined && v !== null && v !== false) return v as T; + } catch (e) { + lastError = e; + } + if (Date.now() > deadline) { + throw new HarnessError('timeout', `${what} did not happen within ${timeoutMs} ms${lastError ? `: ${(lastError as Error).message}` : ''}`); + } + await sleep(intervalMs); + } +} diff --git a/e2e/harness/recorder.ts b/e2e/harness/recorder.ts new file mode 100644 index 0000000..f64720f --- /dev/null +++ b/e2e/harness/recorder.ts @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +export interface CliRecord { + at: string; + container: string; + args: string[]; + stdinBytes: number; + exitCode: number | null; + durationMs: number; + stdout: string; + stderr: string; +} + +export interface HttpRecord { + at: string; + client: 'api' | 'browser'; + actor: string; + method: string; + url: string; + requestHeaders: Record; + requestBodyBytes: number; + status: number; + responseHeaders: Record; + bodyPreview: string; + durationMs: number; +} + +export interface DigRecord { + at: string; + args: string[]; + output: string; +} + +const MAX_TEXT = 8 * 1024; +const MAX_RECORDS = 3000; + +export function clip(s: string, max = MAX_TEXT): string { + return s.length <= max ? s : `${s.slice(0, max)}...[${s.length - max} more characters]`; +} + +function push(list: T[], item: T): void { + if (list.length >= MAX_RECORDS) list.shift(); + list.push(item); +} + +export class Recorder { + readonly cli: CliRecord[] = []; + readonly http: HttpRecord[] = []; + readonly dig: DigRecord[] = []; + readonly notes: string[] = []; + readonly fuzzCases: unknown[] = []; + + addCli(r: Omit): void { + push(this.cli, { at: new Date().toISOString(), ...r, stdout: clip(r.stdout), stderr: clip(r.stderr) }); + } + + addHttp(r: Omit): void { + push(this.http, { at: new Date().toISOString(), ...r, bodyPreview: clip(r.bodyPreview, 2048) }); + } + + addDig(args: string[], output: string): void { + push(this.dig, { at: new Date().toISOString(), args, output: clip(output, 4096) }); + } + + note(text: string): void { + push(this.notes, `${new Date().toISOString()} ${text}`); + } + + clear(): void { + this.cli.length = 0; + this.http.length = 0; + this.dig.length = 0; + this.notes.length = 0; + this.fuzzCases.length = 0; + } +} diff --git a/e2e/harness/records.ts b/e2e/harness/records.ts new file mode 100644 index 0000000..3e40e93 --- /dev/null +++ b/e2e/harness/records.ts @@ -0,0 +1,188 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { expect } from '@playwright/test'; + +export const TYPES = ['A', 'AAAA', 'CNAME', 'NS', 'MX', 'TXT', 'SRV', 'CAA', 'SOA'] as const; +export type RecordType = (typeof TYPES)[number]; +export const EDITABLE_TYPES = TYPES.filter((t) => t !== 'SOA'); + +export const CANONICAL_KEYS: Readonly> = { + A: ['ip'], + AAAA: ['ip'], + CNAME: ['host'], + NS: ['host'], + MX: ['host', 'preference'], + TXT: ['text'], + SRV: ['priority', 'weight', 'port', 'target'], + CAA: ['flag', 'tag', 'value'], + SOA: ['ns', 'MBox', 'refresh', 'retry', 'expire', 'minttl', 'serial'], +}; + +export type RecordData = Record; + +export interface ExpectedRecord { + zone: string; + name: string; + type: RecordType; + ttl: number; + data: RecordData; +} + +export function canonicalObject(type: RecordType, data: RecordData): RecordData { + const out: RecordData = {}; + for (const key of CANONICAL_KEYS[type]) { + if (data[key] === undefined) throw new Error(`missing ${key} for ${type}`); + out[key] = data[key]; + } + return out; +} + +export function canonicalContent(type: RecordType, data: RecordData): string { + return JSON.stringify(canonicalObject(type, data)); +} + +function unescapeGoJson(raw: string): string { + return raw.replace(/\\u003c/g, '<').replace(/\\u003e/g, '>').replace(/\\u0026/g, '&').replace(/\\u2028/g, '
').replace(/\\u2029/g, '
'); +} + +export function expectCanonicalContent(raw: string | null, type: RecordType, data: RecordData, where = 'content'): void { + expect(raw, `${where} is not NULL`).not.toBeNull(); + const expected = canonicalContent(type, data); + let parsed: unknown; + try { + parsed = JSON.parse(raw as string); + } catch { + throw new Error(`${where} is not JSON: ${raw}`); + } + expect(JSON.stringify(parsed), `${where} has the canonical keys, order and values`).toBe(expected); + expect(unescapeGoJson(raw as string), `${where} is compact canonical JSON`).toBe(expected); +} + +export function effectiveTtl(ttl: number): number { + return ttl === 0 ? 360 : ttl; +} + +export function uiTtl(ttl: number | null): string { + if (ttl === null) return 'missing'; + return ttl === 0 ? 'default (360 s)' : String(ttl); +} + +function dnsQuote(s: string): string { + return '"' + s.replace(/"/g, '\\"') + '"'; +} + +export function digData(type: RecordType, d: RecordData): string { + switch (type) { + case 'A': + case 'AAAA': + return String(d.ip); + case 'CNAME': + case 'NS': + return String(d.host); + case 'MX': + return `${d.preference} ${d.host}`; + case 'TXT': { + const text = String(d.text); + const parts: string[] = []; + for (let i = 0; i < text.length; i += 255) parts.push(text.slice(i, i + 255)); + return parts.map(dnsQuote).join(' '); + } + case 'SRV': + return `${d.priority} ${d.weight} ${d.port} ${d.target}`; + case 'CAA': + return `${d.flag} ${d.tag} ${dnsQuote(String(d.value))}`; + case 'SOA': + return `${d.ns} ${d.MBox} ${d.serial} ${d.refresh} ${d.retry} ${d.expire} ${d.minttl}`; + } +} + +export function uiValue(type: RecordType, d: RecordData): string { + switch (type) { + case 'A': + case 'AAAA': + return String(d.ip); + case 'CNAME': + case 'NS': + return String(d.host); + case 'MX': + return `${d.preference} ${d.host}`; + case 'TXT': + return `"${d.text}"`; + case 'SRV': + return `${d.priority} ${d.weight} ${d.port} ${d.target}`; + case 'CAA': + return `${d.flag} ${d.tag} "${d.value}"`; + case 'SOA': + return [d.ns, d.MBox, d.serial ?? 'dynamic', d.refresh, d.retry, d.expire, d.minttl].join(' '); + } +} + +export function zoneFileValue(type: RecordType, d: RecordData): string { + return digData(type, d); +} + +export function utcDay(now = new Date()): number { + return Number(`${now.getUTCFullYear()}${String(now.getUTCMonth() + 1).padStart(2, '0')}${String(now.getUTCDate()).padStart(2, '0')}`) * 100; +} + +export function bumpSerial(prev: number, now = new Date()): number { + let next = (prev + 1) >>> 0; + if (next === 0) next = 1; + return Math.max(next, utcDay(now)); +} + +export function newZoneSerial(now = new Date()): number { + return utcDay(now); +} + +export function acceptableBumps(prev: number, before: Date, after: Date): number[] { + return [...new Set([bumpSerial(prev, before), bumpSerial(prev, after)])]; +} + +export function expectSerialBump(prev: number, actual: number, before: Date, after: Date, what = 'SOA serial'): void { + expect(acceptableBumps(prev, before, after), `${what} bumped once from ${prev}`).toContain(actual); +} + +export function fqdnOf(name: string, zone: string): string { + return name === '' ? zone : `${name}.${zone}`; +} + +export function normalizeZone(zone: string): string { + const z = zone.toLowerCase(); + return z.endsWith('.') ? z : `${z}.`; +} + +export interface RawRecordInput { + zone: string; + name: string; + type: RecordType; + ttl: number; + data: RecordData; +} + +export function rawRecord(r: RawRecordInput): { zone: string; name: string; ttl: number; content: string; record_type: string } { + return { zone: r.zone, name: r.name, ttl: r.ttl, content: canonicalContent(r.type, r.data), record_type: r.type }; +} + +export function soaData(zone: string, serial: number, timers: Partial> = {}): RecordData { + return { + ns: `ns1.${zone}`, + MBox: `hostmaster.${zone}`, + refresh: timers.refresh ?? 3600, + retry: timers.retry ?? 600, + expire: timers.expire ?? 604800, + minttl: timers.minttl ?? 300, + serial, + }; +} + +export function sqlZone(zone: string, serial = newZoneSerial(), ttl = 3600): RawRecordInput[] { + return [ + { zone, name: '', type: 'SOA', ttl, data: soaData(zone, serial) }, + { zone, name: '', type: 'NS', ttl, data: { host: `ns1.${zone}` } }, + { zone, name: '', type: 'NS', ttl, data: { host: `ns2.${zone}` } }, + { zone, name: 'ns1', type: 'A', ttl, data: { ip: '192.0.2.1' } }, + { zone, name: 'ns2', type: 'A', ttl, data: { ip: '192.0.2.2' } }, + ]; +} diff --git a/e2e/harness/reporter.ts b/e2e/harness/reporter.ts new file mode 100644 index 0000000..7a113ce --- /dev/null +++ b/e2e/harness/reporter.ts @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import type { FullConfig, Reporter, TestCase, TestError, TestResult, TestStep } from '@playwright/test/reporter'; +import { loadPersistedSecrets, redactText } from './secrets'; + +const TEXTUAL = /^(text\/|application\/(json|xml|x-ndjson))|markdown/; + +function secretsDirectory(): string | null { + const project = process.env.E2E_PROJECT; + if (!project) return null; + return path.join(os.tmpdir(), `${project}-run`, 'secrets'); +} + +export default class RedactingReporter implements Reporter { + private outputDirs: string[] = []; + + printsToStdio(): boolean { + return false; + } + + onBegin(config: FullConfig): void { + this.outputDirs = config.projects.map((p) => path.resolve(p.outputDir)); + } + + onTestEnd(_test: TestCase, result: TestResult): void { + const dir = secretsDirectory(); + const secrets = dir ? loadPersistedSecrets(dir) : []; + const r = (s: string) => redactText(s, secrets); + const fixError = (e: TestError | undefined) => { + if (!e) return; + if (e.message) e.message = r(e.message); + if (e.stack) e.stack = r(e.stack); + if (e.value) e.value = r(e.value); + if (e.snippet) e.snippet = r(e.snippet); + if (e.cause) fixError(e.cause); + }; + result.errors.forEach(fixError); + fixError(result.error); + const fixStep = (s: TestStep) => { + fixError(s.error); + s.title = r(s.title); + s.steps.forEach(fixStep); + }; + result.steps.forEach(fixStep); + result.stdout = result.stdout.map((c) => (typeof c === 'string' ? r(c) : Buffer.from(r(c.toString('utf8'))))); + result.stderr = result.stderr.map((c) => (typeof c === 'string' ? r(c) : Buffer.from(r(c.toString('utf8'))))); + for (const a of result.attachments) { + if (!TEXTUAL.test(a.contentType)) continue; + if (a.body) a.body = Buffer.from(r(a.body.toString('utf8'))); + if (a.path && this.outputDirs.some((d) => path.resolve(a.path as string).startsWith(d + path.sep)) && fs.existsSync(a.path)) { + const text = fs.readFileSync(a.path, 'utf8'); + const red = r(text); + if (red !== text) fs.writeFileSync(a.path, red); + } + } + } +} diff --git a/e2e/harness/rng.ts b/e2e/harness/rng.ts new file mode 100644 index 0000000..672285e --- /dev/null +++ b/e2e/harness/rng.ts @@ -0,0 +1,85 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import crypto from 'node:crypto'; + +export class Rng { + private a: number; + private b: number; + private c: number; + private d: number; + + constructor(readonly seed: string) { + const h = crypto.createHash('sha256').update(seed, 'utf8').digest(); + this.a = h.readUInt32LE(0); + this.b = h.readUInt32LE(4); + this.c = h.readUInt32LE(8); + this.d = h.readUInt32LE(12); + for (let i = 0; i < 12; i++) this.nextUint32(); + } + + fork(label: string): Rng { + return new Rng(`${this.seed}/${label}`); + } + + nextUint32(): number { + const t = (((this.a + this.b) >>> 0) + this.d) >>> 0; + this.d = (this.d + 1) >>> 0; + this.a = this.b ^ (this.b >>> 9); + this.b = (this.c + (this.c << 3)) >>> 0; + this.c = ((this.c << 21) | (this.c >>> 11)) >>> 0; + this.c = (this.c + t) >>> 0; + return t; + } + + next(): number { + return this.nextUint32() / 4294967296; + } + + int(min: number, max: number): number { + return min + Math.floor(this.next() * (max - min + 1)); + } + + bool(pTrue = 0.5): boolean { + return this.next() < pTrue; + } + + pick(items: readonly T[]): T { + if (items.length === 0) throw new Error('pick from an empty array'); + return items[this.int(0, items.length - 1)]; + } + + weighted(items: ReadonlyArray): T { + const total = items.reduce((s, [, w]) => s + w, 0); + let r = this.next() * total; + for (const [item, w] of items) { + r -= w; + if (r < 0) return item; + } + return items[items.length - 1][0]; + } + + shuffle(items: readonly T[]): T[] { + const a = [...items]; + for (let i = a.length - 1; i > 0; i--) { + const j = this.int(0, i); + [a[i], a[j]] = [a[j], a[i]]; + } + return a; + } + + sample(items: readonly T[], n: number): T[] { + return this.shuffle(items).slice(0, Math.min(n, items.length)); + } + + string(length: number, alphabet = 'abcdefghijklmnopqrstuvwxyz0123456789'): string { + const chars = [...alphabet]; + let s = ''; + for (let i = 0; i < length; i++) s += chars[this.int(0, chars.length - 1)]; + return s; + } +} + +export function testSeed(runSeedValue: string, titlePath: readonly string[]): string { + return `${runSeedValue}::${titlePath.join(' > ')}`; +} diff --git a/e2e/harness/secrets.ts b/e2e/harness/secrets.ts new file mode 100644 index 0000000..074d6a8 --- /dev/null +++ b/e2e/harness/secrets.ts @@ -0,0 +1,108 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import crypto from 'node:crypto'; +import fs from 'node:fs'; +import path from 'node:path'; +import { SESSION_COOKIE } from './env'; + +const TOKEN_CANDIDATE = /(?): string { + let out = text; + const list = [...new Set(secrets)].filter((s) => s.length >= 4).sort((a, b) => b.length - a.length); + for (const s of list) { + if (out.includes(s)) out = out.split(s).join(redactionFor(s)); + } + out = out.replace(COOKIE_PAIR, (_m, k: string) => `${k}[REDACTED]`); + out = out.replace(JSON_SECRET, (_m, k: string) => `${k}"[REDACTED]"`); + out = out.replace(FORM_SECRET, (_m, k: string) => `${k}[REDACTED]`); + out = out.replace(HASH, '[REDACTED:hash]'); + out = out.replace(TOKEN_CANDIDATE, (m) => redactionFor(m)); + return out; +} + +export function redactValue(value: T, secrets: Iterable): T { + const list = [...secrets]; + const walk = (v: unknown): unknown => { + if (typeof v === 'string') return redactText(v, list); + if (Array.isArray(v)) return v.map(walk); + if (Buffer.isBuffer(v)) return redactText(v.toString('utf8'), list); + if (v && typeof v === 'object') { + const o: Record = {}; + for (const [k, x] of Object.entries(v)) { + const lower = k.toLowerCase(); + o[k] = lower === 'cookie' || lower === 'set-cookie' || lower === 'password' || lower === 'current' ? '[REDACTED]' : walk(x); + } + return o; + } + return v; + }; + return walk(value) as T; +} + +export class SecretRegistry { + private readonly secrets = new Map(); + + constructor(private readonly persistFile?: string) {} + + register(secret: string, label = 'secret'): string { + if (!secret || this.secrets.has(secret)) return secret; + this.secrets.set(secret, label); + if (this.persistFile) { + fs.mkdirSync(path.dirname(this.persistFile), { recursive: true, mode: 0o700 }); + fs.appendFileSync(this.persistFile, JSON.stringify(secret) + '\n', { mode: 0o600 }); + } + return secret; + } + + all(): string[] { + return [...this.secrets.keys()]; + } + + labelled(): Array<[string, string]> { + return [...this.secrets.entries()]; + } + + redact(text: string): string { + return redactText(text, this.secrets.keys()); + } + + redactValue(value: T): T { + return redactValue(value, this.secrets.keys()); + } + + findIn(text: string): string[] { + return this.labelled() + .filter(([secret]) => secret.length >= 8 && text.includes(secret)) + .map(([secret, label]) => `${label} ${redactionFor(secret)}`); + } +} + +export function loadPersistedSecrets(dir: string): string[] { + const out = new Set(); + let files: string[] = []; + try { + files = fs.readdirSync(dir); + } catch { + return []; + } + for (const f of files) { + try { + for (const line of fs.readFileSync(path.join(dir, f), 'utf8').split('\n')) { + if (line.trim()) out.add(JSON.parse(line) as string); + } + } catch { + continue; + } + } + return [...out]; +} diff --git a/e2e/harness/served.ts b/e2e/harness/served.ts new file mode 100644 index 0000000..50d5d33 --- /dev/null +++ b/e2e/harness/served.ts @@ -0,0 +1,291 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { expect } from '@playwright/test'; +import { dig, type DigResult, type DigRR } from './dig'; +import type { GroupConfig } from './env'; +import type { RecordRow } from './mysql'; +import type { Recorder } from './recorder'; + +export const PLUGIN_TYPES = ['A', 'AAAA', 'CNAME', 'NS', 'MX', 'TXT', 'SRV', 'CAA', 'SOA']; +const MAX_CNAME_CHAIN = 10; +const DEFAULT_TTL = 360; + +export interface ModelRR { + name: string; + ttl: number; + type: string; + data: string; +} + +export interface ModelAnswer { + rcode: 'NOERROR' | 'NXDOMAIN' | 'SERVFAIL' | 'NOTIMP' | 'REFUSED'; + answer: ModelRR[]; + authority: ModelRR[]; +} + +class ModelFailure extends Error { + constructor(readonly rcode: 'SERVFAIL' | 'NOTIMP') { + super(rcode); + } +} + +function eqCi(a: string, b: string): boolean { + return a.toLowerCase() === b.toLowerCase(); +} + +function fqdn(s: string): string { + return s.endsWith('.') ? s : `${s}.`; +} + +function isSubDomain(parent: string, child: string): boolean { + const p = fqdn(parent).toLowerCase(); + const c = fqdn(child).toLowerCase(); + return c === p || c.endsWith(`.${p}`) || p === '.'; +} + +export function split255(s: string): string[] { + if (s.length < 255) return [s]; + const out: string[] = []; + let p = 0; + let i = 255; + for (;;) { + if (i <= s.length) out.push(s.slice(p, i)); + else { + out.push(s.slice(p)); + break; + } + p += 255; + i += 255; + } + return out; +} + +function quote(s: string): string { + return `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`; +} + +function u16(v: unknown): number { + const n = typeof v === 'number' ? v : 0; + return n & 0xffff; +} + +function u32(v: unknown): number { + const n = typeof v === 'number' ? v : 0; + return n >>> 0; +} + +function str(v: unknown): string { + return typeof v === 'string' ? v : ''; +} + +function parseIp(v: unknown): string | null { + return typeof v === 'string' && v !== '' ? v : null; +} + +function rrFor(row: RecordRow, now: () => number): ModelRR | null { + if (row.ttl === null || row.ttl < 0 || row.ttl > 0xffffffff) throw new ModelFailure('SERVFAIL'); + if (row.content === null) throw new ModelFailure('SERVFAIL'); + const ttl = row.ttl === 0 ? DEFAULT_TTL : row.ttl; + const owner = (row.name === '' ? row.zone : `${row.name}.${row.zone}`).toLowerCase(); + let c: Record; + try { + const parsed = JSON.parse(row.content); + if (parsed === null) { + if (row.record_type === 'A' || row.record_type === 'AAAA') return null; + throw new ModelFailure('SERVFAIL'); + } + if (typeof parsed !== 'object' || Array.isArray(parsed)) throw new ModelFailure('SERVFAIL'); + c = parsed as Record; + } catch (e) { + if (e instanceof ModelFailure) throw e; + throw new ModelFailure('SERVFAIL'); + } + switch (row.record_type) { + case 'A': + case 'AAAA': { + const ip = parseIp(c.ip); + return ip === null ? null : { name: owner, ttl, type: row.record_type, data: ip }; + } + case 'CNAME': + case 'NS': + return { name: owner, ttl, type: row.record_type, data: str(c.host).toLowerCase() }; + case 'MX': + return { name: owner, ttl, type: 'MX', data: `${u16(c.preference)} ${str(c.host).toLowerCase()}` }; + case 'TXT': { + const text = str(c.text); + if (text.length === 0) return null; + return { name: owner, ttl, type: 'TXT', data: split255(text).map(quote).join(' ') }; + } + case 'SRV': + return { name: owner, ttl, type: 'SRV', data: `${u16(c.priority)} ${u16(c.weight)} ${u16(c.port)} ${str(c.target).toLowerCase()}` }; + case 'CAA': { + if (str(c.value) === '' || str(c.tag) === '') return null; + return { name: owner, ttl, type: 'CAA', data: `${u32(c.flag) & 0xff} ${str(c.tag)} ${quote(str(c.value))}` }; + } + case 'SOA': { + const serial = u32(c.serial) === 0 ? now() : u32(c.serial); + return { + name: fqdn(row.zone).toLowerCase(), + ttl, + type: 'SOA', + data: `${str(c.ns).toLowerCase()} ${str(c.MBox).toLowerCase()} ${serial} ${u32(c.refresh)} ${u32(c.retry)} ${u32(c.expire)} ${u32(c.minttl)}`, + }; + } + default: + throw new ModelFailure('NOTIMP'); + } +} + +export class PluginModel { + constructor( + private readonly rows: RecordRow[], + private readonly now: () => number = () => Math.floor(Date.now() / 1000), + ) {} + + zones(): string[] { + return [...new Set(this.rows.map((r) => r.zone))]; + } + + matchZone(qname: string): string { + let best = ''; + for (const z of this.zones()) { + if (isSubDomain(z, qname) && z.length > best.length) best = z; + } + return best; + } + + findRecord(zone: string, name: string, types: string[]): RecordRow[] { + let query = ''; + if (name !== zone) query = name.endsWith(`.${zone}`) ? name.slice(0, -(zone.length + 1)) : name; + const out = this.rows.filter((r) => eqCi(r.zone, zone) && eqCi(r.name, query) && types.some((t) => eqCi(t, r.record_type))); + if (out.length === 0 && name !== zone) return this.findWildcard(zone, name, types); + return out; + } + + private findWildcard(zone: string, name: string, types: string[]): RecordRow[] { + if (name === '*') return []; + const rest = name.startsWith('*.') ? name.slice(2) : name; + const dot = rest.indexOf('.'); + const shot = dot < 0 || dot === rest.length - 1; + const target = shot ? '*' : `*.${rest.slice(dot + 1)}`; + return this.findRecord(zone, target, types); + } + + private cnameTarget(row: RecordRow): string { + if (row.content === null) throw new ModelFailure('SERVFAIL'); + try { + const c = JSON.parse(row.content) as Record; + return str(c?.host); + } catch { + throw new ModelFailure('SERVFAIL'); + } + } + + private cnameChain(zone: string, qname: string, qtype: string): RecordRow[] { + const out: RecordRow[] = []; + const seen = new Set(); + let name = qname; + while (seen.size < MAX_CNAME_CHAIN) { + const key = fqdn(name).toLowerCase(); + if (seen.has(key)) break; + seen.add(key); + const cnames = this.findRecord(zone, name, ['CNAME']); + if (cnames.length === 0) break; + out.push(cnames[0]); + const target = this.cnameTarget(cnames[0]); + if (target === '' || !isSubDomain(zone, target)) break; + const found = this.findRecord(zone, target, [qtype]); + if (found.length > 0) return [...out, ...found]; + name = target; + } + return out; + } + + private nameExists(zone: string, name: string): boolean { + if (eqCi(fqdn(name), fqdn(zone))) return true; + const relative = name.endsWith(`.${zone}`) ? name.slice(0, -(zone.length + 1)) : name; + const labels = relative.split('.').filter(Boolean); + const wild = new Set(); + for (let i = 1; i <= labels.length; i++) wild.add(['*', ...labels.slice(i)].join('.').toLowerCase()); + return this.rows.some( + (r) => eqCi(r.zone, zone) && (eqCi(r.name, relative) || r.name.toLowerCase().endsWith(`.${relative.toLowerCase()}`) || wild.has(r.name.toLowerCase())), + ); + } + + answer(qnameIn: string, qtype: string): ModelAnswer { + const qname = fqdn(qnameIn); + try { + const zone = this.matchZone(qname); + if (zone === '') return { rcode: 'SERVFAIL', answer: [], authority: [] }; + let records = this.findRecord(zone, qname, [qtype]); + if (records.length === 0 && qtype !== 'CNAME') records = this.cnameChain(zone, qname, qtype); + let notFound = false; + let exists = true; + if (records.length === 0) { + notFound = true; + exists = this.nameExists(zone, qname); + records = [...records, ...this.findRecord(zone, '', ['SOA'])]; + } + if (qtype === 'SOA') records = [...records, ...this.findRecord(zone, qname, ['NS'])]; + const rrs: ModelRR[] = []; + for (const r of records) { + const rr = rrFor(r, this.now); + if (rr) rrs.push(rr); + } + if (!notFound) return { rcode: 'NOERROR', answer: rrs, authority: [] }; + return { rcode: exists ? 'NOERROR' : 'NXDOMAIN', answer: [], authority: rrs }; + } catch (e) { + if (e instanceof ModelFailure) return { rcode: e.rcode, answer: [], authority: [] }; + throw e; + } + } +} + +function canon(rrs: Array, wildcardOk: string): string[] { + return rrs + .map((r) => { + const name = r.name.toLowerCase(); + const n = name.startsWith('*.') ? wildcardOk : name; + const data = r.type === 'SOA' ? r.data.toLowerCase().replace(/^(\S+ \S+) \d+/, '$1 SERIAL') : r.data; + return `${n} ${r.ttl} ${r.type} ${data}`; + }) + .sort(); +} + +function soaSerialOf(rrs: Array): number | null { + const soa = rrs.find((r) => r.type === 'SOA'); + if (!soa) return null; + return Number(soa.data.split(/\s+/)[2]); +} + +export interface ServedOptions { + recorder?: Recorder; + serial?: number | null; + label?: string; +} + +export async function expectServed(g: GroupConfig, rows: RecordRow[], qname: string, qtype: string, opts: ServedOptions = {}): Promise { + const model = new PluginModel(rows).answer(qname, qtype); + const label = opts.label ?? `${qname} ${qtype}`; + const got = await dig(g, qname, qtype, { recorder: opts.recorder }); + expect(got.rcode, `${label}: rcode (${got.raw.slice(0, 600)})`).toBe(model.rcode); + if (model.rcode === 'NOERROR' || model.rcode === 'NXDOMAIN') { + expect(got.flags, `${label}: authoritative answer`).toContain('aa'); + } + const wildcard = fqdn(qname).toLowerCase(); + expect(canon(got.answer, wildcard), `${label}: answer section`).toEqual(canon(model.answer, wildcard)); + expect(canon(got.authority, wildcard), `${label}: authority section`).toEqual(canon(model.authority, wildcard)); + const servedSerial = soaSerialOf([...got.answer, ...got.authority]); + const modelSerial = soaSerialOf([...model.answer, ...model.authority]); + if (modelSerial !== null && opts.serial !== undefined && opts.serial !== null) { + expect(servedSerial, `${label}: served SOA serial`).toBe(opts.serial); + } else if (modelSerial !== null && servedSerial !== null && rows.some((r) => r.record_type === 'SOA' && /"serial":[1-9]/.test(r.content ?? ''))) { + expect(servedSerial, `${label}: served SOA serial`).toBe(modelSerial); + } + return got; +} + +export function neverFails(r: DigResult, label: string): void { + expect(['SERVFAIL', 'NOTIMP'], `${label}: CoreDNS must not answer ${r.rcode}`).not.toContain(r.rcode); +} diff --git a/e2e/harness/stack.ts b/e2e/harness/stack.ts new file mode 100644 index 0000000..066fc29 --- /dev/null +++ b/e2e/harness/stack.ts @@ -0,0 +1,71 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { compose, docker, dockerOk } from './docker'; +import { dig } from './dig'; +import { containerName, GROUP_NAMES, GROUPS, ORIGIN2_URL, type GroupConfig } from './env'; +import { HarnessError } from './errors'; +import { initDatabases, waitForMysql } from './mysql'; +import { pollUntil } from './proc'; + +export const STACK_SERVICES = ['mysql', 'coredns', 'origin2', ...GROUP_NAMES.map((g) => GROUPS[g].service)]; + +export async function waitHealth(group: GroupConfig, timeoutMs = 90_000): Promise { + await pollUntil( + `${group.service} /health`, + async () => { + const res = await fetch(`${group.baseURL}/health`, { signal: AbortSignal.timeout(3000) }); + const body = await res.text(); + return res.status === 200 && body.trim() === '{"status":"ok"}'; + }, + timeoutMs, + 500, + ); +} + +export async function waitDns(group: GroupConfig, timeoutMs = 60_000): Promise { + await pollUntil(`coredns port ${group.dnsPort}`, async () => (await dig(group, 'probe.invalid.', 'A')).rcode !== '', timeoutMs, 500); +} + +export async function stackUp(log: (s: string) => void = () => undefined): Promise { + const started = Date.now(); + await compose(['up', '--detach', '--wait', '--wait-timeout', '240', 'mysql'], { timeoutMs: 300_000 }); + await waitForMysql(); + await initDatabases(); + log(`mysql ready and initialized after ${Date.now() - started} ms`); + const rest = STACK_SERVICES.filter((s) => s !== 'mysql'); + try { + await compose(['up', '--detach', '--wait', '--wait-timeout', '240', ...rest], { timeoutMs: 300_000 }); + } catch (e) { + const logs = await Promise.all(rest.map(async (s) => `--- ${s}\n${(await docker(['logs', '--tail', '40', containerName(s)])).stderr}`)); + throw new HarnessError('prerequisite', `stack services did not become healthy: ${(e as Error).message}\n${logs.join('\n')}`); + } + for (const name of GROUP_NAMES) { + await waitHealth(GROUPS[name]); + await waitDns(GROUPS[name]); + } + await pollUntil('second origin', async () => (await fetch(`${ORIGIN2_URL}/health`, { signal: AbortSignal.timeout(3000) })).status === 200, 60_000, 500); + log(`stack ready after ${Date.now() - started} ms`); +} + +export async function stackDown(): Promise { + await compose(['rm', '--stop', '--force', '--volumes', ...STACK_SERVICES], { timeoutMs: 180_000 }); +} + +export async function restartApp(group: GroupConfig): Promise { + await dockerOk(['restart', '--time', '25', containerName(group.service)], { timeoutMs: 120_000 }); + await waitHealth(group); +} + +export async function appLogs(group: GroupConfig): Promise { + const r = await docker(['logs', containerName(group.service)], { timeoutMs: 60_000 }); + return r.stdout + r.stderr; +} + +export async function staticHash(group: GroupConfig): Promise { + const res = await fetch(`${group.baseURL}/login`); + const html = await res.text(); + const m = /\/static\/([0-9a-f]+)\/css\/app\.css/.exec(html); + if (!m) throw new HarnessError('protocol', 'no static hash in the login page'); + return m[1]; +} diff --git a/e2e/harness/ui.ts b/e2e/harness/ui.ts new file mode 100644 index 0000000..aaf0448 --- /dev/null +++ b/e2e/harness/ui.ts @@ -0,0 +1,607 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { expect, type Browser, type BrowserContext, type Page, type Response } from '@playwright/test'; +import { runnerAddress, SESSION_COOKIE, type GroupConfig } from './env'; +import type { LoginHooks } from './api'; +import type { AuditLedger } from './ledger'; +import type { Recorder } from './recorder'; +import type { SecretRegistry } from './secrets'; + +export interface UiDeps { + group: GroupConfig; + ledger?: AuditLedger; + recorder: Recorder; + secrets: SecretRegistry; + hooks?: LoginHooks; +} + +export interface UiRow { + name: string; + fqdn: string; + type: string; + ttl: string; + value: string; + problems: string[]; + checkable: boolean; +} + +export interface RowMatch { + name: string; + type: string; + value?: string; +} + +export interface RecordInput { + name: string; + type: string; + ttl?: string; + fields: Record; +} + +export interface ZoneInput { + name: string; + ns: string; + mbox: string; + extraNs?: string[]; + refresh?: string; + retry?: string; + expire?: string; + minttl?: string; + ttl?: string; +} + +export interface UiResponse { + status: number; + json: any; +} + +export interface UiOpenOptions { + colorScheme?: 'light' | 'dark'; + viewport?: { width: number; height: number }; +} + +async function responseJson(res: Response): Promise { + try { + return await res.json(); + } catch { + return undefined; + } +} + +async function bounded(p: Promise, fallback: T, ms = 5000): Promise { + let timer: NodeJS.Timeout | undefined; + const limit = new Promise((resolve) => { + timer = setTimeout(() => resolve(fallback), ms); + }); + try { + return await Promise.race([p.catch(() => fallback), limit]); + } finally { + clearTimeout(timer); + } +} + +export class Ui { + user = ''; + + private constructor( + readonly context: BrowserContext, + readonly page: Page, + private readonly deps: UiDeps, + ) {} + + static async open(browser: Browser, deps: UiDeps, opts: UiOpenOptions = {}): Promise { + const context = await browser.newContext({ + baseURL: deps.group.baseURL, + colorScheme: opts.colorScheme ?? 'light', + viewport: opts.viewport ?? { width: 1440, height: 900 }, + acceptDownloads: true, + }); + const page = await context.newPage(); + const ui = new Ui(context, page, deps); + ui.attach(); + return ui; + } + + private attach(): void { + const appOrigin = new URL(this.deps.group.baseURL).origin; + this.context.on('response', (res) => { + const p = this.observe(res, appOrigin); + if (this.deps.ledger) this.deps.ledger.track(p); + else p.catch(() => undefined); + }); + this.context.on('requestfailed', (req) => { + const url = new URL(req.url()); + if (url.origin !== appOrigin || !url.pathname.startsWith('/api/v1') || this.user === '') return; + this.deps.recorder.note(`browser request failed: ${req.method()} ${url.pathname} ${req.failure()?.errorText ?? ''}`); + this.deps.ledger?.add({ operation: '*', status: null, anyStatus: true, actor: this.user, origin: runnerAddress(), userIsActor: true, optional: true, source: `aborted browser ${req.method()} ${url.pathname}` }); + }); + } + + private async observe(res: Response, appOrigin: string): Promise { + const url = new URL(res.url()); + if (url.origin !== appOrigin) return; + const req = res.request(); + const method = req.method(); + const path = url.pathname + url.search; + if (method === 'GET' && req.isNavigationRequest() && url.pathname.endsWith('/export')) return; + const status = res.status(); + const reqHeaders = await bounded(req.allHeaders(), {} as Record); + const fetchSite = reqHeaders['sec-fetch-site']; + const origin = reqHeaders.origin; + const referer = reqHeaders.referer; + const otherOrigin = origin !== undefined ? origin !== appOrigin : referer !== undefined && new URL(referer).origin !== appOrigin; + const crossOrigin = method !== 'GET' && method !== 'HEAD' && + (fetchSite === undefined ? otherOrigin : fetchSite !== 'same-origin' && fetchSite !== 'none'); + let body = ''; + if (url.pathname.startsWith('/api/v1')) body = await bounded(res.text(), ''); + this.deps.recorder.addHttp({ + client: 'browser', + actor: this.user, + method, + url: path, + requestHeaders: this.deps.secrets.redactValue(reqHeaders), + requestBodyBytes: req.postDataBuffer()?.length ?? 0, + status, + responseHeaders: this.deps.secrets.redactValue(await bounded(res.allHeaders(), {} as Record)), + bodyPreview: this.deps.secrets.redact(body), + durationMs: 0, + }); + if (crossOrigin) return; + if (url.pathname === '/login' && method === 'POST') { + const form = new URLSearchParams(req.postData() ?? ''); + const username = form.get('username') ?? ''; + const password = form.get('password'); + if (password) this.deps.secrets.register(password, `password of ${username}`); + this.deps.ledger?.login(username, status, runnerAddress(), `browser login ${username}`); + this.deps.hooks?.afterLogin(username, status); + if (status === 303) { + this.user = username; + const cookies = await this.context.cookies(); + const c = cookies.find((x) => x.name === SESSION_COOKIE); + if (c) this.deps.secrets.register(c.value, `session cookie of ${username}`); + } + return; + } + if (url.pathname === '/logout' && method === 'POST') { + this.deps.ledger?.logout(this.user, status, runnerAddress(), this.user !== '', `browser logout ${this.user}`); + this.user = ''; + return; + } + if (!url.pathname.startsWith('/api/v1')) return; + const valid = this.user !== '' && status !== 401; + this.deps.ledger?.api({ method, path, status, actor: this.user, origin: runnerAddress(), body, sessionValid: valid, source: `browser ${method} ${path} as ${this.user}` }); + if (status === 401) this.user = ''; + } + + sessionEnded(): void { + this.user = ''; + } + + async settle(): Promise { + await this.page.waitForLoadState('networkidle'); + await this.deps.ledger?.settle(); + } + + async goto(path: string): Promise { + const res = await this.page.goto(path); + await this.settle(); + return res; + } + + async login(username: string, password: string, opts: { expectSuccess?: boolean } = {}): Promise { + await this.deps.hooks?.beforeLogin(username); + if (!this.page.url().includes('/login')) await this.goto('/login'); + await this.page.fill('#login-username', username); + await this.page.fill('#login-password', password); + const done = this.page.waitForResponse((r) => new URL(r.url()).pathname === '/login' && r.request().method() === 'POST'); + await this.page.getByRole('button', { name: 'Sign in' }).click(); + const res = await done; + await this.settle(); + if (opts.expectSuccess ?? true) { + expect(res.status(), `login of ${username}`).toBe(303); + await expect(this.page).not.toHaveURL(/\/login/); + } + } + + async logout(): Promise { + const done = this.page.waitForResponse((r) => new URL(r.url()).pathname === '/logout'); + await this.page.getByRole('button', { name: 'Log out' }).click(); + await done; + await this.settle(); + } + + async cookie(): Promise { + return (await this.context.cookies()).find((c) => c.name === SESSION_COOKIE)?.value; + } + + async toasts(): Promise { + return this.page.locator('#toasts .toast-text').allTextContents(); + } + + async expectToast(text: string | RegExp): Promise { + await expect(this.page.locator('#toasts .toast-text').filter({ hasText: text }).first()).toBeVisible(); + } + + async createZone(z: ZoneInput, opts: { expectStatus?: number } = {}): Promise { + if (new URL(this.page.url()).pathname !== '/') await this.goto('/'); + await this.page.click('#new-zone'); + await expect(this.page.locator('#zone-dialog')).toBeVisible(); + await this.page.fill('#nz-name', z.name); + await this.page.fill('#nz-ns', z.ns); + await this.page.fill('#nz-mbox', z.mbox); + await this.page.fill('#nz-extra', (z.extraNs ?? []).join('\n')); + if (z.refresh !== undefined) await this.page.fill('#nz-refresh', z.refresh); + if (z.retry !== undefined) await this.page.fill('#nz-retry', z.retry); + if (z.expire !== undefined) await this.page.fill('#nz-expire', z.expire); + if (z.minttl !== undefined) await this.page.fill('#nz-minttl', z.minttl); + if (z.ttl !== undefined) await this.page.fill('#nz-ttl', z.ttl); + const done = this.page.waitForResponse((r) => new URL(r.url()).pathname === '/api/v1/zones' && r.request().method() === 'POST'); + await this.page.locator('#zone-form button[type=submit]').click(); + const res = await done; + const out = { status: res.status(), json: await responseJson(res) }; + if (opts.expectStatus !== undefined) expect(out.status, `create zone ${z.name}: ${JSON.stringify(out.json)}`).toBe(opts.expectStatus); + if (out.status === 201) await expect(this.page.locator('#zone-dialog')).toBeHidden(); + await this.settle(); + return out; + } + + async openZone(zone: string): Promise { + await this.goto(`/zones/${encodeURIComponent(zone)}`); + await expect(this.page.locator('#records-status')).not.toHaveText('Loading records...'); + } + + async rows(): Promise { + return this.page.$$eval('#records-body tr', (trs) => + trs.map((tr) => { + const cells = [...tr.children] as HTMLElement[]; + const box = tr.querySelector('input[type=checkbox]') as HTMLInputElement | null; + return { + name: (tr.querySelector('th .mono')?.textContent ?? '').trim(), + fqdn: tr.querySelector('th')?.getAttribute('title') ?? '', + type: (cells[2]?.textContent ?? '').trim(), + ttl: (cells[3]?.textContent ?? '').trim(), + value: (tr.querySelector('td.value > code')?.textContent ?? '').trim(), + problems: [...tr.querySelectorAll('td.value li code')].map((c) => (c.textContent ?? '').trim()), + checkable: box !== null && !box.disabled, + }; + }), + ); + } + + async rowIndex(m: RowMatch): Promise { + const rows = await this.rows(); + const idx = rows.findIndex((r) => r.name === m.name && r.type === m.type && (m.value === undefined || r.value === m.value)); + if (idx < 0) throw new Error(`no row ${JSON.stringify(m)} in ${JSON.stringify(rows.map((r) => `${r.name} ${r.type} ${r.value}`))}`); + return idx; + } + + async row(m: RowMatch) { + return this.page.locator('#records-body tr').nth(await this.rowIndex(m)); + } + + async expectRow(m: RowMatch & { ttl?: string }): Promise { + await expect + .poll(async () => (await this.rows()).filter((r) => r.name === m.name && r.type === m.type && (m.value === undefined || r.value === m.value) && (m.ttl === undefined || r.ttl === m.ttl)).length, { + message: `UI shows ${JSON.stringify(m)}`, + }) + .toBe(1); + } + + async expectNoRow(m: RowMatch): Promise { + await expect + .poll(async () => (await this.rows()).filter((r) => r.name === m.name && r.type === m.type && (m.value === undefined || r.value === m.value)).length, { + message: `UI no longer shows ${JSON.stringify(m)}`, + }) + .toBe(0); + } + + private async fillRecordForm(input: RecordInput, editing: boolean): Promise { + if (!editing || (await this.page.locator('#rec-type').isEnabled())) await this.page.selectOption('#rec-type', input.type); + await this.page.fill('#rec-name', input.name); + if (input.ttl !== undefined) await this.page.fill('#rec-ttl', input.ttl); + for (const [key, value] of Object.entries(input.fields)) { + const el = this.page.locator(`#rec-f-${key}`); + const tag = await el.evaluate((e) => e.tagName); + if (tag === 'SELECT') await el.selectOption(value); + else await el.fill(value); + } + } + + private async submitRecord(method: string): Promise { + const done = this.page.waitForResponse((r) => /\/api\/v1\/zones\/[^/]+\/records(\/\d+)?$/.test(new URL(r.url()).pathname) && r.request().method() === method); + await this.page.click('#rec-submit'); + const res = await done; + const out = { status: res.status(), json: await responseJson(res) }; + if (out.status < 300) await expect(this.page.locator('#record-dialog')).toBeHidden(); + await this.settle(); + return out; + } + + async addRecord(input: RecordInput, opts: { expectStatus?: number } = {}): Promise { + await this.page.click('#record-add'); + await expect(this.page.locator('#record-dialog')).toBeVisible(); + await this.fillRecordForm(input, false); + const out = await this.submitRecord('POST'); + if (opts.expectStatus !== undefined) expect(out.status, `add ${JSON.stringify(input)}: ${JSON.stringify(out.json)}`).toBe(opts.expectStatus); + return out; + } + + async openEdit(m: RowMatch): Promise { + const row = await this.row(m); + await row.getByRole('button', { name: /^Edit / }).click(); + await expect(this.page.locator('#record-dialog')).toBeVisible(); + } + + async editRecord(m: RowMatch, input: RecordInput, opts: { expectStatus?: number } = {}): Promise { + await this.openEdit(m); + await this.fillRecordForm(input, true); + const out = await this.submitRecord('PUT'); + if (opts.expectStatus !== undefined) expect(out.status, `edit ${JSON.stringify(m)}: ${JSON.stringify(out.json)}`).toBe(opts.expectStatus); + return out; + } + + async confirm(button: string): Promise { + const dialog = this.page.locator('dialog[open]').filter({ has: this.page.getByRole('button', { name: button, exact: true }) }); + await expect(dialog).toBeVisible(); + await dialog.getByRole('button', { name: button, exact: true }).click(); + } + + async deleteRecord(m: RowMatch, opts: { expectStatus?: number } = {}): Promise { + const row = await this.row(m); + await row.getByRole('button', { name: /^Delete / }).click(); + const done = this.page.waitForResponse((r) => /\/records\/\d+$/.test(new URL(r.url()).pathname) && r.request().method() === 'DELETE'); + await this.confirm('Delete'); + const res = await done; + await this.settle(); + const out = { status: res.status(), json: await responseJson(res) }; + if (opts.expectStatus !== undefined) expect(out.status, `delete ${JSON.stringify(m)}`).toBe(opts.expectStatus); + return out; + } + + async select(m: RowMatch): Promise { + const row = await this.row(m); + await row.locator('input[type=checkbox]').check(); + } + + async bulkDelete(matches: RowMatch[], opts: { expectStatus?: number } = {}): Promise { + for (const m of matches) await this.select(m); + await expect(this.page.locator('#bulk-delete')).toHaveText(`Delete selected (${matches.length})`); + await this.page.click('#bulk-delete'); + const done = this.page.waitForResponse((r) => /\/records\/delete$/.test(new URL(r.url()).pathname) && r.request().method() === 'POST'); + await this.confirm('Delete'); + const res = await done; + await this.settle(); + const out = { status: res.status(), json: await responseJson(res) }; + if (opts.expectStatus !== undefined) expect(out.status, 'bulk delete').toBe(opts.expectStatus); + return out; + } + + async editSoa(values: Partial>, opts: { expectStatus?: number } = {}): Promise { + await this.page.click('#soa-edit'); + await expect(this.page.locator('#soa-dialog')).toBeVisible(); + for (const [k, v] of Object.entries(values)) await this.page.fill(`#soa-${k}`, v as string); + const done = this.page.waitForResponse((r) => /\/soa$/.test(new URL(r.url()).pathname) && r.request().method() === 'PUT'); + await this.page.locator('#soa-form button[type=submit]').click(); + const res = await done; + const out = { status: res.status(), json: await responseJson(res) }; + if (out.status < 300) await expect(this.page.locator('#soa-dialog')).toBeHidden(); + await this.settle(); + if (opts.expectStatus !== undefined) expect(out.status, `edit SOA: ${JSON.stringify(out.json)}`).toBe(opts.expectStatus); + return out; + } + + async soaSummary(): Promise> { + return this.page.$$eval('#soa-summary dt', (dts) => Object.fromEntries(dts.map((dt) => [(dt.textContent ?? '').trim(), (dt.nextElementSibling?.textContent ?? '').trim()]))); + } + + async fieldErrors(formSelector: string): Promise> { + return this.page.$$eval(`${formSelector} .field-error`, (els) => + Object.fromEntries( + els.map((el) => { + const control = el.previousElementSibling as HTMLInputElement | null; + return [control?.name ?? control?.id ?? '?', (el.textContent ?? '').trim()]; + }), + ), + ); + } + + private async submitAndWait(method: string, path: RegExp, click: () => Promise): Promise { + const done = this.page.waitForResponse((r) => path.test(new URL(r.url()).pathname) && r.request().method() === method); + await click(); + const res = await done; + const out = { status: res.status(), json: await responseJson(res) }; + await this.settle(); + return out; + } + + async createUserUi(username: string, role: 'admin' | 'user', password: string, repeat = password): Promise { + this.deps.secrets.register(password, `password of ${username}`); + if (new URL(this.page.url()).pathname !== '/users') await this.goto('/users'); + await this.page.click('#new-user'); + await expect(this.page.locator('#user-dialog')).toBeVisible(); + await this.page.fill('#nu-username', username); + await this.page.selectOption('#nu-role', role); + await this.page.fill('#nu-password', password); + await this.page.fill('#nu-repeat', repeat); + if (password !== repeat) { + await this.page.click('#user-form button[type=submit]'); + return { status: 0, json: undefined }; + } + const out = await this.submitAndWait('POST', /^\/api\/v1\/users$/, () => this.page.click('#user-form button[type=submit]')); + if (out.status === 201) await expect(this.page.locator('#user-dialog')).toBeHidden(); + return out; + } + + async usersTable(): Promise> { + return this.page.$$eval('#users-body tr', (trs) => + trs.map((tr) => { + const c = [...tr.children].map((x) => (x.textContent ?? '').trim()); + return { username: c[0], role: c[1], zones: c[2], created: c[3], lastLogin: c[4], state: c[5] }; + }), + ); + } + + async openUser(username: string): Promise { + await this.goto(`/users/${encodeURIComponent(username)}`); + await expect(this.page.locator('#user-status')).toHaveText(''); + } + + async setRoleUi(role: 'admin' | 'user'): Promise { + await this.page.selectOption('#user-role', role); + return this.submitAndWait('PUT', /^\/api\/v1\/users\/[^/]+\/role$/, () => this.page.click('#role-form button[type=submit]')); + } + + async setPasswordUi(password: string): Promise { + this.deps.secrets.register(password, 'password set by an admin'); + await this.page.fill('#up-password', password); + await this.page.fill('#up-repeat', password); + return this.submitAndWait('PUT', /^\/api\/v1\/users\/[^/]+\/password$/, () => this.page.click('#password-form button[type=submit]')); + } + + async delegateFromUserPage(zone: string): Promise { + await this.page.selectOption('#user-zone-pick', zone); + return this.submitAndWait('PUT', /^\/api\/v1\/zones\/[^/]+\/users\/[^/]+$/, () => this.page.click('#zone-add-form button[type=submit]')); + } + + async revokeFromUserPage(zone: string): Promise { + await this.page.getByRole('button', { name: `Remove zone ${zone}`, exact: true }).click(); + return this.submitAndWait('DELETE', /^\/api\/v1\/zones\/[^/]+\/users\/[^/]+$/, () => this.confirm('Remove')); + } + + async userZones(): Promise { + return this.page.$$eval('#user-zones li, #user-zones-readonly li', (lis) => lis.map((li) => (li.textContent ?? '').replace(/\s+Remove$/, '').trim())); + } + + async deleteUserUi(username: string, typed = username): Promise { + await this.page.fill('#user-delete-confirm', typed); + if (await this.page.locator('#user-delete').isDisabled()) return null; + const out = await this.submitAndWait('DELETE', /^\/api\/v1\/users\/[^/]+$/, () => this.page.click('#user-delete')); + if (out.status === 204) await expect(this.page).toHaveURL(/\/users$/); + await this.settle(); + return out; + } + + async zoneUsers(): Promise { + return this.page.$$eval('#zone-users li .mono', (els) => els.map((e) => (e.textContent ?? '').trim())); + } + + async delegateFromZonePage(username: string): Promise { + await this.page.selectOption('#zone-user-pick', username); + return this.submitAndWait('PUT', /^\/api\/v1\/zones\/[^/]+\/users\/[^/]+$/, () => this.page.click('#zone-user-add')); + } + + async revokeFromZonePage(username: string): Promise { + await this.page.getByRole('button', { name: `Remove ${username} from this zone`, exact: true }).click(); + return this.submitAndWait('DELETE', /^\/api\/v1\/zones\/[^/]+\/users\/[^/]+$/, () => this.confirm('Remove')); + } + + async deleteZoneUi(typed: string): Promise { + await this.page.fill('#zone-delete-confirm', typed); + if (await this.page.locator('#zone-delete').isDisabled()) return null; + const out = await this.submitAndWait('DELETE', /^\/api\/v1\/zones\/[^/]+$/, () => this.page.click('#zone-delete')); + if (out.status === 204) await expect(this.page).toHaveURL(/\/$/); + await this.settle(); + return out; + } + + async changeOwnPasswordUi(current: string, password: string, repeat = password): Promise { + this.deps.secrets.register(password, `new password of ${this.user}`); + if (new URL(this.page.url()).pathname !== '/account') await this.goto('/account'); + await this.page.fill('#pw-current', current); + await this.page.fill('#pw-new', password); + await this.page.fill('#pw-repeat', repeat); + if (password !== repeat) { + await this.page.click('#password-form button[type=submit]'); + return null; + } + return this.submitAndWait('PUT', /^\/api\/v1\/account\/password$/, () => this.page.click('#password-form button[type=submit]')); + } + + async zonesTable(): Promise> { + await expect(this.page.locator('#zones-status')).not.toHaveText('Loading zones...'); + await expect(this.page.locator('#zones-body td').filter({ hasText: 'loading...' })).toHaveCount(0); + return this.page.$$eval('#zones-body tr', (trs) => + trs.map((tr) => { + const c = [...tr.children].map((x) => (x.textContent ?? '').replace(/\s+/g, ' ').trim()); + return { zone: c[0], records: c[1], serial: c[2], problems: c[3] }; + }), + ); + } + + async problems(): Promise> { + return this.page.$$eval('#problems-list li', (lis) => + lis.map((li) => ({ + severity: (li.querySelector('.badge')?.textContent ?? '').trim(), + code: (li.querySelector('code')?.textContent ?? '').trim(), + where: (li.querySelector('.muted')?.textContent ?? '').trim(), + })), + ); + } + + async auditRows(): Promise> { + await expect(this.page.locator('#audit-status')).not.toHaveText('Loading...'); + return this.page.$$eval('#audit-body tr:not(.detail-row)', (trs) => + trs.map((tr) => { + const c = [...tr.children].map((x) => (x.textContent ?? '').replace(/\s+/g, ' ').trim()); + return { time: c[0], actor: c[1], origin: c[2], operation: c[3], status: c[4], target: c[5] }; + }), + ); + } + + async filterAudit(filters: Partial>): Promise { + if (new URL(this.page.url()).pathname !== '/audit') await this.goto('/audit'); + if (filters.zone !== undefined) await this.page.fill('#af-zone', filters.zone); + if (filters.actor !== undefined) await this.page.fill('#af-actor', filters.actor); + if (filters.operation !== undefined) await this.page.selectOption('#af-operation', filters.operation); + if (filters.kind !== undefined) await this.page.selectOption('#af-kind', filters.kind); + if (filters.outcome !== undefined) await this.page.selectOption('#af-outcome', filters.outcome); + await this.submitAndWait('GET', /^\/api\/v1\/audit$/, () => this.page.click('#audit-filters button[type=submit]')); + } + + async importPreview(zone: string, content: string, mode: 'merge' | 'replace'): Promise { + await this.goto(`/zones/${encodeURIComponent(zone)}/import`); + await this.page.check(`input[name=mode][value=${mode}]`); + await this.page.fill('#import-content', content); + return this.submitAndWait('POST', /\/import\/preview$/, () => this.page.click('#import-preview')); + } + + async importSummary(): Promise { + return ((await this.page.locator('#import-summary').textContent()) ?? '').replace(/\s+/g, ' ').trim(); + } + + async importApply(): Promise { + await expect(this.page.locator('#import-apply')).toBeVisible(); + const path = /\/import\/apply$/; + let result: UiResponse | undefined; + await this.page.route(path, async (route) => { + const response = await route.fetch(); + result = { status: response.status(), json: await response.json() }; + await route.fulfill({ response }); + }, { times: 1 }); + await this.submitAndWait('POST', path, () => this.page.click('#import-apply')); + if (!result) throw new Error('no import apply response'); + return result; + } + + async exportZone(zone: string): Promise { + if (!new URL(this.page.url()).pathname.startsWith(`/zones/`)) await this.openZone(zone); + const download = this.page.waitForEvent('download'); + await this.page.click('#export-link'); + const d = await download; + const file = await d.path(); + this.deps.ledger?.api({ + method: 'GET', path: new URL(d.url()).pathname, status: 200, actor: this.user, + origin: runnerAddress(), body: '', sessionValid: this.user !== '', crossOrigin: false, + source: 'browser zone export download', + }); + await this.settle(); + const fs = await import('node:fs'); + return fs.readFileSync(file, 'utf8'); + } + + async close(): Promise { + await this.deps.ledger?.settle(); + await this.context.close(); + } +} diff --git a/e2e/harness/verify.ts b/e2e/harness/verify.ts new file mode 100644 index 0000000..d881a1c --- /dev/null +++ b/e2e/harness/verify.ts @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { expect } from '@playwright/test'; +import { waitForZone } from './dig'; +import type { World } from './fixtures'; +import type { AuditRow, RecordRow } from './mysql'; +import { canonicalContent, expectCanonicalContent, expectSerialBump, fqdnOf, uiTtl, uiValue, type RecordData, type RecordType } from './records'; +import { expectServed, neverFails } from './served'; +import type { Ui } from './ui'; + +export interface Rec { + name: string; + type: RecordType; + ttl: number; + data: RecordData; +} + +export interface Change { + serialBefore: number; + t0: Date; + rows: RecordRow[]; +} + +export async function begin(w: World, zone: string): Promise { + const serial = await w.db.soaSerial(zone); + expect(serial, `managed serial of ${zone}`).not.toBeNull(); + return { serialBefore: serial as number, t0: new Date(), rows: await w.db.records(zone) }; +} + +export function rowsOf(rows: RecordRow[], rec: Pick): RecordRow[] { + return rows.filter((r) => r.name === rec.name && r.record_type === rec.type); +} + +export async function storedRow(w: World, zone: string, rec: Rec): Promise { + const rows = await w.db.records(zone); + const expected = canonicalContent(rec.type, rec.data); + const matching = rows.filter((r) => r.zone === zone && r.name === rec.name && r.record_type === rec.type && r.content !== null && normalizeJson(r.content) === expected); + expect(matching, `exactly one row ${zone} ${rec.name || '@'} ${rec.type} ${expected} in ${JSON.stringify(rowsOf(rows, rec))}`).toHaveLength(1); + const row = matching[0]; + expect(row.zone, 'zone column').toBe(zone); + expect(row.name, 'name column').toBe(rec.name); + expect(row.record_type, 'record_type column').toBe(rec.type); + expect(row.ttl, 'ttl column').toBe(rec.ttl); + expectCanonicalContent(row.content, rec.type, rec.data, `content of ${rec.name || '@'} ${rec.type}`); + return row; +} + +export function normalizeJson(raw: string): string { + try { + return JSON.stringify(JSON.parse(raw)); + } catch { + return raw; + } +} + +export async function expectNoRow(w: World, zone: string, rec: Rec): Promise { + const rows = await w.db.records(zone); + const expected = canonicalContent(rec.type, rec.data); + expect( + rows.filter((r) => r.name === rec.name && r.record_type === rec.type && r.content !== null && normalizeJson(r.content) === expected), + `no row ${rec.name || '@'} ${rec.type} ${expected}`, + ).toHaveLength(0); +} + +export async function expectBumped(w: World, zone: string, change: Change, what: string): Promise { + const serial = await w.db.soaSerial(zone); + expect(serial, `${what}: serial`).not.toBeNull(); + expectSerialBump(change.serialBefore, serial as number, change.t0, new Date(), `${what}: SOA serial bumped exactly once`); + return serial as number; +} + +export async function expectUnchangedSerial(w: World, zone: string, serial: number, what: string): Promise { + expect(await w.db.soaSerial(zone), `${what}: serial unchanged`).toBe(serial); +} + +export async function served(w: World, zone: string, qname: string, qtype: string, label?: string): Promise { + const rows = await w.db.records(zone); + const serial = await w.db.soaSerial(zone); + const r = await expectServed(w.g, rows, qname, qtype, { recorder: w.recorder, serial, label }); + neverFails(r, label ?? `${qname} ${qtype}`); +} + +export async function servedZone(w: World, zone: string): Promise { + const rows = await w.db.records(zone); + const seen = new Set(); + await served(w, zone, zone, 'SOA'); + for (const r of rows) { + const key = `${r.name}\u0000${r.record_type}`; + if (seen.has(key)) continue; + seen.add(key); + const name = fqdnOf(r.name.replace(/^\*$/, 'wild-e2e').replace(/^\*\./, 'wild-e2e.'), zone); + await served(w, zone, name, r.record_type, `${r.name || '@'} ${r.record_type}`); + } +} + +export async function threeWay(w: World, ui: Ui | null, zone: string, rec: Rec, change: Change | null, what: string): Promise { + const row = await storedRow(w, zone, rec); + let serial = await w.db.soaSerial(zone); + if (change) serial = await expectBumped(w, zone, change, what); + const qname = fqdnOf(rec.name.replace(/^\*$/, `wild${row.id}`).replace(/^\*\./, `wild${row.id}.`), zone); + await served(w, zone, qname, rec.type, `${what}: dig ${qname} ${rec.type}`); + await served(w, zone, zone, 'SOA', `${what}: dig ${zone} SOA`); + expect(serial).not.toBeNull(); + if (ui) await ui.expectRow({ name: rec.name === '' ? '@' : rec.name, type: rec.type, value: uiValue(rec.type, rec.data), ttl: uiTtl(rec.ttl) }); + return row; +} + +export async function threeWayGone(w: World, ui: Ui | null, zone: string, rec: Rec, change: Change | null, what: string): Promise { + await expectNoRow(w, zone, rec); + if (change) await expectBumped(w, zone, change, what); + const qname = fqdnOf(rec.name.replace(/^\*$/, 'gone-wild').replace(/^\*\./, 'gone-wild.'), zone); + await served(w, zone, qname, rec.type, `${what}: dig ${qname} ${rec.type}`); + if (ui) await ui.expectNoRow({ name: rec.name === '' ? '@' : rec.name, type: rec.type, value: uiValue(rec.type, rec.data) }); +} + +export async function zoneServed(w: World, zone: string): Promise { + await waitForZone(w.g, zone, { recorder: w.recorder }); +} + +export function recordJson(row: RecordRow): Record { + return { id: row.id, zone: row.zone, name: row.name, ttl: row.ttl, record_type: row.record_type, content: row.content }; +} + +function contentEquals(actual: unknown, raw: string | null): boolean { + if (raw === null) return actual === null; + if (typeof actual === 'string') return normalizeJson(actual) === normalizeJson(raw); + try { + return JSON.stringify(actual) === JSON.stringify(JSON.parse(raw)); + } catch { + return false; + } +} + +export function expectAuditRecord(value: unknown, row: RecordRow, what: string): void { + expect(value, `${what}: audit value is a record object`).toBeTruthy(); + const v = value as Record; + expect({ id: v.id, zone: v.zone, name: v.name, ttl: v.ttl, record_type: v.record_type }, `${what}: audit record fields`).toEqual({ + id: row.id, + zone: row.zone, + name: row.name, + ttl: row.ttl, + record_type: row.record_type, + }); + expect(contentEquals(v.content, row.content), `${what}: audit record content ${JSON.stringify(v.content)} equals ${row.content}`).toBe(true); + expect(Object.keys(v).sort(), `${what}: audit record keys`).toEqual(['content', 'id', 'name', 'record_type', 'ttl', 'zone']); +} + +export async function expectAuditChange(w: World, zone: string, audit: AuditRow, change: Change, what: string): Promise { + const after = await w.db.records(zone); + const check = (value: unknown, from: RecordRow[], to: RecordRow[], side: string) => { + const byId = new Map(to.map((row) => [row.id, JSON.stringify(row)])); + const changed = from.filter((row) => byId.get(row.id) !== JSON.stringify(row)); + const stored = asArray(parsedJson(value)); + expect(stored, `${what}: audit ${side} lists exactly the changed records`).toHaveLength(changed.length); + for (const row of changed) { + expectAuditRecord(stored.find((entry) => (entry as { id: number }).id === row.id), row, `${what}: ${side} row ${row.id}`); + } + }; + check(audit.before_value, change.rows, after, 'before'); + check(audit.after_value, after, change.rows, 'after'); +} + +export function asArray(value: unknown): unknown[] { + if (value === null || value === undefined) return []; + return Array.isArray(value) ? value : [value]; +} + +export function findAudit(rows: AuditRow[], operation: string, status?: number): AuditRow { + const found = rows.filter((r) => r.operation === operation && (status === undefined || r.status === status)); + expect(found, `exactly one ${operation}${status ? ` ${status}` : ''} audit row among ${rows.map((r) => `${r.operation}:${r.status}`).join(', ')}`).toHaveLength(1); + return found[0]; +} + +export function parsedJson(v: unknown): unknown { + if (typeof v === 'string') { + try { + return JSON.parse(v); + } catch { + return v; + } + } + return v; +} diff --git a/e2e/package-lock.json b/e2e/package-lock.json new file mode 100644 index 0000000..da46935 --- /dev/null +++ b/e2e/package-lock.json @@ -0,0 +1,269 @@ +{ + "name": "coredns-web-ui-e2e", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "coredns-web-ui-e2e", + "version": "0.0.0", + "license": "GPL-2.0-or-later", + "devDependencies": { + "@axe-core/playwright": "4.14.0", + "@playwright/test": "1.56.1", + "@types/node": "22.20.5", + "mysql2": "3.24.6", + "playwright-core": "1.56.1", + "typescript": "5.9.3" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/@axe-core/playwright": { + "version": "4.14.0", + "resolved": "https://registry.npmjs.org/@axe-core/playwright/-/playwright-4.14.0.tgz", + "integrity": "sha512-SGUhG5PIHd2eMdpgBF2PyQLOhX+qyDR2PT4cmoS4Qk2ak+jX/rrSvst9l0PGv5WTHolKpUMvVmoHpr4cZgf1RQ==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "axe-core": "~4.14.0" + }, + "engines": { + "node": ">=22.12.0" + }, + "peerDependencies": { + "playwright-core": ">= 1.0.0" + } + }, + "node_modules/@playwright/test": { + "version": "1.56.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.56.1.tgz", + "integrity": "sha512-vSMYtL/zOcFpvJCW71Q/OEGQb7KYBPAdKh35WNSkaZA75JlAO8ED8UN6GUNTm3drWomcbcqRPFqQbLae8yBTdg==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright": "1.56.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@types/node": { + "version": "22.20.5", + "resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz", + "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/aws-ssl-profiles": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz", + "integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/axe-core": { + "version": "4.14.1", + "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.14.1.tgz", + "integrity": "sha512-FHfa+lmNjQZfJz1q8wKqIDwC6DExcHt/pkjNQb09a3NPjCKg2rhu5qb2S4r76ASyFNNtuFooJpZe37OgudVGtQ==", + "dev": true, + "license": "MPL-2.0", + "engines": { + "node": ">=4" + } + }, + "node_modules/fsevents": { + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz", + "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/generate-function": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", + "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-property": "^1.0.2" + } + }, + "node_modules/iconv-lite": { + "version": "0.7.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", + "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/is-property": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==", + "dev": true, + "license": "MIT" + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", + "dev": true, + "license": "Apache-2.0" + }, + "node_modules/lru.min": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.5.tgz", + "integrity": "sha512-5J9ysMYUpYIg9RF2vJpy9SinEmSviFSe0GyPpCQ4L5QSkLAgeLXlTAOu2ZwWUU5m+0SBl6gUU1R1ZQB3aKypfA==", + "dev": true, + "license": "MIT", + "engines": { + "bun": ">=1.0.0", + "deno": ">=1.30.0", + "node": ">=8.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wellwelwel" + } + }, + "node_modules/mysql2": { + "version": "3.24.6", + "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.24.6.tgz", + "integrity": "sha512-enu73KhbAua2L3dIxjc6qg6ZJ7H3pt1BImZASWNWY5xSsmJ1ZuUPULTDGXgmJbI61vb+nJAG19IZclIq19UidQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "aws-ssl-profiles": "^1.1.2", + "generate-function": "^2.3.1", + "iconv-lite": "^0.7.3", + "long": "^5.3.2", + "lru.min": "^1.1.4", + "named-placeholders": "^1.1.6", + "sql-escaper": "^1.5.1" + }, + "engines": { + "node": ">= 8.0" + }, + "peerDependencies": { + "@types/node": ">= 8" + } + }, + "node_modules/named-placeholders": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz", + "integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==", + "dev": true, + "license": "MIT", + "dependencies": { + "lru.min": "^1.1.0" + }, + "engines": { + "node": ">=8.0.0" + } + }, + "node_modules/playwright": { + "version": "1.56.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.56.1.tgz", + "integrity": "sha512-aFi5B0WovBHTEvpM3DzXTUaeN6eN0qWnTkKx4NQaH4Wvcmc153PdaY2UBdSYKaGYw+UyWXSVyxDUg5DoPEttjw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.56.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=18" + }, + "optionalDependencies": { + "fsevents": "2.3.2" + } + }, + "node_modules/playwright-core": { + "version": "1.56.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.56.1.tgz", + "integrity": "sha512-hutraynyn31F+Bifme+Ps9Vq59hKuUCz7H1kDOcBs+2oGguKkWTU50bBWrtz34OUWmIwpBTWDxaRPXrIXkgvmQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", + "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", + "dev": true, + "license": "MIT" + }, + "node_modules/sql-escaper": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.9.1.tgz", + "integrity": "sha512-4p522TVYaJXTbMlYgAwacjyg3EJyYe9KYWYlYJVwZG1YjtzxU5m5iSzsZoGI69Po7j3i/2tKlpZQi7uvhTL+WA==", + "dev": true, + "license": "MIT", + "engines": { + "bun": ">=1.0.0", + "deno": ">=2.0.0", + "node": ">=12.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/mysqljs/sql-escaper?sponsor=1" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/e2e/package.json b/e2e/package.json new file mode 100644 index 0000000..6966507 --- /dev/null +++ b/e2e/package.json @@ -0,0 +1,22 @@ +{ + "name": "coredns-web-ui-e2e", + "private": true, + "version": "0.0.0", + "description": "Playwright end-to-end suite for coredns-web-ui", + "license": "GPL-2.0-or-later", + "scripts": { + "test": "playwright test", + "typecheck": "tsc --noEmit" + }, + "engines": { + "node": ">=22" + }, + "devDependencies": { + "@axe-core/playwright": "4.14.0", + "@playwright/test": "1.56.1", + "@types/node": "22.20.5", + "mysql2": "3.24.6", + "playwright-core": "1.56.1", + "typescript": "5.9.3" + } +} diff --git a/e2e/playwright.config.ts b/e2e/playwright.config.ts new file mode 100644 index 0000000..46bf3ea --- /dev/null +++ b/e2e/playwright.config.ts @@ -0,0 +1,35 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { defineConfig, devices } from '@playwright/test'; + +export default defineConfig({ + testDir: './tests', + globalSetup: './harness/global-setup.ts', + globalTeardown: './harness/global-teardown.ts', + fullyParallel: false, + workers: Number(process.env.E2E_WORKERS || 4), + retries: 0, + forbidOnly: true, + timeout: 180_000, + expect: { timeout: 15_000 }, + reportSlowTests: null, + outputDir: './test-results', + reporter: [ + ['./harness/reporter.ts'], + ['list'], + ['json', { outputFile: './reports/results.json' }], + ['junit', { outputFile: './reports/junit.xml' }], + ['html', { open: 'never', outputFolder: './reports/html' }], + ], + use: { + ...devices['Desktop Chrome'], + viewport: { width: 1440, height: 900 }, + trace: 'off', + screenshot: 'only-on-failure', + video: 'off', + actionTimeout: 20_000, + navigationTimeout: 30_000, + }, + projects: [{ name: 'chromium' }], +}); diff --git a/e2e/stack/mysql-init.sql b/e2e/stack/mysql-init.sql new file mode 100644 index 0000000..6dd9cb8 --- /dev/null +++ b/e2e/stack/mysql-init.sql @@ -0,0 +1,25 @@ +-- SPDX-License-Identifier: GPL-2.0-or-later +-- Copyright (C) 2026 Bryan Joshua Pedini + +CREATE DATABASE `{{DATABASE}}` DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci; + +CREATE TABLE `{{DATABASE}}`.`{{PREFIX}}records` ( + `id` INT NOT NULL AUTO_INCREMENT, + `zone` VARCHAR(255) NOT NULL, + `name` VARCHAR(255) NOT NULL, + `ttl` INT DEFAULT NULL, + `content` TEXT, + `record_type` VARCHAR(255) NOT NULL, + PRIMARY KEY (`id`) +) ENGINE = INNODB DEFAULT CHARSET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci; + +CREATE USER '{{DNS_USER}}'@'%' IDENTIFIED BY '{{DNS_PASSWORD}}'; +GRANT SELECT ON `{{DATABASE}}`.`{{PREFIX}}records` TO '{{DNS_USER}}'@'%'; + +CREATE USER '{{APP_USER}}'@'%' IDENTIFIED BY '{{APP_PASSWORD}}'; +GRANT SELECT, INSERT, UPDATE, DELETE ON `{{DATABASE}}`.`{{PREFIX}}records` TO '{{APP_USER}}'@'%'; +GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `{{DATABASE}}`.`{{PREFIX}}webui_schema` TO '{{APP_USER}}'@'%'; +GRANT SELECT, INSERT, UPDATE, CREATE, ALTER, INDEX, REFERENCES ON `{{DATABASE}}`.`{{PREFIX}}webui_users` TO '{{APP_USER}}'@'%'; +GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, REFERENCES ON `{{DATABASE}}`.`{{PREFIX}}webui_sessions` TO '{{APP_USER}}'@'%'; +GRANT SELECT, INSERT, DELETE, CREATE, ALTER, INDEX, REFERENCES ON `{{DATABASE}}`.`{{PREFIX}}webui_zone_delegations` TO '{{APP_USER}}'@'%'; +GRANT SELECT, INSERT, CREATE, ALTER, INDEX, REFERENCES ON `{{DATABASE}}`.`{{PREFIX}}webui_audit` TO '{{APP_USER}}'@'%'; diff --git a/e2e/stack/origin2.mjs b/e2e/stack/origin2.mjs new file mode 100644 index 0000000..4c91683 --- /dev/null +++ b/e2e/stack/origin2.mjs @@ -0,0 +1,83 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import http from 'node:http'; + +const port = Number(process.env.ORIGIN2_PORT || 8081); +const hits = []; + +const attackScript = ` +const params = new URLSearchParams(location.search); +const target = params.get('target'); +const results = {}; +async function probe(name, url, init) { + try { + const res = await fetch(url, init); + results[name] = { type: res.type, status: res.status }; + } catch (err) { + results[name] = { error: String(err && err.message ? err.message : err) }; + } +} +async function main() { + await probe('create_zone_simple', target + '/api/v1/zones', { method: 'POST', mode: 'no-cors', credentials: 'include', headers: { 'Content-Type': 'text/plain' }, body: JSON.stringify({ name: params.get('zone'), ns: 'ns1.' + params.get('zone'), mbox: 'hostmaster@' + params.get('zone'), extra_ns: [], refresh: 3600, retry: 600, expire: 604800, minttl: 300, ttl: 3600 }) }); + await probe('create_zone_cors', target + '/api/v1/zones', { method: 'POST', mode: 'cors', credentials: 'include', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: params.get('zone') }) }); + await probe('read_zones', target + '/api/v1/zones', { method: 'GET', mode: 'cors', credentials: 'include' }); + await probe('delete_user', target + '/api/v1/users/' + encodeURIComponent(params.get('victim') || 'nobody'), { method: 'DELETE', mode: 'no-cors', credentials: 'include', headers: { 'Content-Type': 'text/plain' }, body: JSON.stringify({ confirm: params.get('victim') }) }); + document.getElementById('results').textContent = JSON.stringify(results); + document.body.dataset.done = '1'; + if (params.get('form') === 'logout') document.getElementById('logout').submit(); +} +main(); +`; + +function attackPage(query) { + const target = new URLSearchParams(query).get('target') || ''; + const safeTarget = /^http:\/\/[a-z0-9-]+:[0-9]+$/.test(target) ? target : 'http://invalid.invalid'; + return ` + +Second origin + +

Second origin

+

+
+
+ +
+ + +`; +} + +const server = http.createServer((req, res) => { + const url = new URL(req.url, `http://${req.headers.host || 'origin2'}`); + hits.push({ method: req.method, path: url.pathname, at: new Date().toISOString() }); + if (hits.length > 500) hits.shift(); + if (url.pathname === '/health') { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end('{"status":"ok"}'); + return; + } + if (url.pathname === '/attack.js') { + res.writeHead(200, { 'Content-Type': 'text/javascript; charset=utf-8', 'Cache-Control': 'no-store' }); + res.end(attackScript); + return; + } + if (url.pathname === '/attack.html') { + res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' }); + res.end(attackPage(url.search)); + return; + } + if (url.pathname === '/hits') { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify(hits)); + return; + } + res.writeHead(404, { 'Content-Type': 'text/plain' }); + res.end('not found'); +}); + +server.listen(port, '0.0.0.0'); + +for (const signal of ['SIGINT', 'SIGTERM']) { + process.on(signal, () => server.close(() => process.exit(0))); +} diff --git a/e2e/tests/accessibility.spec.ts b/e2e/tests/accessibility.spec.ts new file mode 100644 index 0000000..46a9915 --- /dev/null +++ b/e2e/tests/accessibility.spec.ts @@ -0,0 +1,49 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import path from 'node:path'; +import AxeBuilder from '@axe-core/playwright'; +import { test, expect } from '../harness/fixtures'; +import { SCREENSHOTS_DIR } from '../harness/env'; +import { up } from '../harness/api'; +import { addAddress, createZone } from '../harness/personas'; + +test.use({ group: 'a11y' }); + +test('all HTML pages meet axe severity limits in both themes and viewport sizes', async ({ world }) => { + test.setTimeout(240_000); + const admin = await world.bootstrapAdmin(); + const api = await world.apiAs(admin); + const user = await world.createUser(api, 'user'); + const zonePath = await createZone(api, world.zoneName()); + await addAddress(api, zonePath, 'www', '192.0.2.15'); + const userPath = up(user.username); + const adminPages = [ + ['zones', '/'], ['zone', zonePath], ['import', `${zonePath}/import`], + ['audit', '/audit'], ['account', '/account'], ['users', '/users'], ['user', userPath], + ]; + for (const colorScheme of ['light', 'dark'] as const) { + for (const width of [360, 1440]) { + const opts = { colorScheme, viewport: { width, height: 900 } }; + const assess = async (ui: Awaited>, name: string, target: string, status = 200) => { + expect((await ui.goto(target))?.status(), target).toBe(status); + await expect(ui.page.getByRole('heading', { level: 1 })).toBeVisible(); + const { violations } = await new AxeBuilder({ page: ui.page }).analyze(); + const severe = violations.filter(({ impact }) => impact === 'serious' || impact === 'critical'); + await ui.page.screenshot({ path: path.join(SCREENSHOTS_DIR, `${name}-${width}-${colorScheme}.png`), fullPage: true }); + expect.soft(severe.map(({ id, nodes }) => ({ id, targets: nodes.map((n) => n.target) })), `${name} at ${width}px in ${colorScheme}`).toEqual([]); + }; + const anon = await world.ui(opts); + await assess(anon, 'login', '/login'); + await assess(anon, 'version', '/version'); + await anon.close(); + const adminUi = await world.uiAs(admin, opts); + for (const [name, target] of adminPages) await assess(adminUi, name, target); + await adminUi.close(); + const userUi = await world.uiAs(user, opts); + await assess(userUi, 'forbidden', '/users', 403); + await assess(userUi, 'not-found', zonePath, 404); + await userUi.close(); + } + } +}); diff --git a/e2e/tests/core.spec.ts b/e2e/tests/core.spec.ts new file mode 100644 index 0000000..829d5b2 --- /dev/null +++ b/e2e/tests/core.spec.ts @@ -0,0 +1,997 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +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 { runnerAddress, SESSION_COOKIE } from '../harness/env'; +import { bulkDeleteBody, expectCheckErrorRowsCarryRaw, expectZoneCreateWarnings, importApplyBody, REVIEW_FIXES, UNKNOWN_API_OPERATION, ZONE_CREATE_DELEGATIONS_IN } from '../harness/decisions'; +import { READ_OPERATIONS } from '../harness/ledger'; +import type { AuditRow, RecordRow } from '../harness/mysql'; +import { newZoneSerial, uiValue, utcDay } from '../harness/records'; +import type { RecordInput, Ui } from '../harness/ui'; +import { expectServed } from '../harness/served'; +import { + asArray, + begin, + expectAuditChange, + expectAuditRecord, + expectBumped, + expectNoRow, + findAudit, + parsedJson, + served, + servedZone, + storedRow, + threeWay, + threeWayGone, + type Rec, +} from '../harness/verify'; + +test.use({ group: 'core' }); +test.describe.configure({ mode: 'serial' }); + +let admin: Account; +let adminUi: Ui; +let adminApi: ApiClient; +let zone = ''; +let zoneB = ''; +let zoneC = ''; +let user1: Account; +let user2: Account; +let admin2: Account; + +async function auditSince(w: { db: { auditSince(id: number): Promise } }, mark: number): Promise { + return w.db.auditSince(mark); +} + +function input(rec: Rec, fields: Record, opts: { name?: string; ttl?: string | null } = {}): RecordInput { + return { name: opts.name ?? (rec.name === '' ? '@' : rec.name), type: rec.type, ttl: opts.ttl === null ? undefined : (opts.ttl ?? String(rec.ttl)), fields }; +} + +test.describe('core flow', () => { + test('1. the stack is up and /health answers', async ({ world }) => { + const health = await fetch(`${world.g.baseURL}/health`); + expect(health.status).toBe(200); + expect(await health.json()).toEqual({ status: 'ok' }); + const anon = await world.api(); + const home = await anon.page('/'); + expect([302, 303]).toContain(home.status); + expect(home.headers.location).toBe('/login?next=%2F'); + const api = await anon.get('/zones'); + expect(api.status).toBe(401); + expect(api.json).toEqual({ error: expect.any(String) }); + expect(await world.db.recordCount()).toBe(0); + expect(await world.db.users()).toEqual([]); + }); + + test('2. the login page shows the bootstrap command, the first admin is created through the CLI and logs in', async ({ world }) => { + adminUi = await world.ui({ keep: true }); + await adminUi.goto('/login'); + await expect(adminUi.page.getByText('No administrator exists yet')).toBeVisible(); + await expect(adminUi.page.locator('.alert-info pre code')).toContainText('/app user add admin'); + const mark = await world.db.auditMaxId(); + admin = await world.bootstrapAdmin(world.unique('root-')); + const row = await world.db.user(admin.username); + expect(row).toMatchObject({ username: admin.username, role: 'admin', deleted_at: null, last_login_at: null }); + expect(row?.password_hash).toMatch(/^\$argon2id\$v=19\$m=65536,t=3,p=2\$/); + const audit = findAudit(await auditSince(world, mark), 'user_create'); + expect(audit).toMatchObject({ user_id: null, actor: 'cli', origin: 'local', status: null, error: null, zone: null, record_id: null, target_user_id: row?.id }); + expect(audit.before_value).toBeNull(); + const after = parsedJson(audit.after_value) as Record; + expect(Object.keys(after).sort()).toEqual(['created_at', 'deleted_at', 'id', 'role', 'username']); + expect(after).toMatchObject({ id: row?.id, username: admin.username, role: 'admin', deleted_at: null }); + expect(JSON.stringify(audit)).not.toContain('argon2'); + const duplicate = await world.cli.run(['user', 'add', admin.username, 'user'], `${world.password()}\n`); + expect(duplicate.code).toBe(1); + const usage = await world.cli.run(['user', 'add', 'x', 'superuser'], `${world.password()}\n`); + expect(usage.code).toBe(2); + expect(usage.stderr).toContain(USAGE_TEXT); + await adminUi.goto('/login'); + await expect(adminUi.page.getByText('No administrator exists yet')).toHaveCount(0); + await adminUi.login(admin.username, admin.password); + await expect(adminUi.page).toHaveURL(/\/$/); + await expect(adminUi.page.locator('.who-name')).toHaveText(admin.username); + await expect(adminUi.page.locator('nav.nav a', { hasText: 'Users' })).toBeVisible(); + const cookies = await adminUi.context.cookies(); + const session = cookies.find((c) => c.name === SESSION_COOKIE); + expect(session).toMatchObject({ httpOnly: true, sameSite: 'Strict', path: '/', secure: false }); + expect(session?.value).toMatch(/^[A-Za-z0-9_-]{43}$/); + const sessions = await world.db.sessions(row?.id); + expect(sessions).toHaveLength(1); + expect(sessions[0].origin).toBe(runnerAddress()); + expect((await world.db.user(admin.username))?.last_login_at).not.toBeNull(); + adminApi = await world.apiAs(admin, { keep: true }); + expect(await world.db.sessions(row?.id)).toHaveLength(2); + }); + + test('3. a zone created in the UI is stored, audited and served after the plugin reload', async ({ world }) => { + const base = world.unique('core-'); + zone = `${base}.core.test.`; + const typed = `${base.toUpperCase()}.Core.TEST`; + const t0 = new Date(); + const mark = await world.db.auditMaxId(); + const created = await adminUi.createZone({ name: typed, ns: `NS1.${base}.core.test`, mbox: `dns.admin@${base}.core.test`, extraNs: [`ns2.${zone}`], ttl: '3600' }, { expectStatus: 201 }); + expect(created.json).toMatchObject({ name: zone, records: 3 }); + expectZoneCreateWarnings(created.json); + await adminUi.expectToast(/next zone list reload/); + const rows = await world.db.records(zone); + expect(rows).toHaveLength(3); + const serial = (await world.db.soaSerial(zone)) as number; + expect([utcDay(t0), utcDay(new Date())]).toContain(serial); + await storedRow(world, zone, { + name: '', + type: 'SOA', + ttl: 3600, + data: { ns: `ns1.${zone}`, MBox: `dns\\.admin.${zone}`, refresh: 3600, retry: 600, expire: 604800, minttl: 300, serial }, + }); + await storedRow(world, zone, { name: '', type: 'NS', ttl: 3600, data: { host: `ns1.${zone}` } }); + await storedRow(world, zone, { name: '', type: 'NS', ttl: 3600, data: { host: `ns2.${zone}` } }); + const audit = findAudit(await auditSince(world, mark), 'zone_create', 201); + expect(audit.zone).toBe(zone); + expect(audit.before_value).toBeNull(); + const after = asArray(parsedJson(audit.after_value)); + expect(after).toHaveLength(3); + for (const r of rows) expectAuditRecord(after.find((a) => (a as { id: number }).id === r.id), r, 'zone_create after'); + const table = await adminUi.zonesTable(); + expect(table).toContainEqual(expect.objectContaining({ zone, records: '3', serial: String(serial) })); + await waitForZone(world.g, zone, { recorder: world.recorder }); + await served(world, zone, zone, 'SOA'); + await served(world, zone, zone, 'NS'); + await served(world, zone, `nothing-here.${zone}`, 'A'); + const dup = await adminApi.post('/zones', { name: zone, ns: `ns1.${zone}`, mbox: `hostmaster@${zone}`, extra_ns: [], refresh: 3600, retry: 600, expire: 604800, minttl: 300, ttl: 3600 }); + expect(dup.status).toBe(409); + expect(dup.json).toEqual({ error: expect.any(String) }); + }); + + test('4. records of all nine types are created, edited and deleted from the UI and verified three ways', async ({ world }) => { + test.setTimeout(600_000); + await adminUi.openZone(zone); + const long = 'long-text-' + 'abcdefghij'.repeat(30); + const R: Record = { + ns1: { name: 'ns1', type: 'A', ttl: 3600, data: { ip: '192.0.2.1' } }, + ns2: { name: 'ns2', type: 'A', ttl: 3600, data: { ip: '192.0.2.2' } }, + www1: { name: 'www', type: 'A', ttl: 300, data: { ip: '192.0.2.10' } }, + www2: { name: 'www', type: 'A', ttl: 300, data: { ip: '192.0.2.11' } }, + www6: { name: 'www', type: 'AAAA', ttl: 300, data: { ip: '2001:db8::10' } }, + web: { name: 'web', type: 'CNAME', ttl: 300, data: { host: `www.${zone}` } }, + alias: { name: 'alias', type: 'CNAME', ttl: 300, data: { host: `web.${zone}` } }, + mail: { name: 'mail', type: 'A', ttl: 3600, data: { ip: '192.0.2.25' } }, + mx: { name: '', type: 'MX', ttl: 3600, data: { host: `mail.${zone}`, preference: 10 } }, + nullmx: { name: 'nomail', type: 'MX', ttl: 3600, data: { host: '.', preference: 0 } }, + spf: { name: '', type: 'TXT', ttl: 3600, data: { text: 'v=spf1 -all' } }, + longtxt: { name: 'long', type: 'TXT', ttl: 3600, data: { text: long } }, + sip: { name: 'sip', type: 'A', ttl: 3600, data: { ip: '192.0.2.30' } }, + srv: { name: '_sip._tcp', type: 'SRV', ttl: 3600, data: { priority: 10, weight: 5, port: 5060, target: `sip.${zone}` } }, + nosrv: { name: '_none._tcp', type: 'SRV', ttl: 3600, data: { priority: 0, weight: 0, port: 0, target: '.' } }, + caa: { name: '', type: 'CAA', ttl: 3600, data: { flag: 0, tag: 'issue', value: 'ca.example.net' } }, + iodef: { name: '', type: 'CAA', ttl: 3600, data: { flag: 128, tag: 'iodef', value: 'mailto:security@example.net' } }, + sub: { name: 'sub', type: 'NS', ttl: 3600, data: { host: 'ns.example.net.' } }, + wild: { name: '*', type: 'A', ttl: 0, data: { ip: '192.0.2.99' } }, + wilddev: { name: '*.dev', type: 'TXT', ttl: 600, data: { text: 'wildcard dev' } }, + }; + const add = async (what: string, rec: Rec, inp: RecordInput, warnings: string[] = []) => { + const change = await begin(world, zone); + const mark = await world.db.auditMaxId(); + const res = await adminUi.addRecord(inp, { expectStatus: 201 }); + if (warnings.length > 0) await adminUi.expectToast(/^Warning: /); + expect(res.json.record).toMatchObject({ name: rec.name, type: rec.type, ttl: rec.ttl, data: rec.data, raw: null }); + expect(res.json.record.etag).toMatch(/^"[0-9a-f]{64}"$/); + const codes = (res.json.warnings as Array<{ code: string; severity?: string }>).map((x) => x.code); + expect(codes, `${what}: warnings`).toEqual(expect.arrayContaining(warnings)); + expect((res.json.warnings as Array<{ severity?: string }>).filter((x) => x.severity === 'error'), `${what}: no error is returned as a warning`).toEqual([]); + const row = await threeWay(world, adminUi, zone, rec, change, what); + const audit = findAudit(await auditSince(world, mark), 'record_create', 201); + expect(audit).toMatchObject({ zone, record_id: row.id, actor: admin.username, error: null }); + await expectAuditChange(world, zone, audit, change, what); + return row; + }; + const edit = async (what: string, from: Rec, to: Rec, inp: RecordInput) => { + const before = await storedRow(world, zone, from); + const change = await begin(world, zone); + const mark = await world.db.auditMaxId(); + const res = await adminUi.editRecord({ name: from.name === '' ? '@' : from.name, type: from.type, value: uiValue(from.type, from.data) }, inp, { expectStatus: 200 }); + expect(res.json.record).toMatchObject({ id: before.id, name: to.name, type: to.type, ttl: to.ttl, data: to.data }); + const row = await threeWay(world, adminUi, zone, to, change, what); + expect(row.id, `${what}: the row is updated in place`).toBe(before.id); + if (from.name !== to.name || JSON.stringify(from.data) !== JSON.stringify(to.data)) await expectNoRow(world, zone, from); + const audit = findAudit(await auditSince(world, mark), 'record_update', 200); + expect(audit).toMatchObject({ zone, record_id: before.id }); + await expectAuditChange(world, zone, audit, change, what); + return row; + }; + const del = async (what: string, rec: Rec) => { + const before = await storedRow(world, zone, rec); + const change = await begin(world, zone); + const mark = await world.db.auditMaxId(); + const deleted = await adminUi.deleteRecord({ name: rec.name === '' ? '@' : rec.name, type: rec.type, value: uiValue(rec.type, rec.data) }); + expect([200, 204]).toContain(deleted.status); + if (deleted.status === 200) expect(deleted.json).toMatchObject({ warnings: expect.any(Array) }); + await threeWayGone(world, adminUi, zone, rec, change, what); + expect(await world.db.recordById(before.id)).toBeUndefined(); + const audit = findAudit(await auditSince(world, mark), 'record_delete', deleted.status); + expect(audit).toMatchObject({ zone, record_id: before.id }); + await expectAuditChange(world, zone, audit, change, what); + }; + + await add('glue ns1 A', R.ns1, input(R.ns1, { ip: '192.0.2.1' })); + await add('glue ns2 A given as an absolute name', R.ns2, input(R.ns2, { ip: '192.0.2.2' }, { name: `NS2.${zone}` })); + await add('A', R.www1, input(R.www1, { ip: '192.0.2.10' })); + await add('second A prefilled with the TTL of its RRset', R.www2, input(R.www2, { ip: '192.0.2.11' }, { ttl: null })); + await add('AAAA in long form', R.www6, input(R.www6, { ip: '2001:DB8:0:0:0:0:0:10' })); + await add('CNAME with an uppercase target without dot', R.web, input(R.web, { host: `WWW.${zone.slice(0, -1)}` })); + await add('CNAME chain', R.alias, input(R.alias, { host: `web.${zone}` })); + await served(world, zone, `alias.${zone}`, 'A', 'CNAME chain alias -> web -> www answered with the chain'); + await served(world, zone, `alias.${zone}`, 'AAAA', 'CNAME chain for AAAA'); + await add('mail A', R.mail, input(R.mail, { ip: '192.0.2.25' })); + await add('MX at the apex', R.mx, input(R.mx, { preference: '10', host: `mail.${zone}` })); + await add('null MX', R.nullmx, input(R.nullmx, { preference: '0', host: '.' })); + await add('TXT at the apex', R.spf, input(R.spf, { text: 'v=spf1 -all' })); + await add('TXT longer than 255 bytes', R.longtxt, input(R.longtxt, { text: long }), ['txt_split']); + await add('SRV target A', R.sip, input(R.sip, { ip: '192.0.2.30' })); + await add('SRV', R.srv, input(R.srv, { priority: '10', weight: '5', port: '5060', target: `sip.${zone}` })); + await add('SRV with the . target', R.nosrv, input(R.nosrv, { priority: '0', weight: '0', port: '0', target: '.' })); + await add('CAA issue', R.caa, input(R.caa, { flag: '0', tag: 'issue', value: 'ca.example.net' })); + await add('CAA iodef critical', R.iodef, input(R.iodef, { flag: '128', tag: 'iodef', value: 'mailto:security@example.net' })); + await add('NS of a delegated subdomain', R.sub, input(R.sub, { host: 'ns.example.net' })); + await add('wildcard A with TTL 0', R.wild, input(R.wild, { ip: '192.0.2.99' })); + await adminUi.expectRow({ name: '*', type: 'A', value: '192.0.2.99', ttl: 'default (360 s)' }); + await served(world, zone, `anything.${zone}`, 'A', 'wildcard answers any name with TTL 360'); + await add('wildcard TXT below a label', R.wilddev, input(R.wilddev, { text: 'wildcard dev' })); + await served(world, zone, `x.dev.${zone}`, 'TXT', 'wildcard *.dev'); + + const soaBefore = await storedRow(world, zone, { name: '', type: 'SOA', ttl: 3600, data: { ns: `ns1.${zone}`, MBox: `dns\\.admin.${zone}`, refresh: 3600, retry: 600, expire: 604800, minttl: 300, serial: (await world.db.soaSerial(zone)) as number } }); + const soaChange = await begin(world, zone); + const soaMark = await world.db.auditMaxId(); + await adminUi.editSoa({ ns: `ns1.${zone}`, mbox: `hostmaster@${zone.slice(0, -1)}`, refresh: '7200', retry: '900', expire: '1209600', minttl: '600', ttl: '1800' }, { expectStatus: 200 }); + const soaSerial = await expectBumped(world, zone, soaChange, 'SOA edit'); + const soaRow = await storedRow(world, zone, { name: '', type: 'SOA', ttl: 1800, data: { ns: `ns1.${zone}`, MBox: `hostmaster.${zone}`, refresh: 7200, retry: 900, expire: 1209600, minttl: 600, serial: soaSerial } }); + expect(soaRow.id).toBe(soaBefore.id); + const summary = await adminUi.soaSummary(); + expect(summary).toMatchObject({ 'Primary name server': `ns1.${zone}`, Hostmaster: `hostmaster.${zone}`, Serial: String(soaSerial), Refresh: '7200', Retry: '900', Expire: '1209600', 'Minimum TTL': '600', TTL: '1800' }); + const soaAudit = findAudit(await auditSince(world, soaMark), 'soa_update', 200); + expectAuditRecord(parsedJson(soaAudit.before_value), soaBefore, 'soa_update before'); + expectAuditRecord(parsedJson(soaAudit.after_value), soaRow, 'soa_update after'); + await served(world, zone, zone, 'SOA', 'edited SOA'); + await served(world, zone, `missing.${zone}`, 'TXT', 'NXDOMAIN carries the authority SOA with the new serial'); + + await edit('edit A address', R.www1, { ...R.www1, data: { ip: '192.0.2.20' } }, input(R.www1, { ip: '192.0.2.20' })); + R.www1 = { ...R.www1, data: { ip: '192.0.2.20' } }; + await edit('edit AAAA address and TTL', R.www6, { ...R.www6, ttl: 600, data: { ip: '2001:db8::20' } }, input(R.www6, { ip: '2001:db8::20' }, { ttl: '600' })); + R.www6 = { ...R.www6, ttl: 600, data: { ip: '2001:db8::20' } }; + await edit('edit CNAME TTL', R.alias, { ...R.alias, ttl: 120 }, input(R.alias, { host: `web.${zone}` }, { ttl: '120' })); + R.alias = { ...R.alias, ttl: 120 }; + await edit('edit MX preference', R.mx, { ...R.mx, data: { host: `mail.${zone}`, preference: 20 } }, input(R.mx, { preference: '20', host: `mail.${zone}` })); + R.mx = { ...R.mx, data: { host: `mail.${zone}`, preference: 20 } }; + await edit('edit TXT text', R.spf, { ...R.spf, data: { text: 'v=spf1 mx -all' } }, input(R.spf, { text: 'v=spf1 mx -all' })); + R.spf = { ...R.spf, data: { text: 'v=spf1 mx -all' } }; + await edit('edit SRV port', R.srv, { ...R.srv, data: { ...R.srv.data, port: 5061 } }, input(R.srv, { priority: '10', weight: '5', port: '5061', target: `sip.${zone}` })); + R.srv = { ...R.srv, data: { ...R.srv.data, port: 5061 } }; + await edit('edit CAA value', R.iodef, { ...R.iodef, data: { flag: 128, tag: 'iodef', value: 'mailto:dns@example.net' } }, input(R.iodef, { flag: '128', tag: 'iodef', value: 'mailto:dns@example.net' })); + R.iodef = { ...R.iodef, data: { flag: 128, tag: 'iodef', value: 'mailto:dns@example.net' } }; + await edit('edit NS host', R.sub, { ...R.sub, data: { host: 'ns2.example.net.' } }, input(R.sub, { host: 'ns2.example.net.' })); + R.sub = { ...R.sub, data: { host: 'ns2.example.net.' } }; + await edit('edit wildcard address', R.wild, { ...R.wild, data: { ip: '192.0.2.98' } }, input(R.wild, { ip: '192.0.2.98' })); + R.wild = { ...R.wild, data: { ip: '192.0.2.98' } }; + await edit('rename a wildcard owner', R.wilddev, { ...R.wilddev, name: '*.stage' }, input(R.wilddev, { text: 'wildcard dev' }, { name: '*.stage' })); + R.wilddev = { ...R.wilddev, name: '*.stage' }; + await served(world, zone, `x.dev.${zone}`, 'TXT', 'the old wildcard no longer answers'); + await served(world, zone, `x.stage.${zone}`, 'TXT', 'the renamed wildcard answers'); + + await del('delete AAAA', R.www6); + await del('delete CNAME', R.alias); + await served(world, zone, `alias.${zone}`, 'A', 'deleted CNAME owner answers through the wildcard'); + await del('delete null MX', R.nullmx); + await del('delete long TXT', R.longtxt); + await del('delete SRV with the . target', R.nosrv); + await del('delete CAA', R.iodef); + await del('delete NS of the subdomain', R.sub); + await del('delete wildcard TXT', R.wilddev); + await del('delete one A of an RRset', R.www2); + await served(world, zone, `www.${zone}`, 'A', 'the remaining A of www'); + await servedZone(world, zone); + }); + + test('5a. bulk deletion removes the selected records in one transaction', async ({ world }) => { + await adminUi.openZone(zone); + const recs: Rec[] = [1, 2, 3].map((i) => ({ name: `bulk${i}`, type: 'TXT', ttl: 300, data: { text: `bulk ${i}` } })); + for (const r of recs) { + const res = await adminApi.post(`${zp(zone)}/records`, { name: r.name, type: r.type, ttl: r.ttl, data: r.data }); + expect(res.status, res.text).toBe(201); + } + await adminUi.openZone(zone); + const rows = await Promise.all(recs.map((r) => storedRow(world, zone, r))); + const change = await begin(world, zone); + const mark = await world.db.auditMaxId(); + const res = await adminUi.bulkDelete(recs.map((r) => ({ name: r.name, type: r.type })), { expectStatus: 200 }); + expect(res.json).toEqual(bulkDeleteBody(3)); + await expectBumped(world, zone, change, 'bulk delete'); + for (const r of recs) await threeWayGone(world, adminUi, zone, r, null, `bulk deleted ${r.name}`); + const audit = findAudit(await auditSince(world, mark), 'record_bulk_delete', 200); + expect(audit.zone).toBe(zone); + await expectAuditChange(world, zone, audit, change, 'bulk delete'); + const survivor = await adminApi.post(`${zp(zone)}/records`, { name: 'bulk4', type: 'TXT', ttl: 300, data: { text: 'bulk 4' } }); + const stale = await adminApi.post(`${zp(zone)}/records/delete`, { records: [{ id: survivor.json.record.id, etag: survivor.json.record.etag }, { id: rows[0].id, etag: '"0000"' }] }); + expect(stale.status, 'a stale or missing ETag fails the whole bulk delete').toBe(412); + await storedRow(world, zone, { name: 'bulk4', type: 'TXT', ttl: 300, data: { text: 'bulk 4' } }); + const done = await adminApi.post(`${zp(zone)}/records/delete`, { records: [{ id: survivor.json.record.id, etag: survivor.json.record.etag }] }); + expect(done.status).toBe(200); + }); + + test('5b. the export replace-imported produces no change; merge and replace imports apply exactly their diff', async ({ world }) => { + test.setTimeout(300_000); + const rows = await world.db.records(zone); + const exported = await adminUi.exportZone(zone); + const lines = exported.split('\n').filter((l) => l.trim() !== '' && !l.startsWith(';')); + expect(lines[0]).toBe(`$ORIGIN ${zone}`); + const rr = lines.filter((l) => !l.startsWith('$')); + expect(rr[0]).toMatch(/\sIN\s+SOA\s/); + expect(rr).toHaveLength(rows.length); + const owner = (l: string) => l.split(/\s+/)[0]; + expect(rr.find((l) => owner(l) === `*.${zone}` || owner(l) === '*'), 'TTL 0 is exported as 360').toMatch(/\s360\s+IN\s+A\s+192\.0\.2\.98$/); + const direct = await adminApi.get(`${zp(zone)}/export`); + expect(direct.status).toBe(200); + expect(direct.headers['content-type']).toMatch(/^text\/plain/); + expect(direct.headers['content-disposition']).toBe(`attachment; filename="${zone}zone"`); + expect(direct.text).toBe(exported); + + const serial = await world.db.soaSerial(zone); + const preview = await adminUi.importPreview(zone, exported, 'replace'); + expect(preview.status).toBe(200); + expect(preview.json).toMatchObject({ added: [], updated: [], deleted: [], unchanged: rows.length, skipped: [] }); + expect(preview.json.soa, 'an unchanged SOA is not reported as a change').toBeNull(); + expect(await adminUi.importSummary()).toContain('0 additions, 0 updates, 0 deletions'); + await expect(adminUi.page.locator('#import-apply')).toBeHidden(); + const noopMark = await world.db.auditMaxId(); + const noop = await adminApi.post(`${zp(zone)}/import/apply`, { mode: 'replace', content: exported, fingerprint: preview.json.fingerprint }); + expect(noop.status, noop.text).toBe(200); + expect(noop.json).toEqual(importApplyBody(0, 0, 0)); + expect(findAudit(await auditSince(world, noopMark), 'zone_import', 200)).toMatchObject({ before_value: null, after_value: null }); + expect(await world.db.records(zone)).toEqual(rows); + expect(await world.db.soaSerial(zone)).toBe(serial); + + const merge = [ + '$TTL 600', + 'imp1 IN A 192.0.2.40', + 'imp1 IN AAAA 2001:db8::40', + 'www 900 IN A 192.0.2.20', + 'multi IN TXT "part one" "part two"', + 'oldbox IN HINFO "PC" "Linux"', + ].join('\n'); + const mp = await adminUi.importPreview(zone, merge, 'merge'); + expect(mp.status).toBe(200); + expect(mp.json.added.map((a: { name: string; type: string }) => `${a.name} ${a.type}`).sort()).toEqual(['imp1 A', 'imp1 AAAA', 'multi TXT']); + expect(mp.json.updated).toEqual([expect.objectContaining({ name: 'www', type: 'A', ttl: 900, old_ttl: 300 })]); + expect(mp.json.deleted).toEqual([]); + expect(mp.json.skipped).toEqual([expect.objectContaining({ reason: expect.any(String) })]); + expect(mp.json.warnings.length).toBeGreaterThanOrEqual(1); + expect(await adminUi.importSummary()).toContain('3 additions, 1 update, 0 deletions'); + const change = await begin(world, zone); + const mark = await world.db.auditMaxId(); + const applied = await adminUi.importApply(); + expect(applied.status).toBe(200); + expect(applied.json).toEqual(importApplyBody(3, 1, 0)); + await expect(adminUi.page).toHaveURL(new RegExp(`/zones/${zone.replace(/\./g, '\\.')}$`)); + await expectBumped(world, zone, change, 'merge import'); + const imported: Rec[] = [ + { name: 'imp1', type: 'A', ttl: 600, data: { ip: '192.0.2.40' } }, + { name: 'imp1', type: 'AAAA', ttl: 600, data: { ip: '2001:db8::40' } }, + { name: 'www', type: 'A', ttl: 900, data: { ip: '192.0.2.20' } }, + { name: 'multi', type: 'TXT', ttl: 600, data: { text: 'part onepart two' } }, + ]; + for (const r of imported) await threeWay(world, adminUi, zone, r, null, `merge import ${r.name} ${r.type}`); + const audit = findAudit(await auditSince(world, mark), 'zone_import', 200); + await expectAuditChange(world, zone, audit, change, 'merge import'); + expect(JSON.stringify(audit)).not.toContain('HINFO'); + + const current = await adminApi.get(`${zp(zone)}/export`); + const dropped = new Set([`imp1.${zone}`, 'imp1', `multi.${zone}`, 'multi']); + const replaceFile = current.text + .split('\n') + .filter((l) => !dropped.has(l.split(/\s+/)[0])) + .join('\n'); + const rp = await adminUi.importPreview(zone, replaceFile, 'replace'); + expect(rp.status).toBe(200); + expect(rp.json.deleted.map((d: { name: string; type: string }) => `${d.name} ${d.type}`).sort()).toEqual(['imp1 A', 'imp1 AAAA', 'multi TXT']); + expect(rp.json.added).toEqual([]); + expect(await adminUi.importSummary()).toContain('0 additions, 0 updates, 3 deletions'); + const rchange = await begin(world, zone); + const rmark = await world.db.auditMaxId(); + const rapplied = await adminUi.importApply(); + expect(rapplied.json).toEqual(importApplyBody(0, 0, 3)); + await expectBumped(world, zone, rchange, 'replace import'); + for (const r of imported.filter((x) => x.name !== 'www')) await threeWayGone(world, adminUi, zone, r, null, `replace import removed ${r.name} ${r.type}`); + const raudit = findAudit(await auditSince(world, rmark), 'zone_import', 200); + await expectAuditChange(world, zone, raudit, rchange, 'replace import'); + + const fp = await adminApi.post(`${zp(zone)}/import/preview`, { mode: 'merge', content: 'late IN A 192.0.2.77' }); + expect(fp.status).toBe(200); + const moved = await adminApi.post(`${zp(zone)}/records`, { name: 'race', type: 'A', ttl: 60, data: { ip: '192.0.2.78' } }); + expect(moved.status).toBe(201); + const conflict = await adminApi.post(`${zp(zone)}/import/apply`, { mode: 'merge', content: 'late IN A 192.0.2.77', fingerprint: fp.json.fingerprint }); + expect(conflict.status, 'a zone changed after the preview refuses the apply').toBe(409); + await expectNoRow(world, zone, { name: 'late', type: 'A', ttl: 600, data: { ip: '192.0.2.77' } }); + const bad = await adminApi.post(`${zp(zone)}/import/preview`, { mode: 'merge', content: 'x.other.example. IN A 192.0.2.1\n$INCLUDE /etc/passwd' }); + expect(bad.status).toBe(422); + expect(bad.json.errors.length).toBeGreaterThanOrEqual(1); + await servedZone(world, zone); + }); + + test('6. the check panel and the check CLI report every error code and the UI repairs the rows', async ({ world }) => { + test.setTimeout(400_000); + zoneC = `${world.unique('broken-')}.core.test.`; + const created = await adminApi.post('/zones', { name: zoneC, ns: `ns1.${zoneC}`, mbox: `hostmaster@${zoneC}`, extra_ns: [], refresh: 3600, retry: 600, expire: 604800, minttl: 300, ttl: 3600 }); + expect(created.status, created.text).toBe(201); + await adminApi.post(`${zp(zoneC)}/records`, { name: 'ns1', type: 'A', ttl: 3600, data: { ip: '192.0.2.1' } }); + await waitForZone(world.g, zoneC, { recorder: world.recorder }); + const soa = (await world.db.records(zoneC)).find((r) => r.record_type === 'SOA') as RecordRow; + const id = async (name: string, type: string, ttl: number | null, content: string | null, z = zoneC) => world.db.insertRaw({ zone: z, name, ttl, content, record_type: type }); + const broken: Record = { + ttl_null: await id('tnull', 'A', null, '{"ip":"192.0.2.60"}'), + ttl_negative: await id('tneg', 'A', -5, '{"ip":"192.0.2.61"}'), + content_null: await id('cnull', 'TXT', 3600, null), + content_json: await id('cjson', 'TXT', 3600, 'not json'), + type_unknown: await id('tunk', 'a', 3600, '{"ip":"192.0.2.62"}'), + field_invalid: await id('finv', 'A', 3600, '{"ip":"999.1.1.1"}'), + name_not_fqdn: await id('nfq', 'CNAME', 3600, '{"host":"target.example.net"}'), + mx_priority_key: await id('mxp', 'MX', 3600, '{"host":"mail.example.net.","priority":10}'), + soa_not_apex: await id('soasub', 'SOA', 3600, soa.content), + soa_multiple: await id('', 'SOA', 3600, soa.content), + cname_apex: await id('', 'CNAME', 3600, '{"host":"target.example.net."}'), + cname_conflict: await id('both', 'CNAME', 3600, '{"host":"target.example.net."}'), + pack_failed: await id('cut', 'NS', 3600, '{"host":"ns.example.net"}'), + }; + await id('both', 'A', 3600, '{"ip":"192.0.2.63"}'); + const codes = Object.keys(broken); + const brokenRows = await world.db.records(zoneC); + for (const [name, type, rcode] of [ + [`tnull.${zoneC}`, 'A', 'SERVFAIL'], + [`tneg.${zoneC}`, 'A', 'SERVFAIL'], + [`cnull.${zoneC}`, 'TXT', 'SERVFAIL'], + [`cjson.${zoneC}`, 'TXT', 'SERVFAIL'], + [`tunk.${zoneC}`, 'A', 'NOTIMP'], + ] as const) { + const r = await expectServed(world.g, brokenRows, name, type, { recorder: world.recorder }); + expect(r.rcode, `the plugin answers ${rcode} for ${name} ${type}`).toBe(rcode); + } + const nodot = zoneC.slice(0, -1); + const upper = zoneC.toUpperCase(); + const nosoa = `${world.unique('nosoa-')}.core.test.`; + const other: Record = { + zone_not_fqdn: await id('nodot', 'A', 3600, '{"ip":"192.0.2.64"}', nodot), + zone_case: await id('upper', 'A', 3600, '{"ip":"192.0.2.65"}', upper), + }; + await id('', 'NS', 3600, `{"host":"ns1.${nosoa}"}`, nosoa); + + const check = await adminApi.get(`${zp(zoneC)}/check`); + expect(check.status).toBe(200); + const problems = check.json.problems as Array<{ zone: string; id: number | null; code: string; severity: string; name: string | null; type: string | null; message: string }>; + for (const [code, rowId] of Object.entries(broken)) { + if (code === 'soa_multiple' || code === 'cname_conflict') { + expect(problems.some((p) => p.code === code && p.severity === 'error'), `check reports ${code}`).toBe(true); + continue; + } + expect(problems.some((p) => p.code === code && p.severity === 'error' && p.id === rowId), `check reports ${code} on row ${rowId}`).toBe(true); + } + for (const p of problems) expect(p.zone).toBe(zoneC); + const all = await adminApi.get('/check'); + const allProblems = all.json.problems as Array<{ zone: string; id: number | null; code: string }>; + for (const [code, rowId] of Object.entries(other)) expect(allProblems.some((p) => p.code === code && p.id === rowId), `check of all zones reports ${code}`).toBe(true); + expect(allProblems.some((p) => p.code === 'soa_missing' && p.zone === nosoa)).toBe(true); + expect(allProblems.filter((p) => p.zone === zone && (p as { severity?: string }).severity === 'error'), 'the application-written zone has no error').toEqual([]); + + const cli = await world.cli.check(zoneC); + expect(cli.code, cli.stderr).toBe(3); + const table = parseTable(cli.stdout); + expect(table.header).toEqual(['ZONE', 'NAME', 'TYPE', 'ID', 'SEVERITY', 'PROBLEM']); + for (const code of codes) expect(table.rows.some((r) => r[5].startsWith(code) || r[5].includes(code)), `check CLI lists ${code}`).toBe(true); + for (const [code, rowId] of Object.entries(broken)) { + if (code === 'soa_multiple' || code === 'cname_conflict') continue; + expect(table.rows.some((r) => r[3] === String(rowId) && r[4] === 'error'), `check CLI row ${rowId} for ${code}`).toBe(true); + } + const cliAll = await world.cli.check(); + expect(cliAll.code).toBe(3); + for (const code of [...codes, 'zone_not_fqdn', 'zone_case', 'soa_missing']) expect(cliAll.stdout).toContain(code); + const badZone = await world.cli.check('not a zone'); + expect(badZone.code).toBe(2); + + await adminUi.openZone(zoneC); + const panel = await adminUi.problems(); + for (const code of codes) expect(panel.some((p) => p.code === code && p.severity === 'error'), `problems panel lists ${code}`).toBe(true); + const uiRows = await adminUi.rows(); + expect(uiRows.find((r) => r.name === 'cjson')?.value).toBe('not json'); + expect(uiRows.find((r) => r.name === 'tnull')?.ttl).toBe('missing'); + await adminUi.goto('/'); + const zonesTable = await adminUi.zonesTable(); + expect(zonesTable.find((z) => z.zone === zoneC)?.problems).toMatch(/\d+ errors?/); + expect(zonesTable.find((z) => z.zone === zone)?.problems).not.toMatch(/error/); + + await world.db.exec(`DELETE FROM ${world.db.t.records} WHERE id IN (?, ?)`, [broken.soa_not_apex, broken.soa_multiple]); + await world.db.deleteZoneRaw(nodot); + await world.db.deleteZoneRaw(upper); + await world.db.deleteZoneRaw(nosoa); + await adminUi.openZone(zoneC); + await adminUi.bulkDelete([{ name: 'both', type: 'CNAME' }, { name: '@', type: 'CNAME' }], { expectStatus: 200 }); + const listed = (await adminApi.get(`${zp(zoneC)}/records`)).json.records as Array<{ id: number; name: string; type: string; data: unknown; raw: string | null; problems: Array<{ severity: string }> }>; + for (const r of listed.filter((x) => x.problems.length > 0 && x.data === null)) expect(r.raw === null || typeof r.raw === 'string').toBe(true); + const storedContent = new Map((await world.db.records(zoneC)).map((r) => [r.id, r.content])); + expectCheckErrorRowsCarryRaw(listed, (i) => storedContent.get(listed[i].id) ?? null); + const repair = async (what: string, match: { name: string; type: string }, inp: RecordInput & { selectType?: string }, rec: Rec) => { + const apiRow = listed.find((x) => x.name === match.name && x.type === match.type); + await adminUi.openEdit(match); + if (apiRow?.data === null) { + await expect(adminUi.page.locator('#record-broken'), `${what}: the broken row is shown with its raw content`).toBeVisible(); + if (apiRow.raw !== null) await expect(adminUi.page.locator('#record-raw')).toHaveText(apiRow.raw); + } + if (inp.selectType) await adminUi.page.selectOption('#rec-type', inp.selectType); + if (apiRow?.data === null) for (const key of Object.keys(inp.fields)) await expect(adminUi.page.locator(`#rec-f-${key}`), `${what}: the typed form starts empty`).toHaveValue(key === 'flag' ? '0' : ''); + await adminUi.page.fill('#rec-name', inp.name); + if (inp.ttl !== undefined) await adminUi.page.fill('#rec-ttl', inp.ttl); + for (const [k, v] of Object.entries(inp.fields)) { + const el = adminUi.page.locator(`#rec-f-${k}`); + if ((await el.evaluate((e) => e.tagName)) === 'SELECT') await el.selectOption(v); + else await el.fill(v); + } + const done = adminUi.page.waitForResponse((r) => /\/records\/\d+$/.test(new URL(r.url()).pathname) && r.request().method() === 'PUT'); + await adminUi.page.click('#rec-submit'); + const res = await done; + expect(res.status(), `${what}: ${await res.text()}`).toBe(200); + await adminUi.settle(); + await threeWay(world, adminUi, zoneC, rec, null, `repair ${what}`); + }; + await repair('ttl_null', { name: 'tnull', type: 'A' }, { name: 'tnull', type: 'A', ttl: '300', fields: { ip: '192.0.2.60' } }, { name: 'tnull', type: 'A', ttl: 300, data: { ip: '192.0.2.60' } }); + await repair('ttl_negative', { name: 'tneg', type: 'A' }, { name: 'tneg', type: 'A', ttl: '300', fields: { ip: '192.0.2.61' } }, { name: 'tneg', type: 'A', ttl: 300, data: { ip: '192.0.2.61' } }); + await repair('content_null', { name: 'cnull', type: 'TXT' }, { name: 'cnull', type: 'TXT', ttl: '3600', fields: { text: 'repaired' } }, { name: 'cnull', type: 'TXT', ttl: 3600, data: { text: 'repaired' } }); + await repair('content_json', { name: 'cjson', type: 'TXT' }, { name: 'cjson', type: 'TXT', ttl: '3600', fields: { text: 'repaired json' } }, { name: 'cjson', type: 'TXT', ttl: 3600, data: { text: 'repaired json' } }); + await repair('type_unknown', { name: 'tunk', type: 'a' }, { name: 'tunk', type: 'A', selectType: 'A', ttl: '3600', fields: { ip: '192.0.2.62' } }, { name: 'tunk', type: 'A', ttl: 3600, data: { ip: '192.0.2.62' } }); + await repair('field_invalid', { name: 'finv', type: 'A' }, { name: 'finv', type: 'A', ttl: '3600', fields: { ip: '192.0.2.66' } }, { name: 'finv', type: 'A', ttl: 3600, data: { ip: '192.0.2.66' } }); + await repair('name_not_fqdn', { name: 'nfq', type: 'CNAME' }, { name: 'nfq', type: 'CNAME', ttl: '3600', fields: { host: 'target.example.net' } }, { name: 'nfq', type: 'CNAME', ttl: 3600, data: { host: 'target.example.net.' } }); + await repair('mx_priority_key', { name: 'mxp', type: 'MX' }, { name: 'mxp', type: 'MX', ttl: '3600', fields: { preference: '10', host: 'mail.example.net' } }, { name: 'mxp', type: 'MX', ttl: 3600, data: { host: 'mail.example.net.', preference: 10 } }); + await repair('pack_failed', { name: 'cut', type: 'NS' }, { name: 'cut', type: 'NS', ttl: '3600', fields: { host: 'ns.example.net' } }, { name: 'cut', type: 'NS', ttl: 3600, data: { host: 'ns.example.net.' } }); + const after = await adminApi.get(`${zp(zoneC)}/check`); + expect((after.json.problems as Array<{ severity: string; code: string }>).filter((p) => p.severity === 'error')).toEqual([]); + const cliAfter = await world.cli.check(zoneC); + expect(cliAfter.code).toBe(after.json.problems.length === 0 ? 0 : 3); + expect(cliAfter.stdout).not.toMatch(/\berror\b/); + await servedZone(world, zoneC); + }); + + 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.`; + const zb = await adminApi.post('/zones', { name: zoneB, ns: `ns1.${zoneB}`, mbox: `hostmaster@${zoneB}`, extra_ns: [], refresh: 3600, retry: 600, expire: 604800, minttl: 300, ttl: 3600 }); + expect(zb.status, zb.text).toBe(201); + user1 = { username: world.unique('alice-'), password: world.password('password of alice'), role: 'user' }; + user2 = { username: world.unique('bob-'), password: world.password('password of bob'), role: 'user' }; + admin2 = { username: world.unique('carol-'), password: world.password('password of carol'), role: 'admin' }; + await adminUi.goto('/users'); + const mismatch = await adminUi.createUserUi(world.unique('typo-'), 'user', world.password(), 'something-else-entirely'); + expect(mismatch.status, 'mismatched passwords are refused before any request').toBe(0); + await expect(adminUi.page.locator('#user-form .field-error')).toHaveText('The two passwords differ.'); + await adminUi.page.keyboard.press('Escape'); + await expect(adminUi.page.locator('#user-dialog')).toBeHidden(); + for (const a of [user1, user2, admin2]) { + const mark = await world.db.auditMaxId(); + const res = await adminUi.createUserUi(a.username, a.role, a.password); + expect(res.status, JSON.stringify(res.json)).toBe(201); + expect(res.json).toMatchObject({ username: a.username, role: a.role, zone_count: 0, last_login_at: null, deleted_at: null }); + const row = await world.db.user(a.username); + expect(row).toMatchObject({ role: a.role, deleted_at: null }); + expect(row?.password_hash).toMatch(/^\$argon2id\$/); + const audit = findAudit(await auditSince(world, mark), 'user_create', 201); + expect(audit).toMatchObject({ actor: admin.username, target_user_id: row?.id, zone: null }); + expect(parsedJson(audit.after_value)).toMatchObject({ id: row?.id, username: a.username, role: a.role, deleted_at: null }); + } + const listed = await adminUi.usersTable(); + expect(listed.map((u) => u.username)).toEqual([admin.username, user1.username, user2.username, admin2.username].sort()); + expect(listed.find((u) => u.username === user1.username)).toMatchObject({ role: 'user', zones: '0', lastLogin: '-', state: 'active' }); + + await adminUi.openZone(zone); + const pickable = await adminUi.page.$$eval('#zone-user-pick option', (os) => os.map((o) => (o as HTMLOptionElement).value)); + expect(pickable.sort(), 'the picker offers active users with role user only').toEqual([user1.username, user2.username].sort()); + const markGrant = await world.db.auditMaxId(); + expect((await adminUi.delegateFromZonePage(user1.username)).status).toBe(204); + expect(await adminUi.zoneUsers()).toEqual([user1.username]); + const grant = findAudit(await auditSince(world, markGrant), 'delegation_grant', 204); + expect(grant).toMatchObject({ zone, target_user_id: (await world.db.user(user1.username))?.id }); + expect(parsedJson(grant.after_value)).toEqual(expect.objectContaining({ zone, username: user1.username })); + await adminUi.openUser(user1.username); + expect((await adminUi.delegateFromUserPage(zoneB)).status).toBe(204); + expect((await adminUi.userZones()).sort()).toEqual([zone, zoneB].sort()); + expect((await adminApi.put(`${zp(zone)}/users/${encodeURIComponent(user1.username)}`)).status, 'granting is idempotent').toBe(204); + expect((await adminApi.put(`${zp(zone)}/users/${encodeURIComponent(admin2.username)}`)).status, 'delegating to an admin').toBe(422); + expect((await adminApi.put(`${zp(`missing-${world.unique('')}.core.test.`)}/users/${encodeURIComponent(user1.username)}`)).status, 'delegating a missing zone').toBe(404); + expect((await adminApi.put(`${zp(zone)}/users/nobody-${world.unique('')}`)).status, 'delegating to a missing user').toBe(404); + const u1id = (await world.db.user(user1.username))?.id as number; + expect((await world.db.delegations()).filter((d) => d.user_id === u1id).map((d) => d.zone).sort()).toEqual([zone, zoneB].sort()); + const rootId = (await world.db.user(admin.username))?.id; + for (const d of (await world.db.delegations()).filter((x) => x.user_id === u1id)) expect(d.created_by).toBe(rootId); + + const u1api = await world.apiAs(user1); + const u1ui = await world.uiAs(user1); + const u2api = await world.apiAs(user2); + const u2ui = await world.uiAs(user2); + expect((await u1api.get('/zones')).json.zones.map((z: { name: string }) => z.name)).toEqual([zone, zoneB].sort()); + expect((await u1api.get('/account')).json).toEqual({ username: user1.username, role: 'user', zones: [zone, zoneB].sort() }); + expect((await u1ui.zonesTable()).map((z) => z.zone)).toEqual([zone, zoneB].sort()); + await expect(u1ui.page.locator('#new-zone')).toHaveCount(0); + await expect(u1ui.page.locator('nav.nav a', { hasText: 'Users' })).toHaveCount(0); + const checkAll = await u1api.get('/check'); + expect([...new Set((checkAll.json.problems as Array<{ zone: string }>).map((p) => p.zone))].every((z) => z === zone || z === zoneB)).toBe(true); + await u1ui.openZone(zone); + await expect(u1ui.page.locator('#users-panel')).toHaveCount(0); + await expect(u1ui.page.locator('#danger')).toHaveCount(0); + const rec: Rec = { name: 'delegated', type: 'A', ttl: 300, data: { ip: '192.0.2.150' } }; + let change = await begin(world, zone); + await u1ui.addRecord({ name: 'delegated', type: 'A', ttl: '300', fields: { ip: '192.0.2.150' } }, { expectStatus: 201 }); + await threeWay(world, u1ui, zone, rec, change, 'a delegated user adds a record'); + change = await begin(world, zone); + await u1ui.editRecord({ name: 'delegated', type: 'A' }, { name: 'delegated', type: 'A', ttl: '300', fields: { ip: '192.0.2.151' } }, { expectStatus: 200 }); + await threeWay(world, u1ui, zone, { ...rec, data: { ip: '192.0.2.151' } }, change, 'a delegated user edits a record'); + expect((await u2api.get('/zones')).json.zones).toEqual([]); + expect((await u2api.get('/account')).json).toEqual({ username: user2.username, role: 'user', zones: [] }); + await u2ui.goto('/'); + await expect(u2ui.page.locator('#zones-status')).toHaveText('No zone is delegated to you.'); + + const missing = `missing-${world.unique('')}.core.test.`; + const cRow = (await world.db.records(zoneC))[0]; + const zoneRoutes = (z: string): Array<[string, string, unknown?]> => [ + ['GET', zp(z)], + ['GET', `${zp(z)}/records`], + ['POST', `${zp(z)}/records`, { name: 'x', type: 'A', ttl: 60, data: { ip: '192.0.2.1' } }], + ['PUT', `${zp(z)}/records/${cRow.id}`, { name: 'x', type: 'A', ttl: 60, data: { ip: '192.0.2.1' } }], + ['DELETE', `${zp(z)}/records/${cRow.id}`], + ['POST', `${zp(z)}/records/delete`, { records: [{ id: cRow.id, etag: '"x"' }] }], + ['PUT', `${zp(z)}/soa`, { ns: 'ns1.x.', mbox: 'h.x.', ttl: 60, refresh: 1, retry: 1, expire: 1, minttl: 1 }], + ['GET', `${zp(z)}/check`], + ['GET', `${zp(z)}/export`], + ['POST', `${zp(z)}/import/preview`, { mode: 'merge', content: 'a IN A 192.0.2.1' }], + ['POST', `${zp(z)}/import/apply`, { mode: 'merge', content: 'a IN A 192.0.2.1', fingerprint: '00' }], + ]; + for (const client of [u1api, u2api]) { + const hidden = zoneRoutes(zoneC); + const absent = zoneRoutes(missing); + for (let i = 0; i < hidden.length; i++) { + const [m, p, b] = hidden[i]; + const r1 = await client.raw(m, `/api/v1${p}`, { body: b, ifMatch: m === 'PUT' || m === 'DELETE' ? `"${'0'.repeat(64)}"` : undefined }); + const [m2, p2, b2] = absent[i]; + const r2 = await client.raw(m2, `/api/v1${p2}`, { body: b2, ifMatch: m2 === 'PUT' || m2 === 'DELETE' ? `"${'0'.repeat(64)}"` : undefined }); + expect(r1.status, `${client.username} ${m} ${p} on a zone not delegated`).toBe(404); + expect({ status: r2.status, body: r2.text }, `${m} ${p}: a hidden zone answers exactly like a missing one`).toEqual({ status: r1.status, body: r1.text }); + } + const admins: Array<[string, string, unknown?]> = [ + ['POST', '/zones', { name: `x-${world.unique('')}.core.test.`, ns: 'ns1.x.', mbox: 'h@x', extra_ns: [], refresh: 1, retry: 1, expire: 1, minttl: 1, ttl: 60 }], + ['DELETE', zp(zone), { confirm: zone }], + ['GET', '/users'], + ['POST', '/users', { username: world.unique('evil-'), role: 'admin', password: world.password() }], + ['GET', up(admin.username)], + ['PUT', `${up(client.username)}/role`, { role: 'admin' }], + ['PUT', `${up(admin.username)}/password`, { password: world.password() }], + ['DELETE', up(admin.username), { confirm: admin.username }], + ['GET', `${zp(zone)}/users`], + ['PUT', `${zp(zone)}/users/${encodeURIComponent(client.username)}`], + ['DELETE', `${zp(zone)}/users/${encodeURIComponent(user1.username)}`], + ]; + for (const [m, p, b] of admins) { + const r = await client.raw(m, `/api/v1${p}`, { body: b }); + expect(r.status, `${client.username} ${m} ${p} is admin only`).toBe(403); + expect(r.json).toEqual({ error: expect.any(String) }); + } + } + const recOfC = await u1api.put(`${zp(zone)}/records/${cRow.id}`, { name: 'x', type: 'A', ttl: 60, data: { ip: '192.0.2.1' } }, { ifMatch: '"x"' }); + expect(recOfC.status, 'a record id of another zone through a delegated zone path').toBe(404); + const notFound = await u2ui.goto(`/zones/${zoneC}`); + expect(notFound?.status()).toBe(404); + await expect(u2ui.page.getByRole('heading', { name: 'Not found' })).toBeVisible(); + const forbidden = await u2ui.goto('/users'); + expect(forbidden?.status()).toBe(403); + await expect(u2ui.page.getByRole('heading', { name: 'Forbidden' })).toBeVisible(); + + await adminUi.openUser(user1.username); + expect((await adminUi.revokeFromUserPage(zoneB)).status).toBe(204); + expect((await u1api.get(zp(zoneB))).status, 'revocation takes effect on the next request of an open session').toBe(404); + expect((await u1api.get('/zones')).json.zones.map((z: { name: string }) => z.name)).toEqual([zone]); + expect((await adminApi.delete(`${zp(zoneB)}/users/${encodeURIComponent(user1.username)}`)).status, 'revoking a missing delegation').toBe(404); + + await adminUi.openUser(user2.username); + expect((await adminUi.setRoleUi('admin')).status).toBe(204); + expect((await u2api.get('/users')).status, 'promotion takes effect on the next request').toBe(200); + expect((await u2api.get(zp(zoneC))).status).toBe(200); + expect((await adminUi.setRoleUi('user')).status).toBe(204); + expect((await u2api.get('/users')).status, 'demotion takes effect on the next request').toBe(403); + expect((await u2api.get(zp(zoneC))).status).toBe(404); + await adminUi.openUser(user1.username); + expect((await adminUi.setRoleUi('admin')).status).toBe(204); + expect((await world.db.delegations()).filter((d) => d.user_id === u1id).map((d) => d.zone), 'a promoted user keeps the delegation rows').toEqual([zone]); + await expect(adminUi.page.locator('#user-zones-status')).toContainText('apply again if the user is demoted'); + expect((await adminUi.setRoleUi('user')).status).toBe(204); + expect((await u1api.get(zp(zone))).status, 'the delegation applies again after the demotion').toBe(200); + + await adminUi.openUser(admin.username); + await expect(adminUi.page.locator('#user-self')).toBeVisible(); + await expect(adminUi.page.locator('#role-form')).toHaveCount(0); + for (const [m, p, b] of [ + ['PUT', `${up(admin.username)}/role`, { role: 'user' }], + ['PUT', `${up(admin.username)}/password`, { password: world.password() }], + ['DELETE', up(admin.username), { confirm: admin.username }], + ] as Array<[string, string, unknown]>) { + expect((await adminApi.raw(m, `/api/v1${p}`, { body: b })).status, `an admin cannot ${m} ${p} on their own account`).toBe(403); + } + + const auditOfU1 = (await world.db.auditSince(0)).filter((row) => row.user_id === u1id); + await adminUi.openUser(user1.username); + expect(await adminUi.deleteUserUi(user1.username, user1.username.slice(0, -1)), 'a wrong username keeps the delete button disabled').toBeNull(); + expect((await adminApi.delete(up(user1.username), { confirm: 'someone-else' })).status).toBe(422); + const delMark = await world.db.auditMaxId(); + const deleted = await adminUi.deleteUserUi(user1.username); + expect(deleted?.status).toBe(204); + const delAudit = findAudit(await auditSince(world, delMark), 'user_delete', 204); + expect(delAudit.target_user_id).toBe(u1id); + expect(parsedJson(delAudit.before_value)).toMatchObject({ username: user1.username, deleted_at: null }); + expect((parsedJson(delAudit.after_value) as { deleted_at: string | null }).deleted_at).not.toBeNull(); + expect((await u1api.get('/account')).status, 'the session of a deleted user ended').toBe(401); + u1api.forgetSession(); + expect(await world.db.sessions(u1id)).toEqual([]); + await u1ui.page.reload(); + await expect(u1ui.page).toHaveURL(/\/login/); + u1ui.sessionEnded(); + const refused = await (await world.api()).login(user1.username, user1.password); + expect(refused.status, 'a deleted user cannot log in').toBe(401); + expect(refused.text).toContain('invalid username or password'); + const u1row = await world.db.user(user1.username); + expect(u1row?.deleted_at).not.toBeNull(); + expect(u1row?.password_hash).toMatch(/^\$argon2id\$/); + expect((await world.db.delegations()).filter((d) => d.user_id === u1id).map((d) => d.zone), 'delegations of a deleted user stay').toEqual([zone]); + const retainedAudit = (await world.db.auditSince(0)).filter((row) => row.user_id === u1id && auditOfU1.some((old) => old.id === row.id)); + expect(retainedAudit, 'audit rows of a deleted user stay').toEqual(auditOfU1); + expect((await adminApi.get(`${zp(zone)}/users`)).json.users, 'zone pages do not list deleted users').toEqual([]); + const reuse = await adminApi.post('/users', { username: user1.username, role: 'user', password: world.password() }); + expect(reuse.status, 'the username of a deleted user stays taken').toBe(409); + expect((await world.cli.userAdd(user1.username, 'user', world.password())).code).toBe(1); + expect((await adminApi.put(`${up(user1.username)}/role`, { role: 'admin' })).status, 'a deleted user cannot be changed').toBe(404); + expect((await adminApi.put(`${zp(zone)}/users/${encodeURIComponent(user1.username)}`)).status, 'a deleted user cannot receive delegations').toBe(404); + expect((await adminApi.get(up(user1.username))).json).toMatchObject({ username: user1.username, deleted_at: expect.any(String) }); + await adminUi.goto('/users'); + expect((await adminUi.usersTable()).map((u) => u.username)).not.toContain(user1.username); + await adminUi.page.check('#show-deleted'); + await adminUi.settle(); + await expect.poll(async () => (await adminUi.usersTable()).find((u) => u.username === user1.username)?.state).toMatch(/^deleted /); + await adminUi.openUser(user1.username); + await expect(adminUi.page.locator('#user-readonly')).toBeVisible(); + await expect(adminUi.page.locator('#user-controls')).toBeHidden(); + const cliList = parseTable((await world.cli.userList()).stdout); + expect(cliList.rows.map((r) => r[0])).not.toContain(user1.username); + const cliAll = parseTable((await world.cli.userList(true)).stdout); + const u1cli = cliAll.rows.find((r) => r[0] === user1.username); + expect(u1cli?.[5]).not.toBe('-'); + expect(u1cli?.[2]).toBe('1'); + + expect((await world.cli.userRole(admin2.username, 'user')).code, 'demoting the second admin leaves one').toBe(0); + expect((await world.cli.userRole(admin.username, 'user')).code, 'the last active admin cannot be demoted').toBe(1); + expect((await world.cli.userDelete(admin.username)).code, 'the last active admin cannot be deleted').toBe(1); + expect((await world.db.user(admin.username))?.role).toBe('admin'); + expect((await world.cli.userRole(admin2.username, 'admin')).code).toBe(0); + const a2api = await world.apiAs(admin2); + const [r1, r2] = await Promise.all([adminApi.put(`${up(admin2.username)}/role`, { role: 'user' }), a2api.put(`${up(admin.username)}/role`, { role: 'user' })]); + const statuses = [r1.status, r2.status]; + expect(statuses.filter((s) => s === 204).length, `exactly one demotion succeeds (${statuses})`).toBe(1); + expect(statuses.filter((s) => s !== 204).every((s) => s === 403 || s === 409)).toBe(true); + const active = (await world.db.users()).filter((u) => u.role === 'admin' && u.deleted_at === null); + expect(active, 'one active admin remains').toHaveLength(1); + if (active[0].username !== admin.username) expect((await world.cli.userRole(admin.username, 'admin')).code).toBe(0); + expect((await world.cli.userRole(admin2.username, 'admin')).code).toBe(0); + expect((await adminApi.get('/users')).status).toBe(200); + }); + + test('8. audit: the page, the API and the CLI show the rows; users see only their rows', async ({ world }) => { + test.setTimeout(300_000); + const all = await world.db.auditSince(0); + expect(all.length).toBeGreaterThan(100); + for (const r of all) { + expect(r.time).toMatch(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{6}Z$/); + if (r.actor === 'cli') expect(r).toMatchObject({ origin: 'local', status: null, user_id: null }); + else expect(r.origin).toBe(runnerAddress()); + } + const api = await adminApi.get('/audit', { query: { limit: 200 } }); + expect(api.status).toBe(200); + const entries = api.json.entries as Array<{ id: number; time: string; actor: string; operation: string; status: number | null; zone: string | null; record_id: number | null; target_user: string | null; error: string | null }>; + expect(entries.length).toBe(200); + for (let i = 1; i < entries.length; i++) expect(entries[i].id).toBeLessThan(entries[i - 1].id); + const byId = new Map((await world.db.auditSince(0)).map((r) => [r.id, r])); + for (const e of entries) { + const row = byId.get(e.id); + if (!row) continue; + expect({ actor: e.actor, operation: e.operation, status: e.status, zone: e.zone, record_id: e.record_id, error: e.error }).toEqual({ + actor: row.actor, + operation: row.operation, + status: row.status, + zone: row.zone, + record_id: row.record_id, + error: row.error, + }); + } + const page2 = await adminApi.get('/audit', { query: { limit: 5, before_id: api.json.next_before_id } }); + expect(page2.json.entries).toHaveLength(5); + expect(page2.json.entries[0].id).toBeLessThan(entries[entries.length - 1].id); + for (const [filter, ok] of [ + [{ zone }, (e: { zone: string | null }) => e.zone === zone], + [{ operation: 'record_update' }, (e: { operation: string }) => e.operation === 'record_update'], + [{ kind: 'read' }, (e: { operation: string }) => READ_OPERATIONS.has(e.operation)], + [{ kind: 'change' }, (e: { operation: string }) => !READ_OPERATIONS.has(e.operation)], + [{ outcome: 'error' }, (e: { status: number | null }) => e.status !== null && e.status >= 400], + [{ outcome: 'success' }, (e: { status: number | null }) => e.status === null || e.status < 400], + [{ actor: user2.username }, (e: { actor: string }) => e.actor === user2.username], + ] as Array<[Record, (e: never) => boolean]>) { + const r = await adminApi.get('/audit', { query: { ...filter, limit: 200 } }); + expect(r.status).toBe(200); + expect(r.json.entries.length, `filter ${JSON.stringify(filter)} returns rows`).toBeGreaterThan(0); + for (const e of r.json.entries) expect(ok(e as never), `filter ${JSON.stringify(filter)}: ${JSON.stringify(e)}`).toBe(true); + } + for (const bad of [{ limit: '0' }, { limit: '201' }, { kind: 'both' }, { outcome: 'maybe' }, { before_id: 'x' }]) { + expect((await adminApi.get('/audit', { query: bad })).status, `invalid audit filter ${JSON.stringify(bad)}`).toBe(400); + } + + await adminUi.goto('/audit'); + const uiRows = await adminUi.auditRows(); + expect(uiRows.length).toBeGreaterThan(0); + await adminUi.filterAudit({ zone, operation: 'record_update' }); + const filtered = await adminUi.auditRows(); + expect(filtered.length).toBeGreaterThan(0); + for (const r of filtered) { + expect(r.operation).toBe('record_update'); + expect(r.target).toContain(zone); + } + const toggle = adminUi.page.locator('#audit-body button[aria-expanded]').first(); + await toggle.click(); + await expect(toggle).toHaveAttribute('aria-expanded', 'true'); + const diff = adminUi.page.locator('#audit-body tr.detail-row:not([hidden]) table.diff'); + await expect(diff).toBeVisible(); + await expect(diff.locator('tr.diff-changed').first()).toBeVisible(); + await adminUi.filterAudit({ zone: '', operation: '', outcome: 'error' }); + for (const r of await adminUi.auditRows()) expect(Number(r.status.slice(0, 3))).toBeGreaterThanOrEqual(400); + + const before = await world.db.auditMaxId(); + const cli = await world.cli.audit(30); + expect(cli.code, cli.stderr).toBe(0); + expect(await world.db.auditMaxId(), 'the audit CLI only reads').toBe(before); + const table = parseTable(cli.stdout); + expect(table.header).toEqual(['TIME', 'ACTOR', 'ORIGIN', 'OPERATION', 'STATUS', 'ZONE', 'RECORD', 'TARGET_USER']); + expect(table.rows).toHaveLength(30); + const tail = await world.db.auditTail(30); + table.rows.forEach((r, i) => { + expect(r[1]).toBe(tail[i].actor); + expect(r[3]).toBe(tail[i].operation); + expect(r[4]).toBe(tail[i].status === null ? '-' : String(tail[i].status)); + expect(r[5]).toBe(tail[i].zone ?? '-'); + expect(r[6]).toBe(tail[i].record_id === null ? '-' : String(tail[i].record_id)); + }); + const dflt = await world.cli.audit(); + expect(parseTable(dflt.stdout).rows).toHaveLength(20); + + expect((await adminApi.put(`${zp(zone)}/users/${encodeURIComponent(user2.username)}`)).status).toBe(204); + const u2api = await world.apiAs(user2); + const seen = await u2api.get('/audit', { query: { limit: 200 } }); + expect(seen.status).toBe(200); + expect(seen.json.entries.length).toBeGreaterThan(0); + for (const e of seen.json.entries) expect(e.zone === zone || e.actor === user2.username, `user visibility: ${JSON.stringify(e)}`).toBe(true); + expect(seen.json.entries.some((e: { actor: string }) => e.actor === admin.username), 'a user sees the rows of a delegated zone made by others').toBe(true); + const otherZone = await u2api.get('/audit', { query: { zone: zoneC } }); + expect(otherZone.json.entries.filter((e: { actor: string }) => e.actor !== user2.username)).toEqual([]); + const u2ui = await world.uiAs(user2); + await u2ui.goto('/audit'); + for (const r of await u2ui.auditRows()) expect(r.actor === user2.username || r.target.includes(zone)).toBe(true); + + const unknownMark = await world.db.auditMaxId(); + const adminRow = await world.db.user(admin.username); + const anon = await world.api(); + const unknownPath = await adminApi.get('/no-such-route'); + expect(unknownPath.status).toBe(404); + const unknownMethod = await adminApi.raw('PATCH', '/api/v1/zones'); + expect(unknownMethod.status).toBe(405); + const anonymousUnknown = await anon.get('/no-such-route'); + const unknownRows = (await auditSince(world, unknownMark)).filter((r) => r.operation === UNKNOWN_API_OPERATION); + expect([0, 2]).toContain(unknownRows.length); + expect(anonymousUnknown.status).toBe(unknownRows.length === 2 ? 401 : 404); + if (unknownRows.length === 2) { + expect(unknownRows.map((r) => r.status)).toEqual([404, 405]); + for (const r of unknownRows) { + expect(r).toMatchObject({ user_id: adminRow?.id, actor: admin.username, origin: runnerAddress(), zone: null, record_id: null, target_user_id: null, before_value: null, after_value: null }); + expect(typeof r.error).toBe('string'); + } + expect(JSON.stringify(unknownRows)).not.toContain('no-such-route/'); + } + expect((await auditSince(world, unknownMark)).filter((r) => r.actor !== admin.username || r.operation !== UNKNOWN_API_OPERATION)).toEqual([]); + }); + + test('9. password change, logout, session end and deletion of a zone with its delegations', async ({ world }) => { + test.setTimeout(300_000); + const u2ui = await world.uiAs(user2); + const other = await world.apiAs(user2); + await u2ui.goto('/account'); + await expect(u2ui.page.locator('#account-zones li')).toHaveText([zone]); + const wrong = await u2ui.changeOwnPasswordUi('not-the-current-password', world.password()); + expect(wrong?.status).toBe(422); + expect(wrong?.json.fields).toHaveProperty('current'); + await expect(u2ui.page.locator('#pw-current + .field-error')).toBeVisible(); + const short = await u2ui.changeOwnPasswordUi(user2.password, 'short'); + expect(short?.status).toBe(422); + expect(short?.json.fields).toHaveProperty('password'); + expect(await u2ui.changeOwnPasswordUi(user2.password, world.password(), 'different-repeat-value')).toBeNull(); + await expect(u2ui.page.locator('#pw-repeat + .field-error')).toHaveText('The two passwords differ.'); + const newPassword = world.password('new password of bob'); + const mark = await world.db.auditMaxId(); + const ok = await u2ui.changeOwnPasswordUi(user2.password, newPassword); + expect(ok?.status).toBe(204); + await u2ui.expectToast('Password changed. Your other sessions ended.'); + const pc = findAudit(await auditSince(world, mark), 'password_change', 204); + expect(JSON.stringify(pc)).not.toContain(newPassword); + expect((await other.get('/account')).status, 'a password change ends the other sessions').toBe(401); + other.forgetSession(); + await u2ui.goto('/account'); + await expect(u2ui.page).toHaveURL(/\/account$/); + const oldLogin = await (await world.api()).login(user2.username, user2.password); + expect(oldLogin.status).toBe(401); + user2 = { ...user2, password: newPassword }; + const u2id = (await world.db.user(user2.username))?.id as number; + const cookie = (await u2ui.cookie()) as string; + const sessionsBefore = (await world.db.sessions(u2id)).length; + await u2ui.logout(); + await expect(u2ui.page).toHaveURL(/\/login/); + expect((await world.db.sessions(u2id)).length, 'logout deletes the session row').toBe(sessionsBefore - 1); + const replay = await world.api(); + await replay.setCookie(cookie); + expect((await replay.get('/account')).status, 'a logged out cookie is refused').toBe(401); + for (const s of await world.db.sessions()) { + const ts = (v: string) => Date.parse(`${v.replace(' ', 'T')}Z`); + expect(ts(s.expires_at) - ts(s.created_at), 'sessions end at the latest SESSION_MAX_AGE after login').toBeLessThanOrEqual(12 * 3600_000 + 1000); + } + + const rowsBefore = await world.db.records(zone); + await adminUi.openZone(zone); + expect(await adminUi.zoneUsers()).toEqual([user2.username]); + expect(await adminUi.deleteZoneUi(`wrong-${zone}`), 'a wrong zone name keeps the delete button disabled').toBeNull(); + expect((await adminApi.delete(zp(zone), { confirm: zoneB })).status).toBe(422); + const dmark = await world.db.auditMaxId(); + const deleted = await adminUi.deleteZoneUi(zone.slice(0, -1).toUpperCase()); + expect(deleted?.status).toBe(204); + await adminUi.expectToast(/stops serving it after its next zone list reload/); + expect(await world.db.records(zone)).toEqual([]); + expect((await world.db.delegations()).filter((d) => d.zone === zone && d.user_id === u2id)).toEqual([]); + const za = findAudit(await auditSince(world, dmark), 'zone_delete', 204); + const zaBefore = JSON.stringify(parsedJson(za.before_value)); + for (const r of rowsBefore) expect(zaBefore).toContain(`"id":${r.id}`); + expect(zaBefore).toContain(user2.username); + expect(za.after_value).toBeNull(); + await waitForZoneGone(world.g, zone, { recorder: world.recorder }); + const u2api = await world.apiAs(user2); + expect((await u2api.get(zp(zone))).status).toBe(404); + const again = await adminApi.post('/zones', { name: zone, ns: `ns1.${zone}`, mbox: `hostmaster@${zone}`, extra_ns: [], refresh: 3600, retry: 600, expire: 604800, minttl: 300, ttl: 3600 }); + expect(again.status).toBe(201); + expect((await adminApi.get(`${zp(zone)}/users`)).json.users, 'a zone created again starts without delegations').toEqual([]); + expect((await world.db.soaSerial(zone)) as number).toBe(newZoneSerial()); + + expect((await adminApi.put(`${zp(zoneB)}/users/${encodeURIComponent(user2.username)}`)).status).toBe(204); + await world.db.deleteZoneRaw(zoneB); + await adminUi.openUser(user2.username); + await expect(adminUi.page.locator('#user-zones li', { hasText: zoneB })).toContainText('zone not found'); + expect((await adminUi.revokeFromUserPage(zoneB)).status, 'a delegation of a zone removed outside the application can be revoked').toBe(204); + expect((await world.db.delegations()).filter((d) => d.zone === zoneB)).toEqual([]); + + const zoneD = `${world.unique('reborn-')}.core.test.`; + const body = { name: zoneD, ns: `ns1.${zoneD}`, mbox: `hostmaster@${zoneD}`, extra_ns: [], refresh: 3600, retry: 600, expire: 604800, minttl: 300, ttl: 3600 }; + expect((await adminApi.post('/zones', body)).status).toBe(201); + expect((await adminApi.put(`${zp(zoneD)}/users/${encodeURIComponent(user2.username)}`)).status).toBe(204); + await world.db.deleteZoneRaw(zoneD); + const cmark = await world.db.auditMaxId(); + expect((await adminApi.post('/zones', body)).status).toBe(201); + expect((await world.db.delegations()).filter((d) => d.zone === zoneD), 'creating a zone deletes stale delegation rows').toEqual([]); + const zc = findAudit(await auditSince(world, cmark), 'zone_create', 201); + const removed = JSON.stringify(parsedJson(ZONE_CREATE_DELEGATIONS_IN === 'before' ? zc.before_value : [zc.before_value, zc.after_value])); + expect(removed, 'the creation audit row lists the removed delegations').toContain(user2.username); + if (REVIEW_FIXES) expect(JSON.stringify(parsedJson(zc.after_value)), 'removed delegations are not in after').not.toContain(`"username":"${user2.username}"`); + await waitForZone(world.g, zoneD, { recorder: world.recorder }); + await servedZone(world, zoneD); + }); +}); diff --git a/e2e/tests/fuzzer.spec.ts b/e2e/tests/fuzzer.spec.ts new file mode 100644 index 0000000..774d4ff --- /dev/null +++ b/e2e/tests/fuzzer.spec.ts @@ -0,0 +1,81 @@ +// 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 { intEnv } from '../harness/env'; +import { addAddress, checkZone, createZone, zoneInput } from '../harness/personas'; + +test.use({ group: 'fuzzer' }); + +test('seeded requests cover every API operation and DNS record type', async ({ world }) => { + test.setTimeout(240_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', '\u200b']; + const 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 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 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/); + } + expect(await world.db.auditSince(mark)).toHaveLength(count); + expect(await world.db.records(zone)).toHaveLength(3); + + 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); + } + 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); +}); diff --git a/e2e/tests/harness.spec.ts b/e2e/tests/harness.spec.ts new file mode 100644 index 0000000..32a5fb3 --- /dev/null +++ b/e2e/tests/harness.spec.ts @@ -0,0 +1,227 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { test, expect } from '../harness/fixtures'; +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 { parseTable, USAGE_TEXT } from '../harness/cli'; +import { rawRecord, sqlZone, canonicalContent, digData, bumpSerial, utcDay, type RawRecordInput } from '../harness/records'; +import { Rng, testSeed } from '../harness/rng'; +import { redactText, redactValue, SecretRegistry } from '../harness/secrets'; +import { expectServed, PluginModel, split255 } from '../harness/served'; +import { waitForZone, waitForZoneGone } from '../harness/dig'; +import { detectLeaks } from '../harness/global-teardown'; +import { STACK_SERVICES } from '../harness/stack'; + +test.use({ group: 'harness' }); + +test.describe('harness self-checks', () => { + test('the seeded generator is deterministic and seeds name the test', async () => { + const a = new Rng('seed-1'); + const b = new Rng('seed-1'); + const c = new Rng('seed-2'); + const seqA = Array.from({ length: 50 }, () => a.nextUint32()); + const seqB = Array.from({ length: 50 }, () => b.nextUint32()); + const seqC = Array.from({ length: 50 }, () => c.nextUint32()); + expect(seqA).toEqual(seqB); + expect(seqA).not.toEqual(seqC); + const r = new Rng('ints'); + for (let i = 0; i < 2000; i++) { + const v = r.int(-3, 7); + expect(v).toBeGreaterThanOrEqual(-3); + expect(v).toBeLessThanOrEqual(7); + } + expect(new Rng('fork').fork('x').nextUint32()).toBe(new Rng('fork/x').nextUint32()); + expect(testSeed('run', ['file', 'describe', 'title'])).toBe('run::file > describe > title'); + }); + + test('the redaction removes passwords, cookies, hashes and session tokens', async () => { + const reg = new SecretRegistry(); + reg.register('Pw-very-secret-value-1', 'password'); + const token = 'A'.repeat(20) + 'b_-' + 'c'.repeat(20); + const text = [ + 'login with Pw-very-secret-value-1 failed', + `Cookie: coredns_webui_session=${token}; Path=/`, + '{"password":"other-secret-123","current":"x"}', + 'username=bob&password=hunter2hunter2', + 'hash $argon2id$v=19$m=65536,t=3,p=2$c2FsdA$aGFzaA', + `bare ${token} token`, + ].join('\n'); + const out = reg.redact(text); + for (const leaked of ['Pw-very-secret-value-1', token, 'other-secret-123', 'hunter2hunter2', '$argon2id$']) expect(out).not.toContain(leaked); + expect(out).toContain('[REDACTED'); + const headers = redactValue({ Cookie: `coredns_webui_session=${token}`, 'set-cookie': 'x', Accept: 'application/json' }, []); + expect(headers).toEqual({ Cookie: '[REDACTED]', 'set-cookie': '[REDACTED]', Accept: 'application/json' }); + expect(redactText('nothing secret here', [])).toBe('nothing secret here'); + expect(reg.findIn('xx Pw-very-secret-value-1 yy')).toHaveLength(1); + }); + + test('the dig parser, the TXT splitting and the serial rules follow the plugin', async () => { + const sample = [ + ';; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN, id: 1', + ';; flags: qr aa; QUERY: 1, ANSWER: 0, AUTHORITY: 1, ADDITIONAL: 1', + '', + ';; AUTHORITY SECTION:', + 'example.org.\t\t3600\tIN\tSOA\tns1.example.org. hostmaster.example.org. 2026111700 3600 600 604800 300', + ].join('\n'); + const parsed = parseDig(sample); + expect(parsed.rcode).toBe('NXDOMAIN'); + expect(parsed.flags).toEqual(['qr', 'aa']); + expect(parsed.authority).toHaveLength(1); + expect(parsed.authority[0]).toMatchObject({ name: 'example.org.', ttl: 3600, type: 'SOA' }); + expect(split255('a'.repeat(254))).toHaveLength(1); + expect(split255('a'.repeat(255))).toEqual(['a'.repeat(255), '']); + expect(split255('a'.repeat(300)).map((s) => s.length)).toEqual([255, 45]); + expect(canonicalContent('MX', { preference: 10, host: 'mail.example.org.' })).toBe('{"host":"mail.example.org.","preference":10}'); + expect(digData('CAA', { flag: 0, tag: 'issue', value: 'ca.example.net' })).toBe('0 issue "ca.example.net"'); + const day = new Date(Date.UTC(2026, 10, 17, 12)); + expect(utcDay(day)).toBe(2026111700); + expect(bumpSerial(2026111700, day)).toBe(2026111701); + expect(bumpSerial(2026111799, day)).toBe(2026111800); + expect(bumpSerial(2026111500, day)).toBe(2026111700); + expect(bumpSerial(2026111805, day)).toBe(2026111806); + expect(bumpSerial(4294967295, day)).toBe(2026111700); + 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(sanitizeActor('a\u0000b\u0007c')).toBe('a b c'); + expect(sanitizeActor('x'.repeat(100))).toHaveLength(64); + }); + + test('the application under test is healthy and serves its version', async ({ world }) => { + const health = await fetch(`${world.g.baseURL}/health`); + expect(health.status).toBe(200); + expect(await health.text()).toBe('{"status":"ok"}'); + const version = await fetch(`${world.g.baseURL}/version`); + expect(version.status).toBe(200); + expect(version.headers.get('content-type')).toContain('text/html'); + }); + + test('the CLI helper runs commands through docker exec', async ({ world }) => { + const help = await world.cli.run(['help']); + expect(help.code).toBe(0); + expect(help.stdout).toBe(USAGE_TEXT); + expect(help.stderr).toBe(''); + const version = await world.cli.run(['version']); + expect(version.code).toBe(0); + expect(version.stdout).toMatch(/^coredns-web-ui \S+ \S+\n$/); + const bad = await world.cli.run(['bogus', 'secret-argument']); + expect(bad.code).toBe(2); + expect(bad.stderr.startsWith('coredns-web-ui: usage error: ')).toBe(true); + expect(bad.stderr).not.toContain('secret-argument'); + expect(bad.stderr).toContain(USAGE_TEXT); + const badCount = await world.cli.run(['audit', '0']); + expect(badCount.code).toBe(2); + const health = await world.cli.run(['healthcheck']); + expect(health.code).toBe(0); + const list = await world.cli.userList(true); + expect(list.code, list.stderr).toBe(0); + expect(parseTable(list.stdout).header).toEqual(['USERNAME', 'ROLE', 'ZONES', 'CREATED_AT', 'LAST_LOGIN_AT', 'DELETED_AT']); + expect(world.recorder.cli.length).toBeGreaterThanOrEqual(6); + }); + + test('the application connects with the least-privilege grants of the plan', async ({ world }) => { + const grants = (await world.db.query>(`SHOW GRANTS FOR '${world.g.appUser}'@'%'`)).map((r) => Object.values(r)[0]); + const on = (table: string) => grants.find((g) => g.includes(`\`${world.g.database}\`.\`${world.g.prefix}${table}\``)) ?? ''; + expect(on('records')).toMatch(/GRANT SELECT, INSERT, UPDATE, DELETE ON/); + expect(on('webui_users')).not.toMatch(/DELETE/); + expect(on('webui_audit')).not.toMatch(/UPDATE|DELETE/); + const dns = (await world.db.query>(`SHOW GRANTS FOR '${world.g.dnsUser}'@'%'`)).map((r) => Object.values(r)[0]); + expect(dns.filter((g) => g.includes(world.g.database))).toEqual([`GRANT SELECT ON \`${world.g.database}\`.\`${world.g.prefix}records\` TO \`${world.g.dnsUser}\`@\`%\``]); + for (const table of ['webui_schema', 'webui_users', 'webui_sessions', 'webui_zone_delegations', 'webui_audit']) { + expect(await world.db.tableExists(`${world.g.prefix}${table}`), `${table} created by the migrations`).toBe(true); + } + }); + + test('rows inserted through SQL are served by CoreDNS exactly as the plugin model predicts', async ({ world }) => { + test.setTimeout(120_000); + const zone = world.zoneName('sql'); + const serial = utcDay() + 7; + const long = 'v=long ' + 'x'.repeat(300); + const rows: RawRecordInput[] = [ + ...sqlZone(zone, serial), + { zone, name: 'www', type: 'A', ttl: 300, data: { ip: '192.0.2.10' } }, + { zone, name: 'www', type: 'A', ttl: 300, data: { ip: '192.0.2.11' } }, + { zone, name: 'www', type: 'AAAA', ttl: 0, data: { ip: '2001:db8::10' } }, + { zone, name: '*', type: 'A', ttl: 120, data: { ip: '192.0.2.99' } }, + { zone, name: '*.dev', type: 'TXT', ttl: 120, data: { text: 'wild dev' } }, + { zone, name: 'alias', type: 'CNAME', ttl: 60, data: { host: `alias2.${zone}` } }, + { zone, name: 'alias2', type: 'CNAME', ttl: 60, data: { host: `www.${zone}` } }, + { zone, name: '', type: 'MX', ttl: 3600, data: { host: '.', preference: 0 } }, + { zone, name: 'mail', type: 'MX', ttl: 3600, data: { host: `mx.${zone}`, preference: 10 } }, + { zone, name: '_sip._tcp', type: 'SRV', ttl: 3600, data: { priority: 0, weight: 0, port: 0, target: '.' } }, + { zone, name: '_https._tcp', type: 'SRV', ttl: 3600, data: { priority: 10, weight: 5, port: 443, target: `www.${zone}` } }, + { zone, name: '', type: 'TXT', ttl: 3600, data: { text: 'v=spf1 -all "quoted"' } }, + { zone, name: 'long', type: 'TXT', ttl: 3600, data: { text: long } }, + { zone, name: '', type: 'CAA', ttl: 3600, data: { flag: 0, tag: 'issue', value: 'ca.example.net' } }, + { zone, name: 'sub', type: 'NS', ttl: 3600, data: { host: `ns.sub.${zone}` } }, + ]; + await world.db.insertMany(rows.map(rawRecord)); + try { + await waitForZone(world.g, zone, { recorder: world.recorder }); + const stored = await world.db.records(zone); + expect(stored).toHaveLength(rows.length); + const queries: Array<[string, string]> = [ + [zone, 'SOA'], + [zone, 'NS'], + [zone, 'MX'], + [zone, 'TXT'], + [zone, 'CAA'], + [zone, 'A'], + [`www.${zone}`, 'A'], + [`www.${zone}`, 'AAAA'], + [`www.${zone}`, 'MX'], + [`anything.${zone}`, 'A'], + [`deep.er.${zone}`, 'A'], + [`x.dev.${zone}`, 'TXT'], + [`alias.${zone}`, 'A'], + [`alias.${zone}`, 'CNAME'], + [`alias2.${zone}`, 'AAAA'], + [`mail.${zone}`, 'MX'], + [`_sip._tcp.${zone}`, 'SRV'], + [`_https._tcp.${zone}`, 'SRV'], + [`long.${zone}`, 'TXT'], + [`sub.${zone}`, 'NS'], + [`missing.dev.${zone}`, 'AAAA'], + ]; + for (const [name, type] of queries) await expectServed(world.g, stored, name, type, { recorder: world.recorder, serial: name === zone && type === 'SOA' ? serial : undefined }); + const model = new PluginModel(stored); + expect(model.answer(`long.${zone}`, 'TXT').answer[0].data).toBe(`"${long.slice(0, 255)}" "${long.slice(255)}"`); + const brokenTtl = await world.db.insertRaw({ zone, name: 'broken', ttl: null, content: '{"ip":"192.0.2.50"}', record_type: 'A' }); + const brokenType = await world.db.insertRaw({ zone, name: 'lower', ttl: 60, content: '{"ip":"192.0.2.51"}', record_type: 'a' }); + const brokenJson = await world.db.insertRaw({ zone, name: 'json', ttl: 60, content: 'not json', record_type: 'TXT' }); + const after = await world.db.records(zone); + for (const [name, type, rcode] of [ + [`broken.${zone}`, 'A', 'SERVFAIL'], + [`lower.${zone}`, 'A', 'NOTIMP'], + [`json.${zone}`, 'TXT', 'SERVFAIL'], + ] as const) { + expect(new PluginModel(after).answer(name, type).rcode).toBe(rcode); + await expectServed(world.g, after, name, type, { recorder: world.recorder }); + } + expect([brokenTtl, brokenType, brokenJson].every((id) => id > 0)).toBe(true); + } finally { + await world.db.deleteZoneRaw(zone); + } + await waitForZoneGone(world.g, zone, { recorder: world.recorder }); + }); + + test('the leak detection finds and removes resources of the run', async () => { + const name = `${project()}-leakprobe`; + const image = process.env.E2E_RUNNER_IMAGE as string; + const started = await docker(['run', '--detach', '--name', name, '--label', `${RUN_LABEL}=${project()}`, '--network', 'none', '--entrypoint', 'node', image, '-e', 'setTimeout(() => {}, 120000)']); + expect(started.code, started.stderr).toBe(0); + const allowed = new Set(STACK_SERVICES.map((s) => containerName(s))); + const leaks = await detectLeaks(allowed); + expect(leaks.join('\n')).toContain(name); + const gone = await docker(['inspect', name]); + expect(gone.code).not.toBe(0); + expect(await detectLeaks(allowed)).toEqual([]); + const ps = await run('docker', ['ps', '--format', '{{.Names}}', '--filter', `label=com.docker.compose.project=${project()}`]); + for (const service of STACK_SERVICES) expect(ps.stdout).toContain(containerName(service)); + expect(Object.keys(GROUPS)).toHaveLength(9); + }); +}); diff --git a/e2e/tests/malicious.spec.ts b/e2e/tests/malicious.spec.ts new file mode 100644 index 0000000..f4c69b2 --- /dev/null +++ b/e2e/tests/malicious.spec.ts @@ -0,0 +1,160 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { test, expect } from '../harness/fixtures'; +import { up, zp } from '../harness/api'; +import { ORIGIN2_URL, runnerAddress } from '../harness/env'; +import { address, addAddress, checkZone, createZone, zoneInput } from '../harness/personas'; +import { staticHash } from '../harness/stack'; +import { begin, threeWay, zoneServed, type Rec } from '../harness/verify'; + +test.use({ group: 'malicious' }); + +test('untrusted origins and unauthorized requests cannot mutate the installation', async ({ world }) => { + const admin = await world.bootstrapAdmin(); + const api = await world.apiAs(admin); + const adminUi = await world.uiAs(admin); + const member = await world.createUser(api, 'user'); + const user = await world.apiAs(member); + const visible = world.zoneName('visible-'); + const hidden = world.zoneName('hidden-'); + const hiddenPath = await createZone(api, hidden); + const visiblePath = await createZone(api, visible); + const missingPath = zp(world.zoneName('missing-')); + expect((await api.put(`${visiblePath}${up(member.username)}`)).status).toBe(204); + const row = await addAddress(api, hiddenPath, 'private', '192.0.2.15'); + const recordsBefore = await world.db.records(); + const usersBefore = await world.db.users(); + + const csrf = world.zoneName('cross-'); + const url = `${ORIGIN2_URL}/attack.html?${new URLSearchParams({ target: world.g.baseURL, zone: csrf, form: 'logout' })}`; + const foreign = adminUi.page.waitForResponse((response) => response.url() === `${world.g.baseURL}/logout` && response.request().method() === 'POST'); + const mark = await world.db.auditMaxId(); + await adminUi.page.goto(url); + expect((await foreign).status()).toBe(403); + await adminUi.page.waitForURL('**/logout', { waitUntil: 'load' }); + expect((await api.post('/zones', zoneInput(csrf), { origin: ORIGIN2_URL })).status).toBe(403); + expect(await world.db.auditSince(mark)).toEqual([]); + await adminUi.goto('/account'); + await expect(adminUi.page.locator('.who-name')).toHaveText(admin.username); + + for (const suffix of ['', '/records', '/export', '/check']) { + const denied = await user.get(hiddenPath + suffix); + const missing = await user.get(missingPath + suffix); + expect([denied.status, denied.json]).toEqual([404, missing.json]); + expect(missing.status).toBe(404); + } + const timings: number[][] = [[], []]; + for (let i = 0; i < 12; i++) { + const paths = i % 2 === 0 ? [hiddenPath, missingPath] : [missingPath, hiddenPath]; + for (const target of paths) { + const response = await user.get(target); + expect(response.status).toBe(404); + timings[target === hiddenPath ? 0 : 1].push(response.durationMs); + } + } + const medians = timings.map((samples) => samples.sort((a, b) => a - b)[6]); + expect(Math.abs(medians[0] - medians[1]), 'no gross latency difference between hidden and missing zones').toBeLessThan(100); + for (const [method, suffix, body] of [ + ['POST', '/records', address('denied', '192.0.2.2')], + ['POST', '/records/delete', { records: [{ id: row.id, etag: row.etag }] }], + ['POST', '/import/preview', { mode: 'merge', content: 'www 300 IN A 192.0.2.4' }], + ['POST', '/import/apply', { mode: 'merge', content: '', fingerprint: 'x' }], + ] as const) { + expect((await user.raw(method, '/api/v1' + hiddenPath + suffix, { body })).status).toBe(404); + } + expect((await user.put(`${visiblePath}/records/${row.id}`, address('denied', '192.0.2.2'), { ifMatch: row.etag })).status).toBe(404); + expect((await user.delete(`${visiblePath}/records/${row.id}`, undefined, { ifMatch: row.etag })).status).toBe(404); + expect((await user.post(`${visiblePath}/records/delete`, { records: [{ id: row.id, etag: row.etag }] })).status).toBe(404); + expect((await user.get('/audit', { query: { zone: hidden } })).json.entries.every((entry: { actor: string }) => entry.actor === member.username)).toBe(true); + expect((await user.put(`${visiblePath}${up(member.username)}`)).status).toBe(403); + expect((await user.put(`${up(member.username)}/role`, { role: 'admin' })).status).toBe(403); + + const forwarded = await user.get('/account', { headers: { 'X-Forwarded-For': '203.0.113.77' } }); + expect(forwarded.status).toBe(200); + expect((await world.db.auditTail(1))[0].origin).toBe(runnerAddress()); + expect(await world.db.records()).toEqual(recordsBefore); + expect(await world.db.users()).toEqual(usersBefore); + await checkZone(world, api, hidden); +}); + +test('input validation, session integrity and rate limiting hold under repeated refusals', async ({ world }) => { + const admin = await world.bootstrapAdmin(); + const api = await world.apiAs(admin); + const ui = await world.uiAs(admin); + const zone = world.zoneName(); + const z = await createZone(api, zone); + const hash = await staticHash(world.g); + const form = { mode: 'merge', content: '' }; + const expected = await world.db.records(zone); + const text = ''; + const quote = "test'quote"; + const malformed = [text, quote, 'bad\u0000name', 'bad\tname', 'eŃ…ample']; + for (const value of malformed) { + expect((await api.post('/zones', zoneInput(value))).status).toBe(422); + expect((await api.post(`${z}/records`, address(value, '192.0.2.7'))).status).toBe(422); + expect((await api.post(`${z}/records`, address('probe', value))).status).toBe(422); + expect((await api.post('/users', { username: value, role: 'user', password: world.password() })).status).toBe(422); + } + const missing = await api.get(zp(quote)); + expect(missing.status).toBe(404); + expect((await api.get('/audit', { query: { actor: quote } })).json.entries).toEqual([]); + expect((await api.page(`/static/${hash}/css/missing.css`)).status).toBe(404); + const normalized = await api.page(`/static/${hash}/css/%2e%2e%2fmissing.css`); + expect(normalized.status).toBe(301); + expect(normalized.headers.location).toBe(`/static/${hash}/missing.css`); + expect((await api.page(normalized.headers.location)).status).toBe(404); + expect((await api.page(`/zones/${encodeURIComponent('invalid/name')}`)).status).toBe(404); + expect((await api.post(`${z}/records`, address('large', 'x'.repeat(70_000)))).status).toBe(413); + expect((await api.post(`${z}/import/preview`, { ...form, content: 'x'.repeat(2 * 1024 * 1024) })).status).toBe(413); + const nested = '['.repeat(10010) + 'null' + ']'.repeat(10010); + expect((await api.post(`${z}/records`, undefined, { raw: `{"data":${nested}}` })).status).toBe(400); + for (const content of ['$INCLUDE missing.zone\n', '$GENERATE 1-10001 fixture$ 300 IN A 192.0.2.2\n']) { + expect((await api.post(`${z}/import/preview`, { ...form, content })).status).toBe(422); + } + + const fixed = world.secrets.register('f'.repeat(43), 'unissued session cookie'); + const candidate = await world.api(); + await candidate.setCookie(fixed); + expect((await candidate.get('/account')).status).toBe(401); + expect((await candidate.login(admin.username, admin.password)).status).toBe(303); + const issued = (await candidate.cookie())!; + expect(issued).not.toBe(fixed); + await candidate.setCookie((issued[0] === 'a' ? 'b' : 'a') + issued.slice(1)); + expect((await candidate.get('/account')).status).toBe(401); + + const failed = await world.api(); + const badPassword = world.password('wrong password'); + const login = await failed.login(text, badPassword, { preserveRateLimit: true }); + expect(login.status).toBe(401); + await ui.goto('/audit'); + await ui.filterAudit({ actor: text }); + await expect(ui.page.getByText(text, { exact: true })).toBeVisible(); + await expect(ui.page.locator('#app script')).toHaveCount(0); + for (let i = 0; i < 4; i++) expect((await failed.login('unknown', badPassword, { preserveRateLimit: true })).status).toBe(401); + expect((await failed.login('unknown', badPassword, { preserveRateLimit: true })).status).toBe(429); + expect(await world.db.records(zone)).toEqual(expected); + await checkZone(world, api, zone); +}); + +test('text fields preserve literal markup and syntax delimiters', async ({ world }) => { + const admin = await world.bootstrapAdmin(); + const api = await world.apiAs(admin); + const zone = world.zoneName(); + await createZone(api, zone); + const ui = await world.uiAs(admin); + await ui.openZone(zone); + await zoneServed(world, zone); + const value = " ' ; --"; + const records: Rec[] = [ + { name: 'text', type: 'TXT', ttl: 300, data: { text: value } }, + { name: 'policy', type: 'CAA', ttl: 300, data: { flag: 0, tag: 'issue', value } }, + ]; + for (const record of records) { + const change = await begin(world, zone); + const fields = Object.fromEntries(Object.entries(record.data).map(([key, data]) => [key, String(data)])); + await ui.addRecord({ name: record.name, type: record.type, ttl: '300', fields }, { expectStatus: 201 }); + await threeWay(world, ui, zone, record, change, `literal ${record.type}`); + await expect(ui.page.locator('#records-body script')).toHaveCount(0); + } +}); diff --git a/e2e/tests/operator.spec.ts b/e2e/tests/operator.spec.ts new file mode 100644 index 0000000..c68a6e9 --- /dev/null +++ b/e2e/tests/operator.spec.ts @@ -0,0 +1,97 @@ +// 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 { intEnv, ORIGIN2_URL } from '../harness/env'; +import { address, checkZone, createZone, restartWithSessions } from '../harness/personas'; +import { begin, expectBumped, storedRow, threeWay, threeWayGone } from '../harness/verify'; +import { waitForZone } from '../harness/dig'; + +test.use({ group: 'operator' }); + +test('a long operator session preserves state and audit invariants through mixed actions', async ({ world }) => { + test.setTimeout(300_000); + const admin = await world.bootstrapAdmin(); + const api = await world.apiAs(admin); + const ui = await world.uiAs(admin); + const member = await world.createUser(api, 'user'); + const outsider = await world.apiAs(member); + const zone = world.zoneName(); + const z = await createZone(api, zone); + const recordsPath = `${z}/records`; + await waitForZone(world.g, zone, { recorder: world.recorder }); + await ui.openZone(zone); + const model = new Map>(); + const initialMark = await world.db.auditMaxId(); + const operations = ['browser-add', 'create', 'edit', 'delete', 'typo', 'cross-origin', 'random', 'private'] as const; + const rounds = Math.max(operations.length, intEnv('E2E_OPERATOR_ACTIONS', 64)); + for (let i = 0; i < rounds; i++) { + const operation = i < operations.length ? operations[i] : world.rng.pick(operations); + const name = `node-${i}`; + const ip = `192.0.2.${world.rng.int(1, 254)}`; + const item = address(name, ip); + world.recorder.fuzzCases.push({ operation, item }); + switch (operation) { + case 'browser-add': { + const change = await begin(world, zone); + await ui.addRecord({ ...item, ttl: '300', fields: { ip } }, { expectStatus: 201 }); + await threeWay(world, ui, zone, item, change, operation); + model.set(name, item); + break; + } + case 'create': { + const change = await begin(world, zone); + expect((await api.post(recordsPath, item)).status).toBe(201); + await expectBumped(world, zone, change, operation); + model.set(name, item); + await ui.openZone(zone); + break; + } + case 'edit': + case 'delete': { + if (model.size === 0) break; + const current = world.rng.pick([...model.values()]); + const match = { name: current.name, type: current.type, value: current.data.ip }; + const change = await begin(world, zone); + if (operation === 'edit') { + await ui.editRecord(match, { name: current.name, type: 'A', ttl: '301', fields: { ip } }, { expectStatus: 200 }); + const replacement = address(current.name, ip, 301); + await threeWay(world, ui, zone, replacement, change, operation); + model.set(current.name, replacement); + } else { + expect([200, 204]).toContain((await ui.deleteRecord(match)).status); + await threeWayGone(world, ui, zone, current, change, operation); + model.delete(current.name); + } + break; + } + case 'typo': + expect((await api.post(recordsPath, address(name, '2001:db8::1'))).status).toBe(422); + break; + case 'cross-origin': + expect((await api.post(recordsPath, item, { origin: ORIGIN2_URL })).status).toBe(403); + break; + case 'random': + expect((await api.post(recordsPath, { ...item, ttl: world.rng.pick([-1, '0', 'NaN', 2 ** 31]) })).status).toBe(422); + break; + case 'private': + expect((await outsider.get(recordsPath)).status).toBe(404); + expect((await outsider.put(z + up(member.username))).status).toBe(403); + break; + } + if ((i + 1) % 8 === 0 || i + 1 === rounds) { + await world.ledger.settle(); + await world.ledger.verify(`audit after ${i + 1} actions`); + const rows = await world.db.records(zone); + expect(rows).toHaveLength(model.size + 2); + for (const current of model.values()) await storedRow(world, zone, current); + await checkZone(world, api, zone); + expect((await world.db.auditSince(initialMark)).length).toBeGreaterThan(i / 2); + } + } + await restartWithSessions(world, ui); + expect((await api.get('/account')).status).toBe(200); + await ui.openZone(zone); + expect((await ui.rows()).filter(({ type }) => type === 'A')).toHaveLength(model.size); +}); diff --git a/e2e/tests/power.spec.ts b/e2e/tests/power.spec.ts new file mode 100644 index 0000000..58fcd96 --- /dev/null +++ b/e2e/tests/power.spec.ts @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { test, expect } from '../harness/fixtures'; +import { up, zp } from '../harness/api'; +import { importApplyBody } from '../harness/decisions'; +import { waitForZone } from '../harness/dig'; +import { address, addAddress, createZone, restartWithSessions, zoneInput } from '../harness/personas'; +import { begin, storedRow, threeWay } from '../harness/verify'; + +test.use({ group: 'power' }); + +test('a power user operates a large installation, with restart and edit conflicts', async ({ world }, info) => { + test.setTimeout(240_000); + const admin = await world.bootstrapAdmin(); + const api = await world.apiAs(admin); + const zones = Array.from({ length: 24 }, (_, i) => world.zoneName(`z${i}-`)); + for (const zone of zones) await createZone(api, zone); + for (let i = 0; i < 24; i++) { + const account = await world.createUser(api, 'user'); + for (const zone of [zones[i], zones[(i + 1) % zones.length]]) { + expect((await api.put(`${zp(zone)}${up(account.username)}`)).status).toBe(204); + } + } + const [large, imports] = zones; + await world.db.insertMany(Array.from({ length: 9998 }, (_, i) => ({ + zone: large, name: `seed-${String(i).padStart(4, '0')}`, ttl: 300, record_type: 'A', + content: JSON.stringify({ ip: `192.0.2.${i % 254 + 1}` }), + }))); + const first = await world.uiAs(admin); + const second = await world.uiAs(admin); + const startZones = performance.now(); + await first.page.goto('/'); + await expect(first.page.getByRole('link', { name: large, exact: true })).toBeVisible(); + const zonesMs = performance.now() - startZones; + const startZone = performance.now(); + await first.page.getByRole('link', { name: large, exact: true }).click(); + await expect(first.page.getByRole('rowheader', { name: 'seed-0000', exact: true })).toBeVisible(); + const editButton = first.page.getByRole('row', { name: /seed-0000/ }).getByRole('button', { name: /^Edit / }); + await editButton.click(); + await expect(first.page.locator('#rec-f-ip')).toHaveValue('192.0.2.1'); + const editMs = performance.now() - startZone; + await info.attach('performance.json', { + body: JSON.stringify({ zones: zones.length, records: 10000, zonesMs, editMs, budgetMs: 2000 }), + contentType: 'application/json', + }); + expect(zonesMs, 'zones page renders its links within 2 seconds').toBeLessThan(2000); + expect(editMs, '10,000-record zone is interactive within 2 seconds').toBeLessThan(2000); + await second.openZone(large); + await second.openEdit({ name: 'seed-0000', type: 'A' }); + await restartWithSessions(world, first, second); + expect((await api.get('/account')).json.username).toBe(admin.username); + const submit = async (ui: typeof first, ip: string) => { + await ui.page.fill('#rec-f-ip', ip); + const response = ui.page.waitForResponse((res) => res.request().method() === 'PUT' && /\/records\/\d+$/.test(new URL(res.url()).pathname)); + await ui.page.click('#rec-submit'); + return (await response).status(); + }; + const change = await begin(world, large); + expect(await submit(first, '192.0.2.240')).toBe(200); + expect(await submit(second, '192.0.2.241')).toBe(412); + await second.page.getByRole('button', { name: 'Reload', exact: true }).click(); + await waitForZone(world.g, large, { recorder: world.recorder }); + await threeWay(world, first, large, address('seed-0000', '192.0.2.240'), change, 'first editor wins'); + await second.expectRow({ name: 'seed-0000', type: 'A', value: '192.0.2.240' }); + expect(await world.db.recordCount()).toBe(10000 + 23 * 2); + expect(await world.db.delegations()).toHaveLength(48); + + const ip = '198.51.100.40'; + const file = Array.from({ length: 1200 }, (_, i) => `load-${i} 300 IN A ${ip}`).join('\n') + '\n'; + expect((await first.importPreview(imports, file, 'merge')).json.added).toHaveLength(1200); + const importChange = await begin(world, imports); + expect((await first.importApply()).json).toEqual(importApplyBody(1200, 0, 0)); + await first.openZone(imports); + await waitForZone(world.g, imports, { recorder: world.recorder }); + await threeWay(world, first, imports, { ...address('load-0', ip), type: 'A' }, importChange, 'large import'); + expect(await world.db.records(imports)).toHaveLength(1202); + await storedRow(world, imports, { ...address('load-1199', ip), type: 'A' }); + expect((await api.get(`${zp(imports)}/check`)).json.problems).toEqual([]); +}); + +test('a power user imports the supported types in one transaction', async ({ world }) => { + const admin = await world.bootstrapAdmin(); + const api = await world.apiAs(admin); + const zone = world.zoneName(); + const zonePath = await createZone(api, zone); + await addAddress(api, zonePath, 'www', '192.0.2.5'); + const ui = await world.uiAs(admin); + const soa = zoneInput(zone); + const entries = [ + ['@', 'SOA', `${soa.ns} ${soa.mbox} 0 3600 600 604800 300`], + ['@', 'NS', 'ns2.example.net.'], + ['www', 'AAAA', '2001:db8::50'], + ['*.alias', 'CNAME', `www.${zone}`], + ['@', 'MX', '0 .'], + ['@', 'TXT', '"test"'], + ['_tcp._svc', 'SRV', '0 0 0 .'], + ['@', 'CAA', '0 issue "ca.example.net"'], + ]; + expect((await ui.importPreview(zone, entries.map(([n, t, v]) => `${n} 300 IN ${t} ${v}\n`).join(''), 'merge')).status).toBe(200); + expect((await ui.importApply()).status).toBe(200); + expect((await world.db.records(zone)).map((row) => row.record_type).sort()).toEqual(['A', 'AAAA', 'CAA', 'CNAME', 'MX', 'NS', 'NS', 'SOA', 'SRV', 'TXT']); +}); diff --git a/e2e/tests/session.spec.ts b/e2e/tests/session.spec.ts new file mode 100644 index 0000000..c13bd63 --- /dev/null +++ b/e2e/tests/session.spec.ts @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { test, expect } from '../harness/fixtures'; +import { createZone } from '../harness/personas'; + +test.use({ group: 'session' }); + +test('an idle session expires with an open record form', async ({ world }) => { + test.setTimeout(world.g.idleTimeoutMs + 90_000); + const account = await world.bootstrapAdmin(); + const client = await world.apiAs(account); + const user = await world.uiAs(account); + const zone = world.zoneName(); + const zonePath = await createZone(client, zone); + await user.openZone(zone); + await user.page.click('#record-add'); + await user.page.selectOption('#rec-type', 'A'); + await user.page.fill('#rec-name', 'pending'); + await user.page.fill('#rec-f-ip', '192.0.2.30'); + await world.ledger.settle(); + const auditMark = await world.db.auditMaxId(); + await new Promise((resolve) => setTimeout(resolve, world.g.idleTimeoutMs + 1000)); + const refused = user.page.waitForResponse((res) => res.url().endsWith(`/api/v1${zonePath}/records`) && res.request().method() === 'POST'); + await user.page.click('#rec-submit'); + expect((await refused).status()).toBe(401); + await expect(user.page).toHaveURL(/\/login\?next=/); + expect(await world.db.auditSince(auditMark)).toEqual([]); + expect((await world.db.records(zone)).map((row) => row.record_type).sort()).toEqual(['NS', 'SOA']); + await user.login(account.username, account.password); + await expect(user.page).toHaveURL(new RegExp(zonePath.replaceAll('.', '\\.'))); +}); diff --git a/e2e/tests/stupid.spec.ts b/e2e/tests/stupid.spec.ts new file mode 100644 index 0000000..4711ede --- /dev/null +++ b/e2e/tests/stupid.spec.ts @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import { test, expect } from '../harness/fixtures'; +import type { RecordInput } from '../harness/ui'; +import { up } from '../harness/api'; +import { addAddress, checkZone, createZone } from '../harness/personas'; + +test.use({ group: 'stupid' }); + +test('operator mistakes preserve DNS, user records and delegations', async ({ world }) => { + const admin = await world.bootstrapAdmin(); + const api = await world.apiAs(admin); + const ui = await world.uiAs(admin); + const zone = world.zoneName(); + const zonePath = await createZone(api, zone); + await addAddress(api, zonePath, 'www', '192.0.2.10'); + await ui.openZone(zone); + const before = await world.db.records(zone); + const wrongRecords: RecordInput[] = [ + { name: 'v6', type: 'A', fields: { ip: '2001:db8::1' } }, + { name: 'www..', type: 'A', fields: { ip: '192.0.2.8' } }, + { name: '@', type: 'CNAME', fields: { host: 'elsewhere.example.net' } }, + { name: 'www', type: 'CNAME', fields: { host: 'elsewhere.example.net.' } }, + ]; + for (const entry of wrongRecords) { + await ui.addRecord({ ...entry, ttl: '300' }, { expectStatus: 422 }); + await expect(ui.page.locator('#record-dialog')).toBeVisible(); + await ui.page.keyboard.press('Escape'); + } + const soa = (await api.get(zonePath)).json.soa; + expect((await api.delete(`${zonePath}/records/${soa.id}`, undefined, { ifMatch: soa.etag })).status).toBe(422); + const ns = (await api.get(`${zonePath}/records`)).json.records.find((r: { type: string }) => r.type === 'NS'); + expect((await api.delete(`${zonePath}/records/${ns.id}`, undefined, { ifMatch: ns.etag })).status).toBe(422); + expect(await world.db.records(zone)).toEqual(before); + + await ui.page.click('#record-add'); + await ui.page.fill('#rec-name', `www.${zone.slice(0, -1)}`); + await expect(ui.page.locator('#rec-fqdn')).toContainText(`www.${zone}${zone}`); + await ui.page.fill('#rec-name', 'double'); + await ui.page.fill('#rec-f-ip', '192.0.2.20'); + const mark = await world.db.auditMaxId(); + const response = ui.page.waitForResponse((res) => res.url().endsWith(`/api/v1${zonePath}/records`) && res.request().method() === 'POST'); + await ui.page.locator('#rec-submit').evaluate((button: HTMLButtonElement) => { + button.click(); + button.click(); + }); + expect((await response).status()).toBe(201); + await ui.settle(); + expect((await world.db.auditSince(mark)).filter((row) => row.operation === 'record_create')).toHaveLength(1); + await checkZone(world, api, zone); + + const member = await world.createUser(api, 'user'); + expect((await api.post('/users', { username: 'short-password', role: 'user', password: world.secrets.register('tiny', 'short password') })).status).toBe(422); + await ui.openUser(member.username); + expect(await ui.deleteUserUi(member.username, 'another-user')).toBeNull(); + expect((await ui.deleteUserUi(member.username))?.status).toBe(204); + await ui.page.goBack(); + await ui.settle(); + expect((await world.db.user(member.username))?.deleted_at).not.toBeNull(); + expect((await api.post('/users', { ...member })).status).toBe(409); + expect((await api.put(`${up(admin.username)}/role`, { role: 'user' })).status).toBe(403); + expect((await api.delete(up(admin.username), { confirm: admin.username })).status).toBe(403); + expect((await api.put(`${zonePath}${up(admin.username)}`)).status).toBe(422); + await ui.openZone(zone); + expect(await ui.deleteZoneUi('wrong.example.net.')).toBeNull(); + expect((await ui.deleteZoneUi(zone))?.status).toBe(204); + await ui.page.goBack(); + await expect(ui.page.locator('#records-body tr')).toHaveCount(0); + expect((await api.get(zonePath)).status).toBe(404); + expect(await world.db.records(zone)).toEqual([]); +}); diff --git a/e2e/tsconfig.json b/e2e/tsconfig.json new file mode 100644 index 0000000..7a78b78 --- /dev/null +++ b/e2e/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "target": "ES2023", + "lib": ["ES2023", "DOM", "DOM.Iterable"], + "module": "preserve", + "moduleResolution": "bundler", + "types": ["node"], + "strict": true, + "noEmit": true, + "noUnusedLocals": true, + "noFallthroughCasesInSwitch": true, + "noImplicitOverride": true, + "skipLibCheck": true, + "esModuleInterop": true, + "isolatedModules": true, + "forceConsistentCasingInFileNames": true, + "resolveJsonModule": true + }, + "include": ["playwright.config.ts", "harness/**/*.ts", "tests/**/*.ts"] +} diff --git a/e2e/unit/conflict.test.mjs b/e2e/unit/conflict.test.mjs new file mode 100644 index 0000000..710b676 --- /dev/null +++ b/e2e/unit/conflict.test.mjs @@ -0,0 +1,52 @@ +// SPDX-License-Identifier: GPL-2.0-or-later +// Copyright (C) 2026 Bryan Joshua Pedini + +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { ApiError, handleError } from '../../static/js/common.js'; + +class Element { + children = []; + attributes = {}; + handlers = {}; + + constructor(tag) { + this.tag = tag; + } + + append(...nodes) { + this.children.push(...nodes); + } + + prepend(node) { + this.children.unshift(node); + } + + querySelector(selector) { + return this.children.find((node) => node.className?.split(' ').includes(selector.slice(1))); + } + + setAttribute(name, value) { + this.attributes[name] = value; + } + + addEventListener(name, callback) { + this.handlers[name] = callback; + } +} + +test('a stale edit puts a usable reload button inside its form', () => { + globalThis.Node = Element; + globalThis.document = { createElement: (tag) => new Element(tag) }; + const form = new Element('form'); + let reloads = 0; + handleError(new ApiError(412, { error: 'Stale record.' }), { form, reload: () => reloads++ }); + const alert = form.querySelector('.form-error'); + assert.equal(alert.attributes.role, 'alert'); + assert.equal(alert.textContent, 'Stale record. Reload to see the current data.'); + const button = alert.children.find((node) => node.tag === 'button'); + assert.equal(button.textContent, 'Reload'); + assert.equal(button.attributes.type, 'button'); + button.handlers.click(); + assert.equal(reloads, 1); +}); diff --git a/handlers_pages_test.go b/handlers_pages_test.go index 87e1b1f..502eb28 100644 --- a/handlers_pages_test.go +++ b/handlers_pages_test.go @@ -577,7 +577,7 @@ func TestRenderLogin(t *testing.T) { renderer := mustRenderer(t) data := pageData{AppName: "Test DNS", Next: "/zones/example.org."} _, body, _ := renderPage(t, renderer, "login", data) - for _, want := range []string{`action="/login"`, `method="post"`, `name="username"`, `name="password"`, `name="next" value="/zones/example.org."`} { + for _, want := range []string{``, `action="/login"`, `method="post"`, `name="username"`, `name="password"`, `name="next" value="/zones/example.org."`} { if !strings.Contains(body, want) { t.Errorf("login: missing %s", want) } diff --git a/scripts/test-e2e.sh b/scripts/test-e2e.sh new file mode 100755 index 0000000..c7c1821 --- /dev/null +++ b/scripts/test-e2e.sh @@ -0,0 +1,132 @@ +#!/bin/sh +# SPDX-License-Identifier: GPL-2.0-or-later +# Copyright (C) 2026 Bryan Joshua Pedini + +set -eu +if [ "$#" -ne 1 ]; then + echo "usage: $0 " >&2 + exit 2 +fi +cd "$(dirname "$0")/.." +image=$1 + +var_default() { + sed -n "s/^export $1=//p" vars.example | head -n 1 +} + +playwright_image=${PLAYWRIGHT_IMAGE:-$(var_default PLAYWRIGHT_IMAGE)} +mysql_image=${MYSQL_IMAGE:-$(var_default MYSQL_IMAGE)} +coredns_image=${COREDNS_IMAGE:-$(var_default COREDNS_IMAGE)} +socket=${E2E_DOCKER_SOCKET:-/var/run/docker.sock} +run_id=${E2E_RUN_ID:-$(od -An -tx1 -N5 /dev/urandom | tr -d ' \n')} +case "$run_id" in + *[!a-z0-9-]*) + echo "test-e2e: E2E_RUN_ID must contain only lowercase letters, digits and hyphens" >&2 + exit 2 + ;; +esac +project="cdwu-e2e-${run_id}" +runner_image="cdwu-e2e-runner:${run_id}" +runner="${project}-runner" +reports="e2e/reports/${project}" +pulled_images= + +E2E_PROJECT=$project +E2E_APP_IMAGE=$image +E2E_RUNNER_IMAGE=$runner_image +E2E_MYSQL_IMAGE=$mysql_image +E2E_COREDNS_IMAGE=$coredns_image +E2E_DOCKER_SOCKET=$socket +E2E_MYSQL_ROOT_PASSWORD="root-$(od -An -tx1 -N16 /dev/urandom | tr -d ' \n')" +export E2E_PROJECT E2E_APP_IMAGE E2E_RUNNER_IMAGE E2E_MYSQL_IMAGE E2E_COREDNS_IMAGE E2E_DOCKER_SOCKET E2E_MYSQL_ROOT_PASSWORD + +compose() { + docker compose --project-name "$project" --file e2e/compose.yaml --profile runner "$@" +} + +leftovers() { + { + docker ps -a --quiet --filter "label=com.docker.compose.project=${project}" + docker ps -a --quiet --filter "label=cdwu.e2e.run=${project}" + docker ps -a --quiet --filter "name=^${project}-" + } | sort -u +} + +cleanup() { + status=$1 + trap - 0 INT TERM + docker rm --force --volumes "$runner" >/dev/null 2>&1 || true + compose down --volumes --remove-orphans --timeout 30 >/dev/null 2>&1 || true + leak=0 + containers=$(leftovers) + if [ -n "$containers" ]; then + echo "test-e2e: removing leftover containers: $(echo "$containers" | tr '\n' ' ')" >&2 + echo "$containers" | xargs docker rm --force --volumes >/dev/null 2>&1 || true + leak=1 + fi + volumes=$({ docker volume ls --quiet --filter "label=com.docker.compose.project=${project}"; docker volume ls --quiet --filter "label=cdwu.e2e.run=${project}"; docker volume ls --quiet --filter "name=^${project}-"; } | sort -u) + if [ -n "$volumes" ]; then + echo "test-e2e: removing leftover volumes: $(echo "$volumes" | tr '\n' ' ')" >&2 + echo "$volumes" | xargs docker volume rm --force >/dev/null 2>&1 || true + leak=1 + fi + networks=$({ docker network ls --quiet --filter "label=com.docker.compose.project=${project}"; docker network ls --quiet --filter "label=cdwu.e2e.run=${project}"; docker network ls --quiet --filter "name=^${project}-"; } | sort -u) + if [ -n "$networks" ]; then + echo "test-e2e: removing leftover networks: $(echo "$networks" | tr '\n' ' ')" >&2 + echo "$networks" | xargs docker network rm >/dev/null 2>&1 || true + leak=1 + fi + if docker image inspect "$runner_image" >/dev/null 2>&1; then + docker image rm "$runner_image" >/dev/null || leak=1 + fi + printf '%s' "$pulled_images" | while IFS= read -r pulled; do + docker image rm "$pulled" >/dev/null || exit 1 + done || leak=1 + if [ "$leak" -ne 0 ] && [ "$status" -eq 0 ]; then + echo "test-e2e: FAIL: the run left Docker resources behind" >&2 + status=1 + fi + exit "$status" +} +if [ -e "$reports" ] || docker image inspect "$runner_image" >/dev/null 2>&1 || [ -n "$(leftovers)" ]; then + echo "test-e2e: project name already in use: ${project}" >&2 + exit 2 +fi +trap 'cleanup "$?"' 0 +trap 'exit 130' INT TERM + +if ! docker image inspect "$image" >/dev/null 2>&1; then + echo "test-e2e: image $image not found; build it first (make docker)" >&2 + exit 2 +fi +for pulled in "$playwright_image" "$mysql_image" "$coredns_image"; do + if ! docker image inspect "$pulled" >/dev/null 2>&1; then + docker pull --quiet "$pulled" >/dev/null + pulled_images="$(printf '%s%s' "$pulled_images" "$pulled") +" + fi +done + +echo "test-e2e: run ${project} against ${image}" +docker build --quiet \ + --build-arg "PLAYWRIGHT_IMAGE=${playwright_image}" \ + --label "cdwu.e2e.run=${project}" \ + --file e2e/dockerfile \ + --tag "$runner_image" \ + e2e >/dev/null + +mkdir -p e2e/reports +mkdir "$reports" +rc=0 +compose run --no-TTY --name "$runner" runner || rc=$? +if ! docker cp "${runner}:/e2e/reports/." "$reports/" >/dev/null 2>&1; then + echo "test-e2e: no reports to copy" >&2 + if [ "$rc" -eq 0 ]; then rc=1; fi +fi +docker cp "${runner}:/e2e/test-results" "$reports/test-results" >/dev/null 2>&1 || true +if [ "$rc" -eq 0 ]; then + echo "test-e2e: PASS (reports in ${reports})" +else + echo "test-e2e: FAIL with exit code ${rc} (reports, screenshots and failing seeds in ${reports})" >&2 +fi +cleanup "$rc" diff --git a/static/js/common.js b/static/js/common.js index 600c44a..9f498d2 100644 --- a/static/js/common.js +++ b/static/js/common.js @@ -247,10 +247,15 @@ export function handleError(err, options = {}) { return; } if (err.status === 412) { - toast(err.message + " Reload to see the current data.", { - kind: "error", - action: { label: "Reload", run: options.reload || (() => location.reload()) }, - }); + const message = err.message + " Reload to see the current data."; + const reload = options.reload || (() => location.reload()); + if (options.form) { + showFormError(options.form, message); + const button = h("button", { type: "button", class: "btn btn-small", text: "Reload", onclick: reload }); + options.form.querySelector(".form-error").append(" ", button); + } else { + toast(message, { kind: "error", action: { label: "Reload", run: reload } }); + } return; } if (options.form) { diff --git a/static/js/zone.js b/static/js/zone.js index 3af90c8..46d4378 100644 --- a/static/js/zone.js +++ b/static/js/zone.js @@ -259,7 +259,7 @@ function setupSoa() { reportWarnings("SOA saved.", data); await load(); } catch (err) { - handleError(err, { form, reload: load }); + handleError(err, { form, reload: () => { dialog.close(); return load(); } }); } }); }); diff --git a/templates/html/layout.html b/templates/html/layout.html index 51fe995..a84362b 100644 --- a/templates/html/layout.html +++ b/templates/html/layout.html @@ -4,6 +4,7 @@ + {{template "title" .}} - {{.AppName}}