PageRenderTime 26ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/core/modules/system/src/Tests/Session/SessionTest.php

https://gitlab.com/reasonat/test8
PHP | 324 lines | 277 code | 18 blank | 29 comment | 5 complexity | cf94d40262932bf2da525e576036ed8f MD5 | raw file
  1. <?php
  2. namespace Drupal\system\Tests\Session;
  3. use Drupal\simpletest\WebTestBase;
  4. /**
  5. * Drupal session handling tests.
  6. *
  7. * @group Session
  8. */
  9. class SessionTest extends WebTestBase {
  10. /**
  11. * Modules to enable.
  12. *
  13. * @var array
  14. */
  15. public static $modules = array('session_test');
  16. protected $dumpHeaders = TRUE;
  17. /**
  18. * Tests for \Drupal\Core\Session\WriteSafeSessionHandler::setSessionWritable()
  19. * ::isSessionWritable and \Drupal\Core\Session\SessionManager::regenerate().
  20. */
  21. function testSessionSaveRegenerate() {
  22. $session_handler = $this->container->get('session_handler.write_safe');
  23. $this->assertTrue($session_handler->isSessionWritable(), 'session_handler->isSessionWritable() initially returns TRUE.');
  24. $session_handler->setSessionWritable(FALSE);
  25. $this->assertFalse($session_handler->isSessionWritable(), '$session_handler->isSessionWritable() returns FALSE after disabling.');
  26. $session_handler->setSessionWritable(TRUE);
  27. $this->assertTrue($session_handler->isSessionWritable(), '$session_handler->isSessionWritable() returns TRUE after enabling.');
  28. // Test session hardening code from SA-2008-044.
  29. $user = $this->drupalCreateUser();
  30. // Enable sessions.
  31. $this->sessionReset($user->id());
  32. // Make sure the session cookie is set as HttpOnly.
  33. $this->drupalLogin($user);
  34. $this->assertTrue(preg_match('/HttpOnly/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie is set as HttpOnly.');
  35. $this->drupalLogout();
  36. // Verify that the session is regenerated if a module calls exit
  37. // in hook_user_login().
  38. $user->name = 'session_test_user';
  39. $user->save();
  40. $this->drupalGet('session-test/id');
  41. $matches = array();
  42. preg_match('/\s*session_id:(.*)\n/', $this->getRawContent(), $matches);
  43. $this->assertTrue(!empty($matches[1]), 'Found session ID before logging in.');
  44. $original_session = $matches[1];
  45. // We cannot use $this->drupalLogin($user); because we exit in
  46. // session_test_user_login() which breaks a normal assertion.
  47. $edit = array(
  48. 'name' => $user->getUsername(),
  49. 'pass' => $user->pass_raw
  50. );
  51. $this->drupalPostForm('user/login', $edit, t('Log in'));
  52. $this->drupalGet('user');
  53. $pass = $this->assertText($user->getUsername(), format_string('Found name: %name', array('%name' => $user->getUsername())), 'User login');
  54. $this->_logged_in = $pass;
  55. $this->drupalGet('session-test/id');
  56. $matches = array();
  57. preg_match('/\s*session_id:(.*)\n/', $this->getRawContent(), $matches);
  58. $this->assertTrue(!empty($matches[1]), 'Found session ID after logging in.');
  59. $this->assertTrue($matches[1] != $original_session, 'Session ID changed after login.');
  60. }
  61. /**
  62. * Test data persistence via the session_test module callbacks.
  63. */
  64. function testDataPersistence() {
  65. $user = $this->drupalCreateUser(array());
  66. // Enable sessions.
  67. $this->sessionReset($user->id());
  68. $this->drupalLogin($user);
  69. $value_1 = $this->randomMachineName();
  70. $this->drupalGet('session-test/set/' . $value_1);
  71. $this->assertText($value_1, 'The session value was stored.', 'Session');
  72. $this->drupalGet('session-test/get');
  73. $this->assertText($value_1, 'Session correctly returned the stored data for an authenticated user.', 'Session');
  74. // Attempt to write over val_1. If drupal_save_session(FALSE) is working.
  75. // properly, val_1 will still be set.
  76. $value_2 = $this->randomMachineName();
  77. $this->drupalGet('session-test/no-set/' . $value_2);
  78. $this->assertText($value_2, 'The session value was correctly passed to session-test/no-set.', 'Session');
  79. $this->drupalGet('session-test/get');
  80. $this->assertText($value_1, 'Session data is not saved for drupal_save_session(FALSE).', 'Session');
  81. // Switch browser cookie to anonymous user, then back to user 1.
  82. $this->sessionReset();
  83. $this->sessionReset($user->id());
  84. $this->assertText($value_1, 'Session data persists through browser close.', 'Session');
  85. // Logout the user and make sure the stored value no longer persists.
  86. $this->drupalLogout();
  87. $this->sessionReset();
  88. $this->drupalGet('session-test/get');
  89. $this->assertNoText($value_1, "After logout, previous user's session data is not available.", 'Session');
  90. // Now try to store some data as an anonymous user.
  91. $value_3 = $this->randomMachineName();
  92. $this->drupalGet('session-test/set/' . $value_3);
  93. $this->assertText($value_3, 'Session data stored for anonymous user.', 'Session');
  94. $this->drupalGet('session-test/get');
  95. $this->assertText($value_3, 'Session correctly returned the stored data for an anonymous user.', 'Session');
  96. // Try to store data when drupal_save_session(FALSE).
  97. $value_4 = $this->randomMachineName();
  98. $this->drupalGet('session-test/no-set/' . $value_4);
  99. $this->assertText($value_4, 'The session value was correctly passed to session-test/no-set.', 'Session');
  100. $this->drupalGet('session-test/get');
  101. $this->assertText($value_3, 'Session data is not saved for drupal_save_session(FALSE).', 'Session');
  102. // Login, the data should persist.
  103. $this->drupalLogin($user);
  104. $this->sessionReset($user->id());
  105. $this->drupalGet('session-test/get');
  106. $this->assertNoText($value_1, 'Session has persisted for an authenticated user after logging out and then back in.', 'Session');
  107. // Change session and create another user.
  108. $user2 = $this->drupalCreateUser(array());
  109. $this->sessionReset($user2->id());
  110. $this->drupalLogin($user2);
  111. }
  112. /**
  113. * Tests storing data in Session() object.
  114. */
  115. public function testSessionPersistenceOnLogin() {
  116. // Store information via hook_user_login().
  117. $user = $this->drupalCreateUser();
  118. $this->drupalLogin($user);
  119. // Test property added to session object form hook_user_login().
  120. $this->drupalGet('session-test/get-from-session-object');
  121. $this->assertText('foobar', 'Session data is saved in Session() object.', 'Session');
  122. }
  123. /**
  124. * Test that empty anonymous sessions are destroyed.
  125. */
  126. function testEmptyAnonymousSession() {
  127. // Disable the dynamic_page_cache module; it'd cause session_test's debug
  128. // output (that is added in
  129. // SessionTestSubscriber::onKernelResponseSessionTest()) to not be added.
  130. $this->container->get('module_installer')->uninstall(['dynamic_page_cache']);
  131. // Verify that no session is automatically created for anonymous user when
  132. // page caching is disabled.
  133. $this->container->get('module_installer')->uninstall(['page_cache']);
  134. $this->drupalGet('');
  135. $this->assertSessionCookie(FALSE);
  136. $this->assertSessionEmpty(TRUE);
  137. // The same behavior is expected when caching is enabled.
  138. $this->container->get('module_installer')->install(['page_cache']);
  139. $config = $this->config('system.performance');
  140. $config->set('cache.page.max_age', 300);
  141. $config->save();
  142. $this->drupalGet('');
  143. $this->assertSessionCookie(FALSE);
  144. // @todo Reinstate when REQUEST and RESPONSE events fire for cached pages.
  145. // $this->assertSessionEmpty(TRUE);
  146. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
  147. // Start a new session by setting a message.
  148. $this->drupalGet('session-test/set-message');
  149. $this->assertSessionCookie(TRUE);
  150. $this->assertTrue($this->drupalGetHeader('Set-Cookie'), 'New session was started.');
  151. // Display the message, during the same request the session is destroyed
  152. // and the session cookie is unset.
  153. $this->drupalGet('');
  154. $this->assertSessionCookie(FALSE);
  155. $this->assertSessionEmpty(FALSE);
  156. $this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Caching was bypassed.');
  157. $this->assertText(t('This is a dummy message.'), 'Message was displayed.');
  158. $this->assertTrue(preg_match('/SESS\w+=deleted/', $this->drupalGetHeader('Set-Cookie')), 'Session cookie was deleted.');
  159. // Verify that session was destroyed.
  160. $this->drupalGet('');
  161. $this->assertSessionCookie(FALSE);
  162. // @todo Reinstate when REQUEST and RESPONSE events fire for cached pages.
  163. // $this->assertSessionEmpty(TRUE);
  164. $this->assertNoText(t('This is a dummy message.'), 'Message was not cached.');
  165. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
  166. $this->assertFalse($this->drupalGetHeader('Set-Cookie'), 'New session was not started.');
  167. // Verify that no session is created if drupal_save_session(FALSE) is called.
  168. $this->drupalGet('session-test/set-message-but-dont-save');
  169. $this->assertSessionCookie(FALSE);
  170. $this->assertSessionEmpty(TRUE);
  171. // Verify that no message is displayed.
  172. $this->drupalGet('');
  173. $this->assertSessionCookie(FALSE);
  174. // @todo Reinstate when REQUEST and RESPONSE events fire for cached pages.
  175. // $this->assertSessionEmpty(TRUE);
  176. $this->assertNoText(t('This is a dummy message.'), 'The message was not saved.');
  177. }
  178. /**
  179. * Test that sessions are only saved when necessary.
  180. */
  181. function testSessionWrite() {
  182. $user = $this->drupalCreateUser(array());
  183. $this->drupalLogin($user);
  184. $sql = 'SELECT u.access, s.timestamp FROM {users_field_data} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE u.uid = :uid';
  185. $times1 = db_query($sql, array(':uid' => $user->id()))->fetchObject();
  186. // Before every request we sleep one second to make sure that if the session
  187. // is saved, its timestamp will change.
  188. // Modify the session.
  189. sleep(1);
  190. $this->drupalGet('session-test/set/foo');
  191. $times2 = db_query($sql, array(':uid' => $user->id()))->fetchObject();
  192. $this->assertEqual($times2->access, $times1->access, 'Users table was not updated.');
  193. $this->assertNotEqual($times2->timestamp, $times1->timestamp, 'Sessions table was updated.');
  194. // Write the same value again, i.e. do not modify the session.
  195. sleep(1);
  196. $this->drupalGet('session-test/set/foo');
  197. $times3 = db_query($sql, array(':uid' => $user->id()))->fetchObject();
  198. $this->assertEqual($times3->access, $times1->access, 'Users table was not updated.');
  199. $this->assertEqual($times3->timestamp, $times2->timestamp, 'Sessions table was not updated.');
  200. // Do not change the session.
  201. sleep(1);
  202. $this->drupalGet('');
  203. $times4 = db_query($sql, array(':uid' => $user->id()))->fetchObject();
  204. $this->assertEqual($times4->access, $times3->access, 'Users table was not updated.');
  205. $this->assertEqual($times4->timestamp, $times3->timestamp, 'Sessions table was not updated.');
  206. // Force updating of users and sessions table once per second.
  207. $this->settingsSet('session_write_interval', 0);
  208. // Write that value also into the test settings.php file.
  209. $settings['settings']['session_write_interval'] = (object) array(
  210. 'value' => 0,
  211. 'required' => TRUE,
  212. );
  213. $this->writeSettings($settings);
  214. $this->drupalGet('');
  215. $times5 = db_query($sql, array(':uid' => $user->id()))->fetchObject();
  216. $this->assertNotEqual($times5->access, $times4->access, 'Users table was updated.');
  217. $this->assertNotEqual($times5->timestamp, $times4->timestamp, 'Sessions table was updated.');
  218. }
  219. /**
  220. * Test that empty session IDs are not allowed.
  221. */
  222. function testEmptySessionID() {
  223. $user = $this->drupalCreateUser(array());
  224. $this->drupalLogin($user);
  225. $this->drupalGet('session-test/is-logged-in');
  226. $this->assertResponse(200, 'User is logged in.');
  227. // Reset the sid in {sessions} to a blank string. This may exist in the
  228. // wild in some cases, although we normally prevent it from happening.
  229. db_query("UPDATE {sessions} SET sid = '' WHERE uid = :uid", array(':uid' => $user->id()));
  230. // Send a blank sid in the session cookie, and the session should no longer
  231. // be valid. Closing the curl handler will stop the previous session ID
  232. // from persisting.
  233. $this->curlClose();
  234. $this->additionalCurlOptions[CURLOPT_COOKIE] = rawurlencode($this->getSessionName()) . '=;';
  235. $this->drupalGet('session-test/id-from-cookie');
  236. $this->assertRaw("session_id:\n", 'Session ID is blank as sent from cookie header.');
  237. // Assert that we have an anonymous session now.
  238. $this->drupalGet('session-test/is-logged-in');
  239. $this->assertResponse(403, 'An empty session ID is not allowed.');
  240. }
  241. /**
  242. * Reset the cookie file so that it refers to the specified user.
  243. *
  244. * @param $uid User id to set as the active session.
  245. */
  246. function sessionReset($uid = 0) {
  247. // Close the internal browser.
  248. $this->curlClose();
  249. $this->loggedInUser = FALSE;
  250. // Change cookie file for user.
  251. $this->cookieFile = \Drupal::service('stream_wrapper_manager')->getViaScheme('temporary')->getDirectoryPath() . '/cookie.' . $uid . '.txt';
  252. $this->additionalCurlOptions[CURLOPT_COOKIEFILE] = $this->cookieFile;
  253. $this->additionalCurlOptions[CURLOPT_COOKIESESSION] = TRUE;
  254. $this->drupalGet('session-test/get');
  255. $this->assertResponse(200, 'Session test module is correctly enabled.', 'Session');
  256. }
  257. /**
  258. * Assert whether the SimpleTest browser sent a session cookie.
  259. */
  260. function assertSessionCookie($sent) {
  261. if ($sent) {
  262. $this->assertNotNull($this->sessionId, 'Session cookie was sent.');
  263. }
  264. else {
  265. $this->assertNull($this->sessionId, 'Session cookie was not sent.');
  266. }
  267. }
  268. /**
  269. * Assert whether $_SESSION is empty at the beginning of the request.
  270. */
  271. function assertSessionEmpty($empty) {
  272. if ($empty) {
  273. $this->assertIdentical($this->drupalGetHeader('X-Session-Empty'), '1', 'Session was empty.');
  274. }
  275. else {
  276. $this->assertIdentical($this->drupalGetHeader('X-Session-Empty'), '0', 'Session was not empty.');
  277. }
  278. }
  279. }