From 7f6f2eb97cf473dbec87c7f8905c765d1b561fdb Mon Sep 17 00:00:00 2001 From: Maurice Date: Wed, 18 Nov 2026 13:20:05 +0100 Subject: [PATCH] fix(db): read every request row id through toRowId, at the trip guards and the repository lookups toRowId moves to src/db/row-id.ts so repositories can use it (src/db sits below src/nest), together with a new withRowId helper; src/nest/common/row-id.ts re-exports both. Its docstring is rewritten to state the rule plainly. TripsRepository read its number | string trip ids raw: SQLite matched '0x1' against nothing, Postgres 14 and 15 refused the cast with a 500, and 16 and later read it as trip 1. Its access reads, DaysRepository.existsInTrip and the packing template lookups now parse the id first, so an id toRowId refuses is no row on every engine. TripAccessGuard, TripOwnerGuard and JourneyAssistantGuard used Number(), which read '0x1' and '1e0' as row 1; they now use toRowId. --- server/src/db/repositories/Days.repository.ts | 14 +- .../PackingTemplateCategories.repository.ts | 9 +- .../PackingTemplateItems.repository.ts | 9 +- .../PackingTemplates.repository.ts | 10 +- .../src/db/repositories/Trips.repository.ts | 84 +++++------ server/src/db/row-id.ts | 53 +++++++ .../nest/assistant/journey-assistant.guard.ts | 6 +- server/src/nest/common/row-id.ts | 141 ++++-------------- .../src/nest/permissions/trip-access.guard.ts | 10 +- .../src/nest/permissions/trip-owner.guard.ts | 8 +- .../trip-membership/trip-access.service.ts | 4 +- server/tests/e2e/roadtrip.e2e.test.ts | 7 +- server/tests/integration/assignments.test.ts | 5 +- server/tests/integration/days.test.ts | 16 +- server/tests/integration/places.test.ts | 14 +- server/tests/unit/nest/common/row-id.test.ts | 29 +++- 16 files changed, 218 insertions(+), 201 deletions(-) create mode 100644 server/src/db/row-id.ts diff --git a/server/src/db/repositories/Days.repository.ts b/server/src/db/repositories/Days.repository.ts index 1827ac614..b7e23a8b7 100644 --- a/server/src/db/repositories/Days.repository.ts +++ b/server/src/db/repositories/Days.repository.ts @@ -1,6 +1,7 @@ import { columnRef } from '../dialect/sql-functions'; import type { Days } from '../entities/Days.entity'; import type { DB } from '../kysely/db'; +import { toRowId } from '../row-id'; import { toRow, type AssertRowKeys } from './_shared/rows'; import { TrekRepository } from './_shared/trek-repository'; @@ -284,15 +285,18 @@ export class DaysRepository extends TrekRepository { /** * AS4 (`AssignmentsService.dayExists`) — `SELECT id FROM days WHERE id = ? - * AND trip_id = ?`. Raw-bind (`number | string`, D4's T5 escape hatch, - * `TripsRepository.findAccessible`'s precedent): the legacy guard binds - * the route's raw params with no `Number()`/`toRowId` conversion of its - * own, so this must accept and bind exactly what it's handed. + * AND trip_id = ?`. Its callers hand over the route's ids as they came, so + * both are read through `toRowId` (as in `TripsRepository.findAccessible`): + * a spelling it refuses is no day on every engine, where bound raw Postgres + * refused or reinterpreted it and SQLite matched nothing. */ async existsInTrip(id: number | string, trip_id: number | string): Promise { + const dayId = toRowId(id); + const tripId = toRowId(trip_id); + if (dayId === null || tripId === null) return false; const row = await this.qb('d') .select(['d.id']) - .where('d.id = ? AND d.trip_id = ?', [id, trip_id]) + .where('d.id = ? AND d.trip_id = ?', [dayId, tripId]) .execute<{ id: number } | undefined>('get', false); return !!row; } diff --git a/server/src/db/repositories/PackingTemplateCategories.repository.ts b/server/src/db/repositories/PackingTemplateCategories.repository.ts index 9e199479e..2878c2f85 100644 --- a/server/src/db/repositories/PackingTemplateCategories.repository.ts +++ b/server/src/db/repositories/PackingTemplateCategories.repository.ts @@ -1,5 +1,6 @@ import type { PackingTemplateCategories } from '../entities/PackingTemplateCategories.entity'; import type { DB } from '../kysely/db'; +import { toRowId } from '../row-id'; import { type AssertRowKeys } from './_shared/rows'; import { TrekRepository } from './_shared/trek-repository'; @@ -75,11 +76,15 @@ export class PackingTemplateCategoriesRepository extends TrekRepository { + // Route ids: a spelling toRowId refuses is no category, on every engine. + const categoryId = toRowId(id); + const templateId = toRowId(template_id); + if (categoryId === null || templateId === null) return undefined; return await this.db() .selectFrom('packing_template_categories') .selectAll() - .where('id', '=', id as number) - .where('template_id', '=', template_id as number) + .where('id', '=', categoryId) + .where('template_id', '=', templateId) .executeTakeFirst(); } diff --git a/server/src/db/repositories/PackingTemplateItems.repository.ts b/server/src/db/repositories/PackingTemplateItems.repository.ts index 81e746e30..668e59e46 100644 --- a/server/src/db/repositories/PackingTemplateItems.repository.ts +++ b/server/src/db/repositories/PackingTemplateItems.repository.ts @@ -1,5 +1,6 @@ import type { PackingTemplateItems } from '../entities/PackingTemplateItems.entity'; import type { DB } from '../kysely/db'; +import { toRowId } from '../row-id'; import { type AssertRowKeys } from './_shared/rows'; import { TrekRepository } from './_shared/trek-repository'; @@ -133,12 +134,16 @@ export class PackingTemplateItemsRepository extends TrekRepository { + // Route ids: a spelling toRowId refuses is no item, on every engine. + const itemId = toRowId(id); + const templateId = toRowId(template_id); + if (itemId === null || templateId === null) return undefined; return await this.db() .selectFrom('packing_template_items as ti') .innerJoin('packing_template_categories as tc', 'tc.id', 'ti.category_id') .selectAll('ti') - .where('ti.id', '=', id as number) - .where('tc.template_id', '=', template_id as number) + .where('ti.id', '=', itemId) + .where('tc.template_id', '=', templateId) .executeTakeFirst(); } diff --git a/server/src/db/repositories/PackingTemplates.repository.ts b/server/src/db/repositories/PackingTemplates.repository.ts index ce44f5a93..bcc06f54e 100644 --- a/server/src/db/repositories/PackingTemplates.repository.ts +++ b/server/src/db/repositories/PackingTemplates.repository.ts @@ -1,5 +1,6 @@ import type { PackingTemplates } from '../entities/PackingTemplates.entity'; import type { DB } from '../kysely/db'; +import { toRowId } from '../row-id'; import { type AssertRowKeys } from './_shared/rows'; import { TrekRepository } from './_shared/trek-repository'; @@ -109,11 +110,10 @@ export class PackingTemplatesRepository extends TrekRepository * `deletePackingTemplate`'s existence check). One method, five sites. */ async findById(id: number | string): Promise { - return await this.db() - .selectFrom('packing_templates') - .selectAll() - .where('id', '=', id as number) - .executeTakeFirst(); + // A route id toRowId refuses is no template, on every engine. + const templateId = toRowId(id); + if (templateId === null) return undefined; + return await this.db().selectFrom('packing_templates').selectAll().where('id', '=', templateId).executeTakeFirst(); } /** diff --git a/server/src/db/repositories/Trips.repository.ts b/server/src/db/repositories/Trips.repository.ts index 978d30f27..4a73ab670 100644 --- a/server/src/db/repositories/Trips.repository.ts +++ b/server/src/db/repositories/Trips.repository.ts @@ -5,6 +5,7 @@ import type { AssertRowKeys } from './_shared/rows'; import { TrekRepository } from './_shared/trek-repository'; import { tripAccessExpr } from './_shared/trip-access'; import type { DB } from '../kysely/db'; +import { toRowId } from '../row-id'; /** What a trip-scoped request learns about the trip once access is verified. */ export interface TripAccess { @@ -110,19 +111,16 @@ export class TripsRepository extends TrekRepository { * LEFT JOIN trip_members m ON m.trip_id = t.id AND m.user_id = ? * WHERE t.id = ? AND (t.user_id = ? OR m.user_id IS NOT NULL) * - * `trip_id: number | string` (Plan 3c Task 0b): the legacy free function - * bound whatever `req.params.tripId` resolved to straight into the - * statement with no `Number()`/`toRowId` conversion first — the raw-bind - * seam. `TripAccessGuard` still does `Number(tripId)` before calling this - * (unchanged), but `DatabaseService.canAccessTrip`/`isOwner` and every - * other of the 41 in-cluster callers pass a `number | string` through - * unconverted, so this method (and `isOwner` below) must accept and bind - * that raw value rather than coerce it — a coercion here would silently - * change the `'0x10'`/`'007'`-shaped id parity the boot matrix pins - * (`Number('0x10') === 16`, a real trip id, where SQLite's own text/integer - * affinity comparison of the unconverted string never matches one). + * `trip_id: number | string`: most of its callers hand over a route or + * tool id as it came. The legacy statement bound it raw, which SQLite + * compared by affinity (`'0x10'` matched nothing) while Postgres 14 and 15 + * refused the cast with an error and 16 and later read `'0x10'` as 16. So + * this method and the other `number | string` reads below parse the id + * with `toRowId` first: a spelling it refuses is no trip on every engine. */ async findAccessible(trip_id: number | string, user_id: number): Promise { + const id = toRowId(trip_id); + if (id === null) return undefined; const row = await this.accessibleTripsQuery(user_id) .select(['t.id', 't.user', 't.currency']) // Raw condition (D4's T5 escape hatch), not `.where({ 't.id': trip_id })`: @@ -132,7 +130,7 @@ export class TripsRepository extends TrekRepository { // `t.id`/`t.user_id` are the physical column names (not translated // through the entity's `trip`/`user` property aliasing the way a typed // filter object is), so the raw text names them directly. - .andWhere('t.id = ?', [trip_id]) + .andWhere('t.id = ?', [id]) // `mapResults: false` leaves the driver's row alone: the keys are the // column names, which is why the result type is spelled out here rather // than inferred from the entity's properties. @@ -187,9 +185,11 @@ export class TripsRepository extends TrekRepository { /** `SELECT id FROM trips WHERE id = ? AND user_id = ?` */ async isOwner(trip_id: number | string, user_id: number): Promise { + const id = toRowId(trip_id); + if (id === null) return false; const row = await this.qb('t') .select(['t.id']) - .where('t.id = ?', [trip_id]) + .where('t.id = ?', [id]) .andWhere({ user: user_id }) .execute<{ id: number } | undefined>('get', false); return !!row; @@ -199,13 +199,13 @@ export class TripsRepository extends TrekRepository { * `SELECT user_id FROM trips WHERE id = ?` (`trip-membership.service.ts:23`, * TB1) — `row ? row.user_id : null` stays the caller's decision to make * ("owner id for budget/MCP guards"); this returns exactly that shape. - * Raw-bind (D4's T5 escape hatch), same `number | string` seam as - * `findAccessible`/`isOwner` above. */ async getOwnerId(trip_id: number | string): Promise { + const id = toRowId(trip_id); + if (id === null) return null; const row = await this.qb('t') .select(['t.user']) - .where('t.id = ?', [trip_id]) + .where('t.id = ?', [id]) .execute<{ user_id: number } | undefined>('get', false); return row ? row.user_id : null; } @@ -215,8 +215,7 @@ export class TripsRepository extends TrekRepository { * TB4) — `joinTripAsMember`'s first check-then-act read (§18.4: the * sequence stays non-transactional, unchanged by this conversion). The * only caller (`TripMembershipService.joinTripAsMember(tripId: number, …)`) - * always passes a real `number`, so this takes one too — no raw-bind seam - * to preserve here, unlike `findAccessible`/`isOwner`/`getOwnerId`. + * always passes a real `number`, so this takes one too. */ async findIdAndOwner(trip_id: number): Promise<{ id: number; user_id: number } | undefined> { return this.qb('t') @@ -290,13 +289,14 @@ export class TripsRepository extends TrekRepository { /** * `SELECT title FROM trips WHERE id = ?` (`trip-members.service.ts:156`, * TM7) — `addMember`'s notification-body read; the caller applies its own - * `?? 'Untitled'` fallback (D4). Raw-bind (D4's T5 escape hatch), the same - * `number | string` seam `findAccessible` documents. + * `?? 'Untitled'` fallback (D4). */ async getTitle(trip_id: number | string): Promise { + const id = toRowId(trip_id); + if (id === null) return null; const row = await this.qb('t') .select(['t.title']) - .where('t.id = ?', [trip_id]) + .where('t.id = ?', [id]) .execute<{ title: string } | undefined>('get', false); return row?.title ?? null; } @@ -306,12 +306,13 @@ export class TripsRepository extends TrekRepository { * (`trip-members.service.ts:180`, TM9) — `transferOwnership`'s first * check-then-act read (miss → 404 `'Trip not found'`; wrong owner → 400 * `'Only the owner can transfer ownership'`, both decided by the caller). - * Raw-bind, the same seam as `getTitle` above. */ async findIdTitleOwner(trip_id: number | string): Promise<{ id: number; title: string; user_id: number } | undefined> { + const id = toRowId(trip_id); + if (id === null) return undefined; return this.qb('t') .select(['t.id', 't.title', 't.user']) - .where('t.id = ?', [trip_id]) + .where('t.id = ?', [id]) .execute<{ id: number; title: string; user_id: number } | undefined>('get', false); } @@ -341,13 +342,14 @@ export class TripsRepository extends TrekRepository { * `.select(['t.*'])` — MikroORM's QueryBuilder recognises the bare * `.*` marker (verified against `QueryBuilder.js`'s own * `prepareFields`, not assumed) and emits every column unprefixed, the - * same `SELECT t.*` shape the legacy statement used. Raw-bind, the same - * `number | string` seam `getTitle`/`findIdTitleOwner` above preserve. + * same `SELECT t.*` shape the legacy statement used. */ async findRaw(trip_id: number | string): Promise { + const id = toRowId(trip_id); + if (id === null) return null; const row = await this.qb('t') .select(['t.*']) - .where('t.id = ?', [trip_id]) + .where('t.id = ?', [id]) .execute('get', false); return row ?? null; } @@ -400,7 +402,9 @@ export class TripsRepository extends TrekRepository { * same apart from `is_owner`. */ async findListShapeById(trip_id: number | string, user_id: number): Promise { - const row = await this.tripSelectQuery(user_id).where('t.id', '=', trip_id as number).executeTakeFirst(); + const id = toRowId(trip_id); + if (id === null) return undefined; + const row = await this.tripSelectQuery(user_id).where('t.id', '=', id).executeTakeFirst(); return row as TripSelectRow | undefined; } @@ -418,15 +422,14 @@ export class TripsRepository extends TrekRepository { * `TripMembersService.getTripForViewer` (TM1, Task 6 review's "for Task * 7" note) — same reasoning: every caller already holds access. * - * Raw-bind (`number | string`, D4's T5 escape hatch — `TripSelectKyselyDB`'s - * `trips.id` is typed `number | string` for exactly this): the legacy - * statement bound the route's unconverted `tripId` with no `Number()`/ - * `toRowId` conversion, matching `findAccessible`'s documented seam. + * `trip_id` is read through `toRowId`, as in `findAccessible`. */ async findForViewer(trip_id: number | string, user_id: number): Promise { + const id = toRowId(trip_id); + if (id === null) return undefined; const row = await this.tripSelectQuery(user_id) .leftJoin('trip_members as m', (join) => join.onRef('m.trip_id', '=', 't.id').on('m.user_id', '=', user_id)) - .where('t.id', '=', trip_id as number) + .where('t.id', '=', id) .where((eb) => tripAccessExpr(eb, 't.user_id', 'm.user_id', user_id)) .executeTakeFirst(); return row as TripSelectRow | undefined; @@ -769,14 +772,9 @@ export class TripsRepository extends TrekRepository { * access check here, matching the legacy statement — the caller's own * `verifyTripAccess`/token validity gates this read. * - * `id: number` (Plan 4 Task 8a, rule 23): unlike `findAccessible`/ - * `isOwner`, this is never on the guard's raw-`req.params` path — its one - * caller (`share.service.ts#getSharedTripData`) passes `shareRow.trip_id`, - * a `number` straight off a Kysely-typed `share_tokens` row, never an - * unconverted URL param — so the `number | string` raw-bind seam those - * two methods' own docstrings describe does not apply here, and this one - * narrows to a typed filter now rather than waiting on that seam's guard- - * level parse (deferred, out of this task's scope). + * `id: number` (Plan 4 Task 8a, rule 23): its one caller + * (`share.service.ts#getSharedTripData`) passes `shareRow.trip_id`, a + * `number` straight off a Kysely-typed `share_tokens` row. */ async findPublicForShare(id: number): Promise { return await this.qb('t') @@ -817,11 +815,13 @@ export class TripsRepository extends TrekRepository { // --------------------------------------------------------------------------- /** BG15/BG16/BGM2/BGM3 — `SELECT currency FROM trips WHERE id = ?`, four legacy call sites, one statement. */ - async getCurrency(id: number | string): Promise { + async getCurrency(trip_id: number | string): Promise { + const id = toRowId(trip_id); + if (id === null) return undefined; const row = await this.kysely>() .selectFrom('trips') .select('currency') - .where('id', '=', id as number) + .where('id', '=', id) .executeTakeFirst(); return row?.currency; } diff --git a/server/src/db/row-id.ts b/server/src/db/row-id.ts new file mode 100644 index 000000000..45c9a0aaa --- /dev/null +++ b/server/src/db/row-id.ts @@ -0,0 +1,53 @@ +/** + * How a row id that arrives as text becomes a number before it reaches SQL. + * `src/nest/common/row-id.ts` re-exports both helpers for the Nest layers. + */ + +/** + * The one rule by which a row id from outside (a path, a query, a body, an MCP + * resource URI, a plugin RPC param, a websocket message) becomes the number a + * repository binds. + * + * Only the canonical spelling is an id: a safe integer, or a string of decimal + * digits naming one ('007' is 7, as SQLite's own conversion reads it). Every + * other spelling names no row and returns null: 'abc', '0x5', '5e0', '5.0', + * '+5', ' 5', '5 ', '5_0', '-5', '' and a number past 2^53. Bound to SQL as + * sent, those strings answer three ways. SQLite compares a TEXT operand with an + * INTEGER column by numeric affinity, so ' 5', '5.0', '+5' and '5e0' match row + * 5 there while '0x5' matches nothing. Postgres 14 and 15 refuse the cast with + * an error, a 500. Postgres 16 and later read hex and underscores as a number. + * `Number()` and `parseInt()` read most of them as 5 on every engine, and hand + * NaN or a number past the bigint range to Postgres, which refuses it. + * + * Our own clients only ever send `String(id)` of an integer column, so the + * refusal costs nothing but a hand-made request, which gets the answer an id + * that names no row gets. Keep the regex as it is: narrowing it to refuse + * '007' or widening it to any spelling an engine accepts brings the + * difference back. + * + * A caller that ran `Number(id)` before handing the value in has already lost + * the spelling: `toRowId(Number('0x10'))` is 16. Pass the raw value. + */ +export function toRowId(value: unknown): number | null { + if (typeof value === 'number') { + return Number.isSafeInteger(value) ? value : null; + } + if (typeof value === 'string' && /^\d+$/.test(value)) { + const parsed = Number(value); + return Number.isSafeInteger(parsed) ? parsed : null; + } + return null; +} + +/** + * Runs `read` with the id `toRowId` parses from `value`, or answers undefined + * without reading when it refuses the value. For the lookups that take an id + * from a request: a spelling no client sends ('0x1', '1e0', '1.0', '+1', '1_0', + * a number past 2^53) is no row, the same answer on every engine, where bound + * raw SQLite matched nothing, Postgres 14 and 15 refused the cast with an + * error and Postgres 16 and later read hex and underscores as a number. + */ +export async function withRowId(value: unknown, read: (id: number) => Promise): Promise { + const id = toRowId(value); + return id === null ? undefined : read(id); +} diff --git a/server/src/nest/assistant/journey-assistant.guard.ts b/server/src/nest/assistant/journey-assistant.guard.ts index 2647c494a..126e55cd1 100644 --- a/server/src/nest/assistant/journey-assistant.guard.ts +++ b/server/src/nest/assistant/journey-assistant.guard.ts @@ -1,6 +1,7 @@ import { ADDON_IDS } from '../../addons'; import type { User } from '../../types'; import { AddonsService } from '../addons/addons.service'; +import { toRowId } from '../common/row-id'; import { AssistantBookContext } from './assistant-book-context'; import { CanActivate, ExecutionContext, HttpException, Injectable } from '@nestjs/common'; @@ -30,8 +31,9 @@ export class JourneyAssistantGuard implements CanActivate { if (!(await this.addons.isAddonEnabled(ADDON_IDS.JOURNEY))) { throw new HttpException({ error: 'Journey addon is not enabled' }, 404); } - const journeyId = Number((request.params as Record).journeyId); - const open = Number.isInteger(journeyId) && journeyId > 0 && (await this.books.canOpen(user.id, journeyId)); + // toRowId, not Number(): Number('0x1') and Number('1e0') are journey 1. + const journeyId = toRowId((request.params as Record).journeyId); + const open = journeyId !== null && journeyId > 0 && (await this.books.canOpen(user.id, journeyId)); if (!open) throw new HttpException({ error: 'Journey not found' }, 404); return true; } diff --git a/server/src/nest/common/row-id.ts b/server/src/nest/common/row-id.ts index 3cbf5125a..28adc5a6a 100644 --- a/server/src/nest/common/row-id.ts +++ b/server/src/nest/common/row-id.ts @@ -1,120 +1,37 @@ -/** - * The one place an external, string-shaped route/tool id is turned into a - * numeric primary key before it reaches a typed repository filter. - * - * The legacy raw-SQL layer bound a route param straight into `WHERE id = ?` - * and let SQLite's column-affinity rules do the work. Those rules are more - * permissive than they look: SQLite applies NUMERIC affinity to a TEXT - * operand compared against an INTEGER column using the same conversion CAST - * uses, which accepts leading/trailing whitespace, a leading sign, a decimal - * point and an exponent — so `WHERE id = ?` genuinely matches integer row 1 - * for `' 1'`, `'1 '`, `'1.0'` and `'+1'`, and matches row 1000 for `'1e3'` - * (verified empirically against `better-sqlite3`, not assumed — this - * docstring previously claimed the opposite, that `'1e3'` "can never equal - * an INTEGER column"; that claim was false). A typed MikroORM filter has no - * such affinity: `Number('abc')` is `NaN`, and the ORM renders that as the - * bare, unquoted token `NaN` in the generated SQL, which SQLite parses as a - * column reference and throws `InvalidFieldNameException: no such column: - * NaN` — a 500 where the legacy route 404'd (Plan 3b Task 2 review, F1). - * - * `toRowId` is the guard every converted service calls instead of a bare - * `Number(id)`. It does NOT reproduce every string SQLite's affinity - * conversion would have matched — that would mean accepting `' 1'`, `'1.0'`, - * `'1e3'`, `'+1'`, and there is no realistic route/tool input that spells an - * id that way: every id in this codebase originates as - * `String()` on our own client (a URL path segment or - * an MCP tool argument), which is always a canonical decimal string, digits - * only, no sign, no leading zero beyond what the id itself is, no decimal - * point, no exponent, no surrounding whitespace. `toRowId` accepts exactly - * that canonical shape (`/^\d+$/`, so `'007'` — an id that happens to have - * leading zeros, which SQLite's own affinity conversion also resolves to 7 — - * still matches) and returns `null` for every non-canonical spelling, - * INCLUDING the ones SQLite's affinity would have matched. This is a - * DELIBERATE, ACCEPTED narrowing (program rule 15, - * `docs/superpowers/plans/2026-09-21-orm-migration-program.md`): a - * non-canonical id can only ever reach this guard from something other than - * our own client (a hand-crafted request), and failing closed to the - * route's legacy not-found result for it is the documented parity - * deviation, not a bug — never widen the regex to `/^(0|[1-9]\d*)$/` or any - * other shape that would reject `'007'`, and never widen it to accept the - * divergent shapes above either. - * - * **The "accepted narrowing" is a different SIZE depending on what the - * legacy seam bound (task-3-rereview.md R1).** Not every legacy raw-SQL - * call site bound the route string straight into `WHERE id = ?` and leaned - * on SQLite's affinity as described above (an "affinity seam" — - * `registration-invites.service.ts::deleteInvite` is one, and so are the - * categories/tags/token routes Task 2 converted): some called `Number(id)` - * FIRST, in application code, before the query ever ran (a "`Number()` - * seam" — `passkey.service.ts::renamePasskey`/`deletePasskey`, - * `AdminService.resetUserPasskeys`). On an affinity seam, `toRowId` removes - * only the genuine false-accepts described above (whitespace, decimal - * point, exponent, leading `+`). On a `Number()` seam it removes a WIDER - * set: `Number('0x10')`, `Number('1e1')`, `Number('16.0')` and `Number(' - * 16')` all coerce to a real integer in JavaScript (unlike SQLite's - * affinity, which never converts a hex literal), so on that kind of seam - * `toRowId` additionally refuses every hex and exponent form that used to - * hit a REAL row, not just malformed ones. Both are the same deliberate, - * accepted deviation — `toRowId` is right for both — but a regression test - * that asserts "`'0x10'` gets the legacy 404" is only true on an affinity - * seam; on a `Number()` seam the legacy statement acted on the row `toRowId` - * now refuses, so the honest claim is "the deliberate `toRowId` narrowing", - * not "parity with the legacy". Check which kind of seam a route's legacy - * handler was (`git show :` on the actual statement, not the - * route) before writing that test. - * - * **A THIRD shape narrows nothing at all: a PRE-COERCED `Number()` seam** - * (Task 7 review, M2/A-M2). The two `Number()`-seam routes above still hand - * `toRowId` the RAW STRING — the legacy code's own `Number(id)` conversion - * moved to a repository-facing call site, so `toRowId` sees what the legacy - * `Number()` used to see and narrows exactly as described. But on some - * routes the legacy's `Number(id)` conversion itself survives UPSTREAM of - * `toRowId`, and `toRowId` receives an already-coerced `number`, not the - * original string — `oauth-api.controller.ts::revokeSession`'s `DELETE - * /api/oauth/sessions/:id` is that shape on both the legacy and the - * converted tree: `Number(id)` runs first, `toRowId(Number(id))` only - * checks `Number.isSafeInteger`, and the legacy statement never matched a - * non-safe-integer either — so `'0x10'`, `'1e1'`, `'16.0'` and `' 16'` all - * reach the SAME row on both trees (verified live, Task 7 review security - * report). There is no narrowing to name here, and no regression test - * should claim one for this shape — record it as "the pre-coerced - * `Number()` seam: full parity" and move on, the same way `passkey.service - * .ts::adminResetPasskeys` (`:502-507`) already documents its own copy of - * this exact shape. - */ -export function toRowId(value: unknown): number | null { - if (typeof value === 'number') { - return Number.isSafeInteger(value) ? value : null; - } - if (typeof value === 'string' && /^\d+$/.test(value)) { - const parsed = Number(value); - return Number.isSafeInteger(parsed) ? parsed : null; - } - return null; -} +// The rule itself lives in the data layer, so a repository that still takes a +// request's string id reads it the same way (src/db sits below src/nest). +import { toRowId, withRowId } from '../../db/row-id'; + +export { toRowId, withRowId }; /** - * The TEXT shape the legacy raw-SQL layer actually stored for an - * `accommodation_id` value bound as a plain JS number (Plan 3d Task 3/7 - * finding, verified empirically against the live `better-sqlite3` driver, - * not assumed): `better-sqlite3` binds every plain JS `number` as SQLite - * REAL regardless of integer-ness (confirmed via `typeof(?)`), and SQLite's - * own "numeric value inserted into a TEXT column becomes text" rule then - * renders a REAL's decimal form — `14` → `'14.0'`, never the plain integer - * text `'14'`. `String(id)` (what a SQL-literal-inlined `em.insert()`, - * rule 22, would produce for a bound `number`) renders `'14'` instead — a - * DIFFERENT stored shape from the legacy's — and a reader that still - * compares against the REAL-bound form (`restampLinkedReservation`/DY23 - * binds the id as a number through Kysely, which is REAL again) silently - * misses every row written that way. + * The text the legacy raw-SQL layer stored for an `accommodation_id` bound + * as a plain JS number. `better-sqlite3` binds every JS `number` as a SQLite + * REAL, whole or not (`typeof(?)` reports 'real'), and SQLite stores a + * numeric value written into a TEXT column as its text form, so `14` was + * stored as `'14.0'`, never `'14'`. `String(id)` gives `'14'`, a different + * stored shape, and a read held to the legacy compare (`reservationStayIs`, + * which `restampLinkedReservation` uses) would miss every row written that + * way. * * Use this wherever a `number` id is written into the `accommodation_id` - * TEXT column so the stored bytes match what the legacy statement would - * have stored for the same input — never `String(id)` for that column. - * `ReservationsRepository`'s reads of this column that must match BOTH the - * legacy shape and a `String(id)` shape go through `castIntegerKysely` - * instead (see that file's docstring); this helper is for WRITES only. + * TEXT column, so the stored text matches what the legacy statement stored + * for the same input; never `String(id)` for that column. The reads go + * through src/db/repositories/_shared/reservation-accommodation.ts, which + * compares this column the same way on both engines; this helper is for + * writes only. */ export function legacyBoundIntegerText(id: number): string { return `${id}.0`; } + +/** + * An id variable of an MCP resource URI (`trek://trips/{tripId}/...`), one + * value or the first of a list, as a positive row id, or null. Read through + * toRowId: Number() took '0x1' and '1e0' for 1 and passed 1e20 to Postgres, + * which refuses it as out of range for bigint. + */ +export function uriRowId(value: string | string[]): number | null { + const id = toRowId(Array.isArray(value) ? value[0] : value); + return id !== null && id > 0 ? id : null; +} diff --git a/server/src/nest/permissions/trip-access.guard.ts b/server/src/nest/permissions/trip-access.guard.ts index a505cbc89..982798c27 100644 --- a/server/src/nest/permissions/trip-access.guard.ts +++ b/server/src/nest/permissions/trip-access.guard.ts @@ -1,6 +1,7 @@ import { Trips } from '../../db/entities/Trips.entity'; import type { TripAccess } from '../../db/repositories/Trips.repository'; import type { User } from '../../types'; +import { withRowId } from '../common/row-id'; import { PermissionsService } from './permissions.service'; import { EntityManager } from '@mikro-orm/core'; import { CanActivate, ExecutionContext, HttpException, Injectable, SetMetadata } from '@nestjs/common'; @@ -72,10 +73,11 @@ export class TripAccessGuard implements CanActivate { // undefined and turn a wiring mistake into a 500. if (!user) throw new HttpException({ error: 'Unauthorized' }, 401); - const tripId = Number((request.params as Record)?.tripId); - const trip = Number.isFinite(tripId) - ? await this.em.getRepository(Trips).findAccessible(tripId, user.id) - : undefined; + // toRowId, not Number(): Number('0x1') and Number('1e0') are 1, so a spelling no + // client sends would reach trip 1 here while the handler binds the raw string, + // which SQLite matches against nothing and Postgres refuses or reads its own way. + const tripId = (request.params as Record)?.tripId; + const trip = await withRowId(tripId, (id) => this.em.getRepository(Trips).findAccessible(id, user.id)); // A trip the user may not see is reported as absent, never as forbidden: a 403 // would confirm the id exists to someone who has no business knowing. if (!trip) throw new HttpException({ error: 'Trip not found' }, 404); diff --git a/server/src/nest/permissions/trip-owner.guard.ts b/server/src/nest/permissions/trip-owner.guard.ts index 21b7db3df..f7ce80ac0 100644 --- a/server/src/nest/permissions/trip-owner.guard.ts +++ b/server/src/nest/permissions/trip-owner.guard.ts @@ -1,6 +1,7 @@ import { Trips } from '../../db/entities/Trips.entity'; import type { TripAccess } from '../../db/repositories/Trips.repository'; import type { User } from '../../types'; +import { withRowId } from '../common/row-id'; import { TRIP_REQUEST_KEY } from './trip-access.guard'; import { EntityManager } from '@mikro-orm/core'; import { CanActivate, ExecutionContext, HttpException, Injectable, SetMetadata } from '@nestjs/common'; @@ -82,10 +83,9 @@ export class TripOwnerGuard implements CanActivate { // so a request never costs two lookups of the same trip. let trip = request[TRIP_REQUEST_KEY]; if (!trip) { - const tripId = Number((request.params as Record)?.[meta?.param ?? 'tripId']); - trip = Number.isFinite(tripId) - ? ((await this.em.getRepository(Trips).findAccessible(tripId, user.id)) ?? undefined) - : undefined; + // toRowId, as in TripAccessGuard: Number() read '0x1' and '1e0' as trip 1. + const tripId = (request.params as Record)?.[meta?.param ?? 'tripId']; + trip = await withRowId(tripId, (id) => this.em.getRepository(Trips).findAccessible(id, user.id)); if (trip) request[TRIP_REQUEST_KEY] = trip; } if (!trip) throw new HttpException({ error: 'Trip not found' }, 404); diff --git a/server/src/nest/trip-membership/trip-access.service.ts b/server/src/nest/trip-membership/trip-access.service.ts index 2af3294b7..1252676f8 100644 --- a/server/src/nest/trip-membership/trip-access.service.ts +++ b/server/src/nest/trip-membership/trip-access.service.ts @@ -14,8 +14,8 @@ import { Injectable } from '@nestjs/common'; * * Before this the domains injected TripsRepository themselves for this one * read, so the trips table had a reader in thirty files outside its domain. - * The id is bound exactly as given (TripsRepository.findAccessible explains - * why it is never coerced here); a caller that coerced before still does. + * The id is read the way TripsRepository.findAccessible reads it (toRowId): + * a spelling no client sends is no trip, on every engine. */ @Injectable() export class TripAccessService { diff --git a/server/tests/e2e/roadtrip.e2e.test.ts b/server/tests/e2e/roadtrip.e2e.test.ts index 6afa5f9b7..9b5c4c70b 100644 --- a/server/tests/e2e/roadtrip.e2e.test.ts +++ b/server/tests/e2e/roadtrip.e2e.test.ts @@ -481,7 +481,7 @@ describe('Roadtrip e2e (real guard chain + temp SQLite)', () => { // raw-bind statement's affinity never converts a hex string, so it // always answered empty. Every one of these three now answers the // legacy empty shape for the same hex id, not the real trip's rows. - it("L1 — vias/tracks by a hex-spelled trip id answer the legacy empty shape, not trip 5's real rows", async () => { + it("vias/tracks by a hex-spelled trip id answer the guard's 404, not trip 5's real rows", async () => { const created = await request(server) .post('/api/trips/5/roadtrip/days/3/vias') .set('Cookie', cookie()) @@ -490,8 +490,9 @@ describe('Roadtrip e2e (real guard chain + temp SQLite)', () => { const hexTripId = '0x' + (5).toString(16); const res = await request(server).get(`/api/trips/${hexTripId}/roadtrip/vias`).set('Cookie', cookie()); - expect(res.status).toBe(200); - expect(res.body).toEqual({ vias: [], tracks: [] }); + // TripAccessGuard reads :tripId through toRowId, so the hex spelling is no trip at all. + expect(res.status).toBe(404); + expect(res.body).toEqual({ error: 'Trip not found' }); const hexDayId = '0x' + (3).toString(16); const dayRes = await request(server).get(`/api/trips/5/roadtrip/days/${hexDayId}/vias`).set('Cookie', cookie()); diff --git a/server/tests/integration/assignments.test.ts b/server/tests/integration/assignments.test.ts index 4c045a719..7d6803fad 100644 --- a/server/tests/integration/assignments.test.ts +++ b/server/tests/integration/assignments.test.ts @@ -458,7 +458,7 @@ describe('Assignment participants', () => { // ───────────────────────────────────────────────────────────────────────────── describe('H1 — trip id parsed once at the gate (rule 21)', () => { - it('POST create-assignment by the hex-spelled trip id 404s "Day not found" (legacy: 404, not 201)', async () => { + it('POST create-assignment by the hex-spelled trip id 404s "Trip not found" at the guard (legacy: 404, not 201)', async () => { const { user } = await makeUser(orm); const { trip, day, place } = await setupAssignmentFixtures(user.id); const hexTripId = '0x' + trip.id.toString(16); @@ -467,8 +467,9 @@ describe('H1 — trip id parsed once at the gate (rule 21)', () => { .post(`/api/trips/${hexTripId}/days/${day.id}/assignments`) .set('Cookie', authCookie(user.id)) .send({ place_id: place.id }); + // TripAccessGuard reads :tripId through toRowId, so the hex spelling is no trip. expect(res.status).toBe(404); - expect(res.body).toEqual({ error: 'Day not found' }); + expect(res.body).toEqual({ error: 'Trip not found' }); expect(await countRows(orm, DayAssignments, { day: day.id })).toBe(0); }); }); diff --git a/server/tests/integration/days.test.ts b/server/tests/integration/days.test.ts index c5686b916..80f7c3c0b 100644 --- a/server/tests/integration/days.test.ts +++ b/server/tests/integration/days.test.ts @@ -670,17 +670,17 @@ describe('Accommodations', () => { // ───────────────────────────────────────────────────────────────────────────── describe('A-H2 — DaysService trip id parsed once, threaded to every survivor (Task 9 fix wave)', () => { - it("GET /days by the hex-spelled trip id answers the legacy-shaped miss ({ days: [] }), not the real trip's days", async () => { + it("GET /days by the hex-spelled trip id answers the guard's 404, not the real trip's days (TripAccessGuard reads :tripId through toRowId)", async () => { const { user } = await makeUser(orm()); const trip = await makeTrip(orm(), user.id, { title: 'Trip', start_date: '2026-09-01', end_date: '2026-09-03' }); const hexTripId = '0x' + trip.id.toString(16); const res = await request(app).get(`/api/trips/${hexTripId}/days`).set('Cookie', authCookie(user.id)); - expect(res.status).toBe(200); - expect(res.body).toEqual({ days: [] }); + expect(res.status).toBe(404); + expect(res.body).toEqual({ error: 'Trip not found' }); }); - it('PUT /days/:id by the hex-spelled trip id 404s "Day not found" (getDay\'s own toRowId gate), not the real trip\'s day', async () => { + it('PUT /days/:id by the hex-spelled trip id 404s "Trip not found" at the guard, not the real trip\'s day', async () => { const { user } = await makeUser(orm()); const trip = await makeTrip(orm(), user.id, { title: 'Trip' }); const day = await makeDay(orm(), trip.id, { title: 'Original' }); @@ -691,7 +691,7 @@ describe('A-H2 — DaysService trip id parsed once, threaded to every survivor ( .set('Cookie', authCookie(user.id)) .send({ title: 'Renamed' }); expect(res.status).toBe(404); - expect(res.body).toEqual({ error: 'Day not found' }); + expect(res.body).toEqual({ error: 'Trip not found' }); const row = await findRow(orm(), Days, { id: day.id }); expect(row?.title).toBe('Original'); }); @@ -841,7 +841,7 @@ describe('A-H2 — DaysService trip id parsed once, threaded to every survivor ( expect(after).toBe(before); }); - it('PUT /days/reorder by the hex-spelled trip id 400s "orderedIds must be a permutation…" and writes NOTHING — the live H2 bug: it used to 200 and invert a real accommodation', async () => { + it('PUT /days/reorder by the hex-spelled trip id 404s "Trip not found" at the guard and writes NOTHING, where it used to answer 200 and invert a real accommodation', async () => { const { user } = await makeUser(orm()); const trip = await makeTrip(orm(), user.id, { title: 'Trip', start_date: '2026-06-01', end_date: '2026-06-03' }); const days = await dayList(trip.id); @@ -859,8 +859,8 @@ describe('A-H2 — DaysService trip id parsed once, threaded to every survivor ( .put(`/api/trips/${hexTripId}/days/reorder`) .set('Cookie', authCookie(user.id)) .send({ orderedIds: [d2.id, d1.id, d3.id] }); - expect(res.status).toBe(400); - expect(res.body).toEqual({ error: 'orderedIds must be a permutation of the trip day ids.' }); + expect(res.status).toBe(404); + expect(res.body).toEqual({ error: 'Trip not found' }); // Nothing renumbered. const after = await dayList(trip.id); diff --git a/server/tests/integration/places.test.ts b/server/tests/integration/places.test.ts index 9dbf37b4b..191981819 100644 --- a/server/tests/integration/places.test.ts +++ b/server/tests/integration/places.test.ts @@ -464,7 +464,7 @@ describe('Search places', () => { expect(res.body.places[0].name).toBe('Scenic Place'); }); - it('PLACE-017c — GET ?category= or ?tag= with an id that is not a number matches nothing', async () => { + it('PLACE-017c: GET ?category= or ?tag= with an id that is not a number matches nothing', async () => { const { user } = await makeUser(orm); const trip = await makeTrip(orm, user.id); await makePlace(orm, trip.id, { name: 'Somewhere' }); @@ -1065,8 +1065,9 @@ describe('H1 — trip id parsed once at the gate (rule 21)', () => { const hexTripId = '0x' + trip.id.toString(16); const res = await request(app).get(`/api/trips/${hexTripId}/places/${place.id}`).set('Cookie', authCookie(user.id)); + // TripAccessGuard reads :tripId through toRowId, so the hex spelling is no trip. expect(res.status).toBe(404); - expect(res.body).toEqual({ error: 'Place not found' }); + expect(res.body).toEqual({ error: 'Trip not found' }); }); it('PUT with tags by the hex-spelled trip id 404s "Trip not found" (Task 9 fix wave: `verifyTripAccess` now gates BEFORE the place-id read, so the string changed from "Place not found") and leaves the tags untouched (H1 live: they used to be wiped)', async () => { @@ -1135,7 +1136,7 @@ describe('H1 — trip id parsed once at the gate (rule 21)', () => { .delete(`/api/trips/${hexTripId}/places/${place.id}`) .set('Cookie', authCookie(user.id)); expect(res.status).toBe(404); - expect(res.body).toEqual({ error: 'Place not found' }); + expect(res.body).toEqual({ error: 'Trip not found' }); expect(await findRow(orm, Places, { id: place.id })).toBeTruthy(); expect(await findRow(orm, BudgetItems, { place: place.id })).toBeTruthy(); expect(broadcast).not.toHaveBeenCalled(); @@ -1303,18 +1304,17 @@ describe('A-H1 / A-M1 / B-H1 — verifyTripAccess parses once with toRowId (Task }); // ───────────────────────────────────────────────────────────────────────────── -// M1 / program rule 22 (task-4-review.md) — control characters in a user -// string round-trip on every engine. The NUL byte, which neither engine +// Control characters in a user string round-trip on every engine. The NUL byte, which neither engine // stores, has its own suite: places-nul.test.ts. // ───────────────────────────────────────────────────────────────────────────── -describe('M1 — control characters in a place name (rule 22)', () => { +describe('control characters in a place name', () => { it('fuzzes every 0x01-0x1F control character in a created place name: none 500 and every one round-trips', async () => { const { user } = await makeUser(orm); const trip = await makeTrip(orm, user.id); // 0x00 is covered by places-nul.test.ts; this sweeps the rest - // of the control-character range the review's fuzz asked for. + // of the control-character range. for (let code = 0x01; code <= 0x1f; code++) { const name = `ctrl${String.fromCharCode(code)}char`; const res = await request(app) diff --git a/server/tests/unit/nest/common/row-id.test.ts b/server/tests/unit/nest/common/row-id.test.ts index a325c1c0a..9893067f6 100644 --- a/server/tests/unit/nest/common/row-id.test.ts +++ b/server/tests/unit/nest/common/row-id.test.ts @@ -1,4 +1,4 @@ -import { toRowId } from '../../../../src/nest/common/row-id'; +import { toRowId, uriRowId, withRowId } from '../../../../src/nest/common/row-id'; import { describe, it, expect } from 'vitest'; @@ -63,3 +63,30 @@ describe('toRowId', () => { expect(toRowId('9007199254740993')).toBeNull(); }); }); + +describe('withRowId', () => { + it('ROWID-013: reads with the parsed id', async () => { + expect(await withRowId('42', async (id) => id + 1)).toBe(43); + }); + + it('ROWID-014: answers undefined without reading for a spelling toRowId refuses', async () => { + let read = false; + const spellings = ['0x2a', '42e0', '42.0', '+42', '4_2', ' 42', 'abc', '99999999999999999999']; + const answers = await Promise.all(spellings.map((spelling) => withRowId(spelling, async () => ((read = true), 1)))); + expect(answers).toEqual(spellings.map(() => undefined)); + expect(read).toBe(false); + }); +}); + +describe('uriRowId', () => { + it('ROWID-015: reads the first value of an MCP URI variable as a positive id', () => { + expect(uriRowId('7')).toBe(7); + expect(uriRowId(['8', '9'])).toBe(8); + }); + + it('ROWID-016: refuses zero and every spelling toRowId refuses, Number() read them as ids', () => { + for (const spelling of ['0', '0x7', '7e0', '7.0', '+7', '1e20', 'not-a-number']) { + expect(uriRowId(spelling)).toBeNull(); + } + }); +});