api-net-spec.ts 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960
  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. // TODO(nornagon): I think this ought to max out at 20, but in practice
  1665. // it seems to exceed that sometimes. This is at 25 to avoid test flakes,
  1666. // but we should investigate if there's actually something broken here and
  1667. // if so fix it and reset this to max at 20, and if not then delete this
  1668. // comment.
  1669. expect(numChunksSent).to.be.at.most(25);
  1670. });
  1671. });
  1672. describe('net.isOnline', () => {
  1673. it('getter returns boolean', () => {
  1674. expect(net.isOnline()).to.be.a('boolean');
  1675. });
  1676. it('property returns boolean', () => {
  1677. expect(net.online).to.be.a('boolean');
  1678. });
  1679. });
  1680. describe('Stability and performance', () => {
  1681. it('should free unreferenced, never-started request objects without crash', (done) => {
  1682. net.request('https://test');
  1683. process.nextTick(() => {
  1684. const v8Util = process._linkedBinding('electron_common_v8_util');
  1685. v8Util.requestGarbageCollectionForTesting();
  1686. done();
  1687. });
  1688. });
  1689. it('should collect on-going requests without crash', async () => {
  1690. let finishResponse: (() => void) | null = null;
  1691. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1692. response.write(randomString(kOneKiloByte));
  1693. finishResponse = () => {
  1694. response.write(randomString(kOneKiloByte));
  1695. response.end();
  1696. };
  1697. });
  1698. const urlRequest = net.request(serverUrl);
  1699. const response = await getResponse(urlRequest);
  1700. process.nextTick(() => {
  1701. // Trigger a garbage collection.
  1702. const v8Util = process._linkedBinding('electron_common_v8_util');
  1703. v8Util.requestGarbageCollectionForTesting();
  1704. finishResponse!();
  1705. });
  1706. await collectStreamBody(response);
  1707. });
  1708. it('should collect unreferenced, ended requests without crash', async () => {
  1709. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1710. response.end();
  1711. });
  1712. const urlRequest = net.request(serverUrl);
  1713. process.nextTick(() => {
  1714. const v8Util = process._linkedBinding('electron_common_v8_util');
  1715. v8Util.requestGarbageCollectionForTesting();
  1716. });
  1717. const response = await getResponse(urlRequest);
  1718. await collectStreamBody(response);
  1719. });
  1720. it('should finish sending data when urlRequest is unreferenced', async () => {
  1721. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1722. const received = await collectStreamBodyBuffer(request);
  1723. expect(received.length).to.equal(kOneMegaByte);
  1724. response.end();
  1725. });
  1726. const urlRequest = net.request(serverUrl);
  1727. urlRequest.on('close', () => {
  1728. process.nextTick(() => {
  1729. const v8Util = process._linkedBinding('electron_common_v8_util');
  1730. v8Util.requestGarbageCollectionForTesting();
  1731. });
  1732. });
  1733. urlRequest.write(randomBuffer(kOneMegaByte));
  1734. const response = await getResponse(urlRequest);
  1735. await collectStreamBody(response);
  1736. });
  1737. it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
  1738. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1739. const received = await collectStreamBodyBuffer(request);
  1740. response.end();
  1741. expect(received.length).to.equal(kOneMegaByte);
  1742. });
  1743. const urlRequest = net.request(serverUrl);
  1744. urlRequest.chunkedEncoding = true;
  1745. urlRequest.write(randomBuffer(kOneMegaByte));
  1746. const response = await getResponse(urlRequest);
  1747. await collectStreamBody(response);
  1748. process.nextTick(() => {
  1749. const v8Util = process._linkedBinding('electron_common_v8_util');
  1750. v8Util.requestGarbageCollectionForTesting();
  1751. });
  1752. });
  1753. it('should finish sending data when urlRequest is unreferenced before close event for chunked encoding', async () => {
  1754. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1755. const received = await collectStreamBodyBuffer(request);
  1756. response.end();
  1757. expect(received.length).to.equal(kOneMegaByte);
  1758. });
  1759. const urlRequest = net.request(serverUrl);
  1760. urlRequest.chunkedEncoding = true;
  1761. urlRequest.write(randomBuffer(kOneMegaByte));
  1762. const v8Util = process._linkedBinding('electron_common_v8_util');
  1763. v8Util.requestGarbageCollectionForTesting();
  1764. await collectStreamBody(await getResponse(urlRequest));
  1765. });
  1766. it('should finish sending data when urlRequest is unreferenced', async () => {
  1767. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1768. const received = await collectStreamBodyBuffer(request);
  1769. response.end();
  1770. expect(received.length).to.equal(kOneMegaByte);
  1771. });
  1772. const urlRequest = net.request(serverUrl);
  1773. urlRequest.on('close', () => {
  1774. process.nextTick(() => {
  1775. const v8Util = process._linkedBinding('electron_common_v8_util');
  1776. v8Util.requestGarbageCollectionForTesting();
  1777. });
  1778. });
  1779. urlRequest.write(randomBuffer(kOneMegaByte));
  1780. await collectStreamBody(await getResponse(urlRequest));
  1781. });
  1782. it('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
  1783. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1784. const received = await collectStreamBodyBuffer(request);
  1785. response.end();
  1786. expect(received.length).to.equal(kOneMegaByte);
  1787. });
  1788. const urlRequest = net.request(serverUrl);
  1789. urlRequest.on('close', () => {
  1790. process.nextTick(() => {
  1791. const v8Util = process._linkedBinding('electron_common_v8_util');
  1792. v8Util.requestGarbageCollectionForTesting();
  1793. });
  1794. });
  1795. urlRequest.chunkedEncoding = true;
  1796. urlRequest.write(randomBuffer(kOneMegaByte));
  1797. await collectStreamBody(await getResponse(urlRequest));
  1798. });
  1799. });
  1800. });