Skip to content

The agent that grows with you

fix(desktop-update): probe .cmd launchers through cmd.exe /d /s /c

Tekniuma9f8800511c3
diff --git a/scripts/desktop-update/runtime.ps1 b/scripts/desktop-update/runtime.ps1
index 69f236a6021..ad7756eed49 100644
--- a/scripts/desktop-update/runtime.ps1
+++ b/scripts/desktop-update/runtime.ps1
@@ -8,6 +8,17 @@ function Invoke-HermesProbe {
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $Exe
$psi.Arguments = (@($Arguments) | ForEach-Object { '"{0}"' -f ($_ -replace '"', '\"') }) -join ' '
+ # A command-file launcher runs through cmd.exe explicitly, exactly as the
+ # update step does: never hand CreateProcess a .cmd and let it pick an
+ # interpreter and re-parse the arguments (BatBadBut). cmd metacharacters
+ # that this quoting cannot neutralise are refused.
+ if ([IO.Path]::GetExtension($Exe) -in @('.cmd', '.bat')) {
+ if ($Exe -match '[%!"\x0D\x0A]' -or @($Arguments | Where-Object { $_ -match '[%!"\x0D\x0A]' }).Count) {
+ throw 'The legacy command launcher cannot safely quote this probe; refresh the installation launcher first.'
+ }
+ $psi.Arguments = '/d /s /c ""' + $Exe + '" ' + $psi.Arguments + '"'
+ $psi.FileName = if ($env:ComSpec) { $env:ComSpec } else { Join-Path $env:SystemRoot 'System32\cmd.exe' }
+ }
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $true
$psi.RedirectStandardInput = $true
diff --git a/tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py b/tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py
index 3bcef6043da..6b161549553 100644
--- a/tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py
+++ b/tests/scripts/desktop_update/test_desktop_update_windows_python_handoff.py
@@ -44,7 +44,7 @@ def test_pm_handoff_reports_update_and_gateway_results(
) -> None:
install = tmp_path / 'checkout with spaces'
publish_fixture_launcher(install, CLI)
- (install / 'hermes_cli/desktop_update_verify.py').write_text('pass\n')
+ (install / 'hermes_cli/desktop_update_verify.py').write_text('pass\n', encoding='utf-8')
home = tmp_path / 'profile'; home.mkdir()
calls = tmp_path / 'calls.jsonl'
command = ['powershell', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File',
@@ -64,7 +64,7 @@ def test_pm_handoff_reports_update_and_gateway_results(
+ ['--branch', 'main', '--keep-stash'], 'cwd': str(install)}]
if code == 0 and not no_gateway:
expected.append({'argv': ['gateway', 'start', '--all'], 'cwd': str(install)})
- assert [json.loads(line) for line in calls.read_text().splitlines()] == expected
+ assert [json.loads(line) for line in calls.read_text(encoding='utf-8-sig').splitlines()] == expected
receipt = json.loads((home / '.hermes-update-result.json').read_text(encoding='utf-8-sig'))
assert receipt['ok'] == (code == 0)
assert receipt.get('manual', False) == (code == 0 and not no_gateway and gateway_code != 0)
@@ -85,7 +85,7 @@ def test_update_killed_by_idle_watchdog_after_completing_is_a_success(
unless anything after its banner already reported a failure."""
install = tmp_path / 'checkout'
publish_fixture_launcher(install, CLI)
- (install / 'hermes_cli/desktop_update_verify.py').write_text('pass\n')
+ (install / 'hermes_cli/desktop_update_verify.py').write_text('pass\n', encoding='utf-8')
home = tmp_path / 'profile'; home.mkdir()
calls = tmp_path / 'calls.jsonl'
result = subprocess.run(
@@ -98,7 +98,7 @@ def test_update_killed_by_idle_watchdog_after_completing_is_a_success(
capture_output=True, text=True, timeout=180,
)
assert result.returncode == code, result.stdout + result.stderr
- argv = [json.loads(line)['argv'][:2] for line in calls.read_text().splitlines()]
+ argv = [json.loads(line)['argv'][:2] for line in calls.read_text(encoding='utf-8-sig').splitlines()]
assert argv == ([['update', '--yes'], ['gateway', 'start']] if code == 0 else [['update', '--yes']])
receipt = json.loads((home / '.hermes-update-result.json').read_text(encoding='utf-8-sig'))
assert receipt['ok'] == (code == 0)
@@ -125,3 +125,29 @@ def test_earlier_pm_userbin_launcher_is_identity_checked(tmp_path: Path) -> None
assert result.returncode == expected_code, result.stdout + result.stderr
if expected_code == 0:
assert json.loads(result.stdout) == str(external)
+
+
+def test_command_file_launcher_probe_runs_through_cmd_exe_explicitly(tmp_path: Path) -> None:
+ """A .cmd launcher probe goes through `cmd.exe /d /s /c` exactly like the update step,
+ never through CreateProcess's implicit batch handling; unquotable arguments are refused."""
+ bin_dir = tmp_path / 'launcher dir'; bin_dir.mkdir()
+ launcher = bin_dir / 'hermes.cmd'
+ launcher.write_text('@echo off\r\necho CMDLINE=%CMDCMDLINE%\r\necho ARGS=%*\r\n', encoding='ascii')
+ helper = str(ROOT / 'scripts/desktop-update/runtime.ps1').replace("'", "''")
+ target = str(launcher).replace("'", "''")
+
+ def probe(argument: str) -> subprocess.CompletedProcess:
+ script = (f". '{helper}'; try {{ $r = Invoke-HermesProbe '{target}' @('--version', '{argument}'); "
+ "[Console]::Out.Write(\"code=$($r.Code)`n$($r.Output)\") } catch { [Console]::Out.Write('refused'); exit 3 }")
+ return subprocess.run(['powershell', '-NoProfile', '-Command', script],
+ capture_output=True, text=True, timeout=60)
+
+ ok = probe('two words')
+ assert ok.returncode == 0, ok.stdout + ok.stderr
+ assert 'code=0' in ok.stdout, ok.stdout
+ cmdline = next(line for line in ok.stdout.splitlines() if line.startswith('CMDLINE='))
+ assert ' /d /s /c ' in cmdline.lower(), cmdline
+ assert 'ARGS="--version" "two words"' in ok.stdout, ok.stdout
+ bad = probe('100%PATH%')
+ assert (bad.returncode, bad.stdout) == (3, 'refused'), bad.stdout + bad.stderr