// 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 { servedSerial, waitForZone, waitForZoneGone } from '../harness/dig'; import { runnerAddress, SESSION_COOKIE } from '../harness/env'; import { bulkDeleteBody, expectCheckErrorRowsCarryRaw, expectZoneCreateWarnings, importApplyBody, UNKNOWN_API_OPERATION, ZONE_CREATE_DELEGATIONS_IN } from '../harness/decisions'; import { READ_OPERATIONS } from '../harness/ledger'; import type { AuditRow } from '../harness/mysql'; import { newZoneSerial, uiValue, utcDay } from '../harness/records'; import type { RecordInput, Ui } from '../harness/ui'; import { expectServed } from '../harness/served'; import { asArray, begin, expectAuditChange, expectAuditRecord, expectBumped, expectNoRow, findAudit, parsedJson, served, servedZone, storedRow, threeWay, threeWayGone, type Rec, } from '../harness/verify'; test.use({ group: 'core' }); test.describe.configure({ mode: 'serial' }); let admin: Account; let adminUi: Ui; let adminApi: ApiClient; let zone = ''; let zoneB = ''; let zoneC = ''; let user1: Account; let user2: Account; let admin2: Account; async function auditSince(w: { db: { auditSince(id: number): Promise } }, mark: number): Promise { return w.db.auditSince(mark); } function input(rec: Rec, fields: Record, opts: { name?: string; ttl?: string | null } = {}): RecordInput { return { name: opts.name ?? (rec.name === '' ? '@' : rec.name), type: rec.type, ttl: opts.ttl === null ? undefined : (opts.ttl ?? String(rec.ttl)), fields }; } test.describe('core flow', () => { test('1. the stack is up and /health answers', async ({ world }) => { const health = await fetch(`${world.g.baseURL}/health`); expect(health.status).toBe(200); expect(await health.json()).toEqual({ status: 'ok' }); const anon = await world.api(); const home = await anon.page('/'); expect([302, 303]).toContain(home.status); expect(home.headers.location).toBe('/login?next=%2F'); const api = await anon.get('/zones'); expect(api.status).toBe(401); expect(api.json).toEqual({ error: expect.any(String) }); expect(await world.db.recordCount()).toBe(0); expect(await world.db.users()).toEqual([]); }); test('2. the login page shows the bootstrap command, the first admin is created through the CLI and logs in', async ({ world }) => { adminUi = await world.ui({ keep: true }); await adminUi.goto('/login'); await expect(adminUi.page.getByText('No administrator exists yet')).toBeVisible(); await expect(adminUi.page.locator('.alert-info pre code')).toContainText('/app user add admin'); const mark = await world.db.auditMaxId(); admin = await world.bootstrapAdmin(world.unique('root-')); const row = await world.db.user(admin.username); expect(row).toMatchObject({ username: admin.username, role: 'admin', deleted_at: null, last_login_at: null }); expect(row?.password_hash).toMatch(/^\$argon2id\$v=19\$m=65536,t=3,p=2\$/); const audit = findAudit(await auditSince(world, mark), 'user_create'); expect(audit).toMatchObject({ user_id: null, actor: 'cli', origin: 'local', status: null, error: null, zone: null, record_id: null, target_user_id: row?.id }); expect(audit.before_value).toBeNull(); const after = parsedJson(audit.after_value) as Record; expect(Object.keys(after).sort()).toEqual(['created_at', 'deleted_at', 'id', 'role', 'username']); expect(after).toMatchObject({ id: row?.id, username: admin.username, role: 'admin', deleted_at: null }); expect(JSON.stringify(audit)).not.toContain('argon2'); const duplicate = await world.cli.run(['user', 'add', admin.username, 'user'], `${world.password()}\n`); expect(duplicate.code).toBe(1); const usage = await world.cli.run(['user', 'add', 'x', 'superuser'], `${world.password()}\n`); expect(usage.code).toBe(2); expect(usage.stderr).toContain(USAGE_TEXT); await adminUi.goto('/login'); await expect(adminUi.page.getByText('No administrator exists yet')).toHaveCount(0); await adminUi.login(admin.username, admin.password); await expect(adminUi.page).toHaveURL(/\/$/); await expect(adminUi.page.locator('.who-name')).toHaveText(admin.username); await expect(adminUi.page.locator('nav.nav a', { hasText: 'Users' })).toBeVisible(); const cookies = await adminUi.context.cookies(); const session = cookies.find((c) => c.name === SESSION_COOKIE); expect(session).toMatchObject({ httpOnly: true, sameSite: 'Strict', path: '/', secure: false }); expect(session?.value).toMatch(/^[A-Za-z0-9_-]{43}$/); const sessions = await world.db.sessions(row?.id); expect(sessions).toHaveLength(1); expect(sessions[0].origin).toBe(runnerAddress()); expect((await world.db.user(admin.username))?.last_login_at).not.toBeNull(); adminApi = await world.apiAs(admin, { keep: true }); expect(await world.db.sessions(row?.id)).toHaveLength(2); }); test('3. a zone created in the UI is stored, audited and served after the plugin reload', async ({ world }) => { const base = world.unique('core-'); zone = `${base}.core.test.`; const typed = `${base.toUpperCase()}.Core.TEST`; const t0 = new Date(); const mark = await world.db.auditMaxId(); const created = await adminUi.createZone({ name: typed, ns: `NS1.${base}.core.test`, mbox: `dns.admin@${base}.core.test`, extraNs: [`ns2.${zone}`], ttl: '3600' }, { expectStatus: 201 }); expect(created.json).toMatchObject({ name: zone, records: 3 }); expectZoneCreateWarnings(created.json); await adminUi.expectToast(/next zone list reload/); const rows = await world.db.records(zone); expect(rows).toHaveLength(3); const serial = (await world.db.soaSerial(zone)) as number; expect([utcDay(t0), utcDay(new Date())]).toContain(serial); await storedRow(world, zone, { name: '', type: 'SOA', ttl: 3600, data: { ns: `ns1.${zone}`, MBox: `dns\\.admin.${zone}`, refresh: 3600, retry: 600, expire: 604800, minttl: 300, serial }, }); await storedRow(world, zone, { name: '', type: 'NS', ttl: 3600, data: { host: `ns1.${zone}` } }); await storedRow(world, zone, { name: '', type: 'NS', ttl: 3600, data: { host: `ns2.${zone}` } }); const audit = findAudit(await auditSince(world, mark), 'zone_create', 201); expect(audit.zone).toBe(zone); expect(audit.before_value).toBeNull(); const after = asArray(parsedJson(audit.after_value)); expect(after).toHaveLength(3); for (const r of rows) expectAuditRecord(after.find((a) => (a as { id: number }).id === r.id), r, 'zone_create after'); const table = await adminUi.zonesTable(); expect(table).toContainEqual(expect.objectContaining({ zone, records: '3', serial: String(serial) })); await waitForZone(world.g, zone, { recorder: world.recorder }); await served(world, zone, zone, 'SOA'); await served(world, zone, zone, 'NS'); await served(world, zone, `nothing-here.${zone}`, 'A'); const dup = await adminApi.post('/zones', { name: zone, ns: `ns1.${zone}`, mbox: `hostmaster@${zone}`, extra_ns: [], refresh: 3600, retry: 600, expire: 604800, minttl: 300, ttl: 3600 }); expect(dup.status).toBe(409); expect(dup.json).toEqual({ error: expect.any(String) }); }); test('4. records of all nine types are created, edited and deleted from the UI and verified three ways', async ({ world }) => { test.setTimeout(600_000); await adminUi.openZone(zone); const long = 'long-text-' + 'abcdefghij'.repeat(30); const R: Record = { ns1: { name: 'ns1', type: 'A', ttl: 3600, data: { ip: '192.0.2.1' } }, ns2: { name: 'ns2', type: 'A', ttl: 3600, data: { ip: '192.0.2.2' } }, www1: { name: 'www', type: 'A', ttl: 300, data: { ip: '192.0.2.10' } }, www2: { name: 'www', type: 'A', ttl: 300, data: { ip: '192.0.2.11' } }, www6: { name: 'www', type: 'AAAA', ttl: 300, data: { ip: '2001:db8::10' } }, web: { name: 'web', type: 'CNAME', ttl: 300, data: { host: `www.${zone}` } }, alias: { name: 'alias', type: 'CNAME', ttl: 300, data: { host: `web.${zone}` } }, mail: { name: 'mail', type: 'A', ttl: 3600, data: { ip: '192.0.2.25' } }, mx: { name: '', type: 'MX', ttl: 3600, data: { host: `mail.${zone}`, preference: 10 } }, nullmx: { name: 'nomail', type: 'MX', ttl: 3600, data: { host: '.', preference: 0 } }, spf: { name: '', type: 'TXT', ttl: 3600, data: { text: 'v=spf1 -all' } }, longtxt: { name: 'long', type: 'TXT', ttl: 3600, data: { text: long } }, sip: { name: 'sip', type: 'A', ttl: 3600, data: { ip: '192.0.2.30' } }, srv: { name: '_sip._tcp', type: 'SRV', ttl: 3600, data: { priority: 10, weight: 5, port: 5060, target: `sip.${zone}` } }, nosrv: { name: '_none._tcp', type: 'SRV', ttl: 3600, data: { priority: 0, weight: 0, port: 0, target: '.' } }, caa: { name: '', type: 'CAA', ttl: 3600, data: { flag: 0, tag: 'issue', value: 'ca.example.net' } }, iodef: { name: '', type: 'CAA', ttl: 3600, data: { flag: 128, tag: 'iodef', value: 'mailto:security@example.net' } }, sub: { name: 'sub', type: 'NS', ttl: 3600, data: { host: 'ns.example.net.' } }, wild: { name: '*', type: 'A', ttl: 0, data: { ip: '192.0.2.99' } }, wilddev: { name: '*.dev', type: 'TXT', ttl: 600, data: { text: 'wildcard dev' } }, }; const add = async (what: string, rec: Rec, inp: RecordInput, warnings: string[] = []) => { const change = await begin(world, zone); const mark = await world.db.auditMaxId(); const res = await adminUi.addRecord(inp, { expectStatus: 201 }); if (warnings.length > 0) await adminUi.expectToast(/^Warning: /); expect(res.json.record).toMatchObject({ name: rec.name, type: rec.type, ttl: rec.ttl, data: rec.data, raw: null }); expect(res.json.record.etag).toMatch(/^"[0-9a-f]{64}"$/); const codes = (res.json.warnings as Array<{ code: string; severity?: string }>).map((x) => x.code); expect(codes, `${what}: warnings`).toEqual(expect.arrayContaining(warnings)); expect((res.json.warnings as Array<{ severity?: string }>).filter((x) => x.severity === 'error'), `${what}: no error is returned as a warning`).toEqual([]); const row = await threeWay(world, adminUi, zone, rec, change, what); const audit = findAudit(await auditSince(world, mark), 'record_create', 201); expect(audit).toMatchObject({ zone, record_id: row.id, actor: admin.username, error: null }); await expectAuditChange(world, zone, audit, change, what); return row; }; const edit = async (what: string, from: Rec, to: Rec, inp: RecordInput) => { const before = await storedRow(world, zone, from); const change = await begin(world, zone); const mark = await world.db.auditMaxId(); const res = await adminUi.editRecord({ name: from.name === '' ? '@' : from.name, type: from.type, value: uiValue(from.type, from.data) }, inp, { expectStatus: 200 }); expect(res.json.record).toMatchObject({ id: before.id, name: to.name, type: to.type, ttl: to.ttl, data: to.data }); const row = await threeWay(world, adminUi, zone, to, change, what); expect(row.id, `${what}: the row is updated in place`).toBe(before.id); if (from.name !== to.name || JSON.stringify(from.data) !== JSON.stringify(to.data)) await expectNoRow(world, zone, from); const audit = findAudit(await auditSince(world, mark), 'record_update', 200); expect(audit).toMatchObject({ zone, record_id: before.id }); await expectAuditChange(world, zone, audit, change, what); return row; }; const del = async (what: string, rec: Rec) => { const before = await storedRow(world, zone, rec); const change = await begin(world, zone); const mark = await world.db.auditMaxId(); const deleted = await adminUi.deleteRecord({ name: rec.name === '' ? '@' : rec.name, type: rec.type, value: uiValue(rec.type, rec.data) }); expect(deleted.status).toBe(200); 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}` } })); const remaining: Rec = { name: 'bulk4', type: 'TXT', ttl: 300, data: { text: 'x'.repeat(256) } }; 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); } const added = await adminApi.post(`${zp(zone)}/records`, remaining); expect(added.status, added.text).toBe(201); const survivor = added.json.record; 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)); expect(res.json.warnings).toContainEqual(expect.objectContaining({ code: 'txt_split' })); await adminUi.expectToast('TXT is served in strings of at most 255 bytes'); 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 stale = await adminApi.post(`${zp(zone)}/records/delete`, { records: [{ id: survivor.id, etag: survivor.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, remaining); const done = await adminApi.post(`${zp(zone)}/records/delete`, { records: [{ id: survivor.id, etag: survivor.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)); expect(applied.json.warnings).toContainEqual(expect.objectContaining({ message: 'TXT strings were joined and the plugin will re-split them at 255 bytes' })); await expect(adminUi.page).toHaveURL(new RegExp(`/zones/${zone.replace(/\./g, '\\.')}$`)); await adminUi.expectToast('TXT strings were joined and the plugin will re-split them at 255 bytes'); 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 original = await begin(world, zoneC); const soa = original.rows.find((r) => r.record_type === 'SOA')!; const duplicateSOA = JSON.stringify({ ...JSON.parse(soa.content!), ns: 'duplicate.example.net.' }); const id = async (name: string, type: string, ttl: number | null, content: string | null, z = zoneC) => world.db.insertRaw({ zone: z, name, ttl, content, record_type: type }); const broken: Record = { ttl_null: await id('tnull', 'A', null, '{"ip":"192.0.2.60"}'), ttl_negative: await id('tneg', 'A', -5, '{"ip":"192.0.2.61"}'), content_null: await id('cnull', 'TXT', 3600, null), content_json: await id('cjson', 'TXT', 3600, 'not json'), type_unknown: await id('tunk', 'a', 3600, '{"ip":"192.0.2.62"}'), field_invalid: await id('finv', 'A', 3600, '{"ip":"999.1.1.1"}'), name_not_fqdn: await id('nfq', 'CNAME', 3600, '{"host":"target.example.net"}'), mx_priority_key: await id('mxp', 'MX', 3600, '{"host":"mail.example.net.","priority":10}'), soa_not_apex: await id('soasub', 'SOA', 3600, soa.content), soa_multiple: await id('', 'SOA', 3600, duplicateSOA), 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"}'), }; const conflictAddress = await id('both', 'A', 3600, '{"ip":"192.0.2.63"}'); const codes = Object.keys(broken); const brokenRows = await world.db.records(zoneC); for (const [name, type, rcode] of [ [`tnull.${zoneC}`, 'A', 'SERVFAIL'], [`tneg.${zoneC}`, 'A', 'SERVFAIL'], [`cnull.${zoneC}`, 'TXT', 'SERVFAIL'], [`cjson.${zoneC}`, 'TXT', 'SERVFAIL'], [`tunk.${zoneC}`, 'A', 'NOTIMP'], ] as const) { const r = await expectServed(world.g, brokenRows, name, type, { recorder: world.recorder }); expect(r.rcode, `the plugin answers ${rcode} for ${name} ${type}`).toBe(rcode); } const nodot = zoneC.slice(0, -1); const upper = zoneC.toUpperCase(); const nosoa = `${world.unique('nosoa-')}.core.test.`; const other: Record = { zone_not_fqdn: await id('nodot', 'A', 3600, '{"ip":"192.0.2.64"}', nodot), zone_case: await id('upper', 'A', 3600, '{"ip":"192.0.2.65"}', upper), }; await id('', 'NS', 3600, `{"host":"ns1.${nosoa}"}`, nosoa); await id('ns1', 'A', 3600, '{"ip":"192.0.2.67"}', nosoa); const noSOARows = await world.db.records(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 adminUi.openZone(zoneC); await adminUi.deleteRecord({ name: 'soasub', type: 'SOA' }, { expectStatus: 200 }); expect(await world.db.recordById(broken.soa_not_apex)).toBeUndefined(); await adminUi.openZone(zoneC); expect((await adminUi.problems()).map((p) => p.code)).toEqual(expect.arrayContaining(['soa_multiple', 'cname_apex', 'cname_conflict'])); await adminUi.deleteRecord({ name: '@', type: 'SOA', value: duplicateSOA }, { expectStatus: 200 }); expect(await world.db.recordById(broken.soa_multiple)).toBeUndefined(); const soaSerial = await expectBumped(world, zoneC, original, 'repair leaves one managed SOA'); expect((await world.db.records(zoneC)).filter((row) => row.record_type === 'SOA')).toEqual([ { ...soa, content: JSON.stringify({ ...JSON.parse(soa.content!), serial: soaSerial }) }, ]); await adminUi.openZone(zoneC); await adminUi.expectRow({ name: '@', type: 'SOA' }); const beforeCNAMERepair = await begin(world, zoneC); await adminUi.bulkDelete([{ name: 'both', type: 'CNAME' }, { name: '@', type: 'CNAME' }], { expectStatus: 200 }); expect(await world.db.recordById(broken.cname_apex)).toBeUndefined(); expect(await world.db.recordById(broken.cname_conflict)).toBeUndefined(); await adminUi.expectNoRow({ name: 'both', type: 'CNAME' }); await adminUi.expectNoRow({ name: '@', type: 'CNAME' }); const preservedAddress = await threeWay(world, adminUi, zoneC, { name: 'both', type: 'A', ttl: 3600, data: { ip: '192.0.2.63' } }, beforeCNAMERepair, 'repair conflicting CNAMEs'); expect(preservedAddress.id).toBe(conflictAddress); 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()).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.' } }); for (const [name, code, ip] of [['nodot', 'zone_not_fqdn', '192.0.2.64'], ['upper', 'zone_case', '192.0.2.65']]) { await repair(code, { name, type: 'A' }, { name, type: 'A', ttl: '3600', fields: { ip } }, { name, type: 'A', ttl: 3600, data: { ip } }); expect((await world.db.recordById(other[code]))?.zone).toBe(zoneC); } const after = await adminApi.get(`${zp(zoneC)}/check`); expect((after.json.problems as Array<{ severity: string; code: string }>).filter((p) => p.severity === 'error')).toEqual([]); expect((await adminUi.problems()).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/); for (const row of original.rows.filter((r) => r.id !== soa.id)) expect(await world.db.recordById(row.id)).toEqual(row); await servedZone(world, zoneC); await adminUi.openZone(nosoa); expect((await adminUi.problems()).some((p) => p.code === 'soa_missing')).toBe(true); const started = new Date(); const preview = await adminUi.importPreview(nosoa, `@ 3600 IN SOA ns1.${nosoa} hostmaster.${nosoa} 1980010100 3600 600 604800 300`, 'merge'); expect(preview.status, JSON.stringify(preview.json)).toBe(200); expect(preview.json).toMatchObject({ added: [expect.objectContaining({ name: '', type: 'SOA', ttl: 3600 })], updated: [], deleted: [] }); const applied = await adminUi.importApply(); expect(applied.status).toBe(200); expect(applied.json).toEqual(importApplyBody(1, 0, 0)); await adminUi.openZone(nosoa); await waitForZone(world.g, nosoa, { recorder: world.recorder }); const restoredSerial = (await world.db.soaSerial(nosoa))!; expect([utcDay(started), utcDay(new Date())]).toContain(restoredSerial); await threeWay(world, adminUi, nosoa, { name: '', type: 'SOA', ttl: 3600, data: { ns: `ns1.${nosoa}`, MBox: `hostmaster.${nosoa}`, serial: restoredSerial, refresh: 3600, retry: 600, expire: 604800, minttl: 300 } }, null, 'merge-import restores missing SOA'); expect((await world.db.records(nosoa)).filter((row) => row.record_type !== 'SOA')).toEqual(noSOARows); expect((await adminApi.get(`${zp(nosoa)}/check`)).json.problems).toEqual([]); expect(await adminUi.problems()).toEqual([]); await servedZone(world, nosoa); }); test('noncanonical zones and selected SOA rows can be repaired through the UI', async ({ world }) => { test.setTimeout(180_000); const api = adminApi; const zone = world.zoneName('repair-'); expect((await api.post('/zones', { name: zone, ns: `ns1.${zone}`, mbox: `hostmaster@${zone}`, extra_ns: [], refresh: 3600, retry: 600, expire: 604800, minttl: 300, ttl: 3600 })).status).toBe(201); const ui = adminUi; await waitForZone(world.g, zone, { recorder: world.recorder }); const baseline = await world.db.records(zone); for (const [name, storedZone, code, ip] of [ ['nodot', zone.slice(0, -1), 'zone_not_fqdn', '192.0.2.71'], ['upper', zone.toUpperCase(), 'zone_case', '192.0.2.72'], ]) { const id = await world.db.insertRaw({ zone: storedZone, name, ttl: 300, content: JSON.stringify({ ip }), record_type: 'A' }); await ui.openZone(zone); expect((await ui.problems()).some((p) => p.code === code)).toBe(true); await ui.editRecord({ name, type: 'A' }, { name, type: 'A', ttl: '300', fields: { ip } }, { expectStatus: 200 }); expect((await world.db.recordById(id))?.zone).toBe(zone); await threeWay(world, ui, zone, { name, type: 'A', ttl: 300, data: { ip } }, null, code); } const soa = baseline.find((row) => row.record_type === 'SOA')!; const duplicateContent = JSON.stringify({ ...JSON.parse(soa.content!), ns: 'duplicate.example.net.' }); const duplicateId = await world.db.insertRaw({ zone, name: '', ttl: soa.ttl, content: duplicateContent, record_type: 'SOA' }); await ui.openZone(zone); expect((await ui.problems()).some((p) => p.code === 'soa_multiple')).toBe(true); await ui.deleteRecord({ name: '@', type: 'SOA', value: duplicateContent }, { expectStatus: 200 }); expect(await world.db.recordById(duplicateId)).toBeUndefined(); expect(await world.db.recordById(soa.id)).toBeDefined(); await ui.expectRow({ name: '@', type: 'SOA' }); await servedZone(world, zone); const subId = await world.db.insertRaw({ zone, name: 'sub', ttl: soa.ttl, content: soa.content, record_type: 'SOA' }); await ui.openZone(zone); expect((await ui.problems()).some((p) => p.code === 'soa_not_apex')).toBe(true); expect((await ui.problems()).some((p) => p.code === 'soa_multiple')).toBe(true); await ui.deleteRecord({ name: '@', type: 'SOA' }, { expectStatus: 200 }); expect(await world.db.recordById(soa.id)).toBeUndefined(); await ui.expectNoRow({ name: '@', type: 'SOA' }); const row = await ui.row({ name: 'sub', type: 'SOA' }); await row.getByRole('button', { name: /^Edit / }).click(); await expect(ui.page.locator('#soa-dialog')).toBeVisible(); for (const [key, value] of Object.entries({ ns: `ns1.${zone}`, mbox: `hostmaster.${zone}`, ttl: '3600', refresh: '3600', retry: '600', expire: '604800', minttl: '300' })) await ui.page.fill(`#soa-${key}`, value); const response = ui.page.waitForResponse((r) => r.request().method() === 'PUT' && new URL(r.url()).pathname.endsWith('/soa')); await ui.page.locator('#soa-form button[type=submit]').click(); expect((await response).status()).toBe(200); await ui.settle(); expect((await world.db.recordById(subId))?.name).toBe(''); await ui.expectRow({ name: '@', type: 'SOA' }); expect((await api.get(`${zp(zone)}/check`)).json.problems.filter((p: { severity: string }) => p.severity === 'error')).toEqual([]); for (const original of baseline.filter((r) => r.id !== soa.id)) expect(await world.db.recordById(original.id)).toEqual(original); await servedZone(world, zone); }); test('a dynamic SOA serial is shown, served as Unix time and replaced by a managed serial through the UI', async ({ world }) => { test.setTimeout(180_000); const ui = adminUi; const dz = world.zoneName('dynamic-'); expect((await adminApi.post('/zones', { name: dz, ns: `ns1.${dz}`, mbox: `hostmaster@${dz}`, extra_ns: [], refresh: 3600, retry: 600, expire: 604800, minttl: 300, ttl: 3600 })).status).toBe(201); await waitForZone(world.g, dz, { recorder: world.recorder }); const managedSoa = (await world.db.records(dz)).find((r) => r.record_type === 'SOA')!; const { serial: createdSerial, ...timers } = JSON.parse(managedSoa.content!) as Record; expect(createdSerial).toEqual(expect.any(Number)); await world.db.updateRaw(managedSoa.id, { content: JSON.stringify(timers) }); expect(await world.db.soaSerial(dz), 'the SOA has no serial key').toBeNull(); await ui.openZone(dz); expect((await ui.soaSummary()).Serial).toBe('dynamic (Unix time)'); await expect(ui.page.locator('#soa-managed')).toBeVisible(); await ui.expectRow({ name: '@', type: 'SOA', value: uiValue('SOA', { ...timers, serial: 'dynamic (Unix time)' }) }); expect(await ui.problems()).toContainEqual({ severity: 'warning', code: 'soa_dynamic_serial', where: '(@ SOA)' }); expect((await adminApi.get(`${zp(dz)}/check`)).json.problems).toContainEqual(expect.objectContaining({ severity: 'warning', code: 'soa_dynamic_serial', id: managedSoa.id, name: '', type: 'SOA' })); await ui.goto('/'); expect(await ui.zonesTable()).toContainEqual(expect.objectContaining({ zone: dz, serial: 'dynamic' })); const before = Math.floor(Date.now() / 1000); const unixSerial = await servedSerial(world.g, dz, { recorder: world.recorder }); const after = Math.floor(Date.now() / 1000); expect(unixSerial, 'CoreDNS serves the Unix time as the dynamic serial').toBeGreaterThanOrEqual(before - 5); expect(unixSerial).toBeLessThanOrEqual(after + 5); await served(world, dz, dz, 'SOA', 'dynamic serial'); await ui.openZone(dz); const rowsBefore = await world.db.records(dz); const mark = await world.db.auditMaxId(); const t0 = new Date(); const done = ui.page.waitForResponse((r) => new URL(r.url()).pathname.endsWith('/soa') && r.request().method() === 'PUT'); await ui.page.click('#soa-managed'); expect((await done).status()).toBe(200); await ui.settle(); await ui.expectToast('The zone now uses a managed serial.'); const serial = (await world.db.soaSerial(dz)) as number; expect([utcDay(t0), utcDay(new Date())], 'the managed serial is YYYYMMDD00 of today').toContain(serial); const soaRow = await storedRow(world, dz, { name: '', type: 'SOA', ttl: managedSoa.ttl as number, data: { ...timers, serial } }); expect(soaRow.id).toBe(managedSoa.id); for (const r of rowsBefore.filter((x) => x.id !== managedSoa.id)) expect(await world.db.recordById(r.id)).toEqual(r); await expect.poll(async () => (await ui.soaSummary()).Serial).toBe(String(serial)); await expect(ui.page.locator('#soa-managed')).toBeHidden(); await ui.expectRow({ name: '@', type: 'SOA', value: uiValue('SOA', { ...timers, serial }) }); expect((await ui.problems()).some((p) => p.code === 'soa_dynamic_serial')).toBe(false); await served(world, dz, dz, 'SOA', 'managed serial in the answer'); await served(world, dz, `missing.${dz}`, 'TXT', 'managed serial in the authority section'); expect(await servedSerial(world.g, dz, { recorder: world.recorder })).toBe(serial); const audits = (await auditSince(world, mark)).filter((r) => r.operation === 'soa_update'); expect(audits, 'exactly one soa_update audit row').toHaveLength(1); expect(audits[0]).toMatchObject({ actor: admin.username, status: 200, error: null, zone: dz, record_id: managedSoa.id, target_user_id: null }); const dynamicRow = rowsBefore.find((r) => r.id === managedSoa.id)!; expectAuditRecord(parsedJson(audits[0].before_value), dynamicRow, 'soa_update before'); expectAuditRecord(parsedJson(audits[0].after_value), soaRow, 'soa_update after'); const contentOf = (v: unknown) => { const c = (parsedJson(v) as { content: unknown }).content; return (typeof c === 'string' ? JSON.parse(c) : c) as Record; }; expect(contentOf(audits[0].before_value)).not.toHaveProperty('serial'); expect(contentOf(audits[0].after_value)).toHaveProperty('serial', serial); const rec: Rec = { name: 'after-managed', type: 'TXT', ttl: 300, data: { text: 'managed serial bump' } }; const change = await begin(world, dz); await ui.addRecord({ name: rec.name, type: 'TXT', ttl: '300', fields: { text: 'managed serial bump' } }, { expectStatus: 201 }); await threeWay(world, ui, dz, rec, change, 'the first change after the managed serial'); const next = (await world.db.soaSerial(dz)) as number; if (utcDay(new Date()) === serial) expect(next, 'the next change of the day is YYYYMMDD01').toBe(serial + 1); expect(await servedSerial(world.g, dz, { recorder: world.recorder })).toBe(next); await expect.poll(async () => (await ui.soaSummary()).Serial).toBe(String(next)); expect((await adminApi.get(`${zp(dz)}/check`)).json.problems.filter((p: { severity: string }) => p.severity === 'error')).toEqual([]); await servedZone(world, dz); }); test('7. users and delegation: roles, zone visibility, revocation, promotion, deletion and the last active admin', async ({ world }) => { test.setTimeout(600_000); zoneB = `${world.unique('second-')}.core.test.`; 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); const u2id = (await world.db.user(user2.username))?.id as number; const hashBefore = (await world.db.user(user2.username))?.password_hash; expect((await u2api.get('/account')).status, 'the API session of the user is open').toBe(200); expect((await world.db.sessions(u2id)).length, 'the user has an API and a browser session').toBe(2); const setPassword = world.password('password of bob set by an admin'); await adminUi.openUser(user2.username); const pwMark = await world.db.auditMaxId(); const pwSet = await adminUi.setPasswordUi(setPassword); expect(pwSet.status, JSON.stringify(pwSet.json)).toBe(204); await adminUi.expectToast(`Password set. The sessions of ${user2.username} ended.`); const pwAudits = (await auditSince(world, pwMark)).filter((r) => r.operation === 'user_password'); expect(pwAudits, 'exactly one user_password audit row').toHaveLength(1); const pwAudit = pwAudits[0]; expect(pwAudit).toMatchObject({ user_id: rootId, actor: admin.username, origin: runnerAddress(), status: 204, error: null, zone: null, record_id: null, target_user_id: u2id }); for (const value of [pwAudit.before_value, pwAudit.after_value]) { const snapshot = parsedJson(value) as Record; expect(Object.keys(snapshot).sort()).toEqual(['created_at', 'deleted_at', 'id', 'role', 'username']); expect(snapshot).toMatchObject({ id: u2id, username: user2.username, role: 'user', deleted_at: null }); } expect(JSON.stringify(pwAudit)).not.toMatch(/argon2|password_hash/); expect(JSON.stringify(pwAudit)).not.toContain(setPassword); expect(await world.db.sessions(u2id), 'setting a password ends every session of the user').toEqual([]); const u2row = await world.db.user(user2.username); expect(u2row?.password_hash).toMatch(/^\$argon2id\$v=19\$m=65536,t=3,p=2\$/); expect(u2row?.password_hash, 'the stored hash changed').not.toBe(hashBefore); expect((await u2api.get('/account')).status, 'the open API session of the user ended').toBe(401); u2api.forgetSession(); await u2ui.page.reload(); await expect(u2ui.page).toHaveURL(/\/login/); u2ui.sessionEnded(); const oldPassword = await (await world.api()).login(user2.username, user2.password); expect(oldPassword.status, 'the previous password is refused').toBe(401); user2 = { ...user2, password: setPassword }; const u2next = await world.apiAs(user2); expect((await u2next.get('/account')).status, 'the password set by the admin works').toBe(200); await adminUi.openZone(zoneB); expect((await adminUi.delegateFromZonePage(user2.username)).status).toBe(204); await expect.poll(() => adminUi.zoneUsers()).toEqual([user2.username]); expect((await u2next.get(zp(zoneB))).status, 'the delegation from the zone page applies').toBe(200); const revokeMark = await world.db.auditMaxId(); expect((await adminUi.revokeFromZonePage(user2.username)).status).toBe(204); await expect.poll(() => adminUi.zoneUsers()).toEqual([]); const revokes = (await auditSince(world, revokeMark)).filter((r) => r.operation === 'delegation_revoke'); expect(revokes, 'exactly one delegation_revoke audit row').toHaveLength(1); expect(revokes[0]).toMatchObject({ user_id: rootId, actor: admin.username, status: 204, error: null, zone: zoneB, record_id: null, target_user_id: u2id }); expect(parsedJson(revokes[0].before_value)).toEqual({ zone: zoneB, username: user2.username }); expect(revokes[0].after_value).toBeNull(); expect((await world.db.delegations()).filter((d) => d.zone === zoneB && d.user_id === u2id), 'the delegation row is gone').toEqual([]); expect((await u2next.get(zp(zoneB))).status, 'a revocation from the zone page takes effect on the next request').toBe(404); await adminUi.openUser(admin.username); await expect(adminUi.page.locator('#user-self')).toBeVisible(); await expect(adminUi.page.locator('#role-form')).toHaveCount(0); for (const [m, p, b] of [ ['PUT', `${up(admin.username)}/role`, { role: 'user' }], ['PUT', `${up(admin.username)}/password`, { password: world.password() }], ['DELETE', up(admin.username), { confirm: admin.username }], ] as Array<[string, string, unknown]>) { expect((await adminApi.raw(m, `/api/v1${p}`, { body: b })).status, `an admin cannot ${m} ${p} on their own account`).toBe(403); } const auditOfU1 = (await world.db.auditSince(0)).filter((row) => row.user_id === u1id); await adminUi.openUser(user1.username); expect(await adminUi.deleteUserUi(user1.username, user1.username.slice(0, -1)), 'a wrong username keeps the delete button disabled').toBeNull(); expect((await adminApi.delete(up(user1.username), { confirm: 'someone-else' })).status).toBe(422); const delMark = await world.db.auditMaxId(); const deleted = await adminUi.deleteUserUi(user1.username); expect(deleted?.status).toBe(204); const delAudit = findAudit(await auditSince(world, delMark), 'user_delete', 204); expect(delAudit.target_user_id).toBe(u1id); expect(parsedJson(delAudit.before_value)).toMatchObject({ username: user1.username, deleted_at: null }); expect((parsedJson(delAudit.after_value) as { deleted_at: string | null }).deleted_at).not.toBeNull(); expect((await u1api.get('/account')).status, 'the session of a deleted user ended').toBe(401); u1api.forgetSession(); expect(await world.db.sessions(u1id)).toEqual([]); await u1ui.page.reload(); await expect(u1ui.page).toHaveURL(/\/login/); u1ui.sessionEnded(); const refused = await (await world.api()).login(user1.username, user1.password); expect(refused.status, 'a deleted user cannot log in').toBe(401); expect(refused.text).toContain('invalid username or password'); const u1row = await world.db.user(user1.username); expect(u1row?.deleted_at).not.toBeNull(); expect(u1row?.password_hash).toMatch(/^\$argon2id\$/); expect((await world.db.delegations()).filter((d) => d.user_id === u1id).map((d) => d.zone), 'delegations of a deleted user stay').toEqual([zone]); const retainedAudit = (await world.db.auditSince(0)).filter((row) => row.user_id === u1id && auditOfU1.some((old) => old.id === row.id)); expect(retainedAudit, 'audit rows of a deleted user stay').toEqual(auditOfU1); expect((await adminApi.get(`${zp(zone)}/users`)).json.users, 'zone pages do not list deleted users').toEqual([]); const reuse = await adminApi.post('/users', { username: user1.username, role: 'user', password: world.password() }); expect(reuse.status, 'the username of a deleted user stays taken').toBe(409); expect((await world.cli.userAdd(user1.username, 'user', world.password())).code).toBe(1); expect((await adminApi.put(`${up(user1.username)}/role`, { role: 'admin' })).status, 'a deleted user cannot be changed').toBe(404); expect((await adminApi.put(`${zp(zone)}/users/${encodeURIComponent(user1.username)}`)).status, 'a deleted user cannot receive delegations').toBe(404); expect((await adminApi.get(up(user1.username))).json).toMatchObject({ username: user1.username, deleted_at: expect.any(String) }); await adminUi.goto('/users'); expect((await adminUi.usersTable()).map((u) => u.username)).not.toContain(user1.username); await adminUi.page.check('#show-deleted'); await adminUi.settle(); await expect.poll(async () => (await adminUi.usersTable()).find((u) => u.username === user1.username)?.state).toMatch(/^deleted /); await adminUi.openUser(user1.username); await expect(adminUi.page.locator('#user-readonly')).toBeVisible(); await expect(adminUi.page.locator('#user-controls')).toBeHidden(); const cliList = parseTable((await world.cli.userList()).stdout); expect(cliList.rows.map((r) => r[0])).not.toContain(user1.username); const cliAll = parseTable((await world.cli.userList(true)).stdout); const u1cli = cliAll.rows.find((r) => r[0] === user1.username); expect(u1cli?.[5]).not.toBe('-'); expect(u1cli?.[2]).toBe('1'); expect((await world.cli.userRole(admin2.username, 'user')).code, 'demoting the second admin leaves one').toBe(0); expect((await world.cli.userRole(admin.username, 'user')).code, 'the last active admin cannot be demoted').toBe(1); expect((await world.cli.userDelete(admin.username)).code, 'the last active admin cannot be deleted').toBe(1); expect((await world.db.user(admin.username))?.role).toBe('admin'); expect((await world.cli.userRole(admin2.username, 'admin')).code).toBe(0); const a2api = await world.apiAs(admin2); const [r1, r2] = await Promise.all([adminApi.put(`${up(admin2.username)}/role`, { role: 'user' }), a2api.put(`${up(admin.username)}/role`, { role: 'user' })]); const statuses = [r1.status, r2.status]; expect(statuses.filter((s) => s === 204).length, `exactly one demotion succeeds (${statuses})`).toBe(1); expect(statuses.filter((s) => s !== 204).every((s) => s === 403 || s === 409)).toBe(true); const active = (await world.db.users()).filter((u) => u.role === 'admin' && u.deleted_at === null); expect(active, 'one active admin remains').toHaveLength(1); if (active[0].username !== admin.username) expect((await world.cli.userRole(admin.username, 'admin')).code).toBe(0); expect((await world.cli.userRole(admin2.username, 'admin')).code).toBe(0); expect((await adminApi.get('/users')).status).toBe(200); }); test('8. audit: the page, the API and the CLI show the rows; users see only their rows', async ({ world }) => { test.setTimeout(300_000); const all = await world.db.auditSince(0); expect(all.length).toBeGreaterThan(100); for (const r of all) { expect(r.time).toMatch(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d\.\d{6}Z$/); if (r.actor === 'cli') expect(r).toMatchObject({ origin: 'local', status: null, user_id: null }); else expect(r.origin).toBe(runnerAddress()); } const api = await adminApi.get('/audit', { query: { limit: 200 } }); expect(api.status).toBe(200); const entries = api.json.entries as Array<{ id: number; time: string; actor: string; operation: string; status: number | null; zone: string | null; record_id: number | null; target_user: string | null; error: string | null }>; expect(entries.length).toBe(200); for (let i = 1; i < entries.length; i++) expect(entries[i].id).toBeLessThan(entries[i - 1].id); const byId = new Map((await world.db.auditSince(0)).map((r) => [r.id, r])); for (const e of entries) { const row = byId.get(e.id); if (!row) continue; expect({ actor: e.actor, operation: e.operation, status: e.status, zone: e.zone, record_id: e.record_id, error: e.error }).toEqual({ actor: row.actor, operation: row.operation, status: row.status, zone: row.zone, record_id: row.record_id, error: row.error, }); } const page2 = await adminApi.get('/audit', { query: { limit: 5, before_id: api.json.next_before_id } }); expect(page2.json.entries).toHaveLength(5); expect(page2.json.entries[0].id).toBeLessThan(entries[entries.length - 1].id); for (const [filter, ok] of [ [{ zone }, (e: { zone: string | null }) => e.zone === zone], [{ operation: 'record_update' }, (e: { operation: string }) => e.operation === 'record_update'], [{ kind: 'read' }, (e: { operation: string }) => READ_OPERATIONS.has(e.operation)], [{ kind: 'change' }, (e: { operation: string }) => !READ_OPERATIONS.has(e.operation)], [{ outcome: 'error' }, (e: { status: number | null }) => e.status !== null && e.status >= 400], [{ outcome: 'success' }, (e: { status: number | null }) => e.status === null || e.status < 400], [{ actor: user2.username }, (e: { actor: string }) => e.actor === user2.username], ] as Array<[Record, (e: never) => boolean]>) { const r = await adminApi.get('/audit', { query: { ...filter, limit: 200 } }); expect(r.status).toBe(200); expect(r.json.entries.length, `filter ${JSON.stringify(filter)} returns rows`).toBeGreaterThan(0); for (const e of r.json.entries) expect(ok(e as never), `filter ${JSON.stringify(filter)}: ${JSON.stringify(e)}`).toBe(true); } for (const bad of [{ limit: '0' }, { limit: '201' }, { kind: 'both' }, { outcome: 'maybe' }, { before_id: 'x' }]) { expect((await adminApi.get('/audit', { query: bad })).status, `invalid audit filter ${JSON.stringify(bad)}`).toBe(400); } await adminUi.goto('/audit'); const uiRows = await adminUi.auditRows(); expect(uiRows.length).toBeGreaterThan(0); await adminUi.filterAudit({ zone, operation: 'record_update' }); const filtered = await adminUi.auditRows(); expect(filtered.length).toBeGreaterThan(0); for (const r of filtered) { expect(r.operation).toBe('record_update'); expect(r.target).toContain(zone); } const toggle = adminUi.page.locator('#audit-body button[aria-expanded]').first(); await toggle.click(); await expect(toggle).toHaveAttribute('aria-expanded', 'true'); const diff = adminUi.page.locator('#audit-body tr.detail-row:not([hidden]) table.diff'); await expect(diff).toBeVisible(); await expect(diff.locator('tr.diff-changed').first()).toBeVisible(); await adminUi.filterAudit({ zone: '', operation: '', outcome: 'error' }); for (const r of await adminUi.auditRows()) expect(Number(r.status.slice(0, 3))).toBeGreaterThanOrEqual(400); const before = await world.db.auditMaxId(); const cli = await world.cli.audit(30); expect(cli.code, cli.stderr).toBe(0); expect(await world.db.auditMaxId(), 'the audit CLI only reads').toBe(before); const table = parseTable(cli.stdout); expect(table.header).toEqual(['TIME', 'ACTOR', 'ORIGIN', 'OPERATION', 'STATUS', 'ZONE', 'RECORD', 'TARGET_USER']); expect(table.rows).toHaveLength(30); const tail = await world.db.auditTail(30); table.rows.forEach((r, i) => { expect(r[1]).toBe(tail[i].actor); expect(r[3]).toBe(tail[i].operation); expect(r[4]).toBe(tail[i].status === null ? '-' : String(tail[i].status)); expect(r[5]).toBe(tail[i].zone ?? '-'); expect(r[6]).toBe(tail[i].record_id === null ? '-' : String(tail[i].record_id)); }); const dflt = await world.cli.audit(); expect(parseTable(dflt.stdout).rows).toHaveLength(20); expect((await adminApi.put(`${zp(zone)}/users/${encodeURIComponent(user2.username)}`)).status).toBe(204); const u2api = await world.apiAs(user2); const seen = await u2api.get('/audit', { query: { limit: 200 } }); expect(seen.status).toBe(200); expect(seen.json.entries.length).toBeGreaterThan(0); for (const e of seen.json.entries) expect(e.zone === zone || e.actor === user2.username, `user visibility: ${JSON.stringify(e)}`).toBe(true); expect(seen.json.entries.some((e: { actor: string }) => e.actor === admin.username), 'a user sees the rows of a delegated zone made by others').toBe(true); const otherZone = await u2api.get('/audit', { query: { zone: zoneC } }); expect(otherZone.json.entries.filter((e: { actor: string }) => e.actor !== user2.username)).toEqual([]); const u2ui = await world.uiAs(user2); await u2ui.goto('/audit'); for (const r of await u2ui.auditRows()) expect(r.actor === user2.username || r.target.includes(zone)).toBe(true); const unknownMark = await world.db.auditMaxId(); const adminRow = await world.db.user(admin.username); const anon = await world.api(); const unknownPath = await adminApi.get('/no-such-route'); expect(unknownPath.status).toBe(404); const unknownMethod = await adminApi.raw('PATCH', '/api/v1/zones'); expect(unknownMethod.status).toBe(405); const anonymousUnknown = await anon.get('/no-such-route'); const unknownRows = (await auditSince(world, unknownMark)).filter((r) => r.operation === UNKNOWN_API_OPERATION); expect([0, 2]).toContain(unknownRows.length); expect(anonymousUnknown.status).toBe(unknownRows.length === 2 ? 401 : 404); if (unknownRows.length === 2) { expect(unknownRows.map((r) => r.status)).toEqual([404, 405]); for (const r of unknownRows) { expect(r).toMatchObject({ user_id: adminRow?.id, actor: admin.username, origin: runnerAddress(), zone: null, record_id: null, target_user_id: null, before_value: null, after_value: null }); expect(typeof r.error).toBe('string'); } expect(JSON.stringify(unknownRows)).not.toContain('no-such-route/'); } expect((await auditSince(world, unknownMark)).filter((r) => r.actor !== admin.username || r.operation !== UNKNOWN_API_OPERATION)).toEqual([]); }); test('9. password change, logout, session end and deletion of a zone with its delegations', async ({ world }) => { test.setTimeout(300_000); const u2ui = await world.uiAs(user2); const other = await world.apiAs(user2); await u2ui.goto('/account'); await expect(u2ui.page.locator('#account-zones li')).toHaveText([zone]); const wrong = await u2ui.changeOwnPasswordUi('not-the-current-password', world.password()); expect(wrong?.status).toBe(422); expect(wrong?.json.fields).toHaveProperty('current'); await expect(u2ui.page.locator('#pw-current + .field-error')).toBeVisible(); const short = await u2ui.changeOwnPasswordUi(user2.password, 'short'); expect(short?.status).toBe(422); expect(short?.json.fields).toHaveProperty('password'); expect(await u2ui.changeOwnPasswordUi(user2.password, world.password(), 'different-repeat-value')).toBeNull(); await expect(u2ui.page.locator('#pw-repeat + .field-error')).toHaveText('The two passwords differ.'); const newPassword = world.password('new password of bob'); const mark = await world.db.auditMaxId(); const ok = await u2ui.changeOwnPasswordUi(user2.password, newPassword); expect(ok?.status).toBe(204); await u2ui.expectToast('Password changed. Your other sessions ended.'); const pc = findAudit(await auditSince(world, mark), 'password_change', 204); expect(JSON.stringify(pc)).not.toContain(newPassword); expect((await other.get('/account')).status, 'a password change ends the other sessions').toBe(401); other.forgetSession(); await u2ui.goto('/account'); await expect(u2ui.page).toHaveURL(/\/account$/); const oldLogin = await (await world.api()).login(user2.username, user2.password); expect(oldLogin.status).toBe(401); user2 = { ...user2, password: newPassword }; const u2id = (await world.db.user(user2.username))?.id as number; const cookie = (await u2ui.cookie()) as string; const sessionsBefore = (await world.db.sessions(u2id)).length; await u2ui.logout(); await expect(u2ui.page).toHaveURL(/\/login/); expect((await world.db.sessions(u2id)).length, 'logout deletes the session row').toBe(sessionsBefore - 1); const replay = await world.api(); await replay.setCookie(cookie); expect((await replay.get('/account')).status, 'a logged out cookie is refused').toBe(401); for (const s of await world.db.sessions()) { const ts = (v: string) => Date.parse(`${v.replace(' ', 'T')}Z`); expect(ts(s.expires_at) - ts(s.created_at), 'sessions end at the latest SESSION_MAX_AGE after login').toBeLessThanOrEqual(12 * 3600_000 + 1000); } const rowsBefore = await world.db.records(zone); await adminUi.openZone(zone); expect(await adminUi.zoneUsers()).toEqual([user2.username]); expect(await adminUi.deleteZoneUi(`wrong-${zone}`), 'a wrong zone name keeps the delete button disabled').toBeNull(); expect((await adminApi.delete(zp(zone), { confirm: zoneB })).status).toBe(422); const dmark = await world.db.auditMaxId(); const deleted = await adminUi.deleteZoneUi(zone.slice(0, -1).toUpperCase()); expect(deleted?.status).toBe(204); await adminUi.expectToast(/stops serving it after its next zone list reload/); expect(await world.db.records(zone)).toEqual([]); expect((await world.db.delegations()).filter((d) => d.zone === zone && d.user_id === u2id)).toEqual([]); const za = findAudit(await auditSince(world, dmark), 'zone_delete', 204); const zaBefore = JSON.stringify(parsedJson(za.before_value)); for (const r of rowsBefore) expect(zaBefore).toContain(`"id":${r.id}`); expect(zaBefore).toContain(user2.username); expect(za.after_value).toBeNull(); await waitForZoneGone(world.g, zone, { recorder: world.recorder }); const u2api = await world.apiAs(user2); expect((await u2api.get(zp(zone))).status).toBe(404); const again = await adminApi.post('/zones', { name: zone, ns: `ns1.${zone}`, mbox: `hostmaster@${zone}`, extra_ns: [], refresh: 3600, retry: 600, expire: 604800, minttl: 300, ttl: 3600 }); expect(again.status).toBe(201); expect((await adminApi.get(`${zp(zone)}/users`)).json.users, 'a zone created again starts without delegations').toEqual([]); expect((await world.db.soaSerial(zone)) as number).toBe(newZoneSerial()); expect((await adminApi.put(`${zp(zoneB)}/users/${encodeURIComponent(user2.username)}`)).status).toBe(204); await world.db.deleteZoneRaw(zoneB); await adminUi.openUser(user2.username); await expect(adminUi.page.locator('#user-zones li', { hasText: zoneB })).toContainText('zone not found'); expect((await adminUi.revokeFromUserPage(zoneB)).status, 'a delegation of a zone removed outside the application can be revoked').toBe(204); expect((await world.db.delegations()).filter((d) => d.zone === zoneB)).toEqual([]); const zoneD = `${world.unique('reborn-')}.core.test.`; const body = { name: zoneD, ns: `ns1.${zoneD}`, mbox: `hostmaster@${zoneD}`, extra_ns: [], refresh: 3600, retry: 600, expire: 604800, minttl: 300, ttl: 3600 }; expect((await adminApi.post('/zones', body)).status).toBe(201); expect((await adminApi.put(`${zp(zoneD)}/users/${encodeURIComponent(user2.username)}`)).status).toBe(204); await world.db.deleteZoneRaw(zoneD); const cmark = await world.db.auditMaxId(); expect((await adminApi.post('/zones', body)).status).toBe(201); expect((await world.db.delegations()).filter((d) => d.zone === zoneD), 'creating a zone deletes stale delegation rows').toEqual([]); const zc = findAudit(await auditSince(world, cmark), 'zone_create', 201); const removed = JSON.stringify(parsedJson(ZONE_CREATE_DELEGATIONS_IN === 'before' ? zc.before_value : [zc.before_value, zc.after_value])); expect(removed, 'the creation audit row lists the removed delegations').toContain(user2.username); 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); }); });