diff --git a/lib/Controller/FileController.php b/lib/Controller/FileController.php index e1d6fa13db..5e4228745c 100644 --- a/lib/Controller/FileController.php +++ b/lib/Controller/FileController.php @@ -572,6 +572,7 @@ private function getMimeFallbackResponse(string $mimeType): ?\OCP\AppFramework\H * * Send a new file to Nextcloud and return the fileId used to create a signature request. * Files must be uploaded as multipart/form-data with field name 'file[]' or 'files[]'. + * Multipart clients can send optional expectedFilesCount to reject incomplete batches. * * **Note on multiple file uploads:** * PHP has a limit on the number of files that can be uploaded in a single request (max_file_uploads directive, default 20). @@ -601,7 +602,11 @@ public function save( try { $this->signingRequestValidator->canRequestSign($this->userSession->getUser()); - $normalizedFiles = $this->prepareFilesForSaving($file, $files, $settings); + $uploadedFiles = $this->request->getUploadedFile('files') ?: $this->request->getUploadedFile('file'); + $normalizedFiles = $this->prepareFilesForSaving($file, $files, $settings, $uploadedFiles); + if ($uploadedFiles) { + $this->assertExpectedUploadedFileCount(count($normalizedFiles)); + } return $this->saveFiles($normalizedFiles, $name, $settings); } catch (LibresignException $e) { @@ -619,6 +624,7 @@ public function save( * * Add one or more files to an existing envelope that is in DRAFT status. * Files must be uploaded as multipart/form-data with field name 'files[]'. + * Multipart clients can send optional expectedFilesCount to reject incomplete batches. * * @param string $uuid The UUID of the envelope * @return DataResponse|DataResponse @@ -659,6 +665,7 @@ public function addFileToEnvelope(string $uuid): DataResponse { } $normalizedFiles = $this->processUploadedFiles($uploadedFiles); + $this->assertExpectedUploadedFileCount(count($normalizedFiles)); $addedFiles = []; foreach ($normalizedFiles as $fileData) { @@ -750,9 +757,7 @@ private function prepareFileForSaving(array $fileData, string $name, array $sett /** * @return list Normalized files array */ - private function prepareFilesForSaving(array $file, array $files, array $settings): array { - $uploadedFiles = $this->request->getUploadedFile('files') ?: $this->request->getUploadedFile('file'); - + private function prepareFilesForSaving(array $file, array $files, array $settings, ?array $uploadedFiles): array { if ($uploadedFiles) { return $this->processUploadedFiles($uploadedFiles); } @@ -776,6 +781,24 @@ private function prepareFilesForSaving(array $file, array $files, array $setting throw new LibresignException($this->l10n->t('File or files parameter is required')); } + /** + * Detect uploads silently truncated by PHP's max_file_uploads limit. + * Clients may omit the count for backwards compatibility. + */ + private function assertExpectedUploadedFileCount(int $receivedCount): void { + $declaredCount = $this->request->getParam('expectedFilesCount'); + if ($declaredCount === null) { + return; + } + if ((!is_string($declaredCount) && !is_int($declaredCount)) + || !ctype_digit((string)$declaredCount) + || (string)(int)$declaredCount !== (string)$declaredCount + || (int)$declaredCount !== $receivedCount) { + // TRANSLATORS Error shown when the number of uploaded documents differs from the count declared by the client. + throw new LibresignException($this->l10n->t('The number of uploaded files does not match the expected count')); + } + } + /** * @return list */ diff --git a/openapi-full.json b/openapi-full.json index 567fa483c0..bec17f3a83 100644 --- a/openapi-full.json +++ b/openapi-full.json @@ -6614,7 +6614,7 @@ "post": { "operationId": "file-save", "summary": "Send a file", - "description": "Send a new file to Nextcloud and return the fileId used to create a signature request. Files must be uploaded as multipart/form-data with field name 'file[]' or 'files[]'.\n**Note on multiple file uploads:** PHP has a limit on the number of files that can be uploaded in a single request (max_file_uploads directive, default 20). When uploading many files (more than 20), consider uploading them sequentially in multiple requests or use individual file uploads like the Files app does.", + "description": "Send a new file to Nextcloud and return the fileId used to create a signature request. Files must be uploaded as multipart/form-data with field name 'file[]' or 'files[]'. Multipart clients can send optional expectedFilesCount to reject incomplete batches.\n**Note on multiple file uploads:** PHP has a limit on the number of files that can be uploaded in a single request (max_file_uploads directive, default 20). When uploading many files (more than 20), consider uploading them sequentially in multiple requests or use individual file uploads like the Files app does.", "tags": [ "documents" ], @@ -6781,7 +6781,7 @@ "post": { "operationId": "file-add-file-to-envelope", "summary": "Add file to envelope", - "description": "Add one or more files to an existing envelope that is in DRAFT status. Files must be uploaded as multipart/form-data with field name 'files[]'.", + "description": "Add one or more files to an existing envelope that is in DRAFT status. Files must be uploaded as multipart/form-data with field name 'files[]'. Multipart clients can send optional expectedFilesCount to reject incomplete batches.", "tags": [ "documents" ], diff --git a/openapi.json b/openapi.json index bdd25f2ca3..e1e90ebafd 100644 --- a/openapi.json +++ b/openapi.json @@ -6072,7 +6072,7 @@ "post": { "operationId": "file-save", "summary": "Send a file", - "description": "Send a new file to Nextcloud and return the fileId used to create a signature request. Files must be uploaded as multipart/form-data with field name 'file[]' or 'files[]'.\n**Note on multiple file uploads:** PHP has a limit on the number of files that can be uploaded in a single request (max_file_uploads directive, default 20). When uploading many files (more than 20), consider uploading them sequentially in multiple requests or use individual file uploads like the Files app does.", + "description": "Send a new file to Nextcloud and return the fileId used to create a signature request. Files must be uploaded as multipart/form-data with field name 'file[]' or 'files[]'. Multipart clients can send optional expectedFilesCount to reject incomplete batches.\n**Note on multiple file uploads:** PHP has a limit on the number of files that can be uploaded in a single request (max_file_uploads directive, default 20). When uploading many files (more than 20), consider uploading them sequentially in multiple requests or use individual file uploads like the Files app does.", "tags": [ "documents" ], @@ -6239,7 +6239,7 @@ "post": { "operationId": "file-add-file-to-envelope", "summary": "Add file to envelope", - "description": "Add one or more files to an existing envelope that is in DRAFT status. Files must be uploaded as multipart/form-data with field name 'files[]'.", + "description": "Add one or more files to an existing envelope that is in DRAFT status. Files must be uploaded as multipart/form-data with field name 'files[]'. Multipart clients can send optional expectedFilesCount to reject incomplete batches.", "tags": [ "documents" ], diff --git a/src/components/Request/RequestPicker.vue b/src/components/Request/RequestPicker.vue index af08106ee5..037a02b02b 100644 --- a/src/components/Request/RequestPicker.vue +++ b/src/components/Request/RequestPicker.vue @@ -342,6 +342,7 @@ async function upload(files: UploadFile[], selectedEnvelopeName: string | null = uploadStartTime.value = Date.now() const formData = new FormData() + formData.append('expectedFilesCount', String(files.length)) if (files.length === 1) { const name = files[0].name.replace(/\.pdf$/i, '') diff --git a/src/components/RightSidebar/EnvelopeFilesList.vue b/src/components/RightSidebar/EnvelopeFilesList.vue index 8ec61c4136..cc133631e8 100644 --- a/src/components/RightSidebar/EnvelopeFilesList.vue +++ b/src/components/RightSidebar/EnvelopeFilesList.vue @@ -512,6 +512,7 @@ function addFileToEnvelope() { uploadStartTime.value = Date.now() const formData = new FormData() + formData.append('expectedFilesCount', String(selectedFileList.length)) let aggregateSize = 0 for (const file of selectedFileList) { diff --git a/src/tests/components/Request/RequestPicker.spec.ts b/src/tests/components/Request/RequestPicker.spec.ts index fda67f8d25..aa2a0f3a0c 100644 --- a/src/tests/components/Request/RequestPicker.spec.ts +++ b/src/tests/components/Request/RequestPicker.spec.ts @@ -678,6 +678,7 @@ describe('RequestPicker component rules', () => { expect(filesStore.upload).toHaveBeenCalled() const [formData] = filesStore.upload.mock.calls[0] as [FormData, { onUploadProgress?: (event: { loaded: number; total: number }) => void } | undefined] expect(formData.get('name')).toBe('document') + expect(formData.get('expectedFilesCount')).toBe('1') }) it('sets upload progress when receiving upload events', async () => { @@ -744,6 +745,8 @@ describe('RequestPicker component rules', () => { expect(filesStore.upload).toHaveBeenCalled() const [formData] = filesStore.upload.mock.calls[0] as [FormData, { onUploadProgress?: (event: { loaded: number; total: number }) => void } | undefined] expect(formData.get('name')).toBe('My Envelope') + expect(formData.get('expectedFilesCount')).toBe('2') + expect(formData.getAll('files[]')).toHaveLength(2) }) it('trims envelope name before upload', async () => { diff --git a/src/tests/components/RightSidebar/EnvelopeFilesList.spec.ts b/src/tests/components/RightSidebar/EnvelopeFilesList.spec.ts index c817890321..b858b286eb 100644 --- a/src/tests/components/RightSidebar/EnvelopeFilesList.spec.ts +++ b/src/tests/components/RightSidebar/EnvelopeFilesList.spec.ts @@ -79,6 +79,7 @@ type EnvelopeFilesListVm = { isTouchDevice: boolean getMaxFileUploads: () => number validateMaxFileUploads: (filesCount: number) => boolean + addFileToEnvelope: () => void getPreviewUrl: (file: Partial) => string | null openFile: (file: EnvelopeFileRecord) => void isSelected: (fileId: number) => boolean @@ -363,6 +364,41 @@ describe('EnvelopeFilesList', () => { }) }) + describe('RULE: multipart envelope upload', () => { + it('sends two files with matching declared count', async () => { + getCapabilitiesMock.mockReturnValue({ + libresign: { + config: { + envelope: { 'is-available': true }, + upload: { 'max-file-uploads': 20 }, + }, + }, + }) + filesStore.selectedFile = { id: 1, uuid: 'envelope-uuid', status: FILE_STATUS.DRAFT } + wrapper = createWrapper() + vi.mocked(axios.post).mockResolvedValue({ + data: { ocs: { data: { files: [], filesCount: 2, message: 'Files added' } } }, + }) + const createElementSpy = vi.spyOn(document, 'createElement') + wrapper.vm.addFileToEnvelope() + const input = createElementSpy.mock.results + .find(result => result.value?.type === 'file')?.value as HTMLInputElement + expect(input).toBeDefined() + Object.defineProperty(input, 'files', { + value: [ + new File(['a'], 'one.pdf', { type: 'application/pdf' }), + new File(['b'], 'two.pdf', { type: 'application/pdf' }), + ], + configurable: true, + }) + await input.onchange?.({ target: input } as unknown as Event) + const multipart = vi.mocked(axios.post).mock.calls[0][1] as FormData + expect(multipart.get('expectedFilesCount')).toBe('2') + expect(multipart.getAll('files[]')).toHaveLength(2) + createElementSpy.mockRestore() + }) + }) + describe('RULE: getPreviewUrl constructs thumbnail URL with parameters', () => { it('prefers file id URLs and appends preview parameters', () => { wrapper = createWrapper() diff --git a/src/types/openapi/openapi-full.ts b/src/types/openapi/openapi-full.ts index 84d80aa12f..3945c2a5c7 100644 --- a/src/types/openapi/openapi-full.ts +++ b/src/types/openapi/openapi-full.ts @@ -308,7 +308,7 @@ export type paths = { put?: never; /** * Send a file - * @description Send a new file to Nextcloud and return the fileId used to create a signature request. Files must be uploaded as multipart/form-data with field name 'file[]' or 'files[]'. + * @description Send a new file to Nextcloud and return the fileId used to create a signature request. Files must be uploaded as multipart/form-data with field name 'file[]' or 'files[]'. Multipart clients can send optional expectedFilesCount to reject incomplete batches. * **Note on multiple file uploads:** PHP has a limit on the number of files that can be uploaded in a single request (max_file_uploads directive, default 20). When uploading many files (more than 20), consider uploading them sequentially in multiple requests or use individual file uploads like the Files app does. */ post: operations["file-save"]; @@ -329,7 +329,7 @@ export type paths = { put?: never; /** * Add file to envelope - * @description Add one or more files to an existing envelope that is in DRAFT status. Files must be uploaded as multipart/form-data with field name 'files[]'. + * @description Add one or more files to an existing envelope that is in DRAFT status. Files must be uploaded as multipart/form-data with field name 'files[]'. Multipart clients can send optional expectedFilesCount to reject incomplete batches. */ post: operations["file-add-file-to-envelope"]; delete?: never; diff --git a/src/types/openapi/openapi.ts b/src/types/openapi/openapi.ts index 592e6f3506..69a860ffff 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -308,7 +308,7 @@ export type paths = { put?: never; /** * Send a file - * @description Send a new file to Nextcloud and return the fileId used to create a signature request. Files must be uploaded as multipart/form-data with field name 'file[]' or 'files[]'. + * @description Send a new file to Nextcloud and return the fileId used to create a signature request. Files must be uploaded as multipart/form-data with field name 'file[]' or 'files[]'. Multipart clients can send optional expectedFilesCount to reject incomplete batches. * **Note on multiple file uploads:** PHP has a limit on the number of files that can be uploaded in a single request (max_file_uploads directive, default 20). When uploading many files (more than 20), consider uploading them sequentially in multiple requests or use individual file uploads like the Files app does. */ post: operations["file-save"]; @@ -329,7 +329,7 @@ export type paths = { put?: never; /** * Add file to envelope - * @description Add one or more files to an existing envelope that is in DRAFT status. Files must be uploaded as multipart/form-data with field name 'files[]'. + * @description Add one or more files to an existing envelope that is in DRAFT status. Files must be uploaded as multipart/form-data with field name 'files[]'. Multipart clients can send optional expectedFilesCount to reject incomplete batches. */ post: operations["file-add-file-to-envelope"]; delete?: never; diff --git a/tests/php/Unit/Controller/FileControllerUploadCountTest.php b/tests/php/Unit/Controller/FileControllerUploadCountTest.php new file mode 100644 index 0000000000..ba4d1b1bdd --- /dev/null +++ b/tests/php/Unit/Controller/FileControllerUploadCountTest.php @@ -0,0 +1,63 @@ + [null, 2, true], + 'single upload' => ['1', 1, true], + 'two uploads' => ['2', 2, true], + 'integer form value' => [2, 2, true], + 'truncated upload' => ['2', 1, false], + 'unexpected extra file' => ['1', 2, false], + 'invalid string' => ['abc', 2, false], + 'invalid array' => [['2'], 2, false], + 'zero files declared' => ['0', 2, false], + 'leading zero' => ['02', 2, false], + 'integer overflow' => ['999999999999999999999999', 2, false], + ]; + } + + #[DataProvider('uploadCountProvider')] + public function testExpectedUploadCount(mixed $declaredCount, int $receivedCount, bool $accepted): void { + $request = $this->createMock(IRequest::class); + $request->expects($this->once()) + ->method('getParam') + ->with('expectedFilesCount') + ->willReturn($declaredCount); + + $l10n = $this->createMock(IL10N::class); + $l10n->method('t')->willReturnCallback(static fn (string $message): string => $message); + + $reflection = new ReflectionClass(FileController::class); + /** @var FileController $controller */ + $controller = $reflection->newInstanceWithoutConstructor(); + $reflection->getProperty('request')->setValue($controller, $request); + $reflection->getProperty('l10n')->setValue($controller, $l10n); + + if (!$accepted) { + $this->expectException(LibresignException::class); + $this->expectExceptionMessage('The number of uploaded files does not match the expected count'); + } + + (new ReflectionMethod(FileController::class, 'assertExpectedUploadedFileCount')) + ->invoke($controller, $receivedCount); + } +}