Skip to content
Merged
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
5 changes: 5 additions & 0 deletions docs/recipe-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,11 @@ subpath that resolves outside the root through a symlink is rejected. Without a
containing `sourceRoot`, the plugin directory is the boundary.
Escaping, dangling, and cyclic symlinks are skipped and reported in runtime evidence.

On Playground, caller-owned plugin directories are staged so runtime writes do
not change the source. ZIP plugins extracted into a run-owned tree of regular
files and directories mount directly from that tree, which is discarded after
runtime teardown. ZIPs containing symlinks still use readonly staging.

External HTTPS zip downloads are gated by `WP_CODEBOX_ALLOW_NETWORK_DOWNLOADS=1`.
Local paths are resolved relative to the recipe file.

Expand Down
16 changes: 11 additions & 5 deletions packages/cli/src/commands/recipe-run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,14 +235,14 @@ export async function runRecipe(options: RecipeRunOptions, interruption?: Recipe
await managedServices.release()
managedServicesReleased = true
}
let runtimeDestroyed = false
let runtimeDestruction: Promise<void> | undefined
const destroyActiveRuntime = async (): Promise<void> => {
if (!runtime || runtimeDestroyed) {
if (!runtime || runtimeDestruction) {
return
}

runtimeDestroyed = true
await bestEffortTimeout(runtime.destroy(), 2_000)
runtimeDestruction = runtime.destroy()
await bestEffortTimeout(runtimeDestruction, 2_000)
}
const phaseExecutor = new RecipeRunPhaseExecutor({ context, timeoutMs: options.timeoutMs, interruption, destroyActiveRuntime })
const phaseTracker = phaseExecutor.tracker
Expand Down Expand Up @@ -647,7 +647,13 @@ export async function runRecipe(options: RecipeRunOptions, interruption?: Recipe

cleanupEvidence = await runManagedServiceCleanup(runRegistry, runRecord, serviceEvidence, true, async () => {
await releaseManagedServices()
await cleanupRecipePreparedSources(workspaceMounts, extraPlugins, stagedFiles, overlays, dependencyOverlays, extraThemes)
const disposablePlugins = runtimeDestruction ? extraPlugins.filter((plugin) => plugin.disposableExtraction) : []
if (disposablePlugins.length > 0 && runtimeDestruction) {
// The best-effort shutdown wait may time out while Playground still has these mounts open.
const cleanup = () => cleanupRecipePreparedSources([], disposablePlugins)
await bestEffortTimeout(runtimeDestruction.then(cleanup, cleanup), 2_000)
}
await cleanupRecipePreparedSources(workspaceMounts, extraPlugins.filter((plugin) => !disposablePlugins.includes(plugin)), stagedFiles, overlays, dependencyOverlays, extraThemes)
await cleanupInputMountBaselines(inputMountBaselinePaths)
})
runRecord = await runRegistry.read(runRecord.runId)
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/commands/recipe-runtime-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,7 @@ function preparedExtraPluginMounts(plugins: PreparedExtraPlugin[]): MountSpec[]
type: "directory",
source: plugin.source,
...(plugin.sourceRoot !== undefined ? { sourceRoot: plugin.sourceRoot } : {}),
...(plugin.disposableExtraction ? { sourceOwnership: "run-disposable" as const } : {}),
target: plugin.target,
mode: "readonly",
...(plugin.metadata?.phase === "pre-install" ? { phase: "pre-install" as const } : {}),
Expand Down
6 changes: 6 additions & 0 deletions packages/cli/src/recipe-sources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,15 @@ export interface RecipeSourceProvenance {
}

interface PreparedExternalSource {
disposableExtraction?: boolean
source: string
sourceRoot?: string
cleanupPaths: string[]
provenance: RecipeSourceProvenance
}

export interface PreparedExtraPlugin {
disposableExtraction?: boolean
source: string
sourceRoot?: string
slug: string
Expand Down Expand Up @@ -320,6 +322,7 @@ export async function prepareExtraPlugins(plugins: readonly WorkspaceRecipeExtra
const prepared = await prepareComposerAutoloadForPlugin(pluginResolved, slug, sourceRef, plugin.composer, resolved.source)
await assertPreparedPluginFileExists(prepared.source, pluginFile.slice(slug.length + 1), sourceRef)
preparedPlugins.push({
...(resolved.disposableExtraction && prepared.source === pluginResolved.source ? { disposableExtraction: true } : {}),
source: prepared.source,
...(prepared.sourceRoot !== undefined ? { sourceRoot: prepared.sourceRoot } : {}),
slug,
Expand Down Expand Up @@ -981,6 +984,7 @@ async function preserveComposerDependencyReference(consumer: PreparedExtraPlugin
await cp(copyRoot, stagedRoot, { recursive: true, verbatimSymlinks: consumer.sourceRoot !== undefined })
if (consumer.sourceRoot !== undefined) await assertExtraPluginSourceWithinRoot(stagedSource, stagedRoot)
consumer.source = stagedSource
delete consumer.disposableExtraction
if (consumer.sourceRoot !== undefined) consumer.sourceRoot = stagedRoot
stagedConsumers.add(consumer)
}
Expand Down Expand Up @@ -1749,6 +1753,7 @@ async function prepareRecipeSource(sourceRef: string, recipeDirectory: string, s
const preparedZip = await prepareLocalZipSource(localPath, slug, source.expectedSha256)
return {
source: await extractedPluginSourceDirectory(preparedZip.extractDirectory, slug),
disposableExtraction: preparedZip.plainTree,
cleanupPaths: [preparedZip.root],
provenance: {
...recipeSourceProvenance(source, recipeDirectory),
Expand All @@ -1772,6 +1777,7 @@ async function prepareRecipeSource(sourceRef: string, recipeDirectory: string, s

return {
source: await extractedPluginSourceDirectory(preparedZip.extractDirectory, slug),
disposableExtraction: preparedZip.plainTree,
cleanupPaths: [preparedZip.root],
provenance: {
...recipeSourceProvenance(source, recipeDirectory),
Expand Down
21 changes: 14 additions & 7 deletions packages/cli/src/zip-source.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ export interface PreparedZipSource {
zipPath: string
extractDirectory: string
digest: string
plainTree: boolean
}

export type RedirectSourceResolver<TSource extends ZipSourceReference> = (source: TSource, finalSourceRef: string, headers?: Headers) => TSource
Expand All @@ -29,9 +30,9 @@ export async function prepareZipSource<TSource extends ZipSourceReference>(sourc
const digest = await downloadZipSource(source, zipPath, redirectSource)
await assertSafeZipEntries(zipPath)
await executeManagedHostCommand({ command: "unzip", args: ["-q", zipPath, "-d", extractDirectory], cwd: root, allowedCwdRoots: [root], label: "extract recipe source zip" })
await assertExtractedSourceBounds(extractDirectory)
const plainTree = await assertExtractedSourceBounds(extractDirectory)

return { root, zipPath, extractDirectory, digest }
return { root, zipPath, extractDirectory, digest, plainTree }
}

export async function prepareLocalZipSource(sourcePath: string, slug: string, expectedSha256?: string): Promise<PreparedZipSource> {
Expand All @@ -52,8 +53,8 @@ export async function prepareLocalZipSource(sourcePath: string, slug: string, ex
await mkdir(extractDirectory, { recursive: true })
await assertSafeZipEntries(zipPath)
await executeManagedHostCommand({ command: "unzip", args: ["-q", zipPath, "-d", extractDirectory], cwd: root, allowedCwdRoots: [root], label: "extract recipe source zip" })
await assertExtractedSourceBounds(extractDirectory)
return { root, zipPath, extractDirectory, digest }
const plainTree = await assertExtractedSourceBounds(extractDirectory)
return { root, zipPath, extractDirectory, digest, plainTree }
} catch (error) {
await rm(root, { recursive: true, force: true })
throw error
Expand Down Expand Up @@ -107,30 +108,36 @@ async function assertSafeZipEntries(zipPath: string): Promise<void> {
}
}

async function assertExtractedSourceBounds(directory: string): Promise<void> {
async function assertExtractedSourceBounds(directory: string): Promise<boolean> {
const totals = await directoryTotals(directory)
if (totals.files > maxExtractedFiles()) {
throw new Error(`Recipe source extraction contains too many files: ${totals.files}`)
}
if (totals.bytes > maxExtractedBytes()) {
throw new Error(`Recipe source extraction exceeds ${maxExtractedBytes()} bytes: ${totals.bytes}`)
}
return totals.plainTree
}

async function directoryTotals(directory: string): Promise<{ files: number; bytes: number }> {
async function directoryTotals(directory: string): Promise<{ files: number; bytes: number; plainTree: boolean }> {
let files = 0
let bytes = 0
let plainTree = true
for (const entry of await readdir(directory, { withFileTypes: true })) {
const path = join(directory, entry.name)
if (entry.isDirectory()) {
const child = await directoryTotals(path)
files += child.files
bytes += child.bytes
plainTree &&= child.plainTree
} else if (entry.isFile()) {
const result = await stat(path)
files += 1
bytes += result.size
} else {
// Keep readonly staging's containment checks for archives with links.
plainTree = false
}
}
return { files, bytes }
return { files, bytes, plainTree }
}
2 changes: 2 additions & 0 deletions packages/runtime-core/src/runtime-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -858,6 +858,8 @@ export interface MountSpec {
source: string
/** Optional host containment boundary for readonly symlinks. Must contain the resolved source. */
sourceRoot?: string
/** An isolated source safe to mount directly, even if readonly. Its owner keeps it alive through runtime teardown. */
sourceOwnership?: "run-disposable"
target: string
mode: "readonly" | "readwrite"
captureArtifacts?: boolean
Expand Down
14 changes: 9 additions & 5 deletions packages/runtime-playground/src/mount-materialization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,13 +58,17 @@ interface ReadonlyMountSourceGeneration {
files: number
}

function needsReadonlySnapshot(mount: MountSpec): boolean {
return mount.mode === "readonly" && mount.sourceOwnership !== "run-disposable"
}

/**
* Playground's Node filesystem mount handler is writable. Snapshot readonly
* inputs into a runtime-owned directory before handing them to that handler.
* inputs unless the caller already owns an isolated, disposable copy.
*/
export async function stageReadonlyPlaygroundMounts(mounts: MountSpec[]): Promise<ReadonlyMountStaging> {
const readonlyMounts = mounts.filter((mount) => mount.mode === "readonly")
if (readonlyMounts.length === 0) {
const snapshotCount = mounts.filter(needsReadonlySnapshot).length
if (snapshotCount === 0) {
return {
mounts,
diagnostics: [],
Expand All @@ -76,7 +80,7 @@ export async function stageReadonlyPlaygroundMounts(mounts: MountSpec[]): Promis
const root = await mkdtemp(join(tmpdir(), "wp-codebox-readonly-mounts-"))
try {
const stagedMountResults = await Promise.allSettled(mounts.map(async (mount, index) => {
if (mount.mode !== "readonly") {
if (!needsReadonlySnapshot(mount)) {
return { mount, diagnostics: [] }
}
const source = join(root, `${index}-${basename(mount.source) || "mount"}`)
Expand Down Expand Up @@ -115,7 +119,7 @@ export async function stageReadonlyPlaygroundMounts(mounts: MountSpec[]): Promis
return {
mounts: stagedMounts,
diagnostics,
phaseResult: readonlyMountStagingPhaseResult(readonlyMounts.length, diagnostics, preparations),
phaseResult: readonlyMountStagingPhaseResult(snapshotCount, diagnostics, preparations),
async [Symbol.asyncDispose]() {
await rm(root, { recursive: true, force: true })
},
Expand Down
10 changes: 6 additions & 4 deletions packages/runtime-playground/src/playground-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,7 @@ class PlaygroundRuntime implements Runtime {
private readonly artifactRoot: string
private readonly hostTools?: HostToolRegistry
private cliServerPromise?: Promise<PlaygroundCliServer>
private destroyPromise?: Promise<void>
private readonly activeExecutionAbortControllers = new Set<AbortController>()
private readonly executionSignals = new AsyncLocalStorage<AbortSignal>()
private readonly requestWorkerExecutions = new AsyncLocalStorage<Record<string, string>>()
Expand Down Expand Up @@ -702,11 +703,12 @@ class PlaygroundRuntime implements Runtime {
return server.playground.readFileAsText(path)
}

async destroy(): Promise<void> {
if (this.status === "destroyed") {
return
}
destroy(): Promise<void> {
this.destroyPromise ??= this.destroyPlayground()
return this.destroyPromise
}

private async destroyPlayground(): Promise<void> {
this.status = "destroyed"
for (const controller of this.activeExecutionAbortControllers) {
controller.abort()
Expand Down
17 changes: 17 additions & 0 deletions tests/playground-readonly-mounts.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,23 @@ try {
{ source: pluginSource, target: "/wordpress/wp-content/plugins/tracked-symlink-plugin", mode: "readonly" },
])
const stagedPlugin = staging.mounts[0].source
const disposableSource = join(root, "disposable")
await mkdir(disposableSource)
await writeFile(join(disposableSource, "plugin.php"), "disposable bytes")
const disposable = { source: disposableSource, target: "/disposable", mode: "readonly", sourceOwnership: "run-disposable" } as const
const mixed = await stageReadonlyPlaygroundMounts([
disposable,
{ source: readonlySource, target: "/readonly", mode: "readonly", type: "file" },
])
try {
assert.equal(mixed.mounts[0], disposable)
assert.notEqual(mixed.mounts[1].source, readonlySource)
assert.equal(mixed.phaseResult.metadata?.mounts, 1)
assert.equal((mixed.phaseResult.metadata?.preparation as { bytes?: number }).bytes, readonlyBytes.length)
} finally {
await mixed[Symbol.asyncDispose]()
}
await access(disposableSource)
assert.match(await readFile(join(stagedPlugin, "plugin.php"), "utf8"), /Plugin Name: Tracked Symlink Fixture/, "the plugin entrypoint remains available")
assert.equal(await readFile(join(stagedPlugin, "includes", "runtime.php"), "utf8"), "<?php return 'runtime';\n", "nested runtime files remain available")
await assert.rejects(access(join(stagedPlugin, ".git")), /ENOENT/, "Git metadata is excluded from the staged mount")
Expand Down
8 changes: 8 additions & 0 deletions tests/recipe-extra-plugin-local-zip.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ await withTempDir("wp-codebox-local-zip-plugin-", async (recipeDirectory) => {
assert.deepEqual(nested.provenance.digest, { sha256: digest, expected: digest, verified: true })
assert.equal(nested.provenance.kind, "local")
assert.equal(nested.cleanupPaths.length, 1)
assert.equal(nested.disposableExtraction, true)
await cleanupRecipePreparedSources([], [nested])

await writeFile(join(recipeDirectory, "flat-plugin.php"), "<?php\n/* Plugin Name: Flat */\n")
Expand All @@ -45,8 +46,15 @@ await withTempDir("wp-codebox-local-zip-plugin-", async (recipeDirectory) => {
assert.deepEqual(await validateWorkspaceRecipeSemantics(flatRecipe, join(recipeDirectory, "flat.json")), [])
const [flat] = await prepareRecipeExtraPlugins(flatRecipe, recipeDirectory)
assert.equal((await stat(join(flat.source, "flat-plugin.php"))).isFile(), true)
assert.equal(flat.disposableExtraction, true)
await cleanupRecipePreparedSources([], [flat])

await symlink("flat-plugin.php", join(recipeDirectory, "linked.php"))
await execFileAsync("zip", ["-qy", "linked.zip", "flat-plugin.php", "linked.php"], { cwd: recipeDirectory })
const [linked] = await prepareRecipeExtraPlugins(recipe("linked.zip", "flat-plugin"), recipeDirectory)
assert.equal(linked.disposableExtraction, undefined, "archives containing symlinks still need readonly staging")
await cleanupRecipePreparedSources([], [linked])

await assert.rejects(() => prepareRecipeExtraPlugins(recipe("nested.zip", "nested-plugin", "0".repeat(64)), recipeDirectory), /sha256 mismatch/)
})

Expand Down
67 changes: 67 additions & 0 deletions tests/recipe-extra-plugin-mounts.integration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import assert from "node:assert/strict"
import { execFile } from "node:child_process"
import { createHash } from "node:crypto"
import { access, mkdir, readFile, writeFile } from "node:fs/promises"
import { join } from "node:path"
import { promisify } from "node:util"

import type { BrowserStartupProgressEvent, LifecycleEvent, MaterializationPhaseResult, MountSpec } from "../packages/runtime-core/src/index.js"
import type { RecipeRunOutput } from "../packages/cli/src/commands/recipe-run-types.js"
import { withTempDir } from "../scripts/test-kit.js"

const execFileAsync = promisify(execFile)

await withTempDir("wp-codebox-extra-plugin-mounts-", async (root) => {
const plugin = "mount-test"
const pluginFile = `${plugin}/${plugin}.php`
const source = join(root, plugin)
const contents = "<?php\n/* Plugin Name: Mount Test */\nfunction wp_codebox_mount_test() { return 'loaded'; }\n"
const recipePath = join(root, "recipe.json")
await mkdir(source)
await writeFile(join(root, pluginFile), contents)
await execFileAsync("zip", ["-q", "plugin.zip", pluginFile], { cwd: root })
const archive = await readFile(join(root, "plugin.zip"))
const sha256 = createHash("sha256").update(archive).digest("hex")

for (const [input, stagedBytes] of [["plugin.zip", 0], [plugin, Buffer.byteLength(contents)]] as const) {
await writeFile(recipePath, JSON.stringify({
schema: "wp-codebox/workspace-recipe/v1",
runtime: { backend: "wordpress-playground", wp: "6.5", blueprint: { steps: [] } },
inputs: { extra_plugins: [{ slug: plugin, pluginFile, source: input, ...(input === "plugin.zip" ? { sha256 } : {}) }] },
workflow: { steps: [{ command: "wordpress.run-php", args: [`code=
if (!in_array('${pluginFile}', get_option('active_plugins', array()), true) || !function_exists('wp_codebox_mount_test') || wp_codebox_mount_test() !== 'loaded') {
throw new RuntimeException('Extra plugin was not activated and loaded');
}
$file = WP_PLUGIN_DIR . '/${pluginFile}';
if (file_put_contents($file, 'updated') !== 7 || file_get_contents($file) !== 'updated') {
throw new RuntimeException('Plugin directory write did not take effect');
}
`] }] },
}))

const { stdout } = await execFileAsync(process.execPath, ["packages/cli/dist/index.js", "recipe-run", "--recipe", recipePath, "--artifacts", join(root, `artifacts-${input}`), "--json"], {
timeout: 180_000,
maxBuffer: 2 * 1024 * 1024,
})
const output = JSON.parse(stdout) as RecipeRunOutput
assert.equal(output.success, true, stdout)
assert.ok(output.artifacts?.eventsPath)
const events = (await readFile(output.artifacts.eventsPath, "utf8")).trim().split("\n").map((line) => JSON.parse(line) as LifecycleEvent)
const progress = events.find((event) => event.type === "runtime.browser-startup-progress" && (event.data?.event as BrowserStartupProgressEvent)?.phase === "preview:materializing-mounts")
const staging = (progress?.data?.event as BrowserStartupProgressEvent | undefined)?.detail?.materialization as MaterializationPhaseResult | undefined
assert.equal((staging?.metadata?.preparation as { bytes?: number } | undefined)?.bytes, stagedBytes, input)
assert.equal(staging?.metadata?.mounts, stagedBytes === 0 ? 0 : 1, input)
assert.equal(await readFile(join(root, pluginFile), "utf8"), contents)
assert.deepEqual(await readFile(join(root, "plugin.zip")), archive)

if (stagedBytes === 0) {
const mountEvent = events.find((event) => event.type === "runtime.mounted" && (event.data?.mount as MountSpec)?.target === `/wordpress/wp-content/plugins/${plugin}`)
const mount = mountEvent?.data?.mount as MountSpec | undefined
assert.equal(mount?.sourceOwnership, "run-disposable")
assert.ok(mount?.source)
await assert.rejects(access(mount.source), { code: "ENOENT" })
}
}
})

console.log("recipe extra plugin mount isolation ok")
Loading