Unverified Commit 90bbac44 authored by Damien Simonin Feugas's avatar Damien Simonin Feugas Committed by GitHub

fix(edge): error handling for edge route and middleware is inconsistent (#38401)

## What’s in there?

This PR brings more consistency in how errors and warnings are reported when running code in the Edge Runtime:

- Dynamic code evaluation (`eval()`, `new Function()`, `WebAssembly.instantiate()`, `WebAssembly.compile()`…)
- Usage of Node.js global APIs (`BroadcastChannel`, `Buffer`, `TextDecoderStream`, `setImmediate()`...)
- Usage of Node.js modules (`fs`, `path`, `child_process`…)

The new error messages should mention *Edge Runtime* instead of *Middleware*, so they are valid in both cases.

It also fixes a bug where the process polyfill would issue a warning for  `process.cwd` (which is `undefined` but legit). Now, one has to invoke the function `process.cwd()` to trigger the error.

It finally fixes the react-dev-overlay, where links from middleware and Edge API route files could not be opened because of the `(middleware)/` prefix in their name.

About the later, please note that we can’t easily remove the prefix or change it for Edge API routes. It comes from the Webpack layer, which is the same for both. We may consider renaming it to *edge* instead in the future.

## How to test?

These changes are almost fully covered with tests:

```bash
pnpm testheadless --testPathPattern runtime-dynamic
pnpm testheadless --testPathPattern runtime-with-node
pnpm testheadless --testPathPattern runtime-module
pnpm testheadless --testPathPattern middleware-dev-errors
```

To try them out manually, you can write a middleware and Edge route files like these:

```jsx
// middleware.js
import { NextResponse } from 'next/server'
import { basename } from 'path'

export default async function middleware() {
  eval('2+2')
  setImmediate(() => {})
  basename()
  return NextResponse.next()
}

export const config = { matcher: '/' }
```

```jsx
// pages/api/route.js
import { basename } from 'path'

export default async function handle() {
  eval('2+2')
  setImmediate(() => {})
  basename()
  return Response.json({ ok: true })
}

export const config = { runtime: 'experimental-edge' }
```

The expected behaviours are:

- [x] dev, middleware/edge route is using a node.js module: error at runtime (logs + read-dev-overlay):

```bash
error - (middleware)/pages/api/route.js (1:0) @ Object.handle [as handler]
error - The edge runtime does not support Node.js 'path' module.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime
> 1 | import { basename } from "path";
  2 | export default async function handle() {
```

- [x] build, middleware/edge route is using a node.js module: warning but succeeds

```bash
warn  - Compiled with warnings

./middleware.js
A Node.js module is loaded ('path' at line 4) which is not supported in the Edge Runtime.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime

./pages/api/route.js
A Node.js module is loaded ('path' at line 1) which is not supported in the Edge Runtime.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime
```

- [x] production, middleware/edge route is using a node.js module: error at runtime (logs + 500 error)

```bash
Error: The edge runtime does not support Node.js 'path' module.
Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime
    at <unknown> (file:///Users/damien/dev/next.js/packages/next/server/web/sandbox/context.ts:149)
```

- [x] dev, middleware/edge route is using a node.js global API: error at runtime (logs + read-dev-overlay):

```bash
error - (middleware)/pages/api/route.js (4:2) @ Object.handle [as handler]
error - A Node.js API is used (setImmediate) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime
  2 |
  3 | export default async function handle() {
> 4 |   setImmediate(() => {})
    |  ^
```

- [x] build, middleware/edge route is using a node.js global API: warning but succeeds

```bash
warn  - Compiled with warnings

./middleware.js
A Node.js API is used (setImmediate at line: 6) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime

./pages/api/route.js
A Node.js API is used (setImmediate at line: 3) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime
```

- [x] production, middleware/edge route is using a node.js module: error at runtime (logs + 500 error)

```bash
Error: A Node.js API is used (setImmediate) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime
    at <unknown> (file:///Users/damien/dev/next.js/packages/next/server/web/sandbox/context.ts:330)
```

- [x] dev, middleware/edge route is loading dynamic code: warning at runtime (logs + read-dev-overlay) and request succeeds (we allow dynamic code in dev only):

```bash
warn  - (middleware)/middleware.js (7:2) @ Object.middleware [as handler]
warn  - Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime
   5 |
   6 | export default async function middleware() {
>  7 |   eval('2+2')
```

- [x] build, middleware/edge route is loading dynamic code: build fails with error:

```bash
Failed to compile.

./middleware.js
Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime
Used by default

./pages/api/route.js
Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime
Used by default
```

## Notes to reviewers

Edge-related errors are either issued from `next/server/web/sandbox/context.ts` file (runtime errors) or from `next/build/webpack/plugins/middleware-plugin.ts` (webpack compilation).

The previous implementation (I’m pleading guilty here) was way too verbose: some errors (Node.js global APIs like using `process.cwd()`) could be reported several times, and the previous mechanism to dedupe them (in middleware-plugin) wasn’t really effective.

Changes in tests are due to renaming existing tests such as `test/integration/middleware-with-node.js-apis` into `test/integration/edge-runtime-with-node.js-apis`. I extended them to cover Edge API route.

@hanneslund I’ve pushed the improvement you did in https://github.com/vercel/next.js/pull/38289/ one step further to avoid duplication.
parent 6486e12e
...@@ -380,7 +380,10 @@ Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`, ...@@ -380,7 +380,10 @@ Learn More: https://nextjs.org/docs/messages/node-module-in-edge-runtime`,
} }
} }
}) })
registerUnsupportedApiHooks(parser, compilation) if (!dev) {
// do not issue compilation warning on dev: invoking code will provide details
registerUnsupportedApiHooks(parser, compilation)
}
} }
} }
...@@ -445,7 +448,7 @@ function getExtractMetadata(params: { ...@@ -445,7 +448,7 @@ function getExtractMetadata(params: {
compilation.errors.push( compilation.errors.push(
buildWebpackError({ buildWebpackError({
message: `Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Middleware ${entryName}${ message: `Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime ${
typeof buildInfo.usingIndirectEval !== 'boolean' typeof buildInfo.usingIndirectEval !== 'boolean'
? `\nUsed by ${Array.from(buildInfo.usingIndirectEval).join( ? `\nUsed by ${Array.from(buildInfo.usingIndirectEval).join(
', ' ', '
......
...@@ -44,7 +44,7 @@ function formatMessage(message, verbose) { ...@@ -44,7 +44,7 @@ function formatMessage(message, verbose) {
message.moduleTrace && message.moduleTrace &&
message.moduleTrace.filter( message.moduleTrace.filter(
(trace) => (trace) =>
!/next-(middleware|client-pages|flight-(client|server))-loader\.js/.test( !/next-(middleware|client-pages|edge-function|flight-(client|server))-loader\.js/.test(
trace.originName trace.originName
) )
) )
......
...@@ -13,7 +13,6 @@ import type { RoutingItem } from '../base-server' ...@@ -13,7 +13,6 @@ import type { RoutingItem } from '../base-server'
import crypto from 'crypto' import crypto from 'crypto'
import fs from 'fs' import fs from 'fs'
import chalk from 'next/dist/compiled/chalk'
import { Worker } from 'next/dist/compiled/jest-worker' import { Worker } from 'next/dist/compiled/jest-worker'
import findUp from 'next/dist/compiled/find-up' import findUp from 'next/dist/compiled/find-up'
import { join as pathJoin, relative, resolve as pathResolve, sep } from 'path' import { join as pathJoin, relative, resolve as pathResolve, sep } from 'path'
...@@ -714,7 +713,12 @@ export default class DevServer extends Server { ...@@ -714,7 +713,12 @@ export default class DevServer extends Server {
page: string page: string
}) { }) {
try { try {
return super.runEdgeFunction(params) return super.runEdgeFunction({
...params,
onWarning: (warn) => {
this.logErrorWithOriginalStack(warn, 'warning')
},
})
} catch (error) { } catch (error) {
if (error instanceof DecodeError) { if (error instanceof DecodeError) {
throw error throw error
...@@ -797,7 +801,9 @@ export default class DevServer extends Server { ...@@ -797,7 +801,9 @@ export default class DevServer extends Server {
const frames = parseStack(err.stack!) const frames = parseStack(err.stack!)
const frame = frames.find( const frame = frames.find(
({ file }) => ({ file }) =>
!file?.startsWith('eval') && !file?.includes('web/adapter') !file?.startsWith('eval') &&
!file?.includes('web/adapter') &&
!file?.includes('sandbox/context')
)! )!
if (frame.lineNumber && frame?.file) { if (frame.lineNumber && frame?.file) {
...@@ -838,12 +844,9 @@ export default class DevServer extends Server { ...@@ -838,12 +844,9 @@ export default class DevServer extends Server {
`${file} (${lineNumber}:${column}) @ ${methodName}` `${file} (${lineNumber}:${column}) @ ${methodName}`
) )
if (src === 'edge-server') { if (src === 'edge-server') {
console[type === 'warning' ? 'warn' : 'error']( err = err.message
`${(type === 'warning' ? chalk.yellow : chalk.red)( }
err.name if (type === 'warning') {
)}: ${err.message}`
)
} else if (type === 'warning') {
Log.warn(err) Log.warn(err)
} else if (type) { } else if (type) {
Log.error(`${type}:`, err) Log.error(`${type}:`, err)
......
...@@ -1247,12 +1247,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1247,12 +1247,7 @@ export default class NextNodeServer extends BaseServer {
body: originalBody?.cloneBodyStream(), body: originalBody?.cloneBodyStream(),
}, },
useCache: !this.nextConfig.experimental.runtime, useCache: !this.nextConfig.experimental.runtime,
onWarning: (warning: Error) => { onWarning: params.onWarning,
if (params.onWarning) {
warning.message += ` "./${middlewareInfo.name}"`
params.onWarning(warning)
}
},
}) })
for (let [key, value] of result.response.headers) { for (let [key, value] of result.response.headers) {
...@@ -1531,6 +1526,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1531,6 +1526,7 @@ export default class NextNodeServer extends BaseServer {
query: ParsedUrlQuery query: ParsedUrlQuery
params: Params | undefined params: Params | undefined
page: string page: string
onWarning?: (warning: Error) => void
}): Promise<FetchEventResult | null> { }): Promise<FetchEventResult | null> {
let middlewareInfo: ReturnType<typeof this.getEdgeFunctionInfo> | undefined let middlewareInfo: ReturnType<typeof this.getEdgeFunctionInfo> | undefined
...@@ -1584,12 +1580,7 @@ export default class NextNodeServer extends BaseServer { ...@@ -1584,12 +1580,7 @@ export default class NextNodeServer extends BaseServer {
: requestToBodyStream(nodeReq.originalRequest), : requestToBodyStream(nodeReq.originalRequest),
}, },
useCache: !this.nextConfig.experimental.runtime, useCache: !this.nextConfig.experimental.runtime,
onWarning: (_warning: Error) => { onWarning: params.onWarning,
// if (params.onWarning) {
// warning.message += ` "./${middlewareInfo.name}"`
// params.onWarning(warning)
// }
},
}) })
params.res.statusCode = result.response.status params.res.statusCode = result.response.status
......
...@@ -120,7 +120,7 @@ async function createModuleContext(options: ModuleContextOptions) { ...@@ -120,7 +120,7 @@ async function createModuleContext(options: ModuleContextOptions) {
if (!warnedEvals.has(key)) { if (!warnedEvals.has(key)) {
const warning = getServerError( const warning = getServerError(
new Error( new Error(
`Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Middleware` `Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime`
), ),
'edge-server' 'edge-server'
) )
...@@ -137,7 +137,7 @@ async function createModuleContext(options: ModuleContextOptions) { ...@@ -137,7 +137,7 @@ async function createModuleContext(options: ModuleContextOptions) {
const key = fn.toString() const key = fn.toString()
if (!warnedWasmCodegens.has(key)) { if (!warnedWasmCodegens.has(key)) {
const warning = getServerError( const warning = getServerError(
new Error(`Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Middleware. new Error(`Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation`), Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation`),
'edge-server' 'edge-server'
) )
...@@ -164,7 +164,7 @@ Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation ...@@ -164,7 +164,7 @@ Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation
const key = fn.toString() const key = fn.toString()
if (instantiatedFromBuffer && !warnedWasmCodegens.has(key)) { if (instantiatedFromBuffer && !warnedWasmCodegens.has(key)) {
const warning = getServerError( const warning = getServerError(
new Error(`Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Middleware. new Error(`Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Edge Runtime.
Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation`), Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation`),
'edge-server' 'edge-server'
) )
...@@ -240,7 +240,7 @@ Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation ...@@ -240,7 +240,7 @@ Learn More: https://nextjs.org/docs/messages/middleware-dynamic-wasm-compilation
} }
for (const name of EDGE_UNSUPPORTED_NODE_APIS) { for (const name of EDGE_UNSUPPORTED_NODE_APIS) {
addStub(context, name, options) addStub(context, name)
} }
Object.assign(context, wasm) Object.assign(context, wasm)
...@@ -285,9 +285,7 @@ function buildEnvironmentVariablesFrom( ...@@ -285,9 +285,7 @@ function buildEnvironmentVariablesFrom(
return env return env
} }
function createProcessPolyfill( function createProcessPolyfill(options: Pick<ModuleContextOptions, 'env'>) {
options: Pick<ModuleContextOptions, 'env' | 'onWarning'>
) {
const env = buildEnvironmentVariablesFrom(options.env) const env = buildEnvironmentVariablesFrom(options.env)
const processPolyfill = { env } const processPolyfill = { env }
...@@ -296,8 +294,13 @@ function createProcessPolyfill( ...@@ -296,8 +294,13 @@ function createProcessPolyfill(
if (key === 'env') continue if (key === 'env') continue
Object.defineProperty(processPolyfill, key, { Object.defineProperty(processPolyfill, key, {
get() { get() {
emitWarning(`process.${key}`, options) if (overridenValue[key]) {
return overridenValue[key] return overridenValue[key]
}
if (typeof (process as any)[key] === 'function') {
return () => throwUnsupportedAPIError(`process.${key}`)
}
return undefined
}, },
set(value) { set(value) {
overridenValue[key] = value overridenValue[key] = value
...@@ -308,35 +311,23 @@ function createProcessPolyfill( ...@@ -308,35 +311,23 @@ function createProcessPolyfill(
return processPolyfill return processPolyfill
} }
const warnedAlready = new Set<string>() function addStub(context: Primitives, name: string) {
function addStub(
context: Primitives,
name: string,
contextOptions: Pick<ModuleContextOptions, 'onWarning'>
) {
Object.defineProperty(context, name, { Object.defineProperty(context, name, {
get() { get() {
emitWarning(name, contextOptions) return function () {
return undefined throwUnsupportedAPIError(name)
}
}, },
enumerable: false, enumerable: false,
}) })
} }
function emitWarning( function throwUnsupportedAPIError(name: string) {
name: string, const error =
contextOptions: Pick<ModuleContextOptions, 'onWarning'> new Error(`A Node.js API is used (${name}) which is not supported in the Edge Runtime.
) {
if (!warnedAlready.has(name)) {
const warning =
new Error(`A Node.js API is used (${name}) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime`) Learn more: https://nextjs.org/docs/api-reference/edge-runtime`)
warning.name = 'NodejsRuntimeApiInMiddlewareWarning' decorateServerError(error, 'edge-server')
contextOptions.onWarning(warning) throw error
console.warn(warning.message)
warnedAlready.add(name)
}
} }
function decorateUnhandledError(error: any) { function decorateUnhandledError(error: any) {
......
...@@ -8,7 +8,7 @@ export const ErrorSource = Symbol('SandboxError') ...@@ -8,7 +8,7 @@ export const ErrorSource = Symbol('SandboxError')
type RunnerFn = (params: { type RunnerFn = (params: {
name: string name: string
env: string[] env: string[]
onWarning: (warn: Error) => void onWarning?: (warn: Error) => void
paths: string[] paths: string[]
request: RequestData request: RequestData
useCache: boolean useCache: boolean
...@@ -19,7 +19,7 @@ type RunnerFn = (params: { ...@@ -19,7 +19,7 @@ type RunnerFn = (params: {
export const run = withTaggedErrors(async (params) => { export const run = withTaggedErrors(async (params) => {
const { runtime, evaluateInContext } = await getModuleContext({ const { runtime, evaluateInContext } = await getModuleContext({
moduleName: params.name, moduleName: params.name,
onWarning: params.onWarning, onWarning: params.onWarning ?? (() => {}),
useCache: params.useCache !== false, useCache: params.useCache !== false,
env: params.env, env: params.env,
edgeFunctionEntry: params.edgeFunctionEntry, edgeFunctionEntry: params.edgeFunctionEntry,
......
...@@ -344,7 +344,11 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) { ...@@ -344,7 +344,11 @@ function getOverlayMiddleware(options: OverlayMiddlewareOptions) {
return res.end() return res.end()
} }
const filePath = path.resolve(options.rootDirectory, frameFile) // frame files may start with their webpack layer, like (middleware)/middleware.js
const filePath = path.resolve(
options.rootDirectory,
frameFile.replace(/^\([^)]+\)\//, '')
)
const fileExists = await fs.access(filePath, FS.F_OK).then( const fileExists = await fs.access(filePath, FS.F_OK).then(
() => true, () => true,
() => false () => false
......
export const useCases = {
eval: 'using-eval',
noEval: 'not-using-eval',
wasmCompile: 'using-webassembly-compile',
wasmInstanciate: 'using-webassembly-instantiate',
wasmBufferInstanciate: 'using-webassembly-instantiate-with-buffer',
}
export async function usingEval() { export async function usingEval() {
// eslint-disable-next-line no-eval // eslint-disable-next-line no-eval
return { value: eval('100') } return { value: eval('100') }
......
import { notUsingEval, usingEval } from './lib/utils' import { NextResponse } from 'next/server'
import { useCases, notUsingEval, usingEval } from './lib/utils'
import { import {
usingWebAssemblyCompile, usingWebAssemblyCompile,
usingWebAssemblyInstantiate, usingWebAssemblyInstantiate,
...@@ -6,37 +7,41 @@ import { ...@@ -6,37 +7,41 @@ import {
} from './lib/wasm' } from './lib/wasm'
export async function middleware(request) { export async function middleware(request) {
if (request.nextUrl.pathname === '/using-eval') { if (request.nextUrl.pathname === `/${useCases.eval}`) {
return new Response(null, { return new Response(null, {
headers: { data: JSON.stringify(await usingEval()) }, headers: { data: JSON.stringify(await usingEval()) },
}) })
} }
if (request.nextUrl.pathname === '/not-using-eval') { if (request.nextUrl.pathname === `/${useCases.noEval}`) {
return new Response(null, { return new Response(null, {
headers: { data: JSON.stringify(await notUsingEval()) }, headers: { data: JSON.stringify(await notUsingEval()) },
}) })
} }
if (request.nextUrl.pathname === '/using-webassembly-compile') { if (request.nextUrl.pathname === `/${useCases.wasmCompile}`) {
return new Response(null, { return new Response(null, {
headers: { data: JSON.stringify(await usingWebAssemblyCompile(9)) }, headers: { data: JSON.stringify(await usingWebAssemblyCompile(9)) },
}) })
} }
if (request.nextUrl.pathname === '/using-webassembly-instantiate') { if (request.nextUrl.pathname === `/${useCases.wasmInstanciate}`) {
return new Response(null, { return new Response(null, {
headers: { data: JSON.stringify(await usingWebAssemblyInstantiate(9)) }, headers: { data: JSON.stringify(await usingWebAssemblyInstantiate(9)) },
}) })
} }
if ( if (request.nextUrl.pathname === `/${useCases.wasmBufferInstanciate}`) {
request.nextUrl.pathname === '/using-webassembly-instantiate-with-buffer'
) {
return new Response(null, { return new Response(null, {
headers: { headers: {
data: JSON.stringify(await usingWebAssemblyInstantiateWithBuffer(9)), data: JSON.stringify(await usingWebAssemblyInstantiateWithBuffer(9)),
}, },
}) })
} }
return NextResponse.next()
}
export const config = {
matcher: Object.values(useCases).map((route) => `/${route}`),
} }
import { useCases, notUsingEval, usingEval } from '../../lib/utils'
import {
usingWebAssemblyCompile,
usingWebAssemblyInstantiate,
usingWebAssemblyInstantiateWithBuffer,
} from '../../lib/wasm'
export default async function handler(request) {
const useCase = request.nextUrl.searchParams.get('case')
return Response.json(
useCase === useCases.eval
? await usingEval()
: useCase === useCases.noEval
? await notUsingEval()
: useCase === useCases.wasmCompile
? await usingWebAssemblyCompile(9)
: useCase === useCases.wasmInstanciate
? await usingWebAssemblyInstantiate(9)
: useCase === useCases.wasmBufferInstanciate
? await usingWebAssemblyInstantiateWithBuffer(9)
: { ok: true }
)
}
export const config = { runtime: 'experimental-edge' }
/* eslint-env jest */
import stripAnsi from 'next/dist/compiled/strip-ansi'
import { join } from 'path'
import {
fetchViaHTTP,
findPort,
killApp,
launchApp,
nextBuild,
renderViaHTTP,
waitFor,
} from 'next-test-utils'
const EVAL_ERROR = `Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Edge Runtime`
const DYNAMIC_CODE_ERROR = `Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Edge Runtime`
const WASM_COMPILE_ERROR = `Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Edge Runtime`
const WASM_INSTANTIATE_ERROR = `Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Edge Runtime`
jest.setTimeout(1000 * 60 * 2)
const context = {
appDir: join(__dirname, '../'),
}
describe('Page using eval in dev mode', () => {
let output = ''
beforeAll(async () => {
context.appPort = await findPort()
context.app = await launchApp(context.appDir, context.appPort, {
env: { __NEXT_TEST_WITH_DEVTOOL: 1 },
onStdout(msg) {
output += msg
},
onStderr(msg) {
output += msg
},
})
})
beforeEach(() => (output = ''))
afterAll(() => killApp(context.app))
it('does issue dynamic code evaluation warnings', async () => {
const html = await renderViaHTTP(context.appPort, '/')
expect(html).toMatch(/>.*?100.*?and.*?100.*?<\//)
await waitFor(500)
expect(output).not.toContain(EVAL_ERROR)
expect(output).not.toContain(DYNAMIC_CODE_ERROR)
expect(output).not.toContain(WASM_COMPILE_ERROR)
expect(output).not.toContain(WASM_INSTANTIATE_ERROR)
})
})
describe.each([
{
title: 'Middleware',
computeRoute(useCase) {
return `/${useCase}`
},
async extractValue(response) {
return JSON.parse(response.headers.get('data')).value
},
},
{
title: 'Edge route',
computeRoute(useCase) {
return `/api/route?case=${useCase}`
},
async extractValue(response) {
return (await response.json()).value
},
},
])(
'$title usage of dynamic code evaluation',
({ extractValue, computeRoute }) => {
describe('dev mode', () => {
let output = ''
beforeAll(async () => {
context.appPort = await findPort()
context.app = await launchApp(context.appDir, context.appPort, {
env: { __NEXT_TEST_WITH_DEVTOOL: 1 },
onStdout(msg) {
output += msg
},
onStderr(msg) {
output += msg
},
})
})
beforeEach(() => (output = ''))
afterAll(() => killApp(context.app))
it('shows a warning when running code with eval', async () => {
const res = await fetchViaHTTP(
context.appPort,
computeRoute('using-eval')
)
expect(await extractValue(res)).toEqual(100)
await waitFor(500)
expect(output).toContain(EVAL_ERROR)
// TODO check why that has a backslash on windows
expect(output).toMatch(/lib[\\/]utils\.js/)
expect(output).toContain('usingEval')
expect(stripAnsi(output)).toContain("value: eval('100')")
})
it('does not show warning when no code uses eval', async () => {
const res = await fetchViaHTTP(
context.appPort,
computeRoute('not-using-eval')
)
expect(await extractValue(res)).toEqual(100)
await waitFor(500)
expect(output).not.toContain('Dynamic Code Evaluation')
})
it('shows a warning when running WebAssembly.compile', async () => {
const res = await fetchViaHTTP(
context.appPort,
computeRoute('using-webassembly-compile')
)
expect(await extractValue(res)).toEqual(81)
await waitFor(500)
expect(output).toContain(WASM_COMPILE_ERROR)
expect(output).toMatch(/lib[\\/]wasm\.js/)
expect(output).toContain('usingWebAssemblyCompile')
expect(stripAnsi(output)).toContain(
'await WebAssembly.compile(SQUARE_WASM_BUFFER)'
)
})
it('shows a warning when running WebAssembly.instantiate with a buffer parameter', async () => {
const res = await fetchViaHTTP(
context.appPort,
computeRoute('using-webassembly-instantiate-with-buffer')
)
expect(await extractValue(res)).toEqual(81)
await waitFor(500)
expect(output).toContain(WASM_INSTANTIATE_ERROR)
expect(output).toMatch(/lib[\\/]wasm\.js/)
expect(output).toContain('usingWebAssemblyInstantiateWithBuffer')
expect(stripAnsi(output)).toContain(
'await WebAssembly.instantiate(SQUARE_WASM_BUFFER, {})'
)
})
it('does not show a warning when running WebAssembly.instantiate with a module parameter', async () => {
const res = await fetchViaHTTP(
context.appPort,
computeRoute('using-webassembly-instantiate')
)
expect(await extractValue(res)).toEqual(81)
await waitFor(500)
expect(output).not.toContain(WASM_INSTANTIATE_ERROR)
expect(output).not.toContain('DynamicWasmCodeGenerationWarning')
})
})
describe('production mode', () => {
let buildResult
beforeAll(async () => {
buildResult = await nextBuild(context.appDir, undefined, {
stderr: true,
stdout: true,
})
})
it('should have middleware warning during build', () => {
expect(buildResult.stderr).toContain(`Failed to compile`)
expect(buildResult.stderr).toContain(`Used by usingEval, usingEvalSync`)
expect(buildResult.stderr).toContain(`Used by usingWebAssemblyCompile`)
expect(buildResult.stderr).toContain(DYNAMIC_CODE_ERROR)
})
})
}
)
/* eslint-disable no-undef */ /* eslint-disable no-undef */
import { NextResponse } from 'next/server' export function invokeNodeAPI(useCase) {
export default function middleware({ nextUrl: { pathname } }) {
let handle let handle
if (pathname === '/Buffer') { if (useCase === 'Buffer') {
Buffer.from('') Buffer.from('')
} } else if (useCase === 'setImmediate') {
if (pathname === '/setImmediate') {
handle = setImmediate(() => {}) handle = setImmediate(() => {})
} } else if (useCase === 'clearImmediate') {
if (pathname === '/clearImmediate') {
clearImmediate(handle) clearImmediate(handle)
} } else if (useCase === 'process.cwd') {
if (pathname === '/process.cwd') {
console.log(process.cwd()) console.log(process.cwd())
} } else if (useCase === 'process.getuid') {
if (pathname === '/process.getuid') {
console.log(process.getuid()) console.log(process.getuid())
} } else if (useCase === 'process.cpuUsage') {
if (pathname === '/BroadcastChannel') { console.log(process.cpuUsage())
} else if (useCase === 'BroadcastChannel') {
new BroadcastChannel() new BroadcastChannel()
} } else if (useCase === 'ByteLengthQueuingStrategy') {
if (pathname === '/ByteLengthQueuingStrategy') {
new ByteLengthQueuingStrategy() new ByteLengthQueuingStrategy()
} } else if (useCase === 'CompressionStream') {
if (pathname === '/CompressionStream') {
new CompressionStream() new CompressionStream()
} } else if (useCase === 'CountQueuingStrategy') {
if (pathname === '/CountQueuingStrategy') {
new CountQueuingStrategy() new CountQueuingStrategy()
} } else if (useCase === 'DecompressionStream') {
if (pathname === '/DecompressionStream') {
new DecompressionStream() new DecompressionStream()
} } else if (useCase === 'DomException') {
if (pathname === '/DomException') {
new DomException() new DomException()
} } else if (useCase === 'MessageChannel') {
if (pathname === '/MessageChannel') {
new MessageChannel() new MessageChannel()
} } else if (useCase === 'MessageEvent') {
if (pathname === '/MessageEvent') {
new MessageEvent() new MessageEvent()
} } else if (useCase === 'MessagePort') {
if (pathname === '/MessagePort') {
new MessagePort() new MessagePort()
} } else if (useCase === 'ReadableByteStreamController') {
if (pathname === '/ReadableByteStreamController') {
new ReadableByteStreamController() new ReadableByteStreamController()
} } else if (useCase === 'ReadableStreamBYOBRequest') {
if (pathname === '/ReadableStreamBYOBRequest') {
new ReadableStreamBYOBRequest() new ReadableStreamBYOBRequest()
} } else if (useCase === 'ReadableStreamDefaultController') {
if (pathname === '/ReadableStreamDefaultController') {
new ReadableStreamDefaultController() new ReadableStreamDefaultController()
} } else if (useCase === 'TextDecoderStream') {
if (pathname === '/TextDecoderStream') {
new TextDecoderStream() new TextDecoderStream()
} } else if (useCase === 'TextEncoderStream') {
if (pathname === '/TextEncoderStream') {
new TextEncoderStream() new TextEncoderStream()
} } else if (useCase === 'TransformStreamDefaultController') {
if (pathname === '/TransformStreamDefaultController') {
new TransformStreamDefaultController() new TransformStreamDefaultController()
} } else if (useCase === 'WritableStreamDefaultController') {
if (pathname === '/WritableStreamDefaultController') {
new WritableStreamDefaultController() new WritableStreamDefaultController()
} else if (useCase === 'process.version') {
console.log(process.version)
} else if (useCase === 'process.arch') {
console.log(process.arch)
} }
return NextResponse.next()
} }
import { NextResponse } from 'next/server'
import { invokeNodeAPI } from './lib/utils'
export default function middleware({ nextUrl }) {
invokeNodeAPI(nextUrl.pathname.slice(1))
return nextUrl.pathname.startsWith('/api')
? NextResponse.next()
: NextResponse.rewrite(new URL('/', nextUrl))
}
import { invokeNodeAPI } from '../../lib/utils'
export default async function handler(request) {
invokeNodeAPI(request.nextUrl.searchParams.get('case'))
return Response.json({ ok: true })
}
export const config = { runtime: 'experimental-edge' }
/* eslint-env jest */ /* eslint-env jest */
import { remove } from 'fs-extra' import { remove } from 'fs-extra'
import stripAnsi from 'next/dist/compiled/strip-ansi'
import { import {
check,
fetchViaHTTP, fetchViaHTTP,
findPort, findPort,
killApp, killApp,
...@@ -19,8 +19,14 @@ const unsupportedFunctions = [ ...@@ -19,8 +19,14 @@ const unsupportedFunctions = [
'clearImmediate', 'clearImmediate',
// no need to test all of the process methods // no need to test all of the process methods
'process.cwd', 'process.cwd',
'process.cpuUsage',
'process.getuid', 'process.getuid',
] ]
const undefinedPropertoes = [
// no need to test all of the process properties
'process.arch',
'process.version',
]
const unsupportedClasses = [ const unsupportedClasses = [
'BroadcastChannel', 'BroadcastChannel',
'ByteLengthQueuingStrategy', 'ByteLengthQueuingStrategy',
...@@ -40,7 +46,20 @@ const unsupportedClasses = [ ...@@ -40,7 +46,20 @@ const unsupportedClasses = [
'WritableStreamDefaultController', 'WritableStreamDefaultController',
] ]
describe('Middleware using Node.js API', () => { describe.each([
{
title: 'Middleware',
computeRoute(useCase) {
return `/${useCase}`
},
},
{
title: 'Edge route',
computeRoute(useCase) {
return `/api/route?case=${useCase}`
},
},
])('$title using Node.js API', ({ computeRoute }) => {
const appDir = join(__dirname, '..') const appDir = join(__dirname, '..')
describe('dev mode', () => { describe('dev mode', () => {
...@@ -64,37 +83,33 @@ describe('Middleware using Node.js API', () => { ...@@ -64,37 +83,33 @@ describe('Middleware using Node.js API', () => {
afterAll(() => killApp(app)) afterAll(() => killApp(app))
it.each(undefinedPropertoes.map((api) => ({ api })))(
'does not throw on using $api',
async ({ api }) => {
const res = await fetchViaHTTP(appPort, computeRoute(api))
expect(res.status).toBe(200)
await waitFor(500)
expect(output).not.toInclude(`A Node.js API is used (${api})`)
}
)
it.each([ it.each([
{
api: 'Buffer',
error: process.version.startsWith('v16')
? `Cannot read properties of undefined (reading 'from')`
: `Cannot read property 'from' of undefined`,
},
...unsupportedFunctions.map((api) => ({ ...unsupportedFunctions.map((api) => ({
api, api,
error: `${api} is not a function`, errorHighlight: `${api}(`,
})), })),
...unsupportedClasses.map((api) => ({ ...unsupportedClasses.map((api) => ({
api, api,
error: `${api} is not a constructor`, errorHighlight: `new ${api}(`,
})), })),
])(`shows error when using $api`, async ({ api, error }) => { ])(`throws error when using $api`, async ({ api, errorHighlight }) => {
const res = await fetchViaHTTP(appPort, `/${api}`) const res = await fetchViaHTTP(appPort, computeRoute(api))
await waitFor(500)
expect(res.status).toBe(500) expect(res.status).toBe(500)
await check( await waitFor(500)
() => expect(output)
output.includes(`A Node.js API is used (${api}) which is not supported in the Edge Runtime. .toInclude(`A Node.js API is used (${api}) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime`) Learn more: https://nextjs.org/docs/api-reference/edge-runtime`)
? 'success' expect(stripAnsi(output)).toInclude(errorHighlight)
: output,
'success'
)
await check(
() => (output.includes(`TypeError: ${error}`) ? 'success' : output),
'success'
)
}) })
}) })
...@@ -113,13 +128,17 @@ Learn more: https://nextjs.org/docs/api-reference/edge-runtime`) ...@@ -113,13 +128,17 @@ Learn more: https://nextjs.org/docs/api-reference/edge-runtime`)
['Buffer', ...unsupportedFunctions, ...unsupportedClasses].map( ['Buffer', ...unsupportedFunctions, ...unsupportedClasses].map(
(api, index) => ({ (api, index) => ({
api, api,
line: 5 + index * 3,
}) })
) )
)(`warns for $api during build`, ({ api, line }) => { )(`warns for $api during build`, ({ api }) => {
expect(buildResult.stderr) expect(buildResult.stderr).toContain(`A Node.js API is used (${api}`)
.toContain(`A Node.js API is used (${api} at line: ${line}) which is not supported in the Edge Runtime.
Learn more: https://nextjs.org/docs/api-reference/edge-runtime`)
}) })
it.each(undefinedPropertoes.map((api) => ({ api })))(
'does not warn on using $api',
({ api }) => {
expect(buildResult.stderr).toContain(`A Node.js API is used (${api}`)
}
)
}) })
}) })
...@@ -58,7 +58,7 @@ describe('Middleware development errors', () => { ...@@ -58,7 +58,7 @@ describe('Middleware development errors', () => {
const output = stripAnsi(context.logs.output) const output = stripAnsi(context.logs.output)
expect(output).toMatch( expect(output).toMatch(
new RegExp( new RegExp(
`error - \\(middleware\\)/middleware.js \\(\\d+:\\d+\\) @ Object.__WEBPACK_DEFAULT_EXPORT__ \\[as handler\\]\nError: boom`, `error - \\(middleware\\)/middleware.js \\(\\d+:\\d+\\) @ Object.__WEBPACK_DEFAULT_EXPORT__ \\[as handler\\]\nerror - boom`,
'm' 'm'
) )
) )
...@@ -93,7 +93,7 @@ describe('Middleware development errors', () => { ...@@ -93,7 +93,7 @@ describe('Middleware development errors', () => {
const output = stripAnsi(context.logs.output) const output = stripAnsi(context.logs.output)
expect(output).toMatch( expect(output).toMatch(
new RegExp( new RegExp(
`error - \\(middleware\\)/middleware.js \\(\\d+:\\d+\\) @ throwError\nError: async boom!`, `error - \\(middleware\\)/middleware.js \\(\\d+:\\d+\\) @ throwError\nerror - unhandledRejection: async boom!`,
'm' 'm'
) )
) )
...@@ -124,7 +124,7 @@ describe('Middleware development errors', () => { ...@@ -124,7 +124,7 @@ describe('Middleware development errors', () => {
const output = stripAnsi(context.logs.output) const output = stripAnsi(context.logs.output)
expect(output).toMatch( expect(output).toMatch(
new RegExp( new RegExp(
`error - \\(middleware\\)/middleware.js \\(\\d+:\\d+\\) @ eval\nReferenceError: test is not defined`, `error - \\(middleware\\)/middleware.js \\(\\d+:\\d+\\) @ eval\nerror - test is not defined`,
'm' 'm'
) )
) )
...@@ -157,7 +157,7 @@ describe('Middleware development errors', () => { ...@@ -157,7 +157,7 @@ describe('Middleware development errors', () => {
const output = stripAnsi(context.logs.output) const output = stripAnsi(context.logs.output)
expect(output).toMatch( expect(output).toMatch(
new RegExp( new RegExp(
`error - \\(middleware\\)/middleware.js \\(\\d+:\\d+\\) @ <unknown>\nError: booooom!`, `error - \\(middleware\\)/middleware.js \\(\\d+:\\d+\\) @ <unknown>\nerror - booooom!`,
'm' 'm'
) )
) )
...@@ -195,7 +195,7 @@ describe('Middleware development errors', () => { ...@@ -195,7 +195,7 @@ describe('Middleware development errors', () => {
const output = stripAnsi(context.logs.output) const output = stripAnsi(context.logs.output)
expect(output).toMatch( expect(output).toMatch(
new RegExp( new RegExp(
`error - \\(middleware\\)/middleware.js \\(\\d+:\\d+\\) @ eval\nError: you shall see me`, `error - \\(middleware\\)/middleware.js \\(\\d+:\\d+\\) @ eval\nerror - unhandledRejection: you shall see me`,
'm' 'm'
) )
) )
...@@ -227,7 +227,7 @@ describe('Middleware development errors', () => { ...@@ -227,7 +227,7 @@ describe('Middleware development errors', () => {
const output = stripAnsi(context.logs.output) const output = stripAnsi(context.logs.output)
expect(output).toMatch( expect(output).toMatch(
new RegExp( new RegExp(
`error - \\(middleware\\)/lib/unhandled.js \\(\\d+:\\d+\\) @ Timeout.eval \\[as _onTimeout\\]\nError: This file asynchronously fails while loading`, `error - \\(middleware\\)/lib/unhandled.js \\(\\d+:\\d+\\) @ Timeout.eval \\[as _onTimeout\\]\nerror - uncaughtException: This file asynchronously fails while loading`,
'm' 'm'
) )
) )
......
/* eslint-env jest */
import stripAnsi from 'next/dist/compiled/strip-ansi'
import { join } from 'path'
import {
fetchViaHTTP,
findPort,
killApp,
launchApp,
nextBuild,
renderViaHTTP,
waitFor,
} from 'next-test-utils'
const context = {}
const EVAL_ERROR = `Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Middleware`
const DYNAMIC_CODE_ERROR = `Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Middleware`
const WASM_COMPILE_ERROR = `Dynamic WASM code generation (e. g. 'WebAssembly.compile') not allowed in Middleware`
const WASM_INSTANTIATE_ERROR = `Dynamic WASM code generation ('WebAssembly.instantiate' with a buffer parameter) not allowed in Middleware`
jest.setTimeout(1000 * 60 * 2)
context.appDir = join(__dirname, '../')
describe('Middleware usage of dynamic code evaluation', () => {
describe('dev mode', () => {
let output = ''
beforeAll(async () => {
context.appPort = await findPort()
context.app = await launchApp(context.appDir, context.appPort, {
env: { __NEXT_TEST_WITH_DEVTOOL: 1 },
onStdout(msg) {
output += msg
},
onStderr(msg) {
output += msg
},
})
})
beforeEach(() => (output = ''))
afterAll(() => killApp(context.app))
it('shows a warning when running code with eval', async () => {
const res = await fetchViaHTTP(context.appPort, `/using-eval`)
const json = JSON.parse(res.headers.get('data'))
await waitFor(500)
expect(json.value).toEqual(100)
expect(output).toContain(EVAL_ERROR)
expect(output).toContain('DynamicCodeEvaluationWarning')
expect(output).toContain('./middleware')
// TODO check why that has a backslash on windows
expect(output).toMatch(/lib[\\/]utils\.js/)
expect(output).toContain('usingEval')
expect(stripAnsi(output)).toContain("value: eval('100')")
})
it('does not show warning when no code uses eval', async () => {
const res = await fetchViaHTTP(context.appPort, `/not-using-eval`)
const json = JSON.parse(res.headers.get('data'))
await waitFor(500)
expect(json.value).toEqual(100)
expect(output).not.toContain('Dynamic Code Evaluation')
})
it('does not has problems with eval in page or server code', async () => {
const html = await renderViaHTTP(context.appPort, `/`)
expect(html).toMatch(/>.*?100.*?and.*?100.*?<\//)
await waitFor(500)
expect(output).not.toContain('Dynamic Code Evaluation')
})
it('shows a warning when running WebAssembly.compile', async () => {
const res = await fetchViaHTTP(
context.appPort,
`/using-webassembly-compile`
)
const json = JSON.parse(res.headers.get('data'))
await waitFor(500)
expect(json.value).toEqual(81)
expect(output).toContain(WASM_COMPILE_ERROR)
expect(output).toContain('DynamicWasmCodeGenerationWarning')
expect(output).toContain('./middleware')
expect(output).toMatch(/lib[\\/]wasm\.js/)
expect(output).toContain('usingWebAssemblyCompile')
expect(stripAnsi(output)).toContain(
'await WebAssembly.compile(SQUARE_WASM_BUFFER)'
)
})
it('shows a warning when running WebAssembly.instantiate w/ a buffer parameter', async () => {
const res = await fetchViaHTTP(
context.appPort,
`/using-webassembly-instantiate-with-buffer`
)
const json = JSON.parse(res.headers.get('data'))
await waitFor(500)
expect(json.value).toEqual(81)
expect(output).toContain(WASM_INSTANTIATE_ERROR)
expect(output).toContain('DynamicWasmCodeGenerationWarning')
expect(output).toContain('./middleware')
expect(output).toMatch(/lib[\\/]wasm\.js/)
expect(output).toContain('usingWebAssemblyInstantiateWithBuffer')
expect(stripAnsi(output)).toContain(
'await WebAssembly.instantiate(SQUARE_WASM_BUFFER, {})'
)
})
it('does not show a warning when running WebAssembly.instantiate w/ a module parameter', async () => {
const res = await fetchViaHTTP(
context.appPort,
`/using-webassembly-instantiate`
)
const json = JSON.parse(res.headers.get('data'))
await waitFor(500)
expect(json.value).toEqual(81)
expect(output).not.toContain(WASM_INSTANTIATE_ERROR)
expect(output).not.toContain('DynamicWasmCodeGenerationWarning')
})
})
describe('production mode', () => {
let buildResult
beforeAll(async () => {
buildResult = await nextBuild(context.appDir, undefined, {
stderr: true,
stdout: true,
})
})
it('should have middleware warning during build', () => {
expect(buildResult.stderr).toContain(`Failed to compile`)
expect(buildResult.stderr).toContain(`Used by usingEval`)
expect(buildResult.stderr).toContain(`./middleware.js`)
expect(buildResult.stderr).toContain(DYNAMIC_CODE_ERROR)
})
})
})
...@@ -32,14 +32,14 @@ describe('Middleware overriding a Node.js API', () => { ...@@ -32,14 +32,14 @@ describe('Middleware overriding a Node.js API', () => {
afterAll(() => killApp(context.app)) afterAll(() => killApp(context.app))
it('shows a warning but allows overriding', async () => { it('does not show a warning and allows overriding', async () => {
const res = await fetchViaHTTP(context.appPort, '/') const res = await fetchViaHTTP(context.appPort, '/')
await waitFor(500) await waitFor(500)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(output).toContain('A Node.js API is used (process.cwd')
expect(output).toContain('fixed-value') expect(output).toContain('fixed-value')
expect(output).not.toContain('TypeError') expect(output).not.toContain('TypeError')
expect(output).not.toContain(`A Node.js API is used (process.env`) expect(output).not.toContain('A Node.js API is used (process.env')
expect(output).not.toContain('A Node.js API is used (process.cwd')
}) })
}) })
}) })
import { createNext, FileRef } from 'e2e-utils'
import { join } from 'path'
import { NextInstance } from 'test/lib/next-modes/base'
describe('Middleware with Dynamic code invocations', () => {
const DYNAMIC_CODE_EVAL_ERROR = `Dynamic Code Evaluation (e. g. 'eval', 'new Function', 'WebAssembly.compile') not allowed in Middleware middleware`
let next: NextInstance
beforeAll(async () => {
next = await createNext({
files: {
'lib/utils.js': '',
'lib/square.wasm': new FileRef(join(__dirname, 'square.wasm')),
'pages/index.js': `
export default function () { return <div>Hello, world!</div> }
`,
'middleware.js': `
import './lib/utils'
export default function middleware() {
return new Response()
}
`,
},
dependencies: {
'@apollo/react-hooks': '3.1.5',
'@aws-sdk/client-s3': 'latest',
'apollo-client': 'latest',
graphql: 'latest',
'graphql-tag': 'latest',
has: 'latest',
qs: 'latest',
},
installCommand: 'yarn install',
})
await next.stop()
})
afterAll(() => next.destroy())
beforeEach(() => next.stop())
it('detects dynamic code nested in @apollo/react-hooks', async () => {
await next.patchFile(
'lib/utils.js',
`
import { useQuery } from '@apollo/react-hooks'
import gql from 'graphql-tag'
export default function useGreeting() {
return useQuery(
gql\`
query getGreeting($language: String!) {
greeting(language: $language) {
message
}
}
\`,
{ variables: { language: 'english' } }
)
}
`
)
await expect(next.start()).rejects.toThrow()
expect(next.cliOutput).toContain(`
./node_modules/ts-invariant/lib/invariant.esm.js
${DYNAMIC_CODE_EVAL_ERROR}`)
})
it('detects dynamic code nested in has', async () => {
await next.patchFile(
'lib/utils.js',
`
import has from 'has'
has(Object.prototype, 'hasOwnProperty')
`
)
await expect(next.start()).rejects.toThrow()
expect(next.cliOutput).toContain(`
./node_modules/function-bind/implementation.js
${DYNAMIC_CODE_EVAL_ERROR}`)
expect(next.cliOutput).toContain(`
./node_modules/has/src/index.js
${DYNAMIC_CODE_EVAL_ERROR}`)
})
it('detects dynamic code nested in qs', async () => {
await next.patchFile(
'lib/utils.js',
`
import qs from 'qs'
qs.parse('a=c')
`
)
await expect(next.start()).rejects.toThrow()
expect(next.cliOutput).toContain(`
./node_modules/get-intrinsic/index.js
${DYNAMIC_CODE_EVAL_ERROR}`)
})
it('does not detects dynamic code nested in @aws-sdk/client-s3 (legit Function.bind)', async () => {
await next.patchFile(
'lib/utils.js',
`
import { S3Client, AbortMultipartUploadCommand } from '@aws-sdk/client-s3'
new S3Client().send(new AbortMultipartUploadCommand({}))
`
)
// this previously threw from a module not found error
// although this is fixed now
await next.start()
expect(next.cliOutput).not.toContain(
`./node_modules/@aws-sdk/smithy-client/dist-es/lazy-json.js`
)
expect(next.cliOutput).not.toContain(DYNAMIC_CODE_EVAL_ERROR)
})
it('does not determine WebAssembly.instantiate with a module parameter as dynamic code execution (legit)', async () => {
await next.patchFile(
'lib/utils.js',
`
import wasm from './square.wasm?module'
const instance = WebAssembly.instantiate(wasm)
`
)
await next.start()
expect(next.cliOutput).not.toContain(DYNAMIC_CODE_EVAL_ERROR)
})
// Actually this causes a dynamic code evaluation however, we can't determine the type of
// first parameter of WebAssembly.instanntiate statically.
it('does not determine WebAssembly.instantiate with a buffer parameter as dynamic code execution', async () => {
await next.patchFile(
'lib/utils.js',
`
const instance = WebAssembly.instantiate(new Uint8Array([0, 1, 2, 3]))
`
)
await next.start()
expect(next.cliOutput).not.toContain(DYNAMIC_CODE_EVAL_ERROR)
})
it('detects use of WebAssembly.compile', async () => {
await next.patchFile(
'lib/utils.js',
`
const module = WebAssembly.compile(new Uint8Array([0, 1, 2, 3]))
`
)
await expect(next.start()).rejects.toThrow()
expect(next.cliOutput).toContain(`
./lib/utils.js
${DYNAMIC_CODE_EVAL_ERROR}`)
})
})
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