api-net-spec.ts 57 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493
  1. import { expect } from 'chai';
  2. import { net, session, ClientRequest, BrowserWindow } from 'electron';
  3. import * as http from 'http';
  4. import * as url from 'url';
  5. import { AddressInfo, Socket } from 'net';
  6. import { emittedOnce } from './events-helpers';
  7. const kOneKiloByte = 1024;
  8. const kOneMegaByte = kOneKiloByte * kOneKiloByte;
  9. function randomBuffer (size: number, start: number = 0, end: number = 255) {
  10. const range = 1 + end - start;
  11. const buffer = Buffer.allocUnsafe(size);
  12. for (let i = 0; i < size; ++i) {
  13. buffer[i] = start + Math.floor(Math.random() * range);
  14. }
  15. return buffer;
  16. }
  17. function randomString (length: number) {
  18. const buffer = randomBuffer(length, '0'.charCodeAt(0), 'z'.charCodeAt(0));
  19. return buffer.toString();
  20. }
  21. const cleanupTasks: (() => void)[] = [];
  22. function cleanUp () {
  23. cleanupTasks.forEach(t => t());
  24. cleanupTasks.length = 0;
  25. }
  26. async function getResponse (urlRequest: Electron.ClientRequest) {
  27. return new Promise<Electron.IncomingMessage>((resolve, reject) => {
  28. urlRequest.on('error', reject);
  29. urlRequest.on('abort', reject);
  30. urlRequest.on('response', (response) => resolve(response));
  31. urlRequest.end();
  32. });
  33. }
  34. async function collectStreamBody (response: Electron.IncomingMessage | http.IncomingMessage) {
  35. return (await collectStreamBodyBuffer(response)).toString();
  36. }
  37. function collectStreamBodyBuffer (response: Electron.IncomingMessage | http.IncomingMessage) {
  38. return new Promise<Buffer>((resolve, reject) => {
  39. response.on('error', reject);
  40. (response as NodeJS.EventEmitter).on('aborted', reject);
  41. const data: Buffer[] = [];
  42. response.on('data', (chunk) => data.push(chunk));
  43. response.on('end', (chunk?: Buffer) => {
  44. if (chunk) data.push(chunk);
  45. resolve(Buffer.concat(data));
  46. });
  47. });
  48. }
  49. function respondNTimes (fn: http.RequestListener, n: number): Promise<string> {
  50. return new Promise((resolve) => {
  51. const server = http.createServer((request, response) => {
  52. fn(request, response);
  53. // don't close if a redirect was returned
  54. if ((response.statusCode < 300 || response.statusCode >= 399) && n <= 0) {
  55. n--;
  56. server.close();
  57. }
  58. });
  59. server.listen(0, '127.0.0.1', () => {
  60. resolve(`http://127.0.0.1:${(server.address() as AddressInfo).port}`);
  61. });
  62. const sockets: Socket[] = [];
  63. server.on('connection', s => sockets.push(s));
  64. cleanupTasks.push(() => {
  65. server.close();
  66. sockets.forEach(s => s.destroy());
  67. });
  68. });
  69. }
  70. function respondOnce (fn: http.RequestListener) {
  71. return respondNTimes(fn, 1);
  72. }
  73. let routeFailure = false;
  74. respondNTimes.toRoutes = (routes: Record<string, http.RequestListener>, n: number) => {
  75. return respondNTimes((request, response) => {
  76. if (routes.hasOwnProperty(request.url || '')) {
  77. (async () => {
  78. await Promise.resolve(routes[request.url || ''](request, response));
  79. })().catch((err) => {
  80. routeFailure = true;
  81. console.error('Route handler failed, this is probably why your test failed', err);
  82. response.statusCode = 500;
  83. response.end();
  84. });
  85. } else {
  86. response.statusCode = 500;
  87. response.end();
  88. expect.fail(`Unexpected URL: ${request.url}`);
  89. }
  90. }, n);
  91. };
  92. respondOnce.toRoutes = (routes: Record<string, http.RequestListener>) => respondNTimes.toRoutes(routes, 1);
  93. respondNTimes.toURL = (url: string, fn: http.RequestListener, n: number) => {
  94. return respondNTimes.toRoutes({ [url]: fn }, n);
  95. };
  96. respondOnce.toURL = (url: string, fn: http.RequestListener) => respondNTimes.toURL(url, fn, 1);
  97. respondNTimes.toSingleURL = (fn: http.RequestListener, n: number) => {
  98. const requestUrl = '/requestUrl';
  99. return respondNTimes.toURL(requestUrl, fn, n).then(url => `${url}${requestUrl}`);
  100. };
  101. respondOnce.toSingleURL = (fn: http.RequestListener) => respondNTimes.toSingleURL(fn, 1);
  102. describe('net module', () => {
  103. beforeEach(() => {
  104. routeFailure = false;
  105. });
  106. afterEach(cleanUp);
  107. afterEach(async function () {
  108. await session.defaultSession.clearCache();
  109. if (routeFailure && this.test) {
  110. if (!this.test.isFailed()) {
  111. throw new Error('Failing this test due an unhandled error in the respondOnce route handler, check the logs above for the actual error');
  112. }
  113. }
  114. });
  115. describe('HTTP basics', () => {
  116. it('should be able to issue a basic GET request', async () => {
  117. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  118. expect(request.method).to.equal('GET');
  119. response.end();
  120. });
  121. const urlRequest = net.request(serverUrl);
  122. const response = await getResponse(urlRequest);
  123. expect(response.statusCode).to.equal(200);
  124. await collectStreamBody(response);
  125. });
  126. it('should be able to issue a basic POST request', async () => {
  127. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  128. expect(request.method).to.equal('POST');
  129. response.end();
  130. });
  131. const urlRequest = net.request({
  132. method: 'POST',
  133. url: serverUrl
  134. });
  135. const response = await getResponse(urlRequest);
  136. expect(response.statusCode).to.equal(200);
  137. await collectStreamBody(response);
  138. });
  139. it('should fetch correct data in a GET request', async () => {
  140. const expectedBodyData = 'Hello World!';
  141. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  142. expect(request.method).to.equal('GET');
  143. response.end(expectedBodyData);
  144. });
  145. const urlRequest = net.request(serverUrl);
  146. const response = await getResponse(urlRequest);
  147. expect(response.statusCode).to.equal(200);
  148. const body = await collectStreamBody(response);
  149. expect(body).to.equal(expectedBodyData);
  150. });
  151. it('should post the correct data in a POST request', async () => {
  152. const bodyData = 'Hello World!';
  153. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  154. const postedBodyData = await collectStreamBody(request);
  155. expect(postedBodyData).to.equal(bodyData);
  156. response.end();
  157. });
  158. const urlRequest = net.request({
  159. method: 'POST',
  160. url: serverUrl
  161. });
  162. urlRequest.write(bodyData);
  163. const response = await getResponse(urlRequest);
  164. expect(response.statusCode).to.equal(200);
  165. });
  166. it('should support chunked encoding', async () => {
  167. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  168. response.statusCode = 200;
  169. response.statusMessage = 'OK';
  170. response.chunkedEncoding = true;
  171. expect(request.method).to.equal('POST');
  172. expect(request.headers['transfer-encoding']).to.equal('chunked');
  173. expect(request.headers['content-length']).to.equal(undefined);
  174. request.on('data', (chunk: Buffer) => {
  175. response.write(chunk);
  176. });
  177. request.on('end', (chunk: Buffer) => {
  178. response.end(chunk);
  179. });
  180. });
  181. const urlRequest = net.request({
  182. method: 'POST',
  183. url: serverUrl
  184. });
  185. let chunkIndex = 0;
  186. const chunkCount = 100;
  187. let sent = Buffer.alloc(0);
  188. urlRequest.chunkedEncoding = true;
  189. while (chunkIndex < chunkCount) {
  190. chunkIndex += 1;
  191. const chunk = randomBuffer(kOneKiloByte);
  192. sent = Buffer.concat([sent, chunk]);
  193. urlRequest.write(chunk);
  194. }
  195. const response = await getResponse(urlRequest);
  196. expect(response.statusCode).to.equal(200);
  197. const received = await collectStreamBodyBuffer(response);
  198. expect(sent.equals(received)).to.be.true('sent equals received');
  199. expect(chunkIndex).to.be.equal(chunkCount);
  200. });
  201. it('should emit the login event when 401', async () => {
  202. const [user, pass] = ['user', 'pass'];
  203. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  204. if (!request.headers.authorization) {
  205. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  206. }
  207. response.writeHead(200).end('ok');
  208. });
  209. let loginAuthInfo: Electron.AuthInfo;
  210. const request = net.request({ method: 'GET', url: serverUrl });
  211. request.on('login', (authInfo, cb) => {
  212. loginAuthInfo = authInfo;
  213. cb(user, pass);
  214. });
  215. const response = await getResponse(request);
  216. expect(response.statusCode).to.equal(200);
  217. expect(loginAuthInfo!.realm).to.equal('Foo');
  218. expect(loginAuthInfo!.scheme).to.equal('basic');
  219. });
  220. it('should response when cancelling authentication', async () => {
  221. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  222. if (!request.headers.authorization) {
  223. response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' });
  224. response.end('unauthenticated');
  225. } else {
  226. response.writeHead(200).end('ok');
  227. }
  228. });
  229. const request = net.request({ method: 'GET', url: serverUrl });
  230. request.on('login', (authInfo, cb) => {
  231. cb();
  232. });
  233. const response = await getResponse(request);
  234. const body = await collectStreamBody(response);
  235. expect(body).to.equal('unauthenticated');
  236. });
  237. it('should share credentials with WebContents', async () => {
  238. const [user, pass] = ['user', 'pass'];
  239. const serverUrl = await respondNTimes.toSingleURL((request, response) => {
  240. if (!request.headers.authorization) {
  241. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  242. }
  243. return response.writeHead(200).end('ok');
  244. }, 2);
  245. const bw = new BrowserWindow({ show: false });
  246. bw.webContents.on('login', (event, details, authInfo, cb) => {
  247. event.preventDefault();
  248. cb(user, pass);
  249. });
  250. await bw.loadURL(serverUrl);
  251. bw.close();
  252. const request = net.request({ method: 'GET', url: serverUrl });
  253. let logInCount = 0;
  254. request.on('login', () => {
  255. logInCount++;
  256. });
  257. const response = await getResponse(request);
  258. await collectStreamBody(response);
  259. expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached');
  260. });
  261. it('should share proxy credentials with WebContents', async () => {
  262. const [user, pass] = ['user', 'pass'];
  263. const proxyUrl = await respondNTimes((request, response) => {
  264. if (!request.headers['proxy-authorization']) {
  265. return response.writeHead(407, { 'Proxy-Authenticate': 'Basic realm="Foo"' }).end();
  266. }
  267. return response.writeHead(200).end('ok');
  268. }, 2);
  269. const customSession = session.fromPartition(`net-proxy-test-${Math.random()}`);
  270. await customSession.setProxy({ proxyRules: proxyUrl.replace('http://', ''), proxyBypassRules: '<-loopback>' } as any);
  271. const bw = new BrowserWindow({ show: false, webPreferences: { session: customSession } });
  272. bw.webContents.on('login', (event, details, authInfo, cb) => {
  273. event.preventDefault();
  274. cb(user, pass);
  275. });
  276. await bw.loadURL('http://127.0.0.1:9999');
  277. bw.close();
  278. const request = net.request({ method: 'GET', url: 'http://127.0.0.1:9999', session: customSession });
  279. let logInCount = 0;
  280. request.on('login', () => {
  281. logInCount++;
  282. });
  283. const response = await getResponse(request);
  284. const body = await collectStreamBody(response);
  285. expect(response.statusCode).to.equal(200);
  286. expect(body).to.equal('ok');
  287. expect(logInCount).to.equal(0, 'should not receive a login event, credentials should be cached');
  288. });
  289. it('should upload body when 401', async () => {
  290. const [user, pass] = ['user', 'pass'];
  291. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  292. if (!request.headers.authorization) {
  293. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  294. }
  295. response.writeHead(200);
  296. request.on('data', (chunk) => response.write(chunk));
  297. request.on('end', () => response.end());
  298. });
  299. const requestData = randomString(kOneKiloByte);
  300. const request = net.request({ method: 'GET', url: serverUrl });
  301. request.on('login', (authInfo, cb) => {
  302. cb(user, pass);
  303. });
  304. request.write(requestData);
  305. const response = await getResponse(request);
  306. const responseData = await collectStreamBody(response);
  307. expect(responseData).to.equal(requestData);
  308. });
  309. });
  310. describe('ClientRequest API', () => {
  311. it('request/response objects should emit expected events', async () => {
  312. const bodyData = randomString(kOneKiloByte);
  313. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  314. response.end(bodyData);
  315. });
  316. const urlRequest = net.request(serverUrl);
  317. // request close event
  318. const closePromise = emittedOnce(urlRequest, 'close');
  319. // request finish event
  320. const finishPromise = emittedOnce(urlRequest, 'close');
  321. // request "response" event
  322. const response = await getResponse(urlRequest);
  323. response.on('error', (error: Error) => {
  324. expect(error).to.be.an('Error');
  325. });
  326. const statusCode = response.statusCode;
  327. expect(statusCode).to.equal(200);
  328. // response data event
  329. // respond end event
  330. const body = await collectStreamBody(response);
  331. expect(body).to.equal(bodyData);
  332. urlRequest.on('error', (error) => {
  333. expect(error).to.be.an('Error');
  334. });
  335. await Promise.all([closePromise, finishPromise]);
  336. });
  337. it('should be able to set a custom HTTP request header before first write', async () => {
  338. const customHeaderName = 'Some-Custom-Header-Name';
  339. const customHeaderValue = 'Some-Customer-Header-Value';
  340. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  341. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
  342. response.statusCode = 200;
  343. response.statusMessage = 'OK';
  344. response.end();
  345. });
  346. const urlRequest = net.request(serverUrl);
  347. urlRequest.setHeader(customHeaderName, customHeaderValue);
  348. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  349. expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
  350. urlRequest.write('');
  351. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  352. expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
  353. const response = await getResponse(urlRequest);
  354. expect(response.statusCode).to.equal(200);
  355. await collectStreamBody(response);
  356. });
  357. it('should be able to set a non-string object as a header value', async () => {
  358. const customHeaderName = 'Some-Integer-Value';
  359. const customHeaderValue = 900;
  360. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  361. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString());
  362. response.statusCode = 200;
  363. response.statusMessage = 'OK';
  364. response.end();
  365. });
  366. const urlRequest = net.request(serverUrl);
  367. urlRequest.setHeader(customHeaderName, customHeaderValue as any);
  368. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  369. expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
  370. urlRequest.write('');
  371. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  372. expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
  373. const response = await getResponse(urlRequest);
  374. expect(response.statusCode).to.equal(200);
  375. await collectStreamBody(response);
  376. });
  377. it('should not be able to set a custom HTTP request header after first write', async () => {
  378. const customHeaderName = 'Some-Custom-Header-Name';
  379. const customHeaderValue = 'Some-Customer-Header-Value';
  380. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  381. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined);
  382. response.statusCode = 200;
  383. response.statusMessage = 'OK';
  384. response.end();
  385. });
  386. const urlRequest = net.request(serverUrl);
  387. urlRequest.write('');
  388. expect(() => {
  389. urlRequest.setHeader(customHeaderName, customHeaderValue);
  390. }).to.throw();
  391. expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined);
  392. const response = await getResponse(urlRequest);
  393. expect(response.statusCode).to.equal(200);
  394. await collectStreamBody(response);
  395. });
  396. it('should be able to remove a custom HTTP request header before first write', async () => {
  397. const customHeaderName = 'Some-Custom-Header-Name';
  398. const customHeaderValue = 'Some-Customer-Header-Value';
  399. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  400. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined);
  401. response.statusCode = 200;
  402. response.statusMessage = 'OK';
  403. response.end();
  404. });
  405. const urlRequest = net.request(serverUrl);
  406. urlRequest.setHeader(customHeaderName, customHeaderValue);
  407. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  408. urlRequest.removeHeader(customHeaderName);
  409. expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined);
  410. urlRequest.write('');
  411. const response = await getResponse(urlRequest);
  412. expect(response.statusCode).to.equal(200);
  413. await collectStreamBody(response);
  414. });
  415. it('should not be able to remove a custom HTTP request header after first write', async () => {
  416. const customHeaderName = 'Some-Custom-Header-Name';
  417. const customHeaderValue = 'Some-Customer-Header-Value';
  418. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  419. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
  420. response.statusCode = 200;
  421. response.statusMessage = 'OK';
  422. response.end();
  423. });
  424. const urlRequest = net.request(serverUrl);
  425. urlRequest.setHeader(customHeaderName, customHeaderValue);
  426. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  427. urlRequest.write('');
  428. expect(() => {
  429. urlRequest.removeHeader(customHeaderName);
  430. }).to.throw();
  431. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  432. const response = await getResponse(urlRequest);
  433. expect(response.statusCode).to.equal(200);
  434. await collectStreamBody(response);
  435. });
  436. it('should be able to set cookie header line', async () => {
  437. const cookieHeaderName = 'Cookie';
  438. const cookieHeaderValue = 'test=12345';
  439. const customSession = session.fromPartition('test-cookie-header');
  440. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  441. expect(request.headers[cookieHeaderName.toLowerCase()]).to.equal(cookieHeaderValue);
  442. response.statusCode = 200;
  443. response.statusMessage = 'OK';
  444. response.end();
  445. });
  446. await customSession.cookies.set({
  447. url: `${serverUrl}`,
  448. name: 'test',
  449. value: '11111',
  450. expirationDate: 0
  451. });
  452. const urlRequest = net.request({
  453. method: 'GET',
  454. url: serverUrl,
  455. session: customSession
  456. });
  457. urlRequest.setHeader(cookieHeaderName, cookieHeaderValue);
  458. expect(urlRequest.getHeader(cookieHeaderName)).to.equal(cookieHeaderValue);
  459. const response = await getResponse(urlRequest);
  460. expect(response.statusCode).to.equal(200);
  461. await collectStreamBody(response);
  462. });
  463. it('should be able to receive cookies', async () => {
  464. const cookie = ['cookie1', 'cookie2'];
  465. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  466. response.statusCode = 200;
  467. response.statusMessage = 'OK';
  468. response.setHeader('set-cookie', cookie);
  469. response.end();
  470. });
  471. const urlRequest = net.request(serverUrl);
  472. const response = await getResponse(urlRequest);
  473. expect(response.headers['set-cookie']).to.have.same.members(cookie);
  474. });
  475. it('should not use the sessions cookie store by default', async () => {
  476. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  477. response.statusCode = 200;
  478. response.statusMessage = 'OK';
  479. response.setHeader('x-cookie', `${request.headers.cookie!}`);
  480. response.end();
  481. });
  482. const sess = session.fromPartition('cookie-tests-1');
  483. const cookieVal = `${Date.now()}`;
  484. await sess.cookies.set({
  485. url: serverUrl,
  486. name: 'wild_cookie',
  487. value: cookieVal
  488. });
  489. const urlRequest = net.request({
  490. url: serverUrl,
  491. session: sess
  492. });
  493. const response = await getResponse(urlRequest);
  494. expect(response.headers['x-cookie']).to.equal(`undefined`);
  495. });
  496. it('should be able to use the sessions cookie store', async () => {
  497. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  498. response.statusCode = 200;
  499. response.statusMessage = 'OK';
  500. response.setHeader('x-cookie', request.headers.cookie!);
  501. response.end();
  502. });
  503. const sess = session.fromPartition('cookie-tests-2');
  504. const cookieVal = `${Date.now()}`;
  505. await sess.cookies.set({
  506. url: serverUrl,
  507. name: 'wild_cookie',
  508. value: cookieVal
  509. });
  510. const urlRequest = net.request({
  511. url: serverUrl,
  512. session: sess,
  513. useSessionCookies: true
  514. });
  515. const response = await getResponse(urlRequest);
  516. expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieVal}`);
  517. });
  518. it('should be able to use the sessions cookie store with set-cookie', async () => {
  519. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  520. response.statusCode = 200;
  521. response.statusMessage = 'OK';
  522. response.setHeader('set-cookie', 'foo=bar');
  523. response.end();
  524. });
  525. const sess = session.fromPartition('cookie-tests-3');
  526. let cookies = await sess.cookies.get({});
  527. expect(cookies).to.have.lengthOf(0);
  528. const urlRequest = net.request({
  529. url: serverUrl,
  530. session: sess,
  531. useSessionCookies: true
  532. });
  533. await collectStreamBody(await getResponse(urlRequest));
  534. cookies = await sess.cookies.get({});
  535. expect(cookies).to.have.lengthOf(1);
  536. expect(cookies[0]).to.deep.equal({
  537. name: 'foo',
  538. value: 'bar',
  539. domain: '127.0.0.1',
  540. hostOnly: true,
  541. path: '/',
  542. secure: false,
  543. httpOnly: false,
  544. session: true
  545. });
  546. });
  547. ['Lax', 'Strict'].forEach((mode) => {
  548. it(`should be able to use the sessions cookie store with same-site ${mode} cookies`, async () => {
  549. const serverUrl = await respondNTimes.toSingleURL((request, response) => {
  550. response.statusCode = 200;
  551. response.statusMessage = 'OK';
  552. response.setHeader('set-cookie', `same=site; SameSite=${mode}`);
  553. response.setHeader('x-cookie', `${request.headers.cookie}`);
  554. response.end();
  555. }, 2);
  556. const sess = session.fromPartition(`cookie-tests-same-site-${mode}`);
  557. let cookies = await sess.cookies.get({});
  558. expect(cookies).to.have.lengthOf(0);
  559. const bw = new BrowserWindow({ show: false, webPreferences: { session: sess } });
  560. await bw.loadURL(serverUrl);
  561. bw.close();
  562. cookies = await sess.cookies.get({});
  563. expect(cookies).to.have.lengthOf(1);
  564. expect(cookies[0]).to.deep.equal({
  565. name: 'same',
  566. value: 'site',
  567. domain: '127.0.0.1',
  568. hostOnly: true,
  569. path: '/',
  570. secure: false,
  571. httpOnly: false,
  572. session: true
  573. });
  574. const urlRequest2 = net.request({
  575. url: serverUrl,
  576. session: sess,
  577. useSessionCookies: true
  578. });
  579. const response2 = await getResponse(urlRequest2);
  580. expect(response2.headers['x-cookie']).to.equal('same=site');
  581. });
  582. });
  583. it('should be able to use the sessions cookie store safely across redirects', async () => {
  584. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  585. response.statusCode = 302;
  586. response.statusMessage = 'Moved';
  587. const newUrl = await respondOnce.toSingleURL((req, res) => {
  588. res.statusCode = 200;
  589. res.statusMessage = 'OK';
  590. res.setHeader('x-cookie', req.headers.cookie!);
  591. res.end();
  592. });
  593. response.setHeader('x-cookie', request.headers.cookie!);
  594. response.setHeader('location', newUrl.replace('127.0.0.1', 'localhost'));
  595. response.end();
  596. });
  597. const sess = session.fromPartition('cookie-tests-4');
  598. const cookie127Val = `${Date.now()}-127`;
  599. const cookieLocalVal = `${Date.now()}-local`;
  600. const localhostUrl = serverUrl.replace('127.0.0.1', 'localhost');
  601. expect(localhostUrl).to.not.equal(serverUrl);
  602. await Promise.all([
  603. sess.cookies.set({
  604. url: serverUrl,
  605. name: 'wild_cookie',
  606. value: cookie127Val
  607. }), sess.cookies.set({
  608. url: localhostUrl,
  609. name: 'wild_cookie',
  610. value: cookieLocalVal
  611. })
  612. ]);
  613. const urlRequest = net.request({
  614. url: serverUrl,
  615. session: sess,
  616. useSessionCookies: true
  617. });
  618. urlRequest.on('redirect', (status, method, url, headers) => {
  619. // The initial redirect response should have received the 127 value here
  620. expect(headers['x-cookie'][0]).to.equal(`wild_cookie=${cookie127Val}`);
  621. urlRequest.followRedirect();
  622. });
  623. const response = await getResponse(urlRequest);
  624. // We expect the server to have received the localhost value here
  625. // The original request was to a 127.0.0.1 URL
  626. // That request would have the cookie127Val cookie attached
  627. // The request is then redirect to a localhost URL (different site)
  628. // Because we are using the session cookie store it should do the safe / secure thing
  629. // and attach the cookies for the new target domain
  630. expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieLocalVal}`);
  631. });
  632. it('should be able to abort an HTTP request before first write', async () => {
  633. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  634. response.end();
  635. expect.fail('Unexpected request event');
  636. });
  637. const urlRequest = net.request(serverUrl);
  638. urlRequest.on('response', () => {
  639. expect.fail('unexpected response event');
  640. });
  641. const aborted = emittedOnce(urlRequest, 'abort');
  642. urlRequest.abort();
  643. urlRequest.write('');
  644. urlRequest.end();
  645. await aborted;
  646. });
  647. it('it should be able to abort an HTTP request before request end', async () => {
  648. let requestReceivedByServer = false;
  649. let urlRequest: ClientRequest | null = null;
  650. const serverUrl = await respondOnce.toSingleURL(() => {
  651. requestReceivedByServer = true;
  652. urlRequest!.abort();
  653. });
  654. let requestAbortEventEmitted = false;
  655. urlRequest = net.request(serverUrl);
  656. urlRequest.on('response', () => {
  657. expect.fail('Unexpected response event');
  658. });
  659. urlRequest.on('finish', () => {
  660. expect.fail('Unexpected finish event');
  661. });
  662. urlRequest.on('error', () => {
  663. expect.fail('Unexpected error event');
  664. });
  665. urlRequest.on('abort', () => {
  666. requestAbortEventEmitted = true;
  667. });
  668. await emittedOnce(urlRequest, 'close', () => {
  669. urlRequest!.chunkedEncoding = true;
  670. urlRequest!.write(randomString(kOneKiloByte));
  671. });
  672. expect(requestReceivedByServer).to.equal(true);
  673. expect(requestAbortEventEmitted).to.equal(true);
  674. });
  675. it('it should be able to abort an HTTP request after request end and before response', async () => {
  676. let requestReceivedByServer = false;
  677. let urlRequest: ClientRequest | null = null;
  678. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  679. requestReceivedByServer = true;
  680. urlRequest!.abort();
  681. process.nextTick(() => {
  682. response.statusCode = 200;
  683. response.statusMessage = 'OK';
  684. response.end();
  685. });
  686. });
  687. let requestFinishEventEmitted = false;
  688. urlRequest = net.request(serverUrl);
  689. urlRequest.on('response', () => {
  690. expect.fail('Unexpected response event');
  691. });
  692. urlRequest.on('finish', () => {
  693. requestFinishEventEmitted = true;
  694. });
  695. urlRequest.on('error', () => {
  696. expect.fail('Unexpected error event');
  697. });
  698. urlRequest.end(randomString(kOneKiloByte));
  699. await emittedOnce(urlRequest, 'abort');
  700. expect(requestFinishEventEmitted).to.equal(true);
  701. expect(requestReceivedByServer).to.equal(true);
  702. });
  703. it('it should be able to abort an HTTP request after response start', async () => {
  704. let requestReceivedByServer = false;
  705. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  706. requestReceivedByServer = true;
  707. response.statusCode = 200;
  708. response.statusMessage = 'OK';
  709. response.write(randomString(kOneKiloByte));
  710. });
  711. let requestFinishEventEmitted = false;
  712. let requestResponseEventEmitted = false;
  713. let responseCloseEventEmitted = false;
  714. const urlRequest = net.request(serverUrl);
  715. urlRequest.on('response', (response) => {
  716. requestResponseEventEmitted = true;
  717. const statusCode = response.statusCode;
  718. expect(statusCode).to.equal(200);
  719. response.on('data', () => {});
  720. response.on('end', () => {
  721. expect.fail('Unexpected end event');
  722. });
  723. response.on('error', () => {
  724. expect.fail('Unexpected error event');
  725. });
  726. response.on('close' as any, () => {
  727. responseCloseEventEmitted = true;
  728. });
  729. urlRequest.abort();
  730. });
  731. urlRequest.on('finish', () => {
  732. requestFinishEventEmitted = true;
  733. });
  734. urlRequest.on('error', () => {
  735. expect.fail('Unexpected error event');
  736. });
  737. urlRequest.end(randomString(kOneKiloByte));
  738. await emittedOnce(urlRequest, 'abort');
  739. expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
  740. expect(requestReceivedByServer).to.be.true('request should be received by the server');
  741. expect(requestResponseEventEmitted).to.be.true('"response" event should be emitted');
  742. expect(responseCloseEventEmitted).to.be.true('response should emit "close" event');
  743. });
  744. it('abort event should be emitted at most once', async () => {
  745. let requestReceivedByServer = false;
  746. let urlRequest: ClientRequest | null = null;
  747. const serverUrl = await respondOnce.toSingleURL(() => {
  748. requestReceivedByServer = true;
  749. urlRequest!.abort();
  750. urlRequest!.abort();
  751. });
  752. let requestFinishEventEmitted = false;
  753. let abortsEmitted = 0;
  754. urlRequest = net.request(serverUrl);
  755. urlRequest.on('response', () => {
  756. expect.fail('Unexpected response event');
  757. });
  758. urlRequest.on('finish', () => {
  759. requestFinishEventEmitted = true;
  760. });
  761. urlRequest.on('error', () => {
  762. expect.fail('Unexpected error event');
  763. });
  764. urlRequest.on('abort', () => {
  765. abortsEmitted++;
  766. });
  767. urlRequest.end(randomString(kOneKiloByte));
  768. await emittedOnce(urlRequest, 'abort');
  769. expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
  770. expect(requestReceivedByServer).to.be.true('request should be received by server');
  771. expect(abortsEmitted).to.equal(1, 'request should emit exactly 1 "abort" event');
  772. });
  773. it('should allow to read response body from non-2xx response', async () => {
  774. const bodyData = randomString(kOneKiloByte);
  775. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  776. response.statusCode = 404;
  777. response.end(bodyData);
  778. });
  779. const urlRequest = net.request(serverUrl);
  780. const bodyCheckPromise = getResponse(urlRequest).then(r => {
  781. expect(r.statusCode).to.equal(404);
  782. return r;
  783. }).then(collectStreamBody).then(receivedBodyData => {
  784. expect(receivedBodyData.toString()).to.equal(bodyData);
  785. });
  786. const eventHandlers = Promise.all([
  787. bodyCheckPromise,
  788. emittedOnce(urlRequest, 'close')
  789. ]);
  790. urlRequest.end();
  791. await eventHandlers;
  792. });
  793. describe('webRequest', () => {
  794. afterEach(() => {
  795. session.defaultSession.webRequest.onBeforeRequest(null);
  796. });
  797. it('Should throw when invalid filters are passed', () => {
  798. expect(() => {
  799. session.defaultSession.webRequest.onBeforeRequest(
  800. { urls: ['*://www.googleapis.com'] },
  801. (details, callback) => { callback({ cancel: false }); }
  802. );
  803. }).to.throw('Invalid url pattern *://www.googleapis.com: Empty path.');
  804. expect(() => {
  805. session.defaultSession.webRequest.onBeforeRequest(
  806. { urls: [ '*://www.googleapis.com/', '*://blahblah.dev' ] },
  807. (details, callback) => { callback({ cancel: false }); }
  808. );
  809. }).to.throw('Invalid url pattern *://blahblah.dev: Empty path.');
  810. });
  811. it('Should not throw when valid filters are passed', () => {
  812. expect(() => {
  813. session.defaultSession.webRequest.onBeforeRequest(
  814. { urls: ['*://www.googleapis.com/'] },
  815. (details, callback) => { callback({ cancel: false }); }
  816. );
  817. }).to.not.throw();
  818. });
  819. it('Requests should be intercepted by webRequest module', async () => {
  820. const requestUrl = '/requestUrl';
  821. const redirectUrl = '/redirectUrl';
  822. let requestIsRedirected = false;
  823. const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
  824. requestIsRedirected = true;
  825. response.end();
  826. });
  827. let requestIsIntercepted = false;
  828. session.defaultSession.webRequest.onBeforeRequest(
  829. (details, callback) => {
  830. if (details.url === `${serverUrl}${requestUrl}`) {
  831. requestIsIntercepted = true;
  832. // Disabled due to false positive in StandardJS
  833. // eslint-disable-next-line standard/no-callback-literal
  834. callback({
  835. redirectURL: `${serverUrl}${redirectUrl}`
  836. });
  837. } else {
  838. callback({
  839. cancel: false
  840. });
  841. }
  842. });
  843. const urlRequest = net.request(`${serverUrl}${requestUrl}`);
  844. const response = await getResponse(urlRequest);
  845. expect(response.statusCode).to.equal(200);
  846. await collectStreamBody(response);
  847. expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
  848. expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
  849. });
  850. it('should to able to create and intercept a request using a custom session object', async () => {
  851. const requestUrl = '/requestUrl';
  852. const redirectUrl = '/redirectUrl';
  853. const customPartitionName = 'custom-partition';
  854. let requestIsRedirected = false;
  855. const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
  856. requestIsRedirected = true;
  857. response.end();
  858. });
  859. session.defaultSession.webRequest.onBeforeRequest(() => {
  860. expect.fail('Request should not be intercepted by the default session');
  861. });
  862. const customSession = session.fromPartition(customPartitionName, { cache: false });
  863. let requestIsIntercepted = false;
  864. customSession.webRequest.onBeforeRequest((details, callback) => {
  865. if (details.url === `${serverUrl}${requestUrl}`) {
  866. requestIsIntercepted = true;
  867. // Disabled due to false positive in StandardJS
  868. // eslint-disable-next-line standard/no-callback-literal
  869. callback({
  870. redirectURL: `${serverUrl}${redirectUrl}`
  871. });
  872. } else {
  873. callback({
  874. cancel: false
  875. });
  876. }
  877. });
  878. const urlRequest = net.request({
  879. url: `${serverUrl}${requestUrl}`,
  880. session: customSession
  881. });
  882. const response = await getResponse(urlRequest);
  883. expect(response.statusCode).to.equal(200);
  884. await collectStreamBody(response);
  885. expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
  886. expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
  887. });
  888. it('should to able to create and intercept a request using a custom partition name', async () => {
  889. const requestUrl = '/requestUrl';
  890. const redirectUrl = '/redirectUrl';
  891. const customPartitionName = 'custom-partition';
  892. let requestIsRedirected = false;
  893. const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
  894. requestIsRedirected = true;
  895. response.end();
  896. });
  897. session.defaultSession.webRequest.onBeforeRequest(() => {
  898. expect.fail('Request should not be intercepted by the default session');
  899. });
  900. const customSession = session.fromPartition(customPartitionName, { cache: false });
  901. let requestIsIntercepted = false;
  902. customSession.webRequest.onBeforeRequest((details, callback) => {
  903. if (details.url === `${serverUrl}${requestUrl}`) {
  904. requestIsIntercepted = true;
  905. // Disabled due to false positive in StandardJS
  906. // eslint-disable-next-line standard/no-callback-literal
  907. callback({
  908. redirectURL: `${serverUrl}${redirectUrl}`
  909. });
  910. } else {
  911. callback({
  912. cancel: false
  913. });
  914. }
  915. });
  916. const urlRequest = net.request({
  917. url: `${serverUrl}${requestUrl}`,
  918. partition: customPartitionName
  919. });
  920. const response = await getResponse(urlRequest);
  921. expect(response.statusCode).to.equal(200);
  922. await collectStreamBody(response);
  923. expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
  924. expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
  925. });
  926. });
  927. it('should throw when calling getHeader without a name', () => {
  928. expect(() => {
  929. (net.request({ url: 'https://test' }).getHeader as any)();
  930. }).to.throw(/`name` is required for getHeader\(name\)/);
  931. expect(() => {
  932. net.request({ url: 'https://test' }).getHeader(null as any);
  933. }).to.throw(/`name` is required for getHeader\(name\)/);
  934. });
  935. it('should throw when calling removeHeader without a name', () => {
  936. expect(() => {
  937. (net.request({ url: 'https://test' }).removeHeader as any)();
  938. }).to.throw(/`name` is required for removeHeader\(name\)/);
  939. expect(() => {
  940. net.request({ url: 'https://test' }).removeHeader(null as any);
  941. }).to.throw(/`name` is required for removeHeader\(name\)/);
  942. });
  943. it('should follow redirect when no redirect handler is provided', async () => {
  944. const requestUrl = '/302';
  945. const serverUrl = await respondOnce.toRoutes({
  946. '/302': (request, response) => {
  947. response.statusCode = 302;
  948. response.setHeader('Location', '/200');
  949. response.end();
  950. },
  951. '/200': (request, response) => {
  952. response.statusCode = 200;
  953. response.end();
  954. }
  955. });
  956. const urlRequest = net.request({
  957. url: `${serverUrl}${requestUrl}`
  958. });
  959. const response = await getResponse(urlRequest);
  960. expect(response.statusCode).to.equal(200);
  961. });
  962. it('should follow redirect chain when no redirect handler is provided', async () => {
  963. const serverUrl = await respondOnce.toRoutes({
  964. '/redirectChain': (request, response) => {
  965. response.statusCode = 302;
  966. response.setHeader('Location', '/302');
  967. response.end();
  968. },
  969. '/302': (request, response) => {
  970. response.statusCode = 302;
  971. response.setHeader('Location', '/200');
  972. response.end();
  973. },
  974. '/200': (request, response) => {
  975. response.statusCode = 200;
  976. response.end();
  977. }
  978. });
  979. const urlRequest = net.request({
  980. url: `${serverUrl}/redirectChain`
  981. });
  982. const response = await getResponse(urlRequest);
  983. expect(response.statusCode).to.equal(200);
  984. });
  985. it('should not follow redirect when request is canceled in redirect handler', async () => {
  986. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  987. response.statusCode = 302;
  988. response.setHeader('Location', '/200');
  989. response.end();
  990. });
  991. const urlRequest = net.request({
  992. url: serverUrl
  993. });
  994. urlRequest.end();
  995. urlRequest.on('redirect', () => { urlRequest.abort(); });
  996. urlRequest.on('error', () => {});
  997. await emittedOnce(urlRequest, 'abort');
  998. });
  999. it('should not follow redirect when mode is error', async () => {
  1000. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1001. response.statusCode = 302;
  1002. response.setHeader('Location', '/200');
  1003. response.end();
  1004. });
  1005. const urlRequest = net.request({
  1006. url: serverUrl,
  1007. redirect: 'error'
  1008. });
  1009. urlRequest.end();
  1010. await emittedOnce(urlRequest, 'error');
  1011. });
  1012. it('should follow redirect when handler calls callback', async () => {
  1013. const serverUrl = await respondOnce.toRoutes({
  1014. '/redirectChain': (request, response) => {
  1015. response.statusCode = 302;
  1016. response.setHeader('Location', '/302');
  1017. response.end();
  1018. },
  1019. '/302': (request, response) => {
  1020. response.statusCode = 302;
  1021. response.setHeader('Location', '/200');
  1022. response.end();
  1023. },
  1024. '/200': (request, response) => {
  1025. response.statusCode = 200;
  1026. response.end();
  1027. }
  1028. });
  1029. const urlRequest = net.request({ url: `${serverUrl}/redirectChain`, redirect: 'manual' });
  1030. const redirects: string[] = [];
  1031. urlRequest.on('redirect', (status, method, url) => {
  1032. redirects.push(url);
  1033. urlRequest.followRedirect();
  1034. });
  1035. const response = await getResponse(urlRequest);
  1036. expect(response.statusCode).to.equal(200);
  1037. expect(redirects).to.deep.equal([
  1038. `${serverUrl}/302`,
  1039. `${serverUrl}/200`
  1040. ]);
  1041. });
  1042. it('should throw if given an invalid session option', () => {
  1043. expect(() => {
  1044. net.request({
  1045. url: 'https://foo',
  1046. session: 1 as any
  1047. });
  1048. }).to.throw('`session` should be an instance of the Session class');
  1049. });
  1050. it('should throw if given an invalid partition option', () => {
  1051. expect(() => {
  1052. net.request({
  1053. url: 'https://foo',
  1054. partition: 1 as any
  1055. });
  1056. }).to.throw('`partition` should be a string');
  1057. });
  1058. it('should be able to create a request with options', async () => {
  1059. const customHeaderName = 'Some-Custom-Header-Name';
  1060. const customHeaderValue = 'Some-Customer-Header-Value';
  1061. const serverUrlUnparsed = await respondOnce.toURL('/', (request, response) => {
  1062. expect(request.method).to.equal('GET');
  1063. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
  1064. response.statusCode = 200;
  1065. response.statusMessage = 'OK';
  1066. response.end();
  1067. });
  1068. const serverUrl = url.parse(serverUrlUnparsed);
  1069. const options = {
  1070. port: serverUrl.port ? parseInt(serverUrl.port, 10) : undefined,
  1071. hostname: '127.0.0.1',
  1072. headers: { [customHeaderName]: customHeaderValue }
  1073. };
  1074. const urlRequest = net.request(options);
  1075. const response = await getResponse(urlRequest);
  1076. expect(response.statusCode).to.be.equal(200);
  1077. await collectStreamBody(response);
  1078. });
  1079. it('should be able to pipe a readable stream into a net request', async () => {
  1080. const bodyData = randomString(kOneMegaByte);
  1081. let netRequestReceived = false;
  1082. let netRequestEnded = false;
  1083. const [nodeServerUrl, netServerUrl] = await Promise.all([
  1084. respondOnce.toSingleURL((request, response) => response.end(bodyData)),
  1085. respondOnce.toSingleURL((request, response) => {
  1086. netRequestReceived = true;
  1087. let receivedBodyData = '';
  1088. request.on('data', (chunk) => {
  1089. receivedBodyData += chunk.toString();
  1090. });
  1091. request.on('end', (chunk: Buffer | undefined) => {
  1092. netRequestEnded = true;
  1093. if (chunk) {
  1094. receivedBodyData += chunk.toString();
  1095. }
  1096. expect(receivedBodyData).to.be.equal(bodyData);
  1097. response.end();
  1098. });
  1099. })
  1100. ]);
  1101. const nodeRequest = http.request(nodeServerUrl);
  1102. const nodeResponse = await getResponse(nodeRequest as any) as any as http.ServerResponse;
  1103. const netRequest = net.request(netServerUrl);
  1104. const responsePromise = emittedOnce(netRequest, 'response');
  1105. // TODO(@MarshallOfSound) - FIXME with #22730
  1106. nodeResponse.pipe(netRequest as any);
  1107. const [netResponse] = await responsePromise;
  1108. expect(netResponse.statusCode).to.equal(200);
  1109. await collectStreamBody(netResponse);
  1110. expect(netRequestReceived).to.be.true('net request received');
  1111. expect(netRequestEnded).to.be.true('net request ended');
  1112. });
  1113. it('should report upload progress', async () => {
  1114. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1115. response.end();
  1116. });
  1117. const netRequest = net.request({ url: serverUrl, method: 'POST' });
  1118. expect(netRequest.getUploadProgress()).to.deep.equal({ active: false });
  1119. netRequest.end(Buffer.from('hello'));
  1120. const [position, total] = await emittedOnce(netRequest, 'upload-progress');
  1121. expect(netRequest.getUploadProgress()).to.deep.equal({ active: true, started: true, current: position, total });
  1122. });
  1123. it('should emit error event on server socket destroy', async () => {
  1124. const serverUrl = await respondOnce.toSingleURL((request) => {
  1125. request.socket.destroy();
  1126. });
  1127. const urlRequest = net.request(serverUrl);
  1128. urlRequest.end();
  1129. const [error] = await emittedOnce(urlRequest, 'error');
  1130. expect(error.message).to.equal('net::ERR_EMPTY_RESPONSE');
  1131. });
  1132. it('should emit error event on server request destroy', async () => {
  1133. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1134. request.destroy();
  1135. response.end();
  1136. });
  1137. const urlRequest = net.request(serverUrl);
  1138. urlRequest.end(randomBuffer(kOneMegaByte));
  1139. const [error] = await emittedOnce(urlRequest, 'error');
  1140. expect(error.message).to.be.oneOf(['net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_ABORTED']);
  1141. });
  1142. it('should not emit any event after close', async () => {
  1143. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1144. response.end();
  1145. });
  1146. const urlRequest = net.request(serverUrl);
  1147. urlRequest.end();
  1148. await emittedOnce(urlRequest, 'close');
  1149. await new Promise((resolve, reject) => {
  1150. ['finish', 'abort', 'close', 'error'].forEach(evName => {
  1151. urlRequest.on(evName as any, () => {
  1152. reject(new Error(`Unexpected ${evName} event`));
  1153. });
  1154. });
  1155. setTimeout(resolve, 50);
  1156. });
  1157. });
  1158. });
  1159. describe('IncomingMessage API', () => {
  1160. it('response object should implement the IncomingMessage API', async () => {
  1161. const customHeaderName = 'Some-Custom-Header-Name';
  1162. const customHeaderValue = 'Some-Customer-Header-Value';
  1163. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1164. response.statusCode = 200;
  1165. response.statusMessage = 'OK';
  1166. response.setHeader(customHeaderName, customHeaderValue);
  1167. response.end();
  1168. });
  1169. const urlRequest = net.request(serverUrl);
  1170. const response = await getResponse(urlRequest);
  1171. expect(response.statusCode).to.equal(200);
  1172. expect(response.statusMessage).to.equal('OK');
  1173. const headers = response.headers;
  1174. expect(headers).to.be.an('object');
  1175. const headerValue = headers[customHeaderName.toLowerCase()];
  1176. expect(headerValue).to.equal(customHeaderValue);
  1177. const httpVersion = response.httpVersion;
  1178. expect(httpVersion).to.be.a('string').and.to.have.lengthOf.at.least(1);
  1179. const httpVersionMajor = response.httpVersionMajor;
  1180. expect(httpVersionMajor).to.be.a('number').and.to.be.at.least(1);
  1181. const httpVersionMinor = response.httpVersionMinor;
  1182. expect(httpVersionMinor).to.be.a('number').and.to.be.at.least(0);
  1183. await collectStreamBody(response);
  1184. });
  1185. it('should discard duplicate headers', async () => {
  1186. const includedHeader = 'max-forwards';
  1187. const discardableHeader = 'Max-Forwards';
  1188. const includedHeaderValue = 'max-fwds-val';
  1189. const discardableHeaderValue = 'max-fwds-val-two';
  1190. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1191. response.statusCode = 200;
  1192. response.statusMessage = 'OK';
  1193. response.setHeader(discardableHeader, discardableHeaderValue);
  1194. response.setHeader(includedHeader, includedHeaderValue);
  1195. response.end();
  1196. });
  1197. const urlRequest = net.request(serverUrl);
  1198. const response = await getResponse(urlRequest);
  1199. expect(response.statusCode).to.equal(200);
  1200. expect(response.statusMessage).to.equal('OK');
  1201. const headers = response.headers;
  1202. expect(headers).to.be.an('object');
  1203. expect(headers).to.have.property(includedHeader);
  1204. expect(headers).to.not.have.property(discardableHeader);
  1205. expect(headers[includedHeader]).to.equal(includedHeaderValue);
  1206. await collectStreamBody(response);
  1207. });
  1208. it('should join repeated non-discardable value with ,', async () => {
  1209. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1210. response.statusCode = 200;
  1211. response.statusMessage = 'OK';
  1212. response.setHeader('referrer-policy', ['first-text', 'second-text']);
  1213. response.end();
  1214. });
  1215. const urlRequest = net.request(serverUrl);
  1216. const response = await getResponse(urlRequest);
  1217. expect(response.statusCode).to.equal(200);
  1218. expect(response.statusMessage).to.equal('OK');
  1219. const headers = response.headers;
  1220. expect(headers).to.be.an('object');
  1221. expect(headers).to.have.property('referrer-policy');
  1222. expect(headers['referrer-policy']).to.equal('first-text, second-text');
  1223. await collectStreamBody(response);
  1224. });
  1225. it('should be able to pipe a net response into a writable stream', async () => {
  1226. const bodyData = randomString(kOneKiloByte);
  1227. let nodeRequestProcessed = false;
  1228. const [netServerUrl, nodeServerUrl] = await Promise.all([
  1229. respondOnce.toSingleURL((request, response) => response.end(bodyData)),
  1230. respondOnce.toSingleURL(async (request, response) => {
  1231. const receivedBodyData = await collectStreamBody(request);
  1232. expect(receivedBodyData).to.be.equal(bodyData);
  1233. nodeRequestProcessed = true;
  1234. response.end();
  1235. })
  1236. ]);
  1237. const netRequest = net.request(netServerUrl);
  1238. const netResponse = await getResponse(netRequest);
  1239. const serverUrl = url.parse(nodeServerUrl);
  1240. const nodeOptions = {
  1241. method: 'POST',
  1242. path: serverUrl.path,
  1243. port: serverUrl.port
  1244. };
  1245. const nodeRequest = http.request(nodeOptions);
  1246. const nodeResponsePromise = emittedOnce(nodeRequest, 'response');
  1247. // TODO(@MarshallOfSound) - FIXME with #22730
  1248. (netResponse as any).pipe(nodeRequest);
  1249. const [nodeResponse] = await nodeResponsePromise;
  1250. netRequest.end();
  1251. await collectStreamBody(nodeResponse);
  1252. expect(nodeRequestProcessed).to.equal(true);
  1253. });
  1254. });
  1255. describe('Stability and performance', () => {
  1256. it('should free unreferenced, never-started request objects without crash', (done) => {
  1257. net.request('https://test');
  1258. process.nextTick(() => {
  1259. const v8Util = process.electronBinding('v8_util');
  1260. v8Util.requestGarbageCollectionForTesting();
  1261. done();
  1262. });
  1263. });
  1264. it('should collect on-going requests without crash', async () => {
  1265. let finishResponse: (() => void) | null = null;
  1266. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1267. response.write(randomString(kOneKiloByte));
  1268. finishResponse = () => {
  1269. response.write(randomString(kOneKiloByte));
  1270. response.end();
  1271. };
  1272. });
  1273. const urlRequest = net.request(serverUrl);
  1274. const response = await getResponse(urlRequest);
  1275. process.nextTick(() => {
  1276. // Trigger a garbage collection.
  1277. const v8Util = process.electronBinding('v8_util');
  1278. v8Util.requestGarbageCollectionForTesting();
  1279. finishResponse!();
  1280. });
  1281. await collectStreamBody(response);
  1282. });
  1283. it('should collect unreferenced, ended requests without crash', async () => {
  1284. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1285. response.end();
  1286. });
  1287. const urlRequest = net.request(serverUrl);
  1288. process.nextTick(() => {
  1289. const v8Util = process.electronBinding('v8_util');
  1290. v8Util.requestGarbageCollectionForTesting();
  1291. });
  1292. const response = await getResponse(urlRequest);
  1293. await collectStreamBody(response);
  1294. });
  1295. it('should finish sending data when urlRequest is unreferenced', async () => {
  1296. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1297. const received = await collectStreamBodyBuffer(request);
  1298. expect(received.length).to.equal(kOneMegaByte);
  1299. response.end();
  1300. });
  1301. const urlRequest = net.request(serverUrl);
  1302. urlRequest.on('close', () => {
  1303. process.nextTick(() => {
  1304. const v8Util = process.electronBinding('v8_util');
  1305. v8Util.requestGarbageCollectionForTesting();
  1306. });
  1307. });
  1308. urlRequest.write(randomBuffer(kOneMegaByte));
  1309. const response = await getResponse(urlRequest);
  1310. await collectStreamBody(response);
  1311. });
  1312. it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
  1313. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1314. const received = await collectStreamBodyBuffer(request);
  1315. response.end();
  1316. expect(received.length).to.equal(kOneMegaByte);
  1317. });
  1318. const urlRequest = net.request(serverUrl);
  1319. urlRequest.chunkedEncoding = true;
  1320. urlRequest.write(randomBuffer(kOneMegaByte));
  1321. const response = await getResponse(urlRequest);
  1322. await collectStreamBody(response);
  1323. process.nextTick(() => {
  1324. const v8Util = process.electronBinding('v8_util');
  1325. v8Util.requestGarbageCollectionForTesting();
  1326. });
  1327. });
  1328. it('should finish sending data when urlRequest is unreferenced before close event for chunked encoding', async () => {
  1329. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1330. const received = await collectStreamBodyBuffer(request);
  1331. response.end();
  1332. expect(received.length).to.equal(kOneMegaByte);
  1333. });
  1334. const urlRequest = net.request(serverUrl);
  1335. urlRequest.chunkedEncoding = true;
  1336. urlRequest.write(randomBuffer(kOneMegaByte));
  1337. const v8Util = process.electronBinding('v8_util');
  1338. v8Util.requestGarbageCollectionForTesting();
  1339. await collectStreamBody(await getResponse(urlRequest));
  1340. });
  1341. it('should finish sending data when urlRequest is unreferenced', async () => {
  1342. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1343. const received = await collectStreamBodyBuffer(request);
  1344. response.end();
  1345. expect(received.length).to.equal(kOneMegaByte);
  1346. });
  1347. const urlRequest = net.request(serverUrl);
  1348. urlRequest.on('close', () => {
  1349. process.nextTick(() => {
  1350. const v8Util = process.electronBinding('v8_util');
  1351. v8Util.requestGarbageCollectionForTesting();
  1352. });
  1353. });
  1354. urlRequest.write(randomBuffer(kOneMegaByte));
  1355. await collectStreamBody(await getResponse(urlRequest));
  1356. });
  1357. it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
  1358. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1359. const received = await collectStreamBodyBuffer(request);
  1360. response.end();
  1361. expect(received.length).to.equal(kOneMegaByte);
  1362. });
  1363. const urlRequest = net.request(serverUrl);
  1364. urlRequest.on('close', () => {
  1365. process.nextTick(() => {
  1366. const v8Util = process.electronBinding('v8_util');
  1367. v8Util.requestGarbageCollectionForTesting();
  1368. });
  1369. });
  1370. urlRequest.chunkedEncoding = true;
  1371. urlRequest.write(randomBuffer(kOneMegaByte));
  1372. await collectStreamBody(await getResponse(urlRequest));
  1373. });
  1374. });
  1375. });