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 state nested too deep to store is a 400, not a 500

Duarte Santos822c765e95f7
diff --git a/api/server.js b/api/server.js
index ee0953955..b0c170158 100644
--- a/api/server.js
+++ b/api/server.js
@@ -2110,7 +2110,12 @@ const routes = {
else delete body.state.resetIds;
}
body.state._rev = curRev + 1; // server-owned; whatever the client sent is ignored
- atomicWrite(stateFile(user.id), JSON.stringify(body.state));
+ // JSON.parse takes any nesting, JSON.stringify recurses and runs out of stack on a document
+ // nested some thousands deep. No client builds one; it is a bad request, not a server error.
+ let text;
+ try { text = JSON.stringify(body.state); }
+ catch (e) { if (e instanceof RangeError) return json(res, 400, { error: 'invalid state' }); throw e; }
+ atomicWrite(stateFile(user.id), text);
// The stat cache cannot see this write on its own: mtime granularity is 4 ms here (ext4 on
// this kernel — 3901 of 3999 back-to-back same-size writes shared one timestamp), and a
// `_rev` going from 7 to 8 does not change the file's size, so two writes inside one 4 ms
diff --git a/api/test/server-bad-input.test.js b/api/test/server-bad-input.test.js
index 648977922..c2898d27e 100644
--- a/api/test/server-bad-input.test.js
+++ b/api/test/server-bad-input.test.js
@@ -161,6 +161,23 @@ test('PUT /api/data: an array is not a document, and null entries never reach th
assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`);
});
+test('PUT /api/data: a document nested too deep to store is a 400, not a 500, and nothing is written', async t => {
+ const h = await startServer(t);
+ const onDisk = () => JSON.parse(fs.readFileSync(path.join(h.dataDir, `state-${UID}.json`), 'utf8'));
+ let r = await status(h, 'PUT', '/api/data', authed, JSON.stringify({ state: { workouts: [], routines: [], unit: 'kg' }, baseRev: 0 }));
+ assert.equal(r.status, 200);
+ // JSON.parse takes this (it is not recursive in V8); JSON.stringify on the way to the disk is.
+ const depth = 200000;
+ const deep = '{"state":{"workouts":[],"routines":[],"x":' + '['.repeat(depth) + ']'.repeat(depth) + '},"baseRev":1}';
+ r = await status(h, 'PUT', '/api/data', authed, deep);
+ assert.equal(r.status, 400);
+ assert.equal(r.body.error, 'invalid state');
+ assert.equal(onDisk()._rev, 1);
+ r = await status(h, 'GET', '/api/data/rev', authed);
+ assert.deepEqual(r.body, { rev: 1 });
+ assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`);
+});
+
test('POST /api/push/rest-timer: a missing or invalid `seconds` is a 400, never a 1-second timer', async t => {
const h = await startServer(t);
const post = b => status(h, 'POST', '/api/push/rest-timer', authed, b);