Files
cacti/tests/tools/test_check_changed_php_coverage.py
T
4e5b2852dc security: harden tokens, imports, script substitution and SpikeKill mutations (#8237)
* security(batch12): constant-time 2FA cookie and reset-token compares (GHSA-4qx8-jj2h-p7q2)

auth_2fa.php used === to compare the 2FA bypass-cookie HMAC and
auth_resetpassword.php used != for the reset-token check; both are
byte-by-byte and leak timing. Switch to hash_equals() so the comparison
is constant-time. Develop-only paths (no released 1.2.x equivalent).

* security(batch12): route package-repo manifest fetches through cacti_http (GHSA-54fg-q9h9-88mm)

package_repos.php fetched the package.manifest for the GitHub and
Direct-URL (repo_type 0/2) repository types with raw file_get_contents()
- the Direct-URL path additionally disabled SSL verification - which
bypassed the hardened cacti_http() client and allowed SSRF (cloud
metadata, internal host/port probing) plus MITM. Both paths now use
cacti_http(), which restricts the scheme to http/https, blocks
private/loopback/link-local targets, pins DNS to prevent rebinding, and
verifies TLS. The GitHub Bearer token is passed via the headers option.
Develop-only (package_repos.php does not exist in released 1.2.x).

* security(batch12): shed matched quotes around resolved data-input tokens (GHSA-5v3j-wcrr-jxjg)

Field values are escaped with cacti_escapeshellarg(), which wraps them
in single quotes. When a Data Input template author placed the <field>
placeholder inside a matched pair of quotes (e.g. "<arg1>"), those
surrounding quotes made the value's own quoting literal, so $(...) or
backticks in the value executed via the shell on the next poll - a
realm-3 user reaching OS command execution, bypassing the CVE-2026-39902
hardening and not addressed by the single-pass fq9x fix.

substitute_script_path() now consumes one matched pair of surrounding
quotes when a token resolves, so the escaped value's own quoting is
authoritative. Unresolved tokens keep their literal form (including any
quotes), and the single-pass behaviour that fixed GHSA-fq9x is retained.
Affects released 1.2.x (<= 1.2.31) and develop; this is the develop fix,
to be backported to 1.2.x.

* security(batch12): regression tests + CHANGELOG for batch-12 develop fixes

Add tests/Unit/Security/Batch12SecurityRegressionTest.php guarding the
batch-12 sinks (GHSA-4qx8, GHSA-54fg, GHSA-5v3j) with a behavioral proof
that a double-quoted Data Input placeholder sheds its quotes, plus a
confirmation test that poller_spikekill.php escapes --rrdfile
(GHSA-vhh2, already fixed in #7235). List the four GHSAs in the CHANGELOG.

* security(batch12): update batch-11 fq9x regression test for quote-aware substitute_script_path

The GHSA-5v3j quote-shedding changed substitute_script_path()'s regex
and capture group, which the batch-11 fq9x test pinned verbatim. Update
those two assertions to the quote-aware pattern marker and $matches[2];
the single-pass guarantee the test covers is unchanged.

* security(batch12): narrow reset-hash row with is_array for PHPStan L6

The hash_equals() guard left $hash inferred as non-empty-array|true, so
$hash['user_id'] tripped PHPStan level 6. Guard with is_array() instead
of a truthy check; db_fetch_row_prepared returns false for no row, so
behavior is unchanged.

* security(batch12): drop the executable bit on the new security test files

* security(batch12): route import-time repo manifest fetches through cacti_http (GHSA-54fg)

get_repo_file() still used raw file_get_contents() for the GitHub and Direct-URL repo types, bypassing the SSRF hardening added to form_save(). Route both remote branches through cacti_http() (scheme/host validation, private-range block, DNS pinning, TLS verify; Bearer token via the headers option) and add a regression assertion covering the import sink.

* security(batch12): make substitute_script_path fully quote-aware (GHSA-5v3j)

The matched-pair quote shed only neutralised a token the template wrapped
exactly ("<arg1>"). A token embedded in a larger quoted word ("prefix<arg1>",
"<arg1>suffix", "<a><b>") kept the outer double quotes, so backticks/$(...) in
the already-escaped value stayed live - the bypass Copilot flagged.

Replace the regex with a single-pass shell-quote-state scanner: it still sheds
an exact wrapping pair, but for any token inside a larger quoted word it briefly
closes the template's quoting around the escaped value so it cannot be
re-interpreted. Values are never re-scanned (single-pass, GHSA-fq9x retained).

Updates the batch-11/12 source assertions, adds prefix/suffix/mixed regression
cases, and drops the Batch12 eval fallback (the unit bootstrap already loads
lib/functions.php via include/global.php).

* security(batch12): relocate batch-12 regressions into vuln-class subfolders

Split tests/Unit/Security/Batch12SecurityRegressionTest.php into behavior-named
files under the existing vulnerability-class layout, per the review feedback:

  Auth/TwoFaCookieAndResetTokenConstantTimeTest.php   GHSA-4qx8
  Ssrf/PackageRepoManifestFetchTest.php               GHSA-54fg
  ShellInjection/DataInputQuotedPlaceholderTest.php   GHSA-5v3j
  ShellInjection/SpikekillRrdfileEscapeTest.php       GHSA-vhh2

Each file reaches the repo root via dirname(__DIR__, 4) for its one
subfolder-deep location. No assertion changes; pure relocation.

* security: preserve template quoting for raw path tokens in substitute_script_path

Keep the develop fix in sync with the 1.2.x backport (#8238): substitute_script_path()
only sheds/closes the template's quotes for self-quoting (cacti_escapeshellarg) values.
Trusted raw path_* tokens are substituted in place so a quoted "<path_php_binary>" keeps
its quotes for the shell and a bare <path_cacti>/scripts/x.php stays unquoted for the PHP
script server, which resolves the first token as a filesystem path. Reformatted per
php-cs-fixer and added a raw-path-token regression test.

* security: keep substituting a token that follows a backslash in substitute_script_path

Mirror the 1.2.x fix (#8238): the scanner's backslash branches consumed the next
character unconditionally, so a legacy/custom template token such as \<arg> never
reached the matcher and the trailing cleanup stripped it to a bare backslash. Both
branches now only pair the backslash with a following quote/backslash (so an escaped
quote still cannot toggle quote-state); any other character - notably a <token> start -
leaves the backslash on its own and is processed on the next iteration. Reformatted per
php-cs-fixer and added a backslash-before-token regression test.

* security: normalize dangling backslash before substituted value in substitute_script_path (GHSA-5v3j)

A template backslash immediately before a <field> token (\<arg1>) escaped the
already-escaped value's opening quote, producing \'...' which the shell rejects
with an unmatched-quote error (odd backslash runs) or prepended a stray literal
backslash (even runs). The quote-aware scanner now sheds one backslash when the
run immediately preceding a self-quoted value is odd, in both the unquoted
in-place branch and the close-around branch, so the value's own quotes always
function as the shell's quotes and $(...)/backticks inside it can never
re-activate.

The backslash regression test now executes each substituted template through
/bin/sh (printf %s) and asserts a clean parse plus a literal round-trip across
odd/even backslash counts, rather than pinning the generated string.

* fix(security): preserve literal backslashes in quoted script fields

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* test(security): cover changed guards and gate PR coverage

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* ci: measure committed PR changes on a policy-compliant runner

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* security: address review - nested cmd-sub/backtick handling, coverage gate, test skip

substitute_script_path() now follows the template's own $(...) and backtick
command substitutions as nested parsing contexts with their own quote state, so a
token placed inside one ("$(printf %s <field>)") is judged against that fresh
context instead of a suspended outer double quote. This closes the
nested-reinterpretation bypass where an escaped value sitting inside a command
substitution could be re-activated by an outer double quote. Backslash pairing in
both the unquoted and double-quoted contexts now also neutralizes $ and backtick,
so an escaped command substitution (\$(...) or \`...`) is not mis-detected as live.

.github/workflows/pr-changed-coverage.yml: drop the hard-coded PR-number
allowlist so the job runs whenever the path filter selects it, rather than
silently skipping every unlisted PR once these merge.

tests/Unit/Security/ShellInjection/ScriptFieldShellRoundTripTest.php: skip when
either exec() or proc_open() is unavailable (the test launches the fixture with
exec() while the fixture itself uses proc_open()). The fixture adds 7 nested
command-substitution and backtick round-trip cases (90 -> 97), each proving the
field value echoes back verbatim with nothing inside it executing.

* fix(security): clear quote-empty flag on single-quote content; cover new parser branches

The stack-based substitute_script_path() rewrite left quoteEmpty set while emitting literal content inside a single-quoted region, so a template like '\<field>' wrongly took the exact-wrap branch and dropped the backslash (ScriptSubstitutionMatrix 'shell 56'). Clear the frame's quoteEmpty whenever a single-quoted character is emitted, matching the pre-rewrite fallthrough.

ScriptSubstitutionMatrix.php: add 8 explicit parser cases exercising the \/backtick nested contexts and escaped \$ / backtick pairing so every rewritten line is covered by the changed-coverage probe (1285 -> 1293).

* style: short array syntax and php-cs-fixer formatting in substitute_script_path

* test(security): tolerate formatting in spikekill escaping contract

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(spikekill): bind menu requests and protect mutations on develop

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* test(spikekill): validate real CSRF tokens and inline coverage

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* ci(coverage): install locked dependencies for Symfony CSRF probes

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* perf(spikekill): skip disabled float debug formatting

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(spikekill): enforce mutation scope and propagate RRD failures

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(spikekill): escape repair notes and cover window boundaries

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* test: remove unused SpikeKill preference binding

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(security): reject unsupported nested shell grammar in #8237 (#8359)

* fix(security): reject unsupported nested shell grammar

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* test(security): exercise nested grammar rejection in CI coverage

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

---------

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(security): reject script fields in backtick substitutions

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* test: retain native security fixture evidence in changed coverage

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* fix(security): reject ambiguous shell expansion contexts

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>

* test(ssrf): assemble insecure manifest schemes at runtime

The SSRF negative-test inputs in PackageManifestMatrix.php are rejected by
the import preflight policy, but storing them as clear-text URL literals
(http://, ftp://, file://) tripped SonarCloud php:S5332 and dropped the
New Code security rating to B. Join the scheme separator at runtime so the
fixture no longer carries clear-text literals while the assembled values
keep the exact insecure schemes the policy must reject. All 32 manifest
cases still pass.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* fix(spikekill): drop dangling href in removeSpikes redirect check

The CSRF POST rewrite of removeSpikes replaced the GET href builder but
left checkForRedirects(data, href) referencing the now-undefined href,
throwing ReferenceError once a POST completed. Call checkForRedirects(data)
so a redirect response reloads (a POST has no GET href to follow).

Update the merged dom_dynamic_boundaries boundary test to exercise the
POST path: define csrfMagicToken and mock $.post instead of $.getJSON, so
it still verifies DOMPurify sanitization of spike results.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

---------

Signed-off-by: Thomas Vincent <thomasvincent@gmail.com>
Co-authored-by: TheWitness <copilot@users.noreply.github.com>
Co-authored-by: TheWitness <1439914+TheWitness@users.noreply.github.com>
Co-authored-by: Thomas Vincent <thomasvincent@gmail.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-03 13:43:12 -08:00

216 lines
12 KiB
Python

"""Regression tests for missing files and coverage threshold boundaries.
Copyright (C) 2004-2026 The Cacti Group. GPL-2.0-or-later.
"""
import importlib.util
import hashlib
import json
from pathlib import Path
import sys
import tempfile
import unittest
from unittest.mock import patch
import xml.etree.ElementTree as ET
sys.dont_write_bytecode = True
SPEC = importlib.util.spec_from_file_location(
'changed_php_coverage', Path(__file__).with_name('check_changed_php_coverage.py'))
GATE = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(GATE)
class ChangedPhpCoverageTest(unittest.TestCase):
def test_package_evidence_requires_both_scenarios_and_current_producers(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
producers = ['tests/fixtures/Core/PackageArchive.php', 'tests/Helpers/RequestCoverage.php']
hashes = {}
for name in producers:
source = root / name
source.parent.mkdir(parents=True, exist_ok=True)
source.write_text('fixture source\n')
hashes[name] = hashlib.sha256(source.read_bytes()).hexdigest()
contract = {'name': 'package-archive', 'complete': True, 'assertions': 2,
'producers': producers, 'hashes': hashes}
path = root / 'package-archive-test.json'
GATE.validate_package_contract({'contract': contract}, path, root)
for field in contract:
with self.subTest(missing=field), self.assertRaises(ValueError):
GATE.validate_package_contract({'contract': {k: v for k, v in contract.items() if k != field}}, path, root)
for count in [0, 1, 3, True, '2']:
with self.subTest(count=count), self.assertRaises(ValueError):
GATE.validate_package_contract({'contract': dict(contract, assertions=count)}, path, root)
with self.assertRaises(ValueError):
GATE.validate_package_contract({'contract': dict(contract, complete=False)}, path, root)
for name in producers:
with self.subTest(missing_producer=name), self.assertRaises(ValueError):
GATE.validate_package_contract({'contract': dict(contract, hashes={k: v for k, v in hashes.items() if k != name})}, path, root)
(root / name).write_text('changed source\n')
with self.subTest(stale=name), self.assertRaises(ValueError):
GATE.validate_package_contract({'contract': contract}, path, root)
(root / name).write_text('fixture source\n')
def test_diff_uses_merge_base_and_ignores_deletion_only_files(self):
diff = ('diff --git a/lib/a.php b/lib/a.php\n+++ b/lib/a.php\n'
'@@ -4,0 +5,2 @@\n+return true;\n+}\n'
'diff --git a/lib/b.php b/lib/b.php\n+++ b/lib/b.php\n'
'@@ -3 +2,0 @@\n-return false;\n')
with patch.object(GATE.subprocess, 'check_output', side_effect=['merge-base\n', diff]) as command:
self.assertEqual(GATE.added_lines('base', Path('.')), {'lib/a.php': {5, 6}})
self.assertIn('merge-base', command.call_args_list[1].args[0])
def test_missing_entrypoint_fails_even_if_library_is_fully_covered(self):
result = {'covered': 100, 'executable': 100, 'files': {
'lib/a.php': {'covered': 100}, 'plugins.php': {'missing': True}}}
self.assertFalse(GATE.passes(result, 80))
def test_threshold_does_not_round_a_failure_up_to_eighty(self):
self.assertFalse(GATE.passes({'covered': 7999, 'executable': 10000, 'files': {}}, 80))
self.assertTrue(GATE.passes({'covered': 80, 'executable': 100, 'files': {}}, 80))
def test_no_executable_changes_are_not_a_missing_report(self):
self.assertTrue(GATE.passes({'covered': 0, 'executable': 0, 'files': {}}, 80))
self.assertFalse(GATE.passes({'covered': 0, 'executable': 0, 'files': {
'plugins.php': {'missing': True}}}, 80))
def test_configuration_only_change_needs_no_clover_report(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
result = GATE.measure({}, root / 'not-created.xml', root)
self.assertTrue(GATE.passes(result, 80))
self.assertEqual(result['files'], {})
def test_deletion_only_changes_pass_without_a_coverage_report(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
result = GATE.measure({}, root / 'coverage-changed.xml', root)
self.assertEqual(result['executable'], 0)
self.assertTrue(GATE.passes(result, 80))
def test_clover_counts_only_statements_on_changed_lines(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
report = root / 'coverage.xml'
report.write_text(f'<coverage><project><file name="{root}/plugins.php">'
'<line num="3" type="method" count="1"/>'
'<line num="3" type="stmt" count="0"/>'
'<line num="4" type="stmt" count="2"/>'
'<line num="9" type="stmt" count="5"/>'
'</file></project></coverage>')
result = GATE.measure({'plugins.php': {3, 4, 5}}, report, root)
self.assertEqual(result['covered'], 1)
self.assertEqual(result['executable'], 2)
self.assertEqual(result['files']['plugins.php']['uncovered'], [3])
def test_config_keeps_tests_and_adds_entrypoints_to_source_scope(self):
with tempfile.TemporaryDirectory() as directory:
config = Path(directory) / 'input.xml'
output = Path(directory) / 'output.xml'
config.write_text('<phpunit bootstrap="tests/bootstrap-unit.php">'
'<testsuites><testsuite name="Unit"><directory>tests/Unit</directory>'
'</testsuite></testsuites><source><include><directory>lib</directory>'
'</include></source></phpunit>')
GATE.prepare_config(config, output, {'lib/plugins.php': {3}, 'plugins.php': {4}})
tree = ET.parse(output)
self.assertEqual(tree.getroot().attrib['bootstrap'], 'tests/bootstrap-unit.php')
self.assertEqual(tree.findtext('testsuites/testsuite/directory'), 'tests/Unit')
self.assertEqual([(output.parent / file.text).resolve() for file in tree.findall('source/include/file')],
[(Path.cwd() / name).resolve() for name in ['lib/plugins.php', 'plugins.php']])
def test_relocated_config_keeps_bootstrap_and_test_paths(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
tests = root / 'tests'
tests.mkdir()
config = tests / 'phpunit.xml'
output = root / 'phpunit-changed.xml'
config.write_text('<phpunit bootstrap="../tests/bootstrap-unit.php">'
'<testsuites><testsuite name="Unit">'
'<directory>../tests/Unit</directory>'
'</testsuite></testsuites></phpunit>')
GATE.prepare_config(config, output, {'lib/plugins.php': {3}})
tree = ET.parse(output)
self.assertEqual((output.parent / tree.getroot().get('bootstrap')).resolve(),
(tests / 'bootstrap-unit.php').resolve())
self.assertEqual((output.parent / tree.findtext('testsuites/testsuite/directory')).resolve(),
(tests / 'Unit').resolve())
def test_request_reports_require_matching_source_and_keep_uncovered_lines(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
source = root / 'plugins.php'
source.write_text('<?php\nreturn true;\n')
report = root / 'coverage.xml'
report.write_text(f'<coverage><project><file name="{source}">'
'<line num="2" type="stmt" count="0"/>'
'<line num="3" type="stmt" count="0"/>'
'</file></project></coverage>')
requests = root / 'requests'
requests.mkdir()
snapshot = {'root': '/var/www/html', 'coverage': {
'/var/www/html/plugins.php': {'2': 1}}, 'hashes': {
'/var/www/html/plugins.php': hashlib.sha256(source.read_bytes()).hexdigest()}}
(requests / 'one.json').write_text(json.dumps(snapshot))
result = GATE.measure({'plugins.php': {2, 3}}, report, root, requests)
self.assertEqual(result['covered'], 1)
self.assertEqual(result['executable'], 2)
self.assertEqual(result['files']['plugins.php']['uncovered'], [3])
source.write_text('<?php\nreturn false;\n')
with self.assertRaisesRegex(ValueError, 'source does not match'):
GATE.measure({'plugins.php': {2, 3}}, report, root, requests)
def test_missing_request_reports_do_not_pass(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
report = root / 'coverage.xml'
report.write_text('<coverage/>')
with self.assertRaisesRegex(ValueError, 'contains no reports'):
GATE.measure({}, report, root, root)
def test_bootstrap_instructions_remain_in_the_coverage_denominator(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
(root / 'include').mkdir()
source = root / 'include/global.php'
source.write_text('<?php\n$theme = "modern";\n$_SESSION["theme"] = $theme;\n')
report = root / 'coverage.xml'
report.write_text(f'<coverage><project><file name="{source}"/></project></coverage>')
result = GATE.measure({'include/global.php': {2, 3}}, report, root)
self.assertEqual(result['executable'], 2)
self.assertFalse(GATE.passes(result, 80))
requests = root / 'requests'
requests.mkdir()
snapshot = {'root': '/var/www/html', 'coverage': {
'/var/www/html/include/global.php': {'2': 1, '3': -1}}, 'hashes': {
'/var/www/html/include/global.php': hashlib.sha256(source.read_bytes()).hexdigest()}}
(requests / 'one.json').write_text(json.dumps(snapshot))
result = GATE.measure({'include/global.php': {2, 3}}, report, root, requests)
self.assertEqual(result['covered'], 1)
self.assertEqual(result['executable'], 2)
self.assertFalse(GATE.passes(result, 80))
def test_multiline_html_is_covered_only_when_its_output_opcode_runs(self):
with tempfile.TemporaryDirectory() as directory:
root = Path(directory)
source = root / 'page.php'
source.write_text('<?php ?>\n<header>\nName\n</header><?php return;\n')
report = root / 'coverage.xml'
report.write_text(f'<coverage><project><file name="{source}">'
'<line num="2" type="stmt" count="0"/>'
'</file></project></coverage>')
requests = root / 'requests'
requests.mkdir()
snapshot = {'root': '/var/www/html', 'coverage': {
'/var/www/html/page.php': {'4': -1}}, 'hashes': {
'/var/www/html/page.php': hashlib.sha256(source.read_bytes()).hexdigest()},
'html_spans': {'/var/www/html/page.php': [[2, 4]]}}
(requests / 'one.json').write_text(json.dumps(snapshot))
self.assertEqual(GATE.measure({'page.php': {2}}, report, root, requests)['covered'], 0)
snapshot['coverage']['/var/www/html/page.php']['4'] = 1
(requests / 'one.json').write_text(json.dumps(snapshot))
self.assertEqual(GATE.measure({'page.php': {2}}, report, root, requests)['covered'], 1)
if __name__ == '__main__':
unittest.main()