Skip to content

Commit

Permalink
fix: improper handling of relative location header (#1523)
Browse files Browse the repository at this point in the history
  • Loading branch information
Hazel committed Jul 4, 2022
1 parent 57e2434 commit 42c43f2
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/handler/redirect.js
Expand Up @@ -99,7 +99,7 @@ class RedirectHandler {
return this.handler.onHeaders(statusCode, headers, resume, statusText)
}

const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin))
const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin)))
const path = search ? `${pathname}${search}` : pathname

// Remove headers referring to the original URL.
Expand Down
22 changes: 22 additions & 0 deletions test/redirect-relative.js
@@ -0,0 +1,22 @@
'use strict'

const t = require('tap')
const { request } = require('..')
const {
startRedirectingWithRelativePath
} = require('./utils/redirecting-servers')

t.test('should redirect to relative URL according to RFC 7231', async t => {
t.plan(2)

const server = await startRedirectingWithRelativePath(t)

const { statusCode, body } = await request(`http://${server}`, {
maxRedirections: 3
})

const finalPath = await body.text()

t.equal(statusCode, 200)
t.equal(finalPath, '/absolute/b')
})
24 changes: 23 additions & 1 deletion test/utils/redirecting-servers.js
Expand Up @@ -178,11 +178,33 @@ async function startRedirectingWithAuthorization (t, authorization) {
return [server1, server2]
}

async function startRedirectingWithRelativePath (t) {
const server = await startServer(t, (req, res) => {
res.setHeader('Connection', 'close')

if (req.url === '/') {
res.statusCode = 301
res.setHeader('Location', '/absolute/a')
res.end('')
} else if (req.url === '/absolute/a') {
res.statusCode = 301
res.setHeader('Location', 'b')
res.end('')
} else {
res.statusCode = 200
res.end(req.url)
}
})

return server
}

module.exports = {
startServer,
startRedirectingServer,
startRedirectingWithBodyServer,
startRedirectingWithoutLocationServer,
startRedirectingChainServers,
startRedirectingWithAuthorization
startRedirectingWithAuthorization,
startRedirectingWithRelativePath
}

0 comments on commit 42c43f2

Please sign in to comment.