Skip to content

Commit

Permalink
fix: encode URIs before setting them as Location header (#58)
Browse files Browse the repository at this point in the history
  • Loading branch information
derz authored Apr 16, 2020
1 parent 4001371 commit a796553
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 3 deletions.
2 changes: 1 addition & 1 deletion lib/middleware.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ module.exports = function (options) {
const toUrl = decodedBaseUrl.replace(foundRule.from, toTarget)

try {
res.setHeader('Location', toUrl)
res.setHeader('Location', encodeURI(toUrl))
} catch (error) {
// Not passing the error as it's caused by URL that was user-provided so we
// can't do anything about the error.
Expand Down
2 changes: 2 additions & 0 deletions test/fixture/redirects.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
module.exports = [
{ from: '^/redirected', to: '/' },
{ from: /^\/äßU</, to: '/' },
{ from: '^/äöü$', to: '/äßU<' },
{ from: '^/many/(.*)$', to: '/posts/abcde' },
{ from: '^/mapped/(.*)$', to: '/posts/$1' },
{ from: '^/function$', to: () => '/' },
Expand All @@ -17,6 +18,7 @@ module.exports = [
setTimeout(() => resolve(`/posts/${param}`), 2000)
})
},
{ from: '^/errorInTo$', to: '/mapped/\uD800ab\u0001/' },
{
from: '^/errorInToFunction$',
to: () => Promise.reject(new Error('forced error'))
Expand Down
14 changes: 12 additions & 2 deletions test/module.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,19 @@ const testSuite = () => {
expect(html).toContain('Works!')
})

test('redirect error with control character', async () => {
test('non-ascii redirect to another non-ascii url', async () => {
const html = await get('/äöü')
expect(html).toContain('Works!')
})

test('redirect with control character', async () => {
const html = await get(encodeURI('/mapped/ab\u0001'))
expect(html).toContain('ab')
})

test('redirect error due to malformatted target url', async () => {
const requestOptions = {
uri: url(encodeURI('/mapped/ab\u0001')),
uri: url('/errorInTo'),
resolveWithFullResponse: true
}

Expand Down

1 comment on commit a796553

@derz
Copy link
Contributor Author

@derz derz commented on a796553 Oct 27, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@manniL any chance you could update the npm package?

Please sign in to comment.