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