Skip to content

Commit 186218e

Browse files
Fix Zero-Knowledge uploads storing 0 bytes (files unrecoverable)
ZK uploads were writing zero bytes to storage, so vault files showed '0 B' and could never be decrypted on download. Two root causes, both in apps/api/src/routes/zk.ts: 1. capStream counted bytes by attaching a raw source.on('data') listener and returning the same stream. That flips the source into flowing mode and the counting listener consumes the data before storage.write's pipeline attaches, so nothing reaches disk. Rewrote capStream as a pass-through Transform wired with stream.pipeline (callback absorbs the terminal error so an over-size upload can't surface as an uncaught exception, while still tearing down the limiter so the consumer's pipeline rejects -> 413). 2. The handler iterated req.parts() and broke on the file part, consuming it later — but breaking lets @fastify/multipart drain the unread file stream. Switched to req.file() (which exposes the preceding 'meta' field) and consume the stream in place; reject genuinely empty uploads. Added regression tests: ZK ciphertext round-trips byte-for-byte with non-zero size, and an over-quota ZK upload returns 413. 43 tests pass. Note: vault files uploaded before this fix are physically 0 bytes and cannot be recovered; re-upload them.
1 parent 3492e74 commit 186218e

2 files changed

Lines changed: 113 additions & 26 deletions

File tree

‎apps/api/src/routes/zk.ts‎

Lines changed: 53 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,34 @@ import { adjustUsage, remainingAllowance } from '../services/quota.js';
1212
import { trashFile } from '../services/trash.js';
1313
import { audit } from '../services/audit.js';
1414
import { FileTooLargeError } from '../services/ingest.js';
15-
import type { Readable } from 'node:stream';
15+
import { Transform, pipeline, type Readable } from 'node:stream';
1616

17-
/** Cap a stream at `maxBytes`, destroying it (and signalling) if exceeded. */
17+
/**
18+
* Cap a stream at `maxBytes`, failing (with FileTooLargeError) if exceeded. Implemented as a
19+
* pass-through Transform that counts bytes as they flow through, then returned for the consumer
20+
* to pipe into storage.
21+
*
22+
* NOTE: do not count by adding a raw `source.on('data')` listener and returning the same stream
23+
* — that flips the source into flowing mode and the bytes get consumed before the consumer's
24+
* pipeline attaches, so nothing is written (this caused ZK uploads to store 0 bytes). We wire
25+
* source -> limiter with stream.pipeline whose callback absorbs the terminal error (so an
26+
* over-size source can't surface as an uncaught exception); the error still tears down the
27+
* limiter, so the consumer's pipeline rejects with it and the upload returns 413.
28+
*/
1829
function capStream(source: Readable, maxBytes: number): Readable {
1930
let total = 0;
20-
source.on('data', (chunk: Buffer) => {
21-
total += chunk.length;
22-
if (total > maxBytes) source.destroy(new FileTooLargeError());
31+
const limiter = new Transform({
32+
transform(chunk: Buffer, _enc, cb) {
33+
total += chunk.length;
34+
if (total > maxBytes) {
35+
cb(new FileTooLargeError());
36+
return;
37+
}
38+
cb(null, chunk);
39+
},
2340
});
24-
return source;
41+
pipeline(source, limiter, () => {});
42+
return limiter;
2543
}
2644

2745
export const zkRoutes: FastifyPluginAsync = async (app) => {
@@ -54,40 +72,49 @@ export const zkRoutes: FastifyPluginAsync = async (app) => {
5472
});
5573

5674
// POST /zk/files — multipart with a `meta` JSON field followed by the `file` blob.
75+
// We use req.file(): it exposes fields that arrived before the file (our `meta`) and hands
76+
// back the file stream to consume in place. (Iterating req.parts() and breaking would let
77+
// the iterator drain the unread file stream, writing zero bytes — the ZK "0 B" bug.)
5778
app.post('/files', async (req, reply) => {
58-
let meta: unknown;
59-
let blob: Readable | undefined;
60-
let blobPart: Awaited<ReturnType<typeof req.file>> | undefined;
79+
const data = await req.file();
80+
if (!data) return reply.code(400).send({ error: 'No file provided' });
6181

62-
for await (const part of req.parts()) {
63-
if (part.type === 'field' && part.fieldname === 'meta') {
64-
try {
65-
meta = JSON.parse(part.value as string);
66-
} catch {
67-
return reply.code(400).send({ error: 'Invalid meta JSON' });
68-
}
69-
} else if (part.type === 'file') {
70-
blobPart = part;
71-
blob = part.file;
72-
break; // the file part must be sent last
73-
}
82+
const metaRaw = (data.fields?.meta as { value?: string } | undefined)?.value;
83+
let meta: unknown;
84+
try {
85+
meta = JSON.parse(metaRaw ?? '');
86+
} catch {
87+
data.file.resume(); // drain so the request can finish cleanly
88+
return reply.code(400).send({ error: 'Invalid meta JSON' });
7489
}
7590

7691
const parsed = zkFileMetaSchema.safeParse(meta);
77-
if (!parsed.success) return reply.code(400).send({ error: 'Invalid ZK metadata' });
78-
if (!blob || !blobPart) return reply.code(400).send({ error: 'No file provided' });
92+
if (!parsed.success) {
93+
data.file.resume();
94+
return reply.code(400).send({ error: 'Invalid ZK metadata' });
95+
}
7996

8097
const folder = await prisma.folder.findFirst({
8198
where: { id: parsed.data.folderId, ownerId: req.user!.id, isZeroKnowledge: true },
8299
});
83-
if (!folder) return reply.code(404).send({ error: 'Vault folder not found' });
100+
if (!folder) {
101+
data.file.resume();
102+
return reply.code(404).send({ error: 'Vault folder not found' });
103+
}
84104

85105
const allowance = await remainingAllowance(req.user!.id);
86-
if (allowance <= 0) return reply.code(413).send({ error: 'Storage quota exhausted' });
106+
if (allowance <= 0) {
107+
data.file.resume();
108+
return reply.code(413).send({ error: 'Storage quota exhausted' });
109+
}
87110

88111
const storageKey = newStorageKey();
89112
try {
90-
const { bytesWritten } = await app.ctx.storage.write(storageKey, capStream(blob, allowance));
113+
const { bytesWritten } = await app.ctx.storage.write(storageKey, capStream(data.file, allowance));
114+
if (bytesWritten === 0) {
115+
await app.ctx.storage.delete(storageKey).catch(() => {});
116+
return reply.code(400).send({ error: 'Empty file' });
117+
}
91118
const file = await prisma.fileObject.create({
92119
data: {
93120
ownerId: req.user!.id,

‎apps/api/test/integration.test.ts‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,66 @@ runIf('API integration', () => {
244244
expect(typeof v1.json().folder.zkSalt).toBe('string');
245245
expect(v1.json().folder.zkSalt).not.toBe(v2.json().folder.zkSalt); // unique per vault
246246
});
247+
248+
it('stores and serves ZK ciphertext byte-for-byte (non-zero size)', async () => {
249+
await createUser({ email: 'zkup@test.local', password: 'correct-horse-battery' });
250+
const auth = await login(app, 'zkup@test.local', 'correct-horse-battery');
251+
const vault = await app.inject({
252+
method: 'POST',
253+
url: '/folders',
254+
headers: authHeaders(auth),
255+
payload: { name: 'vault', isZeroKnowledge: true },
256+
});
257+
const folderId = vault.json().folder.id as string;
258+
259+
// The server treats the blob as opaque ciphertext, so any bytes exercise the path.
260+
const cipher = Buffer.from('this-pretends-to-be-encrypted-bytes-0123456789');
261+
const form = new FormData();
262+
form.append(
263+
'meta',
264+
JSON.stringify({ folderId, encryptedName: 'iv.ct', iv: 'aXY=', wrappedKey: 'aXY=.d3I=', encMode: 'ZK' }),
265+
);
266+
form.append('file', cipher, { filename: 'blob', contentType: 'application/octet-stream' });
267+
const up = await app.inject({
268+
method: 'POST',
269+
url: '/zk/files',
270+
payload: form.getBuffer(),
271+
headers: { ...form.getHeaders(), ...authHeaders(auth) },
272+
});
273+
expect(up.statusCode).toBe(201);
274+
275+
const list = await app.inject({ method: 'GET', url: `/zk/files?folderId=${folderId}`, headers: { cookie: auth.cookie } });
276+
const entry = list.json().files[0];
277+
expect(entry.sizeBytes).toBe(cipher.length); // regression guard: must NOT be 0
278+
expect(entry.iv).toBe('aXY=');
279+
expect(entry.wrappedKey).toBe('aXY=.d3I=');
280+
expect(entry.encryptedName).toBe('iv.ct');
281+
282+
const blob = await app.inject({ method: 'GET', url: `/zk/files/${entry.id}/blob`, headers: { cookie: auth.cookie } });
283+
expect(Buffer.from(blob.rawPayload).equals(cipher)).toBe(true); // byte-for-byte round-trip
284+
});
285+
286+
it('rejects a ZK upload that exceeds the quota', async () => {
287+
await createUser({ email: 'zkq@test.local', password: 'correct-horse-battery', quotaBytes: 8n });
288+
const auth = await login(app, 'zkq@test.local', 'correct-horse-battery');
289+
const vault = await app.inject({
290+
method: 'POST',
291+
url: '/folders',
292+
headers: authHeaders(auth),
293+
payload: { name: 'vault', isZeroKnowledge: true },
294+
});
295+
const folderId = vault.json().folder.id as string;
296+
const form = new FormData();
297+
form.append('meta', JSON.stringify({ folderId, encryptedName: 'iv.ct', iv: 'aXY=', wrappedKey: 'aXY=.d3I=', encMode: 'ZK' }));
298+
form.append('file', Buffer.alloc(64), { filename: 'blob', contentType: 'application/octet-stream' });
299+
const up = await app.inject({
300+
method: 'POST',
301+
url: '/zk/files',
302+
payload: form.getBuffer(),
303+
headers: { ...form.getHeaders(), ...authHeaders(auth) },
304+
});
305+
expect(up.statusCode).toBe(413);
306+
});
247307
});
248308

249309
describe('health', () => {

0 commit comments

Comments
 (0)