test_bootstrap_oss_cad_suite.py 18 KB

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