session.test 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530
  1. <?php
  2. /**
  3. * @file
  4. * Provides SimpleTests for core session handling functionality.
  5. */
  6. class SessionTestCase extends DrupalWebTestCase {
  7. public static function getInfo() {
  8. return array(
  9. 'name' => 'Session tests',
  10. 'description' => 'Drupal session handling tests.',
  11. 'group' => 'Session'
  12. );
  13. }
  14. function setUp() {
  15. parent::setUp('session_test');
  16. }
  17. /**
  18. * Tests for drupal_save_session() and drupal_session_regenerate().
  19. */
  20. function testSessionSaveRegenerate() {
  21. $this->assertFalse(drupal_save_session(), 'drupal_save_session() correctly returns FALSE (inside of testing framework) when initially called with no arguments.', 'Session');
  22. $this->assertFalse(drupal_save_session(FALSE), 'drupal_save_session() correctly returns FALSE when called with FALSE.', 'Session');
  23. $this->assertFalse(drupal_save_session(), 'drupal_save_session() correctly returns FALSE when saving has been disabled.', 'Session');
  24. $this->assertTrue(drupal_save_session(TRUE), 'drupal_save_session() correctly returns TRUE when called with TRUE.', 'Session');
  25. $this->assertTrue(drupal_save_session(), 'drupal_save_session() correctly returns TRUE when saving has been enabled.', 'Session');
  26. // Test session hardening code from SA-2008-044.
  27. $user = $this->drupalCreateUser(array('access content'));
  28. // Enable sessions.
  29. $this->sessionReset($user->uid);
  30. // Make sure the session cookie is set as HttpOnly.
  31. $this->drupalLogin($user);
  32. $this->assertTrue(preg_match('/HttpOnly/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie is set as HttpOnly.');
  33. $this->drupalLogout();
  34. // Verify that the session is regenerated if a module calls exit
  35. // in hook_user_login().
  36. user_save($user, array('name' => 'session_test_user'));
  37. $user->name = 'session_test_user';
  38. $this->drupalGet('session-test/id');
  39. $matches = array();
  40. preg_match('/\s*session_id:(.*)\n/', $this->drupalGetContent(), $matches);
  41. $this->assertTrue(!empty($matches[1]) , 'Found session ID before logging in.');
  42. $original_session = $matches[1];
  43. // We cannot use $this->drupalLogin($user); because we exit in
  44. // session_test_user_login() which breaks a normal assertion.
  45. $edit = array(
  46. 'name' => $user->name,
  47. 'pass' => $user->pass_raw
  48. );
  49. $this->drupalPost('user', $edit, t('Log in'));
  50. $this->drupalGet('user');
  51. $pass = $this->assertText($user->name, format_string('Found name: %name', array('%name' => $user->name)), 'User login');
  52. $this->_logged_in = $pass;
  53. $this->drupalGet('session-test/id');
  54. $matches = array();
  55. preg_match('/\s*session_id:(.*)\n/', $this->drupalGetContent(), $matches);
  56. $this->assertTrue(!empty($matches[1]) , 'Found session ID after logging in.');
  57. $this->assertTrue($matches[1] != $original_session, 'Session ID changed after login.');
  58. }
  59. /**
  60. * Test data persistence via the session_test module callbacks.
  61. */
  62. function testDataPersistence() {
  63. $user = $this->drupalCreateUser(array('access content'));
  64. // Enable sessions.
  65. $this->sessionReset($user->uid);
  66. $this->drupalLogin($user);
  67. $value_1 = $this->randomName();
  68. $this->drupalGet('session-test/set/' . $value_1);
  69. $this->assertText($value_1, 'The session value was stored.', 'Session');
  70. $this->drupalGet('session-test/get');
  71. $this->assertText($value_1, 'Session correctly returned the stored data for an authenticated user.', 'Session');
  72. // Attempt to write over val_1. If drupal_save_session(FALSE) is working.
  73. // properly, val_1 will still be set.
  74. $value_2 = $this->randomName();
  75. $this->drupalGet('session-test/no-set/' . $value_2);
  76. $this->assertText($value_2, 'The session value was correctly passed to session-test/no-set.', 'Session');
  77. $this->drupalGet('session-test/get');
  78. $this->assertText($value_1, 'Session data is not saved for drupal_save_session(FALSE).', 'Session');
  79. // Switch browser cookie to anonymous user, then back to user 1.
  80. $this->sessionReset();
  81. $this->sessionReset($user->uid);
  82. $this->assertText($value_1, 'Session data persists through browser close.', 'Session');
  83. // Logout the user and make sure the stored value no longer persists.
  84. $this->drupalLogout();
  85. $this->sessionReset();
  86. $this->drupalGet('session-test/get');
  87. $this->assertNoText($value_1, "After logout, previous user's session data is not available.", 'Session');
  88. // Now try to store some data as an anonymous user.
  89. $value_3 = $this->randomName();
  90. $this->drupalGet('session-test/set/' . $value_3);
  91. $this->assertText($value_3, 'Session data stored for anonymous user.', 'Session');
  92. $this->drupalGet('session-test/get');
  93. $this->assertText($value_3, 'Session correctly returned the stored data for an anonymous user.', 'Session');
  94. // Try to store data when drupal_save_session(FALSE).
  95. $value_4 = $this->randomName();
  96. $this->drupalGet('session-test/no-set/' . $value_4);
  97. $this->assertText($value_4, 'The session value was correctly passed to session-test/no-set.', 'Session');
  98. $this->drupalGet('session-test/get');
  99. $this->assertText($value_3, 'Session data is not saved for drupal_save_session(FALSE).', 'Session');
  100. // Login, the data should persist.
  101. $this->drupalLogin($user);
  102. $this->sessionReset($user->uid);
  103. $this->drupalGet('session-test/get');
  104. $this->assertNoText($value_1, 'Session has persisted for an authenticated user after logging out and then back in.', 'Session');
  105. // Change session and create another user.
  106. $user2 = $this->drupalCreateUser(array('access content'));
  107. $this->sessionReset($user2->uid);
  108. $this->drupalLogin($user2);
  109. }
  110. /**
  111. * Test that empty anonymous sessions are destroyed.
  112. */
  113. function testEmptyAnonymousSession() {
  114. // Verify that no session is automatically created for anonymous user.
  115. $this->drupalGet('');
  116. $this->assertSessionCookie(FALSE);
  117. $this->assertSessionEmpty(TRUE);
  118. // The same behavior is expected when caching is enabled.
  119. variable_set('cache', 1);
  120. $this->drupalGet('');
  121. $this->assertSessionCookie(FALSE);
  122. $this->assertSessionEmpty(TRUE);
  123. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'MISS', 'Page was not cached.');
  124. // Start a new session by setting a message.
  125. $this->drupalGet('session-test/set-message');
  126. $this->assertSessionCookie(TRUE);
  127. $this->assertTrue($this->drupalGetHeader('Set-Cookie'), 'New session was started.');
  128. // Display the message, during the same request the session is destroyed
  129. // and the session cookie is unset.
  130. $this->drupalGet('');
  131. $this->assertSessionCookie(FALSE);
  132. $this->assertSessionEmpty(FALSE);
  133. $this->assertFalse($this->drupalGetHeader('X-Drupal-Cache'), 'Caching was bypassed.');
  134. $this->assertText(t('This is a dummy message.'), 'Message was displayed.');
  135. $this->assertTrue(preg_match('/SESS\w+=deleted/', $this->drupalGetHeader('Set-Cookie')), 'Session cookie was deleted.');
  136. // Verify that session was destroyed.
  137. $this->drupalGet('');
  138. $this->assertSessionCookie(FALSE);
  139. $this->assertSessionEmpty(TRUE);
  140. $this->assertNoText(t('This is a dummy message.'), 'Message was not cached.');
  141. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
  142. $this->assertFalse($this->drupalGetHeader('Set-Cookie'), 'New session was not started.');
  143. // Verify that no session is created if drupal_save_session(FALSE) is called.
  144. $this->drupalGet('session-test/set-message-but-dont-save');
  145. $this->assertSessionCookie(FALSE);
  146. $this->assertSessionEmpty(TRUE);
  147. // Verify that no message is displayed.
  148. $this->drupalGet('');
  149. $this->assertSessionCookie(FALSE);
  150. $this->assertSessionEmpty(TRUE);
  151. $this->assertNoText(t('This is a dummy message.'), 'The message was not saved.');
  152. }
  153. /**
  154. * Test that sessions are only saved when necessary.
  155. */
  156. function testSessionWrite() {
  157. $user = $this->drupalCreateUser(array('access content'));
  158. $this->drupalLogin($user);
  159. $sql = 'SELECT u.access, s.timestamp FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE u.uid = :uid';
  160. $times1 = db_query($sql, array(':uid' => $user->uid))->fetchObject();
  161. // Before every request we sleep one second to make sure that if the session
  162. // is saved, its timestamp will change.
  163. // Modify the session.
  164. sleep(1);
  165. $this->drupalGet('session-test/set/foo');
  166. $times2 = db_query($sql, array(':uid' => $user->uid))->fetchObject();
  167. $this->assertEqual($times2->access, $times1->access, 'Users table was not updated.');
  168. $this->assertNotEqual($times2->timestamp, $times1->timestamp, 'Sessions table was updated.');
  169. // Write the same value again, i.e. do not modify the session.
  170. sleep(1);
  171. $this->drupalGet('session-test/set/foo');
  172. $times3 = db_query($sql, array(':uid' => $user->uid))->fetchObject();
  173. $this->assertEqual($times3->access, $times1->access, 'Users table was not updated.');
  174. $this->assertEqual($times3->timestamp, $times2->timestamp, 'Sessions table was not updated.');
  175. // Do not change the session.
  176. sleep(1);
  177. $this->drupalGet('');
  178. $times4 = db_query($sql, array(':uid' => $user->uid))->fetchObject();
  179. $this->assertEqual($times4->access, $times3->access, 'Users table was not updated.');
  180. $this->assertEqual($times4->timestamp, $times3->timestamp, 'Sessions table was not updated.');
  181. // Force updating of users and sessions table once per second.
  182. variable_set('session_write_interval', 0);
  183. $this->drupalGet('');
  184. $times5 = db_query($sql, array(':uid' => $user->uid))->fetchObject();
  185. $this->assertNotEqual($times5->access, $times4->access, 'Users table was updated.');
  186. $this->assertNotEqual($times5->timestamp, $times4->timestamp, 'Sessions table was updated.');
  187. }
  188. /**
  189. * Test that empty session IDs are not allowed.
  190. */
  191. function testEmptySessionID() {
  192. $user = $this->drupalCreateUser(array('access content'));
  193. $this->drupalLogin($user);
  194. $this->drupalGet('session-test/is-logged-in');
  195. $this->assertResponse(200, 'User is logged in.');
  196. // Reset the sid in {sessions} to a blank string. This may exist in the
  197. // wild in some cases, although we normally prevent it from happening.
  198. db_query("UPDATE {sessions} SET sid = '' WHERE uid = :uid", array(':uid' => $user->uid));
  199. // Send a blank sid in the session cookie, and the session should no longer
  200. // be valid. Closing the curl handler will stop the previous session ID
  201. // from persisting.
  202. $this->curlClose();
  203. $this->additionalCurlOptions[CURLOPT_COOKIE] = rawurlencode($this->session_name) . '=;';
  204. $this->drupalGet('session-test/id-from-cookie');
  205. $this->assertRaw("session_id:\n", 'Session ID is blank as sent from cookie header.');
  206. // Assert that we have an anonymous session now.
  207. $this->drupalGet('session-test/is-logged-in');
  208. $this->assertResponse(403, 'An empty session ID is not allowed.');
  209. }
  210. /**
  211. * Reset the cookie file so that it refers to the specified user.
  212. *
  213. * @param $uid User id to set as the active session.
  214. */
  215. function sessionReset($uid = 0) {
  216. // Close the internal browser.
  217. $this->curlClose();
  218. $this->loggedInUser = FALSE;
  219. // Change cookie file for user.
  220. $this->cookieFile = file_stream_wrapper_get_instance_by_scheme('temporary')->getDirectoryPath() . '/cookie.' . $uid . '.txt';
  221. $this->additionalCurlOptions[CURLOPT_COOKIEFILE] = $this->cookieFile;
  222. $this->additionalCurlOptions[CURLOPT_COOKIESESSION] = TRUE;
  223. $this->drupalGet('session-test/get');
  224. $this->assertResponse(200, 'Session test module is correctly enabled.', 'Session');
  225. }
  226. /**
  227. * Assert whether the SimpleTest browser sent a session cookie.
  228. */
  229. function assertSessionCookie($sent) {
  230. if ($sent) {
  231. $this->assertNotNull($this->session_id, 'Session cookie was sent.');
  232. }
  233. else {
  234. $this->assertNull($this->session_id, 'Session cookie was not sent.');
  235. }
  236. }
  237. /**
  238. * Assert whether $_SESSION is empty at the beginning of the request.
  239. */
  240. function assertSessionEmpty($empty) {
  241. if ($empty) {
  242. $this->assertIdentical($this->drupalGetHeader('X-Session-Empty'), '1', 'Session was empty.');
  243. }
  244. else {
  245. $this->assertIdentical($this->drupalGetHeader('X-Session-Empty'), '0', 'Session was not empty.');
  246. }
  247. }
  248. }
  249. /**
  250. * Ensure that when running under HTTPS two session cookies are generated.
  251. */
  252. class SessionHttpsTestCase extends DrupalWebTestCase {
  253. public static function getInfo() {
  254. return array(
  255. 'name' => 'Session HTTPS handling',
  256. 'description' => 'Ensure that when running under HTTPS two session cookies are generated.',
  257. 'group' => 'Session'
  258. );
  259. }
  260. public function setUp() {
  261. parent::setUp('session_test');
  262. }
  263. protected function testHttpsSession() {
  264. global $is_https;
  265. if ($is_https) {
  266. $secure_session_name = session_name();
  267. $insecure_session_name = substr(session_name(), 1);
  268. }
  269. else {
  270. $secure_session_name = 'S' . session_name();
  271. $insecure_session_name = session_name();
  272. }
  273. $user = $this->drupalCreateUser(array('access administration pages'));
  274. // Test HTTPS session handling by altering the form action to submit the
  275. // login form through https.php, which creates a mock HTTPS request.
  276. $this->drupalGet('user');
  277. $form = $this->xpath('//form[@id="user-login"]');
  278. $form[0]['action'] = $this->httpsUrl('user');
  279. $edit = array('name' => $user->name, 'pass' => $user->pass_raw);
  280. $this->drupalPost(NULL, $edit, t('Log in'));
  281. // Test a second concurrent session.
  282. $this->curlClose();
  283. $this->drupalGet('user');
  284. $form = $this->xpath('//form[@id="user-login"]');
  285. $form[0]['action'] = $this->httpsUrl('user');
  286. $this->drupalPost(NULL, $edit, t('Log in'));
  287. // Check secure cookie on secure page.
  288. $this->assertTrue($this->cookies[$secure_session_name]['secure'], 'The secure cookie has the secure attribute');
  289. // Check insecure cookie is not set.
  290. $this->assertFalse(isset($this->cookies[$insecure_session_name]));
  291. $ssid = $this->cookies[$secure_session_name]['value'];
  292. $this->assertSessionIds($ssid, $ssid, 'Session has a non-empty SID and a correct secure SID.');
  293. $cookie = $secure_session_name . '=' . $ssid;
  294. // Verify that user is logged in on secure URL.
  295. $this->curlClose();
  296. $this->drupalGet($this->httpsUrl('admin/config'), array(), array('Cookie: ' . $cookie));
  297. $this->assertText(t('Configuration'));
  298. $this->assertResponse(200);
  299. // Verify that user is not logged in on non-secure URL.
  300. $this->curlClose();
  301. $this->drupalGet($this->httpUrl('admin/config'), array(), array('Cookie: ' . $cookie));
  302. $this->assertNoText(t('Configuration'));
  303. $this->assertResponse(403);
  304. // Verify that empty SID cannot be used on the non-secure site.
  305. $this->curlClose();
  306. $cookie = $insecure_session_name . '=';
  307. $this->drupalGet($this->httpUrl('admin/config'), array(), array('Cookie: ' . $cookie));
  308. $this->assertResponse(403);
  309. // Test HTTP session handling by altering the form action to submit the
  310. // login form through http.php, which creates a mock HTTP request on HTTPS
  311. // test environments.
  312. $this->curlClose();
  313. $this->drupalGet('user');
  314. $form = $this->xpath('//form[@id="user-login"]');
  315. $form[0]['action'] = $this->httpUrl('user');
  316. $edit = array('name' => $user->name, 'pass' => $user->pass_raw);
  317. $this->drupalPost(NULL, $edit, t('Log in'));
  318. $this->drupalGet($this->httpUrl('admin/config'));
  319. $this->assertResponse(200);
  320. $sid = $this->cookies[$insecure_session_name]['value'];
  321. $this->assertSessionIds($sid, '', 'Session has the correct SID and an empty secure SID.');
  322. // Verify that empty secure SID cannot be used on the secure site.
  323. $this->curlClose();
  324. $cookie = $secure_session_name . '=';
  325. $this->drupalGet($this->httpsUrl('admin/config'), array(), array('Cookie: ' . $cookie));
  326. $this->assertResponse(403);
  327. // Clear browser cookie jar.
  328. $this->cookies = array();
  329. if ($is_https) {
  330. // The functionality does not make sense when running on HTTPS.
  331. return;
  332. }
  333. // Enable secure pages.
  334. variable_set('https', TRUE);
  335. $this->curlClose();
  336. // Start an anonymous session on the insecure site.
  337. $session_data = $this->randomName();
  338. $this->drupalGet('session-test/set/' . $session_data);
  339. // Check secure cookie on insecure page.
  340. $this->assertFalse(isset($this->cookies[$secure_session_name]), 'The secure cookie is not sent on insecure pages.');
  341. // Check insecure cookie on insecure page.
  342. $this->assertFalse($this->cookies[$insecure_session_name]['secure'], 'The insecure cookie does not have the secure attribute');
  343. // Store the anonymous cookie so we can validate that its session is killed
  344. // after login.
  345. $anonymous_cookie = $insecure_session_name . '=' . $this->cookies[$insecure_session_name]['value'];
  346. // Check that password request form action is not secure.
  347. $this->drupalGet('user/password');
  348. $form = $this->xpath('//form[@id="user-pass"]');
  349. $this->assertNotEqual(substr($form[0]['action'], 0, 6), 'https:', 'Password request form action is not secure');
  350. $form[0]['action'] = $this->httpsUrl('user');
  351. // Check that user login form action is secure.
  352. $this->drupalGet('user');
  353. $form = $this->xpath('//form[@id="user-login"]');
  354. $this->assertEqual(substr($form[0]['action'], 0, 6), 'https:', 'Login form action is secure');
  355. $form[0]['action'] = $this->httpsUrl('user');
  356. $edit = array(
  357. 'name' => $user->name,
  358. 'pass' => $user->pass_raw,
  359. );
  360. $this->drupalPost(NULL, $edit, t('Log in'));
  361. // Check secure cookie on secure page.
  362. $this->assertTrue($this->cookies[$secure_session_name]['secure'], 'The secure cookie has the secure attribute');
  363. // Check insecure cookie on secure page.
  364. $this->assertFalse($this->cookies[$insecure_session_name]['secure'], 'The insecure cookie does not have the secure attribute');
  365. $sid = $this->cookies[$insecure_session_name]['value'];
  366. $ssid = $this->cookies[$secure_session_name]['value'];
  367. $this->assertSessionIds($sid, $ssid, 'Session has both secure and insecure SIDs');
  368. $cookies = array(
  369. $insecure_session_name . '=' . $sid,
  370. $secure_session_name . '=' . $ssid,
  371. );
  372. // Test that session data saved before login is still available on the
  373. // authenticated session.
  374. $this->drupalGet('session-test/get');
  375. $this->assertText($session_data, 'Session correctly returned the stored data set by the anonymous session.');
  376. foreach ($cookies as $cookie_key => $cookie) {
  377. foreach (array('admin/config', $this->httpsUrl('admin/config')) as $url_key => $url) {
  378. $this->curlClose();
  379. $this->drupalGet($url, array(), array('Cookie: ' . $cookie));
  380. if ($cookie_key == $url_key) {
  381. $this->assertText(t('Configuration'));
  382. $this->assertResponse(200);
  383. }
  384. else {
  385. $this->assertNoText(t('Configuration'));
  386. $this->assertResponse(403);
  387. }
  388. }
  389. }
  390. // Test that session data saved before login is not available using the
  391. // pre-login anonymous cookie.
  392. $this->cookies = array();
  393. $this->drupalGet('session-test/get', array('Cookie: ' . $anonymous_cookie));
  394. $this->assertNoText($session_data, 'Initial anonymous session is inactive after login.');
  395. // Clear browser cookie jar.
  396. $this->cookies = array();
  397. // Start an anonymous session on the secure site.
  398. $this->drupalGet($this->httpsUrl('session-test/set/1'));
  399. // Mock a login to the secure site using the secure session cookie.
  400. $this->drupalGet('user');
  401. $form = $this->xpath('//form[@id="user-login"]');
  402. $form[0]['action'] = $this->httpsUrl('user');
  403. $this->drupalPost(NULL, $edit, t('Log in'));
  404. // Test that the user is also authenticated on the insecure site.
  405. $this->drupalGet("user/{$user->uid}/edit");
  406. $this->assertResponse(200);
  407. }
  408. /**
  409. * Test that there exists a session with two specific session IDs.
  410. *
  411. * @param $sid
  412. * The insecure session ID to search for.
  413. * @param $ssid
  414. * The secure session ID to search for.
  415. * @param $assertion_text
  416. * The text to display when we perform the assertion.
  417. *
  418. * @return
  419. * The result of assertTrue() that there's a session in the system that
  420. * has the given insecure and secure session IDs.
  421. */
  422. protected function assertSessionIds($sid, $ssid, $assertion_text) {
  423. $args = array(
  424. ':sid' => $sid,
  425. ':ssid' => $ssid,
  426. );
  427. return $this->assertTrue(db_query('SELECT timestamp FROM {sessions} WHERE sid = :sid AND ssid = :ssid', $args)->fetchField(), $assertion_text);
  428. }
  429. /**
  430. * Builds a URL for submitting a mock HTTPS request to HTTP test environments.
  431. *
  432. * @param $url
  433. * A Drupal path such as 'user'.
  434. *
  435. * @return
  436. * An absolute URL.
  437. */
  438. protected function httpsUrl($url) {
  439. global $base_url;
  440. return $base_url . '/modules/simpletest/tests/https.php?q=' . $url;
  441. }
  442. /**
  443. * Builds a URL for submitting a mock HTTP request to HTTPS test environments.
  444. *
  445. * @param $url
  446. * A Drupal path such as 'user'.
  447. *
  448. * @return
  449. * An absolute URL.
  450. */
  451. protected function httpUrl($url) {
  452. global $base_url;
  453. return $base_url . '/modules/simpletest/tests/http.php?q=' . $url;
  454. }
  455. }