- 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
292 lines
10 KiB
TypeScript
292 lines
10 KiB
TypeScript
// 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);
|
|
}
|