api-utility-process-spec.ts 19 KB

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