- 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
265 lines
10 KiB
TypeScript
265 lines
10 KiB
TypeScript
// SPDX-License-Identifier: GPL-2.0-or-later
|
|
// Copyright (C) 2026 Bryan Joshua Pedini
|
|
|
|
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { test as base, expect, type Browser, type TestInfo } from '@playwright/test';
|
|
import { ApiClient, type LoginHooks } from './api';
|
|
import { Cli } from './cli';
|
|
import { docker } from './docker';
|
|
import { containerName, GROUPS, runSeed, secretsDir, SEEDS_DIR, type GroupConfig, type GroupName } from './env';
|
|
import { AuditLedger } from './ledger';
|
|
import { Db } from './mysql';
|
|
import { Recorder } from './recorder';
|
|
import { Rng, testSeed } from './rng';
|
|
import { redactText, SecretRegistry } from './secrets';
|
|
import { restartApp } from './stack';
|
|
import { Ui, type UiOpenOptions } from './ui';
|
|
|
|
export interface Account {
|
|
username: string;
|
|
password: string;
|
|
role: 'admin' | 'user';
|
|
}
|
|
|
|
export class World implements LoginHooks {
|
|
readonly db: Db;
|
|
readonly secrets: SecretRegistry;
|
|
readonly recorder = new Recorder();
|
|
readonly ledger: AuditLedger;
|
|
readonly cli: Cli;
|
|
rng: Rng;
|
|
testInfo: TestInfo | null = null;
|
|
auditCheck = true;
|
|
private originFailures = 0;
|
|
private readonly usernameFailures = new Map<string, number>();
|
|
private readonly testClients = new Set<ApiClient>();
|
|
private readonly testUis = new Set<Ui>();
|
|
private readonly keptClients = new Set<ApiClient>();
|
|
private readonly keptUis = new Set<Ui>();
|
|
private seq = 0;
|
|
|
|
constructor(
|
|
readonly g: GroupConfig,
|
|
readonly browser: Browser,
|
|
) {
|
|
this.db = new Db(g);
|
|
this.secrets = new SecretRegistry(path.join(secretsDir(), `${g.name}-${process.pid}.jsonl`));
|
|
this.secrets.register(g.appPassword, 'mysql password of the application');
|
|
this.secrets.register(g.dnsPassword, 'mysql password of coredns');
|
|
if (process.env.E2E_MYSQL_ROOT_PASSWORD) this.secrets.register(process.env.E2E_MYSQL_ROOT_PASSWORD, 'mysql root password');
|
|
this.ledger = new AuditLedger(this.db, this.secrets);
|
|
this.cli = new Cli(g, this.recorder, this.secrets, this.ledger);
|
|
this.rng = new Rng(`${runSeed()}::${g.name}`);
|
|
}
|
|
|
|
async beforeLogin(username: string): Promise<void> {
|
|
if (this.originFailures >= 4 || (this.usernameFailures.get(username) ?? 0) >= 4) await this.resetRateLimits();
|
|
}
|
|
|
|
afterLogin(username: string, status: number): void {
|
|
if (status === 303) {
|
|
this.usernameFailures.delete(username);
|
|
return;
|
|
}
|
|
if (status === 401 || status === 429) {
|
|
this.originFailures++;
|
|
this.usernameFailures.set(username, (this.usernameFailures.get(username) ?? 0) + 1);
|
|
}
|
|
}
|
|
|
|
async resetRateLimits(): Promise<void> {
|
|
this.recorder.note(`restarting ${this.g.service} to reset the in-memory login rate limits`);
|
|
await this.ledger.settle();
|
|
await restartApp(this.g);
|
|
this.originFailures = 0;
|
|
this.usernameFailures.clear();
|
|
}
|
|
|
|
async restart(): Promise<void> {
|
|
await this.ledger.settle();
|
|
await restartApp(this.g);
|
|
this.originFailures = 0;
|
|
this.usernameFailures.clear();
|
|
}
|
|
|
|
unique(prefix: string): string {
|
|
this.seq++;
|
|
return `${prefix}${this.rng.string(5)}${this.seq}`;
|
|
}
|
|
|
|
zoneName(prefix = 'z'): string {
|
|
return `${this.unique(prefix)}.${this.g.name}.test.`;
|
|
}
|
|
|
|
password(label = 'password'): string {
|
|
const pw = `Pw-${this.rng.string(10, 'abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789')}-${this.rng.string(8)}`;
|
|
return this.secrets.register(pw, label);
|
|
}
|
|
|
|
async api(opts: { keep?: boolean } = {}): Promise<ApiClient> {
|
|
const c = await ApiClient.create(this.g, { recorder: this.recorder, secrets: this.secrets, ledger: this.ledger, hooks: this });
|
|
(opts.keep ? this.keptClients : this.testClients).add(c);
|
|
return c;
|
|
}
|
|
|
|
async ui(opts: UiOpenOptions & { keep?: boolean } = {}): Promise<Ui> {
|
|
const u = await Ui.open(this.browser, { group: this.g, ledger: this.ledger, recorder: this.recorder, secrets: this.secrets, hooks: this }, opts);
|
|
(opts.keep ? this.keptUis : this.testUis).add(u);
|
|
return u;
|
|
}
|
|
|
|
async apiAs(account: Account, opts: { keep?: boolean } = {}): Promise<ApiClient> {
|
|
const c = await this.api(opts);
|
|
const r = await c.login(account.username, account.password);
|
|
expect(r.status, `login of ${account.username}`).toBe(303);
|
|
return c;
|
|
}
|
|
|
|
async uiAs(account: Account, opts: UiOpenOptions & { keep?: boolean } = {}): Promise<Ui> {
|
|
const u = await this.ui(opts);
|
|
await u.login(account.username, account.password);
|
|
return u;
|
|
}
|
|
|
|
async bootstrapAdmin(username = this.unique('root')): Promise<Account> {
|
|
const password = this.password(`password of ${username}`);
|
|
const r = await this.cli.userAdd(username, 'admin', password);
|
|
expect(r.code, `user add ${username} admin: ${this.secrets.redact(r.stderr)}`).toBe(0);
|
|
return { username, password, role: 'admin' };
|
|
}
|
|
|
|
async createUser(admin: ApiClient, role: 'admin' | 'user', username = this.unique(role === 'admin' ? 'adm' : 'usr')): Promise<Account> {
|
|
const password = this.password(`password of ${username}`);
|
|
const r = await admin.post('/users', { username, role, password });
|
|
expect(r.status, `create user ${username}: ${r.text}`).toBe(201);
|
|
return { username, password, role };
|
|
}
|
|
|
|
async closeTestResources(): Promise<void> {
|
|
for (const u of this.testUis) await u.close().catch(() => undefined);
|
|
for (const c of this.testClients) await c.dispose().catch(() => undefined);
|
|
this.testUis.clear();
|
|
this.testClients.clear();
|
|
}
|
|
|
|
async dispose(): Promise<void> {
|
|
await this.closeTestResources();
|
|
for (const u of this.keptUis) await u.close().catch(() => undefined);
|
|
for (const c of this.keptClients) await c.dispose().catch(() => undefined);
|
|
await this.db.close().catch(() => undefined);
|
|
}
|
|
}
|
|
|
|
let currentSecrets: SecretRegistry | undefined;
|
|
let stdioWrapped = false;
|
|
|
|
function installStdioRedaction(): void {
|
|
if (stdioWrapped) return;
|
|
stdioWrapped = true;
|
|
for (const stream of [process.stdout, process.stderr]) {
|
|
const original = stream.write.bind(stream) as (...a: unknown[]) => boolean;
|
|
stream.write = ((chunk: unknown, ...rest: unknown[]) => {
|
|
const text = typeof chunk === 'string' ? chunk : chunk instanceof Uint8Array ? Buffer.from(chunk).toString('utf8') : undefined;
|
|
return original(text === undefined ? chunk : redactText(text, currentSecrets?.all() ?? []), ...rest);
|
|
}) as typeof stream.write;
|
|
}
|
|
}
|
|
|
|
function slug(s: string): string {
|
|
return s.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 120) || 'test';
|
|
}
|
|
|
|
async function attachFailure(w: World, info: TestInfo, seed: string): Promise<void> {
|
|
const red = <T>(v: T) => w.secrets.redactValue(v);
|
|
await info.attach('http.json', { body: JSON.stringify(red(w.recorder.http), null, 2), contentType: 'application/json' });
|
|
await info.attach('cli.json', { body: JSON.stringify(red(w.recorder.cli), null, 2), contentType: 'application/json' });
|
|
await info.attach('dig.json', { body: JSON.stringify(w.recorder.dig, null, 2), contentType: 'application/json' });
|
|
await info.attach('notes.txt', { body: w.secrets.redact(w.recorder.notes.join('\n')), contentType: 'text/plain' });
|
|
const snapshot = await w.db.snapshot().catch((e) => `snapshot failed: ${(e as Error).message}`);
|
|
await info.attach('database.json', { body: w.secrets.redact(snapshot), contentType: 'application/json' });
|
|
const logs = await docker(['logs', '--tail', '400', containerName(w.g.service)], { timeoutMs: 60_000 }).catch(() => null);
|
|
if (logs) await info.attach('app.log', { body: w.secrets.redact(logs.stdout + logs.stderr), contentType: 'text/plain' });
|
|
const failing = { seed, runSeed: runSeed(), group: w.g.name, title: info.titlePath.join(' > '), reproduce: `E2E_SEED=${JSON.stringify(runSeed())}`, fuzzCases: red(w.recorder.fuzzCases) };
|
|
await info.attach('seed.json', { body: JSON.stringify(failing, null, 2), contentType: 'application/json' });
|
|
fs.mkdirSync(SEEDS_DIR, { recursive: true });
|
|
fs.writeFileSync(path.join(SEEDS_DIR, `${slug(info.titlePath.slice(1).join(' '))}.json`), JSON.stringify(failing, null, 2));
|
|
}
|
|
|
|
async function scanLogs(w: World, since: Date): Promise<string[]> {
|
|
const r = await docker(['logs', '--since', since.toISOString(), containerName(w.g.service)], { timeoutMs: 60_000 });
|
|
const text = r.stdout + r.stderr;
|
|
const found = w.secrets.findIn(text);
|
|
if (/\$argon2id\$/.test(text)) found.push('a password hash');
|
|
if (/coredns_webui_session=/.test(text)) found.push('a session cookie');
|
|
return found;
|
|
}
|
|
|
|
export interface Options {
|
|
group: GroupName;
|
|
}
|
|
|
|
export interface Fixtures {
|
|
world: World;
|
|
seed: string;
|
|
}
|
|
|
|
export interface WorkerFixtures {
|
|
worlds: Map<GroupName, World>;
|
|
}
|
|
|
|
export const test = base.extend<Options & Fixtures, WorkerFixtures>({
|
|
group: ['harness', { option: true }],
|
|
|
|
worlds: [
|
|
async ({}, use) => {
|
|
installStdioRedaction();
|
|
const m = new Map<GroupName, World>();
|
|
await use(m);
|
|
for (const w of m.values()) await w.dispose();
|
|
},
|
|
{ scope: 'worker' },
|
|
],
|
|
|
|
seed: async ({}, use, info) => {
|
|
await use(testSeed(runSeed(), info.titlePath));
|
|
},
|
|
|
|
world: async ({ group, browser, worlds, seed }, use, info) => {
|
|
let w = worlds.get(group);
|
|
if (!w || w.browser !== browser) {
|
|
w = new World(GROUPS[group], browser);
|
|
worlds.set(group, w);
|
|
}
|
|
currentSecrets = w.secrets;
|
|
w.testInfo = info;
|
|
w.rng = new Rng(seed);
|
|
w.auditCheck = true;
|
|
info.annotations.push({ type: 'seed', description: seed });
|
|
const started = new Date(Date.now() - 1000);
|
|
await w.ledger.start();
|
|
let failure: unknown;
|
|
try {
|
|
await use(w);
|
|
} finally {
|
|
try {
|
|
await w.ledger.settle();
|
|
if (info.status === info.expectedStatus) {
|
|
if (w.auditCheck) await w.ledger.verify(`every operation of "${info.title}" has exactly one audit row`);
|
|
const leaks = await scanLogs(w, started);
|
|
expect(leaks, 'secrets in the application log').toEqual([]);
|
|
}
|
|
} catch (e) {
|
|
failure = e;
|
|
}
|
|
await w.closeTestResources();
|
|
if (info.status !== info.expectedStatus || failure) await attachFailure(w, info, seed).catch(() => undefined);
|
|
w.recorder.clear();
|
|
w.testInfo = null;
|
|
}
|
|
if (failure) throw failure;
|
|
},
|
|
});
|
|
|
|
export { expect };
|