Files
Cactiplugin_thold/tests/Unit/PruneFilesTest.php
T
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

256 lines
9.0 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. |
| |
| 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. |
+-------------------------------------------------------------------------+
| Cacti: The Complete RRDTool-based Graphing Solution |
+-------------------------------------------------------------------------+
| This code is designed, written, and maintained by the Cacti Group. See |
| about.php and/or the AUTHORS file for specific developer information. |
+-------------------------------------------------------------------------+
| http://www.cacti.net/ |
+-------------------------------------------------------------------------+
*/
/*
* Unit coverage for thold_prune_files(): tombstone/tests removal,
* whitelist and .git protection, and logging of unaccounted-for entries.
*/
require_once __DIR__ . '/../../setup.php';
function thold_prune_fixture(array $manifest): string {
$base = sys_get_temp_dir() . '/thold-prune-' . uniqid();
$plugin = $base . '/plugins/thold';
mkdir($plugin . '/include', 0777, true);
file_put_contents($plugin . '/include/old.php', "<?php\n");
mkdir($plugin . '/tests/Unit', 0777, true);
file_put_contents($plugin . '/tests/Unit/SomeTest.php', "<?php\n");
mkdir($plugin . '/userdata', 0777, true);
file_put_contents($plugin . '/userdata/keep.dat', 'keep');
mkdir($plugin . '/includes', 0777, true);
file_put_contents($plugin . '/INFO', "[info]\n");
file_put_contents($plugin . '/setup.php', "<?php\n");
file_put_contents($plugin . '/oldfile.php', "<?php\n");
file_put_contents($plugin . '/stray.php', "<?php\n");
file_put_contents($plugin . '/phpunit.xml', '');
file_put_contents($plugin . '/.mdlrc', '');
file_put_contents($plugin . '/.md_style.rb', '');
mkdir($plugin . '/.git', 0777, true);
file_put_contents($plugin . '/.git/config', '');
file_put_contents($plugin . '/manifest.json', json_encode($manifest));
return $base;
}
beforeEach(function () {
$GLOBALS['__test_cacti_log'] = [];
});
it('removes tombstoned paths and the tests/ tree, keeps whitelist/.git/expected, logs strays', function () {
$manifest = [
'tombstones' => ['include/', 'oldfile.php', 'userdata/', 'gone.png'],
'expected' => ['INFO', 'setup.php', 'includes/', 'manifest.json'],
'whitelist' => ['userdata/'],
];
$base = thold_prune_fixture($manifest);
$plugin = $base . '/plugins/thold';
$restore = $GLOBALS['config']['base_path'];
$GLOBALS['config']['base_path'] = $base;
try {
thold_prune_files();
} finally {
$GLOBALS['config']['base_path'] = $restore;
}
// Tombstone and the dev-only tests/ tree are gone.
expect(is_dir($plugin . '/include'))->toBeFalse();
expect(is_dir($plugin . '/tests'))->toBeFalse();
expect(is_file($plugin . '/oldfile.php'))->toBeFalse();
expect(is_file($plugin . '/phpunit.xml'))->toBeFalse();
// Whitelisted user data, VCS metadata, and expected files are untouched.
// (userdata/ is even listed as a tombstone, but the whitelist wins.)
expect(is_file($plugin . '/userdata/keep.dat'))->toBeTrue();
expect(is_dir($plugin . '/.git'))->toBeTrue();
expect(is_file($plugin . '/INFO'))->toBeTrue();
expect(is_dir($plugin . '/includes'))->toBeTrue();
expect(is_file($plugin . '/.mdlrc'))->toBeTrue();
expect(is_file($plugin . '/.md_style.rb'))->toBeTrue();
// An unexpected, non-whitelisted stray is left in place but logged.
expect(is_file($plugin . '/stray.php'))->toBeTrue();
$logged = implode("\n", $GLOBALS['__test_cacti_log']);
expect($logged)->toContain('stray.php');
expect($logged)->not->toContain('userdata');
expect($logged)->not->toContain('.git');
expect($logged)->not->toContain('.mdlrc');
expect($logged)->not->toContain('.md_style.rb');
});
it('is a safe no-op when the manifest is missing', function () {
$base = sys_get_temp_dir() . '/thold-prune-missing-' . uniqid();
mkdir($base . '/plugins/thold', 0777, true);
$restore = $GLOBALS['config']['base_path'];
$GLOBALS['config']['base_path'] = $base;
try {
thold_prune_files();
} finally {
$GLOBALS['config']['base_path'] = $restore;
}
expect($GLOBALS['__test_cacti_log'])->toBe([]);
});
it('logs and skips pruning when the manifest is malformed', function () {
$base = sys_get_temp_dir() . '/thold-prune-bad-' . uniqid();
$plugin = $base . '/plugins/thold';
mkdir($plugin, 0777, true);
file_put_contents($plugin . '/manifest.json', 'not json');
mkdir($plugin . '/tests', 0777, true);
$restore = $GLOBALS['config']['base_path'];
$GLOBALS['config']['base_path'] = $base;
try {
thold_prune_files();
} finally {
$GLOBALS['config']['base_path'] = $restore;
}
// A malformed manifest must not delete anything.
expect(is_dir($plugin . '/tests'))->toBeTrue();
expect(implode("\n", $GLOBALS['__test_cacti_log']))->toContain('could not be parsed');
});
it('refuses to remove a tombstone that resolves outside the plugin directory', function () {
$manifest = [
'tombstones' => ['../escapee.txt'],
'expected' => ['manifest.json'],
'whitelist' => [],
];
$base = thold_prune_fixture($manifest);
$plugin = $base . '/plugins/thold';
$outside = $base . '/plugins/escapee.txt';
file_put_contents($outside, 'precious user data');
$restore = $GLOBALS['config']['base_path'];
$GLOBALS['config']['base_path'] = $base;
try {
thold_prune_files();
} finally {
$GLOBALS['config']['base_path'] = $restore;
}
// The out-of-tree file is untouched and the refusal is logged.
expect(is_file($outside))->toBeTrue();
expect(implode("\n", $GLOBALS['__test_cacti_log']))->toContain('a traversal segment');
});
it('warns when a tombstoned path cannot be removed', function () {
$manifest = [
'tombstones' => ['locked/'],
'expected' => ['manifest.json'],
'whitelist' => [],
];
$base = thold_prune_fixture($manifest);
$plugin = $base . '/plugins/thold';
mkdir($plugin . '/locked/sub', 0777, true);
file_put_contents($plugin . '/locked/sub/data', 'x');
chmod($plugin . '/locked/sub', 0500); // read-only dir: its child cannot be unlinked
$restore = $GLOBALS['config']['base_path'];
$GLOBALS['config']['base_path'] = $base;
set_error_handler(static fn () => true); // swallow the expected unlink warning
try {
thold_prune_files();
} finally {
restore_error_handler();
$GLOBALS['config']['base_path'] = $restore;
@chmod($plugin . '/locked/sub', 0700);
}
expect(implode("\n", $GLOBALS['__test_cacti_log']))->toContain('could not remove');
})->skip(function () {
return function_exists('posix_getuid') && posix_getuid() === 0;
}, 'permission checks are bypassed for the root user');
it('refuses a tombstone that escapes through a symlinked directory', function () {
$manifest = [
'tombstones' => ['escdir/secret.txt'],
'expected' => ['manifest.json'],
'whitelist' => [],
];
$base = thold_prune_fixture($manifest);
$plugin = $base . '/plugins/thold';
$outside = $base . '/outside';
mkdir($outside, 0777, true);
file_put_contents($outside . '/secret.txt', 'precious user data');
@symlink($outside, $plugin . '/escdir');
$restore = $GLOBALS['config']['base_path'];
$GLOBALS['config']['base_path'] = $base;
try {
thold_prune_files();
} finally {
$GLOBALS['config']['base_path'] = $restore;
}
// The out-of-tree file reached through the symlink is untouched and logged.
expect(is_file($outside . '/secret.txt'))->toBeTrue();
expect(implode("\n", $GLOBALS['__test_cacti_log']))->toContain('outside the plugin directory');
})->skip(function () {
$probe = sys_get_temp_dir() . '/.prune-symlink-probe-' . uniqid();
$ok = @symlink(__FILE__, $probe);
@unlink($probe);
return $ok === false;
}, 'symlinks are not supported on this filesystem');
it('protects a whitelisted file from a tombstone on its parent directory', function () {
$manifest = [
'tombstones' => ['userdata/'],
'expected' => ['manifest.json'],
'whitelist' => ['userdata/keep.dat'],
];
$base = thold_prune_fixture($manifest);
$plugin = $base . '/plugins/thold';
$restore = $GLOBALS['config']['base_path'];
$GLOBALS['config']['base_path'] = $base;
try {
thold_prune_files();
} finally {
$GLOBALS['config']['base_path'] = $restore;
}
// A whitelisted file shields its parent directory from a tombstone.
expect(is_file($plugin . '/userdata/keep.dat'))->toBeTrue();
});