api-net-spec.ts 71 KB

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