session.test 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  1. <?php
  2. /**
  3. * @file
  4. * Provides SimpleTests for core session handling functionality.
  5. */
  6. class SessionTestCase extends DrupalWebTestCase {
  7. protected $_logged_in;
  8. public static function getInfo() {
  9. return array(
  10. 'name' => 'Session tests',
  11. 'description' => 'Drupal session handling tests.',
  12. 'group' => 'Session'
  13. );
  14. }
  15. function setUp() {
  16. parent::setUp('session_test');
  17. }
  18. /**
  19. * Tests for drupal_save_session() and drupal_session_regenerate().
  20. */
  21. function testSessionSaveRegenerate() {
  22. $this->assertFalse(drupal_save_session(), 'drupal_save_session() correctly returns FALSE (inside of testing framework) when initially called with no arguments.', 'Session');
  23. $this->assertFalse(drupal_save_session(FALSE), 'drupal_save_session() correctly returns FALSE when called with FALSE.', 'Session');
  24. $this->assertFalse(drupal_save_session(), 'drupal_save_session() correctly returns FALSE when saving has been disabled.', 'Session');
  25. $this->assertTrue(drupal_save_session(TRUE), 'drupal_save_session() correctly returns TRUE when called with TRUE.', 'Session');
  26. $this->assertTrue(drupal_save_session(), 'drupal_save_session() correctly returns TRUE when saving has been enabled.', 'Session');
  27. // Test session hardening code from SA-2008-044.
  28. $user = $this->drupalCreateUser(array('access content'));
  29. // Enable sessions.
  30. $this->sessionReset($user->uid);
  31. // Make sure the session cookie is set as HttpOnly.
  32. $this->drupalLogin($user);
  33. $this->assertTrue(preg_match('/HttpOnly/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie is set as HttpOnly.');
  34. $this->drupalLogout();
  35. // Verify that the session is regenerated if a module calls exit
  36. // in hook_user_login().
  37. user_save($user, array('name' => 'session_test_user'));
  38. $user->name = 'session_test_user';
  39. $this->drupalGet('session-test/id');
  40. $matches = array();
  41. preg_match('/\s*session_id:(.*)\n/', $this->drupalGetContent(), $matches);
  42. $this->assertTrue(!empty($matches[1]) , 'Found session ID before logging in.');
  43. $original_session = $matches[1];
  44. // We cannot use $this->drupalLogin($user); because we exit in
  45. // session_test_user_login() which breaks a normal assertion.
  46. $edit = array(
  47. 'name' => $user->name,
  48. 'pass' => $user->pass_raw
  49. );
  50. $this->drupalPost('user', $edit, t('Log in'));
  51. $this->drupalGet('user');
  52. $pass = $this->assertText($user->name, format_string('Found name: %name', array('%name' => $user->name)), 'User login');
  53. $this->_logged_in = $pass;
  54. $this->drupalGet('session-test/id');
  55. $matches = array();
  56. preg_match('/\s*session_id:(.*)\n/', $this->drupalGetContent(), $matches);
  57. $this->assertTrue(!empty($matches[1]) , 'Found session ID after logging in.');
  58. $this->assertTrue($matches[1] != $original_session, 'Session ID changed after login.');
  59. }
  60. /**
  61. * Test data persistence via the session_test module callbacks.
  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, 'The session value was stored.', 'Session');
  71. $this->drupalGet('session-test/get');
  72. $this->assertText($value_1, 'Session correctly returned the stored data for an authenticated user.', '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, 'The session value was correctly passed to session-test/no-set.', 'Session');
  78. $this->drupalGet('session-test/get');
  79. $this->assertText($value_1, 'Session data is not saved for drupal_save_session(FALSE).', '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, 'Session data persists through browser close.', '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, "After logout, previous user's session data is not available.", '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, 'Session data stored for anonymous user.', 'Session');
  93. $this->drupalGet('session-test/get');
  94. $this->assertText($value_3, 'Session correctly returned the stored data for an anonymous user.', '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, 'The session value was correctly passed to session-test/no-set.', 'Session');
  99. $this->drupalGet('session-test/get');
  100. $this->assertText($value_3, 'Session data is not saved for drupal_save_session(FALSE).', '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, 'Session has persisted for an authenticated user after logging out and then back in.', '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', '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'), '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'), 'Caching was bypassed.');
  135. $this->assertText(t('This is a dummy message.'), 'Message was displayed.');
  136. $this->assertTrue(preg_match('/SESS\w+=deleted/', $this->drupalGetHeader('Set-Cookie')), '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.'), 'Message was not cached.');
  142. $this->assertEqual($this->drupalGetHeader('X-Drupal-Cache'), 'HIT', 'Page was cached.');
  143. $this->assertFalse($this->drupalGetHeader('Set-Cookie'), '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.'), '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, 'Users table was not updated.');
  169. $this->assertNotEqual($times2->timestamp, $times1->timestamp, '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, 'Users table was not updated.');
  175. $this->assertEqual($times3->timestamp, $times2->timestamp, '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, 'Users table was not updated.');
  181. $this->assertEqual($times4->timestamp, $times3->timestamp, '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, 'Users table was updated.');
  187. $this->assertNotEqual($times5->timestamp, $times4->timestamp, '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, '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", '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, 'An empty session ID is not allowed.');
  210. }
  211. /**
  212. * Test hashing of session ids in the database.
  213. */
  214. function testHashedSessionIds() {
  215. $user = $this->drupalCreateUser(array('access content'));
  216. $this->drupalLogin($user);
  217. $this->drupalGet('session-test/is-logged-in');
  218. $this->assertResponse(200, 'User is logged in.');
  219. $this->drupalGet('session-test/id');
  220. $matches = array();
  221. preg_match('/\s*session_id:(.*)\n/', $this->drupalGetContent(), $matches);
  222. $this->assertTrue(!empty($matches[1]) , 'Found session ID after logging in.');
  223. $session_id = $matches[1];
  224. $this->drupalGet('session-test/id-from-cookie');
  225. $matches = array();
  226. preg_match('/\s*session_id:(.*)\n/', $this->drupalGetContent(), $matches);
  227. $this->assertTrue(!empty($matches[1]) , 'Found session ID from cookie.');
  228. $cookie_session_id = $matches[1];
  229. $this->assertEqual($session_id, $cookie_session_id, 'Session id and cookie session id are the same.');
  230. $sql = 'SELECT s.sid FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE u.uid = :uid';
  231. $db_session = db_query($sql, array(':uid' => $user->uid))->fetchObject();
  232. $this->assertNotEqual($db_session->sid, $cookie_session_id, 'Session id in the database is not the same as in the session cookie.');
  233. $this->assertEqual($db_session->sid, drupal_hash_base64($cookie_session_id), 'Session id in the database is the cookie session id hashed.');
  234. }
  235. /**
  236. * Test opt-out of hashing of session ids in the database.
  237. */
  238. function testHashedSessionIdsOptOut() {
  239. variable_set('do_not_hash_session_ids', TRUE);
  240. $user = $this->drupalCreateUser(array('access content'));
  241. $this->drupalLogin($user);
  242. $this->drupalGet('session-test/is-logged-in');
  243. $this->assertResponse(200, 'User is logged in.');
  244. $this->drupalGet('session-test/id');
  245. $matches = array();
  246. preg_match('/\s*session_id:(.*)\n/', $this->drupalGetContent(), $matches);
  247. $this->assertTrue(!empty($matches[1]) , 'Found session ID after logging in.');
  248. $session_id = $matches[1];
  249. $this->drupalGet('session-test/id-from-cookie');
  250. $matches = array();
  251. preg_match('/\s*session_id:(.*)\n/', $this->drupalGetContent(), $matches);
  252. $this->assertTrue(!empty($matches[1]) , 'Found session ID from cookie.');
  253. $cookie_session_id = $matches[1];
  254. $this->assertEqual($session_id, $cookie_session_id, 'Session id and cookie session id are the same.');
  255. $sql = 'SELECT s.sid FROM {users} u INNER JOIN {sessions} s ON u.uid = s.uid WHERE u.uid = :uid';
  256. $db_session = db_query($sql, array(':uid' => $user->uid))->fetchObject();
  257. $this->assertEqual($db_session->sid, $cookie_session_id, 'Session id in the database is the same as in the session cookie.');
  258. $this->assertNotEqual($db_session->sid, drupal_hash_base64($cookie_session_id), 'Session id in the database is not the cookie session id hashed.');
  259. }
  260. /**
  261. * Test absence of SameSite attribute on session cookies by default.
  262. */
  263. function testNoSameSiteCookieAttributeDefault() {
  264. $user = $this->drupalCreateUser(array('access content'));
  265. $this->sessionReset($user->uid);
  266. if (\PHP_VERSION_ID < 70300) {
  267. $this->drupalLogin($user);
  268. }
  269. else {
  270. // PHP often defaults to an empty value for session.cookie_samesite but
  271. // that may vary, so we set an explicit empty value.
  272. // Send our own login POST so that we can pass a custom header to trigger
  273. // session_test.module to call ini_set('session.cookie_samesite', $value)
  274. $headers[] = 'X-Session-Cookie-Ini-Set: *EMPTY*';
  275. $edit = array(
  276. 'name' => $user->name,
  277. 'pass' => $user->pass_raw,
  278. );
  279. $this->drupalPost('user', $edit, t('Log in'), array(), $headers);
  280. }
  281. $this->assertFalse(preg_match('/SameSite=/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie has no SameSite attribute (default).');
  282. }
  283. /**
  284. * Test SameSite attribute = None by default on Secure session cookies.
  285. */
  286. function testSameSiteCookieAttributeNoneSecure() {
  287. $user = $this->drupalCreateUser(array('access content'));
  288. $this->sessionReset($user->uid);
  289. $headers = array();
  290. if (\PHP_VERSION_ID >= 70300) {
  291. // Send our own login POST so that we can pass a custom header to trigger
  292. // session_test.module to call ini_set('session.cookie_samesite', $value)
  293. $headers[] = 'X-Session-Cookie-Ini-Set: None';
  294. }
  295. // Test HTTPS session handling by altering the form action to submit the
  296. // login form through https.php, which creates a mock HTTPS request.
  297. $this->drupalGet('user');
  298. $form = $this->xpath('//form[@id="user-login"]');
  299. $form[0]['action'] = $this->httpsUrl('user');
  300. $edit = array('name' => $user->name, 'pass' => $user->pass_raw);
  301. $this->drupalPost(NULL, $edit, t('Log in'), array(), $headers);
  302. $this->assertTrue(preg_match('/SameSite=None/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie is set as SameSite=None.');
  303. }
  304. /**
  305. * Test SameSite attribute = None on session cookies.
  306. */
  307. function testSameSiteCookieAttributeNone() {
  308. variable_set('samesite_cookie_value', 'None');
  309. $user = $this->drupalCreateUser(array('access content'));
  310. $this->sessionReset($user->uid);
  311. $this->drupalLogin($user);
  312. $this->assertTrue(preg_match('/SameSite=None/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie is set as SameSite=None.');
  313. }
  314. /**
  315. * Test SameSite attribute = Lax on session cookies.
  316. */
  317. function testSameSiteCookieAttributeLax() {
  318. variable_set('samesite_cookie_value', 'Lax');
  319. $user = $this->drupalCreateUser(array('access content'));
  320. $this->sessionReset($user->uid);
  321. $this->drupalLogin($user);
  322. $this->assertTrue(preg_match('/SameSite=Lax/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie is set as SameSite=Lax.');
  323. }
  324. /**
  325. * Test SameSite attribute = Strict on session cookies.
  326. */
  327. function testSameSiteCookieAttributeStrict() {
  328. variable_set('samesite_cookie_value', 'Strict');
  329. $user = $this->drupalCreateUser(array('access content'));
  330. $this->sessionReset($user->uid);
  331. $this->drupalLogin($user);
  332. $this->assertTrue(preg_match('/SameSite=Strict/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie is set as SameSite=Strict.');
  333. }
  334. /**
  335. * Test disabling the samesite attribute on session cookies via $conf
  336. */
  337. function testSameSiteCookieAttributeDisabledViaConf() {
  338. $user = $this->drupalCreateUser(array('access content'));
  339. $this->sessionReset($user->uid);
  340. variable_set('samesite_cookie_value', FALSE);
  341. if (\PHP_VERSION_ID < 70300) {
  342. // There is no session.cookie_samesite in earlier PHP versions.
  343. $this->drupalLogin($user);
  344. }
  345. else {
  346. // Send our own login POST so that we can pass a custom header to trigger
  347. // session_test.module to call ini_set('session.cookie_samesite', $value)
  348. $headers[] = 'X-Session-Cookie-Ini-Set: Lax';
  349. $edit = array(
  350. 'name' => $user->name,
  351. 'pass' => $user->pass_raw,
  352. );
  353. $this->drupalPost('user', $edit, t('Log in'), array(), $headers);
  354. }
  355. $this->assertFalse(preg_match('/SameSite=/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie has no SameSite attribute (conf).');
  356. }
  357. /**
  358. * Test disabling the samesite attribute on session cookies via php ini
  359. */
  360. function testSameSiteCookieAttributeDisabledViaPhpIni() {
  361. if (\PHP_VERSION_ID < 70300) {
  362. // There is no session.cookie_samesite in earlier PHP versions.
  363. $this->pass('This test is only for PHP 7.3 and later.');
  364. return;
  365. }
  366. $user = $this->drupalCreateUser(array('access content'));
  367. // Send our own login POST so that we can pass a custom header to trigger
  368. // session_test.module to call ini_set('session.cookie_samesite', $value)
  369. $headers[] = 'X-Session-Cookie-Ini-Set: *EMPTY*';
  370. $edit = array(
  371. 'name' => $user->name,
  372. 'pass' => $user->pass_raw,
  373. );
  374. $this->drupalPost('user', $edit, t('Log in'), array(), $headers);
  375. $this->assertFalse(preg_match('/SameSite=/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie has no SameSite attribute (ini).');
  376. }
  377. /**
  378. * Test that a PHP setting for session.cookie_samesite is not overridden by
  379. * the default value in Drupal, without a samesite_cookie_value variable.
  380. */
  381. function testSamesiteCookiePhpSettingLax() {
  382. if (\PHP_VERSION_ID < 70300) {
  383. // There is no session.cookie_samesite in earlier PHP versions.
  384. $this->pass('This test is only for PHP 7.3 and later.');
  385. return;
  386. }
  387. $user = $this->drupalCreateUser(array('access content'));
  388. // Send our own login POST so that we can pass a custom header to trigger
  389. // session_test.module to call ini_set('session.cookie_samesite', $value)
  390. $headers[] = 'X-Session-Cookie-Ini-Set: Lax';
  391. $edit = array(
  392. 'name' => $user->name,
  393. 'pass' => $user->pass_raw,
  394. );
  395. $this->drupalPost('user', $edit, t('Log in'), array(), $headers);
  396. $this->assertTrue(preg_match('/SameSite=Lax/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie is set as SameSite=Lax.');
  397. }
  398. /**
  399. * Test overriding the PHP setting for session.cookie_samesite with the
  400. * samesite_cookie_value variable.
  401. */
  402. function testSamesiteCookieOverrideLaxToStrict() {
  403. if (\PHP_VERSION_ID < 70300) {
  404. // There is no session.cookie_samesite in earlier PHP versions.
  405. $this->pass('This test is only for PHP 7.3 and later.');
  406. return;
  407. }
  408. variable_set('samesite_cookie_value', 'Strict');
  409. $user = $this->drupalCreateUser(array('access content'));
  410. // Send our own login POST so that we can pass a custom header to trigger
  411. // session_test.module to call ini_set('session.cookie_samesite', $value)
  412. $headers[] = 'X-Session-Cookie-Ini-Set: Lax';
  413. $edit = array(
  414. 'name' => $user->name,
  415. 'pass' => $user->pass_raw,
  416. );
  417. $this->drupalPost('user', $edit, t('Log in'), array(), $headers);
  418. $this->assertTrue(preg_match('/SameSite=Strict/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie is set as SameSite=Strict.');
  419. }
  420. /**
  421. * Test SameSite attribute = Lax on set-cookie header on logout.
  422. */
  423. function testSamesiteCookieLogoutLax() {
  424. variable_set('samesite_cookie_value', 'Lax');
  425. $user = $this->drupalCreateUser(array('access content'));
  426. $this->sessionReset($user->uid);
  427. $this->drupalLogin($user);
  428. $this->drupalGet('user/logout');
  429. $this->assertTrue(preg_match('/SameSite=Lax/i', $this->drupalGetHeader('Set-Cookie', TRUE)), 'Session cookie deletion includes SameSite=Lax.');
  430. }
  431. /**
  432. * Reset the cookie file so that it refers to the specified user.
  433. *
  434. * @param $uid User id to set as the active session.
  435. */
  436. function sessionReset($uid = 0) {
  437. // Close the internal browser.
  438. $this->curlClose();
  439. $this->loggedInUser = FALSE;
  440. // Change cookie file for user.
  441. $this->cookieFile = file_stream_wrapper_get_instance_by_scheme('temporary')->getDirectoryPath() . '/cookie.' . $uid . '.txt';
  442. $this->additionalCurlOptions[CURLOPT_COOKIEFILE] = $this->cookieFile;
  443. $this->additionalCurlOptions[CURLOPT_COOKIESESSION] = TRUE;
  444. $this->drupalGet('session-test/get');
  445. $this->assertResponse(200, 'Session test module is correctly enabled.', 'Session');
  446. }
  447. /**
  448. * Assert whether the SimpleTest browser sent a session cookie.
  449. */
  450. function assertSessionCookie($sent) {
  451. if ($sent) {
  452. $this->assertNotNull($this->session_id, 'Session cookie was sent.');
  453. }
  454. else {
  455. $this->assertNull($this->session_id, 'Session cookie was not sent.');
  456. }
  457. }
  458. /**
  459. * Assert whether $_SESSION is empty at the beginning of the request.
  460. */
  461. function assertSessionEmpty($empty) {
  462. if ($empty) {
  463. $this->assertIdentical($this->drupalGetHeader('X-Session-Empty'), '1', 'Session was empty.');
  464. }
  465. else {
  466. $this->assertIdentical($this->drupalGetHeader('X-Session-Empty'), '0', 'Session was not empty.');
  467. }
  468. }
  469. /**
  470. * Builds a URL for submitting a mock HTTPS request to HTTP test environments.
  471. *
  472. * @param $url
  473. * A Drupal path such as 'user'.
  474. *
  475. * @return
  476. * An absolute URL.
  477. */
  478. protected function httpsUrl($url) {
  479. global $base_url;
  480. return $base_url . '/modules/simpletest/tests/https.php?q=' . $url;
  481. }
  482. }
  483. /**
  484. * Ensure that when running under HTTPS two session cookies are generated.
  485. */
  486. class SessionHttpsTestCase extends DrupalWebTestCase {
  487. public static function getInfo() {
  488. return array(
  489. 'name' => 'Session HTTPS handling',
  490. 'description' => 'Ensure that when running under HTTPS two session cookies are generated.',
  491. 'group' => 'Session'
  492. );
  493. }
  494. public function setUp() {
  495. parent::setUp('session_test');
  496. }
  497. protected function testHttpsSession() {
  498. global $is_https;
  499. if ($is_https) {
  500. $secure_session_name = session_name();
  501. $insecure_session_name = substr(session_name(), 1);
  502. }
  503. else {
  504. $secure_session_name = 'S' . session_name();
  505. $insecure_session_name = session_name();
  506. }
  507. $user = $this->drupalCreateUser(array('access administration pages'));
  508. // Test HTTPS session handling by altering the form action to submit the
  509. // login form through https.php, which creates a mock HTTPS request.
  510. $this->drupalGet('user');
  511. $form = $this->xpath('//form[@id="user-login"]');
  512. $form[0]['action'] = $this->httpsUrl('user');
  513. $edit = array('name' => $user->name, 'pass' => $user->pass_raw);
  514. $this->drupalPost(NULL, $edit, t('Log in'));
  515. // Test a second concurrent session.
  516. $this->curlClose();
  517. $this->drupalGet('user');
  518. $form = $this->xpath('//form[@id="user-login"]');
  519. $form[0]['action'] = $this->httpsUrl('user');
  520. $this->drupalPost(NULL, $edit, t('Log in'));
  521. // Check secure cookie on secure page.
  522. $this->assertTrue($this->cookies[$secure_session_name]['secure'], 'The secure cookie has the secure attribute');
  523. // Check insecure cookie is not set.
  524. $this->assertFalse(isset($this->cookies[$insecure_session_name]));
  525. $ssid = $this->cookies[$secure_session_name]['value'];
  526. $this->assertSessionIds($ssid, $ssid, 'Session has a non-empty SID and a correct secure SID.');
  527. $cookie = $secure_session_name . '=' . $ssid;
  528. // Verify that user is logged in on secure URL.
  529. $this->curlClose();
  530. $this->drupalGet($this->httpsUrl('admin/config'), array(), array('Cookie: ' . $cookie));
  531. $this->assertText(t('Configuration'));
  532. $this->assertResponse(200);
  533. // Verify that user is not logged in on non-secure URL.
  534. $this->curlClose();
  535. $this->drupalGet($this->httpUrl('admin/config'), array(), array('Cookie: ' . $cookie));
  536. $this->assertNoText(t('Configuration'));
  537. $this->assertResponse(403);
  538. // Verify that empty SID cannot be used on the non-secure site.
  539. $this->curlClose();
  540. $cookie = $insecure_session_name . '=';
  541. $this->drupalGet($this->httpUrl('admin/config'), array(), array('Cookie: ' . $cookie));
  542. $this->assertResponse(403);
  543. // Test HTTP session handling by altering the form action to submit the
  544. // login form through http.php, which creates a mock HTTP request on HTTPS
  545. // test environments.
  546. $this->curlClose();
  547. $this->drupalGet('user');
  548. $form = $this->xpath('//form[@id="user-login"]');
  549. $form[0]['action'] = $this->httpUrl('user');
  550. $edit = array('name' => $user->name, 'pass' => $user->pass_raw);
  551. $this->drupalPost(NULL, $edit, t('Log in'));
  552. $this->drupalGet($this->httpUrl('admin/config'));
  553. $this->assertResponse(200);
  554. $sid = $this->cookies[$insecure_session_name]['value'];
  555. $this->assertSessionIds($sid, '', 'Session has the correct SID and an empty secure SID.');
  556. // Verify that empty secure SID cannot be used on the secure site.
  557. $this->curlClose();
  558. $cookie = $secure_session_name . '=';
  559. $this->drupalGet($this->httpsUrl('admin/config'), array(), array('Cookie: ' . $cookie));
  560. $this->assertResponse(403);
  561. // Clear browser cookie jar.
  562. $this->cookies = array();
  563. if ($is_https) {
  564. // The functionality does not make sense when running on HTTPS.
  565. return;
  566. }
  567. // Enable secure pages.
  568. variable_set('https', TRUE);
  569. $this->curlClose();
  570. // Start an anonymous session on the insecure site.
  571. $session_data = $this->randomName();
  572. $this->drupalGet('session-test/set/' . $session_data);
  573. // Check secure cookie on insecure page.
  574. $this->assertFalse(isset($this->cookies[$secure_session_name]), 'The secure cookie is not sent on insecure pages.');
  575. // Check insecure cookie on insecure page.
  576. $this->assertFalse($this->cookies[$insecure_session_name]['secure'], 'The insecure cookie does not have the secure attribute');
  577. // Store the anonymous cookie so we can validate that its session is killed
  578. // after login.
  579. $anonymous_cookie = $insecure_session_name . '=' . $this->cookies[$insecure_session_name]['value'];
  580. // Check that password request form action is not secure.
  581. $this->drupalGet('user/password');
  582. $form = $this->xpath('//form[@id="user-pass"]');
  583. $this->assertNotEqual(substr($form[0]['action'], 0, 6), 'https:', 'Password request form action is not secure');
  584. $form[0]['action'] = $this->httpsUrl('user');
  585. // Check that user login form action is secure.
  586. $this->drupalGet('user');
  587. $form = $this->xpath('//form[@id="user-login"]');
  588. $this->assertEqual(substr($form[0]['action'], 0, 6), 'https:', 'Login form action is secure');
  589. $form[0]['action'] = $this->httpsUrl('user');
  590. $edit = array(
  591. 'name' => $user->name,
  592. 'pass' => $user->pass_raw,
  593. );
  594. $this->drupalPost(NULL, $edit, t('Log in'));
  595. // Check secure cookie on secure page.
  596. $this->assertTrue($this->cookies[$secure_session_name]['secure'], 'The secure cookie has the secure attribute');
  597. // Check insecure cookie on secure page.
  598. $this->assertFalse($this->cookies[$insecure_session_name]['secure'], 'The insecure cookie does not have the secure attribute');
  599. $sid = $this->cookies[$insecure_session_name]['value'];
  600. $ssid = $this->cookies[$secure_session_name]['value'];
  601. $this->assertSessionIds($sid, $ssid, 'Session has both secure and insecure SIDs');
  602. $cookies = array(
  603. $insecure_session_name . '=' . $sid,
  604. $secure_session_name . '=' . $ssid,
  605. );
  606. // Test that session data saved before login is still available on the
  607. // authenticated session.
  608. $this->drupalGet('session-test/get');
  609. $this->assertText($session_data, 'Session correctly returned the stored data set by the anonymous session.');
  610. foreach ($cookies as $cookie_key => $cookie) {
  611. foreach (array('admin/config', $this->httpsUrl('admin/config')) as $url_key => $url) {
  612. $this->curlClose();
  613. $this->drupalGet($url, array(), array('Cookie: ' . $cookie));
  614. if ($cookie_key == $url_key) {
  615. $this->assertText(t('Configuration'));
  616. $this->assertResponse(200);
  617. }
  618. else {
  619. $this->assertNoText(t('Configuration'));
  620. $this->assertResponse(403);
  621. }
  622. }
  623. }
  624. // Test that session data saved before login is not available using the
  625. // pre-login anonymous cookie.
  626. $this->cookies = array();
  627. $this->drupalGet('session-test/get', array('Cookie: ' . $anonymous_cookie));
  628. $this->assertNoText($session_data, 'Initial anonymous session is inactive after login.');
  629. // Clear browser cookie jar.
  630. $this->cookies = array();
  631. // Start an anonymous session on the secure site.
  632. $this->drupalGet($this->httpsUrl('session-test/set/1'));
  633. // Mock a login to the secure site using the secure session cookie.
  634. $this->drupalGet('user');
  635. $form = $this->xpath('//form[@id="user-login"]');
  636. $form[0]['action'] = $this->httpsUrl('user');
  637. $this->drupalPost(NULL, $edit, t('Log in'));
  638. // Test that the user is also authenticated on the insecure site.
  639. $this->drupalGet("user/{$user->uid}/edit");
  640. $this->assertResponse(200);
  641. }
  642. /**
  643. * Tests that empty session IDs do not cause unrelated sessions to load.
  644. */
  645. public function testEmptySessionId() {
  646. global $is_https;
  647. if ($is_https) {
  648. $secure_session_name = session_name();
  649. }
  650. else {
  651. $secure_session_name = 'S' . session_name();
  652. }
  653. // Enable mixed mode for HTTP and HTTPS.
  654. variable_set('https', TRUE);
  655. $admin_user = $this->drupalCreateUser(array('access administration pages'));
  656. $standard_user = $this->drupalCreateUser(array('access content'));
  657. // First log in as the admin user on HTTP.
  658. // We cannot use $this->drupalLogin() here because we need to use the
  659. // special http.php URLs.
  660. $edit = array(
  661. 'name' => $admin_user->name,
  662. 'pass' => $admin_user->pass_raw
  663. );
  664. $this->drupalGet('user');
  665. $form = $this->xpath('//form[@id="user-login"]');
  666. $form[0]['action'] = $this->httpUrl('user');
  667. $this->drupalPost(NULL, $edit, t('Log in'));
  668. $this->curlClose();
  669. // Now start a session for the standard user on HTTPS.
  670. $edit = array(
  671. 'name' => $standard_user->name,
  672. 'pass' => $standard_user->pass_raw
  673. );
  674. $this->drupalGet('user');
  675. $form = $this->xpath('//form[@id="user-login"]');
  676. $form[0]['action'] = $this->httpsUrl('user');
  677. $this->drupalPost(NULL, $edit, t('Log in'));
  678. // Make the secure session cookie blank.
  679. curl_setopt($this->curlHandle, CURLOPT_COOKIE, "$secure_session_name=");
  680. $this->drupalGet($this->httpsUrl('user'));
  681. $this->assertNoText($admin_user->name, 'User is not logged in as admin');
  682. $this->assertNoText($standard_user->name, "The user's own name is not displayed because the invalid session cookie has logged them out.");
  683. }
  684. /**
  685. * Test that there exists a session with two specific session IDs.
  686. *
  687. * @param $sid
  688. * The insecure session ID to search for.
  689. * @param $ssid
  690. * The secure session ID to search for.
  691. * @param $assertion_text
  692. * The text to display when we perform the assertion.
  693. *
  694. * @return
  695. * The result of assertTrue() that there's a session in the system that
  696. * has the given insecure and secure session IDs.
  697. */
  698. protected function assertSessionIds($sid, $ssid, $assertion_text) {
  699. $args = array(
  700. ':sid' => drupal_session_id($sid),
  701. ':ssid' => !empty($ssid) ? drupal_session_id($ssid) : '',
  702. );
  703. return $this->assertTrue(db_query('SELECT timestamp FROM {sessions} WHERE sid = :sid AND ssid = :ssid', $args)->fetchField(), $assertion_text);
  704. }
  705. /**
  706. * Builds a URL for submitting a mock HTTPS request to HTTP test environments.
  707. *
  708. * @param $url
  709. * A Drupal path such as 'user'.
  710. *
  711. * @return
  712. * An absolute URL.
  713. */
  714. protected function httpsUrl($url) {
  715. global $base_url;
  716. return $base_url . '/modules/simpletest/tests/https.php?q=' . $url;
  717. }
  718. /**
  719. * Builds a URL for submitting a mock HTTP request to HTTPS test environments.
  720. *
  721. * @param $url
  722. * A Drupal path such as 'user'.
  723. *
  724. * @return
  725. * An absolute URL.
  726. */
  727. protected function httpUrl($url) {
  728. global $base_url;
  729. return $base_url . '/modules/simpletest/tests/http.php?q=' . $url;
  730. }
  731. }
  732. /**
  733. * Unit tests for session handling.
  734. */
  735. class SessionUnitTestCase extends DrupalUnitTestCase {
  736. /**
  737. * {@inheritdoc}
  738. */
  739. public static function getInfo() {
  740. return array(
  741. 'name' => 'Session unit tests',
  742. 'description' => 'Test session handling functionality.',
  743. 'group' => 'Session',
  744. );
  745. }
  746. function testCookieDomain() {
  747. $tests = array(
  748. array('example.com', '.example.com'),
  749. array('www.example.com', '.www.example.com'),
  750. array('subdomain.example.com', '.subdomain.example.com'),
  751. );
  752. foreach ($tests as $test) {
  753. $this->assertEqual(_drupal_get_cookie_domain($test[0]), $test[1], 'Correct $cookie_domain for host ' . $test[0]);
  754. }
  755. }
  756. /**
  757. * Unit test drupal_settings_initialize().
  758. */
  759. function testSessionInitialization() {
  760. global $base_url, $cookie_domain;
  761. $tests = array(
  762. array(
  763. 'http_host' => 'example.com',
  764. 'script_name' => '/index.php',
  765. 'session_name' => 'SESSa379a6f6eeafb9a55e378c118034e275',
  766. 'base_url' => 'http://example.com',
  767. 'cookie_domain' => '.example.com',
  768. ),
  769. array(
  770. 'http_host' => 'example.com',
  771. 'script_name' => '/foo/index.php',
  772. 'session_name' => 'SESS76f699faa11e8fbe9a70d933651df90f',
  773. 'base_url' => 'http://example.com/foo',
  774. 'cookie_domain' => '.example.com',
  775. ),
  776. array(
  777. 'http_host' => 'one.two.example.com',
  778. 'script_name' => '/index.php',
  779. 'session_name' => 'SESSc0cc73483118b575693f5c255faeb739',
  780. 'base_url' => 'http://one.two.example.com',
  781. 'cookie_domain' => '.one.two.example.com',
  782. ),
  783. array(
  784. 'http_host' => 'www.sub.example.com',
  785. 'script_name' => '/index.php',
  786. 'session_name' => 'SESSdc70980beaa5d571d3c9785cf9246c96',
  787. 'base_url' => 'http://www.sub.example.com',
  788. 'cookie_domain' => '.www.sub.example.com',
  789. ),
  790. array(
  791. 'http_host' => 'example.com',
  792. 'script_name' => '/foo/bar/index.php',
  793. 'session_name' => 'SESSdbf7edcf4f2656b247021ceb4752f7f9',
  794. 'base_url' => 'http://example.com/foo/bar',
  795. 'cookie_domain' => '.example.com',
  796. ),
  797. array(
  798. 'http_host' => 'www.sub.example.com',
  799. 'script_name' => '/baz/index.php',
  800. 'session_name' => 'SESS63543f965940db9e8a79801aa6d52423',
  801. 'base_url' => 'http://www.sub.example.com/baz',
  802. 'cookie_domain' => '.www.sub.example.com',
  803. ),
  804. array(
  805. 'http_host' => 'sub.example.com',
  806. 'script_name' => '/index.php',
  807. 'session_name' => 'SESS005c4a974d8b94af421206f9ef34efeb',
  808. 'base_url' => 'http://sub.example.com',
  809. 'cookie_domain' => '.sub.example.com',
  810. ),
  811. array(
  812. 'http_host' => 'www.example.com',
  813. 'script_name' => '/index.php',
  814. 'session_name' => 'SESS0e9f0e2600e4d8f26827597c5e324261',
  815. 'base_url' => 'http://www.example.com',
  816. 'cookie_domain' => '.www.example.com',
  817. ),
  818. array(
  819. 'http_host' => 'www.example.com',
  820. 'script_name' => '/foo/index.php',
  821. 'session_name' => 'SESS0ddd0afc0bece848c840cdcd7b8ed9c9',
  822. 'base_url' => 'http://www.example.com/foo',
  823. 'cookie_domain' => '.www.example.com',
  824. ),
  825. array(
  826. 'http_host' => 'www.example.com',
  827. 'script_name' => '/bar/index.php',
  828. 'session_name' => 'SESS22f2cd08599536cb4363fcd09e29d264',
  829. 'base_url' => 'http://www.example.com/bar',
  830. 'cookie_domain' => '.www.example.com',
  831. ),
  832. );
  833. foreach ($tests as $test) {
  834. $_SERVER['HTTP_HOST'] = $test['http_host'];
  835. $_SERVER['SCRIPT_NAME'] = $test['script_name'];
  836. $cookie_domain = NULL;
  837. $base_url = NULL;
  838. drupal_settings_initialize();
  839. $this->assertEqual(session_name(), $test['session_name'], 'Correct session_name for ' . $test['http_host'] . $test['script_name']);
  840. $this->assertEqual($base_url, $test['base_url'], 'Correct base_url for ' . $test['http_host'] . $test['script_name']);
  841. $this->assertEqual($cookie_domain, $test['cookie_domain'], 'Correct cookie_domain for ' . $test['http_host'] . $test['script_name']);
  842. }
  843. }
  844. }