Skip to content

Beautiful Open-Source Form Builder

Refactor file path handling in form controllers to use dedicated methods (#867)

Chirag Chhatrala3e91b0d53b59
diff --git a/api/app/Http/Controllers/Content/FileUploadController.php b/api/app/Http/Controllers/Content/FileUploadController.php
index f0043d325..feaa0fe2d 100644
--- a/api/app/Http/Controllers/Content/FileUploadController.php
+++ b/api/app/Http/Controllers/Content/FileUploadController.php
@@ -3,7 +3,7 @@
namespace App\Http\Controllers\Content;
use App\Http\Controllers\Controller;
-use App\Http\Controllers\Forms\PublicFormController;
+use App\Service\Storage\FileUploadPathService;
use Illuminate\Http\Request;
use Illuminate\Support\Str;
@@ -18,7 +18,7 @@ class FileUploadController extends Controller
{
$request->validate(['file' => 'required|file']);
$uuid = (string) Str::uuid();
- $path = $request->file('file')->storeAs(PublicFormController::TMP_FILE_UPLOAD_PATH, $uuid);
+ $path = $request->file('file')->storeAs(FileUploadPathService::getTmpFileUploadPath(), $uuid);
return response()->json([
'uuid' => $uuid,
diff --git a/api/app/Http/Controllers/Forms/FormController.php b/api/app/Http/Controllers/Forms/FormController.php
index 3775971cc..2fc83f192 100644
--- a/api/app/Http/Controllers/Forms/FormController.php
+++ b/api/app/Http/Controllers/Forms/FormController.php
@@ -13,6 +13,7 @@ use App\Models\Workspace;
use App\Notifications\Forms\MobileEditorEmail;
use App\Service\Forms\FormCleaner;
use App\Service\Storage\StorageFileNameParser;
+use App\Service\Storage\FileUploadPathService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
@@ -206,7 +207,7 @@ class FormController extends Controller
$fileNameParser = StorageFileNameParser::parse($request->url);
// Make sure we retrieve the file in tmp storage, move it to persistent
- $fileName = PublicFormController::TMP_FILE_UPLOAD_PATH . $fileNameParser->uuid;
+ $fileName = FileUploadPathService::getTmpFileUploadPath($fileNameParser->uuid);
if (!Storage::exists($fileName)) {
// File not found, we skip
return null;
@@ -227,7 +228,7 @@ class FormController extends Controller
{
$this->authorize('view', $form);
- $path = Str::of(PublicFormController::FILE_UPLOAD_PATH)->replace('?', $form->id) . '/' . $fileName;
+ $path = FileUploadPathService::getFileUploadPath($form->id, $fileName);
if (!Storage::exists($path)) {
return $this->error([
'message' => 'File not found.',
diff --git a/api/app/Http/Controllers/Forms/FormSubmissionController.php b/api/app/Http/Controllers/Forms/FormSubmissionController.php
index 5375f7b83..95035dc9d 100644
--- a/api/app/Http/Controllers/Forms/FormSubmissionController.php
+++ b/api/app/Http/Controllers/Forms/FormSubmissionController.php
@@ -13,10 +13,10 @@ use App\Jobs\Form\ExportFormSubmissionsJob;
use App\Models\Forms\Form;
use App\Models\Forms\FormSubmission;
use App\Service\Forms\FormExportService;
+use App\Service\Storage\FileUploadPathService;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Auth;
-use Illuminate\Support\Str;
use Maatwebsite\Excel\Facades\Excel;
use Illuminate\Http\Request;
@@ -154,8 +154,7 @@ class FormSubmissionController extends Controller
public function submissionFile(Form $form, $filename)
{
- $fileName = Str::of(PublicFormController::FILE_UPLOAD_PATH)->replace('?', $form->id) . '/'
- . urldecode($filename);
+ $fileName = FileUploadPathService::getFileUploadPath($form->id, urldecode($filename));
if (! Storage::exists($fileName)) {
return $this->error([
diff --git a/api/app/Http/Controllers/Forms/PublicFormController.php b/api/app/Http/Controllers/Forms/PublicFormController.php
index ff8e66ea0..1e0e6f230 100644
--- a/api/app/Http/Controllers/Forms/PublicFormController.php
+++ b/api/app/Http/Controllers/Forms/PublicFormController.php
@@ -21,10 +21,6 @@ use Illuminate\Support\Str;
class PublicFormController extends Controller
{
- public const FILE_UPLOAD_PATH = 'forms/?/submissions';
-
- public const TMP_FILE_UPLOAD_PATH = 'tmp/';
-
public function show(Request $request, Form $form)
{
// Ensure form is public or closed
diff --git a/api/app/Jobs/Form/StoreFormSubmissionJob.php b/api/app/Jobs/Form/StoreFormSubmissionJob.php
index 9686e67f5..aef7101cd 100644
--- a/api/app/Jobs/Form/StoreFormSubmissionJob.php
+++ b/api/app/Jobs/Form/StoreFormSubmissionJob.php
@@ -4,8 +4,8 @@ namespace App\Jobs\Form;
use App\Events\Forms\FormSubmitted;
use App\Http\Controllers\Forms\FormController;
-use App\Http\Controllers\Forms\PublicFormController;
use App\Http\Requests\AnswerFormRequest;
+use App\Service\Storage\FileUploadPathService;
use App\Models\Forms\Form;
use App\Models\Forms\FormSubmission;
use App\Service\Forms\FormLogicPropertyResolver;
@@ -258,8 +258,7 @@ class StoreFormSubmissionJob implements ShouldQueue
return false; // Input $value couldn't be resolved to a canonical stored name format
}
- $destinationPath = Str::of(PublicFormController::FILE_UPLOAD_PATH)->replace('?', $this->form->id);
- $fullPathToCheck = $destinationPath . '/' . $canonicalStoredName;
+ $fullPathToCheck = FileUploadPathService::getFileUploadPath($this->form->id, $canonicalStoredName);
return Storage::exists($fullPathToCheck);
}
@@ -280,8 +279,8 @@ class StoreFormSubmissionJob implements ShouldQueue
if (filter_var($value, FILTER_VALIDATE_URL) !== false && str_contains($value, parse_url(config('app.url'))['host'])) {
$fileName = explode('?', basename($value))[0];
$path = FormController::ASSETS_UPLOAD_PATH . '/' . $fileName; // Assuming assets are in a defined path
- $newPath = Str::of(PublicFormController::FILE_UPLOAD_PATH)->replace('?', $this->form->id);
- Storage::move($path, $newPath . '/' . $fileName);
+ $newPath = FileUploadPathService::getFileUploadPath($this->form->id, $fileName);
+ Storage::move($path, $newPath);
return $fileName;
}
@@ -300,7 +299,7 @@ class StoreFormSubmissionJob implements ShouldQueue
if (!$fileNameParser || !$fileNameParser->uuid) {
return null; // Cannot derive UUID from the reference
}
- $fileNameInTmp = PublicFormController::TMP_FILE_UPLOAD_PATH . $fileNameParser->uuid;
+ $fileNameInTmp = FileUploadPathService::getTmpFileUploadPath($fileNameParser->uuid);
if (!Storage::exists($fileNameInTmp)) {
return null; // Temporary file not found
}
@@ -308,8 +307,7 @@ class StoreFormSubmissionJob implements ShouldQueue
if (empty($movedFileName)) {
return null; // Canonical name generation failed
}
- $newPath = Str::of(PublicFormController::FILE_UPLOAD_PATH)->replace('?', $this->form->id);
- $completeNewFilename = $newPath . '/' . $movedFileName;
+ $completeNewFilename = FileUploadPathService::getFileUploadPath($this->form->id, $movedFileName);
Storage::move($fileNameInTmp, $completeNewFilename);
return $movedFileName;
}
@@ -325,8 +323,7 @@ class StoreFormSubmissionJob implements ShouldQueue
return null;
}
$fileName = 'sign_' . (string) Str::uuid() . '.png';
- $newPath = Str::of(PublicFormController::FILE_UPLOAD_PATH)->replace('?', $this->form->id);
- $completeNewFilename = $newPath . '/' . $fileName;
+ $completeNewFilename = FileUploadPathService::getFileUploadPath($this->form->id, $fileName);
Storage::put($completeNewFilename, base64_decode(explode(',', $value)[1]));
return $fileName;
}
diff --git a/api/app/Listeners/Forms/DeleteFormSubmissionFiles.php b/api/app/Listeners/Forms/DeleteFormSubmissionFiles.php
index f3d2b01c7..97512b921 100644
--- a/api/app/Listeners/Forms/DeleteFormSubmissionFiles.php
+++ b/api/app/Listeners/Forms/DeleteFormSubmissionFiles.php
@@ -3,9 +3,8 @@
namespace App\Listeners\Forms;
use App\Events\Models\FormSubmissionDeleting;
-use App\Http\Controllers\Forms\PublicFormController;
+use App\Service\Storage\FileUploadPathService;
use Illuminate\Support\Facades\Storage;
-use Illuminate\Support\Str;
class DeleteFormSubmissionFiles
{
@@ -45,7 +44,7 @@ class DeleteFormSubmissionFiles
private function deleteFile(int|string $formId, string $fileName): void
{
- $path = Str::of(PublicFormController::FILE_UPLOAD_PATH)->replace('?', $formId) . '/' . urldecode($fileName);
+ $path = FileUploadPathService::getFileUploadPath($formId, urldecode($fileName));
if (Storage::exists($path)) {
Storage::delete($path);
}
diff --git a/api/app/Rules/StorageFile.php b/api/app/Rules/StorageFile.php
index e0ca624fa..c4f0fb96d 100644
--- a/api/app/Rules/StorageFile.php
+++ b/api/app/Rules/StorageFile.php
@@ -2,13 +2,12 @@
namespace App\Rules;
-use App\Http\Controllers\Forms\PublicFormController;
+use App\Service\Storage\FileUploadPathService;
use App\Models\Forms\Form;
use App\Service\Storage\StorageFileNameParser;
use Closure;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Support\Facades\Storage;
-use Illuminate\Support\Str;
class StorageFile implements ValidationRule
{
@@ -36,8 +35,7 @@ class StorageFile implements ValidationRule
// This is use when updating a record, and file uploads aren't changed.
if ($this->form) {
- $newPath = Str::of(PublicFormController::FILE_UPLOAD_PATH)->replace('?', $this->form->id);
- if (Storage::exists($newPath . '/' . $fileNameParser->getMovedFileName())) {
+ if (Storage::exists(FileUploadPathService::getFileUploadPath($this->form->id, $fileNameParser->getMovedFileName()))) {
return true;
}
}
@@ -47,7 +45,7 @@ class StorageFile implements ValidationRule
return false;
}
- $filePath = PublicFormController::TMP_FILE_UPLOAD_PATH . $uuid;
+ $filePath = FileUploadPathService::getTmpFileUploadPath($uuid);
if (! Storage::exists($filePath)) {
return false;
}
diff --git a/api/app/Service/Storage/FileUploadPathService.php b/api/app/Service/Storage/FileUploadPathService.php
new file mode 100644
index 000000000..4c506ecfd
--- /dev/null
+++ b/api/app/Service/Storage/FileUploadPathService.php
@@ -0,0 +1,96 @@
+<?php
+
+namespace App\Service\Storage;
+
+use Illuminate\Support\Str;
+
+/**
+ * Service for managing file upload paths in the application
+ *
+ * This service centralizes all path generation for file uploads, ensuring
+ * consistent path structures throughout the application.
+ */
+class FileUploadPathService
+{
+ /**
+ * Base path for form submission file uploads
+ */
+ private const FILE_UPLOAD_PATH = 'forms/?/submissions';
+
+ /**
+ * Base path for temporary file uploads
+ */
+ private const TMP_FILE_UPLOAD_PATH = 'tmp/';
+
+ /**
+ * Generate the file upload path for a specific form
+ *
+ * @param int|string $formId The form ID
+ * @param string|null $fileName Optional filename to append
+ * @return string The complete file upload path
+ *
+ * @example FileUploadPathService::getFileUploadPath(123) // returns "forms/123/submissions"
+ * @example FileUploadPathService::getFileUploadPath(123, "document.pdf") // returns "forms/123/submissions/document.pdf"
+ */
+ public static function getFileUploadPath(int|string $formId, ?string $fileName = null): string
+ {
+ // Validate form ID to prevent path traversal attacks
+ self::validatePathComponent($formId);
+
+ $path = Str::of(self::FILE_UPLOAD_PATH)->replace('?', $formId);
+
+ if ($fileName) {
+ // Validate filename
+ self::validatePathComponent($fileName);
+
+ // Ensure consistent directory separator
+ $path = Str::finish($path, '/') . $fileName;
+ }
+
+ return $path;
+ }
+
+ /**
+ * Generate the temporary file upload path
+ *
+ * @param string|null $fileName Optional filename to append
+ * @return string The complete temporary file upload path
+ *
+ * @example FileUploadPathService::getTmpFileUploadPath() // returns "tmp/"
+ * @example FileUploadPathService::getTmpFileUploadPath("abc123") // returns "tmp/abc123"
+ */
+ public static function getTmpFileUploadPath(?string $fileName = null): string
+ {
+ $path = self::TMP_FILE_UPLOAD_PATH;
+
+ if ($fileName) {
+ // Validate filename
+ self::validatePathComponent($fileName);
+
+ // Ensure consistent directory separator
+ $path = Str::finish($path, '/') . $fileName;
+ }
+
+ return $path;
+ }
+
+ /**
+ * Validates a path component to prevent path traversal attacks
+ *
+ * @param string|int $component The path component to validate
+ * @throws \InvalidArgumentException If the path component contains invalid characters
+ */
+ private static function validatePathComponent(string|int $component): void
+ {
+ $component = (string) $component;
+
+ // Check for path traversal attempts or problematic characters
+ if (
+ str_contains($component, '..') ||
+ str_contains($component, '/') ||
+ str_contains($component, '\\')
+ ) {
+ throw new \InvalidArgumentException('Path component contains invalid characters');
+ }
+ }
+}
diff --git a/api/app/Service/WorkspaceHelper.php b/api/app/Service/WorkspaceHelper.php
index 33bcee36a..10d8c45cb 100644
--- a/api/app/Service/WorkspaceHelper.php
+++ b/api/app/Service/WorkspaceHelper.php
@@ -8,7 +8,6 @@ class WorkspaceHelper
{
public function __construct(public Workspace $workspace)
{
-
}
public function getAllUsers()
diff --git a/api/tests/Unit/Service/Storage/FileUploadPathServiceTest.php b/api/tests/Unit/Service/Storage/FileUploadPathServiceTest.php
new file mode 100644
index 000000000..873f52038
--- /dev/null
+++ b/api/tests/Unit/Service/Storage/FileUploadPathServiceTest.php
@@ -0,0 +1,71 @@
+<?php
+
+uses(\Tests\TestCase::class);
+
+use App\Service\Storage\FileUploadPathService;
+
+describe('FileUploadPathService', function () {
+ describe('getFileUploadPath', function () {
+ it('returns correct path without filename', function () {
+ $formId = 123;
+ $path = FileUploadPathService::getFileUploadPath($formId);
+ expect($path)->toBe('forms/123/submissions');
+ });
+
+ it('returns correct path with filename', function () {
+ $formId = 456;
+ $fileName = 'document.pdf';
+ $path = FileUploadPathService::getFileUploadPath($formId, $fileName);
+ expect($path)->toBe('forms/456/submissions/document.pdf');
+ });
+
+ it('handles string form ids', function () {
+ $formId = 'abc123';
+ $path = FileUploadPathService::getFileUploadPath($formId);
+ expect($path)->toBe('forms/abc123/submissions');
+ });
+
+ it('throws exception for unsafe form id', function () {
+ expect(fn () => FileUploadPathService::getFileUploadPath('../etc'))
+ ->toThrow(\InvalidArgumentException::class, 'Path component contains invalid characters');
+ });
+
+ it('throws exception for unsafe filename', function () {
+ expect(fn () => FileUploadPathService::getFileUploadPath(123, '../config.php'))
+ ->toThrow(\InvalidArgumentException::class, 'Path component contains invalid characters');
+ });
+ });
+
+ describe('getTmpFileUploadPath', function () {
+ it('returns correct tmp path without filename', function () {
+ $path = FileUploadPathService::getTmpFileUploadPath();
+ expect($path)->toBe('tmp/');
+ });
+
+ it('returns correct tmp path with filename', function () {
+ $uuid = '85e16d7b-58ed-43bc-8dce-7d3ff7d69f41';
+ $path = FileUploadPathService::getTmpFileUploadPath($uuid);
+ expect($path)->toBe('tmp/85e16d7b-58ed-43bc-8dce-7d3ff7d69f41');
+ });
+
+ it('throws exception for unsafe filename in tmp path', function () {
+ expect(fn () => FileUploadPathService::getTmpFileUploadPath('../config.php'))
+ ->toThrow(\InvalidArgumentException::class, 'Path component contains invalid characters');
+ });
+ });
+
+ describe('path consistency', function () {
+ it('ensures consistent directory separators in file paths', function () {
+ // Create a path with an extra slash
+ $formId = 789;
+ $fileName = 'test.pdf';
+
+ // Call the method with a form ID that should insert a trailing slash
+ $path = FileUploadPathService::getFileUploadPath($formId, $fileName);
+
+ // Path should not have double slashes
+ expect($path)->not->toContain('//');
+ expect($path)->toBe('forms/789/submissions/test.pdf');
+ });
+ });
+});