From 917162aa0f7b9c93cd4890c4b0cc04893f99a068 Mon Sep 17 00:00:00 2001 From: le king fu Date: Sun, 15 Nov 2026 07:08:14 -0500 Subject: [PATCH] fix(web): PUT /api/tasks/[id] verifies listId and parentId against the account (#208) The handler copied listId and parentId from the body into its UPDATE without checking them: a direct API call could attach a task to the list, or place it under the task, of another account (controls 7 and 8 of the production probe). The transaction of the PUT now starts with refusedReference, before any write: - listId must name a live list of the account, else 404 "List not found"; - a non-null parentId must name a live task of the account other than the task itself, else 404 "Parent task not found"; that parent must not be a subtask and the updated task must have no live subtask, else 400 "Cannot create sub-subtasks (max 2 levels)"; - parentId: null is still allowed. Every query of the check filters on the account. The task is compared with its parent by PostgreSQL, as uuids: the same id in another letter case is refused too. A refusal writes nothing: no other field of the body is applied, the task is not completed, no next occurrence is created and no notice is sent. The transaction callback now returns { ok: true, task } or a refusal { ok: false, status, error } instead of TaskRow | null. Tests in route.test.ts: 18 new ones, 11 of them red on the tree before the fix (the two cross-account ones answered 200). Resolves #208 Co-Authored-By: Claude Fable 5.2 --- web/src/app/api/tasks/[id]/route.ts | 98 ++++++++++++-- web/src/app/api/tasks/route.test.ts | 199 ++++++++++++++++++++++++++++ 2 files changed, 285 insertions(+), 12 deletions(-) diff --git a/web/src/app/api/tasks/[id]/route.ts b/web/src/app/api/tasks/[id]/route.ts index 3dc5722..3f4ec23 100644 --- a/web/src/app/api/tasks/[id]/route.ts +++ b/web/src/app/api/tasks/[id]/route.ts @@ -1,14 +1,80 @@ import { NextResponse } from 'next/server'; import { db } from '@/db/client'; -import { slTasks } from '@/db/schema'; -import { eq, and, isNull } from 'drizzle-orm'; +import { slLists, slTasks } from '@/db/schema'; +import { eq, and, isNull, ne } from 'drizzle-orm'; import { requireAuth, parseBody } from '@/lib/api'; import { rateLimit } from '@/lib/rateLimit'; import { notifyUserChanged } from '@/lib/ws'; -import { deleteTask } from '@/lib/taskDelete'; +import { deleteTask, type Tx } from '@/lib/taskDelete'; import { completeTask, reopenTask, type TaskRow } from '@/lib/taskWrites'; import { updateTaskSchema } from '@/lib/validators'; +// What the PUT answers instead of the task. NOT_FOUND is the task itself; the +// three others are the references of the body (#208), with the answers of +// POST /api/tasks. +const NOT_FOUND = { ok: false, status: 404, error: 'Not found' } as const; +const LIST_NOT_FOUND = { ok: false, status: 404, error: 'List not found' } as const; +const PARENT_NOT_FOUND = { ok: false, status: 404, error: 'Parent task not found' } as const; +const TOO_DEEP = { ok: false, status: 400, error: 'Cannot create sub-subtasks (max 2 levels)' } as const; + +type Refusal = typeof NOT_FOUND | typeof LIST_NOT_FOUND | typeof PARENT_NOT_FOUND | typeof TOO_DEEP; + +// The list and the parent that a body names, checked against the account of +// the caller (#208). Without this, `listId` and `parentId` went from the body +// to the row as they were: a task could be attached to the list, or placed +// under the task, of another account. +// +// Every query filters on `userId`, so that the answer never depends on a row +// of another account, and a deleted row is not a row. Unlike POST /api/sync, +// which only refuses an id taken by another account, the row must exist: only +// the first sync of the app needs to push a subtask before its parent. +// +// It reads and never writes. The order is the one of POST /api/tasks: the +// list, then the parent. Returns null when the body may be written. +async function refusedReference( + tx: Tx, + userId: string, + taskId: string, + { listId, parentId }: { listId?: string; parentId?: string | null }, +): Promise { + if (listId !== undefined) { + const [list] = await tx + .select({ id: slLists.id }) + .from(slLists) + .where(and(eq(slLists.id, listId), eq(slLists.userId, userId), isNull(slLists.deletedAt))); + if (!list) return LIST_NOT_FOUND; + } + + // null takes the task back to the top level: there is nothing to check. + if (parentId) { + const [parent] = await tx + .select({ parentId: slTasks.parentId }) + .from(slTasks) + .where(and( + eq(slTasks.id, parentId), + eq(slTasks.userId, userId), + isNull(slTasks.deletedAt), + // A task is not its own parent. PostgreSQL compares the two ids as + // uuids: the same id in another letter case is still the task itself, + // which a comparison of the two strings would miss. + ne(slTasks.id, taskId), + )); + if (!parent) return PARENT_NOT_FOUND; + + // Two levels at most, as the app and the site show them: the parent is + // not a subtask, and the task that becomes one has no live subtask. + if (parent.parentId) return TOO_DEEP; + const [subtask] = await tx + .select({ id: slTasks.id }) + .from(slTasks) + .where(and(eq(slTasks.parentId, taskId), eq(slTasks.userId, userId), isNull(slTasks.deletedAt))) + .limit(1); + if (subtask) return TOO_DEEP; + } + + return null; +} + export async function PUT( request: Request, { params }: { params: Promise<{ id: string }> } @@ -32,9 +98,16 @@ export async function PUT( // One transaction for the whole body (#201): the fields, the completion and // the next occurrence of a recurring task are written together or not at - // all. It gives the task back, or null for a 404. A refusal returns before - // the first write: a return commits what was written before it. - const updated = await db.transaction(async (tx) => { + // all. It gives the task back, or the refusal to answer with. A refusal + // returns before the first write: a return commits what was written before + // it. + const outcome = await db.transaction(async (tx): Promise<{ ok: true; task: TaskRow } | Refusal> => { + // Before any write (#208): a body that names a list or a parent that is + // not a live row of the account is refused whole. None of its other fields + // is applied, the task is not completed and has no next occurrence. + const refused = await refusedReference(tx, auth.userId, id, fields); + if (refused) return refused; + let task: TaskRow | undefined; // The other fields first: the task is completed as the body leaves it, and @@ -54,7 +127,7 @@ export async function PUT( completed === undefined ? undefined : isNull(slTasks.deletedAt), )) .returning(); - if (!task) return null; + if (!task) return NOT_FOUND; } if (completed !== undefined) { @@ -64,22 +137,23 @@ export async function PUT( // Not a live task of the account. Nothing was written above in that // case: the write of the fields, when there is one, has the same filter // and has already returned. - if (!result) return null; + if (!result) return NOT_FOUND; task = result.task; } - return task ?? null; + return task ? { ok: true, task } : NOT_FOUND; }); - if (!updated) { - return NextResponse.json({ error: 'Not found' }, { status: 404 }); + // Nothing was written, and nobody is notified. + if (!outcome.ok) { + return NextResponse.json({ error: outcome.error }, { status: outcome.status }); } // Once, and only after the commit: an open page or the app that reloads on // this notice must find the task and its next occurrence. notifyUserChanged(auth.userId); // The task alone, as before: the next occurrence is not part of the answer. - return NextResponse.json(updated); + return NextResponse.json(outcome.task); } export async function DELETE( diff --git a/web/src/app/api/tasks/route.test.ts b/web/src/app/api/tasks/route.test.ts index d9e95f2..7e3c6fe 100644 --- a/web/src/app/api/tasks/route.test.ts +++ b/web/src/app/api/tasks/route.test.ts @@ -164,6 +164,29 @@ async function occurrences(account: Account, seeded: string[]): Promise !seeded.includes(task.id)); } +// One more list for an account; `deletedAt` (an ISO instant) makes it a +// deleted one (#208). +async function newList(account: Account, fields: { deletedAt?: string } = {}): Promise { + const id = u(); + await h.pg.query( + 'insert into sl_lists (id, user_id, name, deleted_at) values ($1, $2, $3, $4)', + [id, account.userId, 'Other', fields.deletedAt ?? null], + ); + return id; +} + +// Every task of the given accounts, every column, in a stable order: what a +// refused request must leave exactly as it was, no row changed and none +// created (#208). +async function tasksOf(...accounts: Account[]): Promise { + const marks = accounts.map((_, i) => `$${i + 1}`).join(', '); + const { rows } = await h.pg.query( + `select * from sl_tasks where user_id in (${marks}) order by id`, + accounts.map((account) => account.userId), + ); + return rows; +} + // The WebSocket notices sent to an account, in order: true for a notice that // left after the commit, false for one sent while a transaction was open. function notices(userId: string): boolean[] { @@ -594,6 +617,182 @@ describe('PUT /api/tasks/[id]: refusals of a body that carries completed (#201)' }); }); +// References of a PUT body (#208): the list and the parent it names are live +// rows of the account of the caller, or the body is refused whole. GONE is +// the instant a deleted row was deleted. +const GONE = '2026-11-10T09:00:00.000Z'; + +const LIST_NOT_FOUND = { status: 404, body: { error: 'List not found' } }; +const PARENT_NOT_FOUND = { status: 404, body: { error: 'Parent task not found' } }; +const TOO_DEEP = { status: 400, body: { error: 'Cannot create sub-subtasks (max 2 levels)' } }; + +// What account A names in the body of a PUT on its own task `id`; B is +// another account. +type Reference = (A: Account, B: Account, id: string) => Promise>; + +describe('PUT /api/tasks/[id]: listId and parentId belong to the account (#208)', () => { + it.each([ + ['the list of another account', LIST_NOT_FOUND, async (_A, B) => ({ listId: B.list })], + ['a deleted list of the account', LIST_NOT_FOUND, async (A) => ({ listId: await newList(A, { deletedAt: GONE }) })], + ['a list that does not exist', LIST_NOT_FOUND, async () => ({ listId: u() })], + ['a parent of another account', PARENT_NOT_FOUND, async (_A, B) => ({ parentId: await newTask(B) })], + ['a deleted parent', PARENT_NOT_FOUND, async (A) => ({ parentId: await newTask(A, { deletedAt: GONE }) })], + ['a parent that does not exist', PARENT_NOT_FOUND, async () => ({ parentId: u() })], + ['the task itself as its parent', PARENT_NOT_FOUND, async (_A, _B, id) => ({ parentId: id })], + // PostgreSQL reads both spellings as the same uuid: comparing the two + // strings in the handler would let this one through. + ['the task itself, id in upper case, as its parent', PARENT_NOT_FOUND, async (_A, _B, id) => ({ parentId: id.toUpperCase() })], + ['a parent that is a subtask', TOO_DEEP, async (A) => ({ parentId: await newTask(A, { parentId: await newTask(A) }) })], + ['a parent, for a task that has a subtask', TOO_DEEP, async (A, _B, id) => { + await newTask(A, { parentId: id }); + return { parentId: await newTask(A) }; + }], + ] as [string, typeof LIST_NOT_FOUND, Reference][])('refuses %s and writes nothing, whatever else the body carries', async (_case, refusal, reference) => { + const A = await newAccount(); + const B = await newAccount(); + // Recurring, with a due date: completing it would create a next occurrence. + const id = await newTask(A, { title: 'Mine', dueDate: DUE, recurrence: 'weekly' }); + const named = await reference(A, B, id); + const before = await tasksOf(A, B); + + // The reference alone, then among the other fields a body can carry. + for (const body of [named, { ...named, title: 'Renamed', priority: 3, completed: true }]) { + const res = await putTask(A.userId, id, body); + expect(res.status, JSON.stringify(body)).toBe(refusal.status); + expect(await res.json()).toEqual(refusal.body); + } + + // Not a column of a row changed and no row was created: the task keeps its + // list, its parent and its title, it is not completed and has no next + // occurrence. + expect(await tasksOf(A, B)).toEqual(before); + expect(notices(A.userId)).toEqual([]); + expect(notices(B.userId)).toEqual([]); + }); + + it('checks the list first, then that the parent exists, as POST /api/tasks does', async () => { + const A = await newAccount(); + const B = await newAccount(); + const id = await newTask(A); + await newTask(A, { parentId: id }); + const theirs = await newTask(B); + const before = await tasksOf(A, B); + + const both = await putTask(A.userId, id, { listId: B.list, parentId: theirs }); + expect(both.status).toBe(404); + expect(await both.json()).toEqual(LIST_NOT_FOUND.body); + + // The task has a subtask, but the parent it names is not found first. + const missing = await putTask(A.userId, id, { parentId: u() }); + expect(missing.status).toBe(404); + expect(await missing.json()).toEqual(PARENT_NOT_FOUND.body); + + expect(await tasksOf(A, B)).toEqual(before); + }); + + it('moves the task to another live list of the account', async () => { + const A = await newAccount(); + const id = await newTask(A); + const other = await newList(A); + const res = await putTask(A.userId, id, { listId: other }); + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ id, listId: other }); + expect((await stored(id)).list_id).toBe(other); + expect(notices(A.userId)).toEqual([true]); + }); + + it('puts the task under a top-level task of the account', async () => { + const A = await newAccount(); + const parent = await newTask(A); + const id = await newTask(A); + const res = await putTask(A.userId, id, { parentId: parent }); + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ id, parentId: parent }); + expect((await stored(id)).parent_id).toBe(parent); + // The same parent once more: a subtask may name the parent it has. + expect((await putTask(A.userId, id, { parentId: parent })).status).toBe(200); + expect((await stored(id)).parent_id).toBe(parent); + expect(notices(A.userId)).toEqual([true, true]); + }); + + it('accepts parentId: null, also for a task that has a subtask', async () => { + const A = await newAccount(); + const parent = await newTask(A); + const first = await newTask(A, { parentId: parent }); + await newTask(A, { parentId: parent }); + + // A subtask goes back to the top level. + const res = await putTask(A.userId, first, { parentId: null }); + expect(res.status).toBe(200); + expect(await res.json()).toMatchObject({ id: first, parentId: null }); + expect((await stored(first)).parent_id).toBeNull(); + + // No parent is named: the subtask that `parent` still has is not looked at. + expect((await putTask(A.userId, parent, { parentId: null })).status).toBe(200); + expect((await stored(parent)).parent_id).toBeNull(); + }); + + it('does not count a deleted subtask: the task can take a parent', async () => { + const A = await newAccount(); + const parent = await newTask(A); + const id = await newTask(A); + await newTask(A, { parentId: id, deletedAt: GONE }); + const res = await putTask(A.userId, id, { parentId: parent }); + expect(res.status).toBe(200); + expect((await stored(id)).parent_id).toBe(parent); + }); + + it('does not count a task of another account placed under the task', async () => { + const A = await newAccount(); + const B = await newAccount(); + const parent = await newTask(A); + const id = await newTask(A); + // What the PUT allowed before #208: a row of B under a task of A. It is + // not a row of A, so it changes nothing to what A may do. + const theirs = await newTask(B, { parentId: id }); + const before = await stored(theirs); + const res = await putTask(A.userId, id, { parentId: parent }); + expect(res.status).toBe(200); + expect((await stored(id)).parent_id).toBe(parent); + expect(await stored(theirs)).toEqual(before); + }); + + it('applies a list and a parent of the account with the other fields of the body', async () => { + const A = await newAccount(); + const other = await newList(A); + const parent = await newTask(A, { list: other }); + const id = await newTask(A, { title: 'Mine' }); + const res = await at(NOW, () => putTask(A.userId, id, { + listId: other, parentId: parent, title: 'Renamed', completed: true, + })); + expect(res.status).toBe(200); + const task = await stored(id); + expect(task).toMatchObject({ list_id: other, parent_id: parent, title: 'Renamed', completed: true }); + expect(task.completed_at?.toISOString()).toBe(NOW); + expect(notices(A.userId)).toEqual([true]); + }); + + it('still answers 404 Not found for a task of another account, whatever the body names', async () => { + const A = await newAccount(); + const B = await newAccount(); + const theirs = await newTask(B, { title: 'Theirs' }); + const parent = await newTask(A); + const before = await tasksOf(A, B); + + for (const body of [ + { listId: A.list }, { parentId: parent }, { listId: A.list, parentId: parent, title: 'Stolen' }, + ]) { + const res = await putTask(A.userId, theirs, body); + expect(res.status, JSON.stringify(body)).toBe(404); + expect(await res.json()).toEqual({ error: 'Not found' }); + } + + expect(await tasksOf(A, B)).toEqual(before); + expect(notices(A.userId)).toEqual([]); + expect(notices(B.userId)).toEqual([]); + }); +}); + // The contract #203 and #204 build on: the functions run in the transaction // of their caller and say what they did. describe('taskWrites: completeTask and reopenTask (#201)', () => {