node-spec.js 15 KB

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