]> BookStack Code Mirror - bookstack/blob - tests/Api/AttachmentsApiTest.php
Merge pull request #3373 from evandroamaro/patch-1
[bookstack] / tests / Api / AttachmentsApiTest.php
1 <?php
2
3 namespace Tests\Api;
4
5 use BookStack\Entities\Models\Page;
6 use BookStack\Uploads\Attachment;
7 use Illuminate\Http\UploadedFile;
8 use Illuminate\Testing\AssertableJsonString;
9 use Tests\TestCase;
10
11 class AttachmentsApiTest extends TestCase
12 {
13     use TestsApi;
14
15     protected $baseEndpoint = '/api/attachments';
16
17     public function test_index_endpoint_returns_expected_book()
18     {
19         $this->actingAsApiEditor();
20         $page = Page::query()->first();
21         $attachment = $this->createAttachmentForPage($page, [
22             'name'     => 'My test attachment',
23             'external' => true,
24         ]);
25
26         $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id');
27         $resp->assertJson(['data' => [
28             [
29                 'id'          => $attachment->id,
30                 'name'        => 'My test attachment',
31                 'uploaded_to' => $page->id,
32                 'external'    => true,
33             ],
34         ]]);
35     }
36
37     public function test_attachments_listing_based_upon_page_visibility()
38     {
39         $this->actingAsApiEditor();
40         /** @var Page $page */
41         $page = Page::query()->first();
42         $attachment = $this->createAttachmentForPage($page, [
43             'name'     => 'My test attachment',
44             'external' => true,
45         ]);
46
47         $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id');
48         $resp->assertJson(['data' => [
49             [
50                 'id' => $attachment->id,
51             ],
52         ]]);
53
54         $page->restricted = true;
55         $page->save();
56         $this->regenEntityPermissions($page);
57
58         $resp = $this->getJson($this->baseEndpoint . '?count=1&sort=+id');
59         $resp->assertJsonMissing(['data' => [
60             [
61                 'id' => $attachment->id,
62             ],
63         ]]);
64     }
65
66     public function test_create_endpoint_for_link_attachment()
67     {
68         $this->actingAsApiAdmin();
69         /** @var Page $page */
70         $page = Page::query()->first();
71
72         $details = [
73             'name'        => 'My attachment',
74             'uploaded_to' => $page->id,
75             'link'        => 'https://cats.example.com',
76         ];
77
78         $resp = $this->postJson($this->baseEndpoint, $details);
79         $resp->assertStatus(200);
80         /** @var Attachment $newItem */
81         $newItem = Attachment::query()->orderByDesc('id')->where('name', '=', $details['name'])->first();
82         $resp->assertJson(['id' => $newItem->id, 'external' => true, 'name' => $details['name'], 'uploaded_to' => $page->id]);
83     }
84
85     public function test_create_endpoint_for_upload_attachment()
86     {
87         $this->actingAsApiAdmin();
88         /** @var Page $page */
89         $page = Page::query()->first();
90         $file = $this->getTestFile('textfile.txt');
91
92         $details = [
93             'name'        => 'My attachment',
94             'uploaded_to' => $page->id,
95         ];
96
97         $resp = $this->call('POST', $this->baseEndpoint, $details, [], ['file' => $file]);
98         $resp->assertStatus(200);
99         /** @var Attachment $newItem */
100         $newItem = Attachment::query()->orderByDesc('id')->where('name', '=', $details['name'])->first();
101         $resp->assertJson(['id' => $newItem->id, 'external' => false, 'extension' => 'txt', 'name' => $details['name'], 'uploaded_to' => $page->id]);
102         $this->assertTrue(file_exists(storage_path($newItem->path)));
103         unlink(storage_path($newItem->path));
104     }
105
106     public function test_upload_limit_restricts_attachment_uploads()
107     {
108         $this->actingAsApiAdmin();
109         /** @var Page $page */
110         $page = Page::query()->first();
111
112         config()->set('app.upload_limit', 1);
113
114         $file = tmpfile();
115         $filePath = stream_get_meta_data($file)['uri'];
116         fwrite($file, str_repeat('a', 1200000));
117         $file = new UploadedFile($filePath, 'test.txt', 'text/plain', null, true);
118
119         $details = [
120             'name'        => 'My attachment',
121             'uploaded_to' => $page->id,
122         ];
123         $resp = $this->call('POST', $this->baseEndpoint, $details, [], ['file' => $file]);
124         $resp->assertStatus(422);
125         $resp->assertJson($this->validationResponse([
126             'file' => ['The file may not be greater than 1000 kilobytes.'],
127         ]));
128     }
129
130     public function test_name_needed_to_create()
131     {
132         $this->actingAsApiAdmin();
133         /** @var Page $page */
134         $page = Page::query()->first();
135
136         $details = [
137             'uploaded_to' => $page->id,
138             'link'        => 'https://example.com',
139         ];
140
141         $resp = $this->postJson($this->baseEndpoint, $details);
142         $resp->assertStatus(422);
143         $resp->assertJson($this->validationResponse(['name' => ['The name field is required.']]));
144     }
145
146     public function test_link_or_file_needed_to_create()
147     {
148         $this->actingAsApiAdmin();
149         /** @var Page $page */
150         $page = Page::query()->first();
151
152         $details = [
153             'name'        => 'my attachment',
154             'uploaded_to' => $page->id,
155         ];
156
157         $resp = $this->postJson($this->baseEndpoint, $details);
158         $resp->assertStatus(422);
159         $resp->assertJson($this->validationResponse([
160             'file' => ['The file field is required when link is not present.'],
161             'link' => ['The link field is required when file is not present.'],
162         ]));
163     }
164
165     public function test_message_shown_if_file_is_not_a_valid_file()
166     {
167         $this->actingAsApiAdmin();
168         /** @var Page $page */
169         $page = Page::query()->first();
170
171         $details = [
172             'name'        => 'my attachment',
173             'uploaded_to' => $page->id,
174             'file'        => 'cat',
175         ];
176
177         $resp = $this->postJson($this->baseEndpoint, $details);
178         $resp->assertStatus(422);
179         $resp->assertJson($this->validationResponse(['file' => ['The file must be provided as a valid file.']]));
180     }
181
182     public function test_read_endpoint_for_link_attachment()
183     {
184         $this->actingAsApiAdmin();
185         /** @var Page $page */
186         $page = Page::query()->first();
187
188         $attachment = $this->createAttachmentForPage($page, [
189             'name'  => 'my attachment',
190             'path'  => 'https://example.com',
191             'order' => 1,
192         ]);
193
194         $resp = $this->getJson("{$this->baseEndpoint}/{$attachment->id}");
195
196         $resp->assertStatus(200);
197         $resp->assertJson([
198             'id'          => $attachment->id,
199             'content'     => 'https://example.com',
200             'external'    => true,
201             'uploaded_to' => $page->id,
202             'order'       => 1,
203             'created_by'  => [
204                 'name' => $attachment->createdBy->name,
205             ],
206             'updated_by' => [
207                 'name' => $attachment->createdBy->name,
208             ],
209             'links' => [
210                 'html'     => "<a target=\"_blank\" href=\"http://localhost/attachments/{$attachment->id}\">my attachment</a>",
211                 'markdown' => "[my attachment](http://localhost/attachments/{$attachment->id})",
212             ],
213         ]);
214     }
215
216     public function test_read_endpoint_for_file_attachment()
217     {
218         $this->actingAsApiAdmin();
219         /** @var Page $page */
220         $page = Page::query()->first();
221         $file = $this->getTestFile('textfile.txt');
222
223         $details = [
224             'name'        => 'My file attachment',
225             'uploaded_to' => $page->id,
226         ];
227         $this->call('POST', $this->baseEndpoint, $details, [], ['file' => $file]);
228         /** @var Attachment $attachment */
229         $attachment = Attachment::query()->orderByDesc('id')->where('name', '=', $details['name'])->firstOrFail();
230
231         $resp = $this->getJson("{$this->baseEndpoint}/{$attachment->id}");
232         $resp->assertStatus(200);
233         $resp->assertHeader('Content-Type', 'application/json');
234
235         $json = new AssertableJsonString($resp->streamedContent());
236         $json->assertSubset([
237             'id'          => $attachment->id,
238             'content'     => base64_encode(file_get_contents(storage_path($attachment->path))),
239             'external'    => false,
240             'uploaded_to' => $page->id,
241             'order'       => 1,
242             'created_by'  => [
243                 'name' => $attachment->createdBy->name,
244             ],
245             'updated_by' => [
246                 'name' => $attachment->updatedBy->name,
247             ],
248             'links' => [
249                 'html'     => "<a target=\"_blank\" href=\"http://localhost/attachments/{$attachment->id}\">My file attachment</a>",
250                 'markdown' => "[My file attachment](http://localhost/attachments/{$attachment->id})",
251             ],
252         ]);
253
254         unlink(storage_path($attachment->path));
255     }
256
257     public function test_attachment_not_visible_on_other_users_draft()
258     {
259         $this->actingAsApiAdmin();
260         $editor = $this->getEditor();
261
262         /** @var Page $page */
263         $page = Page::query()->first();
264         $page->draft = true;
265         $page->owned_by = $editor;
266         $page->save();
267         $this->regenEntityPermissions($page);
268
269         $attachment = $this->createAttachmentForPage($page, [
270             'name'  => 'my attachment',
271             'path'  => 'https://example.com',
272             'order' => 1,
273         ]);
274
275         $resp = $this->getJson("{$this->baseEndpoint}/{$attachment->id}");
276
277         $resp->assertStatus(404);
278     }
279
280     public function test_update_endpoint()
281     {
282         $this->actingAsApiAdmin();
283         /** @var Page $page */
284         $page = Page::query()->first();
285         $attachment = $this->createAttachmentForPage($page);
286
287         $details = [
288             'name' => 'My updated API attachment',
289         ];
290
291         $resp = $this->putJson("{$this->baseEndpoint}/{$attachment->id}", $details);
292         $attachment->refresh();
293
294         $resp->assertStatus(200);
295         $resp->assertJson(['id' => $attachment->id, 'name' => 'My updated API attachment']);
296     }
297
298     public function test_update_link_attachment_to_file()
299     {
300         $this->actingAsApiAdmin();
301         /** @var Page $page */
302         $page = Page::query()->first();
303         $attachment = $this->createAttachmentForPage($page);
304         $file = $this->getTestFile('textfile.txt');
305
306         $resp = $this->call('PUT', "{$this->baseEndpoint}/{$attachment->id}", ['name' => 'My updated file'], [], ['file' => $file]);
307         $resp->assertStatus(200);
308
309         $attachment->refresh();
310         $this->assertFalse($attachment->external);
311         $this->assertEquals('txt', $attachment->extension);
312         $this->assertStringStartsWith('uploads/files/', $attachment->path);
313         $this->assertFileExists(storage_path($attachment->path));
314
315         unlink(storage_path($attachment->path));
316     }
317
318     public function test_update_file_attachment_to_link()
319     {
320         $this->actingAsApiAdmin();
321         /** @var Page $page */
322         $page = Page::query()->first();
323         $file = $this->getTestFile('textfile.txt');
324         $this->call('POST', $this->baseEndpoint, ['name' => 'My file attachment', 'uploaded_to' => $page->id], [], ['file' => $file]);
325         /** @var Attachment $attachment */
326         $attachment = Attachment::query()->where('name', '=', 'My file attachment')->firstOrFail();
327
328         $filePath = storage_path($attachment->path);
329         $this->assertFileExists($filePath);
330
331         $details = [
332             'name' => 'My updated API attachment',
333             'link' => 'https://cats.example.com',
334         ];
335
336         $resp = $this->putJson("{$this->baseEndpoint}/{$attachment->id}", $details);
337         $resp->assertStatus(200);
338         $attachment->refresh();
339
340         $this->assertFileDoesNotExist($filePath);
341         $this->assertTrue($attachment->external);
342         $this->assertEquals('https://cats.example.com', $attachment->path);
343         $this->assertEquals('', $attachment->extension);
344     }
345
346     public function test_delete_endpoint()
347     {
348         $this->actingAsApiAdmin();
349         /** @var Page $page */
350         $page = Page::query()->first();
351         $attachment = $this->createAttachmentForPage($page);
352
353         $resp = $this->deleteJson("{$this->baseEndpoint}/{$attachment->id}");
354
355         $resp->assertStatus(204);
356         $this->assertDatabaseMissing('attachments', ['id' => $attachment->id]);
357     }
358
359     protected function createAttachmentForPage(Page $page, $attributes = []): Attachment
360     {
361         $admin = $this->getAdmin();
362         /** @var Attachment $attachment */
363         $attachment = $page->attachments()->forceCreate(array_merge([
364             'uploaded_to' => $page->id,
365             'name'        => 'test attachment',
366             'external'    => true,
367             'order'       => 1,
368             'created_by'  => $admin->id,
369             'updated_by'  => $admin->id,
370             'path'        => 'https://attachment.example.com',
371         ], $attributes));
372
373         return $attachment;
374     }
375
376     /**
377      * Get a test file that can be uploaded.
378      */
379     protected function getTestFile(string $fileName): UploadedFile
380     {
381         return new UploadedFile(base_path('tests/test-data/test-file.txt'), $fileName, 'text/plain', null, true);
382     }
383 }