diff --git a/lib/ConfigRepository.php b/lib/ConfigRepository.php index 0d319fc..ff410ba 100644 --- a/lib/ConfigRepository.php +++ b/lib/ConfigRepository.php @@ -54,11 +54,67 @@ public function state(array $mappings = []): ConfigState { } /** - * Devices Cacti lists, which is what get_allowed_devices() returns for a - * user with unrestricted device access. + * 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); + + 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 deviceCount(): int { - return (int) db_fetch_cell_prepared("SELECT COUNT(*) FROM host WHERE id > 0 AND deleted = ''", [], '', true, $this->connection); + 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; + } + + $ids = []; + + foreach ($rows as $row) { + if (!is_array($row) || !is_numeric($row['id'] ?? null)) { + return null; + } + + $ids[] = (int) $row['id']; + } + + sort($ids); + + return $ids; } /** diff --git a/setup.php b/setup.php index f2c2aa2..cbc772d 100644 --- a/setup.php +++ b/setup.php @@ -400,14 +400,100 @@ 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. + * 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 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 = get_allowed_devices(); + $allowed = smokeping_allowed_device_ids($repository); + $every = $repository->deviceIds(); + + return $allowed !== null && $every !== null && $allowed === $every; +} + +/** + * 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 + * 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_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; + } + } + + $authMethod = read_config_option('auth_method'); + + if (!is_numeric($authMethod)) { + return null; + } + + $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 is_array($allowed) && count($allowed) === $repository->deviceCount(); + return $repository->allowedDeviceIds($sqlWhere); } /** 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 new file mode 100644 index 0000000..2829e42 --- /dev/null +++ b/tests/Unit/DeviceVisibilityTest.php @@ -0,0 +1,214 @@ + + * 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'; + +// 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; +$GLOBALS['__dv_all_rows'] = null; +$GLOBALS['__dv_hosts'] = [1, 2, 3]; + +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 = $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) { + 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 { + return smokeping_user_sees_every_device(new Somethingwithproof\Smokeping\ConfigRepository(false, '/var/www/cacti/rra')); +} + +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; + $GLOBALS['__dv_all_rows'] = null; + $GLOBALS['__dv_hosts'] = [1, 2, 3]; +}); + +afterEach(function () { + $_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 (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_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_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_dv_user(false, [1, 3]); + + expect(smokeping_sees_every_device())->toBeFalse(); +}); + +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)->toBe(['sess_user_id' => 2, 'sess_user_config_array' => ['hide_disabled' => 'on', 'other' => 'x']]); +}); + +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(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']]], + '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/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..cce4272 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,42 @@ 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) +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 + # 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