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