session.test 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775
  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. * Test absence of SameSite attribute on session cookies by default.
  212. */
  213. function testNoSameSiteCookieAttributeDefault() {
  214. $user = $this->drupalCreateUser(array('access content'));
  215. $this->sessionReset($user->uid);
  216. if (\PHP_VERSION_ID < 70300) {
  217. $this->drupalLogin($user);
  218. }
  219. else {
  220. // PHP often defaults to an empty value for session.cookie_samesite but
  221. // that may vary, so we set an explicit empty value.
  222. // Send our own login POST so that we can pass a custom header to trigger
  223. // session_test.module to call ini_set('session.cookie_samesite', $value)
  224. $headers[] = 'X-Session-Cookie-Ini-Set: *EMPTY*';
  225. $edit = array(
  226. 'name' => $user->name,
  227. 'pass' => $user->pass_raw,
  228. );
  229. $this->drupalPost('user', $edit, t('Log in'), array(), $headers);
  230. }
  231. $this->assertFalse(preg_match('/SameSite=/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie has no SameSite attribute (default).');
  232. }
  233. /**
  234. * Test SameSite attribute = None by default on Secure session cookies.
  235. */
  236. function testSameSiteCookieAttributeNoneSecure() {
  237. $user = $this->drupalCreateUser(array('access content'));
  238. $this->sessionReset($user->uid);
  239. $headers = array();
  240. if (\PHP_VERSION_ID >= 70300) {
  241. // Send our own login POST so that we can pass a custom header to trigger
  242. // session_test.module to call ini_set('session.cookie_samesite', $value)
  243. $headers[] = 'X-Session-Cookie-Ini-Set: None';
  244. }
  245. // Test HTTPS session handling by altering the form action to submit the
  246. // login form through https.php, which creates a mock HTTPS request.
  247. $this->drupalGet('user');
  248. $form = $this->xpath('//form[@id="user-login"]');
  249. $form[0]['action'] = $this->httpsUrl('user');
  250. $edit = array('name' => $user->name, 'pass' => $user->pass_raw);
  251. $this->drupalPost(NULL, $edit, t('Log in'), array(), $headers);
  252. $this->assertTrue(preg_match('/SameSite=None/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie is set as SameSite=None.');
  253. }
  254. /**
  255. * Test SameSite attribute = None on session cookies.
  256. */
  257. function testSameSiteCookieAttributeNone() {
  258. variable_set('samesite_cookie_value', 'None');
  259. $user = $this->drupalCreateUser(array('access content'));
  260. $this->sessionReset($user->uid);
  261. $this->drupalLogin($user);
  262. $this->assertTrue(preg_match('/SameSite=None/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie is set as SameSite=None.');
  263. }
  264. /**
  265. * Test SameSite attribute = Lax on session cookies.
  266. */
  267. function testSameSiteCookieAttributeLax() {
  268. variable_set('samesite_cookie_value', 'Lax');
  269. $user = $this->drupalCreateUser(array('access content'));
  270. $this->sessionReset($user->uid);
  271. $this->drupalLogin($user);
  272. $this->assertTrue(preg_match('/SameSite=Lax/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie is set as SameSite=Lax.');
  273. }
  274. /**
  275. * Test SameSite attribute = Strict on session cookies.
  276. */
  277. function testSameSiteCookieAttributeStrict() {
  278. variable_set('samesite_cookie_value', 'Strict');
  279. $user = $this->drupalCreateUser(array('access content'));
  280. $this->sessionReset($user->uid);
  281. $this->drupalLogin($user);
  282. $this->assertTrue(preg_match('/SameSite=Strict/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie is set as SameSite=Strict.');
  283. }
  284. /**
  285. * Test disabling the samesite attribute on session cookies via $conf
  286. */
  287. function testSameSiteCookieAttributeDisabledViaConf() {
  288. $user = $this->drupalCreateUser(array('access content'));
  289. $this->sessionReset($user->uid);
  290. variable_set('samesite_cookie_value', FALSE);
  291. if (\PHP_VERSION_ID < 70300) {
  292. // There is no session.cookie_samesite in earlier PHP versions.
  293. $this->drupalLogin($user);
  294. }
  295. else {
  296. // Send our own login POST so that we can pass a custom header to trigger
  297. // session_test.module to call ini_set('session.cookie_samesite', $value)
  298. $headers[] = 'X-Session-Cookie-Ini-Set: Lax';
  299. $edit = array(
  300. 'name' => $user->name,
  301. 'pass' => $user->pass_raw,
  302. );
  303. $this->drupalPost('user', $edit, t('Log in'), array(), $headers);
  304. }
  305. $this->assertFalse(preg_match('/SameSite=/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie has no SameSite attribute (conf).');
  306. }
  307. /**
  308. * Test disabling the samesite attribute on session cookies via php ini
  309. */
  310. function testSameSiteCookieAttributeDisabledViaPhpIni() {
  311. if (\PHP_VERSION_ID < 70300) {
  312. // There is no session.cookie_samesite in earlier PHP versions.
  313. $this->pass('This test is only for PHP 7.3 and later.');
  314. return;
  315. }
  316. $user = $this->drupalCreateUser(array('access content'));
  317. // Send our own login POST so that we can pass a custom header to trigger
  318. // session_test.module to call ini_set('session.cookie_samesite', $value)
  319. $headers[] = 'X-Session-Cookie-Ini-Set: *EMPTY*';
  320. $edit = array(
  321. 'name' => $user->name,
  322. 'pass' => $user->pass_raw,
  323. );
  324. $this->drupalPost('user', $edit, t('Log in'), array(), $headers);
  325. $this->assertFalse(preg_match('/SameSite=/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie has no SameSite attribute (ini).');
  326. }
  327. /**
  328. * Test that a PHP setting for session.cookie_samesite is not overridden by
  329. * the default value in Drupal, without a samesite_cookie_value variable.
  330. */
  331. function testSamesiteCookiePhpSettingLax() {
  332. if (\PHP_VERSION_ID < 70300) {
  333. // There is no session.cookie_samesite in earlier PHP versions.
  334. $this->pass('This test is only for PHP 7.3 and later.');
  335. return;
  336. }
  337. $user = $this->drupalCreateUser(array('access content'));
  338. // Send our own login POST so that we can pass a custom header to trigger
  339. // session_test.module to call ini_set('session.cookie_samesite', $value)
  340. $headers[] = 'X-Session-Cookie-Ini-Set: Lax';
  341. $edit = array(
  342. 'name' => $user->name,
  343. 'pass' => $user->pass_raw,
  344. );
  345. $this->drupalPost('user', $edit, t('Log in'), array(), $headers);
  346. $this->assertTrue(preg_match('/SameSite=Lax/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie is set as SameSite=Lax.');
  347. }
  348. /**
  349. * Test overriding the PHP setting for session.cookie_samesite with the
  350. * samesite_cookie_value variable.
  351. */
  352. function testSamesiteCookieOverrideLaxToStrict() {
  353. if (\PHP_VERSION_ID < 70300) {
  354. // There is no session.cookie_samesite in earlier PHP versions.
  355. $this->pass('This test is only for PHP 7.3 and later.');
  356. return;
  357. }
  358. variable_set('samesite_cookie_value', 'Strict');
  359. $user = $this->drupalCreateUser(array('access content'));
  360. // Send our own login POST so that we can pass a custom header to trigger
  361. // session_test.module to call ini_set('session.cookie_samesite', $value)
  362. $headers[] = 'X-Session-Cookie-Ini-Set: Lax';
  363. $edit = array(
  364. 'name' => $user->name,
  365. 'pass' => $user->pass_raw,
  366. );
  367. $this->drupalPost('user', $edit, t('Log in'), array(), $headers);
  368. $this->assertTrue(preg_match('/SameSite=Strict/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie is set as SameSite=Strict.');
  369. }
  370. /**
  371. * Test SameSite attribute = Lax on set-cookie header on logout.
  372. */
  373. function testSamesiteCookieLogoutLax() {
  374. variable_set('samesite_cookie_value', 'Lax');
  375. $user = $this->drupalCreateUser(array('access content'));
  376. $this->sessionReset($user->uid);
  377. $this->drupalLogin($user);
  378. $this->drupalGet('user/logout');
  379. $this->assertTrue(preg_match('/SameSite=Lax/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie deletion includes SameSite=Lax.');
  380. }
  381. /**
  382. * Reset the cookie file so that it refers to the specified user.
  383. *
  384. * @param $uid User id to set as the active session.
  385. */
  386. function sessionReset($uid = 0) {
  387. // Close the internal browser.
  388. $this->curlClose();
  389. $this->loggedInUser = FALSE;
  390. // Change cookie file for user.
  391. $this->cookieFile = file_stream_wrapper_get_instance_by_scheme('temporary')->getDirectoryPath() . '/cookie.' . $uid . '.txt';
  392. $this->additionalCurlOptions[CURLOPT_COOKIEFILE] = $this->cookieFile;
  393. $this->additionalCurlOptions[CURLOPT_COOKIESESSION] = TRUE;
  394. $this->drupalGet('session-test/get');
  395. $this->assertResponse(200, 'Session test module is correctly enabled.', 'Session');
  396. }
  397. /**
  398. * Assert whether the SimpleTest browser sent a session cookie.
  399. */
  400. function assertSessionCookie($sent) {
  401. if ($sent) {
  402. $this->assertNotNull($this->session_id, 'Session cookie was sent.');
  403. }
  404. else {
  405. $this->assertNull($this->session_id, 'Session cookie was not sent.');
  406. }
  407. }
  408. /**
  409. * Assert whether $_SESSION is empty at the beginning of the request.
  410. */
  411. function assertSessionEmpty($empty) {
  412. if ($empty) {
  413. $this->assertIdentical($this->drupalGetHeader('X-Session-Empty'), '1', 'Session was empty.');
  414. }
  415. else {
  416. $this->assertIdentical($this->drupalGetHeader('X-Session-Empty'), '0', 'Session was not empty.');
  417. }
  418. }
  419. /**
  420. * Builds a URL for submitting a mock HTTPS request to HTTP test environments.
  421. *
  422. * @param $url
  423. * A Drupal path such as 'user'.
  424. *
  425. * @return
  426. * An absolute URL.
  427. */
  428. protected function httpsUrl($url) {
  429. global $base_url;
  430. return $base_url . '/modules/simpletest/tests/https.php?q=' . $url;
  431. }
  432. }
  433. /**
  434. * Ensure that when running under HTTPS two session cookies are generated.
  435. */
  436. class SessionHttpsTestCase extends DrupalWebTestCase {
  437. public static function getInfo() {
  438. return array(
  439. 'name' => 'Session HTTPS handling',
  440. 'description' => 'Ensure that when running under HTTPS two session cookies are generated.',
  441. 'group' => 'Session'
  442. );
  443. }
  444. public function setUp() {
  445. parent::setUp('session_test');
  446. }
  447. protected function testHttpsSession() {
  448. global $is_https;
  449. if ($is_https) {
  450. $secure_session_name = session_name();
  451. $insecure_session_name = substr(session_name(), 1);
  452. }
  453. else {
  454. $secure_session_name = 'S' . session_name();
  455. $insecure_session_name = session_name();
  456. }
  457. $user = $this->drupalCreateUser(array('access administration pages'));
  458. // Test HTTPS session handling by altering the form action to submit the
  459. // login form through https.php, which creates a mock HTTPS request.
  460. $this->drupalGet('user');
  461. $form = $this->xpath('//form[@id="user-login"]');
  462. $form[0]['action'] = $this->httpsUrl('user');
  463. $edit = array('name' => $user->name, 'pass' => $user->pass_raw);
  464. $this->drupalPost(NULL, $edit, t('Log in'));
  465. // Test a second concurrent session.
  466. $this->curlClose();
  467. $this->drupalGet('user');
  468. $form = $this->xpath('//form[@id="user-login"]');
  469. $form[0]['action'] = $this->httpsUrl('user');
  470. $this->drupalPost(NULL, $edit, t('Log in'));
  471. // Check secure cookie on secure page.
  472. $this->assertTrue($this->cookies[$secure_session_name]['secure'], 'The secure cookie has the secure attribute');
  473. // Check insecure cookie is not set.
  474. $this->assertFalse(isset($this->cookies[$insecure_session_name]));
  475. $ssid = $this->cookies[$secure_session_name]['value'];
  476. $this->assertSessionIds($ssid, $ssid, 'Session has a non-empty SID and a correct secure SID.');
  477. $cookie = $secure_session_name . '=' . $ssid;
  478. // Verify that user is logged in on secure URL.
  479. $this->curlClose();
  480. $this->drupalGet($this->httpsUrl('admin/config'), array(), array('Cookie: ' . $cookie));
  481. $this->assertText(t('Configuration'));
  482. $this->assertResponse(200);
  483. // Verify that user is not logged in on non-secure URL.
  484. $this->curlClose();
  485. $this->drupalGet($this->httpUrl('admin/config'), array(), array('Cookie: ' . $cookie));
  486. $this->assertNoText(t('Configuration'));
  487. $this->assertResponse(403);
  488. // Verify that empty SID cannot be used on the non-secure site.
  489. $this->curlClose();
  490. $cookie = $insecure_session_name . '=';
  491. $this->drupalGet($this->httpUrl('admin/config'), array(), array('Cookie: ' . $cookie));
  492. $this->assertResponse(403);
  493. // Test HTTP session handling by altering the form action to submit the
  494. // login form through http.php, which creates a mock HTTP request on HTTPS
  495. // test environments.
  496. $this->curlClose();
  497. $this->drupalGet('user');
  498. $form = $this->xpath('//form[@id="user-login"]');
  499. $form[0]['action'] = $this->httpUrl('user');
  500. $edit = array('name' => $user->name, 'pass' => $user->pass_raw);
  501. $this->drupalPost(NULL, $edit, t('Log in'));
  502. $this->drupalGet($this->httpUrl('admin/config'));
  503. $this->assertResponse(200);
  504. $sid = $this->cookies[$insecure_session_name]['value'];
  505. $this->assertSessionIds($sid, '', 'Session has the correct SID and an empty secure SID.');
  506. // Verify that empty secure SID cannot be used on the secure site.
  507. $this->curlClose();
  508. $cookie = $secure_session_name . '=';
  509. $this->drupalGet($this->httpsUrl('admin/config'), array(), array('Cookie: ' . $cookie));
  510. $this->assertResponse(403);
  511. // Clear browser cookie jar.
  512. $this->cookies = array();
  513. if ($is_https) {
  514. // The functionality does not make sense when running on HTTPS.
  515. return;
  516. }
  517. // Enable secure pages.
  518. variable_set('https', TRUE);
  519. $this->curlClose();
  520. // Start an anonymous session on the insecure site.
  521. $session_data = $this->randomName();
  522. $this->drupalGet('session-test/set/' . $session_data);
  523. // Check secure cookie on insecure page.
  524. $this->assertFalse(isset($this->cookies[$secure_session_name]), 'The secure cookie is not sent on insecure pages.');
  525. // Check insecure cookie on insecure page.
  526. $this->assertFalse($this->cookies[$insecure_session_name]['secure'], 'The insecure cookie does not have the secure attribute');
  527. // Store the anonymous cookie so we can validate that its session is killed
  528. // after login.
  529. $anonymous_cookie = $insecure_session_name . '=' . $this->cookies[$insecure_session_name]['value'];
  530. // Check that password request form action is not secure.
  531. $this->drupalGet('user/password');
  532. $form = $this->xpath('//form[@id="user-pass"]');
  533. $this->assertNotEqual(substr($form[0]['action'], 0, 6), 'https:', 'Password request form action is not secure');
  534. $form[0]['action'] = $this->httpsUrl('user');
  535. // Check that user login form action is secure.
  536. $this->drupalGet('user');
  537. $form = $this->xpath('//form[@id="user-login"]');
  538. $this->assertEqual(substr($form[0]['action'], 0, 6), 'https:', 'Login form action is secure');
  539. $form[0]['action'] = $this->httpsUrl('user');
  540. $edit = array(
  541. 'name' => $user->name,
  542. 'pass' => $user->pass_raw,
  543. );
  544. $this->drupalPost(NULL, $edit, t('Log in'));
  545. // Check secure cookie on secure page.
  546. $this->assertTrue($this->cookies[$secure_session_name]['secure'], 'The secure cookie has the secure attribute');
  547. // Check insecure cookie on secure page.
  548. $this->assertFalse($this->cookies[$insecure_session_name]['secure'], 'The insecure cookie does not have the secure attribute');
  549. $sid = $this->cookies[$insecure_session_name]['value'];
  550. $ssid = $this->cookies[$secure_session_name]['value'];
  551. $this->assertSessionIds($sid, $ssid, 'Session has both secure and insecure SIDs');
  552. $cookies = array(
  553. $insecure_session_name . '=' . $sid,
  554. $secure_session_name . '=' . $ssid,
  555. );
  556. // Test that session data saved before login is still available on the
  557. // authenticated session.
  558. $this->drupalGet('session-test/get');
  559. $this->assertText($session_data, 'Session correctly returned the stored data set by the anonymous session.');
  560. foreach ($cookies as $cookie_key => $cookie) {
  561. foreach (array('admin/config', $this->httpsUrl('admin/config')) as $url_key => $url) {
  562. $this->curlClose();
  563. $this->drupalGet($url, array(), array('Cookie: ' . $cookie));
  564. if ($cookie_key == $url_key) {
  565. $this->assertText(t('Configuration'));
  566. $this->assertResponse(200);
  567. }
  568. else {
  569. $this->assertNoText(t('Configuration'));
  570. $this->assertResponse(403);
  571. }
  572. }
  573. }
  574. // Test that session data saved before login is not available using the
  575. // pre-login anonymous cookie.
  576. $this->cookies = array();
  577. $this->drupalGet('session-test/get', array('Cookie: ' . $anonymous_cookie));
  578. $this->assertNoText($session_data, 'Initial anonymous session is inactive after login.');
  579. // Clear browser cookie jar.
  580. $this->cookies = array();
  581. // Start an anonymous session on the secure site.
  582. $this->drupalGet($this->httpsUrl('session-test/set/1'));
  583. // Mock a login to the secure site using the secure session cookie.
  584. $this->drupalGet('user');
  585. $form = $this->xpath('//form[@id="user-login"]');
  586. $form[0]['action'] = $this->httpsUrl('user');
  587. $this->drupalPost(NULL, $edit, t('Log in'));
  588. // Test that the user is also authenticated on the insecure site.
  589. $this->drupalGet("user/{$user->uid}/edit");
  590. $this->assertResponse(200);
  591. }
  592. /**
  593. * Tests that empty session IDs do not cause unrelated sessions to load.
  594. */
  595. public function testEmptySessionId() {
  596. global $is_https;
  597. if ($is_https) {
  598. $secure_session_name = session_name();
  599. }
  600. else {
  601. $secure_session_name = 'S' . session_name();
  602. }
  603. // Enable mixed mode for HTTP and HTTPS.
  604. variable_set('https', TRUE);
  605. $admin_user = $this->drupalCreateUser(array('access administration pages'));
  606. $standard_user = $this->drupalCreateUser(array('access content'));
  607. // First log in as the admin user on HTTP.
  608. // We cannot use $this->drupalLogin() here because we need to use the
  609. // special http.php URLs.
  610. $edit = array(
  611. 'name' => $admin_user->name,
  612. 'pass' => $admin_user->pass_raw
  613. );
  614. $this->drupalGet('user');
  615. $form = $this->xpath('//form[@id="user-login"]');
  616. $form[0]['action'] = $this->httpUrl('user');
  617. $this->drupalPost(NULL, $edit, t('Log in'));
  618. $this->curlClose();
  619. // Now start a session for the standard user on HTTPS.
  620. $edit = array(
  621. 'name' => $standard_user->name,
  622. 'pass' => $standard_user->pass_raw
  623. );
  624. $this->drupalGet('user');
  625. $form = $this->xpath('//form[@id="user-login"]');
  626. $form[0]['action'] = $this->httpsUrl('user');
  627. $this->drupalPost(NULL, $edit, t('Log in'));
  628. // Make the secure session cookie blank.
  629. curl_setopt($this->curlHandle, CURLOPT_COOKIE, "$secure_session_name=");
  630. $this->drupalGet($this->httpsUrl('user'));
  631. $this->assertNoText($admin_user->name, 'User is not logged in as admin');
  632. $this->assertNoText($standard_user->name, "The user's own name is not displayed because the invalid session cookie has logged them out.");
  633. }
  634. /**
  635. * Test that there exists a session with two specific session IDs.
  636. *
  637. * @param $sid
  638. * The insecure session ID to search for.
  639. * @param $ssid
  640. * The secure session ID to search for.
  641. * @param $assertion_text
  642. * The text to display when we perform the assertion.
  643. *
  644. * @return
  645. * The result of assertTrue() that there's a session in the system that
  646. * has the given insecure and secure session IDs.
  647. */
  648. protected function assertSessionIds($sid, $ssid, $assertion_text) {
  649. $args = array(
  650. ':sid' => $sid,
  651. ':ssid' => $ssid,
  652. );
  653. return $this->assertTrue(db_query('SELECT timestamp FROM {sessions} WHERE sid = :sid AND ssid = :ssid', $args)->fetchField(), $assertion_text);
  654. }
  655. /**
  656. * Builds a URL for submitting a mock HTTPS request to HTTP test environments.
  657. *
  658. * @param $url
  659. * A Drupal path such as 'user'.
  660. *
  661. * @return
  662. * An absolute URL.
  663. */
  664. protected function httpsUrl($url) {
  665. global $base_url;
  666. return $base_url . '/modules/simpletest/tests/https.php?q=' . $url;
  667. }
  668. /**
  669. * Builds a URL for submitting a mock HTTP request to HTTPS test environments.
  670. *
  671. * @param $url
  672. * A Drupal path such as 'user'.
  673. *
  674. * @return
  675. * An absolute URL.
  676. */
  677. protected function httpUrl($url) {
  678. global $base_url;
  679. return $base_url . '/modules/simpletest/tests/http.php?q=' . $url;
  680. }
  681. }