Files
coredns-web-ui/e2e/tests/malicious.spec.ts
T
bryanpedini 57a005c19f test(e2e): add playwright harness and test stack
- test(e2e): add playwright harness and test stack
- test(e2e): add core flow
- fix(ui): preserve same-origin browser form submissions
- fix(ui): offer reload inside stale edit dialogs
- test(e2e): add persona session and accessibility suites
- test(e2e): preserve per-run artifacts and clean pulled images
- test(e2e): verify import and audit state across navigation
- test(e2e): tighten verification helpers and persona checks
- test(e2e): bound response body reads of the browser observer
- test: recover review compatibility assertions
- test: stabilize audit and user flow assertions
2026-11-19 15:46:12 +01:00

161 lines
8.8 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright (C) 2026 Bryan Joshua Pedini
import { test, expect } from '../harness/fixtures';
import { up, zp } from '../harness/api';
import { ORIGIN2_URL, runnerAddress } from '../harness/env';
import { address, addAddress, checkZone, createZone, zoneInput } from '../harness/personas';
import { staticHash } from '../harness/stack';
import { begin, threeWay, zoneServed, type Rec } from '../harness/verify';
test.use({ group: 'malicious' });
test('untrusted origins and unauthorized requests cannot mutate the installation', async ({ world }) => {
const admin = await world.bootstrapAdmin();
const api = await world.apiAs(admin);
const adminUi = await world.uiAs(admin);
const member = await world.createUser(api, 'user');
const user = await world.apiAs(member);
const visible = world.zoneName('visible-');
const hidden = world.zoneName('hidden-');
const hiddenPath = await createZone(api, hidden);
const visiblePath = await createZone(api, visible);
const missingPath = zp(world.zoneName('missing-'));
expect((await api.put(`${visiblePath}${up(member.username)}`)).status).toBe(204);
const row = await addAddress(api, hiddenPath, 'private', '192.0.2.15');
const recordsBefore = await world.db.records();
const usersBefore = await world.db.users();
const csrf = world.zoneName('cross-');
const url = `${ORIGIN2_URL}/attack.html?${new URLSearchParams({ target: world.g.baseURL, zone: csrf, form: 'logout' })}`;
const foreign = adminUi.page.waitForResponse((response) => response.url() === `${world.g.baseURL}/logout` && response.request().method() === 'POST');
const mark = await world.db.auditMaxId();
await adminUi.page.goto(url);
expect((await foreign).status()).toBe(403);
await adminUi.page.waitForURL('**/logout', { waitUntil: 'load' });
expect((await api.post('/zones', zoneInput(csrf), { origin: ORIGIN2_URL })).status).toBe(403);
expect(await world.db.auditSince(mark)).toEqual([]);
await adminUi.goto('/account');
await expect(adminUi.page.locator('.who-name')).toHaveText(admin.username);
for (const suffix of ['', '/records', '/export', '/check']) {
const denied = await user.get(hiddenPath + suffix);
const missing = await user.get(missingPath + suffix);
expect([denied.status, denied.json]).toEqual([404, missing.json]);
expect(missing.status).toBe(404);
}
const timings: number[][] = [[], []];
for (let i = 0; i < 12; i++) {
const paths = i % 2 === 0 ? [hiddenPath, missingPath] : [missingPath, hiddenPath];
for (const target of paths) {
const response = await user.get(target);
expect(response.status).toBe(404);
timings[target === hiddenPath ? 0 : 1].push(response.durationMs);
}
}
const medians = timings.map((samples) => samples.sort((a, b) => a - b)[6]);
expect(Math.abs(medians[0] - medians[1]), 'no gross latency difference between hidden and missing zones').toBeLessThan(100);
for (const [method, suffix, body] of [
['POST', '/records', address('denied', '192.0.2.2')],
['POST', '/records/delete', { records: [{ id: row.id, etag: row.etag }] }],
['POST', '/import/preview', { mode: 'merge', content: 'www 300 IN A 192.0.2.4' }],
['POST', '/import/apply', { mode: 'merge', content: '', fingerprint: 'x' }],
] as const) {
expect((await user.raw(method, '/api/v1' + hiddenPath + suffix, { body })).status).toBe(404);
}
expect((await user.put(`${visiblePath}/records/${row.id}`, address('denied', '192.0.2.2'), { ifMatch: row.etag })).status).toBe(404);
expect((await user.delete(`${visiblePath}/records/${row.id}`, undefined, { ifMatch: row.etag })).status).toBe(404);
expect((await user.post(`${visiblePath}/records/delete`, { records: [{ id: row.id, etag: row.etag }] })).status).toBe(404);
expect((await user.get('/audit', { query: { zone: hidden } })).json.entries.every((entry: { actor: string }) => entry.actor === member.username)).toBe(true);
expect((await user.put(`${visiblePath}${up(member.username)}`)).status).toBe(403);
expect((await user.put(`${up(member.username)}/role`, { role: 'admin' })).status).toBe(403);
const forwarded = await user.get('/account', { headers: { 'X-Forwarded-For': '203.0.113.77' } });
expect(forwarded.status).toBe(200);
expect((await world.db.auditTail(1))[0].origin).toBe(runnerAddress());
expect(await world.db.records()).toEqual(recordsBefore);
expect(await world.db.users()).toEqual(usersBefore);
await checkZone(world, api, hidden);
});
test('input validation, session integrity and rate limiting hold under repeated refusals', async ({ world }) => {
const admin = await world.bootstrapAdmin();
const api = await world.apiAs(admin);
const ui = await world.uiAs(admin);
const zone = world.zoneName();
const z = await createZone(api, zone);
const hash = await staticHash(world.g);
const form = { mode: 'merge', content: '' };
const expected = await world.db.records(zone);
const text = '<script>example</script>';
const quote = "test'quote";
const malformed = [text, quote, 'bad\u0000name', 'bad\tname', 'eхample'];
for (const value of malformed) {
expect((await api.post('/zones', zoneInput(value))).status).toBe(422);
expect((await api.post(`${z}/records`, address(value, '192.0.2.7'))).status).toBe(422);
expect((await api.post(`${z}/records`, address('probe', value))).status).toBe(422);
expect((await api.post('/users', { username: value, role: 'user', password: world.password() })).status).toBe(422);
}
const missing = await api.get(zp(quote));
expect(missing.status).toBe(404);
expect((await api.get('/audit', { query: { actor: quote } })).json.entries).toEqual([]);
expect((await api.page(`/static/${hash}/css/missing.css`)).status).toBe(404);
const normalized = await api.page(`/static/${hash}/css/%2e%2e%2fmissing.css`);
expect(normalized.status).toBe(301);
expect(normalized.headers.location).toBe(`/static/${hash}/missing.css`);
expect((await api.page(normalized.headers.location)).status).toBe(404);
expect((await api.page(`/zones/${encodeURIComponent('invalid/name')}`)).status).toBe(404);
expect((await api.post(`${z}/records`, address('large', 'x'.repeat(70_000)))).status).toBe(413);
expect((await api.post(`${z}/import/preview`, { ...form, content: 'x'.repeat(2 * 1024 * 1024) })).status).toBe(413);
const nested = '['.repeat(10010) + 'null' + ']'.repeat(10010);
expect((await api.post(`${z}/records`, undefined, { raw: `{"data":${nested}}` })).status).toBe(400);
for (const content of ['$INCLUDE missing.zone\n', '$GENERATE 1-10001 fixture$ 300 IN A 192.0.2.2\n']) {
expect((await api.post(`${z}/import/preview`, { ...form, content })).status).toBe(422);
}
const fixed = world.secrets.register('f'.repeat(43), 'unissued session cookie');
const candidate = await world.api();
await candidate.setCookie(fixed);
expect((await candidate.get('/account')).status).toBe(401);
expect((await candidate.login(admin.username, admin.password)).status).toBe(303);
const issued = (await candidate.cookie())!;
expect(issued).not.toBe(fixed);
await candidate.setCookie((issued[0] === 'a' ? 'b' : 'a') + issued.slice(1));
expect((await candidate.get('/account')).status).toBe(401);
const failed = await world.api();
const badPassword = world.password('wrong password');
const login = await failed.login(text, badPassword, { preserveRateLimit: true });
expect(login.status).toBe(401);
await ui.goto('/audit');
await ui.filterAudit({ actor: text });
await expect(ui.page.getByText(text, { exact: true })).toBeVisible();
await expect(ui.page.locator('#app script')).toHaveCount(0);
for (let i = 0; i < 4; i++) expect((await failed.login('unknown', badPassword, { preserveRateLimit: true })).status).toBe(401);
expect((await failed.login('unknown', badPassword, { preserveRateLimit: true })).status).toBe(429);
expect(await world.db.records(zone)).toEqual(expected);
await checkZone(world, api, zone);
});
test('text fields preserve literal markup and syntax delimiters', async ({ world }) => {
const admin = await world.bootstrapAdmin();
const api = await world.apiAs(admin);
const zone = world.zoneName();
await createZone(api, zone);
const ui = await world.uiAs(admin);
await ui.openZone(zone);
await zoneServed(world, zone);
const value = "<script>example</script> ' ; --";
const records: Rec[] = [
{ name: 'text', type: 'TXT', ttl: 300, data: { text: value } },
{ name: 'policy', type: 'CAA', ttl: 300, data: { flag: 0, tag: 'issue', value } },
];
for (const record of records) {
const change = await begin(world, zone);
const fields = Object.fromEntries(Object.entries(record.data).map(([key, data]) => [key, String(data)]));
await ui.addRecord({ name: record.name, type: record.type, ttl: '300', fields }, { expectStatus: 201 });
await threeWay(world, ui, zone, record, change, `literal ${record.type}`);
await expect(ui.page.locator('#records-body script')).toHaveCount(0);
}
});