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