Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

API: a signed-out or over-budget upload is drained to at most twice the largest cap and then cut off, instead of read to its end

Duarte Santosbd6000321e6a
diff --git a/api/media.js b/api/media.js
index 489227fbb..20cc290d0 100644
--- a/api/media.js
+++ b/api/media.js
@@ -659,6 +659,10 @@ export function createMediaStore({ dir, limits, now = Date.now, readState = () =
return {
limits: L,
+ /** For a refusal decided before receive() (no session, the hourly budget): takes at most
+ * twice the largest cap off the wire so the answer arrives, then closes the socket, instead
+ * of leaving node to read an unbounded body to its end. */
+ discard: req => drain(req, 2 * maxCap),
usage: uid => usageOf(entry(uid)),
has: (uid, hash) => entry(uid).hashes.has(hash),
/** { path, ext, mime, size } of a stored file, or null. Checks the disk, so a file that
diff --git a/api/server.js b/api/server.js
index 4d3415bc9..1f846ec5d 100644
--- a/api/server.js
+++ b/api/server.js
@@ -1490,8 +1490,8 @@ const mediaRoutes = {
// session and the hourly budget.
'PUT /api/media/{hash}': async (req, res) => {
const user = readSession(req);
- if (!user) return json(res, 401, { error: 'not signed in' });
- mediaThrottle(req, user, MEDIA_BURST);
+ if (!user) { MEDIA.discard(req); return json(res, 401, { error: 'not signed in' }); }
+ try { mediaThrottle(req, user, MEDIA_BURST); } catch (e) { MEDIA.discard(req); throw e; }
const r = await MEDIA.receive(user.id, req.mediaHash, req);
json(res, r.status, r.body);
},
diff --git a/api/test/media-receive.test.js b/api/test/media-receive.test.js
index fc29d3e7d..ff930415c 100644
--- a/api/test/media-receive.test.js
+++ b/api/test/media-receive.test.js
@@ -199,6 +199,22 @@ test('a third upload at once is refused as busy', async t => {
assert.equal((await h.store.receive('u1', M.sha(c), M.fakeReq(c))).status, 201, 'the slots came back');
});
+test('a refused upload is drained up to twice the largest cap, then cut off', async t => {
+ const h = setup(t, { imageMB: 0.001, gifMB: 0.001, videoMB: 0.01 });
+ const small = M.jpeg(15000); // under 2 × 10 KB: read to its end
+ const a = M.fakeReq(small);
+ h.store.discard(a);
+ await new Promise(r => a.on('end', r));
+ assert.equal(a.readableEnded, true);
+ const big = M.jpeg(200000); // far over: cut off, not read to the end
+ const b = M.fakeReq(big, { chunk: 4096 });
+ let seen = 0;
+ b.on('data', d => { seen += d.length; });
+ h.store.discard(b);
+ await new Promise(r => b.on('close', r));
+ assert.ok(!b.readableEnded && seen < 40000, `read ${seen} bytes`);
+});
+
test('the disk floor refuses an upload with 507 and holds no reservation afterwards', async t => {
const h = setup(t, { minFreeMB: 1e9 });
const bytes = M.jpeg();