- 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
238 lines
9.0 KiB
TypeScript
238 lines
9.0 KiB
TypeScript
// SPDX-License-Identifier: GPL-2.0-or-later
|
|
// Copyright (C) 2026 Bryan Joshua Pedini
|
|
|
|
import { request, type APIRequestContext, type APIResponse } from '@playwright/test';
|
|
import { runnerAddress, SESSION_COOKIE, type GroupConfig } from './env';
|
|
import type { AuditLedger } from './ledger';
|
|
import type { Recorder } from './recorder';
|
|
import type { SecretRegistry } from './secrets';
|
|
|
|
export interface ApiResult {
|
|
status: number;
|
|
headers: Record<string, string>;
|
|
text: string;
|
|
json: any;
|
|
etag: string | null;
|
|
durationMs: number;
|
|
setCookie: string;
|
|
}
|
|
|
|
export interface RequestOptions {
|
|
body?: unknown;
|
|
raw?: string | Buffer;
|
|
contentType?: string | null;
|
|
headers?: Record<string, string>;
|
|
query?: Record<string, string | number | undefined>;
|
|
ifMatch?: string;
|
|
origin?: 'same' | 'none' | string;
|
|
audit?: 'auto' | 'none' | 'optional';
|
|
timeoutMs?: number;
|
|
}
|
|
|
|
export interface LoginHooks {
|
|
beforeLogin(username: string): Promise<void>;
|
|
afterLogin(username: string, status: number): void;
|
|
}
|
|
|
|
export interface ApiDeps {
|
|
recorder: Recorder;
|
|
secrets: SecretRegistry;
|
|
ledger?: AuditLedger;
|
|
hooks?: LoginHooks;
|
|
}
|
|
|
|
const UNSAFE = new Set(['POST', 'PUT', 'DELETE', 'PATCH']);
|
|
|
|
export class ApiClient {
|
|
username = '';
|
|
private disposed = false;
|
|
|
|
private constructor(
|
|
readonly group: GroupConfig,
|
|
public ctx: APIRequestContext,
|
|
private readonly deps: ApiDeps,
|
|
) {}
|
|
|
|
static async create(group: GroupConfig, deps: ApiDeps): Promise<ApiClient> {
|
|
const ctx = await request.newContext({ baseURL: group.baseURL, extraHTTPHeaders: { Accept: 'application/json' }, timeout: 90_000 });
|
|
return new ApiClient(group, ctx, deps);
|
|
}
|
|
|
|
get origin(): string {
|
|
return new URL(this.group.baseURL).origin;
|
|
}
|
|
|
|
async cookie(): Promise<string | undefined> {
|
|
const state = await this.ctx.storageState();
|
|
return state.cookies.find((c) => c.name === SESSION_COOKIE)?.value;
|
|
}
|
|
|
|
async cookieAttributes(): Promise<{ httpOnly: boolean; sameSite: string; path: string; secure: boolean } | undefined> {
|
|
const state = await this.ctx.storageState();
|
|
const c = state.cookies.find((x) => x.name === SESSION_COOKIE);
|
|
return c ? { httpOnly: c.httpOnly, sameSite: c.sameSite, path: c.path, secure: c.secure } : undefined;
|
|
}
|
|
|
|
async setCookie(value: string | null): Promise<void> {
|
|
const host = new URL(this.group.baseURL).hostname;
|
|
const state = await this.ctx.storageState();
|
|
const others = state.cookies.filter((c) => c.name !== SESSION_COOKIE);
|
|
const cookies =
|
|
value === null ? others : [...others, { name: SESSION_COOKIE, value, domain: host, path: '/', expires: -1, httpOnly: true, secure: false, sameSite: 'Strict' as const }];
|
|
const fresh = await request.newContext({
|
|
baseURL: this.group.baseURL,
|
|
extraHTTPHeaders: { Accept: 'application/json' },
|
|
timeout: 90_000,
|
|
storageState: { cookies, origins: [] },
|
|
});
|
|
await this.ctx.dispose();
|
|
this.ctx = fresh;
|
|
}
|
|
|
|
async login(username: string, password: string, opts: { next?: string; headers?: Record<string, string>; expectStatus?: number; preserveRateLimit?: boolean } = {}): Promise<ApiResult> {
|
|
this.deps.secrets.register(password, `password of ${username}`);
|
|
if (!opts.preserveRateLimit) await this.deps.hooks?.beforeLogin(username);
|
|
const started = Date.now();
|
|
const res = await this.ctx.post('/login', {
|
|
form: { username, password, next: opts.next ?? '/' },
|
|
headers: { Origin: this.origin, Accept: 'text/html', ...(opts.headers ?? {}) },
|
|
maxRedirects: 0,
|
|
});
|
|
const result = await this.wrap(res, started);
|
|
this.recordHttp('POST', '/login', { 'content-type': 'application/x-www-form-urlencoded' }, 0, result, username);
|
|
this.deps.ledger?.login(username, result.status, runnerAddress(), `api login ${username}`);
|
|
this.deps.hooks?.afterLogin(username, result.status);
|
|
if (result.status === 303) {
|
|
this.username = username;
|
|
const c = await this.cookie();
|
|
if (c) this.deps.secrets.register(c, `session cookie of ${username}`);
|
|
}
|
|
return result;
|
|
}
|
|
|
|
async logout(opts: { sessionValid?: boolean } = {}): Promise<ApiResult> {
|
|
const started = Date.now();
|
|
const res = await this.ctx.post('/logout', { headers: { Origin: this.origin, Accept: 'text/html' }, maxRedirects: 0 });
|
|
const result = await this.wrap(res, started);
|
|
this.recordHttp('POST', '/logout', {}, 0, result, this.username);
|
|
this.deps.ledger?.logout(this.username, result.status, runnerAddress(), opts.sessionValid ?? true, `api logout ${this.username}`);
|
|
this.username = '';
|
|
return result;
|
|
}
|
|
|
|
async page(path: string, opts: RequestOptions = {}): Promise<ApiResult> {
|
|
return this.raw('GET', path, { ...opts, audit: 'none' });
|
|
}
|
|
|
|
async raw(method: string, path: string, opts: RequestOptions = {}): Promise<ApiResult> {
|
|
const headers: Record<string, string> = { ...(opts.headers ?? {}) };
|
|
const origin = opts.origin ?? 'same';
|
|
if (UNSAFE.has(method.toUpperCase()) && origin !== 'none') headers.Origin = origin === 'same' ? this.origin : origin;
|
|
if (opts.ifMatch !== undefined) headers['If-Match'] = opts.ifMatch;
|
|
let data: string | Buffer | undefined;
|
|
if (opts.raw !== undefined) {
|
|
data = opts.raw;
|
|
if (opts.contentType !== null) headers['Content-Type'] = opts.contentType ?? 'application/json';
|
|
} else if (opts.body !== undefined) {
|
|
data = JSON.stringify(opts.body);
|
|
if (opts.contentType !== null) headers['Content-Type'] = opts.contentType ?? 'application/json';
|
|
}
|
|
let url = path;
|
|
if (opts.query) {
|
|
const params = new URLSearchParams();
|
|
for (const [k, v] of Object.entries(opts.query)) if (v !== undefined) params.set(k, String(v));
|
|
const qs = params.toString();
|
|
if (qs) url += (url.includes('?') ? '&' : '?') + qs;
|
|
}
|
|
const started = Date.now();
|
|
const res = await this.ctx.fetch(url, { method, headers, data, maxRedirects: 0, timeout: opts.timeoutMs ?? 90_000 });
|
|
const result = await this.wrap(res, started);
|
|
const bodyBytes = data === undefined ? 0 : Buffer.byteLength(data);
|
|
this.recordHttp(method, url, headers, bodyBytes, result, this.username);
|
|
const audit = opts.audit ?? 'auto';
|
|
if (audit !== 'none' && this.deps.ledger) {
|
|
const crossOrigin = origin !== 'same' && origin !== 'none' && UNSAFE.has(method.toUpperCase());
|
|
const fetchSite = Object.entries(headers).find(([k]) => k.toLowerCase() === 'sec-fetch-site')?.[1];
|
|
this.deps.ledger.api({
|
|
method,
|
|
path: url,
|
|
status: result.status,
|
|
actor: this.username,
|
|
origin: runnerAddress(),
|
|
body: result.text,
|
|
sessionValid: this.username !== '' && result.status !== 401,
|
|
crossOrigin: crossOrigin || (fetchSite !== undefined && fetchSite !== 'same-origin' && fetchSite !== 'none' && UNSAFE.has(method.toUpperCase())),
|
|
optional: audit === 'optional',
|
|
source: `api ${method} ${url} as ${this.username || '(no session)'}`,
|
|
});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
get(path: string, opts: RequestOptions = {}): Promise<ApiResult> {
|
|
return this.raw('GET', `/api/v1${path}`, opts);
|
|
}
|
|
|
|
post(path: string, body?: unknown, opts: RequestOptions = {}): Promise<ApiResult> {
|
|
return this.raw('POST', `/api/v1${path}`, { body, ...opts });
|
|
}
|
|
|
|
put(path: string, body?: unknown, opts: RequestOptions = {}): Promise<ApiResult> {
|
|
return this.raw('PUT', `/api/v1${path}`, { body, ...opts });
|
|
}
|
|
|
|
delete(path: string, body?: unknown, opts: RequestOptions = {}): Promise<ApiResult> {
|
|
return this.raw('DELETE', `/api/v1${path}`, { body, ...opts });
|
|
}
|
|
|
|
forgetSession(): void {
|
|
this.username = '';
|
|
}
|
|
|
|
private async wrap(res: APIResponse, started: number): Promise<ApiResult> {
|
|
const text = await res.text().catch(() => '');
|
|
let json: any = undefined;
|
|
try {
|
|
json = text ? JSON.parse(text) : undefined;
|
|
} catch {
|
|
json = undefined;
|
|
}
|
|
const headers = res.headers();
|
|
const setCookie = res
|
|
.headersArray()
|
|
.filter((h) => h.name.toLowerCase() === 'set-cookie')
|
|
.map((h) => h.value)
|
|
.join('\n');
|
|
return { status: res.status(), headers, text, json, etag: headers['etag'] ?? null, durationMs: Date.now() - started, setCookie };
|
|
}
|
|
|
|
private recordHttp(method: string, url: string, headers: Record<string, string>, bodyBytes: number, r: ApiResult, actor: string): void {
|
|
this.deps.recorder.addHttp({
|
|
client: 'api',
|
|
actor,
|
|
method,
|
|
url,
|
|
requestHeaders: this.deps.secrets.redactValue(headers),
|
|
requestBodyBytes: bodyBytes,
|
|
status: r.status,
|
|
responseHeaders: this.deps.secrets.redactValue(r.headers),
|
|
bodyPreview: this.deps.secrets.redact(r.text),
|
|
durationMs: r.durationMs,
|
|
});
|
|
}
|
|
|
|
async dispose(): Promise<void> {
|
|
if (this.disposed) return;
|
|
this.disposed = true;
|
|
await this.ctx.dispose();
|
|
}
|
|
}
|
|
|
|
export function zp(zone: string): string {
|
|
return `/zones/${encodeURIComponent(zone)}`;
|
|
}
|
|
|
|
export function up(username: string): string {
|
|
return `/users/${encodeURIComponent(username)}`;
|
|
}
|