Unverified Commit 2effca8e authored by JJ Kasper's avatar JJ Kasper Committed by GitHub

Fix redirect query handling for param like values (#17448)

This makes sure to compile query values for rewrites/redirects as non-path items to prevent param like values e.g. `https://` from causing the destination to fail to compile. 

Fixes: https://github.com/vercel/next.js/issues/17440 
x-ref: https://github.com/vercel/next.js/issues/18670
parent 3f4872aa
......@@ -5,6 +5,43 @@ import * as pathToRegexp from 'next/dist/compiled/path-to-regexp'
type Params = { [param: string]: any }
export function compileNonPath(value: string, params: Params): string {
if (!value.includes(':')) {
return value
}
for (const key of Object.keys(params)) {
if (value.includes(`:${key}`)) {
value = value
.replace(
new RegExp(`:${key}\\*`, 'g'),
`:${key}--ESCAPED_PARAM_ASTERISKS`
)
.replace(
new RegExp(`:${key}\\?`, 'g'),
`:${key}--ESCAPED_PARAM_QUESTION`
)
.replace(new RegExp(`:${key}\\+`, 'g'), `:${key}--ESCAPED_PARAM_PLUS`)
.replace(
new RegExp(`:${key}(?!\\w)`, 'g'),
`--ESCAPED_PARAM_COLON${key}`
)
}
}
value = value
.replace(/(:|\*|\?|\+|\(|\)|\{|\})/g, '\\$1')
.replace(/--ESCAPED_PARAM_PLUS/g, '+')
.replace(/--ESCAPED_PARAM_COLON/g, ':')
.replace(/--ESCAPED_PARAM_QUESTION/g, '?')
.replace(/--ESCAPED_PARAM_ASTERISKS/g, '*')
// the value needs to start with a forward-slash to be compiled
// correctly
return pathToRegexp
.compile(`/${value}`, { validate: false })(params)
.substr(1)
}
export default function prepareDestination(
destination: string,
params: Params,
......@@ -76,9 +113,7 @@ export default function prepareDestination(
if (value) {
// the value needs to start with a forward-slash to be compiled
// correctly
value = `/${value}`
const queryCompiler = pathToRegexp.compile(value, { validate: false })
value = queryCompiler(params).substr(1)
value = compileNonPath(value, params)
}
destQuery[key] = value
}
......
......@@ -62,13 +62,14 @@ import Router, {
route,
Route,
} from './router'
import prepareDestination from '../lib/router/utils/prepare-destination'
import prepareDestination, {
compileNonPath,
} from '../lib/router/utils/prepare-destination'
import { sendPayload } from './send-payload'
import { serveStatic } from './serve-static'
import { IncrementalCache } from './incremental-cache'
import { execOnce } from '../lib/utils'
import { isBlockedPage } from './utils'
import { compile as compilePathToRegex } from 'next/dist/compiled/path-to-regexp'
import { loadEnvConfig } from '@next/env'
import './node-polyfill-fetch'
import { PagesManifest } from '../../build/webpack/plugins/pages-manifest-plugin'
......@@ -298,6 +299,7 @@ export default class Server {
if (typeof parsedUrl.query === 'string') {
parsedUrl.query = parseQs(parsedUrl.query)
}
;(req as any).__NEXT_INIT_QUERY = Object.assign({}, parsedUrl.query)
const { basePath, i18n } = this.nextConfig
......@@ -652,46 +654,6 @@ export default class Server {
fn: async (_req, _res, _params, _parsedUrl) => ({ finished: false }),
} as Route & Rewrite & Header)
const updateHeaderValue = (value: string, params: Params): string => {
if (!value.includes(':')) {
return value
}
for (const key of Object.keys(params)) {
if (value.includes(`:${key}`)) {
value = value
.replace(
new RegExp(`:${key}\\*`, 'g'),
`:${key}--ESCAPED_PARAM_ASTERISKS`
)
.replace(
new RegExp(`:${key}\\?`, 'g'),
`:${key}--ESCAPED_PARAM_QUESTION`
)
.replace(
new RegExp(`:${key}\\+`, 'g'),
`:${key}--ESCAPED_PARAM_PLUS`
)
.replace(
new RegExp(`:${key}(?!\\w)`, 'g'),
`--ESCAPED_PARAM_COLON${key}`
)
}
}
value = value
.replace(/(:|\*|\?|\+|\(|\)|\{|\})/g, '\\$1')
.replace(/--ESCAPED_PARAM_PLUS/g, '+')
.replace(/--ESCAPED_PARAM_COLON/g, ':')
.replace(/--ESCAPED_PARAM_QUESTION/g, '?')
.replace(/--ESCAPED_PARAM_ASTERISKS/g, '*')
// the value needs to start with a forward-slash to be compiled
// correctly
return compilePathToRegex(`/${value}`, { validate: false })(
params
).substr(1)
}
// Headers come very first
const headers = this.customRoutes.headers.map((r) => {
const headerRoute = getCustomRoute(r, 'header')
......@@ -705,8 +667,8 @@ export default class Server {
for (const header of (headerRoute as Header).headers) {
let { key, value } = header
if (hasParams) {
key = updateHeaderValue(key, params)
value = updateHeaderValue(value, params)
key = compileNonPath(key, params)
value = compileNonPath(value, params)
}
res.setHeader(key, value)
}
......@@ -715,6 +677,22 @@ export default class Server {
} as Route
})
// since initial query values are decoded by querystring.parse
// we need to re-encode them here but still allow passing through
// values from rewrites/redirects
const stringifyQuery = (req: IncomingMessage, query: ParsedUrlQuery) => {
const initialQueryValues = Object.values((req as any).__NEXT_INIT_QUERY)
return stringifyQs(query, undefined, undefined, {
encodeURIComponent(value) {
if (initialQueryValues.some((val) => val === value)) {
return encodeURIComponent(value)
}
return value
},
})
}
const redirects = this.customRoutes.redirects.map((redirect) => {
const redirectRoute = getCustomRoute(redirect, 'redirect')
return {
......@@ -722,7 +700,7 @@ export default class Server {
match: redirectRoute.match,
statusCode: redirectRoute.statusCode,
name: `Redirect route`,
fn: async (_req, res, params, parsedUrl) => {
fn: async (req, res, params, parsedUrl) => {
const { parsedDestination } = prepareDestination(
redirectRoute.destination,
params,
......@@ -734,7 +712,7 @@ export default class Server {
const { query } = parsedDestination
delete (parsedDestination as any).query
parsedDestination.search = stringifyQs(query)
parsedDestination.search = stringifyQuery(req, query)
const updatedDestination = formatUrl(parsedDestination)
......@@ -776,7 +754,7 @@ export default class Server {
if (parsedDestination.protocol) {
const { query } = parsedDestination
delete (parsedDestination as any).query
parsedDestination.search = stringifyQs(query)
parsedDestination.search = stringifyQuery(req, query)
const target = formatUrl(parsedDestination)
const proxy = new Proxy({
......
......@@ -205,6 +205,18 @@ module.exports = {
destination: '/somewhere',
permanent: false,
},
{
source: '/to-external-with-query',
destination:
'https://authserver.example.com/set-password?returnUrl=https%3A%2F%2Fwww.example.com/login',
permanent: false,
},
{
source: '/to-external-with-query-2',
destination:
'https://authserver.example.com/set-password?returnUrl=https://www.example.com/login',
permanent: false,
},
]
},
......
......@@ -270,7 +270,8 @@ const runTests = (isDev = false) => {
expect(res.status).toBe(307)
expect(pathname).toBe('/with-params')
expect(query).toEqual({
first: 'hello%20world%3Fw%3D24%26focalpoint%3Dcenter',
// this should be decoded since url.parse decodes query values
first: 'hello world?w=24&focalpoint=center',
second: 'world',
a: 'b',
})
......@@ -583,6 +584,38 @@ const runTests = (isDev = false) => {
expect(pathname).toBe('/integrations/-some/thing')
})
it('should redirect with URL in query correctly', async () => {
const res = await fetchViaHTTP(
appPort,
'/to-external-with-query',
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(307)
expect(res.headers.get('location')).toBe(
'https://authserver.example.com/set-password?returnUrl=https://www.example.com/login'
)
})
it('should redirect with URL in query correctly non-encoded', async () => {
const res = await fetchViaHTTP(
appPort,
'/to-external-with-query',
undefined,
{
redirect: 'manual',
}
)
expect(res.status).toBe(307)
expect(res.headers.get('location')).toBe(
'https://authserver.example.com/set-password?returnUrl=https://www.example.com/login'
)
})
if (!isDev) {
it('should output routes-manifest successfully', async () => {
const manifest = await fs.readJSON(
......@@ -736,6 +769,20 @@ const runTests = (isDev = false) => {
source: '/catchall-redirect/:path*',
statusCode: 307,
},
{
destination:
'https://authserver.example.com/set-password?returnUrl=https%3A%2F%2Fwww.example.com/login',
regex: normalizeRegEx('^\\/to-external-with-query$'),
source: '/to-external-with-query',
statusCode: 307,
},
{
destination:
'https://authserver.example.com/set-password?returnUrl=https://www.example.com/login',
regex: normalizeRegEx('^\\/to-external-with-query-2$'),
source: '/to-external-with-query-2',
statusCode: 307,
},
],
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