function SessionTest::testAnonymousSessionFixation

Tests that an invalid session ID in the cookie is rejected.

@covers \Drupal\Core\Session\SessionManager::start

File

core/modules/system/tests/src/Functional/Session/SessionTest.php, line 187

Class

SessionTest
Drupal session handling tests.

Namespace

Drupal\Tests\system\Functional\Session

Code

public function testAnonymousSessionFixation() : void {
    $mink = $this->getSession();
    $connection = Database::getConnection();
    // Initialize a session for anonymous user.
    $this->drupalGet('session-test/set/foo');
    // Switch browser cookie to arbitrary session_id.
    $session_cookie_name = $this->getSessionName();
    $initial_session_cookie_value = $mink->getCookie($session_cookie_name);
    $mink->restart();
    $this->initFrontPage();
    // Session restart always resets all the cookies by design, so we
    // set an arbitrary session_id in the cookie for the next request.
    $invalid_session_cookie_value = bin2hex($this->randomMachineName(13));
    $mink->setCookie($session_cookie_name, $invalid_session_cookie_value);
    // Make another request.
    sleep(1);
    $this->drupalGet('session-test/set/bar');
    // Check returned cookie value.
    $returned_session_cookie_value = $mink->getCookie($session_cookie_name);
    // The backend should reject $invalid_session_cookie_value and return a
    // new session_id that's different from both the first and the invalid
    // SIDs.
    $this->assertNotEquals($initial_session_cookie_value, $returned_session_cookie_value, 'Returned session ID is not equal to initial session ID');
    $this->assertNotEquals($invalid_session_cookie_value, $returned_session_cookie_value, 'Returned session ID is not equal to invalid session ID');
    // Check that invalid SID does not exist in database.
    $this->assertEmpty($connection->select('sessions', 's')
        ->fields('s', [
        'timestamp',
    ])
        ->condition('sid', Crypt::hashBase64($invalid_session_cookie_value))
        ->execute()
        ->fetchField(), 'Invalid session ID is not in database');
    // Check that returned SID does exist in database.
    $this->assertNotEmpty($connection->select('sessions', 's')
        ->fields('s', [
        'timestamp',
    ])
        ->condition('sid', Crypt::hashBase64($returned_session_cookie_value))
        ->execute()
        ->fetchField(), 'Returned session ID is in database');
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.