Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 40 additions & 4 deletions lib/Controller/FileController.php
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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) {
Expand All @@ -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<Http::STATUS_OK, LibresignDetailedFileResponse, array{}>|DataResponse<Http::STATUS_BAD_REQUEST|Http::STATUS_NOT_FOUND|Http::STATUS_UNPROCESSABLE_ENTITY, LibresignMessageResponse, array{}>
Expand Down Expand Up @@ -617,6 +624,7 @@ public function addFileToEnvelope(string $uuid): DataResponse {
}

$normalizedFiles = $this->processUploadedFiles($uploadedFiles);
$this->assertExpectedUploadedFileCount(count($normalizedFiles));

$addedFiles = [];
foreach ($normalizedFiles as $fileData) {
Expand Down Expand Up @@ -705,9 +713,7 @@ private function prepareFileForSaving(array $fileData, string $name, array $sett
/**
* @return list<array{fileNode?: Node, name?: string, uploadedFile?: array}> 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);
}
Expand All @@ -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<array{uploadedFile: array, name: string}>
*/
Expand Down Expand Up @@ -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<Http::STATUS_OK, LibresignDetailedFileResponse, array{}>
*/
Expand Down
6 changes: 3 additions & 3 deletions openapi-full.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand Down Expand Up @@ -5404,7 +5404,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"
],
Expand Down Expand Up @@ -5543,7 +5543,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"
],
Expand Down
6 changes: 3 additions & 3 deletions openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
}
Expand Down Expand Up @@ -4776,7 +4776,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"
],
Expand Down Expand Up @@ -4915,7 +4915,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"
],
Expand Down
4 changes: 2 additions & 2 deletions src/types/openapi/openapi-full.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,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"];
Expand All @@ -325,7 +325,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;
Expand Down
4 changes: 2 additions & 2 deletions src/types/openapi/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -304,7 +304,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"];
Expand All @@ -325,7 +325,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;
Expand Down
150 changes: 150 additions & 0 deletions tests/php/Unit/Controller/FileControllerInputSourceTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
<?php

declare(strict_types=1);

/**
* SPDX-FileCopyrightText: 2026 LibreCode coop and contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/

namespace OCA\Libresign\Tests\Unit\Controller;

use OCA\Libresign\Controller\FileController;
use OCA\Libresign\Exception\LibresignException;
use OCA\Libresign\Helper\ValidateHelper;
use OCA\Libresign\Service\FileService;
use OCA\Libresign\Service\RequestSignatureService;
use OCP\AppFramework\Http;
use OCP\IL10N;
use OCP\IRequest;
use OCP\IUser;
use OCP\IUserSession;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use ReflectionMethod;

final class FileControllerInputSourceTest extends TestCase {
private static function upload(string $name): array {
return [
'name' => $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']);
}
}
Loading