diff --git a/lib/Controller/FileController.php b/lib/Controller/FileController.php index 97d25327c5..2d6de86d83 100644 --- a/lib/Controller/FileController.php +++ b/lib/Controller/FileController.php @@ -535,6 +535,7 @@ private function getMimeFallbackResponse(string $mimeType): ?\OCP\AppFramework\H * * Send a new file to Nextcloud and return the fileId to request signature. * 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). @@ -562,8 +563,13 @@ public function save( ): DataResponse { try { $this->validateHelper->canRequestSign($this->userSession->getUser()); + $this->assertExclusiveFileInputSources($file, $files, $this->request->getUploadedFile('file'), $this->request->getUploadedFile('files')); - $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) { @@ -581,6 +587,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 @@ -617,6 +624,7 @@ public function addFileToEnvelope(string $uuid): DataResponse { } $normalizedFiles = $this->processUploadedFiles($uploadedFiles); + $this->assertExpectedUploadedFileCount(count($normalizedFiles)); $addedFiles = []; foreach ($normalizedFiles as $fileData) { @@ -705,9 +713,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); } @@ -724,6 +730,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 */ @@ -763,6 +787,18 @@ private function processUploadedFiles(array $uploadedFiles): array { return $filesArray; } + /** + * Reject ambiguous request payloads before processing the uploaded files. + */ + private function assertExclusiveFileInputSources(array $file, array $files, ?array $singleUploadedFile, ?array $multipleUploadedFiles): void { + if (($file && $files) + || ($singleUploadedFile && $multipleUploadedFiles) + || (($file || $files) && ($singleUploadedFile || $multipleUploadedFiles))) { + // TRANSLATORS Error shown when a file upload mixes mutually exclusive input formats. + throw new LibresignException($this->l10n->t('Use only one file input format per request')); + } + } + /** * @return DataResponse */ diff --git a/openapi-full.json b/openapi-full.json index 2d0f10eea5..22f7171c8c 100644 --- a/openapi-full.json +++ b/openapi-full.json @@ -3,7 +3,7 @@ "info": { "title": "libresign-full", "version": "0.0.1", - "description": "Control document signing workflows inside Nextcloud", + "description": "Sign documents and manage signing workflows", "license": { "name": "agpl" } @@ -6016,7 +6016,7 @@ "post": { "operationId": "file-save", "summary": "Send a file", - "description": "Send a new file to Nextcloud and return the fileId to request signature. 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 to request signature. 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": [ "file" ], @@ -6155,7 +6155,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": [ "file" ], diff --git a/openapi.json b/openapi.json index ea3e85080a..a4eb62d615 100644 --- a/openapi.json +++ b/openapi.json @@ -3,7 +3,7 @@ "info": { "title": "libresign", "version": "0.0.1", - "description": "Control document signing workflows inside Nextcloud", + "description": "Sign documents and manage signing workflows", "license": { "name": "agpl" } @@ -5392,7 +5392,7 @@ "post": { "operationId": "file-save", "summary": "Send a file", - "description": "Send a new file to Nextcloud and return the fileId to request signature. 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 to request signature. 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": [ "file" ], @@ -5531,7 +5531,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": [ "file" ], diff --git a/src/types/openapi/openapi-full.ts b/src/types/openapi/openapi-full.ts index 0528459922..276f679bb1 100644 --- a/src/types/openapi/openapi-full.ts +++ b/src/types/openapi/openapi-full.ts @@ -598,7 +598,7 @@ export type paths = { put?: never; /** * Send a file - * @description Send a new file to Nextcloud and return the fileId to request signature. 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 to request signature. 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"]; @@ -619,7 +619,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 379ec0dd42..e29584d229 100644 --- a/src/types/openapi/openapi.ts +++ b/src/types/openapi/openapi.ts @@ -598,7 +598,7 @@ export type paths = { put?: never; /** * Send a file - * @description Send a new file to Nextcloud and return the fileId to request signature. 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 to request signature. 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"]; @@ -619,7 +619,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/FileControllerInputSourceTest.php b/tests/php/Unit/Controller/FileControllerInputSourceTest.php new file mode 100644 index 0000000000..cdab19b4d9 --- /dev/null +++ b/tests/php/Unit/Controller/FileControllerInputSourceTest.php @@ -0,0 +1,150 @@ + $name, + 'tmp_name' => '/tmp/upload-placeholder', + 'type' => 'application/pdf', + 'size' => 3, + 'error' => UPLOAD_ERR_OK, + ]; + } + + private static function batch(): array { + return [ + 'name' => ['first.pdf', 'second.pdf'], + 'tmp_name' => ['/tmp/first', '/tmp/second'], + 'type' => ['application/pdf', 'application/pdf'], + 'size' => [3, 4], + 'error' => [UPLOAD_ERR_OK, UPLOAD_ERR_OK], + ]; + } + + public static function acceptedInputs(): array { + return [ + 'JSON single reference' => [['nodeId' => 1], [], null, null, [['nodeId' => 1]]], + 'JSON reference list' => [[], [['nodeId' => 1], ['nodeId' => 2]], null, null, [['nodeId' => 1], ['nodeId' => 2]]], + 'single multipart file' => [[], [], self::upload('one.pdf'), null, [ + ['uploadedFile' => self::upload('one.pdf'), 'name' => 'one'], + ]], + 'multipart list under files' => [[], [], null, self::batch(), [ + ['uploadedFile' => self::uploadFromBatch(0), 'name' => 'first'], + ['uploadedFile' => self::uploadFromBatch(1), 'name' => 'second'], + ]], + 'legacy multipart list under file' => [[], [], self::batch(), null, [ + ['uploadedFile' => self::uploadFromBatch(0), 'name' => 'first'], + ['uploadedFile' => self::uploadFromBatch(1), 'name' => 'second'], + ]], + ]; + } + + private static function uploadFromBatch(int $index): array { + $batch = self::batch(); + return array_map(static fn (array $column): mixed => $column[$index], $batch); + } + + public static function conflictingInputs(): array { + return [ + 'both JSON forms' => [['nodeId' => 1], [['nodeId' => 2]], null, null], + 'both multipart fields' => [[], [], self::upload('one.pdf'), self::batch()], + 'JSON file plus multipart file' => [['nodeId' => 1], [], self::upload('one.pdf'), null], + 'JSON files plus multipart files' => [[], [['nodeId' => 1]], null, self::batch()], + ]; + } + + private function controller(): FileController { + $reflection = new ReflectionClass(FileController::class); + /** @var FileController $controller */ + $controller = $reflection->newInstanceWithoutConstructor(); + + $l10n = $this->createMock(IL10N::class); + $l10n->method('t')->willReturnCallback(static fn (string $message): string => $message); + $reflection->getProperty('l10n')->setValue($controller, $l10n); + + $fileService = $this->createMock(FileService::class); + $reflection->getProperty('fileService')->setValue($controller, $fileService); + + $reflection->getProperty('validateHelper')->setValue($controller, $this->createMock(ValidateHelper::class)); + return $controller; + } + + #[DataProvider('acceptedInputs')] + public function testAcceptsOneFileInputSource(array $file, array $files, ?array $singleUpload, ?array $batchUpload, array $expected): void { + $controller = $this->controller(); + (new ReflectionMethod(FileController::class, 'assertExclusiveFileInputSources')) + ->invoke($controller, $file, $files, $singleUpload, $batchUpload); + $result = (new ReflectionMethod(FileController::class, 'prepareFilesForSaving')) + ->invoke($controller, $file, $files, [], $batchUpload ?: $singleUpload); + // PHP file entries are associative maps: key insertion order is not contractual. + $sortUploadKeys = static function (array $entry): array { + if (isset($entry['uploadedFile'])) { + ksort($entry['uploadedFile']); + } + return $entry; + }; + self::assertSame(array_map($sortUploadKeys, $expected), array_map($sortUploadKeys, $result)); + } + + #[DataProvider('conflictingInputs')] + public function testRejectsAmbiguousFileInputs(array $file, array $files, ?array $singleUpload, ?array $batchUpload): void { + $controller = $this->controller(); + $this->expectException(LibresignException::class); + $this->expectExceptionMessage('Use only one file input format per request'); + (new ReflectionMethod(FileController::class, 'assertExclusiveFileInputSources')) + ->invoke($controller, $file, $files, $singleUpload, $batchUpload); + } + + public function testConflictingMultipartInputReturns422WithoutSaving(): void { + $controller = $this->controller(); + $reflection = new ReflectionClass(FileController::class); + + $request = $this->createMock(IRequest::class); + $request->method('getUploadedFile')->willReturnMap([ + ['file', self::upload('one.pdf')], + ['files', self::batch()], + ]); + $reflection->getProperty('request')->setValue($controller, $request); + + $user = $this->createMock(IUser::class); + $userSession = $this->createMock(IUserSession::class); + $userSession->method('getUser')->willReturn($user); + $reflection->getProperty('userSession')->setValue($controller, $userSession); + + $signingValidator = $this->createMock(ValidateHelper::class); + $signingValidator->expects($this->once())->method('canRequestSign')->with($user); + $reflection->getProperty('validateHelper')->setValue($controller, $signingValidator); + + $requestSignatureService = $this->createMock(RequestSignatureService::class); + $requestSignatureService->expects($this->never())->method('saveFiles'); + $reflection->getProperty('requestSignatureService')->setValue($controller, $requestSignatureService); + + $response = $controller->save(); + self::assertSame(Http::STATUS_UNPROCESSABLE_ENTITY, $response->getStatus()); + self::assertSame('Use only one file input format per request', $response->getData()['message']); + } +}