]> BookStack Code Mirror - bookstack/blob - tests/Uploads/ImageTest.php
Extracted test file handling to its own class
[bookstack] / tests / Uploads / ImageTest.php
1 <?php
2
3 namespace Tests\Uploads;
4
5 use BookStack\Entities\Repos\PageRepo;
6 use BookStack\Uploads\Image;
7 use BookStack\Uploads\ImageService;
8 use Illuminate\Support\Str;
9 use Tests\TestCase;
10
11 class ImageTest extends TestCase
12 {
13     public function test_image_upload()
14     {
15         $page = $this->entities->page();
16         $admin = $this->users->admin();
17         $this->actingAs($admin);
18
19         $imgDetails = $this->files->uploadGalleryImageToPage($this, $page);
20         $relPath = $imgDetails['path'];
21
22         $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath));
23
24         $this->files->deleteAtRelativePath($relPath);
25
26         $this->assertDatabaseHas('images', [
27             'url'         => $this->baseUrl . $relPath,
28             'type'        => 'gallery',
29             'uploaded_to' => $page->id,
30             'path'        => $relPath,
31             'created_by'  => $admin->id,
32             'updated_by'  => $admin->id,
33             'name'        => $imgDetails['name'],
34         ]);
35     }
36
37     public function test_image_display_thumbnail_generation_does_not_increase_image_size()
38     {
39         $page = $this->entities->page();
40         $admin = $this->users->admin();
41         $this->actingAs($admin);
42
43         $originalFile = $this->files->testFilePath('compressed.png');
44         $originalFileSize = filesize($originalFile);
45         $imgDetails = $this->files->uploadGalleryImageToPage($this, $page, 'compressed.png');
46         $relPath = $imgDetails['path'];
47
48         $this->assertTrue(file_exists(public_path($relPath)), 'Uploaded image found at path: ' . public_path($relPath));
49         $displayImage = $imgDetails['response']->thumbs->display;
50
51         $displayImageRelPath = implode('/', array_slice(explode('/', $displayImage), 3));
52         $displayImagePath = public_path($displayImageRelPath);
53         $displayFileSize = filesize($displayImagePath);
54
55         $this->files->deleteAtRelativePath($relPath);
56         $this->files->deleteAtRelativePath($displayImageRelPath);
57
58         $this->assertEquals($originalFileSize, $displayFileSize, 'Display thumbnail generation should not increase image size');
59     }
60
61     public function test_image_display_thumbnail_generation_for_apng_images_uses_original_file()
62     {
63         $page = $this->entities->page();
64         $admin = $this->users->admin();
65         $this->actingAs($admin);
66
67         $imgDetails = $this->files->uploadGalleryImageToPage($this, $page, 'animated.png');
68         $this->files->deleteAtRelativePath($imgDetails['path']);
69
70         $this->assertStringContainsString('thumbs-', $imgDetails['response']->thumbs->gallery);
71         $this->assertStringNotContainsString('thumbs-', $imgDetails['response']->thumbs->display);
72     }
73
74     public function test_image_edit()
75     {
76         $editor = $this->users->editor();
77         $this->actingAs($editor);
78
79         $imgDetails = $this->files->uploadGalleryImageToPage($this, $this->entities->page());
80         $image = Image::query()->first();
81
82         $newName = Str::random();
83         $update = $this->put('/images/' . $image->id, ['name' => $newName]);
84         $update->assertSuccessful();
85         $update->assertSee($newName);
86
87         $this->files->deleteAtRelativePath($imgDetails['path']);
88
89         $this->assertDatabaseHas('images', [
90             'type' => 'gallery',
91             'name' => $newName,
92         ]);
93     }
94
95     public function test_gallery_get_list_format()
96     {
97         $this->asEditor();
98
99         $imgDetails = $this->files->uploadGalleryImageToPage($this, $this->entities->page());
100         $image = Image::query()->first();
101
102         $pageId = $imgDetails['page']->id;
103         $firstPageRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}");
104         $firstPageRequest->assertSuccessful();
105         $this->withHtml($firstPageRequest)->assertElementExists('div');
106         $firstPageRequest->assertSuccessful()->assertSeeText($image->name);
107
108         $secondPageRequest = $this->get("/images/gallery?page=2&uploaded_to={$pageId}");
109         $secondPageRequest->assertSuccessful();
110         $this->withHtml($secondPageRequest)->assertElementNotExists('div');
111
112         $namePartial = substr($imgDetails['name'], 0, 3);
113         $searchHitRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
114         $searchHitRequest->assertSuccessful()->assertSee($imgDetails['name']);
115
116         $namePartial = Str::random(16);
117         $searchFailRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
118         $searchFailRequest->assertSuccessful()->assertDontSee($imgDetails['name']);
119         $searchFailRequest->assertSuccessful();
120         $this->withHtml($searchFailRequest)->assertElementNotExists('div');
121     }
122
123     public function test_image_usage()
124     {
125         $page = $this->entities->page();
126         $editor = $this->users->editor();
127         $this->actingAs($editor);
128
129         $imgDetails = $this->files->uploadGalleryImageToPage($this, $page);
130
131         $image = Image::query()->first();
132         $page->html = '<img src="' . $image->url . '">';
133         $page->save();
134
135         $usage = $this->get('/images/edit/' . $image->id . '?delete=true');
136         $usage->assertSuccessful();
137         $usage->assertSeeText($page->name);
138         $usage->assertSee($page->getUrl());
139
140         $this->files->deleteAtRelativePath($imgDetails['path']);
141     }
142
143     public function test_php_files_cannot_be_uploaded()
144     {
145         $page = $this->entities->page();
146         $admin = $this->users->admin();
147         $this->actingAs($admin);
148
149         $fileName = 'bad.php';
150         $relPath = $this->files->expectedImagePath('gallery', $fileName);
151         $this->files->deleteAtRelativePath($relPath);
152
153         $file = $this->files->imageFromBase64File('bad-php.base64', $fileName);
154         $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
155         $upload->assertStatus(302);
156
157         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
158
159         $this->assertDatabaseMissing('images', [
160             'type' => 'gallery',
161             'name' => $fileName,
162         ]);
163     }
164
165     public function test_php_like_files_cannot_be_uploaded()
166     {
167         $page = $this->entities->page();
168         $admin = $this->users->admin();
169         $this->actingAs($admin);
170
171         $fileName = 'bad.phtml';
172         $relPath = $this->files->expectedImagePath('gallery', $fileName);
173         $this->files->deleteAtRelativePath($relPath);
174
175         $file = $this->files->imageFromBase64File('bad-phtml.base64', $fileName);
176         $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
177         $upload->assertStatus(302);
178
179         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
180     }
181
182     public function test_files_with_double_extensions_will_get_sanitized()
183     {
184         $page = $this->entities->page();
185         $admin = $this->users->admin();
186         $this->actingAs($admin);
187
188         $fileName = 'bad.phtml.png';
189         $relPath = $this->files->expectedImagePath('gallery', $fileName);
190         $expectedRelPath = dirname($relPath) . '/bad-phtml.png';
191         $this->files->deleteAtRelativePath($expectedRelPath);
192
193         $file = $this->files->imageFromBase64File('bad-phtml-png.base64', $fileName);
194         $upload = $this->withHeader('Content-Type', 'image/png')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
195         $upload->assertStatus(200);
196
197         $lastImage = Image::query()->latest('id')->first();
198
199         $this->assertEquals('bad.phtml.png', $lastImage->name);
200         $this->assertEquals('bad-phtml.png', basename($lastImage->path));
201         $this->assertFileDoesNotExist(public_path($relPath), 'Uploaded image file name was not stripped of dots');
202         $this->assertFileExists(public_path($expectedRelPath));
203
204         $this->files->deleteAtRelativePath($lastImage->path);
205     }
206
207     public function test_url_entities_removed_from_filenames()
208     {
209         $this->asEditor();
210         $badNames = [
211             'bad-char-#-image.png',
212             'bad-char-?-image.png',
213             '?#.png',
214             '?.png',
215             '#.png',
216         ];
217         foreach ($badNames as $name) {
218             $galleryFile = $this->files->uploadedImage($name);
219             $page = $this->entities->page();
220             $badPath = $this->files->expectedImagePath('gallery', $name);
221             $this->files->deleteAtRelativePath($badPath);
222
223             $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
224             $upload->assertStatus(200);
225
226             $lastImage = Image::query()->latest('id')->first();
227             $newFileName = explode('.', basename($lastImage->path))[0];
228
229             $this->assertEquals($lastImage->name, $name);
230             $this->assertFalse(strpos($lastImage->path, $name), 'Path contains original image name');
231             $this->assertFalse(file_exists(public_path($badPath)), 'Uploaded image file name was not stripped of url entities');
232
233             $this->assertTrue(strlen($newFileName) > 0, 'File name was reduced to nothing');
234
235             $this->files->deleteAtRelativePath($lastImage->path);
236         }
237     }
238
239     public function test_secure_images_uploads_to_correct_place()
240     {
241         config()->set('filesystems.images', 'local_secure');
242         $this->asEditor();
243         $galleryFile = $this->files->uploadedImage('my-secure-test-upload.png');
244         $page = $this->entities->page();
245         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
246
247         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
248         $upload->assertStatus(200);
249
250         $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
251
252         if (file_exists($expectedPath)) {
253             unlink($expectedPath);
254         }
255     }
256
257     public function test_secure_image_paths_traversal_causes_500()
258     {
259         config()->set('filesystems.images', 'local_secure');
260         $this->asEditor();
261
262         $resp = $this->get('/uploads/images/../../logs/laravel.log');
263         $resp->assertStatus(500);
264     }
265
266     public function test_secure_image_paths_traversal_on_non_secure_images_causes_404()
267     {
268         config()->set('filesystems.images', 'local');
269         $this->asEditor();
270
271         $resp = $this->get('/uploads/images/../../logs/laravel.log');
272         $resp->assertStatus(404);
273     }
274
275     public function test_secure_image_paths_dont_serve_non_images()
276     {
277         config()->set('filesystems.images', 'local_secure');
278         $this->asEditor();
279
280         $testFilePath = storage_path('/uploads/images/testing.txt');
281         file_put_contents($testFilePath, 'hello from test_secure_image_paths_dont_serve_non_images');
282
283         $resp = $this->get('/uploads/images/testing.txt');
284         $resp->assertStatus(404);
285     }
286
287     public function test_secure_images_included_in_exports()
288     {
289         config()->set('filesystems.images', 'local_secure');
290         $this->asEditor();
291         $galleryFile = $this->files->uploadedImage('my-secure-test-upload.png');
292         $page = $this->entities->page();
293         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
294
295         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
296         $imageUrl = json_decode($upload->getContent(), true)['url'];
297         $page->html .= "<img src=\"{$imageUrl}\">";
298         $page->save();
299         $upload->assertStatus(200);
300
301         $encodedImageContent = base64_encode(file_get_contents($expectedPath));
302         $export = $this->get($page->getUrl('/export/html'));
303         $this->assertTrue(strpos($export->getContent(), $encodedImageContent) !== false, 'Uploaded image in export content');
304
305         if (file_exists($expectedPath)) {
306             unlink($expectedPath);
307         }
308     }
309
310     public function test_system_images_remain_public_with_local_secure()
311     {
312         config()->set('filesystems.images', 'local_secure');
313         $this->asAdmin();
314         $galleryFile = $this->files->uploadedImage('my-system-test-upload.png');
315         $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-upload.png');
316
317         $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []);
318         $upload->assertRedirect('/settings/customization');
319
320         $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
321
322         if (file_exists($expectedPath)) {
323             unlink($expectedPath);
324         }
325     }
326
327     public function test_system_images_remain_public_with_local_secure_restricted()
328     {
329         config()->set('filesystems.images', 'local_secure_restricted');
330         $this->asAdmin();
331         $galleryFile = $this->files->uploadedImage('my-system-test-restricted-upload.png');
332         $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-restricted-upload.png');
333
334         $upload = $this->call('POST', '/settings/customization', [], [], ['app_logo' => $galleryFile], []);
335         $upload->assertRedirect('/settings/customization');
336
337         $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
338
339         if (file_exists($expectedPath)) {
340             unlink($expectedPath);
341         }
342     }
343
344     public function test_secure_restricted_images_inaccessible_without_relation_permission()
345     {
346         config()->set('filesystems.images', 'local_secure_restricted');
347         $this->asEditor();
348         $galleryFile = $this->files->uploadedImage('my-secure-restricted-test-upload.png');
349         $page = $this->entities->page();
350
351         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
352         $upload->assertStatus(200);
353         $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
354         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
355
356         $this->get($expectedUrl)->assertOk();
357
358         $this->permissions->setEntityPermissions($page, [], []);
359
360         $resp = $this->get($expectedUrl);
361         $resp->assertNotFound();
362
363         if (file_exists($expectedPath)) {
364             unlink($expectedPath);
365         }
366     }
367
368     public function test_thumbnail_path_handled_by_secure_restricted_images()
369     {
370         config()->set('filesystems.images', 'local_secure_restricted');
371         $this->asEditor();
372         $galleryFile = $this->files->uploadedImage('my-secure-restricted-thumb-test-test.png');
373         $page = $this->entities->page();
374
375         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
376         $upload->assertStatus(200);
377         $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/thumbs-150-150/my-secure-restricted-thumb-test-test.png');
378         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-thumb-test-test.png');
379
380         $this->get($expectedUrl)->assertOk();
381
382         $this->permissions->setEntityPermissions($page, [], []);
383
384         $resp = $this->get($expectedUrl);
385         $resp->assertNotFound();
386
387         if (file_exists($expectedPath)) {
388             unlink($expectedPath);
389         }
390     }
391
392     public function test_secure_restricted_image_access_controlled_in_exports()
393     {
394         config()->set('filesystems.images', 'local_secure_restricted');
395         $this->asEditor();
396         $galleryFile = $this->files->uploadedImage('my-secure-restricted-export-test.png');
397
398         $pageA = $this->entities->page();
399         $pageB = $this->entities->page();
400         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-export-test.png');
401
402         $upload = $this->asEditor()->call('POST', '/images/gallery', ['uploaded_to' => $pageA->id], [], ['file' => $galleryFile], []);
403         $upload->assertOk();
404
405         $imageUrl = json_decode($upload->getContent(), true)['url'];
406         $pageB->html .= "<img src=\"{$imageUrl}\">";
407         $pageB->save();
408
409         $encodedImageContent = base64_encode(file_get_contents($expectedPath));
410         $export = $this->get($pageB->getUrl('/export/html'));
411         $this->assertStringContainsString($encodedImageContent, $export->getContent());
412
413         $this->permissions->setEntityPermissions($pageA, [], []);
414
415         $export = $this->get($pageB->getUrl('/export/html'));
416         $this->assertStringNotContainsString($encodedImageContent, $export->getContent());
417
418         if (file_exists($expectedPath)) {
419             unlink($expectedPath);
420         }
421     }
422
423     public function test_image_delete()
424     {
425         $page = $this->entities->page();
426         $this->asAdmin();
427         $imageName = 'first-image.png';
428         $relPath = $this->files->expectedImagePath('gallery', $imageName);
429         $this->files->deleteAtRelativePath($relPath);
430
431         $this->files->uploadGalleryImage($this, $imageName, $page->id);
432         $image = Image::first();
433
434         $delete = $this->delete('/images/' . $image->id);
435         $delete->assertStatus(200);
436
437         $this->assertDatabaseMissing('images', [
438             'url'  => $this->baseUrl . $relPath,
439             'type' => 'gallery',
440         ]);
441
442         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
443     }
444
445     public function test_image_delete_does_not_delete_similar_images()
446     {
447         $page = $this->entities->page();
448         $this->asAdmin();
449         $imageName = 'first-image.png';
450
451         $relPath = $this->files->expectedImagePath('gallery', $imageName);
452         $this->files->deleteAtRelativePath($relPath);
453
454         $this->files->uploadGalleryImage($this, $imageName, $page->id);
455         $this->files->uploadGalleryImage($this, $imageName, $page->id);
456         $this->files->uploadGalleryImage($this, $imageName, $page->id);
457
458         $image = Image::first();
459         $folder = public_path(dirname($relPath));
460         $imageCount = count(glob($folder . '/*'));
461
462         $delete = $this->delete('/images/' . $image->id);
463         $delete->assertStatus(200);
464
465         $newCount = count(glob($folder . '/*'));
466         $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted');
467         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
468     }
469
470     public function test_image_manager_delete_button_only_shows_with_permission()
471     {
472         $page = $this->entities->page();
473         $this->asAdmin();
474         $imageName = 'first-image.png';
475         $relPath = $this->files->expectedImagePath('gallery', $imageName);
476         $this->files->deleteAtRelativePath($relPath);
477         $viewer = $this->users->viewer();
478
479         $this->files->uploadGalleryImage($this, $imageName, $page->id);
480         $image = Image::first();
481
482         $resp = $this->get("/images/edit/{$image->id}");
483         $this->withHtml($resp)->assertElementExists('button#image-manager-delete[title="Delete"]');
484
485         $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}");
486         $this->withHtml($resp)->assertElementNotExists('button#image-manager-delete[title="Delete"]');
487
488         $this->permissions->grantUserRolePermissions($viewer, ['image-delete-all']);
489
490         $resp = $this->actingAs($viewer)->get("/images/edit/{$image->id}");
491         $this->withHtml($resp)->assertElementExists('button#image-manager-delete[title="Delete"]');
492
493         $this->files->deleteAtRelativePath($relPath);
494     }
495
496     protected function getTestProfileImage()
497     {
498         $imageName = 'profile.png';
499         $relPath = $this->files->expectedImagePath('user', $imageName);
500         $this->files->deleteAtRelativePath($relPath);
501
502         return $this->files->uploadedImage($imageName);
503     }
504
505     public function test_user_image_upload()
506     {
507         $editor = $this->users->editor();
508         $admin = $this->users->admin();
509         $this->actingAs($admin);
510
511         $file = $this->getTestProfileImage();
512         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
513
514         $this->assertDatabaseHas('images', [
515             'type'        => 'user',
516             'uploaded_to' => $editor->id,
517             'created_by'  => $admin->id,
518         ]);
519     }
520
521     public function test_user_images_deleted_on_user_deletion()
522     {
523         $editor = $this->users->editor();
524         $this->actingAs($editor);
525
526         $file = $this->getTestProfileImage();
527         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
528
529         $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
530         $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count');
531
532         $imagePath = public_path($profileImages->first()->path);
533         $this->assertTrue(file_exists($imagePath));
534
535         $userDelete = $this->asAdmin()->delete("/settings/users/{$editor->id}");
536         $userDelete->assertStatus(302);
537
538         $this->assertDatabaseMissing('images', [
539             'type'       => 'user',
540             'created_by' => $editor->id,
541         ]);
542         $this->assertDatabaseMissing('images', [
543             'type'        => 'user',
544             'uploaded_to' => $editor->id,
545         ]);
546
547         $this->assertFalse(file_exists($imagePath));
548     }
549
550     public function test_deleted_unused_images()
551     {
552         $page = $this->entities->page();
553         $admin = $this->users->admin();
554         $this->actingAs($admin);
555
556         $imageName = 'unused-image.png';
557         $relPath = $this->files->expectedImagePath('gallery', $imageName);
558         $this->files->deleteAtRelativePath($relPath);
559
560         $upload = $this->files->uploadGalleryImage($this, $imageName, $page->id);
561         $upload->assertStatus(200);
562         $image = Image::where('type', '=', 'gallery')->first();
563
564         $pageRepo = app(PageRepo::class);
565         $pageRepo->update($page, [
566             'name'    => $page->name,
567             'html'    => $page->html . "<img src=\"{$image->url}\">",
568             'summary' => '',
569         ]);
570
571         // Ensure no images are reported as deletable
572         $imageService = app(ImageService::class);
573         $toDelete = $imageService->deleteUnusedImages(true, true);
574         $this->assertCount(0, $toDelete);
575
576         // Save a revision of our page without the image;
577         $pageRepo->update($page, [
578             'name'    => $page->name,
579             'html'    => '<p>Hello</p>',
580             'summary' => '',
581         ]);
582
583         // Ensure revision images are picked up okay
584         $imageService = app(ImageService::class);
585         $toDelete = $imageService->deleteUnusedImages(true, true);
586         $this->assertCount(0, $toDelete);
587         $toDelete = $imageService->deleteUnusedImages(false, true);
588         $this->assertCount(1, $toDelete);
589
590         // Check image is found when revisions are destroyed
591         $page->revisions()->delete();
592         $toDelete = $imageService->deleteUnusedImages(true, true);
593         $this->assertCount(1, $toDelete);
594
595         // Check the image is deleted
596         $absPath = public_path($relPath);
597         $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
598         $toDelete = $imageService->deleteUnusedImages(true, false);
599         $this->assertCount(1, $toDelete);
600         $this->assertFalse(file_exists($absPath));
601
602         $this->files->deleteAtRelativePath($relPath);
603     }
604 }