Skip to content

Commit d688926

Browse files
authored
fix(device-shell): one typed device-shell boundary for adb, exec-out, and hdc (#2611)
* fix(device-shell): one typed device-shell boundary for adb, exec-out, and hdc `adb shell`, `adb exec-out`, and `hdc shell` join the words after the subcommand into one string the device's `sh` re-parses — adb escapes nothing on purpose, "just like ssh(1)". The host never runs a shell, so the injection surface is purely device-side, and it was covered by hand at a few Android sites and not at all on HarmonyOS. `deviceShellArgv` is now the only way a device-shell command exists. It quotes every word for the device shell — a bare safe word renders byte-identical, so only a value that would have been an injection vector changes — and hands back a frozen command the funnel remembers by identity. Every boundary that dispatches a device command refuses a `shell`/`exec-out` command it did not build, checking the value rather than a call convention, so a variable-built command is caught as fast as a literal one and a copy is refused instead of trusted. The one rebuild a transport is allowed is to take its own addressing out of a minted command — the `-s <serial>` pair a provider scope adopts, the option run `parseAndroidAdbArgv` moves into a typed target — which is `relayDeviceShellArgvWithoutOptions`, and it mints only while the removal stays inside that command's own option run. Addressing stays where #2632 put it: an Android device command is minted as the payload and travels in `AndroidAdbInvocation.command`, and the root adb host checks it before lowering. A command that must carry addressing in the same argv — an `hdc` command over the generic host command port, an adb route spelling `-s`/`-P`/`wait-for-*` inline — mints it with the prefix. Android's funnels are the bridge-facing way to compose a device command: `runAdbShell` / `runAdbExecOut` over an executor and `runAndroidShell` / `runAndroidExecOut` over a device, all exported from `agent-device/android-adb`; HarmonyOS gets `runHarmonyShell`. To keep the array a port checked the same array a transport dispatches — a copy would no longer be the one the guard recognizes — a host command's argv is `readonly` from `runCmd` down. Limrun's install path now asks the runtime adapter to stop the app rather than spelling `am force-stop` itself, which also keeps the kernel funnel out of the provider's eager closure. Refs #2026 * fix(device-shell): render device-shell words for the transport that carries them adb forwards words verbatim, so POSIX single-quoting is what the device shell needs. hdc wraps every element it forwards in double quotes, where a single quote is inert while $, a backquote, and " stay live: text containing $(id) was replaced by the device's own id output and a " escaped its argument, while our quotes arrived as data. A mint now names its transport and derives quoting from it, refuses a fragment on hdc (it can only arrive as literal text), and refuses an empty word on hdc, which drops it on the way to the device.
1 parent 057dfb7 commit d688926

172 files changed

Lines changed: 1812 additions & 958 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎CHANGELOG.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -153,6 +153,30 @@
153153
option → flag round trip and its allowlist carried nothing. Older manifests that still contain
154154
the field parse unchanged; the field is ignored. The adb provider `install` capability now takes
155155
only `replace` (#2364).
156+
- Changed (android, harmonyos): every `adb shell`, `adb exec-out`, and `hdc shell` command now goes
157+
through one device-shell funnel that renders each argument for the quoting its transport applies
158+
(#2026, #2611). The device shell re-parses the arguments it is handed, so an unquoted dynamic value
159+
was a command injection: Android quoted a few sites by hand and HarmonyOS quoted none. The two
160+
transports do not quote alike, which is why a caller names the transport (`'adb'` or `'hdc'`) rather
161+
than choosing quoting. `adb` escapes nothing, so a word reaches the device inside whatever quotes it
162+
is given. `hdc` wraps every element it forwards in double quotes, where a single quote is inert while
163+
`$`, a backquote, and `"` stay live: on a nova 14, `fill` text containing `$(id)` came back as the
164+
device's own `id` output and a `"` in the text ended its argument, so words on that transport are
165+
escaped instead of wrapped. Four effects are visible on a device. HarmonyOS `type` and `fill` text now
166+
reaches `uitest uiInput inputText` byte-identical, confirmed with a payload carrying quotes, a command
167+
substitution, a pipe, and a redirection. On Android an empty argument renders as `''` rather than
168+
vanishing from the command, so a command that read its own shift and its operand as two words no
169+
longer misaligns; HDC drops an empty element on the way to the device and cannot carry one, so it is
170+
refused with `details.reason` `hdc-empty-word-unsupported`, as is a script fragment, which could only
171+
arrive there as literal text. A script body handed to `sh -c` on the adb transport arrives as one
172+
argument. Custom adb executors and providers (SDK, MCP, and relay transports such as Limrun's) that
173+
pass a raw `['shell', …]` or `['exec-out', …]` argv are now refused with `INVALID_ARGS` and
174+
`details.reason` `unguarded-device-shell-argv`, because a command the transport is about to let the
175+
device parse has to be one the funnel built. Build it with `runAndroidShell` / `runAndroidExecOut`
176+
(a `DeviceInfo`) or `runAdbShell` / `runAdbExecOut` (an `AndroidAdbExecutor`), all exported from
177+
`agent-device/android-adb`, and pass each dynamic value as its own word. SDK: `AndroidAdbExecutor`
178+
and `AndroidAdbProvider.exec` now receive `readonly string[]`, so a custom executor annotated
179+
`(args: string[])` must widen its parameter to take the command.
156180
- Fixed: BrowserStack sessions honour `--provider-project`, `--provider-build`, and
157181
`--provider-session-name`. The capability builder emitted the legacy JSON Wire keys `device`,
158182
`os_version`, and `app` at the top level next to the W3C `bstack:options` block; the hub treats a

‎packages/capture-kit/src/recording/swift-cache.test.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { mkdtempForTestSync } from '../tmp-dir.fixtures.ts';
55

66
vi.mock(import('@agent-device/host-kit/command'), async (importOriginal) => ({
77
...(await importOriginal()),
8-
runCmd: vi.fn(async (_cmd: string, args: string[]) => {
8+
runCmd: vi.fn(async (_cmd: string, args: readonly string[]) => {
99
const outputPath = args[args.indexOf('-o') + 1]!;
1010
fs.writeFileSync(outputPath, 'compiled');
1111
fs.chmodSync(outputPath, 0o755);
@@ -166,7 +166,7 @@ test('a compile that failed is reported over a cache lock that could not be give
166166
const sourcePath = writeSourceFile();
167167
const buildFailure = new Error('swiftc: error: build failed');
168168
let lockDir = '';
169-
mockRunCmd.mockImplementationOnce(async (_cmd: string, args: string[]) => {
169+
mockRunCmd.mockImplementationOnce(async (_cmd: string, args: readonly string[]) => {
170170
// The temp executable sits one directory under the cache entry, and the lock beside it.
171171
const outputPath = args[args.indexOf('-o') + 1]!;
172172
const executablePath = path.join(
@@ -210,7 +210,7 @@ async function createBlockedCacheEntry() {
210210
async function expectConcurrentCacheReuse(compile: () => Promise<string>): Promise<void> {
211211
let releaseCompile: () => void = () => {};
212212
const compileStarted = new Promise<void>((resolve) => {
213-
mockRunCmd.mockImplementationOnce(async (_cmd: string, args: string[]) => {
213+
mockRunCmd.mockImplementationOnce(async (_cmd: string, args: readonly string[]) => {
214214
resolve();
215215
await new Promise<void>((release) => {
216216
releaseCompile = release;

‎packages/host-kit/src/command.ts‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,4 +23,3 @@ export {
2323
withCommandExecutorOverride,
2424
withoutCommandExecutorOverride,
2525
} from './internal/exec.ts';
26-
export { shellQuote, shellQuoteIfNeeded } from './internal/shell-quote.ts';

‎packages/host-kit/src/internal/exec-kill-settle.test.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ import {
1010
signalProcessGroupBestEffort,
1111
type ExecBackgroundOptions,
1212
} from './exec.ts';
13-
import { shellQuote } from './shell-quote.ts';
13+
import { shellQuote } from '@agent-device/kernel/device-shell';
1414
import { sleep } from './timeouts.ts';
1515
import { mkdtempForTestSync } from './tmp-dir.fixtures.ts';
1616

‎packages/host-kit/src/internal/exec.ts‎

Lines changed: 33 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ const WINDOWS_PATH_EXTENSIONS = ['.com', '.exe', '.bat', '.cmd'];
7878
const EXEC_DIAGNOSTIC_ARG_LIMIT = 6;
7979
export type CommandExecutorOverride = (
8080
cmd: string,
81-
args: string[],
81+
args: readonly string[],
8282
options: ExecOptions,
8383
) => Promise<ExecResult> | undefined;
8484

@@ -99,7 +99,7 @@ export async function withoutCommandExecutorOverride<T>(fn: () => Promise<T>): P
9999

100100
export async function runCmd(
101101
cmd: string,
102-
args: string[],
102+
args: readonly string[],
103103
options: ExecOptions = {},
104104
): Promise<ExecResult> {
105105
const overrideResult = commandExecutorOverrideScope.getStore()?.(cmd, args, options);
@@ -109,7 +109,7 @@ export async function runCmd(
109109

110110
export async function runCmdStreaming(
111111
cmd: string,
112-
args: string[],
112+
args: readonly string[],
113113
options: ExecStreamOptions = {},
114114
): Promise<ExecResult> {
115115
const overrideResult = commandExecutorOverrideScope.getStore()?.(cmd, args, options);
@@ -139,7 +139,7 @@ export function coerceExecResult<T extends Pick<ExecResult, 'stdout' | 'stderr'
139139

140140
function runSpawnedCommand(
141141
cmd: string,
142-
args: string[],
142+
args: readonly string[],
143143
options: ExecStreamOptions = {},
144144
): Promise<ExecResult> {
145145
const executable = normalizeExecutableCommand(cmd);
@@ -309,7 +309,11 @@ export async function resolveFileOverridePath(
309309
}
310310

311311
// fallow-ignore-next-line complexity
312-
export function runCmdSync(cmd: string, args: string[], options: ExecOptions = {}): ExecResult {
312+
export function runCmdSync(
313+
cmd: string,
314+
args: readonly string[],
315+
options: ExecOptions = {},
316+
): ExecResult {
313317
const executable = normalizeExecutableCommand(cmd);
314318
const result = spawnSync(executable, args, {
315319
cwd: options.cwd,
@@ -366,15 +370,15 @@ export function runCmdSync(cmd: string, args: string[], options: ExecOptions = {
366370

367371
export function runCmdDetached(
368372
cmd: string,
369-
args: string[],
373+
args: readonly string[],
370374
options: ExecDetachedOptions = {},
371375
): number {
372376
return runCmdDetachedMonitored(cmd, args, options).pid;
373377
}
374378

375379
export function runCmdDetachedMonitored(
376380
cmd: string,
377-
args: string[],
381+
args: readonly string[],
378382
options: ExecDetachedOptions = {},
379383
): ExecDetachedProcess {
380384
const executable = normalizeExecutableCommand(cmd);
@@ -405,7 +409,7 @@ export function runCmdDetachedMonitored(
405409

406410
export function runCmdBackground(
407411
cmd: string,
408-
args: string[],
412+
args: readonly string[],
409413
options: ExecBackgroundOptions = {},
410414
): ExecBackgroundResult {
411415
const executable = normalizeExecutableCommand(cmd);
@@ -481,9 +485,9 @@ export function runCmdBackground(
481485
}
482486

483487
type ExecTraceContext = {
484-
emitBackgroundCompletion: (cmd: string, args: string[], event: 'error' | 'exit') => void;
485-
emitBackgroundSpawn: (cmd: string, args: string[]) => void;
486-
emitForegroundCompletion: (cmd: string, args: string[]) => void;
488+
emitBackgroundCompletion: (cmd: string, args: readonly string[], event: 'error' | 'exit') => void;
489+
emitBackgroundSpawn: (cmd: string, args: readonly string[]) => void;
490+
emitForegroundCompletion: (cmd: string, args: readonly string[]) => void;
487491
};
488492

489493
function createExecTraceContext(): ExecTraceContext {
@@ -538,7 +542,7 @@ function createDisabledExecTraceContext(): ExecTraceContext {
538542

539543
function emitExecCommandDiagnostic(params: {
540544
cmd: string;
541-
args: string[];
545+
args: readonly string[];
542546
startedAtMs?: number;
543547
data?: Record<string, unknown>;
544548
}): void {
@@ -570,7 +574,12 @@ function normalizeExecutableCommand(cmd: string): string {
570574
return candidate;
571575
}
572576

573-
function createSpawnError(executable: string, cmd: string, args: string[], err: Error): AppError {
577+
function createSpawnError(
578+
executable: string,
579+
cmd: string,
580+
args: readonly string[],
581+
err: Error,
582+
): AppError {
574583
const code = (err as NodeJS.ErrnoException).code;
575584
if (code === 'ENOENT') {
576585
return createMissingToolError(executable, cmd, err);
@@ -585,7 +594,7 @@ function createMissingToolError(executable: string, cmd: string, cause: Error):
585594
function createCommandFailedError(
586595
executable: string,
587596
cmd: string,
588-
args: string[],
597+
args: readonly string[],
589598
cause: Error,
590599
): AppError {
591600
return new AppError('COMMAND_FAILED', `Failed to run ${executable}`, { cmd, args }, cause);
@@ -594,7 +603,7 @@ function createCommandFailedError(
594603
function createStdinError(
595604
executable: string,
596605
cmd: string,
597-
args: string[],
606+
args: readonly string[],
598607
cause: unknown,
599608
): AppError {
600609
return new AppError(
@@ -605,14 +614,18 @@ function createStdinError(
605614
);
606615
}
607616

608-
function createCommandCanceledError(executable: string, cmd: string, args: string[]): AppError {
617+
function createCommandCanceledError(
618+
executable: string,
619+
cmd: string,
620+
args: readonly string[],
621+
): AppError {
609622
return createRequestCanceledError({ cmd, args, executable });
610623
}
611624

612625
function createTimeoutError(
613626
executable: string,
614627
cmd: string,
615-
args: string[],
628+
args: readonly string[],
616629
timeoutMs: number,
617630
exitCode: number,
618631
stdout: string,
@@ -646,7 +659,7 @@ export function isCommandTimeoutError(error: unknown): error is AppError {
646659
function createExitError(
647660
executable: string,
648661
cmd: string,
649-
args: string[],
662+
args: readonly string[],
650663
exitCode: number,
651664
stdout: string,
652665
stderr: string,
@@ -707,7 +720,7 @@ function spawnRejectionError(
707720
abort: CommandAbort,
708721
executable: string,
709722
cmd: string,
710-
args: string[],
723+
args: readonly string[],
711724
err: Error,
712725
): AppError {
713726
return abort.didAbort
@@ -721,7 +734,7 @@ function commandCloseFailure(
721734
abort: CommandAbort,
722735
executable: string,
723736
cmd: string,
724-
args: string[],
737+
args: readonly string[],
725738
exitCode: number,
726739
allowFailure: boolean | undefined,
727740
stdout: string,

‎packages/host-kit/src/internal/shell-quote.test.ts‎

Lines changed: 0 additions & 21 deletions
This file was deleted.

‎packages/host-kit/src/internal/shell-quote.ts‎

Lines changed: 0 additions & 9 deletions
This file was deleted.

‎packages/kernel/package.json‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@
2121
"types": "./src/device.ts",
2222
"default": "./src/device.ts"
2323
},
24+
"./device-shell": {
25+
"types": "./src/device-shell.ts",
26+
"default": "./src/device-shell.ts"
27+
},
2428
"./device-isolation": {
2529
"types": "./src/device-isolation.ts",
2630
"default": "./src/device-isolation.ts"

0 commit comments

Comments
 (0)