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