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 = $this->entities->page();
19 $admin = $this->users->admin();
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 = $this->entities->page();
43 $admin = $this->users->admin();
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 = $this->entities->page();
67 $admin = $this->users->admin();
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->users->editor();
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 = $this->entities->page();
129 $editor = $this->users->editor();
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 = $this->entities->page();
149 $admin = $this->users->admin();
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 = $this->entities->page();
171 $admin = $this->users->admin();
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 = $this->entities->page();
188 $admin = $this->users->admin();
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 = $this->entities->page();
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 = $this->entities->page();
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 = $this->entities->page();
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_with_local_secure()
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_system_images_remain_public_with_local_secure_restricted()
332 config()->set('filesystems.images', 'local_secure_restricted');
334 $galleryFile = $this->getTestImage('my-system-test-restricted-upload.png');
335 $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-restricted-upload.png');
337 $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []);
338 $upload->assertRedirect('/settings/customization');
340 $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
342 if (file_exists($expectedPath)) {
343 unlink($expectedPath);
347 public function test_secure_restricted_images_inaccessible_without_relation_permission()
349 config()->set('filesystems.images', 'local_secure_restricted');
351 $galleryFile = $this->getTestImage('my-secure-restricted-test-upload.png');
352 $page = $this->entities->page();
354 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
355 $upload->assertStatus(200);
356 $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
357 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
359 $this->get($expectedUrl)->assertOk();
361 $this->permissions->setEntityPermissions($page, [], []);
363 $resp = $this->get($expectedUrl);
364 $resp->assertNotFound();
366 if (file_exists($expectedPath)) {
367 unlink($expectedPath);
371 public function test_thumbnail_path_handled_by_secure_restricted_images()
373 config()->set('filesystems.images', 'local_secure_restricted');
375 $galleryFile = $this->getTestImage('my-secure-restricted-thumb-test-test.png');
376 $page = $this->entities->page();
378 $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
379 $upload->assertStatus(200);
380 $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/thumbs-150-150/my-secure-restricted-thumb-test-test.png');
381 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-thumb-test-test.png');
383 $this->get($expectedUrl)->assertOk();
385 $this->permissions->setEntityPermissions($page, [], []);
387 $resp = $this->get($expectedUrl);
388 $resp->assertNotFound();
390 if (file_exists($expectedPath)) {
391 unlink($expectedPath);
395 public function test_secure_restricted_image_access_controlled_in_exports()
397 config()->set('filesystems.images', 'local_secure_restricted');
399 $galleryFile = $this->getTestImage('my-secure-restricted-export-test.png');
401 /** @var Page $pageA */
402 /** @var Page $pageB */
403 $pageA = Page::query()->first();
404 $pageB = Page::query()->where('id', '!=', $pageA->id)->first();
405 $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-export-test.png');
407 $upload = $this->asEditor()->call('POST', '/images/gallery', ['uploaded_to' => $pageA->id], [], ['file' => $galleryFile], []);
410 $imageUrl = json_decode($upload->getContent(), true)['url'];
411 $pageB->html .= "<img src=\"{$imageUrl}\">";
414 $encodedImageContent = base64_encode(file_get_contents($expectedPath));
415 $export = $this->get($pageB->getUrl('/export/html'));
416 $this->assertStringContainsString($encodedImageContent, $export->getContent());
418 $this->permissions->setEntityPermissions($pageA, [], []);
420 $export = $this->get($pageB->getUrl('/export/html'));
421 $this->assertStringNotContainsString($encodedImageContent, $export->getContent());
423 if (file_exists($expectedPath)) {
424 unlink($expectedPath);
428 public function test_image_delete()
430 $page = $this->entities->page();
432 $imageName = 'first-image.png';
433 $relPath = $this->getTestImagePath('gallery', $imageName);
434 $this->deleteImage($relPath);
436 $this->uploadImage($imageName, $page->id);
437 $image = Image::first();
439 $delete = $this->delete('/images/' . $image->id);
440 $delete->assertStatus(200);
442 $this->assertDatabaseMissing('images', [
443 'url' => $this->baseUrl . $relPath,
447 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
450 public function test_image_delete_does_not_delete_similar_images()
452 $page = $this->entities->page();
454 $imageName = 'first-image.png';
456 $relPath = $this->getTestImagePath('gallery', $imageName);
457 $this->deleteImage($relPath);
459 $this->uploadImage($imageName, $page->id);
460 $this->uploadImage($imageName, $page->id);
461 $this->uploadImage($imageName, $page->id);
463 $image = Image::first();
464 $folder = public_path(dirname($relPath));
465 $imageCount = count(glob($folder . '/*'));
467 $delete = $this->delete('/images/' . $image->id);
468 $delete->assertStatus(200);
470 $newCount = count(glob($folder . '/*'));
471 $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted');
472 $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
475 public function test_image_manager_delete_button_only_shows_with_permission()
477 $page = $this->entities->page();
479 $imageName = 'first-image.png';
480 $relPath = $this->getTestImagePath('gallery', $imageName);
481 $this->deleteImage($relPath);
482 $viewer = $this->users->viewer();
484 $this->uploadImage($imageName, $page->id);
485 $image = Image::first();
487 $resp = $this->get("/images/edit/{$image->id}");
488 $this->withHtml($resp)->assertElementExists('button#image-manager-delete[title="Delete"]');
490 $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}");
491 $this->withHtml($resp)->assertElementNotExists('button#image-manager-delete[title="Delete"]');
493 $this->permissions->grantUserRolePermissions($viewer, ['image-delete-all']);
495 $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}");
496 $this->withHtml($resp)->assertElementExists('button#image-manager-delete[title="Delete"]');
498 $this->deleteImage($relPath);
501 protected function getTestProfileImage()
503 $imageName = 'profile.png';
504 $relPath = $this->getTestImagePath('user', $imageName);
505 $this->deleteImage($relPath);
507 return $this->getTestImage($imageName);
510 public function test_user_image_upload()
512 $editor = $this->users->editor();
513 $admin = $this->users->admin();
514 $this->actingAs($admin);
516 $file = $this->getTestProfileImage();
517 $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
519 $this->assertDatabaseHas('images', [
521 'uploaded_to' => $editor->id,
522 'created_by' => $admin->id,
526 public function test_user_images_deleted_on_user_deletion()
528 $editor = $this->users->editor();
529 $this->actingAs($editor);
531 $file = $this->getTestProfileImage();
532 $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
534 $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
535 $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count');
537 $imagePath = public_path($profileImages->first()->path);
538 $this->assertTrue(file_exists($imagePath));
540 $userDelete = $this->asAdmin()->delete("/settings/users/{$editor->id}");
541 $userDelete->assertStatus(302);
543 $this->assertDatabaseMissing('images', [
545 'created_by' => $editor->id,
547 $this->assertDatabaseMissing('images', [
549 'uploaded_to' => $editor->id,
552 $this->assertFalse(file_exists($imagePath));
555 public function test_deleted_unused_images()
557 $page = $this->entities->page();
558 $admin = $this->users->admin();
559 $this->actingAs($admin);
561 $imageName = 'unused-image.png';
562 $relPath = $this->getTestImagePath('gallery', $imageName);
563 $this->deleteImage($relPath);
565 $upload = $this->uploadImage($imageName, $page->id);
566 $upload->assertStatus(200);
567 $image = Image::where('type', '=', 'gallery')->first();
569 $pageRepo = app(PageRepo::class);
570 $pageRepo->update($page, [
571 'name' => $page->name,
572 'html' => $page->html . "<img src=\"{$image->url}\">",
576 // Ensure no images are reported as deletable
577 $imageService = app(ImageService::class);
578 $toDelete = $imageService->deleteUnusedImages(true, true);
579 $this->assertCount(0, $toDelete);
581 // Save a revision of our page without the image;
582 $pageRepo->update($page, [
583 'name' => $page->name,
584 'html' => '<p>Hello</p>',
588 // Ensure revision images are picked up okay
589 $imageService = app(ImageService::class);
590 $toDelete = $imageService->deleteUnusedImages(true, true);
591 $this->assertCount(0, $toDelete);
592 $toDelete = $imageService->deleteUnusedImages(false, true);
593 $this->assertCount(1, $toDelete);
595 // Check image is found when revisions are destroyed
596 $page->revisions()->delete();
597 $toDelete = $imageService->deleteUnusedImages(true, true);
598 $this->assertCount(1, $toDelete);
600 // Check the image is deleted
601 $absPath = public_path($relPath);
602 $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
603 $toDelete = $imageService->deleteUnusedImages(true, false);
604 $this->assertCount(1, $toDelete);
605 $this->assertFalse(file_exists($absPath));
607 $this->deleteImage($relPath);