api-net-spec.ts 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618
  1. import { net, ClientRequest, ClientRequestConstructorOptions, utilityProcess } from 'electron/main';
  2. import { expect } from 'chai';
  3. import { once } from 'node:events';
  4. import * as http from 'node:http';
  5. import * as path from 'node:path';
  6. import { setTimeout } from 'node:timers/promises';
  7. import { collectStreamBody, collectStreamBodyBuffer, getResponse, kOneKiloByte, kOneMegaByte, randomBuffer, randomString, respondNTimes, respondOnce } from './lib/net-helpers';
  8. const utilityFixturePath = path.resolve(__dirname, 'fixtures', 'api', 'utility-process', 'api-net-spec.js');
  9. async function itUtility (name: string, fn?: Function, args?: {[key:string]: any}) {
  10. it(`${name} in utility process`, async () => {
  11. const child = utilityProcess.fork(utilityFixturePath, [], {
  12. execArgv: ['--expose-gc']
  13. });
  14. if (fn) {
  15. child.postMessage({ fn: `(${fn})()`, args });
  16. } else {
  17. child.postMessage({ fn: '(() => {})()', args });
  18. }
  19. const [data] = await once(child, 'message');
  20. expect(data.ok).to.be.true(data.message);
  21. // Cleanup.
  22. const [code] = await once(child, 'exit');
  23. expect(code).to.equal(0);
  24. });
  25. }
  26. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  27. async function itIgnoringArgs (name: string, fn?: Mocha.Func|Mocha.AsyncFunc, args?: {[key:string]: any}) {
  28. it(name, fn);
  29. }
  30. describe('net module', () => {
  31. beforeEach(() => {
  32. respondNTimes.routeFailure = false;
  33. });
  34. afterEach(async function () {
  35. if (respondNTimes.routeFailure && this.test) {
  36. if (!this.test.isFailed()) {
  37. throw new Error('Failing this test due an unhandled error in the respondOnce route handler, check the logs above for the actual error');
  38. }
  39. }
  40. });
  41. for (const test of [itIgnoringArgs, itUtility]) {
  42. describe('HTTP basics', () => {
  43. test('should be able to issue a basic GET request', async () => {
  44. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  45. expect(request.method).to.equal('GET');
  46. response.end();
  47. });
  48. const urlRequest = net.request(serverUrl);
  49. const response = await getResponse(urlRequest);
  50. expect(response.statusCode).to.equal(200);
  51. await collectStreamBody(response);
  52. });
  53. test('should be able to issue a basic POST request', async () => {
  54. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  55. expect(request.method).to.equal('POST');
  56. response.end();
  57. });
  58. const urlRequest = net.request({
  59. method: 'POST',
  60. url: serverUrl
  61. });
  62. const response = await getResponse(urlRequest);
  63. expect(response.statusCode).to.equal(200);
  64. await collectStreamBody(response);
  65. });
  66. test('should fetch correct data in a GET request', async () => {
  67. const expectedBodyData = 'Hello World!';
  68. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  69. expect(request.method).to.equal('GET');
  70. response.end(expectedBodyData);
  71. });
  72. const urlRequest = net.request(serverUrl);
  73. const response = await getResponse(urlRequest);
  74. expect(response.statusCode).to.equal(200);
  75. const body = await collectStreamBody(response);
  76. expect(body).to.equal(expectedBodyData);
  77. });
  78. test('should post the correct data in a POST request', async () => {
  79. const bodyData = 'Hello World!';
  80. let postedBodyData: string = '';
  81. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  82. postedBodyData = await collectStreamBody(request);
  83. response.end();
  84. });
  85. const urlRequest = net.request({
  86. method: 'POST',
  87. url: serverUrl
  88. });
  89. urlRequest.write(bodyData);
  90. const response = await getResponse(urlRequest);
  91. expect(response.statusCode).to.equal(200);
  92. expect(postedBodyData).to.equal(bodyData);
  93. });
  94. test('a 307 redirected POST request preserves the body', async () => {
  95. const bodyData = 'Hello World!';
  96. let postedBodyData: string = '';
  97. let methodAfterRedirect: string | undefined;
  98. const serverUrl = await respondNTimes.toRoutes({
  99. '/redirect': (req, res) => {
  100. res.statusCode = 307;
  101. res.setHeader('location', serverUrl);
  102. return res.end();
  103. },
  104. '/': async (req, res) => {
  105. methodAfterRedirect = req.method;
  106. postedBodyData = await collectStreamBody(req);
  107. res.end();
  108. }
  109. }, 2);
  110. const urlRequest = net.request({
  111. method: 'POST',
  112. url: serverUrl + '/redirect'
  113. });
  114. urlRequest.write(bodyData);
  115. const response = await getResponse(urlRequest);
  116. expect(response.statusCode).to.equal(200);
  117. await collectStreamBody(response);
  118. expect(methodAfterRedirect).to.equal('POST');
  119. expect(postedBodyData).to.equal(bodyData);
  120. });
  121. test('a 302 redirected POST request DOES NOT preserve the body', async () => {
  122. const bodyData = 'Hello World!';
  123. let postedBodyData: string = '';
  124. let methodAfterRedirect: string | undefined;
  125. const serverUrl = await respondNTimes.toRoutes({
  126. '/redirect': (req, res) => {
  127. res.statusCode = 302;
  128. res.setHeader('location', serverUrl);
  129. return res.end();
  130. },
  131. '/': async (req, res) => {
  132. methodAfterRedirect = req.method;
  133. postedBodyData = await collectStreamBody(req);
  134. res.end();
  135. }
  136. }, 2);
  137. const urlRequest = net.request({
  138. method: 'POST',
  139. url: serverUrl + '/redirect'
  140. });
  141. urlRequest.write(bodyData);
  142. const response = await getResponse(urlRequest);
  143. expect(response.statusCode).to.equal(200);
  144. await collectStreamBody(response);
  145. expect(methodAfterRedirect).to.equal('GET');
  146. expect(postedBodyData).to.equal('');
  147. });
  148. test('should support chunked encoding', async () => {
  149. let receivedRequest: http.IncomingMessage = null as any;
  150. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  151. response.statusCode = 200;
  152. response.statusMessage = 'OK';
  153. response.chunkedEncoding = true;
  154. receivedRequest = request;
  155. request.on('data', (chunk: Buffer) => {
  156. response.write(chunk);
  157. });
  158. request.on('end', (chunk: Buffer) => {
  159. response.end(chunk);
  160. });
  161. });
  162. const urlRequest = net.request({
  163. method: 'POST',
  164. url: serverUrl
  165. });
  166. let chunkIndex = 0;
  167. const chunkCount = 100;
  168. let sent = Buffer.alloc(0);
  169. urlRequest.chunkedEncoding = true;
  170. while (chunkIndex < chunkCount) {
  171. chunkIndex += 1;
  172. const chunk = randomBuffer(kOneKiloByte);
  173. sent = Buffer.concat([sent, chunk]);
  174. urlRequest.write(chunk);
  175. }
  176. const response = await getResponse(urlRequest);
  177. expect(receivedRequest.method).to.equal('POST');
  178. expect(receivedRequest.headers['transfer-encoding']).to.equal('chunked');
  179. expect(receivedRequest.headers['content-length']).to.equal(undefined);
  180. expect(response.statusCode).to.equal(200);
  181. const received = await collectStreamBodyBuffer(response);
  182. expect(sent.equals(received)).to.be.true();
  183. expect(chunkIndex).to.be.equal(chunkCount);
  184. });
  185. for (const extraOptions of [{}, { credentials: 'include' }, { useSessionCookies: false, credentials: 'include' }] as ClientRequestConstructorOptions[]) {
  186. describe(`authentication when ${JSON.stringify(extraOptions)}`, () => {
  187. test('should emit the login event when 401', async () => {
  188. const [user, pass] = ['user', 'pass'];
  189. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  190. if (!request.headers.authorization) {
  191. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  192. }
  193. response.writeHead(200).end('ok');
  194. });
  195. let loginAuthInfo: Electron.AuthInfo;
  196. const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
  197. request.on('login', (authInfo, cb) => {
  198. loginAuthInfo = authInfo;
  199. cb(user, pass);
  200. });
  201. const response = await getResponse(request);
  202. expect(response.statusCode).to.equal(200);
  203. expect(loginAuthInfo!.realm).to.equal('Foo');
  204. expect(loginAuthInfo!.scheme).to.equal('basic');
  205. }, { extraOptions });
  206. test('should receive 401 response when cancelling authentication', async () => {
  207. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  208. if (!request.headers.authorization) {
  209. response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' });
  210. response.end('unauthenticated');
  211. } else {
  212. response.writeHead(200).end('ok');
  213. }
  214. });
  215. const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
  216. request.on('login', (authInfo, cb) => {
  217. cb();
  218. });
  219. const response = await getResponse(request);
  220. const body = await collectStreamBody(response);
  221. expect(response.statusCode).to.equal(401);
  222. expect(body).to.equal('unauthenticated');
  223. }, { extraOptions });
  224. test('should upload body when 401', async () => {
  225. const [user, pass] = ['user', 'pass'];
  226. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  227. if (!request.headers.authorization) {
  228. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  229. }
  230. response.writeHead(200);
  231. request.on('data', (chunk) => response.write(chunk));
  232. request.on('end', () => response.end());
  233. });
  234. const requestData = randomString(kOneKiloByte);
  235. const request = net.request({ method: 'GET', url: serverUrl, ...extraOptions });
  236. request.on('login', (authInfo, cb) => {
  237. cb(user, pass);
  238. });
  239. request.write(requestData);
  240. const response = await getResponse(request);
  241. const responseData = await collectStreamBody(response);
  242. expect(responseData).to.equal(requestData);
  243. }, { extraOptions });
  244. });
  245. }
  246. describe('authentication when {"credentials":"omit"}', () => {
  247. test('should not emit the login event when 401', async () => {
  248. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  249. if (!request.headers.authorization) {
  250. return response.writeHead(401, { 'WWW-Authenticate': 'Basic realm="Foo"' }).end();
  251. }
  252. response.writeHead(200).end('ok');
  253. });
  254. const request = net.request({ method: 'GET', url: serverUrl, credentials: 'omit' });
  255. request.on('login', () => {
  256. expect.fail('unexpected login event');
  257. });
  258. const response = await getResponse(request);
  259. expect(response.statusCode).to.equal(401);
  260. expect(response.headers['www-authenticate']).to.equal('Basic realm="Foo"');
  261. });
  262. });
  263. });
  264. describe('ClientRequest API', () => {
  265. test('request/response objects should emit expected events', async () => {
  266. const bodyData = randomString(kOneKiloByte);
  267. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  268. response.end(bodyData);
  269. });
  270. const urlRequest = net.request(serverUrl);
  271. // request close event
  272. const closePromise = once(urlRequest, 'close');
  273. // request finish event
  274. const finishPromise = once(urlRequest, 'close');
  275. // request "response" event
  276. const response = await getResponse(urlRequest);
  277. response.on('error', (error: Error) => {
  278. expect(error).to.be.an('Error');
  279. });
  280. const statusCode = response.statusCode;
  281. expect(statusCode).to.equal(200);
  282. // response data event
  283. // respond end event
  284. const body = await collectStreamBody(response);
  285. expect(body).to.equal(bodyData);
  286. urlRequest.on('error', (error) => {
  287. expect(error).to.be.an('Error');
  288. });
  289. await Promise.all([closePromise, finishPromise]);
  290. });
  291. test('should be able to set a custom HTTP request header before first write', async () => {
  292. const customHeaderName = 'Some-Custom-Header-Name';
  293. const customHeaderValue = 'Some-Customer-Header-Value';
  294. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  295. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
  296. response.statusCode = 200;
  297. response.statusMessage = 'OK';
  298. response.end();
  299. });
  300. const urlRequest = net.request(serverUrl);
  301. urlRequest.setHeader(customHeaderName, customHeaderValue);
  302. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  303. expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
  304. urlRequest.write('');
  305. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  306. expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
  307. const response = await getResponse(urlRequest);
  308. expect(response.statusCode).to.equal(200);
  309. await collectStreamBody(response);
  310. });
  311. test('should be able to set a non-string object as a header value', async () => {
  312. const customHeaderName = 'Some-Integer-Value';
  313. const customHeaderValue = 900;
  314. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  315. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString());
  316. response.statusCode = 200;
  317. response.statusMessage = 'OK';
  318. response.end();
  319. });
  320. const urlRequest = net.request(serverUrl);
  321. urlRequest.setHeader(customHeaderName, customHeaderValue as any);
  322. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  323. expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
  324. urlRequest.write('');
  325. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  326. expect(urlRequest.getHeader(customHeaderName.toLowerCase())).to.equal(customHeaderValue);
  327. const response = await getResponse(urlRequest);
  328. expect(response.statusCode).to.equal(200);
  329. await collectStreamBody(response);
  330. });
  331. test('should not change the case of header name', async () => {
  332. const customHeaderName = 'X-Header-Name';
  333. const customHeaderValue = 'value';
  334. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  335. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue.toString());
  336. expect(request.rawHeaders.includes(customHeaderName)).to.equal(true);
  337. response.statusCode = 200;
  338. response.statusMessage = 'OK';
  339. response.end();
  340. });
  341. const urlRequest = net.request(serverUrl);
  342. urlRequest.setHeader(customHeaderName, customHeaderValue);
  343. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  344. urlRequest.write('');
  345. const response = await getResponse(urlRequest);
  346. expect(response.statusCode).to.equal(200);
  347. await collectStreamBody(response);
  348. });
  349. test('should not be able to set a custom HTTP request header after first write', async () => {
  350. const customHeaderName = 'Some-Custom-Header-Name';
  351. const customHeaderValue = 'Some-Customer-Header-Value';
  352. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  353. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined);
  354. response.statusCode = 200;
  355. response.statusMessage = 'OK';
  356. response.end();
  357. });
  358. const urlRequest = net.request(serverUrl);
  359. urlRequest.write('');
  360. expect(() => {
  361. urlRequest.setHeader(customHeaderName, customHeaderValue);
  362. }).to.throw();
  363. expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined);
  364. const response = await getResponse(urlRequest);
  365. expect(response.statusCode).to.equal(200);
  366. await collectStreamBody(response);
  367. });
  368. test('should be able to remove a custom HTTP request header before first write', async () => {
  369. const customHeaderName = 'Some-Custom-Header-Name';
  370. const customHeaderValue = 'Some-Customer-Header-Value';
  371. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  372. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(undefined);
  373. response.statusCode = 200;
  374. response.statusMessage = 'OK';
  375. response.end();
  376. });
  377. const urlRequest = net.request(serverUrl);
  378. urlRequest.setHeader(customHeaderName, customHeaderValue);
  379. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  380. urlRequest.removeHeader(customHeaderName);
  381. expect(urlRequest.getHeader(customHeaderName)).to.equal(undefined);
  382. urlRequest.write('');
  383. const response = await getResponse(urlRequest);
  384. expect(response.statusCode).to.equal(200);
  385. await collectStreamBody(response);
  386. });
  387. test('should not be able to remove a custom HTTP request header after first write', async () => {
  388. const customHeaderName = 'Some-Custom-Header-Name';
  389. const customHeaderValue = 'Some-Customer-Header-Value';
  390. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  391. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
  392. response.statusCode = 200;
  393. response.statusMessage = 'OK';
  394. response.end();
  395. });
  396. const urlRequest = net.request(serverUrl);
  397. urlRequest.setHeader(customHeaderName, customHeaderValue);
  398. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  399. urlRequest.write('');
  400. expect(() => {
  401. urlRequest.removeHeader(customHeaderName);
  402. }).to.throw();
  403. expect(urlRequest.getHeader(customHeaderName)).to.equal(customHeaderValue);
  404. const response = await getResponse(urlRequest);
  405. expect(response.statusCode).to.equal(200);
  406. await collectStreamBody(response);
  407. });
  408. test('should keep the order of headers', async () => {
  409. const customHeaderNameA = 'X-Header-100';
  410. const customHeaderNameB = 'X-Header-200';
  411. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  412. const headerNames = Array.from(Object.keys(request.headers));
  413. const headerAIndex = headerNames.indexOf(customHeaderNameA.toLowerCase());
  414. const headerBIndex = headerNames.indexOf(customHeaderNameB.toLowerCase());
  415. expect(headerBIndex).to.be.below(headerAIndex);
  416. response.statusCode = 200;
  417. response.statusMessage = 'OK';
  418. response.end();
  419. });
  420. const urlRequest = net.request(serverUrl);
  421. urlRequest.setHeader(customHeaderNameB, 'b');
  422. urlRequest.setHeader(customHeaderNameA, 'a');
  423. const response = await getResponse(urlRequest);
  424. expect(response.statusCode).to.equal(200);
  425. await collectStreamBody(response);
  426. });
  427. test('should be able to receive cookies', async () => {
  428. const cookie = ['cookie1', 'cookie2'];
  429. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  430. response.statusCode = 200;
  431. response.statusMessage = 'OK';
  432. response.setHeader('set-cookie', cookie);
  433. response.end();
  434. });
  435. const urlRequest = net.request(serverUrl);
  436. const response = await getResponse(urlRequest);
  437. expect(response.headers['set-cookie']).to.have.same.members(cookie);
  438. });
  439. test('should be able to receive content-type', async () => {
  440. const contentType = 'mime/test; charset=test';
  441. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  442. response.statusCode = 200;
  443. response.statusMessage = 'OK';
  444. response.setHeader('content-type', contentType);
  445. response.end();
  446. });
  447. const urlRequest = net.request(serverUrl);
  448. const response = await getResponse(urlRequest);
  449. expect(response.headers['content-type']).to.equal(contentType);
  450. });
  451. describe('when {"credentials":"omit"}', () => {
  452. test('should not send cookies');
  453. test('should not store cookies');
  454. });
  455. test('should set sec-fetch-site to same-origin for request from same origin', async () => {
  456. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  457. expect(request.headers['sec-fetch-site']).to.equal('same-origin');
  458. response.statusCode = 200;
  459. response.statusMessage = 'OK';
  460. response.end();
  461. });
  462. const urlRequest = net.request({
  463. url: serverUrl,
  464. origin: serverUrl
  465. });
  466. await collectStreamBody(await getResponse(urlRequest));
  467. });
  468. test('should set sec-fetch-site to same-origin for request with the same origin header', async () => {
  469. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  470. expect(request.headers['sec-fetch-site']).to.equal('same-origin');
  471. response.statusCode = 200;
  472. response.statusMessage = 'OK';
  473. response.end();
  474. });
  475. const urlRequest = net.request({
  476. url: serverUrl
  477. });
  478. urlRequest.setHeader('Origin', serverUrl);
  479. await collectStreamBody(await getResponse(urlRequest));
  480. });
  481. test('should set sec-fetch-site to cross-site for request from other origin', async () => {
  482. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  483. expect(request.headers['sec-fetch-site']).to.equal('cross-site');
  484. response.statusCode = 200;
  485. response.statusMessage = 'OK';
  486. response.end();
  487. });
  488. const urlRequest = net.request({
  489. url: serverUrl,
  490. origin: 'https://not-exists.com'
  491. });
  492. await collectStreamBody(await getResponse(urlRequest));
  493. });
  494. test('should not send sec-fetch-user header by default', async () => {
  495. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  496. expect(request.headers).not.to.have.property('sec-fetch-user');
  497. response.statusCode = 200;
  498. response.statusMessage = 'OK';
  499. response.end();
  500. });
  501. const urlRequest = net.request({
  502. url: serverUrl
  503. });
  504. await collectStreamBody(await getResponse(urlRequest));
  505. });
  506. test('should set sec-fetch-user to ?1 if requested', async () => {
  507. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  508. expect(request.headers['sec-fetch-user']).to.equal('?1');
  509. response.statusCode = 200;
  510. response.statusMessage = 'OK';
  511. response.end();
  512. });
  513. const urlRequest = net.request({
  514. url: serverUrl
  515. });
  516. urlRequest.setHeader('sec-fetch-user', '?1');
  517. await collectStreamBody(await getResponse(urlRequest));
  518. });
  519. test('should set sec-fetch-mode to no-cors by default', async () => {
  520. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  521. expect(request.headers['sec-fetch-mode']).to.equal('no-cors');
  522. response.statusCode = 200;
  523. response.statusMessage = 'OK';
  524. response.end();
  525. });
  526. const urlRequest = net.request({
  527. url: serverUrl
  528. });
  529. await collectStreamBody(await getResponse(urlRequest));
  530. });
  531. for (const mode of ['navigate', 'cors', 'no-cors', 'same-origin']) {
  532. test(`should set sec-fetch-mode to ${mode} if requested`, async () => {
  533. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  534. expect(request.headers['sec-fetch-mode']).to.equal(mode);
  535. response.statusCode = 200;
  536. response.statusMessage = 'OK';
  537. response.end();
  538. });
  539. const urlRequest = net.request({
  540. url: serverUrl,
  541. origin: serverUrl
  542. });
  543. urlRequest.setHeader('sec-fetch-mode', mode);
  544. await collectStreamBody(await getResponse(urlRequest));
  545. }, { mode });
  546. }
  547. test('should set sec-fetch-dest to empty by default', async () => {
  548. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  549. expect(request.headers['sec-fetch-dest']).to.equal('empty');
  550. response.statusCode = 200;
  551. response.statusMessage = 'OK';
  552. response.end();
  553. });
  554. const urlRequest = net.request({
  555. url: serverUrl
  556. });
  557. await collectStreamBody(await getResponse(urlRequest));
  558. });
  559. for (const dest of [
  560. 'empty', 'audio', 'audioworklet', 'document', 'embed', 'font',
  561. 'frame', 'iframe', 'image', 'manifest', 'object', 'paintworklet',
  562. 'report', 'script', 'serviceworker', 'style', 'track', 'video',
  563. 'worker', 'xslt'
  564. ]) {
  565. test(`should set sec-fetch-dest to ${dest} if requested`, async () => {
  566. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  567. expect(request.headers['sec-fetch-dest']).to.equal(dest);
  568. response.statusCode = 200;
  569. response.statusMessage = 'OK';
  570. response.end();
  571. });
  572. const urlRequest = net.request({
  573. url: serverUrl,
  574. origin: serverUrl
  575. });
  576. urlRequest.setHeader('sec-fetch-dest', dest);
  577. await collectStreamBody(await getResponse(urlRequest));
  578. }, { dest });
  579. }
  580. test('should be able to abort an HTTP request before first write', async () => {
  581. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  582. response.end();
  583. expect.fail('Unexpected request event');
  584. });
  585. const urlRequest = net.request(serverUrl);
  586. urlRequest.on('response', () => {
  587. expect.fail('unexpected response event');
  588. });
  589. const aborted = once(urlRequest, 'abort');
  590. urlRequest.abort();
  591. urlRequest.write('');
  592. urlRequest.end();
  593. await aborted;
  594. });
  595. test('it should be able to abort an HTTP request before request end', async () => {
  596. let requestReceivedByServer = false;
  597. let urlRequest: ClientRequest | null = null;
  598. const serverUrl = await respondOnce.toSingleURL(() => {
  599. requestReceivedByServer = true;
  600. urlRequest!.abort();
  601. });
  602. let requestAbortEventEmitted = false;
  603. urlRequest = net.request(serverUrl);
  604. urlRequest.on('response', () => {
  605. expect.fail('Unexpected response event');
  606. });
  607. urlRequest.on('finish', () => {
  608. expect.fail('Unexpected finish event');
  609. });
  610. urlRequest.on('error', () => {
  611. expect.fail('Unexpected error event');
  612. });
  613. urlRequest.on('abort', () => {
  614. requestAbortEventEmitted = true;
  615. });
  616. const p = once(urlRequest, 'close');
  617. urlRequest.chunkedEncoding = true;
  618. urlRequest.write(randomString(kOneKiloByte));
  619. await p;
  620. expect(requestReceivedByServer).to.equal(true);
  621. expect(requestAbortEventEmitted).to.equal(true);
  622. });
  623. test('it should be able to abort an HTTP request after request end and before response', async () => {
  624. let requestReceivedByServer = false;
  625. let urlRequest: ClientRequest | null = null;
  626. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  627. requestReceivedByServer = true;
  628. urlRequest!.abort();
  629. process.nextTick(() => {
  630. response.statusCode = 200;
  631. response.statusMessage = 'OK';
  632. response.end();
  633. });
  634. });
  635. let requestFinishEventEmitted = false;
  636. urlRequest = net.request(serverUrl);
  637. urlRequest.on('response', () => {
  638. expect.fail('Unexpected response event');
  639. });
  640. urlRequest.on('finish', () => {
  641. requestFinishEventEmitted = true;
  642. });
  643. urlRequest.on('error', () => {
  644. expect.fail('Unexpected error event');
  645. });
  646. urlRequest.end(randomString(kOneKiloByte));
  647. await once(urlRequest, 'abort');
  648. expect(requestFinishEventEmitted).to.equal(true);
  649. expect(requestReceivedByServer).to.equal(true);
  650. });
  651. test('it should be able to abort an HTTP request after response start', async () => {
  652. let requestReceivedByServer = false;
  653. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  654. requestReceivedByServer = true;
  655. response.statusCode = 200;
  656. response.statusMessage = 'OK';
  657. response.write(randomString(kOneKiloByte));
  658. });
  659. let requestFinishEventEmitted = false;
  660. let requestResponseEventEmitted = false;
  661. let responseCloseEventEmitted = false;
  662. const urlRequest = net.request(serverUrl);
  663. urlRequest.on('response', (response) => {
  664. requestResponseEventEmitted = true;
  665. const statusCode = response.statusCode;
  666. expect(statusCode).to.equal(200);
  667. response.on('data', () => {});
  668. response.on('end', () => {
  669. expect.fail('Unexpected end event');
  670. });
  671. response.on('error', () => {
  672. expect.fail('Unexpected error event');
  673. });
  674. response.on('close' as any, () => {
  675. responseCloseEventEmitted = true;
  676. });
  677. urlRequest.abort();
  678. });
  679. urlRequest.on('finish', () => {
  680. requestFinishEventEmitted = true;
  681. });
  682. urlRequest.on('error', () => {
  683. expect.fail('Unexpected error event');
  684. });
  685. urlRequest.end(randomString(kOneKiloByte));
  686. await once(urlRequest, 'abort');
  687. expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
  688. expect(requestReceivedByServer).to.be.true('request should be received by the server');
  689. expect(requestResponseEventEmitted).to.be.true('"response" event should be emitted');
  690. expect(responseCloseEventEmitted).to.be.true('response should emit "close" event');
  691. });
  692. test('abort event should be emitted at most once', async () => {
  693. let requestReceivedByServer = false;
  694. let urlRequest: ClientRequest | null = null;
  695. const serverUrl = await respondOnce.toSingleURL(() => {
  696. requestReceivedByServer = true;
  697. urlRequest!.abort();
  698. urlRequest!.abort();
  699. });
  700. let requestFinishEventEmitted = false;
  701. let abortsEmitted = 0;
  702. urlRequest = net.request(serverUrl);
  703. urlRequest.on('response', () => {
  704. expect.fail('Unexpected response event');
  705. });
  706. urlRequest.on('finish', () => {
  707. requestFinishEventEmitted = true;
  708. });
  709. urlRequest.on('error', () => {
  710. expect.fail('Unexpected error event');
  711. });
  712. urlRequest.on('abort', () => {
  713. abortsEmitted++;
  714. });
  715. urlRequest.end(randomString(kOneKiloByte));
  716. await once(urlRequest, 'abort');
  717. expect(requestFinishEventEmitted).to.be.true('request should emit "finish" event');
  718. expect(requestReceivedByServer).to.be.true('request should be received by server');
  719. expect(abortsEmitted).to.equal(1, 'request should emit exactly 1 "abort" event');
  720. });
  721. test('should allow to read response body from non-2xx response', async () => {
  722. const bodyData = randomString(kOneKiloByte);
  723. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  724. response.statusCode = 404;
  725. response.end(bodyData);
  726. });
  727. const urlRequest = net.request(serverUrl);
  728. const bodyCheckPromise = getResponse(urlRequest).then(r => {
  729. expect(r.statusCode).to.equal(404);
  730. return r;
  731. }).then(collectStreamBody).then(receivedBodyData => {
  732. expect(receivedBodyData.toString()).to.equal(bodyData);
  733. });
  734. const eventHandlers = Promise.all([
  735. bodyCheckPromise,
  736. once(urlRequest, 'close')
  737. ]);
  738. urlRequest.end();
  739. await eventHandlers;
  740. });
  741. test('should throw when calling getHeader without a name', () => {
  742. expect(() => {
  743. (net.request({ url: 'https://test' }).getHeader as any)();
  744. }).to.throw(/`name` is required for getHeader\(name\)/);
  745. expect(() => {
  746. net.request({ url: 'https://test' }).getHeader(null as any);
  747. }).to.throw(/`name` is required for getHeader\(name\)/);
  748. });
  749. test('should throw when calling removeHeader without a name', () => {
  750. expect(() => {
  751. (net.request({ url: 'https://test' }).removeHeader as any)();
  752. }).to.throw(/`name` is required for removeHeader\(name\)/);
  753. expect(() => {
  754. net.request({ url: 'https://test' }).removeHeader(null as any);
  755. }).to.throw(/`name` is required for removeHeader\(name\)/);
  756. });
  757. test('should follow redirect when no redirect handler is provided', async () => {
  758. const requestUrl = '/302';
  759. const serverUrl = await respondOnce.toRoutes({
  760. '/302': (request, response) => {
  761. response.statusCode = 302;
  762. response.setHeader('Location', '/200');
  763. response.end();
  764. },
  765. '/200': (request, response) => {
  766. response.statusCode = 200;
  767. response.end();
  768. }
  769. });
  770. const urlRequest = net.request({
  771. url: `${serverUrl}${requestUrl}`
  772. });
  773. const response = await getResponse(urlRequest);
  774. expect(response.statusCode).to.equal(200);
  775. });
  776. test('should follow redirect chain when no redirect handler is provided', async () => {
  777. const serverUrl = await respondOnce.toRoutes({
  778. '/redirectChain': (request, response) => {
  779. response.statusCode = 302;
  780. response.setHeader('Location', '/302');
  781. response.end();
  782. },
  783. '/302': (request, response) => {
  784. response.statusCode = 302;
  785. response.setHeader('Location', '/200');
  786. response.end();
  787. },
  788. '/200': (request, response) => {
  789. response.statusCode = 200;
  790. response.end();
  791. }
  792. });
  793. const urlRequest = net.request({
  794. url: `${serverUrl}/redirectChain`
  795. });
  796. const response = await getResponse(urlRequest);
  797. expect(response.statusCode).to.equal(200);
  798. });
  799. test('should not follow redirect when request is canceled in redirect handler', async () => {
  800. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  801. response.statusCode = 302;
  802. response.setHeader('Location', '/200');
  803. response.end();
  804. });
  805. const urlRequest = net.request({
  806. url: serverUrl
  807. });
  808. urlRequest.end();
  809. urlRequest.on('redirect', () => { urlRequest.abort(); });
  810. urlRequest.on('error', () => {});
  811. urlRequest.on('response', () => {
  812. expect.fail('Unexpected response');
  813. });
  814. await once(urlRequest, 'abort');
  815. });
  816. test('should not follow redirect when mode is error', async () => {
  817. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  818. response.statusCode = 302;
  819. response.setHeader('Location', '/200');
  820. response.end();
  821. });
  822. const urlRequest = net.request({
  823. url: serverUrl,
  824. redirect: 'error'
  825. });
  826. urlRequest.end();
  827. await once(urlRequest, 'error');
  828. });
  829. test('should follow redirect when handler calls callback', async () => {
  830. const serverUrl = await respondOnce.toRoutes({
  831. '/redirectChain': (request, response) => {
  832. response.statusCode = 302;
  833. response.setHeader('Location', '/302');
  834. response.end();
  835. },
  836. '/302': (request, response) => {
  837. response.statusCode = 302;
  838. response.setHeader('Location', '/200');
  839. response.end();
  840. },
  841. '/200': (request, response) => {
  842. response.statusCode = 200;
  843. response.end();
  844. }
  845. });
  846. const urlRequest = net.request({ url: `${serverUrl}/redirectChain`, redirect: 'manual' });
  847. const redirects: string[] = [];
  848. urlRequest.on('redirect', (status, method, url) => {
  849. redirects.push(url);
  850. urlRequest.followRedirect();
  851. });
  852. const response = await getResponse(urlRequest);
  853. expect(response.statusCode).to.equal(200);
  854. expect(redirects).to.deep.equal([
  855. `${serverUrl}/302`,
  856. `${serverUrl}/200`
  857. ]);
  858. });
  859. test('should be able to create a request with options', async () => {
  860. const customHeaderName = 'Some-Custom-Header-Name';
  861. const customHeaderValue = 'Some-Customer-Header-Value';
  862. const serverUrlUnparsed = await respondOnce.toURL('/', (request, response) => {
  863. expect(request.method).to.equal('GET');
  864. expect(request.headers[customHeaderName.toLowerCase()]).to.equal(customHeaderValue);
  865. response.statusCode = 200;
  866. response.statusMessage = 'OK';
  867. response.end();
  868. });
  869. const serverUrl = new URL(serverUrlUnparsed);
  870. const urlRequest = net.request({
  871. port: serverUrl.port ? parseInt(serverUrl.port, 10) : undefined,
  872. hostname: '127.0.0.1',
  873. headers: { [customHeaderName]: customHeaderValue }
  874. });
  875. const response = await getResponse(urlRequest);
  876. expect(response.statusCode).to.be.equal(200);
  877. await collectStreamBody(response);
  878. });
  879. test('should be able to pipe a readable stream into a net request', async () => {
  880. const bodyData = randomString(kOneMegaByte);
  881. let netRequestReceived = false;
  882. let netRequestEnded = false;
  883. const [nodeServerUrl, netServerUrl] = await Promise.all([
  884. respondOnce.toSingleURL((request, response) => response.end(bodyData)),
  885. respondOnce.toSingleURL((request, response) => {
  886. netRequestReceived = true;
  887. let receivedBodyData = '';
  888. request.on('data', (chunk) => {
  889. receivedBodyData += chunk.toString();
  890. });
  891. request.on('end', (chunk: Buffer | undefined) => {
  892. netRequestEnded = true;
  893. if (chunk) {
  894. receivedBodyData += chunk.toString();
  895. }
  896. expect(receivedBodyData).to.be.equal(bodyData);
  897. response.end();
  898. });
  899. })
  900. ]);
  901. const nodeRequest = http.request(nodeServerUrl);
  902. const nodeResponse = await getResponse(nodeRequest as any) as any as http.ServerResponse;
  903. const netRequest = net.request(netServerUrl);
  904. const responsePromise = once(netRequest, 'response');
  905. // TODO(@MarshallOfSound) - FIXME with #22730
  906. nodeResponse.pipe(netRequest as any);
  907. const [netResponse] = await responsePromise;
  908. expect(netResponse.statusCode).to.equal(200);
  909. await collectStreamBody(netResponse);
  910. expect(netRequestReceived).to.be.true('net request received');
  911. expect(netRequestEnded).to.be.true('net request ended');
  912. });
  913. test('should report upload progress', async () => {
  914. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  915. response.end();
  916. });
  917. const netRequest = net.request({ url: serverUrl, method: 'POST' });
  918. expect(netRequest.getUploadProgress()).to.have.property('active', false);
  919. netRequest.end(Buffer.from('hello'));
  920. const [position, total] = await once(netRequest, 'upload-progress');
  921. expect(netRequest.getUploadProgress()).to.deep.equal({ active: true, started: true, current: position, total });
  922. });
  923. test('should emit error event on server socket destroy', async () => {
  924. const serverUrl = await respondOnce.toSingleURL((request) => {
  925. request.socket.destroy();
  926. });
  927. const urlRequest = net.request(serverUrl);
  928. urlRequest.end();
  929. const [error] = await once(urlRequest, 'error');
  930. expect(error.message).to.equal('net::ERR_EMPTY_RESPONSE');
  931. });
  932. test('should emit error event on server request destroy', async () => {
  933. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  934. request.destroy();
  935. response.end();
  936. });
  937. const urlRequest = net.request(serverUrl);
  938. urlRequest.end(randomBuffer(kOneMegaByte));
  939. const [error] = await once(urlRequest, 'error');
  940. expect(error.message).to.be.oneOf(['net::ERR_FAILED', 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_ABORTED']);
  941. });
  942. test('should not emit any event after close', async () => {
  943. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  944. response.end();
  945. });
  946. const urlRequest = net.request(serverUrl);
  947. urlRequest.end();
  948. await once(urlRequest, 'close');
  949. await new Promise((resolve, reject) => {
  950. for (const evName of ['finish', 'abort', 'close', 'error']) {
  951. urlRequest.on(evName as any, () => {
  952. reject(new Error(`Unexpected ${evName} event`));
  953. });
  954. }
  955. setTimeout(50).then(resolve);
  956. });
  957. });
  958. test('should remove the referer header when no referrer url specified', async () => {
  959. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  960. expect(request.headers.referer).to.equal(undefined);
  961. response.statusCode = 200;
  962. response.statusMessage = 'OK';
  963. response.end();
  964. });
  965. const urlRequest = net.request(serverUrl);
  966. urlRequest.end();
  967. const response = await getResponse(urlRequest);
  968. expect(response.statusCode).to.equal(200);
  969. await collectStreamBody(response);
  970. });
  971. test('should set the referer header when a referrer url specified', async () => {
  972. const referrerURL = 'https://www.electronjs.org/';
  973. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  974. expect(request.headers.referer).to.equal(referrerURL);
  975. response.statusCode = 200;
  976. response.statusMessage = 'OK';
  977. response.end();
  978. });
  979. // The referrerPolicy must be unsafe-url because the referrer's origin
  980. // doesn't match the loaded page. With the default referrer policy
  981. // (strict-origin-when-cross-origin), the request will be canceled by the
  982. // network service when the referrer header is invalid.
  983. // See:
  984. // - https://source.chromium.org/chromium/chromium/src/+/main:net/url_request/url_request.cc;l=682-683;drc=ae587fa7cd2e5cc308ce69353ee9ce86437e5d41
  985. // - https://source.chromium.org/chromium/chromium/src/+/main:services/network/public/mojom/network_context.mojom;l=316-318;drc=ae5c7fcf09509843c1145f544cce3a61874b9698
  986. // - https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
  987. const urlRequest = net.request({ url: serverUrl, referrerPolicy: 'unsafe-url' });
  988. urlRequest.setHeader('referer', referrerURL);
  989. urlRequest.end();
  990. const response = await getResponse(urlRequest);
  991. expect(response.statusCode).to.equal(200);
  992. await collectStreamBody(response);
  993. });
  994. });
  995. describe('IncomingMessage API', () => {
  996. test('response object should implement the IncomingMessage API', async () => {
  997. const customHeaderName = 'Some-Custom-Header-Name';
  998. const customHeaderValue = 'Some-Customer-Header-Value';
  999. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1000. response.statusCode = 200;
  1001. response.statusMessage = 'OK';
  1002. response.setHeader(customHeaderName, customHeaderValue);
  1003. response.end();
  1004. });
  1005. const urlRequest = net.request(serverUrl);
  1006. const response = await getResponse(urlRequest);
  1007. expect(response.statusCode).to.equal(200);
  1008. expect(response.statusMessage).to.equal('OK');
  1009. const headers = response.headers;
  1010. expect(headers).to.be.an('object');
  1011. const headerValue = headers[customHeaderName.toLowerCase()];
  1012. expect(headerValue).to.equal(customHeaderValue);
  1013. const rawHeaders = response.rawHeaders;
  1014. expect(rawHeaders).to.be.an('array');
  1015. expect(rawHeaders[0]).to.equal(customHeaderName);
  1016. expect(rawHeaders[1]).to.equal(customHeaderValue);
  1017. const httpVersion = response.httpVersion;
  1018. expect(httpVersion).to.be.a('string').and.to.have.lengthOf.at.least(1);
  1019. const httpVersionMajor = response.httpVersionMajor;
  1020. expect(httpVersionMajor).to.be.a('number').and.to.be.at.least(1);
  1021. const httpVersionMinor = response.httpVersionMinor;
  1022. expect(httpVersionMinor).to.be.a('number').and.to.be.at.least(0);
  1023. await collectStreamBody(response);
  1024. });
  1025. test('should discard duplicate headers', async () => {
  1026. const includedHeader = 'max-forwards';
  1027. const discardableHeader = 'Max-Forwards';
  1028. const includedHeaderValue = 'max-fwds-val';
  1029. const discardableHeaderValue = 'max-fwds-val-two';
  1030. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1031. response.statusCode = 200;
  1032. response.statusMessage = 'OK';
  1033. response.setHeader(discardableHeader, discardableHeaderValue);
  1034. response.setHeader(includedHeader, includedHeaderValue);
  1035. response.end();
  1036. });
  1037. const urlRequest = net.request(serverUrl);
  1038. const response = await getResponse(urlRequest);
  1039. expect(response.statusCode).to.equal(200);
  1040. expect(response.statusMessage).to.equal('OK');
  1041. const headers = response.headers;
  1042. expect(headers).to.be.an('object');
  1043. expect(headers).to.have.property(includedHeader);
  1044. expect(headers).to.not.have.property(discardableHeader);
  1045. expect(headers[includedHeader]).to.equal(includedHeaderValue);
  1046. await collectStreamBody(response);
  1047. });
  1048. test('should join repeated non-discardable header values with ,', async () => {
  1049. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1050. response.statusCode = 200;
  1051. response.statusMessage = 'OK';
  1052. response.setHeader('referrer-policy', ['first-text', 'second-text']);
  1053. response.end();
  1054. });
  1055. const urlRequest = net.request(serverUrl);
  1056. const response = await getResponse(urlRequest);
  1057. expect(response.statusCode).to.equal(200);
  1058. expect(response.statusMessage).to.equal('OK');
  1059. const headers = response.headers;
  1060. expect(headers).to.be.an('object');
  1061. expect(headers).to.have.property('referrer-policy');
  1062. expect(headers['referrer-policy']).to.equal('first-text, second-text');
  1063. await collectStreamBody(response);
  1064. });
  1065. test('should not join repeated discardable header values with ,', async () => {
  1066. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1067. response.statusCode = 200;
  1068. response.statusMessage = 'OK';
  1069. response.setHeader('last-modified', ['yesterday', 'today']);
  1070. response.end();
  1071. });
  1072. const urlRequest = net.request(serverUrl);
  1073. const response = await getResponse(urlRequest);
  1074. expect(response.statusCode).to.equal(200);
  1075. expect(response.statusMessage).to.equal('OK');
  1076. const headers = response.headers;
  1077. expect(headers).to.be.an('object');
  1078. expect(headers).to.have.property('last-modified');
  1079. expect(headers['last-modified']).to.equal('yesterday');
  1080. await collectStreamBody(response);
  1081. });
  1082. test('should make set-cookie header an array even if single value', async () => {
  1083. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1084. response.statusCode = 200;
  1085. response.statusMessage = 'OK';
  1086. response.setHeader('set-cookie', 'chocolate-chip');
  1087. response.end();
  1088. });
  1089. const urlRequest = net.request(serverUrl);
  1090. const response = await getResponse(urlRequest);
  1091. expect(response.statusCode).to.equal(200);
  1092. expect(response.statusMessage).to.equal('OK');
  1093. const headers = response.headers;
  1094. expect(headers).to.be.an('object');
  1095. expect(headers).to.have.property('set-cookie');
  1096. expect(headers['set-cookie']).to.be.an('array');
  1097. expect(headers['set-cookie'][0]).to.equal('chocolate-chip');
  1098. await collectStreamBody(response);
  1099. });
  1100. test('should keep set-cookie header an array when an array', async () => {
  1101. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1102. response.statusCode = 200;
  1103. response.statusMessage = 'OK';
  1104. response.setHeader('set-cookie', ['chocolate-chip', 'oatmeal']);
  1105. response.end();
  1106. });
  1107. const urlRequest = net.request(serverUrl);
  1108. const response = await getResponse(urlRequest);
  1109. expect(response.statusCode).to.equal(200);
  1110. expect(response.statusMessage).to.equal('OK');
  1111. const headers = response.headers;
  1112. expect(headers).to.be.an('object');
  1113. expect(headers).to.have.property('set-cookie');
  1114. expect(headers['set-cookie']).to.be.an('array');
  1115. expect(headers['set-cookie'][0]).to.equal('chocolate-chip');
  1116. expect(headers['set-cookie'][1]).to.equal('oatmeal');
  1117. await collectStreamBody(response);
  1118. });
  1119. test('should lowercase header keys', async () => {
  1120. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1121. response.statusCode = 200;
  1122. response.statusMessage = 'OK';
  1123. response.setHeader('HEADER-KEY', ['header-value']);
  1124. response.setHeader('SeT-CookiE', ['chocolate-chip', 'oatmeal']);
  1125. response.setHeader('rEFERREr-pOLICy', ['first-text', 'second-text']);
  1126. response.setHeader('LAST-modified', 'yesterday');
  1127. response.end();
  1128. });
  1129. const urlRequest = net.request(serverUrl);
  1130. const response = await getResponse(urlRequest);
  1131. expect(response.statusCode).to.equal(200);
  1132. expect(response.statusMessage).to.equal('OK');
  1133. const headers = response.headers;
  1134. expect(headers).to.be.an('object');
  1135. expect(headers).to.have.property('header-key');
  1136. expect(headers).to.have.property('set-cookie');
  1137. expect(headers).to.have.property('referrer-policy');
  1138. expect(headers).to.have.property('last-modified');
  1139. await collectStreamBody(response);
  1140. });
  1141. test('should return correct raw headers', async () => {
  1142. const customHeaders: [string, string|string[]][] = [
  1143. ['HEADER-KEY-ONE', 'header-value-one'],
  1144. ['set-cookie', 'chocolate-chip'],
  1145. ['header-key-two', 'header-value-two'],
  1146. ['referrer-policy', ['first-text', 'second-text']],
  1147. ['HEADER-KEY-THREE', 'header-value-three'],
  1148. ['last-modified', ['first-text', 'second-text']],
  1149. ['header-key-four', 'header-value-four']
  1150. ];
  1151. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1152. response.statusCode = 200;
  1153. response.statusMessage = 'OK';
  1154. for (const headerTuple of customHeaders) {
  1155. response.setHeader(headerTuple[0], headerTuple[1]);
  1156. }
  1157. response.end();
  1158. });
  1159. const urlRequest = net.request(serverUrl);
  1160. const response = await getResponse(urlRequest);
  1161. expect(response.statusCode).to.equal(200);
  1162. expect(response.statusMessage).to.equal('OK');
  1163. const rawHeaders = response.rawHeaders;
  1164. expect(rawHeaders).to.be.an('array');
  1165. let rawHeadersIdx = 0;
  1166. for (const headerTuple of customHeaders) {
  1167. const headerKey = headerTuple[0];
  1168. const headerValues = Array.isArray(headerTuple[1]) ? headerTuple[1] : [headerTuple[1]];
  1169. for (const headerValue of headerValues) {
  1170. expect(rawHeaders[rawHeadersIdx]).to.equal(headerKey);
  1171. expect(rawHeaders[rawHeadersIdx + 1]).to.equal(headerValue);
  1172. rawHeadersIdx += 2;
  1173. }
  1174. }
  1175. await collectStreamBody(response);
  1176. });
  1177. test('should be able to pipe a net response into a writable stream', async () => {
  1178. const bodyData = randomString(kOneKiloByte);
  1179. let nodeRequestProcessed = false;
  1180. const [netServerUrl, nodeServerUrl] = await Promise.all([
  1181. respondOnce.toSingleURL((request, response) => response.end(bodyData)),
  1182. respondOnce.toSingleURL(async (request, response) => {
  1183. const receivedBodyData = await collectStreamBody(request);
  1184. expect(receivedBodyData).to.be.equal(bodyData);
  1185. nodeRequestProcessed = true;
  1186. response.end();
  1187. })
  1188. ]);
  1189. const netRequest = net.request(netServerUrl);
  1190. const netResponse = await getResponse(netRequest);
  1191. const serverUrl = new URL(nodeServerUrl);
  1192. const nodeOptions = {
  1193. method: 'POST',
  1194. path: serverUrl.pathname,
  1195. port: serverUrl.port
  1196. };
  1197. const nodeRequest = http.request(nodeOptions);
  1198. const nodeResponsePromise = once(nodeRequest, 'response');
  1199. // TODO(@MarshallOfSound) - FIXME with #22730
  1200. (netResponse as any).pipe(nodeRequest);
  1201. const [nodeResponse] = await nodeResponsePromise;
  1202. netRequest.end();
  1203. await collectStreamBody(nodeResponse);
  1204. expect(nodeRequestProcessed).to.equal(true);
  1205. });
  1206. test('should correctly throttle an incoming stream', async () => {
  1207. let numChunksSent = 0;
  1208. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1209. const data = randomString(kOneMegaByte);
  1210. const write = () => {
  1211. let ok = true;
  1212. do {
  1213. numChunksSent++;
  1214. if (numChunksSent > 30) return;
  1215. ok = response.write(data);
  1216. } while (ok);
  1217. response.once('drain', write);
  1218. };
  1219. write();
  1220. });
  1221. const urlRequest = net.request(serverUrl);
  1222. urlRequest.on('response', () => {});
  1223. urlRequest.end();
  1224. await setTimeout(2000);
  1225. // TODO(nornagon): I think this ought to max out at 20, but in practice
  1226. // it seems to exceed that sometimes. This is at 25 to avoid test flakes,
  1227. // but we should investigate if there's actually something broken here and
  1228. // if so fix it and reset this to max at 20, and if not then delete this
  1229. // comment.
  1230. expect(numChunksSent).to.be.at.most(25);
  1231. });
  1232. });
  1233. describe('net.isOnline', () => {
  1234. test('getter returns boolean', () => {
  1235. expect(net.isOnline()).to.be.a('boolean');
  1236. });
  1237. test('property returns boolean', () => {
  1238. expect(net.online).to.be.a('boolean');
  1239. });
  1240. });
  1241. describe('Stability and performance', () => {
  1242. test('should free unreferenced, never-started request objects without crash', async () => {
  1243. net.request('https://test');
  1244. await new Promise<void>((resolve) => {
  1245. process.nextTick(() => {
  1246. const v8Util = process._linkedBinding('electron_common_v8_util');
  1247. v8Util.requestGarbageCollectionForTesting();
  1248. resolve();
  1249. });
  1250. });
  1251. });
  1252. test('should collect on-going requests without crash', async () => {
  1253. let finishResponse: (() => void) | null = null;
  1254. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1255. response.write(randomString(kOneKiloByte));
  1256. finishResponse = () => {
  1257. response.write(randomString(kOneKiloByte));
  1258. response.end();
  1259. };
  1260. });
  1261. const urlRequest = net.request(serverUrl);
  1262. const response = await getResponse(urlRequest);
  1263. process.nextTick(() => {
  1264. // Trigger a garbage collection.
  1265. const v8Util = process._linkedBinding('electron_common_v8_util');
  1266. v8Util.requestGarbageCollectionForTesting();
  1267. finishResponse!();
  1268. });
  1269. await collectStreamBody(response);
  1270. });
  1271. test('should collect unreferenced, ended requests without crash', async () => {
  1272. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1273. response.end();
  1274. });
  1275. const urlRequest = net.request(serverUrl);
  1276. process.nextTick(() => {
  1277. const v8Util = process._linkedBinding('electron_common_v8_util');
  1278. v8Util.requestGarbageCollectionForTesting();
  1279. });
  1280. const response = await getResponse(urlRequest);
  1281. await collectStreamBody(response);
  1282. });
  1283. test('should finish sending data when urlRequest is unreferenced', async () => {
  1284. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1285. const received = await collectStreamBodyBuffer(request);
  1286. expect(received.length).to.equal(kOneMegaByte);
  1287. response.end();
  1288. });
  1289. const urlRequest = net.request(serverUrl);
  1290. urlRequest.on('close', () => {
  1291. process.nextTick(() => {
  1292. const v8Util = process._linkedBinding('electron_common_v8_util');
  1293. v8Util.requestGarbageCollectionForTesting();
  1294. });
  1295. });
  1296. urlRequest.write(randomBuffer(kOneMegaByte));
  1297. const response = await getResponse(urlRequest);
  1298. await collectStreamBody(response);
  1299. });
  1300. test('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
  1301. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1302. const received = await collectStreamBodyBuffer(request);
  1303. response.end();
  1304. expect(received.length).to.equal(kOneMegaByte);
  1305. });
  1306. const urlRequest = net.request(serverUrl);
  1307. urlRequest.chunkedEncoding = true;
  1308. urlRequest.write(randomBuffer(kOneMegaByte));
  1309. const response = await getResponse(urlRequest);
  1310. await collectStreamBody(response);
  1311. process.nextTick(() => {
  1312. const v8Util = process._linkedBinding('electron_common_v8_util');
  1313. v8Util.requestGarbageCollectionForTesting();
  1314. });
  1315. });
  1316. test('should finish sending data when urlRequest is unreferenced before close event for chunked encoding', async () => {
  1317. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1318. const received = await collectStreamBodyBuffer(request);
  1319. response.end();
  1320. expect(received.length).to.equal(kOneMegaByte);
  1321. });
  1322. const urlRequest = net.request(serverUrl);
  1323. urlRequest.chunkedEncoding = true;
  1324. urlRequest.write(randomBuffer(kOneMegaByte));
  1325. const v8Util = process._linkedBinding('electron_common_v8_util');
  1326. v8Util.requestGarbageCollectionForTesting();
  1327. await collectStreamBody(await getResponse(urlRequest));
  1328. });
  1329. test('should finish sending data when urlRequest is unreferenced', async () => {
  1330. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1331. const received = await collectStreamBodyBuffer(request);
  1332. response.end();
  1333. expect(received.length).to.equal(kOneMegaByte);
  1334. });
  1335. const urlRequest = net.request(serverUrl);
  1336. urlRequest.on('close', () => {
  1337. process.nextTick(() => {
  1338. const v8Util = process._linkedBinding('electron_common_v8_util');
  1339. v8Util.requestGarbageCollectionForTesting();
  1340. });
  1341. });
  1342. urlRequest.write(randomBuffer(kOneMegaByte));
  1343. await collectStreamBody(await getResponse(urlRequest));
  1344. });
  1345. test('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
  1346. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1347. const received = await collectStreamBodyBuffer(request);
  1348. response.end();
  1349. expect(received.length).to.equal(kOneMegaByte);
  1350. });
  1351. const urlRequest = net.request(serverUrl);
  1352. urlRequest.on('close', () => {
  1353. process.nextTick(() => {
  1354. const v8Util = process._linkedBinding('electron_common_v8_util');
  1355. v8Util.requestGarbageCollectionForTesting();
  1356. });
  1357. });
  1358. urlRequest.chunkedEncoding = true;
  1359. urlRequest.write(randomBuffer(kOneMegaByte));
  1360. await collectStreamBody(await getResponse(urlRequest));
  1361. });
  1362. });
  1363. describe('non-http schemes', () => {
  1364. test('should be rejected by net.request', async () => {
  1365. expect(() => {
  1366. net.request('file://bar');
  1367. }).to.throw('ClientRequest only supports http: and https: protocols');
  1368. });
  1369. test('should be rejected by net.request when passed in url:', async () => {
  1370. expect(() => {
  1371. net.request({ url: 'file://bar' });
  1372. }).to.throw('ClientRequest only supports http: and https: protocols');
  1373. });
  1374. });
  1375. describe('net.fetch', () => {
  1376. // NB. there exist much more comprehensive tests for fetch() in the form of
  1377. // the WPT: https://github.com/web-platform-tests/wpt/tree/master/fetch
  1378. // It's possible to run these tests against net.fetch(), but the test
  1379. // harness to do so is quite complex and hasn't been munged to smoothly run
  1380. // inside the Electron test runner yet.
  1381. //
  1382. // In the meantime, here are some tests for basic functionality and
  1383. // Electron-specific behavior.
  1384. describe('basic', () => {
  1385. test('can fetch http urls', async () => {
  1386. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1387. response.end('test');
  1388. });
  1389. const resp = await net.fetch(serverUrl);
  1390. expect(resp.ok).to.be.true();
  1391. expect(await resp.text()).to.equal('test');
  1392. });
  1393. test('can upload a string body', async () => {
  1394. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1395. request.on('data', chunk => response.write(chunk));
  1396. request.on('end', () => response.end());
  1397. });
  1398. const resp = await net.fetch(serverUrl, {
  1399. method: 'POST',
  1400. body: 'anchovies'
  1401. });
  1402. expect(await resp.text()).to.equal('anchovies');
  1403. });
  1404. test('can read response as an array buffer', async () => {
  1405. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1406. request.on('data', chunk => response.write(chunk));
  1407. request.on('end', () => response.end());
  1408. });
  1409. const resp = await net.fetch(serverUrl, {
  1410. method: 'POST',
  1411. body: 'anchovies'
  1412. });
  1413. expect(new TextDecoder().decode(new Uint8Array(await resp.arrayBuffer()))).to.equal('anchovies');
  1414. });
  1415. test('can read response as form data', async () => {
  1416. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1417. response.setHeader('content-type', 'application/x-www-form-urlencoded');
  1418. response.end('foo=bar');
  1419. });
  1420. const resp = await net.fetch(serverUrl);
  1421. const result = await resp.formData();
  1422. expect(result.get('foo')).to.equal('bar');
  1423. });
  1424. test('should reject promise on DNS failure', async () => {
  1425. const r = net.fetch('https://i.do.not.exist');
  1426. await expect(r).to.be.rejectedWith(/ERR_NAME_NOT_RESOLVED/);
  1427. });
  1428. test('should reject body promise when stream fails', async () => {
  1429. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1430. response.write('first chunk');
  1431. setTimeout().then(() => response.destroy());
  1432. });
  1433. const r = await net.fetch(serverUrl);
  1434. expect(r.status).to.equal(200);
  1435. await expect(r.text()).to.be.rejectedWith(/ERR_INCOMPLETE_CHUNKED_ENCODING/);
  1436. });
  1437. });
  1438. });
  1439. describe('net.resolveHost', () => {
  1440. test('resolves ipv4.localhost2', async () => {
  1441. const { endpoints } = await net.resolveHost('ipv4.localhost2');
  1442. expect(endpoints).to.be.a('array');
  1443. expect(endpoints).to.have.lengthOf(1);
  1444. expect(endpoints[0].family).to.equal('ipv4');
  1445. expect(endpoints[0].address).to.equal('10.0.0.1');
  1446. });
  1447. test('fails to resolve AAAA record for ipv4.localhost2', async () => {
  1448. await expect(net.resolveHost('ipv4.localhost2', {
  1449. queryType: 'AAAA'
  1450. }))
  1451. .to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/);
  1452. });
  1453. test('resolves ipv6.localhost2', async () => {
  1454. const { endpoints } = await net.resolveHost('ipv6.localhost2');
  1455. expect(endpoints).to.be.a('array');
  1456. expect(endpoints).to.have.lengthOf(1);
  1457. expect(endpoints[0].family).to.equal('ipv6');
  1458. expect(endpoints[0].address).to.equal('::1');
  1459. });
  1460. test('fails to resolve A record for ipv6.localhost2', async () => {
  1461. await expect(net.resolveHost('notfound.localhost2', {
  1462. queryType: 'A'
  1463. }))
  1464. .to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/);
  1465. });
  1466. test('fails to resolve notfound.localhost2', async () => {
  1467. await expect(net.resolveHost('notfound.localhost2'))
  1468. .to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/);
  1469. });
  1470. });
  1471. }
  1472. });