diff --git a/server/src/nest/plugins/host/plugin-guards.module.ts b/server/src/nest/plugins/host/plugin-guards.module.ts index 268b0033d..ae17808fd 100644 --- a/server/src/nest/plugins/host/plugin-guards.module.ts +++ b/server/src/nest/plugins/host/plugin-guards.module.ts @@ -1,6 +1,8 @@ import { Module } from '@nestjs/common'; +import { MikroOrmModule } from '@mikro-orm/nestjs'; import { PermissionsModule } from '../../permissions/permissions.module'; import { AddonsModule } from '../../addons/addons.module'; +import { Users } from '../../../db/entities/Users.entity'; import { PluginGuards } from './plugin-guards.service'; /** @@ -11,12 +13,17 @@ import { PluginGuards } from './plugin-guards.service'; * (PluginsModule -> TodoModule -> PluginsModule) and the only way out would be * forwardRef. PermissionsModule and AddonsModule are themselves leaves and * DatabaseModule is @Global, so this module imports nothing that leads back here. + * `MikroOrmModule.forFeature([Users])` (Plan 3j Task 1 — PluginGuards' own + * role lookup, PG3/PG4, now goes through UsersRepository) is the same kind of + * leaf: it hands out a repository token, not a domain module, so it doesn't + * reopen the cycle either — this module is the one that CONSTRUCTS + * PluginGuards, so it (not each importer) owns the forFeature list. * * Same shape and same reason as MailerModule, which broke * AuthModule <-> NotificationsModule. */ @Module({ - imports: [PermissionsModule, AddonsModule], + imports: [PermissionsModule, AddonsModule, MikroOrmModule.forFeature([Users])], providers: [PluginGuards], exports: [PluginGuards], }) diff --git a/server/src/nest/plugins/host/plugin-guards.service.ts b/server/src/nest/plugins/host/plugin-guards.service.ts index 274b6fccd..26eca1bb7 100644 --- a/server/src/nest/plugins/host/plugin-guards.service.ts +++ b/server/src/nest/plugins/host/plugin-guards.service.ts @@ -1,7 +1,10 @@ import { Injectable } from '@nestjs/common'; +import { InjectRepository } from '@mikro-orm/nestjs'; import { DatabaseService } from '../../database/database.service'; import { PermissionsService } from '../../permissions/permissions.service'; import { AddonsService } from '../../addons/addons.service'; +import { Users } from '../../../db/entities/Users.entity'; +import type { UsersRepository } from '../../../db/repositories/Users.repository'; import { BadParams, ForbiddenResource } from './rpc-errors'; import { num } from './rpc-params'; import type { PluginRpcContext } from './rpc-kit/types'; @@ -23,6 +26,7 @@ export class PluginGuards { private readonly db: DatabaseService, private readonly permissions: PermissionsService, private readonly addons: AddonsService, + @InjectRepository(Users) private readonly users: UsersRepository, ) {} /** @@ -69,9 +73,18 @@ export class PluginGuards { async canEditAs(action: string, tripId: number, userId: number): Promise { const trip = await this.db.canAccessTrip(tripId, userId); if (!trip) return false; - const user = this.db.prepare('SELECT role FROM users WHERE id = ?').get(userId) as { role?: string } | undefined; - if (!user) return false; - return this.permissions.checkPermission(action, user.role ?? 'user', trip.user_id, userId, trip.user_id !== userId); + // UsersRepository.getRole (PG3, Plan 3j Task 1) — `SELECT role FROM users + // WHERE id = ?`, converted. Its `string | null` return already folds "no + // row" and "row with a null role" into one value (the `role` column is + // `NOT NULL DEFAULT 'user'`, so the second case cannot occur against the + // real schema), so a null role here IS the "row is gone" refusal the + // legacy `!user` check made. The `?? 'user'` fallback below is kept + // verbatim rather than dropped, even though it is now unreachable code, + // so a future change to getRole's contract can't silently resurrect the + // old defensive gap. + const role = await this.users.getRole(userId); + if (role === null) return false; + return this.permissions.checkPermission(action, role ?? 'user', trip.user_id, userId, trip.user_id !== userId); } /** @@ -80,8 +93,13 @@ export class PluginGuards { * against yet, which is why the owner id is passed as null. */ async canCreateAs(action: string, userId: number): Promise { - const user = this.db.prepare('SELECT role FROM users WHERE id = ?').get(userId) as { role?: string } | undefined; - return this.permissions.checkPermission(action, user?.role ?? 'user', null, userId, false); + // Same converted read as canEditAs (PG4, identical statement text). No + // early refusal here, unchanged from the legacy branch: a vanished row + // falls back to role 'user' rather than refusing outright, exactly like + // `user?.role ?? 'user'` did — `trip_create`'s 'everybody' default means + // that fallback alone is enough to let the call through today. + const role = await this.users.getRole(userId); + return this.permissions.checkPermission(action, role ?? 'user', null, userId, false); } /** diff --git a/server/tests/helpers/plugin-host.ts b/server/tests/helpers/plugin-host.ts index 1b902c251..8a7d19a7b 100644 --- a/server/tests/helpers/plugin-host.ts +++ b/server/tests/helpers/plugin-host.ts @@ -270,7 +270,10 @@ export async function createPluginRpcHostFactory(dbs: DatabaseService): Promise< const reservations = new ReservationsService(dbs, permissions, budget, realtime, notificationsStub(), new ReservationsReadService(await createTestReservationsRepo(dbs.connection), await createTestReservationEndpointsRepo(dbs.connection), await createTestReservationTravelersRepo(dbs.connection)), accommodations, await createTestUnitOfWork(dbs.connection), await createTestReservationsRepo(dbs.connection), await createTestReservationEndpointsRepo(dbs.connection), await createTestReservationTravelersRepo(dbs.connection), await createTestReservationDayPositionsRepo(dbs.connection), await createTestDayAccommodationsRepo(dbs.connection), await createTestDaysRepo(dbs.connection), await createTestPlacesRepo(dbs.connection), await createTestDayAssignmentsRepo(dbs.connection), await createTestTripMembersRepo(dbs.connection), await createTestUsersRepo(dbs.connection), await createTestTripsRepo(dbs.connection), await createTestBudgetItemsRepo(dbs.connection)); const trips = new TripsService(dbs, reservations, days, permissions, budget, vacay, realtime, unsplash, generalStorage, await createTestUnitOfWork(dbs.connection), (await sharedTestOrm(dbs.connection)).em); const members = new TripMembersService(dbs, budget, new UserCleanupService(dbs, budget, await createTestUnitOfWork(dbs.connection), usersRepo, await createTestBudgetItemsRepo(dbs.connection), await createTestJourneyShareTokensRepo(dbs.connection), await createTestJourneysRepo(dbs.connection), await createTestJourneyEntriesRepo(dbs.connection), await createTestJourneyContributorsRepo(dbs.connection), await createTestShareTokensRepo(dbs.connection)), permissions, realtime, notificationsStub(), await createTestUnitOfWork(dbs.connection), await createTestTripsRepo(dbs.connection), await createTestTripMembersRepo(dbs.connection), usersRepo); - const guards = new PluginGuards(dbs, permissions, addons); + // Plan 3j Task 1 — PluginGuards' own role lookup (PG3/PG4) now goes + // through UsersRepository.getRole; `usersRepo` above is the same + // sharedTestOrm-backed repository every other service in this file uses. + const guards = new PluginGuards(dbs, permissions, addons, usersRepo); const registry = createTestPluginRegistry([ new TagsRpc(new TagsService(await createTestTagsRepo(dbs.connection))), diff --git a/server/tests/unit/budget/costs.rpc.test.ts b/server/tests/unit/budget/costs.rpc.test.ts index f675bcadc..56fc7abb1 100644 --- a/server/tests/unit/budget/costs.rpc.test.ts +++ b/server/tests/unit/budget/costs.rpc.test.ts @@ -17,6 +17,7 @@ import type { RealtimeService } from '../../../src/nest/realtime/realtime.servic import type { DatabaseService } from '../../../src/nest/database/database.service'; import type { PermissionsService } from '../../../src/nest/permissions/permissions.service'; import type { AddonsService } from '../../../src/nest/addons/addons.service'; +import type { UsersRepository } from '../../../src/db/repositories/Users.repository'; import type { TripMembershipService } from '../../../src/nest/trip-membership/trip-membership.service'; import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope'; import { makeDeps } from '../../helpers/rpc-host-deps'; @@ -34,12 +35,12 @@ function build(opts: { addonOn?: boolean; canEdit?: boolean; missing?: boolean } const realtime = { broadcast: vi.fn() } as unknown as RealtimeService & { broadcast: ReturnType }; const db = { canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)), - prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })), } as unknown as DatabaseService; const guards = new PluginGuards( db, { checkPermission: vi.fn(() => opts.canEdit ?? true) } as unknown as PermissionsService, { isAddonEnabled: vi.fn(() => opts.addonOn ?? true) } as unknown as AddonsService, + { getRole: vi.fn(async () => 'user') } as unknown as UsersRepository, ); // The leaf membership read replaced the deleted trips.bridge for listMine. const membership = { listAccessibleTripIds: vi.fn(() => [1, 2]) } as unknown as TripMembershipService; diff --git a/server/tests/unit/days/day-notes.rpc.test.ts b/server/tests/unit/days/day-notes.rpc.test.ts index 4db4e9c3d..c0d8748f8 100644 --- a/server/tests/unit/days/day-notes.rpc.test.ts +++ b/server/tests/unit/days/day-notes.rpc.test.ts @@ -16,6 +16,7 @@ import type { RealtimeService } from '../../../src/nest/realtime/realtime.servic import type { DatabaseService } from '../../../src/nest/database/database.service'; import type { PermissionsService } from '../../../src/nest/permissions/permissions.service'; import type { AddonsService } from '../../../src/nest/addons/addons.service'; +import type { UsersRepository } from '../../../src/db/repositories/Users.repository'; import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope'; import { makeDeps } from '../../helpers/rpc-host-deps'; @@ -36,12 +37,12 @@ function build(canEdit = true) { const realtime = { broadcast: vi.fn() } as unknown as RealtimeService & { broadcast: ReturnType }; const db = { canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)), - prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })), } as unknown as DatabaseService; const guards = new PluginGuards( db, { checkPermission: vi.fn(() => canEdit) } as unknown as PermissionsService, { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService, + { getRole: vi.fn(async () => 'user') } as unknown as UsersRepository, ); const rpc = new DayNotesRpc(notes, realtime, guards); const host = (...grants: string[]) => diff --git a/server/tests/unit/days/days-itinerary.rpc.test.ts b/server/tests/unit/days/days-itinerary.rpc.test.ts index dadfb134f..29a45cacc 100644 --- a/server/tests/unit/days/days-itinerary.rpc.test.ts +++ b/server/tests/unit/days/days-itinerary.rpc.test.ts @@ -20,6 +20,7 @@ import type { RealtimeService } from '../../../src/nest/realtime/realtime.servic import type { DatabaseService } from '../../../src/nest/database/database.service'; import type { PermissionsService } from '../../../src/nest/permissions/permissions.service'; import type { AddonsService } from '../../../src/nest/addons/addons.service'; +import type { UsersRepository } from '../../../src/db/repositories/Users.repository'; import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope'; import { makeDeps } from '../../helpers/rpc-host-deps'; @@ -45,10 +46,10 @@ function build(opts: { canEdit?: boolean } = {}) { const guards = new PluginGuards( { canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)), - prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })), } as unknown as DatabaseService, { checkPermission: vi.fn(() => opts.canEdit ?? true) } as unknown as PermissionsService, { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService, + { getRole: vi.fn(async () => 'user') } as unknown as UsersRepository, ); const registry = createTestPluginRegistry([new DaysRpc(days, realtime, guards), new ItineraryRpc(assignments, realtime, guards)]); const host = (...grants: string[]) => new PluginRpcHost('p', new Set(grants), makeDeps(), registry); diff --git a/server/tests/unit/files/files.rpc.test.ts b/server/tests/unit/files/files.rpc.test.ts index e50e0c343..f07431d9b 100644 --- a/server/tests/unit/files/files.rpc.test.ts +++ b/server/tests/unit/files/files.rpc.test.ts @@ -48,15 +48,18 @@ function build(opts: { file?: Record | undefined; foreign?: str } as unknown as FilesService & Record>; const db = { canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)), - // Still needed by PluginGuards' own role lookup (requireTripEdit) — unrelated to FL28. - prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })), } as unknown as DatabaseService; // FL28 — `SELECT email FROM users WHERE id = ?`, now `UsersRepository.getEmail`. - const usersRepo = { getEmail: vi.fn(async () => 'real@example.test') } as unknown as UsersRepository; + // getRole is PluginGuards' own role lookup (PG3/PG4, Plan 3j Task 1), on the + // same double — both are UsersRepository methods now. + const usersRepo = { + getEmail: vi.fn(async () => 'real@example.test'), + getRole: vi.fn(async () => 'user'), + } as unknown as UsersRepository; const permissions = { checkPermission: vi.fn((action: string) => (opts.allow ? opts.allow(action) : true)), } as unknown as PermissionsService; - const guards = new PluginGuards(db, permissions, { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService); + const guards = new PluginGuards(db, permissions, { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService, usersRepo); const storage = { getStream: vi.fn(async () => ({ stream: Readable.from(Buffer.from('hi')), @@ -289,13 +292,14 @@ describe('FilesRpc writes', () => { const f = build(); const db = { canAccessTrip: vi.fn(async () => ({ id: 1, user_id: 42 })), - // Still needed by PluginGuards' own role lookup — unrelated to FL28. - prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })), } as unknown as DatabaseService; const guards = new PluginGuards( db, { checkPermission: vi.fn(() => true) } as unknown as PermissionsService, { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService, + // PluginGuards' own role lookup — unrelated to FL28's `usersRepo` below, + // which is used for the demo-uploader email check. + { getRole: vi.fn(async () => 'user') } as unknown as UsersRepository, ); const files = { findForeignLinkTarget: vi.fn(() => null), diff --git a/server/tests/unit/packing/packing.rpc.test.ts b/server/tests/unit/packing/packing.rpc.test.ts index 0eb4c3f22..bb9b1e756 100644 --- a/server/tests/unit/packing/packing.rpc.test.ts +++ b/server/tests/unit/packing/packing.rpc.test.ts @@ -18,6 +18,7 @@ import type { RealtimeService } from '../../../src/nest/realtime/realtime.servic import type { DatabaseService } from '../../../src/nest/database/database.service'; import type { PermissionsService } from '../../../src/nest/permissions/permissions.service'; import type { AddonsService } from '../../../src/nest/addons/addons.service'; +import type { UsersRepository } from '../../../src/db/repositories/Users.repository'; import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope'; import { makeDeps } from '../../helpers/rpc-host-deps'; import { notificationsStub } from '../../helpers/notifications'; @@ -55,10 +56,10 @@ function build(opts: { canEdit?: boolean; before?: Item | undefined; updated?: I const guards = new PluginGuards( { canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)), - prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })), } as unknown as DatabaseService, { checkPermission: vi.fn(() => opts.canEdit ?? true) } as unknown as PermissionsService, { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService, + { getRole: vi.fn(async () => 'user') } as unknown as UsersRepository, ); const rpc = new PackingRpc(packing, realtime, guards); const host = (...grants: string[]) => new PluginRpcHost('p', new Set(grants), makeDeps(), createTestPluginRegistry([rpc])); diff --git a/server/tests/unit/places/places.rpc.test.ts b/server/tests/unit/places/places.rpc.test.ts index 5fc32ce80..ed80dd1c5 100644 --- a/server/tests/unit/places/places.rpc.test.ts +++ b/server/tests/unit/places/places.rpc.test.ts @@ -19,6 +19,7 @@ import type { RealtimeService } from '../../../src/nest/realtime/realtime.servic import type { DatabaseService } from '../../../src/nest/database/database.service'; import type { PermissionsService } from '../../../src/nest/permissions/permissions.service'; import type { AddonsService } from '../../../src/nest/addons/addons.service'; +import type { UsersRepository } from '../../../src/db/repositories/Users.repository'; import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope'; import { makeDeps } from '../../helpers/rpc-host-deps'; @@ -53,10 +54,10 @@ function build(opts: { canEdit?: boolean; journeyThrows?: boolean } = {}) { const guards = new PluginGuards( { canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)), - prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })), } as unknown as DatabaseService, { checkPermission: vi.fn(() => opts.canEdit ?? true) } as unknown as PermissionsService, { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService, + { getRole: vi.fn(async () => 'user') } as unknown as UsersRepository, ); // Each double covers only the methods PlacesRpc reaches for, hence the cast. const rpc = new PlacesRpc( diff --git a/server/tests/unit/plugins/addon-domains-errors.rpc.test.ts b/server/tests/unit/plugins/addon-domains-errors.rpc.test.ts index 5cb01ea42..b2c3ba838 100644 --- a/server/tests/unit/plugins/addon-domains-errors.rpc.test.ts +++ b/server/tests/unit/plugins/addon-domains-errors.rpc.test.ts @@ -19,6 +19,7 @@ import { CollectionsRpc } from '../../../src/nest/collections/collections.rpc'; import type { DatabaseService } from '../../../src/nest/database/database.service'; import type { PermissionsService } from '../../../src/nest/permissions/permissions.service'; import type { AddonsService } from '../../../src/nest/addons/addons.service'; +import type { UsersRepository } from '../../../src/db/repositories/Users.repository'; import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope'; import { makeDeps } from '../../helpers/rpc-host-deps'; @@ -45,6 +46,7 @@ function build(overrides: { db, { checkPermission: vi.fn(() => true) } as unknown as PermissionsService, { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService, + { getRole: vi.fn(async () => 'user') } as unknown as UsersRepository, ); const realtime = { broadcast: vi.fn() } as never; const registry = createTestPluginRegistry([ diff --git a/server/tests/unit/plugins/addon-gates.rpc.test.ts b/server/tests/unit/plugins/addon-gates.rpc.test.ts index c4a7d2533..80f559ca3 100644 --- a/server/tests/unit/plugins/addon-gates.rpc.test.ts +++ b/server/tests/unit/plugins/addon-gates.rpc.test.ts @@ -23,6 +23,7 @@ import { CostsRpc } from '../../../src/nest/budget/costs.rpc'; import type { DatabaseService } from '../../../src/nest/database/database.service'; import type { PermissionsService } from '../../../src/nest/permissions/permissions.service'; import type { AddonsService } from '../../../src/nest/addons/addons.service'; +import type { UsersRepository } from '../../../src/db/repositories/Users.repository'; import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope'; import { makeDeps } from '../../helpers/rpc-host-deps'; @@ -63,6 +64,7 @@ function build(addonOn: boolean) { db, { checkPermission: vi.fn(() => true) } as unknown as PermissionsService, { isAddonEnabled: vi.fn(() => addonOn) } as unknown as AddonsService, + { getRole: vi.fn(async () => 'user') } as unknown as UsersRepository, ); const registry = createTestPluginRegistry([ new CollabRpc(spyService(calls, 'collab'), { broadcast: vi.fn() } as never, guards), diff --git a/server/tests/unit/plugins/host-rpc.test.ts b/server/tests/unit/plugins/host-rpc.test.ts index eb5d6e62a..184f72dba 100644 --- a/server/tests/unit/plugins/host-rpc.test.ts +++ b/server/tests/unit/plugins/host-rpc.test.ts @@ -68,6 +68,7 @@ import { DatabaseService } from '../../../src/nest/database/database.service'; import { RealtimeService } from '../../../src/nest/realtime/realtime.service'; import type { PermissionsService } from '../../../src/nest/permissions/permissions.service'; import type { AddonsService } from '../../../src/nest/addons/addons.service'; +import type { UsersRepository } from '../../../src/db/repositories/Users.repository'; import type { NotificationsService } from '../../../src/nest/notifications/notifications.service'; import type { LlmConfigResolver } from '../../../src/nest/llm-parse/llm-config.resolver'; import type { PluginOAuthService } from '../../../src/nest/plugins/oauth/plugin-oauth.service'; @@ -106,7 +107,19 @@ const dbs = new DatabaseService(mockDb); vi.spyOn(dbs, 'canAccessTrip').mockImplementation(async (tripId, userId) => Number(tripId) === 1 && (userId === 5 || userId === 6) ? { id: 1, user_id: 5, currency: null } : undefined, ); -const guards = new PluginGuards(dbs, permissions, addons); +// Plan 3j Task 1: PluginGuards' own role lookup (PG3/PG4) now goes through +// UsersRepository.getRole, not `dbs.prepare(...)`. Same reasoning as the +// canAccessTrip spy above — a real UsersRepository would need a real +// MikroORM over this file's hand-trimmed `:memory:` schema (async init, no +// top-level await here) for no benefit: checkPermission is a blanket stub +// in this file, so no case depends on which role value flows through it. +// Stubbed against the exact seeded rows (users.ts INSERTs above) so it stays +// accurate if a future case ever does start asserting on the role argument. +const seededRoles: Record = { 5: 'trip_owner', 6: 'user', 9: 'user' }; +const usersRepo = { + getRole: vi.fn(async (id: number) => seededRoles[id] ?? null), +} as unknown as UsersRepository; +const guards = new PluginGuards(dbs, permissions, addons, usersRepo); const registry = createTestPluginRegistry([ new DbRpc(userSettings), new MetaRpc(dbs, guards), diff --git a/server/tests/unit/plugins/plugin-guards.test.ts b/server/tests/unit/plugins/plugin-guards.test.ts index 118bec8a3..7e99b1775 100644 --- a/server/tests/unit/plugins/plugin-guards.test.ts +++ b/server/tests/unit/plugins/plugin-guards.test.ts @@ -4,13 +4,20 @@ * the legacy router, because rpc-host.test.ts asserts them and shipped plugins read * them, so these tests pin the exact strings rather than just the refusal. */ -import { describe, it, expect, vi } from 'vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { PluginGuards } from '../../../src/nest/plugins/host/plugin-guards.service'; import { BadParams, ForbiddenResource } from '../../../src/nest/plugins/host/rpc-errors'; import type { DatabaseService } from '../../../src/nest/database/database.service'; -import type { PermissionsService } from '../../../src/nest/permissions/permissions.service'; +import { PermissionsService } from '../../../src/nest/permissions/permissions.service'; import type { AddonsService } from '../../../src/nest/addons/addons.service'; +import type { UsersRepository } from '../../../src/db/repositories/Users.repository'; import type { PluginRpcContext } from '../../../src/nest/plugins/host/rpc-kit/types'; +import { UnitOfWork } from '../../../src/nest/database/unit-of-work'; +import { createTestOrm, type TestOrm } from '../../helpers/test-orm'; +import { createSnapshotTestDb } from '../../helpers/db-mock'; +import { createUser } from '../../helpers/factories'; +import { AppSettings } from '../../../src/db/entities/AppSettings.entity'; +import { Users } from '../../../src/db/entities/Users.entity'; /** * The guards read `actingUserId` and nothing else off the context, so the two per-host @@ -27,23 +34,33 @@ const ctx = (actingUserId: number | undefined): PluginRpcContext => ({ }, }); -/** Trip 1 belongs to user 42 and only user 42 may reach it, mirroring rpc-host.test.ts. */ -function build(overrides: { role?: string | undefined; allow?: boolean; addonOn?: boolean } = {}) { +/** + * Trip 1 belongs to user 42 and only user 42 may reach it, mirroring rpc-host.test.ts. + * + * `overrides.role` drives the stubbed `UsersRepository.getRole` (PG3/PG4, Plan 3j + * Task 1) the same way it used to drive `db.prepare(...).get()`: omitted means a + * normal row with role 'user'; explicitly `undefined` (or `null`) means "no row", + * which `getRole`'s own `string | null` contract folds into a single `null` — the + * `users` column is `NOT NULL DEFAULT 'user'`, so a present row can never actually + * carry a null role, and `getRole` has no way to tell "row absent" from "row present, + * role null" apart even if it could. + */ +function build(overrides: { role?: string | null; allow?: boolean; addonOn?: boolean } = {}) { const db = { canAccessTrip: vi.fn(async (tripId: number, userId: number) => tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined, ), - prepare: vi.fn(() => ({ - get: () => ('role' in overrides ? (overrides.role === undefined ? undefined : { role: overrides.role }) : { role: 'user' }), - })), } as unknown as DatabaseService; + const users = { + getRole: vi.fn(async () => ('role' in overrides ? (overrides.role ?? null) : 'user')), + } as unknown as UsersRepository; const permissions = { checkPermission: vi.fn(() => overrides.allow ?? true), } as unknown as PermissionsService; const addons = { isAddonEnabled: vi.fn(() => overrides.addonOn ?? true), } as unknown as AddonsService; - return { guards: new PluginGuards(db, permissions, addons), db, permissions, addons }; + return { guards: new PluginGuards(db, permissions, addons, users), db, users, permissions, addons }; } describe('PluginGuards — tripRead', () => { @@ -120,24 +137,105 @@ describe('PluginGuards — requireTripEdit and canEditAs', () => { expect(await build({ role: undefined }).guards.canEditAs('trip_edit', 1, 42)).toBe(false); }); - it('PGUARD-013 a missing role column falls back to "user"', async () => { - const { guards, permissions } = build({ role: null as unknown as string }); + it('PGUARD-013 the repository role read actually drives the permission check — mutation proof: flipping the returned role flips the argument checkPermission sees', async () => { + const { guards, permissions } = build({ role: 'admin' }); await guards.canEditAs('trip_edit', 1, 42); - expect(permissions.checkPermission).toHaveBeenCalledWith('trip_edit', 'user', 42, 42, false); + // Seeded row is 'user' by default (see build()'s docstring); forcing the + // double to return 'admin' and seeing THAT value reach checkPermission + // proves canEditAs is reading through PluginGuards' own UsersRepository + // call, not a cached or hard-coded role. + expect(permissions.checkPermission).toHaveBeenCalledWith('trip_edit', 'admin', 42, 42, false); }); it('PGUARD-014 a non-owner member is flagged as shared', async () => { const db = { canAccessTrip: vi.fn(async () => ({ id: 1, user_id: 7 })), - prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })), } as unknown as DatabaseService; + const users = { getRole: vi.fn(async () => 'user') } as unknown as UsersRepository; const permissions = { checkPermission: vi.fn(() => true) } as unknown as PermissionsService; - const guards = new PluginGuards(db, permissions, {} as AddonsService); + const guards = new PluginGuards(db, permissions, {} as AddonsService, users); await guards.canEditAs('trip_edit', 1, 42); expect(permissions.checkPermission).toHaveBeenCalledWith('trip_edit', 'user', 7, 42, true); }); }); +describe('PluginGuards — canCreateAs', () => { + it('PGUARD-021 passes the looked-up role through with no trip-access check at all', async () => { + const { guards, permissions } = build({ role: 'admin', allow: true }); + expect(await guards.canCreateAs('trip_create', 42)).toBe(true); + expect(permissions.checkPermission).toHaveBeenCalledWith('trip_create', 'admin', null, 42, false); + }); + + it('PGUARD-022 a user id with no matching row never throws and falls back to role "user", unchanged from the legacy user?.role ?? "user" branch (no early refusal exists here, unlike canEditAs)', async () => { + const { guards, permissions } = build({ role: undefined }); + await expect(guards.canCreateAs('trip_create', 999)).resolves.not.toThrow(); + expect(permissions.checkPermission).toHaveBeenCalledWith('trip_create', 'user', null, 999, false); + }); + + it('PGUARD-023 mutation proof: flipping the returned role flips the argument checkPermission sees', async () => { + const { guards, permissions } = build({ role: 'admin' }); + await guards.canCreateAs('trip_create', 42); + expect(permissions.checkPermission).toHaveBeenCalledWith('trip_create', 'admin', null, 42, false); + }); +}); + +/** + * The role×action×ownership matrix the sql-inventory calls for (§3), run through the + * REAL UsersRepository (a real MikroORM repository, default allowGlobalContext: true — + * these are direct, unwrapped calls, same TRAP-list allowance test-orm.ts documents) + * and the REAL PermissionsService (default in-memory permission levels, no stored + * overrides), not the stubbed doubles `build()` uses above. This is what actually + * proves PG3/PG4's conversion didn't change plugin-write authorization: a role that + * should fail a check still fails it, a role that should pass still passes, and + * physically changing the STORED row (not a test double) flips the result. + */ +describe('PluginGuards — canEditAs/canCreateAs against a real UsersRepository + PermissionsService', () => { + let testDb: ReturnType; + let orm: TestOrm; + let guards: PluginGuards; + let memberId: number; + const ownerId = 1; + + beforeEach(async () => { + testDb = createSnapshotTestDb(); + orm = await createTestOrm(testDb); + const permissions = new PermissionsService(orm.repo(AppSettings), new UnitOfWork(orm.em)); + const db = { + canAccessTrip: vi.fn(async (tripId: number) => (tripId === 1 ? { id: 1, user_id: ownerId } : undefined)), + } as unknown as DatabaseService; + // The permissions cache is module-scoped (permissions-cache.ts), not + // per-instance — invalidate before every case so a stored override from + // another describe block in this same worker can't leak in. + permissions.invalidatePermissionsCache(); + guards = new PluginGuards(db, permissions, {} as AddonsService, orm.repo(Users)); + createUser(testDb, { role: 'user' }); // id 1, the trip owner — unused by these cases directly + memberId = createUser(testDb, { role: 'user' }).user.id; // id 2, a non-owner trip member + }); + + afterEach(async () => { + await orm.close(); + testDb.close(); + }); + + it('PGUARD-024 a member whose role lacks trip_delete (trip_owner-only by default) is refused', async () => { + expect(await guards.canEditAs('trip_delete', 1, memberId)).toBe(false); + }); + + it('PGUARD-025 mutation proof: promoting that SAME member to admin in the real users table flips PGUARD-024 to pass', async () => { + testDb.prepare('UPDATE users SET role = ? WHERE id = ?').run('admin', memberId); + expect(await guards.canEditAs('trip_delete', 1, memberId)).toBe(true); + }); + + it('PGUARD-026 a non-member is refused regardless of role (trip access is checked first)', async () => { + expect(await guards.canEditAs('trip_delete', 999, memberId)).toBe(false); + }); + + it('PGUARD-027 canCreateAs: a real user id with no matching row never throws, and trip_create\'s "everybody" default lets it through — the legacy fallback preserved, not a new refusal', async () => { + const vanishedId = memberId + 1000; + await expect(guards.canCreateAs('trip_create', vanishedId)).resolves.toBe(true); + }); +}); + describe('PluginGuards — requireAddon', () => { it('PGUARD-015 an enabled addon passes', async () => { await expect(build({ addonOn: true }).guards.requireAddon('budget', 'costs')).resolves.not.toThrow(); diff --git a/server/tests/unit/plugins/request-context.test.ts b/server/tests/unit/plugins/request-context.test.ts index 17c6662c3..7a4a8da39 100644 --- a/server/tests/unit/plugins/request-context.test.ts +++ b/server/tests/unit/plugins/request-context.test.ts @@ -41,6 +41,7 @@ import { UnitOfWork } from '../../../src/nest/database/unit-of-work'; import { RpcRateLimiter, DEFAULT_RPC_LIMIT } from '../../../src/nest/plugins/host/rate-limit'; import { createTestOrm, type TestOrm } from '../../helpers/test-orm'; import { AppSettings } from '../../../src/db/entities/AppSettings.entity'; +import { Users } from '../../../src/db/entities/Users.entity'; import type { PluginRpcHost } from '../../../src/nest/plugins/host/rpc-host'; import type { RpcRequest, RpcResponse, RpcError } from '../../../src/nest/plugins/protocol/envelope'; import type { EntityManager } from '@mikro-orm/core'; @@ -69,7 +70,13 @@ beforeAll(async () => { t = await createTestOrm(testDb, { allowGlobalContext: false }); const dbs = new DatabaseService(testDb); permissions = new PermissionsService(t.repo(AppSettings), new UnitOfWork(t.em)); - guards = new PluginGuards(dbs, permissions, await createTestAddonsService(testDb, dbs)); + // Plan 3j Task 1: PluginGuards' own role lookup (canCreateAs, PG4) now goes + // through UsersRepository.getRole — a REAL repository bound to `t.em` + // (allowGlobalContext: false, same as `permissions`' AppSettingsRepository + // above), not a stub, because this suite's whole point is proving that + // read fails outside withRequestContext and succeeds inside it (D6/C3). + // A mocked UsersRepository would defeat that regression coverage. + guards = new PluginGuards(dbs, permissions, await createTestAddonsService(testDb, dbs), t.repo(Users)); userId = createUser(testDb, { role: 'user' }).user.id; // An admin has tightened trip_create from its 'everybody' default. testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('perm_trip_create', 'admin')").run(); diff --git a/server/tests/unit/plugins/rpc-fallbacks.test.ts b/server/tests/unit/plugins/rpc-fallbacks.test.ts index 60a19a6ff..11d34877d 100644 --- a/server/tests/unit/plugins/rpc-fallbacks.test.ts +++ b/server/tests/unit/plugins/rpc-fallbacks.test.ts @@ -27,6 +27,7 @@ import type { EntityManager } from '@mikro-orm/core'; import type { DatabaseService } from '../../../src/nest/database/database.service'; import type { PermissionsService } from '../../../src/nest/permissions/permissions.service'; import type { AddonsService } from '../../../src/nest/addons/addons.service'; +import type { UsersRepository } from '../../../src/db/repositories/Users.repository'; import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope'; import { makeDeps } from '../../helpers/rpc-host-deps'; import { schemaMessage } from '../../../src/nest/plugins/host/rpc-params'; @@ -65,6 +66,7 @@ function guardsFor() { db, { checkPermission: vi.fn(() => true) } as unknown as PermissionsService, { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService, + { getRole: vi.fn(async () => 'user') } as unknown as UsersRepository, ), }; } diff --git a/server/tests/unit/plugins/rpc-host-inv-strip.test.ts b/server/tests/unit/plugins/rpc-host-inv-strip.test.ts index 718d1e63f..27611051a 100644 --- a/server/tests/unit/plugins/rpc-host-inv-strip.test.ts +++ b/server/tests/unit/plugins/rpc-host-inv-strip.test.ts @@ -39,7 +39,7 @@ const tripsRegistry = () => { canAccessTrip: async (tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined), prepare: () => ({ get: () => ({ id: 1, title: 'Japan' }), all: () => [] }), } as unknown as DatabaseService; - const guards = new PluginGuards(db, {} as never, {} as never); + const guards = new PluginGuards(db, {} as never, {} as never, {} as never); // Plan 3c Task 7: trips.getById (RP1) now reads through // `EntityManager.getRepository(Trips).findRaw(...)`, not `db.prepare(...)`. const em = { diff --git a/server/tests/unit/reservations/bookings.rpc.test.ts b/server/tests/unit/reservations/bookings.rpc.test.ts index 806216f11..214e09b31 100644 --- a/server/tests/unit/reservations/bookings.rpc.test.ts +++ b/server/tests/unit/reservations/bookings.rpc.test.ts @@ -23,6 +23,7 @@ import type { RealtimeService } from '../../../src/nest/realtime/realtime.servic import type { DatabaseService } from '../../../src/nest/database/database.service'; import type { PermissionsService } from '../../../src/nest/permissions/permissions.service'; import type { AddonsService } from '../../../src/nest/addons/addons.service'; +import type { UsersRepository } from '../../../src/db/repositories/Users.repository'; import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope'; import { makeDeps } from '../../helpers/rpc-host-deps'; @@ -81,7 +82,6 @@ function build(opts: { canEdit?: boolean; cascade?: boolean; stop?: boolean; see const guards = new PluginGuards( { canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)), - prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })), } as unknown as DatabaseService, { checkPermission: vi.fn((action: string) => { @@ -90,6 +90,7 @@ function build(opts: { canEdit?: boolean; cascade?: boolean; stop?: boolean; see }), } as unknown as PermissionsService, { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService, + { getRole: vi.fn(async () => 'user') } as unknown as UsersRepository, ); const registry = createTestPluginRegistry([ new ReservationsRpc(reservations, realtime, guards), diff --git a/server/tests/unit/todo/todo.rpc.test.ts b/server/tests/unit/todo/todo.rpc.test.ts index d0433c119..ac5f537dd 100644 --- a/server/tests/unit/todo/todo.rpc.test.ts +++ b/server/tests/unit/todo/todo.rpc.test.ts @@ -15,6 +15,7 @@ import type { RealtimeService } from '../../../src/nest/realtime/realtime.servic import type { DatabaseService } from '../../../src/nest/database/database.service'; import type { PermissionsService } from '../../../src/nest/permissions/permissions.service'; import type { AddonsService } from '../../../src/nest/addons/addons.service'; +import type { UsersRepository } from '../../../src/db/repositories/Users.repository'; import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope'; import { makeDeps } from '../../helpers/rpc-host-deps'; @@ -33,10 +34,10 @@ function build(canEdit = true) { const guards = new PluginGuards( { canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)), - prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })), } as unknown as DatabaseService, permissions, { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService, + { getRole: vi.fn(async () => 'user') } as unknown as UsersRepository, ); const rpc = new TodoRpc(todos, realtime, guards); const host = (...grants: string[]) => diff --git a/server/tests/unit/trips/trips.rpc.test.ts b/server/tests/unit/trips/trips.rpc.test.ts index 194b1bd74..4a992b850 100644 --- a/server/tests/unit/trips/trips.rpc.test.ts +++ b/server/tests/unit/trips/trips.rpc.test.ts @@ -27,6 +27,7 @@ import type { RealtimeService } from '../../../src/nest/realtime/realtime.servic import type { DatabaseService } from '../../../src/nest/database/database.service'; import type { PermissionsService } from '../../../src/nest/permissions/permissions.service'; import type { AddonsService } from '../../../src/nest/addons/addons.service'; +import type { UsersRepository } from '../../../src/db/repositories/Users.repository'; import type { RpcRequest, RpcError } from '../../../src/nest/plugins/protocol/envelope'; import { makeDeps } from '../../helpers/rpc-host-deps'; import { Trips } from '../../../src/db/entities/Trips.entity'; @@ -66,12 +67,12 @@ export function build(opts: { allow?: (action: string) => boolean; updateThrows? } as unknown as TripMembersService & Record>; const membership = { joinTripAsMember: vi.fn(() => ({ joined: true })) } as unknown as TripMembershipService & Record>; // `PluginGuards.canEditAs` (nest/plugins/host/, out of this task's scope) - // still calls `db.prepare('SELECT role FROM users WHERE id = ?')` for its - // own per-field permission role lookup — unrelated to RP4's now-converted - // `SELECT role FROM users WHERE id = ?` inside `TripsRpc.update` itself. + // also reads `UsersRepository.getRole` now (Plan 3j Task 1) for its own + // per-field permission role lookup — the SAME repository method RP4 below + // uses for `TripsRpc.update` itself, but through PluginGuards' own + // constructor param, stubbed separately just below. const db = { canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)), - prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })), } as unknown as DatabaseService; // Plan 3c Task 7: RP1-RP6's SQL-text-keyed `db.prepare` stub is gone — // every raw statement moved to a repository method, so this is a @@ -107,7 +108,12 @@ export function build(opts: { allow?: (action: string) => boolean; updateThrows? } as unknown as EntityManager; const permissions = { checkPermission: vi.fn((a: string) => (opts.allow ? opts.allow(a) : true)) } as unknown as PermissionsService; const realtime = { broadcast: vi.fn() } as unknown as RealtimeService & { broadcast: ReturnType }; - const guards = new PluginGuards(db, permissions, { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService); + const guards = new PluginGuards( + db, + permissions, + { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService, + { getRole: vi.fn(async () => 'user') } as unknown as UsersRepository, + ); const rpc = new TripsRpc(trips, reservations, days, membership, realtime, guards, accommodations, roster, em); const host = (...grants: string[]) => new PluginRpcHost('p', new Set(grants.length ? grants : ALL_TRIP_GRANTS), makeDeps(), createTestPluginRegistry([rpc])); @@ -171,10 +177,14 @@ describe('TripsRpc reads', () => { } as unknown as EntityManager; const db = { canAccessTrip: vi.fn(async (tripId: number, userId: number) => (tripId === 1 && userId === 42 ? { id: 1, user_id: 42 } : undefined)), - prepare: vi.fn(() => ({ get: () => ({ role: 'user' }) })), } as unknown as DatabaseService; const permissions = { checkPermission: vi.fn(() => true) } as unknown as PermissionsService; - const guards = new PluginGuards(db, permissions, { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService); + const guards = new PluginGuards( + db, + permissions, + { isAddonEnabled: vi.fn(() => true) } as unknown as AddonsService, + { getRole: vi.fn(async () => 'user') } as unknown as UsersRepository, + ); const rpc = new TripsRpc(f.trips, f.reservations, f.days, f.membership, f.realtime, guards, f.accommodations, f.roster, em); const host = new PluginRpcHost('p', new Set(ALL_TRIP_GRANTS), makeDeps(), createTestPluginRegistry([rpc]));