api-net-spec.ts 66 KB

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