From d551c1e13d6ee015aa650d2685f02e1cf400b156 Mon Sep 17 00:00:00 2001 From: Copilot Date: Wed, 30 Sep 2026 09:20:01 -0400 Subject: [PATCH 1/8] Relocate schema into includes/database.php - Move npc_setup_tables() verbatim into includes/database.php, loaded once via a top-level require_once in setup.php. - Allowlist the install-only includes/database.php in the patch-coverage gate and drop the stale non-existent include/*.php entries from the measured-source list. Keeps the raw CREATE TABLE definitions as-is (lighter relocation); the version-guarded npc_upgrade_tables() migrations remain in setup.php. --- includes/database.php | 1326 ++++++++++++++++++++++++++++++++++ phpunit.xml | 2 - setup.php | 1312 +-------------------------------- tests/bin/patch-coverage.php | 4 + 4 files changed, 1332 insertions(+), 1312 deletions(-) create mode 100644 includes/database.php diff --git a/includes/database.php b/includes/database.php new file mode 100644 index 0000000..67b9beb --- /dev/null +++ b/includes/database.php @@ -0,0 +1,1326 @@ + setup.php - include/database.php - include/functions.php diff --git a/setup.php b/setup.php index 030a502..cca1d28 100644 --- a/setup.php +++ b/setup.php @@ -1,5 +1,7 @@ Date: Wed, 30 Sep 2026 13:52:28 -0400 Subject: [PATCH 2/8] Add manifest.json + upgrade-time file pruning --- .github/copilot-instructions.md | 4 + .github/workflows/plugin-ci-workflow.yml | 3 + manifest.json | 29 ++++ setup.php | 160 +++++++++++++++++++++ tests/Unit/NpcUpgradeTest.php | 50 +++++++ tests/Unit/PruneFilesTest.php | 173 +++++++++++++++++++++++ tests/bin/validate-manifest.php | 73 ++++++++++ tests/bootstrap-unit.php | 4 +- 8 files changed, 495 insertions(+), 1 deletion(-) create mode 100644 manifest.json create mode 100644 tests/Unit/NpcUpgradeTest.php create mode 100644 tests/Unit/PruneFilesTest.php create mode 100644 tests/bin/validate-manifest.php diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 07a5a49..efdba68 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -185,3 +185,7 @@ existing code or adding new code, not just in dedicated cleanup passes: line, `@param` lines, a blank comment line, then `@return`. Infer parameter/return types from actual usage; don't change the function's real type-hints in the same pass (let static analysis flag mismatches separately). Skip vendored third-party library files. + +## File manifest & upgrade pruning + +The plugin ships a root `manifest.json` with three arrays: `tombstones` (files/directories older versions shipped that have since moved or been removed), `expected` (the top-level files and directories that ship today, directories written with a trailing `/`), and `whitelist` (paths holding user data that must never be touched). Keep `expected` current: CI runs `tests/bin/validate-manifest.php`, which fails on any drift between `expected` and the real top-level tree (it ignores `tests/`, `.git*`, and whitelisted paths). Custom customer CSS/theme files belong in `expected`, and stylesheets live in `css/` (not `themes/`). On upgrade, `plugin_npc_prune_files()` deletes the tombstoned paths and the dev-only `tests/` tree, leaves `whitelist` and `.git*` alone, and logs (without removing) any top-level entry the manifest does not account for. As a safety measure it refuses any tombstone that resolves outside the plugin directory (a tampered manifest.json) and logs a warning for any file or directory it cannot remove. When you move or delete a shipped file, add its old path to `tombstones` and update `expected` in the same change. diff --git a/.github/workflows/plugin-ci-workflow.yml b/.github/workflows/plugin-ci-workflow.yml index acae68a..a782157 100644 --- a/.github/workflows/plugin-ci-workflow.yml +++ b/.github/workflows/plugin-ci-workflow.yml @@ -88,6 +88,9 @@ jobs: - name: Check PHP version run: php -v + - name: Validate plugin manifest (expected-file drift) + run: php cacti/plugins/npc/tests/bin/validate-manifest.php + - name: Run apt-get update run: sudo apt-get update diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000..3705f48 --- /dev/null +++ b/manifest.json @@ -0,0 +1,29 @@ +{ + "tombstones": [], + "expected": [ + ".mdl_style.rb", + ".mdlrc", + "CHANGELOG.md", + "INFO", + "LICENSE", + "QandA.md", + "README.md", + "cli.php", + "config.php", + "controllers/", + "images/", + "includes/", + "index.php", + "js/", + "locales/", + "manifest.json", + "nagioscmd.php", + "npc.php", + "perfdata.php", + "phpunit.xml", + "setup.php", + "top_graph_header.php", + "upgrade_schema.sql" + ], + "whitelist": [] +} diff --git a/setup.php b/setup.php index cca1d28..27588b4 100644 --- a/setup.php +++ b/setup.php @@ -354,6 +354,9 @@ function npc_config_settings() { if (($current_npc_version != $old_npc_version) && ($old_npc_version != '')) { npc_upgrade_tables(); + // Remove files tombstoned in manifest.json plus the dev-only tests/ tree. + plugin_npc_prune_files(); + // Add a new realm if ($old_npc_version != '2.0.2' || $old_npc_version != '2.0.3') { api_plugin_register_realm ('npc', 'npc1.php', 'NPC Global Commands', 1); @@ -507,3 +510,160 @@ function npc_upgrade_tables() { } } + + +/** + * Removes files and directories that a previous version of this plugin + * shipped but that have since moved or been deleted, using the tombstone + * and whitelist lists in manifest.json. Whitelisted (user-data) paths and + * any VCS metadata (.git*) are never touched; the dev-only tests/ tree is + * removed. Any path that resolves outside the plugin directory (a tampered + * manifest.json) is refused, and any file/directory that cannot be removed + * (e.g. read-only) is reported to the Cacti log. Any top-level entry that is + * neither expected nor a tombstone nor whitelisted is logged to the Cacti + * log and left in place. Called on a plugin version change. + * + * @return void + * + * @global array $config Cacti global configuration array; used to resolve + * the plugin directory. + */ +function plugin_npc_prune_files(): void { + global $config; + + $plugin_dir = $config['base_path'] . '/plugins/npc'; + $manifest_path = $plugin_dir . '/manifest.json'; + + if (!is_readable($manifest_path)) { + return; + } + + $manifest = json_decode((string) file_get_contents($manifest_path), true); + + if (!is_array($manifest)) { + cacti_log('WARNING: npc manifest.json could not be parsed; skipping file prune', false, 'NPC'); + + return; + } + + $tombstones = isset($manifest['tombstones']) && is_array($manifest['tombstones']) ? $manifest['tombstones'] : []; + $expected = isset($manifest['expected']) && is_array($manifest['expected']) ? $manifest['expected'] : []; + $whitelist = isset($manifest['whitelist']) && is_array($manifest['whitelist']) ? $manifest['whitelist'] : []; + + $protected = function (string $rel) use ($whitelist): bool { + if (strncmp($rel, '.git', 4) === 0) { + return true; + } + + foreach ($whitelist as $entry) { + $entry = trim((string) $entry, '/'); + + if ($entry !== '' && ($rel === $entry || strncmp($rel, $entry . '/', strlen($entry) + 1) === 0)) { + return true; + } + } + + return false; + }; + + // Security: resolve the plugin directory so a tampered manifest.json + // cannot steer the prune outside of it. + $plugin_real = realpath($plugin_dir); + + // Remove tombstoned (moved/deleted) paths plus the dev-only tests/ tree. + $remove = $tombstones; + $remove[] = 'tests/'; + + foreach ($remove as $rel) { + $rel = trim((string) $rel, '/'); + + if ($rel === '' || $protected($rel)) { + continue; + } + + $path = $plugin_dir . '/' . $rel; + + if (!is_link($path) && !file_exists($path)) { + continue; + } + + // Refuse any path that, after resolving symlinks and ../ segments, + // escapes the plugin directory (protects user data from a tampered + // manifest.json). + $anchor = is_link($path) ? dirname($path) : $path; + $real = realpath($anchor); + + if ($real === false || ($real !== $plugin_real && strncmp($real, $plugin_real . DIRECTORY_SEPARATOR, strlen((string) $plugin_real) + 1) !== 0)) { + cacti_log(sprintf('WARNING: npc prune refused to remove %s: path resolves outside the plugin directory (tampered manifest.json?)', $rel), false, 'NPC'); + + continue; + } + + if (is_dir($path) && !is_link($path)) { + $removed = plugin_npc_rmtree($path); + } else { + $removed = @unlink($path); + } + + if (!$removed) { + cacti_log(sprintf('WARNING: npc upgrade could not remove %s (check file/directory permissions)', $rel), false, 'NPC'); + } + } + + // Surface any top-level entry the manifest does not account for. + $known = []; + + foreach (array_merge($expected, $tombstones) as $entry) { + $top = explode('/', trim((string) $entry, '/'))[0]; + + if ($top !== '') { + $known[$top] = true; + } + } + + $entries = scandir($plugin_dir); + + foreach (($entries !== false ? $entries : []) as $entry) { + if ($entry === '.' || $entry === '..' || $entry === 'tests' || $protected($entry) || isset($known[$entry])) { + continue; + } + + cacti_log(sprintf('WARNING: npc upgrade found a file/directory not described in manifest.json: %s (left in place)', $entry), false, 'NPC'); + } +} + +/** + * Recursively deletes a directory and its contents. Symlinks are removed + * without being followed. Helper for plugin_npc_prune_files(). + * + * @param string $dir Absolute path to the directory to remove. + * + * @return bool True if the directory and everything under it was removed; + * false if any entry could not be deleted. + */ +function plugin_npc_rmtree(string $dir): bool { + $entries = scandir($dir); + $ok = true; + + foreach (($entries !== false ? $entries : []) as $entry) { + if ($entry === '.' || $entry === '..') { + continue; + } + + $path = $dir . '/' . $entry; + + if (is_dir($path) && !is_link($path)) { + if (!plugin_npc_rmtree($path)) { + $ok = false; + } + } elseif (!@unlink($path)) { + $ok = false; + } + } + + if (!@rmdir($dir)) { + $ok = false; + } + + return $ok; +} diff --git a/tests/Unit/NpcUpgradeTest.php b/tests/Unit/NpcUpgradeTest.php new file mode 100644 index 0000000..45bce36 --- /dev/null +++ b/tests/Unit/NpcUpgradeTest.php @@ -0,0 +1,50 @@ +not->toBeEmpty(); +}); diff --git a/tests/Unit/PruneFilesTest.php b/tests/Unit/PruneFilesTest.php new file mode 100644 index 0000000..132abd4 --- /dev/null +++ b/tests/Unit/PruneFilesTest.php @@ -0,0 +1,173 @@ + ['include/', 'oldfile.php', 'userdata/', 'gone.png'], + 'expected' => ['INFO', 'setup.php', 'includes/', 'manifest.json'], + 'whitelist' => ['userdata/'], + ]; + + $base = npc_prune_fixture($manifest); + $plugin = $base . '/plugins/npc'; + $restore = $GLOBALS['config']['base_path']; + + $GLOBALS['config']['base_path'] = $base; + + try { + plugin_npc_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(); + + // 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(); + + // 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'); +}); + +it('is a safe no-op when the manifest is missing', function () { + $base = sys_get_temp_dir() . '/npc-prune-missing-' . uniqid(); + mkdir($base . '/plugins/npc', 0777, true); + $restore = $GLOBALS['config']['base_path']; + + $GLOBALS['config']['base_path'] = $base; + + try { + plugin_npc_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() . '/npc-prune-bad-' . uniqid(); + $plugin = $base . '/plugins/npc'; + 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 { + plugin_npc_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 = npc_prune_fixture($manifest); + $plugin = $base . '/plugins/npc'; + $outside = $base . '/plugins/escapee.txt'; + file_put_contents($outside, 'precious user data'); + $restore = $GLOBALS['config']['base_path']; + + $GLOBALS['config']['base_path'] = $base; + + try { + plugin_npc_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('outside the plugin directory'); +}); + +it('warns when a tombstoned path cannot be removed', function () { + $manifest = [ + 'tombstones' => ['locked/'], + 'expected' => ['manifest.json'], + 'whitelist' => [], + ]; + + $base = npc_prune_fixture($manifest); + $plugin = $base . '/plugins/npc'; + 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 { + plugin_npc_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'); diff --git a/tests/bin/validate-manifest.php b/tests/bin/validate-manifest.php new file mode 100644 index 0000000..aa9858b --- /dev/null +++ b/tests/bin/validate-manifest.php @@ -0,0 +1,73 @@ + Date: Wed, 30 Sep 2026 17:06:15 -0400 Subject: [PATCH 3/8] docs: add PHPDoc to npc_setup_tables() and changelog entries for the relocation --- CHANGELOG.md | 6 ++++++ includes/database.php | 13 +++++++++++++ 2 files changed, 19 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index f20d78e..1846b44 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,12 @@ --- develop --- +* dev: Relocate the schema provisioning function `npc_setup_tables()` from + `setup.php` into `includes/database.php` (loaded via `require_once`) to align + with the fleet schema/includes convention; behavior is unchanged +* dev: Add a root `manifest.json` file manifest with upgrade-time pruning + (`plugin_npc_prune_files()`) that removes tombstoned and dev-only paths on + version change, plus a CI `validate-manifest.php` drift check * dev: Measure CI coverage with xdebug instead of pcov so the plugin's own sources are instrumented (pcov auto-scopes to the Composer root and skipped cacti/plugins/, leaving the patch-coverage gate with nothing to measure) * dev: Enforce patch coverage of changed lines in CI and remove the inert COMPOSER_ROOT_VERSION env from the Pest step * security: Add a version-safe CSP nonce (`plugin_npc_csp_nonce()`) to every inline `