api-net-spec.ts 77 KB

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