]> BookStack Code Mirror - bookstack/blob - tests/Uploads/AttachmentTest.php
b6fcb8f69995d3767d5dc1a8f3f140b5f469d66a
[bookstack] / tests / Uploads / AttachmentTest.php
1 <?php
2
3 namespace Tests\Uploads;
4
5 use BookStack\Entities\Models\Page;
6 use BookStack\Entities\Repos\PageRepo;
7 use BookStack\Entities\Tools\TrashCan;
8 use BookStack\Uploads\Attachment;
9 use BookStack\Uploads\AttachmentService;
10 use Illuminate\Http\UploadedFile;
11 use Tests\TestCase;
12
13 class AttachmentTest extends TestCase
14 {
15     /**
16      * Get a test file that can be uploaded.
17      */
18     protected function getTestFile(string $fileName): UploadedFile
19     {
20         return new UploadedFile(base_path('tests/test-data/test-file.txt'), $fileName, 'text/plain', null, true);
21     }
22
23     /**
24      * Uploads a file with the given name.
25      */
26     protected function uploadFile(string $name, int $uploadedTo = 0): \Illuminate\Testing\TestResponse
27     {
28         $file = $this->getTestFile($name);
29
30         return $this->call('POST', '/attachments/upload', ['uploaded_to' => $uploadedTo], [], ['file' => $file], []);
31     }
32
33     /**
34      * Create a new attachment.
35      */
36     protected function createAttachment(Page $page): Attachment
37     {
38         $this->post('attachments/link', [
39             'attachment_link_url'         => 'https://example.com',
40             'attachment_link_name'        => 'Example Attachment Link',
41             'attachment_link_uploaded_to' => $page->id,
42         ]);
43
44         return Attachment::query()->latest()->first();
45     }
46
47     /**
48      * Create a new upload attachment from the given data.
49      */
50     protected function createUploadAttachment(Page $page, string $filename, string $content, string $mimeType): Attachment
51     {
52         $file = tmpfile();
53         $filePath = stream_get_meta_data($file)['uri'];
54         file_put_contents($filePath, $content);
55         $upload = new UploadedFile($filePath, $filename, $mimeType, null, true);
56
57         $this->call('POST', '/attachments/upload', ['uploaded_to' => $page->id], [], ['file' => $upload], []);
58
59         return $page->attachments()->latest()->firstOrFail();
60     }
61
62     /**
63      * Delete all uploaded files.
64      * To assist with cleanup.
65      */
66     protected function deleteUploads()
67     {
68         $fileService = $this->app->make(AttachmentService::class);
69         foreach (Attachment::all() as $file) {
70             $fileService->deleteFile($file);
71         }
72     }
73
74     public function test_file_upload()
75     {
76         $page = $this->entities->page();
77         $this->asAdmin();
78         $admin = $this->getAdmin();
79         $fileName = 'upload_test_file.txt';
80
81         $expectedResp = [
82             'name'       => $fileName,
83             'uploaded_to' => $page->id,
84             'extension'  => 'txt',
85             'order'      => 1,
86             'created_by' => $admin->id,
87             'updated_by' => $admin->id,
88         ];
89
90         $upload = $this->uploadFile($fileName, $page->id);
91         $upload->assertStatus(200);
92
93         $attachment = Attachment::query()->orderBy('id', 'desc')->first();
94         $upload->assertJson($expectedResp);
95
96         $expectedResp['path'] = $attachment->path;
97         $this->assertDatabaseHas('attachments', $expectedResp);
98
99         $this->deleteUploads();
100     }
101
102     public function test_file_upload_does_not_use_filename()
103     {
104         $page = $this->entities->page();
105         $fileName = 'upload_test_file.txt';
106
107         $upload = $this->asAdmin()->uploadFile($fileName, $page->id);
108         $upload->assertStatus(200);
109
110         $attachment = Attachment::query()->orderBy('id', 'desc')->first();
111         $this->assertStringNotContainsString($fileName, $attachment->path);
112         $this->assertStringEndsWith('-txt', $attachment->path);
113         $this->deleteUploads();
114     }
115
116     public function test_file_display_and_access()
117     {
118         $page = $this->entities->page();
119         $this->asAdmin();
120         $fileName = 'upload_test_file.txt';
121
122         $upload = $this->uploadFile($fileName, $page->id);
123         $upload->assertStatus(200);
124         $attachment = Attachment::orderBy('id', 'desc')->take(1)->first();
125
126         $pageGet = $this->get($page->getUrl());
127         $pageGet->assertSeeText($fileName);
128         $pageGet->assertSee($attachment->getUrl());
129
130         $attachmentGet = $this->get($attachment->getUrl());
131         $content = $attachmentGet->streamedContent();
132         $this->assertStringContainsString('Hi, This is a test file for testing the upload process.', $content);
133
134         $this->deleteUploads();
135     }
136
137     public function test_attaching_link_to_page()
138     {
139         $page = $this->entities->page();
140         $admin = $this->getAdmin();
141         $this->asAdmin();
142
143         $linkReq = $this->call('POST', 'attachments/link', [
144             'attachment_link_url'         => 'https://example.com',
145             'attachment_link_name'        => 'Example Attachment Link',
146             'attachment_link_uploaded_to' => $page->id,
147         ]);
148
149         $expectedData = [
150             'path'        => 'https://example.com',
151             'name'        => 'Example Attachment Link',
152             'uploaded_to' => $page->id,
153             'created_by'  => $admin->id,
154             'updated_by'  => $admin->id,
155             'external'    => true,
156             'order'       => 1,
157             'extension'   => '',
158         ];
159
160         $linkReq->assertStatus(200);
161         $this->assertDatabaseHas('attachments', $expectedData);
162         $attachment = Attachment::orderBy('id', 'desc')->take(1)->first();
163
164         $pageGet = $this->get($page->getUrl());
165         $pageGet->assertSeeText('Example Attachment Link');
166         $pageGet->assertSee($attachment->getUrl());
167
168         $attachmentGet = $this->get($attachment->getUrl());
169         $attachmentGet->assertRedirect('https://example.com');
170
171         $this->deleteUploads();
172     }
173
174     public function test_attachment_updating()
175     {
176         $page = $this->entities->page();
177         $this->asAdmin();
178
179         $attachment = $this->createAttachment($page);
180         $update = $this->call('PUT', 'attachments/' . $attachment->id, [
181             'attachment_edit_name' => 'My new attachment name',
182             'attachment_edit_url'  => 'https://test.example.com',
183         ]);
184
185         $expectedData = [
186             'id'          => $attachment->id,
187             'path'        => 'https://test.example.com',
188             'name'        => 'My new attachment name',
189             'uploaded_to' => $page->id,
190         ];
191
192         $update->assertStatus(200);
193         $this->assertDatabaseHas('attachments', $expectedData);
194
195         $this->deleteUploads();
196     }
197
198     public function test_file_deletion()
199     {
200         $page = $this->entities->page();
201         $this->asAdmin();
202         $fileName = 'deletion_test.txt';
203         $this->uploadFile($fileName, $page->id);
204
205         $attachment = Attachment::query()->orderBy('id', 'desc')->first();
206         $filePath = storage_path($attachment->path);
207         $this->assertTrue(file_exists($filePath), 'File at path ' . $filePath . ' does not exist');
208
209         $attachment = Attachment::first();
210         $this->delete($attachment->getUrl());
211
212         $this->assertDatabaseMissing('attachments', [
213             'name' => $fileName,
214         ]);
215         $this->assertFalse(file_exists($filePath), 'File at path ' . $filePath . ' was not deleted as expected');
216
217         $this->deleteUploads();
218     }
219
220     public function test_attachment_deletion_on_page_deletion()
221     {
222         $page = $this->entities->page();
223         $this->asAdmin();
224         $fileName = 'deletion_test.txt';
225         $this->uploadFile($fileName, $page->id);
226
227         $attachment = Attachment::query()->orderBy('id', 'desc')->first();
228         $filePath = storage_path($attachment->path);
229
230         $this->assertTrue(file_exists($filePath), 'File at path ' . $filePath . ' does not exist');
231         $this->assertDatabaseHas('attachments', [
232             'name' => $fileName,
233         ]);
234
235         app(PageRepo::class)->destroy($page);
236         app(TrashCan::class)->empty();
237
238         $this->assertDatabaseMissing('attachments', [
239             'name' => $fileName,
240         ]);
241         $this->assertFalse(file_exists($filePath), 'File at path ' . $filePath . ' was not deleted as expected');
242
243         $this->deleteUploads();
244     }
245
246     public function test_attachment_access_without_permission_shows_404()
247     {
248         $admin = $this->getAdmin();
249         $viewer = $this->getViewer();
250         $page = $this->entities->page(); /** @var Page $page */
251         $this->actingAs($admin);
252         $fileName = 'permission_test.txt';
253         $this->uploadFile($fileName, $page->id);
254         $attachment = Attachment::orderBy('id', 'desc')->take(1)->first();
255
256         $this->entities->setPermissions($page, [], []);
257
258         $this->actingAs($viewer);
259         $attachmentGet = $this->get($attachment->getUrl());
260         $attachmentGet->assertStatus(404);
261         $attachmentGet->assertSee('Attachment not found');
262
263         $this->deleteUploads();
264     }
265
266     public function test_data_and_js_links_cannot_be_attached_to_a_page()
267     {
268         $page = $this->entities->page();
269         $this->asAdmin();
270
271         $badLinks = [
272             'javascript:alert("bunny")',
273             ' javascript:alert("bunny")',
274             'JavaScript:alert("bunny")',
275             "\t\n\t\nJavaScript:alert(\"bunny\")",
276             'data:text/html;<a></a>',
277             'Data:text/html;<a></a>',
278             'Data:text/html;<a></a>',
279         ];
280
281         foreach ($badLinks as $badLink) {
282             $linkReq = $this->post('attachments/link', [
283                 'attachment_link_url'         => $badLink,
284                 'attachment_link_name'        => 'Example Attachment Link',
285                 'attachment_link_uploaded_to' => $page->id,
286             ]);
287             $linkReq->assertStatus(422);
288             $this->assertDatabaseMissing('attachments', [
289                 'path' => $badLink,
290             ]);
291         }
292
293         $attachment = $this->createAttachment($page);
294
295         foreach ($badLinks as $badLink) {
296             $linkReq = $this->put('attachments/' . $attachment->id, [
297                 'attachment_edit_url'  => $badLink,
298                 'attachment_edit_name' => 'Example Attachment Link',
299             ]);
300             $linkReq->assertStatus(422);
301             $this->assertDatabaseMissing('attachments', [
302                 'path' => $badLink,
303             ]);
304         }
305     }
306
307     public function test_file_access_with_open_query_param_provides_inline_response_with_correct_content_type()
308     {
309         $page = $this->entities->page();
310         $this->asAdmin();
311         $fileName = 'upload_test_file.txt';
312
313         $upload = $this->uploadFile($fileName, $page->id);
314         $upload->assertStatus(200);
315         $attachment = Attachment::query()->orderBy('id', 'desc')->take(1)->first();
316
317         $attachmentGet = $this->get($attachment->getUrl(true));
318         // http-foundation/Response does some 'fixing' of responses to add charsets to text responses.
319         $attachmentGet->assertHeader('Content-Type', 'text/plain; charset=UTF-8');
320         $attachmentGet->assertHeader('Content-Disposition', 'inline; filename="upload_test_file.txt"');
321         $attachmentGet->assertHeader('X-Content-Type-Options', 'nosniff');
322
323         $this->deleteUploads();
324     }
325
326     public function test_html_file_access_with_open_forces_plain_content_type()
327     {
328         $page = $this->entities->page();
329         $this->asAdmin();
330
331         $attachment = $this->createUploadAttachment($page, 'test_file.html', '<html></html><p>testing</p>', 'text/html');
332
333         $attachmentGet = $this->get($attachment->getUrl(true));
334         // http-foundation/Response does some 'fixing' of responses to add charsets to text responses.
335         $attachmentGet->assertHeader('Content-Type', 'text/plain; charset=UTF-8');
336         $attachmentGet->assertHeader('Content-Disposition', 'inline; filename="test_file.html"');
337
338         $this->deleteUploads();
339     }
340
341     public function test_file_upload_works_when_local_secure_restricted_is_in_use()
342     {
343         config()->set('filesystems.attachments', 'local_secure_restricted');
344
345         $page = $this->entities->page();
346         $fileName = 'upload_test_file.txt';
347
348         $upload = $this->asAdmin()->uploadFile($fileName, $page->id);
349         $upload->assertStatus(200);
350
351         $attachment = Attachment::query()->orderBy('id', 'desc')->where('uploaded_to', '=', $page->id)->first();
352         $this->assertFileExists(storage_path($attachment->path));
353         $this->deleteUploads();
354     }
355 }