api-utility-process-spec.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784
  1. import { systemPreferences } from 'electron';
  2. import { BrowserWindow, MessageChannelMain, utilityProcess, app } from 'electron/main';
  3. import { expect } from 'chai';
  4. import * as childProcess from 'node:child_process';
  5. import { once } from 'node:events';
  6. import * as fs from 'node:fs/promises';
  7. import * as os from 'node:os';
  8. import * as path from 'node:path';
  9. import { setImmediate } from 'node:timers/promises';
  10. import { pathToFileURL } from 'node:url';
  11. import { respondOnce, randomString, kOneKiloByte } from './lib/net-helpers';
  12. import { ifit, startRemoteControlApp } from './lib/spec-helpers';
  13. import { closeWindow } from './lib/window-helpers';
  14. const fixturesPath = path.resolve(__dirname, 'fixtures', 'api', 'utility-process');
  15. const isWindowsOnArm = process.platform === 'win32' && process.arch === 'arm64';
  16. const isWindows32Bit = process.platform === 'win32' && process.arch === 'ia32';
  17. describe('utilityProcess module', () => {
  18. describe('UtilityProcess constructor', () => {
  19. it('throws when empty script path is provided', async () => {
  20. expect(() => {
  21. utilityProcess.fork('');
  22. }).to.throw();
  23. });
  24. it('throws when options.stdio is not valid', async () => {
  25. expect(() => {
  26. utilityProcess.fork(path.join(fixturesPath, 'empty.js'), [], {
  27. execArgv: ['--test', '--test2'],
  28. serviceName: 'test',
  29. stdio: 'ipc'
  30. });
  31. }).to.throw(/stdio must be of the following values: inherit, pipe, ignore/);
  32. expect(() => {
  33. utilityProcess.fork(path.join(fixturesPath, 'empty.js'), [], {
  34. execArgv: ['--test', '--test2'],
  35. serviceName: 'test',
  36. stdio: ['ignore', 'ignore']
  37. });
  38. }).to.throw(/configuration missing for stdin, stdout or stderr/);
  39. expect(() => {
  40. utilityProcess.fork(path.join(fixturesPath, 'empty.js'), [], {
  41. execArgv: ['--test', '--test2'],
  42. serviceName: 'test',
  43. stdio: ['pipe', 'inherit', 'inherit']
  44. });
  45. }).to.throw(/stdin value other than ignore is not supported/);
  46. });
  47. });
  48. describe('lifecycle events', () => {
  49. it('emits \'spawn\' when child process successfully launches', async () => {
  50. const child = utilityProcess.fork(path.join(fixturesPath, 'empty.js'));
  51. await once(child, 'spawn');
  52. });
  53. it('emits \'exit\' when child process exits gracefully', (done) => {
  54. const child = utilityProcess.fork(path.join(fixturesPath, 'empty.js'));
  55. child.on('exit', (code) => {
  56. expect(code).to.equal(0);
  57. done();
  58. });
  59. });
  60. it('emits \'exit\' when the child process file does not exist', (done) => {
  61. const child = utilityProcess.fork('nonexistent');
  62. child.on('exit', (code) => {
  63. expect(code).to.equal(1);
  64. done();
  65. });
  66. });
  67. ifit(!isWindows32Bit)('emits the correct error code when child process exits nonzero', async () => {
  68. const child = utilityProcess.fork(path.join(fixturesPath, 'empty.js'));
  69. await once(child, 'spawn');
  70. const exit = once(child, 'exit');
  71. process.kill(child.pid!);
  72. const [code] = await exit;
  73. expect(code).to.not.equal(0);
  74. });
  75. ifit(!isWindows32Bit)('emits the correct error code when child process is killed', async () => {
  76. const child = utilityProcess.fork(path.join(fixturesPath, 'empty.js'));
  77. await once(child, 'spawn');
  78. const exit = once(child, 'exit');
  79. process.kill(child.pid!);
  80. const [code] = await exit;
  81. expect(code).to.not.equal(0);
  82. });
  83. ifit(!isWindows32Bit)('emits \'exit\' when child process crashes', async () => {
  84. const child = utilityProcess.fork(path.join(fixturesPath, 'crash.js'));
  85. // SIGSEGV code can differ across pipelines but should never be 0.
  86. const [code] = await once(child, 'exit');
  87. expect(code).to.not.equal(0);
  88. });
  89. ifit(!isWindows32Bit)('emits \'exit\' corresponding to the child process', async () => {
  90. const child1 = utilityProcess.fork(path.join(fixturesPath, 'endless.js'));
  91. await once(child1, 'spawn');
  92. const child2 = utilityProcess.fork(path.join(fixturesPath, 'crash.js'));
  93. await once(child2, 'exit');
  94. expect(child1.kill()).to.be.true();
  95. await once(child1, 'exit');
  96. });
  97. it('emits \'exit\' when there is uncaught exception', async () => {
  98. const child = utilityProcess.fork(path.join(fixturesPath, 'exception.js'));
  99. const [code] = await once(child, 'exit');
  100. expect(code).to.equal(1);
  101. });
  102. it('emits \'exit\' when there is uncaught exception in ESM', async () => {
  103. const child = utilityProcess.fork(path.join(fixturesPath, 'exception.mjs'));
  104. const [code] = await once(child, 'exit');
  105. expect(code).to.equal(1);
  106. });
  107. it('emits \'exit\' when process.exit is called', async () => {
  108. const exitCode = 2;
  109. const child = utilityProcess.fork(path.join(fixturesPath, 'custom-exit.js'), [`--exitCode=${exitCode}`]);
  110. const [code] = await once(child, 'exit');
  111. expect(code).to.equal(exitCode);
  112. });
  113. // 32-bit system will not have V8 Sandbox enabled.
  114. // WoA testing does not have VS toolchain configured to build native addons.
  115. ifit(process.arch !== 'ia32' && process.arch !== 'arm' && !isWindowsOnArm)('emits \'error\' when fatal error is triggered from V8', async () => {
  116. const child = utilityProcess.fork(path.join(fixturesPath, 'external-ab-test.js'));
  117. const [type, location, report] = await once(child, 'error');
  118. const [code] = await once(child, 'exit');
  119. expect(type).to.equal('FatalError');
  120. expect(location).to.equal('v8_ArrayBuffer_NewBackingStore');
  121. const reportJSON = JSON.parse(report);
  122. expect(reportJSON.header.trigger).to.equal('v8_ArrayBuffer_NewBackingStore');
  123. const addonPath = path.join(require.resolve('@electron-ci/external-ab'), '..', '..', 'build', 'Release', 'external_ab.node');
  124. expect(reportJSON.sharedObjects).to.include(path.toNamespacedPath(addonPath));
  125. expect(code).to.not.equal(0);
  126. });
  127. });
  128. describe('app \'child-process-gone\' event', () => {
  129. const waitForCrash = (name: string) => {
  130. return new Promise<Electron.Details>((resolve) => {
  131. app.on('child-process-gone', function onCrash (_event, details) {
  132. if (details.name === name) {
  133. app.off('child-process-gone', onCrash);
  134. resolve(details);
  135. }
  136. });
  137. });
  138. };
  139. ifit(!isWindows32Bit)('with default serviceName', async () => {
  140. const name = 'Node Utility Process';
  141. const crashPromise = waitForCrash(name);
  142. utilityProcess.fork(path.join(fixturesPath, 'crash.js'));
  143. const details = await crashPromise;
  144. expect(details.type).to.equal('Utility');
  145. expect(details.serviceName).to.equal('node.mojom.NodeService');
  146. expect(details.name).to.equal(name);
  147. expect(details.reason).to.be.oneOf(['crashed', 'abnormal-exit']);
  148. });
  149. ifit(!isWindows32Bit)('with custom serviceName', async () => {
  150. const name = crypto.randomUUID();
  151. const crashPromise = waitForCrash(name);
  152. utilityProcess.fork(path.join(fixturesPath, 'crash.js'), [], { serviceName: name });
  153. const details = await crashPromise;
  154. expect(details.type).to.equal('Utility');
  155. expect(details.serviceName).to.equal('node.mojom.NodeService');
  156. expect(details.name).to.equal(name);
  157. expect(details.reason).to.be.oneOf(['crashed', 'abnormal-exit']);
  158. });
  159. });
  160. describe('app.getAppMetrics()', () => {
  161. it('with default serviceName', async () => {
  162. const child = utilityProcess.fork(path.join(fixturesPath, 'endless.js'));
  163. await once(child, 'spawn');
  164. expect(child.pid).to.not.be.null();
  165. await setImmediate();
  166. const details = app.getAppMetrics().find(item => item.pid === child.pid)!;
  167. expect(details).to.be.an('object');
  168. expect(details.type).to.equal('Utility');
  169. expect(details.serviceName).to.to.equal('node.mojom.NodeService');
  170. expect(details.name).to.equal('Node Utility Process');
  171. });
  172. it('with custom serviceName', async () => {
  173. const child = utilityProcess.fork(path.join(fixturesPath, 'endless.js'), [], { serviceName: 'Hello World!' });
  174. await once(child, 'spawn');
  175. expect(child.pid).to.not.be.null();
  176. await setImmediate();
  177. const details = app.getAppMetrics().find(item => item.pid === child.pid)!;
  178. expect(details).to.be.an('object');
  179. expect(details.type).to.equal('Utility');
  180. expect(details.serviceName).to.to.equal('node.mojom.NodeService');
  181. expect(details.name).to.equal('Hello World!');
  182. });
  183. });
  184. describe('kill() API', () => {
  185. it('terminates the child process gracefully', async () => {
  186. const child = utilityProcess.fork(path.join(fixturesPath, 'endless.js'), [], {
  187. serviceName: 'endless'
  188. });
  189. await once(child, 'spawn');
  190. expect(child.kill()).to.be.true();
  191. const [code] = await once(child, 'exit');
  192. expect(code).to.equal(0);
  193. });
  194. });
  195. describe('esm', () => {
  196. it('is launches an mjs file', async () => {
  197. const fixtureFile = path.join(fixturesPath, 'esm.mjs');
  198. const child = utilityProcess.fork(fixtureFile, [], {
  199. stdio: 'pipe'
  200. });
  201. expect(child.stdout).to.not.be.null();
  202. let log = '';
  203. child.stdout!.on('data', (chunk) => {
  204. log += chunk.toString('utf8');
  205. });
  206. await once(child, 'exit');
  207. expect(log).to.equal(pathToFileURL(fixtureFile) + '\n');
  208. });
  209. });
  210. describe('pid property', () => {
  211. it('is valid when child process launches successfully', async () => {
  212. const child = utilityProcess.fork(path.join(fixturesPath, 'empty.js'));
  213. await once(child, 'spawn');
  214. expect(child).to.have.property('pid').that.is.a('number');
  215. });
  216. it('is undefined when child process fails to launch', async () => {
  217. const child = utilityProcess.fork(path.join(fixturesPath, 'does-not-exist.js'));
  218. expect(child.pid).to.be.undefined();
  219. });
  220. it('is undefined before the child process is spawned succesfully', async () => {
  221. const child = utilityProcess.fork(path.join(fixturesPath, 'empty.js'));
  222. expect(child.pid).to.be.undefined();
  223. await once(child, 'spawn');
  224. child.kill();
  225. });
  226. it('is undefined when child process is killed', async () => {
  227. const child = utilityProcess.fork(path.join(fixturesPath, 'empty.js'));
  228. await once(child, 'spawn');
  229. expect(child).to.have.property('pid').that.is.a('number');
  230. expect(child.kill()).to.be.true();
  231. await once(child, 'exit');
  232. expect(child.pid).to.be.undefined();
  233. });
  234. });
  235. describe('stdout property', () => {
  236. it('is null when child process launches with default stdio', async () => {
  237. const child = utilityProcess.fork(path.join(fixturesPath, 'log.js'));
  238. await once(child, 'spawn');
  239. expect(child.stdout).to.be.null();
  240. expect(child.stderr).to.be.null();
  241. await once(child, 'exit');
  242. });
  243. it('is null when child process launches with ignore stdio configuration', async () => {
  244. const child = utilityProcess.fork(path.join(fixturesPath, 'log.js'), [], {
  245. stdio: 'ignore'
  246. });
  247. await once(child, 'spawn');
  248. expect(child.stdout).to.be.null();
  249. expect(child.stderr).to.be.null();
  250. await once(child, 'exit');
  251. });
  252. it('is valid when child process launches with pipe stdio configuration', async () => {
  253. const child = utilityProcess.fork(path.join(fixturesPath, 'log.js'), [], {
  254. stdio: 'pipe'
  255. });
  256. expect(child.stdout).to.not.be.null();
  257. let log = '';
  258. child.stdout!.on('data', (chunk) => {
  259. log += chunk.toString('utf8');
  260. });
  261. await once(child, 'exit');
  262. expect(log).to.equal('hello\n');
  263. });
  264. });
  265. describe('stderr property', () => {
  266. it('is null when child process launches with default stdio', async () => {
  267. const child = utilityProcess.fork(path.join(fixturesPath, 'log.js'));
  268. await once(child, 'spawn');
  269. expect(child.stdout).to.be.null();
  270. expect(child.stderr).to.be.null();
  271. await once(child, 'exit');
  272. });
  273. it('is null when child process launches with ignore stdio configuration', async () => {
  274. const child = utilityProcess.fork(path.join(fixturesPath, 'log.js'), [], {
  275. stdio: 'ignore'
  276. });
  277. await once(child, 'spawn');
  278. expect(child.stderr).to.be.null();
  279. await once(child, 'exit');
  280. });
  281. ifit(!isWindowsOnArm)('is valid when child process launches with pipe stdio configuration', async () => {
  282. const child = utilityProcess.fork(path.join(fixturesPath, 'log.js'), [], {
  283. stdio: ['ignore', 'pipe', 'pipe']
  284. });
  285. expect(child.stderr).to.not.be.null();
  286. let log = '';
  287. child.stderr!.on('data', (chunk) => {
  288. log += chunk.toString('utf8');
  289. });
  290. await once(child, 'exit');
  291. expect(log).to.equal('world');
  292. });
  293. });
  294. describe('postMessage() API', () => {
  295. it('establishes a default ipc channel with the child process', async () => {
  296. const result = 'I will be echoed.';
  297. const child = utilityProcess.fork(path.join(fixturesPath, 'post-message.js'));
  298. await once(child, 'spawn');
  299. child.postMessage(result);
  300. const [data] = await once(child, 'message');
  301. expect(data).to.equal(result);
  302. const exit = once(child, 'exit');
  303. expect(child.kill()).to.be.true();
  304. await exit;
  305. });
  306. it('supports queuing messages on the receiving end', async () => {
  307. const child = utilityProcess.fork(path.join(fixturesPath, 'post-message-queue.js'));
  308. const p = once(child, 'spawn');
  309. child.postMessage('This message');
  310. child.postMessage(' is');
  311. child.postMessage(' queued');
  312. await p;
  313. const [data] = await once(child, 'message');
  314. expect(data).to.equal('This message is queued');
  315. const exit = once(child, 'exit');
  316. expect(child.kill()).to.be.true();
  317. await exit;
  318. });
  319. it('handles the parent port trying to send an non-clonable object', async () => {
  320. const child = utilityProcess.fork(path.join(fixturesPath, 'non-cloneable.js'));
  321. await once(child, 'spawn');
  322. child.postMessage('non-cloneable');
  323. const [data] = await once(child, 'message');
  324. expect(data).to.equal('caught-non-cloneable');
  325. const exit = once(child, 'exit');
  326. expect(child.kill()).to.be.true();
  327. await exit;
  328. });
  329. });
  330. describe('behavior', () => {
  331. it('supports starting the v8 inspector with --inspect-brk', (done) => {
  332. const child = utilityProcess.fork(path.join(fixturesPath, 'log.js'), [], {
  333. stdio: 'pipe',
  334. execArgv: ['--inspect-brk']
  335. });
  336. let output = '';
  337. const cleanup = () => {
  338. child.stderr!.removeListener('data', listener);
  339. child.stdout!.removeListener('data', listener);
  340. child.once('exit', () => { done(); });
  341. child.kill();
  342. };
  343. const listener = (data: Buffer) => {
  344. output += data;
  345. if (/Debugger listening on ws:/m.test(output)) {
  346. cleanup();
  347. }
  348. };
  349. child.stderr!.on('data', listener);
  350. child.stdout!.on('data', listener);
  351. });
  352. it('supports starting the v8 inspector with --inspect and a provided port', (done) => {
  353. const child = utilityProcess.fork(path.join(fixturesPath, 'log.js'), [], {
  354. stdio: 'pipe',
  355. execArgv: ['--inspect=17364']
  356. });
  357. let output = '';
  358. const cleanup = () => {
  359. child.stderr!.removeListener('data', listener);
  360. child.stdout!.removeListener('data', listener);
  361. child.once('exit', () => { done(); });
  362. child.kill();
  363. };
  364. const listener = (data: Buffer) => {
  365. output += data;
  366. if (/Debugger listening on ws:/m.test(output)) {
  367. expect(output.trim()).to.contain(':17364', 'should be listening on port 17364');
  368. cleanup();
  369. }
  370. };
  371. child.stderr!.on('data', listener);
  372. child.stdout!.on('data', listener);
  373. });
  374. it('supports changing dns verbatim with --dns-result-order', (done) => {
  375. const child = utilityProcess.fork(path.join(fixturesPath, 'dns-result-order.js'), [], {
  376. stdio: 'pipe',
  377. execArgv: ['--dns-result-order=ipv4first']
  378. });
  379. let output = '';
  380. const cleanup = () => {
  381. child.stderr!.removeListener('data', listener);
  382. child.stdout!.removeListener('data', listener);
  383. child.once('exit', () => { done(); });
  384. child.kill();
  385. };
  386. const listener = (data: Buffer) => {
  387. output += data;
  388. expect(output.trim()).to.contain('ipv4first', 'default verbatim should be ipv4first');
  389. cleanup();
  390. };
  391. child.stderr!.on('data', listener);
  392. child.stdout!.on('data', listener);
  393. });
  394. ifit(process.platform !== 'win32')('supports redirecting stdout to parent process', async () => {
  395. const result = 'Output from utility process';
  396. const appProcess = childProcess.spawn(process.execPath, [path.join(fixturesPath, 'inherit-stdout'), `--payload=${result}`]);
  397. let output = '';
  398. appProcess.stdout.on('data', (data: Buffer) => { output += data; });
  399. await once(appProcess, 'exit');
  400. expect(output).to.equal(result);
  401. });
  402. ifit(process.platform !== 'win32')('supports redirecting stderr to parent process', async () => {
  403. const result = 'Error from utility process';
  404. const appProcess = childProcess.spawn(process.execPath, [path.join(fixturesPath, 'inherit-stderr'), `--payload=${result}`]);
  405. let output = '';
  406. appProcess.stderr.on('data', (data: Buffer) => { output += data; });
  407. await once(appProcess, 'exit');
  408. expect(output).to.include(result);
  409. });
  410. ifit(process.platform !== 'linux')('can access exposed main process modules from the utility process', async () => {
  411. const message = 'Message from utility process';
  412. const child = utilityProcess.fork(path.join(fixturesPath, 'expose-main-process-module.js'));
  413. await once(child, 'spawn');
  414. child.postMessage(message);
  415. const [data] = await once(child, 'message');
  416. expect(data).to.equal(systemPreferences.getMediaAccessStatus('screen'));
  417. const exit = once(child, 'exit');
  418. expect(child.kill()).to.be.true();
  419. await exit;
  420. });
  421. it('can establish communication channel with sandboxed renderer', async () => {
  422. const result = 'Message from sandboxed renderer';
  423. const w = new BrowserWindow({
  424. show: false,
  425. webPreferences: {
  426. preload: path.join(fixturesPath, 'preload.js')
  427. }
  428. });
  429. await w.loadFile(path.join(__dirname, 'fixtures', 'blank.html'));
  430. // Create Message port pair for Renderer <-> Utility Process.
  431. const { port1: rendererPort, port2: childPort1 } = new MessageChannelMain();
  432. w.webContents.postMessage('port', result, [rendererPort]);
  433. // Send renderer and main channel port to utility process.
  434. const child = utilityProcess.fork(path.join(fixturesPath, 'receive-message.js'));
  435. await once(child, 'spawn');
  436. child.postMessage('', [childPort1]);
  437. const [data] = await once(child, 'message');
  438. expect(data).to.equal(result);
  439. // Cleanup.
  440. const exit = once(child, 'exit');
  441. expect(child.kill()).to.be.true();
  442. await exit;
  443. await closeWindow(w);
  444. });
  445. ifit(process.platform === 'linux')('allows executing a setuid binary with child_process', async () => {
  446. const child = utilityProcess.fork(path.join(fixturesPath, 'suid.js'));
  447. await once(child, 'spawn');
  448. const [data] = await once(child, 'message');
  449. expect(data).to.not.be.empty();
  450. const exit = once(child, 'exit');
  451. expect(child.kill()).to.be.true();
  452. await exit;
  453. });
  454. it('inherits parent env as default', async () => {
  455. const appProcess = childProcess.spawn(process.execPath, [path.join(fixturesPath, 'env-app')], {
  456. env: {
  457. FROM: 'parent',
  458. ...process.env
  459. }
  460. });
  461. let output = '';
  462. appProcess.stdout.on('data', (data: Buffer) => { output += data; });
  463. await once(appProcess.stdout, 'end');
  464. const result = process.platform === 'win32' ? '\r\nparent' : 'parent';
  465. expect(output).to.equal(result);
  466. });
  467. // TODO(codebytere): figure out why this is failing in ASAN- builds on Linux.
  468. ifit(!process.env.IS_ASAN)('does not inherit parent env when custom env is provided', async () => {
  469. const appProcess = childProcess.spawn(process.execPath, [path.join(fixturesPath, 'env-app'), '--create-custom-env'], {
  470. env: {
  471. FROM: 'parent',
  472. ...process.env
  473. }
  474. });
  475. let output = '';
  476. appProcess.stdout.on('data', (data: Buffer) => { output += data; });
  477. await once(appProcess.stdout, 'end');
  478. const result = process.platform === 'win32' ? '\r\nchild' : 'child';
  479. expect(output).to.equal(result);
  480. });
  481. it('changes working directory with cwd', async () => {
  482. const child = utilityProcess.fork('./log.js', [], {
  483. cwd: fixturesPath,
  484. stdio: ['ignore', 'pipe', 'ignore']
  485. });
  486. await once(child, 'spawn');
  487. expect(child.stdout).to.not.be.null();
  488. let log = '';
  489. child.stdout!.on('data', (chunk) => {
  490. log += chunk.toString('utf8');
  491. });
  492. await once(child, 'exit');
  493. expect(log).to.equal('hello\n');
  494. });
  495. it('does not crash when running eval', async () => {
  496. const child = utilityProcess.fork('./eval.js', [], {
  497. cwd: fixturesPath,
  498. stdio: 'ignore'
  499. });
  500. await once(child, 'spawn');
  501. const [data] = await once(child, 'message');
  502. expect(data).to.equal(42);
  503. // Cleanup.
  504. const exit = once(child, 'exit');
  505. expect(child.kill()).to.be.true();
  506. await exit;
  507. });
  508. it('should emit the app#login event when 401', async () => {
  509. const { remotely } = await startRemoteControlApp();
  510. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  511. if (!request.headers.authorization) {
  512. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  513. }
  514. response.writeHead(200).end('ok');
  515. });
  516. const [loginAuthInfo, statusCode] = await remotely(async (serverUrl: string, fixture: string) => {
  517. const { app, utilityProcess } = require('electron');
  518. const { once } = require('node:events');
  519. const child = utilityProcess.fork(fixture, [`--server-url=${serverUrl}`], {
  520. stdio: 'ignore',
  521. respondToAuthRequestsFromMainProcess: true
  522. });
  523. await once(child, 'spawn');
  524. const [ev,,, authInfo, cb] = await once(app, 'login');
  525. ev.preventDefault();
  526. cb('dummy', 'pass');
  527. const [result] = await once(child, 'message');
  528. return [authInfo, ...result];
  529. }, serverUrl, path.join(fixturesPath, 'net.js'));
  530. expect(statusCode).to.equal(200);
  531. expect(loginAuthInfo!.realm).to.equal('Foo');
  532. expect(loginAuthInfo!.scheme).to.equal('basic');
  533. });
  534. it('should receive 401 response when cancelling authentication via app#login event', async () => {
  535. const { remotely } = await startRemoteControlApp();
  536. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  537. if (!request.headers.authorization) {
  538. response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' });
  539. response.end('unauthenticated');
  540. } else {
  541. response.writeHead(200).end('ok');
  542. }
  543. });
  544. const [authDetails, responseBody, statusCode] = await remotely(async (serverUrl: string, fixture: string) => {
  545. const { app, utilityProcess } = require('electron');
  546. const { once } = require('node:events');
  547. const child = utilityProcess.fork(fixture, [`--server-url=${serverUrl}`], {
  548. stdio: 'ignore',
  549. respondToAuthRequestsFromMainProcess: true
  550. });
  551. await once(child, 'spawn');
  552. const [,, details,, cb] = await once(app, 'login');
  553. cb();
  554. const [response] = await once(child, 'message');
  555. const [responseBody] = await once(child, 'message');
  556. return [details, responseBody, ...response];
  557. }, serverUrl, path.join(fixturesPath, 'net.js'));
  558. expect(authDetails.url).to.equal(serverUrl);
  559. expect(statusCode).to.equal(401);
  560. expect(responseBody).to.equal('unauthenticated');
  561. });
  562. it('should upload body when 401', async () => {
  563. const { remotely } = await startRemoteControlApp();
  564. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  565. if (!request.headers.authorization) {
  566. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  567. }
  568. response.writeHead(200);
  569. request.on('data', (chunk) => response.write(chunk));
  570. request.on('end', () => response.end());
  571. });
  572. const requestData = randomString(kOneKiloByte);
  573. const [authDetails, responseBody, statusCode] = await remotely(async (serverUrl: string, requestData: string, fixture: string) => {
  574. const { app, utilityProcess } = require('electron');
  575. const { once } = require('node:events');
  576. const child = utilityProcess.fork(fixture, [`--server-url=${serverUrl}`, '--request-data'], {
  577. stdio: 'ignore',
  578. respondToAuthRequestsFromMainProcess: true
  579. });
  580. await once(child, 'spawn');
  581. await once(child, 'message');
  582. child.postMessage(requestData);
  583. const [,, details,, cb] = await once(app, 'login');
  584. cb('user', 'pass');
  585. const [response] = await once(child, 'message');
  586. const [responseBody] = await once(child, 'message');
  587. return [details, responseBody, ...response];
  588. }, serverUrl, requestData, path.join(fixturesPath, 'net.js'));
  589. expect(authDetails.url).to.equal(serverUrl);
  590. expect(statusCode).to.equal(200);
  591. expect(responseBody).to.equal(requestData);
  592. });
  593. it('should not emit the app#login event when 401 with {"credentials":"omit"}', async () => {
  594. const rc = await startRemoteControlApp();
  595. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  596. if (!request.headers.authorization) {
  597. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  598. }
  599. response.writeHead(200).end('ok');
  600. });
  601. const [statusCode, responseHeaders] = await rc.remotely(async (serverUrl: string, fixture: string) => {
  602. const { app, utilityProcess } = require('electron');
  603. const { once } = require('node:events');
  604. let gracefulExit = true;
  605. const child = utilityProcess.fork(fixture, [`--server-url=${serverUrl}`, '--omit-credentials'], {
  606. stdio: 'ignore',
  607. respondToAuthRequestsFromMainProcess: true
  608. });
  609. await once(child, 'spawn');
  610. app.on('login', () => {
  611. gracefulExit = false;
  612. });
  613. const [result] = await once(child, 'message');
  614. setTimeout(() => {
  615. if (gracefulExit) {
  616. app.quit();
  617. } else {
  618. process.exit(1);
  619. }
  620. });
  621. return result;
  622. }, serverUrl, path.join(fixturesPath, 'net.js'));
  623. const [code] = await once(rc.process, 'exit');
  624. expect(code).to.equal(0);
  625. expect(statusCode).to.equal(401);
  626. expect(responseHeaders['www-authenticate']).to.equal('Basic realm="Foo"');
  627. });
  628. it('should not emit the app#login event with default respondToAuthRequestsFromMainProcess', async () => {
  629. const rc = await startRemoteControlApp();
  630. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  631. if (!request.headers.authorization) {
  632. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  633. }
  634. response.writeHead(200).end('ok');
  635. });
  636. const [loginAuthInfo, statusCode] = await rc.remotely(async (serverUrl: string, fixture: string) => {
  637. const { app, utilityProcess } = require('electron');
  638. const { once } = require('node:events');
  639. let gracefulExit = true;
  640. const child = utilityProcess.fork(fixture, [`--server-url=${serverUrl}`, '--use-net-login-event'], {
  641. stdio: 'ignore'
  642. });
  643. await once(child, 'spawn');
  644. app.on('login', () => {
  645. gracefulExit = false;
  646. });
  647. const [authInfo] = await once(child, 'message');
  648. const [result] = await once(child, 'message');
  649. setTimeout(() => {
  650. if (gracefulExit) {
  651. app.quit();
  652. } else {
  653. process.exit(1);
  654. }
  655. });
  656. return [authInfo, ...result];
  657. }, serverUrl, path.join(fixturesPath, 'net.js'));
  658. const [code] = await once(rc.process, 'exit');
  659. expect(code).to.equal(0);
  660. expect(statusCode).to.equal(200);
  661. expect(loginAuthInfo!.realm).to.equal('Foo');
  662. expect(loginAuthInfo!.scheme).to.equal('basic');
  663. });
  664. it('should emit the app#login event when creating requests with fetch API', async () => {
  665. const { remotely } = await startRemoteControlApp();
  666. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  667. if (!request.headers.authorization) {
  668. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  669. }
  670. response.writeHead(200).end('ok');
  671. });
  672. const [loginAuthInfo, statusCode] = await remotely(async (serverUrl: string, fixture: string) => {
  673. const { app, utilityProcess } = require('electron');
  674. const { once } = require('node:events');
  675. const child = utilityProcess.fork(fixture, [`--server-url=${serverUrl}`, '--use-fetch-api'], {
  676. stdio: 'ignore',
  677. respondToAuthRequestsFromMainProcess: true
  678. });
  679. await once(child, 'spawn');
  680. const [ev,,, authInfo, cb] = await once(app, 'login');
  681. ev.preventDefault();
  682. cb('dummy', 'pass');
  683. const [response] = await once(child, 'message');
  684. return [authInfo, ...response];
  685. }, serverUrl, path.join(fixturesPath, 'net.js'));
  686. expect(statusCode).to.equal(200);
  687. expect(loginAuthInfo!.realm).to.equal('Foo');
  688. expect(loginAuthInfo!.scheme).to.equal('basic');
  689. });
  690. it('supports generating snapshots via v8.setHeapSnapshotNearHeapLimit', async () => {
  691. const tmpDir = await fs.mkdtemp(path.resolve(os.tmpdir(), 'electron-spec-utility-oom-'));
  692. const child = utilityProcess.fork(path.join(fixturesPath, 'oom-grow.js'), [], {
  693. stdio: 'ignore',
  694. execArgv: [
  695. `--diagnostic-dir=${tmpDir}`,
  696. '--js-flags=--max-old-space-size=50'
  697. ],
  698. env: {
  699. NODE_DEBUG_NATIVE: 'diagnostic'
  700. }
  701. });
  702. await once(child, 'spawn');
  703. await once(child, 'exit');
  704. const files = (await fs.readdir(tmpDir)).filter((file) => file.endsWith('.heapsnapshot'));
  705. expect(files.length).to.be.equal(1);
  706. const stat = await fs.stat(path.join(tmpDir, files[0]));
  707. expect(stat.size).to.be.greaterThan(0);
  708. await fs.rm(tmpDir, { recursive: true });
  709. });
  710. });
  711. });