diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml index 31ee8df..45c2090 100644 --- a/.github/workflows/plugin-ci-workflow.yml +++ b/.github/workflows/plugin-ci-workflow.yml @@ -24,6 +24,12 @@ permissions: env: CACTI: 1.2.x + FLOWVIEW_E2E_SCHEME: http + FLOWVIEW_E2E_HOST: 127.0.0.1:8080 + FLOWVIEW_E2E_DB_HOST: 127.0.0.1 + FLOWVIEW_E2E_DB_NAME: cacti + FLOWVIEW_E2E_DB_USER: cactiuser + FLOWVIEW_E2E_DB_PASS: cactiuser concurrency: group: ${{ github.workflow }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.ref }} @@ -201,6 +207,44 @@ jobs: "$CACTI_PEST_BIN" --configuration=plugins/flowview/phpunit.xml \ --coverage-clover=plugins/flowview/coverage/clover.xml + # The end-to-end tests send real requests to the FlowView pages, so serve + # the installed Cacti with PHP's built-in server as the web user. + - name: Serve Cacti for the end-to-end tests + run: | + p="${{ github.workspace }}" + while [ "$p" != "/" ]; do + sudo chmod o+x "$p" || true + p=$(dirname "$p") + done + + cd ${{ github.workspace }}/cacti + # The CLI installer creates the log as root. Both test users initialize Cacti. + sudo chown runner:www-data log/cacti.log + sudo chmod 664 log/cacti.log + sudo sed -i "s#^\$url_path = .*#\$url_path = '/';#" include/config.php + sudo -u www-data nohup php -S "$FLOWVIEW_E2E_HOST" -t ${{ github.workspace }}/cacti > "${{ runner.temp }}/cacti-web.log" 2>&1 & + + for i in $(seq 1 30); do + if curl -fsS --max-time 5 "$FLOWVIEW_E2E_SCHEME://$FLOWVIEW_E2E_HOST/index.php" -o "${{ runner.temp }}/flowview-login.html" && + grep -Fq "name='login_username'" "${{ runner.temp }}/flowview-login.html"; then + exit 0 + fi + sleep 1 + done + + cat "${{ runner.temp }}/cacti-web.log" + exit 1 + + # tests/Integration is not in phpunit.xml's test suites, so the unit run + # above leaves it out and it is named here. + - name: Run Pest End-to-End Tests + env: + FLOWVIEW_E2E_CACTI: ${{ github.workspace }}/cacti + run: | + cd ${{ github.workspace }}/cacti + "$CACTI_PEST_BIN" --configuration=plugins/flowview/phpunit.xml \ + --no-coverage plugins/flowview/tests/Integration + # Whole-file coverage is meaningless here: most of the plugin only runs # inside a live Cacti. What is enforceable is that a change covers the # lines it adds. diff --git a/flowview_bulkarin.php b/flowview_bulkarin.php index a473f56..da7f8db 100644 --- a/flowview_bulkarin.php +++ b/flowview_bulkarin.php @@ -124,7 +124,7 @@ if ($origin == '') { if (file_exists($whois_path) && is_executable($whois_path) && $whois_provider != '') { - $last_line = exec("$whois_path -h $whois_provider $cidr | grep 'origin:' | head -1 | awk -F':' '{print \$2}'", $output, $return_var); + $last_line = exec(cacti_escapeshellcmd($whois_path) . ' -h ' . cacti_escapeshellarg($whois_provider) . ' ' . cacti_escapeshellarg($cidr) . " | grep 'origin:' | head -1 | awk -F':' '{print \$2}'", $output, $return_var); /* attempt to prevent rate limiting */ sleep(1); diff --git a/flowview_databases.php b/flowview_databases.php index 14ad0a9..8e3543f 100644 --- a/flowview_databases.php +++ b/flowview_databases.php @@ -30,6 +30,7 @@ require('./lib/utility.php'); require_once('./plugins/flowview/includes/functions.php'); require_once('./plugins/flowview/includes/database.php'); +require_once(__DIR__ . '/includes/database_details.php'); flowview_connect(); @@ -70,126 +71,7 @@ function flowview_get_item_details(): bool { require($config['base_path'] . '/plugins/flowview/includes/arrays.php'); - $cols = get_all_columns(); - $tab = get_nfilter_request_var('tab'); - $ids = json_decode(base64_decode(str_replace('line_', '', get_request_var('id'))), true); - $table = "plugin_flowview_irr_$tab"; - - $sql_where = ''; - $sql_params = []; - - if (cacti_sizeof($ids) && flowview_db_table_exists($table)) { - foreach($ids as $col => $value) { - $sql_where .= ($sql_where != '' ? ' AND ':'WHERE ') . "$col = ?"; - $sql_params[] = $value; - } - } else { - return false; - } - - $details = flowview_db_fetch_row_prepared("SELECT * - FROM $table - $sql_where - LIMIT 1", $sql_params); - - ob_start(); - - $mnt_by_present = false; - - print "
"; - - html_start_box(__('Internet Route Registry Details', 'flowview'), '100%', false, 3, 'center', ''); - - $response = flowview_print_details($cols, $details); - - html_end_box(); - - if ($response['mnt_by_present'] == true) { - $maintainers = preg_split('/[\s]+/', trim($response['mnt_by'])) ?: []; - - foreach($maintainers as $m) { - $sql_params = []; - $sql_params[] = $m; - $sql_params[] = $response['mnt_by_source']; - - $details = flowview_db_fetch_row_prepared("SELECT * - FROM plugin_flowview_irr_mntner - WHERE mntner = ? - AND source = ? - LIMIT 1", $sql_params); - - if (cacti_sizeof($details)) { - html_start_box(__('Authorized Agent Details', 'flowview'), '100%', false, 3, 'center', ''); - - flowview_print_details($cols, $details); - - html_end_box(); - } - } - } - - print "
"; - - ob_get_flush(); - return true; -} - -/** - * @param mixed $cols - * @param mixed $details - * - * @return array - */ -function flowview_print_details(&$cols, &$details): array { - $mnt_by_present = false; - $mnt_by = ''; - $mnt_by_source = ''; - - if (cacti_sizeof($details)) { - foreach($details as $column => $value) { - if ($column == 'mnt_by' && $value != '') { - $mnt_by_present = true; - $mnt_by = $value; - } - - if ($column == 'source') { - $mnt_by_source = $value; - } - - /* get rid of some nagging hyphens */ - $value = str_replace("------------------------------------------\n", '', $value); - - if ($value != '' && $value != '0000-00-00 00:00:00' && $column != 'present') { - print ''; - - if ($column == 'as_set') { - $value = strtoupper($value); - } - - if (isset($cols[$column])) { - print '' . html_escape($cols[$column]['display']) . ':'; - } else { - print '' . html_escape(ucfirst(str_replace('_', ' ', $column))) . ':'; - } - - if ($column == 'remarks' || - $column == 'import' || - $column == 'export' || - $column == 'mp_import' || - $column == 'mp_export') { - print '' . str_replace("\n", '
', html_escape($value)) . ''; - } else { - print '' . str_replace("\n", ', ', html_escape($value)) . ''; - } - - print ''; - } - } - } else { - print '' . __('No Details Found', 'flowview') . ''; - } - - return ['mnt_by_present' => $mnt_by_present, 'mnt_by' => $mnt_by, 'mnt_by_source' => $mnt_by_source]; + return flowview_render_item_details(get_all_columns()); } /** @@ -958,7 +840,7 @@ function view_db_table($tab, &$tabs): void { if (cacti_sizeof($sources) > 0) { foreach ($sources as $key => $value) { - print "'; + print "'; } } ?> @@ -1140,9 +1022,9 @@ function() { $value = $result[$c]; } - form_selectable_cell($value, $i, '', $align); + form_selectable_cell(html_escape($value), $i, '', $align); } else { - form_selectable_cell($result[$c], $i, '', $align); + form_selectable_cell(html_escape($result[$c]), $i, '', $align); } } } @@ -1339,7 +1221,7 @@ function view_dns_cache(): void { if (cacti_sizeof($sources) > 0) { foreach ($sources as $key => $value) { - print "'; + print "'; } } ?> @@ -1526,10 +1408,10 @@ function purgeFilter() { form_alternate_row('line' . $l['id'], false); form_selectable_cell(filter_value($l['ip'], get_request_var('filter')), $l['id']); form_selectable_cell(filter_value($l['host'], get_request_var('filter')), $l['id']); - form_selectable_cell($l['source'], $l['id']); + form_selectable_cell(html_escape($l['source']), $l['id']); form_selectable_cell($l['arin_verified'] == 1 ? __('Verified', 'flowview'):__('Unverified', 'flowview'), $l['id']); - form_selectable_cell($l['arin_id'], $l['id'], '', 'right'); - form_selectable_cell($l['origin'], $l['id'], '', 'right'); + form_selectable_cell(html_escape($l['arin_id']), $l['id'], '', 'right'); + form_selectable_cell(html_escape($l['origin']), $l['id'], '', 'right'); form_selectable_cell(date('Y-m-d H:i:s', $l['time']), $l['id'], '', 'right'); form_checkbox_cell($l['host'], $l['id']); form_end_row(); @@ -1644,7 +1526,7 @@ function view_routes($tab): void { if (cacti_sizeof($sources)) { foreach ($sources as $key => $value) { - print "'; + print "'; } } ?> @@ -1901,7 +1783,7 @@ function() { form_selectable_cell(filter_value($l['descr'], get_request_var('filter')), $rid); form_selectable_cell(filter_value($l['source'], get_request_var('filter')), $rid); form_selectable_cell(filter_value($l['mnt_by'], get_request_var('filter')), $rid); - form_selectable_cell($l['last_modified'], $rid, '', 'right'); + form_selectable_cell(html_escape($l['last_modified']), $rid, '', 'right'); form_end_row(); } } else { diff --git a/flowview_filters.php b/flowview_filters.php index d74d397..92853b1 100644 --- a/flowview_filters.php +++ b/flowview_filters.php @@ -133,15 +133,15 @@ function actions_filters(): void { if ($selected_items != false) { if (get_nfilter_request_var('drp_action') == '1') { for ($i=0; $i'; + $filter_list .= '
  • ' . html_escape(flowview_db_fetch_cell_prepared('SELECT name FROM plugin_flowview_queries + WHERE id = ?', [$matches[1]])) . '
  • '; $filter_array[] = $matches[1]; } } @@ -501,7 +501,7 @@ function clearFilter() { if (empty($filter['device'])) { form_selectable_cell(__('All', 'flowview'), $filter['id']); } else { - form_selectable_cell($filter['device'], $filter['id']); + form_selectable_cell(html_escape($filter['device']), $filter['id']); } if ($filter['statistics'] > 0) { diff --git a/flowview_process.php b/flowview_process.php index f49dc3b..7dd01d0 100644 --- a/flowview_process.php +++ b/flowview_process.php @@ -98,16 +98,21 @@ ); if (cacti_sizeof($queued_reports)) { - $sql_where = ' AND fs.id NOT IN (' . implode(', ', $queued_reports) . ')'; + $sql_where = ' AND fs.id NOT IN (' . implode(', ', array_fill(0, cacti_sizeof($queued_reports), '?')) . ')'; + $sql_params = array_values($queued_reports); } else { - $sql_where = ''; + $sql_where = ''; + $sql_params = []; } -$schedules = flowview_db_fetch_assoc("SELECT fs.* +$sql_params[] = $t; + +$schedules = flowview_db_fetch_assoc_prepared("SELECT fs.* FROM plugin_flowview_schedules AS fs WHERE enabled = 'on' $sql_where - AND ($t - sendinterval > lastsent)"); + AND (? - sendinterval > lastsent)", + $sql_params); $php = read_config_option('path_php_binary'); diff --git a/flowview_upgrade.php b/flowview_upgrade.php index 8ea5e8e..c987186 100644 --- a/flowview_upgrade.php +++ b/flowview_upgrade.php @@ -364,7 +364,7 @@ function flowview_upgrade($current, $old): void { flowview_db_execute("UPDATE plugin_flowview_schedules SET title='Ugraded Schedule' WHERE title=''"); /* Set the new version */ - db_execute_prepared("REPLACE INTO settings (name, value) VALUES ('plugin_flowview_version', ?)", [$current]); + set_config_option('plugin_flowview_version', $current); flowview_db_execute('ALTER TABLE plugin_flowview_devices ENGINE=InnoDB'); } diff --git a/includes/database_details.php b/includes/database_details.php new file mode 100644 index 0000000..7a25943 --- /dev/null +++ b/includes/database_details.php @@ -0,0 +1,153 @@ + $value) { + if (!isset($columns[$col])) { + return false; + } + + $sql_where .= ($sql_where != '' ? ' AND ':'WHERE ') . "$col = ?"; + $sql_params[] = $value; + } + } else { + return false; + } + + $details = flowview_db_fetch_row_prepared("SELECT * + FROM $table + $sql_where + LIMIT 1", $sql_params); + + ob_start(); + + $mnt_by_present = false; + + print "
    "; + + html_start_box(__('Internet Route Registry Details', 'flowview'), '100%', false, 3, 'center', ''); + + $response = flowview_print_details($cols, $details); + + html_end_box(); + + if ($response['mnt_by_present'] == true) { + $maintainers = preg_split('/[\s]+/', trim($response['mnt_by'])) ?: []; + + foreach($maintainers as $m) { + $sql_params = []; + $sql_params[] = $m; + $sql_params[] = $response['mnt_by_source']; + + $details = flowview_db_fetch_row_prepared("SELECT * + FROM plugin_flowview_irr_mntner + WHERE mntner = ? + AND source = ? + LIMIT 1", $sql_params); + + if (cacti_sizeof($details)) { + html_start_box(__('Authorized Agent Details', 'flowview'), '100%', false, 3, 'center', ''); + + flowview_print_details($cols, $details); + + html_end_box(); + } + } + } + + print "
    "; + + ob_get_flush(); + return true; +} + +/** + * @param mixed $cols + * @param mixed $details + * + * @return array + */ +function flowview_print_details(&$cols, &$details): array { + $mnt_by_present = false; + $mnt_by = ''; + $mnt_by_source = ''; + + if (cacti_sizeof($details)) { + foreach($details as $column => $value) { + if ($column == 'mnt_by' && $value != '') { + $mnt_by_present = true; + $mnt_by = $value; + } + + if ($column == 'source') { + $mnt_by_source = $value; + } + + /* get rid of some nagging hyphens */ + $value = str_replace("------------------------------------------\n", '', $value); + + if ($value != '' && $value != '0000-00-00 00:00:00' && $column != 'present') { + print ''; + + if ($column == 'as_set') { + $value = strtoupper($value); + } + + if (isset($cols[$column])) { + print '' . html_escape($cols[$column]['display']) . ':'; + } else { + print '' . html_escape(ucfirst(str_replace('_', ' ', $column))) . ':'; + } + + if ($column == 'remarks' || + $column == 'import' || + $column == 'export' || + $column == 'mp_import' || + $column == 'mp_export') { + print '' . str_replace("\n", '
    ', html_escape($value)) . ''; + } else { + print '' . str_replace("\n", ', ', html_escape($value)) . ''; + } + + print ''; + } + } + } else { + print '' . __('No Details Found', 'flowview') . ''; + } + + return ['mnt_by_present' => $mnt_by_present, 'mnt_by' => $mnt_by, 'mnt_by_source' => $mnt_by_source]; +} diff --git a/locales/po/cacti.pot b/locales/po/cacti.pot index 6ffcacd..86602fd 100644 --- a/locales/po/cacti.pot +++ b/locales/po/cacti.pot @@ -49,15 +49,15 @@ msgstr "" msgid "DNS Cache has been purged. It will refill as records come in." msgstr "" -#: flowview_databases.php +#: includes/database_details.php msgid "Internet Route Registry Details" msgstr "" -#: flowview_databases.php +#: includes/database_details.php msgid "Authorized Agent Details" msgstr "" -#: flowview_databases.php +#: includes/database_details.php msgid "No Details Found" msgstr "" diff --git a/phpunit.xml b/phpunit.xml index ca15b0c..e2a49f2 100644 --- a/phpunit.xml +++ b/phpunit.xml @@ -39,6 +39,7 @@ Net/DNS2/Updater.php includes/functions.php includes/database.php + includes/database_details.php includes/arrays.php diff --git a/tests/Integration/FlowviewHttpTest.php b/tests/Integration/FlowviewHttpTest.php new file mode 100644 index 0000000..f7548a8 --- /dev/null +++ b/tests/Integration/FlowviewHttpTest.php @@ -0,0 +1,558 @@ + (getenv('FLOWVIEW_E2E_SCHEME') ?: 'http') . '://' . $host, + 'dsn' => 'mysql:host=' . (getenv('FLOWVIEW_E2E_DB_HOST') ?: '127.0.0.1') . ';dbname=' . $db, + 'user' => (string) getenv('FLOWVIEW_E2E_DB_USER'), + 'pass' => (string) getenv('FLOWVIEW_E2E_DB_PASS'), + 'cacti' => getenv('FLOWVIEW_E2E_CACTI') ?: dirname(__DIR__, 3), + ]; +} + +/** + * Minimal cookie-keeping HTTP client; redirects are reported, not followed. + */ +final class FlowviewE2eClient { + /** @var array */ + private array $cookies = []; + + private string $base; + + public function __construct(string $base) { + $this->base = $base; + } + + /** + * @param array $fields + * + * @return array{status: int, location: string, body: string} + */ + public function request(string $method, string $path, array $fields = []): array { + $header = "User-Agent: flowview-e2e\r\n"; + + foreach ($this->cookies as $name => $value) { + $header .= "Cookie: $name=$value\r\n"; + } + + $http = [ + 'method' => $method, + 'ignore_errors' => true, + 'follow_location' => 0, + 'timeout' => 120, + ]; + + if ($method === 'POST') { + $header .= "Content-Type: application/x-www-form-urlencoded\r\n"; + $http['content'] = http_build_query($fields); + } + + $http['header'] = $header; + + $body = file_get_contents($this->base . $path, false, stream_context_create(['http' => $http])); + + $status = 0; + $location = ''; + + $headers = function_exists('http_get_last_response_headers') ? http_get_last_response_headers() : ($http_response_header ?? []); + foreach ($headers ?? [] as $line) { + if (preg_match('#^HTTP/\S+ (\d+)#', $line, $m)) { + $status = (int) $m[1]; + } elseif (stripos($line, 'Location:') === 0) { + $location = trim(substr($line, 9)); + } elseif (stripos($line, 'Set-Cookie:') === 0 && preg_match('/^Set-Cookie:\s*([^=;\s]+)=([^;]*)/i', $line, $m)) { + $this->cookies[$m[1]] = $m[2]; + } + } + + return ['status' => $status, 'location' => $location, 'body' => (string) $body]; + } + + public function login(string $user, string $pass): bool { + $page = $this->request('GET', '/index.php'); + + if (!preg_match('/name=.__csrf_magic. value="([^"]+)"/', $page['body'], $m)) { + return false; + } + + $result = $this->request('POST', '/index.php', [ + '__csrf_magic' => $m[1], + 'action' => 'login', + 'login_username' => $user, + 'login_password' => $pass, + ]); + + return $result['status'] === 302; + } + + /** + * Sends a POST that carries the CSRF token of the page it is sent to. + * + * @param array $fields + * + * @return array{status: int, location: string, body: string} + */ + public function post(string $path, array $fields): array { + $page = $this->request('GET', $path); + + preg_match('/csrfMagicToken\s*=\s*[\'"]([^\'"]+)[\'"]/', $page['body'], $m); + + $fields['__csrf_magic'] = $m[1] ?? ''; + + return $this->request('POST', $path, $fields); + } + + public function get(string $path): array { + return $this->request('GET', $path); + } +} + +/* ------------------------------------------------------------------ */ +/* database helpers */ +/* ------------------------------------------------------------------ */ + +function flowview_e2e_db(): PDO { + static $pdo = null; + + if ($pdo === null) { + $config = flowview_e2e_config(); + + $pdo = new PDO($config['dsn'], $config['user'], $config['pass'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]); + } + + return $pdo; +} + +function flowview_e2e_cell(string $sql, array $params = []) { + $stmt = flowview_e2e_db()->prepare($sql); + $stmt->execute($params); + + return $stmt->fetchColumn(); +} + +function flowview_e2e_exec(string $sql, array $params = []): void { + flowview_e2e_db()->prepare($sql)->execute($params); +} + +function flowview_e2e_insert(string $sql, array $params = []): int { + flowview_e2e_exec($sql, $params); + + return (int) flowview_e2e_db()->lastInsertId(); +} + +/** + * The user_auth_realm id of the plugin realm that covers a page. + */ +function flowview_e2e_realm(string $file): int { + return 100 + (int) flowview_e2e_cell('SELECT id FROM plugin_realms WHERE FIND_IN_SET(?, file) > 0', [$file]); +} + +/** + * Creates (or recreates) a local user with exactly the given realms. + * + * @param int[] $realms + */ +function flowview_e2e_make_user(string $name, array $realms): void { + flowview_e2e_drop_user($name); + + $id = flowview_e2e_insert( + 'INSERT INTO user_auth (username, password, realm, full_name, must_change_password, enabled, login_opts) VALUES (?, ?, 0, ?, ?, ?, 1)', + [$name, password_hash(FLOWVIEW_E2E_PASS, PASSWORD_DEFAULT), $name, '', 'on'] + ); + + foreach ($realms as $realm) { + flowview_e2e_exec('INSERT INTO user_auth_realm (user_id, realm_id) VALUES (?, ?)', [$id, $realm]); + } +} + +function flowview_e2e_drop_user(string $name): void { + $id = (int) flowview_e2e_cell('SELECT id FROM user_auth WHERE username = ?', [$name]); + + if ($id === 0) { + return; + } + + foreach (['user_auth_realm', 'user_auth_perms', 'settings_user'] as $table) { + flowview_e2e_exec("DELETE FROM $table WHERE user_id = ?", [$id]); + } + + flowview_e2e_exec('DELETE FROM user_auth WHERE id = ?', [$id]); +} + +/** + * Returns the logged-in client for a fixture user, logging in on first use. + */ +function flowview_e2e_client(string $user): FlowviewE2eClient { + static $clients = []; + + if (!isset($clients[$user])) { + $client = new FlowviewE2eClient(flowview_e2e_config()['base']); + + expect($client->login($user, FLOWVIEW_E2E_PASS))->toBeTrue("login as $user failed"); + + $clients[$user] = $client; + } + + return $clients[$user]; +} + +/** + * Stores a global setting and returns the value it replaced. + */ +function flowview_e2e_setting(string $name, ?string $value): ?string { + $old = flowview_e2e_cell('SELECT value FROM settings WHERE name = ?', [$name]); + + if ($value === null) { + flowview_e2e_exec('DELETE FROM settings WHERE name = ?', [$name]); + } else { + flowview_e2e_exec('REPLACE INTO settings (name, value) VALUES (?, ?)', [$name, $value]); + } + + return $old === false ? null : (string) $old; +} + +/** + * Runs a plugin CLI script as a subprocess. + * + * @param string[] $args + * + * @return array{status: int, output: string} + */ +function flowview_e2e_cli(string $script, array $args): array { + $plugin = flowview_e2e_config()['cacti'] . '/plugins/flowview'; + + /* some of the scripts find Cacti relative to the working directory */ + $command = 'cd ' . escapeshellarg($plugin) . ' && ' . escapeshellarg(PHP_BINARY) . ' ' . escapeshellarg($script); + + foreach ($args as $arg) { + $command .= ' ' . escapeshellarg($arg); + } + + exec($command . ' 2>&1', $output, $status); + + return ['status' => $status, 'output' => implode("\n", $output)]; +} + +/** + * The text appended to cacti.log since a size returned by flowview_e2e_log_size(). + */ +function flowview_e2e_log_since(int $mark): string { + $log = flowview_e2e_config()['cacti'] . '/log/cacti.log'; + + clearstatcache(); + + return is_readable($log) ? (string) file_get_contents($log, false, null, $mark) : ''; +} + +function flowview_e2e_log_size(): int { + $log = flowview_e2e_config()['cacti'] . '/log/cacti.log'; + + clearstatcache(); + + return is_readable($log) ? (int) filesize($log) : 0; +} + +/** + * The details of a registry row, as the Databases page asks for them. + */ +function flowview_e2e_details(string $user, array $ids): array { + $id = 'line_' . base64_encode((string) json_encode($ids)); + + return flowview_e2e_client($user)->get('/plugins/flowview/flowview_databases.php?action=database_details&tab=aut_num&id=' . urlencode($id)); +} + +/* ------------------------------------------------------------------ */ +/* fixture */ +/* ------------------------------------------------------------------ */ + +function flowview_e2e_cleanup(): void { + flowview_e2e_exec("DELETE FROM plugin_flowview_irr_aut_num WHERE aut_num LIKE 'AS6450%'"); + flowview_e2e_exec("DELETE FROM plugin_flowview_dnscache WHERE host LIKE 'e2e-%'"); + flowview_e2e_exec("DELETE FROM plugin_flowview_queries WHERE name LIKE 'e2e %'"); + flowview_e2e_exec("DELETE FROM plugin_flowview_devices WHERE name LIKE '%e2e%'"); + flowview_e2e_exec("DELETE FROM plugin_flowview_arin_information WHERE name = 'e2e'"); + flowview_e2e_exec("DELETE FROM reports_queued WHERE source = 'flowview' AND name LIKE 'e2e %'"); + flowview_e2e_exec("DELETE FROM plugin_flowview_schedules WHERE title LIKE 'e2e %'"); +} + +beforeAll(function () { + if (flowview_e2e_config() === null) { + return; + } + + flowview_e2e_cleanup(); + + flowview_e2e_make_user('e2e_fv_admin', [FLOWVIEW_E2E_REALM_CONSOLE, flowview_e2e_realm('flowview_databases.php')]); + flowview_e2e_make_user('e2e_fv_user', [FLOWVIEW_E2E_REALM_CONSOLE, flowview_e2e_realm('flowview.php')]); +}); + +afterAll(function () { + if (flowview_e2e_config() === null) { + return; + } + + flowview_e2e_drop_user('e2e_fv_admin'); + flowview_e2e_drop_user('e2e_fv_user'); + flowview_e2e_cleanup(); +}); + +beforeEach(function () { + if (flowview_e2e_config() === null) { + $this->markTestSkipped('Set FLOWVIEW_E2E_HOST and FLOWVIEW_E2E_DB_NAME to run the end-to-end tests.'); + } +}); + +/* ------------------------------------------------------------------ */ +/* Databases page */ +/* ------------------------------------------------------------------ */ + +describe('the Databases page', function () { + beforeEach(function () { + flowview_e2e_cleanup(); + + /* the registry tables are only listed when they are downloaded */ + $this->irr = flowview_e2e_setting('flowview_download_irr', 'on'); + + flowview_e2e_exec('INSERT INTO plugin_flowview_irr_aut_num (aut_num, source, as_name, descr) VALUES (?, ?, ?, ?)', ['AS64500', 'e2e', 'E2E-NET', 'e2e network']); + flowview_e2e_exec('INSERT INTO plugin_flowview_irr_aut_num (aut_num, source, as_name, descr) VALUES (?, ?, ?, ?)', ['AS64501', 'E2E', 'E2E-OTHER', 'e2e other network']); + }); + + afterEach(function () { + flowview_e2e_setting('flowview_download_irr', $this->irr); + }); + + it('shows the details of the row the id names', function () { + $page = flowview_e2e_details('e2e_fv_admin', ['aut_num' => 'AS64501', 'source' => 'E2E']); + + expect($page['status'])->toBe(200) + ->and($page['body'])->toContain('E2E-OTHER') + ->and($page['body'])->not->toContain('E2E-NET'); + }); + + it('shows no row when a key of the id is not a column', function () { + $page = flowview_e2e_details('e2e_fv_admin', ['aut_num' => 'AS64509', 'aut_num OR source' => 'E2E']); + + expect($page['body'])->not->toContain('E2E-OTHER') + ->and($page['body'])->not->toContain('E2E-NET') + ->and($page['body'])->not->toContain('Internet Route Registry Details'); + }); + + it('does not show the details to a user without the NetFlow Admin realm', function () { + $page = flowview_e2e_details('e2e_fv_user', ['aut_num' => 'AS64501', 'source' => 'E2E']); + + expect($page['body'])->not->toContain('E2E-OTHER'); + }); + + it('escapes the registry values of a table it lists', function () { + $page = flowview_e2e_client('e2e_fv_admin')->get('/plugins/flowview/flowview_databases.php?tab=aut_num&header=false&rows=-1&filter=&source=-1'); + + expect($page['status'])->toBe(200) + ->and($page['body'])->toContain('E2E-NET') + ->and($page['body'])->toContain('<i>e2e</i>') + ->and($page['body'])->not->toContain('e2e'); + }); + + it('escapes the values of the DNS cache', function () { + $arin = flowview_e2e_insert("INSERT INTO plugin_flowview_arin_information (cidr, name, origin) VALUES ('192.0.2.0/24', 'e2e', ?)", ['e2e-as']); + + flowview_e2e_exec('INSERT INTO plugin_flowview_dnscache (ip, host, source, arin_verified, arin_id, time) VALUES (?, ?, ?, 1, ?, UNIX_TIMESTAMP())', ['192.0.2.10', 'e2e-host.example', 'e2e-dns', $arin]); + + $page = flowview_e2e_client('e2e_fv_admin')->get('/plugins/flowview/flowview_databases.php?tab=dns_cache&header=false&rows=-1&filter=&source=-1&verified=-1'); + + expect($page['status'])->toBe(200) + ->and($page['body'])->toContain('e2e-host.example') + ->and($page['body'])->toContain('<i>e2e-dns</i>') + ->and($page['body'])->not->toContain('e2e-dns') + ->and($page['body'])->toContain('<i>e2e-as</i>') + ->and($page['body'])->not->toContain('e2e-as'); + }); +}); + +/* ------------------------------------------------------------------ */ +/* Filters page */ +/* ------------------------------------------------------------------ */ + +describe('the Filters page', function () { + beforeEach(function () { + flowview_e2e_cleanup(); + + $device = flowview_e2e_insert('INSERT INTO plugin_flowview_devices (name, port) VALUES (?, ?)', ['e2e-listener', 2055]); + + $filter = 'INSERT INTO plugin_flowview_queries (name, device_id, startdate, enddate, tosfields, tcpflags, sourceip, sourceport, sourceinterface, sourceas, destip, destport, destinterface, destas, statistics, printed, includeif, sortfield, cutofflines, cutoffoctets, resolve) + VALUES (?, ?, "", "", "", "", "", "", "", "", "", "", "", "", 2, 0, 0, "bytes", "20", "", "N")'; + + $this->filter = flowview_e2e_insert($filter, ['e2e first filter', $device]); + $this->other = flowview_e2e_insert($filter, ['e2e other filter', $device]); + }); + + it('escapes the listener name in the list', function () { + $page = flowview_e2e_client('e2e_fv_admin')->get('/plugins/flowview/flowview_filters.php?header=false&filter=e2e&rows=-1'); + + expect($page['status'])->toBe(200) + ->and($page['body'])->toContain('<i>e2e-listener</i>') + ->and($page['body'])->not->toContain('e2e-listener'); + }); + + it('escapes the Filter names it asks to confirm', function () { + $page = flowview_e2e_client('e2e_fv_admin')->post('/plugins/flowview/flowview_filters.php', [ + 'action' => 'actions', + 'drp_action' => '1', + 'chk_' . $this->filter => 'on', + ]); + + expect($page['status'])->toBe(200) + ->and($page['body'])->toContain('
  • e2e <i>first</i> filter
  • ') + ->and($page['body'])->not->toContain('first'); + }); + + it('deletes only the selected Filter', function () { + flowview_e2e_client('e2e_fv_admin')->post('/plugins/flowview/flowview_filters.php', [ + 'action' => 'actions', + 'drp_action' => '1', + 'selected_items' => serialize([(string) $this->filter]), + ]); + + expect(flowview_e2e_cell('SELECT COUNT(*) FROM plugin_flowview_queries WHERE id = ?', [$this->filter]))->toBe(0) + ->and(flowview_e2e_cell('SELECT COUNT(*) FROM plugin_flowview_queries WHERE id = ?', [$this->other]))->toBe(1); + }); +}); + +/* ------------------------------------------------------------------ */ +/* CLI scripts */ +/* ------------------------------------------------------------------ */ + +describe('the bulk ARIN loader', function () { + beforeEach(function () { + flowview_e2e_cleanup(); + + $this->dir = sys_get_temp_dir() . '/flowview-e2e-' . getmypid(); + + if (!is_dir($this->dir)) { + mkdir($this->dir, 0700, true); + } + + /* a whois that records the arguments it was given, one per line */ + $this->whois = $this->dir . '/whois'; + $this->args = $this->dir . '/args'; + + file_put_contents($this->whois, "#!/bin/sh\nprintf '%s\\n' \"\$@\" > " . escapeshellarg($this->args) . "\nprintf 'origin: AS64500\\n'\n"); + chmod($this->whois, 0700); + + $this->settings = [ + 'flowview_use_arin' => flowview_e2e_setting('flowview_use_arin', 'on'), + 'flowview_whois_provider' => flowview_e2e_setting('flowview_whois_provider', 'whois.example.invalid'), + 'flowview_path_whois' => flowview_e2e_setting('flowview_path_whois', $this->whois), + ]; + }); + + afterEach(function () { + foreach ($this->settings as $name => $value) { + flowview_e2e_setting($name, $value); + } + + foreach ([$this->whois, $this->args] as $file) { + if (is_file($file)) { + unlink($file); + } + } + + rmdir($this->dir); + }); + + it('passes each value to whois as one argument', function () { + $id = flowview_e2e_insert("INSERT INTO plugin_flowview_arin_information (cidr, name, origin) VALUES (?, 'e2e', '')", ['192.0.2.0/24 e2e']); + + $run = flowview_e2e_cli('flowview_bulkarin.php', ['--proceed', '--origins']); + + expect($run['status'])->toBe(0, $run['output']) + ->and(file($this->args, FILE_IGNORE_NEW_LINES))->toBe(['-h', 'whois.example.invalid', '192.0.2.0/24 e2e']) + ->and(flowview_e2e_cell('SELECT origin FROM plugin_flowview_arin_information WHERE id = ?', [$id]))->toBe('AS64500'); + }); +}); + +describe('the FlowView poller', function () { + beforeEach(function () { + flowview_e2e_cleanup(); + }); + + it('queues the schedules that are due and not already queued', function () { + $schedule = 'INSERT INTO plugin_flowview_schedules (title, enabled, sendinterval, lastsent, email, query_id) VALUES (?, ?, 60, 0, ?, 0)'; + + $queued = flowview_e2e_insert($schedule, ['e2e queued schedule', 'on', 'e2e@example.invalid']); + $due = flowview_e2e_insert($schedule, ['e2e due schedule', 'on', 'e2e@example.invalid']); + + flowview_e2e_exec("INSERT INTO reports_queued (name, source, source_id, status, run_command) VALUES ('e2e queued schedule', 'flowview', ?, 'pending', '')", [$queued]); + + /* keep the maintenance of the poller for another run */ + $last = flowview_e2e_setting('flowview_last_change', (string) time()); + $mark = flowview_e2e_log_size(); + + $run = flowview_e2e_cli('flowview_process.php', []); + + flowview_e2e_setting('flowview_last_change', $last); + + $log = flowview_e2e_log_since($mark); + + expect($run['status'])->toBe(0, $run['output']) + ->and($log)->toContain("The Report 'e2e due schedule' from source flowview with id $due is scheduled to run!") + ->and($log)->not->toContain("The Report 'e2e queued schedule' from source flowview with id $queued is scheduled to run!"); + }); +}); diff --git a/tests/Unit/DatabaseDetailsColumnsTest.php b/tests/Unit/DatabaseDetailsColumnsTest.php new file mode 100644 index 0000000..61f589a --- /dev/null +++ b/tests/Unit/DatabaseDetailsColumnsTest.php @@ -0,0 +1,113 @@ + value + * + * @return array{result: bool, output: string} + */ +function flowview_test_item_details(array $ids, ?array $row = null): array { + set_request_var('tab', 'aut_num'); + set_request_var('id', 'line_' . base64_encode((string) json_encode($ids))); + + /* SHOW TABLES LIKE, for flowview_db_table_exists() */ + plugin_test_queue_db_result('db_fetch_cell', 'plugin_flowview_irr_aut_num'); + + plugin_test_queue_db_result('db_fetch_assoc', [ + ['Field' => 'aut_num', 'Type' => 'varchar(20)', 'Null' => 'NO', 'Default' => '', 'Extra' => ''], + ['Field' => 'source', 'Type' => 'varchar(20)', 'Null' => 'NO', 'Default' => '', 'Extra' => ''], + ['Field' => 'descr', 'Type' => 'varchar(128)', 'Null' => 'NO', 'Default' => '', 'Extra' => ''], + ]); + + plugin_test_queue_db_result('db_fetch_row_prepared', $row ?? ['aut_num' => 'AS64500', 'source' => 'TEST', 'descr' => 'Example network']); + + ob_start(); + $result = flowview_render_item_details(['descr' => ['display' => 'Description']]); + $output = (string) ob_get_clean(); + + return ['result' => $result, 'output' => $output]; +} + +/** + * @return array The prepared row reads that were made + */ +function flowview_test_row_reads(): array { + return array_values(array_filter($GLOBALS['__test_db_calls'], function ($call) { + return $call['fn'] === 'db_fetch_row_prepared'; + })); +} + +it('reads the row by the columns of the table it was sent', function () { + $details = flowview_test_item_details(['aut_num' => 'AS64500', 'source' => 'TEST']); + $reads = flowview_test_row_reads(); + + expect($details['result'])->toBeTrue() + ->and($reads)->toHaveCount(1) + ->and($reads[0]['sql'])->toContain('FROM plugin_flowview_irr_aut_num') + ->and($reads[0]['sql'])->toContain('WHERE aut_num = ? AND source = ?') + ->and($reads[0]['params'])->toBe(['AS64500', 'TEST']); +}); + +it('escapes the values of the row it shows', function () { + $details = flowview_test_item_details(['aut_num' => 'AS64500', 'source' => 'TEST']); + + expect($details['output'])->toContain('Example <b>network</b>') + ->and($details['output'])->not->toContain('network'); +}); + +it('reads nothing when a key is not a column of the table', function () { + $details = flowview_test_item_details(['aut_num' => 'AS64501', 'aut_num OR source' => 'TEST']); + + expect($details['result'])->toBeFalse() + ->and(flowview_test_row_reads())->toBe([]) + ->and($details['output'])->toBe(''); +}); + +it('reads nothing when a key is a column of another table', function () { + $details = flowview_test_item_details(['route' => '192.0.2.0/24']); + + expect($details['result'])->toBeFalse() + ->and(flowview_test_row_reads())->toBe([]); +}); + +it('renders the registry maintainer referenced by an item', function () { + plugin_test_queue_db_result('db_fetch_row_prepared', ['mnt_by' => 'TEST-MNT', 'source' => 'TEST']); + $details = flowview_test_item_details(['aut_num' => 'AS64500'], ['as_set' => 'as-example', 'remarks' => 'Test maintainer']); + + expect($details['output'])->toContain('AS-EXAMPLE', 'Test maintainer') + ->and(flowview_test_row_reads()[1]['params'])->toBe(['TEST-MNT', 'TEST']); +}); + +it('handles empty row identifiers and missing rows', function () { + expect(flowview_test_item_details([])['result'])->toBeFalse(); + plugin_test_reset(); + expect(flowview_test_item_details(['aut_num' => 'AS64500'], [])['output'])->toContain('No Details Found'); +});