Commit 6c103ef5 authored by JJ Kasper's avatar JJ Kasper Committed by Joe Haddad

Add checking of custom routes for invalid fields (#9434)

* Add checking of custom routes for invalid fields

* Remove un-used test imports

* Mentioned statusCode can be undefined in error message

* Update test

* Update invalid routes output

* Add checking to make sure source/destination start with slash

* Update import
parent 551daaf1
......@@ -55,6 +55,7 @@ import {
} from './utils'
import getBaseWebpackConfig from './webpack-config'
import { writeBuildId } from './write-build-id'
import checkCustomRoutes from '../lib/check-custom-routes'
const fsAccess = promisify(fs.access)
const fsUnlink = promisify(fs.unlink)
......@@ -102,9 +103,11 @@ export default async function build(dir: string, conf = null): Promise<void> {
if (typeof config.experimental.redirects === 'function') {
redirects.push(...(await config.experimental.redirects()))
checkCustomRoutes(redirects, 'redirect')
}
if (typeof config.experimental.rewrites === 'function') {
rewrites.push(...(await config.experimental.rewrites()))
checkCustomRoutes(rewrites, 'rewrite')
}
if (ciEnvironment.isCI) {
......
......@@ -11,7 +11,7 @@ import prettyBytes from '../lib/pretty-bytes'
import { recursiveReadDir } from '../lib/recursive-readdir'
import { getRouteMatcher, getRouteRegex } from '../next-server/lib/router/utils'
import { isDynamicRoute } from '../next-server/lib/router/utils/is-dynamic'
import { Redirect, Rewrite } from '../next-server/server/next-server'
import { Redirect, Rewrite } from '../lib/check-custom-routes'
import { DEFAULT_REDIRECT_STATUS } from '../next-server/lib/constants'
const fsStatPromise = promisify(fs.stat)
......
export type Rewrite = {
source: string
destination: string
}
export type Redirect = Rewrite & {
statusCode?: number
}
const allowedStatusCodes = new Set([301, 302, 303, 307, 308])
export default function checkCustomRoutes(
routes: Array<Rewrite | Redirect>,
type: 'redirect' | 'rewrite'
): void {
let numInvalidRoutes = 0
let hadInvalidStatus = false
const isRedirect = type === 'redirect'
const allowedKeys = new Set([
'source',
'destination',
...(isRedirect ? ['statusCode'] : []),
])
for (const route of routes) {
const keys = Object.keys(route)
const invalidKeys = keys.filter(key => !allowedKeys.has(key))
const invalidParts = []
// TODO: investigate allowing RegExp directly
if (!route.source) {
invalidParts.push('`source` is missing')
} else if (typeof route.source !== 'string') {
invalidParts.push('`source` is not a string')
} else if (!route.source.startsWith('/')) {
invalidParts.push('`source` does not start with /')
}
if (!route.destination) {
invalidParts.push('`destination` is missing')
} else if (typeof route.destination !== 'string') {
invalidParts.push('`destination` is not a string')
} else if (!route.destination.startsWith('/')) {
invalidParts.push('`destination` does not start with /')
}
if (isRedirect) {
const redirRoute = route as Redirect
if (
redirRoute.statusCode &&
!allowedStatusCodes.has(redirRoute.statusCode)
) {
hadInvalidStatus = true
invalidParts.push(`\`statusCode\` is not undefined or valid statusCode`)
}
}
const hasInvalidKeys = invalidKeys.length > 0
const hasInvalidParts = invalidParts.length > 0
if (hasInvalidKeys || hasInvalidParts) {
console.error(
`${invalidParts.join(', ')}${
invalidKeys.length
? (hasInvalidParts ? ',' : '') +
` invalid field${invalidKeys.length === 1 ? '' : 's'}: ` +
invalidKeys.join(',')
: ''
} for route ${JSON.stringify(route)}`
)
numInvalidRoutes++
}
}
if (numInvalidRoutes > 0) {
if (hadInvalidStatus) {
console.error(
`\nValid redirect statusCode values are ${[...allowedStatusCodes].join(
', '
)}`
)
}
console.error()
throw new Error(`Invalid ${type}${numInvalidRoutes === 1 ? '' : 's'} found`)
}
}
......@@ -39,20 +39,12 @@ import { sendHTML } from './send-html'
import { serveStatic } from './serve-static'
import { getSprCache, initializeSprCache, setSprCache } from './spr-cache'
import { isBlockedPage } from './utils'
import { Redirect, Rewrite } from '../../lib/check-custom-routes'
const getCustomRouteMatcher = pathMatch(true)
type NextConfig = any
export type Rewrite = {
source: string
destination: string
}
export type Redirect = Rewrite & {
statusCode?: number
}
type Middleware = (
req: IncomingMessage,
res: ServerResponse,
......
......@@ -27,6 +27,7 @@ import { Telemetry } from '../telemetry/storage'
import ErrorDebug from './error-debug'
import HotReloader from './hot-reloader'
import { findPageFile } from './lib/find-page-file'
import checkCustomRoutes from '../lib/check-custom-routes'
if (typeof React.Suspense === 'undefined') {
throw new Error(
......@@ -316,9 +317,11 @@ export default class DevServer extends Server {
if (typeof redirects === 'function') {
result.redirects = await redirects()
checkCustomRoutes(result.redirects, 'redirect')
}
if (typeof rewrites === 'function') {
result.rewrites = await rewrites()
checkCustomRoutes(result.rewrites, 'rewrite')
}
this.customRoutes = result
}
......
/* eslint-env jest */
/* global jasmine */
import fs from 'fs-extra'
import { join } from 'path'
import { launchApp, findPort, nextBuild } from 'next-test-utils'
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000 * 60 * 2
let appDir = join(__dirname, '..')
const nextConfigPath = join(appDir, 'next.config.js')
const writeConfig = async (routes = [], type = 'redirects') => {
await fs.writeFile(
nextConfigPath,
`
module.exports = {
experimental: {
async ${type}() {
return ${JSON.stringify(routes)}
}
}
}
`
)
}
const invalidRedirects = [
{
// missing destination
source: '/hello',
},
{
// invalid source
source: 123,
destination: '/another',
},
{
// invalid statusCode type
source: '/hello',
destination: '/another',
statusCode: '301',
},
{
// invalid statusCode
source: '/hello',
destination: '/another',
statusCode: 404,
},
]
const invalidRedirectAssertions = (stderr = '') => {
expect(stderr).toContain(
`\`destination\` is missing for route {"source":"/hello"}`
)
expect(stderr).toContain(
`\`source\` is not a string for route {"source":123,"destination":"/another"}`
)
expect(stderr).toContain(
`\`statusCode\` is not undefined or valid statusCode for route {"source":"/hello","destination":"/another","statusCode":"301"}`
)
expect(stderr).toContain(
`\`statusCode\` is not undefined or valid statusCode for route {"source":"/hello","destination":"/another","statusCode":404}`
)
expect(stderr).toContain(
'Valid redirect statusCode values are 301, 302, 303, 307, 308'
)
expect(stderr).toContain('Invalid redirects found')
}
const invalidRewrites = [
{
// missing destination
source: '/hello',
},
{
// invalid source
source: 123,
destination: '/another',
},
{
// extra field
source: '/hello',
destination: '/another',
headers: 'not-allowed',
},
{
// missing forward slash in source
source: 'hello',
destination: '/another',
},
{
// missing forward slash in destination
source: '/hello',
destination: 'another',
},
]
const invalidRewriteAssertions = (stderr = '') => {
expect(stderr).toContain(
`\`destination\` is missing for route {"source":"/hello"}`
)
expect(stderr).toContain(
`\`source\` is not a string for route {"source":123,"destination":"/another"}`
)
expect(stderr).toContain(
`invalid field: headers for route {"source":"/hello","destination":"/another","headers":"not-allowed"}`
)
expect(stderr).toContain(
`\`source\` does not start with / for route {"source":"hello","destination":"/another"}`
)
expect(stderr).toContain(
`\`destination\` does not start with / for route {"source":"/hello","destination":"another"}`
)
expect(stderr).not.toContain(
'Valid redirect statusCode values are 301, 302, 303, 307, 308'
)
expect(stderr).toContain('Invalid rewrites found')
}
describe('Errors on invalid custom routes', () => {
afterAll(() => fs.remove(nextConfigPath))
it('should error during next build for invalid redirects', async () => {
await writeConfig(invalidRedirects, 'redirects')
const { stderr } = await nextBuild(appDir, undefined, { stderr: true })
invalidRedirectAssertions(stderr)
})
it('should error during next build for invalid rewrites', async () => {
await writeConfig(invalidRewrites, 'rewrites')
const { stderr } = await nextBuild(appDir, undefined, { stderr: true })
invalidRewriteAssertions(stderr)
})
it('should error during next dev for invalid redirects', async () => {
await writeConfig(invalidRedirects, 'redirects')
let stderr = ''
await launchApp(appDir, await findPort(), {
onStderr: msg => {
stderr += msg
},
})
invalidRedirectAssertions(stderr)
})
it('should error during next dev for invalid rewrites', async () => {
await writeConfig(invalidRewrites, 'rewrites')
let stderr = ''
await launchApp(appDir, await findPort(), {
onStderr: msg => {
stderr += msg
},
})
invalidRewriteAssertions(stderr)
})
})
......@@ -137,11 +137,15 @@ export function runNextCommandDev(argv, stdOut, opts = {}) {
return new Promise((resolve, reject) => {
const instance = spawn('node', ['dist/bin/next', ...argv], { cwd, env })
let didResolve = false
function handleStdout(data) {
const message = data.toString()
if (/ready on/i.test(message)) {
resolve(stdOut ? message : instance)
if (!didResolve) {
didResolve = true
resolve(stdOut ? message : instance)
}
}
if (typeof opts.onStdout === 'function') {
opts.onStdout(message)
......@@ -163,6 +167,10 @@ export function runNextCommandDev(argv, stdOut, opts = {}) {
instance.on('close', () => {
instance.stdout.removeListener('data', handleStdout)
instance.stderr.removeListener('data', handleStderr)
if (!didResolve) {
didResolve = true
resolve()
}
})
instance.on('error', err => {
......
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