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(Redirect): Better handle wrong redirect header in a response #1387

Merged
merged 8 commits into from Nov 26, 2021
Merged
Show file tree
Hide file tree
Changes from 4 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
2 changes: 2 additions & 0 deletions docs/CHANGELOG.md
Expand Up @@ -4,6 +4,8 @@ All notable changes will be recorded here.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

* fix(request): fix crash when an invalid redirection URL is encountered https://github.com/node-fetch/node-fetch/pull/1387

## 3.1.0

## What's Changed
Expand Down
10 changes: 9 additions & 1 deletion src/index.js
Expand Up @@ -130,7 +130,15 @@ export default async function fetch(url, options_) {
const location = headers.get('Location');

// HTTP fetch step 5.3
const locationURL = location === null ? null : new URL(location, request.url);
let locationURL;
try {
locationURL = location === null ? null : new URL(location, request.url);
} catch (error) {
// error can only be invalid URL
reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));
jimmywarting marked this conversation as resolved.
Show resolved Hide resolved
finalize();
return;
}

// HTTP fetch step 5.5
switch (request.redirect) {
Expand Down
10 changes: 10 additions & 0 deletions test/main.js
Expand Up @@ -527,6 +527,16 @@ describe('node-fetch', () => {
});
});

it('should throw an error an invalid redirect url', () => {
const url = `${base}redirect/301/invalid`;
return fetch(url).then(() => {
expect.fail();
}, error => {
expect(error).to.be.an.instanceof(FetchError);
expect(error.message).to.equal('uri requested responds with an invalid redirect URL: //super:invalid:url%/');
});
});

it('should throw a TypeError on an invalid redirect option', () => {
const url = `${base}redirect/301`;
const options = {
Expand Down
6 changes: 6 additions & 0 deletions test/utils/server.js
Expand Up @@ -239,6 +239,12 @@ export default class TestServer {
res.end();
}

if (p === '/redirect/301/invalid') {
res.statusCode = 301;
res.setHeader('Location', '//super:invalid:url%/');
res.end();
}

if (p === '/redirect/302') {
res.statusCode = 302;
res.setHeader('Location', '/inspect');
Expand Down