Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / modules / file / src / Tests / FileFieldWidgetTest.php
1 <?php
2
3 namespace Drupal\file\Tests;
4
5 use Drupal\comment\Entity\Comment;
6 use Drupal\comment\Tests\CommentTestTrait;
7 use Drupal\Core\Url;
8 use Drupal\field\Entity\FieldConfig;
9 use Drupal\field\Entity\FieldStorageConfig;
10 use Drupal\field_ui\Tests\FieldUiTestTrait;
11 use Drupal\user\RoleInterface;
12 use Drupal\file\Entity\File;
13 use Drupal\user\Entity\User;
14 use Drupal\user\UserInterface;
15
16 /**
17  * Tests the file field widget, single and multi-valued, with and without AJAX,
18  * with public and private files.
19  *
20  * @group file
21  */
22 class FileFieldWidgetTest extends FileFieldTestBase {
23
24   use CommentTestTrait;
25   use FieldUiTestTrait;
26
27   /**
28    * {@inheritdoc}
29    */
30   protected function setUp() {
31     parent::setUp();
32     $this->drupalPlaceBlock('system_breadcrumb_block');
33   }
34
35   /**
36    * Modules to enable.
37    *
38    * @var array
39    */
40   public static $modules = ['comment', 'block'];
41
42   /**
43    * Creates a temporary file, for a specific user.
44    *
45    * @param string $data
46    *   A string containing the contents of the file.
47    * @param \Drupal\user\UserInterface $user
48    *   The user of the file owner.
49    *
50    * @return \Drupal\file\FileInterface
51    *   A file object, or FALSE on error.
52    */
53   protected function createTemporaryFile($data, UserInterface $user = NULL) {
54     $file = file_save_data($data, NULL, NULL);
55
56     if ($file) {
57       if ($user) {
58         $file->setOwner($user);
59       }
60       else {
61         $file->setOwner($this->adminUser);
62       }
63       // Change the file status to be temporary.
64       $file->setTemporary();
65       // Save the changes.
66       $file->save();
67     }
68
69     return $file;
70   }
71
72   /**
73    * Tests upload and remove buttons for a single-valued File field.
74    */
75   public function testSingleValuedWidget() {
76     $node_storage = $this->container->get('entity.manager')->getStorage('node');
77     $type_name = 'article';
78     $field_name = strtolower($this->randomMachineName());
79     $this->createFileField($field_name, 'node', $type_name);
80
81     $test_file = $this->getTestFile('text');
82
83     foreach (['nojs', 'js'] as $type) {
84       // Create a new node with the uploaded file and ensure it got uploaded
85       // successfully.
86       // @todo This only tests a 'nojs' submission, because drupalPostAjaxForm()
87       //   does not yet support file uploads.
88       $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
89       $node_storage->resetCache([$nid]);
90       $node = $node_storage->load($nid);
91       $node_file = File::load($node->{$field_name}->target_id);
92       $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
93
94       // Ensure the file can be downloaded.
95       $this->drupalGet(file_create_url($node_file->getFileUri()));
96       $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
97
98       // Ensure the edit page has a remove button instead of an upload button.
99       $this->drupalGet("node/$nid/edit");
100       $this->assertNoFieldByXPath('//input[@type="submit"]', t('Upload'), 'Node with file does not display the "Upload" button.');
101       $this->assertFieldByXpath('//input[@type="submit"]', t('Remove'), 'Node with file displays the "Remove" button.');
102
103       // "Click" the remove button (emulating either a nojs or js submission).
104       switch ($type) {
105         case 'nojs':
106           $this->drupalPostForm(NULL, [], t('Remove'));
107           break;
108         case 'js':
109           $button = $this->xpath('//input[@type="submit" and @value="' . t('Remove') . '"]');
110           $this->drupalPostAjaxForm(NULL, [], [(string) $button[0]['name'] => (string) $button[0]['value']]);
111           break;
112       }
113
114       // Ensure the page now has an upload button instead of a remove button.
115       $this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), 'After clicking the "Remove" button, it is no longer displayed.');
116       $this->assertFieldByXpath('//input[@type="submit"]', t('Upload'), 'After clicking the "Remove" button, the "Upload" button is displayed.');
117       // Test label has correct 'for' attribute.
118       $input = $this->xpath('//input[@name="files[' . $field_name . '_0]"]');
119       $label = $this->xpath('//label[@for="' . (string) $input[0]['id'] . '"]');
120       $this->assertTrue(isset($label[0]), 'Label for upload found.');
121
122       // Save the node and ensure it does not have the file.
123       $this->drupalPostForm(NULL, [], t('Save'));
124       $node_storage->resetCache([$nid]);
125       $node = $node_storage->load($nid);
126       $this->assertTrue(empty($node->{$field_name}->target_id), 'File was successfully removed from the node.');
127     }
128   }
129
130   /**
131    * Tests upload and remove buttons for multiple multi-valued File fields.
132    */
133   public function testMultiValuedWidget() {
134     $node_storage = $this->container->get('entity.manager')->getStorage('node');
135     $type_name = 'article';
136     // Use explicit names instead of random names for those fields, because of a
137     // bug in drupalPostForm() with multiple file uploads in one form, where the
138     // order of uploads depends on the order in which the upload elements are
139     // added to the $form (which, in the current implementation of
140     // FileStorage::listAll(), comes down to the alphabetical order on field
141     // names).
142     $field_name = 'test_file_field_1';
143     $field_name2 = 'test_file_field_2';
144     $cardinality = 3;
145     $this->createFileField($field_name, 'node', $type_name, ['cardinality' => $cardinality]);
146     $this->createFileField($field_name2, 'node', $type_name, ['cardinality' => $cardinality]);
147
148     $test_file = $this->getTestFile('text');
149
150     foreach (['nojs', 'js'] as $type) {
151       // Visit the node creation form, and upload 3 files for each field. Since
152       // the field has cardinality of 3, ensure the "Upload" button is displayed
153       // until after the 3rd file, and after that, isn't displayed. Because
154       // SimpleTest triggers the last button with a given name, so upload to the
155       // second field first.
156       // @todo This is only testing a non-Ajax upload, because drupalPostAjaxForm()
157       //   does not yet emulate jQuery's file upload.
158       //
159       $this->drupalGet("node/add/$type_name");
160       foreach ([$field_name2, $field_name] as $each_field_name) {
161         for ($delta = 0; $delta < 3; $delta++) {
162           $edit = ['files[' . $each_field_name . '_' . $delta . '][]' => \Drupal::service('file_system')->realpath($test_file->getFileUri())];
163           // If the Upload button doesn't exist, drupalPostForm() will automatically
164           // fail with an assertion message.
165           $this->drupalPostForm(NULL, $edit, t('Upload'));
166         }
167       }
168       $this->assertNoFieldByXpath('//input[@type="submit"]', t('Upload'), 'After uploading 3 files for each field, the "Upload" button is no longer displayed.');
169
170       $num_expected_remove_buttons = 6;
171
172       foreach ([$field_name, $field_name2] as $current_field_name) {
173         // How many uploaded files for the current field are remaining.
174         $remaining = 3;
175         // Test clicking each "Remove" button. For extra robustness, test them out
176         // of sequential order. They are 0-indexed, and get renumbered after each
177         // iteration, so array(1, 1, 0) means:
178         // - First remove the 2nd file.
179         // - Then remove what is then the 2nd file (was originally the 3rd file).
180         // - Then remove the first file.
181         foreach ([1, 1, 0] as $delta) {
182           // Ensure we have the expected number of Remove buttons, and that they
183           // are numbered sequentially.
184           $buttons = $this->xpath('//input[@type="submit" and @value="Remove"]');
185           $this->assertTrue(is_array($buttons) && count($buttons) === $num_expected_remove_buttons, format_string('There are %n "Remove" buttons displayed (JSMode=%type).', ['%n' => $num_expected_remove_buttons, '%type' => $type]));
186           foreach ($buttons as $i => $button) {
187             $key = $i >= $remaining ? $i - $remaining : $i;
188             $check_field_name = $field_name2;
189             if ($current_field_name == $field_name && $i < $remaining) {
190               $check_field_name = $field_name;
191             }
192
193             $this->assertIdentical((string) $button['name'], $check_field_name . '_' . $key . '_remove_button');
194           }
195
196           // "Click" the remove button (emulating either a nojs or js submission).
197           $button_name = $current_field_name . '_' . $delta . '_remove_button';
198           switch ($type) {
199             case 'nojs':
200               // drupalPostForm() takes a $submit parameter that is the value of the
201               // button whose click we want to emulate. Since we have multiple
202               // buttons with the value "Remove", and want to control which one we
203               // use, we change the value of the other ones to something else.
204               // Since non-clicked buttons aren't included in the submitted POST
205               // data, and since drupalPostForm() will result in $this being updated
206               // with a newly rebuilt form, this doesn't cause problems.
207               foreach ($buttons as $button) {
208                 if ($button['name'] != $button_name) {
209                   $button['value'] = 'DUMMY';
210                 }
211               }
212               $this->drupalPostForm(NULL, [], t('Remove'));
213               break;
214             case 'js':
215               // drupalPostAjaxForm() lets us target the button precisely, so we don't
216               // require the workaround used above for nojs.
217               $this->drupalPostAjaxForm(NULL, [], [$button_name => t('Remove')]);
218               break;
219           }
220           $num_expected_remove_buttons--;
221           $remaining--;
222
223           // Ensure an "Upload" button for the current field is displayed with the
224           // correct name.
225           $upload_button_name = $current_field_name . '_' . $remaining . '_upload_button';
226           $buttons = $this->xpath('//input[@type="submit" and @value="Upload" and @name=:name]', [':name' => $upload_button_name]);
227           $this->assertTrue(is_array($buttons) && count($buttons) == 1, format_string('The upload button is displayed with the correct name (JSMode=%type).', ['%type' => $type]));
228
229           // Ensure only at most one button per field is displayed.
230           $buttons = $this->xpath('//input[@type="submit" and @value="Upload"]');
231           $expected = $current_field_name == $field_name ? 1 : 2;
232           $this->assertTrue(is_array($buttons) && count($buttons) == $expected, format_string('After removing a file, only one "Upload" button for each possible field is displayed (JSMode=%type).', ['%type' => $type]));
233         }
234       }
235
236       // Ensure the page now has no Remove buttons.
237       $this->assertNoFieldByXPath('//input[@type="submit"]', t('Remove'), format_string('After removing all files, there is no "Remove" button displayed (JSMode=%type).', ['%type' => $type]));
238
239       // Save the node and ensure it does not have any files.
240       $this->drupalPostForm(NULL, ['title[0][value]' => $this->randomMachineName()], t('Save'));
241       preg_match('/node\/([0-9]+)/', $this->getUrl(), $matches);
242       $nid = $matches[1];
243       $node_storage->resetCache([$nid]);
244       $node = $node_storage->load($nid);
245       $this->assertTrue(empty($node->{$field_name}->target_id), 'Node was successfully saved without any files.');
246     }
247
248     $upload_files_node_creation = [$test_file, $test_file];
249     // Try to upload multiple files, but fewer than the maximum.
250     $nid = $this->uploadNodeFiles($upload_files_node_creation, $field_name, $type_name);
251     $node_storage->resetCache([$nid]);
252     $node = $node_storage->load($nid);
253     $this->assertEqual(count($node->{$field_name}), count($upload_files_node_creation), 'Node was successfully saved with mulitple files.');
254
255     // Try to upload more files than allowed on revision.
256     $upload_files_node_revision = [$test_file, $test_file, $test_file, $test_file];
257     $this->uploadNodeFiles($upload_files_node_revision, $field_name, $nid, 1);
258     $args = [
259       '%field' => $field_name,
260       '@max' => $cardinality,
261       '@count' => count($upload_files_node_creation) + count($upload_files_node_revision),
262       '%list' => implode(', ', array_fill(0, 3, $test_file->getFilename())),
263     ];
264     $this->assertRaw(t('Field %field can only hold @max values but there were @count uploaded. The following files have been omitted as a result: %list.', $args));
265     $node_storage->resetCache([$nid]);
266     $node = $node_storage->load($nid);
267     $this->assertEqual(count($node->{$field_name}), $cardinality, 'More files than allowed could not be saved to node.');
268
269     // Try to upload exactly the allowed number of files on revision. Create an
270     // empty node first, to fill it in its first revision.
271     $node = $this->drupalCreateNode([
272       'type' => $type_name,
273     ]);
274     $this->uploadNodeFile($test_file, $field_name, $node->id(), 1);
275     $node_storage->resetCache([$nid]);
276     $node = $node_storage->load($nid);
277     $this->assertEqual(count($node->{$field_name}), $cardinality, 'Node was successfully revised to maximum number of files.');
278
279     // Try to upload exactly the allowed number of files, new node.
280     $upload_files = array_fill(0, $cardinality, $test_file);
281     $nid = $this->uploadNodeFiles($upload_files, $field_name, $type_name);
282     $node_storage->resetCache([$nid]);
283     $node = $node_storage->load($nid);
284     $this->assertEqual(count($node->{$field_name}), $cardinality, 'Node was successfully saved with maximum number of files.');
285
286     // Try to upload more files than allowed, new node.
287     $upload_files[] = $test_file;
288     $this->uploadNodeFiles($upload_files, $field_name, $type_name);
289
290     $args = [
291       '%field' => $field_name,
292       '@max' => $cardinality,
293       '@count' => count($upload_files),
294       '%list' => $test_file->getFileName(),
295     ];
296     $this->assertRaw(t('Field %field can only hold @max values but there were @count uploaded. The following files have been omitted as a result: %list.', $args));
297   }
298
299   /**
300    * Tests a file field with a "Private files" upload destination setting.
301    */
302   public function testPrivateFileSetting() {
303     $node_storage = $this->container->get('entity.manager')->getStorage('node');
304     // Grant the admin user required permissions.
305     user_role_grant_permissions($this->adminUser->roles[0]->target_id, ['administer node fields']);
306
307     $type_name = 'article';
308     $field_name = strtolower($this->randomMachineName());
309     $this->createFileField($field_name, 'node', $type_name);
310     $field = FieldConfig::loadByName('node', $type_name, $field_name);
311     $field_id = $field->id();
312
313     $test_file = $this->getTestFile('text');
314
315     // Change the field setting to make its files private, and upload a file.
316     $edit = ['settings[uri_scheme]' => 'private'];
317     $this->drupalPostForm("admin/structure/types/manage/$type_name/fields/$field_id/storage", $edit, t('Save field settings'));
318     $nid = $this->uploadNodeFile($test_file, $field_name, $type_name);
319     $node_storage->resetCache([$nid]);
320     $node = $node_storage->load($nid);
321     $node_file = File::load($node->{$field_name}->target_id);
322     $this->assertFileExists($node_file, 'New file saved to disk on node creation.');
323
324     // Ensure the private file is available to the user who uploaded it.
325     $this->drupalGet(file_create_url($node_file->getFileUri()));
326     $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
327
328     // Ensure we can't change 'uri_scheme' field settings while there are some
329     // entities with uploaded files.
330     $this->drupalGet("admin/structure/types/manage/$type_name/fields/$field_id/storage");
331     $this->assertFieldByXpath('//input[@id="edit-settings-uri-scheme-public" and @disabled="disabled"]', 'public', 'Upload destination setting disabled.');
332
333     // Delete node and confirm that setting could be changed.
334     $node->delete();
335     $this->drupalGet("admin/structure/types/manage/$type_name/fields/$field_id/storage");
336     $this->assertFieldByXpath('//input[@id="edit-settings-uri-scheme-public" and not(@disabled)]', 'public', 'Upload destination setting enabled.');
337   }
338
339   /**
340    * Tests that download restrictions on private files work on comments.
341    */
342   public function testPrivateFileComment() {
343     $user = $this->drupalCreateUser(['access comments']);
344
345     // Grant the admin user required comment permissions.
346     $roles = $this->adminUser->getRoles();
347     user_role_grant_permissions($roles[1], ['administer comment fields', 'administer comments']);
348
349     // Revoke access comments permission from anon user, grant post to
350     // authenticated.
351     user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, ['access comments']);
352     user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['post comments', 'skip comment approval']);
353
354     // Create a new field.
355     $this->addDefaultCommentField('node', 'article');
356
357     $name = strtolower($this->randomMachineName());
358     $label = $this->randomMachineName();
359     $storage_edit = ['settings[uri_scheme]' => 'private'];
360     $this->fieldUIAddNewField('admin/structure/comment/manage/comment', $name, $label, 'file', $storage_edit);
361
362     // Manually clear cache on the tester side.
363     \Drupal::entityManager()->clearCachedFieldDefinitions();
364
365     // Create node.
366     $edit = [
367       'title[0][value]' => $this->randomMachineName(),
368     ];
369     $this->drupalPostForm('node/add/article', $edit, t('Save'));
370     $node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
371
372     // Add a comment with a file.
373     $text_file = $this->getTestFile('text');
374     $edit = [
375       'files[field_' . $name . '_' . 0 . ']' => \Drupal::service('file_system')->realpath($text_file->getFileUri()),
376       'comment_body[0][value]' => $comment_body = $this->randomMachineName(),
377     ];
378     $this->drupalPostForm('node/' . $node->id(), $edit, t('Save'));
379
380     // Get the comment ID.
381     preg_match('/comment-([0-9]+)/', $this->getUrl(), $matches);
382     $cid = $matches[1];
383
384     // Log in as normal user.
385     $this->drupalLogin($user);
386
387     $comment = Comment::load($cid);
388     $comment_file = $comment->{'field_' . $name}->entity;
389     $this->assertFileExists($comment_file, 'New file saved to disk on node creation.');
390     // Test authenticated file download.
391     $url = file_create_url($comment_file->getFileUri());
392     $this->assertNotEqual($url, NULL, 'Confirmed that the URL is valid');
393     $this->drupalGet(file_create_url($comment_file->getFileUri()));
394     $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
395
396     // Test anonymous file download.
397     $this->drupalLogout();
398     $this->drupalGet(file_create_url($comment_file->getFileUri()));
399     $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
400
401     // Unpublishes node.
402     $this->drupalLogin($this->adminUser);
403     $edit = ['status[value]' => FALSE];
404     $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save'));
405
406     // Ensures normal user can no longer download the file.
407     $this->drupalLogin($user);
408     $this->drupalGet(file_create_url($comment_file->getFileUri()));
409     $this->assertResponse(403, 'Confirmed that access is denied for the file without the needed permission.');
410   }
411
412   /**
413    * Tests validation with the Upload button.
414    */
415   public function testWidgetValidation() {
416     $type_name = 'article';
417     $field_name = strtolower($this->randomMachineName());
418     $this->createFileField($field_name, 'node', $type_name);
419     $this->updateFileField($field_name, $type_name, ['file_extensions' => 'txt']);
420
421     foreach (['nojs', 'js'] as $type) {
422       // Create node and prepare files for upload.
423       $node = $this->drupalCreateNode(['type' => 'article']);
424       $nid = $node->id();
425       $this->drupalGet("node/$nid/edit");
426       $test_file_text = $this->getTestFile('text');
427       $test_file_image = $this->getTestFile('image');
428       $name = 'files[' . $field_name . '_0]';
429
430       // Upload file with incorrect extension, check for validation error.
431       $edit[$name] = \Drupal::service('file_system')->realpath($test_file_image->getFileUri());
432       switch ($type) {
433         case 'nojs':
434           $this->drupalPostForm(NULL, $edit, t('Upload'));
435           break;
436         case 'js':
437           $button = $this->xpath('//input[@type="submit" and @value="' . t('Upload') . '"]');
438           $this->drupalPostAjaxForm(NULL, $edit, [(string) $button[0]['name'] => (string) $button[0]['value']]);
439           break;
440       }
441       $error_message = t('Only files with the following extensions are allowed: %files-allowed.', ['%files-allowed' => 'txt']);
442       $this->assertRaw($error_message, t('Validation error when file with wrong extension uploaded (JSMode=%type).', ['%type' => $type]));
443
444       // Upload file with correct extension, check that error message is removed.
445       $edit[$name] = \Drupal::service('file_system')->realpath($test_file_text->getFileUri());
446       switch ($type) {
447         case 'nojs':
448           $this->drupalPostForm(NULL, $edit, t('Upload'));
449           break;
450         case 'js':
451           $button = $this->xpath('//input[@type="submit" and @value="' . t('Upload') . '"]');
452           $this->drupalPostAjaxForm(NULL, $edit, [(string) $button[0]['name'] => (string) $button[0]['value']]);
453           break;
454       }
455       $this->assertNoRaw($error_message, t('Validation error removed when file with correct extension uploaded (JSMode=%type).', ['%type' => $type]));
456     }
457   }
458
459   /**
460    * Tests file widget element.
461    */
462   public function testWidgetElement() {
463     $field_name = mb_strtolower($this->randomMachineName());
464     $html_name = str_replace('_', '-', $field_name);
465     $this->createFileField($field_name, 'node', 'article', ['cardinality' => FieldStorageConfig::CARDINALITY_UNLIMITED]);
466     $file = $this->getTestFile('text');
467     $xpath = "//details[@data-drupal-selector='edit-$html_name']/div[@class='details-wrapper']/table";
468
469     $this->drupalGet('node/add/article');
470
471     $elements = $this->xpath($xpath);
472
473     // If the field has no item, the table should not be visible.
474     $this->assertIdentical(count($elements), 0);
475
476     // Upload a file.
477     $edit['files[' . $field_name . '_0][]'] = $this->container->get('file_system')->realpath($file->getFileUri());
478     $this->drupalPostAjaxForm(NULL, $edit, "{$field_name}_0_upload_button");
479
480     $elements = $this->xpath($xpath);
481
482     // If the field has at least a item, the table should be visible.
483     $this->assertIdentical(count($elements), 1);
484
485     // Test for AJAX error when using progress bar on file field widget
486     $key = $this->randomMachineName();
487     $this->drupalPost('file/progress/' . $key, 'application/json', []);
488     $this->assertNoResponse(500, t('No AJAX error when using progress bar on file field widget'));
489     $this->assertText('Starting upload...');
490   }
491
492   /**
493    * Tests exploiting the temporary file removal of another user using fid.
494    */
495   public function testTemporaryFileRemovalExploit() {
496     // Create a victim user.
497     $victim_user = $this->drupalCreateUser();
498
499     // Create an attacker user.
500     $attacker_user = $this->drupalCreateUser([
501       'access content',
502       'create article content',
503       'edit any article content',
504     ]);
505
506     // Log in as the attacker user.
507     $this->drupalLogin($attacker_user);
508
509     // Perform tests using the newly created users.
510     $this->doTestTemporaryFileRemovalExploit($victim_user, $attacker_user);
511   }
512
513   /**
514    * Tests exploiting the temporary file removal for anonymous users using fid.
515    */
516   public function testTemporaryFileRemovalExploitAnonymous() {
517     // Set up an anonymous victim user.
518     $victim_user = User::getAnonymousUser();
519
520     // Set up an anonymous attacker user.
521     $attacker_user = User::getAnonymousUser();
522
523     // Set up permissions for anonymous attacker user.
524     user_role_change_permissions(RoleInterface::ANONYMOUS_ID, [
525       'access content' => TRUE,
526       'create article content' => TRUE,
527       'edit any article content' => TRUE,
528     ]);
529
530     // Log out so as to be the anonymous attacker user.
531     $this->drupalLogout();
532
533     // Perform tests using the newly set up anonymous users.
534     $this->doTestTemporaryFileRemovalExploit($victim_user, $attacker_user);
535   }
536
537   /**
538    * Helper for testing exploiting the temporary file removal using fid.
539    *
540    * @param \Drupal\user\UserInterface $victim_user
541    *   The victim user.
542    * @param \Drupal\user\UserInterface $attacker_user
543    *   The attacker user.
544    */
545   protected function doTestTemporaryFileRemovalExploit(UserInterface $victim_user, UserInterface $attacker_user) {
546     $type_name = 'article';
547     $field_name = 'test_file_field';
548     $this->createFileField($field_name, 'node', $type_name);
549
550     $test_file = $this->getTestFile('text');
551     foreach (['nojs', 'js'] as $type) {
552       // Create a temporary file owned by the victim user. This will be as if
553       // they had uploaded the file, but not saved the node they were editing
554       // or creating.
555       $victim_tmp_file = $this->createTemporaryFile('some text', $victim_user);
556       $victim_tmp_file = File::load($victim_tmp_file->id());
557       $this->assertTrue($victim_tmp_file->isTemporary(), 'New file saved to disk is temporary.');
558       $this->assertFalse(empty($victim_tmp_file->id()), 'New file has an fid.');
559       $this->assertEqual($victim_user->id(), $victim_tmp_file->getOwnerId(), 'New file belongs to the victim.');
560
561       // Have attacker create a new node with a different uploaded file and
562       // ensure it got uploaded successfully.
563       $edit = [
564         'title[0][value]' => $type . '-title' ,
565       ];
566
567       // Attach a file to a node.
568       $edit['files[' . $field_name . '_0]'] = $this->container->get('file_system')->realpath($test_file->getFileUri());
569       $this->drupalPostForm(Url::fromRoute('node.add', ['node_type' => $type_name]), $edit, t('Save'));
570       $node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
571
572       /** @var \Drupal\file\FileInterface $node_file */
573       $node_file = File::load($node->{$field_name}->target_id);
574       $this->assertFileExists($node_file, 'A file was saved to disk on node creation');
575       $this->assertEqual($attacker_user->id(), $node_file->getOwnerId(), 'New file belongs to the attacker.');
576
577       // Ensure the file can be downloaded.
578       $this->drupalGet(file_create_url($node_file->getFileUri()));
579       $this->assertResponse(200, 'Confirmed that the generated URL is correct by downloading the shipped file.');
580
581       // "Click" the remove button (emulating either a nojs or js submission).
582       // In this POST request, the attacker "guesses" the fid of the victim's
583       // temporary file and uses that to remove this file.
584       $this->drupalGet($node->toUrl('edit-form'));
585       switch ($type) {
586         case 'nojs':
587           $this->drupalPostForm(NULL, [$field_name . '[0][fids]' => (string) $victim_tmp_file->id()], 'Remove');
588           break;
589
590         case 'js':
591           $this->drupalPostAjaxForm(NULL, [$field_name . '[0][fids]' => (string) $victim_tmp_file->id()], ["{$field_name}_0_remove_button" => 'Remove']);
592           break;
593       }
594
595       // The victim's temporary file should not be removed by the attacker's
596       // POST request.
597       $this->assertFileExists($victim_tmp_file);
598     }
599   }
600
601 }