]> BookStack Code Mirror - bookstack/blob - tests/Uploads/AttachmentTest.php
Fixed tests from streaming changes
[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 = Page::query()->first();
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 = Page::query()->first();
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 = Page::query()->first();
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 = Page::query()->first();
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 = Page::query()->first();
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 = Page::query()->first();
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 = Page::query()->first();
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 = Page::query()->first(); /** @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         $page->restricted = true;
257         $page->permissions()->delete();
258         $page->save();
259         $page->rebuildPermissions();
260         $page->load('jointPermissions');
261
262         $this->actingAs($viewer);
263         $attachmentGet = $this->get($attachment->getUrl());
264         $attachmentGet->assertStatus(404);
265         $attachmentGet->assertSee('Attachment not found');
266
267         $this->deleteUploads();
268     }
269
270     public function test_data_and_js_links_cannot_be_attached_to_a_page()
271     {
272         $page = Page::query()->first();
273         $this->asAdmin();
274
275         $badLinks = [
276             'javascript:alert("bunny")',
277             ' javascript:alert("bunny")',
278             'JavaScript:alert("bunny")',
279             "\t\n\t\nJavaScript:alert(\"bunny\")",
280             'data:text/html;<a></a>',
281             'Data:text/html;<a></a>',
282             'Data:text/html;<a></a>',
283         ];
284
285         foreach ($badLinks as $badLink) {
286             $linkReq = $this->post('attachments/link', [
287                 'attachment_link_url'         => $badLink,
288                 'attachment_link_name'        => 'Example Attachment Link',
289                 'attachment_link_uploaded_to' => $page->id,
290             ]);
291             $linkReq->assertStatus(422);
292             $this->assertDatabaseMissing('attachments', [
293                 'path' => $badLink,
294             ]);
295         }
296
297         $attachment = $this->createAttachment($page);
298
299         foreach ($badLinks as $badLink) {
300             $linkReq = $this->put('attachments/' . $attachment->id, [
301                 'attachment_edit_url'  => $badLink,
302                 'attachment_edit_name' => 'Example Attachment Link',
303             ]);
304             $linkReq->assertStatus(422);
305             $this->assertDatabaseMissing('attachments', [
306                 'path' => $badLink,
307             ]);
308         }
309     }
310
311     public function test_file_access_with_open_query_param_provides_inline_response_with_correct_content_type()
312     {
313         $page = Page::query()->first();
314         $this->asAdmin();
315         $fileName = 'upload_test_file.txt';
316
317         $upload = $this->uploadFile($fileName, $page->id);
318         $upload->assertStatus(200);
319         $attachment = Attachment::query()->orderBy('id', 'desc')->take(1)->first();
320
321         $attachmentGet = $this->get($attachment->getUrl(true));
322         // http-foundation/Response does some 'fixing' of responses to add charsets to text responses.
323         $attachmentGet->assertHeader('Content-Type', 'text/plain; charset=UTF-8');
324         $attachmentGet->assertHeader('Content-Disposition', 'inline; filename="upload_test_file.txt"');
325         $attachmentGet->assertHeader('X-Content-Type-Options', 'nosniff');
326
327         $this->deleteUploads();
328     }
329
330     public function test_html_file_access_with_open_forces_plain_content_type()
331     {
332         $page = Page::query()->first();
333         $this->asAdmin();
334
335         $attachment = $this->createUploadAttachment($page, 'test_file.html', '<html></html><p>testing</p>', 'text/html');
336
337         $attachmentGet = $this->get($attachment->getUrl(true));
338         // http-foundation/Response does some 'fixing' of responses to add charsets to text responses.
339         $attachmentGet->assertHeader('Content-Type', 'text/plain; charset=UTF-8');
340         $attachmentGet->assertHeader('Content-Disposition', 'inline; filename="test_file.html"');
341
342         $this->deleteUploads();
343     }
344 }