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: TypeError crashes program in case of invalid url in redirect #59

Closed
wants to merge 2 commits into from
Closed
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
15 changes: 13 additions & 2 deletions lib/index.js
Expand Up @@ -143,8 +143,19 @@ const fetch = async (url, opts) => {
const location = headers.get('Location')

// HTTP fetch step 5.3
const locationURL = location === null ? null
: (new URL(location, request.url)).toString()
let locationURL = null;
try {
locationURL = location === null ? null : new URL(location, request.url).toString();
} catch {
// error here can only be invalid URL in Location: header
// do not throw when options.redirect == manual
// let the user extract the errorneous redirect URL
if (request.redirect !== 'manual') {
reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect'));
finalize();
return;
}
}

// HTTP fetch step 5.5
if (request.redirect === 'error') {
Expand Down
6 changes: 6 additions & 0 deletions test/fixtures/server.js
Expand Up @@ -223,6 +223,12 @@ 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
23 changes: 23 additions & 0 deletions test/index.js
Expand Up @@ -379,6 +379,29 @@ t.test('treat broken redirect as ordinary response (manual)', t => {
})
})

t.test('should process an invalid redirect (manual)', t => {
const url = `${base}redirect/301/invalid`
const options = {
redirect: 'manual',
}
return fetch(url, options).then(res => {
t.equal(res.url, url)
t.equal(res.status, 301)
t.equal(res.headers.get('location'), '//super:invalid:url%/')
})
})

t.test('should throw an error on invalid redirect url', t => {
const url = `${base}redirect/301/invalid`
return fetch(url).then(res => {
t.fail()
}).catch((err) => {
t.type(err, FetchError)
t.equal(err.message, 'uri requested responds with an invalid redirect URL: //super:invalid:url%/')
})
})


t.test('set redirected property on response when redirect', t =>
fetch(`${base}redirect/301`).then(res => t.equal(res.redirected, true)))

Expand Down