node-spec.js 15 KB

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