Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(headers): don't forward secure headers on protocol change #1605

Merged
merged 1 commit into from Jul 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
16 changes: 15 additions & 1 deletion src/index.js
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
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