"""Tests for user-mode OSS CAD Suite bootstrap safety guards.""" from __future__ import annotations import contextlib import io import shutil import subprocess import sys import tempfile import unittest import zipfile from pathlib import Path from unittest import mock sys.dont_write_bytecode = True ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "tools")) import bootstrap_oss_cad_suite as bootstrap # noqa: E402 POWERSHELL = shutil.which("powershell.exe") def ps_literal(path: Path) -> str: return "'" + str(path).replace("'", "''") + "'" def run_powershell(command: str) -> subprocess.CompletedProcess[str]: if POWERSHELL is None: raise unittest.SkipTest("Windows PowerShell is unavailable") return subprocess.run( [POWERSHELL, "-NoProfile", "-NonInteractive", "-Command", command], cwd=ROOT, text=True, capture_output=True, check=False, timeout=60, ) class BootstrapOssCadSuiteTests(unittest.TestCase): def test_default_paths_use_path_home_not_administration_literal(self) -> None: for path in [bootstrap.DEFAULT_ROOT, bootstrap.DEFAULT_DOWNLOAD_DIR, bootstrap.DEFAULT_COCOTB_VENV]: self.assertIn(str(Path.home()), str(path)) self.assertNotIn(r"C:\Users\Administration", str(path)) self.assertEqual( bootstrap.DEFAULT_COCOTB_VENV.name, "prod2u-p4-actuator-trace-cocotb-venv", ) def test_tool_status_does_not_accept_extensionless_verilator_launcher(self) -> None: with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) bin_dir = root / "bin" bin_dir.mkdir() (bin_dir / "verilator").write_text("extensionless launcher", encoding="ascii") status = bootstrap.tool_status(root) self.assertEqual(status["tools"]["verilator"]["status"], "missing") self.assertIsNone(status["tools"]["verilator"]["path"]) def test_print_env_binds_native_verilator_before_exposing_toolchain_path(self) -> None: with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) bin_dir = root / "bin" lib_dir = root / "lib" bin_dir.mkdir() lib_dir.mkdir() verilator_root = root / "share" / "verilator" verilator_root.mkdir(parents=True) native = bin_dir / "verilator_bin.exe" native.write_bytes(b"MZnative") smtbmc = bin_dir / "yosys-smtbmc.exe.exe" smtbmc.write_bytes(b"MZsmtbmc") (bin_dir / "verilator").write_text( "extensionless launcher", encoding="ascii", ) stdout = io.StringIO() with contextlib.redirect_stdout(stdout): result = bootstrap.main( ["--install-root", str(root), "--print-env"] ) output = stdout.getvalue() output_lines = output.splitlines() self.assertEqual(result, 0) self.assertEqual(len(output_lines), 1) self.assertIn(str(bootstrap.ACTIVATION_SCRIPT), output_lines[0]) self.assertIn(str(root.resolve()), output_lines[0]) def test_print_env_runs_native_verilator_with_complete_runtime_environment(self) -> None: with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary: root = Path(temporary) / "suite" native = root / "bin" / "verilator_bin.exe" native.parent.mkdir(parents=True) (root / "lib").mkdir() verilator_root = root / "share" / "verilator" verilator_root.mkdir(parents=True) native.write_bytes(b"MZplaceholder") (root / "bin" / "yosys-smtbmc.exe.exe").write_bytes(b"MZsmtbmc") stdout = io.StringIO() with contextlib.redirect_stdout(stdout): bootstrap.main(["--install-root", str(root), "--print-env"]) env_commands = stdout.getvalue().rstrip() native.unlink() required_lib = str(root / "lib").replace('"', '""') required_verilator_root = str(verilator_root).replace('"', '""') command = f""" $ErrorActionPreference = "Stop" $source = @' using System; using System.IO; public static class FakeVerilator {{ public static int Main(string[] args) {{ string required = Path.GetFullPath(@"{required_lib}").TrimEnd('\\\\'); string requiredRoot = Path.GetFullPath(@"{required_verilator_root}").TrimEnd('\\\\'); string path = Environment.GetEnvironmentVariable("PATH") ?? ""; string configuredRoot = Environment.GetEnvironmentVariable("VERILATOR_ROOT") ?? ""; if (configuredRoot.Length == 0 || !String.Equals( Path.GetFullPath(configuredRoot).TrimEnd('\\\\'), requiredRoot, StringComparison.OrdinalIgnoreCase)) {{ Console.Error.WriteLine("VERILATOR_ROOT is missing or incorrect"); return 87; }} foreach (string entry in path.Split(';')) {{ if (entry.Length > 0 && String.Equals( Path.GetFullPath(entry).TrimEnd('\\\\'), required, StringComparison.OrdinalIgnoreCase)) {{ Console.WriteLine("Fake Verilator 1.0"); return 0; }} }} Console.Error.WriteLine("runtime library directory is missing from PATH"); return 86; }} }} '@ Add-Type -TypeDefinition $source -OutputAssembly {ps_literal(native)} -OutputType ConsoleApplication $envCommands = @' {env_commands} '@ Invoke-Expression $envCommands $resolved = Get-Command verilator -ErrorAction Stop Write-Output "resolved=$($resolved.Definition)" verilator --version $versionExit = $LASTEXITCODE Write-Output "version_exit=$versionExit" exit $versionExit """ completed = run_powershell(command) self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr) self.assertIn(f"resolved={native}", completed.stdout) self.assertIn("Fake Verilator 1.0", completed.stdout) def test_print_env_child_powershell_never_uses_extensionless_verilator(self) -> None: with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary: root = Path(temporary) / "suite" native = root / "bin" / "verilator_bin.exe" wrapper = root / "bin" / "verilator" child_script = Path(temporary) / "child-verilator-check.ps1" native.parent.mkdir(parents=True) (root / "lib").mkdir() (root / "share" / "verilator").mkdir(parents=True) native.write_bytes(b"MZplaceholder") wrapper.write_text("#!/usr/bin/env perl\n", encoding="ascii") (root / "bin" / "yosys-smtbmc.exe.exe").write_bytes(b"MZsmtbmc") child_script.write_text( """$ErrorActionPreference = "Stop" $resolved = Get-Command verilator -ErrorAction Stop if ([System.IO.Path]::GetFullPath($resolved.Definition) -eq [System.IO.Path]::GetFullPath($env:EXPECTED_UNSAFE_VERILATOR)) { Write-Error "child PowerShell resolved the extensionless Verilator wrapper" exit 91 } verilator --version exit $LASTEXITCODE """, encoding="utf-8-sig", ) stdout = io.StringIO() with contextlib.redirect_stdout(stdout): bootstrap.main(["--install-root", str(root), "--print-env"]) env_commands = stdout.getvalue().rstrip() native.unlink() command = f""" $ErrorActionPreference = "Stop" $source = @' using System; public static class FakeVerilator {{ public static int Main(string[] args) {{ Console.WriteLine("Fake Verilator 1.0"); return 0; }} }} '@ Add-Type -TypeDefinition $source -OutputAssembly {ps_literal(native)} -OutputType ConsoleApplication $envCommands = @' {env_commands} '@ Invoke-Expression $envCommands $env:EXPECTED_UNSAFE_VERILATOR = {ps_literal(wrapper)} & (Join-Path $PSHOME "powershell.exe") -NoProfile -NonInteractive -File {ps_literal(child_script)} exit $LASTEXITCODE """ completed = run_powershell(command) self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr) self.assertIn("Fake Verilator 1.0", completed.stdout) def test_print_env_is_idempotent_when_evaluated_repeatedly(self) -> None: with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary: root = Path(temporary) / "suite" native = root / "bin" / "verilator_bin.exe" native.parent.mkdir(parents=True) (root / "lib").mkdir() (root / "share" / "verilator").mkdir(parents=True) native.write_bytes(b"MZplaceholder") (root / "bin" / "yosys-smtbmc.exe.exe").write_bytes(b"MZsmtbmc") stdout = io.StringIO() with contextlib.redirect_stdout(stdout): bootstrap.main(["--install-root", str(root), "--print-env"]) env_commands = stdout.getvalue().rstrip() shim_dir = bootstrap.TOOLCHAIN_SHIM_DIR.resolve() command = f""" $envCommands = @' {env_commands} '@ Invoke-Expression $envCommands Invoke-Expression $envCommands $shim = [System.IO.Path]::GetFullPath({ps_literal(shim_dir)}) $count = @( $env:PATH -split ";" | Where-Object {{ $_ -and [System.IO.Path]::GetFullPath($_) -eq $shim }} ).Count Write-Output "shim_count=$count" """ completed = run_powershell(command) self.assertEqual(completed.returncode, 0, completed.stdout + completed.stderr) self.assertIn("shim_count=1", completed.stdout) def test_print_env_rejects_extensionless_only_verilator_before_path_output(self) -> None: with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) bin_dir = root / "bin" bin_dir.mkdir() (bin_dir / "verilator").write_text( "extensionless launcher", encoding="ascii", ) stdout = io.StringIO() with contextlib.redirect_stdout(stdout): with self.assertRaisesRegex(SystemExit, "native Verilator"): bootstrap.main( ["--install-root", str(root), "--print-env"] ) self.assertEqual(stdout.getvalue(), "") def test_print_env_rejects_incomplete_native_runtime_before_output(self) -> None: for missing in ("lib", "share"): with self.subTest(missing=missing), tempfile.TemporaryDirectory() as temporary: root = Path(temporary) bin_dir = root / "bin" bin_dir.mkdir() (bin_dir / "verilator_bin.exe").write_bytes(b"MZnative") if missing != "lib": (root / "lib").mkdir() if missing != "share": (root / "share" / "verilator").mkdir(parents=True) stdout = io.StringIO() with contextlib.redirect_stdout(stdout): with self.assertRaisesRegex(SystemExit, missing): bootstrap.main( ["--install-root", str(root), "--print-env"] ) self.assertEqual(stdout.getvalue(), "") def test_print_env_rejects_missing_smtbmc_before_output(self) -> None: with tempfile.TemporaryDirectory() as temporary: root = Path(temporary) bin_dir = root / "bin" bin_dir.mkdir() (bin_dir / "verilator_bin.exe").write_bytes(b"MZnative") (root / "lib").mkdir() (root / "share" / "verilator").mkdir(parents=True) stdout = io.StringIO() with contextlib.redirect_stdout(stdout): with self.assertRaisesRegex(SystemExit, "SMTBMC"): bootstrap.main( ["--install-root", str(root), "--print-env"] ) self.assertEqual(stdout.getvalue(), "") def test_safe_toolchain_root_rejects_workspace_root(self) -> None: with self.assertRaises(ValueError): bootstrap._assert_safe_toolchain_root(ROOT) def test_zip_extract_rejects_parent_traversal_member(self) -> None: with tempfile.TemporaryDirectory() as tmp: base = Path(tmp) / "CodexToolchains" / "CPLD" archive = Path(tmp) / "bad.zip" with zipfile.ZipFile(archive, "w") as zf: zf.writestr("../escape.txt", "bad") with mock.patch.object(bootstrap, "DEFAULT_TOOLCHAIN_BASE", base): with self.assertRaises(ValueError): bootstrap.extract_archive(archive, base / "oss-cad-suite" / "latest") def test_extract_archive_refuses_to_replace_unowned_install_root(self) -> None: with tempfile.TemporaryDirectory() as tmp: base = Path(tmp) / "CodexToolchains" / "CPLD" install_root = base / "oss-cad-suite" / "latest" install_root.mkdir(parents=True) archive = Path(tmp) / "tool.zip" with zipfile.ZipFile(archive, "w") as zf: zf.writestr("bin/iverilog.exe", "fake") with mock.patch.object(bootstrap, "DEFAULT_TOOLCHAIN_BASE", base): with self.assertRaises(RuntimeError): bootstrap.extract_archive(archive, install_root) def test_install_latest_writes_owner_marker_and_manifest(self) -> None: with tempfile.TemporaryDirectory() as tmp: base = Path(tmp) / "CodexToolchains" / "CPLD" download_dir = base / "downloads" archive = download_dir / "oss-cad-suite-windows-x64-test.exe" release = { "tag_name": "test", "assets": [ { "name": archive.name, "browser_download_url": "https://example.invalid/tool.exe", "size": 1, } ], } def fake_download(_url: str, output: Path) -> None: output.parent.mkdir(parents=True, exist_ok=True) output.write_text("fake sfx", encoding="utf-8") def fake_extract(_archive: Path, install_root: Path) -> None: (install_root / "bin").mkdir(parents=True, exist_ok=True) for tool in bootstrap.REQUIRED_TOOLS: (install_root / "bin" / f"{tool}.exe").write_text("fake", encoding="utf-8") with mock.patch.object(bootstrap, "DEFAULT_TOOLCHAIN_BASE", base): payload = bootstrap.install_latest_windows_x64( install_root=base / "oss-cad-suite" / "latest", download_dir=download_dir, release_payload=release, download_func=fake_download, extract_func=fake_extract, ) install_root = Path(payload["install_root"]) self.assertEqual(payload["status"], "present") self.assertTrue((install_root / bootstrap.OWNER_MARKER_NAME).is_file()) self.assertTrue((install_root / bootstrap.INSTALL_MANIFEST_NAME).is_file()) def test_install_cocotb_venv_installs_extended_user_mode_packages(self) -> None: with tempfile.TemporaryDirectory() as tmp: base = Path(tmp) / "CodexToolchains" / "CPLD" source_python = Path(tmp) / "python.exe" source_python.write_text("python", encoding="utf-8") venv_dir = base / "venvs" / "prod2u-p4-actuator-trace-cocotb-venv" venv_python = venv_dir / "Scripts" / "python.exe" commands: list[list[str]] = [] def fake_run_checked(cmd: list[str], **_kwargs): commands.append(cmd) if cmd[:3] == [str(source_python), "-m", "venv"]: venv_python.parent.mkdir(parents=True, exist_ok=True) venv_python.write_text("python", encoding="utf-8") if cmd[-1].startswith("import cocotb"): return mock.Mock(returncode=0, stdout=bootstrap.DEFAULT_COCOTB_VERSION + "\n", stderr="") return mock.Mock(returncode=0, stdout="", stderr="") with mock.patch.object(bootstrap, "DEFAULT_TOOLCHAIN_BASE", base), \ mock.patch.object(bootstrap, "run_checked", side_effect=fake_run_checked): payload = bootstrap.install_cocotb_venv(venv_dir=venv_dir, python_exe=source_python) install_commands = [" ".join(cmd) for cmd in commands if "install" in cmd] joined = "\n".join(install_commands) self.assertEqual(payload["status"], "present") self.assertIn("pytest", joined) self.assertIn("hypothesis", joined) self.assertIn("pyserial", joined) self.assertTrue((venv_dir / bootstrap.OWNER_MARKER_NAME).is_file()) self.assertTrue((venv_dir / bootstrap.INSTALL_MANIFEST_NAME).is_file()) def test_uninstall_owned_toolchain_dry_run_does_not_delete_marker_owned_root(self) -> None: with tempfile.TemporaryDirectory() as tmp: base = Path(tmp) / "CodexToolchains" / "CPLD" install_root = base / "oss-cad-suite" / "latest" install_root.mkdir(parents=True) bootstrap._write_owner_marker(install_root, "oss_cad_suite", {"test": True}) payload = bootstrap.uninstall_owned_toolchain(install_root=install_root, cocotb_venv=base / "venv", dry_run=True) self.assertEqual(payload["schema"], "offline-toolchain-uninstall-v1") self.assertEqual(payload["mode"], "dry_run") self.assertEqual(payload["status"], "pass") self.assertTrue(install_root.exists()) self.assertEqual(payload["targets"][0]["action"], "would_delete") def test_uninstall_owned_toolchain_refuses_unowned_path(self) -> None: with tempfile.TemporaryDirectory() as tmp: base = Path(tmp) / "CodexToolchains" / "CPLD" install_root = base / "oss-cad-suite" / "latest" install_root.mkdir(parents=True) payload = bootstrap.uninstall_owned_toolchain(install_root=install_root, cocotb_venv=base / "venv", dry_run=False) self.assertEqual(payload["status"], "blocked_not_owned") self.assertTrue(install_root.exists()) if __name__ == "__main__": unittest.main()