Files
Cactiplugin_thold/tests/Unit/TholdCommandExecutionTest.php
TheWitnessandCopilot 9b217e0e3a INFO: set compat to 1.2.29 (#838)
* INFO: set compat to 1.2.32

* docs: update Copilot instructions Cacti baseline to 1.2.32 (matches INFO compat)

* INFO: back off compat to 1.2.29

* Add manifest.json + upgrade-time file pruning

* Prune phpunit.xml on upgrade and ignore markdown-lint configs

phpunit.xml ships in the repo for CI but is a dev-only test artifact, so it
is removed from manifest.json 'expected', pruned from installs on upgrade
(like tests/), and excluded from the manifest drift check.

The retired markdown-lint configs (.mdlrc, .md_style.rb) are deleted, and
.md* is now ignored like .git*: protected from pruning and excluded from
drift if it reappears.

* Move thold_functions.php and thold_webapi.php into includes/; flatten css

The main threshold library becomes includes/functions.php and the web API
helper becomes includes/webapi.php; every caller (setup.php, includes/*, the
CLI/poller/notify entry points and the test suite) loads them from includes/.
Each per-theme stylesheet css/<theme>/main.css becomes css/<theme>.css so users
can drop their own css/<theme>.css into the css base, and the page_head hook
looks there. Old paths are tombstoned so existing installs drop the stale
copies on upgrade.

* Regenerate cacti.pot for the includes/ file relocations

Moving the plugin's library files into includes/ changed the source-reference
lines in the translation template; regenerate it so the 'Verify translation
template' CI check passes.

* Harden the hook-include test and make RPN integer ops explicit

The HookFunctionsIncludeTest invokes real hooks with placeholder input purely
to execute their relocated include_once lines; it now swallows engine
notices/warnings/deprecations during those calls (and restores the error
handler and config afterward) so it cannot trip the suite's failOnDeprecation
or leak state into other tests. The RPN % and ^ operators now cast their
operands to int explicitly, matching their long-standing integer-truncation
behaviour while silencing the implicit float-to-int conversion deprecation.

* Harden prune against tampered-manifest path traversal

The upgrade-time prune now rejects any tombstone containing '.'/'..' segments
(which could escape the plugin directory or resolve to its root) and treats
ancestors of whitelist entries as protected, so a tombstone on a parent
directory can no longer delete a whitelisted file beneath it.

* docs: update and align the Project Structure block

Point the structure tree at the relocated files (libraries now under
includes/, data files under docs/, stylesheets under css/) and align the
trailing '# ...' comments to a single column so they no longer drift right.

* docs/tests: standardize test header and correct manifest-contract notes

- Use the full license header (from the plugin's own setup.php) in
  tests/Unit/PruneFilesTest.php instead of the abbreviated copyright banner.
- Document that the manifest drift check and the upgrade-time prune also
  handle phpunit.xml and .md* files, matching the implemented behavior.

* refactor: rename prune helpers to the plugin-slug function prefix

The repository naming contract reserves the plugin_<name>_ prefix for plugin
lifecycle / hook-registration functions; all other functions use the plain
<name>_ prefix. Rename the internal upgrade helpers accordingly:

  plugin_<name>_prune_files() -> <name>_prune_files()
  plugin_<name>_rmtree()      -> <name>_rmtree()

The call site, unit tests, and the copilot-instructions.md references are
updated to match. No behavioral change.

* chore: set the Cacti compatibility floor to 1.2.29

Align the compat metadata (and the contributor-guide references) with the
team decision to standardize the minimum supported Cacti version at 1.2.29;
the previously proposed 1.2.32 floor was not adopted.

---------

Co-authored-by: Copilot <copilot@users.noreply.github.com>
2026-10-01 01:40:00 -05:00

270 lines
8.3 KiB
PHP

<?php
/*
+-------------------------------------------------------------------------+
| Copyright (C) 2004-2026 The Cacti Group |
| |
| 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. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDtool-based Graphing Solution |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
/**
* thold_command_execution() runs the operator's trigger command for a breach.
*
* The command is assembled from an admin-configured template, so the point of
* these tests is which template is chosen for which breach direction, and that
* the values spliced into it cannot extend the command line.
*/
final class TholdCommandExecutionTest extends TestCase {
/**
* @return void
*/
public static function setUpBeforeClass(): void {
self::loadPluginSource('includes/functions.php');
}
/**
* @return void
*/
protected function setUp(): void {
parent::setUp();
CactiStubs::$configOptions['thold_enable_scripts'] = 'on';
CactiStubs::$configOptions['thold_notification_queue'] = 'on';
CactiStubs::$configOptions['base_url'] = 'http://cacti.example.org';
}
/**
* @return array<string, mixed>
*/
private function threshold(array $overrides = []) {
return $overrides + [
'id' => 3,
'local_data_id' => 4,
'local_graph_id' => 7,
'name' => 'CPU',
'name_cache' => 'CPU',
'data_source_name' => 'traffic_in',
'lastread' => 95,
'notes' => '',
'dnotes' => '',
'external_id' => '',
'thold_type' => 0,
'thold_hi' => 90,
'thold_low' => 10,
'thold_fail_trigger' => 3,
'thold_template_id' => 0,
'trigger_cmd_high' => '',
'trigger_cmd_low' => '',
'trigger_cmd_norm' => '',
];
}
/**
* @return array<string, mixed>
*/
private function device(array $overrides = []) {
return $overrides + [
'id' => 2,
'description' => 'router1',
'hostname' => '10.0.0.1',
'location' => 'rack 4',
'site_id' => 1,
'status' => 3,
'status_fail_date' => '2026-01-01 00:00:00',
'status_rec_date' => '2026-01-02 00:00:00',
'status_last_error' => '',
];
}
/**
* The queued command, or null when nothing was queued.
*
* @return string|null
*/
private function queuedCommand() {
foreach (CactiStubs::callsTo('db_execute_prepared') as $call) {
foreach ($call['params'] as $param) {
if (is_string($param) && strpos($param, '"command"') !== false) {
$decoded = json_decode($param, true);
return isset($decoded['command']) ? $decoded['command'] : null;
}
}
}
return null;
}
/**
* @return array<string, array{0: string, 1: array<int, bool>}>
*/
public static function breachDirectionProvider() {
return [
'high' => ['trigger_cmd_high', [true, false, false]],
'low' => ['trigger_cmd_low', [false, true, false]],
'restore' => ['trigger_cmd_norm', [false, false, true]],
];
}
/**
* @dataProvider breachDirectionProvider
*
* @param string $column
* @param array<int, bool> $breaches
*
* @return void
*/
public function testEachBreachDirectionRunsItsOwnCommand($column, array $breaches): void {
$thold = $this->threshold([$column => '/usr/bin/alert <HOSTNAME>']);
$device = $this->device();
thold_command_execution($thold, $device, $breaches[0], $breaches[1], $breaches[2]);
$this->assertSame("/usr/bin/alert '10.0.0.1'", $this->queuedCommand());
}
/**
* @dataProvider breachDirectionProvider
*
* @param string $column
* @param array<int, bool> $breaches
*
* @return void
*/
public function testShellMetacharactersInDeviceDataAreQuoted($column, array $breaches): void {
$thold = $this->threshold([$column => '/usr/bin/alert <DESCRIPTION>']);
$device = $this->device(['description' => '; touch /tmp/pwned']);
thold_command_execution($thold, $device, $breaches[0], $breaches[1], $breaches[2]);
$this->assertSame("/usr/bin/alert '; touch /tmp/pwned'", $this->queuedCommand());
}
/**
* thold_command_execution() resolves |pipe| tokens (thold_expand_string())
* and <TAG> tokens (thold_replace_threshold_tags()) through a shared
* deferred-placeholder map, so a device value that happens to contain the
* literal text of the other family's token can't be expanded a second
* time and break out of its own quoting.
*
* @return void
*/
public function testADeviceValueContainingAPipeTokenIsNotReExpandedAsAHostToken(): void {
$malicious = "'; touch /tmp/pwned; echo '";
$thold = $this->threshold(['trigger_cmd_high' => '/usr/bin/alert <DESCRIPTION>']);
$device = $this->device(['description' => '|host_hostname|', 'hostname' => $malicious]);
thold_command_execution($thold, $device, true, false, false);
$this->assertSame('/usr/bin/alert ' . escapeshellarg('|host_hostname|'), $this->queuedCommand());
}
/**
* @return void
*/
public function testNothingRunsWhenScriptsAreDisabled(): void {
CactiStubs::$configOptions['thold_enable_scripts'] = '';
$thold = $this->threshold(['trigger_cmd_high' => '/usr/bin/alert']);
$device = $this->device();
thold_command_execution($thold, $device, true, false, false);
$this->assertNull($this->queuedCommand());
}
/**
* @return void
*/
public function testNothingRunsWhenTheDirectionHasNoCommandConfigured(): void {
$thold = $this->threshold();
$device = $this->device();
thold_command_execution($thold, $device, true, false, false);
$this->assertNull($this->queuedCommand());
}
/**
* A high breach takes precedence, so a threshold configured for both cannot
* run two commands in one evaluation.
*
* @return void
*/
public function testHighBreachTakesPrecedenceOverLow(): void {
$thold = $this->threshold([
'trigger_cmd_high' => '/usr/bin/high',
'trigger_cmd_low' => '/usr/bin/low',
]);
$device = $this->device();
thold_command_execution($thold, $device, true, true, false);
$this->assertSame('/usr/bin/high', $this->queuedCommand());
}
/**
* With the queue off the command runs inline, and its exit status and
* output are logged.
*
* @dataProvider breachDirectionProvider
*
* @param string $column
* @param array<int, bool> $breaches
*
* @return void
*/
public function testInlineExecutionLogsTheCommandOutput($column, array $breaches): void {
CactiStubs::$configOptions['thold_notification_queue'] = '';
$thold = $this->threshold([$column => '/bin/echo breach']);
$device = $this->device();
thold_command_execution($thold, $device, $breaches[0], $breaches[1], $breaches[2]);
$this->assertNull($this->queuedCommand());
$this->assertNotEmpty(CactiStubs::$log);
}
/**
* @return array<string, array{0: string, 1: string}>
*/
public static function inlineOutcomeProvider() {
return [
'success without output' => ['/bin/true', 'NOTE'],
'success with output' => ['/bin/echo ok', 'NOTE'],
'failure without output' => ['/bin/false', 'WARNING'],
'failure with output' => ["/bin/sh -c 'echo oops; exit 1'", 'WARNING'],
];
}
/**
* A trigger command that fails is the operator's only signal that their
* alerting is broken, so the exit status has to reach the log either way.
*
* @dataProvider inlineOutcomeProvider
*
* @param string $command
* @param string $level
*
* @return void
*/
public function testInlineExecutionLogsTheExitStatus($command, $level): void {
CactiStubs::$configOptions['thold_notification_queue'] = '';
$thold = $this->threshold(['trigger_cmd_high' => $command]);
$device = $this->device();
thold_command_execution($thold, $device, true, false, false);
$this->assertStringStartsWith($level, CactiStubs::$log[0]);
}
}