diff --git a/server/src/db/repositories/PackingBags.repository.ts b/server/src/db/repositories/PackingBags.repository.ts index 4982d25f2..61f897fb5 100644 --- a/server/src/db/repositories/PackingBags.repository.ts +++ b/server/src/db/repositories/PackingBags.repository.ts @@ -143,7 +143,12 @@ export class PackingBagsRepository extends TrekRepository { * `name`/`color` keep the legacy `COALESCE(?, col)` truthy-wins * semantics (`present = !!value`); `weight_limit_grams`/`user_id` are * true presence sentinels, already resolved by the SERVICE - * (`assignUser`'s roster check, the bodyKeys presence protocol). + * (`assignUser`'s roster check, the bodyKeys presence protocol). An + * empty write (`{}`, or every field falsy/absent) short-circuits before + * the `UPDATE` — `presenceSet` returns `{}` and Kysely's `set({})` emits + * `UPDATE packing_bags SET WHERE id = ?`, a SQLite syntax error (base + * returned 200; task-8-review.md H2) — the same guard `BudgetItems` + * (`:222`) and `TodoItems` (`:125`) already carry. */ async update(id: number | string, write: { name?: readonly [present: boolean, value: string | null]; @@ -152,6 +157,7 @@ export class PackingBagsRepository extends TrekRepository { user_id?: readonly [present: boolean, value: number | null]; }): Promise { const data = presenceSet<{ name: string; color: string; weight_limit_grams: number | null; user_id: number | null }>(write); + if (Object.keys(data).length === 0) return; await this.db().updateTable('packing_bags').set(data).where('id', '=', id as number).execute(); } diff --git a/server/src/db/repositories/PackingCategoryAssignees.repository.ts b/server/src/db/repositories/PackingCategoryAssignees.repository.ts index 515b186b9..0d83c652e 100644 --- a/server/src/db/repositories/PackingCategoryAssignees.repository.ts +++ b/server/src/db/repositories/PackingCategoryAssignees.repository.ts @@ -14,14 +14,30 @@ interface PackingCategoryAssigneesKyselyDB { users: { id: number; username: string; display_name: string | null; avatar: string | null }; } +interface PackingCategoryAssigneesInsertKyselyDB { + packing_category_assignees: { trip_id: number | string; category_name: string; user_id: number }; +} + /** * `packing_category_assignees` — who is "on the hook" for a packing * category. A surrogate `id` PK plus a `(trip, category_name, user)` * unique index (§16), unlike `packing_item_contributors`'s genuine - * composite PK — `upsertMany` with `onConflictAction: 'ignore'` on that - * unique index is the `AssignmentParticipantsRepository.insertIgnore` - * shape, not the composite-key `em.upsert` form - * `PackingItemContributorsRepository` needs. + * composite PK. + * + * `insertIgnore` used `upsertMany` with `onConflictAction: 'ignore'` + * originally (the `AssignmentParticipantsRepository.insertIgnore` shape). + * That form hydrates each row back through MikroORM's identity map after + * the write, matching it against the condition it was given — and REST + * hands this repository the raw route string for `trip_id` (the service + * never parses it, rule 21's documented carry), so the post-write re-match + * looked for `{"trip":"1", ...}` (a string) against rows the DB has as + * `trip_id = 1` (an integer) and threw `Cannot find matching entity for + * condition`, 500ing every non-empty roster (task-8-review.md H1). Kysely's + * `INSERT OR IGNORE` has no such re-match step — it is the + * `TodoCategoryAssigneesRepository.insertIgnore` / + * `BudgetItemMembersRepository.insertIgnore` shape, and SQLite's own + * column-affinity conversion (rule 15) accepts the string `trip_id` + * exactly as the legacy raw-SQL statement did. */ export class PackingCategoryAssigneesRepository extends TrekRepository { /** @@ -47,21 +63,22 @@ export class PackingCategoryAssigneesRepository extends TrekRepository { if (user_ids.length === 0) return; - await this.upsertMany( - user_ids.map((user_id) => ({ trip: trip_id as number, category_name, user: user_id })), - { onConflictFields: ['trip', 'category_name', 'user'], onConflictAction: 'ignore' }, - ); + for (const user_id of user_ids) { + await this.kysely() + .insertInto('packing_category_assignees') + .values({ trip_id, category_name, user_id }) + .onConflict((oc) => oc.doNothing()) + .execute(); + } } /** PK61 (`updateCategoryAssignees`'s post-write re-select) — `SELECT pca.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar FROM packing_category_assignees pca JOIN users u ON pca.user_id = u.id WHERE pca.trip_id = ? AND pca.category_name = ?`. */ diff --git a/server/src/nest/accommodations/accommodations-domain.module.ts b/server/src/nest/accommodations/accommodations-domain.module.ts index becc324db..5e85b6cdf 100644 --- a/server/src/nest/accommodations/accommodations-domain.module.ts +++ b/server/src/nest/accommodations/accommodations-domain.module.ts @@ -1,3 +1,4 @@ +import { BudgetItems } from '../../db/entities/BudgetItems.entity'; import { Module } from '@nestjs/common'; import { MikroOrmModule } from '@mikro-orm/nestjs'; import { AccommodationsService } from './accommodations.service'; @@ -38,7 +39,7 @@ import { Reservations } from '../../db/entities/Reservations.entity'; @Module({ imports: [ PermissionsModule, RealtimeModule, AssignmentsDomainModule, - MikroOrmModule.forFeature([DayAccommodations, DayAssignments, Places, Days, RoadtripVias, Reservations]), + MikroOrmModule.forFeature([DayAccommodations, DayAssignments, Places, Days, RoadtripVias, Reservations, BudgetItems]), ], providers: [AccommodationsService], exports: [AccommodationsService], diff --git a/server/src/nest/auth/auth.module.ts b/server/src/nest/auth/auth.module.ts index a69481044..bb57d3819 100644 --- a/server/src/nest/auth/auth.module.ts +++ b/server/src/nest/auth/auth.module.ts @@ -1,3 +1,4 @@ +import { BudgetItems } from '../../db/entities/BudgetItems.entity'; import { RateLimitModule } from '../common/rate-limit.module'; import { Module } from '@nestjs/common'; import { MikroOrmModule } from '@mikro-orm/nestjs'; @@ -83,7 +84,7 @@ import { AllowedFileTypesModule } from '../files/allowed-file-types.module'; // resolves from THIS module's own `forFeature` graph regardless of who // else also registers it (`tokens.module.ts`'s own docstring explains // why). PasswordResetTokens: AuthService's own table (Plan 3b Task 5). - MikroOrmModule.forFeature([AppSettings, Users, WebauthnCredentials, WebauthnChallenges, InviteTokens, McpTokens, OauthTokens, PasswordResetTokens])], + MikroOrmModule.forFeature([AppSettings, Users, WebauthnCredentials, WebauthnChallenges, InviteTokens, McpTokens, OauthTokens, PasswordResetTokens, BudgetItems])], controllers: [AuthPublicController, AuthController, PasskeyController], providers: [AuthService, UserProfileService, RegistrationInvitesService, PasskeyService, UserCleanupService, WebauthnConfigService, AuthMcp], exports: [AuthService, RegistrationInvitesService, PasskeyService, UserCleanupService], diff --git a/server/src/nest/budget/budget.module.ts b/server/src/nest/budget/budget.module.ts index 4aef17217..e45ec65e0 100644 --- a/server/src/nest/budget/budget.module.ts +++ b/server/src/nest/budget/budget.module.ts @@ -1,3 +1,12 @@ +import { BudgetItems } from '../../db/entities/BudgetItems.entity'; +import { MikroOrmModule } from '@mikro-orm/nestjs'; +import { BudgetItemMembers } from '../../db/entities/BudgetItemMembers.entity'; +import { BudgetItemPayers } from '../../db/entities/BudgetItemPayers.entity'; +import { BudgetSettlements } from '../../db/entities/BudgetSettlements.entity'; +import { BudgetCategoryOrder } from '../../db/entities/BudgetCategoryOrder.entity'; +import { Reservations } from '../../db/entities/Reservations.entity'; +import { Places } from '../../db/entities/Places.entity'; +import { Trips } from '../../db/entities/Trips.entity'; import { Module } from '@nestjs/common'; import { BudgetController } from './budget.controller'; import { BudgetService } from './budget.service'; @@ -21,7 +30,7 @@ import { McpSharedModule } from '../mcp-shared/mcp-shared.module'; * AppConfigModule is @Global in the app graph; the explicit import keeps the * partial e2e TestingModules resolving RuntimeEnvService. */ @Module({ - imports: [McpSharedModule, PermissionsModule, AppConfigModule, RealtimeModule, PluginGuardsModule, AddonsModule, TripMembershipModule], + imports: [McpSharedModule, PermissionsModule, AppConfigModule, RealtimeModule, PluginGuardsModule, AddonsModule, TripMembershipModule, MikroOrmModule.forFeature([BudgetItems, BudgetItemMembers, BudgetItemPayers, BudgetSettlements, BudgetCategoryOrder, Reservations, Places, Trips])], controllers: [BudgetController], providers: [BudgetService, ExchangeRatesService, BudgetMcp, ExchangeRatesRpc, CostsRpc], // For in-container consumers (CostsRpc, TripsService, diff --git a/server/src/nest/files/files.service.ts b/server/src/nest/files/files.service.ts index 0a376110b..d697c534d 100644 --- a/server/src/nest/files/files.service.ts +++ b/server/src/nest/files/files.service.ts @@ -433,10 +433,12 @@ export class FilesService { console.error(`[files] unlink failed for ${file.filename}, keeping DB row:`, e); } })); + // A single statement is already atomic — no `uow.transactional` wrapper + // needed here (task-8-review.md L1/U1: the wrapper this method used to + // carry was vacuous, and FILE-SVC-062's "rollback" claim never actually + // exercised it — removing it keeps every test green). if (successfullyUnlinked.length > 0) { - await this.uow.transactional(async () => { - await this.tripFilesRepo.deleteMany(successfullyUnlinked); - }); + await this.tripFilesRepo.deleteMany(successfullyUnlinked); } return successfullyUnlinked.length; } diff --git a/server/src/nest/places/places.module.ts b/server/src/nest/places/places.module.ts index fc286b2ea..aa3a65eb2 100644 --- a/server/src/nest/places/places.module.ts +++ b/server/src/nest/places/places.module.ts @@ -1,3 +1,4 @@ +import { BudgetItems } from '../../db/entities/BudgetItems.entity'; import { Module } from '@nestjs/common'; import { MikroOrmModule } from '@mikro-orm/nestjs'; import { Places } from '../../db/entities/Places.entity'; @@ -63,7 +64,7 @@ import { MAX_PLACE_IMAGE_SIZE } from '../common/place-image-upload'; // precedent: a `forFeature` registration only reaches providers declared // in the SAME module. Plan 3c Task 5 adds `CategoriesRepository` for // PL33's `importKmlPlaces` folder → category lookup. - MikroOrmModule.forFeature([Places, Tags, PlaceRatings, TripMembers, DayAssignments, Trips, Categories]), + MikroOrmModule.forFeature([Places, Tags, PlaceRatings, TripMembers, DayAssignments, Trips, Categories, BudgetItems]), ], controllers: [PlacesController], providers: [PlacesService, PlacesMcp, PlacesRpc], diff --git a/server/src/nest/reservations/reservations.module.ts b/server/src/nest/reservations/reservations.module.ts index 29f2e5bce..574996555 100644 --- a/server/src/nest/reservations/reservations.module.ts +++ b/server/src/nest/reservations/reservations.module.ts @@ -1,3 +1,4 @@ +import { BudgetItems } from '../../db/entities/BudgetItems.entity'; import { Module } from '@nestjs/common'; import { MikroOrmModule } from '@mikro-orm/nestjs'; import { ReservationsReadModule } from './reservations-read.module'; @@ -53,7 +54,7 @@ import { Trips } from '../../db/entities/Trips.entity'; // back — accommodations reaches neither days nor reservations (ACC-002). imports: [ McpSharedModule, NotificationsModule, DaysModule, AssignmentsModule, AccommodationsModule, PermissionsModule, BudgetModule, AuthModule, RealtimeModule, PluginGuardsModule, ReservationsReadModule, AirtrailCoreModule, - MikroOrmModule.forFeature([Reservations, ReservationEndpoints, ReservationTravelers, ReservationDayPositions, DayAccommodations, Days, Places, DayAssignments, TripMembers, Users, Trips]), + MikroOrmModule.forFeature([Reservations, ReservationEndpoints, ReservationTravelers, ReservationDayPositions, DayAccommodations, Days, Places, DayAssignments, TripMembers, Users, Trips, BudgetItems]), ], controllers: [ReservationsController, UpcomingReservationsController], providers: [ReservationsService, ReservationsMcp, ReservationsRpc], diff --git a/server/tests/integration/packing.test.ts b/server/tests/integration/packing.test.ts index 0dc340f40..c8a1ff201 100644 --- a/server/tests/integration/packing.test.ts +++ b/server/tests/integration/packing.test.ts @@ -421,6 +421,58 @@ describe('Bags', () => { expect(res.body.bag.name).toBe('New Name'); }); + it('PACK-009b — H2 regression: PUT /bags/:bagId with an empty body no-ops (200, not 500)', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const createRes = await request(app) + .post(`/api/trips/${trip.id}/packing/bags`) + .set('Cookie', authCookie(user.id)) + .send({ name: 'Untouched Name', color: '#abcdef' }); + const bagId = createRes.body.bag.id; + + const res = await request(app) + .put(`/api/trips/${trip.id}/packing/bags/${bagId}`) + .set('Cookie', authCookie(user.id)) + .send({}); + expect(res.status).toBe(200); + expect(res.body.bag.name).toBe('Untouched Name'); + expect(res.body.bag.color).toBe('#abcdef'); + }); + + it('PACK-009c — H2 regression: PUT /bags/:bagId with an empty name no-ops (200, not 500)', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const createRes = await request(app) + .post(`/api/trips/${trip.id}/packing/bags`) + .set('Cookie', authCookie(user.id)) + .send({ name: 'Untouched Name', color: '#abcdef' }); + const bagId = createRes.body.bag.id; + + const res = await request(app) + .put(`/api/trips/${trip.id}/packing/bags/${bagId}`) + .set('Cookie', authCookie(user.id)) + .send({ name: '' }); + expect(res.status).toBe(200); + expect(res.body.bag.name).toBe('Untouched Name'); + }); + + it('PACK-009d — H2 regression: PUT /bags/:bagId with an empty color no-ops (200, not 500)', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const createRes = await request(app) + .post(`/api/trips/${trip.id}/packing/bags`) + .set('Cookie', authCookie(user.id)) + .send({ name: 'Untouched Name', color: '#abcdef' }); + const bagId = createRes.body.bag.id; + + const res = await request(app) + .put(`/api/trips/${trip.id}/packing/bags/${bagId}`) + .set('Cookie', authCookie(user.id)) + .send({ color: '' }); + expect(res.status).toBe(200); + expect(res.body.bag.color).toBe('#abcdef'); + }); + it('PACK-010 — DELETE /bags/:bagId removes bag', async () => { const { user } = createUser(testDb); const trip = createTrip(testDb, user.id); @@ -457,6 +509,24 @@ describe('Category assignees', () => { expect(res.body.assignees).toBeDefined(); }); + it('PACK-012b — H1 regression: a string trip id (the real REST shape) with a non-empty roster does not 500', async () => { + const { user } = createUser(testDb); + const { user: member } = createUser(testDb); + const trip = createTrip(testDb, user.id); + addTripMember(testDb, trip.id, member.id); + + // `trip.id` is a number in the fixture, but the route param — like every + // real REST call — arrives as a string; `insertIgnore` used to hand that + // raw string to `upsertMany`, which threw on the post-write re-match + // (task-8-review.md H1) instead of the 200 base returned. + const res = await request(app) + .put(`/api/trips/${String(trip.id)}/packing/category-assignees/Clothing`) + .set('Cookie', authCookie(user.id)) + .send({ user_ids: [user.id, member.id] }); + expect(res.status).toBe(200); + expect(res.body.assignees).toHaveLength(2); + }); + it('PACK-013 — GET /category-assignees returns all category assignments', async () => { const { user } = createUser(testDb); const trip = createTrip(testDb, user.id); diff --git a/server/tests/unit/db/repositories/PhotoProviders.repository.test.ts b/server/tests/unit/db/repositories/PhotoProviders.repository.test.ts index 9ccea942f..7c84fb4db 100644 --- a/server/tests/unit/db/repositories/PhotoProviders.repository.test.ts +++ b/server/tests/unit/db/repositories/PhotoProviders.repository.test.ts @@ -79,3 +79,20 @@ describe('PhotoProvidersRepository.listEnabled', () => { expect(rawRow('immich')).toMatchObject({ enabled: 1 }); }); }); + +describe('PhotoProvidersRepository.listAll / findEnabled', () => { + it('M1: listAll (the admin listing) returns every row regardless of enabled, unordered by that flag', async () => { + insertProvider({ id: 'immich', name: 'Immich', enabled: 1 }); + insertProvider({ id: 'off', name: 'Off', enabled: 0 }); + + const rows = await photoProviders.listAll(); + expect(rows.map((r) => r.id).sort()).toEqual(['immich', 'off']); + expect(rows.find((r) => r.id === 'off')?.enabled).toBe(0); + }); + + it('M1: findEnabled reads the enabled flag for a known provider and null for an unknown one', async () => { + insertProvider({ id: 'synology', name: 'Synology', enabled: 1 }); + expect(await photoProviders.findEnabled('synology')).toEqual({ enabled: 1 }); + expect(await photoProviders.findEnabled('does-not-exist')).toBeNull(); + }); +}); diff --git a/server/tests/unit/db/repositories/Users.repository.test.ts b/server/tests/unit/db/repositories/Users.repository.test.ts index da8109813..e8e631e86 100644 --- a/server/tests/unit/db/repositories/Users.repository.test.ts +++ b/server/tests/unit/db/repositories/Users.repository.test.ts @@ -985,4 +985,18 @@ describe('UsersRepository — feed tokens (Plan 3d Task 5, FD5-FD8/FD10)', () => // an `IS NULL` match against the many NULL-token rows in the DB. expect(await users.findIdAndUsernameByFeedToken('')).toBeUndefined(); }); + + it('M1: getImmichAutoUpload / getSynologyUsername / findUsernameEmail return their column, and the missing-user branch, honestly', async () => { + const { user } = createUser(testDb, { username: 'imm-user', email: 'imm@example.com' }); + testDb.prepare('UPDATE users SET immich_auto_upload = 1, synology_username = ? WHERE id = ?').run('syno-login', user.id); + + expect(await users.getImmichAutoUpload(user.id)).toBe(1); + expect(await users.getImmichAutoUpload(999999)).toBeNull(); + + expect(await users.getSynologyUsername(user.id)).toBe('syno-login'); + expect(await users.getSynologyUsername(999999)).toBeNull(); + + expect(await users.findUsernameEmail(user.id)).toEqual({ username: 'imm-user', email: 'imm@example.com' }); + expect(await users.findUsernameEmail(999999)).toBeUndefined(); + }); }); diff --git a/server/tests/unit/files/files.rpc.test.ts b/server/tests/unit/files/files.rpc.test.ts index d2067fee9..e50e0c343 100644 --- a/server/tests/unit/files/files.rpc.test.ts +++ b/server/tests/unit/files/files.rpc.test.ts @@ -200,6 +200,18 @@ describe('FilesRpc writes', () => { expect(res.error.message).toBe('file exceeds the 10MB plugin upload cap'); }); + it('M1: a payload whose DECODED bytes exceed the 10MB cap is refused even though its base64 length is under the 14MB encoded cap', async () => { + const f = build(); + // 10,600,000 decoded bytes (> FILE_CONTENT_MAX's 10,485,760) encodes to + // ~14.13M base64 chars — under FILES-RPC-010's 14MB ENCODED-length gate, + // so only `writeFile`'s own decoded-length check can catch this one. + const oversized = b64('x'.repeat(10_600_000)); + const res = (await f.host('db:write:files').dispatch( + req('files.create', { tripId: 1, input: { name: 'big.pdf', content_base64: oversized } }), 42, + )) as RpcError; + expect(res.error.message).toBe('file exceeds the 10MB plugin upload cap'); + }); + it('FILES-RPC-011 empty decoded content is refused', async () => { const f = build(); const res = (await f.host('db:write:files').dispatch(req('files.create', { tripId: 1, input: { name: 'a.pdf', content_base64: '====' } }), 42)) as RpcError; @@ -215,6 +227,22 @@ describe('FilesRpc writes', () => { expect(updated.error.message).toBe('reservation 9 does not belong to trip 1'); }); + it('M1: files.createLink also refuses a link target on another trip', async () => { + const f = build({ foreign: 'place 7' }); + const res = (await f.host('db:write:files').dispatch(req('files.createLink', { tripId: 1, fileId: 2, opts: { place_id: 7 } }), 42)) as RpcError; + expect(res.error.message).toBe('place 7 does not belong to trip 1'); + expect(f.files.createFileLink).not.toHaveBeenCalled(); + }); + + it('M1: files.createLink stringifies a provided place_id and files.update leaves an entirely absent reservation_id as undefined', async () => { + const f = build(); + await f.host('db:write:files').dispatch(req('files.createLink', { tripId: 1, fileId: 2, opts: { place_id: 11 } }), 42); + expect(f.files.createFileLink).toHaveBeenCalledWith(2, { reservation_id: null, assignment_id: null, place_id: '11' }); + + await f.host('db:write:files').dispatch(req('files.update', { tripId: 1, fileId: 2, input: { description: 'x' } }), 42); + expect(f.files.updateFile).toHaveBeenLastCalledWith(2, expect.anything(), expect.objectContaining({ reservation_id: undefined })); + }); + it('FILES-RPC-013 update tells null from undefined, so a link can be cleared', async () => { const f = build(); const host = f.host('db:write:files'); diff --git a/server/tests/unit/nest/budget.service.db.test.ts b/server/tests/unit/nest/budget.service.db.test.ts index 12f42ca1e..06e7f8cb6 100644 --- a/server/tests/unit/nest/budget.service.db.test.ts +++ b/server/tests/unit/nest/budget.service.db.test.ts @@ -73,7 +73,7 @@ import { VacayService } from '../../../src/nest/vacay/vacay.service'; import { QueryHelpersService } from '../../../src/nest/query-helpers/query-helpers.service'; import { notificationsStub } from '../../helpers/notifications'; import { createTestUnitOfWork, createTestAppSettingsRepo, createTestUsersRepo, sharedTestOrm, createTestTripsRepo, createTestTripMembersRepo } from '../../helpers/test-uow'; -import { budgetRepoArgs } from '../../helpers/budget-repos'; +import { budgetRepoArgs, createTestBudgetItemMembersRepo, createTestBudgetItemPayersRepo, createTestBudgetSettlementsRepo } from '../../helpers/budget-repos'; import { createTestBudgetItemsRepo } from '../../helpers/files-repos'; import { BudgetItemMembers } from '../../../src/db/entities/BudgetItemMembers.entity'; @@ -97,8 +97,16 @@ let budget: BudgetService; let membersSvc: TripMembersService; let createGuest: typeof membersSvc.createGuest; let deleteGuest: typeof membersSvc.deleteGuest; +let budgetItemsRepoDirect: Awaited>; +let budgetItemMembersRepoDirect: Awaited>; +let budgetItemPayersRepoDirect: Awaited>; +let budgetSettlementsRepoDirect: Awaited>; beforeAll(async () => { dbsEm = (await sharedTestOrm(testDb)).em; + budgetItemsRepoDirect = await createTestBudgetItemsRepo(testDb); + budgetItemMembersRepoDirect = await createTestBudgetItemMembersRepo(testDb); + budgetItemPayersRepoDirect = await createTestBudgetItemPayersRepo(testDb); + budgetSettlementsRepoDirect = await createTestBudgetSettlementsRepo(testDb); budget = new BudgetService( dbs(), new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb)), @@ -251,6 +259,23 @@ describe('toggleMemberPaid trip-scoping', () => { expect(paidFlag(itemB.id, user.id)).toBe(0); // unchanged }); + it('M2-BUDGET-001: getBudgetItem/deleteBudgetItem refuse an item from a different trip (BudgetItems.findInTrip / findForDelete trip-scoping)', async () => { + const { user } = createUser(testDb); + const tripA = createTrip(testDb, user.id, { title: 'Trip A' }); + const tripB = createTrip(testDb, user.id, { title: 'Trip B' }); + const itemB = await budget.createBudgetItem(tripB.id, { name: 'Foreign expense', total_price: 50 }) as { id: number }; + + // Caller passes a trip they can access (A) but the item lives in trip B — + // both methods must answer the legacy "not found" (null/false), not act + // on a row outside the trip the route claims to scope to. + expect(await budget.getBudgetItem(itemB.id, tripA.id)).toBeNull(); + expect(await budget.deleteBudgetItem(itemB.id, tripA.id)).toBe(false); + + // The item is untouched — proof the delete branch really refused, not + // just returned a stale read. + expect(await budget.getBudgetItem(itemB.id, tripB.id)).not.toBeNull(); + }); + it('BUDGET-SVC-DB-044: a forced mid-transaction failure after the write leaves no partial update (R2-class fix, §17 surprise 4)', async () => { // Plan 3e Task 2: `toggleMemberPaid` used to run its trip-scoping guard // (BG68) and its write (BG69) as two un-transacted statements. Wrapped @@ -497,6 +522,25 @@ describe('rebaseTripCurrency', () => { expect(placeRow(free)).toEqual({ price: null, currency: null }); }); + it('BUDGET-SVC-DB-010: re-freezes a budget_settlements row against the new base (BudgetSettlements.listDistinctCurrencies / setExchangeRateForCurrency)', async () => { + const { user: alice } = createUser(testDb, { username: 'alice' }); + const { user: bob } = createUser(testDb, { username: 'bob' }); + const trip = createTrip(testDb, alice.id, { title: 'Trip' }); + addTripMember(testDb, trip.id, bob.id); + testDb.prepare("UPDATE trips SET currency = 'EUR' WHERE id = ?").run(trip.id); + + const settlement = await budget.createSettlement(trip.id, { from_user_id: bob.id, to_user_id: alice.id, amount: 50, currency: 'USD' }, alice.id) as { id: number }; + const settlementRow = () => + testDb.prepare('SELECT currency, exchange_rate FROM budget_settlements WHERE id = ?').get(settlement.id) as { currency: string | null; exchange_rate: number }; + expect(settlementRow().currency).toBe('USD'); + + await budget.rebaseTripCurrency(trip.id, 'RUB'); + + // USD isn't the incoming base, so the settlement's frozen rate is re-anchored + // against RUB rather than left pointing at the trip's old EUR base. + expect(settlementRow()).toEqual({ currency: 'USD', exchange_rate: RATES.RUB.USD }); + }); + it('BUDGET-SVC-DB-008: is a no-op when the currency is unchanged', async () => { const { user } = createUser(testDb); const trip = createTrip(testDb, user.id, { title: 'Trip' }); @@ -1187,6 +1231,41 @@ describe('an expense whose split leaves a remainder', () => { expect((testDb.prepare('SELECT deleted_at FROM trip_files WHERE id = ?').get(file) as { deleted_at: string | null }).deleted_at).toBeNull(); }); + it('BUDGET-SVC-DB-046: unlinking a receipt that also carries a place link clears only the budget_item_id (BudgetItems.clearLinkBudgetRef)', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const place = Number(testDb.prepare('INSERT INTO places (trip_id, name) VALUES (?, ?)').run(trip.id, 'Cafe').lastInsertRowid); + const file = Number(testDb.prepare('INSERT INTO trip_files (trip_id, filename, original_name) VALUES (?, ?, ?)').run(trip.id, 'receipt.pdf', 'receipt.pdf').lastInsertRowid); + const item = await budget.createBudgetItem(trip.id, { name: 'Lunch' }) as { id: number }; + // Seed a link row that carries BOTH the receipt tie and a place tie — the + // shape unlinkReceipts's clearLinkBudgetRef branch exists for (row also + // ties the file to a place, so it must survive with budget_item_id cleared + // rather than be deleted outright). + testDb.prepare('INSERT INTO file_links (file_id, budget_item_id, place_id) VALUES (?, ?, ?)').run(file, item.id, place); + + await budget.deleteBudgetItem(item.id, trip.id); + + const row = testDb.prepare('SELECT place_id, budget_item_id FROM file_links WHERE file_id = ?').get(file) as { place_id: number | null; budget_item_id: number | null }; + expect(row.place_id).toBe(place); + expect(row.budget_item_id).toBeNull(); + }); + + it('BUDGET-SVC-DB-047: updating receipts adopts a spare file_links row instead of inserting a duplicate (BudgetItems.adoptSpareLink)', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const file = Number(testDb.prepare('INSERT INTO trip_files (trip_id, filename, original_name) VALUES (?, ?, ?)').run(trip.id, 'r.pdf', 'r.pdf').lastInsertRowid); + const item = await budget.createBudgetItem(trip.id, { name: 'Lunch' }) as { id: number }; + const linkId = Number(testDb.prepare('INSERT INTO file_links (file_id) VALUES (?)').run(file).lastInsertRowid); + + await budget.updateBudgetItem(item.id, trip.id, { receipt_file_ids: [file] }); + + const row = testDb.prepare('SELECT id, budget_item_id FROM file_links WHERE file_id = ?').get(file) as { id: number; budget_item_id: number | null }; + // The pre-existing spare row is re-parented rather than left orphaned + // beside a freshly inserted duplicate. + expect(row.id).toBe(linkId); + expect(row.budget_item_id).toBe(item.id); + }); + it('leaves a receipt already in the trash linked, so restoring it comes back attached', async () => { const { user: alice } = createUser(testDb); const trip = createTrip(testDb, alice.id); @@ -1211,3 +1290,124 @@ describe('an expense whose split leaves a remainder', () => { expect(after.id).toBe(before.id); }); }); + +describe('repository parity (rule 19 — full-key toEqual against the legacy statement run raw)', () => { + it('BUDGET-REPO-001: BudgetItemsRepository.listWithCategoryOrder matches BG10 (LEFT JOIN budget_category_order, COALESCE sort) run raw', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + // Two categories; only one has an explicit sort_order row, so the other + // falls back to the 999999 COALESCE default and sorts after it. + testDb.prepare('INSERT INTO budget_category_order (trip_id, category, sort_order) VALUES (?, ?, ?)').run(trip.id, 'Food', 0); + // Creation order assigns bi.sort_order 0, 1, 2 in turn; 'Activities' has no + // budget_category_order row, so it falls back to the 999999 COALESCE + // default and sorts after every 'Food' item regardless of its own sort_order. + await budget.createBudgetItem(trip.id, { name: 'Ramen', category: 'Food', total_price: 12 }); + await budget.createBudgetItem(trip.id, { name: 'Museum', category: 'Activities', total_price: 20 }); + await budget.createBudgetItem(trip.id, { name: 'Coffee', category: 'Food', total_price: 4 }); + + const converted = await budgetItemsRepoDirect.listWithCategoryOrder(trip.id); + const legacy = testDb.prepare(` + SELECT bi.* FROM budget_items bi + LEFT JOIN budget_category_order bco ON bco.trip_id = bi.trip_id AND bco.category = bi.category + WHERE bi.trip_id = ? + ORDER BY COALESCE(bco.sort_order, 999999) ASC, bi.sort_order ASC + `).all(trip.id); + + expect(converted).toEqual(legacy); + expect(converted).toHaveLength(3); + expect(converted.map(r => r.name)).toEqual(['Ramen', 'Coffee', 'Museum']); + }); + + it('BUDGET-REPO-002: BudgetItemMembersRepository/BudgetItemPayersRepository.listForItems and BudgetItemsRepository.listReceiptsForItems match BG11/BG12/BG13 run raw', async () => { + const { user: alice } = createUser(testDb, { username: 'alice' }); + const { user: bob } = createUser(testDb, { username: 'bob' }); + const trip = createTrip(testDb, alice.id); + addTripMember(testDb, trip.id, bob.id); + const file = Number(testDb.prepare('INSERT INTO trip_files (trip_id, filename, original_name) VALUES (?, ?, ?)').run(trip.id, 'r.pdf', 'r.pdf').lastInsertRowid); + + const item1 = await budget.createBudgetItem(trip.id, { + name: 'Dinner', total_price: 40, members: [{ user_id: alice.id }, { user_id: bob.id }], + payers: [{ user_id: alice.id, amount: 40 }], receipt_file_ids: [file], + }) as { id: number }; + const item2 = await budget.createBudgetItem(trip.id, { name: 'Snack', total_price: 5, members: [{ user_id: bob.id }] }) as { id: number }; + const itemIds = [item1.id, item2.id]; + + const convertedMembers = await budgetItemMembersRepoDirect.listForItems(itemIds); + const legacyMembers = testDb.prepare(` + SELECT bm.budget_item_id, bm.user_id, bm.paid, bm.amount, COALESCE(u.display_name, u.username) AS username, u.avatar + FROM budget_item_members bm JOIN users u ON u.id = bm.user_id + WHERE bm.budget_item_id IN (${itemIds.join(',')}) + `).all(); + const sortByUser = (rows: T[]) => [...rows].sort((a, b) => a.budget_item_id - b.budget_item_id || a.user_id - b.user_id); + expect(sortByUser(convertedMembers)).toEqual(sortByUser(legacyMembers as typeof convertedMembers)); + expect(convertedMembers).toHaveLength(3); + + const convertedPayers = await budgetItemPayersRepoDirect.listForItems(itemIds); + const legacyPayers = testDb.prepare(` + SELECT bp.budget_item_id, bp.user_id, bp.amount, COALESCE(u.display_name, u.username) AS username, u.avatar + FROM budget_item_payers bp JOIN users u ON u.id = bp.user_id + WHERE bp.budget_item_id IN (${itemIds.join(',')}) + `).all(); + expect(sortByUser(convertedPayers)).toEqual(sortByUser(legacyPayers as typeof convertedPayers)); + expect(convertedPayers).toHaveLength(1); + + const convertedReceipts = await budgetItemsRepoDirect.listReceiptsForItems(itemIds); + const legacyReceipts = testDb.prepare(` + SELECT f.id, f.filename, f.original_name, f.file_size, f.mime_type, f.trip_id, fl.budget_item_id + FROM trip_files f JOIN file_links fl ON fl.file_id = f.id + WHERE f.deleted_at IS NULL AND fl.budget_item_id IN (${itemIds.join(',')}) + ORDER BY f.created_at ASC + `).all(); + expect(convertedReceipts).toEqual(legacyReceipts); + expect(convertedReceipts).toHaveLength(1); + }); + + it('BUDGET-REPO-003: BudgetSettlementsRepository.listForTrip / findWithUsers match BG76/BG77 (SETTLEMENT_SELECT) run raw', async () => { + const { user: alice } = createUser(testDb, { username: 'alice' }); + const { user: bob } = createUser(testDb, { username: 'bob' }); + const trip = createTrip(testDb, alice.id); + addTripMember(testDb, trip.id, bob.id); + + const s1 = await budget.createSettlement(trip.id, { from_user_id: bob.id, to_user_id: alice.id, amount: 50, currency: 'USD' }, alice.id) as { id: number }; + const s2 = await budget.createSettlement(trip.id, { from_user_id: alice.id, to_user_id: bob.id, amount: 10 }, bob.id) as { id: number }; + + const SETTLEMENT_SELECT = ` + SELECT s.id, s.trip_id, s.from_user_id, s.to_user_id, s.amount, s.currency, s.exchange_rate, + s.created_at, s.settled_at, s.created_by_user_id, + COALESCE(fu.display_name, fu.username) AS from_username, fu.avatar AS from_avatar, + COALESCE(tu.display_name, tu.username) AS to_username, tu.avatar AS to_avatar + FROM budget_settlements s + JOIN users fu ON fu.id = s.from_user_id + JOIN users tu ON tu.id = s.to_user_id + `; + + const convertedList = await budgetSettlementsRepoDirect.listForTrip(trip.id); + const legacyList = testDb.prepare(`${SETTLEMENT_SELECT} WHERE s.trip_id = ? ORDER BY s.created_at DESC, s.id DESC`).all(trip.id); + expect(convertedList).toEqual(legacyList); + expect(convertedList.map(s => s.id).sort()).toEqual([s1.id, s2.id].sort()); + + const convertedOne = await budgetSettlementsRepoDirect.findWithUsers(s1.id, trip.id); + const legacyOne = testDb.prepare(`${SETTLEMENT_SELECT} WHERE s.trip_id = ? AND s.id = ?`).get(trip.id, s1.id); + expect(convertedOne).toEqual(legacyOne); + }); + + it('M1: BudgetItemsRepository.listReceiptsForItems / listIdsForPlaces short-circuit on an empty id array', async () => { + expect(await budgetItemsRepoDirect.listReceiptsForItems([])).toEqual([]); + expect(await budgetItemsRepoDirect.listIdsForPlaces(1, [])).toEqual([]); + }); + + it('M1: BudgetItemMembersRepository/BudgetItemPayersRepository.listForItems short-circuit on an empty id array; BudgetItemMembers.insertIgnore hits its onConflict doNothing branch on a repeat insert', async () => { + expect(await budgetItemMembersRepoDirect.listForItems([])).toEqual([]); + expect(await budgetItemPayersRepoDirect.listForItems([])).toEqual([]); + + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const item = await budget.createBudgetItem(trip.id, { name: 'Lunch', total_price: 10 }) as { id: number }; + await budgetItemMembersRepoDirect.insertIgnore({ budget_item_id: item.id, user_id: user.id }); + // A second insert for the same (budget_item_id, user_id) hits the unique + // index — onConflict(doNothing) swallows it instead of throwing. + await expect(budgetItemMembersRepoDirect.insertIgnore({ budget_item_id: item.id, user_id: user.id })).resolves.toBeUndefined(); + const rows = testDb.prepare('SELECT COUNT(*) c FROM budget_item_members WHERE budget_item_id = ? AND user_id = ?').get(item.id, user.id); + expect(rows).toEqual({ c: 1 }); + }); +}); diff --git a/server/tests/unit/nest/collab.controller.test.ts b/server/tests/unit/nest/collab.controller.test.ts index 8037e5ac7..7ad9f4db7 100644 --- a/server/tests/unit/nest/collab.controller.test.ts +++ b/server/tests/unit/nest/collab.controller.test.ts @@ -188,6 +188,17 @@ describe('CollabController (parity with the legacy /api/trips/:tripId/collab rou expect(await new CollabController(s, storageStub).deleteMessage(user, '5', '3', 'sock')).toEqual({ success: true }); expect(broadcast).toHaveBeenCalledWith('5', 'collab:message:deleted', { messageId: 3, username: 'bob' }, 'sock'); }); + + it('U5: deleteMessage broadcast falls back to the caller\'s own username when the service\'s username is undefined (the real, pre-existing shape)', async () => { + const broadcast = vi.fn(); + // `CollabService.deleteMessage` really does return `{ username: undefined }` + // (findInTrip never joins users) — the controller's `result.username || + // user.username` fallback is what keeps the broadcast correct, and only + // works because the route already requires caller === message owner. + const s = svc({ deleteMessage: vi.fn().mockResolvedValue({ username: undefined }), broadcast } as Partial); + expect(await new CollabController(s, storageStub).deleteMessage(user, '5', '3', 'sock')).toEqual({ success: true }); + expect(broadcast).toHaveBeenCalledWith('5', 'collab:message:deleted', { messageId: 3, username: user.username }, 'sock'); + }); }); // The decorators, not the handler body. Constructing the controller directly, diff --git a/server/tests/unit/nest/collab.service.test.ts b/server/tests/unit/nest/collab.service.test.ts index f0b4c261d..e29ba4763 100644 --- a/server/tests/unit/nest/collab.service.test.ts +++ b/server/tests/unit/nest/collab.service.test.ts @@ -259,6 +259,20 @@ describe('listMessages', () => { expect(msgs).toHaveLength(2); }); + it('COLLAB-SVC-010b: a message created with files inserts a trip_files attachment row per file (CollabMessages.insertAttachmentForMessage)', async () => { + const { user1, trip } = setup(); + const files = [ + { filename: 'stored-a.png', originalname: 'a.png', size: 123, mimetype: 'image/png' }, + { filename: 'stored-b.png', originalname: 'b.png', size: 456, mimetype: 'image/png' }, + ]; + + const result = await svc.createMessage(trip.id, user1.id, 'look at these', undefined, files); + + expect(result.message!.attachments).toHaveLength(2); + const names = result.message!.attachments.map(a => a.original_name).sort(); + expect(names).toEqual(['a.png', 'b.png']); + }); + it('COLLAB-SVC-011: paginates using before cursor (returns messages with id < before)', async () => { const { user1, trip } = setup(); await svc.createMessage(trip.id, user1.id, 'First'); @@ -274,6 +288,21 @@ describe('listMessages', () => { expect(texts).not.toContain('Third'); }); + it('U4: a malformed `before` cursor (non-canonical string, hex, or empty string) narrows to an empty page, not "every message" (rule 15, accepted deviation)', async () => { + const { user1, trip } = setup(); + await svc.createMessage(trip.id, user1.id, 'First'); + await svc.createMessage(trip.id, user1.id, 'Second'); + + // The legacy raw bind let SQLite's TEXT/INTEGER ordering decide (a + // non-numeric cursor always sorted "greater" than every integer id, so + // `m.id < 'garbage'` matched everything). `toRowId` narrows each of + // these three spellings to -1 instead, which matches nothing — our own + // client never sends any of them (task-5 ruling, task-8-review.md L2/U4). + for (const before of ['abc', '0x1', '']) { + expect(await svc.listMessages(trip.id, before)).toEqual([]); + } + }); + it('COLLAB-SVC-012: returns messages in ascending order (reversed after DESC query)', async () => { const { user1, trip } = setup(); await svc.createMessage(trip.id, user1.id, 'A'); @@ -378,6 +407,11 @@ describe('deleteMessage', () => { const result = await svc.deleteMessage(trip.id, r.message!.id, user1.id); expect(result.error).toBeUndefined(); + // U5 (pre-existing, pinned not fixed): findInTrip never joins users, so + // this has always been undefined at runtime — the controller falls back + // to the caller's own username (CollabController.deleteMessage, correct + // because only the owner may delete their own message). + expect(result.username).toBeUndefined(); const row = testDb.prepare('SELECT deleted FROM collab_messages WHERE id = ?').get(r.message!.id) as any; expect(row.deleted).toBe(1); @@ -435,6 +469,18 @@ describe('updateNote', () => { expect(result).toBeNull(); }); + it('M2-COLLAB-001: refuses to update a note from a different trip (CollabNotes.findInTrip trip-scoping)', async () => { + const { user1, trip } = setup(); + const tripB = createTrip(testDb, user1.id); + const noteB = await svc.createNote(tripB.id, user1.id, { title: 'Foreign note' }); + + const result = await svc.updateNote(trip.id, noteB.id, { title: 'Hijacked' }); + + expect(result).toBeNull(); + const untouched = testDb.prepare('SELECT title FROM collab_notes WHERE id = ?').get(noteB.id) as { title: string }; + expect(untouched.title).toBe('Foreign note'); + }); + it('COLLAB-SVC-024: updates pinned flag', async () => { const { user1, trip } = setup(); const note = await svc.createNote(trip.id, user1.id, { title: 'T', pinned: false }); diff --git a/server/tests/unit/nest/files.service.test.ts b/server/tests/unit/nest/files.service.test.ts index f7ff3ba1f..6cb122f39 100644 --- a/server/tests/unit/nest/files.service.test.ts +++ b/server/tests/unit/nest/files.service.test.ts @@ -258,6 +258,16 @@ describe('getFileById / getDeletedFile', () => { await svc.softDeleteFile(file.id); expect((await svc.getDeletedFile(file.id, trip.id))?.id).toBe(file.id); }); + + it('M2-FILES-001: getDeletedFile refuses a soft-deleted file from a different trip (TripFiles.findDeletedInTrip trip-scoping)', async () => { + const { user, trip } = seedTrip(); + const other = createTrip(testDb, user.id); + const file = await makeFile(trip.id, user.id); + await svc.softDeleteFile(file.id); + + expect((await svc.getDeletedFile(file.id, trip.id))?.id).toBe(file.id); + expect(await svc.getDeletedFile(file.id, other.id)).toBeUndefined(); + }); }); describe('listFiles', () => { @@ -531,7 +541,16 @@ describe('emptyTrash', () => { expect(storageDelete).not.toHaveBeenCalled(); }); - it('FILE-SVC-062 (R2): a failing bulk delete leaves every trashed row in place', async () => { + it('FILE-SVC-062: a failing bulk delete leaves every trashed row in place (single-statement atomicity, not a transaction)', async () => { + // `emptyTrash`'s bulk delete is one statement (`tripFilesRepo.deleteMany`), + // not wrapped in `uow.transactional` (task-8-review.md L1/U1: that wrapper + // was vacuous — there is nothing else in the body for a rollback to undo, + // and the FILE-SVC-062 name's old "(R2)" tag overclaimed transactional + // rollback semantics it never actually proved). This pins the honest + // claim instead: a single statement that never runs leaves nothing + // half-done, by construction — the row survives because `deleteMany` + // itself rejected before touching the DB, not because a transaction + // rolled anything back. const { user, trip } = seedTrip(); const a = await makeFile(trip.id, user.id, { filename: 'a.pdf' }); await svc.softDeleteFile(a.id); @@ -583,6 +602,60 @@ describe('findForeignLinkTarget', () => { // Both foreign — the reservation check runs before the place check. expect(await svc.findForeignLinkTarget(mine.id, { reservation_id: foreignRes.id, place_id: foreignPlace.id })).toBe('reservation_id'); }); + + it('M1: a malformed (non-canonical) id for each target kind is refused as foreign (toRowId narrows to null, rule 15)', async () => { + const { mine } = twoTrips(); + expect(await svc.findForeignLinkTarget(mine.id, { reservation_id: 'abc' })).toBe('reservation_id'); + expect(await svc.findForeignLinkTarget(mine.id, { place_id: 'abc' })).toBe('place_id'); + expect(await svc.findForeignLinkTarget(mine.id, { assignment_id: 'abc' })).toBe('assignment_id'); + expect(await svc.findForeignLinkTarget(mine.id, { budget_item_id: 'abc' })).toBe('budget_item_id'); + }); +}); + +// ── rule 21 — every `toRowId(x) ?? -1` guard's malformed-id branch ───────────── + +describe('malformed (non-canonical) ids narrow to -1, not a live row', () => { + it('M1: getFileById / getDeletedFile return undefined for a malformed id', async () => { + const { trip } = seedTrip(); + expect(await svc.getFileById('abc', trip.id)).toBeUndefined(); + expect(await svc.getDeletedFile('abc', trip.id)).toBeUndefined(); + }); + + it('M1: listFiles / emptyTrash treat a malformed trip id as an empty trip', async () => { + expect(await svc.listFiles('abc', false)).toEqual([]); + expect(await svc.emptyTrash('abc')).toBe(0); + }); + + it('M1: updateFile with a malformed id writes nothing and there is no row left to format', async () => { + const { user, trip } = seedTrip(); + const file = await makeFile(trip.id, user.id); + await expect(svc.updateFile('abc', file, { description: 'x' })).rejects.toThrow(); + }); + + it('M1: toggleStarred with a malformed id writes nothing and there is no row left to format', async () => { + await expect(svc.toggleStarred('abc', 0)).rejects.toThrow(); + }); + + it('M1: restoreFile with a malformed id writes nothing and there is no row left to format', async () => { + await expect(svc.restoreFile('abc')).rejects.toThrow(); + }); + + it('M1: softDeleteFile with a malformed id is a safe no-op', async () => { + await expect(svc.softDeleteFile('abc')).resolves.toBeUndefined(); + }); + + it('M1: deleteFileLink / getFileLinks with malformed ids are safe no-ops', async () => { + await expect(svc.deleteFileLink('abc', 'abc')).resolves.toBeUndefined(); + expect(await svc.getFileLinks('abc')).toEqual([]); + }); + + it('M1: createFileLink with a malformed fileId cannot satisfy the file_links FK and rejects', async () => { + await expect(svc.createFileLink('abc', {})).rejects.toThrow(); + }); + + it('M1: TripFilesRepository.deleteMany short-circuits on an empty id array', async () => { + await expect(tripFilesRepo.deleteMany([])).resolves.toBeUndefined(); + }); }); // ── file links ──────────────────────────────────────────────────────────────── diff --git a/server/tests/unit/nest/packing.service.test.ts b/server/tests/unit/nest/packing.service.test.ts index 2a974d08c..e76e2e1d5 100644 --- a/server/tests/unit/nest/packing.service.test.ts +++ b/server/tests/unit/nest/packing.service.test.ts @@ -79,23 +79,33 @@ import { } from '../../helpers/packing-repos'; let svc: PackingService; +let packingItemsRepoDirect: Awaited>; +let packingBagsRepoDirect: Awaited>; +let packingTemplatesRepoDirect: Awaited>; +let packingCategoryAssigneesRepoDirect: Awaited>; +let packingItemContributorsRepoDirect: Awaited>; // ── Lifecycle ───────────────────────────────────────────────────────────────── beforeAll(async () => { createTables(testDb); runMigrations(testDb); + packingItemsRepoDirect = await createTestPackingItemsRepo(testDb); + packingBagsRepoDirect = await createTestPackingBagsRepo(testDb); + packingTemplatesRepoDirect = await createTestPackingTemplatesRepo(testDb); + packingCategoryAssigneesRepoDirect = await createTestPackingCategoryAssigneesRepo(testDb); + packingItemContributorsRepoDirect = await createTestPackingItemContributorsRepo(testDb); svc = new PackingService( await createTestDatabaseService(testDb), permissionsStub, new RealtimeService(), notificationsStub(send), await createTestUnitOfWork(testDb), - await createTestPackingItemsRepo(testDb), - await createTestPackingItemContributorsRepo(testDb), - await createTestPackingBagsRepo(testDb), - await createTestPackingCategoryAssigneesRepo(testDb), - await createTestPackingTemplatesRepo(testDb), + packingItemsRepoDirect, + packingItemContributorsRepoDirect, + packingBagsRepoDirect, + packingCategoryAssigneesRepoDirect, + packingTemplatesRepoDirect, await createTestPackingTemplateCategoriesRepo(testDb), await createTestPackingTemplateItemsRepo(testDb), await createTestTripsRepo(testDb), @@ -1185,6 +1195,47 @@ describe('packing item object-level authorization', () => { expect(await svc.cloneItem(trip.id, personal.id, intruder.id)).toBeNull(); }); + it('L3: a non-viewer cannot add themselves as a contributor on a restricted item they cannot see', async () => { + const { trip, personal, intruder } = await restrictedTrip(); + expect(await svc.addContributor(trip.id, personal.id, intruder.id)).toBeNull(); + }); + + it('L3: a non-viewer cannot remove a contributor from a restricted item they cannot see', async () => { + const { owner, trip, personal, intruder } = await restrictedTrip(); + // Route the contributor delete through the CALLER's own id as the acting + // visibility check (unlike the controller's actual `:userId` wiring, + // which is U3's own hole below) — even so, an intruder with no view + // access to a Personal item must not be able to touch it. + expect(await svc.removeContributor(trip.id, personal.id, intruder.id)).toBeNull(); + expect(testDb.prepare('SELECT owner_id FROM packing_items WHERE id = ?').get(personal.id)).toEqual({ owner_id: owner.id }); + }); + + it('U3 HOLE — contributor removal checks the path user\'s visibility, not the caller\'s: an intruder who cannot see a Personal item still gets it back by naming the owner as :userId', async () => { + // PRE-EXISTING on base (packing.controller.ts ~250 → packing.service.ts + // removeContributor; base carries the identical shape). The controller + // passes the PATH `:userId` — not `user.id`, the caller — as the third + // argument to `PackingService.removeContributor`, which uses that same + // id both to run the visibility check AND as the contributor row to + // delete. An intruder who cannot see `owner`'s Personal item at all can + // still name `owner` as `:userId`: the visibility check passes because + // OWNERS can always see their own item, and the full enriched item comes + // back in the response — an IDOR read of content the intruder has no + // business seeing, RIGHTS-gated only by `packing_edit`, not by the + // three-tier privacy model. Deliberately NOT fixed here (controller + // ruling U3, pinned so it cannot be "fixed" silently); the one-line fix + // is in the fix-wave report for the user: check `findVisibleInTrip` for + // the CALLER, and additionally require `userId === callerId || + // item.owner_id === callerId`. + // The intruder is the caller in the real route (RequirePermission checks + // only packing_edit, never visibility) — but the service signature never + // receives the caller's id at all, only the path :userId. That gap is + // the bug, so there is nothing of the intruder's identity to pass here. + const { owner, trip, personal } = await restrictedTrip(); + const leaked = await svc.removeContributor(trip.id, personal.id, owner.id); + expect(leaked).not.toBeNull(); + expect(leaked.name).toBe('Diary'); + }); + it('PACK-SVC-105b: a visible item the caller does not own still reports forbidden, not missing', async () => { const { trip, common, intruder } = await restrictedTrip(); expect((await svc.setItemSharing(trip.id, common.id, intruder.id, 'personal', []) as any).forbidden).toBe(true); @@ -1196,6 +1247,21 @@ describe('packing item object-level authorization', () => { expect(testDb.prepare('SELECT is_private FROM packing_items WHERE id = ?').get(personal.id)).toEqual({ is_private: 1 }); }); + it('M2-PACKING-001: refuses to update a visible-shaped item from a different trip (PackingItems.findVisibleInTrip trip-scoping)', async () => { + const { user } = createUser(testDb); + const tripA = createTrip(testDb, user.id); + const tripB = createTrip(testDb, user.id); + const itemBId = Number( + testDb.prepare('INSERT INTO packing_items (trip_id, name, category, checked) VALUES (?, ?, ?, 0)').run(tripB.id, 'Foreign item', 'Clothing').lastInsertRowid, + ); + + // itemB is a Common item the caller can see — the guard that must refuse + // this is the trip filter, not the privacy predicate. + const result = await svc.updateItem(tripA.id, itemBId, { name: 'Hijacked' }, ['name'], undefined, user.id); + expect(result).toBeNull(); + expect(testDb.prepare('SELECT name FROM packing_items WHERE id = ?').get(itemBId)).toEqual({ name: 'Foreign item' }); + }); + // Missing actor must deny rather than fall through unfiltered. it('PACK-SVC-106: an update with no actor at all is refused', async () => { const { trip, personal } = await restrictedTrip(); @@ -1223,3 +1289,124 @@ describe('packing item object-level authorization', () => { expect(rows.map(r => r.name).sort()).toEqual(['Tent']); }); }); + +describe('repository parity (rule 19 — full-key toEqual against the legacy statement run raw)', () => { + // The legacy VISIBLE_TO_ACTOR fragment (`_shared/packing-visibility.ts`'s + // own docstring quotes it byte-for-byte): + // ( is_private = 0 OR owner_id = ? OR EXISTS (SELECT 1 FROM + // packing_item_recipients r WHERE r.item_id = packing_items.id AND + // r.user_id = ?) ) + const VISIBLE_TO_ACTOR = `( + is_private = 0 + OR owner_id = ? + OR EXISTS (SELECT 1 FROM packing_item_recipients r WHERE r.item_id = packing_items.id AND r.user_id = ?) + )`; + + it('PACKING-REPO-001: PackingItemsRepository.listVisibleToActor matches PK5 (VISIBLE_TO_ACTOR) run raw, for the owner, a recipient and a plain member', async () => { + const { user: owner } = createUser(testDb); + const { user: friend } = createUser(testDb); + const { user: stranger } = createUser(testDb); + const trip = createTrip(testDb, owner.id); + addTripMember(testDb, trip.id, friend.id); + addTripMember(testDb, trip.id, stranger.id); + + const common = await svc.createItem(trip.id, { name: 'Common tent', visibility: 'common' }, owner.id); + const personal = await svc.createItem(trip.id, { name: 'Owner diary', visibility: 'personal' }, owner.id); + const shared = await svc.createItem(trip.id, { name: 'Shared map', visibility: 'shared', recipient_ids: [friend.id] }, owner.id); + expect([common, personal, shared]).toHaveLength(3); + + for (const [actor, label] of [[owner, 'owner'], [friend, 'recipient'], [stranger, 'plain member']] as const) { + const converted = await packingItemsRepoDirect.listVisibleToActor(trip.id, actor.id); + const legacy = testDb.prepare(` + SELECT * FROM packing_items WHERE trip_id = ? AND ${VISIBLE_TO_ACTOR} + ORDER BY sort_order ASC, created_at ASC + `).all(trip.id, actor.id, actor.id); + expect(converted, `mismatch for ${label}`).toEqual(legacy); + } + // Sanity on the visibility split itself, so a predicate regression that + // still byte-matches (e.g. both sides equally wrong) cannot hide. + expect((await packingItemsRepoDirect.listVisibleToActor(trip.id, owner.id)).map(i => i.name).sort()).toEqual(['Common tent', 'Owner diary', 'Shared map']); + expect((await packingItemsRepoDirect.listVisibleToActor(trip.id, friend.id)).map(i => i.name).sort()).toEqual(['Common tent', 'Shared map']); + expect((await packingItemsRepoDirect.listVisibleToActor(trip.id, stranger.id)).map(i => i.name).sort()).toEqual(['Common tent']); + }); + + it('PACKING-REPO-002: PackingBagsRepository.findWithAssignee matches PK46 (LEFT JOIN users) run raw, assigned and unassigned', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const bag = (await svc.createBag(trip.id, { name: 'Backpack', color: '#123456' }))!; + + const legacyUnassigned = testDb.prepare('SELECT b.*, COALESCE(u.display_name, u.username) as assigned_username FROM packing_bags b LEFT JOIN users u ON b.user_id = u.id WHERE b.id = ?').get(bag.id); + expect(await packingBagsRepoDirect.findWithAssignee(bag.id)).toEqual(legacyUnassigned); + + await packingBagsRepoDirect.update(bag.id, { user_id: [true, user.id] }); + const legacyAssigned = testDb.prepare('SELECT b.*, COALESCE(u.display_name, u.username) as assigned_username FROM packing_bags b LEFT JOIN users u ON b.user_id = u.id WHERE b.id = ?').get(bag.id); + const convertedAssigned = await packingBagsRepoDirect.findWithAssignee(bag.id); + expect(convertedAssigned).toEqual(legacyAssigned); + expect(convertedAssigned!.assigned_username).toBe(user.username); + }); + + it('PACKING-REPO-003: PackingTemplatesRepository.listWithItemCount matches PK49 (correlated COUNT) run raw', async () => { + const { user: owner } = createUser(testDb); + const trip = createTrip(testDb, owner.id); + await svc.createItem(trip.id, { name: 'Tent', visibility: 'common' }, owner.id); + await svc.createItem(trip.id, { name: 'Stove', visibility: 'common' }, owner.id); + await svc.saveAsTemplate(trip.id, owner.id, 'Camping kit'); + await svc.saveAsTemplate(trip.id, owner.id, 'Empty-ish'); // second template, 0 extra items beyond dedupe + + const converted = await packingTemplatesRepoDirect.listWithItemCount(); + const legacy = testDb.prepare(` + SELECT pt.id, pt.name, + (SELECT COUNT(*) FROM packing_template_items ti JOIN packing_template_categories tc ON ti.category_id = tc.id WHERE tc.template_id = pt.id) as item_count + FROM packing_templates pt ORDER BY pt.created_at DESC + `).all(); + expect(converted).toEqual(legacy); + expect(converted.length).toBeGreaterThanOrEqual(2); + }); + + it('PACKING-REPO-004: PackingCategoryAssigneesRepository.listForCategory matches PK61 run raw', async () => { + const { user: alice } = createUser(testDb, { username: 'alice' }); + const { user: bob } = createUser(testDb, { username: 'bob' }); + const trip = createTrip(testDb, alice.id); + addTripMember(testDb, trip.id, bob.id); + + await svc.updateCategoryAssignees(trip.id, 'Clothing', [alice.id, bob.id]); + + const converted = await packingCategoryAssigneesRepoDirect.listForCategory(trip.id, 'Clothing'); + const legacy = testDb.prepare(` + SELECT pca.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar + FROM packing_category_assignees pca JOIN users u ON pca.user_id = u.id + WHERE pca.trip_id = ? AND pca.category_name = ? + `).all(trip.id, 'Clothing'); + const sortByUser = (rows: { user_id: number }[]) => [...rows].sort((a, b) => a.user_id - b.user_id); + expect(sortByUser(converted)).toEqual(sortByUser(legacy as { user_id: number }[])); + expect(converted).toHaveLength(2); + }); + + it('PACKING-REPO-005: PackingItemsRepository.listExportable matches PK54 run raw, dropping another member\'s restricted item', async () => { + const { user: owner } = createUser(testDb); + const { user: other } = createUser(testDb); + const trip = createTrip(testDb, owner.id); + addTripMember(testDb, trip.id, other.id); + + await svc.createItem(trip.id, { name: 'Common tent', visibility: 'common' }, owner.id); + await svc.createItem(trip.id, { name: 'Owner diary', visibility: 'personal' }, owner.id); + await svc.createItem(trip.id, { name: 'Other diary', visibility: 'personal' }, other.id); + + const converted = await packingItemsRepoDirect.listExportable(trip.id, owner.id); + const legacy = testDb.prepare(` + SELECT name, category FROM packing_items WHERE trip_id = ? AND (is_private = 0 OR owner_id = ?) ORDER BY sort_order ASC + `).all(trip.id, owner.id); + expect(converted).toEqual(legacy); + expect(converted.map((r) => r.name).sort()).toEqual(['Common tent', 'Owner diary']); + }); + + it('M1: empty-id-array guards short-circuit on PackingItemContributors/PackingItems batch reads and writes', async () => { + expect(await packingItemContributorsRepoDirect.listForItems([])).toEqual([]); + expect(await packingItemsRepoDirect.listRecipientsForItems([])).toEqual([]); + await expect(packingItemsRepoDirect.insertRecipientsIgnore(1, [])).resolves.toBeUndefined(); + }); + + it('M1: PackingCategoryAssigneesRepository.insertIgnore short-circuits on an empty user_ids array', async () => { + await expect(packingCategoryAssigneesRepoDirect.insertIgnore(1, 'Clothing', [])).resolves.toBeUndefined(); + }); +}); diff --git a/server/tests/unit/nest/todo.service.test.ts b/server/tests/unit/nest/todo.service.test.ts index 84ad5f8b5..56ae20f99 100644 --- a/server/tests/unit/nest/todo.service.test.ts +++ b/server/tests/unit/nest/todo.service.test.ts @@ -52,11 +52,13 @@ import { createTestUnitOfWork, createTestAppSettingsRepo, createTestDatabaseServ import { createTestTodoItemsRepo, createTestTodoCategoryAssigneesRepo } from '../../helpers/todo-repos'; let svc: TodoService; +let todoItemsRepoDirect: Awaited>; beforeAll(async () => { const uow = await createTestUnitOfWork(testDb); + todoItemsRepoDirect = await createTestTodoItemsRepo(testDb); svc = new TodoService( await createTestDatabaseService(testDb), new PermissionsService(await createTestAppSettingsRepo(testDb), uow), new RealtimeService(), uow, - await createTestTodoItemsRepo(testDb), await createTestTodoCategoryAssigneesRepo(testDb), + todoItemsRepoDirect, await createTestTodoCategoryAssigneesRepo(testDb), ); }); @@ -191,6 +193,24 @@ describe('updateItem', () => { const updated = (await svc.updateItem(trip.id, item.id, { due_date: null }, ['due_date'])) as any; expect(updated.due_date).toBeNull(); }); + + it('M2-TODO-001: refuses to update an item from a different trip (TodoItems.findInTrip trip-scoping)', async () => { + const { user } = createUser(testDb); + const tripA = createTrip(testDb, user.id); + const tripB = createTrip(testDb, user.id); + const itemB = (await svc.createItem(tripB.id, { name: 'Foreign task' }))!; + + expect(await svc.updateItem(tripA.id, itemB.id, { name: 'Hijacked' }, ['name'])).toBeNull(); + expect((await svc.listItems(tripB.id))[0].name).toBe('Foreign task'); + }); + + it('M1: TodoItemsRepository.update no-ops on an empty write (presenceSet returns {})', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const item = (await svc.createItem(trip.id, { name: 'Untouched' }))!; + await expect(todoItemsRepoDirect.update(item.id, {})).resolves.toBeUndefined(); + expect((await svc.listItems(trip.id))[0].name).toBe('Untouched'); + }); }); // ── deleteItem ──────────────────────────────────────────────────────────────── diff --git a/server/tests/unit/nest/trek-photos.repository.test.ts b/server/tests/unit/nest/trek-photos.repository.test.ts index 6e872ad4d..bf52faacb 100644 --- a/server/tests/unit/nest/trek-photos.repository.test.ts +++ b/server/tests/unit/nest/trek-photos.repository.test.ts @@ -18,6 +18,7 @@ import { DatabaseService } from '../../../src/nest/database/database.service'; import { TrekPhotoRegistrationService } from '../../../src/nest/photos/trek-photos.repository'; import { TrekPhotos } from '../../../src/db/entities/TrekPhotos.entity'; import { TripPhotos } from '../../../src/db/entities/TripPhotos.entity'; +import { TripAlbumLinks } from '../../../src/db/entities/TripAlbumLinks.entity'; import { decrypt_api_key } from '../../../src/nest/common/crypto/apiKeyCrypto'; const testDb = createSnapshotTestDb(); @@ -230,3 +231,28 @@ describe('TrekPhotoRegistrationService.deleteIfOrphan (PH10-11)', () => { expect(rawRow(id)).toBeDefined(); }); }); + +describe('M1: TripAlbumLinksRepository/TripPhotosRepository onConflict + empty-array branches', () => { + it('TripAlbumLinksRepository.insertIgnore returns true on a fresh insert and false on a repeat (onConflict doNothing); listForTrip short-circuits on an empty provider list', async () => { + const albumLinks = t.repo(TripAlbumLinks); + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const row = { trip_id: trip.id, user_id: user.id, provider: 'immich', album_id: 'alb-1', album_name: 'Album', passphrase: null }; + + expect(await albumLinks.insertIgnore(row)).toBe(true); + expect(await albumLinks.insertIgnore(row)).toBe(false); // same (trip, user, provider, album_id) — conflict + expect(await albumLinks.listForTrip(trip.id, [])).toEqual([]); + }); + + it('TripPhotosRepository.insertIgnore returns true on a fresh insert and false on a repeat (onConflict doNothing); listForTrip short-circuits on an empty provider list', async () => { + const tripPhotos = t.repo(TripPhotos); + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const photoId = await repo.getOrCreate('immich', 'photo-1', user.id); + const row = { trip_id: trip.id, user_id: user.id, photo_id: photoId, shared: 1, album_link_id: null }; + + expect(await tripPhotos.insertIgnore(row)).toBe(true); + expect(await tripPhotos.insertIgnore(row)).toBe(false); // same (trip, user, photo) — conflict + expect(await tripPhotos.listForTrip(trip.id, user.id, [])).toEqual([]); + }); +});