From 5ecc9b7e057486bb84e1056665f815f0f6edefb7 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Wed, 2 Dec 2026 18:57:00 -0800 Subject: [PATCH 1/7] fix: bind and allow-list values in FlowView SQL The registry details lookup on the Databases page built its WHERE clause from the keys of the row id sent by the browser. Column names can not be bound, so only columns of the table are now accepted and any other key returns no row. The Disable, Enable and Delete actions of the Filters page and the poller's query for due schedules now bind their values instead of concatenating them. Signed-off-by: Thomas Vincent --- flowview_databases.php | 7 +++++++ flowview_filters.php | 6 +++--- flowview_process.php | 13 +++++++++---- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/flowview_databases.php b/flowview_databases.php index 14ad0a96..2c1c4ce0 100644 --- a/flowview_databases.php +++ b/flowview_databases.php @@ -79,7 +79,14 @@ function flowview_get_item_details(): bool { $sql_params = []; if (cacti_sizeof($ids) && flowview_db_table_exists($table)) { + // the keys are column names, which can not be bound, so only columns of the table are accepted + $columns = flowview_db_get_table_column_types($table); + foreach($ids as $col => $value) { + if (!isset($columns[$col])) { + return false; + } + $sql_where .= ($sql_where != '' ? ' AND ':'WHERE ') . "$col = ?"; $sql_params[] = $value; } diff --git a/flowview_filters.php b/flowview_filters.php index d74d397b..52970f04 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 lastsent)"); + AND (? - sendinterval > lastsent)", + $sql_params); $php = read_config_option('path_php_binary'); From 532ed974464b0ecd4ad130750ed865d8810112d1 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Wed, 2 Dec 2026 18:57:01 -0800 Subject: [PATCH 2/7] fix: escape registry, DNS cache and Filter values in HTML The Databases page printed registry, DNS cache and ARIN values, and the source options of its filters, without escaping. The Filters page did the same with the listener name in the list and the Filter names in the action confirmation. Escape them with html_escape(). Signed-off-by: Thomas Vincent --- flowview_databases.php | 18 +++++++++--------- flowview_filters.php | 6 +++--- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/flowview_databases.php b/flowview_databases.php index 2c1c4ce0..20464253 100644 --- a/flowview_databases.php +++ b/flowview_databases.php @@ -965,7 +965,7 @@ function view_db_table($tab, &$tabs): void { if (cacti_sizeof($sources) > 0) { foreach ($sources as $key => $value) { - print "'; + print "'; } } ?> @@ -1147,9 +1147,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); } } } @@ -1346,7 +1346,7 @@ function view_dns_cache(): void { if (cacti_sizeof($sources) > 0) { foreach ($sources as $key => $value) { - print "'; + print "'; } } ?> @@ -1533,10 +1533,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(); @@ -1651,7 +1651,7 @@ function view_routes($tab): void { if (cacti_sizeof($sources)) { foreach ($sources as $key => $value) { - print "'; + print "'; } } ?> @@ -1908,7 +1908,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 52970f04..92853b17 100644 --- a/flowview_filters.php +++ b/flowview_filters.php @@ -180,8 +180,8 @@ function actions_filters(): void { input_validate_input_number($matches[1]); /* ==================================================== */ - $filter_list .= '
  • ' . flowview_db_fetch_cell_prepared('SELECT name FROM plugin_flowview_queries - WHERE id = ?', [$matches[1]]) . '
  • '; + $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) { From eef967f4b12b9452abd11818ebf495433f728250 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Wed, 2 Dec 2026 18:57:02 -0800 Subject: [PATCH 3/7] fix: escape the whois arguments of the bulk ARIN loader flowview_bulkarin.php passed the whois path, provider and CIDR to the shell unescaped. Escape them with cacti_escapeshellcmd() and cacti_escapeshellarg(), as core does for external commands. Signed-off-by: Thomas Vincent --- flowview_bulkarin.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flowview_bulkarin.php b/flowview_bulkarin.php index a473f563..da7f8dbd 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); From 1ba7b7aa764056cf90834ee9639f271963f1dd30 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Wed, 2 Dec 2026 18:57:02 -0800 Subject: [PATCH 4/7] fix: write the legacy version setting through set_config_option() The upgrade script wrote plugin_flowview_version straight into the settings table. set_config_option() performs the same REPLACE and keeps Cacti's settings handling in one place. Signed-off-by: Thomas Vincent --- flowview_upgrade.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/flowview_upgrade.php b/flowview_upgrade.php index 8ea5e8e7..c987186f 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'); } From a9a2e73ac7ce7c315cc29bd55e4fdb45bd79f815 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Wed, 2 Dec 2026 18:57:03 -0800 Subject: [PATCH 5/7] test: cover the Databases, Filters and CLI fixes A unit test runs flowview_get_item_details() against the unit doubles and checks that only table columns reach the query. End-to-end tests log in to a served Cacti and check the details lookup, its realm check, the escaped Databases and Filters output and Filter deletion, and run the bulk ARIN loader and the poller as subprocesses. The end-to-end tests skip unless FLOWVIEW_E2E_* is set. Signed-off-by: Thomas Vincent --- tests/Integration/FlowviewHttpTest.php | 557 ++++++++++++++++++++++ tests/Unit/DatabaseDetailsColumnsTest.php | 179 +++++++ 2 files changed, 736 insertions(+) create mode 100644 tests/Integration/FlowviewHttpTest.php create mode 100644 tests/Unit/DatabaseDetailsColumnsTest.php diff --git a/tests/Integration/FlowviewHttpTest.php b/tests/Integration/FlowviewHttpTest.php new file mode 100644 index 00000000..8b40b298 --- /dev/null +++ b/tests/Integration/FlowviewHttpTest.php @@ -0,0 +1,557 @@ + (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 = ''; + + foreach ($http_response_header ?? [] 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 00000000..4ab446ba --- /dev/null +++ b/tests/Unit/DatabaseDetailsColumnsTest.php @@ -0,0 +1,179 @@ + value + * + * @return array{result: bool, output: string} + */ +function flowview_test_item_details(array $ids): 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'); + + /* includes/arrays.php reads three lists, then SHOW COLUMNS is read */ + plugin_test_queue_db_result('db_fetch_assoc', []); + plugin_test_queue_db_result('db_fetch_assoc', []); + plugin_test_queue_db_result('db_fetch_assoc', []); + 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', ['aut_num' => 'AS64500', 'source' => 'TEST', 'descr' => 'Example network']); + + ob_start(); + $result = flowview_get_item_details(); + $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([]); +}); From 2e1026a8f2b9f625eb254a4661d4854943d43d24 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Wed, 2 Dec 2026 18:57:03 -0800 Subject: [PATCH 6/7] ci: serve Cacti and run the end-to-end tests Serve the installed Cacti with PHP's built-in server and run tests/Integration after the unit tests, with the database and host settings in FLOWVIEW_E2E_*. Signed-off-by: Thomas Vincent --- .github/workflows/plugin-ci-workflow.yml | 40 ++++++++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml index 31ee8dff..f33be465 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,40 @@ 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 + 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 -s -o /dev/null --max-time 2 "$FLOWVIEW_E2E_SCHEME://$FLOWVIEW_E2E_HOST/index.php"; 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. From b5f7bd31ebf0fd4584119ff9238084a37575e419 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 3 Dec 2026 01:38:03 -0800 Subject: [PATCH 7/7] ci: run FlowView integration checks against a writable fixture Signed-off-by: Thomas Vincent --- .github/workflows/plugin-ci-workflow.yml | 6 +- flowview_databases.php | 129 +----------------- includes/database_details.php | 153 ++++++++++++++++++++++ locales/po/cacti.pot | 6 +- phpunit.xml | 1 + tests/Integration/FlowviewHttpTest.php | 3 +- tests/Unit/DatabaseDetailsColumnsTest.php | 102 +++------------ 7 files changed, 184 insertions(+), 216 deletions(-) create mode 100644 includes/database_details.php diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml index f33be465..45c20902 100644 --- a/.github/workflows/plugin-ci-workflow.yml +++ b/.github/workflows/plugin-ci-workflow.yml @@ -218,11 +218,15 @@ jobs: 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 -s -o /dev/null --max-time 2 "$FLOWVIEW_E2E_SCHEME://$FLOWVIEW_E2E_HOST/index.php"; then + 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 diff --git a/flowview_databases.php b/flowview_databases.php index 20464253..8e3543fc 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,133 +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)) { - // the keys are column names, which can not be bound, so only columns of the table are accepted - $columns = flowview_db_get_table_column_types($table); - - foreach($ids as $col => $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]; + return flowview_render_item_details(get_all_columns()); } /** diff --git a/includes/database_details.php b/includes/database_details.php new file mode 100644 index 00000000..7a259439 --- /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 6ffcacde..86602fd0 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 ca15b0c5..e2a49f2a 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 index 8b40b298..f7548a86 100644 --- a/tests/Integration/FlowviewHttpTest.php +++ b/tests/Integration/FlowviewHttpTest.php @@ -112,7 +112,8 @@ public function request(string $method, string $path, array $fields = []): array $status = 0; $location = ''; - foreach ($http_response_header ?? [] as $line) { + $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) { diff --git a/tests/Unit/DatabaseDetailsColumnsTest.php b/tests/Unit/DatabaseDetailsColumnsTest.php index 4ab446ba..61f589a6 100644 --- a/tests/Unit/DatabaseDetailsColumnsTest.php +++ b/tests/Unit/DatabaseDetailsColumnsTest.php @@ -16,87 +16,11 @@ exit; } -/* - * flowview_get_item_details() in flowview_databases.php builds its WHERE - * clause from the keys of the row id that the Databases page sends back. The - * keys are column names, which can not be bound, so only the columns of the - * table are accepted. - * - * flowview_databases.php is a web entry point that includes auth.php when it - * is loaded, so the functions under test are read out of the file and defined - * on their own, against the Cacti doubles of the unit bootstrap. - */ - -/** - * Defines the named functions of a plugin source file without running the - * rest of the file. - * - * @param string $relative_file The file, relative to the plugin directory - * @param string[] $names The functions to define - * - * @return void - */ -function flowview_test_define_functions(string $relative_file, array $names): void { - $tokens = token_get_all(plugin_test_read_source($relative_file)); - $count = count($tokens); - - for ($i = 0; $i < $count; $i++) { - if (!is_array($tokens[$i]) || $tokens[$i][0] !== T_FUNCTION) { - continue; - } - - $j = $i + 1; - - while ($j < $count && is_array($tokens[$j]) && $tokens[$j][0] === T_WHITESPACE) { - $j++; - } - - if (!is_array($tokens[$j]) || $tokens[$j][0] !== T_STRING || !in_array($tokens[$j][1], $names, true) || function_exists($tokens[$j][1])) { - continue; - } - - $code = ''; - $depth = 0; - $open = false; - - for ($k = $i; $k < $count; $k++) { - $text = is_array($tokens[$k]) ? $tokens[$k][1] : $tokens[$k]; - $code .= $text; - - if ($text === '{' || (is_array($tokens[$k]) && in_array($tokens[$k][0], [T_CURLY_OPEN, T_DOLLAR_OPEN_CURLY_BRACES], true))) { - $depth++; - $open = true; - } elseif ($text === '}') { - $depth--; - - if ($open && $depth === 0) { - break; - } - } - } - - /* the code is the plugin's own source, read from the repository */ - eval($code); - } -} +require_once dirname(__DIR__, 2) . '/includes/database_details.php'; beforeAll(function () { if (!function_exists('html_start_box')) { function html_start_box(...$args) {} } if (!function_exists('html_end_box')) { function html_end_box(...$args) {} } - - if (!function_exists('array_rekey')) { - function array_rekey($array, $key, $value) { - $ret = []; - - foreach ((array) $array as $item) { - $ret[$item[$key]] = is_array($value) ? array_intersect_key($item, array_flip($value)) : $item[$value]; - } - - return $ret; - } - } - - flowview_test_define_functions('flowview_databases.php', ['flowview_get_item_details', 'flowview_print_details', 'get_all_columns']); }); beforeEach(function () { @@ -110,27 +34,23 @@ function array_rekey($array, $key, $value) { * * @return array{result: bool, output: string} */ -function flowview_test_item_details(array $ids): array { +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'); - /* includes/arrays.php reads three lists, then SHOW COLUMNS is read */ - plugin_test_queue_db_result('db_fetch_assoc', []); - plugin_test_queue_db_result('db_fetch_assoc', []); - plugin_test_queue_db_result('db_fetch_assoc', []); 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', ['aut_num' => 'AS64500', 'source' => 'TEST', 'descr' => 'Example network']); + plugin_test_queue_db_result('db_fetch_row_prepared', $row ?? ['aut_num' => 'AS64500', 'source' => 'TEST', 'descr' => 'Example network']); ob_start(); - $result = flowview_get_item_details(); + $result = flowview_render_item_details(['descr' => ['display' => 'Description']]); $output = (string) ob_get_clean(); return ['result' => $result, 'output' => $output]; @@ -177,3 +97,17 @@ function flowview_test_row_reads(): array { 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'); +});