configuration-test-generator 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636
  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. ),
  174. ),
  175. 'affects' => $vd,
  176. )
  177. ),
  178. 'main/sizelimit' => array(
  179. array(
  180. 'setting' => 10,
  181. 'tests' => array(
  182. array(
  183. 'conditions' => array('steps' => array('create'), 'traffic/limit' => 10),
  184. 'type' => 'Equals',
  185. 'args' => array(
  186. 1,
  187. '$response["status"]',
  188. 'when sizelimit limit exceeded, fail to create paste',
  189. ),
  190. ),
  191. ),
  192. 'affects' => array('create'),
  193. ), array(
  194. 'setting' => 2097152,
  195. 'tests' => array(
  196. array(
  197. 'conditions' => array('steps' => array('create'), 'traffic/limit' => 0, 'main/burnafterreadingselected' => true),
  198. 'settings' => array('sleep(3)'),
  199. 'type' => 'Equals',
  200. 'args' => array(
  201. 0,
  202. '$response["status"]',
  203. 'when sizelimit limit is not reached, successfully create paste',
  204. ),
  205. ), array(
  206. 'conditions' => array('steps' => array('create'), 'traffic/limit' => 0, 'main/burnafterreadingselected' => true),
  207. 'settings' => array('sleep(3)'),
  208. 'type' => 'True',
  209. 'args' => array(
  210. '$this->_model->exists($response["id"])',
  211. 'when sizelimit limit is not reached, paste exists after posting data',
  212. ),
  213. ),
  214. ),
  215. 'affects' => array('create'),
  216. ),
  217. ),
  218. 'traffic/limit' => array(
  219. array(
  220. 'setting' => 0,
  221. 'tests' => array(
  222. array(
  223. 'conditions' => array('steps' => array('create'), 'main/sizelimit' => 2097152),
  224. 'type' => 'Equals',
  225. 'args' => array(
  226. 0,
  227. '$response["status"]',
  228. 'when traffic limit is disabled, successfully create paste',
  229. ),
  230. ), array(
  231. 'conditions' => array('steps' => array('create'), 'main/sizelimit' => 2097152),
  232. 'type' => 'True',
  233. 'args' => array(
  234. '$this->_model->exists($response["id"])',
  235. 'when traffic limit is disabled, paste exists after posting data',
  236. ),
  237. ),
  238. ),
  239. 'affects' => array('create'),
  240. ), array(
  241. 'setting' => 10,
  242. 'tests' => array(
  243. array(
  244. 'conditions' => array('steps' => array('create')),
  245. 'type' => 'Equals',
  246. 'args' => array(
  247. 1,
  248. '$response["status"]',
  249. 'when traffic limit is on and we do not wait, fail to create paste',
  250. ),
  251. ),
  252. ),
  253. 'affects' => array('create'),
  254. ), array(
  255. 'setting' => 2,
  256. 'tests' => array(
  257. array(
  258. 'conditions' => array('steps' => array('create'), 'main/sizelimit' => 2097152),
  259. 'settings' => array('sleep(3)'),
  260. 'type' => 'Equals',
  261. 'args' => array(
  262. 0,
  263. '$response["status"]',
  264. 'when traffic limit is on and we wait, successfully create paste',
  265. ),
  266. ), array(
  267. 'conditions' => array('steps' => array('create'), 'main/sizelimit' => 2097152),
  268. 'settings' => array('sleep(3)'),
  269. 'type' => 'True',
  270. 'args' => array(
  271. '$this->_model->exists($response["id"])',
  272. 'when traffic limit is on and we wait, paste exists after posting data',
  273. ),
  274. ),
  275. ),
  276. 'affects' => array('create'),
  277. ),
  278. ),
  279. ));
  280. class ConfigurationTestGenerator
  281. {
  282. /**
  283. * endless loop protection, since we're working with a recursive function,
  284. * creating factorial configurations
  285. * @var int
  286. */
  287. const MAX_ITERATIONS = 2000;
  288. /**
  289. * options to test
  290. * @var array
  291. */
  292. private $_options;
  293. /**
  294. * iteration count to guarantee timely end
  295. * @var int
  296. */
  297. private $_iterationCount = 0;
  298. /**
  299. * generated configurations
  300. * @var array
  301. */
  302. private $_configurations = array(
  303. array('options' => array(), 'tests' => array(), 'affects' => array()),
  304. );
  305. /**
  306. * constructor, generates the configuration test
  307. * @param array $options
  308. */
  309. public function __construct($options)
  310. {
  311. $this->_options = $options;
  312. // generate all possible combinations of options: options^settings
  313. $this->_generateConfigurations();
  314. $this->_writeConfigurationTest();
  315. }
  316. /**
  317. * write configuration test file based on generated configuration array
  318. */
  319. private function _writeConfigurationTest()
  320. {
  321. $defaultOptions = parse_ini_file(CONF_SAMPLE, true);
  322. $code = $this->_getHeader();
  323. foreach ($this->_configurations as $key => $conf) {
  324. $fullOptions = array_replace_recursive($defaultOptions, $conf['options']);
  325. $options = Helper::varExportMin($fullOptions, true);
  326. foreach ($conf['affects'] as $step) {
  327. $testCode = $preCode = array();
  328. foreach ($conf['tests'] as $tests) {
  329. foreach ($tests[0] as $test) {
  330. // skip if test does not affect this step
  331. if (!in_array($step, $tests[1])) {
  332. continue;
  333. }
  334. // skip if not all test conditions are met
  335. if (array_key_exists('conditions', $test)) {
  336. foreach ($test['conditions'] as $path => $setting) {
  337. if ($path == 'steps' && !in_array($step, $setting)) {
  338. continue 2;
  339. } elseif ($path != 'steps') {
  340. list($section, $option) = explode('/', $path);
  341. if ($fullOptions[$section][$option] !== $setting) {
  342. continue 2;
  343. }
  344. }
  345. }
  346. }
  347. if (array_key_exists('settings', $test)) {
  348. foreach ($test['settings'] as $setting) {
  349. $preCode[$setting] = $setting;
  350. }
  351. }
  352. $args = array();
  353. foreach ($test['args'] as $arg) {
  354. if (is_string($arg) && str_starts_with($arg, '$')) {
  355. $args[] = $arg;
  356. } else {
  357. $args[] = Helper::varExportMin($arg, true);
  358. }
  359. }
  360. $testCode[] = array($test['type'], implode(', ', $args));
  361. }
  362. }
  363. $code .= $this->_getFunction(
  364. ucfirst($step), $key, $options, $preCode, $testCode, $fullOptions['main']['discussion']
  365. );
  366. }
  367. }
  368. $code .= '}' . PHP_EOL;
  369. file_put_contents(dirname(__FILE__) . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'tst' . DIRECTORY_SEPARATOR . 'ConfigurationCombinationsTest.php', $code);
  370. }
  371. /**
  372. * get header of configuration test file
  373. *
  374. * @return string
  375. */
  376. private function _getHeader()
  377. {
  378. return <<<'EOT'
  379. <?php declare(strict_types=1);
  380. /**
  381. * DO NOT EDIT: This file is generated automatically using configGenerator.php
  382. */
  383. use PHPUnit\Framework\TestCase;
  384. use PrivateBin\Controller;
  385. use PrivateBin\Data\Filesystem;
  386. use PrivateBin\Persistence\ServerSalt;
  387. use PrivateBin\Persistence\TrafficLimiter;
  388. use PrivateBin\Request;
  389. class ConfigurationCombinationsTest extends TestCase
  390. {
  391. private $_conf;
  392. private $_model;
  393. private $_path;
  394. public function setUp(): void
  395. {
  396. /* Setup Routine */
  397. Helper::confBackup();
  398. $this->_path = sys_get_temp_dir() . DIRECTORY_SEPARATOR . 'privatebin_data';
  399. $this->_model = new Filesystem(array('dir' => $this->_path));
  400. ServerSalt::setStore($this->_model);
  401. TrafficLimiter::setStore($this->_model);
  402. $this->reset();
  403. }
  404. public function tearDown(): void
  405. {
  406. /* Tear Down Routine */
  407. unlink(CONF);
  408. Helper::confRestore();
  409. Helper::rmDir($this->_path);
  410. }
  411. public function reset($configuration = array())
  412. {
  413. $_POST = array();
  414. $_GET = array();
  415. $_SERVER = array();
  416. if ($this->_model->exists(Helper::getPasteId()))
  417. $this->_model->delete(Helper::getPasteId());
  418. $configuration['model_options']['dir'] = $this->_path;
  419. Helper::createIniFile(CONF, $configuration);
  420. }
  421. EOT;
  422. }
  423. /**
  424. * get unit tests function block
  425. *
  426. * @param string $step
  427. * @param int $key
  428. * @param array $options
  429. * @param array $preCode
  430. * @param array $testCode
  431. * @return string
  432. */
  433. private function _getFunction($step, $key, &$options, $preCode, $testCode, $discussionEnabled)
  434. {
  435. if (count($testCode) == 0) {
  436. echo "skipping creation of test$step$key, no valid tests found for configuration: $options" . PHP_EOL;
  437. return '';
  438. }
  439. $preString = $testString = '';
  440. foreach ($preCode as $setting) {
  441. $preString .= " $setting;" . PHP_EOL;
  442. }
  443. foreach ($testCode as $test) {
  444. $type = $test[0];
  445. $args = $test[1];
  446. $testString .= " \$this->assert$type($args);" . PHP_EOL;
  447. }
  448. $code = <<<EOT
  449. /**
  450. * @runInSeparateProcess
  451. */
  452. public function test$step$key()
  453. {
  454. \$this->reset($options);
  455. EOT;
  456. // step specific initialization
  457. switch ($step) {
  458. case 'Create':
  459. if ($discussionEnabled) {
  460. $code .= PHP_EOL . <<<'EOT'
  461. $paste = Helper::getPasteJson();
  462. EOT;
  463. } else {
  464. $code .= PHP_EOL . <<<'EOT'
  465. $paste = json_decode(Helper::getPasteJson(), true);
  466. $paste['adata'][2] = 0;
  467. $paste = json_encode($paste);
  468. EOT;
  469. }
  470. $code .= PHP_EOL . <<<'EOT'
  471. $file = Helper::createTempFile();
  472. file_put_contents($file, $paste);
  473. Request::setInputStream($file);
  474. $_SERVER['HTTP_X_REQUESTED_WITH'] = 'JSONHttpRequest';
  475. $_SERVER['REQUEST_METHOD'] = 'POST';
  476. $_SERVER['REMOTE_ADDR'] = '::1';
  477. TrafficLimiter::canPass();
  478. EOT;
  479. break;
  480. case 'Read':
  481. $code .= PHP_EOL . <<<'EOT'
  482. $this->_model->create(Helper::getPasteId(), Helper::getPaste());
  483. $_SERVER['QUERY_STRING'] = Helper::getPasteId();
  484. $_GET[Helper::getPasteId()] = '';
  485. $_SERVER['HTTP_X_REQUESTED_WITH'] = 'JSONHttpRequest';
  486. EOT;
  487. break;
  488. case 'Delete':
  489. $code .= PHP_EOL . <<<'EOT'
  490. $paste = Helper::getPaste();
  491. $this->_model->create(Helper::getPasteId(), $paste);
  492. $this->assertTrue($this->_model->exists(Helper::getPasteId()), 'paste exists before deleting data');
  493. $_GET['pasteid'] = Helper::getPasteId();
  494. $_GET['deletetoken'] = hash_hmac('sha256', Helper::getPasteId(), $this->_model->read(Helper::getPasteId())['meta']['salt']);
  495. EOT;
  496. break;
  497. }
  498. // all steps
  499. $code .= PHP_EOL . $preString;
  500. $code .= <<<'EOT'
  501. ob_start();
  502. new Controller;
  503. $content = ob_get_contents();
  504. ob_end_clean();
  505. EOT;
  506. // step specific tests
  507. switch ($step) {
  508. case 'Create':
  509. $code .= <<<'EOT'
  510. $response = json_decode($content, true);
  511. EOT;
  512. break;
  513. case 'Read':
  514. $code .= <<<'EOT'
  515. $response = json_decode($content, true);
  516. $this->assertEquals(0, $response['status'], 'outputs success status');
  517. $this->assertEquals(Helper::getPasteId(), $response['id'], 'outputs id correctly');
  518. $this->assertEquals(Helper::getPaste()['data'], $response['data'], 'outputs data correctly');
  519. EOT;
  520. break;
  521. case 'Delete':
  522. $code .= <<<'EOT'
  523. $this->assertMatchesRegularExpression(
  524. '#<div[^>]*id="status"[^>]*>.*Document was properly deleted[^<]*(<button|<\/div>)#s',
  525. $content,
  526. 'outputs deleted status correctly'
  527. );
  528. $this->assertFalse($this->_model->exists(Helper::getPasteId()), 'paste successfully deleted');
  529. EOT;
  530. break;
  531. }
  532. return $code . PHP_EOL . PHP_EOL . $testString . ' }' . PHP_EOL . PHP_EOL;
  533. }
  534. /**
  535. * recursive function to generate configurations based on options
  536. *
  537. * @throws Exception
  538. * @return array
  539. */
  540. private function _generateConfigurations()
  541. {
  542. // recursive factorial function
  543. if (++$this->_iterationCount > self::MAX_ITERATIONS) {
  544. echo 'max iterations reached, stopping', PHP_EOL;
  545. return $this->_configurations;
  546. }
  547. echo "generateConfigurations: iteration $this->_iterationCount", PHP_EOL;
  548. $path = key($this->_options);
  549. $settings = current($this->_options);
  550. if (next($this->_options) === false) {
  551. return $this->_configurations;
  552. }
  553. list($section, $option) = explode('/', $path);
  554. for ($c = 0, $max = count($this->_configurations); $c < $max; ++$c) {
  555. if (!array_key_exists($section, $this->_configurations[$c]['options'])) {
  556. $this->_configurations[$c]['options'][$section] = array();
  557. }
  558. if (count($settings) == 0) {
  559. throw new Exception("Check your \$options: option $option has no settings!");
  560. }
  561. // set the first setting in the original configuration
  562. $setting = current($settings);
  563. $this->_addSetting($this->_configurations[$c], $setting, $section, $option);
  564. // create clones for each of the other settings
  565. while ($setting = next($settings)) {
  566. $clone = $this->_configurations[$c];
  567. $this->_configurations[] = $this->_addSetting($clone, $setting, $section, $option);
  568. }
  569. reset($settings);
  570. }
  571. return $this->_generateConfigurations();
  572. }
  573. /**
  574. * add a setting to the given configuration
  575. *
  576. * @param array $configuration
  577. * @param array $setting
  578. * @param string $section
  579. * @param string $option
  580. * @throws Exception
  581. * @return array
  582. */
  583. private function _addSetting(&$configuration, &$setting, &$section, &$option)
  584. {
  585. if (++$this->_iterationCount > self::MAX_ITERATIONS) {
  586. echo 'max iterations reached, stopping', PHP_EOL;
  587. return $configuration;
  588. }
  589. echo "addSetting: iteration $this->_iterationCount", PHP_EOL;
  590. if (
  591. array_key_exists($option, $configuration['options'][$section]) &&
  592. $configuration['options'][$section][$option] === $setting['setting']
  593. ) {
  594. $val = Helper::varExportMin($setting['setting'], true);
  595. throw new Exception("Endless loop or error in options detected: option '$option' already exists with setting '$val' in one of the configurations!");
  596. }
  597. $configuration['options'][$section][$option] = $setting['setting'];
  598. $configuration['tests'][$option] = array($setting['tests'], $setting['affects']);
  599. foreach ($setting['affects'] as $affects) {
  600. if (!in_array($affects, $configuration['affects'])) {
  601. $configuration['affects'][] = $affects;
  602. }
  603. }
  604. return $configuration;
  605. }
  606. }