api-utility-process-spec.ts 29 KB

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