PdoSessionHandlerTest.php 14 KB

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