DatabaseTest.php 14 KB

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