3 namespace Tests\Uploads;
5 use BookStack\Entities\Models\Page;
6 use BookStack\Entities\Repos\PageRepo;
7 use BookStack\Uploads\Image;
8 use BookStack\Uploads\ImageService;
9 use Illuminate\Support\Str;
12 class ImageTest extends TestCase
16 public function test_image_upload()
18 $page = Page::query()->first();
19 $admin = $this->getAdmin();
20 $this->actingAs($admin);
22 $imgDetails = $this->uploadGalleryImage($page);
23 $relPath = $imgDetails['path'];
25 $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath));
27 $this->deleteImage($relPath);
29 $this->assertDatabaseHas('images', [
30 'url' => $this->baseUrl . $relPath,
32 'uploaded_to' => $page->id,
34 'created_by' => $admin->id,
35 'updated_by' => $admin->id,
36 'name' => $imgDetails['name'],
40 public function test_image_display_thumbnail_generation_does_not_increase_image_size()
42 $page = Page::query()->first();
43 $admin = $this->getAdmin();
44 $this->actingAs($admin);
46 $originalFile = $this->getTestImageFilePath('compressed.png');
47 $originalFileSize = filesize($originalFile);
48 $imgDetails = $this->uploadGalleryImage($page, 'compressed.png');
49 $relPath = $imgDetails['path'];
51 $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath));
52 $displayImage = $imgDetails['response']->thumbs->display;
54 $displayImageRelPath = implode('/', array_slice(explode('/', $displayImage), 3));
55 $displayImagePath = public_path($displayImageRelPath);
56 $displayFileSize = filesize($displayImagePath);
58 $this->deleteImage($relPath);
59 $this->deleteImage($displayImageRelPath);
61 $this->assertEquals($originalFileSize, $displayFileSize, 'Display thumbnail generation should not increase image size');
64 public function test_image_display_thumbnail_generation_for_apng_images_uses_original_file()
66 $page = Page::query()->first();
67 $admin = $this->getAdmin();
68 $this->actingAs($admin);
70 $imgDetails = $this->uploadGalleryImage($page, 'animated.png');
71 $this->deleteImage($imgDetails['path']);
73 $this->assertStringContainsString('thumbs-', $imgDetails['response']->thumbs->gallery);
74 $this->assertStringNotContainsString('thumbs-', $imgDetails['response']->thumbs->display);
77 public function test_image_edit()
79 $editor = $this->getEditor();
80 $this->actingAs($editor);
82 $imgDetails = $this->uploadGalleryImage();
83 $image = Image::query()->first();
85 $newName = Str::random();
86 $update = $this->put('/images/' . $image->id, ['name' => $newName]);
87 $update->assertSuccessful();
88 $update->assertSee($newName);
90 $this->deleteImage($imgDetails['path']);
92 $this->assertDatabaseHas('images', [
98 public function test_gallery_get_list_format()
102 $imgDetails = $this->uploadGalleryImage();
103 $image = Image::query()->first();
105 $pageId = $imgDetails['page']->id;
106 $firstPageRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}");
107 $firstPageRequest->assertSuccessful();
108 $this->withHtml($firstPageRequest)->assertElementExists('div');
109 $firstPageRequest->assertSuccessful()->assertSeeText($image->name);
111 $secondPageRequest = $this->get("/images/gallery?page=2&uploaded_to={$pageId}");
112 $secondPageRequest->assertSuccessful();
113 $this->withHtml($secondPageRequest)->assertElementNotExists('div');
115 $namePartial = substr($imgDetails['name'], 0, 3);
116 $searchHitRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
117 $searchHitRequest->assertSuccessful()->assertSee($imgDetails['name']);
119 $namePartial = Str::random(16);
120 $searchFailRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
121 $searchFailRequest->assertSuccessful()->assertDontSee($imgDetails['name']);
122 $searchFailRequest->assertSuccessful();
123 $this->withHtml($searchFailRequest)->assertElementNotExists('div');
126 public function test_image_usage()
128 $page = Page::query()->first();
129 $editor = $this->getEditor();
130 $this->actingAs($editor);
132 $imgDetails = $this->uploadGalleryImage($page);
134 $image = Image::query()->first();
135 $page->html = '<img src="' . $image->url . '">';
138 $usage = $this->get('/images/edit/' . $image->id . '?delete=true');
139 $usage->assertSuccessful();
140 $usage->assertSeeText($page->name);
141 $usage->assertSee($page->getUrl());
143 $this->deleteImage($imgDetails['path']);
146 public function test_php_files_cannot_be_uploaded()
148 $page = Page::query()->first();
149 $admin = $this->getAdmin();
150 $this->actingAs($admin);
152 $fileName = 'bad.php';
153 $relPath = $this->getTestImagePath('gallery', $fileName);
154 $this->deleteImage($relPath);
156 $file = $this->newTestImageFromBase64('bad-php.base64', $fileName);
157 $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
158 $upload->assertStatus(302);
160 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
162 $this->assertDatabaseMissing('images', [
168 public function test_php_like_files_cannot_be_uploaded()
170 $page = Page::query()->first();
171 $admin = $this->getAdmin();
172 $this->actingAs($admin);
174 $fileName = 'bad.phtml';
175 $relPath = $this->getTestImagePath('gallery', $fileName);
176 $this->deleteImage($relPath);
178 $file = $this->newTestImageFromBase64('bad-phtml.base64', $fileName);
179 $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
180 $upload->assertStatus(302);
182 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
185 public function test_files_with_double_extensions_will_get_sanitized()
187 $page = Page::query()->first();
188 $admin = $this->getAdmin();
189 $this->actingAs($admin);
191 $fileName = 'bad.phtml.png';
192 $relPath = $this->getTestImagePath('gallery', $fileName);
193 $expectedRelPath = dirname($relPath) . '/bad-phtml.png';
194 $this->deleteImage($expectedRelPath);
196 $file = $this->newTestImageFromBase64('bad-phtml-png.base64', $fileName);
197 $upload = $this->withHeader('Content-Type', 'image/png')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
198 $upload->assertStatus(200);
200 $lastImage = Image::query()->latest('id')->first();
202 $this->assertEquals('bad.phtml.png', $lastImage->name);
203 $this->assertEquals('bad-phtml.png', basename($lastImage->path));
204 $this->assertFileDoesNotExist(public_path($relPath), 'Uploaded image file name was not stripped of dots');
205 $this->assertFileExists(public_path($expectedRelPath));
207 $this->deleteImage($lastImage->path);
210 public function test_url_entities_removed_from_filenames()
214 'bad-char-#-image.png',
215 'bad-char-?-image.png',
220 foreach ($badNames as $name) {
221 $galleryFile = $this->getTestImage($name);
222 $page = Page::query()->first();
223 $badPath = $this->getTestImagePath('gallery', $name);
224 $this->deleteImage($badPath);
226 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
227 $upload->assertStatus(200);
229 $lastImage = Image::query()->latest('id')->first();
230 $newFileName = explode('.', basename($lastImage->path))[0];
232 $this->assertEquals($lastImage->name, $name);
233 $this->assertFalse(strpos($lastImage->path, $name), 'Path contains original image name');
234 $this->assertFalse(file_exists(public_path($badPath)), 'Uploaded image file name was not stripped of url entities');
236 $this->assertTrue(strlen($newFileName) > 0, 'File name was reduced to nothing');
238 $this->deleteImage($lastImage->path);
242 public function test_secure_images_uploads_to_correct_place()
244 config()->set('filesystems.images', 'local_secure');
246 $galleryFile = $this->getTestImage('my-secure-test-upload.png');
247 $page = Page::query()->first();
248 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
250 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
251 $upload->assertStatus(200);
253 $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
255 if (file_exists($expectedPath)) {
256 unlink($expectedPath);
260 public function test_secure_image_paths_traversal_causes_500()
262 config()->set('filesystems.images', 'local_secure');
265 $resp = $this->get('/uploads/images/../../logs/laravel.log');
266 $resp->assertStatus(500);
269 public function test_secure_image_paths_traversal_on_non_secure_images_causes_404()
271 config()->set('filesystems.images', 'local');
274 $resp = $this->get('/uploads/images/../../logs/laravel.log');
275 $resp->assertStatus(404);
278 public function test_secure_image_paths_dont_serve_non_images()
280 config()->set('filesystems.images', 'local_secure');
283 $testFilePath = storage_path('/uploads/images/testing.txt');
284 file_put_contents($testFilePath, 'hello from test_secure_image_paths_dont_serve_non_images');
286 $resp = $this->get('/uploads/images/testing.txt');
287 $resp->assertStatus(404);
290 public function test_secure_images_included_in_exports()
292 config()->set('filesystems.images', 'local_secure');
294 $galleryFile = $this->getTestImage('my-secure-test-upload.png');
295 $page = Page::query()->first();
296 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
298 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
299 $imageUrl = json_decode($upload->getContent(), true)['url'];
300 $page->html .= "<img src=\"{$imageUrl}\">";
302 $upload->assertStatus(200);
304 $encodedImageContent = base64_encode(file_get_contents($expectedPath));
305 $export = $this->get($page->getUrl('/export/html'));
306 $this->assertTrue(strpos($export->getContent(), $encodedImageContent) !== false, 'Uploaded image in export content');
308 if (file_exists($expectedPath)) {
309 unlink($expectedPath);
313 public function test_system_images_remain_public()
315 config()->set('filesystems.images', 'local_secure');
317 $galleryFile = $this->getTestImage('my-system-test-upload.png');
318 $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-upload.png');
320 $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []);
321 $upload->assertRedirect('/settings/customization');
323 $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
325 if (file_exists($expectedPath)) {
326 unlink($expectedPath);
330 public function test_secure_restricted_images_inaccessible_without_relation_permission()
332 config()->set('filesystems.images', 'local_secure_restricted');
334 $galleryFile = $this->getTestImage('my-secure-restricted-test-upload.png');
335 /** @var Page $page */
336 $page = Page::query()->first();
338 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
339 $upload->assertStatus(200);
340 $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
341 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
343 $this->get($expectedUrl)->assertOk();
345 $this->setEntityRestrictions($page, [], []);
347 $resp = $this->get($expectedUrl);
348 $resp->assertNotFound();
350 if (file_exists($expectedPath)) {
351 unlink($expectedPath);
355 public function test_thumbnail_path_handled_by_secure_restricted_images()
357 config()->set('filesystems.images', 'local_secure_restricted');
359 $galleryFile = $this->getTestImage('my-secure-restricted-thumb-test-test.png');
360 /** @var Page $page */
361 $page = Page::query()->first();
363 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
364 $upload->assertStatus(200);
365 $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/thumbs-150-150/my-secure-restricted-thumb-test-test.png');
366 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-thumb-test-test.png');
368 $this->get($expectedUrl)->assertOk();
370 $this->setEntityRestrictions($page, [], []);
372 $resp = $this->get($expectedUrl);
373 $resp->assertNotFound();
375 if (file_exists($expectedPath)) {
376 unlink($expectedPath);
380 public function test_secure_restricted_image_access_controlled_in_exports()
382 config()->set('filesystems.images', 'local_secure_restricted');
384 $galleryFile = $this->getTestImage('my-secure-restricted-export-test.png');
386 /** @var Page $pageA */
387 /** @var Page $pageB */
388 $pageA = Page::query()->first();
389 $pageB = Page::query()->where('id', '!=', $pageA->id)->first();
390 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-export-test.png');
392 $upload = $this->asEditor()->call('POST', '/images/gallery', ['uploaded_to' => $pageA->id], [], ['file' => $galleryFile], []);
395 $imageUrl = json_decode($upload->getContent(), true)['url'];
396 $pageB->html .= "<img src=\"{$imageUrl}\">";
399 $encodedImageContent = base64_encode(file_get_contents($expectedPath));
400 $export = $this->get($pageB->getUrl('/export/html'));
401 $this->assertStringContainsString($encodedImageContent, $export->getContent());
403 $this->setEntityRestrictions($pageA, [], []);
405 $export = $this->get($pageB->getUrl('/export/html'));
406 $this->assertStringNotContainsString($encodedImageContent, $export->getContent());
408 if (file_exists($expectedPath)) {
409 unlink($expectedPath);
413 public function test_image_delete()
415 $page = Page::query()->first();
417 $imageName = 'first-image.png';
418 $relPath = $this->getTestImagePath('gallery', $imageName);
419 $this->deleteImage($relPath);
421 $this->uploadImage($imageName, $page->id);
422 $image = Image::first();
424 $delete = $this->delete('/images/' . $image->id);
425 $delete->assertStatus(200);
427 $this->assertDatabaseMissing('images', [
428 'url' => $this->baseUrl . $relPath,
432 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
435 public function test_image_delete_does_not_delete_similar_images()
437 $page = Page::query()->first();
439 $imageName = 'first-image.png';
441 $relPath = $this->getTestImagePath('gallery', $imageName);
442 $this->deleteImage($relPath);
444 $this->uploadImage($imageName, $page->id);
445 $this->uploadImage($imageName, $page->id);
446 $this->uploadImage($imageName, $page->id);
448 $image = Image::first();
449 $folder = public_path(dirname($relPath));
450 $imageCount = count(glob($folder . '/*'));
452 $delete = $this->delete('/images/' . $image->id);
453 $delete->assertStatus(200);
455 $newCount = count(glob($folder . '/*'));
456 $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted');
457 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
460 protected function getTestProfileImage()
462 $imageName = 'profile.png';
463 $relPath = $this->getTestImagePath('user', $imageName);
464 $this->deleteImage($relPath);
466 return $this->getTestImage($imageName);
469 public function test_user_image_upload()
471 $editor = $this->getEditor();
472 $admin = $this->getAdmin();
473 $this->actingAs($admin);
475 $file = $this->getTestProfileImage();
476 $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
478 $this->assertDatabaseHas('images', [
480 'uploaded_to' => $editor->id,
481 'created_by' => $admin->id,
485 public function test_user_images_deleted_on_user_deletion()
487 $editor = $this->getEditor();
488 $this->actingAs($editor);
490 $file = $this->getTestProfileImage();
491 $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
493 $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
494 $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count');
496 $imagePath = public_path($profileImages->first()->path);
497 $this->assertTrue(file_exists($imagePath));
499 $userDelete = $this->asAdmin()->delete("/settings/users/{$editor->id}");
500 $userDelete->assertStatus(302);
502 $this->assertDatabaseMissing('images', [
504 'created_by' => $editor->id,
506 $this->assertDatabaseMissing('images', [
508 'uploaded_to' => $editor->id,
511 $this->assertFalse(file_exists($imagePath));
514 public function test_deleted_unused_images()
516 $page = Page::query()->first();
517 $admin = $this->getAdmin();
518 $this->actingAs($admin);
520 $imageName = 'unused-image.png';
521 $relPath = $this->getTestImagePath('gallery', $imageName);
522 $this->deleteImage($relPath);
524 $upload = $this->uploadImage($imageName, $page->id);
525 $upload->assertStatus(200);
526 $image = Image::where('type', '=', 'gallery')->first();
528 $pageRepo = app(PageRepo::class);
529 $pageRepo->update($page, [
530 'name' => $page->name,
531 'html' => $page->html . "<img src=\"{$image->url}\">",
535 // Ensure no images are reported as deletable
536 $imageService = app(ImageService::class);
537 $toDelete = $imageService->deleteUnusedImages(true, true);
538 $this->assertCount(0, $toDelete);
540 // Save a revision of our page without the image;
541 $pageRepo->update($page, [
542 'name' => $page->name,
543 'html' => '<p>Hello</p>',
547 // Ensure revision images are picked up okay
548 $imageService = app(ImageService::class);
549 $toDelete = $imageService->deleteUnusedImages(true, true);
550 $this->assertCount(0, $toDelete);
551 $toDelete = $imageService->deleteUnusedImages(false, true);
552 $this->assertCount(1, $toDelete);
554 // Check image is found when revisions are destroyed
555 $page->revisions()->delete();
556 $toDelete = $imageService->deleteUnusedImages(true, true);
557 $this->assertCount(1, $toDelete);
559 // Check the image is deleted
560 $absPath = public_path($relPath);
561 $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
562 $toDelete = $imageService->deleteUnusedImages(true, false);
563 $this->assertCount(1, $toDelete);
564 $this->assertFalse(file_exists($absPath));
566 $this->deleteImage($relPath);