Files
jobtrackingapp/job-tracker-ui/e2e/phase7-admin-audit.spec.ts
T

123 lines
15 KiB
TypeScript

import AxeBuilder from '@axe-core/playwright';
import { expect, test as base, type APIRequestContext, type APIResponse, type Locator, type Page, type TestInfo } from '@playwright/test';
import { translations } from '../src/i18n/translations';
const apiUrl = 'http://localhost:5302/api';
const password = 'E2ePassword123!';
type Language = 'en' | 'nb';
type Headers = Record<string, string>;
type Owner = { id: string; email: string; headers: Headers };
type RequestRecord = { channel: 'browser' | 'api'; method: string; path: string; query: string; status?: number };
type Session = { owner: Owner; admin: APIRequestContext; adminHeaders: Headers; requests: RequestRecord[] };
const boundary = 'Actual isolated API/Identity/CSRF administrators and ordinary owners exercise owned job soft-delete/Restore and authorized cross-owner Admin Audit Undo, persisted readback, unsupported400, foreign ordinary-Restore404 and non-admin403. No account deletion, provider/model/billing/probe/maintenance, production or Phase8 action occurs. The named Audit GET503 is controlled; read Retry does not replay writes. Google Fonts stylesheets are aborted and other nonlocal requests rejected. Named table horizontal scrolling is intentional and keyboard verified; human reader/device/zoom acceptance remains unverified.';
function copy(key: string, language: Language = 'en') { return (translations[language] as Record<string, string>)[key] ?? key; }
function browserRequests(session: Session, path: string, method?: string) { return session.requests.filter(value => value.channel === 'browser' && value.path === `/api${path}` && (!method || value.method === method)); }
async function call(records: RequestRecord[], api: APIRequestContext, method: 'GET' | 'POST' | 'PUT', path: string, headers?: Headers, data?: unknown) {
const result = await api.fetch(`${apiUrl}${path}`, { method, headers, data });
const url = new URL(result.url()); records.push({ channel: 'api', method, path: url.pathname, query: url.search, status: result.status() }); return result;
}
async function json<T>(response: Pick<APIResponse, 'status' | 'url' | 'json'>, status = 200): Promise<T> { expect(response.status(), response.url()).toBe(status); return response.json(); }
async function login(records: RequestRecord[], api: APIRequestContext, email: string): Promise<Owner> {
expect((await call(records, api, 'POST', '/auth/login', undefined, { email, password })).status()).toBe(200);
const me = await json<{ id: string; sessionContext: string }>(await call(records, api, 'GET', '/auth/me'));
const token = (await api.storageState()).cookies.find(value => value.name === 'XSRF-TOKEN'); expect(token).toBeDefined();
return { id: me.id, email, headers: { 'X-CSRF-TOKEN': token!.value, 'X-Session-Context': me.sessionContext } };
}
async function createOwner(records: RequestRecord[], admin: APIRequestContext, headers: Headers) {
const email = `p710-audit-${Date.now()}-${Math.random().toString(36).slice(2)}@example.test`;
expect((await call(records, admin, 'POST', '/users', headers, { email, password, roles: [] })).status()).toBe(200); return email;
}
const test = base.extend<{ session: Session }>({
session: async ({ page, context, playwright }, provide, info) => {
expect(process.env.PLAYWRIGHT_REUSE_SERVERS).not.toBe('true'); expect(info.config.metadata.isolatedDataRoot).toEqual(expect.any(String));
const records: RequestRecord[] = []; const forbidden: string[] = []; const fonts: string[] = []; const admin = await playwright.request.newContext();
context.on('request', request => { const url = new URL(request.url()); records.push({ channel: 'browser', method: request.method(), path: url.pathname, query: url.search }); });
context.on('response', result => { const url = new URL(result.url()); const record = [...records].reverse().find(value => value.channel === 'browser' && value.status === undefined && value.method === result.request().method() && value.path === url.pathname && value.query === url.search); if (record) record.status = result.status(); });
await context.route('**/*', route => {
const request = route.request(); const url = new URL(request.url());
if (url.protocol === 'https:' && url.hostname === 'fonts.googleapis.com' && url.port === '' && url.pathname === '/css2' && request.method() === 'GET' && request.resourceType() === 'stylesheet') { fonts.push(url.href); return route.abort(); }
const mailbox = /^\/api\/(gmail|microsoft-graph|imap)(?:\/|$)/.test(url.pathname);
const statusRead = request.method() === 'GET' && /^\/api\/(gmail|microsoft-graph|imap)\/status$/.test(url.pathname);
const ai = /^\/api\/ai(?:\/|$)/.test(url.pathname); const accountAiRead = request.method() === 'GET' && ['/api/ai/settings', '/api/ai/usage'].includes(url.pathname) || request.method() === 'PUT' && url.pathname === '/api/ai/settings';
if (mailbox && !statusRead || ai && !accountAiRead || /\/api\/(?:email\/send|billing\/(?:checkout|portal)|account-lifecycle\/delete|backup\/restore)(?:\/|$)/.test(url.pathname) || !['blob:', 'data:', 'about:'].includes(url.protocol) && (!['localhost', '127.0.0.1'].includes(url.hostname) || !['3300', '5302'].includes(url.port))) { forbidden.push(`${request.method()} ${url.origin}${url.pathname}`); return route.abort(); }
return route.continue();
});
await context.addInitScript(() => { if (!localStorage.getItem('uiLanguage')) localStorage.setItem('uiLanguage', 'en'); if (!localStorage.getItem('jobtracker.themeMode')) localStorage.setItem('jobtracker.themeMode', 'light'); });
try {
const administrator = await login(records, admin, 'e2e@example.test'); const email = await createOwner(records, admin, administrator.headers); const owner = await login(records, page.request, email);
expect((await json<{ entitlements: { ai: boolean } }>(await call(records, page.request, 'GET', '/auth/me'))).entitlements.ai).toBe(false);
await provide({ owner, admin, adminHeaders: administrator.headers, requests: records }); expect(forbidden).toEqual([]);
} finally { await info.attach('settings-preferences-boundary-and-requests', { body: JSON.stringify({ boundary, requests: records, forbiddenRequests: forbidden, abortedFontStylesheets: fonts }), contentType: 'application/json' }); await admin.dispose(); }
},
});
async function start(page: Page, path = '/settings', width = 1440) { await page.setViewportSize({ width, height: width < 768 ? 844 : 900 }); await page.emulateMedia({ reducedMotion: 'reduce' }); await page.goto(path); await expect(page.getByRole('main').getByRole('heading', { level: 1 })).toBeVisible(); }
async function keyboard(control: Locator) { await expect(control).toBeVisible(); await expect(control).toBeEnabled(); await control.focus(); await expect(control).toBeFocused(); await control.press('Enter'); }
async function capture(page: Page, info: TestInfo, name: string) {
const geometry = await page.getByRole('main').evaluate(main => {
const bounds = main.getBoundingClientRect(); const targets = Array.from(main.querySelectorAll('h1,h2,h3,p,button,input,[role="combobox"],[role="status"],.MuiFormControlLabel-root'));
// MUI Switch uses a transparent 300%-wide native input; its painted label/control remains in the checked targets.
// The named Audit region intentionally scrolls its table; keyboard reachability is tested separately.
return { width: innerWidth, rootOverflow: document.documentElement.scrollWidth - document.documentElement.clientWidth, outside: targets.filter(node => !node.closest('table') && node.getClientRects().length && getComputedStyle(node).visibility !== 'hidden' && !(node instanceof HTMLInputElement && getComputedStyle(node).opacity === '0')).map(node => ({ text: node.textContent?.slice(0, 90), left: node.getBoundingClientRect().left, right: node.getBoundingClientRect().right })).filter(rect => rect.left < bounds.left - 1 || rect.right > Math.min(bounds.right, innerWidth) + 1) };
});
await info.attach(`${name}-reflow`, { body: JSON.stringify(geometry), contentType: 'application/json' }); expect(geometry.rootOverflow).toBeLessThanOrEqual(1); expect(geometry.outside).toEqual([]);
await info.attach(name, { body: await page.screenshot({ fullPage: true, animations: 'disabled' }), contentType: 'image/png' });
const axe = await new AxeBuilder({ page }).analyze(); await info.attach(`${name}-axe`, { body: JSON.stringify({ violations: axe.violations, incomplete: axe.incomplete, qualification: 'All enabled axe rules; raw incomplete contexts retained for root triage, not human screen-reader acceptance.' }), contentType: 'application/json' }); expect(axe.violations).toEqual([]);
}
function response(page: Page, method: string, path: string) { return page.waitForResponse(value => value.request().method()===method && new URL(value.url()).pathname===`/api${path}`); }
type Event = { id: number; type: string; jobApplicationId: number };
async function makeJob(api: APIRequestContext, owner: Owner, title: string) {
const company=await json<{ id: number }>(await api.post(`${apiUrl}/companies`, { headers: owner.headers, data: { name: title+' AS' } }), 201);
return json<{ id: number }>(await api.post(`${apiUrl}/jobapplications`, { headers: owner.headers, data: { companyId: company.id, jobTitle: title, status: 'Saved' } }), 201);
}
async function events(api: APIRequestContext) { return json<Event[]>(await api.get(`${apiUrl}/admin/audit?take=200`)); }
function deletedRow(page: Page, title: string, language: Language='en') { return page.getByRole('row').filter({ hasText: title }).filter({ has: page.getByRole('button', { name: copy('adminAuditRestore', language), exact: true }) }); }
test('[P7-10 Audit A02 E09] persisted authorized Undo differs from ordinary owner-filtered Restore; unsupported and ordinary-user requests stay denied', async ({ page, playwright, session }) => {
const foreignTitle=`Foreign audit fixture ${Date.now()}`; const foreign=await makeJob(page.request, session.owner, foreignTitle);
expect((await page.request.delete(`${apiUrl}/jobapplications/${foreign.id}`, { headers: session.owner.headers })).status()).toBe(204);
const administrator=await login(session.requests, page.request, 'e2e@example.test');
const ownTitle=`Owned audit fixture ${Date.now()}`; const own=await makeJob(page.request, administrator, ownTitle);
expect((await page.request.delete(`${apiUrl}/jobapplications/${own.id}`, { headers: administrator.headers })).status()).toBe(204);
const initial=await events(page.request); const foreignDelete=initial.find(value => value.jobApplicationId===foreign.id && value.type==='Deleted'); expect(foreignDelete).toBeDefined();
const unsupported=initial.find(value => value.jobApplicationId===own.id && value.type==='Created'); expect(unsupported).toBeDefined();
expect((await page.request.post(`${apiUrl}/admin/audit/${unsupported!.id}/undo`, { headers: administrator.headers, data: {} })).status()).toBe(400);
await start(page, '/admin/audit', 390);
const denied=response(page, 'POST', `/jobapplications/${foreign.id}/restore`); await keyboard(deletedRow(page, foreignTitle).getByRole('button', { name: copy('adminAuditRestore'), exact: true })); expect((await denied).status()).toBe(404);
const undone=response(page, 'POST', `/admin/audit/${foreignDelete!.id}/undo`); await keyboard(deletedRow(page, foreignTitle).getByRole('button', { name: copy('adminAuditUndo'), exact: true })); expect((await undone).status()).toBe(200);
const restored=response(page, 'POST', `/jobapplications/${own.id}/restore`); await keyboard(deletedRow(page, ownTitle).getByRole('button', { name: copy('adminAuditRestore'), exact: true })); expect((await restored).status()).toBe(204);
expect((await page.request.get(`${apiUrl}/jobapplications/${own.id}`)).status()).toBe(200);
await page.reload(); await expect(deletedRow(page, ownTitle)).toBeVisible();
const other=await playwright.request.newContext();
try { const owner=await login(session.requests, other, session.owner.email); expect((await other.get(`${apiUrl}/jobapplications/${foreign.id}`)).status()).toBe(200); expect((await other.get(`${apiUrl}/admin/audit?take=200`)).status()).toBe(403); expect((await other.post(`${apiUrl}/admin/audit/${foreignDelete!.id}/undo`, { headers: owner.headers, data: {} })).status()).toBe(403); }
finally { await other.dispose(); }
expect((await events(page.request)).some(value => value.type==='Undo' && value.jobApplicationId===foreign.id)).toBe(true);
});
test('[P7-10 Audit A02 E08] failed read Retry remains GET-only and preserves the named focus target', async ({ page, session }, info) => {
await login(session.requests, page.request, 'e2e@example.test'); let failed=false;
await page.route(`${apiUrl}/admin/audit?take=200`, route => { if (!failed) { failed=true; return route.fulfill({ status: 503, json: { title: 'Controlled Audit unavailable' } }); } return route.continue(); });
await start(page, '/admin/audit', 390); await expect(page.getByRole('alert').filter({ hasText: copy('adminAuditLoadFailed') })).toBeVisible();
await keyboard(page.getByRole('button', { name: copy('retry'), exact: true }));
await expect(page.getByRole('region', { name: copy('adminAuditTitle'), exact: true })).toBeFocused(); await expect(page.getByRole('table', { name: copy('adminAuditTitle'), exact: true })).toBeVisible();
expect(session.requests.filter(value => value.channel==='browser' && value.method!=='GET')).toEqual([]);
await capture(page, info, 'audit-actual-read-recovery-en-light-390');
});
test('[P7-10 Audit A02] finite bilingual theme widths retain long event identity and keyboard table scrolling', async ({ page, session }, info) => {
test.setTimeout(180_000); const administrator=await login(session.requests, page.request, 'e2e@example.test');
const title=`Long owned audit event Æ Ø Å ${Date.now()} `+'International collaboration '.repeat(4); const own=await makeJob(page.request, administrator, title);
expect((await page.request.delete(`${apiUrl}/jobapplications/${own.id}`, { headers: administrator.headers })).status()).toBe(204);
const samples=[{ width: 320, language: 'nb', mode: 'dark' }, { width: 390, language: 'en', mode: 'light' }, { width: 768, language: 'nb', mode: 'light' }, { width: 1024, language: 'en', mode: 'dark' }, { width: 1440, language: 'en', mode: 'light' }, { width: 1920, language: 'nb', mode: 'dark' }] as const;
for (const sample of samples) {
expect((await call(session.requests, page.request, 'PUT', '/auth/preferences/language', administrator.headers, { language: sample.language==='nb' ? 'nb-NO' : 'en' })).status()).toBe(204);
await page.addInitScript(value => { localStorage.setItem('uiLanguage', value.language); localStorage.setItem('jobtracker.themeMode', value.mode); }, sample); await start(page, '/admin/audit', sample.width);
const region=page.getByRole('region', { name: copy('adminAuditTitle', sample.language), exact: true }); await region.focus(); await expect(region).toBeFocused();
const jobColumn=await region.getByRole('columnheader', { name: copy('adminAuditJob', sample.language), exact: true }).boundingBox(); expect(jobColumn).not.toBeNull(); expect(jobColumn!.width).toBeGreaterThanOrEqual(240);
const before=await region.evaluate(node => node.scrollLeft); await region.press('ArrowRight'); if (sample.width<1024) await expect.poll(() => region.evaluate(node => node.scrollLeft)).toBeGreaterThan(before);
await expect(deletedRow(page, title, sample.language)).toBeVisible(); await capture(page, info, `audit-long-event-${sample.width}-${sample.language}-${sample.mode}`);
}
expect(session.requests.filter(value => value.channel==='browser' && value.method!=='GET')).toEqual([]);
});