You are here

public function CaptchaSessionReuseAttackTestCase::testCaptchaSessionReuseAttackDetectionOnNodeForm in CAPTCHA 8

Test captcha attach detection on node form.

File

tests/src/Functional/CaptchaSessionReuseAttackTestCase.php, line 73

Class

CaptchaSessionReuseAttackTestCase
Tests CAPTCHA session reusing.

Namespace

Drupal\Tests\captcha\Functional

Code

public function testCaptchaSessionReuseAttackDetectionOnNodeForm() {

  // Set CAPTCHA on page form.
  captcha_set_form_id_setting('node_page_form', 'captcha/Test');
  $this
    ->config('captcha.settings')
    ->set('persistence', CAPTCHA_PERSISTENCE_SKIP_ONCE_SUCCESSFUL_PER_FORM_INSTANCE)
    ->save();

  // Log in as normal user.
  $this
    ->drupalLogin($this->normalUser);

  // Go to node add form.
  $this
    ->drupalGet('node/add/page');
  $this
    ->assertCaptchaPresence(TRUE);

  // Get CAPTCHA session ID and solution of the challenge.
  $captcha_sid = $this
    ->getCaptchaSidFromForm();
  $captcha_token = $this
    ->getCaptchaTokenFromForm();
  $solution = "Test 123";

  // Page settings to post, with correct CAPTCHA answer.
  $edit = $this
    ->getNodeFormValues();
  $edit['captcha_response'] = $solution;

  // Preview the node.
  $this
    ->submitForm($edit, 'Preview');

  // Answer should be accepted.
  $this
    ->assertCaptchaResponseAccepted();

  // Check that there is no CAPTCHA after preview.
  $this
    ->assertCaptchaPresence(FALSE);

  // Go to node add form again.
  $this
    ->drupalGet('node/add/page');
  $this
    ->assertCaptchaPresence(TRUE);

  // Post a new node, reusing the previous CAPTCHA session.
  $edit = $this
    ->getNodeFormValues();
  $this
    ->assertSession()
    ->hiddenFieldExists("captcha_sid")
    ->setValue((string) $captcha_sid);
  $this
    ->assertSession()
    ->hiddenFieldExists("captcha_token")
    ->setValue((string) $captcha_token);
  $edit['captcha_response'] = $solution;
  $this
    ->submitForm($edit, 'Preview');

  // CAPTCHA session reuse attack should be detected.
  $this
    ->assertCaptchaSessionIdReuseAttackDetection();

  // There should be a CAPTCHA.
  $this
    ->assertCaptchaPresence(TRUE);
}