Skip to content
Merged
31 changes: 27 additions & 4 deletions lib/Controller/FileController.php
Original file line number Diff line number Diff line change
Expand Up @@ -559,6 +559,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).
Expand Down Expand Up @@ -587,7 +588,11 @@ public function save(
try {
$this->validateHelper->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) {
Expand All @@ -605,6 +610,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 @@ -644,6 +650,7 @@ public function addFileToEnvelope(string $uuid): DataResponse {
}

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

$addedFiles = [];
foreach ($normalizedFiles as $fileData) {
Expand Down Expand Up @@ -735,9 +742,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 @@ -755,6 +760,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
4 changes: 2 additions & 2 deletions openapi-full.json
Original file line number Diff line number Diff line change
Expand Up @@ -6206,7 +6206,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": [
"file"
],
Expand Down Expand Up @@ -6345,7 +6345,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 openapi.json
Original file line number Diff line number Diff line change
Expand Up @@ -5504,7 +5504,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": [
"file"
],
Expand Down Expand Up @@ -5643,7 +5643,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
1 change: 1 addition & 0 deletions src/components/Request/RequestPicker.vue
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,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, '')
Expand Down
1 change: 1 addition & 0 deletions src/components/RightSidebar/EnvelopeFilesList.vue
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,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) {
Expand Down
3 changes: 3 additions & 0 deletions src/tests/components/Request/RequestPicker.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -599,6 +599,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 () => {
Expand Down Expand Up @@ -665,6 +666,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 () => {
Expand Down
36 changes: 36 additions & 0 deletions src/tests/components/RightSidebar/EnvelopeFilesList.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ type EnvelopeFilesListVm = {
isTouchDevice: boolean
getMaxFileUploads: () => number
validateMaxFileUploads: (filesCount: number) => boolean
addFileToEnvelope: () => void
getPreviewUrl: (file: Partial<EnvelopeFileRecord>) => string | null
openFile: (file: EnvelopeFileRecord) => void
isSelected: (fileId: number) => boolean
Expand Down Expand Up @@ -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()
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 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"];
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 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"];
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
63 changes: 63 additions & 0 deletions tests/php/Unit/Controller/FileControllerUploadCountTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
<?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 OCP\IL10N;
use OCP\IRequest;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use ReflectionClass;
use ReflectionMethod;

final class FileControllerUploadCountTest extends TestCase {
public static function uploadCountProvider(): array {
return [
'legacy request without count' => [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);
}
}
Loading