DatabaseTest.php 16 KB

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