test(e2e): add playwright harness and test stack
- test(e2e): add playwright harness and test stack - test(e2e): add core flow - fix(ui): preserve same-origin browser form submissions - fix(ui): offer reload inside stale edit dialogs - test(e2e): add persona session and accessibility suites - test(e2e): preserve per-run artifacts and clean pulled images - test(e2e): verify import and audit state across navigation - test(e2e): tighten verification helpers and persona checks - test(e2e): bound response body reads of the browser observer - test: recover review compatibility assertions - test: stabilize audit and user flow assertions
This commit is contained in:
1 parent
a7ba01fc77
commit
57a005c19f
48 files changed
+6239
-6
No files matched your search
@@ -0,0 +1,312 @@
|
||||
// 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 mysql from 'mysql2/promise';
|
||||
import { GROUP_NAMES, GROUPS, MYSQL_HOST, requireEnv, type GroupConfig } from './env';
|
||||
import { HarnessError } from './errors';
|
||||
|
||||
export interface RecordRow {
|
||||
id: number;
|
||||
zone: string;
|
||||
name: string;
|
||||
ttl: number | null;
|
||||
content: string | null;
|
||||
record_type: string;
|
||||
}
|
||||
|
||||
export interface UserRow {
|
||||
id: number;
|
||||
username: string;
|
||||
role: string;
|
||||
password_hash: string;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
last_login_at: string | null;
|
||||
deleted_at: string | null;
|
||||
}
|
||||
|
||||
export interface AuditRow {
|
||||
id: number;
|
||||
time: string;
|
||||
user_id: number | null;
|
||||
actor: string;
|
||||
origin: string;
|
||||
operation: string;
|
||||
status: number | null;
|
||||
error: string | null;
|
||||
zone: string | null;
|
||||
record_id: number | null;
|
||||
target_user_id: number | null;
|
||||
before_value: unknown;
|
||||
after_value: unknown;
|
||||
}
|
||||
|
||||
export interface DelegationRow {
|
||||
zone: string;
|
||||
user_id: number;
|
||||
username: string;
|
||||
created_at: string;
|
||||
created_by: number;
|
||||
}
|
||||
|
||||
export interface SessionRow {
|
||||
user_id: number;
|
||||
created_at: string;
|
||||
last_seen_at: string;
|
||||
expires_at: string;
|
||||
origin: string;
|
||||
user_agent: string;
|
||||
}
|
||||
|
||||
export type RawRecord = { zone: string; name: string; ttl: number | null; content: string | null; record_type: string };
|
||||
|
||||
const INIT_TEMPLATE = path.resolve(process.cwd(), 'stack', 'mysql-init.sql');
|
||||
|
||||
function connectionOptions(database?: string): mysql.ConnectionOptions {
|
||||
return {
|
||||
host: MYSQL_HOST,
|
||||
port: 3306,
|
||||
user: 'root',
|
||||
password: requireEnv('E2E_MYSQL_ROOT_PASSWORD'),
|
||||
database,
|
||||
timezone: 'Z',
|
||||
dateStrings: true,
|
||||
supportBigNumbers: true,
|
||||
bigNumberStrings: false,
|
||||
charset: 'utf8mb4_0900_ai_ci',
|
||||
connectTimeout: 10_000,
|
||||
};
|
||||
}
|
||||
|
||||
function q(identifier: string): string {
|
||||
if (!/^[A-Za-z0-9_]+$/.test(identifier)) throw new HarnessError('infrastructure', `unsafe identifier ${identifier}`);
|
||||
return '`' + identifier + '`';
|
||||
}
|
||||
|
||||
export function initSql(g: GroupConfig): string {
|
||||
const template = fs.readFileSync(INIT_TEMPLATE, 'utf8');
|
||||
const values: Record<string, string> = {
|
||||
DATABASE: g.database,
|
||||
PREFIX: g.prefix,
|
||||
DNS_USER: g.dnsUser,
|
||||
DNS_PASSWORD: g.dnsPassword,
|
||||
APP_USER: g.appUser,
|
||||
APP_PASSWORD: g.appPassword,
|
||||
};
|
||||
return template
|
||||
.split('\n')
|
||||
.filter((l) => !l.startsWith('--'))
|
||||
.join('\n')
|
||||
.replace(/\{\{([A-Z_]+)\}\}/g, (_m, k: string) => {
|
||||
const v = values[k];
|
||||
if (v === undefined || !/^[A-Za-z0-9_-]+$/.test(v)) throw new HarnessError('infrastructure', `bad template value ${k}`);
|
||||
return v;
|
||||
});
|
||||
}
|
||||
|
||||
export async function initDatabases(): Promise<void> {
|
||||
const conn = await mysql.createConnection({ ...connectionOptions(), multipleStatements: true });
|
||||
try {
|
||||
for (const name of GROUP_NAMES) {
|
||||
const [rows] = await conn.query<mysql.RowDataPacket[]>('SELECT SCHEMA_NAME FROM information_schema.SCHEMATA WHERE SCHEMA_NAME = ?', [GROUPS[name].database]);
|
||||
if (rows.length > 0) continue;
|
||||
await conn.query(initSql(GROUPS[name]));
|
||||
}
|
||||
} finally {
|
||||
await conn.end();
|
||||
}
|
||||
}
|
||||
|
||||
export async function waitForMysql(timeoutMs = 120_000): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
for (;;) {
|
||||
try {
|
||||
const conn = await mysql.createConnection(connectionOptions());
|
||||
await conn.query('SELECT 1');
|
||||
await conn.end();
|
||||
return;
|
||||
} catch (e) {
|
||||
if (Date.now() > deadline) throw new HarnessError('timeout', `mysql not reachable: ${(e as Error).message}`);
|
||||
await new Promise((r) => setTimeout(r, 500));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export class Db {
|
||||
private readonly pool: mysql.Pool;
|
||||
readonly t: { records: string; users: string; sessions: string; delegations: string; audit: string; schema: string };
|
||||
|
||||
constructor(readonly group: GroupConfig) {
|
||||
this.pool = mysql.createPool({ ...connectionOptions(group.database), connectionLimit: 4 });
|
||||
const p = group.prefix;
|
||||
this.t = {
|
||||
records: q(`${p}records`),
|
||||
users: q(`${p}webui_users`),
|
||||
sessions: q(`${p}webui_sessions`),
|
||||
delegations: q(`${p}webui_zone_delegations`),
|
||||
audit: q(`${p}webui_audit`),
|
||||
schema: q(`${p}webui_schema`),
|
||||
};
|
||||
}
|
||||
|
||||
async query<T = mysql.RowDataPacket>(sql: string, params: unknown[] = []): Promise<T[]> {
|
||||
const [rows] = await this.pool.query(sql, params);
|
||||
return rows as T[];
|
||||
}
|
||||
|
||||
async exec(sql: string, params: unknown[] = []): Promise<mysql.ResultSetHeader> {
|
||||
const [r] = await this.pool.query<mysql.ResultSetHeader>(sql, params);
|
||||
return r;
|
||||
}
|
||||
|
||||
async records(zone?: string): Promise<RecordRow[]> {
|
||||
const where = zone === undefined ? '' : 'WHERE `zone` = BINARY ?';
|
||||
return this.query<RecordRow>(`SELECT id, zone, name, ttl, content, record_type FROM ${this.t.records} ${where} ORDER BY id`, zone === undefined ? [] : [zone]);
|
||||
}
|
||||
|
||||
async recordById(id: number): Promise<RecordRow | undefined> {
|
||||
const rows = await this.query<RecordRow>(`SELECT id, zone, name, ttl, content, record_type FROM ${this.t.records} WHERE id = ?`, [id]);
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
async zones(): Promise<string[]> {
|
||||
const rows = await this.query<{ zone: string }>(`SELECT DISTINCT zone FROM ${this.t.records} ORDER BY zone`);
|
||||
return rows.map((r) => r.zone);
|
||||
}
|
||||
|
||||
async recordCount(): Promise<number> {
|
||||
const rows = await this.query<{ n: number }>(`SELECT COUNT(*) AS n FROM ${this.t.records}`);
|
||||
return Number(rows[0].n);
|
||||
}
|
||||
|
||||
async insertRaw(r: RawRecord): Promise<number> {
|
||||
const res = await this.exec(`INSERT INTO ${this.t.records} (zone, name, ttl, content, record_type) VALUES (?, ?, ?, ?, ?)`, [r.zone, r.name, r.ttl, r.content, r.record_type]);
|
||||
return res.insertId;
|
||||
}
|
||||
|
||||
async insertMany(rows: RawRecord[]): Promise<void> {
|
||||
for (let i = 0; i < rows.length; i += 1000) {
|
||||
const chunk = rows.slice(i, i + 1000);
|
||||
await this.exec(
|
||||
`INSERT INTO ${this.t.records} (zone, name, ttl, content, record_type) VALUES ${chunk.map(() => '(?, ?, ?, ?, ?)').join(', ')}`,
|
||||
chunk.flatMap((r) => [r.zone, r.name, r.ttl, r.content, r.record_type]),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async updateRaw(id: number, fields: Partial<RawRecord>): Promise<void> {
|
||||
const keys = Object.keys(fields) as Array<keyof RawRecord>;
|
||||
if (keys.length === 0) return;
|
||||
await this.exec(`UPDATE ${this.t.records} SET ${keys.map((k) => `${q(k)} = ?`).join(', ')} WHERE id = ?`, [...keys.map((k) => fields[k]), id]);
|
||||
}
|
||||
|
||||
async deleteZoneRaw(zone: string): Promise<void> {
|
||||
await this.exec(`DELETE FROM ${this.t.records} WHERE zone = BINARY ?`, [zone]);
|
||||
}
|
||||
|
||||
async soaContent(zone: string): Promise<Record<string, unknown> | null> {
|
||||
const rows = await this.query<RecordRow>(`SELECT id, zone, name, ttl, content, record_type FROM ${this.t.records} WHERE zone = BINARY ? AND name = '' AND record_type = 'SOA'`, [zone]);
|
||||
if (rows.length !== 1 || rows[0].content === null) return null;
|
||||
return JSON.parse(rows[0].content) as Record<string, unknown>;
|
||||
}
|
||||
|
||||
async soaSerial(zone: string): Promise<number | null> {
|
||||
const soa = await this.soaContent(zone);
|
||||
return soa && typeof soa.serial === 'number' ? soa.serial : null;
|
||||
}
|
||||
|
||||
async users(): Promise<UserRow[]> {
|
||||
return this.query<UserRow>(`SELECT id, username, role, password_hash, created_at, updated_at, last_login_at, deleted_at FROM ${this.t.users} ORDER BY id`);
|
||||
}
|
||||
|
||||
async user(username: string): Promise<UserRow | undefined> {
|
||||
const rows = await this.query<UserRow>(
|
||||
`SELECT id, username, role, password_hash, created_at, updated_at, last_login_at, deleted_at FROM ${this.t.users} WHERE username = ?`,
|
||||
[username],
|
||||
);
|
||||
return rows[0];
|
||||
}
|
||||
|
||||
async userId(username: string): Promise<number | null> {
|
||||
return (await this.user(username))?.id ?? null;
|
||||
}
|
||||
|
||||
async usernameById(id: number): Promise<string | null> {
|
||||
const rows = await this.query<{ username: string }>(`SELECT username FROM ${this.t.users} WHERE id = ?`, [id]);
|
||||
return rows[0]?.username ?? null;
|
||||
}
|
||||
|
||||
async delegations(): Promise<DelegationRow[]> {
|
||||
return this.query<DelegationRow>(
|
||||
`SELECT d.zone, d.user_id, u.username, d.created_at, d.created_by FROM ${this.t.delegations} d JOIN ${this.t.users} u ON u.id = d.user_id ORDER BY d.zone, u.username`,
|
||||
);
|
||||
}
|
||||
|
||||
async sessions(userId?: number): Promise<SessionRow[]> {
|
||||
const where = userId === undefined ? '' : 'WHERE user_id = ?';
|
||||
return this.query<SessionRow>(`SELECT user_id, created_at, last_seen_at, expires_at, origin, user_agent FROM ${this.t.sessions} ${where}`, userId === undefined ? [] : [userId]);
|
||||
}
|
||||
|
||||
async sessionExists(hash: Buffer): Promise<boolean> {
|
||||
const [row] = await this.query<{ n: number }>(`SELECT COUNT(*) AS n FROM ${this.t.sessions} WHERE token_hash = ?`, [hash]);
|
||||
return Number(row.n) === 1;
|
||||
}
|
||||
|
||||
async deleteSessions(userId: number): Promise<void> {
|
||||
await this.exec(`DELETE FROM ${this.t.sessions} WHERE user_id = ?`, [userId]);
|
||||
}
|
||||
|
||||
async auditMaxId(): Promise<number> {
|
||||
const rows = await this.query<{ id: number | null }>(`SELECT MAX(id) AS id FROM ${this.t.audit}`);
|
||||
return Number(rows[0].id ?? 0);
|
||||
}
|
||||
|
||||
async auditSince(id: number): Promise<AuditRow[]> {
|
||||
return this.query<AuditRow>(
|
||||
`SELECT id, DATE_FORMAT(time, '%Y-%m-%dT%H:%i:%s.%fZ') AS time, user_id, actor, origin, operation, status, error, zone, record_id, target_user_id, before_value, after_value FROM ${this.t.audit} WHERE id > ? ORDER BY id`,
|
||||
[id],
|
||||
);
|
||||
}
|
||||
|
||||
async auditTail(n: number): Promise<AuditRow[]> {
|
||||
const rows = await this.query<AuditRow>(
|
||||
`SELECT id, DATE_FORMAT(time, '%Y-%m-%dT%H:%i:%s.%fZ') AS time, user_id, actor, origin, operation, status, error, zone, record_id, target_user_id, before_value, after_value FROM ${this.t.audit} ORDER BY id DESC LIMIT ?`,
|
||||
[n],
|
||||
);
|
||||
return rows.reverse();
|
||||
}
|
||||
|
||||
async auditCount(where = '1 = 1', params: unknown[] = []): Promise<number> {
|
||||
const rows = await this.query<{ n: number }>(`SELECT COUNT(*) AS n FROM ${this.t.audit} WHERE ${where}`, params);
|
||||
return Number(rows[0].n);
|
||||
}
|
||||
|
||||
async tableExists(name: string): Promise<boolean> {
|
||||
const rows = await this.query<{ n: number }>('SELECT COUNT(*) AS n FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = ?', [name]);
|
||||
return Number(rows[0].n) === 1;
|
||||
}
|
||||
|
||||
async snapshot(): Promise<string> {
|
||||
const records = await this.records().catch(() => []);
|
||||
const audit = await this.auditTail(60).catch(() => []);
|
||||
const users = await this.users().catch(() => []);
|
||||
const delegations = await this.delegations().catch(() => []);
|
||||
return JSON.stringify(
|
||||
{
|
||||
records: records.slice(-300),
|
||||
recordCount: records.length,
|
||||
users: users.map((u) => ({ ...u, password_hash: u.password_hash ? '[hash]' : '' })),
|
||||
delegations,
|
||||
audit,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
);
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
await this.pool.end();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user