NOW MANAGED ON CODEBERG
Allow uploads of files containing dots in filename. Closes BookStackApp/BookStack#2217
Timo Förster745d15d200dc
diff --git a/app/Http/Controllers/Controller.php b/app/Http/Controllers/Controller.phpindex 479d5ac15..034dfa524 100644--- a/app/Http/Controllers/Controller.php+++ b/app/Http/Controllers/Controller.php@@ -159,6 +159,6 @@ abstract class Controller extends BaseController*/protected function getImageValidationRules(): string{- return 'image_extension|no_double_extension|mimes:jpeg,png,gif,webp';+ return 'image_extension|mimes:jpeg,png,gif,webp';}}diff --git a/app/Providers/CustomValidationServiceProvider.php b/app/Providers/CustomValidationServiceProvider.phpindex 4a5272b40..b668a4cd2 100644--- a/app/Providers/CustomValidationServiceProvider.php+++ b/app/Providers/CustomValidationServiceProvider.php@@ -18,11 +18,6 @@ class CustomValidationServiceProvider extends ServiceProviderreturn in_array(strtolower($value->getClientOriginalExtension()), $validImageExtensions);});- Validator::extend('no_double_extension', function ($attribute, $value, $parameters, $validator) {- $uploadName = $value->getClientOriginalName();- return substr_count($uploadName, '.') < 2;- });-Validator::extend('safe_url', function ($attribute, $value, $parameters, $validator) {$cleanLinkName = strtolower(trim($value));$isJs = strpos($cleanLinkName, 'javascript:') === 0;diff --git a/app/Uploads/ImageService.php b/app/Uploads/ImageService.phpindex 92c3994a7..ee42e6e33 100644--- a/app/Uploads/ImageService.php+++ b/app/Uploads/ImageService.php@@ -60,7 +60,7 @@ class ImageServiceint $resizeHeight = null,bool $keepRatio = true) {- $imageName = $uploadedFile->getClientOriginalName();+ $imageName = $this->sanitizeFileName($uploadedFile->getClientOriginalName());$imageData = file_get_contents($uploadedFile->getRealPath());if ($resizeWidth !== null || $resizeHeight !== null) {@@ -426,4 +426,15 @@ class ImageService$basePath = ($this->storageUrl == false) ? url('/') : $this->storageUrl;return rtrim($basePath, '/') . $filePath;}++ /**+ * Returns a sanitized filename with only one file extension+ */+ private function sanitizeFileName(string $fileName): string+ {+ $parts = explode('.', $fileName);+ $extension = array_pop($parts);++ return sprintf('%s.%s', implode('-', $parts), $extension);+ }}diff --git a/resources/lang/ar/validation.php b/resources/lang/ar/validation.phpindex d0b17460b..3c03f2efd 100644--- a/resources/lang/ar/validation.php+++ b/resources/lang/ar/validation.php@@ -78,7 +78,6 @@ return ['string' => 'يجب أن يكون :attribute على الأقل :min حرف / حروف.','array' => 'يجب أن يحتوي :attribute على :min عنصر / عناصر كحد أدنى.',],- 'no_double_extension' => 'يجب أن يكون للسمة: امتداد ملف واحد فقط.','not_in' => ':attribute المحدد غير صالح.','not_regex' => 'صيغة السمة: غير صالحة.','numeric' => 'يجب أن يكون :attribute رقم.',diff --git a/resources/lang/bg/validation.php b/resources/lang/bg/validation.phpindex 578ea999f..4031de2ae 100644--- a/resources/lang/bg/validation.php+++ b/resources/lang/bg/validation.php@@ -78,7 +78,6 @@ return ['string' => 'The :attribute must be at least :min characters.','array' => 'The :attribute must have at least :min items.',],- 'no_double_extension' => 'The :attribute must only have a single file extension.','not_in' => 'The selected :attribute is invalid.','not_regex' => 'The :attribute format is invalid.','numeric' => 'The :attribute must be a number.',diff --git a/resources/lang/cs/validation.php b/resources/lang/cs/validation.phpindex a84397349..1a94b9e24 100644--- a/resources/lang/cs/validation.php+++ b/resources/lang/cs/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attribute musí být delší než :min znaků.','array' => ':attribute musí obsahovat více než :min prvků.',],- 'no_double_extension' => ':attribute musí obsahovat pouze jednu příponu souboru.','not_in' => 'Zvolená hodnota pro :attribute je neplatná.','not_regex' => ':attribute musí být regulární výraz.','numeric' => ':attribute musí být číslo.',diff --git a/resources/lang/da/validation.php b/resources/lang/da/validation.phpindex 7647132ca..d4564c571 100644--- a/resources/lang/da/validation.php+++ b/resources/lang/da/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attribute skal mindst være :min tegn.','array' => ':attribute skal have mindst :min elementer.',],- 'no_double_extension' => ':attribute må kun indeholde én filtype.','not_in' => 'Den valgte :attribute er ikke gyldig.','not_regex' => ':attribute-formatet er ugyldigt.','numeric' => ':attribute skal være et tal.',diff --git a/resources/lang/de/validation.php b/resources/lang/de/validation.phpindex 8b1febc85..50f8a76a3 100644--- a/resources/lang/de/validation.php+++ b/resources/lang/de/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attribute muss mindestens :min Zeichen lang sein.','array' => ':attribute muss mindesten :min Elemente enthalten.',],- 'no_double_extension' => ':attribute darf nur eine gültige Dateiendung','not_in' => ':attribute ist ungültig.','not_regex' => ':attribute ist kein valides Format.','numeric' => ':attribute muss eine Zahl sein.',diff --git a/resources/lang/de_informal/validation.php b/resources/lang/de_informal/validation.phpindex 24c1e8add..42456da6e 100644--- a/resources/lang/de_informal/validation.php+++ b/resources/lang/de_informal/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attribute muss mindestens :min Zeichen lang sein.','array' => ':attribute muss mindesten :min Elemente enthalten.',],- 'no_double_extension' => ':attribute darf nur eine gültige Dateiendung','not_in' => ':attribute ist ungültig.','not_regex' => ':attribute ist kein gültiges Format.','numeric' => ':attribute muss eine Zahl sein.',diff --git a/resources/lang/en/validation.php b/resources/lang/en/validation.phpindex 578ea999f..4031de2ae 100644--- a/resources/lang/en/validation.php+++ b/resources/lang/en/validation.php@@ -78,7 +78,6 @@ return ['string' => 'The :attribute must be at least :min characters.','array' => 'The :attribute must have at least :min items.',],- 'no_double_extension' => 'The :attribute must only have a single file extension.','not_in' => 'The selected :attribute is invalid.','not_regex' => 'The :attribute format is invalid.','numeric' => 'The :attribute must be a number.',diff --git a/resources/lang/es/validation.php b/resources/lang/es/validation.phpindex f6f9a1ee1..450e92375 100644--- a/resources/lang/es/validation.php+++ b/resources/lang/es/validation.php@@ -78,7 +78,6 @@ return ['string' => 'El :attribute debe ser al menos :min caracteres.','array' => 'El :attribute debe tener como mínimo :min items.',],- 'no_double_extension' => 'El :attribute solo debe tener una extensión de archivo.','not_in' => 'El :attribute seleccionado es inválio.','not_regex' => 'El formato de :attribute es inválido.','numeric' => 'El :attribute debe ser numérico.',diff --git a/resources/lang/es_AR/validation.php b/resources/lang/es_AR/validation.phpindex 7afd2bb46..3e37f619e 100644--- a/resources/lang/es_AR/validation.php+++ b/resources/lang/es_AR/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attribute debe ser al menos :min caracteres.','array' => ':attribute debe tener como mínimo :min items.',],- 'no_double_extension' => 'El :attribute debe tener una única extensión de archivo.','not_in' => ':attribute seleccionado es inválido.','not_regex' => 'El formato de :attribute es inválido.','numeric' => ':attribute debe ser numérico.',diff --git a/resources/lang/fa/validation.php b/resources/lang/fa/validation.phpindex 76b57a2a3..f4af9bc6f 100644--- a/resources/lang/fa/validation.php+++ b/resources/lang/fa/validation.php@@ -78,7 +78,6 @@ return ['string' => 'The :attribute must be at least :min characters.','array' => 'The :attribute must have at least :min items.',],- 'no_double_extension' => 'The :attribute must only have a single file extension.','not_in' => 'The selected :attribute is invalid.','not_regex' => 'The :attribute format is invalid.','numeric' => 'The :attribute must be a number.',diff --git a/resources/lang/fr/validation.php b/resources/lang/fr/validation.phpindex 60d8d34ac..684404f42 100644--- a/resources/lang/fr/validation.php+++ b/resources/lang/fr/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attribute doit contenir au moins :min caractères.','array' => ':attribute doit contenir au moins :min éléments.',],- 'no_double_extension' => ':attribute ne doit avoir qu\'une seule extension de fichier.','not_in' => 'L\'attribut sélectionné :attribute est invalide.','not_regex' => ':attribute a un format invalide.','numeric' => ':attribute doit être un nombre.',diff --git a/resources/lang/he/validation.php b/resources/lang/he/validation.phpindex 7c02735ca..8a18ca27a 100644--- a/resources/lang/he/validation.php+++ b/resources/lang/he/validation.php@@ -78,7 +78,6 @@ return ['string' => 'שדה :attribute חייב להיות לפחות :min תווים.','array' => 'שדה :attribute חייב להיות לפחות :min פריטים.',],- 'no_double_extension' => 'השדה :attribute חייב להיות בעל סיומת קובץ אחת בלבד.','not_in' => 'בחירת ה-:attribute אינה תקפה.','not_regex' => 'The :attribute format is invalid.','numeric' => 'שדה :attribute חייב להיות מספר.',diff --git a/resources/lang/hu/validation.php b/resources/lang/hu/validation.phpindex 7c378e983..d82e32632 100644--- a/resources/lang/hu/validation.php+++ b/resources/lang/hu/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attribute legalább :min karakter kell legyen.','array' => ':attribute legalább :min elem kell legyen.',],- 'no_double_extension' => ':attribute csak egy fájlkiterjesztéssel rendelkezhet.','not_in' => 'A kiválasztott :attribute érvénytelen.','not_regex' => ':attribute formátuma érvénytelen.','numeric' => ':attribute szám kell legyen.',diff --git a/resources/lang/it/validation.php b/resources/lang/it/validation.phpindex 2e460cdc3..bb602619c 100755--- a/resources/lang/it/validation.php+++ b/resources/lang/it/validation.php@@ -78,7 +78,6 @@ return ['string' => 'Il campo :attribute deve essere almeno :min caratteri.','array' => 'Il campo :attribute deve contenere almeno :min elementi.',],- 'no_double_extension' => ':attribute deve avere solo un\'estensione.','not_in' => 'Il :attribute selezionato non è valido.','not_regex' => 'Il formato di :attribute non è valido.','numeric' => ':attribute deve essere un numero.',diff --git a/resources/lang/ja/validation.php b/resources/lang/ja/validation.phpindex 61057f17e..7d9987ce0 100644--- a/resources/lang/ja/validation.php+++ b/resources/lang/ja/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attributeは:min文字以上である必要があります。','array' => ':attributeは:min個以上である必要があります。',],- 'no_double_extension' => 'The :attribute must only have a single file extension.','not_in' => '選択された:attributeは不正です。','not_regex' => 'The :attribute format is invalid.','numeric' => ':attributeは数値である必要があります。',diff --git a/resources/lang/ko/validation.php b/resources/lang/ko/validation.phpindex 64c4a4345..6754d9620 100644--- a/resources/lang/ko/validation.php+++ b/resources/lang/ko/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attribute(을)를 적어도 :value바이트로 구성하세요.','array' => ':attribute(을)를 적어도 :value개로 구성하세요..',],- 'no_double_extension' => ':attribute(이)가 단일한 확장자를 가져야 합니다.','not_in' => '고른 :attribute(이)가 유효하지 않습니다.','not_regex' => ':attribute(은)는 유효하지 않은 형식입니다.','numeric' => ':attribute(을)를 숫자로만 구성하세요.',diff --git a/resources/lang/nb/validation.php b/resources/lang/nb/validation.phpindex 87e6c7529..eca6dd6ba 100644--- a/resources/lang/nb/validation.php+++ b/resources/lang/nb/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attribute må være på minst :min tegn.','array' => ':attribute må minst ha :min ting.',],- 'no_double_extension' => ':attribute kan bare ha en formattype spesifisert.','not_in' => 'Den valgte :attribute er ugyldig.','not_regex' => ':attribute format er ugyldig.','numeric' => ':attribute må være et nummer.',diff --git a/resources/lang/nl/validation.php b/resources/lang/nl/validation.phpindex 2f8ffc9f0..fa1691050 100644--- a/resources/lang/nl/validation.php+++ b/resources/lang/nl/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attribute moet minstens :min karakters bevatten.','array' => ':attribute moet minstens :min items bevatten.',],- 'no_double_extension' => ':attribute mag maar een enkele bestandsextensie hebben.','not_in' => ':attribute is ongeldig.','not_regex' => ':attribute formaat is ongeldig.','numeric' => ':attribute moet een getal zijn.',diff --git a/resources/lang/pl/validation.php b/resources/lang/pl/validation.phpindex 26ac348c1..cc33dc878 100644--- a/resources/lang/pl/validation.php+++ b/resources/lang/pl/validation.php@@ -78,7 +78,6 @@ return ['string' => 'Długość :attribute nie może być mniejsza niż :min znaków.','array' => 'Rozmiar :attribute musi posiadać co najmniej :min elementy.',],- 'no_double_extension' => ':attribute może mieć tylko jedno rozszerzenie.','not_in' => 'Wartość :attribute jest nieprawidłowa.','not_regex' => 'Format :attribute jest nieprawidłowy.','numeric' => ':attribute musi być liczbą.',diff --git a/resources/lang/pt/validation.php b/resources/lang/pt/validation.phpindex 76b57a2a3..f4af9bc6f 100644--- a/resources/lang/pt/validation.php+++ b/resources/lang/pt/validation.php@@ -78,7 +78,6 @@ return ['string' => 'The :attribute must be at least :min characters.','array' => 'The :attribute must have at least :min items.',],- 'no_double_extension' => 'The :attribute must only have a single file extension.','not_in' => 'The selected :attribute is invalid.','not_regex' => 'The :attribute format is invalid.','numeric' => 'The :attribute must be a number.',diff --git a/resources/lang/pt_BR/validation.php b/resources/lang/pt_BR/validation.phpindex 9777eacac..0d25a9b6a 100644--- a/resources/lang/pt_BR/validation.php+++ b/resources/lang/pt_BR/validation.php@@ -78,7 +78,6 @@ return ['string' => 'O campo :attribute não deve ter menos que :min caracteres.','array' => 'O campo :attribute não deve ter menos que :min itens.',],- 'no_double_extension' => 'O campo :attribute deve ter apenas uma extensão de arquivo.','not_in' => 'O campo selecionado :attribute é inválido.','not_regex' => 'O formato do campo :attribute é inválido.','numeric' => 'O campo :attribute deve ser um número.',diff --git a/resources/lang/ru/validation.php b/resources/lang/ru/validation.phpindex d16ead5d8..8c583f7e7 100644--- a/resources/lang/ru/validation.php+++ b/resources/lang/ru/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attribute должен быть минимум :min символов.','array' => ':attribute должен содержать хотя бы :min элементов.',],- 'no_double_extension' => ':attribute должен иметь только одно расширение файла.','not_in' => 'Выбранный :attribute некорректен.','not_regex' => 'Формат :attribute некорректен.','numeric' => ':attribute должен быть числом.',diff --git a/resources/lang/sk/validation.php b/resources/lang/sk/validation.phpindex c127b0623..545313415 100644--- a/resources/lang/sk/validation.php+++ b/resources/lang/sk/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attribute musí mať aspoň :min znakov.','array' => ':attribute musí mať aspoň :min položiek.',],- 'no_double_extension' => 'The :attribute must only have a single file extension.','not_in' => 'Vybraný :attribute je neplatný.','not_regex' => 'The :attribute format is invalid.','numeric' => ':attribute musí byť číslo.',diff --git a/resources/lang/sl/validation.php b/resources/lang/sl/validation.phpindex bc7242bac..9b1a5ff46 100644--- a/resources/lang/sl/validation.php+++ b/resources/lang/sl/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attribute mora biti najmanj :min znakov.','array' => ':attribute mora imeti vsaj :min elementov.',],- 'no_double_extension' => ':attribute mora imeti samo eno razširitveno datoteko','not_in' => 'Izbrani atribut je neveljaven.','not_regex' => ':attribute oblika ni veljavna.','numeric' => 'Atribut mora biti število.',diff --git a/resources/lang/sv/validation.php b/resources/lang/sv/validation.phpindex 319031855..da39796bc 100644--- a/resources/lang/sv/validation.php+++ b/resources/lang/sv/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attribute måste vara minst :min tecken.','array' => ':attribute måste ha minst :min poster.',],- 'no_double_extension' => ':attribute får bara ha ett filtillägg.','not_in' => 'Vald :attribute är inte giltig','not_regex' => 'Formatet på :attribute är ogiltigt.','numeric' => ':attribute måste vara ett nummer.',diff --git a/resources/lang/th/validation.php b/resources/lang/th/validation.phpindex 76b57a2a3..f4af9bc6f 100644--- a/resources/lang/th/validation.php+++ b/resources/lang/th/validation.php@@ -78,7 +78,6 @@ return ['string' => 'The :attribute must be at least :min characters.','array' => 'The :attribute must have at least :min items.',],- 'no_double_extension' => 'The :attribute must only have a single file extension.','not_in' => 'The selected :attribute is invalid.','not_regex' => 'The :attribute format is invalid.','numeric' => 'The :attribute must be a number.',diff --git a/resources/lang/tr/validation.php b/resources/lang/tr/validation.phpindex 45b7189d7..48bbef92b 100644--- a/resources/lang/tr/validation.php+++ b/resources/lang/tr/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attribute, en az :min karakter içermelidir.','array' => ':attribute, en az :min öge içermelidir.',],- 'no_double_extension' => ':attribute, sadece tek bir dosya tipinde olmalıdır.','not_in' => 'Seçili :attribute geçersiz.','not_regex' => ':attribute formatı geçersiz.','numeric' => ':attribute, bir sayı olmalıdır.',diff --git a/resources/lang/uk/validation.php b/resources/lang/uk/validation.phpindex 51b9a0999..63b356cfe 100644--- a/resources/lang/uk/validation.php+++ b/resources/lang/uk/validation.php@@ -78,7 +78,6 @@ return ['string' => 'Текст в полі :attribute повинен містити не менше :min символів.','array' => 'Поле :attribute повинне містити не менше :min елементів.',],- 'no_double_extension' => 'Поле :attribute повинне містити тільки одне розширення файлу.','not_in' => 'Вибране для :attribute значення не коректне.','not_regex' => 'Формат поля :attribute не вірний.','numeric' => 'Поле :attribute повинно містити число.',diff --git a/resources/lang/vi/validation.php b/resources/lang/vi/validation.phpindex c00207175..bcfb178fb 100644--- a/resources/lang/vi/validation.php+++ b/resources/lang/vi/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attribute phải có tối thiểu :min ký tự.','array' => ':attribute phải có tối thiểu :min mục.',],- 'no_double_extension' => ':attribute chỉ được có một định dạng mở rộng duy nhất.','not_in' => ':attribute đã chọn không hợp lệ.','not_regex' => 'Định dạng của :attribute không hợp lệ.','numeric' => ':attribute phải là một số.',diff --git a/resources/lang/zh_CN/validation.php b/resources/lang/zh_CN/validation.phpindex 8bb8a207a..72b0d594e 100644--- a/resources/lang/zh_CN/validation.php+++ b/resources/lang/zh_CN/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attribute 至少为:min个字符。','array' => ':attribute 至少有:min项。',],- 'no_double_extension' => ':attribute 必须具有一个扩展名。','not_in' => '选中的 :attribute 无效。','not_regex' => ':attribute 格式错误。','numeric' => ':attribute 必须是一个数。',diff --git a/resources/lang/zh_TW/validation.php b/resources/lang/zh_TW/validation.phpindex 7a46288ad..f8a7dac63 100644--- a/resources/lang/zh_TW/validation.php+++ b/resources/lang/zh_TW/validation.php@@ -78,7 +78,6 @@ return ['string' => ':attribute 至少為:min個字元。','array' => ':attribute 至少有:min項。',],- 'no_double_extension' => 'The :attribute必須僅具有一個文件擴展名。','not_in' => '選中的 :attribute 無效。','not_regex' => 'The :attribute格式無效。','numeric' => ':attribute 必須是一個數。',diff --git a/tests/Uploads/ImageTest.php b/tests/Uploads/ImageTest.phpindex 9b0e004b1..55d580e46 100644--- a/tests/Uploads/ImageTest.php+++ b/tests/Uploads/ImageTest.php@@ -165,7 +165,7 @@ class ImageTest extends TestCase$this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');}- public function test_files_with_double_extensions_cannot_be_uploaded()+ public function test_files_with_double_extensions_will_get_sanitized(){$page = Page::first();$admin = $this->getAdmin();@@ -177,9 +177,17 @@ class ImageTest extends TestCase$file = $this->newTestImageFromBase64('bad-phtml-png.base64', $fileName);$upload = $this->withHeader('Content-Type', 'image/png')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);- $upload->assertStatus(302);+ $upload->assertStatus(200);++ $lastImage = Image::query()->latest('id')->first();+ $newFileName = explode('.', basename($lastImage->path))[0];++ $this->assertEquals($lastImage->name, 'bad-phtml.png');+ $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image file name was not stripped of dots');++ $this->assertTrue(strlen($newFileName) > 0, 'File name was reduced to nothing');- $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded double extension file was uploaded but should have been stopped');+ $this->deleteImage($lastImage->path);}public function test_url_entities_removed_from_filenames()@@ -428,4 +436,4 @@ class ImageTest extends TestCase$this->deleteImage($relPath);}-}\ No newline at end of file+}