test_bootstrap_oss_cad_suite.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. """Tests for user-mode OSS CAD Suite bootstrap safety guards."""
  2. from __future__ import annotations
  3. import contextlib
  4. import io
  5. import shutil
  6. import subprocess
  7. import sys
  8. import tempfile
  9. import unittest
  10. import zipfile
  11. from pathlib import Path
  12. from unittest import mock
  13. sys.dont_write_bytecode = True
  14. ROOT = Path(__file__).resolve().parents[2]
  15. sys.path.insert(0, str(ROOT / "tools"))
  16. import bootstrap_oss_cad_suite as bootstrap # noqa: E402
  17. POWERSHELL = shutil.which("powershell.exe")
  18. def ps_literal(path: Path) -> str:
  19. return "'" + str(path).replace("'", "''") + "'"
  20. def run_powershell(command: str) -> subprocess.CompletedProcess[str]:
  21. if POWERSHELL is None:
  22. raise unittest.SkipTest("Windows PowerShell is unavailable")
  23. return subprocess.run(
  24. [POWERSHELL, "-NoProfile", "-NonInteractive", "-Command", command],
  25. cwd=ROOT,
  26. text=True,
  27. capture_output=True,
  28. check=False,
  29. timeout=60,
  30. )
  31. class BootstrapOssCadSuiteTests(unittest.TestCase):
  32. def test_default_paths_use_path_home_not_administration_literal(self) -> None:
  33. allowed_roots = {str(Path.home()), "/data/prod2u"}
  34. for path in [bootstrap.DEFAULT_ROOT, bootstrap.DEFAULT_DOWNLOAD_DIR, bootstrap.DEFAULT_COCOTB_VENV]:
  35. text = str(path)
  36. self.assertTrue(
  37. any(text.startswith(root) or root in text for root in allowed_roots),
  38. f"unexpected toolchain path {text}",
  39. )
  40. self.assertNotIn(r"C:\Users\Administration", text)
  41. self.assertEqual(
  42. bootstrap.DEFAULT_COCOTB_VENV.name,
  43. "prod2u-p4-actuator-trace-cocotb-venv",
  44. )
  45. def test_tool_status_does_not_accept_extensionless_verilator_launcher(self) -> None:
  46. with tempfile.TemporaryDirectory() as temporary:
  47. root = Path(temporary)
  48. bin_dir = root / "bin"
  49. bin_dir.mkdir()
  50. (bin_dir / "verilator").write_text("extensionless launcher", encoding="ascii")
  51. status = bootstrap.tool_status(root)
  52. self.assertEqual(status["tools"]["verilator"]["status"], "missing")
  53. self.assertIsNone(status["tools"]["verilator"]["path"])
  54. def test_print_env_binds_native_verilator_before_exposing_toolchain_path(self) -> None:
  55. with tempfile.TemporaryDirectory() as temporary:
  56. root = Path(temporary)
  57. bin_dir = root / "bin"
  58. lib_dir = root / "lib"
  59. bin_dir.mkdir()
  60. lib_dir.mkdir()
  61. verilator_root = root / "share" / "verilator"
  62. verilator_root.mkdir(parents=True)
  63. native = bin_dir / "verilator_bin.exe"
  64. native.write_bytes(b"MZnative")
  65. smtbmc = bin_dir / "yosys-smtbmc.exe.exe"
  66. smtbmc.write_bytes(b"MZsmtbmc")
  67. (bin_dir / "verilator").write_text(
  68. "extensionless launcher",
  69. encoding="ascii",
  70. )
  71. stdout = io.StringIO()
  72. with contextlib.redirect_stdout(stdout):
  73. result = bootstrap.main(
  74. ["--install-root", str(root), "--print-env"]
  75. )
  76. output = stdout.getvalue()
  77. output_lines = output.splitlines()
  78. self.assertEqual(result, 0)
  79. self.assertEqual(len(output_lines), 1)
  80. self.assertIn(str(bootstrap.ACTIVATION_SCRIPT), output_lines[0])
  81. self.assertIn(str(root.resolve()), output_lines[0])
  82. def test_print_env_runs_native_verilator_with_complete_runtime_environment(self) -> None:
  83. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  84. root = Path(temporary) / "suite"
  85. native = root / "bin" / "verilator_bin.exe"
  86. native.parent.mkdir(parents=True)
  87. (root / "lib").mkdir()
  88. verilator_root = root / "share" / "verilator"
  89. verilator_root.mkdir(parents=True)
  90. native.write_bytes(b"MZplaceholder")
  91. (root / "bin" / "yosys-smtbmc.exe.exe").write_bytes(b"MZsmtbmc")
  92. stdout = io.StringIO()
  93. with contextlib.redirect_stdout(stdout):
  94. bootstrap.main(["--install-root", str(root), "--print-env"])
  95. env_commands = stdout.getvalue().rstrip()
  96. native.unlink()
  97. required_lib = str(root / "lib").replace('"', '""')
  98. required_verilator_root = str(verilator_root).replace('"', '""')
  99. command = f"""
  100. $ErrorActionPreference = "Stop"
  101. $source = @'
  102. using System;
  103. using System.IO;
  104. public static class FakeVerilator {{
  105. public static int Main(string[] args) {{
  106. string required = Path.GetFullPath(@"{required_lib}").TrimEnd('\\\\');
  107. string requiredRoot = Path.GetFullPath(@"{required_verilator_root}").TrimEnd('\\\\');
  108. string path = Environment.GetEnvironmentVariable("PATH") ?? "";
  109. string configuredRoot = Environment.GetEnvironmentVariable("VERILATOR_ROOT") ?? "";
  110. if (configuredRoot.Length == 0 ||
  111. !String.Equals(
  112. Path.GetFullPath(configuredRoot).TrimEnd('\\\\'),
  113. requiredRoot,
  114. StringComparison.OrdinalIgnoreCase)) {{
  115. Console.Error.WriteLine("VERILATOR_ROOT is missing or incorrect");
  116. return 87;
  117. }}
  118. foreach (string entry in path.Split(';')) {{
  119. if (entry.Length > 0 && String.Equals(
  120. Path.GetFullPath(entry).TrimEnd('\\\\'),
  121. required,
  122. StringComparison.OrdinalIgnoreCase)) {{
  123. Console.WriteLine("Fake Verilator 1.0");
  124. return 0;
  125. }}
  126. }}
  127. Console.Error.WriteLine("runtime library directory is missing from PATH");
  128. return 86;
  129. }}
  130. }}
  131. '@
  132. Add-Type -TypeDefinition $source -OutputAssembly {ps_literal(native)} -OutputType ConsoleApplication
  133. $envCommands = @'
  134. {env_commands}
  135. '@
  136. Invoke-Expression $envCommands
  137. $resolved = Get-Command verilator -ErrorAction Stop
  138. Write-Output "resolved=$($resolved.Definition)"
  139. verilator --version
  140. $versionExit = $LASTEXITCODE
  141. Write-Output "version_exit=$versionExit"
  142. exit $versionExit
  143. """
  144. completed = run_powershell(command)
  145. self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
  146. self.assertIn(f"resolved={native}", completed.stdout)
  147. self.assertIn("Fake Verilator 1.0", completed.stdout)
  148. def test_print_env_child_powershell_never_uses_extensionless_verilator(self) -> None:
  149. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  150. root = Path(temporary) / "suite"
  151. native = root / "bin" / "verilator_bin.exe"
  152. wrapper = root / "bin" / "verilator"
  153. child_script = Path(temporary) / "child-verilator-check.ps1"
  154. native.parent.mkdir(parents=True)
  155. (root / "lib").mkdir()
  156. (root / "share" / "verilator").mkdir(parents=True)
  157. native.write_bytes(b"MZplaceholder")
  158. wrapper.write_text("#!/usr/bin/env perl\n", encoding="ascii")
  159. (root / "bin" / "yosys-smtbmc.exe.exe").write_bytes(b"MZsmtbmc")
  160. child_script.write_text(
  161. """$ErrorActionPreference = "Stop"
  162. $resolved = Get-Command verilator -ErrorAction Stop
  163. if ([System.IO.Path]::GetFullPath($resolved.Definition) -eq
  164. [System.IO.Path]::GetFullPath($env:EXPECTED_UNSAFE_VERILATOR)) {
  165. Write-Error "child PowerShell resolved the extensionless Verilator wrapper"
  166. exit 91
  167. }
  168. verilator --version
  169. exit $LASTEXITCODE
  170. """,
  171. encoding="utf-8-sig",
  172. )
  173. stdout = io.StringIO()
  174. with contextlib.redirect_stdout(stdout):
  175. bootstrap.main(["--install-root", str(root), "--print-env"])
  176. env_commands = stdout.getvalue().rstrip()
  177. native.unlink()
  178. command = f"""
  179. $ErrorActionPreference = "Stop"
  180. $source = @'
  181. using System;
  182. public static class FakeVerilator {{
  183. public static int Main(string[] args) {{
  184. Console.WriteLine("Fake Verilator 1.0");
  185. return 0;
  186. }}
  187. }}
  188. '@
  189. Add-Type -TypeDefinition $source -OutputAssembly {ps_literal(native)} -OutputType ConsoleApplication
  190. $envCommands = @'
  191. {env_commands}
  192. '@
  193. Invoke-Expression $envCommands
  194. $env:EXPECTED_UNSAFE_VERILATOR = {ps_literal(wrapper)}
  195. & (Join-Path $PSHOME "powershell.exe") -NoProfile -NonInteractive -File {ps_literal(child_script)}
  196. exit $LASTEXITCODE
  197. """
  198. completed = run_powershell(command)
  199. self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
  200. self.assertIn("Fake Verilator 1.0", completed.stdout)
  201. def test_print_env_is_idempotent_when_evaluated_repeatedly(self) -> None:
  202. with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary:
  203. root = Path(temporary) / "suite"
  204. native = root / "bin" / "verilator_bin.exe"
  205. native.parent.mkdir(parents=True)
  206. (root / "lib").mkdir()
  207. (root / "share" / "verilator").mkdir(parents=True)
  208. native.write_bytes(b"MZplaceholder")
  209. (root / "bin" / "yosys-smtbmc.exe.exe").write_bytes(b"MZsmtbmc")
  210. stdout = io.StringIO()
  211. with contextlib.redirect_stdout(stdout):
  212. bootstrap.main(["--install-root", str(root), "--print-env"])
  213. env_commands = stdout.getvalue().rstrip()
  214. shim_dir = bootstrap.TOOLCHAIN_SHIM_DIR.resolve()
  215. command = f"""
  216. $envCommands = @'
  217. {env_commands}
  218. '@
  219. Invoke-Expression $envCommands
  220. Invoke-Expression $envCommands
  221. $shim = [System.IO.Path]::GetFullPath({ps_literal(shim_dir)})
  222. $count = @(
  223. $env:PATH -split ";" |
  224. Where-Object {{ $_ -and [System.IO.Path]::GetFullPath($_) -eq $shim }}
  225. ).Count
  226. Write-Output "shim_count=$count"
  227. """
  228. completed = run_powershell(command)
  229. self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr)
  230. self.assertIn("shim_count=1", completed.stdout)
  231. def test_print_env_rejects_extensionless_only_verilator_before_path_output(self) -> None:
  232. with tempfile.TemporaryDirectory() as temporary:
  233. root = Path(temporary)
  234. bin_dir = root / "bin"
  235. bin_dir.mkdir()
  236. (bin_dir / "verilator").write_text(
  237. "extensionless launcher",
  238. encoding="ascii",
  239. )
  240. stdout = io.StringIO()
  241. with contextlib.redirect_stdout(stdout):
  242. with self.assertRaisesRegex(SystemExit, "native Verilator"):
  243. bootstrap.main(
  244. ["--install-root", str(root), "--print-env"]
  245. )
  246. self.assertEqual(stdout.getvalue(), "")
  247. def test_print_env_rejects_incomplete_native_runtime_before_output(self) -> None:
  248. for missing in ("lib", "share"):
  249. with self.subTest(missing=missing), tempfile.TemporaryDirectory() as temporary:
  250. root = Path(temporary)
  251. bin_dir = root / "bin"
  252. bin_dir.mkdir()
  253. (bin_dir / "verilator_bin.exe").write_bytes(b"MZnative")
  254. if missing != "lib":
  255. (root / "lib").mkdir()
  256. if missing != "share":
  257. (root / "share" / "verilator").mkdir(parents=True)
  258. stdout = io.StringIO()
  259. with contextlib.redirect_stdout(stdout):
  260. with self.assertRaisesRegex(SystemExit, missing):
  261. bootstrap.main(
  262. ["--install-root", str(root), "--print-env"]
  263. )
  264. self.assertEqual(stdout.getvalue(), "")
  265. def test_print_env_rejects_missing_smtbmc_before_output(self) -> None:
  266. with tempfile.TemporaryDirectory() as temporary:
  267. root = Path(temporary)
  268. bin_dir = root / "bin"
  269. bin_dir.mkdir()
  270. (bin_dir / "verilator_bin.exe").write_bytes(b"MZnative")
  271. (root / "lib").mkdir()
  272. (root / "share" / "verilator").mkdir(parents=True)
  273. stdout = io.StringIO()
  274. with contextlib.redirect_stdout(stdout):
  275. with self.assertRaisesRegex(SystemExit, "SMTBMC"):
  276. bootstrap.main(
  277. ["--install-root", str(root), "--print-env"]
  278. )
  279. self.assertEqual(stdout.getvalue(), "")
  280. def test_safe_toolchain_root_rejects_workspace_root(self) -> None:
  281. with self.assertRaises(ValueError):
  282. bootstrap._assert_safe_toolchain_root(ROOT)
  283. def test_zip_extract_rejects_parent_traversal_member(self) -> None:
  284. with tempfile.TemporaryDirectory() as tmp:
  285. base = Path(tmp) / "CodexToolchains" / "CPLD"
  286. archive = Path(tmp) / "bad.zip"
  287. with zipfile.ZipFile(archive, "w") as zf:
  288. zf.writestr("../escape.txt", "bad")
  289. with mock.patch.object(bootstrap, "DEFAULT_TOOLCHAIN_BASE", base):
  290. with self.assertRaises(ValueError):
  291. bootstrap.extract_archive(archive, base / "oss-cad-suite" / "latest")
  292. def test_extract_archive_refuses_to_replace_unowned_install_root(self) -> None:
  293. with tempfile.TemporaryDirectory() as tmp:
  294. base = Path(tmp) / "CodexToolchains" / "CPLD"
  295. install_root = base / "oss-cad-suite" / "latest"
  296. install_root.mkdir(parents=True)
  297. archive = Path(tmp) / "tool.zip"
  298. with zipfile.ZipFile(archive, "w") as zf:
  299. zf.writestr("bin/iverilog.exe", "fake")
  300. with mock.patch.object(bootstrap, "DEFAULT_TOOLCHAIN_BASE", base):
  301. with self.assertRaises(RuntimeError):
  302. bootstrap.extract_archive(archive, install_root)
  303. def test_install_latest_writes_owner_marker_and_manifest(self) -> None:
  304. with tempfile.TemporaryDirectory() as tmp:
  305. base = Path(tmp) / "CodexToolchains" / "CPLD"
  306. download_dir = base / "downloads"
  307. archive = download_dir / "oss-cad-suite-windows-x64-test.exe"
  308. release = {
  309. "tag_name": "test",
  310. "assets": [
  311. {
  312. "name": archive.name,
  313. "browser_download_url": "https://example.invalid/tool.exe",
  314. "size": 1,
  315. }
  316. ],
  317. }
  318. def fake_download(_url: str, output: Path) -> None:
  319. output.parent.mkdir(parents=True, exist_ok=True)
  320. output.write_text("fake sfx", encoding="utf-8")
  321. def fake_extract(_archive: Path, install_root: Path) -> None:
  322. (install_root / "bin").mkdir(parents=True, exist_ok=True)
  323. for tool in bootstrap.REQUIRED_TOOLS:
  324. (install_root / "bin" / f"{tool}.exe").write_text("fake", encoding="utf-8")
  325. with mock.patch.object(bootstrap, "DEFAULT_TOOLCHAIN_BASE", base):
  326. payload = bootstrap.install_latest_windows_x64(
  327. install_root=base / "oss-cad-suite" / "latest",
  328. download_dir=download_dir,
  329. release_payload=release,
  330. download_func=fake_download,
  331. extract_func=fake_extract,
  332. )
  333. install_root = Path(payload["install_root"])
  334. self.assertEqual(payload["status"], "present")
  335. self.assertTrue((install_root / bootstrap.OWNER_MARKER_NAME).is_file())
  336. self.assertTrue((install_root / bootstrap.INSTALL_MANIFEST_NAME).is_file())
  337. def test_install_cocotb_venv_installs_extended_user_mode_packages(self) -> None:
  338. with tempfile.TemporaryDirectory() as tmp:
  339. base = Path(tmp) / "CodexToolchains" / "CPLD"
  340. source_python = Path(tmp) / "python.exe"
  341. source_python.write_text("python", encoding="utf-8")
  342. venv_dir = base / "venvs" / "prod2u-p4-actuator-trace-cocotb-venv"
  343. venv_python = venv_dir / "Scripts" / "python.exe"
  344. commands: list[list[str]] = []
  345. def fake_run_checked(cmd: list[str], **_kwargs):
  346. commands.append(cmd)
  347. if cmd[:3] == [str(source_python), "-m", "venv"]:
  348. venv_python.parent.mkdir(parents=True, exist_ok=True)
  349. venv_python.write_text("python", encoding="utf-8")
  350. if cmd[-1].startswith("import cocotb"):
  351. return mock.Mock(returncode=0, stdout=bootstrap.DEFAULT_COCOTB_VERSION + "\n", stderr="")
  352. return mock.Mock(returncode=0, stdout="", stderr="")
  353. with mock.patch.object(bootstrap, "DEFAULT_TOOLCHAIN_BASE", base), \
  354. mock.patch.object(bootstrap, "run_checked", side_effect=fake_run_checked):
  355. payload = bootstrap.install_cocotb_venv(venv_dir=venv_dir, python_exe=source_python)
  356. install_commands = [" ".join(cmd) for cmd in commands if "install" in cmd]
  357. joined = "\n".join(install_commands)
  358. self.assertEqual(payload["status"], "present")
  359. self.assertIn("pytest", joined)
  360. self.assertIn("hypothesis", joined)
  361. self.assertIn("pyserial", joined)
  362. self.assertTrue((venv_dir / bootstrap.OWNER_MARKER_NAME).is_file())
  363. self.assertTrue((venv_dir / bootstrap.INSTALL_MANIFEST_NAME).is_file())
  364. def test_uninstall_owned_toolchain_dry_run_does_not_delete_marker_owned_root(self) -> None:
  365. with tempfile.TemporaryDirectory() as tmp:
  366. base = Path(tmp) / "CodexToolchains" / "CPLD"
  367. install_root = base / "oss-cad-suite" / "latest"
  368. install_root.mkdir(parents=True)
  369. bootstrap._write_owner_marker(install_root, "oss_cad_suite", {"test": True})
  370. payload = bootstrap.uninstall_owned_toolchain(install_root=install_root, cocotb_venv=base / "venv", dry_run=True)
  371. self.assertEqual(payload["schema"], "offline-toolchain-uninstall-v1")
  372. self.assertEqual(payload["mode"], "dry_run")
  373. self.assertEqual(payload["status"], "pass")
  374. self.assertTrue(install_root.exists())
  375. self.assertEqual(payload["targets"][0]["action"], "would_delete")
  376. def test_uninstall_owned_toolchain_refuses_unowned_path(self) -> None:
  377. with tempfile.TemporaryDirectory() as tmp:
  378. base = Path(tmp) / "CodexToolchains" / "CPLD"
  379. install_root = base / "oss-cad-suite" / "latest"
  380. install_root.mkdir(parents=True)
  381. payload = bootstrap.uninstall_owned_toolchain(install_root=install_root, cocotb_venv=base / "venv", dry_run=False)
  382. self.assertEqual(payload["status"], "blocked_not_owned")
  383. self.assertTrue(install_root.exists())
  384. if __name__ == "__main__":
  385. unittest.main()