You are here

public function LoginSecurityUserBlockingTest::testThresholdNotify in Login Security 8

Test threshold notify functionality.

File

src/Tests/LoginSecurityUserBlockingTest.php, line 127

Class

LoginSecurityUserBlockingTest
Test Login Security's user-blocking restrictions and default messages.

Namespace

Drupal\login_security\Tests

Code

public function testThresholdNotify() {

  // Set notify threshold to 5, and user locking to 5.
  \Drupal::configFactory()
    ->getEditable('login_security.settings')
    ->set('user_wrong_count', 5)
    ->set('activity_threshold', 5)
    ->save();

  // Attempt 10 bad logins. Since the user will be locked out after 5, only
  // a single log message should be set, and an attack should not be
  // detected.
  for ($i = 0; $i < 10; $i++) {
    $login = [
      'name' => $this->badUsers[0]
        ->getAccountName(),
      'pass' => 'bad_password_' . $i,
    ];
    $this
      ->drupalPostForm('user', $login, t('Log in'));
  }

  // Ensure a log message has been set.
  $logs = $this
    ->getLogMessages();
  $this
    ->assertEqual(count($logs), 1, '1 event was logged.');
  $log = array_pop($logs);
  $this
    ->assertBlockedUser($log, $this->badUsers[0]
    ->getAccountName());
  db_truncate('watchdog')
    ->execute();

  // Run failed logins as second user to trigger an attack warning.
  for ($i = 0; $i < 10; $i++) {
    $login = [
      'name' => $this->badUsers[1]
        ->getAccountName(),
      'pass' => 'bad_password_' . $i,
    ];
    $this
      ->drupalPostForm('user', $login, t('Log in'));
  }
  $logs = $this
    ->getLogMessages();

  // 2 logs should be generated.
  $this
    ->assertEqual(count($logs), 2, '2 events were logged.');

  // First log should be the ongoing attack, triggered on attempt after the
  // threshold.
  $log = array_shift($logs);
  $variables = [
    '@activity_threshold' => 5,
    '@tracking_current_count' => 6,
  ];
  $expected = SafeMarkup::format('Ongoing attack detected: Suspicious activity detected in login form submissions. Too many invalid login attempts threshold reached: currently @tracking_current_count events are tracked, and threshold is configured for @activity_threshold attempts.', $variables);
  $this
    ->assertEqual(SafeMarkup::format($log->message, unserialize($log->variables)), $expected);
  $this
    ->assertEqual($log->severity, RfcLogLevel::WARNING, 'The logged alert was of severity "Warning".');

  // Second log should be a blocked user.
  $log = array_shift($logs);
  $this
    ->assertBlockedUser($log, $this->badUsers[1]
    ->getAccountName());
}