refactor(backend): standardize errors and simplify configuration and test setup

This commit is contained in:
TakuyaYagam1 committed 2026-10-05 16:15:30 +03:00
1 parent 1535c19b8c
commit 138666a7bb
92 files changed
+3994 -210

No files matched your search

+136
View File
@@ -0,0 +1,136 @@
"""Check installer integrity and scanner failure propagation without network access."""
import contextlib
import hashlib
import io
import json
import subprocess
import sys
import tarfile
import tempfile
import unittest
from pathlib import Path
from unittest.mock import patch
import install
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 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_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()