mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-29 16:10:07 +00:00
fix(server): plan 3c close-out — non-finite ids bound as NULL, trip id parsed once at every places/days/ws gate
Platform: NulSafeSqlitePlatform now renders a bound NaN as NULL and +/-Infinity as 9e999/-9e999, matching better-sqlite3's own legacy binding (rule 22 extension) — the program-wide fail-safe for any caller that still passes an unguarded Number(untrusted) into a converted statement. PlacesService.verifyTripAccess and RealtimeGateway.handleJoin stop doing that: verifyTripAccess parses once with toRowId and threads the parsed id through create/import/bulk/rating/export.gpx (deleting the seven toRowId(tripId) ?? -1 sites), and handleJoin gets a Number.isFinite guard. DaysService gets the same treatment across list/create/getDay/reorder/ insert/resyncAccommodationDays, closing the gap where a hex-spelled trip id could renumber a real trip's days while the raw-bind inverted-accommodation guard silently matched nothing. DatabaseService.getTripTitle is deleted; PlacesService injects TripsRepository directly and calls getTitle itself. Template/cheap-item cleanup: DayAssignmentsRepository.listForTimeSort uses $castTo instead of an unknown bridge; the duplicated TagRow interface in Places.repository.ts is now imported from Tags.repository.ts; AssignmentWithPlaceRow extends the guarded DayAssignmentRow instead of restating its columns; PlaceShadowPicksRepository.totals drops its unreachable ??-fallback branch; Places.repository.ts's updatePlace types the NOT NULL name column as string; trip-members.service.ts's transferOwnership threads one parsed trip id through all three writes and corrects two stale "raw-bind seam" docstrings that were actually Number() seams; a dead canAccessTrip mock is removed from reservations.e2e.test.ts. Tests: the 23 new no-explicit-any warnings in TRIP-SVC-069 are typed (lint back to 2416); HTTP and WS regression coverage for the non-finite and non-canonical id shapes across places/days routes, mutation-proved; TRIP-JOIN-005 asserts the exact concurrent-join settlement instead of >= 1; a new tests/unit/db/transaction-yield.test.ts pins rule 24's measured transaction-yield/dirty-read/nested-BEGIN behaviour.
This commit is contained in:
@@ -1,7 +1,12 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
import { NulSafeSqlitePlatform } from '../../../src/db/nul-safe-sqlite-platform';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { createTrip, createUser } from '../../helpers/factories';
|
||||
import { Trips } from '../../../src/db/entities/Trips.entity';
|
||||
|
||||
/**
|
||||
* Plan 3c Task 4 review M1 / program rule 22: MikroORM 7 inlines every bound
|
||||
@@ -85,4 +90,105 @@ describe('NulSafeSqlitePlatform', () => {
|
||||
const row = db.prepare(selectSql).get() as { name: string } | undefined;
|
||||
expect(row?.name).toBe(value);
|
||||
});
|
||||
|
||||
/**
|
||||
* Program rule 22's extension (Plan 3c Task 9 close-out, review A H1): a
|
||||
* non-finite `number` used to render as an unquoted bareword (`NaN`/
|
||||
* `Infinity`/`-Infinity`), which SQLite parses as a column reference and
|
||||
* throws `no such column: …` — a 500 where the raw better-sqlite3 bind
|
||||
* (`NaN` -> `NULL`, `±Infinity` -> the `REAL` value, verified empirically
|
||||
* against the installed driver above the class docstring) never had the
|
||||
* problem. These pin the rendered SQL literal AND the real round-trip.
|
||||
*/
|
||||
describe('non-finite numbers (rule 22 extension)', () => {
|
||||
it('NaN renders as the literal `NULL`, not the bareword `NaN`', () => {
|
||||
expect(platform.escape(NaN)).toBe('NULL');
|
||||
});
|
||||
|
||||
it('+Infinity renders as the literal `9e999`, which SQLite parses back to the REAL value Infinity', () => {
|
||||
expect(platform.escape(Infinity)).toBe('9e999');
|
||||
const row = db.prepare('select typeof(9e999) as t, 9e999 as v').get() as { t: string; v: number };
|
||||
expect(row).toEqual({ t: 'real', v: Infinity });
|
||||
});
|
||||
|
||||
it('-Infinity renders as the literal `-9e999`, which SQLite parses back to the REAL value -Infinity', () => {
|
||||
expect(platform.escape(-Infinity)).toBe('-9e999');
|
||||
const row = db.prepare('select typeof(-9e999) as t, -9e999 as v').get() as { t: string; v: number };
|
||||
expect(row).toEqual({ t: 'real', v: -Infinity });
|
||||
});
|
||||
|
||||
it('a finite number is untouched (only the three non-finite values take the new branch)', () => {
|
||||
expect(platform.escape(0)).toBe('0');
|
||||
expect(platform.escape(-1)).toBe('-1');
|
||||
expect(platform.escape(3.14)).toBe('3.14');
|
||||
});
|
||||
|
||||
it('formatQuery renders `NULL` for a bound NaN, matching better-sqlite3\'s own binding of NaN as NULL', () => {
|
||||
db.exec('CREATE TABLE nanprobe (n REAL)');
|
||||
db.exec(platform.formatQuery('insert into nanprobe (n) values (?)', [NaN]));
|
||||
const viaLiteral = db.prepare('select n from nanprobe').get() as { n: unknown };
|
||||
const viaBind = db.prepare('select ? as n').get(NaN) as { n: unknown };
|
||||
expect(viaLiteral.n).toBeNull();
|
||||
expect(viaBind.n).toBeNull();
|
||||
});
|
||||
|
||||
it('formatQuery renders `9e999`/`-9e999` for bound ±Infinity, matching better-sqlite3\'s own REAL binding', () => {
|
||||
db.exec('CREATE TABLE infprobe (n REAL)');
|
||||
db.exec(platform.formatQuery('insert into infprobe (n) values (?), (?)', [Infinity, -Infinity]));
|
||||
const rows = db.prepare('select n from infprobe order by rowid').all() as { n: number }[];
|
||||
expect(rows.map(r => r.n)).toEqual([Infinity, -Infinity]);
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* The mechanism above through the REAL ORM call path (`findOne`,
|
||||
* `nativeUpdate`, a QB `where`, and an `$in` list), against a real trip
|
||||
* row — the shape `PlacesService.verifyTripAccess`/`RealtimeGateway
|
||||
* .handleJoin` reach when a non-finite id slips past their own guard.
|
||||
* Before this override, every one of these threw `SqliteError: no such
|
||||
* column: NaN`; after, each answers a clean miss.
|
||||
*/
|
||||
describe('non-finite numbers through the real ORM call path', () => {
|
||||
const orm = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(orm);
|
||||
});
|
||||
beforeEach(() => { resetTestDb(orm); t.clear(); });
|
||||
afterAll(async () => { await t.close(); orm.close(); });
|
||||
|
||||
it('em.findOne(Trips, { id: NaN }) misses cleanly, never throws', async () => {
|
||||
const { user } = createUser(orm);
|
||||
createTrip(orm, user.id);
|
||||
await expect(t.em.findOne(Trips, { id: NaN })).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('em.nativeUpdate(Trips, { id: NaN }, …) updates 0 rows, never throws', async () => {
|
||||
const { user } = createUser(orm);
|
||||
const trip = createTrip(orm, user.id);
|
||||
const affected = await t.em.nativeUpdate(Trips, { id: NaN }, { title: 'renamed' });
|
||||
expect(affected).toBe(0);
|
||||
const untouched = orm.prepare('SELECT title FROM trips WHERE id = ?').get(trip.id) as { title: string };
|
||||
expect(untouched.title).not.toBe('renamed');
|
||||
});
|
||||
|
||||
it('a QB `where` on a non-finite id misses cleanly, never throws (the exact `findAccessible` shape)', async () => {
|
||||
const { user } = createUser(orm);
|
||||
createTrip(orm, user.id);
|
||||
const row = await t.em.getRepository(Trips)
|
||||
.qb('t')
|
||||
.select(['t.id'])
|
||||
.where('t.id = ?', [NaN])
|
||||
.execute<{ id: number } | undefined>('get', false);
|
||||
expect(row).toBeUndefined();
|
||||
});
|
||||
|
||||
it('an `$in` list containing NaN/Infinity still matches the finite members, never throws', async () => {
|
||||
const { user } = createUser(orm);
|
||||
const trip = createTrip(orm, user.id);
|
||||
const rows = await t.em.find(Trips, { id: { $in: [trip.id, NaN, Infinity, -Infinity] } });
|
||||
expect(rows.map(r => r.id)).toEqual([trip.id]);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -813,17 +813,30 @@ describe('UsersRepository — TripMembersService (Plan 3c Task 6)', () => {
|
||||
});
|
||||
|
||||
describe('findInvitableByEmailOrUsername (TM4)', () => {
|
||||
// Task 9 fix wave (B-L7): the legacy statement TM4's docstring quotes,
|
||||
// run raw on the same fixture — `toEqual(legacy)` on the FULL key set,
|
||||
// so a renamed or dropped column would fail this, not just the
|
||||
// literal-object assertion below (rule 19; #1362 is security-relevant,
|
||||
// so this is one of the L7 reads the fix wave covers).
|
||||
const legacyInvitable = (identifier: string) =>
|
||||
testDb.prepare(
|
||||
'SELECT id, username, email, avatar FROM users WHERE (email = ? OR username = ?) AND COALESCE(is_guest, 0) = 0',
|
||||
).get(identifier, identifier) ?? null;
|
||||
|
||||
it('USERSREPO-063: matches on email OR username, case-SENSITIVE (unlike findByEmailCI/findIdByEmailCI above)', async () => {
|
||||
const { user: byEmail } = createUser(testDb, { email: 'invitee@example.test', username: 'invitee-handle' });
|
||||
expect(await users.findInvitableByEmailOrUsername('invitee@example.test')).toEqual({
|
||||
id: byEmail.id, username: 'invitee-handle', email: 'invitee@example.test', avatar: null,
|
||||
});
|
||||
expect(await users.findInvitableByEmailOrUsername('invitee@example.test')).toEqual(legacyInvitable('invitee@example.test'));
|
||||
expect(await users.findInvitableByEmailOrUsername('invitee-handle')).toEqual({
|
||||
id: byEmail.id, username: 'invitee-handle', email: 'invitee@example.test', avatar: null,
|
||||
});
|
||||
expect(await users.findInvitableByEmailOrUsername('invitee-handle')).toEqual(legacyInvitable('invitee-handle'));
|
||||
// Case-sensitive: an uppercased email must NOT match (program rule 18
|
||||
// only applies where the legacy statement itself folds case — TM4's does not).
|
||||
expect(await users.findInvitableByEmailOrUsername('INVITEE@EXAMPLE.TEST')).toBeNull();
|
||||
expect(legacyInvitable('INVITEE@EXAMPLE.TEST')).toBeNull();
|
||||
});
|
||||
|
||||
it('USERSREPO-064: excludes guests — a trip-scoped guest can never be re-invited through the box', async () => {
|
||||
@@ -837,11 +850,17 @@ describe('UsersRepository — TripMembersService (Plan 3c Task 6)', () => {
|
||||
expect(await users.findInvitableByEmailOrUsername('nobody@example.test')).toBeNull();
|
||||
});
|
||||
|
||||
// Task 6 review, L3: `findInvitableByEmailOrUsername` is `findOne`-based
|
||||
// (unlike the qb-based projections above), so rule 21's D-shape test
|
||||
// applies for real — this is the guest-exclusion guard (#1362), so
|
||||
// staleness here would re-open the bug the guard exists to close.
|
||||
it('USERSREPO-072 (D-shape): an is_guest flip written after an unrelated identity-map read is visible in the FIRST wider projection', async () => {
|
||||
// Task 9 fix wave (B-M3): relabelled — this comment previously claimed
|
||||
// rule 20's PK-only D-shape guarantee "applies for real", but
|
||||
// `findInvitableByEmailOrUsername` filters `findOne` on `{$or:
|
||||
// [{email},{username}], is_guest}`, not the primary key (rule 20 draws
|
||||
// that PK-only line precisely because a non-PK filter always re-runs
|
||||
// the WHERE clause against the live table, so it can never serve a
|
||||
// stale identity-map snapshot the way a PK lookup can). What this DOES
|
||||
// prove, honestly: a row that flips `is_guest` after an unrelated wider
|
||||
// identity-map read is fresh here — the guest-exclusion guard (#1362)
|
||||
// sees the current value, not a cached one.
|
||||
it('USERSREPO-072 (fresh after a raw UPDATE, not D-shape): an is_guest flip written after an unrelated identity-map read is visible in the FIRST wider projection', async () => {
|
||||
const { user } = createUser(testDb, { email: 'flip@example.test', username: 'flip-handle' });
|
||||
await t.repo(Users).find({}, { disableIdentityMap: false }); // populate the identity map with an unrelated read
|
||||
testDb.prepare('UPDATE users SET is_guest = 1 WHERE id = ?').run(user.id);
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
/**
|
||||
* Program rule 24 (`docs/superpowers/plans/2026-09-21-orm-migration-program.md`),
|
||||
* added by Plan 3c Task 9's whole-plan review (reviewer A, ruling 5): "transactional
|
||||
* bodies await DB work only." The server holds ONE better-sqlite3 connection, shared
|
||||
* by MikroORM's Kysely-backed driver (`orm-driver.ts`'s `BoundSqliteDriver`) and by
|
||||
* `DatabaseService`'s raw `db.prepare(...)` calls. This file pins the two concrete
|
||||
* behaviours that measurement (fork A2, real `UnitOfWork` + `withRequestContext` +
|
||||
* the bound driver, no mocks) found when a `uow.transactional` body is left open
|
||||
* across a real `await` (which no converted service does today — a static scan of
|
||||
* all 131 `.transactional(` call sites found none awaiting non-DB I/O; this file's
|
||||
* own transactional bodies hold one open ONLY to observe the window, which is
|
||||
* exactly the shape a future violation of rule 24 would take):
|
||||
*
|
||||
* A. Another request's ORM/Kysely statement QUEUES behind the open transaction —
|
||||
* Kysely's own `ConnectionMutex` for SQLite serialises every statement onto
|
||||
* the one connection, so there is no interleaving: the queued statement's
|
||||
* result only becomes observable after the holder's transaction settles.
|
||||
* B. A raw `DatabaseService` statement issued while that same transaction is
|
||||
* open does NOT queue — it shares the connection directly, with no mutex of
|
||||
* its own, so it runs INSIDE the open transaction: a "dirty read" of the
|
||||
* transaction's uncommitted write, which then reverts to its pre-transaction
|
||||
* value the moment the holder rolls back (the hazard rule 24 exists to keep
|
||||
* out of production code, by keeping every transactional body DB-only).
|
||||
*
|
||||
* Both requests run through `withRequestContext` (MikroORM's `RequestContext`,
|
||||
* AsyncLocalStorage-based), the same per-request fork every real HTTP/MCP/WS/cron
|
||||
* entrypoint uses — not two calls sharing one ambient EntityManager, which would
|
||||
* make MikroORM treat the second as a SAVEPOINT of the first (`UnitOfWork`'s own
|
||||
* docstring: NESTED propagation) rather than the independent, connection-mutex-
|
||||
* queued transaction two unrelated concurrent requests actually are.
|
||||
*/
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
|
||||
import { createUser, createTrip } from '../../helpers/factories';
|
||||
import { Trips } from '../../../src/db/entities/Trips.entity';
|
||||
import type { TripsRepository } from '../../../src/db/repositories/Trips.repository';
|
||||
import { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
import { withRequestContext } from '../../../src/nest/database/request-context';
|
||||
import { DatabaseService } from '../../../src/nest/database/database.service';
|
||||
|
||||
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let trips: TripsRepository;
|
||||
let uow: UnitOfWork;
|
||||
let dbs: DatabaseService;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
trips = t.repo(Trips);
|
||||
uow = new UnitOfWork(t.em);
|
||||
dbs = new DatabaseService(testDb, t.em);
|
||||
});
|
||||
beforeEach(() => { resetTestDb(testDb); t.clear(); });
|
||||
afterAll(async () => { await t.close(); testDb.close(); });
|
||||
|
||||
describe('transaction yield (rule 24)', () => {
|
||||
it('A — another request\'s ORM statement queues behind an open transaction: no interleaving, and its result only becomes observable after the holder commits', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id, { end_date: '2026-01-01' });
|
||||
|
||||
const order: string[] = [];
|
||||
const HOLD_MS = 40;
|
||||
|
||||
// Request 1: opens a transaction, holds it open across a real `await` (the
|
||||
// window this test needs to observe — never how production code shapes a
|
||||
// transactional body; see the file docstring), then writes and commits.
|
||||
const holder = withRequestContext(t.orm, async () => {
|
||||
return uow.transactional(async () => {
|
||||
order.push('holder:open');
|
||||
await sleep(HOLD_MS);
|
||||
await trips.setEndDate(trip.id, '2099-12-31');
|
||||
order.push('holder:commit');
|
||||
});
|
||||
});
|
||||
|
||||
// Give the holder a tick to actually open its transaction before the
|
||||
// second "request" starts, so the queued statement is provably issued
|
||||
// while the first is open, not racing to start first itself.
|
||||
await sleep(5);
|
||||
|
||||
// Request 2: an unrelated concurrent request's plain ORM read (no
|
||||
// transaction of its own) for the SAME row, through its own forked
|
||||
// context — the shape `TripAccessGuard`/`findAccessible` reads take.
|
||||
const queued = withRequestContext(t.orm, async () => {
|
||||
order.push('queued:issue');
|
||||
const row = await trips.getTitle(trip.id);
|
||||
order.push('queued:resolve');
|
||||
return row;
|
||||
});
|
||||
|
||||
await Promise.all([holder, queued]);
|
||||
|
||||
// The queued read was ISSUED while the holder was still open (between
|
||||
// "holder:open" and "holder:commit")…
|
||||
expect(order.indexOf('queued:issue')).toBeGreaterThan(order.indexOf('holder:open'));
|
||||
expect(order.indexOf('queued:issue')).toBeLessThan(order.indexOf('holder:commit'));
|
||||
// …but it only RESOLVED after the holder committed — the connection
|
||||
// mutex queued it rather than interleaving it inside the open transaction.
|
||||
expect(order.indexOf('queued:resolve')).toBeGreaterThan(order.indexOf('holder:commit'));
|
||||
});
|
||||
|
||||
it('B — a raw DatabaseService statement issued while a transaction is open runs INSIDE it (a dirty read of the uncommitted write), then reverts when the holder rolls back', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const trip = createTrip(testDb, user.id, { end_date: '2026-01-01' });
|
||||
|
||||
let dirtyRead: string | null | undefined;
|
||||
const HOLD_MS = 40;
|
||||
|
||||
const holder = withRequestContext(t.orm, async () => {
|
||||
await expect(
|
||||
uow.transactional(async () => {
|
||||
await trips.setEndDate(trip.id, '2099-12-31');
|
||||
// The write is now inside the open, uncommitted transaction. A raw
|
||||
// statement issued from a DIFFERENT concurrent "request" — no
|
||||
// request-context fork, no `uow.transactional` of its own — shares
|
||||
// the one better-sqlite3 connection directly and is NOT behind
|
||||
// Kysely's mutex, so it runs synchronously, right now, still
|
||||
// inside this open transaction.
|
||||
const row = dbs.get<{ end_date: string | null }>('SELECT end_date FROM trips WHERE id = ?', trip.id);
|
||||
dirtyRead = row?.end_date;
|
||||
await sleep(HOLD_MS);
|
||||
// Force a rollback: the write above must not survive.
|
||||
throw new Error('forced rollback (rule 24 probe)');
|
||||
}),
|
||||
).rejects.toThrow('forced rollback');
|
||||
});
|
||||
|
||||
await holder;
|
||||
|
||||
// The raw read saw the uncommitted value — a dirty read, proving the raw
|
||||
// path is NOT queued behind the transaction the way an ORM/Kysely
|
||||
// statement is (probe A above).
|
||||
expect(dirtyRead).toBe('2099-12-31');
|
||||
// After the holder rolled back, the row reverts — the dirty read never
|
||||
// should have been trusted, which is exactly why rule 24 keeps every
|
||||
// transactional body DB-only: a raw statement issued mid-transaction by
|
||||
// ANOTHER request would otherwise report success on a write that this
|
||||
// rollback just erased.
|
||||
const after = testDb.prepare('SELECT end_date FROM trips WHERE id = ?').get(trip.id) as { end_date: string | null };
|
||||
expect(after.end_date).toBe('2026-01-01');
|
||||
});
|
||||
|
||||
it('I — a second, unrelated transaction opened while the first is still open does not error (no nested-BEGIN exception); it queues and commits its own write once the first settles', async () => {
|
||||
const { user } = createUser(testDb);
|
||||
const tripA = createTrip(testDb, user.id, { end_date: '2026-01-01' });
|
||||
const tripB = createTrip(testDb, user.id, { end_date: '2026-01-01' });
|
||||
const HOLD_MS = 40;
|
||||
|
||||
const first = withRequestContext(t.orm, () =>
|
||||
uow.transactional(async () => {
|
||||
await sleep(HOLD_MS);
|
||||
await trips.setEndDate(tripA.id, '2099-01-01');
|
||||
}),
|
||||
);
|
||||
// Give the first a moment to actually open before the second starts, so
|
||||
// the second's own BEGIN is provably attempted while one is already open.
|
||||
await sleep(5);
|
||||
const second = withRequestContext(t.orm, () =>
|
||||
uow.transactional(async () => {
|
||||
await trips.setEndDate(tripB.id, '2099-02-01');
|
||||
}),
|
||||
);
|
||||
|
||||
await expect(Promise.all([first, second])).resolves.toBeDefined();
|
||||
|
||||
const rowA = testDb.prepare('SELECT end_date FROM trips WHERE id = ?').get(tripA.id) as { end_date: string | null };
|
||||
const rowB = testDb.prepare('SELECT end_date FROM trips WHERE id = ?').get(tripB.id) as { end_date: string | null };
|
||||
expect(rowA.end_date).toBe('2099-01-01');
|
||||
expect(rowB.end_date).toBe('2099-02-01');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user