]> BookStack Code Mirror - bookstack/blob - tests/Uploads/ImageTest.php
2a3023a9eafe470418d3354aaed614d506002afd
[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();
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 = Page::query()->first();
129         $editor = $this->getEditor();
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 = Page::query()->first();
149         $admin = $this->getAdmin();
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 = Page::query()->first();
171         $admin = $this->getAdmin();
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 = Page::query()->first();
188         $admin = $this->getAdmin();
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 = Page::query()->first();
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 = Page::query()->first();
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 = Page::query()->first();
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()
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_secure_restricted_images_inaccessible_without_relation_permission()
331     {
332         config()->set('filesystems.images', 'local_secure_restricted');
333         $this->asEditor();
334         $galleryFile = $this->getTestImage('my-secure-restricted-test-upload.png');
335         /** @var Page $page */
336         $page = Page::query()->first();
337
338         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
339         $upload->assertStatus(200);
340         $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
341         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-test-upload.png');
342
343         $this->get($expectedUrl)->assertOk();
344
345         $this->setEntityRestrictions($page, [], []);
346
347         $resp = $this->get($expectedUrl);
348         $resp->assertNotFound();
349
350         if (file_exists($expectedPath)) {
351             unlink($expectedPath);
352         }
353     }
354
355     public function test_thumbnail_path_handled_by_secure_restricted_images()
356     {
357         config()->set('filesystems.images', 'local_secure_restricted');
358         $this->asEditor();
359         $galleryFile = $this->getTestImage('my-secure-restricted-thumb-test-test.png');
360         /** @var Page $page */
361         $page = Page::query()->first();
362
363         $upload = $this->call('POST', '/images/gallery', ['uploaded_to' => $page->id], [], ['file' => $galleryFile], []);
364         $upload->assertStatus(200);
365         $expectedUrl = url('uploads/images/gallery/' . date('Y-m') . '/thumbs-150-150/my-secure-restricted-thumb-test-test.png');
366         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-thumb-test-test.png');
367
368         $this->get($expectedUrl)->assertOk();
369
370         $this->setEntityRestrictions($page, [], []);
371
372         $resp = $this->get($expectedUrl);
373         $resp->assertNotFound();
374
375         if (file_exists($expectedPath)) {
376             unlink($expectedPath);
377         }
378     }
379
380     public function test_secure_restricted_image_access_controlled_in_exports()
381     {
382         config()->set('filesystems.images', 'local_secure_restricted');
383         $this->asEditor();
384         $galleryFile = $this->getTestImage('my-secure-restricted-export-test.png');
385
386         /** @var Page $pageA */
387         /** @var Page $pageB */
388         $pageA = Page::query()->first();
389         $pageB = Page::query()->where('id', '!=', $pageA->id)->first();
390         $expectedPath = storage_path('uploads/images/gallery/' . date('Y-m') . '/my-secure-restricted-export-test.png');
391
392         $upload = $this->asEditor()->call('POST', '/images/gallery', ['uploaded_to' => $pageA->id], [], ['file' => $galleryFile], []);
393         $upload->assertOk();
394
395         $imageUrl = json_decode($upload->getContent(), true)['url'];
396         $pageB->html .= "<img src=\"{$imageUrl}\">";
397         $pageB->save();
398
399         $encodedImageContent = base64_encode(file_get_contents($expectedPath));
400         $export = $this->get($pageB->getUrl('/export/html'));
401         $this->assertStringContainsString($encodedImageContent, $export->getContent());
402
403         $this->setEntityRestrictions($pageA, [], []);
404
405         $export = $this->get($pageB->getUrl('/export/html'));
406         $this->assertStringNotContainsString($encodedImageContent, $export->getContent());
407
408         if (file_exists($expectedPath)) {
409             unlink($expectedPath);
410         }
411     }
412
413     public function test_image_delete()
414     {
415         $page = Page::query()->first();
416         $this->asAdmin();
417         $imageName = 'first-image.png';
418         $relPath = $this->getTestImagePath('gallery', $imageName);
419         $this->deleteImage($relPath);
420
421         $this->uploadImage($imageName, $page->id);
422         $image = Image::first();
423
424         $delete = $this->delete('/images/' . $image->id);
425         $delete->assertStatus(200);
426
427         $this->assertDatabaseMissing('images', [
428             'url'  => $this->baseUrl . $relPath,
429             'type' => 'gallery',
430         ]);
431
432         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
433     }
434
435     public function test_image_delete_does_not_delete_similar_images()
436     {
437         $page = Page::query()->first();
438         $this->asAdmin();
439         $imageName = 'first-image.png';
440
441         $relPath = $this->getTestImagePath('gallery', $imageName);
442         $this->deleteImage($relPath);
443
444         $this->uploadImage($imageName, $page->id);
445         $this->uploadImage($imageName, $page->id);
446         $this->uploadImage($imageName, $page->id);
447
448         $image = Image::first();
449         $folder = public_path(dirname($relPath));
450         $imageCount = count(glob($folder . '/*'));
451
452         $delete = $this->delete('/images/' . $image->id);
453         $delete->assertStatus(200);
454
455         $newCount = count(glob($folder . '/*'));
456         $this->assertEquals($imageCount - 1, $newCount, 'More files than expected have been deleted');
457         $this->assertFalse(file_exists(public_path($relPath)), 'Uploaded image has not been deleted as expected');
458     }
459
460     protected function getTestProfileImage()
461     {
462         $imageName = 'profile.png';
463         $relPath = $this->getTestImagePath('user', $imageName);
464         $this->deleteImage($relPath);
465
466         return $this->getTestImage($imageName);
467     }
468
469     public function test_user_image_upload()
470     {
471         $editor = $this->getEditor();
472         $admin = $this->getAdmin();
473         $this->actingAs($admin);
474
475         $file = $this->getTestProfileImage();
476         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
477
478         $this->assertDatabaseHas('images', [
479             'type'        => 'user',
480             'uploaded_to' => $editor->id,
481             'created_by'  => $admin->id,
482         ]);
483     }
484
485     public function test_user_images_deleted_on_user_deletion()
486     {
487         $editor = $this->getEditor();
488         $this->actingAs($editor);
489
490         $file = $this->getTestProfileImage();
491         $this->call('PUT', '/settings/users/' . $editor->id, [], [], ['profile_image' => $file], []);
492
493         $profileImages = Image::where('type', '=', 'user')->where('created_by', '=', $editor->id)->get();
494         $this->assertTrue($profileImages->count() === 1, 'Found profile images does not match upload count');
495
496         $imagePath = public_path($profileImages->first()->path);
497         $this->assertTrue(file_exists($imagePath));
498
499         $userDelete = $this->asAdmin()->delete("/settings/users/{$editor->id}");
500         $userDelete->assertStatus(302);
501
502         $this->assertDatabaseMissing('images', [
503             'type'       => 'user',
504             'created_by' => $editor->id,
505         ]);
506         $this->assertDatabaseMissing('images', [
507             'type'        => 'user',
508             'uploaded_to' => $editor->id,
509         ]);
510
511         $this->assertFalse(file_exists($imagePath));
512     }
513
514     public function test_deleted_unused_images()
515     {
516         $page = Page::query()->first();
517         $admin = $this->getAdmin();
518         $this->actingAs($admin);
519
520         $imageName = 'unused-image.png';
521         $relPath = $this->getTestImagePath('gallery', $imageName);
522         $this->deleteImage($relPath);
523
524         $upload = $this->uploadImage($imageName, $page->id);
525         $upload->assertStatus(200);
526         $image = Image::where('type', '=', 'gallery')->first();
527
528         $pageRepo = app(PageRepo::class);
529         $pageRepo->update($page, [
530             'name'    => $page->name,
531             'html'    => $page->html . "<img src=\"{$image->url}\">",
532             'summary' => '',
533         ]);
534
535         // Ensure no images are reported as deletable
536         $imageService = app(ImageService::class);
537         $toDelete = $imageService->deleteUnusedImages(true, true);
538         $this->assertCount(0, $toDelete);
539
540         // Save a revision of our page without the image;
541         $pageRepo->update($page, [
542             'name'    => $page->name,
543             'html'    => '<p>Hello</p>',
544             'summary' => '',
545         ]);
546
547         // Ensure revision images are picked up okay
548         $imageService = app(ImageService::class);
549         $toDelete = $imageService->deleteUnusedImages(true, true);
550         $this->assertCount(0, $toDelete);
551         $toDelete = $imageService->deleteUnusedImages(false, true);
552         $this->assertCount(1, $toDelete);
553
554         // Check image is found when revisions are destroyed
555         $page->revisions()->delete();
556         $toDelete = $imageService->deleteUnusedImages(true, true);
557         $this->assertCount(1, $toDelete);
558
559         // Check the image is deleted
560         $absPath = public_path($relPath);
561         $this->assertTrue(file_exists($absPath), "Existing uploaded file at path {$absPath} exists");
562         $toDelete = $imageService->deleteUnusedImages(true, false);
563         $this->assertCount(1, $toDelete);
564         $this->assertFalse(file_exists($absPath));
565
566         $this->deleteImage($relPath);
567     }
568 }