// 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 { decodedApiPath, 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(decodedApiPath('/api/v1/zones/a%20b.org/records?limit=1')).toBe('/zones/a b.org/records'); expect(matchRoute('GET', decodedApiPath('/api/v1/users/%3Cscript%3Ex%3C%2Fscript%3E'))).toBeNull(); expect(matchRoute('PUT', decodedApiPath('/api/v1/zones/x.org/users/%27%20OR%20%271%27'))).toEqual({ operation: 'delegation_grant', zone: 'x.org.', recordId: null, targetUser: "' OR '1'" }); expect(sanitizeActor('a\u0000b\u0007c')).toBe('a b c'); expect(sanitizeActor('x'.repeat(100))).toHaveLength(64); }); test('the application under test is healthy and serves its version', async ({ world }) => { const health = await fetch(`${world.g.baseURL}/health`); expect(health.status).toBe(200); expect(await health.text()).toBe('{"status":"ok"}'); const version = await fetch(`${world.g.baseURL}/version`); expect(version.status).toBe(200); expect(version.headers.get('content-type')).toContain('text/html'); }); test('the CLI helper runs commands through docker exec', async ({ world }) => { const help = await world.cli.run(['help']); expect(help.code).toBe(0); expect(help.stdout).toBe(USAGE_TEXT); expect(help.stderr).toBe(''); const version = await world.cli.run(['version']); expect(version.code).toBe(0); expect(version.stdout).toMatch(/^coredns-web-ui \S+ \S+\n$/); const bad = await world.cli.run(['bogus', 'secret-argument']); expect(bad.code).toBe(2); expect(bad.stderr.startsWith('coredns-web-ui: usage error: ')).toBe(true); expect(bad.stderr).not.toContain('secret-argument'); expect(bad.stderr).toContain(USAGE_TEXT); const badCount = await world.cli.run(['audit', '0']); expect(badCount.code).toBe(2); const health = await world.cli.run(['healthcheck']); expect(health.code).toBe(0); const list = await world.cli.userList(true); expect(list.code, list.stderr).toBe(0); expect(parseTable(list.stdout).header).toEqual(['USERNAME', 'ROLE', 'ZONES', 'CREATED_AT', 'LAST_LOGIN_AT', 'DELETED_AT']); expect(world.recorder.cli.length).toBeGreaterThanOrEqual(6); }); test('the application connects with the least-privilege grants of the plan', async ({ world }) => { const grants = (await world.db.query>(`SHOW GRANTS FOR '${world.g.appUser}'@'%'`)).map((r) => Object.values(r)[0]); const on = (table: string) => grants.find((g) => g.includes(`\`${world.g.database}\`.\`${world.g.prefix}${table}\``)) ?? ''; expect(on('records')).toMatch(/GRANT SELECT, INSERT, UPDATE, DELETE ON/); expect(on('webui_users')).not.toMatch(/DELETE/); expect(on('webui_audit')).not.toMatch(/UPDATE|DELETE/); const dns = (await world.db.query>(`SHOW GRANTS FOR '${world.g.dnsUser}'@'%'`)).map((r) => Object.values(r)[0]); expect(dns.filter((g) => g.includes(world.g.database))).toEqual([`GRANT SELECT ON \`${world.g.database}\`.\`${world.g.prefix}records\` TO \`${world.g.dnsUser}\`@\`%\``]); for (const table of ['webui_schema', 'webui_users', 'webui_sessions', 'webui_zone_delegations', 'webui_audit']) { expect(await world.db.tableExists(`${world.g.prefix}${table}`), `${table} created by the migrations`).toBe(true); } }); test('rows inserted through SQL are served by CoreDNS exactly as the plugin model predicts', async ({ world }) => { test.setTimeout(120_000); const zone = world.zoneName('sql'); const serial = utcDay() + 7; const long = 'v=long ' + 'x'.repeat(300); const rows: RawRecordInput[] = [ ...sqlZone(zone, serial), { zone, name: 'www', type: 'A', ttl: 300, data: { ip: '192.0.2.10' } }, { zone, name: 'www', type: 'A', ttl: 300, data: { ip: '192.0.2.11' } }, { zone, name: 'www', type: 'AAAA', ttl: 0, data: { ip: '2001:db8::10' } }, { zone, name: '*', type: 'A', ttl: 120, data: { ip: '192.0.2.99' } }, { zone, name: '*.dev', type: 'TXT', ttl: 120, data: { text: 'wild dev' } }, { zone, name: 'alias', type: 'CNAME', ttl: 60, data: { host: `alias2.${zone}` } }, { zone, name: 'alias2', type: 'CNAME', ttl: 60, data: { host: `www.${zone}` } }, { zone, name: '', type: 'MX', ttl: 3600, data: { host: '.', preference: 0 } }, { zone, name: 'mail', type: 'MX', ttl: 3600, data: { host: `mx.${zone}`, preference: 10 } }, { zone, name: '_sip._tcp', type: 'SRV', ttl: 3600, data: { priority: 0, weight: 0, port: 0, target: '.' } }, { zone, name: '_https._tcp', type: 'SRV', ttl: 3600, data: { priority: 10, weight: 5, port: 443, target: `www.${zone}` } }, { zone, name: '', type: 'TXT', ttl: 3600, data: { text: 'v=spf1 -all "quoted"' } }, { zone, name: 'long', type: 'TXT', ttl: 3600, data: { text: long } }, { zone, name: '', type: 'CAA', ttl: 3600, data: { flag: 0, tag: 'issue', value: 'ca.example.net' } }, { zone, name: 'sub', type: 'NS', ttl: 3600, data: { host: `ns.sub.${zone}` } }, ]; await world.db.insertMany(rows.map(rawRecord)); try { await waitForZone(world.g, zone, { recorder: world.recorder }); const stored = await world.db.records(zone); expect(stored).toHaveLength(rows.length); const queries: Array<[string, string]> = [ [zone, 'SOA'], [zone, 'NS'], [zone, 'MX'], [zone, 'TXT'], [zone, 'CAA'], [zone, 'A'], [`www.${zone}`, 'A'], [`www.${zone}`, 'AAAA'], [`www.${zone}`, 'MX'], [`anything.${zone}`, 'A'], [`deep.er.${zone}`, 'A'], [`x.dev.${zone}`, 'TXT'], [`alias.${zone}`, 'A'], [`alias.${zone}`, 'CNAME'], [`alias2.${zone}`, 'AAAA'], [`mail.${zone}`, 'MX'], [`_sip._tcp.${zone}`, 'SRV'], [`_https._tcp.${zone}`, 'SRV'], [`long.${zone}`, 'TXT'], [`sub.${zone}`, 'NS'], [`missing.dev.${zone}`, 'AAAA'], ]; for (const [name, type] of queries) await expectServed(world.g, stored, name, type, { recorder: world.recorder, serial: name === zone && type === 'SOA' ? serial : undefined }); const model = new PluginModel(stored); expect(model.answer(`long.${zone}`, 'TXT').answer[0].data).toBe(`"${long.slice(0, 255)}" "${long.slice(255)}"`); const brokenTtl = await world.db.insertRaw({ zone, name: 'broken', ttl: null, content: '{"ip":"192.0.2.50"}', record_type: 'A' }); const brokenType = await world.db.insertRaw({ zone, name: 'lower', ttl: 60, content: '{"ip":"192.0.2.51"}', record_type: 'a' }); const brokenJson = await world.db.insertRaw({ zone, name: 'json', ttl: 60, content: 'not json', record_type: 'TXT' }); const after = await world.db.records(zone); for (const [name, type, rcode] of [ [`broken.${zone}`, 'A', 'SERVFAIL'], [`lower.${zone}`, 'A', 'NOTIMP'], [`json.${zone}`, 'TXT', 'SERVFAIL'], ] as const) { expect(new PluginModel(after).answer(name, type).rcode).toBe(rcode); await expectServed(world.g, after, name, type, { recorder: world.recorder }); } expect([brokenTtl, brokenType, brokenJson].every((id) => id > 0)).toBe(true); } finally { await world.db.deleteZoneRaw(zone); } await waitForZoneGone(world.g, zone, { recorder: world.recorder }); }); test('the leak detection finds and removes resources of the run', async () => { const name = `${project()}-leakprobe`; const sentinel = `${project()}-unlabeled`; const image = process.env.E2E_RUNNER_IMAGE as string; const volume = await docker(['volume', 'create', sentinel]); expect(volume.code, volume.stderr).toBe(0); try { 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 preserved = await docker(['volume', 'inspect', sentinel]); expect(preserved.code, preserved.stderr).toBe(0); } finally { const removed = await docker(['volume', 'rm', sentinel]); expect(removed.code, removed.stderr).toBe(0); } 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); }); });