fix(audit-7): keepsake viewer integrity, readable archives, quota_tolerance floor

Seventh round, both defects in the keepsake — the one artifact that leaves the
system entirely, and so the one where a green server-side signal carries no
information at all.

Squashed from 2 commits, original messages preserved below.

──────── fix(export): stop a caption bricking the viewer, and ship readable archives

Two defects in the keepsake, both silent server-side and both only visible by
extracting the real artifact and trying to use it.

1. A CAPTION COULD BRICK THE VIEWER.

The viewer's data is inlined as `<script>window.__EXPORT_DATA__={…}</script>` -- it has
to be, since guests open index.html over file:// where fetching a sibling data.json is
blocked. The escape was `</` -> `<\/`. Against XSS that holds; I fired
`</script><img src=x onerror=…>` through a real Chromium parser and it round-trips
inert.

It does not stop the caption steering the HTML TOKENIZER. `<!--<script` with no later
`-->` drives the parser into script-data-double-escaped state, where the template's own
`</script>` only steps back to script-data-escaped instead of closing the element.
Everything after it -- including the viewer bundle -- is swallowed as script data.
Nothing executes and nothing leaks: `__EXPORT_DATA__` is simply never assigned and the
keepsake opens blank. A denial of the deliverable, not an XSS.

Reproduced in Chromium before changing anything, and the near-miss is worth recording:
`<!--<script>alert(1)</script>-->` comes back CLEAN, because the trailing `-->` returns
the parser to script-data state. A probe using the terminated form quietly repairs the
thing it is testing for.

Fix: escape every `<` as `<`, not just `</`. `<` never appears in JSON structural
syntax -- only inside string values -- so a global replace is sound, and one rule covers
`</script`, `<!--` and `<script` together. That is the point: the old escape was named
for the single case it handled. Only the INLINED copy is escaped; data.json is written
separately, in no HTML context, and stays literal.

2. EVERY ENTRY IN BOTH ARCHIVES WAS STORED MODE 0000.

`ZipEntryBuilder::new` leaves the external file attribute at zero and async_zip's host
compatibility defaults to Unix, so `unzip -Z` showed `?---------` on every line of both
Gallery.zip and Memories.zip. Windows Explorer ignores Unix modes, which is why this
survived; on Linux and macOS `unzip` faithfully applies what the archive asks for and
the guest gets a folder of photos none of which they can open.

Unconditional -- every keepsake ever produced, no hostile input required -- and
invisible server-side: the export succeeds, the ZIP is well-formed, the job writes
`done`, /export/status is green.

Found by accident. The browser test for defect 1 failed with ERR_ACCESS_DENIED on
file://, which looked exactly like a Playwright sandbox quirk; I twice "worked around"
it (fresh context, then a separately launched browser) before checking the extracted
files and finding mode 000. The workaround was suppressing a real bug. Both workarounds
are gone -- the ordinary `page` fixture loads the archive fine now.

Fix: all six ZipEntryBuilder sites route through one `keepsake_entry` helper stamping
`S_IFREG | 0644`, so the mode cannot be forgotten at a call site.

Tests: 3 unit (no `<` survives; the payload still decodes to the original value, because
this is a transport encoding and not a sanitiser; a clean payload is untouched) and 2
e2e that release for real, download the real archives, and check them from outside the
app -- one opening index.html over file:// in Chromium and asserting the viewer booted,
the captions came back verbatim and nothing executed; one asserting every stored mode
and every extracted file is readable. Both assertions verified to FAIL against the
pre-fix artifacts.

──────── fix(admin): reject quota_tolerance = 0 instead of silently blocking every upload

Zero is inside the documented 0–1 range and catastrophic. The per-user limit is
`free_disk * tolerance / active_uploaders`, so a tolerance of 0 makes every limit 0 and
refuses EVERY upload -- mid-event, with "Du hast dein Upload-Limit für dieses Event
erreicht", an error naming the wrong cause entirely. An admin reaching for an off-switch
wants `storage_quota_enabled`; the rejection now says so.

Rejecting the value rather than raising the floor. A floor of 0.01 was the obvious fix
and it is wrong: very small tolerances are legitimate -- they are how a large disk is
throttled down to a sensible per-guest ceiling, and how the quota specs steer it
(tolerance = target * active / free lands around 1e-5 on the 174 GB volume this suite
runs on). A floor would forbid real configurations, and would have broken the entire
storage-quota describe block, to prevent one typo. Verified: those four tests still pass.

Tests: the rejection, that the stored value is untouched (validation fully precedes any
write), and the mirror -- 0.00001 still round-trips -- so the guard can't quietly become
a floor later.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
fabi
2026-07-29 21:37:39 +02:00
parent 06bc9ddcb3
commit 08d92b7531
5 changed files with 396 additions and 8 deletions

View File

@@ -0,0 +1,103 @@
/**
* Regression guard — the keepsake extracts to files a guest can actually open.
*
* `ZipEntryBuilder::new` leaves the external file attribute at zero, and async_zip's host
* compatibility defaults to Unix — so every entry in BOTH archives was written with a stored mode
* of 0000. `unzip -Z` showed `?---------` on every line.
*
* Windows Explorer ignores Unix modes, which is exactly why this survived. On Linux and macOS,
* `unzip` faithfully applies what the archive asks for, and the guest gets a folder of photos none
* of which they can open — plus an index.html the browser refuses with ERR_ACCESS_DENIED.
*
* Unconditional: it affected every keepsake ever produced, no hostile input required. And it is
* invisible server-side — the export succeeds, the ZIP is well-formed, the job writes `done`,
* /export/status is green. The only way to see it is to extract the real artifact and try to read
* it, which is what this does.
*
* Found while chasing an unrelated ERR_ACCESS_DENIED that looked like a Playwright quirk.
*/
import { test, expect } from '../../fixtures/test';
import { execFileSync } from 'node:child_process';
import { mkdtempSync, writeFileSync, rmSync, readFileSync, statSync, readdirSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { seedUpload } from '../../helpers/seed';
import { BASE } from '../../helpers/env';
/** Walk every file under `dir`, ignoring the archives we dropped there ourselves. */
function walk(dir: string, skip: string[] = []): string[] {
return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
const p = join(dir, e.name);
if (e.isDirectory()) return walk(p, skip);
return skip.includes(e.name) ? [] : [p];
});
}
test.describe('Export — the archives extract to readable files', () => {
test('every entry in both keepsake archives is owner-readable', async ({ host, guest, db }) => {
test.setTimeout(120_000);
const bearer = { Authorization: `Bearer ${host.jwt}` };
const g = await guest('Archivist');
const id = await seedUpload(g.jwt, { caption: 'ein Foto' });
await expect.poll(() => db.compressionStatus(id), { timeout: 30_000 }).toBe('done');
expect(
(await fetch(`${BASE}/api/v1/host/gallery/release`, { method: 'POST', headers: bearer }))
.status
).toBe(204);
await expect
.poll(
async () => {
const res = await fetch(`${BASE}/api/v1/export/status`, { headers: bearer });
const s = await res.json();
return s.zip?.status === 'done' && s.html?.status === 'done';
},
{ timeout: 90_000, intervals: [500] }
)
.toBe(true);
for (const kind of ['zip', 'html'] as const) {
const ticketRes = await fetch(`${BASE}/api/v1/export/ticket`, {
method: 'POST',
headers: bearer,
});
const { ticket } = (await ticketRes.json()) as { ticket: string };
const dl = await fetch(`${BASE}/api/v1/export/${kind}?ticket=${encodeURIComponent(ticket)}`);
expect(dl.status, `downloading the ${kind} archive`).toBe(200);
const dir = mkdtempSync(join(tmpdir(), `eventsnap-perms-${kind}-`));
try {
const zipPath = join(dir, 'archive.zip');
writeFileSync(zipPath, Buffer.from(await dl.arrayBuffer()));
// The mode as STORED in the archive — this is what a guest's unzip will apply. Reading it
// from the central directory catches the defect even on a filesystem that would mask it.
const listing = execFileSync('unzip', ['-Z', zipPath], { encoding: 'utf8' });
const modes = listing
.split('\n')
.filter((l) => /^[?d-][rwx-]{9}\s/.test(l))
.map((l) => l.slice(0, 10));
expect(modes.length, `${kind}: no entries listed`).toBeGreaterThan(0);
for (const m of modes) {
expect(m, `${kind}: an entry is stored mode ${m} — the guest cannot open it`).toMatch(
/^.r[w-]-/
);
}
// And extraction really does produce readable files.
execFileSync('unzip', ['-qo', zipPath, '-d', dir]);
const files = walk(dir, ['archive.zip']);
expect(files.length, `${kind}: nothing extracted`).toBeGreaterThan(0);
for (const f of files) {
expect(statSync(f).mode & 0o400, `${f} is not owner-readable`).toBeTruthy();
// The assertion that matters to a guest: the bytes actually come out.
expect(() => readFileSync(f)).not.toThrow();
}
} finally {
rmSync(dir, { recursive: true, force: true });
}
}
});
});

View File

@@ -0,0 +1,125 @@
/**
* Regression guard — a guest-authored caption cannot brick the offline keepsake.
*
* The viewer's data is inlined as `<script>window.__EXPORT_DATA__={…};</script>` (it must be:
* guests open index.html over file://, where a cross-origin fetch of a sibling data.json is
* blocked). Captions and comments are guest text and land in that payload.
*
* The escape used to be `</` → `<\/`. Against XSS that holds — `</script><img src=x onerror=…>`
* round-trips inert. It does NOT stop the caption steering the HTML TOKENIZER: `<!--<script` with
* no later `-->` drives the parser into script-data-double-escaped state, where the template's own
* `</script>` steps back to script-data-escaped instead of closing the element. Everything after —
* including the viewer bundle — is swallowed as script data. Nothing executes and nothing leaks;
* `__EXPORT_DATA__` is never assigned and the keepsake renders blank.
*
* What makes it worth a browser-level test rather than a unit test alone: the failure is SILENT and
* POST-DISTRIBUTION. The export succeeds, the ZIP is well-formed, the job writes `done`,
* /export/status is green, and the host hands out a file that only fails when a guest
* double-clicks it — in every copy, unfixably. It is not visible by reading the escape. It is only
* visible by running a real parser over the real artifact, which is what this does: release, pull
* the actual Memories.zip, extract index.html, open it over file:// in Chromium, and assert the
* viewer actually booted.
*
* The near-miss worth recording: `<!--<script>alert(1)</script>-->` comes back CLEAN, because the
* trailing `-->` returns the parser to script-data state. A probe using the terminated form
* quietly repairs the very thing it is testing for. Only the unterminated variant exposes it.
*/
import { test, expect } from '../../fixtures/test';
import { execFileSync } from 'node:child_process';
import { mkdtempSync, writeFileSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { seedUpload } from '../../helpers/seed';
import { BASE } from '../../helpers/env';
/** Unterminated on purpose — see the header. The terminated form self-repairs. */
const TOKENIZER_PAYLOAD = '<!--<script';
/** The classic break-out. Already handled, kept so the fix can never regress on it. */
const BREAKOUT_PAYLOAD = '</script><img src=x onerror=window.__XSS__=1>';
test.describe('Export — a caption cannot brick the keepsake viewer', () => {
test('the exported viewer boots with a tokenizer-hostile caption in it', async ({
page,
host,
guest,
db,
}) => {
test.setTimeout(120_000);
const bearer = { Authorization: `Bearer ${host.jwt}` };
const g = await guest('Trickster');
const a = await seedUpload(g.jwt, { caption: TOKENIZER_PAYLOAD });
const b = await seedUpload(g.jwt, { caption: BREAKOUT_PAYLOAD });
for (const id of [a, b]) {
await expect.poll(() => db.compressionStatus(id), { timeout: 30_000 }).toBe('done');
}
expect(
(await fetch(`${BASE}/api/v1/host/gallery/release`, { method: 'POST', headers: bearer }))
.status
).toBe(204);
await expect
.poll(
async () => {
const res = await fetch(`${BASE}/api/v1/export/status`, { headers: bearer });
return (await res.json()).html?.status;
},
{ timeout: 90_000, intervals: [500] }
)
.toBe('done');
const ticketRes = await fetch(`${BASE}/api/v1/export/ticket`, {
method: 'POST',
headers: bearer,
});
const { ticket } = (await ticketRes.json()) as { ticket: string };
const dl = await fetch(`${BASE}/api/v1/export/html?ticket=${encodeURIComponent(ticket)}`);
expect(dl.status).toBe(200);
const dir = mkdtempSync(join(tmpdir(), 'eventsnap-viewer-'));
try {
const zipPath = join(dir, 'Memories.zip');
writeFileSync(zipPath, Buffer.from(await dl.arrayBuffer()));
// Extract the WHOLE archive: index.html pulls in the viewer's own JS/CSS, and the point of
// this test is that those later resources are still reachable by the parser.
execFileSync('unzip', ['-qo', zipPath, '-d', dir]);
// file://, not http://. That is how a guest actually opens the keepsake, and it is the
// whole reason the data is inlined rather than fetched from a sibling data.json.
let xss = false;
page.on('dialog', (d) => {
xss = true;
void d.dismiss();
});
await page.goto('file://' + join(dir, 'index.html'));
// 1. The payload was assigned at all. This is the assertion that fails on the old escape —
// the second script block is never reached, so the global stays undefined.
const captions = await page.evaluate(() => {
const d = (window as unknown as { __EXPORT_DATA__?: { posts?: { caption?: string }[] } })
.__EXPORT_DATA__;
return d?.posts?.map((p) => p.caption ?? '') ?? null;
});
expect(captions, '__EXPORT_DATA__ was never assigned — the viewer is bricked').not.toBeNull();
// 2. The captions survived verbatim. The escape is a transport encoding, not a sanitiser:
// a guest's text has to come back exactly, or we have silently rewritten their words.
expect(captions).toContain(TOKENIZER_PAYLOAD);
expect(captions).toContain(BREAKOUT_PAYLOAD);
// 3. And nothing executed.
expect(
await page.evaluate(() => (window as unknown as { __XSS__?: number }).__XSS__ === 1),
'the caption must be inert, not merely non-fatal'
).toBe(false);
expect(xss).toBe(false);
// 4. The viewer actually rendered — the whole document parsed, not just the head. If the
// tokenizer had swallowed the bundle, the body would be empty of viewer output.
await expect(page.locator('body')).not.toBeEmpty();
} finally {
rmSync(dir, { recursive: true, force: true });
}
});
});