Files
EventSnap/e2e/specs/07-adversarial/ddos.spec.ts
fabi 02971f3186 test(e2e): de-vacuum security tests; add quota, authz-sweep, keepsake-regen coverage
An audit found tests that pass on broken code. The dominant pattern: fire a security
assertion at the all-zeros UUID and accept [403, 404] — the 404 comes from the resource
LOOKUP, not the guard, so the guard can be deleted and the test still passes. Repaired to
use real resources and demand exactly 403:
  - banned-user cannot like / comment (the only coverage of those ban invariants)
  - host cannot promote a real guest (or self) to admin — asserts nobody's role changed
  - IDOR comment-delete already used a real resource; kept
Also inverted recovery.spec's "unknown name → nicht gefunden" test: that asserted the exact
account-enumeration oracle the F4 fix removed, so restoring the vuln would have made it
pass. Now: an unknown name must be byte-identical to a wrong PIN.

New coverage for paths that ran in production but in zero tests:
  - quota.spec.ts: storage quota enforcement (413 over-limit, atomic increment under two
    uploads held mid-body so both carry a stale total=0 — the real race; a naive Promise.all
    version was itself vacuous and is documented as such). Proven to fail without the guard.
  - authz-sweep.spec.ts: table-driven guest→403 / host→403 over ALL 19 privileged routes +
    anonymous + __truncate. No live hole found; the whole surface is now locked.
  - ban / unban / host-comment-delete AFTER release regenerate the keepsake (data-loss
    paths that were dead under test); comment-delete mid-build doesn't strand the ZIP.

Lower-severity de-vacuuming: 10 MB comment test hit Caddy's 502 before the real 500-char
cap (now seeds a real upload, 501→400 / 500→201, mutation-verified); XSS name payloads
shortened under the 50-char cap so they actually store+render; ui-rendering XSS test now
proves the payload rendered before asserting no <b>; export page-object locators fixed to
the real "Download" label with a positive empty-state anchor; avatar palette spread test.

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

117 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';
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
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);
});
});