"""Windows activation-script guards for the local verification toolchain.""" from __future__ import annotations import json import base64 import re import shutil import os import subprocess import tempfile import unittest from pathlib import Path ROOT = Path(__file__).resolve().parents[2] ACTIVATION_SCRIPT = ROOT / "tools" / "activate_verification_toolchain.ps1" AGENT_INSTRUCTIONS = ROOT / "AGENTS.md" POWERSHELL = shutil.which("powershell.exe") CMD = shutil.which("cmd.exe") CMD_SHIM = ROOT / "tools" / "toolchain_shims" / "verilator.cmd" 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, ) def last_json_line(stdout: str) -> dict[str, object]: for line in reversed(stdout.splitlines()): if line.strip().startswith("{"): return json.loads(line) raise AssertionError(f"PowerShell output did not contain JSON:\n{stdout}") class ActivateVerificationToolchainTests(unittest.TestCase): def test_repository_instructions_require_a_native_verilator_entrypoint(self) -> None: instructions = AGENT_INSTRUCTIONS.read_text(encoding="utf-8") self.assertIn("tools/activate_verification_toolchain.ps1", instructions) self.assertIn("resolver", instructions) self.assertIn("Verilator", instructions) self.assertIn("PATH", instructions) def test_verilator_command_is_bound_to_native_windows_binary(self) -> None: source = ACTIVATION_SCRIPT.read_text(encoding="utf-8") self.assertIn('"verilator_bin.exe"', source) self.assertIn('"verilator.exe"', source) self.assertIn("$env:VERILATOR = $VerilatorNative", source) self.assertRegex( source, re.compile( r"Set-Alias\s+-Name\s+verilator\s+-Value\s+\$VerilatorNative" r"\s+-Scope\s+Global\s+-Force", re.IGNORECASE, ), ) def test_repeated_activation_runs_native_verilator_without_file_association(self) -> None: with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary: toolchain = Path(temporary) / "suite" native = toolchain / "bin" / "verilator_bin.exe" native.parent.mkdir(parents=True) command = f""" $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 & {ps_literal(ACTIVATION_SCRIPT)} -ToolchainRoot {ps_literal(toolchain)} & {ps_literal(ACTIVATION_SCRIPT)} -ToolchainRoot {ps_literal(toolchain)} $resolved = Get-Command verilator -ErrorAction Stop verilator --version $versionExit = $LASTEXITCODE [pscustomobject]@{{ command_type = [string]$resolved.CommandType definition = [string]$resolved.Definition env_verilator = [string]$env:VERILATOR version_exit = $versionExit }} | ConvertTo-Json -Compress """ completed = run_powershell(command) self.assertEqual(completed.returncode, 0, completed.stderr) payload = last_json_line(completed.stdout) self.assertEqual(payload["command_type"], "Alias") self.assertEqual(Path(str(payload["definition"])).resolve(), native.resolve()) self.assertEqual(Path(str(payload["env_verilator"])).resolve(), native.resolve()) self.assertEqual(payload["version_exit"], 0) self.assertIn("Fake Verilator 1.0", completed.stdout) def test_child_powershell_never_resolves_extensionless_verilator_wrapper(self) -> None: with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary: toolchain = Path(temporary) / "suite" native = toolchain / "bin" / "verilator_bin.exe" wrapper = toolchain / "bin" / "verilator" child_script = Path(temporary) / "child-verilator-check.ps1" native.parent.mkdir(parents=True) wrapper.write_text("#!/usr/bin/env perl\n", encoding="ascii") 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", ) 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 & {ps_literal(ACTIVATION_SCRIPT)} -ToolchainRoot {ps_literal(toolchain)} $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_child_powershell_preserves_verilator_metacharacters_and_exit_code(self) -> None: arguments = [ "--lint-only", r"C:\space dir\file.v", "D=100%", "bang!name", "caret^name", "paren(name)", "amp&name", ] expected = [ base64.b64encode(argument.encode("utf-8")).decode("ascii") for argument in arguments ] with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary: toolchain = Path(temporary) / "suite" native = toolchain / "bin" / "verilator_bin.exe" native.parent.mkdir(parents=True) child_script = Path(temporary) / "child-verilator-argv.ps1" child_script.write_text( r"""verilator '--lint-only' 'C:\space dir\file.v' 'D=100%' 'bang!name' 'caret^name' 'paren(name)' 'amp&name' exit $LASTEXITCODE """, encoding="utf-8-sig", ) command = f""" $ErrorActionPreference = "Stop" $source = @' using System; using System.Text; public static class FakeVerilator {{ public static int Main(string[] args) {{ foreach (string argument in args) {{ Console.WriteLine(Convert.ToBase64String(Encoding.UTF8.GetBytes(argument))); }} return 37; }} }} '@ Add-Type -TypeDefinition $source -OutputAssembly {ps_literal(native)} -OutputType ConsoleApplication & {ps_literal(ACTIVATION_SCRIPT)} -ToolchainRoot {ps_literal(toolchain)} & (Join-Path $PSHOME "powershell.exe") -NoProfile -NonInteractive -File {ps_literal(child_script)} exit $LASTEXITCODE """ completed = run_powershell(command) self.assertEqual(completed.returncode, 37, completed.stdout + completed.stderr) observed = [line.strip() for line in completed.stdout.splitlines() if line.strip() in expected] self.assertEqual(observed, expected) def test_child_powershell_rejects_verilator_target_outside_toolchain_root(self) -> None: with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary: root = Path(temporary) toolchain = root / "suite" native = toolchain / "bin" / "verilator_bin.exe" attacker = root / "attacker" / "verilator_bin.exe" native.parent.mkdir(parents=True) attacker.parent.mkdir(parents=True) child_script = root / "child-verilator-target.ps1" child_script.write_text( """$env:VERILATOR = $env:UNTRUSTED_VERILATOR verilator --version exit $LASTEXITCODE """, encoding="utf-8-sig", ) command = f""" $ErrorActionPreference = "Stop" $safeSource = @' using System; public static class SafeVerilator {{ public static int Main(string[] args) {{ return 0; }} }} '@ $attackerSource = @' using System; public static class AttackerVerilator {{ public static int Main(string[] args) {{ Console.WriteLine("UNTRUSTED_VERILATOR_EXECUTED"); return 0; }} }} '@ Add-Type -TypeDefinition $safeSource -OutputAssembly {ps_literal(native)} -OutputType ConsoleApplication Add-Type -TypeDefinition $attackerSource -OutputAssembly {ps_literal(attacker)} -OutputType ConsoleApplication & {ps_literal(ACTIVATION_SCRIPT)} -ToolchainRoot {ps_literal(toolchain)} $env:UNTRUSTED_VERILATOR = {ps_literal(attacker)} & (Join-Path $PSHOME "powershell.exe") -NoProfile -NonInteractive -File {ps_literal(child_script)} exit $LASTEXITCODE """ completed = run_powershell(command) self.assertNotEqual(completed.returncode, 0, completed.stdout + completed.stderr) self.assertNotIn("UNTRUSTED_VERILATOR_EXECUTED", completed.stdout) def test_extensionless_only_toolchain_fails_before_path_or_command_exposure(self) -> None: with tempfile.TemporaryDirectory(dir=ROOT.parent) as temporary: toolchain = Path(temporary) / "suite" wrapper = toolchain / "bin" / "verilator" wrapper.parent.mkdir(parents=True) wrapper.write_text("extensionless Perl wrapper", encoding="ascii") command = f""" $system32 = Join-Path $env:SystemRoot "System32" $env:PATH = "$system32;$env:SystemRoot" Remove-Item Env:VERILATOR -ErrorAction SilentlyContinue $beforePath = $env:PATH $caught = $null try {{ & {ps_literal(ACTIVATION_SCRIPT)} -ToolchainRoot {ps_literal(toolchain)} }} catch {{ $caught = $_.Exception.Message }} $resolved = Get-Command verilator -ErrorAction SilentlyContinue [pscustomobject]@{{ caught = [string]$caught path_unchanged = ($env:PATH -ceq $beforePath) command_found = ($null -ne $resolved) env_verilator = [string]$env:VERILATOR }} | ConvertTo-Json -Compress """ completed = run_powershell(command) self.assertEqual(completed.returncode, 0, completed.stderr) payload = last_json_line(completed.stdout) self.assertIn("native Verilator", str(payload["caught"])) self.assertTrue(payload["path_unchanged"]) self.assertFalse(payload["command_found"]) self.assertEqual(payload["env_verilator"], "") def test_cmd_verilator_shim_is_fail_closed_and_never_forwards_arguments(self) -> None: source = CMD_SHIM.read_text(encoding="ascii") self.assertNotIn("%*", source) if CMD is None: raise unittest.SkipTest("cmd.exe is unavailable") env = os.environ.copy() env["PATH"] = os.pathsep.join((str(CMD_SHIM.parent), env.get("PATH", ""))) completed = subprocess.run( [CMD, "/d", "/s", "/c", "verilator --version"], cwd=ROOT, env=env, text=True, capture_output=True, check=False, timeout=30, ) self.assertEqual(completed.returncode, 126, completed.stdout + completed.stderr) self.assertIn("supported only from PowerShell", completed.stderr) if __name__ == "__main__": unittest.main()