]> BookStack Code Mirror - bookstack/blob - tests/Uploads/ImageTest.php
Updated markdown editor to use svg drawio images
[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 = Page::query()->first();
19         $admin = $this->getAdmin();
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 = Page::query()->first();
43         $admin = $this->getAdmin();
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 = Page::query()->first();
67         $admin = $this->getAdmin();
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_svg_upload()
78     {
79         /** @var Page $page */
80         $page = Page::query()->first();
81         $admin = $this->getAdmin();
82         $this->actingAs($admin);
83
84         $imgDetails = $this->uploadGalleryImage($page, 'diagram.svg', 'image/svg+xml');
85         $this->assertFileExists(public_path($imgDetails['path']));
86         $this->assertTrue(
87             $imgDetails['response']->url === $imgDetails['response']->thumbs->gallery
88             && $imgDetails['response']->url === $imgDetails['response']->thumbs->display,
89         );
90
91         $this->deleteImage($imgDetails['path']);
92     }
93
94     public function test_image_edit()
95     {
96         $editor = $this->getEditor();
97         $this->actingAs($editor);
98
99         $imgDetails = $this->uploadGalleryImage();
100         $image = Image::query()->first();
101
102         $newName = Str::random();
103         $update = $this->put('/images/' . $image->id, ['name' => $newName]);
104         $update->assertSuccessful();
105         $update->assertSee($newName);
106
107         $this->deleteImage($imgDetails['path']);
108
109         $this->assertDatabaseHas('images', [
110             'type' => 'gallery',
111             'name' => $newName,
112         ]);
113     }
114
115     public function test_gallery_get_list_format()
116     {
117         $this->asEditor();
118
119         $imgDetails = $this->uploadGalleryImage();
120         $image = Image::query()->first();
121
122         $pageId = $imgDetails['page']->id;
123         $firstPageRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}");
124         $firstPageRequest->assertSuccessful()->assertElementExists('div');
125         $firstPageRequest->assertSuccessful()->assertSeeText($image->name);
126
127         $secondPageRequest = $this->get("/images/gallery?page=2&uploaded_to={$pageId}");
128         $secondPageRequest->assertSuccessful()->assertElementNotExists('div');
129
130         $namePartial = substr($imgDetails['name'], 0, 3);
131         $searchHitRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
132         $searchHitRequest->assertSuccessful()->assertSee($imgDetails['name']);
133
134         $namePartial = Str::random(16);
135         $searchFailRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
136         $searchFailRequest->assertSuccessful()->assertDontSee($imgDetails['name']);
137         $searchFailRequest->assertSuccessful()->assertElementNotExists('div');
138     }
139
140     public function test_image_usage()
141     {
142         $page = Page::query()->first();
143         $editor = $this->getEditor();
144         $this->actingAs($editor);
145
146         $imgDetails = $this->uploadGalleryImage($page);
147
148         $image = Image::query()->first();
149         $page->html = '<img src="' . $image->url . '">';
150         $page->save();
151
152         $usage = $this->get('/images/edit/' . $image->id . '?delete=true');
153         $usage->assertSuccessful();
154         $usage->assertSeeText($page->name);
155         $usage->assertSee($page->getUrl());
156
157         $this->deleteImage($imgDetails['path']);
158     }
159
160     public function test_php_files_cannot_be_uploaded()
161     {
162         $page = Page::query()->first();
163         $admin = $this->getAdmin();
164         $this->actingAs($admin);
165
166         $fileName = 'bad.php';
167         $relPath = $this->getTestImagePath('gallery', $fileName);
168         $this->deleteImage($relPath);
169
170         $file = $this->newTestImageFromBase64('bad-php.base64', $fileName);
171         $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
172         $upload->assertStatus(302);
173
174         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
175
176         $this->assertDatabaseMissing('images', [
177             'type' => 'gallery',
178             'name' => $fileName,
179         ]);
180     }
181
182     public function test_php_like_files_cannot_be_uploaded()
183     {
184         $page = Page::query()->first();
185         $admin = $this->getAdmin();
186         $this->actingAs($admin);
187
188         $fileName = 'bad.phtml';
189         $relPath = $this->getTestImagePath('gallery', $fileName);
190         $this->deleteImage($relPath);
191
192         $file = $this->newTestImageFromBase64('bad-phtml.base64', $fileName);
193         $upload = $this->withHeader('Content-Type', 'image/jpeg')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
194         $upload->assertStatus(302);
195
196         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded php file was uploaded but should have been stopped');
197     }
198
199     public function test_files_with_double_extensions_will_get_sanitized()
200     {
201         $page = Page::query()->first();
202         $admin = $this->getAdmin();
203         $this->actingAs($admin);
204
205         $fileName = 'bad.phtml.png';
206         $relPath = $this->getTestImagePath('gallery', $fileName);
207         $expectedRelPath = dirname($relPath) . '/bad-phtml.png';
208         $this->deleteImage($expectedRelPath);
209
210         $file = $this->newTestImageFromBase64('bad-phtml-png.base64', $fileName);
211         $upload = $this->withHeader('Content-Type', 'image/png')->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $file], []);
212         $upload->assertStatus(200);
213
214         $lastImage = Image::query()->latest('id')->first();
215
216         $this->assertEquals('bad.phtml.png', $lastImage->name);
217         $this->assertEquals('bad-phtml.png', basename($lastImage->path));
218         $this->assertFileDoesNotExist(public_path($relPath), 'Uploaded image file name was not stripped of dots');
219         $this->assertFileExists(public_path($expectedRelPath));
220
221         $this->deleteImage($lastImage->path);
222     }
223
224     public function test_url_entities_removed_from_filenames()
225     {
226         $this->asEditor();
227         $badNames = [
228             'bad-char-#-image.png',
229             'bad-char-?-image.png',
230             '?#.png',
231             '?.png',
232             '#.png',
233         ];
234         foreach ($badNames as $name) {
235             $galleryFile = $this->getTestImage($name);
236             $page = Page::query()->first();
237             $badPath = $this->getTestImagePath('gallery', $name);
238             $this->deleteImage($badPath);
239
240             $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
241             $upload->assertStatus(200);
242
243             $lastImage = Image::query()->latest('id')->first();
244             $newFileName = explode('.', basename($lastImage->path))[0];
245
246             $this->assertEquals($lastImage->name, $name);
247             $this->assertFalse(strpos($lastImage->path, $name), 'Path contains original image name');
248             $this->assertFalse(file_exists(public_path($badPath)), 'Uploaded image file name was not stripped of url entities');
249
250             $this->assertTrue(strlen($newFileName) > 0, 'File name was reduced to nothing');
251
252             $this->deleteImage($lastImage->path);
253         }
254     }
255
256     public function test_secure_images_uploads_to_correct_place()
257     {
258         config()->set('filesystems.images', 'local_secure');
259         $this->asEditor();
260         $galleryFile = $this->getTestImage('my-secure-test-upload.png');
261         $page = Page::query()->first();
262         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
263
264         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
265         $upload->assertStatus(200);
266
267         $this->assertTrue(file_exists($expectedPath), 'Uploaded image not found at path: ' . $expectedPath);
268
269         if (file_exists($expectedPath)) {
270             unlink($expectedPath);
271         }
272     }
273
274     public function test_secure_image_paths_traversal_causes_500()
275     {
276         config()->set('filesystems.images', 'local_secure');
277         $this->asEditor();
278
279         $resp = $this->get('/uploads/images/../../logs/laravel.log');
280         $resp->assertStatus(500);
281     }
282
283     public function test_secure_image_paths_traversal_on_non_secure_images_causes_404()
284     {
285         config()->set('filesystems.images', 'local');
286         $this->asEditor();
287
288         $resp = $this->get('/uploads/images/../../logs/laravel.log');
289         $resp->assertStatus(404);
290     }
291
292     public function test_secure_image_paths_dont_serve_non_images()
293     {
294         config()->set('filesystems.images', 'local_secure');
295         $this->asEditor();
296
297         $testFilePath = storage_path('/uploads/images/testing.txt');
298         file_put_contents($testFilePath, 'hello from test_secure_image_paths_dont_serve_non_images');
299
300         $resp = $this->get('/uploads/images/testing.txt');
301         $resp->assertStatus(404);
302     }
303
304     public function test_secure_images_included_in_exports()
305     {
306         config()->set('filesystems.images', 'local_secure');
307         $this->asEditor();
308         $galleryFile = $this->getTestImage('my-secure-test-upload.png');
309         $page = Page::query()->first();
310         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-test-upload.png');
311
312         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
313         $imageUrl = json_decode($upload->getContent(), true)['url'];
314         $page->html .= "<img src=\"{$imageUrl}\">";
315         $page->save();
316         $upload->assertStatus(200);
317
318         $encodedImageContent = base64_encode(file_get_contents($expectedPath));
319         $export = $this->get($page->getUrl('/export/html'));
320         $this->assertTrue(strpos($export->getContent(), $encodedImageContent) !== false, 'Uploaded image in export content');
321
322         if (file_exists($expectedPath)) {
323             unlink($expectedPath);
324         }
325     }
326
327     public function test_system_images_remain_public()
328     {
329         config()->set('filesystems.images', 'local_secure');
330         $this->asAdmin();
331         $galleryFile = $this->getTestImage('my-system-test-upload.png');
332         $expectedPath = public_path('uploads/images/system/' . date('Y-m') . '/my-system-test-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_image_delete()
345     {
346         $page = Page::query()->first();
347         $this->asAdmin();
348         $imageName = 'first-image.png';
349         $relPath = $this->getTestImagePath('gallery', $imageName);
350         $this->deleteImage($relPath);
351
352         $this->uploadImage($imageName, $page->id);
353         $image = Image::first();
354
355         $delete = $this->delete('/images/' . $image->id);
356         $delete->assertStatus(200);
357
358         $this->assertDatabaseMissing('images', [
359             'url'  => $this->baseUrl . $relPath,
360             'type' => 'gallery',
361         ]);
362
363         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
364     }
365
366     public function test_image_delete_does_not_delete_similar_images()
367     {
368         $page = Page::query()->first();
369         $this->asAdmin();
370         $imageName = 'first-image.png';
371
372         $relPath = $this->getTestImagePath('gallery', $imageName);
373         $this->deleteImage($relPath);
374
375         $this->uploadImage($imageName, $page->id);
376         $this->uploadImage($imageName, $page->id);
377         $this->uploadImage($imageName, $page->id);
378
379         $image = Image::first();
380         $folder = public_path(dirname($relPath));
381         $imageCount = count(glob($folder . '/*'));
382
383         $delete = $this->delete('/images/' . $image->id);
384         $delete->assertStatus(200);
385
386         $newCount = count(glob($folder . '/*'));
387         $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted');
388         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
389     }
390
391     protected function getTestProfileImage()
392     {
393         $imageName = 'profile.png';
394         $relPath = $this->getTestImagePath('user', $imageName);
395         $this->deleteImage($relPath);
396
397         return $this->getTestImage($imageName);
398     }
399
400     public function test_user_image_upload()
401     {
402         $editor = $this->getEditor();
403         $admin = $this->getAdmin();
404         $this->actingAs($admin);
405
406         $file = $this->getTestProfileImage();
407         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
408
409         $this->assertDatabaseHas('images', [
410             'type'        => 'user',
411             'uploaded_to' => $editor->id,
412             'created_by'  => $admin->id,
413         ]);
414     }
415
416     public function test_user_images_deleted_on_user_deletion()
417     {
418         $editor = $this->getEditor();
419         $this->actingAs($editor);
420
421         $file = $this->getTestProfileImage();
422         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
423
424         $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
425         $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count');
426
427         $imagePath = public_path($profileImages->first()->path);
428         $this->assertTrue(file_exists($imagePath));
429
430         $userDelete = $this->asAdmin()->delete("/settings/users/{$editor->id}");
431         $userDelete->assertStatus(302);
432
433         $this->assertDatabaseMissing('images', [
434             'type'       => 'user',
435             'created_by' => $editor->id,
436         ]);
437         $this->assertDatabaseMissing('images', [
438             'type'        => 'user',
439             'uploaded_to' => $editor->id,
440         ]);
441
442         $this->assertFalse(file_exists($imagePath));
443     }
444
445     public function test_deleted_unused_images()
446     {
447         $page = Page::query()->first();
448         $admin = $this->getAdmin();
449         $this->actingAs($admin);
450
451         $imageName = 'unused-image.png';
452         $relPath = $this->getTestImagePath('gallery', $imageName);
453         $this->deleteImage($relPath);
454
455         $upload = $this->uploadImage($imageName, $page->id);
456         $upload->assertStatus(200);
457         $image = Image::where('type', '=', 'gallery')->first();
458
459         $pageRepo = app(PageRepo::class);
460         $pageRepo->update($page, [
461             'name'    => $page->name,
462             'html'    => $page->html . "<img src=\"{$image->url}\">",
463             'summary' => '',
464         ]);
465
466         // Ensure no images are reported as deletable
467         $imageService = app(ImageService::class);
468         $toDelete = $imageService->deleteUnusedImages(true, true);
469         $this->assertCount(0, $toDelete);
470
471         // Save a revision of our page without the image;
472         $pageRepo->update($page, [
473             'name'    => $page->name,
474             'html'    => '<p>Hello</p>',
475             'summary' => '',
476         ]);
477
478         // Ensure revision images are picked up okay
479         $imageService = app(ImageService::class);
480         $toDelete = $imageService->deleteUnusedImages(true, true);
481         $this->assertCount(0, $toDelete);
482         $toDelete = $imageService->deleteUnusedImages(false, true);
483         $this->assertCount(1, $toDelete);
484
485         // Check image is found when revisions are destroyed
486         $page->revisions()->delete();
487         $toDelete = $imageService->deleteUnusedImages(true, true);
488         $this->assertCount(1, $toDelete);
489
490         // Check the image is deleted
491         $absPath = public_path($relPath);
492         $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
493         $toDelete = $imageService->deleteUnusedImages(true, false);
494         $this->assertCount(1, $toDelete);
495         $this->assertFalse(file_exists($absPath));
496
497         $this->deleteImage($relPath);
498     }
499 }