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