You are here

function SaveUploadTest::testHandleDangerousFile in Zircon Profile 8

Same name and namespace in other branches
  1. 8.0 core/modules/file/src/Tests/SaveUploadTest.php \Drupal\file\Tests\SaveUploadTest::testHandleDangerousFile()

Test dangerous file handling.

File

core/modules/file/src/Tests/SaveUploadTest.php, line 193
Contains \Drupal\file\Tests\SaveUploadTest.

Class

SaveUploadTest
Tests the file_save_upload() function.

Namespace

Drupal\file\Tests

Code

function testHandleDangerousFile() {
  $config = $this
    ->config('system.file');

  // 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 = array(
    'file_test_replace' => FILE_EXISTS_REPLACE,
    'files[file_test_upload]' => drupal_realpath($this->phpfile->uri),
    'is_image_file' => FALSE,
    'extensions' => 'php',
  );
  $this
    ->drupalPostForm('file-test/upload', $edit, t('Submit'));
  $this
    ->assertResponse(200, 'Received a 200 response for posted test file.');
  $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(array(
    '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/upload', $edit, t('Submit'));
  $this
    ->assertResponse(200, 'Received a 200 response for posted test file.');
  $this
    ->assertNoRaw(t('For security reasons, your upload has been renamed'), 'Found no security message.');
  $this
    ->assertRaw(t('File name is @filename', array(
    '@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(array(
    'validate',
    'insert',
  ));

  // Turn off insecure uploads.
  $config
    ->set('allow_insecure_uploads', 0)
    ->save();
}