From 52de13bbdcd94db58ffcf39f87293af9249594c1 Mon Sep 17 00:00:00 2001 From: Szymon Marczak <36894700+szmarczak@users.noreply.github.com> Date: Thu, 17 Sep 2020 02:41:34 +0200 Subject: [PATCH] Do not ignore userinfo on a redirect to the same origin Fixes #1351 --- source/core/index.ts | 18 +++++++++--------- test/redirects.ts | 16 ++++++++++++++++ 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/source/core/index.ts b/source/core/index.ts index d440eaef1..9b145f48d 100644 --- a/source/core/index.ts +++ b/source/core/index.ts @@ -1631,6 +1631,10 @@ export default class Request extends Duplex implements RequestEvents { } if (options.url) { + if ('port' in options) { + delete options.port; + } + // Make it possible to change `options.prefixUrl` let {prefixUrl} = options; Object.defineProperty(options, 'prefixUrl', { @@ -2088,16 +2092,12 @@ export default class Request extends Duplex implements RequestEvents { } if (options.username || options.password) { - // TODO: Fix this ignore. - // @ts-expect-error - delete options.username; - // @ts-expect-error - delete options.password; - } - - if ('port' in options) { - delete options.port; + options.username = ''; + options.password = ''; } + } else { + redirectUrl.username = options.username; + redirectUrl.password = options.password; } this.redirects.push(redirectString); diff --git a/test/redirects.ts b/test/redirects.ts index c57bf17cf..93b505cba 100644 --- a/test/redirects.ts +++ b/test/redirects.ts @@ -440,6 +440,22 @@ test('clears the authorization header when redirecting to a different hostname', t.is(headers.Authorization, undefined); }); +test('preserves userinfo on redirect to the same origin', withServer, async (t, server) => { + server.get('/redirect', (_request, response) => { + response.writeHead(303, { + location: `http://localhost:${server.port}/` + }); + response.end(); + }); + + server.get('/', (request, response) => { + t.is(request.headers.authorization, 'Basic aGVsbG86d29ybGQ='); + response.end(); + }); + + await got(`http://hello:world@localhost:${server.port}/redirect`); +}); + test('clears the host header when redirecting to a different hostname', async t => { nock('https://testweb.com').get('/redirect').reply(302, undefined, {location: 'https://webtest.com/'}); nock('https://webtest.com').get('/').reply(function (_uri, _body) {