Files
EventSnap/e2e/specs/07-adversarial/ddos.spec.ts
fabi bbdfae09a0 chore(e2e): add ESLint + Prettier; fix real findings; dedupe BASE
The Playwright suite had no linter and no formatter — only tsc. Add flat-config ESLint
(typescript-eslint, type-aware) and Prettier (2-space, matching the suite's style).

Rules keep the ones that catch real TEST bugs and drop the noise:
  - no-floating-promises KEPT — an un-awaited request/assertion can let a test end before it runs,
    passing vacuously. It caught one: the SSE reader loop in sse-listener is now explicitly `void`.
  - no-unused-vars KEPT — caught three dead bindings (an unused adminToken fixture arg, an unused
    `api` arg, an unused JPEG_MAGIC import), all removed.
  - no-explicit-any OFF — all test code; `any` is the honest type for an untyped res.json() body or
    a page.evaluate() return.
  - no-empty-pattern OFF — Playwright's dependency-free fixtures are `async ({}, use) => {}`.

Refactor: `const BASE = process.env.E2E_FRONTEND_URL ?? '...'` was redeclared verbatim in 23
files — extracted to helpers/env.ts and imported, so a port/scheme change is one edit not a sweep.

Then `prettier --write`. Verified: eslint clean, tsc clean, prettier clean, desktop suite 210
passed / 1 skipped. (One mobile spec flaked once under retries:0 — a pre-existing cross-test
reflow-timing vector from the flakiness audit, not this change: the each-key edit is stable across
16 isolated runs and a clean full mobile re-run.)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-15 20:45:59 +02:00

120 lines
5.3 KiB
TypeScript

/**
* Phase 2 adversarial — small-scale DDoS / oversized-body tests. These are
* NOT real load tests. We just verify that obvious abuse is rate-limited
* or rejected gracefully without crashing the backend.
*/
import { test, expect } from '../../fixtures/test';
import { mintSseTicket } from '../../helpers/sse';
import { seedUpload } from '../../helpers/seed';
import { BASE } from '../../helpers/env';
test.describe('Adversarial — small-scale abuse', () => {
// Note: the truncate auto-fixture resets every rate-limit toggle back to false
// before each test, so we re-enable in beforeEach (not beforeAll).
test.beforeEach(async ({ api, adminToken }) => {
await api.patchConfig(adminToken, { rate_limits_enabled: 'true', join_rate_enabled: 'true' });
});
test('20 parallel /join from one IP — rate limiter catches the excess', async () => {
const requests = Array.from({ length: 20 }, (_, i) =>
fetch(`${BASE}/api/v1/join`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ display_name: `Flood${i}_${Date.now()}` }),
})
);
const statuses = (await Promise.all(requests)).map((r) => r.status);
// 5/min limit → at least some should be 429.
expect(statuses.filter((s) => s === 429).length).toBeGreaterThan(0);
// Server stays up — at least one succeeded.
expect(statuses.some((s) => s === 201 || s === 409)).toBe(true);
});
// The comment body cap lives in [backend/src/handlers/social.rs] `add_comment`:
// if text_chars == 0 || text_chars > 500 → 400
// It must be exercised against a REAL upload: the handler looks the upload up (and
// 404s) *before* it reaches the length check, so posting to a non-existent id proves
// nothing about the cap.
async function postComment(jwt: string, uploadId: string, body: string) {
return fetch(`${BASE}/api/v1/upload/${uploadId}/comments`, {
method: 'POST',
headers: { Authorization: `Bearer ${jwt}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ body }),
});
}
test('comment body over the 500-char cap is rejected with 400', async ({ guest }) => {
const g = await guest('LongComment');
const uploadId = await seedUpload(g.jwt);
const res = await postComment(g.jwt, uploadId, 'A'.repeat(501));
expect(res.status, '501 chars must be rejected by the length cap').toBe(400);
const json: any = await res.json().catch(() => ({}));
expect((json.message ?? '').toLowerCase()).toMatch(/500 zeichen/);
});
test('comment body exactly at the 500-char cap is accepted', async ({ guest }) => {
const g = await guest('MaxComment');
const uploadId = await seedUpload(g.jwt);
// The boundary must be inclusive — otherwise the "cap" is really 499 and the
// rejection test above would also pass on an off-by-one implementation.
const res = await postComment(g.jwt, uploadId, 'A'.repeat(500));
expect(res.status, '500 chars is the documented maximum and must be accepted').toBe(201);
});
test('10 MB comment body never reaches the handler (body-size limit rejects it)', async ({
guest,
}) => {
const g = await guest('BigComment');
const uploadId = await seedUpload(g.jwt);
const huge = 'A'.repeat(10 * 1024 * 1024);
const res = await postComment(g.jwt, uploadId, huge);
// This asserts ONLY what it can prove: a 10 MB JSON body is refused somewhere on the
// path (Caddy's request-body limit → 502/413, or the backend's own body limit → 413,
// or the 500-char cap if it does get through → 400). The upload exists, so a 404 here
// would be a bug, and a 201 would mean we stored a 10 MB comment.
expect([400, 413, 502]).toContain(res.status);
});
test('SSE: 10 concurrent streams from one user do not crash the server', async ({ guest }) => {
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.
// (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) =>
fetch(`${BASE}/api/v1/stream?ticket=${encodeURIComponent(ticket)}`, {
signal: controllers[i].signal,
})
);
const responses = await Promise.all(requests);
// All accepted (or some rate-limited — both fine).
for (const r of responses) {
expect([200, 429]).toContain(r.status);
}
// Tear them all down so the next test doesn't see leaked connections.
controllers.forEach((c) => c.abort());
// Sanity: a new request still works.
const ping = await fetch(`${BASE}/api/v1/me/context`, {
headers: { Authorization: `Bearer ${g.jwt}` },
});
expect(ping.status).toBe(200);
});
test('malformed JSON in /join is rejected with 400, not 500', async () => {
const res = await fetch(`${BASE}/api/v1/join`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: '{"display_name":',
});
expect([400, 422]).toContain(res.status);
expect(res.status).not.toBe(500);
});
});