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: improper handling of relative location header #1523

Merged
merged 2 commits into from Jul 4, 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
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
}