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
3 changes: 3 additions & 0 deletions packages/next/src/build/collect-build-traces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,9 @@ export async function collectBuildTraces({

const standaloneImageOptimizerEntries = isStandalone
? [
require.resolve(
'next/dist/server/image-optimizer/sandbox-support'
),
require.resolve('next/dist/server/image-optimizer/sandbox-worker'),
require.resolve(
'next/dist/server/image-optimizer/sandbox-worker-child'
Expand Down
3 changes: 2 additions & 1 deletion packages/next/src/server/config-shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -641,6 +641,7 @@ export interface ExperimentalConfig {
imgOptMaxInputPixels?: number
imgOptSequentialRead?: boolean | null
imgOptMozjpeg?: boolean
/** Defaults to sandboxed subprocesses when host tools and OS permissions support them. */
imgOptWorker?: boolean
/**
* Replaces the sandboxed image worker's default trusted runtime directories.
Expand Down Expand Up @@ -2413,7 +2414,7 @@ export const defaultConfig = Object.freeze({
imgOptMaxInputPixels: 268_402_689, // https://sharp.pixelplumbing.com/api-constructor#:~:text=%5Boptions.limitInputPixels%5D
imgOptSequentialRead: null,
imgOptMozjpeg: true,
imgOptWorker: false,
imgOptWorker: undefined,
isrFlushToDisk: true,
workerThreads: false,
proxyTimeout: undefined,
Expand Down
15 changes: 10 additions & 5 deletions packages/next/src/server/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1782,10 +1782,15 @@ function assignDefaultsAndValidate(
* consumers don't each need to know the current framework default (which may
* evolve over time).
*/
function finalizeConfig(
async function finalizeConfig(
config: NextConfigComplete,
bundler: Bundler | undefined
): NextConfigComplete {
): Promise<NextConfigComplete> {
if (config.experimental.imgOptWorker === true) {
const { resolveImageOptimizerWorker } =
require('./image-optimizer/sandbox-support') as typeof import('./image-optimizer/sandbox-support')
await resolveImageOptimizerWorker(true)
}
config.experimental.instantInsights = {
validationLevel:
config.experimental.instantInsights?.validationLevel ?? 'warning',
Expand Down Expand Up @@ -2043,7 +2048,7 @@ async function loadConfigImpl(
// Check deprecation warnings on the custom config before merging with defaults
checkDeprecations(customConfig as NextConfig, configFileName, silent, dir)

const config = finalizeConfig(
const config = await finalizeConfig(
await applyModifyConfig(
assignDefaultsAndValidate(
dir,
Expand Down Expand Up @@ -2282,7 +2287,7 @@ async function loadConfigImpl(
phase
)

const finalConfig = finalizeConfig(
const finalConfig = await finalizeConfig(
await applyModifyConfig(completeConfig, phase, silent, dir),
bundler
)
Expand Down Expand Up @@ -2355,7 +2360,7 @@ async function loadConfigImpl(

setHttpClientAndAgentOptions(completeConfig)

const finalConfig = finalizeConfig(
const finalConfig = await finalizeConfig(
await applyModifyConfig(completeConfig, phase, silent, dir),
bundler
)
Expand Down
56 changes: 56 additions & 0 deletions packages/next/src/server/image-optimizer/sandbox-support.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { execFile } from 'child_process'
import { promisify } from 'util'

const execFileAsync = promisify(execFile)
let supportCheck: Promise<string | undefined> | undefined

async function checkSupport(): Promise<string | undefined> {
if (process.platform !== 'darwin' && process.platform !== 'linux') {
return `unsupported platform ${process.platform}`
}
try {
const { SandboxManager } = await import(
/* webpackIgnore: true */ /* turbopackIgnore: true */
'@anthropic-ai/sandbox-runtime'
)
const { errors } = SandboxManager.checkDependencies()
if (errors.length) return errors.join(', ')

// Installed tools alone are insufficient: containers may forbid namespaces
// or sandbox creation. Probe only trusted OS code, never an input image.
const command =
process.platform === 'darwin' ? '/usr/bin/sandbox-exec' : 'bwrap'
const args =
process.platform === 'darwin'
? ['-p', '(version 1)(allow default)', '/usr/bin/true']
: [
'--ro-bind',
'/',
'/',
'--unshare-all',
'--die-with-parent',
'--proc',
'/proc',
'--dev',
'/dev',
'/bin/true',
]
await execFileAsync(command, args, { timeout: 5000, killSignal: 'SIGKILL' })
return undefined
} catch {
return 'sandbox prerequisites or OS permissions are unavailable'
}
}

export async function resolveImageOptimizerWorker(
requested: boolean | undefined,
check = () => (supportCheck ??= checkSupport())
): Promise<boolean> {
if (requested === false) return false
const reason = await check()
if (!reason) return true
if (requested === true) {
throw new Error(`experimental.imgOptWorker cannot be enabled: ${reason}`)
}
return false
}
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,13 @@ export function getImageOptimizerSandboxConfig(
addPath('/bin/sh')
addPath('/usr/bin/env')
addPath(workerPath)
// In a source checkout Next itself is outside node_modules.
const nextPackageRoot = resolve(__dirname, '..', '..', '..')
addPath(join(nextPackageRoot, 'dist'))
addPath(join(nextPackageRoot, 'package.json'))
// Repository development opts into reading the checkout's build output.
// Installed applications must not receive this additional allowance.
if (process.env.NEXT_PRIVATE_LOCAL_DEV) {
const nextPackageRoot = resolve(__dirname, '..', '..', '..')
addPath(join(nextPackageRoot, 'dist'))
addPath(join(nextPackageRoot, 'package.json'))
}

// Preserve Node resolution, including pnpm's physical store paths, without
// granting the surrounding project or home directory.
Expand Down
18 changes: 15 additions & 3 deletions packages/next/src/server/next-server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ export default class NextNodeServer extends BaseServer<
private imageResponseCache?: ResponseCache
private imageCacheHandler?: ICacheHandler
private imageOptimizerWorker?: import('./image-optimizer/sandbox-worker').SandboxedImageOptimizerWorker
private imageOptimizerWorkerEnabled = false
protected renderWorkersPromises?: Promise<void>
protected dynamicRoutes?: {
match: import('../shared/lib/router/utils/route-matcher').RouteMatchFn
Expand Down Expand Up @@ -390,6 +391,15 @@ export default class NextNodeServer extends BaseServer<

protected async prepareImpl() {
await super.prepareImpl()
if (this.nextConfig.experimental.imgOptWorker !== false) {
const { resolveImageOptimizerWorker } = await import(
/* webpackIgnore: true */ /* turbopackIgnore: true */
'./image-optimizer/sandbox-support.js'
)
this.imageOptimizerWorkerEnabled = await resolveImageOptimizerWorker(
this.nextConfig.experimental.imgOptWorker
)
}
await this.runInstrumentationHookIfAvailable()
}

Expand Down Expand Up @@ -803,10 +813,12 @@ export default class NextNodeServer extends BaseServer<
let runOperation:
| import('./image-optimizer').ImageOptimizerOperationRunner
| undefined
if (this.nextConfig.experimental.imgOptWorker) {
if (this.imageOptimizerWorkerEnabled) {
if (!this.imageOptimizerWorker) {
const { SandboxedImageOptimizerWorker } =
require('./image-optimizer/sandbox-worker') as typeof import('./image-optimizer/sandbox-worker')
const { SandboxedImageOptimizerWorker } = await import(
/* webpackIgnore: true */ /* turbopackIgnore: true */
'./image-optimizer/sandbox-worker.js'
)
this.imageOptimizerWorker = new SandboxedImageOptimizerWorker({
readAllowlist:
this.nextConfig.experimental.imgOptWorkerReadAllowlist,
Expand Down
6 changes: 5 additions & 1 deletion test/e2e/image-optimizer/sharp.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import { setupTests } from './util'

describe('with latest sharp', () => {
describe('with default image worker selection', () => {
setupTests({})
})

describe('with image subprocesses disabled', () => {
setupTests({ nextConfigExperimental: { imgOptWorker: false } })
})

// @force-gate imageSandbox
describe('with sandboxed sharp', () => {
setupTests({ nextConfigExperimental: { imgOptWorker: true } })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ function operation(href, buffer = Buffer.from('image')) {
}

async function main() {
delete process.env.NEXT_PRIVATE_LOCAL_DEV
let server
const homeProbeDirectory = fs.mkdtempSync(
path.join(os.homedir(), '.next-image-sandbox-')
Expand Down Expand Up @@ -94,6 +95,9 @@ async function main() {
`/read?path=${encodeURIComponent(require.resolve('next/package.json'))}`
)
)
const readCheckout = await probeRead(
path.join(projectRoot, 'packages/next/dist/server/config.js')
)
const libraries = await Promise.all(
libraryNames.map((name) => probeRead(path.join(homeProbeDirectory, name)))
)
Expand Down Expand Up @@ -173,6 +177,8 @@ async function main() {
const customOutsideRead = await probeRead(envFile)

await worker.close()
// The transform worker executes Next directly from its source checkout.
process.env.NEXT_PRIVATE_LOCAL_DEV = '1'
worker = new SandboxedImageOptimizerWorker()
const image = fs.readFileSync(
path.join(projectRoot, 'test/unit/image-optimizer/images/test.png')
Expand All @@ -185,6 +191,7 @@ async function main() {
readHome: readHome.diagnostics[0].message,
readApplication: readApplication.diagnostics[0].message,
readDependency: readDependency.diagnostics[0].message,
readCheckout,
libraries,
customRead,
customOutsideRead,
Expand Down
24 changes: 24 additions & 0 deletions test/unit/image-optimizer/fixtures/sandbox-worker-unsupported.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const loadConfig = require('next/dist/server/config').default
const {
resolveImageOptimizerWorker,
} = require('next/dist/server/image-optimizer/sandbox-support')

// Simulate an unsupported host without requiring a Windows test runner.
Object.defineProperty(process, 'platform', { value: 'win32' })
const requested = process.argv[2]
loadConfig('phase-test', __dirname, {
customConfig: {
experimental: {
imgOptWorker: requested === 'auto' ? undefined : requested === 'true',
},
},
})
.then(async (config) => {
console.log(
`WORKER_ENABLED=${await resolveImageOptimizerWorker(config.experimental.imgOptWorker)}`
)
})
.catch((error) => {
console.error(error.message)
process.exitCode = 1
})
82 changes: 81 additions & 1 deletion test/unit/image-optimizer/sandbox-worker.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
SandboxedImageOptimizerWorker,
} from 'next/dist/server/image-optimizer/sandbox-worker'
import type { ImageOptimizerOperation } from 'next/dist/server/image-optimizer/operation'
import { resolveImageOptimizerWorker } from 'next/dist/server/image-optimizer/sandbox-support'
import {
defaultConfig,
getNextConfigRuntime,
Expand Down Expand Up @@ -79,6 +80,65 @@ describe('SandboxedImageOptimizerWorker', () => {
worker = undefined
})

it('enables subprocesses by default when sandboxing is supported', async () => {
await expect(
resolveImageOptimizerWorker(undefined, async () => undefined)
).resolves.toBe(true)
})

it('disables subprocesses without probing when explicitly opted out', async () => {
const check = jest.fn()
await expect(resolveImageOptimizerWorker(false, check)).resolves.toBe(false)
expect(check).not.toHaveBeenCalled()
})

it.each([
'unsupported platform win32',
'bubblewrap not installed',
'sandbox creation denied',
])('only auto mode falls back when %s', async (reason) => {
const check = async () => reason
await expect(resolveImageOptimizerWorker(undefined, check)).resolves.toBe(
false
)
await expect(resolveImageOptimizerWorker(true, check)).rejects.toThrow(
`experimental.imgOptWorker cannot be enabled: ${reason}`
)
})

it('enables explicitly requested subprocesses when supported', async () => {
await expect(
resolveImageOptimizerWorker(true, async () => undefined)
).resolves.toBe(true)
})

it.each(['auto', 'false'])(
'starts with subprocesses disabled on an unsupported host (%s)',
async (requested) => {
const { stdout } = await execFileAsync(
process.execPath,
[join(__dirname, 'fixtures/sandbox-worker-unsupported.js'), requested],
{ timeout: 10000 }
)
expect(stdout).toContain('WORKER_ENABLED=false')
}
)

it('fails config loading when subprocesses are explicitly enabled on an unsupported host', async () => {
await expect(
execFileAsync(
process.execPath,
[join(__dirname, 'fixtures/sandbox-worker-unsupported.js'), 'true'],
{ timeout: 10000 }
)
).rejects.toMatchObject({
code: 1,
stderr: expect.stringContaining(
'experimental.imgOptWorker cannot be enabled: unsupported platform win32'
),
})
})

it('shares shutdown listeners and removes them when workers close', async () => {
const listenerCounts = () => [
process.listeners('SIGINT').length,
Expand Down Expand Up @@ -175,6 +235,25 @@ describe('SandboxedImageOptimizerWorker', () => {
expect(config.filesystem.denyRead).toEqual(['/'])
})

it('only grants the source checkout allowance during local development', () => {
const previous = process.env.NEXT_PRIVATE_LOCAL_DEV
const dist = join(__dirname, '../../../packages/next/dist')
const packageJson = join(dist, '../package.json')
try {
delete process.env.NEXT_PRIVATE_LOCAL_DEV
const normal = getImageOptimizerSandboxConfig(fixtureWorker)
expect(normal.filesystem.allowRead).not.toContain(dist)
expect(normal.filesystem.allowRead).not.toContain(packageJson)
process.env.NEXT_PRIVATE_LOCAL_DEV = '1'
const local = getImageOptimizerSandboxConfig(fixtureWorker)
expect(local.filesystem.allowRead).toContain(dist)
expect(local.filesystem.allowRead).toContain(packageJson)
} finally {
if (previous === undefined) delete process.env.NEXT_PRIVATE_LOCAL_DEV
else process.env.NEXT_PRIVATE_LOCAL_DEV = previous
}
})

it.each(['relative/path', '/tmp/*', '/tmp/[abc]', '/tmp/file?'])(
'rejects ambiguous read allowance %s',
(path) => {
Expand Down Expand Up @@ -276,7 +355,8 @@ describe('SandboxedImageOptimizerWorker', () => {
read: expect.stringMatching(/^read-blocked:/),
readHome: expect.stringMatching(/^read-blocked:/),
readApplication: expect.stringMatching(/^read-blocked:/),
readDependency: 'read-allowed',
readDependency: expect.stringMatching(/^read-blocked:/),
readCheckout: expect.stringMatching(/^read-blocked:/),
libraries: Array(6).fill(expect.stringMatching(/^read-blocked:/)),
customRead: 'read-allowed',
customOutsideRead: expect.stringMatching(/^read-blocked:/),
Expand Down
Loading