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>
This commit is contained in:
fabi
2026-07-15 07:26:40 +02:00
parent e5201a9889
commit 02971f3186
13 changed files with 681 additions and 67 deletions

View File

@@ -110,7 +110,7 @@ test.describe('Adversarial — PIN brute-force', () => {
expect(correct.status).toBe(429);
});
test('parallel wrong-PIN attempts may NOT all hit lockout (race-condition finding)', async ({ guest }) => {
test('parallel wrong-PIN attempts still lock the account (counter is not lost to the race)', async ({ guest }) => {
const g = await guest('BruteParallel');
const wrong = g.pin === '0000' ? '1111' : '0000';
@@ -124,12 +124,22 @@ test.describe('Adversarial — PIN brute-force', () => {
)
);
const statuses = attempts.map((r) => r.status);
expect(statuses.filter((s) => s === 200)).toHaveLength(0);
// Documented behavior: lockout counter may race so not every status is 429.
// Critical invariant: no attempt succeeded.
if (!statuses.some((s) => s === 429)) {
console.warn('[finding] PIN-attempt counter races under parallel requests — none hit lockout.');
}
expect(statuses.filter((s) => s === 200), 'a wrong PIN must never authenticate').toHaveLength(0);
// The in-flight requests all read `pin_locked_until` before any of them wrote it, so
// *which* of the 10 come back 429 is genuinely racy and can't be asserted. What is NOT
// racy — and is the property this test exists to guard — is the state left behind:
// `failed_pin_attempts` is incremented with an atomic `SET x = x + 1 ... RETURNING`, so
// 10 wrong PINs must push it past the 3-strike threshold and leave the account locked.
//
// We prove that with a follow-up request using the CORRECT pin: it must be refused with
// 429 (locked), not 200. Delete the lockout counter and this line goes 200 → red.
const correct = await fetch(`${BASE}/api/v1/recover`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ display_name: g.displayName, pin: g.pin }),
});
expect(correct.status, 'after 10 wrong PINs the account must be locked, even for the right PIN').toBe(429);
});
});

View File

@@ -80,27 +80,39 @@ test.describe('Adversarial — deep authorization', () => {
expect(row?.caption).toBe('original caption');
});
// These two fire at a REAL upload, and demand exactly 403.
//
// They used to POST to the all-zeros UUID and accept `[403, 404]`. Both handlers check
// `user.is_banned` BEFORE they look the upload up (social.rs) — so the 404 came from the
// *lookup*, not the guard. Delete the ban check entirely and the request still 404s on the
// nonexistent upload, and both tests still passed. They were the only coverage of
// ban-blocks-like and ban-blocks-comment, and they guarded nothing.
test('banned user cannot toggle a like', async ({ api, host, guest }) => {
const target = await guest('BannedLike');
const uploadId = await seedUpload(host.jwt, { caption: 'likeable' });
await api.banUser(host.jwt, target.userId);
const res = await fetch(`${BASE}/api/v1/upload/00000000-0000-0000-0000-000000000000/like`, {
const res = await fetch(`${BASE}/api/v1/upload/${uploadId}/like`, {
method: 'POST',
headers: { Authorization: `Bearer ${target.jwt}` },
});
expect([403, 404]).toContain(res.status);
expect(res.status, 'a banned user must be Forbidden, not merely miss the resource').toBe(403);
});
test('banned user cannot post a comment', async ({ api, host, guest }) => {
const target = await guest('BannedComment');
const uploadId = await seedUpload(host.jwt, { caption: 'commentable' });
await api.banUser(host.jwt, target.userId);
const res = await fetch(`${BASE}/api/v1/upload/00000000-0000-0000-0000-000000000000/comments`, {
const res = await fetch(`${BASE}/api/v1/upload/${uploadId}/comments`, {
method: 'POST',
headers: { Authorization: `Bearer ${target.jwt}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ body: 'should be rejected' }),
});
expect([403, 404]).toContain(res.status);
expect(res.status, 'a banned user must be Forbidden, not merely miss the resource').toBe(403);
// ...and nothing was written.
expect(await listComments(host.jwt, uploadId)).toHaveLength(0);
});
test('banned user can still read the feed (read-only access preserved)', async ({ api, host, guest }) => {
@@ -130,15 +142,40 @@ test.describe('Adversarial — deep authorization', () => {
expect(stillWorks.status).toBe(200);
});
test('promote endpoint cannot be used to make oneself admin', async ({ host }) => {
const res = await fetch(`${BASE}/api/v1/host/users/${'00000000-0000-0000-0000-000000000000'}/role`, {
// Privilege escalation, tested against REAL targets.
//
// The old version PATCHed the all-zeros UUID and accepted `[400, 403, 404]`. The role whitelist
// rejects "admin" with a 400 before the target is ever looked up — so adding `"admin"` to the
// whitelist would make the request 404 on the nonexistent user instead, which was in the accepted
// list. It never promoted anyone, never targeted *oneself*, and could not detect escalation.
test('a host cannot promote a real guest to admin', async ({ api, host, guest, adminToken }) => {
const victim = await guest('EscalationTarget');
const res = await fetch(`${BASE}/api/v1/host/users/${victim.userId}/role`, {
method: 'PATCH',
headers: { Authorization: `Bearer ${host.jwt}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ role: 'admin' }),
});
// 400 (invalid role for host-callable endpoint) or 403/404.
expect([400, 403, 404]).toContain(res.status);
// Critically, NOT 200/204.
expect([200, 204]).not.toContain(res.status);
expect(res.status).not.toBe(204);
expect(res.status).not.toBe(200);
// The assertion that actually matters: nobody got promoted.
const users = await api.listUsers(adminToken);
const row = users.find((u: any) => u.id === victim.userId);
expect(row?.role, 'the guest must NOT have become an admin').not.toBe('admin');
});
test('a host cannot promote THEMSELVES to admin', async ({ api, host, adminToken }) => {
const res = await fetch(`${BASE}/api/v1/host/users/${host.userId}/role`, {
method: 'PATCH',
headers: { Authorization: `Bearer ${host.jwt}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ role: 'admin' }),
});
expect(res.status).not.toBe(204);
expect(res.status).not.toBe(200);
const users = await api.listUsers(adminToken);
const me = users.find((u: any) => u.id === host.userId);
expect(me?.role, 'the host must NOT have self-promoted to admin').not.toBe('admin');
});
});

View File

@@ -5,6 +5,7 @@
*/
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';
@@ -30,19 +31,50 @@ test.describe('Adversarial — small-scale abuse', () => {
expect(statuses.some((s) => s === 201 || s === 409)).toBe(true);
});
test('10 MB comment body is rejected (multipart-less endpoint)', async ({ guest }) => {
const g = await guest('BigComment');
const huge = 'A'.repeat(10 * 1024 * 1024);
const res = await fetch(`${BASE}/api/v1/upload/00000000-0000-0000-0000-000000000000/comments`, {
// 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 ${g.jwt}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ body: huge }),
headers: { Authorization: `Bearer ${jwt}`, 'Content-Type': 'application/json' },
body: JSON.stringify({ body }),
});
// 400 (length cap), 404 (no such upload), 413 (payload too large), 429 (rate-limited),
// or 502 (Caddy rejected the body before it reached the backend) — all fine.
expect([400, 404, 413, 429, 502]).toContain(res.status);
// Not 200 — that would mean we accepted a 10 MB comment.
expect(res.status).not.toBe(200);
}
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 }) => {

View File

@@ -26,14 +26,20 @@ test.describe('Adversarial — UI render escape', () => {
});
await page.goto('/account');
await page.waitForLoadState('domcontentloaded');
// Render guard FIRST. `domcontentloaded` fires before Svelte hydrates, so asserting
// the *absence* of a <b> at that point passes on a page that never rendered the name
// at all — a false green on an XSS test. Prove the payload actually reached the DOM
// (as escaped text) before concluding anything about how it was 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).toBe(false);
// <b> tag inside the name should also not render as bold — Svelte escapes the entire string.
const boldCount = await page.locator('b:has-text("BOLD")').count();
expect(boldCount).toBe(0);
// <b> tag inside the name should also not render as bold — Svelte escapes the entire
// string. toHaveCount auto-retries, so this can't win by racing hydration.
await expect(page.locator('b:has-text("BOLD")')).toHaveCount(0);
await expect(page.locator('script:has-text("__xssFired")')).toHaveCount(0);
});
test('rendering of a known SQL-injection-shaped name does not break the page', async ({ page, api }) => {

View File

@@ -16,15 +16,29 @@ import { seedUpload, seedComment } from '../../helpers/seed';
const BASE = process.env.E2E_FRONTEND_URL ?? 'http://localhost:3101';
/**
* Every payload sets `window.__x = 1` if it executes. The marker is deliberately terse:
* the join handler caps display names at 50 chars, and a payload that trips that cap is
* rejected at the API — which means it is NEVER stored and NEVER rendered, so the test
* that "nothing executed" proves nothing at all. Each payload below is < 50 chars, so it
* survives the join and actually reaches the render sink under test.
*/
const XSS_PAYLOADS = [
`<script>window.__xssFired=true</script>`,
`<img src=x onerror="window.__xssFired=true">`,
`"><svg onload="window.__xssFired=true">`,
`<iframe src="javascript:window.parent.__xssFired=true"></iframe>`,
`javascript:window.__xssFired=true`,
`<a href="javascript:window.__xssFired=true">click</a>`,
`<script>window.__x=1</script>`, // 29
`<img src=x onerror="window.__x=1">`, // 34
`"><svg onload="window.__x=1">`, // 29
`<iframe src="javascript:parent.__x=1"></iframe>`, // 47
`javascript:window.__x=1`, // 23
`<a href="javascript:window.__x=1">c</a>`, // 39
];
// Guard the invariant the payloads depend on: if the display-name cap ever changes, or a
// payload is edited past it, we want a loud failure here rather than six silent no-ops.
const NAME_MAX = 50;
for (const p of XSS_PAYLOADS) {
if (p.length > NAME_MAX) throw new Error(`XSS payload exceeds the ${NAME_MAX}-char display-name cap and would never be stored: ${p}`);
}
const SQLI_PAYLOADS = [
`'; DROP TABLE "user"; --`,
`' OR 1=1 --`,
@@ -35,19 +49,10 @@ const SQLI_PAYLOADS = [
test.describe('Adversarial — input injection (display name)', () => {
for (const payload of XSS_PAYLOADS) {
test(`name with XSS payload ${JSON.stringify(payload).slice(0, 40)} never executes`, async ({ api, page }) => {
// Payloads > 50 chars are rejected by the join handler — that's a valid defense.
// Only if the API accepts the payload do we proceed to assert it never executes
// when rendered.
let res;
try {
res = await api.join(payload);
} catch (e: any) {
if (/→ 400/.test(e.message ?? '')) {
// Defended at the API. No need to render.
return;
}
throw e;
}
// No try/catch escape hatch: every payload is short enough to be accepted, so a
// rejection here is a real failure (the payload would never be rendered, and the
// "nothing executed" assertions below would be vacuous).
const res = await api.join(payload);
expect(res.jwt).toBeTruthy();
// Render the name in the account page by signing in.
@@ -74,12 +79,12 @@ test.describe('Adversarial — input injection (display name)', () => {
// 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);
const fired = await page.evaluate(() => (window as any).__x === 1);
expect(fired, 'window.__x should never be set').toBe(false);
expect(dialogs, 'no dialogs should appear').toHaveLength(0);
// Inline script tag in the displayed name should be rendered as text, not parsed.
const scriptCount = await page.locator('script:has-text("window.__xssFired")').count();
const scriptCount = await page.locator('script:has-text("window.__x")').count();
expect(scriptCount, 'no executable script tags rendered from name').toBe(0);
});
}
@@ -101,11 +106,11 @@ test.describe('Adversarial — stored XSS (caption)', () => {
// Wait for the caption text to land in the DOM (escaped, as literal text).
await expect(page.getByText('CAPMARK', { exact: false }).first()).toBeVisible({ timeout: 10_000 });
expect(await page.evaluate(() => (window as any).__xssFired === true), 'caption XSS must not fire').toBe(false);
expect(await page.evaluate(() => (window as any).__x === 1), 'caption XSS must not fire').toBe(false);
expect(dialogs, 'no dialogs from a caption').toHaveLength(0);
// The payload must be inert text, not a live element / script.
expect(await page.locator('img[onerror]').count(), 'no live onerror img from caption').toBe(0);
expect(await page.locator('script:has-text("__xssFired")').count(), 'no executable script from caption').toBe(0);
expect(await page.locator('script:has-text("window.__x")').count(), 'no executable script from caption').toBe(0);
});
}
});
@@ -114,8 +119,8 @@ test.describe('Adversarial — stored XSS (comment)', () => {
// The two payloads that actually execute on render (script injection via innerHTML
// does not) — enough to prove the comment body is escaped without a slow 6× lightbox loop.
const COMMENT_PAYLOADS = [
`<img src=x onerror="window.__xssFired=true">`,
`"><svg onload="window.__xssFired=true">`,
`<img src=x onerror="window.__x=1">`,
`"><svg onload="window.__x=1">`,
];
for (const payload of COMMENT_PAYLOADS) {
test(`comment with XSS payload ${JSON.stringify(payload).slice(0, 40)} renders inert`, async ({ guest, page, signIn }) => {
@@ -139,7 +144,7 @@ test.describe('Adversarial — stored XSS (comment)', () => {
// Wait until the comment (marker) has rendered.
await expect(lightbox.getByText('CMTMARK', { exact: false })).toBeVisible({ timeout: 10_000 });
expect(await page.evaluate(() => (window as any).__xssFired === true), 'comment XSS must not fire').toBe(false);
expect(await page.evaluate(() => (window as any).__x === 1), 'comment XSS must not fire').toBe(false);
expect(dialogs, 'no dialogs from a comment').toHaveLength(0);
expect(await page.locator('img[onerror]').count(), 'no live onerror img from comment').toBe(0);
});