Files
lincodex/security/tests/test_checks.py
T

497 lines
21 KiB
Python

"""Check installer integrity and scanner failure propagation without network access."""
import contextlib
import hashlib
import io
import json
import os
import re
import secrets
import subprocess
import sys
import tarfile
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
import install
import scan_inputs
SECURITY = Path(__file__).resolve().parents[1]
class SecurityChecksTest(unittest.TestCase):
def setUp(self) -> None:
cache = SECURITY / ".cache"
cache.mkdir(exist_ok=True)
self.temporary = tempfile.TemporaryDirectory(prefix="checks-", dir=cache)
self.addCleanup(self.temporary.cleanup)
self.folder = Path(self.temporary.name)
def _init_git_repo(self, root: Path) -> None:
root.mkdir(parents=True, exist_ok=True)
subprocess.run(["git", "init", str(root)], check=True, capture_output=True)
identity = (
("user.name", "Security Test"),
("user.email", "security-test@example.invalid"),
)
for key, value in identity:
subprocess.run(
["git", "-C", str(root), "config", key, value],
check=True,
capture_output=True,
)
def _commit(self, root: Path) -> None:
subprocess.run(["git", "-C", str(root), "add", "-A"], check=True, capture_output=True)
subprocess.run(
["git", "-C", str(root), "commit", "-m", "fixture"],
check=True,
capture_output=True,
)
def _run_gitleaks_make(
self,
root: Path,
reports: Path,
scanner: Path,
*,
config: Path | None = None,
) -> subprocess.CompletedProcess[str]:
env = os.environ.copy()
env.setdefault("TMPDIR", str(self.folder))
return subprocess.run(
[
"make",
"-C",
str(SECURITY),
"secrets",
f"ROOT={root}",
f"REPORTS={reports}",
f"GITLEAKS={scanner}",
f"GITLEAKS_CONFIG={config or SECURITY / 'gitleaks/gitleaks.toml'}",
],
env=env,
capture_output=True,
text=True,
check=False,
)
def test_current_input_copy_keeps_tracked_ignored_files_and_skips_unsafe_inputs(self) -> None:
root = self.folder / "copy-repo"
self._init_git_repo(root)
(root / ".gitignore").write_text(".env\nignored-*\n", encoding="utf-8")
(root / "tracked.txt").write_text("tracked fixture\n", encoding="utf-8")
(root / ".env").write_text("tracked ignored fixture\n", encoding="utf-8")
(root / "deleted.txt").write_text("deleted fixture\n", encoding="utf-8")
outside = self.folder / "outside.txt"
outside.write_text("outside fixture\n", encoding="utf-8")
(root / "outside-link").symlink_to(outside)
subprocess.run(
[
"git",
"-C",
str(root),
"add",
".gitignore",
"tracked.txt",
"deleted.txt",
"outside-link",
],
check=True,
capture_output=True,
)
subprocess.run(
["git", "-C", str(root), "add", "-f", ".env"],
check=True,
capture_output=True,
)
self._commit(root)
(root / "deleted.txt").unlink()
(root / "incoming $(touch marker).txt").write_text(
"untracked fixture\n", encoding="utf-8"
)
(root / "ignored-local.txt").write_text("ignored fixture\n", encoding="utf-8")
fifo = root / "untracked-pipe"
if hasattr(os, "mkfifo"):
os.mkfifo(fifo)
destination = self.folder / "private-scan"
destination.mkdir(mode=0o700)
os.chmod(destination, 0o700)
copied = scan_inputs.copy_git_inputs(root, destination)
self.assertGreater(copied, 0)
self.assertTrue((destination / ".env").is_file())
self.assertTrue((destination / "incoming $(touch marker).txt").is_file())
self.assertFalse((destination / "ignored-local.txt").exists())
self.assertFalse((destination / "deleted.txt").exists())
self.assertFalse((destination / "outside-link").exists())
self.assertFalse((self.folder / "marker").exists())
if hasattr(os, "mkfifo"):
self.assertFalse((destination / "untracked-pipe").exists())
self.assertEqual((destination / ".env").stat().st_mode & 0o777, 0o600)
self.assertEqual(destination.stat().st_mode & 0o777, 0o700)
self.assertEqual(outside.read_text(encoding="utf-8"), "outside fixture\n")
def test_gitleaks_reports_findings_and_keeps_full_history_scan(self) -> None:
scanner = SECURITY / ".bin" / "gitleaks"
if not scanner.is_file():
self.skipTest("local Gitleaks binary is not installed")
root = self.folder / "scan-repo"
self._init_git_repo(root)
(root / ".gitignore").write_text(".env\n", encoding="utf-8")
(root / ".env").write_text(
"API_KEY=synthetic" + secrets.token_hex(24) + "\n", encoding="utf-8"
)
subprocess.run(
["git", "-C", str(root), "add", ".gitignore"],
check=True,
capture_output=True,
)
subprocess.run(
["git", "-C", str(root), "add", "-f", ".env"],
check=True,
capture_output=True,
)
self._commit(root)
(root / "incoming $(touch marker).txt").write_text(
"API_KEY=synthetic" + secrets.token_hex(24) + "\n", encoding="utf-8"
)
outside = self.folder / "outside-secret.txt"
outside.write_text(
"API_KEY=synthetic" + secrets.token_hex(24) + "\n", encoding="utf-8"
)
(root / "outside-link").symlink_to(outside)
reports = self.folder / "gitleaks-reports"
result = self._run_gitleaks_make(root, reports, scanner)
self.assertNotEqual(result.returncode, 0)
current = json.loads((reports / "gitleaks-files.json").read_text(encoding="utf-8"))
history = json.loads((reports / "gitleaks-history.json").read_text(encoding="utf-8"))
current_paths = {item["File"] for item in current}
history_paths = {item["File"] for item in history}
self.assertIn(".env", current_paths)
self.assertIn("incoming $(touch marker).txt", current_paths)
self.assertNotIn("outside-link", current_paths)
self.assertIn(".env", history_paths)
self.assertFalse((self.folder / "marker").exists())
self.assertEqual((reports / "gitleaks-files.json").stat().st_mode & 0o777, 0o600)
(root / "incoming $(touch marker).txt").unlink()
subprocess.run(
["git", "-C", str(root), "rm", "--cached", ".env"],
check=True,
capture_output=True,
)
(root / ".env").write_text(
"API_KEY=synthetic" + secrets.token_hex(24) + "\n", encoding="utf-8"
)
result = self._run_gitleaks_make(root, reports, scanner)
self.assertNotEqual(result.returncode, 0)
current = json.loads((reports / "gitleaks-files.json").read_text(encoding="utf-8"))
history = json.loads((reports / "gitleaks-history.json").read_text(encoding="utf-8"))
self.assertEqual(current, [])
self.assertIn(".env", {item["File"] for item in history})
def test_gitleaks_allowlist_requires_exact_path_match_and_rule(self) -> None:
scanner = SECURITY / ".bin" / "gitleaks"
if not scanner.is_file():
self.skipTest("local Gitleaks binary is not installed")
allowed_path = Path("deploy/scripts/test_release_manifest.py")
config_text = (SECURITY / "gitleaks/gitleaks.toml").read_text(encoding="utf-8")
exception = next(
section
for section in config_text.split("[[allowlists]]")
if "test_release_manifest" in section
)
regex_section = exception.split("regexes = [", 1)[1].split("]", 1)[0]
regex_match = re.search(r'^\s*"([^"\n]+)"', regex_section, flags=re.MULTILINE)
self.assertIsNotNone(regex_match)
pattern = regex_match.group(1)
self.assertTrue(pattern.startswith("^") and pattern.endswith("$"))
fixture_line = pattern[1:-1]
self.assertTrue(fixture_line.startswith("AKIA") and fixture_line.isalnum())
source = (SECURITY.parent / allowed_path).read_text(encoding="utf-8")
self.assertTrue(fixture_line in source)
root = self.folder / "allowlist-repo"
self._init_git_repo(root)
(root / "clean.txt").write_text("clean history fixture\n", encoding="utf-8")
self._commit(root)
(root / allowed_path).parent.mkdir(parents=True)
changed_fixture = fixture_line[:-1] + ("Z" if fixture_line[-1] != "Z" else "Y")
(root / allowed_path).write_text(
fixture_line
+ "\n"
+ changed_fixture
+ "\n",
encoding="utf-8",
)
(root / "unrelated.txt").write_text(fixture_line + "\n", encoding="utf-8")
config = self.folder / "target-rule-config.toml"
config.write_text(
config_text
+ "\n[[rules]]\n"
+ 'id = "fixture-literal"\n'
+ 'description = "Test rule for allowlist target scope"\n'
+ f"regex = '''(?m)^{fixture_line}$'''\n"
+ "secretGroup = 0\n"
+ 'keywords = ["AKIA"]\n',
encoding="utf-8",
)
reports = self.folder / "allowlist-reports"
result = self._run_gitleaks_make(root, reports, scanner, config=config)
self.assertNotEqual(result.returncode, 0)
current = json.loads((reports / "gitleaks-files.json").read_text(encoding="utf-8"))
finding_pairs = {(item["RuleID"], item["File"]) for item in current}
allowed_name = allowed_path.as_posix()
self.assertIn(("aws-access-token", allowed_name), finding_pairs)
self.assertIn(("aws-access-token", "unrelated.txt"), finding_pairs)
self.assertIn(("fixture-literal", allowed_name), finding_pairs)
self.assertIn(("fixture-literal", "unrelated.txt"), finding_pairs)
allowed_rule_count = sum(
item["RuleID"] == "aws-access-token" and item["File"] == allowed_name
for item in current
)
self.assertEqual(allowed_rule_count, 1)
def test_gitleaks_missing_malformed_nonzero_and_nonempty_reports_fail(self) -> None:
root = self.folder / "fake-scan-repo"
self._init_git_repo(root)
(root / "clean.txt").write_text("clean fixture\n", encoding="utf-8")
self._commit(root)
for mode in ("missing", "malformed", "nonzero", "finding"):
with self.subTest(mode=mode):
scanner = self.folder / f"scanner-{mode}"
scanner.write_text(
f"#!{sys.executable}\n"
"import json, sys\n"
"from pathlib import Path\n"
f"mode = {mode!r}\n"
"args = sys.argv[1:]\n"
"if args == ['version']:\n"
" print('synthetic scanner')\n"
" raise SystemExit(0)\n"
"report_path = Path(args[args.index('--report-path') + 1])\n"
"if args[0] == 'dir' and mode == 'missing':\n"
" raise SystemExit(0)\n"
"if args[0] == 'dir' and mode == 'malformed':\n"
" report_path.write_text('{', encoding='utf-8')\n"
" raise SystemExit(0)\n"
"if args[0] == 'dir' and mode == 'nonzero':\n"
" report_path.write_text('[]', encoding='utf-8')\n"
" raise SystemExit(17)\n"
"if args[0] == 'dir' and mode == 'finding':\n"
" report_path.write_text(\n"
" json.dumps([{'RuleID': 'generic-api-key', 'File': 'fixture.txt'}]),\n"
" encoding='utf-8'\n"
" )\n"
" raise SystemExit(0)\n"
"report_path.write_text('[]', encoding='utf-8')\n"
"raise SystemExit(0)\n",
encoding="utf-8",
)
scanner.chmod(0o700)
reports = self.folder / f"reports-{mode}"
reports.mkdir()
for name in ("gitleaks-files.json", "gitleaks-history.json"):
(reports / name).write_text("stale report", encoding="utf-8")
result = self._run_gitleaks_make(root, reports, scanner)
self.assertNotEqual(result.returncode, 0)
self.assertTrue((reports / "gitleaks-version.txt").is_file())
def test_installer_rejects_checksum_mismatch_without_replacing_binary(self) -> None:
binary_dir = self.folder / ".bin"
binary_dir.mkdir()
existing = binary_dir / "trivy"
existing.write_bytes(b"existing tool")
responses = [
json.dumps({"tag_name": "v1.2.3"}).encode(),
("0" * 64 + " trivy_1.2.3_Linux-64bit.tar.gz\n").encode(),
b"download with an incorrect checksum",
]
with (
patch.object(sys, "argv", ["install.py", "trivy"]),
patch.object(install, "__file__", str(self.folder / "install.py")),
patch.object(install.platform, "system", return_value="Linux"),
patch.object(install.platform, "machine", return_value="x86_64"),
patch.object(install, "download", side_effect=responses),
self.assertRaisesRegex(ValueError, "SHA256 verification failed"),
):
install.main()
self.assertEqual(existing.read_bytes(), b"existing tool")
def test_installer_writes_only_the_verified_executable(self) -> None:
archive = io.BytesIO()
payload = b"synthetic executable fixture"
with tarfile.open(fileobj=archive, mode="w:gz") as bundle:
member = tarfile.TarInfo("trivy")
member.size = len(payload)
bundle.addfile(member, io.BytesIO(payload))
data = archive.getvalue()
responses = [
json.dumps({"tag_name": "v1.2.3"}).encode(),
(
hashlib.sha256(data).hexdigest() + " trivy_1.2.3_Linux-64bit.tar.gz\n"
).encode(),
data,
]
with (
patch.object(sys, "argv", ["install.py", "trivy"]),
patch.object(install, "__file__", str(self.folder / "install.py")),
patch.object(install.platform, "system", return_value="Linux"),
patch.object(install.platform, "machine", return_value="x86_64"),
patch.object(install, "download", side_effect=responses),
contextlib.redirect_stdout(io.StringIO()),
):
install.main()
executable = self.folder / ".bin" / "trivy"
self.assertEqual(executable.read_bytes(), payload)
self.assertEqual(executable.stat().st_mode & 0o777, 0o755)
def test_go_scan_preserves_failure_through_report_pipeline(self) -> None:
scanner = self.folder / "scanner"
for code in (0, 3, 17):
with self.subTest(exit_code=code):
scanner.write_text(
"#!/usr/bin/env bash\n"
'if [ "$1" = -version ]; then exit 0; fi\n'
'echo "Synthetic scan result"\n'
f"exit {code}\n"
)
scanner.chmod(0o700)
reports = self.folder / "reports"
result = subprocess.run(
["make", "go", f"GOVULNCHECK={scanner}", f"REPORTS={reports}"],
cwd=SECURITY,
capture_output=True,
text=True,
check=False,
)
self.assertEqual(result.returncode == 0, code == 0, result.stderr)
self.assertEqual(
(reports / "govulncheck.txt").read_text(), "Synthetic scan result\n"
)
def test_trivy_reports_are_visible_without_masking_failures(self) -> None:
cases = [
("clean", 0, 0, True, True),
("findings", 1, 0, True, False),
("scan_error", 17, 0, False, False),
("conversion_error", 0, 7, True, False),
("both_errors", 17, 7, True, False),
("missing_report", 0, 0, False, False),
]
docker = self.folder / "docker"
docker.write_text(
"#!/usr/bin/env bash\n"
'if [ "$1" = build ]; then exit 0; fi\n'
'if [ "$1" = image ]; then echo sha256:fixture; exit 0; fi\n'
"exit 2\n"
)
docker.chmod(0o700)
for target in ("filesystem", "images"):
for name, scan_code, convert_code, write_report, success in cases:
with self.subTest(target=target, case=name):
reports = self.folder / f"{target}-{name}"
scanner = self.folder / "trivy"
scanner.write_text(
f"#!{sys.executable}\n"
"import json, sys\n"
"from pathlib import Path\n"
"args = sys.argv[1:]\n"
"if '--version' in args: sys.exit(0)\n"
"if args[0] == 'convert':\n"
" assert args[1:3] == ['--format', 'table']\n"
" assert args[3:5] == ['--scanners', 'vuln,misconfig']\n"
" report = json.loads(Path(args[-1]).read_text())\n"
f" if {convert_code}:\n"
" print('Report conversion failed', file=sys.stderr)\n"
f" sys.exit({convert_code})\n"
" print('Scan table:', report['result'])\n"
" sys.exit(0)\n"
"assert args[0] in ('fs', 'image')\n"
f"if {write_report}:\n"
" output = Path(args[args.index('--output') + 1])\n"
" output.write_text(json.dumps({'result': "
f"{'HIGH CVE-2099-0001' if scan_code else 'No findings'!r}}}))\n"
f"sys.exit({scan_code})\n"
)
scanner.chmod(0o700)
result = subprocess.run(
[
"make",
target,
f"TRIVY={scanner}",
f"DOCKER={docker}",
f"REPORTS={reports}",
],
cwd=SECURITY,
capture_output=True,
text=True,
check=False,
)
self.assertEqual(result.returncode == 0, success, result.stderr)
report_count = 1 if target == "filesystem" else 3
self.assertEqual(
len(list(reports.glob("trivy-*.json"))),
report_count if write_report else 0,
)
if write_report and not convert_code:
self.assertEqual(result.stdout.count("Scan table:"), report_count)
self.assertIn(
"HIGH CVE-2099-0001" if scan_code else "No findings",
result.stdout,
)
else:
self.assertNotIn("Scan table:", result.stdout)
if write_report and convert_code:
self.assertIn("Report conversion failed", result.stderr)
if scan_code and target == "filesystem":
self.assertIn(f"Error {scan_code}", result.stderr)
def test_failed_preflight_removes_previous_scan_reports(self) -> None:
outputs = {
"filesystem": ["trivy-filesystem.json"],
"secrets": ["gitleaks-files.json", "gitleaks-history.json"],
"go": ["govulncheck.txt"],
"semgrep": ["semgrep.json"],
"images": ["trivy-ml.json", "ml-image-id.txt"],
}
for target, filenames in outputs.items():
with self.subTest(target=target):
reports = self.folder / target
reports.mkdir()
for filename in filenames:
(reports / filename).write_text("previous result")
result = subprocess.run(
[
"make",
target,
f"REPORTS={reports}",
f"ROOT={self.folder}",
"TRIVY=/nonexistent/scanner",
"SEMGREP=/nonexistent/scanner",
"GOVULNCHECK=/nonexistent/scanner",
],
cwd=SECURITY,
capture_output=True,
text=True,
check=False,
)
self.assertNotEqual(result.returncode, 0)
for filename in filenames:
self.assertFalse((reports / filename).exists(), filename)
if __name__ == "__main__":
unittest.main()