Skip to content

Commit

Permalink
fix(headers): don't forward secure headers on protocol change (#1605)
Browse files Browse the repository at this point in the history
backport for #1599 to the 2.x branch

Co-authored-by: Guilherme Victal <guilherme.a@dasa.com.br>
  • Loading branch information
victal and Guilherme Victal authored Jul 19, 2022
1 parent 50536d1 commit fddad0e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
16 changes: 15 additions & 1 deletion src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,20 @@ const isDomainOrSubdomain = (destination, original) => {
);
};

/**
* isSameProtocol reports whether the two provided URLs use the same protocol.
*
* Both domains must already be in canonical form.
* @param {string|URL} original
* @param {string|URL} destination
*/
const isSameProtocol = (destination, original) => {
const orig = new URL(original).protocol;
const dest = new URL(destination).protocol;

return orig === dest;
};


/**
* Fetch function
Expand Down Expand Up @@ -214,7 +228,7 @@ export default function fetch(url, opts) {
size: request.size
};

if (!isDomainOrSubdomain(request.url, locationURL)) {
if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) {
for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) {
requestOpts.headers.delete(name);
}
Expand Down
23 changes: 23 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1677,6 +1677,29 @@ describe('node-fetch', () => {
});
});

it('should not forward secure headers to changed protocol', async () => {
const res = await fetch('https://httpbin.org/redirect-to?url=http%3A%2F%2Fhttpbin.org%2Fget&status_code=302', {
headers: new Headers({
cookie: 'gets=removed',
cookie2: 'gets=removed',
authorization: 'gets=removed',
'www-authenticate': 'gets=removed',
'other-safe-headers': 'stays',
'x-foo': 'bar'
})
});

const headers = new Headers((await res.json()).headers);
// Safe headers are not removed
expect(headers.get('other-safe-headers')).to.equal('stays');
expect(headers.get('x-foo')).to.equal('bar');
// Unsafe headers should not have been sent to downgraded http
expect(headers.get('cookie')).to.equal(null);
expect(headers.get('cookie2')).to.equal(null);
expect(headers.get('www-authenticate')).to.equal(null);
expect(headers.get('authorization')).to.equal(null);
});

it('should forward secure headers to same host', () => {
return fetch(`${base}redirect-to/302/${base}inspect`, {
headers: new Headers({
Expand Down

0 comments on commit fddad0e

Please sign in to comment.