CsrfTokenRaceTest.php 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. <?php
  2. namespace Drupal\FunctionalJavascriptTests\Core;
  3. use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
  4. /**
  5. * Test race condition for CSRF tokens for simultaneous requests.
  6. *
  7. * @group Session
  8. */
  9. class CsrfTokenRaceTest extends WebDriverTestBase {
  10. /**
  11. * {@inheritdoc}
  12. */
  13. protected static $modules = ['csrf_race_test'];
  14. /**
  15. * {@inheritdoc}
  16. */
  17. protected $defaultTheme = 'stark';
  18. /**
  19. * Test race condition for CSRF tokens for simultaneous requests.
  20. */
  21. public function testCsrfRace() {
  22. $user = $this->createUser(['access content']);
  23. $this->drupalLogin($user);
  24. $this->drupalGet('/csrf_race/test');
  25. $script = '';
  26. // Delay the request processing of the first request by one second through
  27. // the request parameter, which will simulate the concurrent processing
  28. // of both requests.
  29. foreach ([1, 0] as $i) {
  30. $script .= <<<EOT
  31. jQuery.ajax({
  32. url: "$this->baseUrl/csrf_race/get_csrf_token/$i",
  33. method: "GET",
  34. headers: {
  35. "Content-Type": "application/json"
  36. },
  37. success: function(response) {
  38. jQuery('body').append("<p class='csrf$i'></p>");
  39. jQuery('.csrf$i').html(response);
  40. },
  41. error: function() {
  42. jQuery('body').append('Nothing');
  43. }
  44. });
  45. EOT;
  46. }
  47. $this->getSession()->getDriver()->executeScript($script);
  48. $token0 = $this->assertSession()->waitForElement('css', '.csrf0')->getHtml();
  49. $token1 = $this->assertSession()->waitForElement('css', '.csrf1')->getHtml();
  50. $this->assertNotNull($token0);
  51. $this->assertNotNull($token1);
  52. $this->assertEqual($token0, $token1);
  53. }
  54. }