Skip to content

Commit f312543

Browse files
committed
fix(process): preserve Windows executable provenance
1 parent b07b730 commit f312543

4 files changed

Lines changed: 120 additions & 7 deletions

File tree

‎packages/host-kit/src/internal/process-executable-path.test.ts‎

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,16 @@ const originalPlatform = Object.getOwnPropertyDescriptor(process, 'platform')!;
2020
afterEach(() => {
2121
Object.defineProperty(process, 'platform', originalPlatform);
2222
vi.resetAllMocks();
23+
vi.unstubAllEnvs();
2324
});
2425
function platform(value: NodeJS.Platform) {
2526
Object.defineProperty(process, 'platform', { ...originalPlatform, value });
27+
if (value === 'win32') {
28+
for (const key of Object.keys(process.env)) {
29+
if (key.toUpperCase() === 'SYSTEMROOT') vi.stubEnv(key, undefined);
30+
}
31+
vi.stubEnv('SystemRoot', String.raw`D:\WinNT`);
32+
}
2633
}
2734

2835
test('Linux reads requested executable links and refuses missing, deleted and invalid paths', async () => {
@@ -69,18 +76,26 @@ test.each(['darwin', 'win32'] as const)(
6976
{ pid: 5, path: valid },
7077
]),
7178
});
72-
const paths = await readProcessExecutablePaths([1, 2, 3, 4, 5, 0, 1], 20);
79+
const paths = await readProcessExecutablePaths([1, 2, 3, 4, 5, 0, 1, -1, 1.5, 2147483648], 20);
7380
assert.deepEqual([...paths], [[1, valid]]);
7481
assert.equal(runCmdMock.mock.calls.length, 1);
7582
const [cmd, args, options] = runCmdMock.mock.calls[0]!;
7683
if (os === 'darwin') {
7784
assert.equal(cmd, '/usr/bin/osascript');
7885
assert.match(args[3], /proc_pidpath/);
86+
const selected = /JSON\.stringify\((\[[^\]]*\])\.map/.exec(args[3]);
87+
assert.ok(selected);
88+
assert.deepEqual(JSON.parse(selected[1]!), [1, 2, 3, 4, 5]);
7989
assert.match(args[3], /n<=0 \|\| n>=4096/);
8090
assert.equal(options.timeoutMs, 20);
8191
} else {
82-
assert.equal(cmd, String.raw`C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`);
92+
assert.equal(cmd, String.raw`D:\WinNT\System32\WindowsPowerShell\v1.0\powershell.exe`);
8393
assert.match(args[3], /ExecutablePath/);
94+
const filter = /-Filter '([^']*)'/.exec(args[3]);
95+
assert.equal(
96+
filter?.[1],
97+
'ProcessId=1 OR ProcessId=2 OR ProcessId=3 OR ProcessId=4 OR ProcessId=5',
98+
);
8499
assert.doesNotMatch(args[3], /CommandLine/);
85100
assert.equal(options.timeoutMs, 2000);
86101
}
@@ -107,3 +122,25 @@ test.each(['darwin', 'win32'] as const)(
107122
assert.equal(runCmdMock.mock.calls.length, 3);
108123
},
109124
);
125+
126+
test.each([undefined, '', 'Windows', String.raw`C:Windows`, String.raw`\Windows`])(
127+
'Windows refuses missing or nonabsolute SystemRoot %s without a PATH lookup',
128+
async (root) => {
129+
platform('win32');
130+
vi.stubEnv('SystemRoot', root);
131+
assert.equal((await readProcessExecutablePaths([1])).size, 0);
132+
assert.equal(runCmdMock.mock.calls.length, 0);
133+
},
134+
);
135+
136+
test('Windows host SystemRoot variable names are case-insensitive', async () => {
137+
platform('win32');
138+
vi.stubEnv('SystemRoot', undefined);
139+
vi.stubEnv('sYsTeMrOoT', String.raw`E:\Windows`);
140+
runCmdMock.mockResolvedValue({ stdout: '[]', stderr: '', exitCode: 0 });
141+
await readProcessExecutablePaths([1]);
142+
assert.equal(
143+
runCmdMock.mock.calls[0]?.[0],
144+
String.raw`E:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`,
145+
);
146+
});

‎packages/host-kit/src/internal/process-executable-path.ts‎

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import { hostPlatform, uniquePositivePids } from './host-process.ts';
77
const DEFAULT_TIMEOUT_MS = 1_000;
88
const WINDOWS_TIMEOUT_FLOOR_MS = 2_000;
99
const PATH_BUFFER_BYTES = 4_096;
10-
const WINDOWS_POWERSHELL = String.raw`C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe`;
1110

1211
export async function readProcessExecutablePaths(
1312
pids: Iterable<number>,
@@ -21,8 +20,10 @@ export async function readProcessExecutablePaths(
2120
return await withoutCommandExecutorOverride(async () => {
2221
try {
2322
const windows = platform === 'win32';
23+
const executable = windows ? windowsPowerShellPath() : '/usr/bin/osascript';
24+
if (!executable) return new Map();
2425
const result = await runCmd(
25-
windows ? WINDOWS_POWERSHELL : '/usr/bin/osascript',
26+
executable,
2627
windows ? windowsArgs(selected) : darwinArgs(selected),
2728
{
2829
allowFailure: true,
@@ -36,6 +37,15 @@ export async function readProcessExecutablePaths(
3637
});
3738
}
3839

40+
function windowsPowerShellPath(): string | undefined {
41+
const key = Object.keys(process.env).find((name) => name.toUpperCase() === 'SYSTEMROOT');
42+
const root = key === undefined ? undefined : process.env[key];
43+
if (!root || !path.win32.isAbsolute(root) || path.win32.parse(root).root.length < 3) {
44+
return undefined;
45+
}
46+
return path.win32.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
47+
}
48+
3949
async function readLinuxPaths(
4050
pids: readonly number[],
4151
timeoutMs: number,

‎packages/platform-web/src/agent-browser-lifecycle.test.ts‎

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { bindTestCommandHost, installFakeManagedAgentBrowser } from '@agent-device/test-kit';
22
import assert from 'node:assert/strict';
3+
import * as hostFile from '@agent-device/host-kit/host-file';
34
import { ChildProcess } from 'node:child_process';
45
import fs from 'node:fs';
56
import path from 'node:path';
@@ -10,7 +11,7 @@ import { mkdtempForTestSync } from './__tests__/test-utils.ts';
1011
const { runCmdMock, spawnMock, probe } = vi.hoisted(() => ({
1112
runCmdMock: vi.fn(),
1213
spawnMock: vi.fn(),
13-
probe: { unanswered: false },
14+
probe: { unanswered: false, platform: undefined as NodeJS.Platform | undefined },
1415
}));
1516

1617
vi.mock('@agent-device/host-kit/command', async (importOriginal) => ({
@@ -43,6 +44,7 @@ vi.mock('@agent-device/host-kit/process', async (importOriginal) => {
4344
const actual = await importOriginal<typeof import('@agent-device/host-kit/process')>();
4445
return {
4546
...actual,
47+
hostPlatform: () => probe.platform ?? actual.hostPlatform(),
4648
listHostProcesses: async (options: Parameters<typeof actual.listHostProcesses>[0]) =>
4749
await actual.listHostProcesses({ ...options, runCommand: runCmdMock }),
4850
readHostProcessIdentityObservationsAsync: async (pids: Iterable<number>) =>
@@ -83,6 +85,7 @@ beforeEach(() => {
8385
identitiesMock.mockClear();
8486
executablePathsMock.mockReset();
8587
probe.unanswered = false;
88+
probe.platform = undefined;
8689
});
8790

8891
afterEach(() => {
@@ -521,6 +524,45 @@ function observeProcesses(processes: ProcessFixture[]) {
521524
);
522525
}
523526

527+
test.each([
528+
['win32', 'same', [101]],
529+
['win32', 'different-file', []],
530+
['win32', 'different-device', []],
531+
['win32', 'missing', []],
532+
['win32', 'unsafe-inode', []],
533+
['darwin', 'same', []],
534+
] as const)(
535+
'case-only executable spelling on %s requires %s file identity',
536+
async (os, identity, expected) => {
537+
const stateDir = mkdtempForTestSync('agent-device-web-case-');
538+
try {
539+
installFakeManagedAgentBrowser(stateDir);
540+
const status = getManagedAgentBrowserStatus({
541+
stateDir,
542+
host: { env: process.env, cwd: process.cwd() },
543+
});
544+
const binary = nativeBinary(status.installDir);
545+
const observed = binary.replaceAll('\\', '/').toUpperCase();
546+
probe.platform = os;
547+
vi.spyOn(hostFile, 'hostFileStatSync').mockImplementation((candidate) => {
548+
if (candidate === observed && identity === 'missing') throw new Error('unavailable');
549+
const stats = fs.statSync(candidate === observed ? binary : candidate);
550+
if (candidate === observed) {
551+
if (identity === 'different-file') stats.ino += 1;
552+
if (identity === 'different-device') stats.dev += 1;
553+
if (identity === 'unsafe-inode') stats.ino = Number.MAX_SAFE_INTEGER + 1;
554+
}
555+
return stats;
556+
});
557+
observeProcesses([{ pid: 101, command: `${binary} daemon`, executable: observed }]);
558+
const store = { replace: vi.fn(), clear: vi.fn(), read: vi.fn(() => []) };
559+
expect((await recordManagedAgentBrowserProcesses(status, store)).pids).toEqual(expected);
560+
} finally {
561+
fs.rmSync(stateDir, { recursive: true, force: true });
562+
}
563+
},
564+
);
565+
524566
test('a managed binary symlink cannot confer ownership on an executable outside its install', async () => {
525567
const stateDir = mkdtempForTestSync('agent-device-web-install-boundary-');
526568
try {

‎packages/platform-web/src/agent-browser-process-record.ts‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,12 @@ import crypto from 'node:crypto';
22
import path from 'node:path';
33
import type { OwnedProcessRecord } from '@agent-device/contracts/platform-runtime-host';
44
import { uniqueStrings } from '@agent-device/kernel/collections';
5-
import { realHostPathSync } from '@agent-device/host-kit/host-file';
5+
import { hostFileStatSync, realHostPathSync } from '@agent-device/host-kit/host-file';
66
import { withoutCommandExecutorOverride } from '@agent-device/host-kit/command';
77
import {
88
expandProcessTree,
99
hostProcessId,
10+
hostPlatform,
1011
isProcessAlive,
1112
listHostProcesses,
1213
readHostProcessIdentityObservationsAsync,
@@ -79,12 +80,35 @@ function matchManagedAgentBrowserProcess(
7980
const chrome = matchChromeProcess(processInfo, ownership);
8081
if (chrome) return chrome;
8182
}
82-
if (processInfo.pid !== hostProcessId() && ownership.daemonEntries.includes(executable)) {
83+
if (
84+
processInfo.pid !== hostProcessId() &&
85+
matchesManagedDaemonExecutable(executable, ownership.daemonEntries)
86+
) {
8387
return { process: processInfo, reason: 'agent-browser-daemon' };
8488
}
8589
return undefined;
8690
}
8791

92+
function matchesManagedDaemonExecutable(executable: string, entries: readonly string[]): boolean {
93+
if (entries.includes(executable)) return true;
94+
if (hostPlatform() !== 'win32') return false;
95+
const entry = entries.find((candidate) => candidate.toLowerCase() === executable.toLowerCase());
96+
if (!entry) return false;
97+
try {
98+
const expected = hostFileStatSync(entry);
99+
const observed = hostFileStatSync(executable);
100+
return (
101+
Number.isSafeInteger(expected.ino) &&
102+
expected.ino > 0 &&
103+
Number.isSafeInteger(expected.dev) &&
104+
expected.ino === observed.ino &&
105+
expected.dev === observed.dev
106+
);
107+
} catch {
108+
return false;
109+
}
110+
}
111+
88112
function isChromeExecutable(executable: string): boolean {
89113
const name = executable.slice(executable.lastIndexOf('/') + 1);
90114
return /^(?:Google Chrome(?: for Testing)?|Chrome for Testing|Chromium|chrome(?:\.exe)?|chromium|chromium-browser|headless_shell)$/i.test(

0 commit comments

Comments
 (0)