test(e2e): address self-review follow-ups (dedup, XSS render guard, SSE hardening)
Follow-ups from the code review of the test-quality batches: - Consolidate duplicated helpers into e2e/helpers/: seed.ts (seedUpload, seedComment, listComments, findFeedRow) and sse.ts (mintSseTicket, openStream, trackStreamOpens). Refactor authorization-deep, xss-injection, like-comment, sse-ticket-abuse, ddos, sse-realtime, multi-tab, and SseListener to use them — the upload/comment/ticket-flow contracts now live in one place each instead of being re-inlined across 3–7 specs. - xss-injection display-name loop: it navigated to /feed (which renders uploader names, not the viewer's) so "nothing fired" passed vacuously — the payload was never rendered. Now navigate to /account (the actual sink) and add a render guard asserting the payload reached the DOM as escaped text before checking __xssFired. - sse-realtime reconnect: snapshot the stream-open count AFTER backgrounding, so the "new connection" assertion is attributable to the foreground event and can't be satisfied by a spurious native/error reconnect before the toggle. - recover-page: correct the comment (auto-submit is the onPinInput handler, not an $effect). 44 affected specs verified green. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -5,37 +5,10 @@
|
||||
* with cross-user and banned-user scenarios that span multiple resources.
|
||||
*/
|
||||
import { test, expect } from '../../fixtures/test';
|
||||
import { uploadRaw, JPEG_MAGIC } from '../../helpers/upload-client';
|
||||
import { seedUpload, seedComment, listComments, findFeedRow } from '../../helpers/seed';
|
||||
|
||||
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
|
||||
|
||||
/** Seed a real upload owned by `jwt` and return its id. */
|
||||
async function seedUpload(jwt: string, caption?: string): Promise<string> {
|
||||
const body = new Uint8Array(1024);
|
||||
body.set(JPEG_MAGIC, 0);
|
||||
const res = await uploadRaw(jwt, body, { filename: 'a.jpg', contentType: 'image/jpeg', caption });
|
||||
if (res.status !== 201) throw new Error(`seed upload failed: ${res.status} ${await res.text()}`);
|
||||
return (await res.json()).id;
|
||||
}
|
||||
|
||||
/** Seed a real comment on `uploadId` authored by `jwt`; return its id. */
|
||||
async function seedComment(jwt: string, uploadId: string, body = 'mine'): Promise<string> {
|
||||
const res = await fetch(`${BASE}/api/v1/upload/${uploadId}/comments`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${jwt}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ body }),
|
||||
});
|
||||
if (res.status !== 201) throw new Error(`seed comment failed: ${res.status} ${await res.text()}`);
|
||||
return (await res.json()).id;
|
||||
}
|
||||
|
||||
async function listComments(jwt: string, uploadId: string): Promise<any[]> {
|
||||
const res = await fetch(`${BASE}/api/v1/upload/${uploadId}/comments`, {
|
||||
headers: { Authorization: `Bearer ${jwt}` },
|
||||
});
|
||||
return res.json();
|
||||
}
|
||||
|
||||
test.describe('Adversarial — deep authorization', () => {
|
||||
// IDOR: user B must not be able to delete user A's REAL comment. This exercises the
|
||||
// ownership guard (`comment.user_id != auth.user_id` → 403) — the previous version fired
|
||||
@@ -87,13 +60,12 @@ test.describe('Adversarial — deep authorization', () => {
|
||||
});
|
||||
|
||||
// IDOR: user B must not be able to edit (re-caption / re-tag) user A's upload.
|
||||
test('user B cannot edit user A\'s upload caption (403, caption unchanged)', async ({ guest, db }) => {
|
||||
test('user B cannot edit user A\'s upload caption (403, caption unchanged)', async ({ guest }) => {
|
||||
const a = await guest('UploadOwnerA2');
|
||||
const b = await guest('AttackerB3');
|
||||
|
||||
const uploadId = await seedUpload(a.jwt, 'original caption');
|
||||
// Make it visible in the feed so we can read the caption back.
|
||||
await db.setUploadCompressionStatus(uploadId, 'done');
|
||||
// seedUpload marks compression done, so the upload is feed-visible for the read-back.
|
||||
const uploadId = await seedUpload(a.jwt, { caption: 'original caption' });
|
||||
|
||||
const res = await fetch(`${BASE}/api/v1/upload/${uploadId}`, {
|
||||
method: 'PATCH',
|
||||
@@ -104,9 +76,7 @@ test.describe('Adversarial — deep authorization', () => {
|
||||
|
||||
// No state change: the caption A set is intact.
|
||||
const feedRes = await fetch(`${BASE}/api/v1/feed`, { headers: { Authorization: `Bearer ${a.jwt}` } });
|
||||
const feed: any = await feedRes.json();
|
||||
const list: any[] = feed.uploads ?? feed.items ?? feed;
|
||||
const row = list.find((u: any) => u.id === uploadId);
|
||||
const row = findFeedRow(await feedRes.json(), uploadId);
|
||||
expect(row?.caption).toBe('original caption');
|
||||
});
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
* or rejected gracefully without crashing the backend.
|
||||
*/
|
||||
import { test, expect } from '../../fixtures/test';
|
||||
import { mintSseTicket } from '../../helpers/sse';
|
||||
|
||||
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
|
||||
|
||||
@@ -48,15 +49,9 @@ test.describe('Adversarial — small-scale abuse', () => {
|
||||
const g = await guest('SseFlood');
|
||||
// The stream endpoint authenticates via single-use tickets (POST /stream/ticket),
|
||||
// not the raw JWT — a `?token=` open is rejected with 400. Mint one ticket per stream.
|
||||
const mintTicket = async () => {
|
||||
const res = await fetch(`${BASE}/api/v1/stream/ticket`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${g.jwt}` },
|
||||
});
|
||||
const json: any = await res.json();
|
||||
return json.ticket as string;
|
||||
};
|
||||
const tickets = await Promise.all(Array.from({ length: 10 }, mintTicket));
|
||||
// (These streams must be held open concurrently, so we can't use the openStream
|
||||
// helper which opens-and-aborts a single stream.)
|
||||
const tickets = await Promise.all(Array.from({ length: 10 }, () => mintSseTicket(g.jwt)));
|
||||
|
||||
const controllers = tickets.map(() => new AbortController());
|
||||
const requests = tickets.map((ticket, i) =>
|
||||
|
||||
@@ -7,31 +7,10 @@
|
||||
* on first use so it cannot be replayed.
|
||||
*/
|
||||
import { test, expect } from '../../fixtures/test';
|
||||
import { mintSseTicket, openStream } from '../../helpers/sse';
|
||||
|
||||
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
|
||||
|
||||
async function mintTicket(jwt: string): Promise<string> {
|
||||
const res = await fetch(`${BASE}/api/v1/stream/ticket`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${jwt}` },
|
||||
});
|
||||
if (res.status !== 200) throw new Error(`mint failed: ${res.status} ${await res.text()}`);
|
||||
return (await res.json()).ticket;
|
||||
}
|
||||
|
||||
/** Open the SSE stream with a ticket, return the HTTP status, and tear the stream down. */
|
||||
async function openStream(ticket: string): Promise<number> {
|
||||
const c = new AbortController();
|
||||
try {
|
||||
const res = await fetch(`${BASE}/api/v1/stream?ticket=${encodeURIComponent(ticket)}`, {
|
||||
signal: c.signal,
|
||||
});
|
||||
return res.status;
|
||||
} finally {
|
||||
c.abort();
|
||||
}
|
||||
}
|
||||
|
||||
test.describe('Adversarial — SSE ticket abuse', () => {
|
||||
test('minting a ticket requires authentication', async () => {
|
||||
const res = await fetch(`${BASE}/api/v1/stream/ticket`, { method: 'POST' });
|
||||
@@ -40,7 +19,7 @@ test.describe('Adversarial — SSE ticket abuse', () => {
|
||||
|
||||
test('a ticket is single-use: replay after first open is rejected', async ({ guest }) => {
|
||||
const g = await guest('SseReplay');
|
||||
const ticket = await mintTicket(g.jwt);
|
||||
const ticket = await mintSseTicket(g.jwt);
|
||||
|
||||
// First open consumes the ticket.
|
||||
expect(await openStream(ticket)).toBe(200);
|
||||
|
||||
@@ -12,22 +12,10 @@
|
||||
* / a navigation to a `javascript:` URL.
|
||||
*/
|
||||
import { test, expect } from '../../fixtures/test';
|
||||
import { uploadRaw, JPEG_MAGIC } from '../../helpers/upload-client';
|
||||
import { seedUpload, seedComment } from '../../helpers/seed';
|
||||
|
||||
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
|
||||
|
||||
/** Seed a real, feed-visible upload owned by `jwt`; returns its id. */
|
||||
async function seedVisibleUpload(jwt: string, caption: string, db: any): Promise<string> {
|
||||
const body = new Uint8Array(1024);
|
||||
body.set(JPEG_MAGIC, 0);
|
||||
const res = await uploadRaw(jwt, body, { filename: 'x.jpg', contentType: 'image/jpeg', caption });
|
||||
if (res.status !== 201) throw new Error(`seed upload failed: ${res.status} ${await res.text()}`);
|
||||
const { id } = await res.json();
|
||||
// Mark compression done so the card is fully rendered in the feed.
|
||||
await db.setUploadCompressionStatus(id, 'done');
|
||||
return id;
|
||||
}
|
||||
|
||||
const XSS_PAYLOADS = [
|
||||
`<script>window.__xssFired=true</script>`,
|
||||
`<img src=x onerror="window.__xssFired=true">`,
|
||||
@@ -76,9 +64,16 @@ test.describe('Adversarial — input injection (display name)', () => {
|
||||
d.dismiss().catch(() => {});
|
||||
});
|
||||
|
||||
await page.goto('/feed');
|
||||
// /account is where the viewer's own display name is rendered (the sink). /feed
|
||||
// shows uploader names, not the viewer's — navigating there rendered nothing, so
|
||||
// the non-firing check passed vacuously. Go where the payload actually lands.
|
||||
await page.goto('/account');
|
||||
await page.waitForLoadState('domcontentloaded');
|
||||
|
||||
// Render guard: confirm the payload actually reached the DOM as escaped text,
|
||||
// so a "nothing fired" pass can't be because the name was never rendered.
|
||||
await expect(page.getByText(payload, { exact: false }).first()).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
const fired = await page.evaluate(() => (window as any).__xssFired === true);
|
||||
expect(fired, 'window.__xssFired should never be set').toBe(false);
|
||||
expect(dialogs, 'no dialogs should appear').toHaveLength(0);
|
||||
@@ -92,11 +87,11 @@ test.describe('Adversarial — input injection (display name)', () => {
|
||||
|
||||
test.describe('Adversarial — stored XSS (caption)', () => {
|
||||
for (const payload of XSS_PAYLOADS) {
|
||||
test(`caption with XSS payload ${JSON.stringify(payload).slice(0, 40)} renders inert`, async ({ guest, db, page, signIn }) => {
|
||||
test(`caption with XSS payload ${JSON.stringify(payload).slice(0, 40)} renders inert`, async ({ guest, page, signIn }) => {
|
||||
const g = await guest('CapXss');
|
||||
// A trailing marker lets us wait until the caption has actually rendered before
|
||||
// asserting nothing fired — otherwise a caption that never rendered would pass vacuously.
|
||||
const id = await seedVisibleUpload(g.jwt, `${payload} CAPMARK`, db);
|
||||
const id = await seedUpload(g.jwt, { caption: `${payload} CAPMARK` });
|
||||
expect(id).toMatch(/^[0-9a-f-]{36}$/);
|
||||
|
||||
const dialogs: string[] = [];
|
||||
@@ -123,16 +118,11 @@ test.describe('Adversarial — stored XSS (comment)', () => {
|
||||
`"><svg onload="window.__xssFired=true">`,
|
||||
];
|
||||
for (const payload of COMMENT_PAYLOADS) {
|
||||
test(`comment with XSS payload ${JSON.stringify(payload).slice(0, 40)} renders inert`, async ({ guest, db, page, signIn }) => {
|
||||
test(`comment with XSS payload ${JSON.stringify(payload).slice(0, 40)} renders inert`, async ({ guest, page, signIn }) => {
|
||||
const author = await guest('CmtXss');
|
||||
const id = await seedVisibleUpload(author.jwt, 'pic CAPMARK', db);
|
||||
const id = await seedUpload(author.jwt, { caption: 'pic CAPMARK' });
|
||||
// Post the XSS comment via the API (verbatim storage).
|
||||
const cRes = await fetch(`${BASE}/api/v1/upload/${id}/comments`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${author.jwt}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ body: `${payload} CMTMARK` }),
|
||||
});
|
||||
expect(cRes.status).toBe(201);
|
||||
await seedComment(author.jwt, id, `${payload} CMTMARK`);
|
||||
|
||||
const dialogs: string[] = [];
|
||||
page.on('dialog', (d) => { dialogs.push(d.message()); d.dismiss().catch(() => {}); });
|
||||
|
||||
Reference in New Issue
Block a user