The minimalistic document archiving platform.
fix(upload): properly handle file-too-big errors (#491)
Corentin Thomassetbb9d5556d3f1
diff --git a/.changeset/curly-cases-wash.md b/.changeset/curly-cases-wash.mdnew file mode 100644index 00000000..9c107c8f--- /dev/null+++ b/.changeset/curly-cases-wash.md@@ -0,0 +1,5 @@+---+"@papra/app-server": patch+---++Fix cleanup state when a too-big-file is uploadeddiff --git a/apps/papra-server/src/modules/documents/documents.constants.test.ts b/apps/papra-server/src/modules/documents/documents.constants.test.tsnew file mode 100644index 00000000..c689b4ea--- /dev/null+++ b/apps/papra-server/src/modules/documents/documents.constants.test.ts@@ -0,0 +1,21 @@+import { Buffer } from 'node:buffer';+import { describe, expect, test } from 'vitest';+import { MULTIPART_FORM_DATA_SINGLE_FILE_CONTENT_LENGTH_OVERHEAD } from './documents.constants';++const unusuallyLongFileName = 'an-unusually-long-file-name-in-order-to-test-the-content-length-header-with-the-metadata-that-are-included-in-the-form-data-so-lorem-ipsum-dolor-sit-amet-consectetur-adipiscing-elit-sed-do-eiusmod-tempor-incididunt-ut-labore-et-dolore-magna-aliqua-ut-enim-ad-minim-veniam-quis-nostrud-exercitation-ullamco-laboris-nisi-ut-aliquip-ex-ea-commodo-consequat-duis-aute-irure-dolor-in-reprehenderit-in-voluptate-velit-esse-cillum-dolore-eu-fugiat-nulla-pariatur-excepteur-sint-occaecat-proident-in-voluptate-velit-esse-cillum-dolore-eu-fugiat-nulla-pariatur-excepteur-sint-occaecat-proident-in-voluptate-velit-esse-cillum-dolore-eu-fugiat-nulla-pariatur-excepteur-sint-occaecat-proident.txt';++describe('documents constants', () => {+ // eslint-disable-next-line test/prefer-lowercase-title+ describe('MULTIPART_FORM_DATA_SINGLE_FILE_CONTENT_LENGTH_OVERHEAD', () => {+ test('when uploading a formdata multipart, the body has boundaries and other metadata, so the content length is greater than the file size', async () => {+ const fileSize = 100;+ const formData = new FormData();+ formData.append('file', new File(['a'.repeat(fileSize)], unusuallyLongFileName, { type: 'text/plain' }));+ const body = new Response(formData);+ const contentLength = Buffer.from(await body.arrayBuffer()).length;++ expect(contentLength).to.be.greaterThan(fileSize);+ expect(contentLength).to.be.lessThan(fileSize + MULTIPART_FORM_DATA_SINGLE_FILE_CONTENT_LENGTH_OVERHEAD);+ });+ });+});diff --git a/apps/papra-server/src/modules/documents/documents.constants.ts b/apps/papra-server/src/modules/documents/documents.constants.tsindex aa09a047..72b63cfc 100644--- a/apps/papra-server/src/modules/documents/documents.constants.ts+++ b/apps/papra-server/src/modules/documents/documents.constants.ts@@ -11,3 +11,6 @@ export const ORIGINAL_DOCUMENTS_STORAGE_KEY = 'originals';// import { ocrLanguages } from '@papra/lecture';// console.log(JSON.stringify(ocrLanguages));export const OCR_LANGUAGES = ['afr', 'amh', 'ara', 'asm', 'aze', 'aze_cyrl', 'bel', 'ben', 'bod', 'bos', 'bul', 'cat', 'ceb', 'ces', 'chi_sim', 'chi_tra', 'chr', 'cym', 'dan', 'deu', 'dzo', 'ell', 'eng', 'enm', 'epo', 'est', 'eus', 'fas', 'fin', 'fra', 'frk', 'frm', 'gle', 'glg', 'grc', 'guj', 'hat', 'heb', 'hin', 'hrv', 'hun', 'iku', 'ind', 'isl', 'ita', 'ita_old', 'jav', 'jpn', 'kan', 'kat', 'kat_old', 'kaz', 'khm', 'kir', 'kor', 'kur', 'lao', 'lat', 'lav', 'lit', 'mal', 'mar', 'mkd', 'mlt', 'msa', 'mya', 'nep', 'nld', 'nor', 'ori', 'pan', 'pol', 'por', 'pus', 'ron', 'rus', 'san', 'sin', 'slk', 'slv', 'spa', 'spa_old', 'sqi', 'srp', 'srp_latn', 'swa', 'swe', 'syr', 'tam', 'tel', 'tgk', 'tgl', 'tha', 'tir', 'tur', 'uig', 'ukr', 'urd', 'uzb', 'uzb_cyrl', 'vie', 'yid'] as const;++// When uploading a formdata multipart, the body has boundaries and other metadata that need to be accounted for+export const MULTIPART_FORM_DATA_SINGLE_FILE_CONTENT_LENGTH_OVERHEAD = 1024; // 1024 bytesdiff --git a/apps/papra-server/src/modules/documents/documents.routes.ts b/apps/papra-server/src/modules/documents/documents.routes.tsindex f8b7eee3..d283ff5d 100644--- a/apps/papra-server/src/modules/documents/documents.routes.ts+++ b/apps/papra-server/src/modules/documents/documents.routes.ts@@ -13,7 +13,7 @@ import { deferTriggerWebhooks } from '../webhooks/webhook.usecases';import { createDocumentActivityRepository } from './document-activity/document-activity.repository';import { deferRegisterDocumentActivityLog } from './document-activity/document-activity.usecases';import { createDocumentIsNotDeletedError } from './documents.errors';-import { formatDocumentForApi, formatDocumentsForApi } from './documents.models';+import { formatDocumentForApi, formatDocumentsForApi, isDocumentSizeLimitEnabled } from './documents.models';import { createDocumentsRepository } from './documents.repository';import { documentIdSchema } from './documents.schemas';import { createDocumentCreationUsecase, deleteAllTrashDocuments, deleteTrashDocument, ensureDocumentExists, getDocumentOrThrow } from './documents.usecases';@@ -34,6 +34,8 @@ export function registerDocumentsRoutes(context: RouteDefinitionContext) {}function setupCreateDocumentRoute({ app, ...deps }: RouteDefinitionContext) {+ const { config } = deps;+app.post('/api/organizations/:organizationId/documents',requireAuthentication({ apiKeyPermissions: ['documents:create'] }),@@ -44,9 +46,12 @@ function setupCreateDocumentRoute({ app, ...deps }: RouteDefinitionContext) {const { userId } = getUser({ context });const { organizationId } = context.req.valid('param');+ const { maxUploadSize } = config.documentsStorage;+const { fileStream, fileName, mimeType } = await getFileStreamFromMultipartForm({body: context.req.raw.body,headers: context.req.header(),+ maxFileSize: isDocumentSizeLimitEnabled({ maxUploadSize }) ? maxUploadSize : undefined,});const createDocument = createDocumentCreationUsecase({ ...deps });diff --git a/apps/papra-server/src/modules/documents/documents.usecases.ts b/apps/papra-server/src/modules/documents/documents.usecases.tsindex 2fa5fb77..00e0e3ea 100644--- a/apps/papra-server/src/modules/documents/documents.usecases.ts+++ b/apps/papra-server/src/modules/documents/documents.usecases.ts@@ -14,6 +14,8 @@ import type { DocumentsRepository } from './documents.repository';import type { Document } from './documents.types';import type { DocumentStorageService } from './storage/documents.storage.services';import type { EncryptionContext } from './storage/drivers/drivers.models';+import { PassThrough } from 'node:stream';+import { pipeline } from 'node:stream/promises';import { safely } from '@corentinth/chisels';import pLimit from 'p-limit';import { createOrganizationDocumentStorageLimitReachedError } from '../organizations/organizations.errors';@@ -101,17 +103,27 @@ export async function createDocument({},});- const outputStream = fileStream- .pipe(hashStream)- .pipe(byteCountStream);+ // Create a PassThrough stream that will be used for saving the file+ // This allows us to use pipeline for better error handling+ const outputStream = new PassThrough();++ const streamProcessingPromise = pipeline(+ fileStream,+ hashStream,+ byteCountStream,+ outputStream,+ );// We optimistically save the file to leverage streaming, if the file already exists, we will delete it- const newFileStorageContext = await documentsStorageService.saveFile({- fileStream: outputStream,- storageKey: originalDocumentStorageKey,- mimeType,- fileName,- });+ const [newFileStorageContext] = await Promise.all([+ documentsStorageService.saveFile({+ fileStream: outputStream,+ storageKey: originalDocumentStorageKey,+ mimeType,+ fileName,+ }),+ streamProcessingPromise,+ ]);const hash = getHash();const size = getByteCount();diff --git a/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.ts b/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.tsindex 22c115f6..a2f0d2b1 100644--- a/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.ts+++ b/apps/papra-server/src/modules/documents/storage/drivers/fs/fs.storage-driver.ts@@ -37,6 +37,14 @@ export const fsStorageDriverFactory = defineStorageDriver(({ documentStorageConfwriteStream.on('error', (error) => {reject(error);});++ // Listen for errors on the input stream as well+ fileStream.on('error', (error) => {+ // Clean up the write stream and file+ writeStream.destroy();+ fs.unlink(storagePath, () => {}); // Ignore errors when cleaning up+ reject(error);+ });});},getFileStream: async ({ storageKey }) => {diff --git a/apps/papra-server/src/modules/shared/headers/headers.models.ts b/apps/papra-server/src/modules/shared/headers/headers.models.tsindex 1e387d3a..a819357f 100644--- a/apps/papra-server/src/modules/shared/headers/headers.models.ts+++ b/apps/papra-server/src/modules/shared/headers/headers.models.ts@@ -1,4 +1,5 @@import type { Context } from '../../app/server.types';+import { isNil } from '../utils';export function getHeader({ context, name }: { context: Context; name: string }) {return context.req.header(name);@@ -15,3 +16,13 @@ export function getImpersonatedUserIdFromHeader({ context }: { context: Contextreturn { impersonatedUserId };}++export function getContentLengthHeader({ headers }: { headers: Record<string, string> }): number | undefined {+ const contentLengthHeaderValue = headers['content-length'] ?? headers['Content-Length'];++ if (isNil(contentLengthHeaderValue)) {+ return undefined;+ }++ return Number(contentLengthHeaderValue);+}diff --git a/apps/papra-server/src/modules/shared/streams/file-upload.test.ts b/apps/papra-server/src/modules/shared/streams/file-upload.test.tsnew file mode 100644index 00000000..6dd4e887--- /dev/null+++ b/apps/papra-server/src/modules/shared/streams/file-upload.test.ts@@ -0,0 +1,51 @@+import { describe, expect, test } from 'vitest';+import { isContentLengthPessimisticallyTooLarge } from './file-upload';++describe('file-upload', () => {+ describe('isContentLengthPessimisticallyTooLarge', () => {+ test(`a file upload request is considered pessimistically too large when+ - a content length header is present+ - a max file size limit is provided+ - the content length is greater than the max file size limit plus an over-estimated overhead due to the multipart form data (boundaries, metadata, etc)`, () => {+ expect(+ isContentLengthPessimisticallyTooLarge({+ contentLength: 1_000,+ maxFileSize: 1_000,+ overhead: 512,+ }),+ ).to.eql(false);++ expect(+ isContentLengthPessimisticallyTooLarge({+ contentLength: undefined,+ maxFileSize: 1_000,+ overhead: 512,+ }),+ ).to.eql(false);++ expect(+ isContentLengthPessimisticallyTooLarge({+ contentLength: 1_000,+ maxFileSize: undefined,+ overhead: 512,+ }),+ ).to.eql(false);++ expect(+ isContentLengthPessimisticallyTooLarge({+ contentLength: undefined,+ maxFileSize: undefined,+ overhead: 512,+ }),+ ).to.eql(false);++ expect(+ isContentLengthPessimisticallyTooLarge({+ contentLength: 1_513,+ maxFileSize: 1_000,+ overhead: 512,+ }),+ ).to.eql(true);+ });+ });+});diff --git a/apps/papra-server/src/modules/shared/streams/file-upload.ts b/apps/papra-server/src/modules/shared/streams/file-upload.tsindex 6ef3cdd9..31b56331 100644--- a/apps/papra-server/src/modules/shared/streams/file-upload.ts+++ b/apps/papra-server/src/modules/shared/streams/file-upload.ts@@ -1,18 +1,41 @@import type { Logger } from '../logger/logger';import { Readable } from 'node:stream';import createBusboy from 'busboy';+import { MULTIPART_FORM_DATA_SINGLE_FILE_CONTENT_LENGTH_OVERHEAD } from '../../documents/documents.constants';+import { createDocumentSizeTooLargeError } from '../../documents/documents.errors';import { createError } from '../errors/errors';+import { getContentLengthHeader } from '../headers/headers.models';import { createLogger } from '../logger/logger';+import { isNil } from '../utils';++// Early check to avoid parsing the stream if the content length is set and too large+export function isContentLengthPessimisticallyTooLarge({+ contentLength,+ maxFileSize,+ overhead = MULTIPART_FORM_DATA_SINGLE_FILE_CONTENT_LENGTH_OVERHEAD,+}: {+ contentLength?: number;+ maxFileSize?: number;+ overhead?: number;+}) {+ if (isNil(contentLength) || isNil(maxFileSize)) {+ return false;+ }++ return contentLength > maxFileSize + overhead;+}export async function getFileStreamFromMultipartForm({body,headers,fieldName = 'file',+ maxFileSize,logger = createLogger({ namespace: 'file-upload' }),}: {body: ReadableStream | null | undefined;headers: Record<string, string>;fieldName?: string;+ maxFileSize?: number;logger?: Logger;}) {if (!body) {@@ -23,12 +46,20 @@ export async function getFileStreamFromMultipartForm({});}+ const contentLength = getContentLengthHeader({ headers });+ if (isContentLengthPessimisticallyTooLarge({ contentLength, maxFileSize })) {+ logger.debug({ contentLength, maxFileSize }, 'Content length is pessimistically too large');++ throw createDocumentSizeTooLargeError();+ }+const { promise, resolve, reject } = Promise.withResolvers<{ fileStream: Readable; fileName: string; mimeType: string }>();const bb = createBusboy({headers,limits: {files: 1, // Only allow one file+ fileSize: maxFileSize,},}).on('file', (formFieldname, fileStream, info) => {@@ -44,6 +75,11 @@ export async function getFileStreamFromMultipartForm({}));}+ fileStream.on('limit', () => {+ logger.info({ contentLength, maxFileSize }, 'File stream limit reached');+ fileStream.destroy(createDocumentSizeTooLargeError());+ });+resolve({fileStream,fileName: info.filename,