Skip to content

fix(source-control): bypass unsafe Windows batch shims - #11384

Open
bbingz wants to merge 1 commit into
stablyai:mainfrom
bbingz:fix/windows-batch-shim-argv
Open

bbingz wants to merge 1 commit into
stablyai:mainfrom
bbingz:fix/windows-batch-shim-argv

Conversation

@bbingz

@bbingz bbingz commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

When a Windows source-control agent or relay agent execution resolves to a batch shim, multiline or cmd-sensitive arguments currently fail the batch-argument safety check. These two paths now use an existing sibling .ps1 through powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File, passing the original arguments separately.

The fallback is opt-in. Safe batch arguments retain the existing cmd path; missing sibling PowerShell shims still reject unsafe arguments. Other callers, including external editors, Git and setup runners, retain their existing behavior. No -Command concatenation, temporary-script fallback or command-length expansion is introduced. The Windows overall command-line length ceiling remains a limitation.

Testing and review

At e551983779f5bc03743e0bcc66da300dda19deac, independent verification passed 172 tests across 19 files, including source-control subprocess planning, the Windows helper and relay agent execution. CLI, Node and Web TypeScript (--composite false), all changed-file lint/format, diff whitespace and native preflight/postflight passed. Two independent Cursor security reviews passed on this exact commit.

Tests cover opt-in scope, a sibling present with the default flag disabled, missing sibling rejection, fixed PowerShell flags and preservation of multiline/metacharacter arguments. Checks ran on macOS with platform-pinned tests. Actual Windows/SSH execution, full repository tests and packaging were not run on this commit. Earlier Windows field results in the discussion are historical, not validation inherited by this head.

AI disclosure

Cursor ported and independently security-reviewed the change. Codex independently checked the original scope, current code, reviewer transcripts and validation results.

Comment thread src/relay/agent-exec-handler.ts Resolved
Comment thread src/relay/agent-exec-handler.ts Resolved
@greptile-apps

greptile-apps Bot commented Jul 29, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR adds a safe Windows bypass for .cmd/.bat launchers when argv contains cmd.exe metacharacters (e.g. newlines in multiline prompts). It extracts the shim resolver into a new shared module (windows-powershell-shim-spawn.ts) used by both the local generation path and the SSH relay, directly addressing the previously flagged env-propagation and code-duplication issues.

  • New shared resolver (src/shared/windows-powershell-shim-spawn.ts): replaces the batch extension with .ps1, validates the sibling file exists, resolves powershell.exe from env.SystemRoot/env.WINDIR with a safe C:\Windows fallback, and returns null when no sibling is present so callers preserve their existing rejection behavior.
  • Opt-in local path (commit-message-text-generation.ts): passes allowPowerShellShimFallback: true and the merged spawnEnv into getSpawnArgsForWindows, enabling the shim for multiline staged diffs.
  • Always-on relay path (agent-exec-handler.ts): calls the shared resolver directly with the merged spawnEnv, keeping safe args on the existing cmd.exe route and unsafe args with no sibling on the existing rejection route.

Confidence Score: 5/5

Safe to merge — the new PowerShell shim path is opt-in on the local side and correctly isolated to Windows batch scripts with unsafe args on the relay side; all other platforms and safe-arg invocations are unaffected.

The two previously flagged issues (wrong env consulted for SystemRoot and duplicated shim logic) are both resolved by the shared module. The shim resolver uses only the caller-supplied env, validates SystemRoot as an absolute drive path, checks sibling existence before use, and falls back safely to the existing rejection when no .ps1 is present. Tests cover all key paths.

Files Needing Attention: No files require special attention.

Important Files Changed

Filename Overview
src/shared/windows-powershell-shim-spawn.ts New shared module that resolves a sibling .ps1 shim and builds PowerShell argv; correctly uses the passed env for SystemRoot, validates the path as an absolute drive root, and guards against a missing sibling.
src/shared/windows-batch-spawn.ts Adds opt-in allowPowerShellShimFallback + env options; on the first unsafe arg it tries the shared shim resolver before throwing, cleanly preserving the existing rejection path when no sibling .ps1 exists.
src/relay/agent-exec-handler.ts Relay's getWindowsSafeSpawn now delegates to the shared getWindowsPowerShellShimSpawn (with the merged spawnEnv) for unsafe args, fixing the previously flagged env-propagation gap and deduplication issue.
src/main/text-generation/commit-message-text-generation.ts Passes allowPowerShellShimFallback: true and the merged spawnEnv into getSpawnArgsForWindows so multiline prompts can use the PS1 shim path on Windows.
src/relay/agent-exec-handler-windows.test.ts Adds an end-to-end relay test: creates real .cmd/.ps1 temp files, sends multiline args over the relay handler, and asserts the resulting spawn targets the correct PowerShell path with the client-supplied SystemRoot.
src/main/text-generation/commit-message-text-generation.test.ts New integration test exercises the full local-generation path with a multiline staged patch, verifying the PS1 shim is selected and the prompt text reaches the last spawn argument.
src/main/win32-utils.test.ts Adds unit tests for both the safe-args cmd.exe path and the unsafe-args PowerShell shim fallback through getSpawnArgsForWindows, including SystemRoot propagation.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[Spawn request with binary + args] --> B{Windows platform?}
    B -- No --> Z[spawn binary directly]
    B -- Yes --> C[resolveWindowsCommand via PATH]
    C --> D{Is .cmd / .bat script?}
    D -- No --> Z
    D -- Yes --> E{Any unsafe batch metachar in command or args?}
    E -- No --> F[cmd.exe /d /c command args]
    E -- Yes --> G[getWindowsPowerShellShimSpawn: replace ext to .ps1]
    G --> H{sibling .ps1 exists on disk?}
    H -- Yes --> I[Build SystemRoot from env.SystemRoot/WINDIR, fallback C:\Windows]
    I --> J[powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File shim.ps1 args]
    H -- No --> K{allowPowerShellShimFallback path}
    K -- relay always-on --> L[fall through to quoteWindowsBatchToken, throws]
    K -- local opt-in fallback=false --> M[throw UnsafeWindowsBatchArgumentsError]
Loading

Reviews (7): Last reviewed commit: "style: format Windows shim tests" | Re-trigger Greptile

@coderabbitai

coderabbitai Bot commented Jul 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Important

Review skipped

We couldn't safely recover the incremental review. No full review was started, and the last reviewed checkpoint was preserved. Retry later, or explicitly request a full review by commenting @coderabbitai full review.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Windows batch execution now supports PowerShell shim fallback when arguments contain unsafe syntax. The fallback validates sibling .ps1 shims and preserves execution arguments. Agent execution and commit-message generation enable this behavior. Windows tests cover safe cmd.exe execution, multiline argument forwarding, PowerShell flags, and temporary shim cleanup.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly describes the main change: bypassing unsafe Windows batch shims.
Description check ✅ Passed The description covers the required sections, testing, cross-platform review, security audit, and platform-specific follow-up.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
src/relay/agent-exec-handler-windows.test.ts (1)

128-128: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Test doesn't actually discriminate the env vs. process.env bug.

Using env: { SystemRoot: 'C:\\Windows' } — the same value the code's hardcoded fallback would produce anyway — means this assertion passes even with the process.env-based bug flagged in getWindowsSafeSpawn (lines 66-85). Use a SystemRoot value that differs from the fallback default (e.g., 'D:\\Windows') to make this test actually catch the regression once fixed.

Also applies to: 136-136

src/main/text-generation/commit-message-text-generation.test.ts (1)

1742-1746: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Test doesn't discriminate the missing env forwarding.

The custom env.SystemRoot: 'C:\\Windows' matches the code's hardcoded fallback, so this test would still pass even with the env: spawnEnv omission flagged in commit-message-text-generation.ts (lines 581-583). Use a distinguishing SystemRoot value to make this assertion meaningful.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 6560e804-a33b-4d6e-9807-8c3e638ac998

📥 Commits

Reviewing files that changed from the base of the PR and between 4543bb6 and 1cc5c3a135e6f73d14504026f76ea926f0096f75.

📒 Files selected for processing (6)
  • src/main/text-generation/commit-message-text-generation.test.ts
  • src/main/text-generation/commit-message-text-generation.ts
  • src/main/win32-utils.test.ts
  • src/main/win32-utils.ts
  • src/relay/agent-exec-handler-windows.test.ts
  • src/relay/agent-exec-handler.ts

Comment thread src/main/win32-utils.ts Resolved
Comment thread src/relay/agent-exec-handler.ts Resolved
@iFwu

iFwu commented Jul 29, 2026

Copy link
Copy Markdown
Contributor

Thanks for putting this together. I tested this PR's head (86c3594676d5be7c644b5e0e655fcc4b8a751306) through Orca's real dev renderer IPC on Windows, using the actual cursor-agent.cmd with cursor-grok-4.5-high-fast.

Results:

  • main rejected a ~14.5K staged diff immediately as unsafe batch argv.
  • This PR completed the same case in ~12.1 seconds.
  • A ~28.9K staged diff also completed successfully in ~11.4 seconds.
  • Focused tests passed 81/81; typecheck:node and git diff --check also passed.

Process inspection confirmed that the sibling PowerShell shim was used:

powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File ...\cursor-agent.ps1

For completeness, a 31,605-character patch / 32,143-character prompt reached the Windows command-line limit and failed with spawn ENAMETOOLONG. Given that the ~28.9K staged diff succeeded end-to-end, I consider the fix validated for practical Orca workloads. The remaining argv length ceiling looks like a separate robustness improvement rather than a blocker for this PR.

@bbingz
bbingz force-pushed the fix/windows-batch-shim-argv branch 4 times, most recently from a720d0b to 5f2e399 Compare August 5, 2026 04:10
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 0cacec40-8440-4a91-9657-a3fccf6f19cf

📥 Commits

Reviewing files that changed from the base of the PR and between 9507cbc and 5f2e399e63c5440358a180a25f6a9c65d9190f8d.

📒 Files selected for processing (7)
  • src/main/text-generation/commit-message-text-generation.test.ts
  • src/main/text-generation/commit-message-text-generation.ts
  • src/main/win32-utils.test.ts
  • src/relay/agent-exec-handler-windows.test.ts
  • src/relay/agent-exec-handler.ts
  • src/shared/windows-batch-spawn.ts
  • src/shared/windows-powershell-shim-spawn.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/main/text-generation/commit-message-text-generation.ts
  • src/shared/windows-powershell-shim-spawn.ts
  • src/main/win32-utils.test.ts

@nwparker

Copy link
Copy Markdown
Contributor

I picked up #11374 from the issue queue, found this PR already open on the same seam, and stopped rather than open a competing one. Here is everything I worked out, so it is useful to you rather than duplicated.

Short version: the sibling-.ps1 seam is the right one. It is the only launch path that avoids the cmd.exe hop, and it is the only one with a confirmed end-to-end reproduction. Nothing below argues against it.

Confirming what this covers, with measurements

I measured the current main behaviour off a macOS host with process.platform pinned to win32, using Cursor's real spec argv (--print --mode ask --trust --output-format text --model auto <prompt>) against C:\Users\dev\AppData\Local\cursor-agent\cursor-agent.cmd:

input getSpawnArgsForWindows (today's path) buildWindowsCmdShimCommandLine (src/shared/child-process/windows-command-line.ts)
prompt with & | < > ^ " % !, no newline UNSAFE_WINDOWS_BATCH_ARGUMENTS accepted, 219-char line
prompt with a newline UNSAFE_WINDOWS_BATCH_ARGUMENTS cmd.exe cannot receive an argument containing a line break

Two things fall out of that:

  1. A large slice of Windows: Source Control AI cannot run argv-prompt agents through .cmd/.bat shims #11374 is fixable without any PowerShell at all. Any staged diff containing &, ", %, <, >, ^ or ! — which is most of them — is rejected today purely because src/main/text-generation/source-control-agent-launch.ts pre-wraps into cmd.exe /d /c … via getSpawnArgsForWindows before calling spawnProcess. spawnProcess already knows how to start a .cmd correctly: resolveSpawn routes it through buildWindowsCmdShimCommandLine, which encodes % as "^%", writes embedded quotes as "" to keep cmd's naive quote count even, and doubles backslash runs. Handing it resolvedBinary + args directly, instead of a pre-built cmd invocation, converts "reject on any metacharacter" into "reject only on CR/LF". That is a one-call change and it is orthogonal to your .ps1 work — worth folding in here if you want the win, since the child-process allowlist header already names Windows: Source Control AI cannot run argv-prompt agents through .cmd/.bat shims #11374 as one of the mangled-prompt regressions that module exists to prevent.

  2. The newline rejection is real and not fixable by better escaping. cmd's line parser ends the command at a raw CR or LF regardless of quote state, so the .ps1 seam is necessary, not merely nicer. That is the part your PR gets right.

The two gaps, precisely

Per @iFwu's live results and the scope note, this stays open for:

  • Cursor IDE's cursor.cmd, which ships no sibling cursor.ps1. Standalone cursor-agent has both; the IDE install has only the .cmd. No sibling means no launcher to fall back to.
  • Prompts near the Windows command-line ceiling. This one is worse than the docs suggest. I rebuilt the exact size @iFwu reported failing — a 31,605-char patch producing a 32,143-char prompt — and the resulting powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -File cursor-agent.ps1 <flags> <prompt> command line is 32,376 characters: 391 under the documented 32,767 CreateProcess ceiling, and it still produced spawn ENAMETOOLONG. So the effective ceiling sits below the documented one, which means a length guard cannot be derived analytically — you would be picking a fudge factor. That is what makes me think the prompt has to come off the command line entirely rather than be bounded on it.

A design for closing both, as a follow-up on top of this

Keep your sibling-.ps1 resolution exactly as it is — it stays the thing that decides what to launch. Change only how the argv reaches it: instead of -File <ps1> <args…>, generate a short temp PowerShell script that carries the whole argv inside itself, and run -File <temp.ps1> with no arguments at all.

$shim = [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('<b64 of the .ps1 path>'))
$argv = @(foreach ($item in @('<b64>','<b64>',…)) {
  [Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($item))
})
[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false
$OutputEncoding = [Console]::OutputEncoding
& $shim @argv
exit $LASTEXITCODE

Why base64 rather than quoting — this is the non-obvious part, and it is what makes the fix durable rather than another round of escaping whack-a-mole. Three separate parsers get a look at anything written on a Windows command line, and they disagree:

  • cmd.exe re-parses quoting for any .cmd/.bat target and expands %VAR% even inside a quoted token, so a \" written for one parser silently flips cmd's quote parity and turns every later & into an operator.
  • MSYS/Git Bash rewrites anything argument-shaped like /foo into a drive path — the same class of bug as [Bug]: Worktree "Local setup command" is built as a cmd.exe invocation on Windows — fails to run under the configured Git Bash shell #6896, where a bare cmd.exe /c from a bash pane became C:\... and cmd opened interactively instead of running the runner.
  • powershell.exe does its own parse of its raw command line for -File, which is not CommandLineToArgvW and is historically unreliable for arguments carrying embedded double quotes. Diff text carries embedded double quotes constantly.

Base64 sidesteps all three at once: every byte that reaches a command line is [A-Za-z0-9+/=], which no parser transforms. And because the payload lives in a file rather than on the command line, the 32,767 ceiling stops applying — the 32,143-char prompt that fails today becomes a ~43KB script file, which is nothing. The OutputEncoding lines are there because PowerShell re-emits a native command's stdout through the console code page, which mangles UTF-8 in commit messages.

This does not close the cursor.cmd-with-no-.ps1 gap — I could not find an honest way to close that one, since the shim is Cursor's own and there is no way to inject a multiline argument through it. That case may simply need resolveCliCommand to prefer a non-batch sibling, or an explicit "this launcher cannot carry the prompt" error naming the command override that works.

Caveats on all of the above

I have no Windows host. Everything above is either arithmetic, a platform-pinned unit measurement, or reasoning from the parser behaviour already documented in src/shared/child-process/windows-command-line.ts — the ENAMETOOLONG and the working .ps1 launch are @iFwu's field results, not mine. Someone with a real box should confirm the temp-script path before anyone commits to it.

Happy to build the follow-up once this lands, or to hand the design over if you would rather carry it yourself. Either way this PR is the dependency, not the competitor.

@bbingz

bbingz commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for stopping instead of opening a competing PR, and for writing the measurements down.

This PR stays the sibling-.ps1 dependency. I rechecked current origin/main (dd9eaa9585):

  • src/shared/windows-powershell-shim-spawn.ts still does not exist.
  • src/main/text-generation/source-control-agent-launch.ts still pre-wraps through getSpawnArgsForWindows before spawnProcess, so metacharacters without a newline are still UNSAFE_WINDOWS_BATCH_ARGUMENTS.
  • The newline case still has no launcher except a sibling .ps1.

So the seam you confirmed is still the one that needs to land. I am not opening another PR on it.

I am not folding extra work into this head right now. Head 59567e7270 is mergeable_state=dirty against current main: commit-message-text-generation.ts and its tests were split/rewritten, so a rebase is not mechanical. The PR is also assigned to @brennanb2025. I will not force-push a reconstructed patch over that.

On the two follow-ups:

  1. Hand resolvedBinary + args to spawnProcess instead of a pre-built cmd.exe /d /c line. Agreed, still true, and orthogonal. Same files as this PR, so I will not start a twin. Happy to fold it after this head is rebased onto current main, or to leave it for you / Brennan if you would rather take the rebase.

  2. Temp .ps1 with base64 argv, no prompt on the command line. Also agreed as a follow-up after this lands. I will not expand this PR into that. The cursor.cmd-with-no-sibling-.ps1 gap stays out of scope here, for the reason you gave.

@iFwu's live ENAMETOOLONG at ~32k remains the reproduction for follow-up (1) vs (2); I still do not have a Windows host to re-run it.

If you or Brennan would rather rebase this yourselves, I will stay comments-only. If you want me to port the sibling-.ps1 resolver onto current main without the temp-script work, say so and I will do that as an update to this PR, not a new one.

@bbingz
bbingz force-pushed the fix/windows-batch-shim-argv branch from 59567e7 to e551983 Compare September 8, 2026 22:32
@bbingz
bbingz force-pushed the fix/windows-batch-shim-argv branch from e551983 to 5dbfc6f Compare September 19, 2026 12:32
@bbingz
bbingz force-pushed the fix/windows-batch-shim-argv branch from 5dbfc6f to 8baf3a6 Compare September 19, 2026 12:37

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants