Beautiful Open-Source Form Builder
Fix file uploads with special characters causing invalid signature errors
Cursor Agent5ebf15fefca4
diff --git a/api/app/Http/Controllers/Forms/FormSubmissionController.php b/api/app/Http/Controllers/Forms/FormSubmissionController.phpindex 04e14e0b3..7cae55137 100644--- a/api/app/Http/Controllers/Forms/FormSubmissionController.php+++ b/api/app/Http/Controllers/Forms/FormSubmissionController.php@@ -14,6 +14,7 @@ use App\Models\Forms\Form;use App\Models\Forms\FormSubmission;use App\Service\Forms\FormExportService;use App\Service\Storage\FileUploadPathService;+use App\Service\Storage\FilenameUrlEncoder;use Illuminate\Support\Facades\Storage;use Illuminate\Support\Facades\Cache;use Illuminate\Support\Facades\Auth;@@ -163,9 +164,14 @@ class FormSubmissionController extends Controllerpublic function submissionFile(Form $form, $filename){- $fileName = FileUploadPathService::getFileUploadPath($form->id, urldecode($filename));+ // Decode the base64url encoded filename+ // See: https://github.com/OpnForm/OpnForm/issues/1024+ $decodedFilename = FilenameUrlEncoder::decode($filename);- if (! Storage::exists($fileName)) {+ // Build the full storage path+ $filePath = FileUploadPathService::getFileUploadPath($form->id, $decodedFilename);++ if (! Storage::exists($filePath)) {return $this->error(['message' => 'File not found.',], 404);@@ -173,12 +179,12 @@ class FormSubmissionController extends Controllerif (config('filesystems.default') !== 's3') {return response()->download(- Storage::path($fileName),- basename($fileName),+ Storage::path($filePath),+ basename($filePath),['Content-Type' => 'application/octet-stream','X-Content-Type-Options' => 'nosniff',- 'Content-Disposition' => 'attachment; filename="' . basename($fileName) . '"'+ 'Content-Disposition' => 'attachment; filename="' . basename($filePath) . '"']);}@@ -186,10 +192,10 @@ class FormSubmissionController extends Controller// Force download on S3 as wellreturn redirect(Storage::temporaryUrl(- $fileName,+ $filePath,now()->addMinute(),[- 'ResponseContentDisposition' => 'attachment; filename="' . basename($fileName) . '"',+ 'ResponseContentDisposition' => 'attachment; filename="' . basename($filePath) . '"','ResponseContentType' => 'application/octet-stream'])diff --git a/api/app/Http/Resources/FormSubmissionResource.php b/api/app/Http/Resources/FormSubmissionResource.phpindex 031478722..01e348833 100644--- a/api/app/Http/Resources/FormSubmissionResource.php+++ b/api/app/Http/Resources/FormSubmissionResource.php@@ -2,6 +2,7 @@namespace App\Http\Resources;+use App\Service\Storage\FilenameUrlEncoder;use Illuminate\Http\Resources\Json\JsonResource;use Illuminate\Support\Facades\URL;use Stevebauman\Purify\Facades\Purify;@@ -83,10 +84,14 @@ class FormSubmissionResource extends JsonResource$mapped = collect($fileItems)->filter(fn ($file) => !is_null($file) && $file !== '')->map(function ($file) {+ // Use base64url encoding to avoid URL encoding issues with special characters+ // See: https://github.com/OpnForm/OpnForm/issues/1024+ $encodedFilename = FilenameUrlEncoder::encode($file);+return ['file_url' => URL::signedRoute('open.forms.submissions.file',- [$this->form_id, $file],+ [$this->form_id, $encodedFilename],now()->addMinutes(10)),'file_name' => $file,diff --git a/api/app/Service/Forms/FormSubmissionFormatter.php b/api/app/Service/Forms/FormSubmissionFormatter.phpindex a6373f01d..20e9ab855 100644--- a/api/app/Service/Forms/FormSubmissionFormatter.php+++ b/api/app/Service/Forms/FormSubmissionFormatter.php@@ -3,6 +3,7 @@namespace App\Service\Forms;use App\Models\Forms\Form;+use App\Service\Storage\FilenameUrlEncoder;use Carbon\Carbon;use Illuminate\Support\Str;use Illuminate\Support\Facades\URL;@@ -294,10 +295,14 @@ class FormSubmissionFormatterprivate function getFileUrl($formId, $file){try {+ // Use base64url encoding to avoid URL encoding issues with special characters+ // See: https://github.com/OpnForm/OpnForm/issues/1024+ $encodedFilename = FilenameUrlEncoder::encode($file);+return $this->useSignedUrlForFiles ? URL::signedRoute('open.forms.submissions.file',- [$formId, $file]- ) : route('open.forms.submissions.file', [$formId, $file]);+ [$formId, $encodedFilename]+ ) : route('open.forms.submissions.file', [$formId, $encodedFilename]);} catch (\Exception $e) {throw $e;return null;diff --git a/api/app/Service/Storage/FilenameUrlEncoder.php b/api/app/Service/Storage/FilenameUrlEncoder.phpnew file mode 100644index 000000000..f26b52bdb--- /dev/null+++ b/api/app/Service/Storage/FilenameUrlEncoder.php@@ -0,0 +1,82 @@+<?php++namespace App\Service\Storage;++/**+ * Service for URL-safe encoding/decoding of filenames.+ *+ * This is needed because filenames with special characters (like parentheses, apostrophes)+ * cause issues with Laravel signed URLs when the web server decodes the URL path+ * before passing it to PHP. Using base64url encoding ensures the filename only+ * contains URL-safe characters that don't get decoded by the web server.+ *+ * @see https://github.com/OpnForm/OpnForm/issues/1024+ */+class FilenameUrlEncoder+{+ /**+ * Encode a filename using URL-safe base64 encoding.+ *+ * Uses base64url encoding (RFC 4648 §5) which replaces:+ * - '+' with '-'+ * - '/' with '_'+ * - Removes padding '='+ *+ * @param string $filename The original filename+ * @return string The URL-safe encoded filename+ */+ public static function encode(string $filename): string+ {+ return rtrim(strtr(base64_encode($filename), '+/', '-_'), '=');+ }++ /**+ * Decode a URL-safe base64 encoded filename.+ *+ * @param string $encoded The encoded filename+ * @return string The original filename+ */+ public static function decode(string $encoded): string+ {+ // Add padding back if needed+ $padded = str_pad(strtr($encoded, '-_', '+/'), strlen($encoded) + (4 - strlen($encoded) % 4) % 4, '=', STR_PAD_RIGHT);++ $decoded = base64_decode($padded, true);++ if ($decoded === false) {+ // If decoding fails, return the original string (backward compatibility)+ return $encoded;+ }++ return $decoded;+ }++ /**+ * Check if a string appears to be base64url encoded.+ *+ * This helps with backward compatibility - if a filename doesn't look+ * like it's encoded, we can handle it as a raw filename.+ *+ * @param string $value The value to check+ * @return bool True if the value appears to be base64url encoded+ */+ public static function isEncoded(string $value): bool+ {+ // Base64url only contains alphanumeric, dash, and underscore+ // Real filenames typically have dots and other characters+ if (!preg_match('/^[A-Za-z0-9_-]+$/', $value)) {+ return false;+ }++ // Try to decode and check if result is valid UTF-8+ $decoded = self::decode($value);++ // If decoded equals input, it wasn't really encoded+ if ($decoded === $value) {+ return false;+ }++ // Check if the decoded value is valid UTF-8+ return mb_check_encoding($decoded, 'UTF-8');+ }+}diff --git a/api/phpunit.xml b/api/phpunit.xmlindex 3d9dc1d9b..35b9e00ef 100644--- a/api/phpunit.xml+++ b/api/phpunit.xml@@ -16,6 +16,8 @@<env name="APP_ENV" value="testing"/><env name="BCRYPT_ROUNDS" value="4"/><env name="CACHE_DRIVER" value="array"/>+ <env name="DB_CONNECTION" value="sqlite"/>+ <env name="DB_DATABASE" value=":memory:"/><env name="DB_FOREIGN_KEYS" value="(false)"/><env name="MAIL_MAILER" value="log"/><env name="MAIL_FROM_ADDRESS" value="[email protected]"/>diff --git a/api/tests/Feature/Forms/FileDownloadSecurityTest.php b/api/tests/Feature/Forms/FileDownloadSecurityTest.phpindex 09b29e1a3..4c4e970ea 100644--- a/api/tests/Feature/Forms/FileDownloadSecurityTest.php+++ b/api/tests/Feature/Forms/FileDownloadSecurityTest.php@@ -2,6 +2,7 @@use App\Models\Forms\FormSubmission;use App\Service\Storage\FileUploadPathService;+use App\Service\Storage\FilenameUrlEncoder;use Illuminate\Support\Facades\Storage;use Illuminate\Support\Facades\URL;@@ -26,8 +27,10 @@ it('forces attachment download with safe headers for submission files', function'status' => FormSubmission::STATUS_COMPLETED,]);- // Call signed file route (route is protected by 'signed' middleware)- $signedUrl = URL::signedRoute('open.forms.submissions.file', [$form->id, $fileName]);+ // Call signed file route with encoded filename (as the new implementation does)+ // See: https://github.com/OpnForm/OpnForm/issues/1024+ $encodedFilename = FilenameUrlEncoder::encode($fileName);+ $signedUrl = URL::signedRoute('open.forms.submissions.file', [$form->id, $encodedFilename]);$response = $this->get($signedUrl);$response->assertOk();diff --git a/api/tests/Feature/Forms/FileDownloadSpecialCharsTest.php b/api/tests/Feature/Forms/FileDownloadSpecialCharsTest.phpnew file mode 100644index 000000000..237e0a931--- /dev/null+++ b/api/tests/Feature/Forms/FileDownloadSpecialCharsTest.php@@ -0,0 +1,178 @@+<?php++use App\Models\Forms\FormSubmission;+use App\Service\Storage\FileUploadPathService;+use App\Service\Storage\FilenameUrlEncoder;+use Illuminate\Support\Facades\Storage;+use Illuminate\Support\Facades\URL;+use Illuminate\Support\Str;++describe('File download with special characters in filename', function () {+ it('downloads files with parentheses in filename using encoded URL', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->createForm($user, $workspace);++ Storage::fake();++ // Filename with parentheses - simulates "image (1).jpg" after S3KeyCleaner sanitization+ $uuid = Str::uuid()->toString();+ $fileName = "image-(1)_{$uuid}.jpg";+ $path = FileUploadPathService::getFileUploadPath($form->id, $fileName);+ Storage::put($path, 'test image content');++ $form->submissions()->create([+ 'form_id' => $form->id,+ 'data' => [+ 'files_field' => [$fileName],+ ],+ 'status' => FormSubmission::STATUS_COMPLETED,+ ]);++ // Use base64url encoded filename (as the new implementation does)+ $encodedFilename = FilenameUrlEncoder::encode($fileName);+ $signedUrl = URL::signedRoute('open.forms.submissions.file', [$form->id, $encodedFilename]);+ $response = $this->get($signedUrl);++ $response->assertOk();+ });++ it('downloads files with spaces converted to dashes in filename using encoded URL', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->createForm($user, $workspace);++ Storage::fake();++ // Filename with dashes (from original spaces) - simulates "my file.pdf" after S3KeyCleaner sanitization+ $uuid = Str::uuid()->toString();+ $fileName = "my-file_{$uuid}.pdf";+ $path = FileUploadPathService::getFileUploadPath($form->id, $fileName);+ Storage::put($path, 'test pdf content');++ $form->submissions()->create([+ 'form_id' => $form->id,+ 'data' => [+ 'files_field' => [$fileName],+ ],+ 'status' => FormSubmission::STATUS_COMPLETED,+ ]);++ $encodedFilename = FilenameUrlEncoder::encode($fileName);+ $signedUrl = URL::signedRoute('open.forms.submissions.file', [$form->id, $encodedFilename]);+ $response = $this->get($signedUrl);++ $response->assertOk();+ });++ it('downloads files with apostrophe in filename using encoded URL', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->createForm($user, $workspace);++ Storage::fake();++ // Filename with apostrophe - "John's-document.pdf"+ $uuid = Str::uuid()->toString();+ $fileName = "John's-document_{$uuid}.pdf";+ $path = FileUploadPathService::getFileUploadPath($form->id, $fileName);+ Storage::put($path, 'test pdf content');++ $form->submissions()->create([+ 'form_id' => $form->id,+ 'data' => [+ 'files_field' => [$fileName],+ ],+ 'status' => FormSubmission::STATUS_COMPLETED,+ ]);++ $encodedFilename = FilenameUrlEncoder::encode($fileName);+ $signedUrl = URL::signedRoute('open.forms.submissions.file', [$form->id, $encodedFilename]);+ $response = $this->get($signedUrl);++ $response->assertOk();+ });++ it('downloads files with multiple special characters in filename using encoded URL', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->createForm($user, $workspace);++ Storage::fake();++ // Filename with multiple special characters - "Report (Q1) - John's copy.pdf"+ // After S3KeyCleaner: "Report-(Q1)---John's-copy.pdf" (spaces → dashes)+ $uuid = Str::uuid()->toString();+ $fileName = "Report-(Q1)---John's-copy_{$uuid}.pdf";+ $path = FileUploadPathService::getFileUploadPath($form->id, $fileName);+ Storage::put($path, 'test pdf content');++ $form->submissions()->create([+ 'form_id' => $form->id,+ 'data' => [+ 'files_field' => [$fileName],+ ],+ 'status' => FormSubmission::STATUS_COMPLETED,+ ]);++ $encodedFilename = FilenameUrlEncoder::encode($fileName);+ $signedUrl = URL::signedRoute('open.forms.submissions.file', [$form->id, $encodedFilename]);+ $response = $this->get($signedUrl);++ $response->assertOk();+ });++ it('downloads files with exclamation mark in filename using encoded URL', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->createForm($user, $workspace);++ Storage::fake();++ $uuid = Str::uuid()->toString();+ $fileName = "Important!-document_{$uuid}.pdf";+ $path = FileUploadPathService::getFileUploadPath($form->id, $fileName);+ Storage::put($path, 'test pdf content');++ $form->submissions()->create([+ 'form_id' => $form->id,+ 'data' => [+ 'files_field' => [$fileName],+ ],+ 'status' => FormSubmission::STATUS_COMPLETED,+ ]);++ $encodedFilename = FilenameUrlEncoder::encode($fileName);+ $signedUrl = URL::signedRoute('open.forms.submissions.file', [$form->id, $encodedFilename]);+ $response = $this->get($signedUrl);++ $response->assertOk();+ });++ it('downloads files with asterisk in filename using encoded URL', function () {+ $user = $this->actingAsUser();+ $workspace = $this->createUserWorkspace($user);+ $form = $this->createForm($user, $workspace);++ Storage::fake();++ $uuid = Str::uuid()->toString();+ $fileName = "star*file_{$uuid}.pdf";+ $path = FileUploadPathService::getFileUploadPath($form->id, $fileName);+ Storage::put($path, 'test pdf content');++ $form->submissions()->create([+ 'form_id' => $form->id,+ 'data' => [+ 'files_field' => [$fileName],+ ],+ 'status' => FormSubmission::STATUS_COMPLETED,+ ]);++ $encodedFilename = FilenameUrlEncoder::encode($fileName);+ $signedUrl = URL::signedRoute('open.forms.submissions.file', [$form->id, $encodedFilename]);+ $response = $this->get($signedUrl);++ $response->assertOk();+ });+});diff --git a/api/tests/Unit/Service/Storage/FilenameUrlEncoderTest.php b/api/tests/Unit/Service/Storage/FilenameUrlEncoderTest.phpnew file mode 100644index 000000000..eec1f7cc0--- /dev/null+++ b/api/tests/Unit/Service/Storage/FilenameUrlEncoderTest.php@@ -0,0 +1,153 @@+<?php++uses(\Tests\TestCase::class);++use App\Service\Storage\FilenameUrlEncoder;++describe('FilenameUrlEncoder', function () {+ describe('encode', function () {+ it('encodes a simple filename', function () {+ $filename = 'document.pdf';+ $encoded = FilenameUrlEncoder::encode($filename);++ // Verify it's URL-safe (only contains alphanumeric, dash, underscore)+ expect($encoded)->toMatch('/^[A-Za-z0-9_-]+$/');+ // Verify it can be decoded back+ expect(FilenameUrlEncoder::decode($encoded))->toBe($filename);+ });++ it('encodes filename with parentheses', function () {+ $filename = 'image-(1)_abc-def-ghi.jpg';+ $encoded = FilenameUrlEncoder::encode($filename);++ expect($encoded)->toMatch('/^[A-Za-z0-9_-]+$/');+ expect(FilenameUrlEncoder::decode($encoded))->toBe($filename);+ });++ it('encodes filename with apostrophe', function () {+ $filename = "John's-document_uuid.pdf";+ $encoded = FilenameUrlEncoder::encode($filename);++ expect($encoded)->toMatch('/^[A-Za-z0-9_-]+$/');+ expect(FilenameUrlEncoder::decode($encoded))->toBe($filename);+ });++ it('encodes filename with multiple special characters', function () {+ $filename = "Report-(Q1)---John's-copy_uuid.pdf";+ $encoded = FilenameUrlEncoder::encode($filename);++ expect($encoded)->toMatch('/^[A-Za-z0-9_-]+$/');+ expect(FilenameUrlEncoder::decode($encoded))->toBe($filename);+ });++ it('encodes filename with exclamation mark', function () {+ $filename = 'Important!-document_uuid.pdf';+ $encoded = FilenameUrlEncoder::encode($filename);++ expect($encoded)->toMatch('/^[A-Za-z0-9_-]+$/');+ expect(FilenameUrlEncoder::decode($encoded))->toBe($filename);+ });++ it('encodes filename with asterisk', function () {+ $filename = 'star*file_uuid.pdf';+ $encoded = FilenameUrlEncoder::encode($filename);++ expect($encoded)->toMatch('/^[A-Za-z0-9_-]+$/');+ expect(FilenameUrlEncoder::decode($encoded))->toBe($filename);+ });++ it('encodes filename with unicode characters', function () {+ $filename = 'файл_document_uuid.pdf';+ $encoded = FilenameUrlEncoder::encode($filename);++ expect($encoded)->toMatch('/^[A-Za-z0-9_-]+$/');+ expect(FilenameUrlEncoder::decode($encoded))->toBe($filename);+ });++ it('encodes filename with spaces', function () {+ $filename = 'my file with spaces_uuid.pdf';+ $encoded = FilenameUrlEncoder::encode($filename);++ expect($encoded)->toMatch('/^[A-Za-z0-9_-]+$/');+ expect(FilenameUrlEncoder::decode($encoded))->toBe($filename);+ });+ });++ describe('decode', function () {+ it('decodes a valid base64url string', function () {+ $original = 'image-(1)_abc-def-ghi.jpg';+ $encoded = FilenameUrlEncoder::encode($original);++ expect(FilenameUrlEncoder::decode($encoded))->toBe($original);+ });++ it('returns original string if decoding fails', function () {+ // Invalid base64 that would produce invalid UTF-8+ $invalid = 'not-valid-base64!!!';++ // Should return the original string for backward compatibility+ $result = FilenameUrlEncoder::decode($invalid);+ expect($result)->toBe($invalid);+ });++ it('handles empty string', function () {+ $encoded = FilenameUrlEncoder::encode('');+ expect(FilenameUrlEncoder::decode($encoded))->toBe('');+ });+ });++ describe('isEncoded', function () {+ it('returns true for encoded filenames', function () {+ $original = 'image-(1)_abc.jpg';+ $encoded = FilenameUrlEncoder::encode($original);++ expect(FilenameUrlEncoder::isEncoded($encoded))->toBeTrue();+ });++ it('returns false for raw filenames with special characters', function () {+ $filename = 'image-(1)_abc.jpg';++ expect(FilenameUrlEncoder::isEncoded($filename))->toBeFalse();+ });++ it('returns false for filenames with dots', function () {+ $filename = 'document.pdf';++ expect(FilenameUrlEncoder::isEncoded($filename))->toBeFalse();+ });++ it('returns false for simple alphanumeric that matches itself when decoded', function () {+ // A string that is valid base64url but decodes to gibberish+ $simple = 'abc123';++ // This might or might not be considered encoded depending on decode result+ // The key is it should be safe to use+ $result = FilenameUrlEncoder::isEncoded($simple);+ expect($result)->toBeBool();+ });+ });++ describe('roundtrip', function () {+ it('handles various S3-safe filenames correctly', function () {+ $testCases = [+ 'simple.pdf',+ 'file_uuid.jpg',+ 'image-(1)_abc-def.png',+ "John's-file_uuid.pdf",+ 'Important!_uuid.txt',+ 'star*file_uuid.doc',+ 'mixed-(chars)_uuid.pdf',+ 'unicode_файл_uuid.pdf',+ 'spaces in name_uuid.pdf',+ ];++ foreach ($testCases as $filename) {+ $encoded = FilenameUrlEncoder::encode($filename);+ $decoded = FilenameUrlEncoder::decode($encoded);++ expect($decoded)->toBe($filename, "Failed for filename: {$filename}");+ expect($encoded)->toMatch('/^[A-Za-z0-9_-]+$/', "Encoded value contains unsafe chars: {$encoded}");+ }+ });+ });+});