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