fix(journey): validate and safely serve media uploads

This commit is contained in:
Maurice
2026-12-02 09:21:51 +01:00
parent a4cb6c69d8
commit 24ddc3e4b0
5 changed files with 126 additions and 4 deletions
+12 -3
View File
@@ -24,6 +24,8 @@ import crypto from 'node:crypto';
import type { User } from '../../types';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { isDemoWriteBlocked, DEMO_WRITE_ERROR } from '../common/demo-write';
import { fileMatchesRasterType } from '../memories/media-redact';
import { journeyImageType } from '../storage/content-type';
import { StorageService } from '../storage/storage.service';
import { JourneyGalleryService } from './journey-gallery.service';
import { captureHintFrom } from './journey-capture-hint';
@@ -103,6 +105,7 @@ export function journeyImageFileFilter(allowedTypes: AllowedFileTypesService): O
err.statusCode = 400;
cb(err);
};
if (ext && !journeyImageType(file.originalname)) return reject();
// R1.5: multer's fileFilter is a callback API that cannot await, and the
// allowed-extension list is now an async read. The decision runs in a
// detached async function that always answers through `cb`; a rejection
@@ -184,12 +187,18 @@ export class JourneyController {
) {}
/**
* Commit spooled multer files to their final uploads/journey location. On any
* failure: best-effort removal of both spool leftovers and already-committed
* names, then rethrow (500) — so a DB row never references a missing file.
* Check image bytes before committing the batch. On failure, remove spool
* leftovers and any already-committed objects before the error reaches the caller.
*/
private async commitJourneyUploads(files: Express.Multer.File[]): Promise<void> {
try {
for (const file of files) {
if (file.fieldname === 'video' || file.fieldname === 'poster') continue;
const contentType = journeyImageType(file.filename);
if (!contentType || !(await fileMatchesRasterType(file.path, contentType))) {
throw new HttpException({ error: 'Invalid image file' }, 400);
}
}
for (const f of files) await this.storage.put('journey', f.filename, { tmpPath: f.path });
} catch (err) {
for (const f of files) {
+31
View File
@@ -96,6 +96,37 @@ function sniffFormat(head: Buffer): MediaFormat {
return 'unknown';
}
const PNG_SIGNATURE = Buffer.from('89504e470d0a1a0a', 'hex');
const ICON_SIGNATURE = Buffer.from([0, 0, 1, 0]);
/** Match raster headers without decoding untrusted pixel data on upload. */
export async function fileMatchesRasterType(file: string, contentType: string): Promise<boolean> {
const handle = await fsPromises.open(file, 'r');
try {
const head = await readAt(handle, 0, 16);
const format = sniffFormat(head);
switch (contentType) {
case 'image/png':
return head.subarray(0, 8).equals(PNG_SIGNATURE);
case 'image/gif':
return ['GIF87a', 'GIF89a'].includes(head.toString('latin1', 0, 6));
case 'image/avif':
case 'image/heic':
case 'image/heif':
return format === 'isobmff' && isStillImageBrand(head);
case 'image/bmp':
return head.length >= 14 && head.toString('latin1', 0, 2) === 'BM';
case 'image/vnd.microsoft.icon':
case 'image/x-icon':
return head.length >= 6 && head.subarray(0, 4).equals(ICON_SIGNATURE);
default:
return contentType === `image/${format}`;
}
} finally {
await handle.close();
}
}
// ── EXIF / TIFF ─────────────────────────────────────────────────────────────
/** 'le' or 'be' for a TIFF header at `base`, null when there is none. */
+27
View File
@@ -1,3 +1,4 @@
import { lookup } from 'mime-types';
import path from 'node:path';
/**
@@ -40,3 +41,29 @@ const MIME_BY_EXT: Record<string, string> = {
export function contentTypeFor(key: string): string {
return MIME_BY_EXT[path.extname(key).toLowerCase()] ?? 'application/octet-stream';
}
const JOURNEY_IMAGE_TYPES = new Set([
'image/avif',
'image/bmp',
'image/gif',
'image/heic',
'image/heif',
'image/jpeg',
'image/png',
'image/tiff',
'image/vnd.microsoft.icon',
'image/webp',
'image/x-icon',
]);
export function journeyImageType(key: string): string | undefined {
const type = lookup(key);
return type && JOURNEY_IMAGE_TYPES.has(type) ? type : undefined;
}
export function journeyInlineType(key: string): string | undefined {
const type = contentTypeFor(key);
if (type.startsWith('video/')) return type;
if (path.extname(key).toLowerCase() === '.m4v') return 'video/mp4';
return journeyImageType(key);
}
+12 -1
View File
@@ -1,6 +1,6 @@
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { logDebug } from '../audit/audit-log.logger';
import { contentTypeFor } from './content-type';
import { contentTypeFor, journeyInlineType } from './content-type';
import type { ReplicaFailure } from './drivers/mirror.driver';
import { decideRange, isNotModified, validatorsFor, type ServingHeaders, type Validators } from './http-serving';
import { assertValidKey } from './storage-keys';
@@ -193,6 +193,17 @@ export class StorageService {
async sendToResponse(category: ServedCategory, name: string, res: Response, opts?: SendOptions): Promise<void> {
const { driver, key } = this.resolve(category, name);
if (category === 'journey') {
// Older uploads can have arbitrary extensions. Use the same response policy
// for local and remote objects, including when a browser opens one directly.
const contentType = journeyInlineType(name);
opts = contentType
? { ...opts, contentType }
: { contentType: 'application/octet-stream', disposition: 'attachment' };
res.setHeader('Content-Security-Policy', 'sandbox');
res.setHeader('X-Content-Type-Options', 'nosniff');
}
const localPath = this.localPathIfPresent(driver, key);
if (localPath !== null) {
this.applyHeaders(res, opts);
@@ -10,12 +10,14 @@
*/
import { buildApp } from '../../src/bootstrap';
import { Addons } from '../../src/db/entities/Addons.entity';
import { JourneyPhotos } from '../../src/db/entities/JourneyPhotos.entity';
import { Photos } from '../../src/db/entities/Photos.entity';
import { TrekPhotos } from '../../src/db/entities/TrekPhotos.entity';
import { authCookie, generateToken } from '../helpers/auth';
import { jpegWithExif } from '../helpers/exif-jpeg';
import { makeJourney } from '../helpers/factories/journeys';
import { findRow, insertRow, upsertRow } from '../helpers/factories/rows';
import { setAppSetting } from '../helpers/factories/settings';
import { makeShareToken, makeTrip } from '../helpers/factories/trips';
import { makeUser } from '../helpers/factories/users';
import { resetDatabase } from '../helpers/reset-database';
@@ -123,6 +125,9 @@ describe('journey share link', () => {
const owned = await bytes(request(app).get(`/api/photos/${photoId}/original`).set('Cookie', authCookie(user.id)));
expect(owned.status).toBe(200);
expect(owned.headers['content-type']).toBe('image/jpeg');
expect(owned.headers['content-disposition']).toBeUndefined();
expect(owned.headers['content-security-policy']).toBe('sandbox');
expect(await gpsOf(owned.body as Buffer)).toBeCloseTo(GPS.lat, 5);
});
@@ -150,6 +155,45 @@ describe('journey share link', () => {
});
});
describe('Journey media format', () => {
it.each(['document.txt', 'invalid.png'])(
'rejects %s submitted as a photo even with wildcard uploads',
async (filename) => {
const { user } = await makeUser(orm);
const journey = await makeJourney(orm, user.id);
await setAppSetting(orm, 'allowed_file_types', '*');
await request(app)
.post(`/api/journeys/${journey.id}/gallery/photos`)
.set('Cookie', authCookie(user.id))
.attach('photos', Buffer.from('not an image'), { filename, contentType: 'image/png' })
.expect(400);
expect(await findRow(orm, JourneyPhotos, { journey: journey.id })).toBeNull();
},
);
it('serves a legacy document stored as a Journey photo as a download', async () => {
const { user } = await makeUser(orm);
const journey = await makeJourney(orm, user.id);
const name = 'pubmedia-legacy.integration.html';
const data = Buffer.from('legacy document fixture');
fs.mkdirSync(path.join(uploadsDir, 'journey'), { recursive: true });
fs.writeFileSync(path.join(uploadsDir, 'journey', name), data);
track('journey', name);
const photoId = await insertRow(orm, TrekPhotos, { provider: 'local', file_path: `journey/${name}` });
await insertRow(orm, JourneyPhotos, { journey: journey.id, photo: photoId, created_at: Date.now() });
const res = await bytes(request(app).get(`/api/photos/${photoId}/original`).set('Cookie', authCookie(user.id)));
expect(res.status).toBe(200);
expect(res.headers['content-type']).toBe('application/octet-stream');
expect(res.headers['content-disposition']).toBe('attachment');
expect(res.headers['content-security-policy']).toBe('sandbox');
expect(res.headers['x-content-type-options']).toBe('nosniff');
expect(res.body).toEqual(data);
});
});
describe('/uploads/journey', () => {
it('PUBMEDIA-010: serves a cover, location-free, and 404s an entry photo for everyone', async () => {
const { user } = await makeUser(orm);