test(e2e): add playwright harness and test stack
- test(e2e): add playwright harness and test stack - test(e2e): add core flow - fix(ui): preserve same-origin browser form submissions - fix(ui): offer reload inside stale edit dialogs - test(e2e): add persona session and accessibility suites - test(e2e): preserve per-run artifacts and clean pulled images - test(e2e): verify import and audit state across navigation - test(e2e): tighten verification helpers and persona checks - test(e2e): bound response body reads of the browser observer - test: recover review compatibility assertions - test: stabilize audit and user flow assertions
This commit is contained in:
1 parent
a7ba01fc77
commit
57a005c19f
48 files changed
+6239
-6
No files matched your search
@@ -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<string, string>;
|
||||
text: string;
|
||||
json: any;
|
||||
etag: string | null;
|
||||
durationMs: number;
|
||||
setCookie: string;
|
||||
}
|
||||
|
||||
export interface RequestOptions {
|
||||
body?: unknown;
|
||||
raw?: string | Buffer;
|
||||
contentType?: string | null;
|
||||
headers?: Record<string, string>;
|
||||
query?: Record<string, string | number | undefined>;
|
||||
ifMatch?: string;
|
||||
origin?: 'same' | 'none' | string;
|
||||
audit?: 'auto' | 'none' | 'optional';
|
||||
timeoutMs?: number;
|
||||
}
|
||||
|
||||
export interface LoginHooks {
|
||||
beforeLogin(username: string): Promise<void>;
|
||||
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<ApiClient> {
|
||||
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<string | undefined> {
|
||||
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<void> {
|
||||
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<string, string>; expectStatus?: number; preserveRateLimit?: boolean } = {}): Promise<ApiResult> {
|
||||
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<ApiResult> {
|
||||
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<ApiResult> {
|
||||
return this.raw('GET', path, { ...opts, audit: 'none' });
|
||||
}
|
||||
|
||||
async raw(method: string, path: string, opts: RequestOptions = {}): Promise<ApiResult> {
|
||||
const headers: Record<string, string> = { ...(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<ApiResult> {
|
||||
return this.raw('GET', `/api/v1${path}`, opts);
|
||||
}
|
||||
|
||||
post(path: string, body?: unknown, opts: RequestOptions = {}): Promise<ApiResult> {
|
||||
return this.raw('POST', `/api/v1${path}`, { body, ...opts });
|
||||
}
|
||||
|
||||
put(path: string, body?: unknown, opts: RequestOptions = {}): Promise<ApiResult> {
|
||||
return this.raw('PUT', `/api/v1${path}`, { body, ...opts });
|
||||
}
|
||||
|
||||
delete(path: string, body?: unknown, opts: RequestOptions = {}): Promise<ApiResult> {
|
||||
return this.raw('DELETE', `/api/v1${path}`, { body, ...opts });
|
||||
}
|
||||
|
||||
forgetSession(): void {
|
||||
this.username = '';
|
||||
}
|
||||
|
||||
private async wrap(res: APIResponse, started: number): Promise<ApiResult> {
|
||||
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<string, string>, 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<void> {
|
||||
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)}`;
|
||||
}
|
||||
@@ -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 <username> <role> create a user with role admin or user, reading the password from stdin
|
||||
coredns-web-ui user passwd <username> set the password of a user, reading it from stdin
|
||||
coredns-web-ui user role <username> <role> set the role of a user to admin or user
|
||||
coredns-web-ui user delete <username> 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<CliResult> {
|
||||
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<CliResult> {
|
||||
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<CliResult> {
|
||||
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<CliResult> {
|
||||
this.secrets.register(password, `password of ${username}`);
|
||||
return this.change('user_password', username, ['user', 'passwd', username], `${password}\n`);
|
||||
}
|
||||
|
||||
userRole(username: string, role: string): Promise<CliResult> {
|
||||
return this.change('user_role', username, ['user', 'role', username, role]);
|
||||
}
|
||||
|
||||
userDelete(username: string): Promise<CliResult> {
|
||||
return this.change('user_delete', username, ['user', 'delete', username]);
|
||||
}
|
||||
|
||||
userList(all = false): Promise<CliResult> {
|
||||
return this.run(all ? ['user', 'list', 'all'] : ['user', 'list']);
|
||||
}
|
||||
|
||||
check(zone?: string): Promise<CliResult> {
|
||||
return this.run(zone === undefined ? ['check'] : ['check', zone]);
|
||||
}
|
||||
|
||||
audit(n?: number | string): Promise<CliResult> {
|
||||
return this.run(n === undefined ? ['audit'] : ['audit', String(n)]);
|
||||
}
|
||||
}
|
||||
@@ -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<string, unknown> {
|
||||
return expect.objectContaining({ deleted });
|
||||
}
|
||||
|
||||
export function importApplyBody(added: number, updated: number, deleted: number): Record<string, unknown> {
|
||||
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));
|
||||
});
|
||||
}
|
||||
@@ -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<DigResult> {
|
||||
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<DigResult> {
|
||||
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<DigResult> {
|
||||
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<number> {
|
||||
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);
|
||||
}
|
||||
@@ -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<ProcResult> {
|
||||
return run('docker', args, opts);
|
||||
}
|
||||
|
||||
export function dockerOk(args: readonly string[], opts: ProcOptions = {}): Promise<ProcResult> {
|
||||
return runOk('docker', args, opts);
|
||||
}
|
||||
|
||||
export function compose(args: readonly string[], opts: ProcOptions = {}): Promise<ProcResult> {
|
||||
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<ProjectResources> {
|
||||
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<string>();
|
||||
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<string>();
|
||||
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);
|
||||
}
|
||||
@@ -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> = {}): 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<Record<GroupName, GroupConfig>> = {
|
||||
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');
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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<string, number>();
|
||||
private readonly testClients = new Set<ApiClient>();
|
||||
private readonly testUis = new Set<Ui>();
|
||||
private readonly keptClients = new Set<ApiClient>();
|
||||
private readonly keptUis = new Set<Ui>();
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<ApiClient> {
|
||||
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<Ui> {
|
||||
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<ApiClient> {
|
||||
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<Ui> {
|
||||
const u = await this.ui(opts);
|
||||
await u.login(account.username, account.password);
|
||||
return u;
|
||||
}
|
||||
|
||||
async bootstrapAdmin(username = this.unique('root')): Promise<Account> {
|
||||
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<Account> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
const red = <T>(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<string[]> {
|
||||
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<GroupName, World>;
|
||||
}
|
||||
|
||||
export const test = base.extend<Options & Fixtures, WorkerFixtures>({
|
||||
group: ['harness', { option: true }],
|
||||
|
||||
worlds: [
|
||||
async ({}, use) => {
|
||||
installStdioRedaction();
|
||||
const m = new Map<GroupName, World>();
|
||||
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 };
|
||||
@@ -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<void> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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<string> = new Set()): Promise<string[]> {
|
||||
const leaks: string[] = [];
|
||||
const resources = await projectResources();
|
||||
const self = runnerContainer();
|
||||
const runnerNetworks = new Set<string>();
|
||||
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<void> {
|
||||
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`);
|
||||
}
|
||||
@@ -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<readonly [string, RegExp, string, Target[]]> = [
|
||||
['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<Promise<unknown>>();
|
||||
private skipped = 0;
|
||||
|
||||
constructor(
|
||||
private readonly db: Db,
|
||||
private readonly secrets: SecretRegistry,
|
||||
) {}
|
||||
|
||||
async start(): Promise<void> {
|
||||
await this.settle();
|
||||
this.mark = await this.db.auditMaxId();
|
||||
this.expected = [];
|
||||
}
|
||||
|
||||
track<T>(p: Promise<T>): Promise<T> {
|
||||
this.pending.add(p);
|
||||
p.finally(() => this.pending.delete(p)).catch(() => undefined);
|
||||
return p;
|
||||
}
|
||||
|
||||
async settle(): Promise<void> {
|
||||
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<AuditRow[]> {
|
||||
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<number, string>();
|
||||
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<number>();
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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<string, string> = {
|
||||
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<void> {
|
||||
const conn = await mysql.createConnection({ ...connectionOptions(), multipleStatements: true });
|
||||
try {
|
||||
for (const name of GROUP_NAMES) {
|
||||
const [rows] = await conn.query<mysql.RowDataPacket[]>('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<void> {
|
||||
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<T = mysql.RowDataPacket>(sql: string, params: unknown[] = []): Promise<T[]> {
|
||||
const [rows] = await this.pool.query(sql, params);
|
||||
return rows as T[];
|
||||
}
|
||||
|
||||
async exec(sql: string, params: unknown[] = []): Promise<mysql.ResultSetHeader> {
|
||||
const [r] = await this.pool.query<mysql.ResultSetHeader>(sql, params);
|
||||
return r;
|
||||
}
|
||||
|
||||
async records(zone?: string): Promise<RecordRow[]> {
|
||||
const where = zone === undefined ? '' : 'WHERE `zone` = BINARY ?';
|
||||
return this.query<RecordRow>(`SELECT id, zone, name, ttl, content, record_type FROM ${this.t.records} ${where} ORDER BY id`, zone === undefined ? [] : [zone]);
|
||||
}
|
||||
|
||||
async recordById(id: number): Promise<RecordRow | undefined> {
|
||||
const rows = await this.query<RecordRow>(`SELECT id, zone, name, ttl, content, record_type FROM ${this.t.records} WHERE id = ?`, [id]);
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
async zones(): Promise<string[]> {
|
||||
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<number> {
|
||||
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<number> {
|
||||
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<void> {
|
||||
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<RawRecord>): Promise<void> {
|
||||
const keys = Object.keys(fields) as Array<keyof RawRecord>;
|
||||
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<void> {
|
||||
await this.exec(`DELETE FROM ${this.t.records} WHERE zone = BINARY ?`, [zone]);
|
||||
}
|
||||
|
||||
async soaContent(zone: string): Promise<Record<string, unknown> | null> {
|
||||
const rows = await this.query<RecordRow>(`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<string, unknown>;
|
||||
}
|
||||
|
||||
async soaSerial(zone: string): Promise<number | null> {
|
||||
const soa = await this.soaContent(zone);
|
||||
return soa && typeof soa.serial === 'number' ? soa.serial : null;
|
||||
}
|
||||
|
||||
async users(): Promise<UserRow[]> {
|
||||
return this.query<UserRow>(`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<UserRow | undefined> {
|
||||
const rows = await this.query<UserRow>(
|
||||
`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<number | null> {
|
||||
return (await this.user(username))?.id ?? null;
|
||||
}
|
||||
|
||||
async usernameById(id: number): Promise<string | null> {
|
||||
const rows = await this.query<{ username: string }>(`SELECT username FROM ${this.t.users} WHERE id = ?`, [id]);
|
||||
return rows[0]?.username ?? null;
|
||||
}
|
||||
|
||||
async delegations(): Promise<DelegationRow[]> {
|
||||
return this.query<DelegationRow>(
|
||||
`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<SessionRow[]> {
|
||||
const where = userId === undefined ? '' : 'WHERE user_id = ?';
|
||||
return this.query<SessionRow>(`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<boolean> {
|
||||
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<void> {
|
||||
await this.exec(`DELETE FROM ${this.t.sessions} WHERE user_id = ?`, [userId]);
|
||||
}
|
||||
|
||||
async auditMaxId(): Promise<number> {
|
||||
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<AuditRow[]> {
|
||||
return this.query<AuditRow>(
|
||||
`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<AuditRow[]> {
|
||||
const rows = await this.query<AuditRow>(
|
||||
`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<number> {
|
||||
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<boolean> {
|
||||
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<string> {
|
||||
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<void> {
|
||||
await this.pool.end();
|
||||
}
|
||||
}
|
||||
@@ -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<string> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<ProcResult> {
|
||||
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<ProcResult> {
|
||||
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<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
export async function pollUntil<T>(what: string, fn: () => Promise<T | undefined | null | false>, timeoutMs = 30_000, intervalMs = 250): Promise<T> {
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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<string, string>;
|
||||
requestBodyBytes: number;
|
||||
status: number;
|
||||
responseHeaders: Record<string, string>;
|
||||
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<T>(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<CliRecord, 'at'>): void {
|
||||
push(this.cli, { at: new Date().toISOString(), ...r, stdout: clip(r.stdout), stderr: clip(r.stderr) });
|
||||
}
|
||||
|
||||
addHttp(r: Omit<HttpRecord, 'at'>): 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;
|
||||
}
|
||||
}
|
||||
@@ -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<Record<RecordType, readonly string[]>> = {
|
||||
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<string, string | number>;
|
||||
|
||||
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<Record<'refresh' | 'retry' | 'expire' | 'minttl', number>> = {}): 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' } },
|
||||
];
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<T>(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<T>(items: ReadonlyArray<readonly [T, number]>): 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<T>(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<T>(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(' > ')}`;
|
||||
}
|
||||
@@ -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 = /(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{43}(?![A-Za-z0-9_-])/g;
|
||||
const COOKIE_PAIR = new RegExp(`(${SESSION_COOKIE}=)([^;\\s"'&]*)`, 'g');
|
||||
const JSON_SECRET = /("(?:password|current|repeat)"\s*:\s*)"(?:[^"\\]|\\.)*"/g;
|
||||
const FORM_SECRET = /((?:^|[?&\s])(?:password|current)=)[^&\s]*/g;
|
||||
const HASH = /\$argon2id\$[^\s"']+/g;
|
||||
|
||||
export function redactionFor(secret: string): string {
|
||||
return `[REDACTED:${crypto.createHash('sha256').update(secret, 'utf8').digest('hex').slice(0, 8)}]`;
|
||||
}
|
||||
|
||||
export function redactText(text: string, secrets: Iterable<string>): 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<T>(value: T, secrets: Iterable<string>): 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<string, unknown> = {};
|
||||
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<string, string>();
|
||||
|
||||
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<T>(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<string>();
|
||||
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];
|
||||
}
|
||||
@@ -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<string, unknown>;
|
||||
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<string, unknown>;
|
||||
} 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<string, unknown>;
|
||||
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<string>();
|
||||
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<string>();
|
||||
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<ModelRR | DigRR>, 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<ModelRR | DigRR>): 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<DigResult> {
|
||||
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);
|
||||
}
|
||||
@@ -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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
await compose(['rm', '--stop', '--force', '--volumes', ...STACK_SERVICES], { timeoutMs: 180_000 });
|
||||
}
|
||||
|
||||
export async function restartApp(group: GroupConfig): Promise<void> {
|
||||
await dockerOk(['restart', '--time', '25', containerName(group.service)], { timeoutMs: 120_000 });
|
||||
await waitHealth(group);
|
||||
}
|
||||
|
||||
export async function appLogs(group: GroupConfig): Promise<string> {
|
||||
const r = await docker(['logs', containerName(group.service)], { timeoutMs: 60_000 });
|
||||
return r.stdout + r.stderr;
|
||||
}
|
||||
|
||||
export async function staticHash(group: GroupConfig): Promise<string> {
|
||||
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];
|
||||
}
|
||||
@@ -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<string, string>;
|
||||
}
|
||||
|
||||
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<any> {
|
||||
try {
|
||||
return await res.json();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
async function bounded<T>(p: Promise<T>, fallback: T, ms = 5000): Promise<T> {
|
||||
let timer: NodeJS.Timeout | undefined;
|
||||
const limit = new Promise<T>((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<Ui> {
|
||||
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<void> {
|
||||
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<string, string>);
|
||||
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<string, string>)),
|
||||
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<void> {
|
||||
await this.page.waitForLoadState('networkidle');
|
||||
await this.deps.ledger?.settle();
|
||||
}
|
||||
|
||||
async goto(path: string): Promise<Response | null> {
|
||||
const res = await this.page.goto(path);
|
||||
await this.settle();
|
||||
return res;
|
||||
}
|
||||
|
||||
async login(username: string, password: string, opts: { expectSuccess?: boolean } = {}): Promise<void> {
|
||||
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<void> {
|
||||
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<string | undefined> {
|
||||
return (await this.context.cookies()).find((c) => c.name === SESSION_COOKIE)?.value;
|
||||
}
|
||||
|
||||
async toasts(): Promise<string[]> {
|
||||
return this.page.locator('#toasts .toast-text').allTextContents();
|
||||
}
|
||||
|
||||
async expectToast(text: string | RegExp): Promise<void> {
|
||||
await expect(this.page.locator('#toasts .toast-text').filter({ hasText: text }).first()).toBeVisible();
|
||||
}
|
||||
|
||||
async createZone(z: ZoneInput, opts: { expectStatus?: number } = {}): Promise<UiResponse> {
|
||||
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<void> {
|
||||
await this.goto(`/zones/${encodeURIComponent(zone)}`);
|
||||
await expect(this.page.locator('#records-status')).not.toHaveText('Loading records...');
|
||||
}
|
||||
|
||||
async rows(): Promise<UiRow[]> {
|
||||
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<number> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<UiResponse> {
|
||||
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<UiResponse> {
|
||||
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<void> {
|
||||
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<UiResponse> {
|
||||
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<void> {
|
||||
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<UiResponse> {
|
||||
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<void> {
|
||||
const row = await this.row(m);
|
||||
await row.locator('input[type=checkbox]').check();
|
||||
}
|
||||
|
||||
async bulkDelete(matches: RowMatch[], opts: { expectStatus?: number } = {}): Promise<UiResponse> {
|
||||
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<Record<'ns' | 'mbox' | 'refresh' | 'retry' | 'expire' | 'minttl' | 'ttl', string>>, opts: { expectStatus?: number } = {}): Promise<UiResponse> {
|
||||
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<Record<string, string>> {
|
||||
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<Record<string, string>> {
|
||||
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<void>): Promise<UiResponse> {
|
||||
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<UiResponse> {
|
||||
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<Array<{ username: string; role: string; zones: string; created: string; lastLogin: string; state: string }>> {
|
||||
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<void> {
|
||||
await this.goto(`/users/${encodeURIComponent(username)}`);
|
||||
await expect(this.page.locator('#user-status')).toHaveText('');
|
||||
}
|
||||
|
||||
async setRoleUi(role: 'admin' | 'user'): Promise<UiResponse> {
|
||||
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<UiResponse> {
|
||||
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<UiResponse> {
|
||||
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<UiResponse> {
|
||||
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<string[]> {
|
||||
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<UiResponse | null> {
|
||||
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<string[]> {
|
||||
return this.page.$$eval('#zone-users li .mono', (els) => els.map((e) => (e.textContent ?? '').trim()));
|
||||
}
|
||||
|
||||
async delegateFromZonePage(username: string): Promise<UiResponse> {
|
||||
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<UiResponse> {
|
||||
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<UiResponse | null> {
|
||||
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<UiResponse | null> {
|
||||
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<Array<{ zone: string; records: string; serial: string; problems: string }>> {
|
||||
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<Array<{ severity: string; code: string; where: string }>> {
|
||||
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<Array<{ time: string; actor: string; origin: string; operation: string; status: string; target: string }>> {
|
||||
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<Record<'zone' | 'actor' | 'operation' | 'kind' | 'outcome', string>>): Promise<void> {
|
||||
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<UiResponse> {
|
||||
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<string> {
|
||||
return ((await this.page.locator('#import-summary').textContent()) ?? '').replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
|
||||
async importApply(): Promise<UiResponse> {
|
||||
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<string> {
|
||||
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<void> {
|
||||
await this.deps.ledger?.settle();
|
||||
await this.context.close();
|
||||
}
|
||||
}
|
||||
@@ -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<Change> {
|
||||
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<Rec, 'name' | 'type'>): 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<RecordRow> {
|
||||
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<void> {
|
||||
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<number> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
const rows = await w.db.records(zone);
|
||||
const seen = new Set<string>();
|
||||
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<RecordRow> {
|
||||
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<void> {
|
||||
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<void> {
|
||||
await waitForZone(w.g, zone, { recorder: w.recorder });
|
||||
}
|
||||
|
||||
export function recordJson(row: RecordRow): Record<string, unknown> {
|
||||
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<string, unknown>;
|
||||
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<void> {
|
||||
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;
|
||||
}
|
||||
Reference in new issue
Block a user