Skip to content

armgit / TREK

Public Imported from GitHub
0

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

Make ownership a guard instead of four hand-written checks

Maurice45916453163c
diff --git a/server/src/nest/permissions/permissions.module.ts b/server/src/nest/permissions/permissions.module.ts
index 0a6256683..4794cbab2 100644
--- a/server/src/nest/permissions/permissions.module.ts
+++ b/server/src/nest/permissions/permissions.module.ts
@@ -1,15 +1,16 @@
import { Module } from '@nestjs/common';
import { PermissionsService } from './permissions.service';
import { TripAccessGuard } from './trip-access.guard';
+import { TripOwnerGuard } from './trip-owner.guard';
/** Cross-cutting permissions domain (Wave 2). No controller/MCP surface of its
* own — the admin HTTP surface stays with AdminModule. Exports
- * PermissionsService for the 17 in-container consumers and TripAccessGuard for
- * every trip-scoped controller; deliberately NOT @Global so e2e TestingModules
+ * PermissionsService for the 17 in-container consumers and TripAccessGuard/TripOwnerGuard
+ * for every trip-scoped controller; deliberately NOT @Global so e2e TestingModules
* resolve it transitively through each consumer's explicit import. Registered in
* AppModule. */
@Module({
- providers: [PermissionsService, TripAccessGuard],
- exports: [PermissionsService, TripAccessGuard],
+ providers: [PermissionsService, TripAccessGuard, TripOwnerGuard],
+ exports: [PermissionsService, TripAccessGuard, TripOwnerGuard],
})
export class PermissionsModule {}
diff --git a/server/src/nest/permissions/trip-owner.guard.ts b/server/src/nest/permissions/trip-owner.guard.ts
new file mode 100644
index 000000000..a69ec9675
--- /dev/null
+++ b/server/src/nest/permissions/trip-owner.guard.ts
@@ -0,0 +1,81 @@
+import { CanActivate, ExecutionContext, HttpException, Injectable, SetMetadata } from '@nestjs/common';
+import { Reflector } from '@nestjs/core';
+import type { Request } from 'express';
+import { DatabaseService, type TripAccess } from '../database/database.service';
+import { TRIP_REQUEST_KEY } from './trip-access.guard';
+import type { User } from '../../types';
+
+/** Metadata `@RequireTripOwner()` writes and the guard reads. */
+export const TRIP_OWNER_KEY = 'trekTripOwner';
+
+export interface TripOwnerOptions {
+ /** Route param holding the trip id. Defaults to `tripId`; the trip routes use `id`. */
+ param?: string;
+}
+
+/**
+ * Owner-only, with the refusal message the route has always sent.
+ *
+ * The message is part of the metadata rather than a constant because the two
+ * places that need this today say different things, and both strings are
+ * asserted: 'Only the owner can transfer ownership' and 'Only the owner can
+ * manage guests'.
+ */
+export const RequireTripOwner = (message: string, options: TripOwnerOptions = {}) =>
+ SetMetadata(TRIP_OWNER_KEY, { message, ...options });
+
+type TripRequest = Request & { user?: User; [TRIP_REQUEST_KEY]?: TripAccess };
+
+/**
+ * Requires that the caller *owns* the trip, not merely that they may edit it.
+ *
+ * Handing a trip over and creating or deleting guests are the two things a
+ * collaborator must never do, however generous the trip's permission settings
+ * are. Until now each route asserted `access.user_id !== user.id` by hand, and
+ * `src/nest/**` had no owner guard at all.
+ *
+ * It deliberately does NOT consult PermissionsService. `checkPermission` returns
+ * true for every admin, and the permission actions are admin-lowerable, so
+ * routing ownership through it would quietly hand any admin the ability to
+ * transfer other people's trips — the opposite of what these four routes are
+ * for. The check here is the literal one the routes did: `trip.user_id === user.id`.
+ *
+ * Absent access is a 404, never a 403, for the same reason TripAccessGuard does
+ * it that way: a 403 would confirm the id exists to someone who has no business
+ * knowing. A 403 only ever goes to somebody who can already see the trip.
+ */
+@Injectable()
+export class TripOwnerGuard implements CanActivate {
+ constructor(
+ private readonly db: DatabaseService,
+ private readonly reflector: Reflector,
+ ) {}
+
+ canActivate(context: ExecutionContext): boolean {
+ const request = context.switchToHttp().getRequest<TripRequest>();
+ const user = request.user;
+ // JwtAuthGuard runs first and 401s an anonymous request, so a missing user
+ // here means the route was wired without it. Refuse rather than read
+ // `user.id` off undefined and turn a wiring mistake into a 500.
+ if (!user) throw new HttpException({ error: 'Unauthorized' }, 401);
+
+ const meta = this.reflector.getAllAndOverride<{ message: string; param?: string } | undefined>(
+ TRIP_OWNER_KEY,
+ [context.getHandler(), context.getClass()],
+ );
+ const message = meta?.message ?? 'Only the trip owner can do this';
+
+ // Reuse the row TripAccessGuard already resolved when the route carries both,
+ // so a request never costs two lookups of the same trip.
+ let trip = request[TRIP_REQUEST_KEY];
+ if (!trip) {
+ const tripId = Number((request.params as Record<string, string>)?.[meta?.param ?? 'tripId']);
+ trip = Number.isFinite(tripId) ? this.db.canAccessTrip(tripId, user.id) ?? undefined : undefined;
+ if (trip) request[TRIP_REQUEST_KEY] = trip;
+ }
+ if (!trip) throw new HttpException({ error: 'Trip not found' }, 404);
+
+ if (trip.user_id !== user.id) throw new HttpException({ error: message }, 403);
+ return true;
+ }
+}
diff --git a/server/src/nest/places/places.controller.ts b/server/src/nest/places/places.controller.ts
index 3acb5727c..b0c2183fe 100644
--- a/server/src/nest/places/places.controller.ts
+++ b/server/src/nest/places/places.controller.ts
@@ -24,6 +24,7 @@ import { PlacesService } from './places.service';
import { isUpdateConflict } from '../common/conflictResult';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
+import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
import { PLACE_IMAGE_UPLOAD } from '../common/place-image-upload';
import { placeImageUrl } from './place-image';
import {
@@ -106,6 +107,7 @@ export class PlacesController {
}
@Get()
+ @UseGuards(TripAccessGuard)
list(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@@ -113,7 +115,6 @@ export class PlacesController {
@Query('category') category?: string,
@Query('tag') tag?: string,
) {
- this.requireTrip(tripId, user);
return { places: this.places.list(tripId, { search, category, tag }) };
}
@@ -291,8 +292,8 @@ export class PlacesController {
}
@Get(':id')
+ @UseGuards(TripAccessGuard)
get(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string) {
- this.requireTrip(tripId, user);
const place = this.places.get(tripId, id);
if (!place) {
throw new HttpException({ error: 'Place not found' }, 404);
@@ -352,8 +353,8 @@ export class PlacesController {
}
@Delete(':id/rating')
+ @UseGuards(TripAccessGuard)
unrate(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) {
- this.requireTrip(tripId, user);
const place = this.places.rate(tripId, id, user.id, null);
if (!place) {
throw new HttpException({ error: 'Place not found' }, 404);
@@ -363,8 +364,8 @@ export class PlacesController {
}
@Get(':id/image')
+ @UseGuards(TripAccessGuard)
async image(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string) {
- this.requireTrip(tripId, user);
try {
const result = await this.places.searchImage(tripId, id, user.id);
if ('error' in result) {
@@ -407,9 +408,9 @@ export class PlacesController {
}
@Delete(':id')
+ @UseGuards(TripAccessGuard)
+ @RequirePermission('place_edit')
remove(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) {
- const trip = this.requireTrip(tripId, user);
- this.requireEdit(trip, user);
// Scope the id to the trip before the hook (see bulkDelete), then sync the
// journey ahead of the actual delete.
if (!this.places.get(tripId, id)) {
diff --git a/server/src/nest/trip-members/trip-members.controller.ts b/server/src/nest/trip-members/trip-members.controller.ts
index f95a11dd8..eef37bf91 100644
--- a/server/src/nest/trip-members/trip-members.controller.ts
+++ b/server/src/nest/trip-members/trip-members.controller.ts
@@ -17,6 +17,7 @@ import type { User } from '../../types';
import { TripMembersService } from './trip-members.service';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { CurrentUser } from '../auth/current-user.decorator';
+import { RequireTripOwner, TripOwnerGuard } from '../permissions/trip-owner.guard';
import { getClientIp } from '../audit/client-ip';
import { AuditService } from '../audit/audit.service';
import { NotFoundError, ValidationError } from '../common/domain-errors';
@@ -34,6 +35,11 @@ import { TripAddMemberDto, TripTransferOwnershipDto, TripCreateGuestDto, TripRen
* here would answer the trip 404 before the body pipe could answer its 400, and
* the e2e cases pin that order. The inline canAccessTrip checks are the ones
* that moved, unchanged.
+ *
+ * The four owner-only routes are the exception: they carry TripOwnerGuard, which
+ * replaces the hand-written `access.user_id !== user.id` each of them had. Their
+ * bodies are ids and names, so the 400-before-404 ordering does not arise —
+ * transfer is the one with a DTO, and its own e2e asserts the 404 first.
*/
@Controller('api/trips')
@UseGuards(JwtAuthGuard)
@@ -87,6 +93,8 @@ export class TripMembersController {
}
@Post(':id/transfer')
+ @UseGuards(TripOwnerGuard)
+ @RequireTripOwner('Only the owner can transfer ownership', { param: 'id' })
transferOwnership(
@CurrentUser() user: User,
@Param('id') id: string,
@@ -95,15 +103,6 @@ export class TripMembersController {
@Headers('x-socket-id') socketId?: string,
) {
const { newOwnerId } = body;
- const access = this.roster.canAccessTrip(id, user.id);
- if (!access) {
- throw new HttpException({ error: 'Trip not found' }, 404);
- }
- // Owner-only: handing over a trip is reserved for its actual owner, not just
- // anyone who can manage members.
- if (access.user_id !== user.id) {
- throw new HttpException({ error: 'Only the owner can transfer ownership' }, 403);
- }
try {
const result = this.roster.transferOwnership(id, newOwnerId, user.id);
this.audit.writeAudit({ userId: user.id, action: 'trip.transfer_ownership', ip: getClientIp(req), details: { tripId: Number(id), trip: result.tripTitle, from: result.fromEmail, to: result.toEmail } });
@@ -119,21 +118,11 @@ export class TripMembersController {
}
}
- /** Loads the trip or throws 404, then asserts the caller is its owner (guest CRUD, #1362). */
- private requireOwner(id: string, user: User): void {
- const access = this.roster.canAccessTrip(id, user.id);
- if (!access) {
- throw new HttpException({ error: 'Trip not found' }, 404);
- }
- if (access.user_id !== user.id) {
- throw new HttpException({ error: 'Only the owner can manage guests' }, 403);
- }
- }
-
@Post(':id/guests')
@HttpCode(201)
+ @UseGuards(TripOwnerGuard)
+ @RequireTripOwner('Only the owner can manage guests', { param: 'id' })
createGuest(@CurrentUser() user: User, @Param('id') id: string, @Body() body: TripCreateGuestDto) {
- this.requireOwner(id, user);
// Whitespace-only names still 400 with the legacy body — the service throws
// ValidationError('Guest name is required') after trimming.
try {
@@ -146,8 +135,9 @@ export class TripMembersController {
}
@Put(':id/guests/:userId')
+ @UseGuards(TripOwnerGuard)
+ @RequireTripOwner('Only the owner can manage guests', { param: 'id' })
renameGuest(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string, @Body() body: TripRenameGuestDto) {
- this.requireOwner(id, user);
try {
if (!this.roster.renameGuest(id, parseInt(userId), body.name)) {
throw new HttpException({ error: 'Guest not found' }, 404);
@@ -161,8 +151,9 @@ export class TripMembersController {
}
@Delete(':id/guests/:userId')
+ @UseGuards(TripOwnerGuard)
+ @RequireTripOwner('Only the owner can manage guests', { param: 'id' })
deleteGuest(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string) {
- this.requireOwner(id, user);
if (!this.roster.deleteGuest(id, parseInt(userId))) {
throw new HttpException({ error: 'Guest not found' }, 404);
}
diff --git a/server/tests/e2e/places.e2e.test.ts b/server/tests/e2e/places.e2e.test.ts
index 978cd926f..0978166f9 100644
--- a/server/tests/e2e/places.e2e.test.ts
+++ b/server/tests/e2e/places.e2e.test.ts
@@ -264,4 +264,40 @@ describe('Places e2e (real auth guard + temp SQLite)', () => {
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Trip not found' });
});
+
+ // The first attempt at guarding places lost the delete permission check and
+ // answered 200 where 403 belonged. This asserts the argument list, not just
+ // the status, so a check that happens to return the right code for the wrong
+ // reason still fails.
+ it('DELETE :id demands place_edit, by name', async () => {
+ db.prepare("INSERT INTO places (id, trip_id, name) VALUES (11, 5, 'Guarded')").run();
+ checkPermission.mockReturnValue(false);
+
+ const res = await request(server).delete('/api/trips/5/places/11').set('Cookie', sessionCookie(1));
+ expect(res.status).toBe(403);
+ expect(res.body).toEqual({ error: 'No permission' });
+ expect(checkPermission).toHaveBeenCalledWith('place_edit', 'user', 1, 1, false);
+ expect(db.prepare('SELECT id FROM places WHERE id = 11').get()).toBeDefined();
+ });
+
+ it('the guarded read routes 404 an inaccessible trip without touching the place', async () => {
+ canAccessTrip.mockReturnValue(undefined);
+ for (const path of ['/api/trips/5/places/9', '/api/trips/5/places/9/image']) {
+ const res = await request(server).get(path).set('Cookie', sessionCookie(1));
+ expect(res.status).toBe(404);
+ expect(res.body).toEqual({ error: 'Trip not found' });
+ }
+ const del = await request(server).delete('/api/trips/5/places/9').set('Cookie', sessionCookie(1));
+ expect(del.status).toBe(404);
+ expect(del.body).toEqual({ error: 'Trip not found' });
+ });
+
+ // The reason places keeps its inline checks on the write routes: a guard runs
+ // before the pipe, so guarding create would answer 404 where the suite above
+ // pins a 400. This is the non-regression pin for that decision.
+ it('a bad create body still 400s ahead of the trip 404', async () => {
+ canAccessTrip.mockReturnValue(undefined);
+ const res = await request(server).post('/api/trips/5/places').set('Cookie', sessionCookie(1)).send({});
+ expect(res.status).toBe(400);
+ });
});
diff --git a/server/tests/unit/nest/places.controller.test.ts b/server/tests/unit/nest/places.controller.test.ts
index b539357d8..973f798c4 100644
--- a/server/tests/unit/nest/places.controller.test.ts
+++ b/server/tests/unit/nest/places.controller.test.ts
@@ -39,8 +39,10 @@ async function thrownAsync(fn: () => Promise<unknown>): Promise<{ status: number
beforeEach(() => vi.spyOn(console, 'error').mockImplementation(() => {}));
describe('PlacesController (parity with the legacy /api/trips/:tripId/places route)', () => {
- it('GET / lists with filters; 404 when trip not accessible', () => {
- expect(thrown(() => new PlacesController(svc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) }), new RuntimeEnvService()).list(user, '5'))).toEqual({ status: 404, body: { error: 'Trip not found' } });
+ // The trip 404 for this handler is TripAccessGuard's now (see
+ // trip-access.guard.test.ts and the places e2e), so it is no longer reachable
+ // by calling the method directly.
+ it('GET / lists with filters', () => {
const list = vi.fn().mockReturnValue([{ id: 1 }]);
expect(new PlacesController(svc({ list } as Partial<PlacesService>), new RuntimeEnvService()).list(user, '5', 'beach', 'cat', 'tag')).toEqual({ places: [{ id: 1 }] });
expect(list).toHaveBeenCalledWith('5', { search: 'beach', category: 'cat', tag: 'tag' });
diff --git a/server/tests/unit/nest/trip-members.controller.test.ts b/server/tests/unit/nest/trip-members.controller.test.ts
index 5b21d302f..06748b868 100644
--- a/server/tests/unit/nest/trip-members.controller.test.ts
+++ b/server/tests/unit/nest/trip-members.controller.test.ts
@@ -94,16 +94,11 @@ describe('members', () => {
});
describe('POST /:id/transfer (#973)', () => {
- it('404 without trip access', () => {
- const s = svc({ canAccessTrip: vi.fn().mockReturnValue(undefined) });
- expect(thrown(() => tc(s).transferOwnership(user, '9', { newOwnerId: 2 }, req))).toEqual({ status: 404, body: { error: 'Trip not found' } });
- });
- it('403 when the requester is not the owner', () => {
- // access.user_id (5) differs from the requesting user (1)
- const s = svc({ canAccessTrip: vi.fn().mockReturnValue({ user_id: 5 }) });
- expect(thrown(() => tc(s).transferOwnership(user, '9', { newOwnerId: 2 }, req))).toEqual({ status: 403, body: { error: 'Only the owner can transfer ownership' } });
- });
+ // The 404-without-access and 403-for-a-non-owner cases moved to
+ // trip-owner.guard.test.ts (OWNER-001..010) with the check itself: the route
+ // carries @RequireTripOwner('Only the owner can transfer ownership') now, and
+ // a guard runs before the handler this file constructs by hand.
it('a non-numeric newOwnerId 400s in the ZodValidationPipe', () => {
// The hand-rolled 'newOwnerId is required' 400 moved into the global
@@ -131,10 +126,8 @@ describe('POST /:id/transfer (#973)', () => {
});
describe('guests (#1362)', () => {
- it('404 without access, 403 for a non-owner, 400 without a name; else creates', () => {
- expect(thrown(() => tc(svc({ canAccessTrip: vi.fn().mockReturnValue(undefined) })).createGuest(user, '9', { name: 'Anna' }))).toEqual({ status: 404, body: { error: 'Trip not found' } });
- // access.user_id (5) ≠ requester (1) → not the owner
- expect(thrown(() => tc(svc({ canAccessTrip: vi.fn().mockReturnValue({ user_id: 5 }) })).createGuest(user, '9', { name: 'Anna' }))).toEqual({ status: 403, body: { error: 'Only the owner can manage guests' } });
+ // Ownership is TripOwnerGuard's job now (OWNER-002 pins the exact message).
+ it('400 without a name; else creates', () => {
// A whitespace-only name still 400s with the legacy body — the service
// throws after trimming (the schema only enforces 1..50 chars).
const wsGuest = svc({ createGuest: vi.fn().mockImplementation(() => { throw new ValidationError('Guest name is required'); }) } as Partial<TripMembersService>);
@@ -145,16 +138,14 @@ describe('guests (#1362)', () => {
expect(createGuest).toHaveBeenCalledWith('9', 'Anna', user.id);
});
- it('rename: 403 non-owner, 404 when the guest is missing, else success', () => {
- expect(thrown(() => tc(svc({ canAccessTrip: vi.fn().mockReturnValue({ user_id: 5 }) })).renameGuest(user, '9', '7', { name: 'Bob' }))).toEqual({ status: 403, body: { error: 'Only the owner can manage guests' } });
+ it('rename: 404 when the guest is missing, else success', () => {
const miss = svc({ renameGuest: vi.fn().mockReturnValue(false) } as Partial<TripMembersService>);
expect(thrown(() => tc(miss).renameGuest(user, '9', '7', { name: 'Bob' }))).toEqual({ status: 404, body: { error: 'Guest not found' } });
const ok = svc({ renameGuest: vi.fn().mockReturnValue(true) } as Partial<TripMembersService>);
expect(tc(ok).renameGuest(user, '9', '7', { name: 'Bob' })).toEqual({ success: true });
});
- it('delete: 403 non-owner, 404 when the guest is missing, else success', () => {
- expect(thrown(() => tc(svc({ canAccessTrip: vi.fn().mockReturnValue({ user_id: 5 }) })).deleteGuest(user, '9', '7'))).toEqual({ status: 403, body: { error: 'Only the owner can manage guests' } });
+ it('delete: 404 when the guest is missing, else success', () => {
const miss = svc({ deleteGuest: vi.fn().mockReturnValue(false) } as Partial<TripMembersService>);
expect(thrown(() => tc(miss).deleteGuest(user, '9', '7'))).toEqual({ status: 404, body: { error: 'Guest not found' } });
const ok = svc({ deleteGuest: vi.fn().mockReturnValue(true) } as Partial<TripMembersService>);
diff --git a/server/tests/unit/nest/trip-owner.guard.test.ts b/server/tests/unit/nest/trip-owner.guard.test.ts
new file mode 100644
index 000000000..5debb93a0
--- /dev/null
+++ b/server/tests/unit/nest/trip-owner.guard.test.ts
@@ -0,0 +1,151 @@
+/**
+ * TripOwnerGuard — "only the owner", which `src/nest/**` had no guard for at all.
+ * Ownership was asserted by hand in four routes, and the two things it protects
+ * (handing a trip over, creating and deleting guests) are exactly the ones a
+ * collaborator must never do however generous the trip's permissions are.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import { HttpException } from '@nestjs/common';
+import { Reflector } from '@nestjs/core';
+import { TRIP_REQUEST_KEY } from '../../../src/nest/permissions/trip-access.guard';
+import {
+ RequireTripOwner,
+ TRIP_OWNER_KEY,
+ TripOwnerGuard,
+} from '../../../src/nest/permissions/trip-owner.guard';
+import type { DatabaseService } from '../../../src/nest/database/database.service';
+import type { User } from '../../../src/types';
+
+const owner = { id: 42, role: 'user' } as User;
+const member = { id: 7, role: 'user' } as User;
+const admin = { id: 99, role: 'admin' } as User;
+/** Trip 5 belongs to user 42; user 7 is a member. Nobody else can reach it. */
+const TRIP = { id: 5, user_id: 42 };
+
+function makeGuard(meta: { message: string; param?: string } | undefined = { message: 'Only the owner can do this' }) {
+ const canAccessTrip = vi.fn((tripId: number, userId: number) =>
+ tripId === 5 && (userId === 42 || userId === 7) ? TRIP : undefined,
+ );
+ const reflector = { getAllAndOverride: vi.fn(() => meta) } as unknown as Reflector;
+ const guard = new TripOwnerGuard({ canAccessTrip } as unknown as DatabaseService, reflector);
+ return { guard, canAccessTrip };
+}
+
+function ctx(request: Record<string, unknown>) {
+ return {
+ switchToHttp: () => ({ getRequest: () => request }),
+ getHandler: () => function handler() {},
+ getClass: () => class Controller {},
+ } as never;
+}
+
+const thrown = (run: () => unknown) => {
+ try {
+ run();
+ } catch (err) {
+ expect(err).toBeInstanceOf(HttpException);
+ const e = err as HttpException;
+ return { status: e.getStatus(), body: e.getResponse() };
+ }
+ throw new Error('expected throw');
+};
+
+describe('TripOwnerGuard', () => {
+ it('OWNER-001: the owner passes', () => {
+ const { guard } = makeGuard();
+ expect(guard.canActivate(ctx({ user: owner, params: { tripId: '5' } }))).toBe(true);
+ });
+
+ it('OWNER-002: a member of the trip is refused with the route own message', () => {
+ const { guard } = makeGuard({ message: 'Only the owner can manage guests' });
+ expect(thrown(() => guard.canActivate(ctx({ user: member, params: { tripId: '5' } })))).toEqual({
+ status: 403,
+ body: { error: 'Only the owner can manage guests' },
+ });
+ });
+
+ it('OWNER-003: a stranger gets 404, never 403 — a 403 would confirm the id exists', () => {
+ const { guard } = makeGuard();
+ expect(thrown(() => guard.canActivate(ctx({ user: { id: 123, role: 'user' } as User, params: { tripId: '5' } })))).toEqual({
+ status: 404,
+ body: { error: 'Trip not found' },
+ });
+ });
+
+ it('OWNER-004: an admin who does not own the trip is refused', () => {
+ // The regression this guard must not introduce. PermissionsService.checkPermission
+ // returns true for every admin and the trip actions are admin-lowerable, so routing
+ // ownership through it would hand admins other people's trips. The guard does not
+ // inject it at all.
+ const canAccessTrip = vi.fn(() => TRIP);
+ const reflector = { getAllAndOverride: vi.fn(() => ({ message: 'Only the owner can transfer ownership' })) } as unknown as Reflector;
+ const guard = new TripOwnerGuard({ canAccessTrip } as unknown as DatabaseService, reflector);
+ expect(thrown(() => guard.canActivate(ctx({ user: admin, params: { tripId: '5' } })))).toEqual({
+ status: 403,
+ body: { error: 'Only the owner can transfer ownership' },
+ });
+ });
+
+ it('OWNER-005: reads the param the metadata names, so the :id routes work', () => {
+ const { guard, canAccessTrip } = makeGuard({ message: 'no', param: 'id' });
+ expect(guard.canActivate(ctx({ user: owner, params: { id: '5' } }))).toBe(true);
+ expect(canAccessTrip).toHaveBeenCalledWith(5, 42);
+ });
+
+ it('OWNER-006: reuses the row TripAccessGuard resolved instead of looking it up twice', () => {
+ const { guard, canAccessTrip } = makeGuard();
+ const request = { user: owner, params: {}, [TRIP_REQUEST_KEY]: TRIP };
+ expect(guard.canActivate(ctx(request))).toBe(true);
+ expect(canAccessTrip).not.toHaveBeenCalled();
+ });
+
+ it('OWNER-007: parks the row it resolved, so a later @Trip() reads it', () => {
+ const { guard } = makeGuard();
+ const request: Record<string, unknown> = { user: owner, params: { tripId: '5' } };
+ guard.canActivate(ctx(request));
+ expect(request[TRIP_REQUEST_KEY]).toEqual(TRIP);
+ });
+
+ it('OWNER-008: a missing user is a 401, not a 500 on undefined', () => {
+ const { guard } = makeGuard();
+ expect(thrown(() => guard.canActivate(ctx({ params: { tripId: '5' } })))).toEqual({
+ status: 401,
+ body: { error: 'Unauthorized' },
+ });
+ });
+
+ it('OWNER-009: a non-numeric or absent id is a 404 without touching the database', () => {
+ const { guard, canAccessTrip } = makeGuard();
+ expect(thrown(() => guard.canActivate(ctx({ user: owner, params: { tripId: 'abc' } })))).toEqual({
+ status: 404,
+ body: { error: 'Trip not found' },
+ });
+ expect(thrown(() => guard.canActivate(ctx({ user: owner, params: {} })))).toEqual({
+ status: 404,
+ body: { error: 'Trip not found' },
+ });
+ expect(canAccessTrip).not.toHaveBeenCalled();
+ });
+
+ it('OWNER-010: without metadata it still refuses a non-owner, with a generic message', () => {
+ // Built inline: passing undefined to makeGuard would hit its own default.
+ const canAccessTrip = vi.fn(() => TRIP);
+ const reflector = { getAllAndOverride: vi.fn(() => undefined) } as unknown as Reflector;
+ const guard = new TripOwnerGuard({ canAccessTrip } as unknown as DatabaseService, reflector);
+ expect(thrown(() => guard.canActivate(ctx({ user: member, params: { tripId: '5' } })))).toEqual({
+ status: 403,
+ body: { error: 'Only the trip owner can do this' },
+ });
+ });
+
+ it('OWNER-011: @RequireTripOwner writes the message and the param under the key the guard reads', () => {
+ class Probe {
+ @RequireTripOwner('Only the owner can transfer ownership', { param: 'id' })
+ handler() {}
+ }
+ expect(Reflect.getMetadata(TRIP_OWNER_KEY, Probe.prototype.handler)).toEqual({
+ message: 'Only the owner can transfer ownership',
+ param: 'id',
+ });
+ });
+});