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
21 changes: 16 additions & 5 deletions lib/Controller/FileController.php
Original file line number Diff line number Diff line change
Expand Up @@ -571,7 +571,9 @@ private function getMimeFallbackResponse(string $mimeType): ?\OCP\AppFramework\H
* Send a file
*
* 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[]'.
* File references can be sent as JSON using 'file' (single) or 'files' (list).
* Binary files use multipart/form-data: 'file' for one file, 'files[]' for several;
* the legacy 'file[]' field is also accepted. Do not combine these input forms.
* Multipart clients can send optional expectedFilesCount to reject incomplete batches.
*
* **Note on multiple file uploads:**
Expand Down Expand Up @@ -602,9 +604,10 @@ public function save(
try {
$this->signingRequestValidator->canRequestSign($this->userSession->getUser());

$uploadedFiles = $this->request->getUploadedFile('files') ?: $this->request->getUploadedFile('file');
$normalizedFiles = $this->prepareFilesForSaving($file, $files, $settings, $uploadedFiles);
if ($uploadedFiles) {
$singleUploadedFile = $this->request->getUploadedFile('file');
$multipleUploadedFiles = $this->request->getUploadedFile('files');
$normalizedFiles = $this->prepareFilesForSaving($file, $files, $settings, $singleUploadedFile, $multipleUploadedFiles);
if ($singleUploadedFile || $multipleUploadedFiles) {
$this->assertExpectedUploadedFileCount(count($normalizedFiles));
}

Expand Down Expand Up @@ -757,7 +760,15 @@ 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): array {
private function prepareFilesForSaving(array $file, array $files, array $settings, ?array $singleUploadedFile, ?array $multipleUploadedFiles): array {
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'));
}

$uploadedFiles = $multipleUploadedFiles ?: $singleUploadedFile;
if ($uploadedFiles) {
return $this->processUploadedFiles($uploadedFiles);
}
Expand Down
2 changes: 1 addition & 1 deletion openapi-full.json
Original file line number Diff line number Diff line change
Expand Up @@ -6613,7 +6613,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[]'. 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.",
"description": "Send a new file to Nextcloud and return the fileId used to create a signature request. File references can be sent as JSON using 'file' (single) or 'files' (list). Binary files use multipart/form-data: 'file' for one file, 'files[]' for several; the legacy 'file[]' field is also accepted. Do not combine these input forms. 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"
],
Expand Down
2 changes: 1 addition & 1 deletion openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -6071,7 +6071,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[]'. 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.",
"description": "Send a new file to Nextcloud and return the fileId used to create a signature request. File references can be sent as JSON using 'file' (single) or 'files' (list). Binary files use multipart/form-data: 'file' for one file, 'files[]' for several; the legacy 'file[]' field is also accepted. Do not combine these input forms. 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"
],
Expand Down
2 changes: 1 addition & 1 deletion src/types/openapi/openapi-full.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[]'. Multipart clients can send optional expectedFilesCount to reject incomplete batches.
* @description Send a new file to Nextcloud and return the fileId used to create a signature request. File references can be sent as JSON using 'file' (single) or 'files' (list). Binary files use multipart/form-data: 'file' for one file, 'files[]' for several; the legacy 'file[]' field is also accepted. Do not combine these input forms. 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 Down
2 changes: 1 addition & 1 deletion src/types/openapi/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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[]'. Multipart clients can send optional expectedFilesCount to reject incomplete batches.
* @description Send a new file to Nextcloud and return the fileId used to create a signature request. File references can be sent as JSON using 'file' (single) or 'files' (list). Binary files use multipart/form-data: 'file' for one file, 'files[]' for several; the legacy 'file[]' field is also accepted. Do not combine these input forms. 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 Down
151 changes: 151 additions & 0 deletions tests/php/Unit/Controller/FileControllerInputSourceTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
<?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\Service\FileService;
use OCA\Libresign\Service\RequestSignatureService;
use OCA\Libresign\Service\Validation\FileInputValidator;
use OCA\Libresign\Service\Validation\SigningRequestValidator;
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);

$validator = $this->createMock(FileInputValidator::class);
$validator->method('normalizeNodeId')->willReturnCallback(static fn (array $file): array => $file);
$reflection->getProperty('fileInputValidator')->setValue($controller, $validator);
return $controller;
}

#[DataProvider('acceptedInputs')]
public function testAcceptsOneFileInputSource(array $file, array $files, ?array $singleUpload, ?array $batchUpload, array $expected): void {
$controller = $this->controller();
$result = (new ReflectionMethod(FileController::class, 'prepareFilesForSaving'))
->invoke($controller, $file, $files, [], $singleUpload, $batchUpload);
// 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, 'prepareFilesForSaving'))
->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(SigningRequestValidator::class);
$signingValidator->expects($this->once())->method('canRequestSign')->with($user);
$reflection->getProperty('signingRequestValidator')->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