function SaveUploadFormTest::testHandleDangerousFile
Same name in other branches
- 9 core/modules/file/tests/src/Functional/SaveUploadFormTest.php \Drupal\Tests\file\Functional\SaveUploadFormTest::testHandleDangerousFile()
- 10 core/modules/file/tests/src/Functional/SaveUploadFormTest.php \Drupal\Tests\file\Functional\SaveUploadFormTest::testHandleDangerousFile()
- 11.x core/modules/file/tests/src/Functional/SaveUploadFormTest.php \Drupal\Tests\file\Functional\SaveUploadFormTest::testHandleDangerousFile()
Tests dangerous file handling.
File
-
core/
modules/ file/ tests/ src/ Functional/ SaveUploadFormTest.php, line 215
Class
- SaveUploadFormTest
- Tests the _file_save_upload_from_form() function.
Namespace
Drupal\Tests\file\FunctionalCode
public function testHandleDangerousFile() {
$config = $this->config('system.file');
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
// Allow the .php extension and make sure it gets renamed to .txt for
// safety. Also check to make sure its MIME type was changed.
$edit = [
'file_test_replace' => FileSystemInterface::EXISTS_REPLACE,
'files[file_test_upload][]' => $file_system->realpath($this->phpfile->uri),
'is_image_file' => FALSE,
'extensions' => 'php',
];
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertSession()
->statusCodeEquals(200);
$message = t('For security reasons, your upload has been renamed to') . ' <em class="placeholder">' . $this->phpfile->filename . '_.txt' . '</em>';
$this->assertRaw($message, 'Dangerous file was renamed.');
$this->assertRaw(t('File MIME type is text/plain.'), "Dangerous file's MIME type was changed.");
$this->assertRaw(t('You WIN!'), 'Found the success message.');
// Check that the correct hooks were called.
$this->assertFileHooksCalled([
'validate',
'insert',
]);
// Ensure dangerous files are not renamed when insecure uploads is TRUE.
// Turn on insecure uploads.
$config->set('allow_insecure_uploads', 1)
->save();
// Reset the hook counters.
file_test_reset();
$this->drupalPostForm('file-test/save_upload_from_form_test', $edit, t('Submit'));
$this->assertSession()
->statusCodeEquals(200);
$this->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
$this->assertRaw(t('File name is @filename', [
'@filename' => $this->phpfile->filename,
]), 'Dangerous file was not renamed when insecure uploads is TRUE.');
$this->assertRaw(t('You WIN!'), 'Found the success message.');
// Check that the correct hooks were called.
$this->assertFileHooksCalled([
'validate',
'insert',
]);
// Turn off insecure uploads.
$config->set('allow_insecure_uploads', 0)
->save();
}
Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.