configuration-test-generator 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643
  1. #!/usr/bin/env php
  2. <?php declare(strict_types=1);
  3. /**
  4. * PrivateBin
  5. *
  6. * a zero-knowledge paste bin
  7. *
  8. * @link https://github.com/PrivateBin/PrivateBin
  9. * @copyright 2012 Sébastien SAUVAGE (sebsauvage.net)
  10. * @license https://www.opensource.org/licenses/zlib-license.php The zlib/libpng License
  11. *
  12. * generates a config unit test class
  13. *
  14. * This generator is meant to test all possible configuration combinations
  15. * without having to write endless amounts of code manually.
  16. *
  17. * DANGER: Too many options/settings and too high max iteration setting may trigger
  18. * a fork bomb. Please save your work before executing this script.
  19. */
  20. define('PATH', dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR);
  21. include PATH . 'tst' . DIRECTORY_SEPARATOR . 'Bootstrap.php';
  22. $vd = array('view', 'delete');
  23. $vcd = array('view', 'create', 'delete');
  24. new ConfigurationTestGenerator(array(
  25. 'main/discussion' => array(
  26. array(
  27. 'setting' => true,
  28. 'tests' => array(
  29. array(
  30. 'conditions' => array('steps' => $vd),
  31. 'type' => 'MatchesRegularExpression',
  32. 'args' => array(
  33. '#<div[^>]*id="opendiscussionoption"[^>]*>#',
  34. '$content',
  35. 'outputs enabled discussion correctly',
  36. ),
  37. ), array(
  38. 'conditions' => array('steps' => array('create'), 'traffic/limit' => 10),
  39. 'settings' => array('$_POST["opendiscussion"] = "neither 1 nor 0"'),
  40. 'type' => 'Equals',
  41. 'args' => array(
  42. 1,
  43. '$response["status"]',
  44. 'when discussions are enabled, but invalid flag posted, fail to create paste',
  45. ),
  46. ), array(
  47. 'conditions' => array('steps' => array('create'), 'traffic/limit' => 10),
  48. 'settings' => array('$_POST["opendiscussion"] = "neither 1 nor 0"'),
  49. 'type' => 'False',
  50. 'args' => array(
  51. '$this->_model->exists(Helper::getPasteId())',
  52. 'when discussions are enabled, but invalid flag posted, paste is not created',
  53. ),
  54. ),
  55. ),
  56. 'affects' => $vcd,
  57. ), array(
  58. 'setting' => false,
  59. 'tests' => array(
  60. array(
  61. 'type' => 'DoesNotMatchRegularExpression',
  62. 'args' => array(
  63. '#<div[^>]*id="opendiscussionoption"[^>]*>#',
  64. '$content',
  65. 'outputs disabled discussion correctly',
  66. ),
  67. ),
  68. ),
  69. 'affects' => $vd,
  70. ),
  71. ),
  72. 'main/opendiscussion' => array(
  73. array(
  74. 'setting' => true,
  75. 'tests' => array(
  76. array(
  77. 'conditions' => array('main/discussion' => true),
  78. 'type' => 'MatchesRegularExpression',
  79. 'args' => array(
  80. '#<input[^>]+id="opendiscussion"[^>]*checked="checked"[^>]*>#',
  81. '$content',
  82. 'outputs checked discussion correctly',
  83. ),
  84. ),
  85. ),
  86. 'affects' => $vd,
  87. ), array(
  88. 'setting' => false,
  89. 'tests' => array(
  90. array(
  91. 'conditions' => array('main/discussion' => true),
  92. 'type' => 'DoesNotMatchRegularExpression',
  93. 'args' => array(
  94. '#<input[^>]+id="opendiscussion"[^>]*checked="checked"[^>]*>#',
  95. '$content',
  96. 'outputs unchecked discussion correctly',
  97. ),
  98. ),
  99. ),
  100. 'affects' => $vd,
  101. ),
  102. ),
  103. 'main/burnafterreadingselected' => array(
  104. array(
  105. 'setting' => true,
  106. 'tests' => array(
  107. array(
  108. 'type' => 'MatchesRegularExpression',
  109. 'args' => array(
  110. '#<input[^>]+id="burnafterreading"[^>]*checked="checked"[^>]*>#',
  111. '$content',
  112. 'preselects burn after reading option',
  113. ),
  114. ),
  115. ),
  116. 'affects' => array('view'),
  117. ), array(
  118. 'setting' => false,
  119. 'tests' => array(
  120. array(
  121. 'type' => 'DoesNotMatchRegularExpression',
  122. 'args' => array(
  123. '#<input[^>]+id="burnafterreading"[^>]*checked="checked"[^>]*>#',
  124. '$content',
  125. 'burn after reading option is unchecked',
  126. ),
  127. ),
  128. ),
  129. 'affects' => array('view'),
  130. ),
  131. ),
  132. 'main/password' => array(
  133. array(
  134. 'setting' => true,
  135. 'tests' => array(
  136. array(
  137. 'type' => 'MatchesRegularExpression',
  138. 'args' => array(
  139. '#<div[^>]*id="password"[^>]*>#',
  140. '$content',
  141. 'outputs password input correctly',
  142. ),
  143. ),
  144. ),
  145. 'affects' => $vd,
  146. ), array(
  147. 'setting' => false,
  148. 'tests' => array(
  149. array(
  150. 'conditions' => array('main/discussion' => true),
  151. 'type' => 'DoesNotMatchRegularExpression',
  152. 'args' => array(
  153. '#<div[^>]*id="password"[^>]*>#',
  154. '$content',
  155. 'removes password input correctly',
  156. ),
  157. ),
  158. ),
  159. 'affects' => $vd,
  160. ),
  161. ),
  162. 'main/template' => array(
  163. array(
  164. 'setting' => 'bootstrap5',
  165. 'tests' => array(
  166. array(
  167. 'type' => 'MatchesRegularExpression',
  168. 'args' => array(
  169. '#<link[^>]+type="text/css"[^>]+rel="stylesheet"[^>]+href="css/bootstrap5/privatebin\.css\\?\d[\d\.]+\d+"[^>]*/>#',
  170. '$content',
  171. 'outputs "bootstrap5" stylesheet correctly',
  172. ),
  173. ), array(
  174. 'type' => 'DoesNotMatchRegularExpression',
  175. 'args' => array(
  176. '#<link[^>]+type="text/css"[^>]+rel="stylesheet"[^>]+href="css/bootstrap/bootstrap-\d[\d\.]+\d\.css"[^>]*/>#',
  177. '$content',
  178. 'removes "bootstrap" stylesheet correctly',
  179. ),
  180. ),
  181. ),
  182. 'affects' => $vd,
  183. )
  184. ),
  185. 'main/sizelimit' => array(
  186. array(
  187. 'setting' => 10,
  188. 'tests' => array(
  189. array(
  190. 'conditions' => array('steps' => array('create'), 'traffic/limit' => 10),
  191. 'type' => 'Equals',
  192. 'args' => array(
  193. 1,
  194. '$response["status"]',
  195. 'when sizelimit limit exceeded, fail to create paste',
  196. ),
  197. ),
  198. ),
  199. 'affects' => array('create'),
  200. ), array(
  201. 'setting' => 2097152,
  202. 'tests' => array(
  203. array(
  204. 'conditions' => array('steps' => array('create'), 'traffic/limit' => 0, 'main/burnafterreadingselected' => true),
  205. 'settings' => array('sleep(3)'),
  206. 'type' => 'Equals',
  207. 'args' => array(
  208. 0,
  209. '$response["status"]',
  210. 'when sizelimit limit is not reached, successfully create paste',
  211. ),
  212. ), array(
  213. 'conditions' => array('steps' => array('create'), 'traffic/limit' => 0, 'main/burnafterreadingselected' => true),
  214. 'settings' => array('sleep(3)'),
  215. 'type' => 'True',
  216. 'args' => array(
  217. '$this->_model->exists($response["id"])',
  218. 'when sizelimit limit is not reached, paste exists after posting data',
  219. ),
  220. ),
  221. ),
  222. 'affects' => array('create'),
  223. ),
  224. ),
  225. 'traffic/limit' => array(
  226. array(
  227. 'setting' => 0,
  228. 'tests' => array(
  229. array(
  230. 'conditions' => array('steps' => array('create'), 'main/sizelimit' => 2097152),
  231. 'type' => 'Equals',
  232. 'args' => array(
  233. 0,
  234. '$response["status"]',
  235. 'when traffic limit is disabled, successfully create paste',
  236. ),
  237. ), array(
  238. 'conditions' => array('steps' => array('create'), 'main/sizelimit' => 2097152),
  239. 'type' => 'True',
  240. 'args' => array(
  241. '$this->_model->exists($response["id"])',
  242. 'when traffic limit is disabled, paste exists after posting data',
  243. ),
  244. ),
  245. ),
  246. 'affects' => array('create'),
  247. ), array(
  248. 'setting' => 10,
  249. 'tests' => array(
  250. array(
  251. 'conditions' => array('steps' => array('create')),
  252. 'type' => 'Equals',
  253. 'args' => array(
  254. 1,
  255. '$response["status"]',
  256. 'when traffic limit is on and we do not wait, fail to create paste',
  257. ),
  258. ),
  259. ),
  260. 'affects' => array('create'),
  261. ), array(
  262. 'setting' => 2,
  263. 'tests' => array(
  264. array(
  265. 'conditions' => array('steps' => array('create'), 'main/sizelimit' => 2097152),
  266. 'settings' => array('sleep(3)'),
  267. 'type' => 'Equals',
  268. 'args' => array(
  269. 0,
  270. '$response["status"]',
  271. 'when traffic limit is on and we wait, successfully create paste',
  272. ),
  273. ), array(
  274. 'conditions' => array('steps' => array('create'), 'main/sizelimit' => 2097152),
  275. 'settings' => array('sleep(3)'),
  276. 'type' => 'True',
  277. 'args' => array(
  278. '$this->_model->exists($response["id"])',
  279. 'when traffic limit is on and we wait, paste exists after posting data',
  280. ),
  281. ),
  282. ),
  283. 'affects' => array('create'),
  284. ),
  285. ),
  286. ));
  287. class ConfigurationTestGenerator
  288. {
  289. /**
  290. * endless loop protection, since we're working with a recursive function,
  291. * creating factorial configurations
  292. * @var int
  293. */
  294. const MAX_ITERATIONS = 2000;
  295. /**
  296. * options to test
  297. * @var array
  298. */
  299. private $_options;
  300. /**
  301. * iteration count to guarantee timely end
  302. * @var int
  303. */
  304. private $_iterationCount = 0;
  305. /**
  306. * generated configurations
  307. * @var array
  308. */
  309. private $_configurations = array(
  310. array('options' => array(), 'tests' => array(), 'affects' => array()),
  311. );
  312. /**
  313. * constructor, generates the configuration test
  314. * @param array $options
  315. */
  316. public function __construct($options)
  317. {
  318. $this->_options = $options;
  319. // generate all possible combinations of options: options^settings
  320. $this->_generateConfigurations();
  321. $this->_writeConfigurationTest();
  322. }
  323. /**
  324. * write configuration test file based on generated configuration array
  325. */
  326. private function _writeConfigurationTest()
  327. {
  328. $defaultOptions = parse_ini_file(CONF_SAMPLE, true);
  329. $code = $this->_getHeader();
  330. foreach ($this->_configurations as $key => $conf) {
  331. $fullOptions = array_replace_recursive($defaultOptions, $conf['options']);
  332. $options = Helper::varExportMin($fullOptions, true);
  333. foreach ($conf['affects'] as $step) {
  334. $testCode = $preCode = array();
  335. foreach ($conf['tests'] as $tests) {
  336. foreach ($tests[0] as $test) {
  337. // skip if test does not affect this step
  338. if (!in_array($step, $tests[1])) {
  339. continue;
  340. }
  341. // skip if not all test conditions are met
  342. if (array_key_exists('conditions', $test)) {
  343. foreach ($test['conditions'] as $path => $setting) {
  344. if ($path == 'steps' && !in_array($step, $setting)) {
  345. continue 2;
  346. } elseif ($path != 'steps') {
  347. list($section, $option) = explode('/', $path);
  348. if ($fullOptions[$section][$option] !== $setting) {
  349. continue 2;
  350. }
  351. }
  352. }
  353. }
  354. if (array_key_exists('settings', $test)) {
  355. foreach ($test['settings'] as $setting) {
  356. $preCode[$setting] = $setting;
  357. }
  358. }
  359. $args = array();
  360. foreach ($test['args'] as $arg) {
  361. if (is_string($arg) && strpos($arg, '$') === 0) {
  362. $args[] = $arg;
  363. } else {
  364. $args[] = Helper::varExportMin($arg, true);
  365. }
  366. }
  367. $testCode[] = array($test['type'], implode(', ', $args));
  368. }
  369. }
  370. $code .= $this->_getFunction(
  371. ucfirst($step), $key, $options, $preCode, $testCode, $fullOptions['main']['discussion']
  372. );
  373. }
  374. }
  375. $code .= '}' . PHP_EOL;
  376. file_put_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'tst' . DIRECTORY_SEPARATOR . 'ConfigurationCombinationsTest.php', $code);
  377. }
  378. /**
  379. * get header of configuration test file
  380. *
  381. * @return string
  382. */
  383. private function _getHeader()
  384. {
  385. return <<<'EOT'
  386. <?php declare(strict_types=1);
  387. /**
  388. * DO NOT EDIT: This file is generated automatically using configGenerator.php
  389. */
  390. use PHPUnit\Framework\TestCase;
  391. use PrivateBin\Controller;
  392. use PrivateBin\Data\Filesystem;
  393. use PrivateBin\Persistence\ServerSalt;
  394. use PrivateBin\Persistence\TrafficLimiter;
  395. use PrivateBin\Request;
  396. class ConfigurationCombinationsTest extends TestCase
  397. {
  398. private $_conf;
  399. private $_model;
  400. private $_path;
  401. public function setUp(): void
  402. {
  403. /* Setup Routine */
  404. Helper::confBackup();
  405. $this->_path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'privatebin_data';
  406. $this->_model = new Filesystem(array('dir' => $this->_path));
  407. ServerSalt::setStore($this->_model);
  408. TrafficLimiter::setStore($this->_model);
  409. $this->reset();
  410. }
  411. public function tearDown(): void
  412. {
  413. /* Tear Down Routine */
  414. unlink(CONF);
  415. Helper::confRestore();
  416. Helper::rmDir($this->_path);
  417. }
  418. public function reset($configuration = array())
  419. {
  420. $_POST = array();
  421. $_GET = array();
  422. $_SERVER = array();
  423. if ($this->_model->exists(Helper::getPasteId()))
  424. $this->_model->delete(Helper::getPasteId());
  425. $configuration['model_options']['dir'] = $this->_path;
  426. Helper::createIniFile(CONF, $configuration);
  427. }
  428. EOT;
  429. }
  430. /**
  431. * get unit tests function block
  432. *
  433. * @param string $step
  434. * @param int $key
  435. * @param array $options
  436. * @param array $preCode
  437. * @param array $testCode
  438. * @return string
  439. */
  440. private function _getFunction($step, $key, &$options, $preCode, $testCode, $discussionEnabled)
  441. {
  442. if (count($testCode) == 0) {
  443. echo "skipping creation of test$step$key, no valid tests found for configuration: $options" . PHP_EOL;
  444. return '';
  445. }
  446. $preString = $testString = '';
  447. foreach ($preCode as $setting) {
  448. $preString .= " $setting;" . PHP_EOL;
  449. }
  450. foreach ($testCode as $test) {
  451. $type = $test[0];
  452. $args = $test[1];
  453. $testString .= " \$this->assert$type($args);" . PHP_EOL;
  454. }
  455. $code = <<<EOT
  456. /**
  457. * @runInSeparateProcess
  458. */
  459. public function test$step$key()
  460. {
  461. \$this->reset($options);
  462. EOT;
  463. // step specific initialization
  464. switch ($step) {
  465. case 'Create':
  466. if ($discussionEnabled) {
  467. $code .= PHP_EOL . <<<'EOT'
  468. $paste = Helper::getPasteJson();
  469. EOT;
  470. } else {
  471. $code .= PHP_EOL . <<<'EOT'
  472. $paste = json_decode(Helper::getPasteJson(), true);
  473. $paste['adata'][2] = 0;
  474. $paste = json_encode($paste);
  475. EOT;
  476. }
  477. $code .= PHP_EOL . <<<'EOT'
  478. $file = Helper::createTempFile();
  479. file_put_contents($file, $paste);
  480. Request::setInputStream($file);
  481. $_SERVER['HTTP_X_REQUESTED_WITH'] = 'JSONHttpRequest';
  482. $_SERVER['REQUEST_METHOD'] = 'POST';
  483. $_SERVER['REMOTE_ADDR'] = '::1';
  484. TrafficLimiter::canPass();
  485. EOT;
  486. break;
  487. case 'Read':
  488. $code .= PHP_EOL . <<<'EOT'
  489. $this->_model->create(Helper::getPasteId(), Helper::getPaste());
  490. $_SERVER['QUERY_STRING'] = Helper::getPasteId();
  491. $_GET[Helper::getPasteId()] = '';
  492. $_SERVER['HTTP_X_REQUESTED_WITH'] = 'JSONHttpRequest';
  493. EOT;
  494. break;
  495. case 'Delete':
  496. $code .= PHP_EOL . <<<'EOT'
  497. $paste = Helper::getPaste();
  498. $this->_model->create(Helper::getPasteId(), $paste);
  499. $this->assertTrue($this->_model->exists(Helper::getPasteId()), 'paste exists before deleting data');
  500. $_GET['pasteid'] = Helper::getPasteId();
  501. $_GET['deletetoken'] = hash_hmac('sha256', Helper::getPasteId(), $this->_model->read(Helper::getPasteId())['meta']['salt']);
  502. EOT;
  503. break;
  504. }
  505. // all steps
  506. $code .= PHP_EOL . $preString;
  507. $code .= <<<'EOT'
  508. ob_start();
  509. new Controller;
  510. $content = ob_get_contents();
  511. ob_end_clean();
  512. EOT;
  513. // step specific tests
  514. switch ($step) {
  515. case 'Create':
  516. $code .= <<<'EOT'
  517. $response = json_decode($content, true);
  518. EOT;
  519. break;
  520. case 'Read':
  521. $code .= <<<'EOT'
  522. $response = json_decode($content, true);
  523. $this->assertEquals(0, $response['status'], 'outputs success status');
  524. $this->assertEquals(Helper::getPasteId(), $response['id'], 'outputs id correctly');
  525. $this->assertEquals(Helper::getPaste()['data'], $response['data'], 'outputs data correctly');
  526. EOT;
  527. break;
  528. case 'Delete':
  529. $code .= <<<'EOT'
  530. $this->assertMatchesRegularExpression(
  531. '#<div[^>]*id="status"[^>]*>.*Document was properly deleted[^<]*(<button|<\/div>)#s',
  532. $content,
  533. 'outputs deleted status correctly'
  534. );
  535. $this->assertFalse($this->_model->exists(Helper::getPasteId()), 'paste successfully deleted');
  536. EOT;
  537. break;
  538. }
  539. return $code . PHP_EOL . PHP_EOL . $testString . ' }' . PHP_EOL . PHP_EOL;
  540. }
  541. /**
  542. * recursive function to generate configurations based on options
  543. *
  544. * @throws Exception
  545. * @return array
  546. */
  547. private function _generateConfigurations()
  548. {
  549. // recursive factorial function
  550. if (++$this->_iterationCount > self::MAX_ITERATIONS) {
  551. echo 'max iterations reached, stopping', PHP_EOL;
  552. return $this->_configurations;
  553. }
  554. echo "generateConfigurations: iteration $this->_iterationCount", PHP_EOL;
  555. $path = key($this->_options);
  556. $settings = current($this->_options);
  557. if (next($this->_options) === false) {
  558. return $this->_configurations;
  559. }
  560. list($section, $option) = explode('/', $path);
  561. for ($c = 0, $max = count($this->_configurations); $c < $max; ++$c) {
  562. if (!array_key_exists($section, $this->_configurations[$c]['options'])) {
  563. $this->_configurations[$c]['options'][$section] = array();
  564. }
  565. if (count($settings) == 0) {
  566. throw new Exception("Check your \$options: option $option has no settings!");
  567. }
  568. // set the first setting in the original configuration
  569. $setting = current($settings);
  570. $this->_addSetting($this->_configurations[$c], $setting, $section, $option);
  571. // create clones for each of the other settings
  572. while ($setting = next($settings)) {
  573. $clone = $this->_configurations[$c];
  574. $this->_configurations[] = $this->_addSetting($clone, $setting, $section, $option);
  575. }
  576. reset($settings);
  577. }
  578. return $this->_generateConfigurations();
  579. }
  580. /**
  581. * add a setting to the given configuration
  582. *
  583. * @param array $configuration
  584. * @param array $setting
  585. * @param string $section
  586. * @param string $option
  587. * @throws Exception
  588. * @return array
  589. */
  590. private function _addSetting(&$configuration, &$setting, &$section, &$option)
  591. {
  592. if (++$this->_iterationCount > self::MAX_ITERATIONS) {
  593. echo 'max iterations reached, stopping', PHP_EOL;
  594. return $configuration;
  595. }
  596. echo "addSetting: iteration $this->_iterationCount", PHP_EOL;
  597. if (
  598. array_key_exists($option, $configuration['options'][$section]) &&
  599. $configuration['options'][$section][$option] === $setting['setting']
  600. ) {
  601. $val = Helper::varExportMin($setting['setting'], true);
  602. throw new Exception("Endless loop or error in options detected: option '$option' already exists with setting '$val' in one of the configurations!");
  603. }
  604. $configuration['options'][$section][$option] = $setting['setting'];
  605. $configuration['tests'][$option] = array($setting['tests'], $setting['affects']);
  606. foreach ($setting['affects'] as $affects) {
  607. if (!in_array($affects, $configuration['affects'])) {
  608. $configuration['affects'][] = $affects;
  609. }
  610. }
  611. return $configuration;
  612. }
  613. }