Files
orca/src/shared/setup-runner-command.test.ts
T
OrcaWinandOrca Worker cff202c16a fix(windows): drop EDR-flagged -ExecutionPolicy Bypass from encoded PowerShell (#17880)
* fix(windows): drop EDR-flagged -ExecutionPolicy Bypass from encoded PowerShell

MDE flags `-ExecutionPolicy Bypass` paired with base64 `-EncodedCommand` as a
behavioural signal. Measured on Windows 11: neither `-Command` nor
`-EncodedCommand` is execution-policy gated (both run under an explicit
`-ExecutionPolicy Restricted` and `AllSigned`; only `-File` fails), so the
switch was a pure no-op on every one of these command lines.

Removes the switch from all four sites that spelled it, and de-encodes the one
site whose payload never passes through a re-parsing shell:

- ssh-remote-powershell: one chokepoint for ~40 remote-Windows call sites.
  Base64 kept — the remote sshd DefaultShell re-parses this string.
- setup-agent-sequencing / windows-cmd-runner-delayed-launch: base64 kept —
  these strings are typed into a terminal pane.
- windows-interactive-login-spawn: base64 kept — `cmd.exe /c start` re-parses,
  and the cmd-safe-token guard rejects the `&` and `"` in the raw relay script.
- windows-mobile-firewall local runner: `-EncodedCommand` -> `-Command`, since
  execFile reaches CreateProcess with no shell in between.

The setup startup gate keeps execution-policy relief in-payload (process scope),
because it evals a user-authored startup command that may invoke a `.ps1`, and a
`.ps1` IS gated. Caught by the real-process suite; mirrors the agent-hooks
launcher's trade.

The elevated firewall child deliberately stays encoded: `Start-Process
-ArgumentList` joins its array into one ShellExecuteEx string without quoting
and PowerShell re-splits on whitespace, measured to collapse `C:\My  App\...`
to `C:\My App\...` — a firewall rule for the wrong program.

* test(ssh): enforce the no-script-file invariant remote payloads rely on

Dropping `-ExecutionPolicy Bypass` from `powerShellCommand` is a no-op only
while no remote payload loads a PowerShell script file — execution policy has
never gated anything else. That invariant held by inspection and was guarded by
nothing, so a future payload that dot-sourced, used `-File`, or imported a
`.psm1` would break only on a remote host with a Restricted/AllSigned
LocalMachine policy and no GPO: a failure on someone else's machine.

States the invariant at the wrapper, and adds a ratchet that scans every module
importing it for `.ps1`/`.psm1`, `Import-Module`, `-File`, and dot-sourcing.
The scan discovers importers itself (13 today) so new ones are covered, and
asserts it found some, so an emptied list cannot pass vacuously.

Mutation-checked: injecting each construct into a real importer fails the
matching case and names the file. The first dot-source pattern passed a
`;`-prefixed sample but missed `powerShellCommand(". '$x'")` — the likelier
shape — so the pattern now accepts a string-literal start and the self-test
samples carry their surrounding quotes.

* test(ssh): close two blind spots in the remote-payload ratchet

Both found by independent mutation testing of the ratchet itself, and both let
a real violation pass while the guard reported green.

`-File` was matched case-sensitively, so `-file $scriptVar` slipped through —
PowerShell switches are case-insensitive, and with a variable path the `.ps1`
pattern does not cover for it, so that shape escaped both nets. The naive fix
is wrong: bare /-File\b/i matches `--credential-file`, `--log-file` and
`--body-file`, which occur in three of these importers. Anchoring to a token
boundary catches the lowercase, odd-spacing and argv-element forms with zero
offenders across all 14.

Comment stripping paired a `/*` appearing inside a string (a glob such as
'src/*.ts') with any later comment close and deleted everything between, hiding
violations in the gap. Anchoring the block strip to line start, as the `//`
strip already was, fixes it — verified by injecting an `Import-Module` after a
glob string: the unanchored form misses it, the anchored form catches it.

Extends the same case-insensitivity to `.ps1`/`.psm1` and `Import-Module`,
which had the identical flaw (`import-module`, `DEPLOY.PS1` are legitimate
spellings); measured to add no false positive.

Each construct now carries the fixtures it must catch AND the near-misses it
must not, so a future tightening cannot quietly trade one for the other — the
negative fixtures are what would have caught the naive `-File` fix. Non-vacuity
bound tightened to >10 against 14 importers.

* docs(ssh): state what the remote-payload ratchet cannot see

The scan matches source text, so a script file reached only through a variable
(`& $scriptPath`) never appears in source and no pattern can catch it. The
ratchet narrows the hole; the invariant note on `powerShellCommand` covers the
remainder.

Recorded because a guard that reads as complete coverage when it is not is
worse than one that states its edge: the next author trusts it further than it
deserves, and should learn this limit from the test rather than an incident.

* test(ssh): scan remote payloads with the shared source walk

The ratchet had its own tree walk and comment stripper. The walk skipped
neither node_modules/dist/.git nor dot-directories and excluded tests by
`.test.ts` alone, so its importer count -- the guard's own goalpost -- could
be wrong about what it scanned. The stripper was anchored to line start to
dodge a `/*` inside a glob string, which silently skipped trailing comments;
`stripComments` tracks quote state and handles both.

Importer set re-derived against the shared walk: 15, floor unchanged at 10.

* fix(setup): report a failed execution-policy relief instead of swallowing it

The in-payload Set-ExecutionPolicy carried -ErrorAction SilentlyContinue and
an empty catch, so any failure vanished. A Windows PowerShell 5.1 install with
duplicate extended type data fails every cmdlet in Microsoft.PowerShell.Security
-- autoload, not policy -- and the user then saw only their own .ps1 being
refused, with no trace that the relief had been attempted or why.

-ErrorAction Stop is what routes a non-terminating failure into the catch at
all; the catch reports the FullyQualifiedErrorId to stderr and deliberately
does not rethrow, so a broken policy cmdlet cannot take down the startup this
gate exists to run. Success path is unchanged and stays stderr-clean.

Verified by execution on a clean child environment: success -> policy=Bypass,
stderr empty; shadowed failing cmdlet -> diagnostic on stderr and the gate
still continues; the old empty catch -> silent.

---------

Co-authored-by: Orca Worker <orca-worker@localhost>
2026-09-05 21:12:40 -07:00

248 lines
9.2 KiB
TypeScript

import { describe, expect, it } from 'vitest'
import {
buildSetupRunnerCommand,
getSetupRunnerCommandPlatformForPath,
nativeWindowsPathToPosixShellPath,
resolveSetupRunnerCommand
} from './setup-runner-command'
describe('buildSetupRunnerCommand', () => {
it('uses bash for WSL UNC runner scripts regardless of host casing', () => {
expect(
buildSetupRunnerCommand(
'\\\\WSL.LOCALHOST\\Ubuntu\\home\\jin\\repo\\.git\\worktrees\\feature\\orca\\setup-runner.sh',
'windows'
)
).toBe('bash /home/jin/repo/.git/worktrees/feature/orca/setup-runner.sh')
})
it('uses bash with Linux paths for forward-slash WSL UNC runner scripts', () => {
expect(
buildSetupRunnerCommand(
'//wsl.localhost/Ubuntu/home/jin/repo/.git/worktrees/feature/orca/setup-runner.sh',
'windows'
)
).toBe('bash /home/jin/repo/.git/worktrees/feature/orca/setup-runner.sh')
})
it('keeps generic forward-slash UNC runner scripts on cmd.exe', () => {
expect(
buildSetupRunnerCommand('//server/share/repo/.git/orca/setup-runner.cmd', 'windows')
).toBe('cmd.exe /c "//server/share/repo/.git/orca/setup-runner.cmd"')
})
it('uses POSIX launch semantics for native Windows runners when the setup shell is POSIX', () => {
expect(
buildSetupRunnerCommand('C:\\repo\\.git\\orca\\setup-runner.sh', 'windows', {
family: 'posix'
})
).toBe('bash /c/repo/.git/orca/setup-runner.sh')
})
it('uses the active WSL shell with WSL paths for native Windows POSIX runners', () => {
expect(
buildSetupRunnerCommand('C:\\repo\\.git\\orca\\setup-runner.sh', 'windows', {
family: 'posix',
executable: 'wsl.exe'
})
).toBe('bash /mnt/c/repo/.git/orca/setup-runner.sh')
})
it('keeps cmd.exe launch semantics for cmd setup runners', () => {
expect(
buildSetupRunnerCommand('C:\\repo\\.git\\orca\\setup-runner.cmd', 'windows', {
family: 'cmd'
})
).toBe('cmd.exe /c "C:\\repo\\.git\\orca\\setup-runner.cmd"')
})
it('infers generated POSIX runner shell semantics from extension when metadata is absent', () => {
expect(buildSetupRunnerCommand('C:\\repo\\.git\\orca\\setup-runner.sh', 'windows')).toBe(
'bash /c/repo/.git/orca/setup-runner.sh'
)
})
it('never hands a batch runner to bash, even from a Git Bash pane', () => {
// Regression: a Git Bash terminal with a batch-syntax setup script gets a .cmd runner,
// so the launch shell being POSIX must not be read as "the runner is a shell script".
const command = buildSetupRunnerCommand('C:\\repo\\.git\\orca\\setup-runner.cmd', 'windows', {
family: 'posix'
})
expect(command).not.toContain('bash ')
expect(command).not.toContain('/c/repo')
})
it('avoids the bare /c switch when a POSIX pane launches a batch runner', () => {
// Regression (#6896): MSYS rewrites `cmd.exe /c` into a drive path inside Git Bash, so cmd
// opens interactively and the runner payload never executes.
const command = buildSetupRunnerCommand('C:\\repo\\.git\\orca\\setup-runner.cmd', 'windows', {
family: 'posix'
})
expect(command).not.toContain('cmd.exe /c')
expect(command).toMatch(
/^powershell\.exe -NoProfile -NonInteractive -EncodedCommand [A-Za-z0-9+/=]+$/
)
})
it('keeps the batch runner path in native form for a POSIX pane launch', () => {
// Why: the PowerShell launcher hands the path to cmd, which cannot read /c/... MSYS paths;
// marker and completion paths derive from this value too.
expect(
resolveSetupRunnerCommand('C:\\repo\\.git\\orca\\setup-runner.cmd', 'windows', {
family: 'posix'
})
).toMatchObject({
runnerScriptPathForShell: 'C:\\repo\\.git\\orca\\setup-runner.cmd',
shell: 'windows'
})
})
it('still uses bash for a POSIX runner launched from a POSIX pane', () => {
expect(
buildSetupRunnerCommand('C:\\repo\\.git\\orca\\setup-runner.sh', 'windows', {
family: 'posix'
})
).toBe('bash /c/repo/.git/orca/setup-runner.sh')
})
})
describe('buildSetupRunnerCommand cmd metacharacter guard', () => {
const cmdRunner = (segment: string) => `C:\\repo${segment}\\.git\\orca\\setup-runner.cmd`
const decodePowerShellCommand = (command: string): string => {
const encoded = command.match(/-EncodedCommand (\S+)$/)?.[1]
expect(encoded).toBeTruthy()
const bytes = atob(encoded as string)
let decoded = ''
for (let index = 0; index < bytes.length; index += 2) {
decoded += String.fromCharCode(bytes.charCodeAt(index) | (bytes.charCodeAt(index + 1) << 8))
}
return decoded
}
it.each(['%', '&', '|', '<', '>', '^', '(', ')', '!', ',', ';', '=', '$', '`'])(
'hardens the launch when the runner path contains %s',
(character) => {
const command = buildSetupRunnerCommand(cmdRunner(`\\a${character}b`), 'windows', {
family: 'cmd'
})
expect(command).toMatch(
/^powershell\.exe -NoProfile -NonInteractive -EncodedCommand [A-Za-z0-9+/=]+$/
)
}
)
it.each([
['plain', 'C:\\repo\\.git\\orca\\setup-runner.cmd'],
['spaces', 'C:\\Program Files\\repo\\.git\\orca\\setup-runner.cmd'],
['single quote', "C:\\o'brien\\.git\\orca\\setup-runner.cmd"],
['brackets and dash', 'C:\\repo-[2]\\.git\\orca\\setup-runner.cmd']
])('keeps the plain cmd launch for a %s path', (_label, runnerScriptPath) => {
expect(buildSetupRunnerCommand(runnerScriptPath, 'windows', { family: 'cmd' })).toBe(
`cmd.exe /c "${runnerScriptPath}"`
)
})
it('passes the runner path through the environment rather than the cmd argument string', () => {
const runnerScriptPath = cmdRunner('\\100%%\\a&b')
const script = decodePowerShellCommand(
buildSetupRunnerCommand(runnerScriptPath, 'windows', { family: 'cmd' })
)
expect(script).toContain(`$runner = '${runnerScriptPath}'`)
expect(script).toContain('$processInfo.EnvironmentVariables["ORCA_SETUP_RUNNER"] = $runner')
expect(script).toContain('/d /s /v:on /c ""!ORCA_SETUP_RUNNER!""')
// Why: the whole point of the guard is that the hostile path never reaches cmd as syntax.
expect(script).not.toContain(`/c ""${runnerScriptPath}""`)
expect(script).toContain('$processInfo.UseShellExecute = $false')
})
it('escapes single quotes when embedding the path in the PowerShell literal', () => {
const script = decodePowerShellCommand(
buildSetupRunnerCommand("C:\\o'brien&co\\.git\\orca\\setup-runner.cmd", 'windows', {
family: 'cmd'
})
)
expect(script).toContain("$runner = 'C:\\o''brien&co\\.git\\orca\\setup-runner.cmd'")
})
it('leaves runnerScriptPathForShell untouched so marker paths keep the native form', () => {
const runnerScriptPath = cmdRunner('\\a&b')
expect(resolveSetupRunnerCommand(runnerScriptPath, 'windows', { family: 'cmd' })).toMatchObject(
{
runnerScriptPathForShell: runnerScriptPath,
shell: 'windows'
}
)
})
it.each([
['native POSIX runner', 'C:\\repo\\a&b\\.git\\orca\\setup-runner.sh', undefined],
['WSL UNC runner', '\\\\wsl.localhost\\Ubuntu\\home\\a&b\\orca\\setup-runner.sh', undefined]
])('does not disturb the %s launch', (_label, runnerScriptPath) => {
expect(buildSetupRunnerCommand(runnerScriptPath, 'windows')).toMatch(/^bash /)
})
it('does not disturb the wsl.exe POSIX launch', () => {
expect(
buildSetupRunnerCommand('C:\\repo\\a&b\\.git\\orca\\setup-runner.sh', 'windows', {
family: 'posix',
executable: 'wsl.exe'
})
).toBe("bash '/mnt/c/repo/a&b/.git/orca/setup-runner.sh'")
})
})
describe('nativeWindowsPathToPosixShellPath', () => {
it('converts a drive path to the MSYS form Git Bash uses', () => {
expect(nativeWindowsPathToPosixShellPath('C:\\Users\\jin\\repo')).toBe('/c/Users/jin/repo')
})
it('is idempotent, so a double-applied conversion cannot corrupt a value', () => {
const once = nativeWindowsPathToPosixShellPath('D:\\repo\\worktrees\\feature')
expect(nativeWindowsPathToPosixShellPath(once)).toBe(once)
})
})
describe('getSetupRunnerCommandPlatformForPath', () => {
it('prefers POSIX for absolute POSIX runner paths even from Windows clients', () => {
expect(
getSetupRunnerCommandPlatformForPath('/remote/repo/.git/orca/setup-runner.sh', 'windows')
).toBe('posix')
})
it('prefers Windows for native Windows runner paths even from POSIX clients', () => {
expect(
getSetupRunnerCommandPlatformForPath('C:\\repo\\.git\\orca\\setup-runner.cmd', 'posix')
).toBe('windows')
})
it('keeps WSL UNC paths on the Windows resolver so they can be converted', () => {
expect(
getSetupRunnerCommandPlatformForPath(
'\\\\wsl.localhost\\Ubuntu\\home\\jin\\repo\\.git\\orca\\setup-runner.sh',
'posix'
)
).toBe('windows')
})
it('keeps forward-slash UNC paths on the Windows resolver', () => {
expect(
getSetupRunnerCommandPlatformForPath(
'//wsl.localhost/Ubuntu/home/jin/repo/.git/orca/setup-runner.sh',
'posix'
)
).toBe('windows')
expect(
getSetupRunnerCommandPlatformForPath(
'//server/share/repo/.git/orca/setup-runner.cmd',
'posix'
)
).toBe('windows')
})
})