1
0

DatabaseTest.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. <?php
  2. use PrivateBin\Controller;
  3. use PrivateBin\Data\Database;
  4. use PrivateBin\Data\Filesystem;
  5. use PrivateBin\Persistence\ServerSalt;
  6. class DatabaseTest extends PHPUnit_Framework_TestCase
  7. {
  8. private $_model;
  9. private $_path;
  10. private $_options = array(
  11. 'dsn' => 'sqlite::memory:',
  12. 'usr' => null,
  13. 'pwd' => null,
  14. 'opt' => array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION),
  15. );
  16. public function setUp()
  17. {
  18. /* Setup Routine */
  19. $this->_path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'privatebin_data';
  20. $this->_model = Database::getInstance($this->_options);
  21. }
  22. public function tearDown()
  23. {
  24. /* Tear Down Routine */
  25. if (is_dir($this->_path)) {
  26. Helper::rmDir($this->_path);
  27. }
  28. }
  29. public function testSaltMigration()
  30. {
  31. ServerSalt::setStore(Filesystem::getInstance(array('dir' => 'data')));
  32. $salt = ServerSalt::get();
  33. $file = 'data' . DIRECTORY_SEPARATOR . 'salt.php';
  34. $this->assertFileExists($file, 'ServerSalt got initialized and stored on disk');
  35. $this->assertNotEquals($salt, '');
  36. ServerSalt::setStore($this->_model);
  37. ServerSalt::get();
  38. $this->assertFileNotExists($file, 'legacy ServerSalt got removed');
  39. $this->assertEquals($salt, ServerSalt::get(), 'ServerSalt got preserved & migrated');
  40. }
  41. public function testDatabaseBasedDataStoreWorks()
  42. {
  43. $this->_model->delete(Helper::getPasteId());
  44. // storing pastes
  45. $paste = Helper::getPaste();
  46. $this->assertFalse($this->_model->exists(Helper::getPasteId()), 'paste does not yet exist');
  47. $this->assertTrue($this->_model->create(Helper::getPasteId(), $paste), 'store new paste');
  48. $this->assertTrue($this->_model->exists(Helper::getPasteId()), 'paste exists after storing it');
  49. $this->assertFalse($this->_model->create(Helper::getPasteId(), $paste), 'unable to store the same paste twice');
  50. $this->assertEquals($paste, $this->_model->read(Helper::getPasteId()));
  51. // storing comments
  52. $this->assertFalse($this->_model->existsComment(Helper::getPasteId(), Helper::getPasteId(), Helper::getCommentId()), 'v1 comment does not yet exist');
  53. $this->assertTrue($this->_model->createComment(Helper::getPasteId(), Helper::getPasteId(), Helper::getCommentId(), Helper::getComment(1)) !== false, 'store v1 comment');
  54. $this->assertTrue($this->_model->existsComment(Helper::getPasteId(), Helper::getPasteId(), Helper::getCommentId()), 'v1 comment exists after storing it');
  55. $this->assertFalse($this->_model->existsComment(Helper::getPasteId(), Helper::getPasteId(), Helper::getPasteId()), 'v2 comment does not yet exist');
  56. $this->assertTrue($this->_model->createComment(Helper::getPasteId(), Helper::getPasteId(), Helper::getPasteId(), Helper::getComment(2)) !== false, 'store v2 comment');
  57. $this->assertTrue($this->_model->existsComment(Helper::getPasteId(), Helper::getPasteId(), Helper::getPasteId()), 'v2 comment exists after storing it');
  58. $comment1 = Helper::getComment(1);
  59. $comment1['id'] = Helper::getCommentId();
  60. $comment1['parentid'] = Helper::getPasteId();
  61. $comment2 = Helper::getComment(2);
  62. $comment2['id'] = Helper::getPasteId();
  63. $comment2['parentid'] = Helper::getPasteId();
  64. $this->assertEquals(
  65. array(
  66. $comment1['meta']['postdate'] => $comment1,
  67. $comment2['meta']['created'] . '.1' => $comment2,
  68. ),
  69. $this->_model->readComments(Helper::getPasteId())
  70. );
  71. // deleting pastes
  72. $this->_model->delete(Helper::getPasteId());
  73. $this->assertFalse($this->_model->exists(Helper::getPasteId()), 'paste successfully deleted');
  74. $this->assertFalse($this->_model->existsComment(Helper::getPasteId(), Helper::getPasteId(), Helper::getCommentId()), 'comment was deleted with paste');
  75. $this->assertFalse($this->_model->read(Helper::getPasteId()), 'paste can no longer be found');
  76. }
  77. public function testDatabaseBasedAttachmentStoreWorks()
  78. {
  79. // this assumes a version 1 formatted paste
  80. $this->_model->delete(Helper::getPasteId());
  81. $original = $paste = Helper::getPasteWithAttachment(1, array('expire_date' => 1344803344));
  82. $paste['meta']['burnafterreading'] = $original['meta']['burnafterreading'] = true;
  83. $paste['meta']['attachment'] = $paste['attachment'];
  84. $paste['meta']['attachmentname'] = $paste['attachmentname'];
  85. unset($paste['attachment'], $paste['attachmentname']);
  86. $this->assertFalse($this->_model->exists(Helper::getPasteId()), 'paste does not yet exist');
  87. $this->assertTrue($this->_model->create(Helper::getPasteId(), $paste), 'store new paste');
  88. $this->assertTrue($this->_model->exists(Helper::getPasteId()), 'paste exists after storing it');
  89. $this->assertFalse($this->_model->create(Helper::getPasteId(), $paste), 'unable to store the same paste twice');
  90. $this->assertEquals($original, $this->_model->read(Helper::getPasteId()));
  91. }
  92. /**
  93. * pastes a-g are expired and should get deleted, x never expires and y-z expire in an hour
  94. */
  95. public function testPurge()
  96. {
  97. $this->_model->delete(Helper::getPasteId());
  98. $expired = Helper::getPaste(2, array('expire_date' => 1344803344));
  99. $paste = Helper::getPaste(2, array('expire_date' => time() + 3600));
  100. $keys = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'x', 'y', 'z');
  101. $ids = array();
  102. foreach ($keys as $key) {
  103. $ids[$key] = hash('fnv164', $key);
  104. $this->_model->delete($ids[$key]);
  105. $this->assertFalse($this->_model->exists($ids[$key]), "paste $key does not yet exist");
  106. if (in_array($key, array('y', 'z'))) {
  107. $this->assertTrue($this->_model->create($ids[$key], $paste), "store $key paste");
  108. } elseif ($key === 'x') {
  109. $this->assertTrue($this->_model->create($ids[$key], Helper::getPaste()), "store $key paste");
  110. } else {
  111. $this->assertTrue($this->_model->create($ids[$key], $expired), "store $key paste");
  112. }
  113. $this->assertTrue($this->_model->exists($ids[$key]), "paste $key exists after storing it");
  114. }
  115. $this->_model->purge(10);
  116. foreach ($ids as $key => $id) {
  117. if (in_array($key, array('x', 'y', 'z'))) {
  118. $this->assertTrue($this->_model->exists($id), "paste $key exists after purge");
  119. $this->_model->delete($id);
  120. } else {
  121. $this->assertFalse($this->_model->exists($id), "paste $key was purged");
  122. }
  123. }
  124. }
  125. /**
  126. * @expectedException PDOException
  127. */
  128. public function testGetIbmInstance()
  129. {
  130. Database::getInstance(array(
  131. 'dsn' => 'ibm:', 'usr' => null, 'pwd' => null,
  132. 'opt' => array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION),
  133. ));
  134. }
  135. /**
  136. * @expectedException PDOException
  137. */
  138. public function testGetInformixInstance()
  139. {
  140. Database::getInstance(array(
  141. 'dsn' => 'informix:', 'usr' => null, 'pwd' => null,
  142. 'opt' => array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION),
  143. ));
  144. }
  145. /**
  146. * @expectedException PDOException
  147. */
  148. public function testGetMssqlInstance()
  149. {
  150. Database::getInstance(array(
  151. 'dsn' => 'mssql:', 'usr' => null, 'pwd' => null,
  152. 'opt' => array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION),
  153. ));
  154. }
  155. /**
  156. * @expectedException PDOException
  157. */
  158. public function testGetMysqlInstance()
  159. {
  160. Database::getInstance(array(
  161. 'dsn' => 'mysql:', 'usr' => null, 'pwd' => null,
  162. 'opt' => array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION),
  163. ));
  164. }
  165. /**
  166. * @expectedException PDOException
  167. */
  168. public function testGetOciInstance()
  169. {
  170. Database::getInstance(array(
  171. 'dsn' => 'oci:', 'usr' => null, 'pwd' => null,
  172. 'opt' => array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION),
  173. ));
  174. }
  175. /**
  176. * @expectedException PDOException
  177. */
  178. public function testGetPgsqlInstance()
  179. {
  180. Database::getInstance(array(
  181. 'dsn' => 'pgsql:', 'usr' => null, 'pwd' => null,
  182. 'opt' => array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION),
  183. ));
  184. }
  185. /**
  186. * @expectedException Exception
  187. * @expectedExceptionCode 5
  188. */
  189. public function testGetFooInstance()
  190. {
  191. Database::getInstance(array(
  192. 'dsn' => 'foo:', 'usr' => null, 'pwd' => null, 'opt' => null,
  193. ));
  194. }
  195. /**
  196. * @expectedException Exception
  197. * @expectedExceptionCode 6
  198. */
  199. public function testMissingDsn()
  200. {
  201. $options = $this->_options;
  202. unset($options['dsn']);
  203. Database::getInstance($options);
  204. }
  205. /**
  206. * @expectedException Exception
  207. * @expectedExceptionCode 6
  208. */
  209. public function testMissingUsr()
  210. {
  211. $options = $this->_options;
  212. unset($options['usr']);
  213. Database::getInstance($options);
  214. }
  215. /**
  216. * @expectedException Exception
  217. * @expectedExceptionCode 6
  218. */
  219. public function testMissingPwd()
  220. {
  221. $options = $this->_options;
  222. unset($options['pwd']);
  223. Database::getInstance($options);
  224. }
  225. /**
  226. * @expectedException Exception
  227. * @expectedExceptionCode 6
  228. */
  229. public function testMissingOpt()
  230. {
  231. $options = $this->_options;
  232. unset($options['opt']);
  233. Database::getInstance($options);
  234. }
  235. public function testOldAttachments()
  236. {
  237. mkdir($this->_path);
  238. $path = $this->_path . DIRECTORY_SEPARATOR . 'attachement-test.sq3';
  239. if (is_file($path)) {
  240. unlink($path);
  241. }
  242. $this->_options['dsn'] = 'sqlite:' . $path;
  243. $this->_options['tbl'] = 'bar_';
  244. $model = Database::getInstance($this->_options);
  245. $original = $paste = Helper::getPasteWithAttachment(1, array('expire_date' => 1344803344));
  246. $meta = $paste['meta'];
  247. $meta['attachment'] = $paste['attachment'];
  248. $meta['attachmentname'] = $paste['attachmentname'];
  249. unset($paste['attachment'], $paste['attachmentname']);
  250. $db = new PDO(
  251. $this->_options['dsn'],
  252. $this->_options['usr'],
  253. $this->_options['pwd'],
  254. $this->_options['opt']
  255. );
  256. $statement = $db->prepare('INSERT INTO bar_paste VALUES(?,?,?,?,?,?,?,?,?)');
  257. $statement->execute(
  258. array(
  259. Helper::getPasteId(),
  260. $paste['data'],
  261. $paste['meta']['postdate'],
  262. $paste['meta']['expire_date'],
  263. 0,
  264. 0,
  265. json_encode($meta),
  266. null,
  267. null,
  268. )
  269. );
  270. $statement->closeCursor();
  271. $this->assertTrue($model->exists(Helper::getPasteId()), 'paste exists after storing it');
  272. $this->assertEquals($original, $model->read(Helper::getPasteId()));
  273. Helper::rmDir($this->_path);
  274. }
  275. public function testCorruptMeta()
  276. {
  277. mkdir($this->_path);
  278. $path = $this->_path . DIRECTORY_SEPARATOR . 'meta-test.sq3';
  279. if (is_file($path)) {
  280. unlink($path);
  281. }
  282. $this->_options['dsn'] = 'sqlite:' . $path;
  283. $this->_options['tbl'] = 'baz_';
  284. $model = Database::getInstance($this->_options);
  285. $paste = Helper::getPaste(1, array('expire_date' => 1344803344));
  286. unset($paste['meta']['formatter'], $paste['meta']['opendiscussion'], $paste['meta']['salt']);
  287. $model->delete(Helper::getPasteId());
  288. $db = new PDO(
  289. $this->_options['dsn'],
  290. $this->_options['usr'],
  291. $this->_options['pwd'],
  292. $this->_options['opt']
  293. );
  294. $statement = $db->prepare('INSERT INTO baz_paste VALUES(?,?,?,?,?,?,?,?,?)');
  295. $statement->execute(
  296. array(
  297. Helper::getPasteId(),
  298. $paste['data'],
  299. $paste['meta']['postdate'],
  300. $paste['meta']['expire_date'],
  301. 0,
  302. 0,
  303. '{',
  304. null,
  305. null,
  306. )
  307. );
  308. $statement->closeCursor();
  309. $this->assertTrue($model->exists(Helper::getPasteId()), 'paste exists after storing it');
  310. $this->assertEquals($paste, $model->read(Helper::getPasteId()));
  311. Helper::rmDir($this->_path);
  312. }
  313. public function testTableUpgrade()
  314. {
  315. mkdir($this->_path);
  316. $path = $this->_path . DIRECTORY_SEPARATOR . 'db-test.sq3';
  317. if (is_file($path)) {
  318. unlink($path);
  319. }
  320. $this->_options['dsn'] = 'sqlite:' . $path;
  321. $this->_options['tbl'] = 'foo_';
  322. $db = new PDO(
  323. $this->_options['dsn'],
  324. $this->_options['usr'],
  325. $this->_options['pwd'],
  326. $this->_options['opt']
  327. );
  328. $db->exec(
  329. 'CREATE TABLE foo_paste ( ' .
  330. 'dataid CHAR(16), ' .
  331. 'data TEXT, ' .
  332. 'postdate INT, ' .
  333. 'expiredate INT, ' .
  334. 'opendiscussion INT, ' .
  335. 'burnafterreading INT );'
  336. );
  337. $db->exec(
  338. 'CREATE TABLE foo_comment ( ' .
  339. 'dataid CHAR(16) NOT NULL, ' .
  340. 'pasteid CHAR(16), ' .
  341. 'parentid CHAR(16), ' .
  342. 'data BLOB, ' .
  343. 'nickname BLOB, ' .
  344. 'vizhash BLOB, ' .
  345. 'postdate INT );'
  346. );
  347. $this->assertInstanceOf('PrivateBin\\Data\\Database', Database::getInstance($this->_options));
  348. // check if version number was upgraded in created configuration table
  349. $statement = $db->prepare('SELECT value FROM foo_config WHERE id LIKE ?');
  350. $statement->execute(array('VERSION'));
  351. $result = $statement->fetch(PDO::FETCH_ASSOC);
  352. $statement->closeCursor();
  353. $this->assertEquals(Controller::VERSION, $result['value']);
  354. Helper::rmDir($this->_path);
  355. }
  356. public function testOciClob()
  357. {
  358. $int = (int) random_bytes(1);
  359. $string = random_bytes(10);
  360. $clob = fopen('php://memory', 'r+');
  361. fwrite($clob, $string);
  362. rewind($clob);
  363. $this->assertEquals($int, Database::_sanitizeClob($int));
  364. $this->assertEquals($string, Database::_sanitizeClob($string));
  365. $this->assertEquals($string, Database::_sanitizeClob($clob));
  366. }
  367. }