Unverified Commit 660026d5 authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

fix: this in edge sandbox setTimeout/setInterval (#94754)

Our attempts at setting the correct `this` in our
`setTimeout`/`setInterval` polyfills were slightly incorrect, because
they used the wrong global object.

(Thanks to [cyberjoker](https://hackerone.com/cyberjoker) for
discovering this)
parent 643e34a5
......@@ -436,7 +436,7 @@ Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`),
// @ts-ignore the timeouts have weird types in the edge runtime
context.setInterval = (...args: Parameters<typeof setInterval>) =>
intervalsManager.add(args)
intervalsManager.add([context, ...args])
// @ts-ignore the timeouts have weird types in the edge runtime
context.clearInterval = (interval: number) =>
......@@ -444,7 +444,7 @@ Learn More: https://nextjs.org/docs/messages/edge-dynamic-code-evaluation`),
// @ts-ignore the timeouts have weird types in the edge runtime
context.setTimeout = (...args: Parameters<typeof setTimeout>) =>
timeoutsManager.add(args)
timeoutsManager.add([context, ...args])
// @ts-ignore the timeouts have weird types in the edge runtime
context.clearTimeout = (timeout: number) =>
......
......@@ -23,9 +23,9 @@ abstract class ResourceManager<T, Args> {
class IntervalsManager extends ResourceManager<
number,
Parameters<typeof setInterval>
Parameters<typeof webSetIntervalPolyfill>
> {
create(args: Parameters<typeof setInterval>) {
create(args: Parameters<typeof webSetIntervalPolyfill>) {
// TODO: use the edge runtime provided `setInterval` instead
return webSetIntervalPolyfill(...args)
}
......@@ -37,9 +37,9 @@ class IntervalsManager extends ResourceManager<
class TimeoutsManager extends ResourceManager<
number,
Parameters<typeof setTimeout>
Parameters<typeof webSetTimeoutPolyfill>
> {
create(args: Parameters<typeof setTimeout>) {
create(args: Parameters<typeof webSetTimeoutPolyfill>) {
// TODO: use the edge runtime provided `setTimeout` instead
return webSetTimeoutPolyfill(...args)
}
......@@ -49,7 +49,10 @@ class TimeoutsManager extends ResourceManager<
}
}
export type GlobalObject = import('edge-runtime').EdgeRuntime['context']
function webSetIntervalPolyfill<TArgs extends any[]>(
globalObject: GlobalObject,
callback: (...args: TArgs) => void,
ms?: number,
...args: TArgs
......@@ -58,11 +61,12 @@ function webSetIntervalPolyfill<TArgs extends any[]>(
// node's `setInterval` sets `this` to the `Timeout` instance it returned,
// but web `setInterval` always sets `this` to `window`
// see: https://developer.mozilla.org/en-US/docs/Web/API/Window/setInterval#the_this_problem
return callback.apply(globalThis, args)
return callback.apply(globalObject, args)
}, ms)[Symbol.toPrimitive]()
}
function webSetTimeoutPolyfill<TArgs extends any[]>(
globalObject: GlobalObject,
callback: (...args: TArgs) => void,
ms?: number,
...args: TArgs
......@@ -72,7 +76,7 @@ function webSetTimeoutPolyfill<TArgs extends any[]>(
// node's `setTimeout` sets `this` to the `Timeout` instance it returned,
// but web `setTimeout` always sets `this` to `window`
// see: https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout#the_this_problem
return callback.apply(globalThis, args)
return callback.apply(globalObject, args)
} finally {
// On certain older node versions (<20.16.0, <22.4.0),
// a `setTimeout` whose Timeout was converted to a primitive will leak.
......
export const runtime = 'edge'
export async function GET() {
const result = await new Promise<string>((resolve) => {
setTimeout(function (this: typeof globalThis) {
try {
// The `this` available here should be the edge sandbox global object,
// not the one from node. If we get the node one, we can access require
// and thus modules that are not allowed in the edge runtime, like 'fs'.
const outerGlobalThis = this
const fs = outerGlobalThis.process.mainModule!.require(
'fs'
) as typeof import('fs')
fs.writeFileSync('hello.txt', 'sandbox? what sandbox?')
resolve('escape successful')
} catch (error) {
resolve('escape failed:\n' + (error as Error).toString())
}
})
})
return new Response(result)
}
import { nextTestSetup } from 'e2e-utils'
const enableCacheComponents = process.env.__NEXT_CACHE_COMPONENTS === 'true'
describe('edge-runtime-timer-this', () => {
const { next, skipped } = nextTestSetup({
files: __dirname,
// This is testing the edge runtime sandbox, which is only used in `next start`.
skipDeployment: true,
})
if (skipped) {
return
}
if (enableCacheComponents) {
it.skip('skipped because `runtime = "edge"` is not allowed in cacheComponents', () => {})
return
}
it('should not expose the outer globalThis to edge runtime callbacks', async () => {
const res = await next.fetch('/')
const text = await res.text()
// If the sandbox is escaped, the route resolves with exactly "escape successful"
// after writing a file via the outer process. It should instead fail to
// reach the outer globalThis and resolve with "escape failed:" plus the error.
expect(await next.hasFile('hello.txt')).toBe(false)
expect(text).not.toBe('escape successful')
expect(text).toMatchInlineSnapshot(`
"escape failed:
TypeError: Cannot read properties of undefined (reading 'require')"
`)
})
})
import type { NextConfig } from 'next'
const nextConfig: NextConfig = {}
export default nextConfig
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