UserLoginHttpTest.php 12.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356
<?php

namespace Drupal\Tests\user\Functional;

use Drupal\Core\Flood\DatabaseBackend;
use Drupal\Core\Url;
use Drupal\Tests\BrowserTestBase;
use Drupal\user\Controller\UserAuthenticationController;
use GuzzleHttp\Cookie\CookieJar;
use Psr\Http\Message\ResponseInterface;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Encoder\XmlEncoder;
use Symfony\Component\Serializer\Serializer;

/**
 * Tests login via direct HTTP.
 *
 * @group user
 */
class UserLoginHttpTest extends BrowserTestBase {

  /**
   * The cookie jar.
   *
   * @var \GuzzleHttp\Cookie\CookieJar
   */
  protected $cookies;

  /**
   * The serializer.
   *
   * @var \Symfony\Component\Serializer\Serializer
   */
  protected $serializer;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->cookies = new CookieJar();
    $encoders = [new JsonEncoder(), new XmlEncoder()];
    $this->serializer = new Serializer([], $encoders);
  }

  /**
   * Executes a login HTTP request.
   *
   * @param string $name
   *   The username.
   * @param string $pass
   *   The user password.
   * @param string $format
   *   The format to use to make the request.
   *
   * @return \Psr\Http\Message\ResponseInterface The HTTP response.
   *   The HTTP response.
   */
  protected function loginRequest($name, $pass, $format = 'json') {
    $user_login_url = Url::fromRoute('user.login.http')
      ->setRouteParameter('_format', $format)
      ->setAbsolute();

    $request_body = [];
    if (isset($name)) {
      $request_body['name'] = $name;
    }
    if (isset($pass)) {
      $request_body['pass'] = $pass;
    }

    $result = \Drupal::httpClient()->post($user_login_url->toString(), [
      'body' => $this->serializer->encode($request_body, $format),
      'headers' => [
        'Accept' => "application/$format",
      ],
      'http_errors' => FALSE,
      'cookies' => $this->cookies,
    ]);
    return $result;
  }

  /**
   * Tests user session life cycle.
   */
  public function testLogin() {
    $client = \Drupal::httpClient();
    foreach ([FALSE, TRUE] as $serialization_enabled_option) {
      if ($serialization_enabled_option) {
        /** @var \Drupal\Core\Extension\ModuleInstaller $module_installer */
        $module_installer = $this->container->get('module_installer');
        $module_installer->install(['serialization']);
        $formats = ['json', 'xml'];
      }
      else {
        // Without the serialization module only JSON is supported.
        $formats = ['json'];
      }
      foreach ($formats as $format) {
        // Create new user for each iteration to reset flood.
        // Grant the user administer users permissions to they can see the
        // 'roles' field.
        $account = $this->drupalCreateUser(['administer users']);
        $name = $account->getUsername();
        $pass = $account->passRaw;

        $user_login_status_url = Url::fromRoute('user.login_status.http');
        $user_login_status_url->setRouteParameter('_format', $format);
        $user_login_status_url->setAbsolute();

        $response = $client->get($user_login_status_url->toString());
        $this->assertHttpResponse($response, 200, UserAuthenticationController::LOGGED_OUT);

        // Flooded.
        $this->config('user.flood')
          ->set('user_limit', 3)
          ->save();

        $response = $this->loginRequest($name, 'wrong-pass', $format);
        $this->assertHttpResponseWithMessage($response, 400, 'Sorry, unrecognized username or password.', $format);

        $response = $this->loginRequest($name, 'wrong-pass', $format);
        $this->assertHttpResponseWithMessage($response, 400, 'Sorry, unrecognized username or password.', $format);

        $response = $this->loginRequest($name, 'wrong-pass', $format);
        $this->assertHttpResponseWithMessage($response, 400, 'Sorry, unrecognized username or password.', $format);

        $response = $this->loginRequest($name, 'wrong-pass', $format);
        $this->assertHttpResponseWithMessage($response, 403, 'Too many failed login attempts from your IP address. This IP address is temporarily blocked.', $format);

        // After testing the flood control we can increase the limit.
        $this->config('user.flood')
          ->set('user_limit', 100)
          ->save();

        $response = $this->loginRequest(NULL, NULL, $format);
        $this->assertHttpResponseWithMessage($response, 400, 'Missing credentials.', $format);

        $response = $this->loginRequest(NULL, $pass, $format);
        $this->assertHttpResponseWithMessage($response, 400, 'Missing credentials.name.', $format);

        $response = $this->loginRequest($name, NULL, $format);
        $this->assertHttpResponseWithMessage($response, 400, 'Missing credentials.pass.', $format);

        // Blocked.
        $account
          ->block()
          ->save();

        $response = $this->loginRequest($name, $pass, $format);
        $this->assertHttpResponseWithMessage($response, 400, 'The user has not been activated or is blocked.', $format);

        $account
          ->activate()
          ->save();

        $response = $this->loginRequest($name, 'garbage', $format);
        $this->assertHttpResponseWithMessage($response, 400, 'Sorry, unrecognized username or password.', $format);

        $response = $this->loginRequest('garbage', $pass, $format);
        $this->assertHttpResponseWithMessage($response, 400, 'Sorry, unrecognized username or password.', $format);

        $response = $this->loginRequest($name, $pass, $format);
        $this->assertEquals(200, $response->getStatusCode());
        $result_data = $this->serializer->decode($response->getBody(), $format);
        $this->assertEquals($name, $result_data['current_user']['name']);
        $this->assertEquals($account->id(), $result_data['current_user']['uid']);
        $this->assertEquals($account->getRoles(), $result_data['current_user']['roles']);

        $response = $client->get($user_login_status_url->toString(), ['cookies' => $this->cookies]);
        $this->assertEquals(200, $response->getStatusCode());
        $this->assertEquals(UserAuthenticationController::LOGGED_IN, (string) $response->getBody());

        $response = $this->logoutRequest($format);
        $this->assertEquals(204, $response->getStatusCode());

        $response = $client->get($user_login_status_url->toString(), ['cookies' => $this->cookies]);
        $this->assertHttpResponse($response, 200, UserAuthenticationController::LOGGED_OUT);

        $this->resetFlood();
      }
    }
  }

  /**
   * Gets a value for a given key from the response.
   *
   * @param \Psr\Http\Message\ResponseInterface $response
   *   The response object.
   * @param string $key
   *   The key for the value.
   * @param string $format
   *   The encoded format.
   *
   * @return mixed
   *   The value for the key.
   */
  protected function getResultValue(ResponseInterface $response, $key, $format) {
    $decoded = $this->serializer->decode((string) $response->getBody(), $format);
    if (is_array($decoded)) {
      return $decoded[$key];
    }
    else {
      return $decoded->{$key};
    }
  }

  /**
   * Resets all flood entries.
   */
  protected function resetFlood() {
    $this->container->get('database')->delete(DatabaseBackend::TABLE_NAME)->execute();
  }

  /**
   * Tests the global login flood control.
   *
   * @see \Drupal\basic_auth\Tests\Authentication\BasicAuthTest::testGlobalLoginFloodControl
   * @see \Drupal\user\Tests\UserLoginTest::testGlobalLoginFloodControl
   */
  public function testGlobalLoginFloodControl() {
    $this->config('user.flood')
      ->set('ip_limit', 2)
      // Set a high per-user limit out so that it is not relevant in the test.
      ->set('user_limit', 4000)
      ->save();

    $user = $this->drupalCreateUser([]);
    $incorrect_user = clone $user;
    $incorrect_user->passRaw .= 'incorrect';

    // Try 2 failed logins.
    for ($i = 0; $i < 2; $i++) {
      $response = $this->loginRequest($incorrect_user->getUsername(), $incorrect_user->passRaw);
      $this->assertEquals('400', $response->getStatusCode());
    }

    // IP limit has reached to its limit. Even valid user credentials will fail.
    $response = $this->loginRequest($user->getUsername(), $user->passRaw);
    $this->assertHttpResponseWithMessage($response, '403', 'Access is blocked because of IP based flood prevention.');
  }

  /**
   * Checks a response for status code and body.
   *
   * @param \Psr\Http\Message\ResponseInterface $response
   *   The response object.
   * @param int $expected_code
   *   The expected status code.
   * @param mixed $expected_body
   *   The expected response body.
   */
  protected function assertHttpResponse(ResponseInterface $response, $expected_code, $expected_body) {
    $this->assertEquals($expected_code, $response->getStatusCode());
    $this->assertEquals($expected_body, (string) $response->getBody());
  }

  /**
   * Checks a response for status code and message.
   *
   * @param \Psr\Http\Message\ResponseInterface $response
   *   The response object.
   * @param int $expected_code
   *   The expected status code.
   * @param string $expected_message
   *   The expected message encoded in response.
   * @param string $format
   *   The format that the response is encoded in.
   */
  protected function assertHttpResponseWithMessage(ResponseInterface $response, $expected_code, $expected_message, $format = 'json') {
    $this->assertEquals($expected_code, $response->getStatusCode());
    $this->assertEquals($expected_message, $this->getResultValue($response, 'message', $format));
  }

  /**
   * Test the per-user login flood control.
   *
   * @see \Drupal\user\Tests\UserLoginTest::testPerUserLoginFloodControl
   * @see \Drupal\basic_auth\Tests\Authentication\BasicAuthTest::testPerUserLoginFloodControl
   */
  public function testPerUserLoginFloodControl() {
    foreach ([TRUE, FALSE] as $uid_only_setting) {
      $this->config('user.flood')
        // Set a high global limit out so that it is not relevant in the test.
        ->set('ip_limit', 4000)
        ->set('user_limit', 3)
        ->set('uid_only', $uid_only_setting)
        ->save();

      $user1 = $this->drupalCreateUser([]);
      $incorrect_user1 = clone $user1;
      $incorrect_user1->passRaw .= 'incorrect';

      $user2 = $this->drupalCreateUser([]);

      // Try 2 failed logins.
      for ($i = 0; $i < 2; $i++) {
        $response = $this->loginRequest($incorrect_user1->getUsername(), $incorrect_user1->passRaw);
        $this->assertHttpResponseWithMessage($response, 400, 'Sorry, unrecognized username or password.');
      }

      // A successful login will reset the per-user flood control count.
      $this->loginRequest($user1->getUsername(), $user1->passRaw);
      $this->logoutRequest();

      // Try 3 failed logins for user 1, they will not trigger flood control.
      for ($i = 0; $i < 3; $i++) {
        $response = $this->loginRequest($incorrect_user1->getUsername(), $incorrect_user1->passRaw);
        $this->assertHttpResponseWithMessage($response, 400, 'Sorry, unrecognized username or password.');
      }

      // Try one successful attempt for user 2, it should not trigger any
      // flood control.
      $this->drupalLogin($user2);
      $this->drupalLogout();

      // Try one more attempt for user 1, it should be rejected, even if the
      // correct password has been used.
      $response = $this->loginRequest($user1->getUsername(), $user1->passRaw);
      // Depending on the uid_only setting the error message will be different.
      if ($uid_only_setting) {
        $excepted_message = 'There have been more than 3 failed login attempts for this account. It is temporarily blocked. Try again later or request a new password.';
      }
      else {
        $excepted_message = 'Too many failed login attempts from your IP address. This IP address is temporarily blocked.';
      }
      $this->assertHttpResponseWithMessage($response, 403, $excepted_message);
    }

  }

  /**
   * Executes a logout HTTP request.
   *
   * @param string $format
   *   The format to use to make the request.
   *
   * @return \Psr\Http\Message\ResponseInterface The HTTP response.
   *   The HTTP response.
   */
  protected function logoutRequest($format = 'json') {
    $client = $this->container->get('http_client');
    $user_logout_url = Url::fromRoute('user.logout.http')
      ->setRouteParameter('_format', $format)
      ->setAbsolute();
    $response = $client->post($user_logout_url->toString(), [
      'headers' => [
        'Accept' => "application/$format",
      ],
      'http_errors' => FALSE,
      'cookies' => $this->cookies,
    ]);
    return $response;
  }

}