DatabaseTest.php 15 KB

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