SessionTest.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
  5. * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  6. *
  7. * Licensed under The MIT License
  8. * For full copyright and license information, please see the LICENSE.txt
  9. * Redistributions of files must retain the above copyright notice
  10. *
  11. * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
  12. * @link https://cakephp.org CakePHP(tm) Project
  13. * @since 1.2.0
  14. * @license https://opensource.org/licenses/mit-license.php MIT License
  15. */
  16. namespace Cake\Test\TestCase\Http;
  17. use Cake\Core\Exception\CakeException;
  18. use Cake\Http\Session;
  19. use Cake\TestSuite\TestCase;
  20. use InvalidArgumentException;
  21. use PHPUnit\Framework\Attributes\PreserveGlobalState;
  22. use PHPUnit\Framework\Attributes\RunInSeparateProcess;
  23. use TestApp\Http\Session\TestAppLibSession;
  24. use TestApp\Http\Session\TestWebSession;
  25. use TestPlugin\Http\Session\TestPluginSession;
  26. /**
  27. * SessionTest class
  28. */
  29. class SessionTest extends TestCase
  30. {
  31. /**
  32. * tearDown method
  33. */
  34. protected function tearDown(): void
  35. {
  36. parent::tearDown();
  37. $this->clearPlugins();
  38. unset($_SESSION);
  39. }
  40. public function testInvalidDefaultsNameException(): void
  41. {
  42. $this->expectException(CakeException::class);
  43. $this->expectExceptionMessage('Invalid session defaults name `derp`. Valid values are: php, cake, cache, database.');
  44. Session::create(['defaults' => 'derp']);
  45. }
  46. /**
  47. * test setting ini properties with Session configuration.
  48. */
  49. #[PreserveGlobalState(false)]
  50. #[RunInSeparateProcess]
  51. public function testSessionConfigIniSetting(): void
  52. {
  53. $_SESSION = null;
  54. $config = [
  55. 'cookie' => 'test',
  56. 'checkAgent' => false,
  57. 'timeout' => 86400,
  58. 'ini' => [
  59. 'session.referer_check' => 'example.com',
  60. 'session.use_trans_sid' => false,
  61. ],
  62. ];
  63. Session::create($config);
  64. $this->assertSame('', ini_get('session.use_trans_sid'), 'Ini value is incorrect');
  65. $this->assertSame('example.com', ini_get('session.referer_check'), 'Ini value is incorrect');
  66. $this->assertSame('test', ini_get('session.name'), 'Ini value is incorrect');
  67. }
  68. /**
  69. * test setting ini properties with Session configuration.
  70. */
  71. #[PreserveGlobalState(false)]
  72. #[RunInSeparateProcess]
  73. public function testSessionConfigTimeoutZero(): void
  74. {
  75. $_SESSION = null;
  76. ini_set('session.gc_maxlifetime', 86400);
  77. $config = [
  78. 'defaults' => 'php',
  79. 'timeout' => 0,
  80. ];
  81. Session::create($config);
  82. $this->assertEquals(86400, ini_get('session.gc_maxlifetime'), 'ini value unchanged when timeout disabled');
  83. }
  84. /**
  85. * test setting ini properties with Session configuration.
  86. */
  87. #[PreserveGlobalState(false)]
  88. #[RunInSeparateProcess]
  89. public function testSessionConfigTimeout(): void
  90. {
  91. $_SESSION = null;
  92. ini_set('session.gc_maxlifetime', 86400);
  93. $config = [
  94. 'defaults' => 'php',
  95. 'timeout' => 30,
  96. ];
  97. Session::create($config);
  98. $this->assertEquals(30 * 60, ini_get('session.gc_maxlifetime'), 'timeout should set gc maxlifetime');
  99. }
  100. /**
  101. * test session cookie path setting
  102. */
  103. #[PreserveGlobalState(false)]
  104. #[RunInSeparateProcess]
  105. public function testCookiePath(): void
  106. {
  107. ini_set('session.cookie_path', '/foo');
  108. new Session();
  109. $this->assertSame('/', ini_get('session.cookie_path'));
  110. new Session(['cookiePath' => '/base']);
  111. $this->assertSame('/base', ini_get('session.cookie_path'));
  112. }
  113. /**
  114. * testCheck method
  115. */
  116. public function testCheck(): void
  117. {
  118. $session = new Session();
  119. $session->write('SessionTestCase', 'value');
  120. $this->assertTrue($session->check());
  121. $this->assertTrue($session->check('SessionTestCase'));
  122. $this->assertFalse($session->check('NotExistingSessionTestCase'));
  123. $this->assertFalse($session->check('Crazy.foo'));
  124. $session->write('Crazy.foo', ['bar' => 'baz']);
  125. $this->assertTrue($session->check('Crazy.foo'));
  126. $this->assertTrue($session->check('Crazy.foo.bar'));
  127. }
  128. /**
  129. * test read with simple values
  130. */
  131. public function testReadSimple(): void
  132. {
  133. $session = new Session();
  134. $session->write('testing', '1,2,3');
  135. $result = $session->read('testing');
  136. $this->assertSame('1,2,3', $result);
  137. $session->write('testing', ['1' => 'one', '2' => 'two', '3' => 'three']);
  138. $result = $session->read('testing.1');
  139. $this->assertSame('one', $result);
  140. $result = $session->read('testing');
  141. $this->assertEquals(['1' => 'one', '2' => 'two', '3' => 'three'], $result);
  142. $result = $session->read();
  143. $this->assertArrayHasKey('testing', $result);
  144. $session->write('This.is.a.deep.array.my.friend', 'value');
  145. $result = $session->read('This.is.a.deep.array');
  146. $this->assertEquals(['my' => ['friend' => 'value']], $result);
  147. }
  148. /**
  149. * testReadEmpty
  150. */
  151. public function testReadEmpty(): void
  152. {
  153. $session = new Session();
  154. $this->assertNull($session->read(''));
  155. }
  156. /**
  157. * test read fallback
  158. */
  159. public function testReadFallback(): void
  160. {
  161. $_SESSION = null;
  162. $session = new Session();
  163. $this->assertSame('default', $session->read('no', 'default'));
  164. }
  165. /**
  166. * Tests read() with defaulting.
  167. */
  168. public function testReadDefault(): void
  169. {
  170. $session = new Session();
  171. $this->assertSame('bar', $session->read('foo', 'bar'));
  172. }
  173. /**
  174. * Tests readOrFail()
  175. */
  176. public function testReadOrFail(): void
  177. {
  178. $session = new Session();
  179. $session->write('testing', '1,2,3');
  180. $result = $session->readOrFail('testing');
  181. $this->assertSame('1,2,3', $result);
  182. $session->write('testing', ['1' => 'one', '2' => 'two', '3' => 'three']);
  183. $result = $session->readOrFail('testing.1');
  184. $this->assertSame('one', $result);
  185. }
  186. /**
  187. * Tests readOrFail() with nonexistent value
  188. */
  189. public function testReadOrFailException(): void
  190. {
  191. $session = new Session();
  192. $this->expectException(CakeException::class);
  193. $session->readOrFail('testing');
  194. }
  195. /**
  196. * Test writing simple keys
  197. */
  198. public function testWriteSimple(): void
  199. {
  200. $session = new Session();
  201. $session->write('', 'empty');
  202. $this->assertSame('empty', $session->read(''));
  203. $session->write('Simple', ['values']);
  204. $this->assertEquals(['values'], $session->read('Simple'));
  205. }
  206. /**
  207. * test writing a hash of values
  208. */
  209. public function testWriteArray(): void
  210. {
  211. $session = new Session();
  212. $session->write([
  213. 'one' => 1,
  214. 'two' => 2,
  215. 'three' => ['something'],
  216. 'null' => null,
  217. ]);
  218. $this->assertSame(1, $session->read('one'));
  219. $this->assertEquals(['something'], $session->read('three'));
  220. $this->assertNull($session->read('null'));
  221. }
  222. /**
  223. * Test overwriting a string value as if it were an array.
  224. */
  225. public function testWriteOverwriteStringValue(): void
  226. {
  227. $session = new Session();
  228. $session->write('Some.string', 'value');
  229. $this->assertSame('value', $session->read('Some.string'));
  230. $session->write('Some.string.array', ['values']);
  231. $this->assertEquals(['values'], $session->read('Some.string.array'));
  232. }
  233. /**
  234. * Test consuming session data.
  235. */
  236. public function testConsume(): void
  237. {
  238. $session = new Session();
  239. $session->write('Some.string', 'value');
  240. $session->write('Some.array', ['key1' => 'value1', 'key2' => 'value2']);
  241. $this->assertSame('value', $session->read('Some.string'));
  242. $value = $session->consume('Some.string');
  243. $this->assertSame('value', $value);
  244. $this->assertFalse($session->check('Some.string'));
  245. $value = $session->consume('');
  246. $this->assertNull($value);
  247. $value = $session->consume('Some.array');
  248. $expected = ['key1' => 'value1', 'key2' => 'value2'];
  249. $this->assertEquals($expected, $value);
  250. $this->assertFalse($session->check('Some.array'));
  251. }
  252. /**
  253. * testId method
  254. */
  255. #[PreserveGlobalState(false)]
  256. #[RunInSeparateProcess]
  257. public function testId(): void
  258. {
  259. $session = new Session();
  260. $session->start();
  261. $result = $session->id();
  262. $this->assertNotEmpty($result);
  263. $this->assertSame(session_id(), $result);
  264. $session->id('MySessionId');
  265. $this->assertSame('MySessionId', $session->id());
  266. $this->assertSame('MySessionId', session_id());
  267. $session->id('');
  268. $this->assertSame('', session_id());
  269. }
  270. /**
  271. * testStarted method
  272. */
  273. public function testStarted(): void
  274. {
  275. $session = new Session();
  276. $this->assertFalse($session->started());
  277. $this->assertTrue($session->start());
  278. $this->assertTrue($session->started());
  279. }
  280. /**
  281. * test close method
  282. */
  283. public function testCloseNotStarted(): void
  284. {
  285. $session = new Session();
  286. $this->assertTrue($session->start());
  287. $session->close();
  288. $this->assertFalse($session->started());
  289. }
  290. /**
  291. * testClear method
  292. */
  293. public function testClear(): void
  294. {
  295. $session = new Session();
  296. $session->write('Delete.me', 'Clearing out');
  297. $session->clear();
  298. $this->assertFalse($session->check('Delete.me'));
  299. $this->assertFalse($session->check('Delete'));
  300. }
  301. /**
  302. * testDelete method
  303. */
  304. public function testDelete(): void
  305. {
  306. $session = new Session();
  307. $session->write('Delete.me', 'Clearing out');
  308. $session->delete('Delete.me');
  309. $this->assertFalse($session->check('Delete.me'));
  310. $this->assertTrue($session->check('Delete'));
  311. $session->write('Clearing.sale', 'everything must go');
  312. $session->delete('');
  313. $this->assertTrue($session->check('Clearing.sale'));
  314. $session->delete('Clearing');
  315. $this->assertFalse($session->check('Clearing.sale'));
  316. $this->assertFalse($session->check('Clearing'));
  317. }
  318. /**
  319. * test delete
  320. */
  321. public function testDeleteEmptyString(): void
  322. {
  323. $session = new Session();
  324. $session->write('', 'empty string');
  325. $session->delete('');
  326. $this->assertFalse($session->check(''));
  327. }
  328. /**
  329. * testDestroy method
  330. */
  331. public function testDestroy(): void
  332. {
  333. $session = new Session();
  334. $session->start();
  335. $session->write('bulletProof', 'invincible');
  336. $session->id('foo');
  337. $session->destroy();
  338. $this->assertFalse($session->check('bulletProof'));
  339. }
  340. /**
  341. * testCheckingSavedEmpty method
  342. */
  343. public function testCheckingSavedEmpty(): void
  344. {
  345. $session = new Session();
  346. $session->write('SessionTestCase', 0);
  347. $this->assertTrue($session->check('SessionTestCase'));
  348. $session->write('SessionTestCase', '0');
  349. $this->assertTrue($session->check('SessionTestCase'));
  350. $session->write('SessionTestCase', false);
  351. $this->assertTrue($session->check('SessionTestCase'));
  352. $session->write('SessionTestCase', null);
  353. $this->assertFalse($session->check('SessionTestCase'));
  354. }
  355. /**
  356. * testCheckKeyWithSpaces method
  357. */
  358. public function testCheckKeyWithSpaces(): void
  359. {
  360. $session = new Session();
  361. $session->write('Session Test', 'test');
  362. $this->assertTrue($session->check('Session Test'));
  363. $session->delete('Session Test');
  364. $session->write('Session Test.Test Case', 'test');
  365. $this->assertTrue($session->check('Session Test.Test Case'));
  366. }
  367. /**
  368. * testCheckEmpty
  369. */
  370. public function testCheckEmpty(): void
  371. {
  372. $session = new Session();
  373. $this->assertFalse($session->check());
  374. }
  375. /**
  376. * test key exploitation
  377. */
  378. public function testKeyExploit(): void
  379. {
  380. $session = new Session();
  381. $key = "a'] = 1; phpinfo(); \$_SESSION['a";
  382. $session->write($key, 'haxored');
  383. $result = $session->read($key);
  384. $this->assertNull($result);
  385. }
  386. /**
  387. * testReadingSavedEmpty method
  388. */
  389. public function testReadingSavedEmpty(): void
  390. {
  391. $session = new Session();
  392. $session->write('', 'empty string');
  393. $this->assertTrue($session->check(''));
  394. $this->assertSame('empty string', $session->read(''));
  395. $session->write('SessionTestCase', 0);
  396. $this->assertSame(0, $session->read('SessionTestCase'));
  397. $session->write('SessionTestCase', '0');
  398. $this->assertSame('0', $session->read('SessionTestCase'));
  399. $this->assertNotSame($session->read('SessionTestCase'), 0);
  400. $session->write('SessionTestCase', false);
  401. $this->assertFalse($session->read('SessionTestCase'));
  402. $session->write('SessionTestCase', null);
  403. $this->assertNull($session->read('SessionTestCase'));
  404. }
  405. /**
  406. * test using a handler from app/Http/Session.
  407. */
  408. #[PreserveGlobalState(false)]
  409. #[RunInSeparateProcess]
  410. public function testUsingAppLibsHandler(): void
  411. {
  412. static::setAppNamespace();
  413. $config = [
  414. 'defaults' => 'cake',
  415. 'handler' => [
  416. 'engine' => 'TestAppLibSession',
  417. 'these' => 'are',
  418. 'a few' => 'options',
  419. ],
  420. ];
  421. $session = Session::create($config);
  422. $this->assertInstanceOf(TestAppLibSession::class, $session->engine());
  423. $this->assertSame('user', ini_get('session.save_handler'));
  424. $this->assertEquals(['these' => 'are', 'a few' => 'options'], $session->engine()->options);
  425. }
  426. /**
  427. * test using a handler from a plugin.
  428. */
  429. #[PreserveGlobalState(false)]
  430. #[RunInSeparateProcess]
  431. public function testUsingPluginHandler(): void
  432. {
  433. static::setAppNamespace();
  434. $this->loadPlugins(['TestPlugin']);
  435. $config = [
  436. 'defaults' => 'cake',
  437. 'handler' => [
  438. 'engine' => 'TestPlugin.TestPluginSession',
  439. ],
  440. ];
  441. $session = Session::create($config);
  442. $this->assertInstanceOf(TestPluginSession::class, $session->engine());
  443. $this->assertSame('user', ini_get('session.save_handler'));
  444. }
  445. /**
  446. * Tests that it is possible to pass an already made instance as the session engine
  447. */
  448. #[PreserveGlobalState(false)]
  449. #[RunInSeparateProcess]
  450. public function testEngineWithPreMadeInstance(): void
  451. {
  452. static::setAppNamespace();
  453. $engine = new TestAppLibSession();
  454. $session = new Session(['handler' => ['engine' => $engine]]);
  455. $this->assertSame($engine, $session->engine());
  456. $session = new Session();
  457. $session->engine($engine);
  458. $this->assertSame($engine, $session->engine());
  459. }
  460. public function testEngineIsNull(): void
  461. {
  462. $session = new Session();
  463. $this->assertNull($session->engine());
  464. }
  465. /**
  466. * Tests instantiating a missing engine
  467. */
  468. public function testBadEngine(): void
  469. {
  470. $this->expectException(InvalidArgumentException::class);
  471. $this->expectExceptionMessage('The class `Derp` does not exist and cannot be used as a session engine');
  472. $session = new Session();
  473. $session->engine('Derp');
  474. }
  475. /**
  476. * Test that cookieTimeout matches timeout when unspecified.
  477. */
  478. #[PreserveGlobalState(false)]
  479. #[RunInSeparateProcess]
  480. public function testCookieTimeoutFallback(): void
  481. {
  482. $config = [
  483. 'defaults' => 'cake',
  484. 'timeout' => 400,
  485. ];
  486. new Session($config);
  487. $this->assertSame('0', ini_get('session.cookie_lifetime'));
  488. $this->assertSame((string)(400 * 60), ini_get('session.gc_maxlifetime'));
  489. }
  490. /**
  491. * Tests that the cookie name can be changed with configuration
  492. */
  493. #[PreserveGlobalState(false)]
  494. #[RunInSeparateProcess]
  495. public function testSessionName(): void
  496. {
  497. new Session(['cookie' => 'made_up_name']);
  498. $this->assertSame('made_up_name', session_name());
  499. }
  500. /**
  501. * Test that a call of check() starts the session when cookies are disabled in php.ini
  502. */
  503. #[PreserveGlobalState(false)]
  504. #[RunInSeparateProcess]
  505. public function testCheckStartsSessionWithCookiesDisabled(): void
  506. {
  507. $_COOKIE = [];
  508. $_GET = [];
  509. $session = new TestWebSession([
  510. 'ini' => [
  511. 'session.use_cookies' => 0,
  512. 'session.use_trans_sid' => 0,
  513. ],
  514. ]);
  515. $this->assertFalse($session->started());
  516. $session->check('something');
  517. $this->assertTrue($session->started());
  518. }
  519. /**
  520. * Test that a call of check() starts the session when a cookie is already set
  521. */
  522. public function testCheckStartsSessionWithCookie(): void
  523. {
  524. $_COOKIE[session_name()] = '123abc';
  525. $_GET = [];
  526. $session = new TestWebSession([
  527. 'ini' => [
  528. 'session.use_cookies' => 1,
  529. 'session.use_trans_sid' => 0,
  530. ],
  531. ]);
  532. $this->assertFalse($session->started());
  533. $session->check('something');
  534. $this->assertTrue($session->started());
  535. }
  536. /**
  537. * Test that a call of check() starts the session when the session ID is passed via URL and session.use_trans_sid is enabled
  538. */
  539. #[PreserveGlobalState(false)]
  540. #[RunInSeparateProcess]
  541. public function testCheckStartsSessionWithSIDinURL(): void
  542. {
  543. $_COOKIE = [];
  544. $_GET[session_name()] = '123abc';
  545. $session = new TestWebSession([
  546. 'ini' => [
  547. 'session.use_cookies' => 1,
  548. 'session.use_trans_sid' => 1,
  549. ],
  550. ]);
  551. $this->assertFalse($session->started());
  552. $session->check('something');
  553. $this->assertTrue($session->started());
  554. }
  555. /**
  556. * Test that a call of check() does not start the session when the session ID is passed via URL and session.use_trans_sid is disabled
  557. */
  558. public function testCheckDoesntStartSessionWithoutTransSID(): void
  559. {
  560. $_COOKIE = [];
  561. $_GET[session_name()] = '123abc';
  562. $session = new TestWebSession([
  563. 'ini' => [
  564. 'session.use_cookies' => 1,
  565. 'session.use_trans_sid' => 0,
  566. ],
  567. ]);
  568. $this->assertFalse($session->started());
  569. $session->check('something');
  570. $this->assertFalse($session->started());
  571. }
  572. }