diff --git a/server/src/nest/files/files-download.controller.ts b/server/src/nest/files/files-download.controller.ts index 96fdfbd9a..3512af506 100644 --- a/server/src/nest/files/files-download.controller.ts +++ b/server/src/nest/files/files-download.controller.ts @@ -1,9 +1,9 @@ import { Controller, Get, HttpException, Param, Req, Res } from '@nestjs/common'; import type { Request, Response } from 'express'; import path from 'path'; -import fs from 'fs'; import { FilesService } from './files.service'; import { Public } from '../auth/public.decorator'; +import { StorageService } from '../storage/storage.service'; /** * GET /api/trips/:tripId/files/:id/download — authenticated file download. @@ -11,15 +11,25 @@ import { Public } from '../auth/public.decorator'; * Deliberately NOT behind the JwtAuthGuard: it accepts a cookie, a Bearer header * OR a one-shot `?token=` query param (so links can be opened directly), all via * the legacy authenticateDownload helper. Byte-identical to the legacy route: - * 401 token, 404 trip/file, 403 path traversal, .pkpass served inline for Wallet. + * 401 token, 404 trip/file, .pkpass served inline for Wallet. Bytes come from + * storage.sendToResponse, whose local branch is the root-relative res.sendFile + * form this route needs under the ExpressAdapter. */ @Public('authenticates itself: the download link carries a short-lived ?token the client mints') @Controller('api/trips/:tripId/files') export class FilesDownloadController { - constructor(private readonly files: FilesService) {} + constructor( + private readonly files: FilesService, + private readonly storage: StorageService, + ) {} @Get(':id/download') - download(@Req() req: Request, @Res() res: Response, @Param('tripId') tripId: string, @Param('id') id: string): void { + async download( + @Req() req: Request, + @Res() res: Response, + @Param('tripId') tripId: string, + @Param('id') id: string, + ): Promise { const auth = this.files.authenticateDownload(req); if ('error' in auth) { throw new HttpException({ error: auth.error }, auth.status); @@ -35,11 +45,10 @@ export class FilesDownloadController { throw new HttpException({ error: 'File not found' }, 404); } - const { resolved, safe } = this.files.resolveFilePath(file.filename); - if (!safe) { - throw new HttpException({ error: 'Forbidden' }, 403); - } - if (!fs.existsSync(resolved)) { + // basename() keeps resolveFilePath()'s tolerance: a stray prefixed row + // still resolves to its bare stored name. + const name = path.basename(file.filename); + if (!(await this.storage.exists('files', name).catch(() => false))) { throw new HttpException({ error: 'File not found' }, 404); } @@ -47,22 +56,20 @@ export class FilesDownloadController { // (iOS/macOS) hands them to Wallet instead of downloading as a blob. A // `.pkpasses` bundle (a ZIP of multiple passes) is a distinct type with its // own plural MIME type — without it Wallet won't offer to add the passes. + const ext = path.extname(name).toLowerCase(); const walletMime = - path.extname(resolved).toLowerCase() === '.pkpass' + ext === '.pkpass' ? 'application/vnd.apple.pkpass' - : path.extname(resolved).toLowerCase() === '.pkpasses' + : ext === '.pkpasses' ? 'application/vnd.apple.pkpasses' : null; - if (walletMime) { - res.setHeader('Content-Type', walletMime); - res.setHeader('Content-Disposition', `inline; filename="${path.basename(file.original_name || resolved)}"`); - } - - // Serve with an explicit { root } + basename rather than an absolute path: - // under the Nest ExpressAdapter, res.sendFile(absolutePath) resolves the - // file relative to the (rewritten) req.url and fails with a spurious - // "Not Found", whereas the root-relative form streams correctly. The - // resolveFilePath guard above already pins this to the uploads dir. - res.sendFile(path.basename(resolved), { root: path.dirname(resolved) }); + await this.storage.sendToResponse( + 'files', + name, + res, + walletMime + ? { contentType: walletMime, disposition: `inline; filename="${path.basename(file.original_name || name)}"` } + : undefined, + ); } } diff --git a/server/tests/integration/files.test.ts b/server/tests/integration/files.test.ts index c3dd50388..fda7f26bd 100644 --- a/server/tests/integration/files.test.ts +++ b/server/tests/integration/files.test.ts @@ -565,4 +565,64 @@ describe('File download', () => { .set('Cookie', `trek_session=${token}`); expect(dl.status).toBe(200); }); + + it('FILE-P04 — download serves the exact bytes with Content-Type, ETag, and Range support', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const upload = await uploadFile(trip.id, user.id, FIXTURE_PDF); + const fileId = upload.body.file.id; + const fixtureBytes = fs.readFileSync(FIXTURE_PDF); + + const dl = await request(app) + .get(`/api/trips/${trip.id}/files/${fileId}/download`) + .set('Cookie', authCookie(user.id)); + expect(dl.status).toBe(200); + expect(dl.headers['content-type']).toBe('application/pdf'); + expect(dl.headers.etag).toMatch(/^W\/"[0-9a-f]+-[0-9a-f]+"$/); + expect(Buffer.from(dl.body).equals(fixtureBytes)).toBe(true); + + const ranged = await request(app) + .get(`/api/trips/${trip.id}/files/${fileId}/download`) + .set('Cookie', authCookie(user.id)) + .set('Range', 'bytes=0-3'); + expect(ranged.status).toBe(206); + expect(ranged.headers['content-range']).toBe(`bytes 0-3/${fixtureBytes.length}`); + }); + + it('FILE-P05 — Apple Wallet passes are served inline with the canonical MIME types', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + + for (const [ext, mime] of [ + ['pkpass', 'application/vnd.apple.pkpass'], + ['pkpasses', 'application/vnd.apple.pkpasses'], + ] as const) { + const upload = await request(app) + .post(`/api/trips/${trip.id}/files`) + .set('Cookie', authCookie(user.id)) + .attach('file', Buffer.from('PK-wallet-bytes'), `pass.${ext}`); + expect(upload.status).toBe(201); + + const dl = await request(app) + .get(`/api/trips/${trip.id}/files/${upload.body.file.id}/download`) + .set('Cookie', authCookie(user.id)); + expect(dl.status).toBe(200); + expect(dl.headers['content-type']).toBe(mime); + expect(dl.headers['content-disposition']).toBe(`inline; filename="pass.${ext}"`); + } + }); + + it('FILE-P06 — a DB row whose bytes are gone answers 404 File not found', async () => { + const { user } = createUser(testDb); + const trip = createTrip(testDb, user.id); + const upload = await uploadFile(trip.id, user.id, FIXTURE_PDF); + const fileId = upload.body.file.id; + fs.rmSync(path.join(uploadsDir, upload.body.file.filename), { force: true }); + + const dl = await request(app) + .get(`/api/trips/${trip.id}/files/${fileId}/download`) + .set('Cookie', authCookie(user.id)); + expect(dl.status).toBe(404); + expect(dl.body).toEqual({ error: 'File not found' }); + }); }); diff --git a/server/tests/unit/nest/files.controller.test.ts b/server/tests/unit/nest/files.controller.test.ts index 7c3e5e6ea..0241d92ea 100644 --- a/server/tests/unit/nest/files.controller.test.ts +++ b/server/tests/unit/nest/files.controller.test.ts @@ -2,9 +2,6 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service'; import { HttpException } from '@nestjs/common'; import type { Request, Response } from 'express'; -import os from 'os'; -import path from 'path'; -import fs from 'fs'; vi.mock('../../../src/nest/common/demo', () => ({ isDemoEmail: vi.fn(() => false) })); @@ -196,95 +193,81 @@ describe('FilesDownloadController', () => { authenticateDownload: vi.fn().mockReturnValue({ userId: 1 }), verifyTripAccess: vi.fn().mockReturnValue({ user_id: 1 }), getFileById: vi.fn().mockReturnValue({ filename: 'x.pdf', original_name: 'x.pdf' }), - resolveFilePath: vi.fn().mockReturnValue({ resolved: 'C:/nope/x.pdf', safe: true }), ...o, } as unknown as FilesService; } + function dstor(o: Record = {}): StorageService { + return { + exists: vi.fn().mockResolvedValue(true), + sendToResponse: vi.fn().mockResolvedValue(undefined), + ...o, + } as unknown as StorageService; + } const req = { headers: {}, query: {} } as Request; - const res = { setHeader: vi.fn(), sendFile: vi.fn() } as unknown as Response; + const res = {} as Response; - it('maps the auth error from authenticateDownload', () => { + it('maps the auth error from authenticateDownload', async () => { const s = dsvc({ authenticateDownload: vi.fn().mockReturnValue({ error: 'Authentication required', status: 401 }) }); - expect(thrown(() => new FilesDownloadController(s).download(req, res, '5', '9'))).toEqual({ status: 401, body: { error: 'Authentication required' } }); - }); - it('404 without trip access, 404 unknown file, 403 on an unsafe path', () => { - expect(thrown(() => new FilesDownloadController(dsvc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) })).download(req, res, '5', '9'))).toEqual({ status: 404, body: { error: 'Trip not found' } }); - expect(thrown(() => new FilesDownloadController(dsvc({ getFileById: vi.fn().mockReturnValue(undefined) })).download(req, res, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found' } }); - expect(thrown(() => new FilesDownloadController(dsvc({ resolveFilePath: vi.fn().mockReturnValue({ resolved: '/x', safe: false }) })).download(req, res, '5', '9'))).toEqual({ status: 403, body: { error: 'Forbidden' } }); + expect(await rejected(new FilesDownloadController(s, dstor()).download(req, res, '5', '9'))).toEqual({ status: 401, body: { error: 'Authentication required' } }); }); - it('404 when the safe path is gone from disk', () => { - const missing = path.join(os.tmpdir(), `trek-no-such-${Date.now()}.pdf`); - const s = dsvc({ resolveFilePath: vi.fn().mockReturnValue({ resolved: missing, safe: true }) }); - expect(thrown(() => new FilesDownloadController(s).download(req, res, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found' } }); + it('404 without trip access and 404 for an unknown file', async () => { + expect(await rejected(new FilesDownloadController(dsvc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) }), dstor()).download(req, res, '5', '9'))).toEqual({ status: 404, body: { error: 'Trip not found' } }); + expect(await rejected(new FilesDownloadController(dsvc({ getFileById: vi.fn().mockReturnValue(undefined) }), dstor()).download(req, res, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found' } }); }); - it('streams a regular file via sendFile with an explicit root', () => { - const real = path.join(os.tmpdir(), `trek-dl-${Date.now()}.pdf`); - fs.writeFileSync(real, 'x'); - try { - const sendFile = vi.fn(); - const localRes = { setHeader: vi.fn(), sendFile } as unknown as Response; - const s = dsvc({ resolveFilePath: vi.fn().mockReturnValue({ resolved: real, safe: true }) }); - new FilesDownloadController(s).download(req, localRes, '5', '9'); - expect(sendFile).toHaveBeenCalledWith(path.basename(real), { root: path.dirname(real) }); - expect(localRes.setHeader).not.toHaveBeenCalled(); - } finally { - fs.unlinkSync(real); - } + it('404 when the object is gone from storage', async () => { + const storage = dstor({ exists: vi.fn().mockResolvedValue(false) }); + expect(await rejected(new FilesDownloadController(dsvc(), storage).download(req, res, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found' } }); }); - it('serves a .pkpass inline with the Wallet MIME type and the original name', () => { - const real = path.join(os.tmpdir(), `trek-pass-${Date.now()}.pkpass`); - fs.writeFileSync(real, 'x'); - try { - const setHeader = vi.fn(); - const localRes = { setHeader, sendFile: vi.fn() } as unknown as Response; - const s = dsvc({ - getFileById: vi.fn().mockReturnValue({ filename: 'pass.pkpass', original_name: 'BoardingPass.pkpass' }), - resolveFilePath: vi.fn().mockReturnValue({ resolved: real, safe: true }), - }); - new FilesDownloadController(s).download(req, localRes, '5', '9'); - expect(setHeader).toHaveBeenCalledWith('Content-Type', 'application/vnd.apple.pkpass'); - expect(setHeader).toHaveBeenCalledWith('Content-Disposition', 'inline; filename="BoardingPass.pkpass"'); - } finally { - fs.unlinkSync(real); - } + it('404 when the stored name is an invalid key (exists rejects)', async () => { + const storage = dstor({ exists: vi.fn().mockRejectedValue(new Error('invalid storage key')) }); + expect(await rejected(new FilesDownloadController(dsvc(), storage).download(req, res, '5', '9'))).toEqual({ status: 404, body: { error: 'File not found' } }); }); - it('serves a .pkpasses bundle inline with its own Wallet MIME type', () => { - const real = path.join(os.tmpdir(), `trek-pass-${Date.now()}.pkpasses`); - fs.writeFileSync(real, 'x'); - try { - const setHeader = vi.fn(); - const localRes = { setHeader, sendFile: vi.fn() } as unknown as Response; - const s = dsvc({ - getFileById: vi.fn().mockReturnValue({ filename: 'passes.pkpasses', original_name: 'BoardingPasses.pkpasses' }), - resolveFilePath: vi.fn().mockReturnValue({ resolved: real, safe: true }), - }); - new FilesDownloadController(s).download(req, localRes, '5', '9'); - expect(setHeader).toHaveBeenCalledWith('Content-Type', 'application/vnd.apple.pkpasses'); - expect(setHeader).toHaveBeenCalledWith('Content-Disposition', 'inline; filename="BoardingPasses.pkpasses"'); - } finally { - fs.unlinkSync(real); - } + it('streams a regular file through storage with no wallet headers', async () => { + const storage = dstor(); + await new FilesDownloadController(dsvc(), storage).download(req, res, '5', '9'); + expect(storage.exists).toHaveBeenCalledWith('files', 'x.pdf'); + expect(storage.sendToResponse).toHaveBeenCalledWith('files', 'x.pdf', res, undefined); }); - it('falls back to the resolved basename when a .pkpass has no original name', () => { - const real = path.join(os.tmpdir(), `trek-pass-${Date.now()}.pkpass`); - fs.writeFileSync(real, 'x'); - try { - const setHeader = vi.fn(); - const localRes = { setHeader, sendFile: vi.fn() } as unknown as Response; - const s = dsvc({ - getFileById: vi.fn().mockReturnValue({ filename: 'pass.pkpass', original_name: null }), - resolveFilePath: vi.fn().mockReturnValue({ resolved: real, safe: true }), - }); - new FilesDownloadController(s).download(req, localRes, '5', '9'); - expect(setHeader).toHaveBeenCalledWith('Content-Disposition', `inline; filename="${path.basename(real)}"`); - } finally { - fs.unlinkSync(real); - } + it('tolerates a stray prefixed row via basename, like resolveFilePath did', async () => { + const storage = dstor(); + const s = dsvc({ getFileById: vi.fn().mockReturnValue({ filename: 'files/x.pdf', original_name: 'x.pdf' }) }); + await new FilesDownloadController(s, storage).download(req, res, '5', '9'); + expect(storage.sendToResponse).toHaveBeenCalledWith('files', 'x.pdf', res, undefined); + }); + + it('serves a .pkpass inline with the Wallet MIME type and the original name', async () => { + const storage = dstor(); + const s = dsvc({ getFileById: vi.fn().mockReturnValue({ filename: 'pass.pkpass', original_name: 'BoardingPass.pkpass' }) }); + await new FilesDownloadController(s, storage).download(req, res, '5', '9'); + expect(storage.sendToResponse).toHaveBeenCalledWith('files', 'pass.pkpass', res, { + contentType: 'application/vnd.apple.pkpass', + disposition: 'inline; filename="BoardingPass.pkpass"', + }); + }); + + it('serves a .pkpasses bundle inline with its own Wallet MIME type', async () => { + const storage = dstor(); + const s = dsvc({ getFileById: vi.fn().mockReturnValue({ filename: 'passes.pkpasses', original_name: 'BoardingPasses.pkpasses' }) }); + await new FilesDownloadController(s, storage).download(req, res, '5', '9'); + expect(storage.sendToResponse).toHaveBeenCalledWith('files', 'passes.pkpasses', res, { + contentType: 'application/vnd.apple.pkpasses', + disposition: 'inline; filename="BoardingPasses.pkpasses"', + }); + }); + + it('falls back to the stored basename when a .pkpass has no original name', async () => { + const storage = dstor(); + const s = dsvc({ getFileById: vi.fn().mockReturnValue({ filename: 'pass.pkpass', original_name: null }) }); + await new FilesDownloadController(s, storage).download(req, res, '5', '9'); + expect(storage.sendToResponse).toHaveBeenCalledWith('files', 'pass.pkpass', res, { + contentType: 'application/vnd.apple.pkpass', + disposition: 'inline; filename="pass.pkpass"', + }); }); });