From f94f8ca32055980f7a273a395bf1daa4f741e677 Mon Sep 17 00:00:00 2001 From: Duarte Santos Date: Sat, 19 Sep 2026 21:20:00 +0200 Subject: [PATCH] =?UTF-8?q?API:=20a=20request=20the=20client=20got=20wrong?= =?UTF-8?q?=20is=20a=20400=20(or=20413),=20never=20a=20500=20with=20a=20st?= =?UTF-8?q?ack=20trace=20=E2=80=94=20bad=20or=20non-object=20JSON,=20an=20?= =?UTF-8?q?array=20as=20the=20state=20document,=20null=20workout=20entries?= =?UTF-8?q?,=20a=20rest=20timer=20without=20seconds=20(QA=20C17,=20C19,=20?= =?UTF-8?q?C20,=20C16)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit readBody rejects with a typed HttpError for unparseable text and for a JSON null, string, number or array; the catch-all answers it with its status and does not log it — three of these routes are reachable without a session, and a stack trace per malformed body let anyone fill the container log. String() on a caller-supplied field went through the same door ({"code":{"toString":1}} is valid JSON) and is replaced by a text() helper. PUT /api/data refuses an array state (typeof 'object', but _rev on it is dropped by JSON.stringify, so the file read back as rev 0 while the response claimed rev N+1) and drops null and non-object entries from workouts/routines instead of refusing them: such an entry carries nothing worth keeping, while a 400 would strand a client whose own copy is already malformed in a re-send loop. Every server-side reader of the document (reminder tick, admin drill-down) dereferences the entries. POST /api/push/rest-timer validates seconds before clamping — the clamp ran first, turned any missing or unusable value into a 1-second push and made the documented 400 unreachable. A body over 5 MiB is a 413 the client actually gets to read: the remainder of the upload is drained instead of the socket destroyed under it (which sent a reset that a node client hit before parsing the answer — the QA proxy reported 502 on 3 of 4 attempts, 5 of 5 read the 413 afterwards); past twice the cap the upload is cut off. openapi.yaml documents the 400/413 bodies and the rest-timer 400. --- api/openapi.yaml | 24 ++-- api/server.js | 77 ++++++++++--- api/test/server-bad-input.test.js | 183 ++++++++++++++++++++++++++++++ 3 files changed, 263 insertions(+), 21 deletions(-) create mode 100644 api/test/server-bad-input.test.js diff --git a/api/openapi.yaml b/api/openapi.yaml index 14ecfdf..fd2f23d 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -50,7 +50,11 @@ info: - Errors are always `{"error": ""}`. - Unknown method+path pairs return `404 {"error":"not found"}`; an unhandled exception returns `500 {"error":"server error"}`. - - Request bodies are parsed as JSON regardless of Content-Type; max 5 MiB. + - Request bodies are parsed as JSON regardless of Content-Type. A body that does + not parse, or parses to anything but an object (`null`, a string, an array), is + `400 {"error":"invalid json"}` on every route that reads one; an empty body counts + as `{}`. A body over 5 MiB is `413 {"error":"body too large"}`; the rest of the + upload is discarded so the answer reaches the client. - CORS: the request's `Origin` is reflected in `Access-Control-Allow-Origin` **without** `Allow-Credentials` — cross-origin callers can only ever authenticate with a Bearer token, never with the cookie. @@ -556,8 +560,10 @@ paths: - type: 'null' '400': description: >- - `state` missing or not an object, or `workouts`/`routines` set to anything - other than an array or null. + `state` missing or not an object, `state` an array, or `workouts`/`routines` + set to anything other than an array or null. Entries inside those two arrays + that are not objects (`null`, numbers, nested arrays) are dropped before the + write rather than refused, so a client with a damaged copy still syncs. content: application/json: schema: { $ref: '#/components/schemas/Error' } @@ -725,7 +731,8 @@ paths: operationId: pushRestTimer summary: Schedule a server-side rest-timer push description: | - Schedules one push after `seconds` (clamped to 1–3600). One pending timer per + Schedules one push after `seconds` (a number or numeric string ≥ 1, clamped to + 3600). One pending timer per device — `deviceId`, the same token the subscription was registered with; a new call from the same device replaces it, and the push goes only to that device's subscriptions. Without a `deviceId` there is one timer per account @@ -733,9 +740,6 @@ paths: on rest start/extend and cancels on skip or on-screen completion — the push only actually fires when the tab was backgrounded/suspended and never got to cancel it. Timers live in memory: an API restart drops them. - - Note: the documented `400 seconds required` exists in the code but is - unreachable — the clamp turns any missing/invalid value into 1. requestBody: required: true content: @@ -759,6 +763,12 @@ paths: content: application/json: schema: { $ref: '#/components/schemas/Ok' } + '400': + description: '`seconds` missing, not numeric, or below 1. Nothing is scheduled.' + content: + application/json: + schema: { $ref: '#/components/schemas/Error' } + example: { error: "seconds required" } '401': { $ref: '#/components/responses/Unauthorized' } /api/push/rest-timer/cancel: diff --git a/api/server.js b/api/server.js index 5f2745c..8da9389 100644 --- a/api/server.js +++ b/api/server.js @@ -513,21 +513,53 @@ function json(res, code, obj, extraHeaders) { res.writeHead(code, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', ...(extraHeaders || {}) }); res.end(body); } +// A request the caller got wrong. The catch-all at the bottom answers it with this status and +// message and does not log it: three of the routes below are reachable without a session, and a +// stack trace per malformed body would let anyone fill the container log with noise that looks +// like a crash. Anything else that escapes a handler is still a real 500 and still logged. +class HttpError extends Error { + constructor(status, message) { super(message); this.status = status; } +} function readBody(req) { return new Promise((resolve, reject) => { - let size = 0; const chunks = []; + let size = 0, over = false; const chunks = []; req.on('data', d => { size += d.length; - if (size > MAX_BODY) { reject(new Error('body too large')); req.destroy(); return; } + if (over) { + // The 413 is already on its way. The rest of the upload is read and thrown away rather + // than the socket destroyed under it: closing with unread bytes on the wire makes the + // kernel send a reset, and a client (node's own http client included) that hits the + // reset before it has parsed the answer reports a dropped connection instead of the + // 413. A client that keeps streaming past twice the cap is not a mistaken one, and is + // cut off. + if (size > 2 * MAX_BODY) req.destroy(); + return; + } + if (size > MAX_BODY) { + over = true; chunks.length = 0; + reject(new HttpError(413, 'body too large')); + return; + } chunks.push(d); }); req.on('end', () => { - try { resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}); } - catch { reject(new Error('bad json')); } + if (over) return; + if (!chunks.length) return resolve({}); + let body; + try { body = JSON.parse(Buffer.concat(chunks).toString('utf8')); } + catch { return reject(new HttpError(400, 'invalid json')); } + // Every handler reads fields off the result, so a JSON `null`, string, number or array is + // as much a client mistake as unparseable text — refused once here rather than dereferenced + // (and turned into a TypeError) in each route. + if (!body || typeof body !== 'object' || Array.isArray(body)) return reject(new HttpError(400, 'invalid json')); + resolve(body); }); req.on('error', reject); }); } +// A caller-supplied field that is meant to be text. String() alone is not safe on a parsed body: +// `{"code":{"toString":1}}` is valid JSON and String() throws on it. +const text = v => (typeof v === 'string' ? v : typeof v === 'number' ? String(v) : ''); const b64uToBuf = s => Buffer.from(s, 'base64url'); /* ---------- live presence (in-memory) ---------- */ @@ -658,9 +690,9 @@ const routes = { 'POST /api/register/options': async (req, res) => { const body = await readBody(req); - const name = String(body.name || '').trim().slice(0, 40); + const name = text(body.name).trim().slice(0, 40); if (!name) return json(res, 400, { error: 'name required' }); - const code = String(body.code || '').trim().toUpperCase(); + const code = text(body.code).trim().toUpperCase(); if (INVITE_ONLY && !db.invites.some(i => i.code === code && !i.usedBy && !i.revoked)) { // The rejected code itself is never recorded — a near-miss guess in the log is a liability. audit(req, 'auth.register.denied', { ok: false, name, msg: 'invite-rejected' }); @@ -830,7 +862,7 @@ const routes = { // the code IS the credential, one-shot and 5-minute-lived like a WebAuthn challenge. 'POST /api/pair/redeem': async (req, res) => { const body = await readBody(req); - const code = String(body.code || '').trim().toUpperCase(); + const code = text(body.code).trim().toUpperCase(); const p = pairings.get(code); if (p) pairings.delete(code); if (!p || p.exp < Date.now()) { @@ -871,9 +903,17 @@ const routes = { if (!body.state || typeof body.state !== 'object') return json(res, 400, { error: 'state required' }); // The reminder tick and the admin routes iterate these two on the server's side, so a truthy // non-array would throw there on every pass for as long as it sat on disk. Absent or null is - // fine — every client fills its own defaults. + // fine — every client fills its own defaults. An array is `typeof 'object'` but no document: + // `_rev` set on it is dropped by JSON.stringify, so the file would read back as rev 0 while + // the response claimed the next revision. const list = v => v == null || Array.isArray(v); - if (!list(body.state.workouts) || !list(body.state.routines)) return json(res, 400, { error: 'invalid state' }); + if (Array.isArray(body.state) || !list(body.state.workouts) || !list(body.state.routines)) return json(res, 400, { error: 'invalid state' }); + // The same readers dereference every entry (`w.d`, `w.name`), so a null or non-object entry + // would throw there — and blank the admin's drill-down of this profile. Dropped, not refused: + // such an entry carries nothing worth keeping, whereas a 400 would strand a client whose own + // copy is already malformed — it keeps re-sending the same document and never syncs again. + const record = x => x && typeof x === 'object' && !Array.isArray(x); + for (const k of ['workouts', 'routines']) if (Array.isArray(body.state[k])) body.state[k] = body.state[k].filter(record); // Conditional write: a `baseRev` that is not the current revision means this client last // read an older document — another device has written since — and the copy it is about to // push would silently drop that write. The current document travels back with the 409, so @@ -954,8 +994,13 @@ const routes = { const user = readSession(req); if (!user) return json(res, 401, { error: 'not signed in' }); const body = await readBody(req); - const sec = Math.max(1, Math.min(3600, Math.round(+body.seconds || 0))); - if (!sec) return json(res, 400, { error: 'seconds required' }); + // Validated before it is clamped: the clamp used to run first, which turned a missing or + // unusable value into a 1-second push and made the 400 below unreachable. `Number()` only + // on a number or a string — on an object it can throw. + const raw = body.seconds; + const n = typeof raw === 'number' || typeof raw === 'string' ? Number(raw) : NaN; + if (!(n >= 1)) return json(res, 400, { error: 'seconds required' }); + const sec = Math.min(3600, Math.round(n)); scheduleRestTimer(user.id, deviceIdOf(body.deviceId), sec, readState(user.id)?.lang); json(res, 200, { ok: true }); }, @@ -975,7 +1020,7 @@ const routes = { const body = await readBody(req); if (body.active) { presence.set(user.id, { - name: String(body.name || '').slice(0, 60), + name: text(body.name).slice(0, 60), exIdx: +body.exIdx || 0, exTotal: +body.exTotal || 0, setsDone: +body.setsDone || 0, setsTotal: +body.setsTotal || 0, startedAt: +body.startedAt || Date.now(), @@ -1054,7 +1099,7 @@ const routes = { // good, so the code itself has to be the thing that isn't worth guessing. Codes already in // db.json keep working — validation is an exact string compare, never a length or format check. do { code = crypto.randomBytes(8).toString('hex').toUpperCase(); } while (db.invites.some(i => i.code === code)); - const invite = { code, note: String(body.note || '').slice(0, 60), createdBy: admin.id, created: new Date().toISOString() }; + const invite = { code, note: text(body.note).slice(0, 60), createdBy: admin.id, created: new Date().toISOString() }; db.invites.push(invite); saveDb(); audit(req, 'admin.invite.create', { user: admin, msg: code }); @@ -1064,7 +1109,7 @@ const routes = { 'POST /api/admin/invites/revoke': async (req, res) => { const admin = requireAdmin(req, res); if (!admin) return; const body = await readBody(req); - const inv = db.invites.find(i => i.code === String(body.code || '').toUpperCase()); + const inv = db.invites.find(i => i.code === text(body.code).toUpperCase()); if (!inv) return json(res, 404, { error: 'no such code' }); if (inv.usedBy) return json(res, 400, { error: 'already used — cannot revoke' }); db.invites = db.invites.filter(i => i.code !== inv.code); @@ -1166,6 +1211,10 @@ http.createServer(async (req, res) => { } try { await handler(req, res); } catch (e) { + if (e instanceof HttpError) { + if (!res.headersSent) json(res, e.status, { error: e.message }); + return; + } console.error(key, e); if (!res.headersSent) json(res, 500, { error: 'server error' }); } diff --git a/api/test/server-bad-input.test.js b/api/test/server-bad-input.test.js new file mode 100644 index 0000000..a734fe2 --- /dev/null +++ b/api/test/server-bad-input.test.js @@ -0,0 +1,183 @@ +/* A client's mistake is a 400 (or a 413), never a 500 with a stack trace in the log: unparseable + or non-object JSON bodies, a state document that is an array, null entries inside it, and a + rest-timer request without a usable `seconds` (QA C17, C19, C20). Real server.js in a child. */ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; +import net from 'node:net'; +import http from 'node:http'; +import fs from 'node:fs'; +import os from 'node:os'; +import path from 'node:path'; +import { spawn } from 'node:child_process'; +import { fileURLToPath } from 'node:url'; + +const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..'); +const SECRET = crypto.randomBytes(32).toString('hex'); + +// Same construction as server.js makeSession(): payload `uid:exp:sv`, HMAC-SHA256 over SECRET. +function mintSession(uid, sv = 0) { + const payload = `${uid}:${Date.now() + 86400000}:${sv}`; + return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url'); +} +const UID = 'u_bad_1'; +const authed = { Cookie: `gymsid=${mintSession(UID)}`, 'Content-Type': 'application/json' }; +const anon = { 'Content-Type': 'application/json' }; + +const freePort = () => new Promise(r => { + const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); }); +}); + +async function startServer(t) { + const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-bad-')); + fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 }); + fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ + users: [{ id: UID, name: 'One', created: new Date().toISOString() }], creds: [], subs: [], invites: [] + })); + const port = await freePort(); + const child = spawn(process.execPath, ['server.js'], { + cwd: API, stdio: ['ignore', 'pipe', 'pipe'], + env: { ...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost' } + }); + const h = { api: `http://127.0.0.1:${port}`, log: '', dataDir }; + child.stdout.on('data', d => h.log += d); + child.stderr.on('data', d => h.log += d); + t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); }); + let up = false; + for (let i = 0; i < 100 && !up; i++) { + try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ } + if (!up) await new Promise(r => setTimeout(r, 100)); + } + assert.ok(up, `server never came up:\n${h.log}`); + // The boot line is fine; anything that looks like a stack frame after this is a defect. + h.stackFrames = () => h.log.split('\n').filter(l => /^\s+at /.test(l)).length; + return h; +} + +const send = (h, method, p, headers, body) => fetch(`${h.api}${p}`, { method, headers, body }); +const status = async (h, method, p, headers, body) => { + const r = await send(h, method, p, headers, body); + return { status: r.status, body: await r.json() }; +}; + +test('malformed and non-object JSON bodies are a 400 with no stack trace, on every route', async t => { + const h = await startServer(t); + const bad = ['not json', '{bad', 'null', '"str"', '42', '[]']; + const routes = [ + ['POST', '/api/register/options', anon], + ['POST', '/api/register/verify', anon], + ['POST', '/api/pair/redeem', anon], + ['PUT', '/api/data', authed], + ['POST', '/api/push/rest-timer', authed] + ]; + for (const [method, p, headers] of routes) { + for (const b of bad) { + const r = await status(h, method, p, headers, b); + assert.equal(r.status, 400, `${method} ${p} with body ${b}`); + assert.equal(r.body.error, 'invalid json', `${method} ${p} with body ${b}`); + } + } + // A field whose toString is not callable is valid JSON; String() on it used to throw. + let r = await status(h, 'POST', '/api/register/options', anon, JSON.stringify({ name: 'x', code: { toString: 1 } })); + assert.notEqual(r.status, 500); + r = await status(h, 'POST', '/api/pair/redeem', anon, JSON.stringify({ code: { toString: 1 } })); + assert.equal(r.status, 400); + r = await status(h, 'POST', '/api/register/options', anon, JSON.stringify({ name: { toString: 1 } })); + assert.equal(r.status, 400); + assert.equal(r.body.error, 'name required'); + // An empty body is still "no fields", as the routes that send none rely on. + r = await status(h, 'POST', '/api/logout', { Cookie: authed.Cookie }); + assert.equal(r.status, 200); + // Well-formed controls keep their own answers. + r = await status(h, 'POST', '/api/register/options', anon, '{}'); + assert.deepEqual(r, { status: 400, body: { error: 'name required' } }); + r = await status(h, 'PUT', '/api/data', authed, JSON.stringify({ state: { workouts: [], routines: [] }, baseRev: 0 })); + assert.equal(r.status, 200); + assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`); + assert.doesNotMatch(h.log, /bad json|TypeError/); +}); + +// node's own http client, writing the whole body in one go on a keep-alive socket: the client +// the QA proxy (and any node-side caller) is, and the one that used to report a reset instead +// of the 413 when the server closed the socket under the still-running upload. +const rawPut = (h, agent, body) => new Promise((resolve, reject) => { + const rq = http.request(`${h.api}/api/data`, { method: 'PUT', headers: authed, agent }, res => { + let data = ''; res.on('data', d => data += d); res.on('end', () => resolve({ status: res.statusCode, body: JSON.parse(data) })); + }); + rq.on('error', reject); + rq.end(body); +}); + +test('a body over the 5 MiB cap is a 413 that every client gets to read, and nothing is written', async t => { + const h = await startServer(t); + const big = JSON.stringify({ state: { workouts: [], routines: [], pad: 'x'.repeat(6 * 1024 * 1024) }, baseRev: 0 }); + let r = await status(h, 'PUT', '/api/data', authed, big); + assert.equal(r.status, 413); + assert.equal(r.body.error, 'body too large'); + assert.equal(fs.existsSync(path.join(h.dataDir, `state-${UID}.json`)), false, 'nothing was written'); + const agent = new http.Agent({ keepAlive: true, maxSockets: 1 }); + t.after(() => agent.destroy()); + for (let i = 0; i < 3; i++) { + r = await rawPut(h, agent, big); + assert.equal(r.status, 413, `node client, attempt ${i + 1}`); + } + // The same keep-alive socket, and the server as a whole, are still fine afterwards. + r = await rawPut(h, agent, JSON.stringify({ state: { workouts: [], routines: [] }, baseRev: 0 })); + assert.equal(r.status, 200); + // Past twice the cap the upload is cut off rather than drained: the 413 may or may not + // arrive, but the process must not be left reading, and must still serve. + const huge = 'x'.repeat(11 * 1024 * 1024); + await rawPut(h, new http.Agent(), huge).catch(() => {}); + r = await status(h, 'GET', '/api/health', {}); + assert.equal(r.status, 200); + assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`); +}); + +test('PUT /api/data: an array is not a document, and null entries never reach the disk', async t => { + const h = await startServer(t); + const put = body => status(h, 'PUT', '/api/data', authed, JSON.stringify(body)); + const onDisk = () => JSON.parse(fs.readFileSync(path.join(h.dataDir, `state-${UID}.json`), 'utf8')); + + let r = await put({ state: { _ts: 100, workouts: [{ id: 'w1', d: '2026-09-01' }], routines: [], unit: 'kg' }, baseRev: 0 }); + assert.equal(r.status, 200); + assert.equal(r.body.rev, 1); + + // An array passes `typeof === 'object'`; it used to be written as `[]`, losing the document + // and, since `_rev` cannot live on an array, resetting the revision to 0 while the response + // claimed rev 2. + r = await put({ state: [], baseRev: 1 }); + assert.equal(r.status, 400); + assert.equal(r.body.error, 'invalid state'); + assert.equal(onDisk()._rev, 1); + assert.deepEqual(onDisk().workouts.map(w => w.id), ['w1']); + r = await status(h, 'GET', '/api/data/rev', authed); + assert.deepEqual(r.body, { rev: 1 }); + + // Null and other non-object entries are dropped: every server-side reader of the document + // (reminder tick, admin drill-down) dereferences the entries, and a 400 would strand a client + // whose own copy is already malformed. + r = await put({ state: { workouts: [null, { id: 'w2', d: '2026-09-02' }, 7, 'x', [], { id: 'w3', d: '2026-09-03' }], routines: [null, { id: 'r1', name: 'A', ex: [] }] }, baseRev: 1 }); + assert.equal(r.status, 200); + assert.equal(r.body.rev, 2); + assert.deepEqual(onDisk().workouts.map(w => w.id), ['w2', 'w3']); + assert.deepEqual(onDisk().routines.map(x => x.id), ['r1']); + // Absent lists stay absent — every client fills its own defaults. + r = await put({ state: { unit: 'kg' }, baseRev: 2 }); + assert.equal(r.status, 200); + assert.equal('workouts' in onDisk(), false); + 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); + for (const b of ['{}', '{"seconds":"abc"}', '{"seconds":0}', '{"seconds":-5}', '{"seconds":null}', '{"seconds":0.4}', '{"seconds":{"valueOf":1}}', '{"seconds":[90]}']) { + const r = await post(b); + assert.deepEqual(r, { status: 400, body: { error: 'seconds required' } }, `body ${b}`); + } + for (const b of ['{"seconds":90}', '{"seconds":"90"}', '{"seconds":1}', '{"seconds":99999}']) { + const r = await post(b); + assert.deepEqual(r, { status: 200, body: { ok: true } }, `body ${b}`); + } + assert.equal(h.stackFrames(), 0, `stack traces in the log:\n${h.log}`); +});