Replace the copied requireTrip helpers with a TripAccessGuard

Every trip-scoped controller carried its own three-line requireTrip, and a
requireEdit next to it: eighteen copies of a security check, each of which had to
remember that no access is a 404 'Trip not found' and never a 403 — the
distinction that stops a stranger learning which trip ids exist. One of them
getting it wrong would have looked like nothing.

TripAccessGuard resolves :tripId once, refuses what the user cannot reach and
hands the row to the handler through a @Trip() param decorator (a param
decorator rather than a req.trip cast, because the request type that used to be
widened for that is gone). @RequirePermission carries the same action string the
domain services pass to checkPermission, so the HTTP and MCP paths cannot drift
apart on which right they demand. Status codes and bodies are unchanged.

Piloted on days, day-notes, todo, packing and files. Two things worth knowing:

Files applies the guard PER HANDLER and leaves the upload route on its own
check. Guards run before interceptors, so a class-level guard would answer 404
before multer had read the multipart body, and a response sent while the client
is still streaming gets the socket destroyed — the caller sees ECONNRESET
instead of the 404. Refusing after the body has been read costs the bandwidth
and keeps the answer readable.

The services keep verifyTripAccess and canEdit: the large majority of their
callers are *.mcp.ts tools, which never pass through an HTTP guard. canEdit lost
its incidental controller-test coverage in the move, so it now has direct tests
asserting the action and the shared flag — the same pair the guard reproduces.

Also fixes the backup zip-slip test that failed only on CI: it asserted a
drive-letter path, which is absolute on win32 and an ordinary relative segment on
Linux, so the branch it was guarding never fired there.
This commit is contained in:
Maurice
2026-08-09 19:12:51 +02:00
committed by Maurice
parent fef338091c
commit 8c0280e287
18 changed files with 513 additions and 237 deletions
+6 -1
View File
@@ -786,7 +786,12 @@ describe('BACKUP-061 restoreFromZip extraction', () => {
expect(fsMock.createWriteStream).not.toHaveBeenCalled();
});
it('BACKUP-061b — an absolute entry path is refused the same way', async () => {
// The `path.isAbsolute(rel)` half of the guard is only reachable where drive letters
// exist: on POSIX, path.join always keeps an entry under extractDir, so a leading
// slash is normalised away and only the `..` check above can fire. Asserting it
// unconditionally passed locally on Windows and failed on the Linux CI runner, which
// is the wrong way round for a security test to be discovered.
it.runIf(process.platform === 'win32')('BACKUP-061b — a drive-letter entry path is refused the same way', async () => {
unzipperMock.Open.file.mockResolvedValueOnce({ files: [zipEntry('C:/Windows/system32/evil.dll')] });
const result = await restoreFromZip('/data/tmp/abs.zip');
@@ -223,3 +223,29 @@ describe('remove', () => {
expect(testDb.prepare('SELECT * FROM day_notes WHERE id = ?').get(note.id)).toBeUndefined();
});
});
/**
* canEdit is MCP-only now: the HTTP path checks the same right through
* TripAccessGuard's @RequirePermission('day_edit'), so nothing in a controller test
* reaches this method any more. It stays because the *.mcp.ts tools never pass through
* an HTTP guard, and it is tested directly here for the same reason.
*/
describe('DayNotesService.canEdit', () => {
it('DAYNOTE-SVC-090 asks for day_edit and flags a non-owner as shared', () => {
const checkPermission = vi.fn(() => true);
const permissions = { checkPermission } as unknown as PermissionsService;
const withStub = new DayNotesService(new DatabaseService(testDb), permissions, new RealtimeService());
const trip = { id: 1, user_id: 1 } as never;
expect(withStub.canEdit(trip, { id: 1, role: 'user' } as never)).toBe(true);
expect(checkPermission).toHaveBeenLastCalledWith('day_edit', 'user', 1, 1, false);
withStub.canEdit(trip, { id: 2, role: 'user' } as never);
// The shared flag is what the guard has to reproduce; getting it wrong would give a
// member the owner's rights on somebody else's trip.
expect(checkPermission).toHaveBeenLastCalledWith('day_edit', 'user', 1, 2, true);
checkPermission.mockReturnValue(false);
expect(withStub.canEdit(trip, { id: 2, role: 'user' } as never)).toBe(false);
});
});
+8 -21
View File
@@ -28,28 +28,23 @@ function notesSvc(o: Partial<DayNotesService> = {}): DayNotesService {
}
describe('DaysController (parity with the legacy /api/trips/:tripId/days route)', () => {
it('404 when trip not accessible', () => {
const svc = daysSvc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) });
expect(thrown(() => new DaysController(svc).list(user, '5'))).toEqual({ status: 404, body: { error: 'Trip not found' } });
});
// The 404 "Trip not found" and 403 "No permission" cases moved to
// trip-access.guard.test.ts with the check itself: TripAccessGuard resolves :tripId
// for the whole controller now, so a handler is only ever reached for a trip the
// user may see. What is left here is what the handlers themselves still decide.
it('GET / returns the list service result verbatim (the { days } envelope)', () => {
const svc = daysSvc({ list: vi.fn().mockReturnValue({ days: [{ id: 1 }] }) } as Partial<DaysService>);
expect(new DaysController(svc).list(user, '5')).toEqual({ days: [{ id: 1 }] });
});
it('POST / 403 without day_edit, then creates + broadcasts', () => {
expect(thrown(() => new DaysController(daysSvc({ canEdit: vi.fn().mockReturnValue(false) })).create(user, '5', {}))).toEqual({ status: 403, body: { error: 'No permission' } });
it('POST / creates + broadcasts', () => {
const create = vi.fn().mockReturnValue({ id: 9 }); const broadcast = vi.fn();
expect(new DaysController(daysSvc({ create, broadcast } as Partial<DaysService>)).create(user, '5', { date: '2026-07-01' }, 'sock')).toEqual({ day: { id: 9 } });
expect(create).toHaveBeenCalledWith('5', '2026-07-01', undefined);
expect(broadcast).toHaveBeenCalledWith('5', 'day:created', { day: { id: 9 } }, 'sock');
});
it('POST / 404 when the trip is not accessible', () => {
const svc = daysSvc({ verifyTripAccess: vi.fn().mockReturnValue(null) });
expect(thrown(() => new DaysController(svc).create(user, '5', {}))).toEqual({ status: 404, body: { error: 'Trip not found' } });
});
it('POST / with a position inserts + broadcasts day:reordered', () => {
const insert = vi.fn().mockReturnValue({ id: 12 }); const create = vi.fn(); const broadcast = vi.fn();
@@ -61,15 +56,7 @@ describe('DaysController (parity with the legacy /api/trips/:tripId/days route)'
});
describe('PUT /reorder', () => {
it('404 when the trip is not accessible', () => {
const svc = daysSvc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) });
expect(thrown(() => new DaysController(svc).reorder(user, '5', { orderedIds: [1, 2] }))).toEqual({ status: 404, body: { error: 'Trip not found' } });
});
it('403 without day_edit', () => {
const svc = daysSvc({ canEdit: vi.fn().mockReturnValue(false) });
expect(thrown(() => new DaysController(svc).reorder(user, '5', { orderedIds: [1, 2] }))).toEqual({ status: 403, body: { error: 'No permission' } });
});
it('400 when orderedIds is missing', () => {
expect(thrown(() => new DaysController(daysSvc()).reorder(user, '5', {}))).toEqual({ status: 400, body: { error: 'orderedIds must be an array' } });
@@ -130,9 +117,9 @@ describe('DayNotesController (parity with the legacy /api/.../days/:dayId/notes
expect(DayNoteUpdateDto.schema.safeParse({ time: null }).success).toBe(true);
});
it('404 trip, 403 permission, 404 day, 400 empty text, then creates', () => {
expect(thrown(() => new DayNotesController(notesSvc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) })).create(user, '5', '3', { text: 'ok' }))).toEqual({ status: 404, body: { error: 'Trip not found' } });
expect(thrown(() => new DayNotesController(notesSvc({ canEdit: vi.fn().mockReturnValue(false) })).create(user, '5', '3', { text: 'ok' }))).toEqual({ status: 403, body: { error: 'No permission' } });
// Trip access and day_edit are TripAccessGuard's now (trip-access.guard.test.ts);
// what stays here is what this handler decides for itself.
it('404 day, 400 empty text, then creates', () => {
expect(thrown(() => new DayNotesController(notesSvc({ dayExists: vi.fn().mockReturnValue(false) } as Partial<DayNotesService>)).create(user, '5', '3', { text: 'ok' }))).toEqual({ status: 404, body: { error: 'Day not found' } });
expect(thrown(() => new DayNotesController(notesSvc({ dayExists: vi.fn().mockReturnValue(true) } as Partial<DayNotesService>)).create(user, '5', '3', { text: ' ' }))).toEqual({ status: 400, body: { error: 'Text required' } });
const create = vi.fn().mockReturnValue({ id: 7 }); const broadcast = vi.fn();
@@ -548,3 +548,29 @@ describe('quirk fixes', () => {
expect(assignments[0].place.tags[0]).toMatchObject({ id: tagId, name: 'Food', color: '#ff0000' });
});
});
/**
* canEdit is MCP-only now: the HTTP path checks the same right through
* TripAccessGuard's @RequirePermission('day_edit'), so nothing in a controller test
* reaches this method any more. It stays because the *.mcp.ts tools never pass through
* an HTTP guard, and it is tested directly here for the same reason.
*/
describe('DaysService.canEdit', () => {
it('DAY-SVC-090 asks for day_edit and flags a non-owner as shared', () => {
const checkPermission = vi.fn(() => true);
const permissions = { checkPermission } as unknown as PermissionsService;
const withStub = new DaysService(new DatabaseService(testDb), permissions, new RealtimeService(), new QueryHelpersService(new DatabaseService(testDb)));
const trip = { id: 1, user_id: 1 } as never;
expect(withStub.canEdit(trip, { id: 1, role: 'user' } as never)).toBe(true);
expect(checkPermission).toHaveBeenLastCalledWith('day_edit', 'user', 1, 1, false);
withStub.canEdit(trip, { id: 2, role: 'user' } as never);
// The shared flag is what the guard has to reproduce; getting it wrong would give a
// member the owner's rights on somebody else's trip.
expect(checkPermission).toHaveBeenLastCalledWith('day_edit', 'user', 1, 2, true);
checkPermission.mockReturnValue(false);
expect(withStub.canEdit(trip, { id: 2, role: 'user' } as never)).toBe(false);
});
});
+34 -25
View File
@@ -40,15 +40,28 @@ function thrown(fn: () => unknown): { status: number; body: unknown } {
beforeEach(() => vi.clearAllMocks());
afterEach(() => { delete process.env.DEMO_MODE; });
/** The trip row TripAccessGuard resolves and hands to every handler via @Trip(). */
const trip = { id: 5, user_id: 42 } as never;
// The 404 "Trip not found" cases moved to trip-access.guard.test.ts with the check.
describe('FilesController (parity with the legacy /api/trips/:tripId/files route)', () => {
it('GET / 404 without access, else lists with the trash flag', () => {
expect(thrown(() => new FilesController(fsvc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) }), new RuntimeEnvService()).list(user, '5'))).toEqual({ status: 404, body: { error: 'Trip not found' } });
it('GET / lists with the trash flag', () => {
const listFiles = vi.fn().mockReturnValue([{ id: 1 }]);
expect(new FilesController(fsvc({ listFiles } as Partial<FilesService>), new RuntimeEnvService()).list(user, '5', 'true')).toEqual({ files: [{ id: 1 }] });
expect(new FilesController(fsvc({ listFiles } as Partial<FilesService>), new RuntimeEnvService()).list(user, trip, '5', 'true')).toEqual({ files: [{ id: 1 }] });
expect(listFiles).toHaveBeenCalledWith('5', true);
});
describe('POST / (upload)', () => {
it('404 without trip access — upload keeps its own check so the body is read first', () => {
// The guard would answer before multer, and a response sent mid-upload destroys
// the socket: the caller would see ECONNRESET rather than this 404.
const svc = fsvc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) });
expect(thrown(() => new FilesController(svc, new RuntimeEnvService()).upload(user, '5', undefined, {}))).toEqual({
status: 404,
body: { error: 'Trip not found' },
});
});
const file = { filename: 'a.pdf' } as Express.Multer.File;
it('403 in demo mode for a demo email', () => {
process.env.DEMO_MODE = 'true';
@@ -82,37 +95,37 @@ describe('FilesController (parity with the legacy /api/trips/:tripId/files route
});
it('PUT /:id 403 without file_edit, 404 unknown, else updates + broadcasts', () => {
expect(thrown(() => new FilesController(fsvc({ can: vi.fn().mockReturnValue(false) }), new RuntimeEnvService()).update(user, '5', '9', {}))).toEqual({ status: 403, body: { error: 'No permission to edit files' } });
expect(thrown(() => new FilesController(fsvc({ getFileById: vi.fn().mockReturnValue(undefined) } as Partial<FilesService>), new RuntimeEnvService()).update(user, '5', '9', {}))).toEqual({ status: 404, body: { error: 'File not found' } });
expect(thrown(() => new FilesController(fsvc({ can: vi.fn().mockReturnValue(false) }), new RuntimeEnvService()).update(user, trip, '5', '9', {}))).toEqual({ status: 403, body: { error: 'No permission to edit files' } });
expect(thrown(() => new FilesController(fsvc({ getFileById: vi.fn().mockReturnValue(undefined) } as Partial<FilesService>), new RuntimeEnvService()).update(user, trip, '5', '9', {}))).toEqual({ status: 404, body: { error: 'File not found' } });
const updateFile = vi.fn().mockReturnValue({ id: 9 });
const s = fsvc({ getFileById: vi.fn().mockReturnValue({ id: 9, description: 'x' }), updateFile, broadcast: vi.fn() } as Partial<FilesService>);
expect(new FilesController(s, new RuntimeEnvService()).update(user, '5', '9', { description: 'new' })).toEqual({ file: { id: 9 } });
expect(new FilesController(s, new RuntimeEnvService()).update(user, trip, '5', '9', { description: 'new' })).toEqual({ file: { id: 9 } });
});
it('PATCH /:id/star 403/404, else toggles', () => {
expect(thrown(() => new FilesController(fsvc({ can: vi.fn().mockReturnValue(false) }), new RuntimeEnvService()).star(user, '5', '9'))).toEqual({ status: 403, body: { error: 'No permission' } });
expect(thrown(() => new FilesController(fsvc({ getFileById: vi.fn().mockReturnValue(undefined) } as Partial<FilesService>), new RuntimeEnvService()).star(user, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found' } });
expect(thrown(() => new FilesController(fsvc({ can: vi.fn().mockReturnValue(false) }), new RuntimeEnvService()).star(user, trip, '5', '9'))).toEqual({ status: 403, body: { error: 'No permission' } });
expect(thrown(() => new FilesController(fsvc({ getFileById: vi.fn().mockReturnValue(undefined) } as Partial<FilesService>), new RuntimeEnvService()).star(user, trip, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found' } });
const toggleStarred = vi.fn().mockReturnValue({ id: 9, starred: 1 });
const s = fsvc({ getFileById: vi.fn().mockReturnValue({ id: 9, starred: 0 }), toggleStarred, broadcast: vi.fn() } as Partial<FilesService>);
expect(new FilesController(s, new RuntimeEnvService()).star(user, '5', '9')).toEqual({ file: { id: 9, starred: 1 } });
expect(new FilesController(s, new RuntimeEnvService()).star(user, trip, '5', '9')).toEqual({ file: { id: 9, starred: 1 } });
expect(toggleStarred).toHaveBeenCalledWith('9', 0);
});
it('DELETE /:id soft-delete 403/404, else success', () => {
expect(thrown(() => new FilesController(fsvc({ can: vi.fn().mockReturnValue(false) }), new RuntimeEnvService()).remove(user, '5', '9'))).toEqual({ status: 403, body: { error: 'No permission to delete files' } });
expect(thrown(() => new FilesController(fsvc({ getFileById: vi.fn().mockReturnValue(undefined) } as Partial<FilesService>), new RuntimeEnvService()).remove(user, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found' } });
expect(thrown(() => new FilesController(fsvc({ can: vi.fn().mockReturnValue(false) }), new RuntimeEnvService()).remove(user, trip, '5', '9'))).toEqual({ status: 403, body: { error: 'No permission to delete files' } });
expect(thrown(() => new FilesController(fsvc({ getFileById: vi.fn().mockReturnValue(undefined) } as Partial<FilesService>), new RuntimeEnvService()).remove(user, trip, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found' } });
const softDeleteFile = vi.fn();
const broadcast = vi.fn();
const s = fsvc({ getFileById: vi.fn().mockReturnValue({ id: 9 }), softDeleteFile, broadcast } as Partial<FilesService>);
expect(new FilesController(s, new RuntimeEnvService()).remove(user, '5', '9', 'sock')).toEqual({ success: true });
expect(new FilesController(s, new RuntimeEnvService()).remove(user, trip, '5', '9', 'sock')).toEqual({ success: true });
expect(broadcast).toHaveBeenCalledWith('5', 'file:deleted', { fileId: 9 }, 'sock');
});
it('POST /:id/restore 404 not in trash, else restores', () => {
expect(thrown(() => new FilesController(fsvc({ getDeletedFile: vi.fn().mockReturnValue(undefined) } as Partial<FilesService>), new RuntimeEnvService()).restore(user, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found in trash' } });
expect(thrown(() => new FilesController(fsvc({ getDeletedFile: vi.fn().mockReturnValue(undefined) } as Partial<FilesService>), new RuntimeEnvService()).restore(user, trip, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found in trash' } });
const restoreFile = vi.fn().mockReturnValue({ id: 9 });
const s = fsvc({ getDeletedFile: vi.fn().mockReturnValue({ id: 9 }), restoreFile, broadcast: vi.fn() } as Partial<FilesService>);
expect(new FilesController(s, new RuntimeEnvService()).restore(user, '5', '9')).toEqual({ file: { id: 9 } });
expect(new FilesController(s, new RuntimeEnvService()).restore(user, trip, '5', '9')).toEqual({ file: { id: 9 } });
});
it('DELETE /:id/permanent 404 not in trash, else deletes', async () => {
@@ -129,32 +142,28 @@ describe('FilesController (parity with the legacy /api/trips/:tripId/files route
});
it('POST /:id/link 404 unknown file, else links', () => {
expect(thrown(() => new FilesController(fsvc({ getFileById: vi.fn().mockReturnValue(undefined) } as Partial<FilesService>), new RuntimeEnvService()).link(user, '5', '9', {}))).toEqual({ status: 404, body: { error: 'File not found' } });
expect(thrown(() => new FilesController(fsvc({ getFileById: vi.fn().mockReturnValue(undefined) } as Partial<FilesService>), new RuntimeEnvService()).link(user, trip, '5', '9', {}))).toEqual({ status: 404, body: { error: 'File not found' } });
const createFileLink = vi.fn().mockReturnValue([{ id: 1 }]);
const s = fsvc({ getFileById: vi.fn().mockReturnValue({ id: 9 }), createFileLink } as Partial<FilesService>);
expect(new FilesController(s, new RuntimeEnvService()).link(user, '5', '9', { reservation_id: 2 })).toEqual({ success: true, links: [{ id: 1 }] });
expect(new FilesController(s, new RuntimeEnvService()).link(user, trip, '5', '9', { reservation_id: 2 })).toEqual({ success: true, links: [{ id: 1 }] });
});
it('DELETE /:id/link/:linkId removes the link; GET /:id/links lists', () => {
const deleteFileLink = vi.fn();
expect(new FilesController(fsvc({ deleteFileLink } as Partial<FilesService>), new RuntimeEnvService()).unlink(user, '5', '9', '3')).toEqual({ success: true });
expect(new FilesController(fsvc({ deleteFileLink } as Partial<FilesService>), new RuntimeEnvService()).unlink(user, trip, '5', '9', '3')).toEqual({ success: true });
expect(deleteFileLink).toHaveBeenCalledWith('3', '9');
const s = fsvc({ getFileLinks: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<FilesService>);
expect(new FilesController(s, new RuntimeEnvService()).links(user, '5', '9')).toEqual({ links: [{ id: 1 }] });
expect(new FilesController(s, new RuntimeEnvService()).links(user, trip, '5', '9')).toEqual({ links: [{ id: 1 }] });
});
it('the trash + link routes all reject without file_delete / file_edit', async () => {
const denied = () => fsvc({ can: vi.fn().mockReturnValue(false) });
await expect(new FilesController(denied(), new RuntimeEnvService()).permanent(user, '5', '9')).rejects.toMatchObject({ status: 403 });
expect(thrown(() => new FilesController(denied(), new RuntimeEnvService()).restore(user, '5', '9'))).toEqual({ status: 403, body: { error: 'No permission' } });
expect(thrown(() => new FilesController(denied(), new RuntimeEnvService()).link(user, '5', '9', {}))).toEqual({ status: 403, body: { error: 'No permission' } });
expect(thrown(() => new FilesController(denied(), new RuntimeEnvService()).unlink(user, '5', '9', '3'))).toEqual({ status: 403, body: { error: 'No permission' } });
expect(thrown(() => new FilesController(denied(), new RuntimeEnvService()).restore(user, trip, '5', '9'))).toEqual({ status: 403, body: { error: 'No permission' } });
expect(thrown(() => new FilesController(denied(), new RuntimeEnvService()).link(user, trip, '5', '9', {}))).toEqual({ status: 403, body: { error: 'No permission' } });
expect(thrown(() => new FilesController(denied(), new RuntimeEnvService()).unlink(user, trip, '5', '9', '3'))).toEqual({ status: 403, body: { error: 'No permission' } });
});
it('GET /:id/links 404 without trip access', () => {
const s = fsvc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) });
expect(thrown(() => new FilesController(s, new RuntimeEnvService()).links(user, '5', '9'))).toEqual({ status: 404, body: { error: 'Trip not found' } });
});
});
describe('FilesDownloadController', () => {
@@ -60,13 +60,9 @@ function thrown(fn: () => unknown): { status: number; body: unknown } {
throw new Error('expected the handler to throw');
}
// The 404 "Trip not found" and 403 "No permission" cases moved to
// trip-access.guard.test.ts with the check itself.
describe('PackingController (parity with the legacy /api/trips/:tripId/packing route)', () => {
it('404 when the trip is not accessible', () => {
const svc = makeService({ verifyTripAccess: vi.fn().mockReturnValue(undefined) });
expect(thrown(() => new PackingController(svc).list(user, '5'))).toEqual({
status: 404, body: { error: 'Trip not found' },
});
});
it('GET / returns items for an accessible trip', () => {
const svc = makeService({ listItems: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<PackingService>);
@@ -74,12 +70,6 @@ describe('PackingController (parity with the legacy /api/trips/:tripId/packing r
});
describe('POST / (create)', () => {
it('403 without packing_edit permission', () => {
const svc = makeService({ canEdit: vi.fn().mockReturnValue(false) });
expect(thrown(() => new PackingController(svc).create(user, '5', { name: 'Socks' }))).toEqual({
status: 403, body: { error: 'No permission' },
});
});
// The missing-name 400 moved from a bespoke controller check into the
// ZodValidationPipe (packingCreateItemRequestSchema) — direct method calls
@@ -126,12 +116,6 @@ describe('PackingController (parity with the legacy /api/trips/:tripId/packing r
// requires an array) — direct method calls bypass parameter pipes, so that
// path is covered by the e2e suite and the schema spec in @trek/shared.
it('403 without packing_edit permission', () => {
const svc = makeService({ canEdit: vi.fn().mockReturnValue(false) });
expect(thrown(() => new PackingController(svc).importItems(user, '5', { items: [{ name: 'a' }] }))).toEqual({
status: 403, body: { error: 'No permission' },
});
});
it('imports (owned by the importer) and broadcasts per item', () => {
const bulkImport = vi.fn().mockReturnValue([{ id: 1 }, { id: 2 }]);
@@ -220,12 +204,6 @@ describe('PackingController (parity with the legacy /api/trips/:tripId/packing r
expect(reorderItems).toHaveBeenCalledWith('5', [3, 1, 2]);
});
it('403 without packing_edit permission', () => {
const svc = makeService({ canEdit: vi.fn().mockReturnValue(false) });
expect(thrown(() => new PackingController(svc).reorder(user, '5', { orderedIds: [1] }))).toEqual({
status: 403, body: { error: 'No permission' },
});
});
});
describe('DELETE /:id (remove)', () => {
+2 -12
View File
@@ -27,13 +27,9 @@ function thrown(fn: () => unknown): { status: number; body: unknown } {
throw new Error('expected the handler to throw');
}
// The 404 "Trip not found" and 403 "No permission" cases moved to
// trip-access.guard.test.ts with the check itself.
describe('TodoController (parity with the legacy /api/trips/:tripId/todo route)', () => {
it('404 when the trip is not accessible', () => {
const svc = makeService({ verifyTripAccess: vi.fn().mockReturnValue(undefined) });
expect(thrown(() => new TodoController(svc).list(user, '5'))).toEqual({
status: 404, body: { error: 'Trip not found' },
});
});
it('GET / returns items', () => {
const svc = makeService({ listItems: vi.fn().mockReturnValue([{ id: 1 }]) } as Partial<TodoService>);
@@ -41,12 +37,6 @@ describe('TodoController (parity with the legacy /api/trips/:tripId/todo route)'
});
describe('POST /', () => {
it('403 without permission', () => {
const svc = makeService({ canEdit: vi.fn().mockReturnValue(false) });
expect(thrown(() => new TodoController(svc).create(user, '5', { name: 'Pack' }))).toEqual({
status: 403, body: { error: 'No permission' },
});
});
// The missing-name 400 moved from a bespoke controller check into the
// ZodValidationPipe (todoCreateItemRequestSchema) — direct method calls
@@ -289,3 +289,29 @@ describe('getCategoryAssignees / updateCategoryAssignees', () => {
// TODO-SVC-021..024 (todo.bridge delegation) were deleted with the bridge —
// its last consumer, the legacy get_trip_summary registrar in
// src/mcp/tools/trips.ts, moved to the DI-discovered trips.mcp.ts.
/**
* canEdit is MCP-only now: the HTTP path checks the same right through
* TripAccessGuard's @RequirePermission('packing_edit'), so nothing in a controller test
* reaches this method any more. It stays because the *.mcp.ts tools never pass through
* an HTTP guard, and it is tested directly here for the same reason.
*/
describe('TodoService.canEdit', () => {
it('TODO-SVC-090 asks for packing_edit and flags a non-owner as shared', () => {
const checkPermission = vi.fn(() => true);
const permissions = { checkPermission } as unknown as PermissionsService;
const withStub = new TodoService(new DatabaseService(testDb), permissions, new RealtimeService());
const trip = { id: 1, user_id: 1 } as never;
expect(withStub.canEdit(trip, { id: 1, role: 'user' } as never)).toBe(true);
expect(checkPermission).toHaveBeenLastCalledWith('packing_edit', 'user', 1, 1, false);
withStub.canEdit(trip, { id: 2, role: 'user' } as never);
// The shared flag is what the guard has to reproduce; getting it wrong would give a
// member the owner's rights on somebody else's trip.
expect(checkPermission).toHaveBeenLastCalledWith('packing_edit', 'user', 1, 2, true);
checkPermission.mockReturnValue(false);
expect(withStub.canEdit(trip, { id: 2, role: 'user' } as never)).toBe(false);
});
});
@@ -0,0 +1,182 @@
/**
* TripAccessGuard — the trip-scoping check that used to be a `requireTrip` helper
* copied into every trip-scoped controller.
*
* The cases here are the ones those copies each carried: an inaccessible trip is a 404
* "Trip not found" and never a 403 (a 403 would confirm the id exists to someone with
* no business knowing), and a mutation additionally needs its own permission. They
* moved out of days.controller.test.ts with the check itself.
*/
import { describe, it, expect, vi } from 'vitest';
import { HttpException } from '@nestjs/common';
import { ROUTE_ARGS_METADATA } from '@nestjs/common/constants';
import { Reflector } from '@nestjs/core';
import {
RequirePermission,
TRIP_PERMISSION_KEY,
TRIP_REQUEST_KEY,
TripAccessGuard,
} from '../../../src/nest/permissions/trip-access.guard';
import { Trip } from '../../../src/nest/permissions/trip.decorator';
import type { DatabaseService } from '../../../src/nest/database/database.service';
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
import type { User } from '../../../src/types';
const owner = { id: 42, role: 'user' } as User;
const member = { id: 7, role: 'user' } as User;
/** Trip 5 belongs to user 42; user 7 is a member of it. Nothing else is reachable. */
const TRIP = { id: 5, user_id: 42 };
function makeGuard(options: { checkPermission?: ReturnType<typeof vi.fn>; action?: string } = {}) {
const canAccessTrip = vi.fn((tripId: number, userId: number) =>
tripId === 5 && (userId === 42 || userId === 7) ? TRIP : undefined,
);
const checkPermission = options.checkPermission ?? vi.fn(() => true);
const reflector = { getAllAndOverride: vi.fn(() => options.action) } as unknown as Reflector;
const guard = new TripAccessGuard(
{ canAccessTrip } as unknown as DatabaseService,
{ checkPermission } as unknown as PermissionsService,
reflector,
);
return { guard, canAccessTrip, checkPermission, reflector };
}
/** The slice of ExecutionContext the guard reads. */
function ctx(request: Record<string, unknown>) {
return {
switchToHttp: () => ({ getRequest: () => request }),
getHandler: () => function handler() {},
getClass: () => class Controller {},
} as never;
}
const thrown = (run: () => unknown) => {
try {
run();
return null;
} catch (e) {
return e instanceof HttpException ? { status: e.getStatus(), body: e.getResponse() } : e;
}
};
describe('TripAccessGuard', () => {
it('TRIPGUARD-001 lets a member through and parks the trip row on the request', () => {
const { guard, canAccessTrip } = makeGuard();
const request = { user: member, params: { tripId: '5' } } as Record<string, unknown>;
expect(guard.canActivate(ctx(request))).toBe(true);
expect(canAccessTrip).toHaveBeenCalledWith(5, 7);
expect(request[TRIP_REQUEST_KEY]).toBe(TRIP);
});
it('TRIPGUARD-002 a trip the user cannot reach is 404 "Trip not found", never 403', () => {
const { guard } = makeGuard();
const stranger = { user: { id: 99, role: 'user' }, params: { tripId: '5' } };
expect(thrown(() => guard.canActivate(ctx(stranger)))).toEqual({ status: 404, body: { error: 'Trip not found' } });
const missing = { user: owner, params: { tripId: '404' } };
expect(thrown(() => guard.canActivate(ctx(missing)))).toEqual({ status: 404, body: { error: 'Trip not found' } });
});
it('TRIPGUARD-003 a non-numeric tripId is refused without touching the database', () => {
const { guard, canAccessTrip } = makeGuard();
const request = { user: owner, params: { tripId: 'not-a-number' } };
expect(thrown(() => guard.canActivate(ctx(request)))).toEqual({ status: 404, body: { error: 'Trip not found' } });
expect(canAccessTrip).not.toHaveBeenCalled();
});
it('TRIPGUARD-004 a missing tripId param is refused rather than read as NaN', () => {
const { guard } = makeGuard();
expect(thrown(() => guard.canActivate(ctx({ user: owner, params: {} })))).toEqual({
status: 404,
body: { error: 'Trip not found' },
});
expect(thrown(() => guard.canActivate(ctx({ user: owner })))).toEqual({
status: 404,
body: { error: 'Trip not found' },
});
});
it('TRIPGUARD-005 no authenticated user is a 401, not a crash on user.id', () => {
// JwtAuthGuard runs first, so this only happens when a route was wired without it.
// Refusing beats turning a wiring mistake into a 500 nobody can read.
const { guard, canAccessTrip } = makeGuard();
expect(thrown(() => guard.canActivate(ctx({ params: { tripId: '5' } })))).toEqual({
status: 401,
body: { error: 'Unauthorized' },
});
expect(canAccessTrip).not.toHaveBeenCalled();
});
it('TRIPGUARD-006 without @RequirePermission the permission service is never consulted', () => {
const { guard, checkPermission } = makeGuard();
guard.canActivate(ctx({ user: member, params: { tripId: '5' } }));
expect(checkPermission).not.toHaveBeenCalled();
});
it('TRIPGUARD-007 @RequirePermission passes the action and the shared flag through', () => {
const checkPermission = vi.fn(() => true);
const { guard } = makeGuard({ checkPermission, action: 'day_edit' });
// A member editing somebody else's trip is the SHARED case…
guard.canActivate(ctx({ user: member, params: { tripId: '5' } }));
expect(checkPermission).toHaveBeenLastCalledWith('day_edit', 'user', 42, 7, true);
// …and the owner editing their own is not.
guard.canActivate(ctx({ user: owner, params: { tripId: '5' } }));
expect(checkPermission).toHaveBeenLastCalledWith('day_edit', 'user', 42, 42, false);
});
it('TRIPGUARD-008 a refused permission is 403 "No permission", and access still came first', () => {
const { guard } = makeGuard({ checkPermission: vi.fn(() => false), action: 'day_edit' });
expect(thrown(() => guard.canActivate(ctx({ user: member, params: { tripId: '5' } })))).toEqual({
status: 403,
body: { error: 'No permission' },
});
// A stranger gets the 404 rather than the 403: access is checked before rights, so
// the permission answer never leaks that the trip exists.
expect(thrown(() => guard.canActivate(ctx({ user: { id: 99, role: 'user' }, params: { tripId: '5' } })))).toEqual({
status: 404,
body: { error: 'Trip not found' },
});
});
it('TRIPGUARD-009 the metadata is read from the handler first, then the class', () => {
const { guard, reflector } = makeGuard({ action: 'day_edit' });
guard.canActivate(ctx({ user: owner, params: { tripId: '5' } }));
expect(reflector.getAllAndOverride).toHaveBeenCalledWith(TRIP_PERMISSION_KEY, [expect.any(Function), expect.any(Function)]);
});
it('TRIPGUARD-010 @RequirePermission writes the action under the key the guard reads', () => {
class Probe {
@RequirePermission('budget_edit')
handler() {}
}
expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, Probe.prototype.handler)).toBe('budget_edit');
});
});
describe('@Trip() param decorator', () => {
/**
* Nest stores a custom param decorator's factory in ROUTE_ARGS_METADATA on the
* controller class, keyed by `${CUSTOM_ROUTE_ARGS_METADATA}:${index}`. Pulling it
* back out is how the factory gets exercised for real rather than asserted to be a
* function.
*/
function tripFactory(): (data: unknown, context: unknown) => unknown {
class Probe {
handler(@Trip() _trip: unknown) {}
}
const args = Reflect.getMetadata(ROUTE_ARGS_METADATA, Probe, 'handler') as Record<
string,
{ factory: (data: unknown, context: unknown) => unknown }
>;
return Object.values(args)[0].factory;
}
it('TRIPGUARD-011 returns the row the guard parked on the request', () => {
expect(tripFactory()(undefined, ctx({ [TRIP_REQUEST_KEY]: TRIP }))).toBe(TRIP);
});
it('TRIPGUARD-012 a route without the guard is a loud throw, not an undefined trip', () => {
// Silently handing the handler `undefined` would turn a missing guard into a
// crash somewhere further down, with nothing pointing at the wiring.
expect(() => tripFactory()(undefined, ctx({}))).toThrow(/without @UseGuards\(TripAccessGuard\)/);
});
});