Unverified Commit 49c99cc3 authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Fix host segment replacing for custom routes (#29090)

This fixes segments inside of the host of the destination failing to parse with url.parse due to the unexpected colon by escaping the colon for segments and then unescaping them after we have parsed the URL.

## Bug

- [x] Related issues linked using `fixes #number`
- [x] Integration tests added
- [x] Errors have helpful link attached, see `contributing.md`

x-ref: https://github.com/vercel/vercel/pull/6713
parent 7d664d5b
...@@ -125,6 +125,11 @@ export function compileNonPath(value: string, params: Params): string { ...@@ -125,6 +125,11 @@ export function compileNonPath(value: string, params: Params): string {
.substr(1) .substr(1)
} }
const escapeSegment = (str: string, segmentName: string) =>
str.replace(new RegExp(`:${segmentName}`, 'g'), `__ESC_COLON_${segmentName}`)
const unescapeSegments = (str: string) => str.replace(/__ESC_COLON_/gi, ':')
export default function prepareDestination( export default function prepareDestination(
destination: string, destination: string,
params: Params, params: Params,
...@@ -137,17 +142,29 @@ export default function prepareDestination( ...@@ -137,17 +142,29 @@ export default function prepareDestination(
delete query.__nextLocale delete query.__nextLocale
delete query.__nextDefaultLocale delete query.__nextDefaultLocale
const parsedDestination = parseUrl(destination) let escapedDestination = destination
for (const param of Object.keys({ ...params, ...query })) {
escapedDestination = escapeSegment(escapedDestination, param)
}
const parsedDestination = parseUrl(escapedDestination)
const destQuery = parsedDestination.query const destQuery = parsedDestination.query
const destPath = `${parsedDestination.pathname!}${ const destPath = unescapeSegments(
parsedDestination.hash || '' `${parsedDestination.pathname!}${parsedDestination.hash || ''}`
}` )
const destHostname = unescapeSegments(parsedDestination.hostname || '')
const destPathParamKeys: pathToRegexp.Key[] = [] const destPathParamKeys: pathToRegexp.Key[] = []
const destHostnameParamKeys: pathToRegexp.Key[] = []
pathToRegexp.pathToRegexp(destPath, destPathParamKeys) pathToRegexp.pathToRegexp(destPath, destPathParamKeys)
pathToRegexp.pathToRegexp(destHostname, destHostnameParamKeys)
const destPathParams = destPathParamKeys.map((key) => key.name) const destParams: (string | number)[] = []
let destinationCompiler = pathToRegexp.compile( destPathParamKeys.forEach((key) => destParams.push(key.name))
destHostnameParamKeys.forEach((key) => destParams.push(key.name))
const destPathCompiler = pathToRegexp.compile(
destPath, destPath,
// we don't validate while compiling the destination since we should // we don't validate while compiling the destination since we should
// have already validated before we got to this point and validating // have already validated before we got to this point and validating
...@@ -157,6 +174,9 @@ export default function prepareDestination( ...@@ -157,6 +174,9 @@ export default function prepareDestination(
// params from a separate path-regex into another // params from a separate path-regex into another
{ validate: false } { validate: false }
) )
const destHostnameCompiler = pathToRegexp.compile(destHostname, {
validate: false,
})
let newUrl let newUrl
// update any params in query values // update any params in query values
...@@ -164,9 +184,11 @@ export default function prepareDestination( ...@@ -164,9 +184,11 @@ export default function prepareDestination(
// the value needs to start with a forward-slash to be compiled // the value needs to start with a forward-slash to be compiled
// correctly // correctly
if (Array.isArray(strOrArray)) { if (Array.isArray(strOrArray)) {
destQuery[key] = strOrArray.map((value) => compileNonPath(value, params)) destQuery[key] = strOrArray.map((value) =>
compileNonPath(unescapeSegments(value), params)
)
} else { } else {
destQuery[key] = compileNonPath(strOrArray, params) destQuery[key] = compileNonPath(unescapeSegments(strOrArray), params)
} }
} }
...@@ -181,7 +203,7 @@ export default function prepareDestination( ...@@ -181,7 +203,7 @@ export default function prepareDestination(
if ( if (
appendParamsToQuery && appendParamsToQuery &&
!paramKeys.some((key) => destPathParams.includes(key)) !paramKeys.some((key) => destParams.includes(key))
) { ) {
for (const key of paramKeys) { for (const key of paramKeys) {
if (!(key in destQuery)) { if (!(key in destQuery)) {
...@@ -191,14 +213,19 @@ export default function prepareDestination( ...@@ -191,14 +213,19 @@ export default function prepareDestination(
} }
try { try {
newUrl = destinationCompiler(params) newUrl = destPathCompiler(params)
const [pathname, hash] = newUrl.split('#') const [pathname, hash] = newUrl.split('#')
parsedDestination.hostname = destHostnameCompiler(params)
parsedDestination.pathname = pathname parsedDestination.pathname = pathname
parsedDestination.hash = `${hash ? '#' : ''}${hash || ''}` parsedDestination.hash = `${hash ? '#' : ''}${hash || ''}`
delete (parsedDestination as any).search delete (parsedDestination as any).search
} catch (err) { } catch (err) {
if (err.message.match(/Expected .*? to not repeat, but got an array/)) { if (
(err as Error).message.match(
/Expected .*? to not repeat, but got an array/
)
) {
throw new Error( throw new Error(
`To use a multi-match in the destination you must add \`*\` at the end of the param name to signify it should repeat. https://nextjs.org/docs/messages/invalid-multi-match` `To use a multi-match in the destination you must add \`*\` at the end of the param name to signify it should repeat. https://nextjs.org/docs/messages/invalid-multi-match`
) )
......
...@@ -389,6 +389,17 @@ module.exports = { ...@@ -389,6 +389,17 @@ module.exports = {
destination: '/somewhere', destination: '/somewhere',
permanent: false, permanent: false,
}, },
{
source: '/has-redirect-6',
has: [
{
type: 'host',
value: '(?<subdomain>.*)-test.example.com',
},
],
destination: 'https://:subdomain.example.com/some-path/end?a=b',
permanent: false,
},
] ]
}, },
......
...@@ -1028,6 +1028,30 @@ const runTests = (isDev = false) => { ...@@ -1028,6 +1028,30 @@ const runTests = (isDev = false) => {
}) })
}) })
it('should match has host redirect and insert in destination correctly', async () => {
const res1 = await fetchViaHTTP(appPort, '/has-redirect-6', undefined, {
redirect: 'manual',
})
expect(res1.status).toBe(404)
const res = await fetchViaHTTP(appPort, '/has-redirect-6', undefined, {
headers: {
host: 'hello-test.example.com',
},
redirect: 'manual',
})
expect(res.status).toBe(307)
const parsed = url.parse(res.headers.get('location'), true)
expect(parsed.protocol).toBe('https:')
expect(parsed.hostname).toBe('hello.example.com')
expect(parsed.pathname).toBe('/some-path/end')
expect(parsed.query).toEqual({
a: 'b',
})
})
it('should match has header for header correctly', async () => { it('should match has header for header correctly', async () => {
const res = await fetchViaHTTP(appPort, '/has-header-1', undefined, { const res = await fetchViaHTTP(appPort, '/has-header-1', undefined, {
headers: { headers: {
...@@ -1360,6 +1384,18 @@ const runTests = (isDev = false) => { ...@@ -1360,6 +1384,18 @@ const runTests = (isDev = false) => {
source: '/:path/has-redirect-5', source: '/:path/has-redirect-5',
statusCode: 307, statusCode: 307,
}, },
{
destination: 'https://:subdomain.example.com/some-path/end?a=b',
has: [
{
type: 'host',
value: '(?<subdomain>.*)-test.example.com',
},
],
regex: normalizeRegEx('^(?!\\/_next)\\/has-redirect-6(?:\\/)?$'),
source: '/has-redirect-6',
statusCode: 307,
},
], ],
headers: [ headers: [
{ {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment