From 8097d844847dfc7b9a396b22cee9cae7106ed29a Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 19 Nov 2026 20:24:31 -0800 Subject: [PATCH 1/6] fix: count only enabled devices when the user hides disabled devices get_allowed_devices() drops disabled devices while the user's Hide Disabled setting is on (the default), but deviceCount() counted them, so an unrestricted admin was refused on any site with a disabled device. Signed-off-by: Thomas Vincent --- lib/ConfigRepository.php | 10 ++-- setup.php | 6 ++- tests/Unit/DeviceVisibilityTest.php | 72 +++++++++++++++++++++++++++++ tests/bootstrap-unit.php | 9 ++++ 4 files changed, 92 insertions(+), 5 deletions(-) create mode 100644 tests/Unit/DeviceVisibilityTest.php diff --git a/lib/ConfigRepository.php b/lib/ConfigRepository.php index 0d319fc..8dd3bda 100644 --- a/lib/ConfigRepository.php +++ b/lib/ConfigRepository.php @@ -55,10 +55,14 @@ public function state(array $mappings = []): ConfigState { /** * Devices Cacti lists, which is what get_allowed_devices() returns for a - * user with unrestricted device access. + * user with unrestricted device access. That function leaves disabled + * devices out when the user's Hide Disabled setting is on, so $enabledOnly + * must follow that setting or the two counts differ. */ - public function deviceCount(): int { - return (int) db_fetch_cell_prepared("SELECT COUNT(*) FROM host WHERE id > 0 AND deleted = ''", [], '', true, $this->connection); + public function deviceCount(bool $enabledOnly = false): int { + $disabled = $enabledOnly ? " AND (disabled = '' OR disabled IS NULL)" : ''; + + return (int) db_fetch_cell_prepared("SELECT COUNT(*) FROM host WHERE id > 0 AND deleted = ''" . $disabled, [], '', true, $this->connection); } /** diff --git a/setup.php b/setup.php index f2c2aa2..fe2b93a 100644 --- a/setup.php +++ b/setup.php @@ -402,12 +402,14 @@ function smokeping_config_service(bool $webUser = false): \Somethingwithproof\Sm /** * Whether the user's device permissions cover every device: only when * get_allowed_devices() returns every device Cacti lists. A user limited to - * some devices, however many, is not unrestricted. + * some devices, however many, is not unrestricted. Cacti drops disabled + * devices from that list when the user's Hide Disabled setting (on by + * default) is on, so the count drops them too. */ function smokeping_user_sees_every_device(\Somethingwithproof\Smokeping\ConfigRepository $repository): bool { $allowed = get_allowed_devices(); - return is_array($allowed) && count($allowed) === $repository->deviceCount(); + return is_array($allowed) && count($allowed) === $repository->deviceCount(read_user_setting('hide_disabled') == 'on'); } /** diff --git a/tests/Unit/DeviceVisibilityTest.php b/tests/Unit/DeviceVisibilityTest.php new file mode 100644 index 0000000..3261141 --- /dev/null +++ b/tests/Unit/DeviceVisibilityTest.php @@ -0,0 +1,72 @@ + + * SPDX-License-Identifier: GPL-2.0-or-later + * + * This file is part of plugin_smokeping, a plugin for Cacti. + * https://github.com/somethingwithproof/plugin_smokeping + * + * This program is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License as published by the Free + * Software Foundation; either version 2 of the License, or (at your option) + * any later version. + * + * This program is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + */ + +require_once __DIR__ . '/../Support/OperatorStubs.php'; + +// Cacti's get_allowed_devices() leaves disabled devices out while the user's +// hide_disabled setting is on, which is its default. The fake host table has +// two enabled devices and one disabled device. +function smokeping_fake_host_table(): void { + $GLOBALS['__smokeping_db_cell'] = fn (string $sql, array $params) => str_contains($sql, 'disabled') ? 2 : 3; +} + +function smokeping_sees_every_device(): bool { + return smokeping_user_sees_every_device(new Somethingwithproof\Smokeping\ConfigRepository(false, '/var/www/cacti/rra')); +} + +afterEach(function () { + $GLOBALS['__smokeping_user_settings'] = []; + $GLOBALS['__smokeping_db_cell'] = 0; + $GLOBALS['__operator_devices'] = []; +}); + +it('treats an unrestricted user with Hide Disabled on as seeing every device', function () { + smokeping_fake_host_table(); + $GLOBALS['__smokeping_user_settings']['hide_disabled'] = 'on'; + $GLOBALS['__operator_devices'] = [['id' => '1'], ['id' => '2']]; + + expect(smokeping_sees_every_device())->toBeTrue(); +}); + +it('treats an unrestricted user with Hide Disabled off as seeing every device', function () { + smokeping_fake_host_table(); + $GLOBALS['__smokeping_user_settings']['hide_disabled'] = ''; + $GLOBALS['__operator_devices'] = [['id' => '1'], ['id' => '2'], ['id' => '3']]; + + expect(smokeping_sees_every_device())->toBeTrue(); +}); + +it('refuses a user limited to some devices whatever Hide Disabled says', function (string $hideDisabled, array $devices) { + smokeping_fake_host_table(); + $GLOBALS['__smokeping_user_settings']['hide_disabled'] = $hideDisabled; + $GLOBALS['__operator_devices'] = $devices; + + expect(smokeping_sees_every_device())->toBeFalse(); +})->with([ + 'on' => ['on', [['id' => '1']]], + 'off' => ['', [['id' => '1'], ['id' => '2']]], +]); + +it('counts disabled devices only when asked to leave them out', function () { + smokeping_fake_host_table(); + $repository = new Somethingwithproof\Smokeping\ConfigRepository(false, '/var/www/cacti/rra'); + + expect($repository->deviceCount())->toBe(3) + ->and($repository->deviceCount(true))->toBe(2); +}); diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php index 4e7d567..5b460ad 100644 --- a/tests/bootstrap-unit.php +++ b/tests/bootstrap-unit.php @@ -72,6 +72,15 @@ function read_config_option($config_name, $force = false) { } } +// A per-user Cacti setting, as read_user_setting() returns it. +$GLOBALS['__smokeping_user_settings'] = []; + +if (!function_exists('read_user_setting')) { + function read_user_setting($config_name, $default = false, $force = false, $user = 0) { + return $GLOBALS['__smokeping_user_settings'][$config_name] ?? $default; + } +} + // The purge sweep reads the purge queue; unit tests have no database. A test // fills $GLOBALS['__smokeping_purge_queue'] with queue rows and reads the // statements the code ran from $GLOBALS['__smokeping_db_exec']. From 854e874eb109ca215b3ce30ab24de0609580f828 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 19 Nov 2026 20:27:12 -0800 Subject: [PATCH 2/6] fix: compare device id sets with Hide Disabled off Counting enabled devices only would treat a user denied just a disabled device as unrestricted. Read the allowed ids with the session's Hide Disabled turned off for the call, and compare them with every non-deleted host id. Signed-off-by: Thomas Vincent --- lib/ConfigRepository.php | 16 ++++--- setup.php | 36 +++++++++++++--- tests/Support/OperatorStubs.php | 5 ++- tests/Unit/DeviceVisibilityTest.php | 67 ++++++++++++++++++----------- tests/bootstrap-unit.php | 9 ---- 5 files changed, 84 insertions(+), 49 deletions(-) diff --git a/lib/ConfigRepository.php b/lib/ConfigRepository.php index 8dd3bda..7efce1d 100644 --- a/lib/ConfigRepository.php +++ b/lib/ConfigRepository.php @@ -54,15 +54,17 @@ public function state(array $mappings = []): ConfigState { } /** - * Devices Cacti lists, which is what get_allowed_devices() returns for a - * user with unrestricted device access. That function leaves disabled - * devices out when the user's Hide Disabled setting is on, so $enabledOnly - * must follow that setting or the two counts differ. + * Ids of every device Cacti lists, disabled ones included. These are the + * devices get_allowed_devices() returns for a user with unrestricted + * device access when Hide Disabled is off. + * + * @return list */ - public function deviceCount(bool $enabledOnly = false): int { - $disabled = $enabledOnly ? " AND (disabled = '' OR disabled IS NULL)" : ''; + public function deviceIds(): array { + $ids = array_map(static fn (array $row): int => (int) $row['id'], Row::rows(db_fetch_assoc_prepared("SELECT id FROM host WHERE id > 0 AND deleted = ''", [], true, $this->connection))); + sort($ids); - return (int) db_fetch_cell_prepared("SELECT COUNT(*) FROM host WHERE id > 0 AND deleted = ''" . $disabled, [], '', true, $this->connection); + return $ids; } /** diff --git a/setup.php b/setup.php index fe2b93a..045db36 100644 --- a/setup.php +++ b/setup.php @@ -401,15 +401,39 @@ function smokeping_config_service(bool $webUser = false): \Somethingwithproof\Sm /** * Whether the user's device permissions cover every device: only when - * get_allowed_devices() returns every device Cacti lists. A user limited to - * some devices, however many, is not unrestricted. Cacti drops disabled - * devices from that list when the user's Hide Disabled setting (on by - * default) is on, so the count drops them too. + * get_allowed_devices() returns the id of every device Cacti lists. A user + * limited to some devices, however many, is not unrestricted. + * + * get_allowed_devices() drops disabled devices while the user's Hide Disabled + * display setting is on (the default), which would hide a permission denied on + * a disabled device. It reads that setting from the session's cached user + * settings, so the check turns it off for the one call and restores it. */ function smokeping_user_sees_every_device(\Somethingwithproof\Smokeping\ConfigRepository $repository): bool { - $allowed = get_allowed_devices(); + $hadSettings = isset($_SESSION['sess_user_config_array']); + $saved = $hadSettings ? $_SESSION['sess_user_config_array'] : null; + + $_SESSION['sess_user_config_array'] = $hadSettings ? $saved : []; + $_SESSION['sess_user_config_array']['hide_disabled'] = ''; + + try { + $allowed = get_allowed_devices(); + } finally { + if ($hadSettings) { + $_SESSION['sess_user_config_array'] = $saved; + } else { + unset($_SESSION['sess_user_config_array']); + } + } + + if (!is_array($allowed)) { + return false; + } + + $ids = array_map(static fn (array $device): int => (int) $device['id'], $allowed); + sort($ids); - return is_array($allowed) && count($allowed) === $repository->deviceCount(read_user_setting('hide_disabled') == 'on'); + return $ids === $repository->deviceIds(); } /** diff --git a/tests/Support/OperatorStubs.php b/tests/Support/OperatorStubs.php index 955015e..33ecbdc 100644 --- a/tests/Support/OperatorStubs.php +++ b/tests/Support/OperatorStubs.php @@ -41,7 +41,10 @@ function api_plugin_user_realm_auth($filename = '') { } function get_allowed_devices($sql_where = '', $sql_order = 'description', $sql_limit = '', &$total_rows = 0, $user_id = 0, $device_id = 0) { - return $GLOBALS['__operator_devices'] ?? []; + $devices = $GLOBALS['__operator_devices'] ?? []; + + // A closure stands in for Cacti's own filtering, such as Hide Disabled. + return $devices instanceof Closure ? $devices() : $devices; } function form_start($action, $id = '', $multipart = false) { diff --git a/tests/Unit/DeviceVisibilityTest.php b/tests/Unit/DeviceVisibilityTest.php index 3261141..bf5d7ca 100644 --- a/tests/Unit/DeviceVisibilityTest.php +++ b/tests/Unit/DeviceVisibilityTest.php @@ -20,53 +20,68 @@ require_once __DIR__ . '/../Support/OperatorStubs.php'; // Cacti's get_allowed_devices() leaves disabled devices out while the user's -// hide_disabled setting is on, which is its default. The fake host table has -// two enabled devices and one disabled device. -function smokeping_fake_host_table(): void { - $GLOBALS['__smokeping_db_cell'] = fn (string $sql, array $params) => str_contains($sql, 'disabled') ? 2 : 3; +// hide_disabled setting is on, which is its default, and reads the setting +// from the session. Devices 1 and 2 are enabled; device 3 is disabled. +function smokeping_stub_devices(array $permitted): void { + $GLOBALS['__smokeping_db_assoc'] = [['id' => '1'], ['id' => '2'], ['id' => '3']]; + $GLOBALS['__operator_devices'] = function () use ($permitted): array { + $hide = ($_SESSION['sess_user_config_array']['hide_disabled'] ?? 'on') === 'on'; + + return array_map(fn (int $id) => ['id' => (string) $id], array_values(array_filter($permitted, fn (int $id) => !($hide && $id === 3)))); + }; } function smokeping_sees_every_device(): bool { return smokeping_user_sees_every_device(new Somethingwithproof\Smokeping\ConfigRepository(false, '/var/www/cacti/rra')); } +beforeEach(function () { + $_SESSION = ['sess_user_id' => 2]; +}); + afterEach(function () { - $GLOBALS['__smokeping_user_settings'] = []; - $GLOBALS['__smokeping_db_cell'] = 0; - $GLOBALS['__operator_devices'] = []; + $_SESSION = []; + $GLOBALS['__smokeping_db_assoc'] = []; + $GLOBALS['__operator_devices'] = []; }); it('treats an unrestricted user with Hide Disabled on as seeing every device', function () { - smokeping_fake_host_table(); - $GLOBALS['__smokeping_user_settings']['hide_disabled'] = 'on'; - $GLOBALS['__operator_devices'] = [['id' => '1'], ['id' => '2']]; + smokeping_stub_devices([1, 2, 3]); + $_SESSION['sess_user_config_array'] = ['hide_disabled' => 'on']; expect(smokeping_sees_every_device())->toBeTrue(); }); it('treats an unrestricted user with Hide Disabled off as seeing every device', function () { - smokeping_fake_host_table(); - $GLOBALS['__smokeping_user_settings']['hide_disabled'] = ''; - $GLOBALS['__operator_devices'] = [['id' => '1'], ['id' => '2'], ['id' => '3']]; + smokeping_stub_devices([1, 2, 3]); + $_SESSION['sess_user_config_array'] = ['hide_disabled' => '']; expect(smokeping_sees_every_device())->toBeTrue(); }); -it('refuses a user limited to some devices whatever Hide Disabled says', function (string $hideDisabled, array $devices) { - smokeping_fake_host_table(); - $GLOBALS['__smokeping_user_settings']['hide_disabled'] = $hideDisabled; - $GLOBALS['__operator_devices'] = $devices; +it('refuses a user denied only a disabled device, whatever Hide Disabled says', function (string $hideDisabled) { + smokeping_stub_devices([1, 2]); + $_SESSION['sess_user_config_array'] = ['hide_disabled' => $hideDisabled]; expect(smokeping_sees_every_device())->toBeFalse(); -})->with([ - 'on' => ['on', [['id' => '1']]], - 'off' => ['', [['id' => '1'], ['id' => '2']]], -]); +})->with(['on', '']); + +it('refuses a user limited to some enabled devices', function () { + smokeping_stub_devices([1, 3]); + $_SESSION['sess_user_config_array'] = ['hide_disabled' => 'on']; + + expect(smokeping_sees_every_device())->toBeFalse(); +}); + +it('restores the session settings after the check', function () { + smokeping_stub_devices([1, 2, 3]); + $_SESSION['sess_user_config_array'] = ['hide_disabled' => 'on', 'other' => 'x']; + smokeping_sees_every_device(); + + expect($_SESSION['sess_user_config_array'])->toBe(['hide_disabled' => 'on', 'other' => 'x']); -it('counts disabled devices only when asked to leave them out', function () { - smokeping_fake_host_table(); - $repository = new Somethingwithproof\Smokeping\ConfigRepository(false, '/var/www/cacti/rra'); + unset($_SESSION['sess_user_config_array']); + smokeping_sees_every_device(); - expect($repository->deviceCount())->toBe(3) - ->and($repository->deviceCount(true))->toBe(2); + expect($_SESSION)->not->toHaveKey('sess_user_config_array'); }); diff --git a/tests/bootstrap-unit.php b/tests/bootstrap-unit.php index 5b460ad..4e7d567 100644 --- a/tests/bootstrap-unit.php +++ b/tests/bootstrap-unit.php @@ -72,15 +72,6 @@ function read_config_option($config_name, $force = false) { } } -// A per-user Cacti setting, as read_user_setting() returns it. -$GLOBALS['__smokeping_user_settings'] = []; - -if (!function_exists('read_user_setting')) { - function read_user_setting($config_name, $default = false, $force = false, $user = 0) { - return $GLOBALS['__smokeping_user_settings'][$config_name] ?? $default; - } -} - // The purge sweep reads the purge queue; unit tests have no database. A test // fills $GLOBALS['__smokeping_purge_queue'] with queue rows and reads the // statements the code ran from $GLOBALS['__smokeping_db_exec']. From 54bc582e07a1fdc8d9825908450e903818a408cd Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 19 Nov 2026 20:35:28 -0800 Subject: [PATCH 3/6] fix: satisfy PHPStan level 9 in the device visibility check Signed-off-by: Thomas Vincent --- setup.php | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/setup.php b/setup.php index 045db36..f7239f5 100644 --- a/setup.php +++ b/setup.php @@ -412,9 +412,10 @@ function smokeping_config_service(bool $webUser = false): \Somethingwithproof\Sm function smokeping_user_sees_every_device(\Somethingwithproof\Smokeping\ConfigRepository $repository): bool { $hadSettings = isset($_SESSION['sess_user_config_array']); $saved = $hadSettings ? $_SESSION['sess_user_config_array'] : null; + $override = is_array($saved) ? $saved : []; - $_SESSION['sess_user_config_array'] = $hadSettings ? $saved : []; - $_SESSION['sess_user_config_array']['hide_disabled'] = ''; + $override['hide_disabled'] = ''; + $_SESSION['sess_user_config_array'] = $override; try { $allowed = get_allowed_devices(); @@ -430,7 +431,7 @@ function smokeping_user_sees_every_device(\Somethingwithproof\Smokeping\ConfigRe return false; } - $ids = array_map(static fn (array $device): int => (int) $device['id'], $allowed); + $ids = array_map(static fn (mixed $device): int => is_array($device) ? (int) ($device['id'] ?? 0) : 0, $allowed); sort($ids); return $ids === $repository->deviceIds(); From a6a3d9e813a0e80b37bbfa900636abc9bea204e5 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 19 Nov 2026 20:42:52 -0800 Subject: [PATCH 4/6] fix: avoid casting mixed in the device visibility check Signed-off-by: Thomas Vincent --- setup.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/setup.php b/setup.php index f7239f5..e1956b1 100644 --- a/setup.php +++ b/setup.php @@ -431,7 +431,7 @@ function smokeping_user_sees_every_device(\Somethingwithproof\Smokeping\ConfigRe return false; } - $ids = array_map(static fn (mixed $device): int => is_array($device) ? (int) ($device['id'] ?? 0) : 0, $allowed); + $ids = array_map(static fn (mixed $device): int => is_array($device) && isset($device['id']) && is_numeric($device['id']) ? (int) $device['id'] : 0, $allowed); sort($ids); return $ids === $repository->deviceIds(); From 96f30bca1a1eae71058a53821950f7c729e75f36 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 19 Nov 2026 22:44:59 -0800 Subject: [PATCH 5/6] fix: work out allowed devices without the Hide Disabled filter get_allowed_devices() reads hide_disabled for the session user from settings_user, not from the session, so forcing it off in sess_user_config_array had no effect when authentication is on. An administrator with the default setting was still refused export and import while any device was disabled. Build the allowed device set from Cacti's own helpers instead (get_simple_device_perms, get_policies, get_policy_where) with the joins of get_allowed_devices() and no disabled filter, and compare it with every non-deleted host id. Anything unexpected, such as a missing helper, an unknown user, an unknown permission method, a failed query or a malformed row, counts as restricted. The unit model now reads Hide Disabled the way Cacti does, and the permissions end-to-end suite covers an administrator with a disabled device and a user denied only that device. Signed-off-by: Thomas Vincent --- lib/ConfigRepository.php | 44 +++++++- setup.php | 106 +++++++++++++----- tests/Unit/DeviceVisibilityTest.php | 160 +++++++++++++++++++++++----- tests/bin/permission-setup.php | 3 + tests/permissions-e2e.sh | 39 ++++++- 5 files changed, 293 insertions(+), 59 deletions(-) diff --git a/lib/ConfigRepository.php b/lib/ConfigRepository.php index 7efce1d..9e20166 100644 --- a/lib/ConfigRepository.php +++ b/lib/ConfigRepository.php @@ -53,10 +53,50 @@ public function state(array $mappings = []): ConfigState { return new ConfigState($effective, $this->targets(), $this->mappingRows(), $this->pollers(), $this->devices($mappings), Settings::defaultMountPath($this->rraPath)); } + /** + * Sorted ids of the devices a device permission condition allows, or null + * when the query fails or a row has no numeric id. $sqlWhere is the WHERE + * clause smokeping_allowed_device_ids() builds with Cacti's + * get_policy_where(); the joins are those of get_allowed_devices() in + * Cacti 1.2.31 and 1.2.x lib/auth.php, which the condition refers to. + * The clause is SQL and is never built from request input. + * + * @return list|null + */ + public function allowedDeviceIds(string $sqlWhere): ?array { + $rows = db_fetch_assoc_prepared("SELECT DISTINCT h.id + FROM host AS h + LEFT JOIN graph_local AS gl + ON h.id = gl.host_id + LEFT JOIN graph_templates AS gt + ON gt.id = gl.graph_template_id + LEFT JOIN host_template AS ht + ON h.host_template_id = ht.id + $sqlWhere", [], true, $this->connection); + + if (!is_array($rows)) { + return null; + } + + $ids = []; + + foreach ($rows as $row) { + if (!is_array($row) || !is_numeric($row['id'] ?? null)) { + return null; + } + + $ids[] = (int) $row['id']; + } + + sort($ids); + + return $ids; + } + /** * Ids of every device Cacti lists, disabled ones included. These are the - * devices get_allowed_devices() returns for a user with unrestricted - * device access when Hide Disabled is off. + * devices smokeping_allowed_device_ids() returns for a user with + * unrestricted device access. * * @return list */ diff --git a/setup.php b/setup.php index e1956b1..abbdf83 100644 --- a/setup.php +++ b/setup.php @@ -400,41 +400,95 @@ function smokeping_config_service(bool $webUser = false): \Somethingwithproof\Sm } /** - * Whether the user's device permissions cover every device: only when - * get_allowed_devices() returns the id of every device Cacti lists. A user - * limited to some devices, however many, is not unrestricted. + * Whether the user's device permissions cover every device: only when the + * devices they allow, disabled ones included, are exactly the devices Cacti + * lists. A user limited to some devices, however many, is not unrestricted, + * and any doubt about the allowed set counts as limited. + */ +function smokeping_user_sees_every_device(\Somethingwithproof\Smokeping\ConfigRepository $repository): bool { + $allowed = smokeping_allowed_device_ids($repository); + + return $allowed !== null && $allowed === $repository->deviceIds(); +} + +/** + * Sorted ids of the devices the logged-in user's permissions allow, disabled + * devices included, or null when they cannot be worked out. * + * This is Cacti's get_allowed_devices() without its Hide Disabled filter. * get_allowed_devices() drops disabled devices while the user's Hide Disabled - * display setting is on (the default), which would hide a permission denied on - * a disabled device. It reads that setting from the session's cached user - * settings, so the check turns it off for the one call and restores it. + * setting is on, the default, and reads that setting for the session user + * from settings_user (read_user_setting() with $user > 0 never consults the + * session), so it cannot be turned off for one call. The query is rebuilt + * from Cacti's own permission helpers instead. It mirrors get_allowed_devices() + * in lib/auth.php (Cacti 1.2.31 lines 2768-2870; the 1.2.x branch, as of + * this change, lines 2810-2912): the user from the session when + * auth_method > 0, get_simple_device_perms(), get_policy_where() over + * get_policies() unless the permissions are simple or authentication is off, + * and the same host, graph_local, graph_templates and host_template joins + * (ConfigRepository::allowedDeviceIds()). The helpers are called, not copied; + * review this function and that query when get_allowed_devices() changes. + * + * It refuses where Cacti would not: a missing helper, a session user that + * does not exist, a graph permission method other than 1-4 (for which + * get_policy_where() adds no condition), a policy row of the wrong shape, a + * failed query, or a non-numeric id gives null. + * + * @return list|null */ -function smokeping_user_sees_every_device(\Somethingwithproof\Smokeping\ConfigRepository $repository): bool { - $hadSettings = isset($_SESSION['sess_user_config_array']); - $saved = $hadSettings ? $_SESSION['sess_user_config_array'] : null; - $override = is_array($saved) ? $saved : []; - - $override['hide_disabled'] = ''; - $_SESSION['sess_user_config_array'] = $override; - - try { - $allowed = get_allowed_devices(); - } finally { - if ($hadSettings) { - $_SESSION['sess_user_config_array'] = $saved; - } else { - unset($_SESSION['sess_user_config_array']); +function smokeping_allowed_device_ids(\Somethingwithproof\Smokeping\ConfigRepository $repository): ?array { + foreach (['read_config_option', 'auth_valid_user', 'get_simple_device_perms', 'get_policies', 'get_policy_where'] as $helper) { + if (!function_exists($helper)) { + return null; } } - if (!is_array($allowed)) { - return false; + $authMethod = read_config_option('auth_method'); + + if (!is_numeric($authMethod)) { + return null; } - $ids = array_map(static fn (mixed $device): int => is_array($device) && isset($device['id']) && is_numeric($device['id']) ? (int) $device['id'] : 0, $allowed); - sort($ids); + $sqlWhere = "WHERE ((h.id > 0 AND h.deleted = '') OR h.id IS NULL)"; + + if ((int) $authMethod > 0) { + $userId = $_SESSION['sess_user_id'] ?? null; + + if (!is_numeric($userId) || (int) $userId <= 0 || !auth_valid_user((int) $userId)) { + return null; + } + + $userId = (int) $userId; + + if (!get_simple_device_perms($userId)) { + $graphAuthMethod = read_config_option('graph_auth_method'); + $policies = get_policies($userId); + + if (!is_numeric($graphAuthMethod) || !in_array((int) $graphAuthMethod, [1, 2, 3, 4], true) || !is_array($policies) || $policies === []) { + return null; + } + + foreach ($policies as $policy) { + if (!is_array($policy) || !is_numeric($policy['id'] ?? null) || !isset($policy['type'])) { + return null; + } + + foreach (['policy_graphs', 'policy_hosts', 'policy_graph_templates'] as $column) { + if (!array_key_exists($column, $policy)) { + return null; + } + } + } + + $sqlWhere = get_policy_where((int) $graphAuthMethod, $policies, $sqlWhere); + + if (!is_string($sqlWhere)) { + return null; + } + } + } - return $ids === $repository->deviceIds(); + return $repository->allowedDeviceIds($sqlWhere); } /** diff --git a/tests/Unit/DeviceVisibilityTest.php b/tests/Unit/DeviceVisibilityTest.php index bf5d7ca..509ca39 100644 --- a/tests/Unit/DeviceVisibilityTest.php +++ b/tests/Unit/DeviceVisibilityTest.php @@ -19,16 +19,89 @@ require_once __DIR__ . '/../Support/OperatorStubs.php'; -// Cacti's get_allowed_devices() leaves disabled devices out while the user's -// hide_disabled setting is on, which is its default, and reads the setting -// from the session. Devices 1 and 2 are enabled; device 3 is disabled. -function smokeping_stub_devices(array $permitted): void { - $GLOBALS['__smokeping_db_assoc'] = [['id' => '1'], ['id' => '2'], ['id' => '3']]; - $GLOBALS['__operator_devices'] = function () use ($permitted): array { - $hide = ($_SESSION['sess_user_config_array']['hide_disabled'] ?? 'on') === 'on'; - - return array_map(fn (int $id) => ['id' => (string) $id], array_values(array_filter($permitted, fn (int $id) => !($hide && $id === 3)))); - }; +// A small model of Cacti 1.2's device permissions. Devices 1 and 2 are +// enabled; device 3 is disabled. A user either has simple device permissions +// (every device) or a policy that allows $GLOBALS['__dv_permitted']. +// +// Hide Disabled is read the way Cacti reads it for a logged-in user: from +// settings_user by user id, defaulting to 'on'. read_user_setting() with +// $user > 0 never consults $_SESSION, so a session value changes nothing. +$GLOBALS['__dv_settings_user'] = []; +$GLOBALS['__dv_simple'] = false; +$GLOBALS['__dv_permitted'] = []; +$GLOBALS['__dv_valid_user'] = true; +$GLOBALS['__dv_policies'] = null; +$GLOBALS['__dv_rows'] = null; + +const SMOKEPING_DV_DISABLED = [3]; + +if (!function_exists('read_user_setting')) { + function read_user_setting($config_name, $default = false, $force = false, $user = 0) { + return $GLOBALS['__dv_settings_user'][$user][$config_name] ?? 'on'; + } +} + +if (!function_exists('auth_valid_user')) { + function auth_valid_user($user_id) { + return $GLOBALS['__dv_valid_user']; + } +} + +if (!function_exists('get_simple_device_perms')) { + function get_simple_device_perms($user) { + return $GLOBALS['__dv_simple']; + } +} + +if (!function_exists('get_policies')) { + function get_policies($user_id) { + return $GLOBALS['__dv_policies'] ?? [['id' => $user_id, 'type' => 'user', 'name' => 'user', 'policy_graphs' => 2, 'policy_hosts' => 2, 'policy_graph_templates' => 2, 'policy_trees' => 1]]; + } +} + +if (!function_exists('get_policy_where')) { + function get_policy_where($graph_auth_method, $policies, $sql_where) { + return $sql_where . ' AND (POLICY)'; + } +} + +// The device query: every host, narrowed to the permitted ones when a policy +// condition was added, and without disabled hosts when the SQL filters on +// h.disabled as get_allowed_devices() does under Hide Disabled. Any other +// query is ConfigRepository::deviceIds(), every non-deleted host. +function smokeping_dv_query(string $sql): mixed { + $ids = [1, 2, 3]; + + if (str_contains($sql, 'DISTINCT h.id')) { + if ($GLOBALS['__dv_rows'] !== null) { + return $GLOBALS['__dv_rows']; + } + + if (str_contains($sql, 'POLICY')) { + $ids = array_values(array_intersect($ids, $GLOBALS['__dv_permitted'])); + } + + if (str_contains($sql, 'h.disabled')) { + $ids = array_values(array_diff($ids, SMOKEPING_DV_DISABLED)); + } + } + + return array_map(fn (int $id): array => ['id' => (string) $id], $ids); +} + +// Cacti's get_allowed_devices() over the same model, Hide Disabled included. +function smokeping_dv_cacti_allowed(): array { + $user = (int) ($_SESSION['sess_user_id'] ?? 0); + $ids = $GLOBALS['__dv_simple'] ? [1, 2, 3] : $GLOBALS['__dv_permitted']; + $hide = read_user_setting('hide_disabled', false, false, $user) == 'on'; + + return array_map(fn (int $id): array => ['id' => (string) $id], array_values(array_filter($ids, fn (int $id): bool => !($hide && in_array($id, SMOKEPING_DV_DISABLED, true))))); +} + +function smokeping_dv_user(bool $simple, array $permitted = [], string $hideDisabled = 'on'): void { + $GLOBALS['__dv_simple'] = $simple; + $GLOBALS['__dv_permitted'] = $permitted; + $GLOBALS['__dv_settings_user'][2]['hide_disabled'] = $hideDisabled; } function smokeping_sees_every_device(): bool { @@ -37,51 +110,80 @@ function smokeping_sees_every_device(): bool { beforeEach(function () { $_SESSION = ['sess_user_id' => 2]; + $GLOBALS['__smokeping_options'] = ['auth_method' => '1', 'graph_auth_method' => '1']; + $GLOBALS['__smokeping_db_assoc'] = fn (string $sql): mixed => smokeping_dv_query($sql); + $GLOBALS['__operator_devices'] = fn (): array => smokeping_dv_cacti_allowed(); + $GLOBALS['__dv_settings_user'] = []; + $GLOBALS['__dv_valid_user'] = true; + $GLOBALS['__dv_policies'] = null; + $GLOBALS['__dv_rows'] = null; }); afterEach(function () { - $_SESSION = []; - $GLOBALS['__smokeping_db_assoc'] = []; - $GLOBALS['__operator_devices'] = []; + $_SESSION = []; + $GLOBALS['__smokeping_options'] = []; + $GLOBALS['__smokeping_db_assoc'] = []; + $GLOBALS['__operator_devices'] = []; +}); + +it('models Cacti: get_allowed_devices() leaves the disabled device out under the stored Hide Disabled, whatever the session says', function () { + smokeping_dv_user(true); + $_SESSION['sess_user_config_array'] = ['hide_disabled' => '']; + + expect(array_column(get_allowed_devices(), 'id'))->toBe(['1', '2']); }); -it('treats an unrestricted user with Hide Disabled on as seeing every device', function () { - smokeping_stub_devices([1, 2, 3]); - $_SESSION['sess_user_config_array'] = ['hide_disabled' => 'on']; +it('treats an unrestricted user with Hide Disabled on as seeing every device', function (bool $simple) { + smokeping_dv_user($simple, [1, 2, 3], 'on'); expect(smokeping_sees_every_device())->toBeTrue(); -}); +})->with(['simple permissions' => true, 'policy allowing every device' => false]); it('treats an unrestricted user with Hide Disabled off as seeing every device', function () { - smokeping_stub_devices([1, 2, 3]); - $_SESSION['sess_user_config_array'] = ['hide_disabled' => '']; + smokeping_dv_user(true, [], ''); expect(smokeping_sees_every_device())->toBeTrue(); }); it('refuses a user denied only a disabled device, whatever Hide Disabled says', function (string $hideDisabled) { - smokeping_stub_devices([1, 2]); - $_SESSION['sess_user_config_array'] = ['hide_disabled' => $hideDisabled]; + smokeping_dv_user(false, [1, 2], $hideDisabled); expect(smokeping_sees_every_device())->toBeFalse(); })->with(['on', '']); it('refuses a user limited to some enabled devices', function () { - smokeping_stub_devices([1, 3]); - $_SESSION['sess_user_config_array'] = ['hide_disabled' => 'on']; + smokeping_dv_user(false, [1, 3]); expect(smokeping_sees_every_device())->toBeFalse(); }); -it('restores the session settings after the check', function () { - smokeping_stub_devices([1, 2, 3]); +it('leaves the session alone', function () { + smokeping_dv_user(true); $_SESSION['sess_user_config_array'] = ['hide_disabled' => 'on', 'other' => 'x']; smokeping_sees_every_device(); - expect($_SESSION['sess_user_config_array'])->toBe(['hide_disabled' => 'on', 'other' => 'x']); + expect($_SESSION)->toBe(['sess_user_id' => 2, 'sess_user_config_array' => ['hide_disabled' => 'on', 'other' => 'x']]); +}); - unset($_SESSION['sess_user_config_array']); - smokeping_sees_every_device(); +it('treats every user as unrestricted when Cacti authentication is off, as Cacti does', function () { + smokeping_dv_user(false, [1]); + $GLOBALS['__smokeping_options']['auth_method'] = '0'; - expect($_SESSION)->not->toHaveKey('sess_user_config_array'); + expect(smokeping_sees_every_device())->toBeTrue(); }); + +it('refuses when the allowed devices cannot be worked out', function (Closure $break) { + smokeping_dv_user(false, [1, 2, 3]); + $break(); + + expect(smokeping_sees_every_device())->toBeFalse(); +})->with([ + 'no session user' => [fn () => $_SESSION = []], + 'a user Cacti does not know' => [fn () => $GLOBALS['__dv_valid_user'] = false], + 'no authentication setting' => [fn () => $GLOBALS['__smokeping_options']['auth_method'] = ''], + 'an unknown permission method' => [fn () => $GLOBALS['__smokeping_options']['graph_auth_method'] = '0'], + 'no policies' => [fn () => $GLOBALS['__dv_policies'] = []], + 'a policy without its columns' => [fn () => $GLOBALS['__dv_policies'] = [['id' => 2, 'type' => 'user']]], + 'a failed device query' => [fn () => $GLOBALS['__dv_rows'] = false], + 'a device row without an id' => [fn () => $GLOBALS['__dv_rows'] = [['id' => '1'], ['id' => '2'], ['name' => 'x']]], +]); diff --git a/tests/bin/permission-setup.php b/tests/bin/permission-setup.php index 40f5efb..ccf1287 100644 --- a/tests/bin/permission-setup.php +++ b/tests/bin/permission-setup.php @@ -32,6 +32,8 @@ * sees unmapped targets but only the mapped ones of device A * broad View Graphs and SmokePing View, everything allowed by policy * norealm View Graphs only, every device allowed by policy + * nodisabled the SmokePing admin realm, devices denied by policy; the suite + * grants every device but a disabled one */ chdir(dirname(__DIR__, 4)); @@ -70,6 +72,7 @@ 'revoked' => array('policy' => 2, 'realms' => array(7, $viewRealm), 'devices' => array((int) $deviceA)), 'broad' => array('policy' => 1, 'realms' => array(7, $viewRealm), 'devices' => array()), 'norealm' => array('policy' => 1, 'realms' => array(7), 'devices' => array()), + 'nodisabled' => array('policy' => 2, 'realms' => array(7, $viewRealm, $adminRealm), 'devices' => array()), ); foreach ($users as $name => $spec) { diff --git a/tests/permissions-e2e.sh b/tests/permissions-e2e.sh index 645dc90..9e3bf69 100644 --- a/tests/permissions-e2e.sh +++ b/tests/permissions-e2e.sh @@ -137,9 +137,9 @@ has() { grep -q -- "$1"; } # token is turned away before the plugin's code runs. csrf() { get "$1" "$2" | sed -n "s/.*var csrfMagicToken='\([^']*\)'.*/\1/p" | head -1; } -for u in admin restricted scoped revoked broad norealm; do login $u; done +for u in admin restricted scoped revoked broad norealm nodisabled; do login $u; done title() { get "$1" index.php | grep -o '[^<]*' | head -1; } -for u in admin restricted scoped revoked broad norealm; do +for u in admin restricted scoped revoked broad norealm nodisabled; do t=$(title $u) # Users without console access land on a permission page after login; what matters is that the session exists. case "$t" in *Login*) result FAIL "login-$u" "$t";; *) result PASS "login-$u" "$t";; esac @@ -437,6 +437,41 @@ done get admin "$HEALTH?language=en-US" > /dev/null $L set_setting "i18n_language_support=0" >/dev/null +# ---- a disabled device: Hide Disabled must not decide who sees every device ---- +# Cacti's get_allowed_devices() leaves disabled devices out while the user's +# Hide Disabled setting is on, its default, and reads that setting from +# settings_user. The administrator, who may see every device, keeps export and +# import with a disabled device present; a user granted every device but the +# disabled one is refused them. +$L make_devices "1:bulkoff" >/dev/null +dev_off=$(q "SELECT id FROM host WHERE description = 'bulkoff1'" | ids_of) +php -r 'chdir("/cacti"); include("./include/cli_check.php"); + $off = (int) $argv[1]; + db_execute_prepared("UPDATE host SET disabled = \"on\" WHERE id = ?", array($off)); + db_execute("DELETE s FROM settings_user AS s INNER JOIN user_auth AS u ON u.id = s.user_id WHERE s.name = \"hide_disabled\" AND u.username IN (\"admin\", \"nodisabled\")"); + db_execute_prepared("DELETE p FROM user_auth_perms AS p INNER JOIN user_auth AS u ON u.id = p.user_id WHERE u.username = \"nodisabled\""); + db_execute_prepared("INSERT INTO user_auth_perms (user_id, item_id, type) SELECT u.id, h.id, 3 FROM user_auth AS u, host AS h WHERE u.username = \"nodisabled\" AND h.id > 0 AND h.deleted = \"\" AND h.id <> ?", array($off));' "$dev_off" +hide=$(php -r 'chdir("/cacti"); include("./include/cli_check.php"); echo read_user_setting("hide_disabled", false, false, 1);') +[ -n "$dev_off" ] && [ "$hide" = on ] && [ "$(q "SELECT disabled FROM host WHERE id = $dev_off" | jcell)" = on ] && result PASS disabled-fixture "device $dev_off disabled, administrator's Hide Disabled on by default" || result FAIL disabled-fixture "device '$dev_off', hide_disabled '$hide'" + +check disabled-config-page-admin "export and import forms with a disabled device present" sh -c 'echo "$1" | grep -q "Export the SmokePing Configuration" && ! echo "$1" | grep -q "do not cover every device"' x "$(get admin $CONF)" +token=$(conf_token admin) +check disabled-config-export-admin "the export downloads" sh -c 'echo "$1" | grep -q "^schema_version: 1$"' x "$(curl -s -b $WORK/admin.jar -c $WORK/admin.jar --data-urlencode "__csrf_magic=$token" --data "action=export&format=yaml" "$BASE/$CONF")" +check disabled-import-page-admin "the import form" sh -c 'echo "$1" | grep -q "Preview reads the configuration" && ! echo "$1" | grep -q "do not cover every device"' x "$(get admin $IMP)" + +check disabled-config-page-refused "no forms for a user denied only the disabled device" sh -c '! echo "$1" | grep -q "Import a SmokePing Configuration\|Export the SmokePing" && echo "$1" | grep -q "do not cover every device"' x "$(get nodisabled $CONF)" +token=$(csrf nodisabled $INV) +check disabled-config-export-refused "a POST to export returns no configuration" sh -c '! echo "$1" | grep -q "schema_version\|Perm/\|hostname" && echo "$1" | grep -q "do not cover every device"' x "$(curl -s -b $WORK/nodisabled.jar -c $WORK/nodisabled.jar --data-urlencode "__csrf_magic=$token" --data "action=export&format=yaml" "$BASE/$CONF")" +printf 'schema_version: 1\ntargets:\n - path: Conf/nodisabled\n host: nodisabled.example\n' > $WORK/conf-nd.yaml +token=$(csrf nodisabled $INV) +check disabled-config-plan-refused "an upload to check returns no plan" sh -c '! echo "$1" | grep -q "add target\|Apply Import\|Plan " && echo "$1" | grep -q "do not cover every device"' x "$(curl -s -b $WORK/nodisabled.jar -c $WORK/nodisabled.jar -F "__csrf_magic=$token" -F action=check -F format=yaml -F "config_file=@$WORK/conf-nd.yaml" "$BASE/$CONF")" +token=$(csrf nodisabled $INV) +curl -s -b $WORK/nodisabled.jar -c $WORK/nodisabled.jar -o /dev/null --data-urlencode "__csrf_magic=$token" --data "action=apply&plan=0000000000000000" "$BASE/$CONF" +[ "$(q "SELECT COUNT(*) FROM plugin_smokeping_target WHERE path = 'Conf/nodisabled'" | jcell)" = 0 ] && result PASS disabled-config-apply-refused "an apply post changes nothing" || result FAIL disabled-config-apply-refused "a target was added" +check disabled-import-page-refused "no import form" sh -c '! echo "$1" | grep -q "Preview reads the configuration" && echo "$1" | grep -q "do not cover every device"' x "$(get nodisabled $IMP)" +check disabled-import-preview-refused "no import plan" sh -c '! echo "$1" | grep -q "Devices: \|imp.example" && echo "$1" | grep -q "do not cover every device"' x "$(imp_preview nodisabled $WORK/imp.conf)" +[ -n "$dev_off" ] && $L remove_devices "$dev_off" >/dev/null 2>&1 + # Leave no devices behind. left=$(q "SELECT id FROM host WHERE description LIKE 'bulk%' OR id IN (SELECT host_id FROM plugin_smokeping_object)" 2>/dev/null | ids_of) [ -n "$left" ] && $L remove_devices "$left" >/dev/null 2>&1 From 66a263787a157c72fda5e7c109a991ed202ccd45 Mon Sep 17 00:00:00 2001 From: Thomas Vincent Date: Thu, 19 Nov 2026 22:59:06 -0800 Subject: [PATCH 6/6] fix: refuse when the full device list cannot be read deviceIds() passed the query result through Row::rows(), so a failed query read as "no devices". A user allowed no devices then matched it and counted as unrestricted. deviceIds() now returns null on a failed query or a malformed row, as allowedDeviceIds() does, and the check refuses when either side is null. A Cacti with no devices still lets a user with the realm through: both sets are empty, there is nothing to hide, and refusing would block the import that first populates it. The e2e apply check for the user denied only the disabled device now also requires the device coverage refusal in the response. Signed-off-by: Thomas Vincent --- lib/ConfigRepository.php | 38 ++++++++++++++++++----------- setup.php | 9 +++++-- tests/Unit/DeviceVisibilityTest.php | 27 +++++++++++++++++++- tests/permissions-e2e.sh | 5 ++-- 4 files changed, 60 insertions(+), 19 deletions(-) diff --git a/lib/ConfigRepository.php b/lib/ConfigRepository.php index 9e20166..ff410ba 100644 --- a/lib/ConfigRepository.php +++ b/lib/ConfigRepository.php @@ -74,6 +74,30 @@ public function allowedDeviceIds(string $sqlWhere): ?array { ON h.host_template_id = ht.id $sqlWhere", [], true, $this->connection); + return self::sortedIds($rows); + } + + /** + * Ids of every device Cacti lists, disabled ones included. These are the + * devices smokeping_allowed_device_ids() returns for a user with + * unrestricted device access. Null when the query fails or a row has no + * numeric id, so a failure never reads as "no devices". + * + * @return list|null + */ + public function deviceIds(): ?array { + $rows = db_fetch_assoc_prepared("SELECT id FROM host WHERE id > 0 AND deleted = ''", [], true, $this->connection); + + return self::sortedIds($rows); + } + + /** + * The sorted ids of a device query's rows, or null when the query failed + * (Cacti returns false) or a row has no numeric id. + * + * @return list|null + */ + private static function sortedIds(mixed $rows): ?array { if (!is_array($rows)) { return null; } @@ -93,20 +117,6 @@ public function allowedDeviceIds(string $sqlWhere): ?array { return $ids; } - /** - * Ids of every device Cacti lists, disabled ones included. These are the - * devices smokeping_allowed_device_ids() returns for a user with - * unrestricted device access. - * - * @return list - */ - public function deviceIds(): array { - $ids = array_map(static fn (array $row): int => (int) $row['id'], Row::rows(db_fetch_assoc_prepared("SELECT id FROM host WHERE id > 0 AND deleted = ''", [], true, $this->connection))); - sort($ids); - - return $ids; - } - /** * Write a plan in one transaction. Nothing changes when any statement * fails. The plan is applied as decided; the caller has already compared diff --git a/setup.php b/setup.php index abbdf83..cbc772d 100644 --- a/setup.php +++ b/setup.php @@ -403,12 +403,17 @@ function smokeping_config_service(bool $webUser = false): \Somethingwithproof\Sm * Whether the user's device permissions cover every device: only when the * devices they allow, disabled ones included, are exactly the devices Cacti * lists. A user limited to some devices, however many, is not unrestricted, - * and any doubt about the allowed set counts as limited. + * and a failure to read either set counts as limited. + * + * With no devices at all, both sets are empty and every user with the realm + * passes: there is no device name to export or to hide, and refusing would + * block the import that first populates a new Cacti. */ function smokeping_user_sees_every_device(\Somethingwithproof\Smokeping\ConfigRepository $repository): bool { $allowed = smokeping_allowed_device_ids($repository); + $every = $repository->deviceIds(); - return $allowed !== null && $allowed === $repository->deviceIds(); + return $allowed !== null && $every !== null && $allowed === $every; } /** diff --git a/tests/Unit/DeviceVisibilityTest.php b/tests/Unit/DeviceVisibilityTest.php index 509ca39..2829e42 100644 --- a/tests/Unit/DeviceVisibilityTest.php +++ b/tests/Unit/DeviceVisibilityTest.php @@ -32,6 +32,8 @@ $GLOBALS['__dv_valid_user'] = true; $GLOBALS['__dv_policies'] = null; $GLOBALS['__dv_rows'] = null; +$GLOBALS['__dv_all_rows'] = null; +$GLOBALS['__dv_hosts'] = [1, 2, 3]; const SMOKEPING_DV_DISABLED = [3]; @@ -70,7 +72,11 @@ function get_policy_where($graph_auth_method, $policies, $sql_where) { // h.disabled as get_allowed_devices() does under Hide Disabled. Any other // query is ConfigRepository::deviceIds(), every non-deleted host. function smokeping_dv_query(string $sql): mixed { - $ids = [1, 2, 3]; + $ids = $GLOBALS['__dv_hosts']; + + if (!str_contains($sql, 'DISTINCT h.id') && $GLOBALS['__dv_all_rows'] !== null) { + return $GLOBALS['__dv_all_rows']; + } if (str_contains($sql, 'DISTINCT h.id')) { if ($GLOBALS['__dv_rows'] !== null) { @@ -117,6 +123,8 @@ function smokeping_sees_every_device(): bool { $GLOBALS['__dv_valid_user'] = true; $GLOBALS['__dv_policies'] = null; $GLOBALS['__dv_rows'] = null; + $GLOBALS['__dv_all_rows'] = null; + $GLOBALS['__dv_hosts'] = [1, 2, 3]; }); afterEach(function () { @@ -186,4 +194,21 @@ function smokeping_sees_every_device(): bool { 'a policy without its columns' => [fn () => $GLOBALS['__dv_policies'] = [['id' => 2, 'type' => 'user']]], 'a failed device query' => [fn () => $GLOBALS['__dv_rows'] = false], 'a device row without an id' => [fn () => $GLOBALS['__dv_rows'] = [['id' => '1'], ['id' => '2'], ['name' => 'x']]], + 'a failed full device query' => [fn () => $GLOBALS['__dv_all_rows'] = false], + 'a full device row without an id' => [fn () => $GLOBALS['__dv_all_rows'] = [['id' => '1'], ['name' => 'x']]], ]); + +it('refuses a user allowed no devices when the full device query fails', function () { + smokeping_dv_user(false, []); + $GLOBALS['__dv_all_rows'] = false; + + expect(smokeping_allowed_device_ids(new Somethingwithproof\Smokeping\ConfigRepository(false, '/var/www/cacti/rra')))->toBe([]) + ->and(smokeping_sees_every_device())->toBeFalse(); +}); + +it('lets a user with the realm through when Cacti has no devices at all', function () { + smokeping_dv_user(false, []); + $GLOBALS['__dv_hosts'] = []; + + expect(smokeping_sees_every_device())->toBeTrue(); +}); diff --git a/tests/permissions-e2e.sh b/tests/permissions-e2e.sh index 9e3bf69..cce4272 100644 --- a/tests/permissions-e2e.sh +++ b/tests/permissions-e2e.sh @@ -466,8 +466,9 @@ printf 'schema_version: 1\ntargets:\n - path: Conf/nodisabled\n host: nodisa token=$(csrf nodisabled $INV) check disabled-config-plan-refused "an upload to check returns no plan" sh -c '! echo "$1" | grep -q "add target\|Apply Import\|Plan " && echo "$1" | grep -q "do not cover every device"' x "$(curl -s -b $WORK/nodisabled.jar -c $WORK/nodisabled.jar -F "__csrf_magic=$token" -F action=check -F format=yaml -F "config_file=@$WORK/conf-nd.yaml" "$BASE/$CONF")" token=$(csrf nodisabled $INV) -curl -s -b $WORK/nodisabled.jar -c $WORK/nodisabled.jar -o /dev/null --data-urlencode "__csrf_magic=$token" --data "action=apply&plan=0000000000000000" "$BASE/$CONF" -[ "$(q "SELECT COUNT(*) FROM plugin_smokeping_target WHERE path = 'Conf/nodisabled'" | jcell)" = 0 ] && result PASS disabled-config-apply-refused "an apply post changes nothing" || result FAIL disabled-config-apply-refused "a target was added" +apply_nd=$(curl -s -b $WORK/nodisabled.jar -c $WORK/nodisabled.jar --data-urlencode "__csrf_magic=$token" --data "action=apply&plan=0000000000000000" "$BASE/$CONF") +check disabled-config-apply-refused "an apply post is refused for device coverage" sh -c 'echo "$1" | grep -q "do not cover every device"' x "$apply_nd" +[ "$(q "SELECT COUNT(*) FROM plugin_smokeping_target WHERE path = 'Conf/nodisabled'" | jcell)" = 0 ] && result PASS disabled-config-apply-writes-nothing "an apply post changes nothing" || result FAIL disabled-config-apply-writes-nothing "a target was added" check disabled-import-page-refused "no import form" sh -c '! echo "$1" | grep -q "Preview reads the configuration" && echo "$1" | grep -q "do not cover every device"' x "$(get nodisabled $IMP)" check disabled-import-preview-refused "no import plan" sh -c '! echo "$1" | grep -q "Devices: \|imp.example" && echo "$1" | grep -q "do not cover every device"' x "$(imp_preview nodisabled $WORK/imp.conf)" [ -n "$dev_off" ] && $L remove_devices "$dev_off" >/dev/null 2>&1