Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(reservations): parse every referenced id in a booking body with toRowId

Mauricee8f808b67f8c
diff --git a/server/scripts/size-baseline.json b/server/scripts/size-baseline.json
index 1dc1d52e6..12c527e90 100644
--- a/server/scripts/size-baseline.json
+++ b/server/scripts/size-baseline.json
@@ -15,6 +15,6 @@
"src/nest/places/places.service.ts": 1546,
"src/nest/plugins/plugin-runtime.service.ts": 1460,
"src/nest/plugins/runtime/plugin-sdk.ts": 1093,
- "src/nest/reservations/reservations.service.ts": 1168,
+ "src/nest/reservations/reservations.service.ts": 1166,
"src/nest/vacay/vacay.service.ts": 1393
}
diff --git a/server/src/nest/reservations/reservation-rows.ts b/server/src/nest/reservations/reservation-rows.ts
new file mode 100644
index 000000000..dbe4efe93
--- /dev/null
+++ b/server/src/nest/reservations/reservation-rows.ts
@@ -0,0 +1,35 @@
+import type { ReservationEndpoint } from './reservation-inputs';
+
+/*
+ * The shapes the reservations service hands out: a booking row as the joined
+ * reads return it, and the travelers on it. Kept apart from
+ * reservations.service.ts, which is at its size baseline, the way
+ * reservation-inputs.ts is; the service exports them on, so their importers
+ * did not change.
+ */
+
+// --- Travelers (#1517): trip members / named guests assigned to a booking -----
+
+export interface ReservationTraveler {
+ user_id: number;
+ username: string;
+ avatar: string | null;
+ avatar_url?: string | null;
+ is_guest?: number | null;
+}
+
+/** A reservation row as the joined list/get queries return it (open record —
+ * the legacy queries selected `r.*` and callers pass the row through; the
+ * named fields are the columns consumers read in a typed position). */
+export type ReservationRow = Record<string, unknown> & {
+ id: number;
+ trip_id: number;
+ title: string;
+ status: string;
+ type: string;
+ metadata?: string | null;
+ accommodation_id?: number | string | null;
+ day_positions?: Record<number, number> | null;
+ endpoints?: ReservationEndpoint[];
+ travelers?: ReservationTraveler[];
+};
diff --git a/server/src/nest/reservations/reservations.service.ts b/server/src/nest/reservations/reservations.service.ts
index e3cf0205c..f9f82ce0b 100644
--- a/server/src/nest/reservations/reservations.service.ts
+++ b/server/src/nest/reservations/reservations.service.ts
@@ -1,6 +1,8 @@
import { originColumns } from './reservation-origin.contract';
import type { CreateAccommodation, CreateReservationData, EndpointInput, ReservationEndpoint, UpdateReservationData } from './reservation-inputs';
export type { CreateAccommodation, CreateReservationData, EndpointInput, ReservationEndpoint, UpdateReservationData } from './reservation-inputs';
+import type { ReservationRow, ReservationTraveler } from './reservation-rows';
+export type { ReservationRow, ReservationTraveler } from './reservation-rows';
import { BadRequestException, Injectable } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import type { TripAccess, TripsRepository } from '../../db/repositories/Trips.repository';
@@ -55,32 +57,6 @@ export type CostEvent =
| { event: 'budget:updated'; payload: TrekWsPayload<'budget:updated'> }
| { event: 'budget:deleted'; payload: TrekWsPayload<'budget:deleted'> };
-// --- Travelers (#1517): trip members / named guests assigned to a booking -----
-
-export interface ReservationTraveler {
- user_id: number;
- username: string;
- avatar: string | null;
- avatar_url?: string | null;
- is_guest?: number | null;
-}
-
-/** A reservation row as the joined list/get queries return it (open record —
- * the legacy queries selected `r.*` and callers pass the row through; the
- * named fields are the columns consumers read in a typed position). */
-export type ReservationRow = Record<string, unknown> & {
- id: number;
- trip_id: number;
- title: string;
- status: string;
- type: string;
- metadata?: string | null;
- accommodation_id?: number | string | null;
- day_positions?: Record<number, number> | null;
- endpoints?: ReservationEndpoint[];
- travelers?: ReservationTraveler[];
-};
-
type AccommodationTimesMeta = {
check_in_time?: string | null;
check_in_end_time?: string | null;
@@ -406,7 +382,14 @@ export class ReservationsService {
// every call site below `await`s it; the async-closure mutation harness
// (`tests/integration/async-closure-truthiness-guards.test.ts`,
// RS21-001/RS21-002) proves a dropped `await` goes red.
- const elsewhere = async (table: 'days' | 'places' | 'day_accommodations', id: number): Promise<boolean> => {
+ //
+ // The body is not schema-checked, so an id can be any string: one `toRowId`
+ // refuses resolves to nothing, as on SQLite, where `'0x1'` or `'abc'` matches
+ // no integer id. Postgres would refuse the cast (14, 15) or read the hex
+ // (16 on): a 500 on one engine and a real row on another.
+ const elsewhere = async (table: 'days' | 'places' | 'day_accommodations', value: unknown): Promise<boolean> => {
+ const id = toRowId(value);
+ if (id === null) return false;
let rowTripId: number | undefined;
if (table === 'days') {
rowTripId = (await this.daysRepo.findById(id))?.trip_id;
@@ -427,7 +410,8 @@ export class ReservationsService {
if (data.assignment_id != null) {
// An assignment belongs to a trip through its day, so the join is the
// lookup — same shape as the MCP tool's getAssignmentForTrip. RS22.
- const rowTripId = await this.reservationsRepo.getAssignmentTripId(data.assignment_id);
+ const assignmentId = toRowId(data.assignment_id);
+ const rowTripId = assignmentId === null ? undefined : await this.reservationsRepo.getAssignmentTripId(assignmentId);
check('assignment_id', rowTripId !== undefined && String(rowTripId) !== String(tripId));
}
@@ -469,7 +453,10 @@ export class ReservationsService {
// NOT catch a dropped `await` here (Task 0's finding), so every call
// site below is `await`ed deliberately and the async-closure mutation
// harness (RS23-001) is the only net.
- const onTrip = async (table: 'days' | 'places', id: number): Promise<boolean> => {
+ // An id `toRowId` refuses resolves to nothing, as in referencesOutsideTrip.
+ const onTrip = async (table: 'days' | 'places', value: unknown): Promise<boolean> => {
+ const id = toRowId(value);
+ if (id === null) return false;
const tripIdNum = this.rowIdNum(tripId);
return table === 'days' ? this.daysRepo.existsInTrip(id, tripIdNum) : this.placesRepo.existsInTrip(id, tripIdNum);
};
@@ -480,7 +467,8 @@ export class ReservationsService {
if (data.assignment_id) {
// An assignment belongs to a trip through its day, the same join the
// other guard walks. RS24.
- const row = await this.dayAssignmentsRepo.findInTrip(data.assignment_id, tripId);
+ const assignmentId = toRowId(data.assignment_id);
+ const row = assignmentId === null ? undefined : await this.dayAssignmentsRepo.findInTrip(assignmentId, tripId);
if (!row) offenders.push('assignment_id');
}
@@ -489,8 +477,14 @@ export class ReservationsService {
// on a write that currently succeeds is not what this guard is for.
if (data.create_accommodation && data.type === 'hotel') {
const acc = data.create_accommodation;
+ const ref = (field: 'place_id' | 'start_day_id' | 'end_day_id'): number | undefined => {
+ if (!acc[field]) return undefined;
+ const id = toRowId(acc[field]);
+ if (id === null) offenders.push(`create_accommodation.${field}`);
+ return id ?? undefined;
+ };
const errors = await this.accommodations.validateAccommodationRefs(
- tripId, acc.place_id || undefined, acc.start_day_id || undefined, acc.end_day_id || undefined,
+ tripId, ref('place_id'), ref('start_day_id'), ref('end_day_id'),
);
for (const { field } of errors) offenders.push(`create_accommodation.${field}`);
}
@@ -618,7 +612,10 @@ export class ReservationsService {
// surface has its own field set and its own COALESCE semantics, and folding
// the two together would bend one of them out of shape. The day stop is the
// part that must not exist twice, so it comes from AccommodationsService.
- let resolvedAccommodationId: number | null = accommodation_id || null;
+ // The payload's accommodation_id is untrusted input and goes through
+ // `toRowId` the way update() reads it (L2): a `'0x1'` or an `'abc'` used to
+ // be stored as `'0x1.0'`, which Postgres cannot cast back for the join.
+ let resolvedAccommodationId: number | null = toRowId(accommodation_id) || null;
if (type === 'hotel' && !resolvedAccommodationId && create_accommodation) {
const { place_id: accPlaceId, start_day_id, end_day_id, check_in, check_out, confirmation: accConf } = create_accommodation;
if (start_day_id && end_day_id) {
diff --git a/server/tests/integration/reservations.test.ts b/server/tests/integration/reservations.test.ts
index 355fff945..50968376d 100644
--- a/server/tests/integration/reservations.test.ts
+++ b/server/tests/integration/reservations.test.ts
@@ -316,6 +316,101 @@ describe('Update reservation', () => {
const row = (await findRow(orm, Reservations, { id: resv.id }))!;
expect(row.accommodation_id).toBeNull();
});
+
+ it('L2 — POST with a hex-spelled accommodation_id stores NULL, the same as PUT', async () => {
+ const { user } = await makeUser(orm);
+ const trip = await makeTrip(orm, user.id);
+ const day = await makeDay(orm, trip.id);
+ const place = await makePlace(orm, trip.id, { name: 'Hotel' });
+ const { accommodation: accom } = (
+ await request(app)
+ .post(`/api/trips/${trip.id}/accommodations`)
+ .set('Cookie', authCookie(user.id))
+ .send({ place_id: place.id, start_day_id: day.id, end_day_id: day.id })
+ ).body as { accommodation: { id: number } };
+
+ const res = await request(app)
+ .post(`/api/trips/${trip.id}/reservations`)
+ .set('Cookie', authCookie(user.id))
+ .send({ title: 'Flight', type: 'flight', accommodation_id: '0x' + accom.id.toString(16) });
+ expect(res.status).toBe(201);
+
+ const row = await findRow(orm, Reservations, { id: res.body.reservation.id as number });
+ expect(row).toMatchObject({ accommodation_id: null });
+ });
+});
+
+// ─────────────────────────────────────────────────────────────────────────────
+// The body is not schema-checked, so a referenced id can arrive as any string.
+// Only the canonical shapes toRowId accepts reach SQL: SQLite matches nothing
+// for '0x1' or 'abc' against an integer column, while Postgres refuses the
+// cast (14 and 15) or reads hex as a number (16 and later). Every engine has
+// to answer the same 400 instead of a 500 on one and a write on another.
+// ─────────────────────────────────────────────────────────────────────────────
+
+describe('a referenced id the row-id rule refuses is an unknown reference on every engine', () => {
+ const shapes = [
+ ['hex', (id: number) => '0x' + id.toString(16)],
+ ['exponent', (id: number) => `${id}e0`],
+ ['word', () => 'abc'],
+ ] as const;
+ const fields = [
+ ['day_id', 'day_id'],
+ ['end_day_id', 'end_day_id'],
+ ['place_id', 'place_id'],
+ ['create_accommodation.place_id', 'place_id'],
+ ['create_accommodation.start_day_id', 'start_day_id'],
+ ] as const;
+
+ for (const [field, key] of fields) {
+ for (const [shapeName, spell] of shapes) {
+ it(`${field} spelled as ${shapeName}: PUT and POST answer 400 "Unknown reference: ${field}"`, async () => {
+ const { user } = await makeUser(orm);
+ const trip = await makeTrip(orm, user.id);
+ const day = await makeDay(orm, trip.id);
+ const place = await makePlace(orm, trip.id, { name: 'Hotel' });
+ const resv = await makeReservation(orm, trip.id, { title: 'Stay', type: 'hotel' });
+ const value = spell(key === 'place_id' ? place.id : day.id);
+ const body = field.startsWith('create_accommodation.')
+ ? {
+ type: 'hotel',
+ create_accommodation: { place_id: place.id, start_day_id: day.id, end_day_id: day.id, [key]: value },
+ }
+ : { [key]: value };
+
+ const put = await request(app)
+ .put(`/api/trips/${trip.id}/reservations/${resv.id}`)
+ .set('Cookie', authCookie(user.id))
+ .send(body);
+ expect(put.status).toBe(400);
+ expect(put.body.error).toBe(`Unknown reference: ${field}`);
+
+ const post = await request(app)
+ .post(`/api/trips/${trip.id}/reservations`)
+ .set('Cookie', authCookie(user.id))
+ .send({ title: 'Stay', type: 'hotel', ...body });
+ expect(post.status).toBe(400);
+ expect(post.body.error).toBe(`Unknown reference: ${field}`);
+ expect(await findRows(orm, Reservations, { trip: trip.id })).toHaveLength(1);
+ });
+ }
+ }
+
+ it('assignment_id spelled as hex: PUT answers 400 "Unknown reference: assignment_id"', async () => {
+ const { user } = await makeUser(orm);
+ const trip = await makeTrip(orm, user.id);
+ const day = await makeDay(orm, trip.id);
+ const place = await makePlace(orm, trip.id, { name: 'Museum' });
+ const assignment = await makeDayAssignment(orm, day.id, place.id);
+ const resv = await makeReservation(orm, trip.id, { title: 'Ticket', type: 'event' });
+
+ const res = await request(app)
+ .put(`/api/trips/${trip.id}/reservations/${resv.id}`)
+ .set('Cookie', authCookie(user.id))
+ .send({ assignment_id: '0x' + assignment.id.toString(16) });
+ expect(res.status).toBe(400);
+ expect(res.body.error).toBe('Unknown reference: assignment_id');
+ });
});
// ─────────────────────────────────────────────────────────────────────────────