]> BookStack Code Mirror - bookstack/blob - tests/Uploads/ImageTest.php
Split out settings view and made functional
[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_image_edit()
78     {
79         $editor = $this->getEditor();
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()->assertElementExists('div');
108         $firstPageRequest->assertSuccessful()->assertSeeText($image->name);
109
110         $secondPageRequest = $this->get("/images/gallery?page=2&uploaded_to={$pageId}");
111         $secondPageRequest->assertSuccessful()->assertElementNotExists('div');
112
113         $namePartial = substr($imgDetails['name'], 0, 3);
114         $searchHitRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
115         $searchHitRequest->assertSuccessful()->assertSee($imgDetails['name']);
116
117         $namePartial = Str::random(16);
118         $searchFailRequest = $this->get("/images/gallery?page=1&uploaded_to={$pageId}&search={$namePartial}");
119         $searchFailRequest->assertSuccessful()->assertDontSee($imgDetails['name']);
120         $searchFailRequest->assertSuccessful()->assertElementNotExists('div');
121     }
122
123     public function test_image_usage()
124     {
125         $page = Page::query()->first();
126         $editor = $this->getEditor();
127         $this->actingAs($editor);
128
129         $imgDetails = $this->uploadGalleryImage($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->deleteImage($imgDetails['path']);
141     }
142
143     public function test_php_files_cannot_be_uploaded()
144     {
145         $page = Page::query()->first();
146         $admin = $this->getAdmin();
147         $this->actingAs($admin);
148
149         $fileName = 'bad.php';
150         $relPath = $this->getTestImagePath('gallery', $fileName);
151         $this->deleteImage($relPath);
152
153         $file = $this->newTestImageFromBase64('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 = Page::query()->first();
168         $admin = $this->getAdmin();
169         $this->actingAs($admin);
170
171         $fileName = 'bad.phtml';
172         $relPath = $this->getTestImagePath('gallery', $fileName);
173         $this->deleteImage($relPath);
174
175         $file = $this->newTestImageFromBase64('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 = Page::query()->first();
185         $admin = $this->getAdmin();
186         $this->actingAs($admin);
187
188         $fileName = 'bad.phtml.png';
189         $relPath = $this->getTestImagePath('gallery', $fileName);
190         $expectedRelPath = dirname($relPath) . '/bad-phtml.png';
191         $this->deleteImage($expectedRelPath);
192
193         $file = $this->newTestImageFromBase64('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->deleteImage($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->getTestImage($name);
219             $page = Page::query()->first();
220             $badPath = $this->getTestImagePath('gallery', $name);
221             $this->deleteImage($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->deleteImage($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->getTestImage('my-secure-test-upload.png');
244         $page = Page::query()->first();
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->getTestImage('my-secure-test-upload.png');
292         $page = Page::query()->first();
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()
311     {
312         config()->set('filesystems.images', 'local_secure');
313         $this->asAdmin();
314         $galleryFile = $this->getTestImage('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_image_delete()
328     {
329         $page = Page::query()->first();
330         $this->asAdmin();
331         $imageName = 'first-image.png';
332         $relPath = $this->getTestImagePath('gallery', $imageName);
333         $this->deleteImage($relPath);
334
335         $this->uploadImage($imageName, $page->id);
336         $image = Image::first();
337
338         $delete = $this->delete('/images/' . $image->id);
339         $delete->assertStatus(200);
340
341         $this->assertDatabaseMissing('images', [
342             'url'  => $this->baseUrl . $relPath,
343             'type' => 'gallery',
344         ]);
345
346         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
347     }
348
349     public function test_image_delete_does_not_delete_similar_images()
350     {
351         $page = Page::query()->first();
352         $this->asAdmin();
353         $imageName = 'first-image.png';
354
355         $relPath = $this->getTestImagePath('gallery', $imageName);
356         $this->deleteImage($relPath);
357
358         $this->uploadImage($imageName, $page->id);
359         $this->uploadImage($imageName, $page->id);
360         $this->uploadImage($imageName, $page->id);
361
362         $image = Image::first();
363         $folder = public_path(dirname($relPath));
364         $imageCount = count(glob($folder . '/*'));
365
366         $delete = $this->delete('/images/' . $image->id);
367         $delete->assertStatus(200);
368
369         $newCount = count(glob($folder . '/*'));
370         $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted');
371         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
372     }
373
374     protected function getTestProfileImage()
375     {
376         $imageName = 'profile.png';
377         $relPath = $this->getTestImagePath('user', $imageName);
378         $this->deleteImage($relPath);
379
380         return $this->getTestImage($imageName);
381     }
382
383     public function test_user_image_upload()
384     {
385         $editor = $this->getEditor();
386         $admin = $this->getAdmin();
387         $this->actingAs($admin);
388
389         $file = $this->getTestProfileImage();
390         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
391
392         $this->assertDatabaseHas('images', [
393             'type'        => 'user',
394             'uploaded_to' => $editor->id,
395             'created_by'  => $admin->id,
396         ]);
397     }
398
399     public function test_user_images_deleted_on_user_deletion()
400     {
401         $editor = $this->getEditor();
402         $this->actingAs($editor);
403
404         $file = $this->getTestProfileImage();
405         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
406
407         $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
408         $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count');
409
410         $imagePath = public_path($profileImages->first()->path);
411         $this->assertTrue(file_exists($imagePath));
412
413         $userDelete = $this->asAdmin()->delete("/settings/users/{$editor->id}");
414         $userDelete->assertStatus(302);
415
416         $this->assertDatabaseMissing('images', [
417             'type'       => 'user',
418             'created_by' => $editor->id,
419         ]);
420         $this->assertDatabaseMissing('images', [
421             'type'        => 'user',
422             'uploaded_to' => $editor->id,
423         ]);
424
425         $this->assertFalse(file_exists($imagePath));
426     }
427
428     public function test_deleted_unused_images()
429     {
430         $page = Page::query()->first();
431         $admin = $this->getAdmin();
432         $this->actingAs($admin);
433
434         $imageName = 'unused-image.png';
435         $relPath = $this->getTestImagePath('gallery', $imageName);
436         $this->deleteImage($relPath);
437
438         $upload = $this->uploadImage($imageName, $page->id);
439         $upload->assertStatus(200);
440         $image = Image::where('type', '=', 'gallery')->first();
441
442         $pageRepo = app(PageRepo::class);
443         $pageRepo->update($page, [
444             'name'    => $page->name,
445             'html'    => $page->html . "<img src=\"{$image->url}\">",
446             'summary' => '',
447         ]);
448
449         // Ensure no images are reported as deletable
450         $imageService = app(ImageService::class);
451         $toDelete = $imageService->deleteUnusedImages(true, true);
452         $this->assertCount(0, $toDelete);
453
454         // Save a revision of our page without the image;
455         $pageRepo->update($page, [
456             'name'    => $page->name,
457             'html'    => '<p>Hello</p>',
458             'summary' => '',
459         ]);
460
461         // Ensure revision images are picked up okay
462         $imageService = app(ImageService::class);
463         $toDelete = $imageService->deleteUnusedImages(true, true);
464         $this->assertCount(0, $toDelete);
465         $toDelete = $imageService->deleteUnusedImages(false, true);
466         $this->assertCount(1, $toDelete);
467
468         // Check image is found when revisions are destroyed
469         $page->revisions()->delete();
470         $toDelete = $imageService->deleteUnusedImages(true, true);
471         $this->assertCount(1, $toDelete);
472
473         // Check the image is deleted
474         $absPath = public_path($relPath);
475         $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
476         $toDelete = $imageService->deleteUnusedImages(true, false);
477         $this->assertCount(1, $toDelete);
478         $this->assertFalse(file_exists($absPath));
479
480         $this->deleteImage($relPath);
481     }
482 }