Skip to content

Beautiful Open-Source Form Builder

fix: harden public uploads against active-content abuse

Julien Nahum6b3bb4973e53
diff --git a/api/app/Exceptions/UploadSecurityException.php b/api/app/Exceptions/UploadSecurityException.php
new file mode 100644
index 000000000..8208f7bd5
--- /dev/null
+++ b/api/app/Exceptions/UploadSecurityException.php
@@ -0,0 +1,9 @@
+<?php
+
+namespace App\Exceptions;
+
+use RuntimeException;
+
+class UploadSecurityException extends RuntimeException
+{
+}
diff --git a/api/app/Http/Controllers/Content/FileUploadController.php b/api/app/Http/Controllers/Content/FileUploadController.php
index feaa0fe2d..2fe7407cf 100644
--- a/api/app/Http/Controllers/Content/FileUploadController.php
+++ b/api/app/Http/Controllers/Content/FileUploadController.php
@@ -3,9 +3,13 @@
namespace App\Http\Controllers\Content;
use App\Http\Controllers\Controller;
+use App\Http\Requests\UploadAssetRequest;
use App\Service\Storage\FileUploadPathService;
+use App\Service\Storage\UploadSecurityService;
use Illuminate\Http\Request;
+use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
+use Illuminate\Validation\ValidationException;
class FileUploadController extends Controller
{
@@ -14,11 +18,28 @@ class FileUploadController extends Controller
*
* @return \Illuminate\Http\JsonResponse
*/
- public function upload(Request $request)
+ public function upload(Request $request, UploadSecurityService $uploadSecurityService)
{
- $request->validate(['file' => 'required|file']);
+ $request->validate([
+ 'file' => 'required|file|max:' . (int) ceil(UploadAssetRequest::FORM_ASSET_MAX_SIZE / 1024),
+ ]);
+
+ try {
+ $inspection = $uploadSecurityService->inspectUploadedFile($request->file('file'));
+ } catch (\App\Exceptions\UploadSecurityException $exception) {
+ throw ValidationException::withMessages([
+ 'file' => [$exception->getMessage()],
+ ]);
+ }
+
$uuid = (string) Str::uuid();
- $path = $request->file('file')->storeAs(FileUploadPathService::getTmpFileUploadPath(), $uuid);
+ $path = FileUploadPathService::getTmpFileUploadPath($uuid);
+
+ if ($inspection->isSvg) {
+ Storage::put($path, $inspection->sanitizedContents);
+ } else {
+ Storage::putFileAs(FileUploadPathService::getTmpFileUploadPath(), $request->file('file'), $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 8c649f03b..391687533 100644
--- a/api/app/Http/Controllers/Forms/FormController.php
+++ b/api/app/Http/Controllers/Forms/FormController.php
@@ -13,11 +13,13 @@ use App\Models\Forms\FormSubmission;
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 App\Service\Storage\StorageFileNameParser;
+use App\Service\Storage\UploadSecurityService;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
+use Illuminate\Validation\ValidationException;
class FormController extends Controller
{
@@ -223,18 +225,43 @@ class FormController extends Controller
/**
* Upload a form asset
*/
- public function uploadAsset(UploadAssetRequest $request)
+ public function uploadAsset(UploadAssetRequest $request, UploadSecurityService $uploadSecurityService)
{
$fileNameParser = StorageFileNameParser::parse($request->url);
+ if (!$fileNameParser->uuid || !$fileNameParser->getMovedFileName()) {
+ throw ValidationException::withMessages([
+ 'url' => ['Invalid file.'],
+ ]);
+ }
// Make sure we retrieve the file in tmp storage, move it to persistent
$fileName = FileUploadPathService::getTmpFileUploadPath($fileNameParser->uuid);
if (!Storage::exists($fileName)) {
- // File not found, we skip
- return null;
+ throw ValidationException::withMessages([
+ 'url' => ['File not found.'],
+ ]);
+ }
+ if (Storage::size($fileName) > UploadAssetRequest::FORM_ASSET_MAX_SIZE) {
+ throw ValidationException::withMessages([
+ 'url' => ['File is too large.'],
+ ]);
}
+
+ try {
+ $inspection = $uploadSecurityService->inspectStoredFile($fileName, $request->url);
+ } catch (\App\Exceptions\UploadSecurityException $exception) {
+ throw ValidationException::withMessages([
+ 'url' => [$exception->getMessage()],
+ ]);
+ }
+
$newPath = self::ASSETS_UPLOAD_PATH . '/' . $fileNameParser->getMovedFileName();
- Storage::move($fileName, $newPath);
+ if ($inspection->isSvg) {
+ Storage::put($newPath, $inspection->sanitizedContents);
+ Storage::delete($fileName);
+ } else {
+ Storage::move($fileName, $newPath);
+ }
return $this->success([
'message' => 'File uploaded.',
diff --git a/api/app/Http/Controllers/Forms/PublicFormController.php b/api/app/Http/Controllers/Forms/PublicFormController.php
index e179db8c5..4fda93fa5 100644
--- a/api/app/Http/Controllers/Forms/PublicFormController.php
+++ b/api/app/Http/Controllers/Forms/PublicFormController.php
@@ -12,6 +12,7 @@ use App\Service\Forms\Analytics\UserAgentHelper;
use App\Service\Forms\FormSubmissionProcessor;
use App\Service\Forms\FormCleaner;
use App\Service\Forms\SubmissionUrlService;
+use App\Service\Storage\SafeFileResponseService;
use App\Service\WorkspaceHelper;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
@@ -89,7 +90,7 @@ class PublicFormController extends Controller
return (new WorkspaceHelper($workspace))->getAllUsers();
}
- public function showAsset($assetFileName)
+ public function showAsset(string $assetFileName, SafeFileResponseService $safeFileResponseService)
{
$path = FormController::ASSETS_UPLOAD_PATH . '/' . $assetFileName;
if (!Storage::exists($path)) {
@@ -99,13 +100,7 @@ class PublicFormController extends Controller
]);
}
- $internal_url = Storage::temporaryUrl($path, now()->addMinutes(5));
-
- foreach (config('filesystems.disks.s3.temporary_url_rewrites') as $from => $to) {
- $internal_url = str_replace($from, $to, $internal_url);
- }
-
- return redirect()->to($internal_url);
+ return $safeFileResponseService->serve($path, $assetFileName);
}
/**
diff --git a/api/app/Http/Requests/UploadAssetRequest.php b/api/app/Http/Requests/UploadAssetRequest.php
index 70c494792..5bffb25a4 100644
--- a/api/app/Http/Requests/UploadAssetRequest.php
+++ b/api/app/Http/Requests/UploadAssetRequest.php
@@ -2,7 +2,6 @@
namespace App\Http\Requests;
-use App\Rules\StorageFile;
use Illuminate\Foundation\Http\FormRequest;
class UploadAssetRequest extends FormRequest
@@ -16,20 +15,9 @@ class UploadAssetRequest extends FormRequest
*/
public function rules()
{
- $fileTypes = [
- 'png',
- 'jpeg',
- 'jpg',
- 'bmp',
- 'gif',
- 'svg',
- ];
- if ($this->offsetExists('type') && $this->get('type') === 'files') {
- $fileTypes = [];
- }
-
return [
- 'url' => ['required', new StorageFile(self::FORM_ASSET_MAX_SIZE, $fileTypes)],
+ 'url' => ['required', 'string'],
+ 'type' => ['nullable', 'string'],
];
}
}
diff --git a/api/app/Service/Storage/SafeFileResponseService.php b/api/app/Service/Storage/SafeFileResponseService.php
new file mode 100644
index 000000000..aefc115a4
--- /dev/null
+++ b/api/app/Service/Storage/SafeFileResponseService.php
@@ -0,0 +1,39 @@
+<?php
+
+namespace App\Service\Storage;
+
+use Illuminate\Support\Facades\Storage;
+use Illuminate\Support\Str;
+use Symfony\Component\HttpFoundation\StreamedResponse;
+
+class SafeFileResponseService
+{
+ public function serve(string $path, ?string $downloadName = null): StreamedResponse
+ {
+ $stream = Storage::readStream($path);
+
+ abort_if($stream === false, 404, 'File not found.');
+
+ $mimeType = Storage::mimeType($path) ?: 'application/octet-stream';
+ $headers = [
+ 'Content-Type' => $mimeType,
+ 'Content-Security-Policy' => "default-src 'none'; script-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; sandbox",
+ 'X-Content-Type-Options' => 'nosniff',
+ 'X-Frame-Options' => 'DENY',
+ ];
+
+ if (!Str::startsWith($mimeType, 'image/')) {
+ $headers['Content-Disposition'] = 'attachment; filename="' . ($downloadName ?? basename($path)) . '"';
+ }
+
+ return response()->stream(function () use ($stream) {
+ try {
+ fpassthru($stream);
+ } finally {
+ if (is_resource($stream)) {
+ fclose($stream);
+ }
+ }
+ }, 200, $headers);
+ }
+}
diff --git a/api/app/Service/Storage/UploadSecurityInspection.php b/api/app/Service/Storage/UploadSecurityInspection.php
new file mode 100644
index 000000000..973c170e5
--- /dev/null
+++ b/api/app/Service/Storage/UploadSecurityInspection.php
@@ -0,0 +1,14 @@
+<?php
+
+namespace App\Service\Storage;
+
+readonly class UploadSecurityInspection
+{
+ public function __construct(
+ public string $mimeType,
+ public bool $isImage,
+ public bool $isSvg,
+ public ?string $sanitizedContents = null,
+ ) {
+ }
+}
diff --git a/api/app/Service/Storage/UploadSecurityService.php b/api/app/Service/Storage/UploadSecurityService.php
new file mode 100644
index 000000000..c1d7a0263
--- /dev/null
+++ b/api/app/Service/Storage/UploadSecurityService.php
@@ -0,0 +1,93 @@
+<?php
+
+namespace App\Service\Storage;
+
+use App\Exceptions\UploadSecurityException;
+use enshrined\svgSanitize\Sanitizer;
+use Illuminate\Http\UploadedFile;
+use Illuminate\Support\Facades\Storage;
+
+class UploadSecurityService
+{
+ private const BLOCKED_EXTENSIONS = ['html', 'htm', 'xhtml', 'xml'];
+ private const BLOCKED_MIME_TYPES = ['text/html', 'application/xhtml+xml', 'application/xml', 'text/xml'];
+
+ public function inspectUploadedFile(UploadedFile $file): UploadSecurityInspection
+ {
+ $contents = $file->get();
+
+ if (!is_string($contents)) {
+ throw new UploadSecurityException('Unable to read the uploaded file.');
+ }
+
+ return $this->inspectContents($contents, $file->getClientOriginalName());
+ }
+
+ public function inspectStoredFile(string $path, ?string $originalFileName = null): UploadSecurityInspection
+ {
+ if (!Storage::exists($path)) {
+ throw new UploadSecurityException('File not found.');
+ }
+
+ return $this->inspectContents(Storage::get($path), $originalFileName);
+ }
+
+ private function inspectContents(string $contents, ?string $originalFileName = null): UploadSecurityInspection
+ {
+ $extension = strtolower((string) pathinfo($originalFileName ?? '', PATHINFO_EXTENSION));
+ $mimeType = $this->detectMimeType($contents);
+
+ if ($this->isBlockedActiveContent($extension, $mimeType)) {
+ throw new UploadSecurityException('This file type is not allowed.');
+ }
+
+ if ($this->isSvg($extension, $mimeType)) {
+ return new UploadSecurityInspection(
+ mimeType: 'image/svg+xml',
+ isImage: true,
+ isSvg: true,
+ sanitizedContents: $this->sanitizeSvg($contents),
+ );
+ }
+
+ return new UploadSecurityInspection(
+ mimeType: $mimeType,
+ isImage: str_starts_with($mimeType, 'image/'),
+ isSvg: false,
+ sanitizedContents: null,
+ );
+ }
+
+ private function detectMimeType(string $contents): string
+ {
+ $finfo = new \finfo(FILEINFO_MIME_TYPE);
+ $mimeType = $finfo->buffer($contents);
+
+ return is_string($mimeType) && $mimeType !== ''
+ ? strtolower($mimeType)
+ : 'application/octet-stream';
+ }
+
+ private function isBlockedActiveContent(string $extension, string $mimeType): bool
+ {
+ return in_array($extension, self::BLOCKED_EXTENSIONS, true)
+ || in_array($mimeType, self::BLOCKED_MIME_TYPES, true);
+ }
+
+ private function isSvg(string $extension, string $mimeType): bool
+ {
+ return $extension === 'svg' || $mimeType === 'image/svg+xml';
+ }
+
+ private function sanitizeSvg(string $contents): string
+ {
+ $sanitizer = new Sanitizer();
+ $sanitized = $sanitizer->sanitize($contents);
+
+ if (!is_string($sanitized) || trim($sanitized) === '' || stripos($sanitized, '<svg') === false) {
+ throw new UploadSecurityException('Invalid SVG file.');
+ }
+
+ return $sanitized;
+ }
+}
diff --git a/api/composer.json b/api/composer.json
index 577cbee0e..fe2d5962d 100644
--- a/api/composer.json
+++ b/api/composer.json
@@ -16,6 +16,7 @@
"ext-json": "*",
"aws/aws-sdk-php": "*",
"doctrine/dbal": "*",
+ "enshrined/svg-sanitize": "^0.22",
"fakerphp/faker": "^1.23",
"giggsey/libphonenumber-for-php": "*",
"google/apiclient": "^2.16",
diff --git a/api/composer.lock b/api/composer.lock
index fac8b7ef1..6bfd2940a 100644
--- a/api/composer.lock
+++ b/api/composer.lock
@@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
- "content-hash": "d850ed3a2994eefced4f63a9eac0f5de",
+ "content-hash": "da92420ac840f60ed83fe78c66ccf9af",
"packages": [
{
"name": "aws/aws-crt-php",
@@ -1140,6 +1140,51 @@
],
"time": "2025-03-06T22:45:56+00:00"
},
+ {
+ "name": "enshrined/svg-sanitize",
+ "version": "0.22.0",
+ "source": {
+ "type": "git",
+ "url": "https://github.com/darylldoyle/svg-sanitizer.git",
+ "reference": "0afa95ea74be155a7bcd6c6fb60c276c39984500"
+ },
+ "dist": {
+ "type": "zip",
+ "url": "https://api.github.com/repos/darylldoyle/svg-sanitizer/zipball/0afa95ea74be155a7bcd6c6fb60c276c39984500",
+ "reference": "0afa95ea74be155a7bcd6c6fb60c276c39984500",
+ "shasum": ""
+ },
+ "require": {
+ "ext-dom": "*",
+ "ext-libxml": "*",
+ "php": "^7.1 || ^8.0"
+ },
+ "require-dev": {
+ "phpunit/phpunit": "^6.5 || ^8.5"
+ },
+ "type": "library",
+ "autoload": {
+ "psr-4": {
+ "enshrined\\svgSanitize\\": "src"
+ }
+ },
+ "notification-url": "https://packagist.org/downloads/",
+ "license": [
+ "GPL-2.0-or-later"
+ ],
+ "authors": [
+ {
+ "name": "Daryll Doyle",
+ "email": "[email protected]"
+ }
+ ],
+ "description": "An SVG sanitizer for PHP",
+ "support": {
+ "issues": "https://github.com/darylldoyle/svg-sanitizer/issues",
+ "source": "https://github.com/darylldoyle/svg-sanitizer/tree/0.22.0"
+ },
+ "time": "2025-08-12T10:13:48+00:00"
+ },
{
"name": "ezyang/htmlpurifier",
"version": "v4.19.0",
@@ -16442,5 +16487,5 @@
"ext-pcntl": "8.0",
"ext-posix": "8.0"
},
- "plugin-api-version": "2.9.0"
+ "plugin-api-version": "2.6.0"
}
diff --git a/api/routes/api.php b/api/routes/api.php
index cb7652299..570a8d18d 100644
--- a/api/routes/api.php
+++ b/api/routes/api.php
@@ -25,10 +25,10 @@ use App\Http\Controllers\Auth\UserInviteController;
use App\Http\Controllers\Forms\FormPaymentController;
use App\Http\Controllers\WorkspaceController;
use App\Http\Controllers\WorkspaceUserController;
+use App\Service\Storage\SafeFileResponseService;
use Illuminate\Foundation\Http\Middleware\HandlePrecognitiveRequests;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
-use Illuminate\Support\Facades\Storage;
use App\Http\Controllers\HealthCheckController;
/*
@@ -204,7 +204,7 @@ Route::group(['middleware' => 'auth.multi'], function () {
Route::post(
'/assets/upload',
[FormController::class, 'uploadAsset']
- )->withoutMiddleware(['auth.multi'])->name('assets.upload');
+ )->middleware(['throttle:10,1', 'throttle:30,60'])->withoutMiddleware(['auth.multi'])->name('assets.upload');
Route::get(
'/{form}/uploaded-file/{filename}',
[FormController::class, 'viewFile']
@@ -366,13 +366,13 @@ Route::prefix('forms')->name('forms.')->group(function () {
)->name('users.index');
});
+ // File uploads
+ Route::get('assets/{assetFileName}', [PublicFormController::class, 'showAsset'])->name('assets.show');
+
// Get form and submit
Route::get('{form}', [PublicFormController::class, 'show'])->name('show');
Route::get('{form}/submissions/{submission_id}', [PublicFormController::class, 'fetchSubmission'])->name('fetchSubmission');
- // File uploads
- Route::get('assets/{assetFileName}', [PublicFormController::class, 'showAsset'])->name('assets.show');
-
// AI
Route::post('ai/generate', [\App\Http\Controllers\Forms\AiFormController::class, 'generateForm'])->name('ai.generate');
Route::get('ai/{aiFormCompletion}', [\App\Http\Controllers\Forms\AiFormController::class, 'show'])->name('ai.show');
@@ -413,14 +413,14 @@ Route::post(
Route::post(
'/upload-file',
[\App\Http\Controllers\Content\FileUploadController::class, 'upload']
-)->name('upload-file');
+)->middleware(['throttle:10,1', 'throttle:30,60'])->name('upload-file');
Route::get('local/temp/{path}', function (Request $request, string $path) {
if (!$request->hasValidSignature()) {
abort(401);
}
- return response()->file(Storage::path($path), ['Content-Type' => Storage::mimeType($path)]);
+ return app(SafeFileResponseService::class)->serve($path, basename($path));
})->where('path', '(.*)')->name('local.temp');
Route::get('caddy/ask-certificate/{secret?}', [\App\Http\Controllers\CaddyController::class, 'ask'])
diff --git a/api/tests/Feature/Forms/PublicAssetSecurityTest.php b/api/tests/Feature/Forms/PublicAssetSecurityTest.php
new file mode 100644
index 000000000..8a3f3dc58
--- /dev/null
+++ b/api/tests/Feature/Forms/PublicAssetSecurityTest.php
@@ -0,0 +1,70 @@
+<?php
+
+use App\Http\Controllers\Forms\FormController;
+use Illuminate\Support\Facades\Storage;
+use Illuminate\Support\Facades\URL;
+
+function pngFixture(): string
+{
+ return base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO2Z9f8AAAAASUVORK5CYII=');
+}
+
+it('serves image assets inline with restrictive headers', function () {
+ Storage::fake();
+
+ $fileName = 'test_asset_' . uniqid() . '.png';
+ $path = FormController::ASSETS_UPLOAD_PATH . '/' . $fileName;
+ Storage::put($path, pngFixture());
+
+ $response = $this->get(route('forms.assets.show', [$fileName]));
+
+ $response->assertOk();
+ expect(strtolower($response->headers->get('content-type')))
+ ->toStartWith('image/png');
+ expect($response->headers->get('content-disposition'))
+ ->toBeNull();
+ expect($response->headers->get('x-content-type-options'))
+ ->toBe('nosniff');
+ expect($response->headers->get('content-security-policy'))
+ ->toContain("default-src 'none'")
+ ->toContain('sandbox');
+});
+
+it('serves non-image public assets as attachments with restrictive headers', function () {
+ Storage::fake();
+
+ $fileName = 'test_asset_' . uniqid() . '.pdf';
+ $path = FormController::ASSETS_UPLOAD_PATH . '/' . $fileName;
+ Storage::put($path, '%PDF-1.4 test');
+
+ $response = $this->get(route('forms.assets.show', [$fileName]));
+
+ $response->assertOk();
+ expect(strtolower($response->headers->get('content-type')))
+ ->toStartWith('application/pdf');
+ expect($response->headers->get('content-disposition'))
+ ->toStartWith('attachment;');
+ expect($response->headers->get('x-frame-options'))
+ ->toBe('DENY');
+});
+
+it('serves signed local temporary files with restrictive anti-execution headers', function () {
+ Storage::fake();
+
+ $path = 'tmp/' . uniqid() . '.html';
+ Storage::put($path, '<html><script>alert(1)</script></html>');
+
+ $signedUrl = URL::temporarySignedRoute('local.temp', now()->addMinute(), ['path' => $path]);
+ $response = $this->get($signedUrl);
+
+ $response->assertOk();
+ expect(strtolower($response->headers->get('content-type')))
+ ->toStartWith('text/html');
+ expect($response->headers->get('content-disposition'))
+ ->toStartWith('attachment;');
+ expect($response->headers->get('x-content-type-options'))
+ ->toBe('nosniff');
+ expect($response->headers->get('content-security-policy'))
+ ->toContain("script-src 'none'")
+ ->toContain('sandbox');
+});
diff --git a/api/tests/Feature/Forms/UploadFileSecurityTest.php b/api/tests/Feature/Forms/UploadFileSecurityTest.php
new file mode 100644
index 000000000..0d465a942
--- /dev/null
+++ b/api/tests/Feature/Forms/UploadFileSecurityTest.php
@@ -0,0 +1,120 @@
+<?php
+
+use App\Http\Controllers\Forms\FormController;
+use Illuminate\Http\UploadedFile;
+use Illuminate\Routing\Middleware\ThrottleRequests;
+use Illuminate\Support\Facades\Storage;
+use Illuminate\Support\Str;
+
+it('rejects html uploads in the temp upload endpoint', function () {
+ Storage::fake();
+
+ $response = $this->post('/upload-file', [
+ 'file' => UploadedFile::fake()->createWithContent('evil.html', '<html><script>alert(1)</script></html>'),
+ ]);
+
+ $response->assertStatus(422)
+ ->assertJsonValidationErrors('file');
+});
+
+it('rejects xml uploads in the temp upload endpoint', function () {
+ Storage::fake();
+
+ $response = $this->post('/upload-file', [
+ 'file' => UploadedFile::fake()->createWithContent('evil.xml', '<?xml version="1.0"?><root><script/></root>'),
+ ]);
+
+ $response->assertStatus(422)
+ ->assertJsonValidationErrors('file');
+});
+
+it('sanitizes svg uploads before storing them in temporary storage', function () {
+ Storage::fake();
+
+ $response = $this->post('/upload-file', [
+ 'file' => UploadedFile::fake()->createWithContent('evil.svg', '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script><rect width="5" height="5"/></svg>'),
+ ]);
+
+ $response->assertCreated();
+
+ $storedContents = Storage::get($response->json('key'));
+ expect($storedContents)
+ ->not->toContain('<script')
+ ->toContain('<svg');
+});
+
+it('rejects blocked active content when moving temp files to public assets', function () {
+ Storage::fake();
+
+ $uuid = (string) Str::uuid();
+ Storage::put('tmp/' . $uuid, '<html><script>alert(1)</script></html>');
+
+ $response = $this->postJson('/open/forms/assets/upload', [
+ 'url' => 'evil_' . $uuid . '.html',
+ 'type' => 'files',
+ ]);
+
+ $response->assertStatus(422)
+ ->assertJsonValidationErrors('url');
+});
+
+it('sanitizes svg files when moving them to public assets', function () {
+ Storage::fake();
+
+ $uuid = (string) Str::uuid();
+ Storage::put('tmp/' . $uuid, '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script><rect width="5" height="5"/></svg>');
+
+ $response = $this->postJson('/open/forms/assets/upload', [
+ 'url' => 'evil_' . $uuid . '.svg',
+ 'type' => 'files',
+ ]);
+
+ $response->assertOk();
+
+ $storedContents = Storage::get(FormController::ASSETS_UPLOAD_PATH . '/evil_' . $uuid . '.svg');
+ expect($storedContents)
+ ->not->toContain('<script')
+ ->toContain('<svg');
+});
+
+it('throttles the unauthenticated upload endpoints', function () {
+ Storage::fake();
+ $this->withMiddleware(ThrottleRequests::class);
+ $this->withServerVariables(['REMOTE_ADDR' => '192.0.2.10']);
+
+ $uploadFileThrottled = false;
+ for ($attempt = 0; $attempt < 15; $attempt++) {
+ $response = $this->post('/upload-file', [
+ 'file' => UploadedFile::fake()->createWithContent('note-' . $attempt . '.txt', 'ok'),
+ ]);
+
+ if ($response->status() === 429) {
+ $uploadFileThrottled = true;
+ break;
+ }
+
+ $response->assertCreated();
+ }
+ expect($uploadFileThrottled)->toBeTrue();
+
+ $this->withServerVariables(['REMOTE_ADDR' => '192.0.2.11']);
+
+ $assetUploadThrottled = false;
+ for ($attempt = 0; $attempt < 15; $attempt++) {
+ $uuid = (string) Str::uuid();
+ Storage::put('tmp/' . $uuid, 'safe file');
+
+ $response = $this->postJson('/open/forms/assets/upload', [
+ 'url' => 'asset_' . $uuid . '.txt',
+ 'type' => 'files',
+ ]);
+
+ if ($response->status() === 429) {
+ $assetUploadThrottled = true;
+ break;
+ }
+
+ $response->assertOk();
+ }
+ expect($assetUploadThrottled)->toBeTrue();
+});
diff --git a/api/tests/Unit/Service/Storage/UploadSecurityServiceTest.php b/api/tests/Unit/Service/Storage/UploadSecurityServiceTest.php
new file mode 100644
index 000000000..66e63de77
--- /dev/null
+++ b/api/tests/Unit/Service/Storage/UploadSecurityServiceTest.php
@@ -0,0 +1,53 @@
+<?php
+
+use App\Exceptions\UploadSecurityException;
+use App\Service\Storage\UploadSecurityService;
+use Illuminate\Http\UploadedFile;
+use Illuminate\Support\Facades\Storage;
+use Tests\TestCase;
+
+uses(TestCase::class);
+
+it('rejects blocked html files by extension', function () {
+ $service = new UploadSecurityService();
+
+ expect(fn () => $service->inspectUploadedFile(
+ UploadedFile::fake()->createWithContent('evil.html', 'plain text')
+ ))->toThrow(UploadSecurityException::class);
+});
+
+it('allows non-image files that are not active content', function () {
+ $service = new UploadSecurityService();
+
+ $inspection = $service->inspectUploadedFile(
+ UploadedFile::fake()->createWithContent('notes.txt', 'hello world')
+ );
+
+ expect($inspection->isImage)->toBeFalse();
+ expect($inspection->isSvg)->toBeFalse();
+});
+
+it('sanitizes svg uploads', function () {
+ $service = new UploadSecurityService();
+
+ $inspection = $service->inspectUploadedFile(
+ UploadedFile::fake()->createWithContent('evil.svg', '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(1)</script><rect width="1" height="1"/></svg>')
+ );
+
+ expect($inspection->isSvg)->toBeTrue();
+ expect($inspection->sanitizedContents)
+ ->not->toContain('<script')
+ ->toContain('<svg');
+});
+
+it('uses detected mime when the extension is misleading', function () {
+ Storage::fake();
+
+ $service = new UploadSecurityService();
+ Storage::put('tmp/mismatch', '<svg xmlns="http://www.w3.org/2000/svg"><rect width="1" height="1"/></svg>');
+
+ $inspection = $service->inspectStoredFile('tmp/mismatch', 'not-really.txt');
+
+ expect($inspection->mimeType)->toBe('image/svg+xml');
+ expect($inspection->isSvg)->toBeTrue();
+});