You are here

public function CsrfTokenRaceTest::testCsrfRace in Drupal 8

Same name and namespace in other branches
  1. 9 core/tests/Drupal/FunctionalJavascriptTests/Core/CsrfTokenRaceTest.php \Drupal\FunctionalJavascriptTests\Core\CsrfTokenRaceTest::testCsrfRace()
  2. 10 core/tests/Drupal/FunctionalJavascriptTests/Core/CsrfTokenRaceTest.php \Drupal\FunctionalJavascriptTests\Core\CsrfTokenRaceTest::testCsrfRace()

Test race condition for CSRF tokens for simultaneous requests.

File

core/tests/Drupal/FunctionalJavascriptTests/Core/CsrfTokenRaceTest.php, line 27

Class

CsrfTokenRaceTest
Test race condition for CSRF tokens for simultaneous requests.

Namespace

Drupal\FunctionalJavascriptTests\Core

Code

public function testCsrfRace() {
  $user = $this
    ->createUser([
    'access content',
  ]);
  $this
    ->drupalLogin($user);
  $this
    ->drupalGet('/csrf_race/test');
  $script = '';

  // Delay the request processing of the first request by one second through
  // the request parameter, which will simulate the concurrent processing
  // of both requests.
  foreach ([
    1,
    0,
  ] as $i) {
    $script .= <<<EOT
      jQuery.ajax({
        url: "{<span class="php-variable">$this</span>-&gt;<span class="php-function-or-constant property member-of-self">baseUrl</span>}/csrf_race/get_csrf_token/{<span class="php-variable">$i</span>}",
        method: "GET",
        headers: {
          "Content-Type": "application/json"
        },
        success: function(response) {
          jQuery('body').append("<p class='csrf{<span class="php-variable">$i</span>}'></p>");
          jQuery('.csrf{<span class="php-variable">$i</span>}').html(response);
        },
        error: function() {
          jQuery('body').append('Nothing');
        }
      });
EOT;
  }
  $this
    ->getSession()
    ->getDriver()
    ->executeScript($script);
  $token0 = $this
    ->assertSession()
    ->waitForElement('css', '.csrf0')
    ->getHtml();
  $token1 = $this
    ->assertSession()
    ->waitForElement('css', '.csrf1')
    ->getHtml();
  $this
    ->assertNotNull($token0);
  $this
    ->assertNotNull($token1);
  $this
    ->assertEqual($token0, $token1);
}