api-net-spec.ts 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617
  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 options = {
  872. port: serverUrl.port ? parseInt(serverUrl.port, 10) : undefined,
  873. hostname: '127.0.0.1',
  874. headers: { [customHeaderName]: customHeaderValue }
  875. };
  876. const urlRequest = net.request(options);
  877. const response = await getResponse(urlRequest);
  878. expect(response.statusCode).to.be.equal(200);
  879. await collectStreamBody(response);
  880. });
  881. test('should be able to pipe a readable stream into a net request', async () => {
  882. const bodyData = randomString(kOneMegaByte);
  883. let netRequestReceived = false;
  884. let netRequestEnded = false;
  885. const [nodeServerUrl, netServerUrl] = await Promise.all([
  886. respondOnce.toSingleURL((request, response) => response.end(bodyData)),
  887. respondOnce.toSingleURL((request, response) => {
  888. netRequestReceived = true;
  889. let receivedBodyData = '';
  890. request.on('data', (chunk) => {
  891. receivedBodyData += chunk.toString();
  892. });
  893. request.on('end', (chunk: Buffer | undefined) => {
  894. netRequestEnded = true;
  895. if (chunk) {
  896. receivedBodyData += chunk.toString();
  897. }
  898. expect(receivedBodyData).to.be.equal(bodyData);
  899. response.end();
  900. });
  901. })
  902. ]);
  903. const nodeRequest = http.request(nodeServerUrl);
  904. const nodeResponse = await getResponse(nodeRequest as any) as any as http.ServerResponse;
  905. const netRequest = net.request(netServerUrl);
  906. const responsePromise = once(netRequest, 'response');
  907. // TODO(@MarshallOfSound) - FIXME with #22730
  908. nodeResponse.pipe(netRequest as any);
  909. const [netResponse] = await responsePromise;
  910. expect(netResponse.statusCode).to.equal(200);
  911. await collectStreamBody(netResponse);
  912. expect(netRequestReceived).to.be.true('net request received');
  913. expect(netRequestEnded).to.be.true('net request ended');
  914. });
  915. test('should report upload progress', async () => {
  916. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  917. response.end();
  918. });
  919. const netRequest = net.request({ url: serverUrl, method: 'POST' });
  920. expect(netRequest.getUploadProgress()).to.have.property('active', false);
  921. netRequest.end(Buffer.from('hello'));
  922. const [position, total] = await once(netRequest, 'upload-progress');
  923. expect(netRequest.getUploadProgress()).to.deep.equal({ active: true, started: true, current: position, total });
  924. });
  925. test('should emit error event on server socket destroy', async () => {
  926. const serverUrl = await respondOnce.toSingleURL((request) => {
  927. request.socket.destroy();
  928. });
  929. const urlRequest = net.request(serverUrl);
  930. urlRequest.end();
  931. const [error] = await once(urlRequest, 'error');
  932. expect(error.message).to.equal('net::ERR_EMPTY_RESPONSE');
  933. });
  934. test('should emit error event on server request destroy', async () => {
  935. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  936. request.destroy();
  937. response.end();
  938. });
  939. const urlRequest = net.request(serverUrl);
  940. urlRequest.end(randomBuffer(kOneMegaByte));
  941. const [error] = await once(urlRequest, 'error');
  942. expect(error.message).to.be.oneOf(['net::ERR_FAILED', 'net::ERR_CONNECTION_RESET', 'net::ERR_CONNECTION_ABORTED']);
  943. });
  944. test('should not emit any event after close', async () => {
  945. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  946. response.end();
  947. });
  948. const urlRequest = net.request(serverUrl);
  949. urlRequest.end();
  950. await once(urlRequest, 'close');
  951. await new Promise((resolve, reject) => {
  952. for (const evName of ['finish', 'abort', 'close', 'error']) {
  953. urlRequest.on(evName as any, () => {
  954. reject(new Error(`Unexpected ${evName} event`));
  955. });
  956. }
  957. setTimeout(50).then(resolve);
  958. });
  959. });
  960. test('should remove the referer header when no referrer url specified', async () => {
  961. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  962. expect(request.headers.referer).to.equal(undefined);
  963. response.statusCode = 200;
  964. response.statusMessage = 'OK';
  965. response.end();
  966. });
  967. const urlRequest = net.request(serverUrl);
  968. urlRequest.end();
  969. const response = await getResponse(urlRequest);
  970. expect(response.statusCode).to.equal(200);
  971. await collectStreamBody(response);
  972. });
  973. test('should set the referer header when a referrer url specified', async () => {
  974. const referrerURL = 'https://www.electronjs.org/';
  975. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  976. expect(request.headers.referer).to.equal(referrerURL);
  977. response.statusCode = 200;
  978. response.statusMessage = 'OK';
  979. response.end();
  980. });
  981. // The referrerPolicy must be unsafe-url because the referrer's origin
  982. // doesn't match the loaded page. With the default referrer policy
  983. // (strict-origin-when-cross-origin), the request will be canceled by the
  984. // network service when the referrer header is invalid.
  985. // See:
  986. // - https://source.chromium.org/chromium/chromium/src/+/main:net/url_request/url_request.cc;l=682-683;drc=ae587fa7cd2e5cc308ce69353ee9ce86437e5d41
  987. // - https://source.chromium.org/chromium/chromium/src/+/main:services/network/public/mojom/network_context.mojom;l=316-318;drc=ae5c7fcf09509843c1145f544cce3a61874b9698
  988. // - https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer
  989. const urlRequest = net.request({ url: serverUrl, referrerPolicy: 'unsafe-url' });
  990. urlRequest.setHeader('referer', referrerURL);
  991. urlRequest.end();
  992. const response = await getResponse(urlRequest);
  993. expect(response.statusCode).to.equal(200);
  994. await collectStreamBody(response);
  995. });
  996. });
  997. describe('IncomingMessage API', () => {
  998. test('response object should implement the IncomingMessage API', async () => {
  999. const customHeaderName = 'Some-Custom-Header-Name';
  1000. const customHeaderValue = 'Some-Customer-Header-Value';
  1001. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1002. response.statusCode = 200;
  1003. response.statusMessage = 'OK';
  1004. response.setHeader(customHeaderName, customHeaderValue);
  1005. response.end();
  1006. });
  1007. const urlRequest = net.request(serverUrl);
  1008. const response = await getResponse(urlRequest);
  1009. expect(response.statusCode).to.equal(200);
  1010. expect(response.statusMessage).to.equal('OK');
  1011. const headers = response.headers;
  1012. expect(headers).to.be.an('object');
  1013. const headerValue = headers[customHeaderName.toLowerCase()];
  1014. expect(headerValue).to.equal(customHeaderValue);
  1015. const rawHeaders = response.rawHeaders;
  1016. expect(rawHeaders).to.be.an('array');
  1017. expect(rawHeaders[0]).to.equal(customHeaderName);
  1018. expect(rawHeaders[1]).to.equal(customHeaderValue);
  1019. const httpVersion = response.httpVersion;
  1020. expect(httpVersion).to.be.a('string').and.to.have.lengthOf.at.least(1);
  1021. const httpVersionMajor = response.httpVersionMajor;
  1022. expect(httpVersionMajor).to.be.a('number').and.to.be.at.least(1);
  1023. const httpVersionMinor = response.httpVersionMinor;
  1024. expect(httpVersionMinor).to.be.a('number').and.to.be.at.least(0);
  1025. await collectStreamBody(response);
  1026. });
  1027. test('should discard duplicate headers', async () => {
  1028. const includedHeader = 'max-forwards';
  1029. const discardableHeader = 'Max-Forwards';
  1030. const includedHeaderValue = 'max-fwds-val';
  1031. const discardableHeaderValue = 'max-fwds-val-two';
  1032. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1033. response.statusCode = 200;
  1034. response.statusMessage = 'OK';
  1035. response.setHeader(discardableHeader, discardableHeaderValue);
  1036. response.setHeader(includedHeader, includedHeaderValue);
  1037. response.end();
  1038. });
  1039. const urlRequest = net.request(serverUrl);
  1040. const response = await getResponse(urlRequest);
  1041. expect(response.statusCode).to.equal(200);
  1042. expect(response.statusMessage).to.equal('OK');
  1043. const headers = response.headers;
  1044. expect(headers).to.be.an('object');
  1045. expect(headers).to.have.property(includedHeader);
  1046. expect(headers).to.not.have.property(discardableHeader);
  1047. expect(headers[includedHeader]).to.equal(includedHeaderValue);
  1048. await collectStreamBody(response);
  1049. });
  1050. test('should join repeated non-discardable header values with ,', async () => {
  1051. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1052. response.statusCode = 200;
  1053. response.statusMessage = 'OK';
  1054. response.setHeader('referrer-policy', ['first-text', 'second-text']);
  1055. response.end();
  1056. });
  1057. const urlRequest = net.request(serverUrl);
  1058. const response = await getResponse(urlRequest);
  1059. expect(response.statusCode).to.equal(200);
  1060. expect(response.statusMessage).to.equal('OK');
  1061. const headers = response.headers;
  1062. expect(headers).to.be.an('object');
  1063. expect(headers).to.have.property('referrer-policy');
  1064. expect(headers['referrer-policy']).to.equal('first-text, second-text');
  1065. await collectStreamBody(response);
  1066. });
  1067. test('should not join repeated discardable header values with ,', async () => {
  1068. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1069. response.statusCode = 200;
  1070. response.statusMessage = 'OK';
  1071. response.setHeader('last-modified', ['yesterday', 'today']);
  1072. response.end();
  1073. });
  1074. const urlRequest = net.request(serverUrl);
  1075. const response = await getResponse(urlRequest);
  1076. expect(response.statusCode).to.equal(200);
  1077. expect(response.statusMessage).to.equal('OK');
  1078. const headers = response.headers;
  1079. expect(headers).to.be.an('object');
  1080. expect(headers).to.have.property('last-modified');
  1081. expect(headers['last-modified']).to.equal('yesterday');
  1082. await collectStreamBody(response);
  1083. });
  1084. test('should make set-cookie header an array even if single value', async () => {
  1085. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1086. response.statusCode = 200;
  1087. response.statusMessage = 'OK';
  1088. response.setHeader('set-cookie', 'chocolate-chip');
  1089. response.end();
  1090. });
  1091. const urlRequest = net.request(serverUrl);
  1092. const response = await getResponse(urlRequest);
  1093. expect(response.statusCode).to.equal(200);
  1094. expect(response.statusMessage).to.equal('OK');
  1095. const headers = response.headers;
  1096. expect(headers).to.be.an('object');
  1097. expect(headers).to.have.property('set-cookie');
  1098. expect(headers['set-cookie']).to.be.an('array');
  1099. expect(headers['set-cookie'][0]).to.equal('chocolate-chip');
  1100. await collectStreamBody(response);
  1101. });
  1102. test('should keep set-cookie header an array when an array', async () => {
  1103. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1104. response.statusCode = 200;
  1105. response.statusMessage = 'OK';
  1106. response.setHeader('set-cookie', ['chocolate-chip', 'oatmeal']);
  1107. response.end();
  1108. });
  1109. const urlRequest = net.request(serverUrl);
  1110. const response = await getResponse(urlRequest);
  1111. expect(response.statusCode).to.equal(200);
  1112. expect(response.statusMessage).to.equal('OK');
  1113. const headers = response.headers;
  1114. expect(headers).to.be.an('object');
  1115. expect(headers).to.have.property('set-cookie');
  1116. expect(headers['set-cookie']).to.be.an('array');
  1117. expect(headers['set-cookie'][0]).to.equal('chocolate-chip');
  1118. expect(headers['set-cookie'][1]).to.equal('oatmeal');
  1119. await collectStreamBody(response);
  1120. });
  1121. test('should lowercase header keys', async () => {
  1122. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1123. response.statusCode = 200;
  1124. response.statusMessage = 'OK';
  1125. response.setHeader('HEADER-KEY', ['header-value']);
  1126. response.setHeader('SeT-CookiE', ['chocolate-chip', 'oatmeal']);
  1127. response.setHeader('rEFERREr-pOLICy', ['first-text', 'second-text']);
  1128. response.setHeader('LAST-modified', 'yesterday');
  1129. response.end();
  1130. });
  1131. const urlRequest = net.request(serverUrl);
  1132. const response = await getResponse(urlRequest);
  1133. expect(response.statusCode).to.equal(200);
  1134. expect(response.statusMessage).to.equal('OK');
  1135. const headers = response.headers;
  1136. expect(headers).to.be.an('object');
  1137. expect(headers).to.have.property('header-key');
  1138. expect(headers).to.have.property('set-cookie');
  1139. expect(headers).to.have.property('referrer-policy');
  1140. expect(headers).to.have.property('last-modified');
  1141. await collectStreamBody(response);
  1142. });
  1143. test('should return correct raw headers', async () => {
  1144. const customHeaders: [string, string|string[]][] = [
  1145. ['HEADER-KEY-ONE', 'header-value-one'],
  1146. ['set-cookie', 'chocolate-chip'],
  1147. ['header-key-two', 'header-value-two'],
  1148. ['referrer-policy', ['first-text', 'second-text']],
  1149. ['HEADER-KEY-THREE', 'header-value-three'],
  1150. ['last-modified', ['first-text', 'second-text']],
  1151. ['header-key-four', 'header-value-four']
  1152. ];
  1153. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1154. response.statusCode = 200;
  1155. response.statusMessage = 'OK';
  1156. for (const headerTuple of customHeaders) {
  1157. response.setHeader(headerTuple[0], headerTuple[1]);
  1158. }
  1159. response.end();
  1160. });
  1161. const urlRequest = net.request(serverUrl);
  1162. const response = await getResponse(urlRequest);
  1163. expect(response.statusCode).to.equal(200);
  1164. expect(response.statusMessage).to.equal('OK');
  1165. const rawHeaders = response.rawHeaders;
  1166. expect(rawHeaders).to.be.an('array');
  1167. let rawHeadersIdx = 0;
  1168. for (const headerTuple of customHeaders) {
  1169. const headerKey = headerTuple[0];
  1170. const headerValues = Array.isArray(headerTuple[1]) ? headerTuple[1] : [headerTuple[1]];
  1171. for (const headerValue of headerValues) {
  1172. expect(rawHeaders[rawHeadersIdx]).to.equal(headerKey);
  1173. expect(rawHeaders[rawHeadersIdx + 1]).to.equal(headerValue);
  1174. rawHeadersIdx += 2;
  1175. }
  1176. }
  1177. await collectStreamBody(response);
  1178. });
  1179. test('should be able to pipe a net response into a writable stream', async () => {
  1180. const bodyData = randomString(kOneKiloByte);
  1181. let nodeRequestProcessed = false;
  1182. const [netServerUrl, nodeServerUrl] = await Promise.all([
  1183. respondOnce.toSingleURL((request, response) => response.end(bodyData)),
  1184. respondOnce.toSingleURL(async (request, response) => {
  1185. const receivedBodyData = await collectStreamBody(request);
  1186. expect(receivedBodyData).to.be.equal(bodyData);
  1187. nodeRequestProcessed = true;
  1188. response.end();
  1189. })
  1190. ]);
  1191. const netRequest = net.request(netServerUrl);
  1192. const netResponse = await getResponse(netRequest);
  1193. const serverUrl = url.parse(nodeServerUrl);
  1194. const nodeOptions = {
  1195. method: 'POST',
  1196. path: serverUrl.path,
  1197. port: serverUrl.port
  1198. };
  1199. const nodeRequest = http.request(nodeOptions);
  1200. const nodeResponsePromise = once(nodeRequest, 'response');
  1201. // TODO(@MarshallOfSound) - FIXME with #22730
  1202. (netResponse as any).pipe(nodeRequest);
  1203. const [nodeResponse] = await nodeResponsePromise;
  1204. netRequest.end();
  1205. await collectStreamBody(nodeResponse);
  1206. expect(nodeRequestProcessed).to.equal(true);
  1207. });
  1208. test('should correctly throttle an incoming stream', async () => {
  1209. let numChunksSent = 0;
  1210. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1211. const data = randomString(kOneMegaByte);
  1212. const write = () => {
  1213. let ok = true;
  1214. do {
  1215. numChunksSent++;
  1216. if (numChunksSent > 30) return;
  1217. ok = response.write(data);
  1218. } while (ok);
  1219. response.once('drain', write);
  1220. };
  1221. write();
  1222. });
  1223. const urlRequest = net.request(serverUrl);
  1224. urlRequest.on('response', () => {});
  1225. urlRequest.end();
  1226. await setTimeout(2000);
  1227. // TODO(nornagon): I think this ought to max out at 20, but in practice
  1228. // it seems to exceed that sometimes. This is at 25 to avoid test flakes,
  1229. // but we should investigate if there's actually something broken here and
  1230. // if so fix it and reset this to max at 20, and if not then delete this
  1231. // comment.
  1232. expect(numChunksSent).to.be.at.most(25);
  1233. });
  1234. });
  1235. describe('net.isOnline', () => {
  1236. test('getter returns boolean', () => {
  1237. expect(net.isOnline()).to.be.a('boolean');
  1238. });
  1239. test('property returns boolean', () => {
  1240. expect(net.online).to.be.a('boolean');
  1241. });
  1242. });
  1243. describe('Stability and performance', () => {
  1244. test('should free unreferenced, never-started request objects without crash', async () => {
  1245. net.request('https://test');
  1246. await new Promise<void>((resolve) => {
  1247. process.nextTick(() => {
  1248. const v8Util = process._linkedBinding('electron_common_v8_util');
  1249. v8Util.requestGarbageCollectionForTesting();
  1250. resolve();
  1251. });
  1252. });
  1253. });
  1254. test('should collect on-going requests without crash', async () => {
  1255. let finishResponse: (() => void) | null = null;
  1256. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1257. response.write(randomString(kOneKiloByte));
  1258. finishResponse = () => {
  1259. response.write(randomString(kOneKiloByte));
  1260. response.end();
  1261. };
  1262. });
  1263. const urlRequest = net.request(serverUrl);
  1264. const response = await getResponse(urlRequest);
  1265. process.nextTick(() => {
  1266. // Trigger a garbage collection.
  1267. const v8Util = process._linkedBinding('electron_common_v8_util');
  1268. v8Util.requestGarbageCollectionForTesting();
  1269. finishResponse!();
  1270. });
  1271. await collectStreamBody(response);
  1272. });
  1273. test('should collect unreferenced, ended requests without crash', async () => {
  1274. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1275. response.end();
  1276. });
  1277. const urlRequest = net.request(serverUrl);
  1278. process.nextTick(() => {
  1279. const v8Util = process._linkedBinding('electron_common_v8_util');
  1280. v8Util.requestGarbageCollectionForTesting();
  1281. });
  1282. const response = await getResponse(urlRequest);
  1283. await collectStreamBody(response);
  1284. });
  1285. test('should finish sending data when urlRequest is unreferenced', async () => {
  1286. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1287. const received = await collectStreamBodyBuffer(request);
  1288. expect(received.length).to.equal(kOneMegaByte);
  1289. response.end();
  1290. });
  1291. const urlRequest = net.request(serverUrl);
  1292. urlRequest.on('close', () => {
  1293. process.nextTick(() => {
  1294. const v8Util = process._linkedBinding('electron_common_v8_util');
  1295. v8Util.requestGarbageCollectionForTesting();
  1296. });
  1297. });
  1298. urlRequest.write(randomBuffer(kOneMegaByte));
  1299. const response = await getResponse(urlRequest);
  1300. await collectStreamBody(response);
  1301. });
  1302. test('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
  1303. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1304. const received = await collectStreamBodyBuffer(request);
  1305. response.end();
  1306. expect(received.length).to.equal(kOneMegaByte);
  1307. });
  1308. const urlRequest = net.request(serverUrl);
  1309. urlRequest.chunkedEncoding = true;
  1310. urlRequest.write(randomBuffer(kOneMegaByte));
  1311. const response = await getResponse(urlRequest);
  1312. await collectStreamBody(response);
  1313. process.nextTick(() => {
  1314. const v8Util = process._linkedBinding('electron_common_v8_util');
  1315. v8Util.requestGarbageCollectionForTesting();
  1316. });
  1317. });
  1318. test('should finish sending data when urlRequest is unreferenced before close event for chunked encoding', async () => {
  1319. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1320. const received = await collectStreamBodyBuffer(request);
  1321. response.end();
  1322. expect(received.length).to.equal(kOneMegaByte);
  1323. });
  1324. const urlRequest = net.request(serverUrl);
  1325. urlRequest.chunkedEncoding = true;
  1326. urlRequest.write(randomBuffer(kOneMegaByte));
  1327. const v8Util = process._linkedBinding('electron_common_v8_util');
  1328. v8Util.requestGarbageCollectionForTesting();
  1329. await collectStreamBody(await getResponse(urlRequest));
  1330. });
  1331. test('should finish sending data when urlRequest is unreferenced', async () => {
  1332. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1333. const received = await collectStreamBodyBuffer(request);
  1334. response.end();
  1335. expect(received.length).to.equal(kOneMegaByte);
  1336. });
  1337. const urlRequest = net.request(serverUrl);
  1338. urlRequest.on('close', () => {
  1339. process.nextTick(() => {
  1340. const v8Util = process._linkedBinding('electron_common_v8_util');
  1341. v8Util.requestGarbageCollectionForTesting();
  1342. });
  1343. });
  1344. urlRequest.write(randomBuffer(kOneMegaByte));
  1345. await collectStreamBody(await getResponse(urlRequest));
  1346. });
  1347. test('should finish sending data when urlRequest is unreferenced for chunked encoding', async () => {
  1348. const serverUrl = await respondOnce.toSingleURL(async (request, response) => {
  1349. const received = await collectStreamBodyBuffer(request);
  1350. response.end();
  1351. expect(received.length).to.equal(kOneMegaByte);
  1352. });
  1353. const urlRequest = net.request(serverUrl);
  1354. urlRequest.on('close', () => {
  1355. process.nextTick(() => {
  1356. const v8Util = process._linkedBinding('electron_common_v8_util');
  1357. v8Util.requestGarbageCollectionForTesting();
  1358. });
  1359. });
  1360. urlRequest.chunkedEncoding = true;
  1361. urlRequest.write(randomBuffer(kOneMegaByte));
  1362. await collectStreamBody(await getResponse(urlRequest));
  1363. });
  1364. });
  1365. describe('non-http schemes', () => {
  1366. test('should be rejected by net.request', async () => {
  1367. expect(() => {
  1368. net.request('file://bar');
  1369. }).to.throw('ClientRequest only supports http: and https: protocols');
  1370. });
  1371. test('should be rejected by net.request when passed in url:', async () => {
  1372. expect(() => {
  1373. net.request({ url: 'file://bar' });
  1374. }).to.throw('ClientRequest only supports http: and https: protocols');
  1375. });
  1376. });
  1377. describe('net.fetch', () => {
  1378. // NB. there exist much more comprehensive tests for fetch() in the form of
  1379. // the WPT: https://github.com/web-platform-tests/wpt/tree/master/fetch
  1380. // It's possible to run these tests against net.fetch(), but the test
  1381. // harness to do so is quite complex and hasn't been munged to smoothly run
  1382. // inside the Electron test runner yet.
  1383. //
  1384. // In the meantime, here are some tests for basic functionality and
  1385. // Electron-specific behavior.
  1386. describe('basic', () => {
  1387. test('can fetch http urls', async () => {
  1388. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1389. response.end('test');
  1390. });
  1391. const resp = await net.fetch(serverUrl);
  1392. expect(resp.ok).to.be.true();
  1393. expect(await resp.text()).to.equal('test');
  1394. });
  1395. test('can upload a string body', async () => {
  1396. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1397. request.on('data', chunk => response.write(chunk));
  1398. request.on('end', () => response.end());
  1399. });
  1400. const resp = await net.fetch(serverUrl, {
  1401. method: 'POST',
  1402. body: 'anchovies'
  1403. });
  1404. expect(await resp.text()).to.equal('anchovies');
  1405. });
  1406. test('can read response as an array buffer', async () => {
  1407. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1408. request.on('data', chunk => response.write(chunk));
  1409. request.on('end', () => response.end());
  1410. });
  1411. const resp = await net.fetch(serverUrl, {
  1412. method: 'POST',
  1413. body: 'anchovies'
  1414. });
  1415. expect(new TextDecoder().decode(new Uint8Array(await resp.arrayBuffer()))).to.equal('anchovies');
  1416. });
  1417. test('can read response as form data', async () => {
  1418. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1419. response.setHeader('content-type', 'application/x-www-form-urlencoded');
  1420. response.end('foo=bar');
  1421. });
  1422. const resp = await net.fetch(serverUrl);
  1423. const result = await resp.formData();
  1424. expect(result.get('foo')).to.equal('bar');
  1425. });
  1426. test('should reject promise on DNS failure', async () => {
  1427. const r = net.fetch('https://i.do.not.exist');
  1428. await expect(r).to.be.rejectedWith(/ERR_NAME_NOT_RESOLVED/);
  1429. });
  1430. test('should reject body promise when stream fails', async () => {
  1431. const serverUrl = await respondOnce.toSingleURL((request, response) => {
  1432. response.write('first chunk');
  1433. setTimeout().then(() => response.destroy());
  1434. });
  1435. const r = await net.fetch(serverUrl);
  1436. expect(r.status).to.equal(200);
  1437. await expect(r.text()).to.be.rejectedWith(/ERR_INCOMPLETE_CHUNKED_ENCODING/);
  1438. });
  1439. });
  1440. });
  1441. describe('net.resolveHost', () => {
  1442. test('resolves ipv4.localhost2', async () => {
  1443. const { endpoints } = await net.resolveHost('ipv4.localhost2');
  1444. expect(endpoints).to.be.a('array');
  1445. expect(endpoints).to.have.lengthOf(1);
  1446. expect(endpoints[0].family).to.equal('ipv4');
  1447. expect(endpoints[0].address).to.equal('10.0.0.1');
  1448. });
  1449. test('fails to resolve AAAA record for ipv4.localhost2', async () => {
  1450. await expect(net.resolveHost('ipv4.localhost2', {
  1451. queryType: 'AAAA'
  1452. }))
  1453. .to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/);
  1454. });
  1455. test('resolves ipv6.localhost2', async () => {
  1456. const { endpoints } = await net.resolveHost('ipv6.localhost2');
  1457. expect(endpoints).to.be.a('array');
  1458. expect(endpoints).to.have.lengthOf(1);
  1459. expect(endpoints[0].family).to.equal('ipv6');
  1460. expect(endpoints[0].address).to.equal('::1');
  1461. });
  1462. test('fails to resolve A record for ipv6.localhost2', async () => {
  1463. await expect(net.resolveHost('notfound.localhost2', {
  1464. queryType: 'A'
  1465. }))
  1466. .to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/);
  1467. });
  1468. test('fails to resolve notfound.localhost2', async () => {
  1469. await expect(net.resolveHost('notfound.localhost2'))
  1470. .to.eventually.be.rejectedWith(/net::ERR_NAME_NOT_RESOLVED/);
  1471. });
  1472. });
  1473. }
  1474. });