Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion .github/workflows/image-sandbox.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,40 @@ name: Image sandbox verification
on:
push:
branches: [sandbox-images]
pull_request:
paths:
- '.github/workflows/image-sandbox.yml'
- 'packages/next/package.json'
- 'packages/next/src/server/config-schema.ts'
- 'packages/next/src/server/config-shared.ts'
- 'packages/next/src/server/config.ts'
- 'packages/next/src/server/image-optimizer.ts'
- 'packages/next/src/server/image-optimizer/**'
- 'packages/next/src/server/next-server.ts'
- 'pnpm-lock.yaml'
- 'test/development/image-optimizer-shutdown/**'
- 'test/e2e/image-optimizer/**'
- 'test/unit/image-optimizer/**'
workflow_dispatch:

permissions: {}

concurrency:
group: image-sandbox-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true

jobs:
linux:
if: github.repository == 'petehunt/next.js'
if: >-
github.repository == 'vercel/next.js' ||
github.repository == 'petehunt/next.js'
runs-on: ubuntu-22.04
timeout-minutes: 30
permissions:
contents: read
env:
NEXT_TELEMETRY_DISABLED: '1'
NEXT_TEST_IMAGE_SANDBOX: '1'
# Isolated route tests need the published SWC binary. Most repository CI
# jobs provide a locally built one, so the postinstall defaults to off.
NEXT_SKIP_NATIVE_POSTINSTALL: '0'
Expand All @@ -37,6 +58,8 @@ jobs:
run: pnpm exec turbo run build --filter=next...
- name: Test the shipped sandbox policy and direct transform API
run: pnpm exec jest --runInBand test/unit/image-optimizer
- name: Test dev shutdown with a stuck image worker
run: pnpm test-dev-webpack test/development/image-optimizer-shutdown/image-optimizer-shutdown.test.ts
- name: Test the development image route with and without sandboxing
run: pnpm test-dev-webpack test/e2e/image-optimizer/sharp.test.ts -t 'should resize relative url and png accept header'
- name: Test the production image route with and without sandboxing
Expand Down
99 changes: 74 additions & 25 deletions packages/next/src/server/image-optimizer/sandbox-worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,36 @@ const MIN_REQUEST_TIMEOUT_MS = 60_000
const WATCHDOG_GRACE_MS = 2_000
const KILL_GRACE_MS = 1_000

const shutdownHandlers = new Set<() => void>()
function killWorkers() {
for (const shutdown of shutdownHandlers) shutdown()
}
function onSignal(signal: NodeJS.Signals) {
killWorkers()
// Do not swallow Node's default termination behavior in custom servers
// that have no signal handler of their own.
if (process.listenerCount(signal) === 1) {
process.removeListener(signal, onSignal)
process.kill(process.pid, signal)
}
}
function registerShutdown(handler: () => void) {
if (shutdownHandlers.size === 0) {
process.prependListener('SIGINT', onSignal)
process.prependListener('SIGTERM', onSignal)
process.on('exit', killWorkers)
}
shutdownHandlers.add(handler)
}
function unregisterShutdown(handler: () => void) {
shutdownHandlers.delete(handler)
if (shutdownHandlers.size === 0) {
process.removeListener('SIGINT', onSignal)
process.removeListener('SIGTERM', onSignal)
process.removeListener('exit', killWorkers)
}
}

type SandboxManager =
(typeof import('@anthropic-ai/sandbox-runtime'))['SandboxManager']

Expand Down Expand Up @@ -120,6 +150,14 @@ export class SandboxedImageOptimizerWorker {
private nextId = 1
private pumping = false
private closed = false
private interrupted = false
private children = new Set<ChildProcess>()
private shutdown = () => {
this.interrupted = true
// Do not wait for graceful termination: next dev can force-kill the
// server before our normal SIGTERM-to-SIGKILL timer gets a chance to run.
for (const child of this.children) this.signal(child, 'SIGKILL')
}

constructor(options: WorkerOptions = {}) {
this.readAllowlist = options.readAllowlist?.slice()
Expand All @@ -134,12 +172,13 @@ export class SandboxedImageOptimizerWorker {
this.requestTimeoutMs = options.requestTimeoutMs
this.killGraceMs = options.killGraceMs ?? KILL_GRACE_MS
this.sandboxManager = options.sandboxManager
registerShutdown(this.shutdown)
}

runOperation(
operation: ImageOptimizerOperation
): Promise<ImageOptimizerOperationResult> {
if (this.closed) {
if (this.closed || this.interrupted) {
return Promise.reject(new Error('Image optimizer worker is closed'))
}

Expand Down Expand Up @@ -255,7 +294,7 @@ export class SandboxedImageOptimizerWorker {
}

private async spawnChild(): Promise<ChildProcess> {
if (this.closed) {
if (this.closed || this.interrupted) {
throw new Error('Image optimizer worker is closed')
}
const sandboxManager =
Expand All @@ -278,7 +317,7 @@ export class SandboxedImageOptimizerWorker {
undefined,
undefined
)
if (this.closed) {
if (this.closed || this.interrupted) {
throw new Error('Image optimizer worker is closed')
}

Expand All @@ -291,6 +330,12 @@ export class SandboxedImageOptimizerWorker {
}
const child = spawn(argv[0], argv.slice(1), spawnOptions)
this.child = child
this.children.add(child)
// Keep terminating workers tracked even after this.child is cleared.
child.once('exit', () => this.children.delete(child))
child.once('error', () => {
if (!child.pid) this.children.delete(child)
})

child.stdout?.pipe(process.stdout)
child.stderr?.pipe(process.stderr)
Expand Down Expand Up @@ -430,30 +475,34 @@ export class SandboxedImageOptimizerWorker {
return
}
this.closed = true
const closedError = new Error('Image optimizer worker is closed')
for (const operation of this.queue.splice(0)) {
operation.reject(closedError)
}
this.rejectActive(closedError)
try {
const closedError = new Error('Image optimizer worker is closed')
for (const operation of this.queue.splice(0)) {
operation.reject(closedError)
}
this.rejectActive(closedError)

let child = this.child
if (!child && this.childPromise) {
child = await this.childPromise.catch(() => undefined)
}
this.child = undefined
if (child && child.exitCode === null && child.signalCode === null) {
const exited = new Promise<void>((resolveExit) =>
child.once('exit', () => resolveExit())
)
this.terminate(child)
await exited
}
let child = this.child
if (!child && this.childPromise) {
child = await this.childPromise.catch(() => undefined)
}
this.child = undefined
if (child && child.exitCode === null && child.signalCode === null) {
const exited = new Promise<void>((resolveExit) =>
child.once('exit', () => resolveExit())
)
this.terminate(child)
await exited
}

await this.terminationPromise
this.terminationPromise = undefined
await this.terminationPromise
this.terminationPromise = undefined

this.sandboxManager?.cleanupAfterCommand()
await this.sandboxManager?.reset()
this.sandboxManager = undefined
this.sandboxManager?.cleanupAfterCommand()
await this.sandboxManager?.reset()
this.sandboxManager = undefined
} finally {
unregisterShutdown(this.shutdown)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
import { execFile, type ChildProcess } from 'child_process'
import { promisify } from 'util'
import { nextTestSetup } from 'e2e-utils'
import { findPort, retry } from 'next-test-utils'

const execFileAsync = promisify(execFile)

async function processTree(root: number): Promise<number[]> {
// Read host PIDs: the sandboxed worker sees different PIDs on Linux.
const { stdout } = await execFileAsync('ps', ['-A', '-o', 'pid=,ppid='])
const processes = stdout
.trim()
.split('\n')
.map((line) => line.trim().split(/\s+/).map(Number))
const tree = new Set([root])
for (const pid of tree) {
for (const [child, parent] of processes) {
if (parent === pid) tree.add(child)
}
}
return [...tree]
}

// @force-gate imageSandbox
describe('image optimizer shutdown', () => {
const { next } = nextTestSetup({ files: __dirname, skipStart: true })

it.each(['SIGINT', 'SIGTERM'] as const)(
'kills a stuck image worker when the server receives %s',
async (signal) => {
const port = await findPort()
let cli: ChildProcess | undefined
let output = ''
let imageProcessPid: number | undefined
let workerPids: number[] = []
let serverPid: number | undefined
const capture = (text: string) => {
output += text
const imageProcess = output.match(/IMAGE_PROCESS_PID:(\d+)/)
const server = output.match(/IMAGE_SERVER_PID:(\d+)/)
if (imageProcess) imageProcessPid = Number(imageProcess[1])
if (server) serverPid = Number(server[1])
}
const exited = next.runCommand(['dev', '--webpack', '-p', String(port)], {
instance: (child) => {
cli = child
},
onStdout: capture,
onStderr: capture,
})
let request: Promise<unknown> | undefined
try {
await retry(() => expect(output).toMatch(/Ready in/))
request = fetch(
`http://localhost:${port}/_next/image?url=%2Fimage.svg&w=64&q=75`
).catch(() => {})
await retry(() => {
expect(output).toMatch(/IMAGE_WORKER_STUCK:(\d+)/)
expect(output).toMatch(/IMAGE_SERVER_PID:(\d+)/)
expect(imageProcessPid).toBeDefined()
})
workerPids = await processTree(imageProcessPid!)
// Signal the CLI, which forwards the signal to the server. The hung
// worker cannot run either signal callbacks or disconnect handlers.
process.kill(cli!.pid!, signal)
await retry(() => {
for (const pid of workerPids) {
try {
process.kill(pid, 0)
} catch (error) {
// Permission denied is not evidence that the process exited.
expect(error).toMatchObject({ code: 'ESRCH' })
continue
}
throw new Error(`Image worker process ${pid} survived shutdown`)
}
})
await exited
await request
} finally {
// Also clean up if a readiness assertion failed before tree discovery.
if (!workerPids.length && imageProcessPid) {
workerPids = await processTree(imageProcessPid)
}
for (const pid of [...workerPids.reverse(), serverPid, cli?.pid]) {
if (!pid) continue
try {
process.kill(pid, 'SIGKILL')
} catch {}
}
await exited
await request
}
}
)
})
23 changes: 23 additions & 0 deletions test/development/image-optimizer-shutdown/next.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const {
SandboxedImageOptimizerWorker,
} = require('next/dist/server/image-optimizer/sandbox-worker')

// Use the real launcher, IPC and sandbox, but replace the transform with a
// permanently blocked event loop. No production testing hooks are needed.
const original = SandboxedImageOptimizerWorker.prototype.runOperation
const spawnChild = SandboxedImageOptimizerWorker.prototype.spawnChild
SandboxedImageOptimizerWorker.prototype.spawnChild = async function () {
const child = await spawnChild.call(this)
console.log(`IMAGE_PROCESS_PID:${child.pid}`)
return child
}
SandboxedImageOptimizerWorker.prototype.runOperation = function (operation) {
this.workerPath = require.resolve('./stuck-worker.js')
console.log(`IMAGE_SERVER_PID:${process.pid}`)
return original.call(this, operation)
}

module.exports = {
experimental: { imgOptWorker: true },
images: { dangerouslyAllowSVG: true },
}
3 changes: 3 additions & 0 deletions test/development/image-optimizer-shutdown/pages/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export default function Page() {
return <p>hello world</p>
}
1 change: 1 addition & 0 deletions test/development/image-optimizer-shutdown/public/image.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 changes: 9 additions & 0 deletions test/development/image-optimizer-shutdown/stuck-worker.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const { writeSync } = require('fs')

process.on('SIGTERM', () => {})
process.on('message', () => {
writeSync(1, `IMAGE_WORKER_STUCK:${process.pid}\n`)
// Block signal callbacks and IPC-disconnect handling, not just the request.
for (;;) {}
})
process.on('disconnect', () => process.exit(0))
8 changes: 8 additions & 0 deletions test/unit/image-optimizer/fixtures/sandbox-worker-signal.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const {
SandboxedImageOptimizerWorker,
} = require('next/dist/server/image-optimizer/sandbox-worker')

new SandboxedImageOptimizerWorker()
process.kill(process.pid, process.argv[2])
// The worker's cleanup handler must not swallow default signal termination.
setInterval(() => {}, 1000)
Loading
Loading