Skip to content

Commit 45e1372

Browse files
authored
fix(maestro): run child entrypoints through symlinked paths (#4397)
* fix(maestro): run child entrypoints through symlinked paths * test(maestro): use the package-local temporary directory fixture * test(maestro): cover child entry protocol boundaries * test(maestro): colocate child protocol tests with their entry module
1 parent 5e742bb commit 45e1372

5 files changed

Lines changed: 142 additions & 40 deletions

File tree

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import assert from 'node:assert/strict';
2+
import fs from 'node:fs';
3+
import path from 'node:path';
4+
import { fileURLToPath } from 'node:url';
5+
import { afterEach, beforeEach, test, vi } from 'vitest';
6+
import { mkdtempForTestSync } from '../../tmp-dir.fixtures.ts';
7+
8+
const stdin = vi.hoisted(() => ({ text: '' }));
9+
10+
vi.mock('node:fs', async (importOriginal) => {
11+
const actual = await importOriginal<typeof import('node:fs')>();
12+
return {
13+
...actual,
14+
readFileSync: (...args: Parameters<typeof actual.readFileSync>) =>
15+
args[0] === 0 ? stdin.text : actual.readFileSync(...args),
16+
};
17+
});
18+
19+
let originalExitCode: typeof process.exitCode;
20+
let originalArgv: typeof process.argv;
21+
22+
beforeEach(() => {
23+
vi.resetModules();
24+
originalExitCode = process.exitCode;
25+
originalArgv = process.argv;
26+
process.argv = [...process.argv];
27+
process.exitCode = undefined;
28+
});
29+
30+
afterEach(() => {
31+
vi.restoreAllMocks();
32+
process.exitCode = originalExitCode;
33+
process.argv = originalArgv;
34+
});
35+
36+
function captureOutput() {
37+
const chunks: string[] = [];
38+
const written = new Promise<void>((resolve) => {
39+
vi.spyOn(process.stdout, 'write').mockImplementation((chunk) => {
40+
chunks.push(String(chunk));
41+
resolve();
42+
return true;
43+
});
44+
});
45+
return { written, text: () => chunks.join('') };
46+
}
47+
48+
test('the VM entry reads its stdin request and writes the output envelope', async () => {
49+
const scriptPath = path.join(mkdtempForTestSync('run-script-entry-'), 'setup.js');
50+
fs.writeFileSync(scriptPath, 'output.answer = VALUE.toUpperCase();');
51+
stdin.text = JSON.stringify({ scriptPath, env: { VALUE: 'child' }, publicNetworkOnly: false });
52+
const output = captureOutput();
53+
process.argv[1] = fileURLToPath(new URL('../run-script-child.ts', import.meta.url));
54+
55+
await import('../run-script-child.ts');
56+
57+
await output.written;
58+
assert.deepEqual(JSON.parse(output.text()), { outputEnv: { 'output.answer': 'CHILD' } });
59+
});
60+
61+
test('the HTTP entry writes typed refusals as JSON without failing the process', async () => {
62+
stdin.text = JSON.stringify({
63+
method: 'POST',
64+
url: 'not a URL',
65+
headers: {},
66+
publicNetworkOnly: true,
67+
});
68+
const output = captureOutput();
69+
const stderr = vi.spyOn(console, 'error').mockImplementation(() => {});
70+
process.argv[1] = fileURLToPath(new URL('../run-script-http-child.ts', import.meta.url));
71+
72+
await import('../run-script-http-child.ts');
73+
74+
await output.written;
75+
assert.deepEqual(JSON.parse(output.text()), {
76+
error: { code: 'INVALID_ARGS', message: 'Invalid Maestro runScript HTTP URL' },
77+
});
78+
assert.equal(stderr.mock.calls.length, 0);
79+
assert.equal(process.exitCode, undefined);
80+
});
81+
82+
test('the HTTP entry reports malformed protocol input on stderr with a failing exit code', async () => {
83+
stdin.text = '{';
84+
const stdout = vi.spyOn(process.stdout, 'write').mockReturnValue(true);
85+
const failure = new Promise<unknown>((resolve) => {
86+
vi.spyOn(console, 'error').mockImplementation((value) => resolve(value));
87+
});
88+
process.argv[1] = fileURLToPath(new URL('../run-script-http-child.ts', import.meta.url));
89+
90+
await import('../run-script-http-child.ts');
91+
92+
assert.match(String(await failure), /SyntaxError/);
93+
assert.equal(stdout.mock.calls.length, 0);
94+
assert.equal(process.exitCode, 1);
95+
});
Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,27 @@
11
import assert from 'node:assert/strict';
2+
import fs from 'node:fs';
3+
import path from 'node:path';
24
import { fileURLToPath } from 'node:url';
35
import { test } from 'vitest';
46
import { runCmdSync } from '@agent-device/host-kit/command';
7+
import { mkdtempForTestSync } from '../../tmp-dir.fixtures.ts';
58

6-
test('the packaged HTTP child reports malformed input', () => {
7-
const childPath = fileURLToPath(new URL('../run-script-http-child.ts', import.meta.url));
8-
const result = runCmdSync(process.execPath, ['--experimental-strip-types', childPath], {
9-
stdin: '{',
10-
allowFailure: true,
11-
});
9+
test.each(['canonical', 'directory-symlink'])(
10+
'the HTTP child reports malformed input through a %s path',
11+
(kind) => {
12+
const childPath = fileURLToPath(new URL('../run-script-http-child.ts', import.meta.url));
13+
let entryPath = childPath;
14+
if (kind === 'directory-symlink') {
15+
const alias = path.join(mkdtempForTestSync('run-script-http-child-'), 'entry');
16+
fs.symlinkSync(path.dirname(childPath), alias, 'junction');
17+
entryPath = path.join(alias, path.basename(childPath));
18+
}
19+
const result = runCmdSync(process.execPath, ['--experimental-strip-types', entryPath], {
20+
stdin: '{',
21+
allowFailure: true,
22+
});
1223

13-
assert.notEqual(result.exitCode, 0);
14-
assert.match(result.stderr, /SyntaxError/);
15-
});
24+
assert.notEqual(result.exitCode, 0);
25+
assert.match(result.stderr, /SyntaxError/);
26+
},
27+
);
Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,4 @@
11
import { readFileSync } from 'node:fs';
2-
import { pathToFileURL } from 'node:url';
32
import { runScriptChildOutput } from './run-script-vm.ts';
43

5-
if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
6-
process.stdout.write(JSON.stringify(runScriptChildOutput(readFileSync(0, 'utf8'))));
7-
}
4+
process.stdout.write(JSON.stringify(runScriptChildOutput(readFileSync(0, 'utf8'))));
Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,10 @@
11
import { readFileSync } from 'node:fs';
2-
import { pathToFileURL } from 'node:url';
32
import { runScriptHttpChildOutput } from './run-script-http.ts';
43

5-
if (process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url) {
6-
void runScriptHttpChildOutput(readFileSync(0, 'utf8'), process.env).then(
7-
(output) => process.stdout.write(JSON.stringify(output)),
8-
(error: unknown) => {
9-
console.error(error instanceof Error ? (error.stack ?? error.message) : String(error));
10-
process.exitCode = 1;
11-
},
12-
);
13-
}
4+
void runScriptHttpChildOutput(readFileSync(0, 'utf8'), process.env).then(
5+
(output) => process.stdout.write(JSON.stringify(output)),
6+
(error: unknown) => {
7+
console.error(error instanceof Error ? (error.stack ?? error.message) : String(error));
8+
process.exitCode = 1;
9+
},
10+
);

‎test/integration/installed-package-metro.test.ts‎

Lines changed: 18 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -88,30 +88,31 @@ function linkRuntimeDependencies(installedPackageRoot: string, consumerRoot: str
8888
* are found from the bundled chunk that holds the resolver, so this proves the shipped layout.
8989
*/
9090
async function assertPackagedRunScriptChild(installedPackageRoot: string, root: string) {
91-
const childPath = path.join(
92-
installedPackageRoot,
93-
'dist',
94-
'src',
95-
'internal',
96-
'run-script-child.js',
91+
const childPath = fs.realpathSync(
92+
path.join(installedPackageRoot, 'dist', 'src', 'internal', 'run-script-child.js'),
9793
);
9894
assert.equal(fs.existsSync(childPath), true);
95+
const aliasRoot = path.join(root, 'run-script-entry-alias');
96+
fs.symlinkSync(installedPackageRoot, aliasRoot, 'junction');
97+
const aliasChildPath = path.join(aliasRoot, 'dist', 'src', 'internal', 'run-script-child.js');
9998
const server = http.createServer((_req, res) => res.end('x'.repeat(2 * 1024 * 1024)));
10099
try {
101100
const port = await listenOnLoopback(server);
102101
const scriptPath = path.join(root, 'run-script-setup.js');
103102
fs.writeFileSync(scriptPath, 'output.size = http.post(SERVER_URL).body.length');
104-
const result = await runCmd(process.execPath, [childPath], {
105-
stdin: JSON.stringify({
106-
scriptPath,
107-
env: { SERVER_URL: `http://127.0.0.1:${port}/` },
108-
publicNetworkOnly: false,
109-
}),
110-
timeoutMs: SUBPROCESS_TIMEOUT_MS,
111-
});
112-
assert.deepEqual(readJson(result.stdout), {
113-
outputEnv: { 'output.size': String(2 * 1024 * 1024) },
114-
});
103+
for (const entryPath of [childPath, aliasChildPath]) {
104+
const result = await runCmd(process.execPath, [entryPath], {
105+
stdin: JSON.stringify({
106+
scriptPath,
107+
env: { SERVER_URL: `http://127.0.0.1:${port}/` },
108+
publicNetworkOnly: false,
109+
}),
110+
timeoutMs: SUBPROCESS_TIMEOUT_MS,
111+
});
112+
assert.deepEqual(readJson(result.stdout), {
113+
outputEnv: { 'output.size': String(2 * 1024 * 1024) },
114+
});
115+
}
115116
} finally {
116117
await closeLoopbackServer(server);
117118
}

0 commit comments

Comments
 (0)