session.test 21 KB

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