node-spec.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. const ChildProcess = require('child_process');
  2. const { expect } = require('chai');
  3. const fs = require('fs');
  4. const path = require('path');
  5. const os = require('os');
  6. const { ipcRenderer } = require('electron');
  7. const features = process._linkedBinding('electron_common_features');
  8. const { emittedOnce } = require('./events-helpers');
  9. const { ifit } = require('./spec-helpers');
  10. describe('node feature', () => {
  11. const fixtures = path.join(__dirname, 'fixtures');
  12. describe('child_process', () => {
  13. beforeEach(function () {
  14. if (!features.isRunAsNodeEnabled()) {
  15. this.skip();
  16. }
  17. });
  18. describe('child_process.fork', () => {
  19. it('works in current process', async () => {
  20. const child = ChildProcess.fork(path.join(fixtures, 'module', 'ping.js'));
  21. const message = emittedOnce(child, 'message');
  22. child.send('message');
  23. const [msg] = await message;
  24. expect(msg).to.equal('message');
  25. });
  26. it('preserves args', async () => {
  27. const args = ['--expose_gc', '-test', '1'];
  28. const child = ChildProcess.fork(path.join(fixtures, 'module', 'process_args.js'), args);
  29. const message = emittedOnce(child, 'message');
  30. child.send('message');
  31. const [msg] = await message;
  32. expect(args).to.deep.equal(msg.slice(2));
  33. });
  34. it('works in forked process', async () => {
  35. const child = ChildProcess.fork(path.join(fixtures, 'module', 'fork_ping.js'));
  36. const message = emittedOnce(child, 'message');
  37. child.send('message');
  38. const [msg] = await message;
  39. expect(msg).to.equal('message');
  40. });
  41. it('works in forked process when options.env is specifed', async () => {
  42. const child = ChildProcess.fork(path.join(fixtures, 'module', 'fork_ping.js'), [], {
  43. path: process.env.PATH
  44. });
  45. const message = emittedOnce(child, 'message');
  46. child.send('message');
  47. const [msg] = await message;
  48. expect(msg).to.equal('message');
  49. });
  50. it('has String::localeCompare working in script', async () => {
  51. const child = ChildProcess.fork(path.join(fixtures, 'module', 'locale-compare.js'));
  52. const message = emittedOnce(child, 'message');
  53. child.send('message');
  54. const [msg] = await message;
  55. expect(msg).to.deep.equal([0, -1, 1]);
  56. });
  57. it('has setImmediate working in script', async () => {
  58. const child = ChildProcess.fork(path.join(fixtures, 'module', 'set-immediate.js'));
  59. const message = emittedOnce(child, 'message');
  60. child.send('message');
  61. const [msg] = await message;
  62. expect(msg).to.equal('ok');
  63. });
  64. it('pipes stdio', async () => {
  65. const child = ChildProcess.fork(path.join(fixtures, 'module', 'process-stdout.js'), { silent: true });
  66. let data = '';
  67. child.stdout.on('data', (chunk) => {
  68. data += String(chunk);
  69. });
  70. const [code] = await emittedOnce(child, 'close');
  71. expect(code).to.equal(0);
  72. expect(data).to.equal('pipes stdio');
  73. });
  74. it('works when sending a message to a process forked with the --eval argument', async () => {
  75. const source = "process.on('message', (message) => { process.send(message) })";
  76. const forked = ChildProcess.fork('--eval', [source]);
  77. const message = emittedOnce(forked, 'message');
  78. forked.send('hello');
  79. const [msg] = await message;
  80. expect(msg).to.equal('hello');
  81. });
  82. it('has the electron version in process.versions', async () => {
  83. const source = 'process.send(process.versions)';
  84. const forked = ChildProcess.fork('--eval', [source]);
  85. const [message] = await emittedOnce(forked, 'message');
  86. expect(message)
  87. .to.have.own.property('electron')
  88. .that.is.a('string')
  89. .and.matches(/^\d+\.\d+\.\d+(\S*)?$/);
  90. });
  91. });
  92. describe('child_process.spawn', () => {
  93. let child;
  94. afterEach(() => {
  95. if (child != null) child.kill();
  96. });
  97. it('supports spawning Electron as a node process via the ELECTRON_RUN_AS_NODE env var', async () => {
  98. child = ChildProcess.spawn(process.execPath, [path.join(__dirname, 'fixtures', 'module', 'run-as-node.js')], {
  99. env: {
  100. ELECTRON_RUN_AS_NODE: true
  101. }
  102. });
  103. let output = '';
  104. child.stdout.on('data', data => {
  105. output += data;
  106. });
  107. await emittedOnce(child.stdout, 'close');
  108. expect(JSON.parse(output)).to.deep.equal({
  109. stdoutType: 'pipe',
  110. processType: 'undefined',
  111. window: 'undefined'
  112. });
  113. });
  114. });
  115. describe('child_process.exec', () => {
  116. (process.platform === 'linux' ? it : it.skip)('allows executing a setuid binary from non-sandboxed renderer', () => {
  117. // Chrome uses prctl(2) to set the NO_NEW_PRIVILEGES flag on Linux (see
  118. // https://github.com/torvalds/linux/blob/40fde647cc/Documentation/userspace-api/no_new_privs.rst).
  119. // We disable this for unsandboxed processes, which the renderer tests
  120. // are running in. If this test fails with an error like 'effective uid
  121. // is not 0', then it's likely that our patch to prevent the flag from
  122. // being set has become ineffective.
  123. const stdout = ChildProcess.execSync('sudo --help');
  124. expect(stdout).to.not.be.empty();
  125. });
  126. });
  127. });
  128. describe('contexts', () => {
  129. describe('setTimeout in fs callback', () => {
  130. it('does not crash', (done) => {
  131. fs.readFile(__filename, () => {
  132. setTimeout(done, 0);
  133. });
  134. });
  135. });
  136. describe('error thrown in renderer process node context', () => {
  137. it('gets emitted as a process uncaughtException event', (done) => {
  138. const error = new Error('boo!');
  139. const listeners = process.listeners('uncaughtException');
  140. process.removeAllListeners('uncaughtException');
  141. process.on('uncaughtException', (thrown) => {
  142. try {
  143. expect(thrown).to.equal(error);
  144. done();
  145. } catch (e) {
  146. done(e);
  147. } finally {
  148. process.removeAllListeners('uncaughtException');
  149. listeners.forEach((listener) => process.on('uncaughtException', listener));
  150. }
  151. });
  152. fs.readFile(__filename, () => {
  153. throw error;
  154. });
  155. });
  156. });
  157. describe('URL handling in the renderer process', () => {
  158. it('can successfully handle WHATWG URLs constructed by Blink', () => {
  159. const url = new URL('file://' + path.resolve(fixtures, 'pages', 'base-page.html'));
  160. expect(() => {
  161. fs.createReadStream(url);
  162. }).to.not.throw();
  163. });
  164. });
  165. describe('error thrown in main process node context', () => {
  166. it('gets emitted as a process uncaughtException event', () => {
  167. const error = ipcRenderer.sendSync('handle-uncaught-exception', 'hello');
  168. expect(error).to.equal('hello');
  169. });
  170. });
  171. describe('promise rejection in main process node context', () => {
  172. it('gets emitted as a process unhandledRejection event', () => {
  173. const error = ipcRenderer.sendSync('handle-unhandled-rejection', 'hello');
  174. expect(error).to.equal('hello');
  175. });
  176. });
  177. describe('setTimeout called under blink env in renderer process', () => {
  178. it('can be scheduled in time', (done) => {
  179. setTimeout(done, 10);
  180. });
  181. it('works from the timers module', (done) => {
  182. require('timers').setTimeout(done, 10);
  183. });
  184. });
  185. describe('setInterval called under blink env in renderer process', () => {
  186. it('can be scheduled in time', (done) => {
  187. const id = setInterval(() => {
  188. clearInterval(id);
  189. done();
  190. }, 10);
  191. });
  192. it('can be scheduled in time from timers module', (done) => {
  193. const { setInterval, clearInterval } = require('timers');
  194. const id = setInterval(() => {
  195. clearInterval(id);
  196. done();
  197. }, 10);
  198. });
  199. });
  200. });
  201. describe('message loop', () => {
  202. describe('process.nextTick', () => {
  203. it('emits the callback', (done) => process.nextTick(done));
  204. it('works in nested calls', (done) => {
  205. process.nextTick(() => {
  206. process.nextTick(() => process.nextTick(done));
  207. });
  208. });
  209. });
  210. describe('setImmediate', () => {
  211. it('emits the callback', (done) => setImmediate(done));
  212. it('works in nested calls', (done) => {
  213. setImmediate(() => {
  214. setImmediate(() => setImmediate(done));
  215. });
  216. });
  217. });
  218. });
  219. describe('net.connect', () => {
  220. before(function () {
  221. if (!features.isRunAsNodeEnabled() || process.platform !== 'darwin') {
  222. this.skip();
  223. }
  224. });
  225. it('emit error when connect to a socket path without listeners', async () => {
  226. const socketPath = path.join(os.tmpdir(), 'atom-shell-test.sock');
  227. const script = path.join(fixtures, 'module', 'create_socket.js');
  228. const child = ChildProcess.fork(script, [socketPath]);
  229. const [code] = await emittedOnce(child, 'exit');
  230. expect(code).to.equal(0);
  231. const client = require('net').connect(socketPath);
  232. const [error] = await emittedOnce(client, 'error');
  233. expect(error.code).to.equal('ECONNREFUSED');
  234. });
  235. });
  236. describe('Buffer', () => {
  237. it('can be created from WebKit external string', () => {
  238. const p = document.createElement('p');
  239. p.innerText = '闲云潭影日悠悠,物换星移几度秋';
  240. const b = Buffer.from(p.innerText);
  241. expect(b.toString()).to.equal('闲云潭影日悠悠,物换星移几度秋');
  242. expect(Buffer.byteLength(p.innerText)).to.equal(45);
  243. });
  244. it('correctly parses external one-byte UTF8 string', () => {
  245. const p = document.createElement('p');
  246. p.innerText = 'Jøhänñéß';
  247. const b = Buffer.from(p.innerText);
  248. expect(b.toString()).to.equal('Jøhänñéß');
  249. expect(Buffer.byteLength(p.innerText)).to.equal(13);
  250. });
  251. it('does not crash when creating large Buffers', () => {
  252. let buffer = Buffer.from(new Array(4096).join(' '));
  253. expect(buffer.length).to.equal(4095);
  254. buffer = Buffer.from(new Array(4097).join(' '));
  255. expect(buffer.length).to.equal(4096);
  256. });
  257. it('does not crash for crypto operations', () => {
  258. const crypto = require('crypto');
  259. const data = 'lG9E+/g4JmRmedDAnihtBD4Dfaha/GFOjd+xUOQI05UtfVX3DjUXvrS98p7kZQwY3LNhdiFo7MY5rGft8yBuDhKuNNag9vRx/44IuClDhdQ=';
  260. const key = 'q90K9yBqhWZnAMCMTOJfPQ==';
  261. const cipherText = '{"error_code":114,"error_message":"Tham số không hợp lệ","data":null}';
  262. for (let i = 0; i < 10000; ++i) {
  263. const iv = Buffer.from('0'.repeat(32), 'hex');
  264. const input = Buffer.from(data, 'base64');
  265. const decipher = crypto.createDecipheriv('aes-128-cbc', Buffer.from(key, 'base64'), iv);
  266. const result = Buffer.concat([decipher.update(input), decipher.final()]).toString('utf8');
  267. expect(cipherText).to.equal(result);
  268. }
  269. });
  270. it('does not crash when using crypto.diffieHellman() constructors', () => {
  271. const crypto = require('crypto');
  272. crypto.createDiffieHellman('abc');
  273. crypto.createDiffieHellman('abc', 2);
  274. // Needed to test specific DiffieHellman ctors.
  275. // eslint-disable-next-line no-octal
  276. crypto.createDiffieHellman('abc', Buffer.from([02]));
  277. // eslint-disable-next-line no-octal
  278. crypto.createDiffieHellman('abc', '123');
  279. });
  280. it('does not crash when calling crypto.createPrivateKey() with an unsupported algorithm', () => {
  281. const crypto = require('crypto');
  282. const ed448 = {
  283. crv: 'Ed448',
  284. x: 'KYWcaDwgH77xdAwcbzOgvCVcGMy9I6prRQBhQTTdKXUcr-VquTz7Fd5adJO0wT2VHysF3bk3kBoA',
  285. d: 'UhC3-vN5vp_g9PnTknXZgfXUez7Xvw-OfuJ0pYkuwzpYkcTvacqoFkV_O05WMHpyXkzH9q2wzx5n',
  286. kty: 'OKP'
  287. };
  288. expect(() => {
  289. crypto.createPrivateKey({ key: ed448, format: 'jwk' });
  290. }).to.throw(/Invalid JWK data/);
  291. });
  292. });
  293. describe('process.stdout', () => {
  294. it('does not throw an exception when accessed', () => {
  295. expect(() => process.stdout).to.not.throw();
  296. });
  297. it('does not throw an exception when calling write()', () => {
  298. expect(() => {
  299. process.stdout.write('test');
  300. }).to.not.throw();
  301. });
  302. // TODO: figure out why process.stdout.isTTY is true on Darwin but not Linux/Win.
  303. ifit(process.platform !== 'darwin')('isTTY should be undefined in the renderer process', function () {
  304. expect(process.stdout.isTTY).to.be.undefined();
  305. });
  306. });
  307. describe('process.stdin', () => {
  308. it('does not throw an exception when accessed', () => {
  309. expect(() => process.stdin).to.not.throw();
  310. });
  311. it('returns null when read from', () => {
  312. expect(process.stdin.read()).to.be.null();
  313. });
  314. });
  315. describe('process.version', () => {
  316. it('should not have -pre', () => {
  317. expect(process.version.endsWith('-pre')).to.be.false();
  318. });
  319. });
  320. describe('vm.runInNewContext', () => {
  321. it('should not crash', () => {
  322. require('vm').runInNewContext('');
  323. });
  324. });
  325. describe('crypto', () => {
  326. it('should list the ripemd160 hash in getHashes', () => {
  327. expect(require('crypto').getHashes()).to.include('ripemd160');
  328. });
  329. it('should be able to create a ripemd160 hash and use it', () => {
  330. const hash = require('crypto').createHash('ripemd160');
  331. hash.update('electron-ripemd160');
  332. expect(hash.digest('hex')).to.equal('fa7fec13c624009ab126ebb99eda6525583395fe');
  333. });
  334. it('should list aes-{128,256}-cfb in getCiphers', () => {
  335. expect(require('crypto').getCiphers()).to.include.members(['aes-128-cfb', 'aes-256-cfb']);
  336. });
  337. it('should be able to create an aes-128-cfb cipher', () => {
  338. require('crypto').createCipheriv('aes-128-cfb', '0123456789abcdef', '0123456789abcdef');
  339. });
  340. it('should be able to create an aes-256-cfb cipher', () => {
  341. require('crypto').createCipheriv('aes-256-cfb', '0123456789abcdef0123456789abcdef', '0123456789abcdef');
  342. });
  343. it('should be able to create a bf-{cbc,cfb,ecb} ciphers', () => {
  344. require('crypto').createCipheriv('bf-cbc', Buffer.from('0123456789abcdef'), Buffer.from('01234567'));
  345. require('crypto').createCipheriv('bf-cfb', Buffer.from('0123456789abcdef'), Buffer.from('01234567'));
  346. require('crypto').createCipheriv('bf-ecb', Buffer.from('0123456789abcdef'), Buffer.from('01234567'));
  347. });
  348. it('should list des-ede-cbc in getCiphers', () => {
  349. expect(require('crypto').getCiphers()).to.include('des-ede-cbc');
  350. });
  351. it('should be able to create an des-ede-cbc cipher', () => {
  352. const key = Buffer.from('0123456789abcdeff1e0d3c2b5a49786', 'hex');
  353. const iv = Buffer.from('fedcba9876543210', 'hex');
  354. require('crypto').createCipheriv('des-ede-cbc', key, iv);
  355. });
  356. it('should not crash when getting an ECDH key', () => {
  357. const ecdh = require('crypto').createECDH('prime256v1');
  358. expect(ecdh.generateKeys()).to.be.an.instanceof(Buffer);
  359. expect(ecdh.getPrivateKey()).to.be.an.instanceof(Buffer);
  360. });
  361. it('should not crash when generating DH keys or fetching DH fields', () => {
  362. const dh = require('crypto').createDiffieHellman('modp15');
  363. expect(dh.generateKeys()).to.be.an.instanceof(Buffer);
  364. expect(dh.getPublicKey()).to.be.an.instanceof(Buffer);
  365. expect(dh.getPrivateKey()).to.be.an.instanceof(Buffer);
  366. expect(dh.getPrime()).to.be.an.instanceof(Buffer);
  367. expect(dh.getGenerator()).to.be.an.instanceof(Buffer);
  368. });
  369. it('should not crash when creating an ECDH cipher', () => {
  370. const crypto = require('crypto');
  371. const dh = crypto.createECDH('prime256v1');
  372. dh.generateKeys();
  373. dh.setPrivateKey(dh.getPrivateKey());
  374. });
  375. });
  376. it('includes the electron version in process.versions', () => {
  377. expect(process.versions)
  378. .to.have.own.property('electron')
  379. .that.is.a('string')
  380. .and.matches(/^\d+\.\d+\.\d+(\S*)?$/);
  381. });
  382. it('includes the chrome version in process.versions', () => {
  383. expect(process.versions)
  384. .to.have.own.property('chrome')
  385. .that.is.a('string')
  386. .and.matches(/^\d+\.\d+\.\d+\.\d+$/);
  387. });
  388. });