api-utility-process-spec.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. import { expect } from 'chai';
  2. import * as childProcess from 'node:child_process';
  3. import * as path from 'node:path';
  4. import { BrowserWindow, MessageChannelMain, utilityProcess, app } from 'electron/main';
  5. import { ifit } from './lib/spec-helpers';
  6. import { closeWindow } from './lib/window-helpers';
  7. import { once } from 'node:events';
  8. import { pathToFileURL } from 'node:url';
  9. import { setImmediate } from 'node:timers/promises';
  10. const fixturesPath = path.resolve(__dirname, 'fixtures', 'api', 'utility-process');
  11. const isWindowsOnArm = process.platform === 'win32' && process.arch === 'arm64';
  12. const isWindows32Bit = process.platform === 'win32' && process.arch === 'ia32';
  13. describe('utilityProcess module', () => {
  14. describe('UtilityProcess constructor', () => {
  15. it('throws when empty script path is provided', async () => {
  16. expect(() => {
  17. utilityProcess.fork('');
  18. }).to.throw();
  19. });
  20. it('throws when options.stdio is not valid', async () => {
  21. expect(() => {
  22. utilityProcess.fork(path.join(fixturesPath, 'empty.js'), [], {
  23. execArgv: ['--test', '--test2'],
  24. serviceName: 'test',
  25. stdio: 'ipc'
  26. });
  27. }).to.throw(/stdio must be of the following values: inherit, pipe, ignore/);
  28. expect(() => {
  29. utilityProcess.fork(path.join(fixturesPath, 'empty.js'), [], {
  30. execArgv: ['--test', '--test2'],
  31. serviceName: 'test',
  32. stdio: ['ignore', 'ignore']
  33. });
  34. }).to.throw(/configuration missing for stdin, stdout or stderr/);
  35. expect(() => {
  36. utilityProcess.fork(path.join(fixturesPath, 'empty.js'), [], {
  37. execArgv: ['--test', '--test2'],
  38. serviceName: 'test',
  39. stdio: ['pipe', 'inherit', 'inherit']
  40. });
  41. }).to.throw(/stdin value other than ignore is not supported/);
  42. });
  43. });
  44. describe('lifecycle events', () => {
  45. it('emits \'spawn\' when child process successfully launches', async () => {
  46. const child = utilityProcess.fork(path.join(fixturesPath, 'empty.js'));
  47. await once(child, 'spawn');
  48. });
  49. it('emits \'exit\' when child process exits gracefully', async () => {
  50. const child = utilityProcess.fork(path.join(fixturesPath, 'empty.js'));
  51. const [code] = await once(child, 'exit');
  52. expect(code).to.equal(0);
  53. });
  54. ifit(!isWindows32Bit)('emits \'exit\' when child process crashes', async () => {
  55. const child = utilityProcess.fork(path.join(fixturesPath, 'crash.js'));
  56. // Do not check for exit code in this case,
  57. // SIGSEGV code can be 139 or 11 across our different CI pipeline.
  58. await once(child, 'exit');
  59. });
  60. ifit(!isWindows32Bit)('emits \'exit\' corresponding to the child process', async () => {
  61. const child1 = utilityProcess.fork(path.join(fixturesPath, 'endless.js'));
  62. await once(child1, 'spawn');
  63. const child2 = utilityProcess.fork(path.join(fixturesPath, 'crash.js'));
  64. await once(child2, 'exit');
  65. expect(child1.kill()).to.be.true();
  66. await once(child1, 'exit');
  67. });
  68. it('emits \'exit\' when there is uncaught exception', async () => {
  69. const child = utilityProcess.fork(path.join(fixturesPath, 'exception.js'));
  70. const [code] = await once(child, 'exit');
  71. expect(code).to.equal(1);
  72. });
  73. it('emits \'exit\' when there is uncaught exception in ESM', async () => {
  74. const child = utilityProcess.fork(path.join(fixturesPath, 'exception.mjs'));
  75. const [code] = await once(child, 'exit');
  76. expect(code).to.equal(1);
  77. });
  78. it('emits \'exit\' when process.exit is called', async () => {
  79. const exitCode = 2;
  80. const child = utilityProcess.fork(path.join(fixturesPath, 'custom-exit.js'), [`--exitCode=${exitCode}`]);
  81. const [code] = await once(child, 'exit');
  82. expect(code).to.equal(exitCode);
  83. });
  84. });
  85. describe('app \'child-process-gone\' event', () => {
  86. ifit(!isWindows32Bit)('with default serviceName', async () => {
  87. utilityProcess.fork(path.join(fixturesPath, 'crash.js'));
  88. const [, details] = await once(app, 'child-process-gone') as [any, Electron.Details];
  89. expect(details.type).to.equal('Utility');
  90. expect(details.serviceName).to.equal('node.mojom.NodeService');
  91. expect(details.name).to.equal('Node Utility Process');
  92. expect(details.reason).to.be.oneOf(['crashed', 'abnormal-exit']);
  93. });
  94. ifit(!isWindows32Bit)('with custom serviceName', async () => {
  95. utilityProcess.fork(path.join(fixturesPath, 'crash.js'), [], { serviceName: 'Hello World!' });
  96. const [, details] = await once(app, 'child-process-gone') as [any, Electron.Details];
  97. expect(details.type).to.equal('Utility');
  98. expect(details.serviceName).to.equal('node.mojom.NodeService');
  99. expect(details.name).to.equal('Hello World!');
  100. expect(details.reason).to.be.oneOf(['crashed', 'abnormal-exit']);
  101. });
  102. });
  103. describe('app.getAppMetrics()', () => {
  104. it('with default serviceName', async () => {
  105. const child = utilityProcess.fork(path.join(fixturesPath, 'endless.js'));
  106. await once(child, 'spawn');
  107. expect(child.pid).to.not.be.null();
  108. await setImmediate();
  109. const details = app.getAppMetrics().find(item => item.pid === child.pid)!;
  110. expect(details).to.be.an('object');
  111. expect(details.type).to.equal('Utility');
  112. expect(details.serviceName).to.to.equal('node.mojom.NodeService');
  113. expect(details.name).to.equal('Node Utility Process');
  114. });
  115. it('with custom serviceName', async () => {
  116. const child = utilityProcess.fork(path.join(fixturesPath, 'endless.js'), [], { serviceName: 'Hello World!' });
  117. await once(child, 'spawn');
  118. expect(child.pid).to.not.be.null();
  119. await setImmediate();
  120. const details = app.getAppMetrics().find(item => item.pid === child.pid)!;
  121. expect(details).to.be.an('object');
  122. expect(details.type).to.equal('Utility');
  123. expect(details.serviceName).to.to.equal('node.mojom.NodeService');
  124. expect(details.name).to.equal('Hello World!');
  125. });
  126. });
  127. describe('kill() API', () => {
  128. it('terminates the child process gracefully', async () => {
  129. const child = utilityProcess.fork(path.join(fixturesPath, 'endless.js'), [], {
  130. serviceName: 'endless'
  131. });
  132. await once(child, 'spawn');
  133. expect(child.kill()).to.be.true();
  134. await once(child, 'exit');
  135. });
  136. });
  137. describe('esm', () => {
  138. it('is launches an mjs file', async () => {
  139. const fixtureFile = path.join(fixturesPath, 'esm.mjs');
  140. const child = utilityProcess.fork(fixtureFile, [], {
  141. stdio: 'pipe'
  142. });
  143. await once(child, 'spawn');
  144. expect(child.stdout).to.not.be.null();
  145. let log = '';
  146. child.stdout!.on('data', (chunk) => {
  147. log += chunk.toString('utf8');
  148. });
  149. await once(child, 'exit');
  150. expect(log).to.equal(pathToFileURL(fixtureFile) + '\n');
  151. });
  152. });
  153. describe('pid property', () => {
  154. it('is valid when child process launches successfully', async () => {
  155. const child = utilityProcess.fork(path.join(fixturesPath, 'empty.js'));
  156. await once(child, 'spawn');
  157. expect(child.pid).to.not.be.null();
  158. });
  159. it('is undefined when child process fails to launch', async () => {
  160. const child = utilityProcess.fork(path.join(fixturesPath, 'does-not-exist.js'));
  161. expect(child.pid).to.be.undefined();
  162. });
  163. });
  164. describe('stdout property', () => {
  165. it('is null when child process launches with default stdio', async () => {
  166. const child = utilityProcess.fork(path.join(fixturesPath, 'log.js'));
  167. await once(child, 'spawn');
  168. expect(child.stdout).to.be.null();
  169. expect(child.stderr).to.be.null();
  170. await once(child, 'exit');
  171. });
  172. it('is null when child process launches with ignore stdio configuration', async () => {
  173. const child = utilityProcess.fork(path.join(fixturesPath, 'log.js'), [], {
  174. stdio: 'ignore'
  175. });
  176. await once(child, 'spawn');
  177. expect(child.stdout).to.be.null();
  178. expect(child.stderr).to.be.null();
  179. await once(child, 'exit');
  180. });
  181. it('is valid when child process launches with pipe stdio configuration', async () => {
  182. const child = utilityProcess.fork(path.join(fixturesPath, 'log.js'), [], {
  183. stdio: 'pipe'
  184. });
  185. await once(child, 'spawn');
  186. expect(child.stdout).to.not.be.null();
  187. let log = '';
  188. child.stdout!.on('data', (chunk) => {
  189. log += chunk.toString('utf8');
  190. });
  191. await once(child, 'exit');
  192. expect(log).to.equal('hello\n');
  193. });
  194. });
  195. describe('stderr property', () => {
  196. it('is null when child process launches with default stdio', async () => {
  197. const child = utilityProcess.fork(path.join(fixturesPath, 'log.js'));
  198. await once(child, 'spawn');
  199. expect(child.stdout).to.be.null();
  200. expect(child.stderr).to.be.null();
  201. await once(child, 'exit');
  202. });
  203. it('is null when child process launches with ignore stdio configuration', async () => {
  204. const child = utilityProcess.fork(path.join(fixturesPath, 'log.js'), [], {
  205. stdio: 'ignore'
  206. });
  207. await once(child, 'spawn');
  208. expect(child.stderr).to.be.null();
  209. await once(child, 'exit');
  210. });
  211. ifit(!isWindowsOnArm)('is valid when child process launches with pipe stdio configuration', async () => {
  212. const child = utilityProcess.fork(path.join(fixturesPath, 'log.js'), [], {
  213. stdio: ['ignore', 'pipe', 'pipe']
  214. });
  215. await once(child, 'spawn');
  216. expect(child.stderr).to.not.be.null();
  217. let log = '';
  218. child.stderr!.on('data', (chunk) => {
  219. log += chunk.toString('utf8');
  220. });
  221. await once(child, 'exit');
  222. expect(log).to.equal('world');
  223. });
  224. });
  225. describe('postMessage() API', () => {
  226. it('establishes a default ipc channel with the child process', async () => {
  227. const result = 'I will be echoed.';
  228. const child = utilityProcess.fork(path.join(fixturesPath, 'post-message.js'));
  229. await once(child, 'spawn');
  230. child.postMessage(result);
  231. const [data] = await once(child, 'message');
  232. expect(data).to.equal(result);
  233. const exit = once(child, 'exit');
  234. expect(child.kill()).to.be.true();
  235. await exit;
  236. });
  237. it('supports queuing messages on the receiving end', async () => {
  238. const child = utilityProcess.fork(path.join(fixturesPath, 'post-message-queue.js'));
  239. const p = once(child, 'spawn');
  240. child.postMessage('This message');
  241. child.postMessage(' is');
  242. child.postMessage(' queued');
  243. await p;
  244. const [data] = await once(child, 'message');
  245. expect(data).to.equal('This message is queued');
  246. const exit = once(child, 'exit');
  247. expect(child.kill()).to.be.true();
  248. await exit;
  249. });
  250. });
  251. describe('behavior', () => {
  252. it('supports starting the v8 inspector with --inspect-brk', (done) => {
  253. const child = utilityProcess.fork(path.join(fixturesPath, 'log.js'), [], {
  254. stdio: 'pipe',
  255. execArgv: ['--inspect-brk']
  256. });
  257. let output = '';
  258. const cleanup = () => {
  259. child.stderr!.removeListener('data', listener);
  260. child.stdout!.removeListener('data', listener);
  261. child.once('exit', () => { done(); });
  262. child.kill();
  263. };
  264. const listener = (data: Buffer) => {
  265. output += data;
  266. if (/Debugger listening on ws:/m.test(output)) {
  267. cleanup();
  268. }
  269. };
  270. child.stderr!.on('data', listener);
  271. child.stdout!.on('data', listener);
  272. });
  273. it('supports starting the v8 inspector with --inspect and a provided port', (done) => {
  274. const child = utilityProcess.fork(path.join(fixturesPath, 'log.js'), [], {
  275. stdio: 'pipe',
  276. execArgv: ['--inspect=17364']
  277. });
  278. let output = '';
  279. const cleanup = () => {
  280. child.stderr!.removeListener('data', listener);
  281. child.stdout!.removeListener('data', listener);
  282. child.once('exit', () => { done(); });
  283. child.kill();
  284. };
  285. const listener = (data: Buffer) => {
  286. output += data;
  287. if (/Debugger listening on ws:/m.test(output)) {
  288. expect(output.trim()).to.contain(':17364', 'should be listening on port 17364');
  289. cleanup();
  290. }
  291. };
  292. child.stderr!.on('data', listener);
  293. child.stdout!.on('data', listener);
  294. });
  295. it('supports changing dns verbatim with --dns-result-order', (done) => {
  296. const child = utilityProcess.fork(path.join(fixturesPath, 'dns-result-order.js'), [], {
  297. stdio: 'pipe',
  298. execArgv: ['--dns-result-order=ipv4first']
  299. });
  300. let output = '';
  301. const cleanup = () => {
  302. child.stderr!.removeListener('data', listener);
  303. child.stdout!.removeListener('data', listener);
  304. child.once('exit', () => { done(); });
  305. child.kill();
  306. };
  307. const listener = (data: Buffer) => {
  308. output += data;
  309. expect(output.trim()).to.contain('ipv4first', 'default verbatim should be ipv4first');
  310. cleanup();
  311. };
  312. child.stderr!.on('data', listener);
  313. child.stdout!.on('data', listener);
  314. });
  315. ifit(process.platform !== 'win32')('supports redirecting stdout to parent process', async () => {
  316. const result = 'Output from utility process';
  317. const appProcess = childProcess.spawn(process.execPath, [path.join(fixturesPath, 'inherit-stdout'), `--payload=${result}`]);
  318. let output = '';
  319. appProcess.stdout.on('data', (data: Buffer) => { output += data; });
  320. await once(appProcess, 'exit');
  321. expect(output).to.equal(result);
  322. });
  323. ifit(process.platform !== 'win32')('supports redirecting stderr to parent process', async () => {
  324. const result = 'Error from utility process';
  325. const appProcess = childProcess.spawn(process.execPath, [path.join(fixturesPath, 'inherit-stderr'), `--payload=${result}`]);
  326. let output = '';
  327. appProcess.stderr.on('data', (data: Buffer) => { output += data; });
  328. await once(appProcess, 'exit');
  329. expect(output).to.include(result);
  330. });
  331. it('can establish communication channel with sandboxed renderer', async () => {
  332. const result = 'Message from sandboxed renderer';
  333. const w = new BrowserWindow({
  334. show: false,
  335. webPreferences: {
  336. preload: path.join(fixturesPath, 'preload.js')
  337. }
  338. });
  339. await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  340. // Create Message port pair for Renderer <-> Utility Process.
  341. const { port1: rendererPort, port2: childPort1 } = new MessageChannelMain();
  342. w.webContents.postMessage('port', result, [rendererPort]);
  343. // Send renderer and main channel port to utility process.
  344. const child = utilityProcess.fork(path.join(fixturesPath, 'receive-message.js'));
  345. await once(child, 'spawn');
  346. child.postMessage('', [childPort1]);
  347. const [data] = await once(child, 'message');
  348. expect(data).to.equal(result);
  349. // Cleanup.
  350. const exit = once(child, 'exit');
  351. expect(child.kill()).to.be.true();
  352. await exit;
  353. await closeWindow(w);
  354. });
  355. ifit(process.platform === 'linux')('allows executing a setuid binary with child_process', async () => {
  356. const child = utilityProcess.fork(path.join(fixturesPath, 'suid.js'));
  357. await once(child, 'spawn');
  358. const [data] = await once(child, 'message');
  359. expect(data).to.not.be.empty();
  360. const exit = once(child, 'exit');
  361. expect(child.kill()).to.be.true();
  362. await exit;
  363. });
  364. it('inherits parent env as default', async () => {
  365. const appProcess = childProcess.spawn(process.execPath, [path.join(fixturesPath, 'env-app')], {
  366. env: {
  367. FROM: 'parent',
  368. ...process.env
  369. }
  370. });
  371. let output = '';
  372. appProcess.stdout.on('data', (data: Buffer) => { output += data; });
  373. await once(appProcess.stdout, 'end');
  374. const result = process.platform === 'win32' ? '\r\nparent' : 'parent';
  375. expect(output).to.equal(result);
  376. });
  377. it('does not inherit parent env when custom env is provided', async () => {
  378. const appProcess = childProcess.spawn(process.execPath, [path.join(fixturesPath, 'env-app'), '--create-custom-env'], {
  379. env: {
  380. FROM: 'parent',
  381. ...process.env
  382. }
  383. });
  384. let output = '';
  385. appProcess.stdout.on('data', (data: Buffer) => { output += data; });
  386. await once(appProcess.stdout, 'end');
  387. const result = process.platform === 'win32' ? '\r\nchild' : 'child';
  388. expect(output).to.equal(result);
  389. });
  390. it('changes working directory with cwd', async () => {
  391. const child = utilityProcess.fork('./log.js', [], {
  392. cwd: fixturesPath,
  393. stdio: ['ignore', 'pipe', 'ignore']
  394. });
  395. await once(child, 'spawn');
  396. expect(child.stdout).to.not.be.null();
  397. let log = '';
  398. child.stdout!.on('data', (chunk) => {
  399. log += chunk.toString('utf8');
  400. });
  401. await once(child, 'exit');
  402. expect(log).to.equal('hello\n');
  403. });
  404. it('does not crash when running eval', async () => {
  405. const child = utilityProcess.fork('./eval.js', [], {
  406. cwd: fixturesPath,
  407. stdio: 'ignore'
  408. });
  409. await once(child, 'spawn');
  410. const [data] = await once(child, 'message');
  411. expect(data).to.equal(42);
  412. // Cleanup.
  413. const exit = once(child, 'exit');
  414. expect(child.kill()).to.be.true();
  415. await exit;
  416. });
  417. });
  418. });