Skip to content

Commit bd77046

Browse files
committed
Enable image subprocesses by default on supported hosts
1 parent 8553bae commit bd77046

9 files changed

Lines changed: 201 additions & 13 deletions

File tree

‎packages/next/src/server/config-shared.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -641,6 +641,7 @@ export interface ExperimentalConfig {
641641
imgOptMaxInputPixels?: number
642642
imgOptSequentialRead?: boolean | null
643643
imgOptMozjpeg?: boolean
644+
/** Defaults to sandboxed subprocesses when host tools and OS permissions support them. */
644645
imgOptWorker?: boolean
645646
/**
646647
* Replaces the sandboxed image worker's default trusted runtime directories.
@@ -2413,7 +2414,7 @@ export const defaultConfig = Object.freeze({
24132414
imgOptMaxInputPixels: 268_402_689, // https://sharp.pixelplumbing.com/api-constructor#:~:text=%5Boptions.limitInputPixels%5D
24142415
imgOptSequentialRead: null,
24152416
imgOptMozjpeg: true,
2416-
imgOptWorker: false,
2417+
imgOptWorker: undefined,
24172418
isrFlushToDisk: true,
24182419
workerThreads: false,
24192420
proxyTimeout: undefined,

‎packages/next/src/server/config.ts‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1782,10 +1782,15 @@ function assignDefaultsAndValidate(
17821782
* consumers don't each need to know the current framework default (which may
17831783
* evolve over time).
17841784
*/
1785-
function finalizeConfig(
1785+
async function finalizeConfig(
17861786
config: NextConfigComplete,
17871787
bundler: Bundler | undefined
1788-
): NextConfigComplete {
1788+
): Promise<NextConfigComplete> {
1789+
if (config.experimental.imgOptWorker === true) {
1790+
const { resolveImageOptimizerWorker } =
1791+
require('./image-optimizer/sandbox-support') as typeof import('./image-optimizer/sandbox-support')
1792+
await resolveImageOptimizerWorker(true)
1793+
}
17891794
config.experimental.instantInsights = {
17901795
validationLevel:
17911796
config.experimental.instantInsights?.validationLevel ?? 'warning',
@@ -2043,7 +2048,7 @@ async function loadConfigImpl(
20432048
// Check deprecation warnings on the custom config before merging with defaults
20442049
checkDeprecations(customConfig as NextConfig, configFileName, silent, dir)
20452050

2046-
const config = finalizeConfig(
2051+
const config = await finalizeConfig(
20472052
await applyModifyConfig(
20482053
assignDefaultsAndValidate(
20492054
dir,
@@ -2282,7 +2287,7 @@ async function loadConfigImpl(
22822287
phase
22832288
)
22842289

2285-
const finalConfig = finalizeConfig(
2290+
const finalConfig = await finalizeConfig(
22862291
await applyModifyConfig(completeConfig, phase, silent, dir),
22872292
bundler
22882293
)
@@ -2355,7 +2360,7 @@ async function loadConfigImpl(
23552360

23562361
setHttpClientAndAgentOptions(completeConfig)
23572362

2358-
const finalConfig = finalizeConfig(
2363+
const finalConfig = await finalizeConfig(
23592364
await applyModifyConfig(completeConfig, phase, silent, dir),
23602365
bundler
23612366
)
Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import { execFile } from 'child_process'
2+
import { promisify } from 'util'
3+
4+
const execFileAsync = promisify(execFile)
5+
let supportCheck: Promise<string | undefined> | undefined
6+
7+
async function checkSupport(): Promise<string | undefined> {
8+
if (process.platform !== 'darwin' && process.platform !== 'linux') {
9+
return `unsupported platform ${process.platform}`
10+
}
11+
try {
12+
const { SandboxManager } = await import(
13+
/* webpackIgnore: true */ /* turbopackIgnore: true */
14+
'@anthropic-ai/sandbox-runtime'
15+
)
16+
const { errors } = SandboxManager.checkDependencies()
17+
if (errors.length) return errors.join(', ')
18+
19+
// Installed tools alone are insufficient: containers may forbid namespaces
20+
// or sandbox creation. Probe only trusted OS code, never an input image.
21+
const command =
22+
process.platform === 'darwin' ? '/usr/bin/sandbox-exec' : 'bwrap'
23+
const args =
24+
process.platform === 'darwin'
25+
? ['-p', '(version 1)(allow default)', '/usr/bin/true']
26+
: [
27+
'--ro-bind',
28+
'/',
29+
'/',
30+
'--unshare-all',
31+
'--die-with-parent',
32+
'--proc',
33+
'/proc',
34+
'--dev',
35+
'/dev',
36+
'/bin/true',
37+
]
38+
await execFileAsync(command, args, { timeout: 5000, killSignal: 'SIGKILL' })
39+
return undefined
40+
} catch {
41+
return 'sandbox prerequisites or OS permissions are unavailable'
42+
}
43+
}
44+
45+
export async function resolveImageOptimizerWorker(
46+
requested: boolean | undefined,
47+
check = () => (supportCheck ??= checkSupport())
48+
): Promise<boolean> {
49+
if (requested === false) return false
50+
const reason = await check()
51+
if (!reason) return true
52+
if (requested === true) {
53+
throw new Error(`experimental.imgOptWorker cannot be enabled: ${reason}`)
54+
}
55+
return false
56+
}

‎packages/next/src/server/image-optimizer/sandbox-worker-policy.ts‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,13 @@ export function getImageOptimizerSandboxConfig(
5252
addPath('/bin/sh')
5353
addPath('/usr/bin/env')
5454
addPath(workerPath)
55-
// In a source checkout Next itself is outside node_modules.
56-
const nextPackageRoot = resolve(__dirname, '..', '..', '..')
57-
addPath(join(nextPackageRoot, 'dist'))
58-
addPath(join(nextPackageRoot, 'package.json'))
55+
// Repository development opts into reading the checkout's build output.
56+
// Installed applications must not receive this additional allowance.
57+
if (process.env.NEXT_PRIVATE_LOCAL_DEV) {
58+
const nextPackageRoot = resolve(__dirname, '..', '..', '..')
59+
addPath(join(nextPackageRoot, 'dist'))
60+
addPath(join(nextPackageRoot, 'package.json'))
61+
}
5962

6063
// Preserve Node resolution, including pnpm's physical store paths, without
6164
// granting the surrounding project or home directory.

‎packages/next/src/server/next-server.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -197,6 +197,7 @@ export default class NextNodeServer extends BaseServer<
197197
private imageResponseCache?: ResponseCache
198198
private imageCacheHandler?: ICacheHandler
199199
private imageOptimizerWorker?: import('./image-optimizer/sandbox-worker').SandboxedImageOptimizerWorker
200+
private imageOptimizerWorkerEnabled = false
200201
protected renderWorkersPromises?: Promise<void>
201202
protected dynamicRoutes?: {
202203
match: import('../shared/lib/router/utils/route-matcher').RouteMatchFn
@@ -390,6 +391,13 @@ export default class NextNodeServer extends BaseServer<
390391

391392
protected async prepareImpl() {
392393
await super.prepareImpl()
394+
if (this.nextConfig.experimental.imgOptWorker !== false) {
395+
const { resolveImageOptimizerWorker } =
396+
require('./image-optimizer/sandbox-support') as typeof import('./image-optimizer/sandbox-support')
397+
this.imageOptimizerWorkerEnabled = await resolveImageOptimizerWorker(
398+
this.nextConfig.experimental.imgOptWorker
399+
)
400+
}
393401
await this.runInstrumentationHookIfAvailable()
394402
}
395403

@@ -803,7 +811,7 @@ export default class NextNodeServer extends BaseServer<
803811
let runOperation:
804812
| import('./image-optimizer').ImageOptimizerOperationRunner
805813
| undefined
806-
if (this.nextConfig.experimental.imgOptWorker) {
814+
if (this.imageOptimizerWorkerEnabled) {
807815
if (!this.imageOptimizerWorker) {
808816
const { SandboxedImageOptimizerWorker } =
809817
require('./image-optimizer/sandbox-worker') as typeof import('./image-optimizer/sandbox-worker')

‎test/e2e/image-optimizer/sharp.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
11
import { setupTests } from './util'
22

3-
describe('with latest sharp', () => {
3+
describe('with default image worker selection', () => {
44
setupTests({})
55
})
66

7+
describe('with image subprocesses disabled', () => {
8+
setupTests({ nextConfigExperimental: { imgOptWorker: false } })
9+
})
10+
711
// @force-gate imageSandbox
812
describe('with sandboxed sharp', () => {
913
setupTests({ nextConfigExperimental: { imgOptWorker: true } })

‎test/unit/image-optimizer/fixtures/sandbox-worker-integration.js‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ function operation(href, buffer = Buffer.from('image')) {
3535
}
3636

3737
async function main() {
38+
delete process.env.NEXT_PRIVATE_LOCAL_DEV
3839
let server
3940
const homeProbeDirectory = fs.mkdtempSync(
4041
path.join(os.homedir(), '.next-image-sandbox-')
@@ -94,6 +95,9 @@ async function main() {
9495
`/read?path=${encodeURIComponent(require.resolve('next/package.json'))}`
9596
)
9697
)
98+
const readCheckout = await probeRead(
99+
path.join(projectRoot, 'packages/next/dist/server/config.js')
100+
)
97101
const libraries = await Promise.all(
98102
libraryNames.map((name) => probeRead(path.join(homeProbeDirectory, name)))
99103
)
@@ -173,6 +177,8 @@ async function main() {
173177
const customOutsideRead = await probeRead(envFile)
174178

175179
await worker.close()
180+
// The transform worker executes Next directly from its source checkout.
181+
process.env.NEXT_PRIVATE_LOCAL_DEV = '1'
176182
worker = new SandboxedImageOptimizerWorker()
177183
const image = fs.readFileSync(
178184
path.join(projectRoot, 'test/unit/image-optimizer/images/test.png')
@@ -185,6 +191,7 @@ async function main() {
185191
readHome: readHome.diagnostics[0].message,
186192
readApplication: readApplication.diagnostics[0].message,
187193
readDependency: readDependency.diagnostics[0].message,
194+
readCheckout,
188195
libraries,
189196
customRead,
190197
customOutsideRead,
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
const loadConfig = require('next/dist/server/config').default
2+
const {
3+
resolveImageOptimizerWorker,
4+
} = require('next/dist/server/image-optimizer/sandbox-support')
5+
6+
// Simulate an unsupported host without requiring a Windows test runner.
7+
Object.defineProperty(process, 'platform', { value: 'win32' })
8+
const requested = process.argv[2]
9+
loadConfig('phase-test', __dirname, {
10+
customConfig: {
11+
experimental: {
12+
imgOptWorker: requested === 'auto' ? undefined : requested === 'true',
13+
},
14+
},
15+
})
16+
.then(async (config) => {
17+
console.log(
18+
`WORKER_ENABLED=${await resolveImageOptimizerWorker(config.experimental.imgOptWorker)}`
19+
)
20+
})
21+
.catch((error) => {
22+
console.error(error.message)
23+
process.exitCode = 1
24+
})

‎test/unit/image-optimizer/sandbox-worker.test.ts‎

Lines changed: 81 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
SandboxedImageOptimizerWorker,
1010
} from 'next/dist/server/image-optimizer/sandbox-worker'
1111
import type { ImageOptimizerOperation } from 'next/dist/server/image-optimizer/operation'
12+
import { resolveImageOptimizerWorker } from 'next/dist/server/image-optimizer/sandbox-support'
1213
import {
1314
defaultConfig,
1415
getNextConfigRuntime,
@@ -79,6 +80,65 @@ describe('SandboxedImageOptimizerWorker', () => {
7980
worker = undefined
8081
})
8182

83+
it('enables subprocesses by default when sandboxing is supported', async () => {
84+
await expect(
85+
resolveImageOptimizerWorker(undefined, async () => undefined)
86+
).resolves.toBe(true)
87+
})
88+
89+
it('disables subprocesses without probing when explicitly opted out', async () => {
90+
const check = jest.fn()
91+
await expect(resolveImageOptimizerWorker(false, check)).resolves.toBe(false)
92+
expect(check).not.toHaveBeenCalled()
93+
})
94+
95+
it.each([
96+
'unsupported platform win32',
97+
'bubblewrap not installed',
98+
'sandbox creation denied',
99+
])('only auto mode falls back when %s', async (reason) => {
100+
const check = async () => reason
101+
await expect(resolveImageOptimizerWorker(undefined, check)).resolves.toBe(
102+
false
103+
)
104+
await expect(resolveImageOptimizerWorker(true, check)).rejects.toThrow(
105+
`experimental.imgOptWorker cannot be enabled: ${reason}`
106+
)
107+
})
108+
109+
it('enables explicitly requested subprocesses when supported', async () => {
110+
await expect(
111+
resolveImageOptimizerWorker(true, async () => undefined)
112+
).resolves.toBe(true)
113+
})
114+
115+
it.each(['auto', 'false'])(
116+
'starts with subprocesses disabled on an unsupported host (%s)',
117+
async (requested) => {
118+
const { stdout } = await execFileAsync(
119+
process.execPath,
120+
[join(__dirname, 'fixtures/sandbox-worker-unsupported.js'), requested],
121+
{ timeout: 10000 }
122+
)
123+
expect(stdout).toContain('WORKER_ENABLED=false')
124+
}
125+
)
126+
127+
it('fails config loading when subprocesses are explicitly enabled on an unsupported host', async () => {
128+
await expect(
129+
execFileAsync(
130+
process.execPath,
131+
[join(__dirname, 'fixtures/sandbox-worker-unsupported.js'), 'true'],
132+
{ timeout: 10000 }
133+
)
134+
).rejects.toMatchObject({
135+
code: 1,
136+
stderr: expect.stringContaining(
137+
'experimental.imgOptWorker cannot be enabled: unsupported platform win32'
138+
),
139+
})
140+
})
141+
82142
it('shares shutdown listeners and removes them when workers close', async () => {
83143
const listenerCounts = () => [
84144
process.listeners('SIGINT').length,
@@ -175,6 +235,25 @@ describe('SandboxedImageOptimizerWorker', () => {
175235
expect(config.filesystem.denyRead).toEqual(['/'])
176236
})
177237

238+
it('only grants the source checkout allowance during local development', () => {
239+
const previous = process.env.NEXT_PRIVATE_LOCAL_DEV
240+
const dist = join(__dirname, '../../../packages/next/dist')
241+
const packageJson = join(dist, '../package.json')
242+
try {
243+
delete process.env.NEXT_PRIVATE_LOCAL_DEV
244+
const normal = getImageOptimizerSandboxConfig(fixtureWorker)
245+
expect(normal.filesystem.allowRead).not.toContain(dist)
246+
expect(normal.filesystem.allowRead).not.toContain(packageJson)
247+
process.env.NEXT_PRIVATE_LOCAL_DEV = '1'
248+
const local = getImageOptimizerSandboxConfig(fixtureWorker)
249+
expect(local.filesystem.allowRead).toContain(dist)
250+
expect(local.filesystem.allowRead).toContain(packageJson)
251+
} finally {
252+
if (previous === undefined) delete process.env.NEXT_PRIVATE_LOCAL_DEV
253+
else process.env.NEXT_PRIVATE_LOCAL_DEV = previous
254+
}
255+
})
256+
178257
it.each(['relative/path', '/tmp/*', '/tmp/[abc]', '/tmp/file?'])(
179258
'rejects ambiguous read allowance %s',
180259
(path) => {
@@ -276,7 +355,8 @@ describe('SandboxedImageOptimizerWorker', () => {
276355
read: expect.stringMatching(/^read-blocked:/),
277356
readHome: expect.stringMatching(/^read-blocked:/),
278357
readApplication: expect.stringMatching(/^read-blocked:/),
279-
readDependency: 'read-allowed',
358+
readDependency: expect.stringMatching(/^read-blocked:/),
359+
readCheckout: expect.stringMatching(/^read-blocked:/),
280360
libraries: Array(6).fill(expect.stringMatching(/^read-blocked:/)),
281361
customRead: 'read-allowed',
282362
customOutsideRead: expect.stringMatching(/^read-blocked:/),

0 commit comments

Comments
 (0)