api-net-spec.ts 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532
  1. import { expect } from 'chai';
  2. import { net, session, ClientRequest, BrowserWindow } from 'electron/main';
  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 (Object.prototype.hasOwnProperty.call(routes, 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();
  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>' });
  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. sameSite: 'unspecified'
  546. });
  547. });
  548. ['Lax', 'Strict'].forEach((mode) => {
  549. it(`should be able to use the sessions cookie store with same-site ${mode} cookies`, async () => {
  550. const serverUrl = await respondNTimes.toSingleURL((request, response) => {
  551. response.statusCode = 200;
  552. response.statusMessage = 'OK';
  553. response.setHeader('set-cookie', `same=site; SameSite=${mode}`);
  554. response.setHeader('x-cookie', `${request.headers.cookie}`);
  555. response.end();
  556. }, 2);
  557. const sess = session.fromPartition(`cookie-tests-same-site-${mode}`);
  558. let cookies = await sess.cookies.get({});
  559. expect(cookies).to.have.lengthOf(0);
  560. const urlRequest = net.request({
  561. url: serverUrl,
  562. session: sess,
  563. useSessionCookies: true
  564. });
  565. const response = await getResponse(urlRequest);
  566. expect(response.headers['x-cookie']).to.equal('undefined');
  567. await collectStreamBody(response);
  568. cookies = await sess.cookies.get({});
  569. expect(cookies).to.have.lengthOf(1);
  570. expect(cookies[0]).to.deep.equal({
  571. name: 'same',
  572. value: 'site',
  573. domain: '127.0.0.1',
  574. hostOnly: true,
  575. path: '/',
  576. secure: false,
  577. httpOnly: false,
  578. session: true,
  579. sameSite: mode.toLowerCase()
  580. });
  581. const urlRequest2 = net.request({
  582. url: serverUrl,
  583. session: sess,
  584. useSessionCookies: true
  585. });
  586. const response2 = await getResponse(urlRequest2);
  587. expect(response2.headers['x-cookie']).to.equal('same=site');
  588. });
  589. });
  590. it('should be able to use the sessions cookie store safely across redirects', async () => {
  591. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  592. response.statusCode = 302;
  593. response.statusMessage = 'Moved';
  594. const newUrl = await respondOnce.toSingleURL((req, res) => {
  595. res.statusCode = 200;
  596. res.statusMessage = 'OK';
  597. res.setHeader('x-cookie', req.headers.cookie!);
  598. res.end();
  599. });
  600. response.setHeader('x-cookie', request.headers.cookie!);
  601. response.setHeader('location', newUrl.replace('127.0.0.1', 'localhost'));
  602. response.end();
  603. });
  604. const sess = session.fromPartition('cookie-tests-4');
  605. const cookie127Val = `${Date.now()}-127`;
  606. const cookieLocalVal = `${Date.now()}-local`;
  607. const localhostUrl = serverUrl.replace('127.0.0.1', 'localhost');
  608. expect(localhostUrl).to.not.equal(serverUrl);
  609. await Promise.all([
  610. sess.cookies.set({
  611. url: serverUrl,
  612. name: 'wild_cookie',
  613. value: cookie127Val
  614. }), sess.cookies.set({
  615. url: localhostUrl,
  616. name: 'wild_cookie',
  617. value: cookieLocalVal
  618. })
  619. ]);
  620. const urlRequest = net.request({
  621. url: serverUrl,
  622. session: sess,
  623. useSessionCookies: true
  624. });
  625. urlRequest.on('redirect', (status, method, url, headers) => {
  626. // The initial redirect response should have received the 127 value here
  627. expect(headers['x-cookie'][0]).to.equal(`wild_cookie=${cookie127Val}`);
  628. urlRequest.followRedirect();
  629. });
  630. const response = await getResponse(urlRequest);
  631. // We expect the server to have received the localhost value here
  632. // The original request was to a 127.0.0.1 URL
  633. // That request would have the cookie127Val cookie attached
  634. // The request is then redirect to a localhost URL (different site)
  635. // Because we are using the session cookie store it should do the safe / secure thing
  636. // and attach the cookies for the new target domain
  637. expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieLocalVal}`);
  638. });
  639. it('should be able to abort an HTTP request before first write', async () => {
  640. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  641. response.end();
  642. expect.fail('Unexpected request event');
  643. });
  644. const urlRequest = net.request(serverUrl);
  645. urlRequest.on('response', () => {
  646. expect.fail('unexpected response event');
  647. });
  648. const aborted = emittedOnce(urlRequest, 'abort');
  649. urlRequest.abort();
  650. urlRequest.write('');
  651. urlRequest.end();
  652. await aborted;
  653. });
  654. it('it should be able to abort an HTTP request before request end', async () => {
  655. let requestReceivedByServer = false;
  656. let urlRequest: ClientRequest | null = null;
  657. const serverUrl = await respondOnce.toSingleURL(() => {
  658. requestReceivedByServer = true;
  659. urlRequest!.abort();
  660. });
  661. let requestAbortEventEmitted = false;
  662. urlRequest = net.request(serverUrl);
  663. urlRequest.on('response', () => {
  664. expect.fail('Unexpected response event');
  665. });
  666. urlRequest.on('finish', () => {
  667. expect.fail('Unexpected finish event');
  668. });
  669. urlRequest.on('error', () => {
  670. expect.fail('Unexpected error event');
  671. });
  672. urlRequest.on('abort', () => {
  673. requestAbortEventEmitted = true;
  674. });
  675. await emittedOnce(urlRequest, 'close', () => {
  676. urlRequest!.chunkedEncoding = true;
  677. urlRequest!.write(randomString(kOneKiloByte));
  678. });
  679. expect(requestReceivedByServer).to.equal(true);
  680. expect(requestAbortEventEmitted).to.equal(true);
  681. });
  682. it('it should be able to abort an HTTP request after request end and before response', async () => {
  683. let requestReceivedByServer = false;
  684. let urlRequest: ClientRequest | null = null;
  685. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  686. requestReceivedByServer = true;
  687. urlRequest!.abort();
  688. process.nextTick(() => {
  689. response.statusCode = 200;
  690. response.statusMessage = 'OK';
  691. response.end();
  692. });
  693. });
  694. let requestFinishEventEmitted = false;
  695. urlRequest = net.request(serverUrl);
  696. urlRequest.on('response', () => {
  697. expect.fail('Unexpected response event');
  698. });
  699. urlRequest.on('finish', () => {
  700. requestFinishEventEmitted = true;
  701. });
  702. urlRequest.on('error', () => {
  703. expect.fail('Unexpected error event');
  704. });
  705. urlRequest.end(randomString(kOneKiloByte));
  706. await emittedOnce(urlRequest, 'abort');
  707. expect(requestFinishEventEmitted).to.equal(true);
  708. expect(requestReceivedByServer).to.equal(true);
  709. });
  710. it('it should be able to abort an HTTP request after response start', async () => {
  711. let requestReceivedByServer = false;
  712. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  713. requestReceivedByServer = true;
  714. response.statusCode = 200;
  715. response.statusMessage = 'OK';
  716. response.write(randomString(kOneKiloByte));
  717. });
  718. let requestFinishEventEmitted = false;
  719. let requestResponseEventEmitted = false;
  720. let responseCloseEventEmitted = false;
  721. const urlRequest = net.request(serverUrl);
  722. urlRequest.on('response', (response) => {
  723. requestResponseEventEmitted = true;
  724. const statusCode = response.statusCode;
  725. expect(statusCode).to.equal(200);
  726. response.on('data', () => {});
  727. response.on('end', () => {
  728. expect.fail('Unexpected end event');
  729. });
  730. response.on('error', () => {
  731. expect.fail('Unexpected error event');
  732. });
  733. response.on('close' as any, () => {
  734. responseCloseEventEmitted = true;
  735. });
  736. urlRequest.abort();
  737. });
  738. urlRequest.on('finish', () => {
  739. requestFinishEventEmitted = true;
  740. });
  741. urlRequest.on('error', () => {
  742. expect.fail('Unexpected error event');
  743. });
  744. urlRequest.end(randomString(kOneKiloByte));
  745. await emittedOnce(urlRequest, 'abort');
  746. expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
  747. expect(requestReceivedByServer).to.be.true('request should be received by the server');
  748. expect(requestResponseEventEmitted).to.be.true('"response" event should be emitted');
  749. expect(responseCloseEventEmitted).to.be.true('response should emit "close" event');
  750. });
  751. it('abort event should be emitted at most once', async () => {
  752. let requestReceivedByServer = false;
  753. let urlRequest: ClientRequest | null = null;
  754. const serverUrl = await respondOnce.toSingleURL(() => {
  755. requestReceivedByServer = true;
  756. urlRequest!.abort();
  757. urlRequest!.abort();
  758. });
  759. let requestFinishEventEmitted = false;
  760. let abortsEmitted = 0;
  761. urlRequest = net.request(serverUrl);
  762. urlRequest.on('response', () => {
  763. expect.fail('Unexpected response event');
  764. });
  765. urlRequest.on('finish', () => {
  766. requestFinishEventEmitted = true;
  767. });
  768. urlRequest.on('error', () => {
  769. expect.fail('Unexpected error event');
  770. });
  771. urlRequest.on('abort', () => {
  772. abortsEmitted++;
  773. });
  774. urlRequest.end(randomString(kOneKiloByte));
  775. await emittedOnce(urlRequest, 'abort');
  776. expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
  777. expect(requestReceivedByServer).to.be.true('request should be received by server');
  778. expect(abortsEmitted).to.equal(1, 'request should emit exactly 1 "abort" event');
  779. });
  780. it('should allow to read response body from non-2xx response', async () => {
  781. const bodyData = randomString(kOneKiloByte);
  782. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  783. response.statusCode = 404;
  784. response.end(bodyData);
  785. });
  786. const urlRequest = net.request(serverUrl);
  787. const bodyCheckPromise = getResponse(urlRequest).then(r => {
  788. expect(r.statusCode).to.equal(404);
  789. return r;
  790. }).then(collectStreamBody).then(receivedBodyData => {
  791. expect(receivedBodyData.toString()).to.equal(bodyData);
  792. });
  793. const eventHandlers = Promise.all([
  794. bodyCheckPromise,
  795. emittedOnce(urlRequest, 'close')
  796. ]);
  797. urlRequest.end();
  798. await eventHandlers;
  799. });
  800. describe('webRequest', () => {
  801. afterEach(() => {
  802. session.defaultSession.webRequest.onBeforeRequest(null);
  803. });
  804. it('Should throw when invalid filters are passed', () => {
  805. expect(() => {
  806. session.defaultSession.webRequest.onBeforeRequest(
  807. { urls: ['*://www.googleapis.com'] },
  808. (details, callback) => { callback({ cancel: false }); }
  809. );
  810. }).to.throw('Invalid url pattern *://www.googleapis.com: Empty path.');
  811. expect(() => {
  812. session.defaultSession.webRequest.onBeforeRequest(
  813. { urls: ['*://www.googleapis.com/', '*://blahblah.dev'] },
  814. (details, callback) => { callback({ cancel: false }); }
  815. );
  816. }).to.throw('Invalid url pattern *://blahblah.dev: Empty path.');
  817. });
  818. it('Should not throw when valid filters are passed', () => {
  819. expect(() => {
  820. session.defaultSession.webRequest.onBeforeRequest(
  821. { urls: ['*://www.googleapis.com/'] },
  822. (details, callback) => { callback({ cancel: false }); }
  823. );
  824. }).to.not.throw();
  825. });
  826. it('Requests should be intercepted by webRequest module', async () => {
  827. const requestUrl = '/requestUrl';
  828. const redirectUrl = '/redirectUrl';
  829. let requestIsRedirected = false;
  830. const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
  831. requestIsRedirected = true;
  832. response.end();
  833. });
  834. let requestIsIntercepted = false;
  835. session.defaultSession.webRequest.onBeforeRequest(
  836. (details, callback) => {
  837. if (details.url === `${serverUrl}${requestUrl}`) {
  838. requestIsIntercepted = true;
  839. // Disabled due to false positive in StandardJS
  840. // eslint-disable-next-line standard/no-callback-literal
  841. callback({
  842. redirectURL: `${serverUrl}${redirectUrl}`
  843. });
  844. } else {
  845. callback({
  846. cancel: false
  847. });
  848. }
  849. });
  850. const urlRequest = net.request(`${serverUrl}${requestUrl}`);
  851. const response = await getResponse(urlRequest);
  852. expect(response.statusCode).to.equal(200);
  853. await collectStreamBody(response);
  854. expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
  855. expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
  856. });
  857. it('should to able to create and intercept a request using a custom session object', async () => {
  858. const requestUrl = '/requestUrl';
  859. const redirectUrl = '/redirectUrl';
  860. const customPartitionName = 'custom-partition';
  861. let requestIsRedirected = false;
  862. const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
  863. requestIsRedirected = true;
  864. response.end();
  865. });
  866. session.defaultSession.webRequest.onBeforeRequest(() => {
  867. expect.fail('Request should not be intercepted by the default session');
  868. });
  869. const customSession = session.fromPartition(customPartitionName, { cache: false });
  870. let requestIsIntercepted = false;
  871. customSession.webRequest.onBeforeRequest((details, callback) => {
  872. if (details.url === `${serverUrl}${requestUrl}`) {
  873. requestIsIntercepted = true;
  874. // Disabled due to false positive in StandardJS
  875. // eslint-disable-next-line standard/no-callback-literal
  876. callback({
  877. redirectURL: `${serverUrl}${redirectUrl}`
  878. });
  879. } else {
  880. callback({
  881. cancel: false
  882. });
  883. }
  884. });
  885. const urlRequest = net.request({
  886. url: `${serverUrl}${requestUrl}`,
  887. session: customSession
  888. });
  889. const response = await getResponse(urlRequest);
  890. expect(response.statusCode).to.equal(200);
  891. await collectStreamBody(response);
  892. expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
  893. expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
  894. });
  895. it('should to able to create and intercept a request using a custom partition name', async () => {
  896. const requestUrl = '/requestUrl';
  897. const redirectUrl = '/redirectUrl';
  898. const customPartitionName = 'custom-partition';
  899. let requestIsRedirected = false;
  900. const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
  901. requestIsRedirected = true;
  902. response.end();
  903. });
  904. session.defaultSession.webRequest.onBeforeRequest(() => {
  905. expect.fail('Request should not be intercepted by the default session');
  906. });
  907. const customSession = session.fromPartition(customPartitionName, { cache: false });
  908. let requestIsIntercepted = false;
  909. customSession.webRequest.onBeforeRequest((details, callback) => {
  910. if (details.url === `${serverUrl}${requestUrl}`) {
  911. requestIsIntercepted = true;
  912. // Disabled due to false positive in StandardJS
  913. // eslint-disable-next-line standard/no-callback-literal
  914. callback({
  915. redirectURL: `${serverUrl}${redirectUrl}`
  916. });
  917. } else {
  918. callback({
  919. cancel: false
  920. });
  921. }
  922. });
  923. const urlRequest = net.request({
  924. url: `${serverUrl}${requestUrl}`,
  925. partition: customPartitionName
  926. });
  927. const response = await getResponse(urlRequest);
  928. expect(response.statusCode).to.equal(200);
  929. await collectStreamBody(response);
  930. expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
  931. expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
  932. });
  933. });
  934. it('should throw when calling getHeader without a name', () => {
  935. expect(() => {
  936. (net.request({ url: 'https://test' }).getHeader as any)();
  937. }).to.throw(/`name` is required for getHeader\(name\)/);
  938. expect(() => {
  939. net.request({ url: 'https://test' }).getHeader(null as any);
  940. }).to.throw(/`name` is required for getHeader\(name\)/);
  941. });
  942. it('should throw when calling removeHeader without a name', () => {
  943. expect(() => {
  944. (net.request({ url: 'https://test' }).removeHeader as any)();
  945. }).to.throw(/`name` is required for removeHeader\(name\)/);
  946. expect(() => {
  947. net.request({ url: 'https://test' }).removeHeader(null as any);
  948. }).to.throw(/`name` is required for removeHeader\(name\)/);
  949. });
  950. it('should follow redirect when no redirect handler is provided', async () => {
  951. const requestUrl = '/302';
  952. const serverUrl = await respondOnce.toRoutes({
  953. '/302': (request, response) => {
  954. response.statusCode = 302;
  955. response.setHeader('Location', '/200');
  956. response.end();
  957. },
  958. '/200': (request, response) => {
  959. response.statusCode = 200;
  960. response.end();
  961. }
  962. });
  963. const urlRequest = net.request({
  964. url: `${serverUrl}${requestUrl}`
  965. });
  966. const response = await getResponse(urlRequest);
  967. expect(response.statusCode).to.equal(200);
  968. });
  969. it('should follow redirect chain when no redirect handler is provided', async () => {
  970. const serverUrl = await respondOnce.toRoutes({
  971. '/redirectChain': (request, response) => {
  972. response.statusCode = 302;
  973. response.setHeader('Location', '/302');
  974. response.end();
  975. },
  976. '/302': (request, response) => {
  977. response.statusCode = 302;
  978. response.setHeader('Location', '/200');
  979. response.end();
  980. },
  981. '/200': (request, response) => {
  982. response.statusCode = 200;
  983. response.end();
  984. }
  985. });
  986. const urlRequest = net.request({
  987. url: `${serverUrl}/redirectChain`
  988. });
  989. const response = await getResponse(urlRequest);
  990. expect(response.statusCode).to.equal(200);
  991. });
  992. it('should not follow redirect when request is canceled in redirect handler', async () => {
  993. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  994. response.statusCode = 302;
  995. response.setHeader('Location', '/200');
  996. response.end();
  997. });
  998. const urlRequest = net.request({
  999. url: serverUrl
  1000. });
  1001. urlRequest.end();
  1002. urlRequest.on('redirect', () => { urlRequest.abort(); });
  1003. urlRequest.on('error', () => {});
  1004. await emittedOnce(urlRequest, 'abort');
  1005. });
  1006. it('should not follow redirect when mode is error', async () => {
  1007. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1008. response.statusCode = 302;
  1009. response.setHeader('Location', '/200');
  1010. response.end();
  1011. });
  1012. const urlRequest = net.request({
  1013. url: serverUrl,
  1014. redirect: 'error'
  1015. });
  1016. urlRequest.end();
  1017. await emittedOnce(urlRequest, 'error');
  1018. });
  1019. it('should follow redirect when handler calls callback', async () => {
  1020. const serverUrl = await respondOnce.toRoutes({
  1021. '/redirectChain': (request, response) => {
  1022. response.statusCode = 302;
  1023. response.setHeader('Location', '/302');
  1024. response.end();
  1025. },
  1026. '/302': (request, response) => {
  1027. response.statusCode = 302;
  1028. response.setHeader('Location', '/200');
  1029. response.end();
  1030. },
  1031. '/200': (request, response) => {
  1032. response.statusCode = 200;
  1033. response.end();
  1034. }
  1035. });
  1036. const urlRequest = net.request({ url: `${serverUrl}/redirectChain`, redirect: 'manual' });
  1037. const redirects: string[] = [];
  1038. urlRequest.on('redirect', (status, method, url) => {
  1039. redirects.push(url);
  1040. urlRequest.followRedirect();
  1041. });
  1042. const response = await getResponse(urlRequest);
  1043. expect(response.statusCode).to.equal(200);
  1044. expect(redirects).to.deep.equal([
  1045. `${serverUrl}/302`,
  1046. `${serverUrl}/200`
  1047. ]);
  1048. });
  1049. it('should throw if given an invalid session option', () => {
  1050. expect(() => {
  1051. net.request({
  1052. url: 'https://foo',
  1053. session: 1 as any
  1054. });
  1055. }).to.throw('`session` should be an instance of the Session class');
  1056. });
  1057. it('should throw if given an invalid partition option', () => {
  1058. expect(() => {
  1059. net.request({
  1060. url: 'https://foo',
  1061. partition: 1 as any
  1062. });
  1063. }).to.throw('`partition` should be a string');
  1064. });
  1065. it('should be able to create a request with options', async () => {
  1066. const customHeaderName = 'Some-Custom-Header-Name';
  1067. const customHeaderValue = 'Some-Customer-Header-Value';
  1068. const serverUrlUnparsed = await respondOnce.toURL('/', (request, response) => {
  1069. expect(request.method).to.equal('GET');
  1070. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
  1071. response.statusCode = 200;
  1072. response.statusMessage = 'OK';
  1073. response.end();
  1074. });
  1075. const serverUrl = url.parse(serverUrlUnparsed);
  1076. const options = {
  1077. port: serverUrl.port ? parseInt(serverUrl.port, 10) : undefined,
  1078. hostname: '127.0.0.1',
  1079. headers: { [customHeaderName]: customHeaderValue }
  1080. };
  1081. const urlRequest = net.request(options);
  1082. const response = await getResponse(urlRequest);
  1083. expect(response.statusCode).to.be.equal(200);
  1084. await collectStreamBody(response);
  1085. });
  1086. it('should be able to pipe a readable stream into a net request', async () => {
  1087. const bodyData = randomString(kOneMegaByte);
  1088. let netRequestReceived = false;
  1089. let netRequestEnded = false;
  1090. const [nodeServerUrl, netServerUrl] = await Promise.all([
  1091. respondOnce.toSingleURL((request, response) => response.end(bodyData)),
  1092. respondOnce.toSingleURL((request, response) => {
  1093. netRequestReceived = true;
  1094. let receivedBodyData = '';
  1095. request.on('data', (chunk) => {
  1096. receivedBodyData += chunk.toString();
  1097. });
  1098. request.on('end', (chunk: Buffer | undefined) => {
  1099. netRequestEnded = true;
  1100. if (chunk) {
  1101. receivedBodyData += chunk.toString();
  1102. }
  1103. expect(receivedBodyData).to.be.equal(bodyData);
  1104. response.end();
  1105. });
  1106. })
  1107. ]);
  1108. const nodeRequest = http.request(nodeServerUrl);
  1109. const nodeResponse = await getResponse(nodeRequest as any) as any as http.ServerResponse;
  1110. const netRequest = net.request(netServerUrl);
  1111. const responsePromise = emittedOnce(netRequest, 'response');
  1112. // TODO(@MarshallOfSound) - FIXME with #22730
  1113. nodeResponse.pipe(netRequest as any);
  1114. const [netResponse] = await responsePromise;
  1115. expect(netResponse.statusCode).to.equal(200);
  1116. await collectStreamBody(netResponse);
  1117. expect(netRequestReceived).to.be.true('net request received');
  1118. expect(netRequestEnded).to.be.true('net request ended');
  1119. });
  1120. it('should report upload progress', async () => {
  1121. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1122. response.end();
  1123. });
  1124. const netRequest = net.request({ url: serverUrl, method: 'POST' });
  1125. expect(netRequest.getUploadProgress()).to.have.property('active', false);
  1126. netRequest.end(Buffer.from('hello'));
  1127. const [position, total] = await emittedOnce(netRequest, 'upload-progress');
  1128. expect(netRequest.getUploadProgress()).to.deep.equal({ active: true, started: true, current: position, total });
  1129. });
  1130. it('should emit error event on server socket destroy', async () => {
  1131. const serverUrl = await respondOnce.toSingleURL((request) => {
  1132. request.socket.destroy();
  1133. });
  1134. const urlRequest = net.request(serverUrl);
  1135. urlRequest.end();
  1136. const [error] = await emittedOnce(urlRequest, 'error');
  1137. expect(error.message).to.equal('net::ERR_EMPTY_RESPONSE');
  1138. });
  1139. it('should emit error event on server request destroy', async () => {
  1140. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1141. request.destroy();
  1142. response.end();
  1143. });
  1144. const urlRequest = net.request(serverUrl);
  1145. urlRequest.end(randomBuffer(kOneMegaByte));
  1146. const [error] = await emittedOnce(urlRequest, 'error');
  1147. expect(error.message).to.be.oneOf(['net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_ABORTED']);
  1148. });
  1149. it('should not emit any event after close', async () => {
  1150. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1151. response.end();
  1152. });
  1153. const urlRequest = net.request(serverUrl);
  1154. urlRequest.end();
  1155. await emittedOnce(urlRequest, 'close');
  1156. await new Promise((resolve, reject) => {
  1157. ['finish', 'abort', 'close', 'error'].forEach(evName => {
  1158. urlRequest.on(evName as any, () => {
  1159. reject(new Error(`Unexpected ${evName} event`));
  1160. });
  1161. });
  1162. setTimeout(resolve, 50);
  1163. });
  1164. });
  1165. it('should remove the referer header when no referrer url specified', async () => {
  1166. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1167. expect(request.headers.referer).to.equal(undefined);
  1168. response.statusCode = 200;
  1169. response.statusMessage = 'OK';
  1170. response.end();
  1171. });
  1172. const urlRequest = net.request(serverUrl);
  1173. urlRequest.end();
  1174. const response = await getResponse(urlRequest);
  1175. expect(response.statusCode).to.equal(200);
  1176. await collectStreamBody(response);
  1177. });
  1178. it('should set the referer header when a referrer url specified', async () => {
  1179. const referrerURL = 'https://www.electronjs.org/';
  1180. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1181. expect(request.headers.referer).to.equal(referrerURL);
  1182. response.statusCode = 200;
  1183. response.statusMessage = 'OK';
  1184. response.end();
  1185. });
  1186. const urlRequest = net.request(serverUrl);
  1187. urlRequest.setHeader('referer', referrerURL);
  1188. urlRequest.end();
  1189. const response = await getResponse(urlRequest);
  1190. expect(response.statusCode).to.equal(200);
  1191. await collectStreamBody(response);
  1192. });
  1193. });
  1194. describe('IncomingMessage API', () => {
  1195. it('response object should implement the IncomingMessage API', async () => {
  1196. const customHeaderName = 'Some-Custom-Header-Name';
  1197. const customHeaderValue = 'Some-Customer-Header-Value';
  1198. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1199. response.statusCode = 200;
  1200. response.statusMessage = 'OK';
  1201. response.setHeader(customHeaderName, customHeaderValue);
  1202. response.end();
  1203. });
  1204. const urlRequest = net.request(serverUrl);
  1205. const response = await getResponse(urlRequest);
  1206. expect(response.statusCode).to.equal(200);
  1207. expect(response.statusMessage).to.equal('OK');
  1208. const headers = response.headers;
  1209. expect(headers).to.be.an('object');
  1210. const headerValue = headers[customHeaderName.toLowerCase()];
  1211. expect(headerValue).to.equal(customHeaderValue);
  1212. const httpVersion = response.httpVersion;
  1213. expect(httpVersion).to.be.a('string').and.to.have.lengthOf.at.least(1);
  1214. const httpVersionMajor = response.httpVersionMajor;
  1215. expect(httpVersionMajor).to.be.a('number').and.to.be.at.least(1);
  1216. const httpVersionMinor = response.httpVersionMinor;
  1217. expect(httpVersionMinor).to.be.a('number').and.to.be.at.least(0);
  1218. await collectStreamBody(response);
  1219. });
  1220. it('should discard duplicate headers', async () => {
  1221. const includedHeader = 'max-forwards';
  1222. const discardableHeader = 'Max-Forwards';
  1223. const includedHeaderValue = 'max-fwds-val';
  1224. const discardableHeaderValue = 'max-fwds-val-two';
  1225. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1226. response.statusCode = 200;
  1227. response.statusMessage = 'OK';
  1228. response.setHeader(discardableHeader, discardableHeaderValue);
  1229. response.setHeader(includedHeader, includedHeaderValue);
  1230. response.end();
  1231. });
  1232. const urlRequest = net.request(serverUrl);
  1233. const response = await getResponse(urlRequest);
  1234. expect(response.statusCode).to.equal(200);
  1235. expect(response.statusMessage).to.equal('OK');
  1236. const headers = response.headers;
  1237. expect(headers).to.be.an('object');
  1238. expect(headers).to.have.property(includedHeader);
  1239. expect(headers).to.not.have.property(discardableHeader);
  1240. expect(headers[includedHeader]).to.equal(includedHeaderValue);
  1241. await collectStreamBody(response);
  1242. });
  1243. it('should join repeated non-discardable value with ,', async () => {
  1244. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1245. response.statusCode = 200;
  1246. response.statusMessage = 'OK';
  1247. response.setHeader('referrer-policy', ['first-text', 'second-text']);
  1248. response.end();
  1249. });
  1250. const urlRequest = net.request(serverUrl);
  1251. const response = await getResponse(urlRequest);
  1252. expect(response.statusCode).to.equal(200);
  1253. expect(response.statusMessage).to.equal('OK');
  1254. const headers = response.headers;
  1255. expect(headers).to.be.an('object');
  1256. expect(headers).to.have.property('referrer-policy');
  1257. expect(headers['referrer-policy']).to.equal('first-text, second-text');
  1258. await collectStreamBody(response);
  1259. });
  1260. it('should be able to pipe a net response into a writable stream', async () => {
  1261. const bodyData = randomString(kOneKiloByte);
  1262. let nodeRequestProcessed = false;
  1263. const [netServerUrl, nodeServerUrl] = await Promise.all([
  1264. respondOnce.toSingleURL((request, response) => response.end(bodyData)),
  1265. respondOnce.toSingleURL(async (request, response) => {
  1266. const receivedBodyData = await collectStreamBody(request);
  1267. expect(receivedBodyData).to.be.equal(bodyData);
  1268. nodeRequestProcessed = true;
  1269. response.end();
  1270. })
  1271. ]);
  1272. const netRequest = net.request(netServerUrl);
  1273. const netResponse = await getResponse(netRequest);
  1274. const serverUrl = url.parse(nodeServerUrl);
  1275. const nodeOptions = {
  1276. method: 'POST',
  1277. path: serverUrl.path,
  1278. port: serverUrl.port
  1279. };
  1280. const nodeRequest = http.request(nodeOptions);
  1281. const nodeResponsePromise = emittedOnce(nodeRequest, 'response');
  1282. // TODO(@MarshallOfSound) - FIXME with #22730
  1283. (netResponse as any).pipe(nodeRequest);
  1284. const [nodeResponse] = await nodeResponsePromise;
  1285. netRequest.end();
  1286. await collectStreamBody(nodeResponse);
  1287. expect(nodeRequestProcessed).to.equal(true);
  1288. });
  1289. });
  1290. describe('Stability and performance', () => {
  1291. it('should free unreferenced, never-started request objects without crash', (done) => {
  1292. net.request('https://test');
  1293. process.nextTick(() => {
  1294. const v8Util = process.electronBinding('v8_util');
  1295. v8Util.requestGarbageCollectionForTesting();
  1296. done();
  1297. });
  1298. });
  1299. it('should collect on-going requests without crash', async () => {
  1300. let finishResponse: (() => void) | null = null;
  1301. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1302. response.write(randomString(kOneKiloByte));
  1303. finishResponse = () => {
  1304. response.write(randomString(kOneKiloByte));
  1305. response.end();
  1306. };
  1307. });
  1308. const urlRequest = net.request(serverUrl);
  1309. const response = await getResponse(urlRequest);
  1310. process.nextTick(() => {
  1311. // Trigger a garbage collection.
  1312. const v8Util = process.electronBinding('v8_util');
  1313. v8Util.requestGarbageCollectionForTesting();
  1314. finishResponse!();
  1315. });
  1316. await collectStreamBody(response);
  1317. });
  1318. it('should collect unreferenced, ended requests without crash', async () => {
  1319. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1320. response.end();
  1321. });
  1322. const urlRequest = net.request(serverUrl);
  1323. process.nextTick(() => {
  1324. const v8Util = process.electronBinding('v8_util');
  1325. v8Util.requestGarbageCollectionForTesting();
  1326. });
  1327. const response = await getResponse(urlRequest);
  1328. await collectStreamBody(response);
  1329. });
  1330. it('should finish sending data when urlRequest is unreferenced', async () => {
  1331. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1332. const received = await collectStreamBodyBuffer(request);
  1333. expect(received.length).to.equal(kOneMegaByte);
  1334. response.end();
  1335. });
  1336. const urlRequest = net.request(serverUrl);
  1337. urlRequest.on('close', () => {
  1338. process.nextTick(() => {
  1339. const v8Util = process.electronBinding('v8_util');
  1340. v8Util.requestGarbageCollectionForTesting();
  1341. });
  1342. });
  1343. urlRequest.write(randomBuffer(kOneMegaByte));
  1344. const response = await getResponse(urlRequest);
  1345. await collectStreamBody(response);
  1346. });
  1347. it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
  1348. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1349. const received = await collectStreamBodyBuffer(request);
  1350. response.end();
  1351. expect(received.length).to.equal(kOneMegaByte);
  1352. });
  1353. const urlRequest = net.request(serverUrl);
  1354. urlRequest.chunkedEncoding = true;
  1355. urlRequest.write(randomBuffer(kOneMegaByte));
  1356. const response = await getResponse(urlRequest);
  1357. await collectStreamBody(response);
  1358. process.nextTick(() => {
  1359. const v8Util = process.electronBinding('v8_util');
  1360. v8Util.requestGarbageCollectionForTesting();
  1361. });
  1362. });
  1363. it('should finish sending data when urlRequest is unreferenced before close event for chunked encoding', async () => {
  1364. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1365. const received = await collectStreamBodyBuffer(request);
  1366. response.end();
  1367. expect(received.length).to.equal(kOneMegaByte);
  1368. });
  1369. const urlRequest = net.request(serverUrl);
  1370. urlRequest.chunkedEncoding = true;
  1371. urlRequest.write(randomBuffer(kOneMegaByte));
  1372. const v8Util = process.electronBinding('v8_util');
  1373. v8Util.requestGarbageCollectionForTesting();
  1374. await collectStreamBody(await getResponse(urlRequest));
  1375. });
  1376. it('should finish sending data when urlRequest is unreferenced', async () => {
  1377. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1378. const received = await collectStreamBodyBuffer(request);
  1379. response.end();
  1380. expect(received.length).to.equal(kOneMegaByte);
  1381. });
  1382. const urlRequest = net.request(serverUrl);
  1383. urlRequest.on('close', () => {
  1384. process.nextTick(() => {
  1385. const v8Util = process.electronBinding('v8_util');
  1386. v8Util.requestGarbageCollectionForTesting();
  1387. });
  1388. });
  1389. urlRequest.write(randomBuffer(kOneMegaByte));
  1390. await collectStreamBody(await getResponse(urlRequest));
  1391. });
  1392. it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
  1393. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1394. const received = await collectStreamBodyBuffer(request);
  1395. response.end();
  1396. expect(received.length).to.equal(kOneMegaByte);
  1397. });
  1398. const urlRequest = net.request(serverUrl);
  1399. urlRequest.on('close', () => {
  1400. process.nextTick(() => {
  1401. const v8Util = process.electronBinding('v8_util');
  1402. v8Util.requestGarbageCollectionForTesting();
  1403. });
  1404. });
  1405. urlRequest.chunkedEncoding = true;
  1406. urlRequest.write(randomBuffer(kOneMegaByte));
  1407. await collectStreamBody(await getResponse(urlRequest));
  1408. });
  1409. });
  1410. });