api-net-spec.ts 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955
  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 rawHeaders = response.rawHeaders;
  1453. expect(rawHeaders).to.be.an('array');
  1454. expect(rawHeaders[0]).to.equal(customHeaderName);
  1455. expect(rawHeaders[1]).to.equal(customHeaderValue);
  1456. const httpVersion = response.httpVersion;
  1457. expect(httpVersion).to.be.a('string').and.to.have.lengthOf.at.least(1);
  1458. const httpVersionMajor = response.httpVersionMajor;
  1459. expect(httpVersionMajor).to.be.a('number').and.to.be.at.least(1);
  1460. const httpVersionMinor = response.httpVersionMinor;
  1461. expect(httpVersionMinor).to.be.a('number').and.to.be.at.least(0);
  1462. await collectStreamBody(response);
  1463. });
  1464. it('should discard duplicate headers', async () => {
  1465. const includedHeader = 'max-forwards';
  1466. const discardableHeader = 'Max-Forwards';
  1467. const includedHeaderValue = 'max-fwds-val';
  1468. const discardableHeaderValue = 'max-fwds-val-two';
  1469. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1470. response.statusCode = 200;
  1471. response.statusMessage = 'OK';
  1472. response.setHeader(discardableHeader, discardableHeaderValue);
  1473. response.setHeader(includedHeader, includedHeaderValue);
  1474. response.end();
  1475. });
  1476. const urlRequest = net.request(serverUrl);
  1477. const response = await getResponse(urlRequest);
  1478. expect(response.statusCode).to.equal(200);
  1479. expect(response.statusMessage).to.equal('OK');
  1480. const headers = response.headers;
  1481. expect(headers).to.be.an('object');
  1482. expect(headers).to.have.property(includedHeader);
  1483. expect(headers).to.not.have.property(discardableHeader);
  1484. expect(headers[includedHeader]).to.equal(includedHeaderValue);
  1485. await collectStreamBody(response);
  1486. });
  1487. it('should join repeated non-discardable header values with ,', async () => {
  1488. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1489. response.statusCode = 200;
  1490. response.statusMessage = 'OK';
  1491. response.setHeader('referrer-policy', ['first-text', 'second-text']);
  1492. response.end();
  1493. });
  1494. const urlRequest = net.request(serverUrl);
  1495. const response = await getResponse(urlRequest);
  1496. expect(response.statusCode).to.equal(200);
  1497. expect(response.statusMessage).to.equal('OK');
  1498. const headers = response.headers;
  1499. expect(headers).to.be.an('object');
  1500. expect(headers).to.have.property('referrer-policy');
  1501. expect(headers['referrer-policy']).to.equal('first-text, second-text');
  1502. await collectStreamBody(response);
  1503. });
  1504. it('should not join repeated discardable header values with ,', async () => {
  1505. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1506. response.statusCode = 200;
  1507. response.statusMessage = 'OK';
  1508. response.setHeader('last-modified', ['yesterday', 'today']);
  1509. response.end();
  1510. });
  1511. const urlRequest = net.request(serverUrl);
  1512. const response = await getResponse(urlRequest);
  1513. expect(response.statusCode).to.equal(200);
  1514. expect(response.statusMessage).to.equal('OK');
  1515. const headers = response.headers;
  1516. expect(headers).to.be.an('object');
  1517. expect(headers).to.have.property('last-modified');
  1518. expect(headers['last-modified']).to.equal('yesterday');
  1519. await collectStreamBody(response);
  1520. });
  1521. it('should make set-cookie header an array even if single value', async () => {
  1522. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1523. response.statusCode = 200;
  1524. response.statusMessage = 'OK';
  1525. response.setHeader('set-cookie', 'chocolate-chip');
  1526. response.end();
  1527. });
  1528. const urlRequest = net.request(serverUrl);
  1529. const response = await getResponse(urlRequest);
  1530. expect(response.statusCode).to.equal(200);
  1531. expect(response.statusMessage).to.equal('OK');
  1532. const headers = response.headers;
  1533. expect(headers).to.be.an('object');
  1534. expect(headers).to.have.property('set-cookie');
  1535. expect(headers['set-cookie']).to.be.an('array');
  1536. expect(headers['set-cookie'][0]).to.equal('chocolate-chip');
  1537. await collectStreamBody(response);
  1538. });
  1539. it('should keep set-cookie header an array when an array', async () => {
  1540. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1541. response.statusCode = 200;
  1542. response.statusMessage = 'OK';
  1543. response.setHeader('set-cookie', ['chocolate-chip', 'oatmeal']);
  1544. response.end();
  1545. });
  1546. const urlRequest = net.request(serverUrl);
  1547. const response = await getResponse(urlRequest);
  1548. expect(response.statusCode).to.equal(200);
  1549. expect(response.statusMessage).to.equal('OK');
  1550. const headers = response.headers;
  1551. expect(headers).to.be.an('object');
  1552. expect(headers).to.have.property('set-cookie');
  1553. expect(headers['set-cookie']).to.be.an('array');
  1554. expect(headers['set-cookie'][0]).to.equal('chocolate-chip');
  1555. expect(headers['set-cookie'][1]).to.equal('oatmeal');
  1556. await collectStreamBody(response);
  1557. });
  1558. it('should lowercase header keys', async () => {
  1559. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1560. response.statusCode = 200;
  1561. response.statusMessage = 'OK';
  1562. response.setHeader('HEADER-KEY', ['header-value']);
  1563. response.setHeader('SeT-CookiE', ['chocolate-chip', 'oatmeal']);
  1564. response.setHeader('rEFERREr-pOLICy', ['first-text', 'second-text']);
  1565. response.setHeader('LAST-modified', 'yesterday');
  1566. response.end();
  1567. });
  1568. const urlRequest = net.request(serverUrl);
  1569. const response = await getResponse(urlRequest);
  1570. expect(response.statusCode).to.equal(200);
  1571. expect(response.statusMessage).to.equal('OK');
  1572. const headers = response.headers;
  1573. expect(headers).to.be.an('object');
  1574. expect(headers).to.have.property('header-key');
  1575. expect(headers).to.have.property('set-cookie');
  1576. expect(headers).to.have.property('referrer-policy');
  1577. expect(headers).to.have.property('last-modified');
  1578. await collectStreamBody(response);
  1579. });
  1580. it('should return correct raw headers', async () => {
  1581. const customHeaders: [string, string|string[]][] = [
  1582. ['HEADER-KEY-ONE', 'header-value-one'],
  1583. ['set-cookie', 'chocolate-chip'],
  1584. ['header-key-two', 'header-value-two'],
  1585. ['referrer-policy', ['first-text', 'second-text']],
  1586. ['HEADER-KEY-THREE', 'header-value-three'],
  1587. ['last-modified', ['first-text', 'second-text']],
  1588. ['header-key-four', 'header-value-four']
  1589. ];
  1590. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1591. response.statusCode = 200;
  1592. response.statusMessage = 'OK';
  1593. customHeaders.forEach((headerTuple) => {
  1594. response.setHeader(headerTuple[0], headerTuple[1]);
  1595. });
  1596. response.end();
  1597. });
  1598. const urlRequest = net.request(serverUrl);
  1599. const response = await getResponse(urlRequest);
  1600. expect(response.statusCode).to.equal(200);
  1601. expect(response.statusMessage).to.equal('OK');
  1602. const rawHeaders = response.rawHeaders;
  1603. expect(rawHeaders).to.be.an('array');
  1604. let rawHeadersIdx = 0;
  1605. customHeaders.forEach((headerTuple) => {
  1606. const headerKey = headerTuple[0];
  1607. const headerValues = Array.isArray(headerTuple[1]) ? headerTuple[1] : [headerTuple[1]];
  1608. headerValues.forEach((headerValue) => {
  1609. expect(rawHeaders[rawHeadersIdx]).to.equal(headerKey);
  1610. expect(rawHeaders[rawHeadersIdx + 1]).to.equal(headerValue);
  1611. rawHeadersIdx += 2;
  1612. });
  1613. });
  1614. await collectStreamBody(response);
  1615. });
  1616. it('should be able to pipe a net response into a writable stream', async () => {
  1617. const bodyData = randomString(kOneKiloByte);
  1618. let nodeRequestProcessed = false;
  1619. const [netServerUrl, nodeServerUrl] = await Promise.all([
  1620. respondOnce.toSingleURL((request, response) => response.end(bodyData)),
  1621. respondOnce.toSingleURL(async (request, response) => {
  1622. const receivedBodyData = await collectStreamBody(request);
  1623. expect(receivedBodyData).to.be.equal(bodyData);
  1624. nodeRequestProcessed = true;
  1625. response.end();
  1626. })
  1627. ]);
  1628. const netRequest = net.request(netServerUrl);
  1629. const netResponse = await getResponse(netRequest);
  1630. const serverUrl = url.parse(nodeServerUrl);
  1631. const nodeOptions = {
  1632. method: 'POST',
  1633. path: serverUrl.path,
  1634. port: serverUrl.port
  1635. };
  1636. const nodeRequest = http.request(nodeOptions);
  1637. const nodeResponsePromise = emittedOnce(nodeRequest, 'response');
  1638. // TODO(@MarshallOfSound) - FIXME with #22730
  1639. (netResponse as any).pipe(nodeRequest);
  1640. const [nodeResponse] = await nodeResponsePromise;
  1641. netRequest.end();
  1642. await collectStreamBody(nodeResponse);
  1643. expect(nodeRequestProcessed).to.equal(true);
  1644. });
  1645. it('should correctly throttle an incoming stream', async () => {
  1646. let numChunksSent = 0;
  1647. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1648. const data = randomString(kOneMegaByte);
  1649. const write = () => {
  1650. let ok = true;
  1651. do {
  1652. numChunksSent++;
  1653. if (numChunksSent > 30) return;
  1654. ok = response.write(data);
  1655. } while (ok);
  1656. response.once('drain', write);
  1657. };
  1658. write();
  1659. });
  1660. const urlRequest = net.request(serverUrl);
  1661. urlRequest.on('response', () => {});
  1662. urlRequest.end();
  1663. await delay(2000);
  1664. expect(numChunksSent).to.be.at.most(20);
  1665. });
  1666. });
  1667. describe('net.isOnline', () => {
  1668. it('getter returns boolean', () => {
  1669. expect(net.isOnline()).to.be.a('boolean');
  1670. });
  1671. it('property returns boolean', () => {
  1672. expect(net.online).to.be.a('boolean');
  1673. });
  1674. });
  1675. describe('Stability and performance', () => {
  1676. it('should free unreferenced, never-started request objects without crash', (done) => {
  1677. net.request('https://test');
  1678. process.nextTick(() => {
  1679. const v8Util = process._linkedBinding('electron_common_v8_util');
  1680. v8Util.requestGarbageCollectionForTesting();
  1681. done();
  1682. });
  1683. });
  1684. it('should collect on-going requests without crash', async () => {
  1685. let finishResponse: (() => void) | null = null;
  1686. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1687. response.write(randomString(kOneKiloByte));
  1688. finishResponse = () => {
  1689. response.write(randomString(kOneKiloByte));
  1690. response.end();
  1691. };
  1692. });
  1693. const urlRequest = net.request(serverUrl);
  1694. const response = await getResponse(urlRequest);
  1695. process.nextTick(() => {
  1696. // Trigger a garbage collection.
  1697. const v8Util = process._linkedBinding('electron_common_v8_util');
  1698. v8Util.requestGarbageCollectionForTesting();
  1699. finishResponse!();
  1700. });
  1701. await collectStreamBody(response);
  1702. });
  1703. it('should collect unreferenced, ended requests without crash', async () => {
  1704. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1705. response.end();
  1706. });
  1707. const urlRequest = net.request(serverUrl);
  1708. process.nextTick(() => {
  1709. const v8Util = process._linkedBinding('electron_common_v8_util');
  1710. v8Util.requestGarbageCollectionForTesting();
  1711. });
  1712. const response = await getResponse(urlRequest);
  1713. await collectStreamBody(response);
  1714. });
  1715. it('should finish sending data when urlRequest is unreferenced', async () => {
  1716. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1717. const received = await collectStreamBodyBuffer(request);
  1718. expect(received.length).to.equal(kOneMegaByte);
  1719. response.end();
  1720. });
  1721. const urlRequest = net.request(serverUrl);
  1722. urlRequest.on('close', () => {
  1723. process.nextTick(() => {
  1724. const v8Util = process._linkedBinding('electron_common_v8_util');
  1725. v8Util.requestGarbageCollectionForTesting();
  1726. });
  1727. });
  1728. urlRequest.write(randomBuffer(kOneMegaByte));
  1729. const response = await getResponse(urlRequest);
  1730. await collectStreamBody(response);
  1731. });
  1732. it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
  1733. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1734. const received = await collectStreamBodyBuffer(request);
  1735. response.end();
  1736. expect(received.length).to.equal(kOneMegaByte);
  1737. });
  1738. const urlRequest = net.request(serverUrl);
  1739. urlRequest.chunkedEncoding = true;
  1740. urlRequest.write(randomBuffer(kOneMegaByte));
  1741. const response = await getResponse(urlRequest);
  1742. await collectStreamBody(response);
  1743. process.nextTick(() => {
  1744. const v8Util = process._linkedBinding('electron_common_v8_util');
  1745. v8Util.requestGarbageCollectionForTesting();
  1746. });
  1747. });
  1748. it('should finish sending data when urlRequest is unreferenced before close event for chunked encoding', async () => {
  1749. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1750. const received = await collectStreamBodyBuffer(request);
  1751. response.end();
  1752. expect(received.length).to.equal(kOneMegaByte);
  1753. });
  1754. const urlRequest = net.request(serverUrl);
  1755. urlRequest.chunkedEncoding = true;
  1756. urlRequest.write(randomBuffer(kOneMegaByte));
  1757. const v8Util = process._linkedBinding('electron_common_v8_util');
  1758. v8Util.requestGarbageCollectionForTesting();
  1759. await collectStreamBody(await getResponse(urlRequest));
  1760. });
  1761. it('should finish sending data when urlRequest is unreferenced', async () => {
  1762. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1763. const received = await collectStreamBodyBuffer(request);
  1764. response.end();
  1765. expect(received.length).to.equal(kOneMegaByte);
  1766. });
  1767. const urlRequest = net.request(serverUrl);
  1768. urlRequest.on('close', () => {
  1769. process.nextTick(() => {
  1770. const v8Util = process._linkedBinding('electron_common_v8_util');
  1771. v8Util.requestGarbageCollectionForTesting();
  1772. });
  1773. });
  1774. urlRequest.write(randomBuffer(kOneMegaByte));
  1775. await collectStreamBody(await getResponse(urlRequest));
  1776. });
  1777. it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
  1778. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1779. const received = await collectStreamBodyBuffer(request);
  1780. response.end();
  1781. expect(received.length).to.equal(kOneMegaByte);
  1782. });
  1783. const urlRequest = net.request(serverUrl);
  1784. urlRequest.on('close', () => {
  1785. process.nextTick(() => {
  1786. const v8Util = process._linkedBinding('electron_common_v8_util');
  1787. v8Util.requestGarbageCollectionForTesting();
  1788. });
  1789. });
  1790. urlRequest.chunkedEncoding = true;
  1791. urlRequest.write(randomBuffer(kOneMegaByte));
  1792. await collectStreamBody(await getResponse(urlRequest));
  1793. });
  1794. });
  1795. });