3 namespace Drupal\file\Tests;
5 use Drupal\comment\Entity\Comment;
6 use Drupal\comment\Tests\CommentTestTrait;
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;
17 * Tests the file field widget, single and multi-valued, with and without AJAX,
18 * with public and private files.
22 class FileFieldWidgetTest extends FileFieldTestBase {
30 protected function setUp() {
32 $this->drupalPlaceBlock('system_breadcrumb_block');
40 public static $modules = ['comment', 'block'];
43 * Creates a temporary file, for a specific user.
46 * A string containing the contents of the file.
47 * @param \Drupal\user\UserInterface $user
48 * The user of the file owner.
50 * @return \Drupal\file\FileInterface
51 * A file object, or FALSE on error.
53 protected function createTemporaryFile($data, UserInterface $user = NULL) {
54 $file = file_save_data($data, NULL, NULL);
58 $file->setOwner($user);
61 $file->setOwner($this->adminUser);
63 // Change the file status to be temporary.
64 $file->setTemporary();
73 * Tests upload and remove buttons for a single-valued File field.
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);
81 $test_file = $this->getTestFile('text');
83 foreach (['nojs', 'js'] as $type) {
84 // Create a new node with the uploaded file and ensure it got uploaded
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.');
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.');
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.');
103 // "Click" the remove button (emulating either a nojs or js submission).
106 $this->drupalPostForm(NULL, [], t('Remove'));
109 $button = $this->xpath('//input[@type="submit" and @value="' . t('Remove') . '"]');
110 $this->drupalPostAjaxForm(NULL, [], [(string) $button[0]['name'] => (string) $button[0]['value']]);
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.');
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.');
131 * Tests upload and remove buttons for multiple multi-valued File fields.
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
142 $field_name = 'test_file_field_1';
143 $field_name2 = 'test_file_field_2';
145 $this->createFileField($field_name, 'node', $type_name, ['cardinality' => $cardinality]);
146 $this->createFileField($field_name2, 'node', $type_name, ['cardinality' => $cardinality]);
148 $test_file = $this->getTestFile('text');
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.
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'));
168 $this->assertNoFieldByXpath('//input[@type="submit"]', t('Upload'), 'After uploading 3 files for each field, the "Upload" button is no longer displayed.');
170 $num_expected_remove_buttons = 6;
172 foreach ([$field_name, $field_name2] as $current_field_name) {
173 // How many uploaded files for the current field are remaining.
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;
193 $this->assertIdentical((string) $button['name'], $check_field_name . '_' . $key . '_remove_button');
196 // "Click" the remove button (emulating either a nojs or js submission).
197 $button_name = $current_field_name . '_' . $delta . '_remove_button';
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';
212 $this->drupalPostForm(NULL, [], t('Remove'));
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')]);
220 $num_expected_remove_buttons--;
223 // Ensure an "Upload" button for the current field is displayed with the
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]));
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]));
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]));
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);
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.');
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.');
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);
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())),
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.');
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,
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.');
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.');
286 // Try to upload more files than allowed, new node.
287 $upload_files[] = $test_file;
288 $this->uploadNodeFiles($upload_files, $field_name, $type_name);
291 '%field' => $field_name,
292 '@max' => $cardinality,
293 '@count' => count($upload_files),
294 '%list' => $test_file->getFileName(),
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));
300 * Tests a file field with a "Private files" upload destination setting.
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']);
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();
313 $test_file = $this->getTestFile('text');
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.');
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.');
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.');
333 // Delete node and confirm that setting could be changed.
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.');
340 * Tests that download restrictions on private files work on comments.
342 public function testPrivateFileComment() {
343 $user = $this->drupalCreateUser(['access comments']);
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']);
349 // Revoke access comments permission from anon user, grant post to
351 user_role_revoke_permissions(RoleInterface::ANONYMOUS_ID, ['access comments']);
352 user_role_grant_permissions(RoleInterface::AUTHENTICATED_ID, ['post comments', 'skip comment approval']);
354 // Create a new field.
355 $this->addDefaultCommentField('node', 'article');
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);
362 // Manually clear cache on the tester side.
363 \Drupal::entityManager()->clearCachedFieldDefinitions();
367 'title[0][value]' => $this->randomMachineName(),
369 $this->drupalPostForm('node/add/article', $edit, t('Save'));
370 $node = $this->drupalGetNodeByTitle($edit['title[0][value]']);
372 // Add a comment with a file.
373 $text_file = $this->getTestFile('text');
375 'files[field_' . $name . '_' . 0 . ']' => \Drupal::service('file_system')->realpath($text_file->getFileUri()),
376 'comment_body[0][value]' => $comment_body = $this->randomMachineName(),
378 $this->drupalPostForm('node/' . $node->id(), $edit, t('Save'));
380 // Get the comment ID.
381 preg_match('/comment-([0-9]+)/', $this->getUrl(), $matches);
384 // Log in as normal user.
385 $this->drupalLogin($user);
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.');
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.');
402 $this->drupalLogin($this->adminUser);
403 $edit = ['status[value]' => FALSE];
404 $this->drupalPostForm('node/' . $node->id() . '/edit', $edit, t('Save'));
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.');
413 * Tests validation with the Upload button.
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']);
421 foreach (['nojs', 'js'] as $type) {
422 // Create node and prepare files for upload.
423 $node = $this->drupalCreateNode(['type' => 'article']);
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]';
430 // Upload file with incorrect extension, check for validation error.
431 $edit[$name] = \Drupal::service('file_system')->realpath($test_file_image->getFileUri());
434 $this->drupalPostForm(NULL, $edit, t('Upload'));
437 $button = $this->xpath('//input[@type="submit" and @value="' . t('Upload') . '"]');
438 $this->drupalPostAjaxForm(NULL, $edit, [(string) $button[0]['name'] => (string) $button[0]['value']]);
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]));
444 // Upload file with correct extension, check that error message is removed.
445 $edit[$name] = \Drupal::service('file_system')->realpath($test_file_text->getFileUri());
448 $this->drupalPostForm(NULL, $edit, t('Upload'));
451 $button = $this->xpath('//input[@type="submit" and @value="' . t('Upload') . '"]');
452 $this->drupalPostAjaxForm(NULL, $edit, [(string) $button[0]['name'] => (string) $button[0]['value']]);
455 $this->assertNoRaw($error_message, t('Validation error removed when file with correct extension uploaded (JSMode=%type).', ['%type' => $type]));
460 * Tests file widget element.
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";
469 $this->drupalGet('node/add/article');
471 $elements = $this->xpath($xpath);
473 // If the field has no item, the table should not be visible.
474 $this->assertIdentical(count($elements), 0);
477 $edit['files[' . $field_name . '_0][]'] = $this->container->get('file_system')->realpath($file->getFileUri());
478 $this->drupalPostAjaxForm(NULL, $edit, "{$field_name}_0_upload_button");
480 $elements = $this->xpath($xpath);
482 // If the field has at least a item, the table should be visible.
483 $this->assertIdentical(count($elements), 1);
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...');
493 * Tests exploiting the temporary file removal of another user using fid.
495 public function testTemporaryFileRemovalExploit() {
496 // Create a victim user.
497 $victim_user = $this->drupalCreateUser();
499 // Create an attacker user.
500 $attacker_user = $this->drupalCreateUser([
502 'create article content',
503 'edit any article content',
506 // Log in as the attacker user.
507 $this->drupalLogin($attacker_user);
509 // Perform tests using the newly created users.
510 $this->doTestTemporaryFileRemovalExploit($victim_user, $attacker_user);
514 * Tests exploiting the temporary file removal for anonymous users using fid.
516 public function testTemporaryFileRemovalExploitAnonymous() {
517 // Set up an anonymous victim user.
518 $victim_user = User::getAnonymousUser();
520 // Set up an anonymous attacker user.
521 $attacker_user = User::getAnonymousUser();
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,
530 // Log out so as to be the anonymous attacker user.
531 $this->drupalLogout();
533 // Perform tests using the newly set up anonymous users.
534 $this->doTestTemporaryFileRemovalExploit($victim_user, $attacker_user);
538 * Helper for testing exploiting the temporary file removal using fid.
540 * @param \Drupal\user\UserInterface $victim_user
542 * @param \Drupal\user\UserInterface $attacker_user
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);
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
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.');
561 // Have attacker create a new node with a different uploaded file and
562 // ensure it got uploaded successfully.
564 'title[0][value]' => $type . '-title' ,
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]']);
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.');
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.');
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'));
587 $this->drupalPostForm(NULL, [$field_name . '[0][fids]' => (string) $victim_tmp_file->id()], 'Remove');
591 $this->drupalPostAjaxForm(NULL, [$field_name . '[0][fids]' => (string) $victim_tmp_file->id()], ["{$field_name}_0_remove_button" => 'Remove']);
595 // The victim's temporary file should not be removed by the attacker's
597 $this->assertFileExists($victim_tmp_file);