PdoSessionHandlerTest.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\HttpFoundation\Tests\Session\Storage\Handler;
  11. use PHPUnit\Framework\TestCase;
  12. use Symfony\Component\HttpFoundation\Session\Storage\Handler\PdoSessionHandler;
  13. /**
  14. * @requires extension pdo_sqlite
  15. *
  16. * @group time-sensitive
  17. */
  18. class PdoSessionHandlerTest extends TestCase
  19. {
  20. private $dbFile;
  21. protected function tearDown(): void
  22. {
  23. // make sure the temporary database file is deleted when it has been created (even when a test fails)
  24. if ($this->dbFile) {
  25. @unlink($this->dbFile);
  26. }
  27. parent::tearDown();
  28. }
  29. protected function getPersistentSqliteDsn()
  30. {
  31. $this->dbFile = tempnam(sys_get_temp_dir(), 'sf_sqlite_sessions');
  32. return 'sqlite:'.$this->dbFile;
  33. }
  34. protected function getMemorySqlitePdo()
  35. {
  36. $pdo = new \PDO('sqlite::memory:');
  37. $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
  38. $storage = new PdoSessionHandler($pdo);
  39. $storage->createTable();
  40. return $pdo;
  41. }
  42. public function testWrongPdoErrMode()
  43. {
  44. $this->expectException(\InvalidArgumentException::class);
  45. $pdo = $this->getMemorySqlitePdo();
  46. $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT);
  47. new PdoSessionHandler($pdo);
  48. }
  49. public function testInexistentTable()
  50. {
  51. $this->expectException(\RuntimeException::class);
  52. $storage = new PdoSessionHandler($this->getMemorySqlitePdo(), ['db_table' => 'inexistent_table']);
  53. $storage->open('', 'sid');
  54. $storage->read('id');
  55. $storage->write('id', 'data');
  56. $storage->close();
  57. }
  58. public function testCreateTableTwice()
  59. {
  60. $this->expectException(\RuntimeException::class);
  61. $storage = new PdoSessionHandler($this->getMemorySqlitePdo());
  62. $storage->createTable();
  63. }
  64. public function testWithLazyDsnConnection()
  65. {
  66. $dsn = $this->getPersistentSqliteDsn();
  67. $storage = new PdoSessionHandler($dsn);
  68. $storage->createTable();
  69. $storage->open('', 'sid');
  70. $data = $storage->read('id');
  71. $storage->write('id', 'data');
  72. $storage->close();
  73. $this->assertSame('', $data, 'New session returns empty string data');
  74. $storage->open('', 'sid');
  75. $data = $storage->read('id');
  76. $storage->close();
  77. $this->assertSame('data', $data, 'Written value can be read back correctly');
  78. }
  79. public function testWithLazySavePathConnection()
  80. {
  81. $dsn = $this->getPersistentSqliteDsn();
  82. // Open is called with what ini_set('session.save_path', $dsn) would mean
  83. $storage = new PdoSessionHandler(null);
  84. $storage->open($dsn, 'sid');
  85. $storage->createTable();
  86. $data = $storage->read('id');
  87. $storage->write('id', 'data');
  88. $storage->close();
  89. $this->assertSame('', $data, 'New session returns empty string data');
  90. $storage->open($dsn, 'sid');
  91. $data = $storage->read('id');
  92. $storage->close();
  93. $this->assertSame('data', $data, 'Written value can be read back correctly');
  94. }
  95. public function testReadWriteReadWithNullByte()
  96. {
  97. $sessionData = 'da'."\0".'ta';
  98. $storage = new PdoSessionHandler($this->getMemorySqlitePdo());
  99. $storage->open('', 'sid');
  100. $readData = $storage->read('id');
  101. $storage->write('id', $sessionData);
  102. $storage->close();
  103. $this->assertSame('', $readData, 'New session returns empty string data');
  104. $storage->open('', 'sid');
  105. $readData = $storage->read('id');
  106. $storage->close();
  107. $this->assertSame($sessionData, $readData, 'Written value can be read back correctly');
  108. }
  109. public function testReadConvertsStreamToString()
  110. {
  111. $pdo = new MockPdo('pgsql');
  112. $pdo->prepareResult = $this->createMock(\PDOStatement::class);
  113. $content = 'foobar';
  114. $stream = $this->createStream($content);
  115. $pdo->prepareResult->expects($this->once())->method('fetchAll')
  116. ->willReturn([[$stream, 42, time()]]);
  117. $storage = new PdoSessionHandler($pdo);
  118. $result = $storage->read('foo');
  119. $this->assertSame($content, $result);
  120. }
  121. public function testReadLockedConvertsStreamToString()
  122. {
  123. if (filter_var(\ini_get('session.use_strict_mode'), \FILTER_VALIDATE_BOOLEAN)) {
  124. $this->markTestSkipped('Strict mode needs no locking for new sessions.');
  125. }
  126. $pdo = new MockPdo('pgsql');
  127. $selectStmt = $this->createMock(\PDOStatement::class);
  128. $insertStmt = $this->createMock(\PDOStatement::class);
  129. $pdo->prepareResult = function ($statement) use ($selectStmt, $insertStmt) {
  130. return str_starts_with($statement, 'INSERT') ? $insertStmt : $selectStmt;
  131. };
  132. $content = 'foobar';
  133. $stream = $this->createStream($content);
  134. $exception = null;
  135. $selectStmt->expects($this->atLeast(2))->method('fetchAll')
  136. ->willReturnCallback(function () use (&$exception, $stream) {
  137. return $exception ? [[$stream, 42, time()]] : [];
  138. });
  139. $insertStmt->expects($this->once())->method('execute')
  140. ->willReturnCallback(function () use (&$exception) {
  141. throw $exception = new \PDOException('', '23');
  142. });
  143. $storage = new PdoSessionHandler($pdo);
  144. $result = $storage->read('foo');
  145. $this->assertSame($content, $result);
  146. }
  147. public function testReadingRequiresExactlySameId()
  148. {
  149. $storage = new PdoSessionHandler($this->getMemorySqlitePdo());
  150. $storage->open('', 'sid');
  151. $storage->write('id', 'data');
  152. $storage->write('test', 'data');
  153. $storage->write('space ', 'data');
  154. $storage->close();
  155. $storage->open('', 'sid');
  156. $readDataCaseSensitive = $storage->read('ID');
  157. $readDataNoCharFolding = $storage->read('tést');
  158. $readDataKeepSpace = $storage->read('space ');
  159. $readDataExtraSpace = $storage->read('space ');
  160. $storage->close();
  161. $this->assertSame('', $readDataCaseSensitive, 'Retrieval by ID should be case-sensitive (collation setting)');
  162. $this->assertSame('', $readDataNoCharFolding, 'Retrieval by ID should not do character folding (collation setting)');
  163. $this->assertSame('data', $readDataKeepSpace, 'Retrieval by ID requires spaces as-is');
  164. $this->assertSame('', $readDataExtraSpace, 'Retrieval by ID requires spaces as-is');
  165. }
  166. /**
  167. * Simulates session_regenerate_id(true) which will require an INSERT or UPDATE (replace).
  168. */
  169. public function testWriteDifferentSessionIdThanRead()
  170. {
  171. $storage = new PdoSessionHandler($this->getMemorySqlitePdo());
  172. $storage->open('', 'sid');
  173. $storage->read('id');
  174. $storage->destroy('id');
  175. $storage->write('new_id', 'data_of_new_session_id');
  176. $storage->close();
  177. $storage->open('', 'sid');
  178. $data = $storage->read('new_id');
  179. $storage->close();
  180. $this->assertSame('data_of_new_session_id', $data, 'Data of regenerated session id is available');
  181. }
  182. public function testWrongUsageStillWorks()
  183. {
  184. // wrong method sequence that should no happen, but still works
  185. $storage = new PdoSessionHandler($this->getMemorySqlitePdo());
  186. $storage->write('id', 'data');
  187. $storage->write('other_id', 'other_data');
  188. $storage->destroy('inexistent');
  189. $storage->open('', 'sid');
  190. $data = $storage->read('id');
  191. $otherData = $storage->read('other_id');
  192. $storage->close();
  193. $this->assertSame('data', $data);
  194. $this->assertSame('other_data', $otherData);
  195. }
  196. public function testSessionDestroy()
  197. {
  198. $pdo = $this->getMemorySqlitePdo();
  199. $storage = new PdoSessionHandler($pdo);
  200. $storage->open('', 'sid');
  201. $storage->read('id');
  202. $storage->write('id', 'data');
  203. $storage->close();
  204. $this->assertEquals(1, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn());
  205. $storage->open('', 'sid');
  206. $storage->read('id');
  207. $storage->destroy('id');
  208. $storage->close();
  209. $this->assertEquals(0, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn());
  210. $storage->open('', 'sid');
  211. $data = $storage->read('id');
  212. $storage->close();
  213. $this->assertSame('', $data, 'Destroyed session returns empty string');
  214. }
  215. /**
  216. * @runInSeparateProcess
  217. */
  218. public function testSessionGC()
  219. {
  220. $previousLifeTime = ini_set('session.gc_maxlifetime', 1000);
  221. $pdo = $this->getMemorySqlitePdo();
  222. $storage = new PdoSessionHandler($pdo);
  223. $storage->open('', 'sid');
  224. $storage->read('id');
  225. $storage->write('id', 'data');
  226. $storage->close();
  227. $storage->open('', 'sid');
  228. $storage->read('gc_id');
  229. ini_set('session.gc_maxlifetime', -1); // test that you can set lifetime of a session after it has been read
  230. $storage->write('gc_id', 'data');
  231. $storage->close();
  232. $this->assertEquals(2, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn(), 'No session pruned because gc not called');
  233. $storage->open('', 'sid');
  234. $data = $storage->read('gc_id');
  235. $storage->gc(-1);
  236. $storage->close();
  237. ini_set('session.gc_maxlifetime', $previousLifeTime);
  238. $this->assertSame('', $data, 'Session already considered garbage, so not returning data even if it is not pruned yet');
  239. $this->assertEquals(1, $pdo->query('SELECT COUNT(*) FROM sessions')->fetchColumn(), 'Expired session is pruned');
  240. }
  241. public function testGetConnection()
  242. {
  243. $storage = new PdoSessionHandler($this->getMemorySqlitePdo());
  244. $method = new \ReflectionMethod($storage, 'getConnection');
  245. $method->setAccessible(true);
  246. $this->assertInstanceOf(\PDO::class, $method->invoke($storage));
  247. }
  248. public function testGetConnectionConnectsIfNeeded()
  249. {
  250. $storage = new PdoSessionHandler('sqlite::memory:');
  251. $method = new \ReflectionMethod($storage, 'getConnection');
  252. $method->setAccessible(true);
  253. $this->assertInstanceOf(\PDO::class, $method->invoke($storage));
  254. }
  255. /**
  256. * @dataProvider provideUrlDsnPairs
  257. */
  258. public function testUrlDsn($url, $expectedDsn, $expectedUser = null, $expectedPassword = null)
  259. {
  260. $storage = new PdoSessionHandler($url);
  261. $reflection = new \ReflectionClass(PdoSessionHandler::class);
  262. foreach (['dsn' => $expectedDsn, 'username' => $expectedUser, 'password' => $expectedPassword] as $property => $expectedValue) {
  263. if (!isset($expectedValue)) {
  264. continue;
  265. }
  266. $property = $reflection->getProperty($property);
  267. $property->setAccessible(true);
  268. $this->assertSame($expectedValue, $property->getValue($storage));
  269. }
  270. }
  271. public static function provideUrlDsnPairs()
  272. {
  273. yield ['mysql://localhost/test', 'mysql:host=localhost;dbname=test;'];
  274. yield ['mysql://localhost/test?charset=utf8mb4', 'mysql:charset=utf8mb4;host=localhost;dbname=test;'];
  275. yield ['mysql://localhost/test?unix_socket=socket.sock&charset=utf8mb4', 'mysql:charset=utf8mb4;unix_socket=socket.sock;dbname=test;'];
  276. yield ['mysql://localhost:56/test', 'mysql:host=localhost;port=56;dbname=test;'];
  277. yield ['mysql2://root:pwd@localhost/test', 'mysql:host=localhost;dbname=test;', 'root', 'pwd'];
  278. yield ['postgres://localhost/test', 'pgsql:host=localhost;dbname=test;'];
  279. yield ['postgresql://localhost:5634/test', 'pgsql:host=localhost;port=5634;dbname=test;'];
  280. yield ['postgres://root:pwd@localhost/test', 'pgsql:host=localhost;dbname=test;', 'root', 'pwd'];
  281. yield 'sqlite relative path' => ['sqlite://localhost/tmp/test', 'sqlite:tmp/test'];
  282. yield 'sqlite absolute path' => ['sqlite://localhost//tmp/test', 'sqlite:/tmp/test'];
  283. yield 'sqlite relative path without host' => ['sqlite:///tmp/test', 'sqlite:tmp/test'];
  284. yield 'sqlite absolute path without host' => ['sqlite3:////tmp/test', 'sqlite:/tmp/test'];
  285. yield ['sqlite://localhost/:memory:', 'sqlite::memory:'];
  286. yield ['mssql://localhost/test', 'sqlsrv:server=localhost;Database=test'];
  287. yield ['mssql://localhost:56/test', 'sqlsrv:server=localhost,56;Database=test'];
  288. }
  289. /**
  290. * @return resource
  291. */
  292. private function createStream($content)
  293. {
  294. $stream = tmpfile();
  295. fwrite($stream, $content);
  296. fseek($stream, 0);
  297. return $stream;
  298. }
  299. }
  300. class MockPdo extends \PDO
  301. {
  302. public $prepareResult;
  303. private $driverName;
  304. private $errorMode;
  305. public function __construct(string $driverName = null, int $errorMode = null)
  306. {
  307. $this->driverName = $driverName;
  308. $this->errorMode = null !== $errorMode ?: \PDO::ERRMODE_EXCEPTION;
  309. }
  310. /**
  311. * @return mixed
  312. */
  313. #[\ReturnTypeWillChange]
  314. public function getAttribute($attribute)
  315. {
  316. if (\PDO::ATTR_ERRMODE === $attribute) {
  317. return $this->errorMode;
  318. }
  319. if (\PDO::ATTR_DRIVER_NAME === $attribute) {
  320. return $this->driverName;
  321. }
  322. return parent::getAttribute($attribute);
  323. }
  324. /**
  325. * @return false|\PDOStatement
  326. */
  327. #[\ReturnTypeWillChange]
  328. public function prepare($statement, $driverOptions = [])
  329. {
  330. return \is_callable($this->prepareResult)
  331. ? ($this->prepareResult)($statement, $driverOptions)
  332. : $this->prepareResult;
  333. }
  334. public function beginTransaction(): bool
  335. {
  336. return true;
  337. }
  338. public function rollBack(): bool
  339. {
  340. return true;
  341. }
  342. }