PdoSessionHandlerTest.php 14 KB

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