diff --git a/core/includes/install.core.inc b/core/includes/install.core.inc index 34e68241ab..200f69eb66 100644 --- a/core/includes/install.core.inc +++ b/core/includes/install.core.inc @@ -1557,6 +1557,8 @@ function install_bootstrap_full() { $session = \Drupal::service('session'); \Drupal::request()->setSession($session); $session->start(); + // Ensure the session is maintained throughout the install. + $_SESSION['_drupal_installing'] = TRUE; } /** diff --git a/core/lib/Drupal/Core/Cache/Context/SessionCacheContext.php b/core/lib/Drupal/Core/Cache/Context/SessionCacheContext.php index bccd0f01a4..40a48f87f9 100644 --- a/core/lib/Drupal/Core/Cache/Context/SessionCacheContext.php +++ b/core/lib/Drupal/Core/Cache/Context/SessionCacheContext.php @@ -24,7 +24,11 @@ public static function getLabel() { public function getContext() { $request = $this->requestStack->getCurrentRequest(); if ($request->hasSession()) { - return Crypt::hashBase64($request->getSession()->getId()); + $id = $request->getSession()->getId(); + if (!$id) { + throw new Exception('No session ID'); + } + return Crypt::hashBase64($id); } return 'none'; } diff --git a/core/lib/Drupal/Core/Session/MetadataBag.php b/core/lib/Drupal/Core/Session/MetadataBag.php index ee0fbd4855..dad5dabdf1 100644 --- a/core/lib/Drupal/Core/Session/MetadataBag.php +++ b/core/lib/Drupal/Core/Session/MetadataBag.php @@ -51,7 +51,8 @@ public function getCsrfTokenSeed() { /** * Clear the CSRF token seed. */ - public function clearCsrfTokenSeed() { + public function stampNew($lifetime = NULL) { + parent::stampNew($lifetime); unset($this->meta[static::CSRF_TOKEN_SEED]); } diff --git a/core/lib/Drupal/Core/Session/SessionManager.php b/core/lib/Drupal/Core/Session/SessionManager.php index 607103109d..0fcb915f25 100644 --- a/core/lib/Drupal/Core/Session/SessionManager.php +++ b/core/lib/Drupal/Core/Session/SessionManager.php @@ -2,7 +2,6 @@ namespace Drupal\Core\Session; -use Drupal\Component\Utility\Crypt; use Drupal\Core\Database\Connection; use Drupal\Core\DependencyInjection\DependencySerializationTrait; use Symfony\Component\HttpFoundation\RequestStack; @@ -119,17 +118,6 @@ public function start() { } if (empty($result)) { - // Randomly generate a session identifier for this request. This is - // necessary because \Drupal\Core\TempStore\SharedTempStoreFactory::get() - // wants to know the future session ID of a lazily started session in - // advance. - // - // @todo: With current versions of PHP there is little reason to generate - // the session id from within application code. Consider using the - // default php session id instead of generating a custom one: - // https://www.drupal.org/node/2238561 - $this->setId(Crypt::randomBytesBase64()); - // Initialize the session global and attach the Symfony session bags. $_SESSION = []; $this->loadSession(); @@ -210,30 +198,7 @@ public function regenerate($destroy = FALSE, $lifetime = NULL) { return; } - // We do not support the optional $destroy and $lifetime parameters as long - // as #2238561 remains open. - if ($destroy || isset($lifetime)) { - throw new \InvalidArgumentException('The optional parameters $destroy and $lifetime of SessionManager::regenerate() are not supported currently'); - } - - if ($this->isStarted()) { - $old_session_id = $this->getId(); - } - session_id(Crypt::randomBytesBase64()); - - $this->getMetadataBag()->clearCsrfTokenSeed(); - - if (isset($old_session_id)) { - $params = session_get_cookie_params(); - $expire = $params['lifetime'] ? REQUEST_TIME + $params['lifetime'] : 0; - setcookie($this->getName(), $this->getId(), $expire, $params['path'], $params['domain'], $params['secure'], $params['httponly']); - $this->migrateStoredSession($old_session_id); - } - - if (!$this->isStarted()) { - // Start the session when it doesn't exist yet. - $this->startNow(); - } + return parent::regenerate($destroy, $lifetime); } /** @@ -324,18 +289,4 @@ protected function getSessionDataMask() { return array_intersect_key($mask, $_SESSION); } - /** - * Migrates the current session to a new session id. - * - * @param string $old_session_id - * The old session ID. The new session ID is $this->getId(). - */ - protected function migrateStoredSession($old_session_id) { - $fields = ['sid' => Crypt::hashBase64($this->getId())]; - $this->connection->update('sessions') - ->fields($fields) - ->condition('sid', Crypt::hashBase64($old_session_id)) - ->execute(); - } - } diff --git a/core/lib/Drupal/Core/TempStore/PrivateTempStore.php b/core/lib/Drupal/Core/TempStore/PrivateTempStore.php index ea7ec3fc37..714021fd30 100644 --- a/core/lib/Drupal/Core/TempStore/PrivateTempStore.php +++ b/core/lib/Drupal/Core/TempStore/PrivateTempStore.php @@ -2,6 +2,7 @@ namespace Drupal\Core\TempStore; +use Drupal\Component\Utility\Crypt; use Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface; use Drupal\Core\Lock\LockBackendInterface; use Drupal\Core\Session\AccountProxyInterface; @@ -117,17 +118,16 @@ public function get($key) { * Thrown when a lock for the backend storage could not be acquired. */ public function set($key, $value) { - // Ensure that an anonymous user has a session created for them, as - // otherwise subsequent page loads will not be able to retrieve their - // tempstore data. if ($this->currentUser->isAnonymous()) { - // @todo when https://www.drupal.org/node/2865991 is resolved, use force - // start session API rather than setting an arbitrary value directly. + // Ensure that an anonymous user has a session created for them, as + // otherwise subsequent page loads will not be able to retrieve their + // tempstore data. Note this has to be done before the key is created as + // the owner is used in key creation. $this->startSession(); - $this->requestStack - ->getCurrentRequest() - ->getSession() - ->set('core.tempstore.private', TRUE); + $session = $this->requestStack->getCurrentRequest()->getSession(); + if (!$session->has('core.tempstore.private.owner')) { + $session->set('core.tempstore.private.owner', Crypt::randomBytesBase64()); + } } $key = $this->createkey($key); @@ -222,8 +222,10 @@ protected function createkey($key) { protected function getOwner() { $owner = $this->currentUser->id(); if ($this->currentUser->isAnonymous()) { + // Check to see if an owner key exists in the session. $this->startSession(); - $owner = $this->requestStack->getCurrentRequest()->getSession()->getId(); + $session = $this->requestStack->getCurrentRequest()->getSession(); + $owner = $session->get('core.tempstore.private.owner'); } return $owner; } diff --git a/core/lib/Drupal/Core/TempStore/SharedTempStore.php b/core/lib/Drupal/Core/TempStore/SharedTempStore.php index c131a80fd2..aeaa2d811b 100644 --- a/core/lib/Drupal/Core/TempStore/SharedTempStore.php +++ b/core/lib/Drupal/Core/TempStore/SharedTempStore.php @@ -4,6 +4,7 @@ use Drupal\Core\KeyValueStore\KeyValueStoreExpirableInterface; use Drupal\Core\Lock\LockBackendInterface; +use Drupal\Core\Session\AccountProxyInterface; use Symfony\Component\HttpFoundation\RequestStack; /** @@ -74,6 +75,13 @@ class SharedTempStore { */ protected $expire; + /** + * The current user. + * + * @var \Drupal\Core\Session\AccountProxyInterface + */ + protected $currentUser; + /** * Constructs a new object for accessing data from a key/value store. * @@ -87,14 +95,28 @@ class SharedTempStore { * The owner key to store along with the data (e.g. a user or session ID). * @param \Symfony\Component\HttpFoundation\RequestStack $request_stack * The request stack. + * @param \Drupal\Core\Session\AccountProxyInterface|null $current_user + * The current user. * @param int $expire * The time to live for items, in seconds. */ - public function __construct(KeyValueStoreExpirableInterface $storage, LockBackendInterface $lock_backend, $owner, RequestStack $request_stack, $expire = 604800) { + public function __construct(KeyValueStoreExpirableInterface $storage, LockBackendInterface $lock_backend, $owner, RequestStack $request_stack, $current_user = NULL, $expire = 604800) { $this->storage = $storage; $this->lockBackend = $lock_backend; $this->owner = $owner; $this->requestStack = $request_stack; + if ($current_user instanceof AccountProxyInterface) { + $this->currentUser = $current_user; + } + else { + @trigger_error('@todo', E_USER_DEPRECATED); + $this->currentUser = \Drupal::currentUser(); + if (is_int($current_user)) { + // If the $current_user argument is numeric then this object has been + // instantiated with the old constructor signature. + $expire = $current_user; + } + } $this->expire = $expire; } @@ -147,7 +169,11 @@ public function setIfNotExists($key, $value) { 'data' => $value, 'updated' => (int) $this->requestStack->getMasterRequest()->server->get('REQUEST_TIME'), ]; - return $this->storage->setWithExpireIfNotExists($key, $value, $this->expire); + $set = $this->storage->setWithExpireIfNotExists($key, $value, $this->expire); + if ($set) { + $this->ensureAnonymousSession(); + } + return $set; } /** @@ -205,6 +231,7 @@ public function set($key, $value) { 'data' => $value, 'updated' => (int) $this->requestStack->getMasterRequest()->server->get('REQUEST_TIME'), ]; + $this->ensureAnonymousSession(); $this->storage->setWithExpire($key, $value, $this->expire); $this->lockBackend->release($key); } @@ -276,4 +303,15 @@ public function deleteIfOwner($key) { return FALSE; } + /** + * Stores the owner in session if the user is anonymous. + * + * This method should be called when a value is set. + */ + protected function ensureAnonymousSession() { + if ($this->currentUser->isAnonymous()) { + $this->requestStack->getCurrentRequest()->getSession()->set('core.tempstore.shared.owner', $this->owner); + } + } + } diff --git a/core/lib/Drupal/Core/TempStore/SharedTempStoreFactory.php b/core/lib/Drupal/Core/TempStore/SharedTempStoreFactory.php index 90e816a7dd..29745a1769 100644 --- a/core/lib/Drupal/Core/TempStore/SharedTempStoreFactory.php +++ b/core/lib/Drupal/Core/TempStore/SharedTempStoreFactory.php @@ -2,6 +2,7 @@ namespace Drupal\Core\TempStore; +use Drupal\Component\Utility\Crypt; use Drupal\Core\KeyValueStore\KeyValueExpirableFactoryInterface; use Drupal\Core\Lock\LockBackendInterface; use Symfony\Component\HttpFoundation\RequestStack; @@ -75,13 +76,26 @@ public function __construct(KeyValueExpirableFactoryInterface $storage_factory, public function get($collection, $owner = NULL) { // Use the currently authenticated user ID or the active user ID unless // the owner is overridden. + $account = \Drupal::currentUser(); if (!isset($owner)) { - $owner = \Drupal::currentUser()->id() ?: session_id(); + $owner = $account->id(); + if ($account->isAnonymous()) { + $has_session = $this->requestStack + ->getCurrentRequest() + ->hasSession(); + if (!$has_session) { + /** @var \Symfony\Component\HttpFoundation\Session\SessionInterface $session */ + $session = \Drupal::service('session'); + $this->requestStack->getCurrentRequest()->setSession($session); + $session->start(); + } + $owner = $this->requestStack->getCurrentRequest()->getSession()->get('core.tempstore.shared.owner', Crypt::randomBytesBase64()); + } } // Store the data for this collection in the database. $storage = $this->storageFactory->get("tempstore.shared.$collection"); - return new SharedTempStore($storage, $this->lockBackend, $owner, $this->requestStack, $this->expire); + return new SharedTempStore($storage, $this->lockBackend, $owner, $this->requestStack, $account, $this->expire); } } diff --git a/core/modules/user/tests/src/Kernel/TempStoreDatabaseTest.php b/core/modules/user/tests/src/Kernel/TempStoreDatabaseTest.php index 51a3b9f8e7..9e4ea6ed70 100644 --- a/core/modules/user/tests/src/Kernel/TempStoreDatabaseTest.php +++ b/core/modules/user/tests/src/Kernel/TempStoreDatabaseTest.php @@ -73,8 +73,12 @@ protected function setUp() { * @expectedDeprecation \Drupal\user\SharedTempStore is scheduled for removal in Drupal 9.0.0. Use \Drupal\Core\TempStore\SharedTempStore instead. See https://www.drupal.org/node/2935639. */ public function testUserTempStore() { + $session = \Drupal::service('session'); + $session->start(); + $request_stack = $this->container->get('request_stack'); + $request_stack->getCurrentRequest()->setSession($session); // Create a key/value collection. - $factory = new SharedTempStoreFactory(new KeyValueExpirableFactory(\Drupal::getContainer()), new DatabaseLockBackend(Database::getConnection()), $this->container->get('request_stack')); + $factory = new SharedTempStoreFactory(new KeyValueExpirableFactory(\Drupal::getContainer()), new DatabaseLockBackend(Database::getConnection()), $request_stack); $collection = $this->randomMachineName(); // Create two mock users. diff --git a/core/modules/user/tests/src/Unit/SharedTempStoreTest.php b/core/modules/user/tests/src/Unit/SharedTempStoreTest.php index 6b5d441968..321636979e 100644 --- a/core/modules/user/tests/src/Unit/SharedTempStoreTest.php +++ b/core/modules/user/tests/src/Unit/SharedTempStoreTest.php @@ -2,11 +2,13 @@ namespace Drupal\Tests\user\Unit; +use Drupal\Core\Session\AccountProxyInterface; use Drupal\Tests\UnitTestCase; use Drupal\user\SharedTempStore; use Drupal\user\TempStoreException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpFoundation\Session\SessionInterface; /** * @coversDefaultClass \Drupal\user\SharedTempStore @@ -76,9 +78,12 @@ protected function setUp() { $this->lock = $this->getMock('Drupal\Core\Lock\LockBackendInterface'); $this->requestStack = new RequestStack(); $request = Request::createFromGlobals(); + $session = $this->getMock(SessionInterface::class); + $request->setSession($session); $this->requestStack->push($request); + $current_user = $this->getMock(AccountProxyInterface::class); - $this->tempStore = new SharedTempStore($this->keyValue, $this->lock, $this->owner, $this->requestStack, 604800); + $this->tempStore = new SharedTempStore($this->keyValue, $this->lock, $this->owner, $this->requestStack, $current_user, 604800); $this->ownObject = (object) [ 'data' => 'test_data', diff --git a/core/modules/user/user.module b/core/modules/user/user.module index 053429f4b8..78fbdb2a20 100644 --- a/core/modules/user/user.module +++ b/core/modules/user/user.module @@ -561,8 +561,10 @@ function user_login_finalize(UserInterface $account) { // This is called before hook_user_login() in case one of those functions // fails or incorrectly does a redirect which would leave the old session // in place. - \Drupal::service('session')->migrate(); - \Drupal::service('session')->set('uid', $account->id()); + /** @var \Symfony\Component\HttpFoundation\Session\Session $session */ + $session = \Drupal::service('session'); + $session->migrate(TRUE); + $session->set('uid', $account->id()); \Drupal::moduleHandler()->invokeAll('user_login', [$account]); } diff --git a/core/tests/Drupal/KernelTests/Core/TempStore/TempStoreDatabaseTest.php b/core/tests/Drupal/KernelTests/Core/TempStore/TempStoreDatabaseTest.php index 830432f8cc..a936a431a3 100644 --- a/core/tests/Drupal/KernelTests/Core/TempStore/TempStoreDatabaseTest.php +++ b/core/tests/Drupal/KernelTests/Core/TempStore/TempStoreDatabaseTest.php @@ -64,7 +64,11 @@ protected function setUp() { public function testSharedTempStore() { // Create a key/value collection. $database = Database::getConnection(); - $factory = new SharedTempStoreFactory(new KeyValueExpirableFactory(\Drupal::getContainer()), new DatabaseLockBackend($database), $this->container->get('request_stack')); + $session = \Drupal::service('session'); + $session->start(); + $request_stack = $this->container->get('request_stack'); + $request_stack->getCurrentRequest()->setSession($session); + $factory = new SharedTempStoreFactory(new KeyValueExpirableFactory(\Drupal::getContainer()), new DatabaseLockBackend($database), $request_stack); $collection = $this->randomMachineName(); // Create two mock users. diff --git a/core/tests/Drupal/Tests/Core/TempStore/SharedTempStoreTest.php b/core/tests/Drupal/Tests/Core/TempStore/SharedTempStoreTest.php index 55a78b9a25..f8edcd066c 100644 --- a/core/tests/Drupal/Tests/Core/TempStore/SharedTempStoreTest.php +++ b/core/tests/Drupal/Tests/Core/TempStore/SharedTempStoreTest.php @@ -2,11 +2,14 @@ namespace Drupal\Tests\Core\TempStore; +use Drupal\Core\DependencyInjection\ContainerBuilder; +use Drupal\Core\Session\AccountProxyInterface; use Drupal\Tests\UnitTestCase; use Drupal\Core\TempStore\SharedTempStore; use Drupal\Core\TempStore\TempStoreException; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\RequestStack; +use Symfony\Component\HttpFoundation\Session\SessionInterface; /** * @coversDefaultClass \Drupal\Core\TempStore\SharedTempStore @@ -73,9 +76,12 @@ protected function setUp() { $this->lock = $this->getMock('Drupal\Core\Lock\LockBackendInterface'); $this->requestStack = new RequestStack(); $request = Request::createFromGlobals(); + $session = $this->getMock(SessionInterface::class); + $request->setSession($session); $this->requestStack->push($request); + $current_user = $this->getMock(AccountProxyInterface::class); - $this->tempStore = new SharedTempStore($this->keyValue, $this->lock, $this->owner, $this->requestStack, 604800); + $this->tempStore = new SharedTempStore($this->keyValue, $this->lock, $this->owner, $this->requestStack, $current_user, 604800); $this->ownObject = (object) [ 'data' => 'test_data', @@ -350,4 +356,25 @@ public function testDeleteIfOwner() { $this->assertFalse($this->tempStore->deleteIfOwner('test_3')); } + /** + * @group legacy + * @expectedDeprecation @todo + */ + public function testLegacyConstructor() { + $container = new ContainerBuilder(); + $current_user = $this->getMock(AccountProxyInterface::class); + $container->set('current_user', $current_user); + \Drupal::setContainer($container); + $store = new SharedTempStore($this->keyValue, $this->lock, 2, $this->requestStack, 1000); + $reflection_class = new \ReflectionClass(SharedTempStore::class); + + $current_user_property = $reflection_class->getProperty('currentUser'); + $current_user_property->setAccessible(TRUE); + $this->assertSame($current_user, $current_user_property->getValue($store)); + + $expire_property = $reflection_class->getProperty('expire'); + $expire_property->setAccessible(TRUE); + $this->assertSame(1000, $expire_property->getValue($store)); + } + }