api-net-spec.ts 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824
  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. // cookies with lax or strict same-site settings will not
  715. // persist after redirects. no_restriction must be used
  716. await Promise.all([
  717. sess.cookies.set({
  718. url: serverUrl,
  719. name: 'wild_cookie',
  720. sameSite: 'no_restriction',
  721. value: cookie127Val
  722. }), sess.cookies.set({
  723. url: localhostUrl,
  724. name: 'wild_cookie',
  725. sameSite: 'no_restriction',
  726. value: cookieLocalVal
  727. })
  728. ]);
  729. const urlRequest = net.request({
  730. url: serverUrl,
  731. session: sess,
  732. ...extraOptions
  733. });
  734. urlRequest.on('redirect', (status, method, url, headers) => {
  735. // The initial redirect response should have received the 127 value here
  736. expect(headers['x-cookie'][0]).to.equal(`wild_cookie=${cookie127Val}`);
  737. urlRequest.followRedirect();
  738. });
  739. const response = await getResponse(urlRequest);
  740. // We expect the server to have received the localhost value here
  741. // The original request was to a 127.0.0.1 URL
  742. // That request would have the cookie127Val cookie attached
  743. // The request is then redirect to a localhost URL (different site)
  744. // Because we are using the session cookie store it should do the safe / secure thing
  745. // and attach the cookies for the new target domain
  746. expect(response.headers['x-cookie']).to.equal(`wild_cookie=${cookieLocalVal}`);
  747. });
  748. });
  749. }
  750. describe('when {"credentials":"omit"}', () => {
  751. it('should not send cookies');
  752. it('should not store cookies');
  753. });
  754. it('should set sec-fetch-site to same-origin for request from same origin', async () => {
  755. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  756. expect(request.headers['sec-fetch-site']).to.equal('same-origin');
  757. response.statusCode = 200;
  758. response.statusMessage = 'OK';
  759. response.end();
  760. });
  761. const urlRequest = net.request({
  762. url: serverUrl,
  763. origin: serverUrl
  764. });
  765. await collectStreamBody(await getResponse(urlRequest));
  766. });
  767. it('should set sec-fetch-site to same-origin for request with the same origin header', async () => {
  768. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  769. expect(request.headers['sec-fetch-site']).to.equal('same-origin');
  770. response.statusCode = 200;
  771. response.statusMessage = 'OK';
  772. response.end();
  773. });
  774. const urlRequest = net.request({
  775. url: serverUrl
  776. });
  777. urlRequest.setHeader('Origin', serverUrl);
  778. await collectStreamBody(await getResponse(urlRequest));
  779. });
  780. it('should set sec-fetch-site to cross-site for request from other origin', async () => {
  781. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  782. expect(request.headers['sec-fetch-site']).to.equal('cross-site');
  783. response.statusCode = 200;
  784. response.statusMessage = 'OK';
  785. response.end();
  786. });
  787. const urlRequest = net.request({
  788. url: serverUrl,
  789. origin: 'https://not-exists.com'
  790. });
  791. await collectStreamBody(await getResponse(urlRequest));
  792. });
  793. it('should not send sec-fetch-user header by default', async () => {
  794. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  795. expect(request.headers).not.to.have.property('sec-fetch-user');
  796. response.statusCode = 200;
  797. response.statusMessage = 'OK';
  798. response.end();
  799. });
  800. const urlRequest = net.request({
  801. url: serverUrl
  802. });
  803. await collectStreamBody(await getResponse(urlRequest));
  804. });
  805. it('should set sec-fetch-user to ?1 if requested', async () => {
  806. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  807. expect(request.headers['sec-fetch-user']).to.equal('?1');
  808. response.statusCode = 200;
  809. response.statusMessage = 'OK';
  810. response.end();
  811. });
  812. const urlRequest = net.request({
  813. url: serverUrl
  814. });
  815. urlRequest.setHeader('sec-fetch-user', '?1');
  816. await collectStreamBody(await getResponse(urlRequest));
  817. });
  818. it('should set sec-fetch-mode to no-cors by default', async () => {
  819. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  820. expect(request.headers['sec-fetch-mode']).to.equal('no-cors');
  821. response.statusCode = 200;
  822. response.statusMessage = 'OK';
  823. response.end();
  824. });
  825. const urlRequest = net.request({
  826. url: serverUrl
  827. });
  828. await collectStreamBody(await getResponse(urlRequest));
  829. });
  830. ['navigate', 'cors', 'no-cors', 'same-origin'].forEach((mode) => {
  831. it(`should set sec-fetch-mode to ${mode} if requested`, async () => {
  832. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  833. expect(request.headers['sec-fetch-mode']).to.equal(mode);
  834. response.statusCode = 200;
  835. response.statusMessage = 'OK';
  836. response.end();
  837. });
  838. const urlRequest = net.request({
  839. url: serverUrl,
  840. origin: serverUrl
  841. });
  842. urlRequest.setHeader('sec-fetch-mode', mode);
  843. await collectStreamBody(await getResponse(urlRequest));
  844. });
  845. });
  846. it('should set sec-fetch-dest to empty by default', async () => {
  847. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  848. expect(request.headers['sec-fetch-dest']).to.equal('empty');
  849. response.statusCode = 200;
  850. response.statusMessage = 'OK';
  851. response.end();
  852. });
  853. const urlRequest = net.request({
  854. url: serverUrl
  855. });
  856. await collectStreamBody(await getResponse(urlRequest));
  857. });
  858. [
  859. 'empty', 'audio', 'audioworklet', 'document', 'embed', 'font',
  860. 'frame', 'iframe', 'image', 'manifest', 'object', 'paintworklet',
  861. 'report', 'script', 'serviceworker', 'style', 'track', 'video',
  862. 'worker', 'xslt'
  863. ].forEach((dest) => {
  864. it(`should set sec-fetch-dest to ${dest} if requested`, async () => {
  865. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  866. expect(request.headers['sec-fetch-dest']).to.equal(dest);
  867. response.statusCode = 200;
  868. response.statusMessage = 'OK';
  869. response.end();
  870. });
  871. const urlRequest = net.request({
  872. url: serverUrl,
  873. origin: serverUrl
  874. });
  875. urlRequest.setHeader('sec-fetch-dest', dest);
  876. await collectStreamBody(await getResponse(urlRequest));
  877. });
  878. });
  879. it('should be able to abort an HTTP request before first write', async () => {
  880. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  881. response.end();
  882. expect.fail('Unexpected request event');
  883. });
  884. const urlRequest = net.request(serverUrl);
  885. urlRequest.on('response', () => {
  886. expect.fail('unexpected response event');
  887. });
  888. const aborted = emittedOnce(urlRequest, 'abort');
  889. urlRequest.abort();
  890. urlRequest.write('');
  891. urlRequest.end();
  892. await aborted;
  893. });
  894. it('it should be able to abort an HTTP request before request end', async () => {
  895. let requestReceivedByServer = false;
  896. let urlRequest: ClientRequest | null = null;
  897. const serverUrl = await respondOnce.toSingleURL(() => {
  898. requestReceivedByServer = true;
  899. urlRequest!.abort();
  900. });
  901. let requestAbortEventEmitted = false;
  902. urlRequest = net.request(serverUrl);
  903. urlRequest.on('response', () => {
  904. expect.fail('Unexpected response event');
  905. });
  906. urlRequest.on('finish', () => {
  907. expect.fail('Unexpected finish event');
  908. });
  909. urlRequest.on('error', () => {
  910. expect.fail('Unexpected error event');
  911. });
  912. urlRequest.on('abort', () => {
  913. requestAbortEventEmitted = true;
  914. });
  915. await emittedOnce(urlRequest, 'close', () => {
  916. urlRequest!.chunkedEncoding = true;
  917. urlRequest!.write(randomString(kOneKiloByte));
  918. });
  919. expect(requestReceivedByServer).to.equal(true);
  920. expect(requestAbortEventEmitted).to.equal(true);
  921. });
  922. it('it should be able to abort an HTTP request after request end and before response', async () => {
  923. let requestReceivedByServer = false;
  924. let urlRequest: ClientRequest | null = null;
  925. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  926. requestReceivedByServer = true;
  927. urlRequest!.abort();
  928. process.nextTick(() => {
  929. response.statusCode = 200;
  930. response.statusMessage = 'OK';
  931. response.end();
  932. });
  933. });
  934. let requestFinishEventEmitted = false;
  935. urlRequest = net.request(serverUrl);
  936. urlRequest.on('response', () => {
  937. expect.fail('Unexpected response event');
  938. });
  939. urlRequest.on('finish', () => {
  940. requestFinishEventEmitted = true;
  941. });
  942. urlRequest.on('error', () => {
  943. expect.fail('Unexpected error event');
  944. });
  945. urlRequest.end(randomString(kOneKiloByte));
  946. await emittedOnce(urlRequest, 'abort');
  947. expect(requestFinishEventEmitted).to.equal(true);
  948. expect(requestReceivedByServer).to.equal(true);
  949. });
  950. it('it should be able to abort an HTTP request after response start', async () => {
  951. let requestReceivedByServer = false;
  952. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  953. requestReceivedByServer = true;
  954. response.statusCode = 200;
  955. response.statusMessage = 'OK';
  956. response.write(randomString(kOneKiloByte));
  957. });
  958. let requestFinishEventEmitted = false;
  959. let requestResponseEventEmitted = false;
  960. let responseCloseEventEmitted = false;
  961. const urlRequest = net.request(serverUrl);
  962. urlRequest.on('response', (response) => {
  963. requestResponseEventEmitted = true;
  964. const statusCode = response.statusCode;
  965. expect(statusCode).to.equal(200);
  966. response.on('data', () => {});
  967. response.on('end', () => {
  968. expect.fail('Unexpected end event');
  969. });
  970. response.on('error', () => {
  971. expect.fail('Unexpected error event');
  972. });
  973. response.on('close' as any, () => {
  974. responseCloseEventEmitted = true;
  975. });
  976. urlRequest.abort();
  977. });
  978. urlRequest.on('finish', () => {
  979. requestFinishEventEmitted = true;
  980. });
  981. urlRequest.on('error', () => {
  982. expect.fail('Unexpected error event');
  983. });
  984. urlRequest.end(randomString(kOneKiloByte));
  985. await emittedOnce(urlRequest, 'abort');
  986. expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
  987. expect(requestReceivedByServer).to.be.true('request should be received by the server');
  988. expect(requestResponseEventEmitted).to.be.true('"response" event should be emitted');
  989. expect(responseCloseEventEmitted).to.be.true('response should emit "close" event');
  990. });
  991. it('abort event should be emitted at most once', async () => {
  992. let requestReceivedByServer = false;
  993. let urlRequest: ClientRequest | null = null;
  994. const serverUrl = await respondOnce.toSingleURL(() => {
  995. requestReceivedByServer = true;
  996. urlRequest!.abort();
  997. urlRequest!.abort();
  998. });
  999. let requestFinishEventEmitted = false;
  1000. let abortsEmitted = 0;
  1001. urlRequest = net.request(serverUrl);
  1002. urlRequest.on('response', () => {
  1003. expect.fail('Unexpected response event');
  1004. });
  1005. urlRequest.on('finish', () => {
  1006. requestFinishEventEmitted = true;
  1007. });
  1008. urlRequest.on('error', () => {
  1009. expect.fail('Unexpected error event');
  1010. });
  1011. urlRequest.on('abort', () => {
  1012. abortsEmitted++;
  1013. });
  1014. urlRequest.end(randomString(kOneKiloByte));
  1015. await emittedOnce(urlRequest, 'abort');
  1016. expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
  1017. expect(requestReceivedByServer).to.be.true('request should be received by server');
  1018. expect(abortsEmitted).to.equal(1, 'request should emit exactly 1 "abort" event');
  1019. });
  1020. it('should allow to read response body from non-2xx response', async () => {
  1021. const bodyData = randomString(kOneKiloByte);
  1022. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1023. response.statusCode = 404;
  1024. response.end(bodyData);
  1025. });
  1026. const urlRequest = net.request(serverUrl);
  1027. const bodyCheckPromise = getResponse(urlRequest).then(r => {
  1028. expect(r.statusCode).to.equal(404);
  1029. return r;
  1030. }).then(collectStreamBody).then(receivedBodyData => {
  1031. expect(receivedBodyData.toString()).to.equal(bodyData);
  1032. });
  1033. const eventHandlers = Promise.all([
  1034. bodyCheckPromise,
  1035. emittedOnce(urlRequest, 'close')
  1036. ]);
  1037. urlRequest.end();
  1038. await eventHandlers;
  1039. });
  1040. describe('webRequest', () => {
  1041. afterEach(() => {
  1042. session.defaultSession.webRequest.onBeforeRequest(null);
  1043. });
  1044. it('Should throw when invalid filters are passed', () => {
  1045. expect(() => {
  1046. session.defaultSession.webRequest.onBeforeRequest(
  1047. { urls: ['*://www.googleapis.com'] },
  1048. (details, callback) => { callback({ cancel: false }); }
  1049. );
  1050. }).to.throw('Invalid url pattern *://www.googleapis.com: Empty path.');
  1051. expect(() => {
  1052. session.defaultSession.webRequest.onBeforeRequest(
  1053. { urls: ['*://www.googleapis.com/', '*://blahblah.dev'] },
  1054. (details, callback) => { callback({ cancel: false }); }
  1055. );
  1056. }).to.throw('Invalid url pattern *://blahblah.dev: Empty path.');
  1057. });
  1058. it('Should not throw when valid filters are passed', () => {
  1059. expect(() => {
  1060. session.defaultSession.webRequest.onBeforeRequest(
  1061. { urls: ['*://www.googleapis.com/'] },
  1062. (details, callback) => { callback({ cancel: false }); }
  1063. );
  1064. }).to.not.throw();
  1065. });
  1066. it('Requests should be intercepted by webRequest module', async () => {
  1067. const requestUrl = '/requestUrl';
  1068. const redirectUrl = '/redirectUrl';
  1069. let requestIsRedirected = false;
  1070. const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
  1071. requestIsRedirected = true;
  1072. response.end();
  1073. });
  1074. let requestIsIntercepted = false;
  1075. session.defaultSession.webRequest.onBeforeRequest(
  1076. (details, callback) => {
  1077. if (details.url === `${serverUrl}${requestUrl}`) {
  1078. requestIsIntercepted = true;
  1079. // Disabled due to false positive in StandardJS
  1080. // eslint-disable-next-line standard/no-callback-literal
  1081. callback({
  1082. redirectURL: `${serverUrl}${redirectUrl}`
  1083. });
  1084. } else {
  1085. callback({
  1086. cancel: false
  1087. });
  1088. }
  1089. });
  1090. const urlRequest = net.request(`${serverUrl}${requestUrl}`);
  1091. const response = await getResponse(urlRequest);
  1092. expect(response.statusCode).to.equal(200);
  1093. await collectStreamBody(response);
  1094. expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
  1095. expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
  1096. });
  1097. it('should to able to create and intercept a request using a custom session object', async () => {
  1098. const requestUrl = '/requestUrl';
  1099. const redirectUrl = '/redirectUrl';
  1100. const customPartitionName = `custom-partition-${Math.random()}`;
  1101. let requestIsRedirected = false;
  1102. const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
  1103. requestIsRedirected = true;
  1104. response.end();
  1105. });
  1106. session.defaultSession.webRequest.onBeforeRequest(() => {
  1107. expect.fail('Request should not be intercepted by the default session');
  1108. });
  1109. const customSession = session.fromPartition(customPartitionName, { cache: false });
  1110. let requestIsIntercepted = false;
  1111. customSession.webRequest.onBeforeRequest((details, callback) => {
  1112. if (details.url === `${serverUrl}${requestUrl}`) {
  1113. requestIsIntercepted = true;
  1114. // Disabled due to false positive in StandardJS
  1115. // eslint-disable-next-line standard/no-callback-literal
  1116. callback({
  1117. redirectURL: `${serverUrl}${redirectUrl}`
  1118. });
  1119. } else {
  1120. callback({
  1121. cancel: false
  1122. });
  1123. }
  1124. });
  1125. const urlRequest = net.request({
  1126. url: `${serverUrl}${requestUrl}`,
  1127. session: customSession
  1128. });
  1129. const response = await getResponse(urlRequest);
  1130. expect(response.statusCode).to.equal(200);
  1131. await collectStreamBody(response);
  1132. expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
  1133. expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
  1134. });
  1135. it('should to able to create and intercept a request using a custom partition name', async () => {
  1136. const requestUrl = '/requestUrl';
  1137. const redirectUrl = '/redirectUrl';
  1138. const customPartitionName = `custom-partition-${Math.random()}`;
  1139. let requestIsRedirected = false;
  1140. const serverUrl = await respondOnce.toURL(redirectUrl, (request, response) => {
  1141. requestIsRedirected = true;
  1142. response.end();
  1143. });
  1144. session.defaultSession.webRequest.onBeforeRequest(() => {
  1145. expect.fail('Request should not be intercepted by the default session');
  1146. });
  1147. const customSession = session.fromPartition(customPartitionName, { cache: false });
  1148. let requestIsIntercepted = false;
  1149. customSession.webRequest.onBeforeRequest((details, callback) => {
  1150. if (details.url === `${serverUrl}${requestUrl}`) {
  1151. requestIsIntercepted = true;
  1152. // Disabled due to false positive in StandardJS
  1153. // eslint-disable-next-line standard/no-callback-literal
  1154. callback({
  1155. redirectURL: `${serverUrl}${redirectUrl}`
  1156. });
  1157. } else {
  1158. callback({
  1159. cancel: false
  1160. });
  1161. }
  1162. });
  1163. const urlRequest = net.request({
  1164. url: `${serverUrl}${requestUrl}`,
  1165. partition: customPartitionName
  1166. });
  1167. const response = await getResponse(urlRequest);
  1168. expect(response.statusCode).to.equal(200);
  1169. await collectStreamBody(response);
  1170. expect(requestIsRedirected).to.be.true('The server should receive a request to the forward URL');
  1171. expect(requestIsIntercepted).to.be.true('The request should be intercepted by the webRequest module');
  1172. });
  1173. });
  1174. it('should throw when calling getHeader without a name', () => {
  1175. expect(() => {
  1176. (net.request({ url: 'https://test' }).getHeader as any)();
  1177. }).to.throw(/`name` is required for getHeader\(name\)/);
  1178. expect(() => {
  1179. net.request({ url: 'https://test' }).getHeader(null as any);
  1180. }).to.throw(/`name` is required for getHeader\(name\)/);
  1181. });
  1182. it('should throw when calling removeHeader without a name', () => {
  1183. expect(() => {
  1184. (net.request({ url: 'https://test' }).removeHeader as any)();
  1185. }).to.throw(/`name` is required for removeHeader\(name\)/);
  1186. expect(() => {
  1187. net.request({ url: 'https://test' }).removeHeader(null as any);
  1188. }).to.throw(/`name` is required for removeHeader\(name\)/);
  1189. });
  1190. it('should follow redirect when no redirect handler is provided', async () => {
  1191. const requestUrl = '/302';
  1192. const serverUrl = await respondOnce.toRoutes({
  1193. '/302': (request, response) => {
  1194. response.statusCode = 302;
  1195. response.setHeader('Location', '/200');
  1196. response.end();
  1197. },
  1198. '/200': (request, response) => {
  1199. response.statusCode = 200;
  1200. response.end();
  1201. }
  1202. });
  1203. const urlRequest = net.request({
  1204. url: `${serverUrl}${requestUrl}`
  1205. });
  1206. const response = await getResponse(urlRequest);
  1207. expect(response.statusCode).to.equal(200);
  1208. });
  1209. it('should follow redirect chain when no redirect handler is provided', async () => {
  1210. const serverUrl = await respondOnce.toRoutes({
  1211. '/redirectChain': (request, response) => {
  1212. response.statusCode = 302;
  1213. response.setHeader('Location', '/302');
  1214. response.end();
  1215. },
  1216. '/302': (request, response) => {
  1217. response.statusCode = 302;
  1218. response.setHeader('Location', '/200');
  1219. response.end();
  1220. },
  1221. '/200': (request, response) => {
  1222. response.statusCode = 200;
  1223. response.end();
  1224. }
  1225. });
  1226. const urlRequest = net.request({
  1227. url: `${serverUrl}/redirectChain`
  1228. });
  1229. const response = await getResponse(urlRequest);
  1230. expect(response.statusCode).to.equal(200);
  1231. });
  1232. it('should not follow redirect when request is canceled in redirect handler', async () => {
  1233. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1234. response.statusCode = 302;
  1235. response.setHeader('Location', '/200');
  1236. response.end();
  1237. });
  1238. const urlRequest = net.request({
  1239. url: serverUrl
  1240. });
  1241. urlRequest.end();
  1242. urlRequest.on('redirect', () => { urlRequest.abort(); });
  1243. urlRequest.on('error', () => {});
  1244. await emittedOnce(urlRequest, 'abort');
  1245. });
  1246. it('should not follow redirect when mode is error', async () => {
  1247. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1248. response.statusCode = 302;
  1249. response.setHeader('Location', '/200');
  1250. response.end();
  1251. });
  1252. const urlRequest = net.request({
  1253. url: serverUrl,
  1254. redirect: 'error'
  1255. });
  1256. urlRequest.end();
  1257. await emittedOnce(urlRequest, 'error');
  1258. });
  1259. it('should follow redirect when handler calls callback', async () => {
  1260. const serverUrl = await respondOnce.toRoutes({
  1261. '/redirectChain': (request, response) => {
  1262. response.statusCode = 302;
  1263. response.setHeader('Location', '/302');
  1264. response.end();
  1265. },
  1266. '/302': (request, response) => {
  1267. response.statusCode = 302;
  1268. response.setHeader('Location', '/200');
  1269. response.end();
  1270. },
  1271. '/200': (request, response) => {
  1272. response.statusCode = 200;
  1273. response.end();
  1274. }
  1275. });
  1276. const urlRequest = net.request({ url: `${serverUrl}/redirectChain`, redirect: 'manual' });
  1277. const redirects: string[] = [];
  1278. urlRequest.on('redirect', (status, method, url) => {
  1279. redirects.push(url);
  1280. urlRequest.followRedirect();
  1281. });
  1282. const response = await getResponse(urlRequest);
  1283. expect(response.statusCode).to.equal(200);
  1284. expect(redirects).to.deep.equal([
  1285. `${serverUrl}/302`,
  1286. `${serverUrl}/200`
  1287. ]);
  1288. });
  1289. it('should throw if given an invalid session option', () => {
  1290. expect(() => {
  1291. net.request({
  1292. url: 'https://foo',
  1293. session: 1 as any
  1294. });
  1295. }).to.throw('`session` should be an instance of the Session class');
  1296. });
  1297. it('should throw if given an invalid partition option', () => {
  1298. expect(() => {
  1299. net.request({
  1300. url: 'https://foo',
  1301. partition: 1 as any
  1302. });
  1303. }).to.throw('`partition` should be a string');
  1304. });
  1305. it('should be able to create a request with options', async () => {
  1306. const customHeaderName = 'Some-Custom-Header-Name';
  1307. const customHeaderValue = 'Some-Customer-Header-Value';
  1308. const serverUrlUnparsed = await respondOnce.toURL('/', (request, response) => {
  1309. expect(request.method).to.equal('GET');
  1310. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
  1311. response.statusCode = 200;
  1312. response.statusMessage = 'OK';
  1313. response.end();
  1314. });
  1315. const serverUrl = url.parse(serverUrlUnparsed);
  1316. const options = {
  1317. port: serverUrl.port ? parseInt(serverUrl.port, 10) : undefined,
  1318. hostname: '127.0.0.1',
  1319. headers: { [customHeaderName]: customHeaderValue }
  1320. };
  1321. const urlRequest = net.request(options);
  1322. const response = await getResponse(urlRequest);
  1323. expect(response.statusCode).to.be.equal(200);
  1324. await collectStreamBody(response);
  1325. });
  1326. it('should be able to pipe a readable stream into a net request', async () => {
  1327. const bodyData = randomString(kOneMegaByte);
  1328. let netRequestReceived = false;
  1329. let netRequestEnded = false;
  1330. const [nodeServerUrl, netServerUrl] = await Promise.all([
  1331. respondOnce.toSingleURL((request, response) => response.end(bodyData)),
  1332. respondOnce.toSingleURL((request, response) => {
  1333. netRequestReceived = true;
  1334. let receivedBodyData = '';
  1335. request.on('data', (chunk) => {
  1336. receivedBodyData += chunk.toString();
  1337. });
  1338. request.on('end', (chunk: Buffer | undefined) => {
  1339. netRequestEnded = true;
  1340. if (chunk) {
  1341. receivedBodyData += chunk.toString();
  1342. }
  1343. expect(receivedBodyData).to.be.equal(bodyData);
  1344. response.end();
  1345. });
  1346. })
  1347. ]);
  1348. const nodeRequest = http.request(nodeServerUrl);
  1349. const nodeResponse = await getResponse(nodeRequest as any) as any as http.ServerResponse;
  1350. const netRequest = net.request(netServerUrl);
  1351. const responsePromise = emittedOnce(netRequest, 'response');
  1352. // TODO(@MarshallOfSound) - FIXME with #22730
  1353. nodeResponse.pipe(netRequest as any);
  1354. const [netResponse] = await responsePromise;
  1355. expect(netResponse.statusCode).to.equal(200);
  1356. await collectStreamBody(netResponse);
  1357. expect(netRequestReceived).to.be.true('net request received');
  1358. expect(netRequestEnded).to.be.true('net request ended');
  1359. });
  1360. it('should report upload progress', async () => {
  1361. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1362. response.end();
  1363. });
  1364. const netRequest = net.request({ url: serverUrl, method: 'POST' });
  1365. expect(netRequest.getUploadProgress()).to.have.property('active', false);
  1366. netRequest.end(Buffer.from('hello'));
  1367. const [position, total] = await emittedOnce(netRequest, 'upload-progress');
  1368. expect(netRequest.getUploadProgress()).to.deep.equal({ active: true, started: true, current: position, total });
  1369. });
  1370. it('should emit error event on server socket destroy', async () => {
  1371. const serverUrl = await respondOnce.toSingleURL((request) => {
  1372. request.socket.destroy();
  1373. });
  1374. const urlRequest = net.request(serverUrl);
  1375. urlRequest.end();
  1376. const [error] = await emittedOnce(urlRequest, 'error');
  1377. expect(error.message).to.equal('net::ERR_EMPTY_RESPONSE');
  1378. });
  1379. it('should emit error event on server request destroy', async () => {
  1380. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1381. request.destroy();
  1382. response.end();
  1383. });
  1384. const urlRequest = net.request(serverUrl);
  1385. urlRequest.end(randomBuffer(kOneMegaByte));
  1386. const [error] = await emittedOnce(urlRequest, 'error');
  1387. expect(error.message).to.be.oneOf(['net::ERR_FAILED', 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_ABORTED']);
  1388. });
  1389. it('should not emit any event after close', async () => {
  1390. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1391. response.end();
  1392. });
  1393. const urlRequest = net.request(serverUrl);
  1394. urlRequest.end();
  1395. await emittedOnce(urlRequest, 'close');
  1396. await new Promise((resolve, reject) => {
  1397. ['finish', 'abort', 'close', 'error'].forEach(evName => {
  1398. urlRequest.on(evName as any, () => {
  1399. reject(new Error(`Unexpected ${evName} event`));
  1400. });
  1401. });
  1402. setTimeout(resolve, 50);
  1403. });
  1404. });
  1405. it('should remove the referer header when no referrer url specified', async () => {
  1406. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1407. expect(request.headers.referer).to.equal(undefined);
  1408. response.statusCode = 200;
  1409. response.statusMessage = 'OK';
  1410. response.end();
  1411. });
  1412. const urlRequest = net.request(serverUrl);
  1413. urlRequest.end();
  1414. const response = await getResponse(urlRequest);
  1415. expect(response.statusCode).to.equal(200);
  1416. await collectStreamBody(response);
  1417. });
  1418. it('should set the referer header when a referrer url specified', async () => {
  1419. const referrerURL = 'https://www.electronjs.org/';
  1420. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1421. expect(request.headers.referer).to.equal(referrerURL);
  1422. response.statusCode = 200;
  1423. response.statusMessage = 'OK';
  1424. response.end();
  1425. });
  1426. const urlRequest = net.request(serverUrl);
  1427. urlRequest.setHeader('referer', referrerURL);
  1428. urlRequest.end();
  1429. const response = await getResponse(urlRequest);
  1430. expect(response.statusCode).to.equal(200);
  1431. await collectStreamBody(response);
  1432. });
  1433. });
  1434. describe('IncomingMessage API', () => {
  1435. it('response object should implement the IncomingMessage API', async () => {
  1436. const customHeaderName = 'Some-Custom-Header-Name';
  1437. const customHeaderValue = 'Some-Customer-Header-Value';
  1438. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1439. response.statusCode = 200;
  1440. response.statusMessage = 'OK';
  1441. response.setHeader(customHeaderName, customHeaderValue);
  1442. response.end();
  1443. });
  1444. const urlRequest = net.request(serverUrl);
  1445. const response = await getResponse(urlRequest);
  1446. expect(response.statusCode).to.equal(200);
  1447. expect(response.statusMessage).to.equal('OK');
  1448. const headers = response.headers;
  1449. expect(headers).to.be.an('object');
  1450. const headerValue = headers[customHeaderName.toLowerCase()];
  1451. expect(headerValue).to.equal(customHeaderValue);
  1452. const httpVersion = response.httpVersion;
  1453. expect(httpVersion).to.be.a('string').and.to.have.lengthOf.at.least(1);
  1454. const httpVersionMajor = response.httpVersionMajor;
  1455. expect(httpVersionMajor).to.be.a('number').and.to.be.at.least(1);
  1456. const httpVersionMinor = response.httpVersionMinor;
  1457. expect(httpVersionMinor).to.be.a('number').and.to.be.at.least(0);
  1458. await collectStreamBody(response);
  1459. });
  1460. it('should discard duplicate headers', async () => {
  1461. const includedHeader = 'max-forwards';
  1462. const discardableHeader = 'Max-Forwards';
  1463. const includedHeaderValue = 'max-fwds-val';
  1464. const discardableHeaderValue = 'max-fwds-val-two';
  1465. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1466. response.statusCode = 200;
  1467. response.statusMessage = 'OK';
  1468. response.setHeader(discardableHeader, discardableHeaderValue);
  1469. response.setHeader(includedHeader, includedHeaderValue);
  1470. response.end();
  1471. });
  1472. const urlRequest = net.request(serverUrl);
  1473. const response = await getResponse(urlRequest);
  1474. expect(response.statusCode).to.equal(200);
  1475. expect(response.statusMessage).to.equal('OK');
  1476. const headers = response.headers;
  1477. expect(headers).to.be.an('object');
  1478. expect(headers).to.have.property(includedHeader);
  1479. expect(headers).to.not.have.property(discardableHeader);
  1480. expect(headers[includedHeader]).to.equal(includedHeaderValue);
  1481. await collectStreamBody(response);
  1482. });
  1483. it('should join repeated non-discardable value with ,', async () => {
  1484. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1485. response.statusCode = 200;
  1486. response.statusMessage = 'OK';
  1487. response.setHeader('referrer-policy', ['first-text', 'second-text']);
  1488. response.end();
  1489. });
  1490. const urlRequest = net.request(serverUrl);
  1491. const response = await getResponse(urlRequest);
  1492. expect(response.statusCode).to.equal(200);
  1493. expect(response.statusMessage).to.equal('OK');
  1494. const headers = response.headers;
  1495. expect(headers).to.be.an('object');
  1496. expect(headers).to.have.property('referrer-policy');
  1497. expect(headers['referrer-policy']).to.equal('first-text, second-text');
  1498. await collectStreamBody(response);
  1499. });
  1500. it('should be able to pipe a net response into a writable stream', async () => {
  1501. const bodyData = randomString(kOneKiloByte);
  1502. let nodeRequestProcessed = false;
  1503. const [netServerUrl, nodeServerUrl] = await Promise.all([
  1504. respondOnce.toSingleURL((request, response) => response.end(bodyData)),
  1505. respondOnce.toSingleURL(async (request, response) => {
  1506. const receivedBodyData = await collectStreamBody(request);
  1507. expect(receivedBodyData).to.be.equal(bodyData);
  1508. nodeRequestProcessed = true;
  1509. response.end();
  1510. })
  1511. ]);
  1512. const netRequest = net.request(netServerUrl);
  1513. const netResponse = await getResponse(netRequest);
  1514. const serverUrl = url.parse(nodeServerUrl);
  1515. const nodeOptions = {
  1516. method: 'POST',
  1517. path: serverUrl.path,
  1518. port: serverUrl.port
  1519. };
  1520. const nodeRequest = http.request(nodeOptions);
  1521. const nodeResponsePromise = emittedOnce(nodeRequest, 'response');
  1522. // TODO(@MarshallOfSound) - FIXME with #22730
  1523. (netResponse as any).pipe(nodeRequest);
  1524. const [nodeResponse] = await nodeResponsePromise;
  1525. netRequest.end();
  1526. await collectStreamBody(nodeResponse);
  1527. expect(nodeRequestProcessed).to.equal(true);
  1528. });
  1529. it('should correctly throttle an incoming stream', async () => {
  1530. let numChunksSent = 0;
  1531. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1532. const data = randomString(kOneMegaByte);
  1533. const write = () => {
  1534. let ok = true;
  1535. do {
  1536. numChunksSent++;
  1537. if (numChunksSent > 30) return;
  1538. ok = response.write(data);
  1539. } while (ok);
  1540. response.once('drain', write);
  1541. };
  1542. write();
  1543. });
  1544. const urlRequest = net.request(serverUrl);
  1545. urlRequest.on('response', () => {});
  1546. urlRequest.end();
  1547. await delay(2000);
  1548. // TODO(nornagon): I think this ought to max out at 20, but in practice
  1549. // it seems to exceed that sometimes. This is at 25 to avoid test flakes,
  1550. // but we should investigate if there's actually something broken here and
  1551. // if so fix it and reset this to max at 20, and if not then delete this
  1552. // comment.
  1553. expect(numChunksSent).to.be.at.most(25);
  1554. });
  1555. });
  1556. describe('net.isOnline', () => {
  1557. it('getter returns boolean', () => {
  1558. expect(net.isOnline()).to.be.a('boolean');
  1559. });
  1560. it('property returns boolean', () => {
  1561. expect(net.online).to.be.a('boolean');
  1562. });
  1563. });
  1564. describe('Stability and performance', () => {
  1565. it('should free unreferenced, never-started request objects without crash', (done) => {
  1566. net.request('https://test');
  1567. process.nextTick(() => {
  1568. const v8Util = process._linkedBinding('electron_common_v8_util');
  1569. v8Util.requestGarbageCollectionForTesting();
  1570. done();
  1571. });
  1572. });
  1573. it('should collect on-going requests without crash', async () => {
  1574. let finishResponse: (() => void) | null = null;
  1575. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1576. response.write(randomString(kOneKiloByte));
  1577. finishResponse = () => {
  1578. response.write(randomString(kOneKiloByte));
  1579. response.end();
  1580. };
  1581. });
  1582. const urlRequest = net.request(serverUrl);
  1583. const response = await getResponse(urlRequest);
  1584. process.nextTick(() => {
  1585. // Trigger a garbage collection.
  1586. const v8Util = process._linkedBinding('electron_common_v8_util');
  1587. v8Util.requestGarbageCollectionForTesting();
  1588. finishResponse!();
  1589. });
  1590. await collectStreamBody(response);
  1591. });
  1592. it('should collect unreferenced, ended requests without crash', async () => {
  1593. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1594. response.end();
  1595. });
  1596. const urlRequest = net.request(serverUrl);
  1597. process.nextTick(() => {
  1598. const v8Util = process._linkedBinding('electron_common_v8_util');
  1599. v8Util.requestGarbageCollectionForTesting();
  1600. });
  1601. const response = await getResponse(urlRequest);
  1602. await collectStreamBody(response);
  1603. });
  1604. it('should finish sending data when urlRequest is unreferenced', async () => {
  1605. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1606. const received = await collectStreamBodyBuffer(request);
  1607. expect(received.length).to.equal(kOneMegaByte);
  1608. response.end();
  1609. });
  1610. const urlRequest = net.request(serverUrl);
  1611. urlRequest.on('close', () => {
  1612. process.nextTick(() => {
  1613. const v8Util = process._linkedBinding('electron_common_v8_util');
  1614. v8Util.requestGarbageCollectionForTesting();
  1615. });
  1616. });
  1617. urlRequest.write(randomBuffer(kOneMegaByte));
  1618. const response = await getResponse(urlRequest);
  1619. await collectStreamBody(response);
  1620. });
  1621. it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
  1622. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1623. const received = await collectStreamBodyBuffer(request);
  1624. response.end();
  1625. expect(received.length).to.equal(kOneMegaByte);
  1626. });
  1627. const urlRequest = net.request(serverUrl);
  1628. urlRequest.chunkedEncoding = true;
  1629. urlRequest.write(randomBuffer(kOneMegaByte));
  1630. const response = await getResponse(urlRequest);
  1631. await collectStreamBody(response);
  1632. process.nextTick(() => {
  1633. const v8Util = process._linkedBinding('electron_common_v8_util');
  1634. v8Util.requestGarbageCollectionForTesting();
  1635. });
  1636. });
  1637. it('should finish sending data when urlRequest is unreferenced before close event for chunked encoding', async () => {
  1638. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1639. const received = await collectStreamBodyBuffer(request);
  1640. response.end();
  1641. expect(received.length).to.equal(kOneMegaByte);
  1642. });
  1643. const urlRequest = net.request(serverUrl);
  1644. urlRequest.chunkedEncoding = true;
  1645. urlRequest.write(randomBuffer(kOneMegaByte));
  1646. const v8Util = process._linkedBinding('electron_common_v8_util');
  1647. v8Util.requestGarbageCollectionForTesting();
  1648. await collectStreamBody(await getResponse(urlRequest));
  1649. });
  1650. it('should finish sending data when urlRequest is unreferenced', async () => {
  1651. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1652. const received = await collectStreamBodyBuffer(request);
  1653. response.end();
  1654. expect(received.length).to.equal(kOneMegaByte);
  1655. });
  1656. const urlRequest = net.request(serverUrl);
  1657. urlRequest.on('close', () => {
  1658. process.nextTick(() => {
  1659. const v8Util = process._linkedBinding('electron_common_v8_util');
  1660. v8Util.requestGarbageCollectionForTesting();
  1661. });
  1662. });
  1663. urlRequest.write(randomBuffer(kOneMegaByte));
  1664. await collectStreamBody(await getResponse(urlRequest));
  1665. });
  1666. it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
  1667. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1668. const received = await collectStreamBodyBuffer(request);
  1669. response.end();
  1670. expect(received.length).to.equal(kOneMegaByte);
  1671. });
  1672. const urlRequest = net.request(serverUrl);
  1673. urlRequest.on('close', () => {
  1674. process.nextTick(() => {
  1675. const v8Util = process._linkedBinding('electron_common_v8_util');
  1676. v8Util.requestGarbageCollectionForTesting();
  1677. });
  1678. });
  1679. urlRequest.chunkedEncoding = true;
  1680. urlRequest.write(randomBuffer(kOneMegaByte));
  1681. await collectStreamBody(await getResponse(urlRequest));
  1682. });
  1683. });
  1684. });