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
8 changes: 8 additions & 0 deletions docs/recipe-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,14 @@ Supported `loadAs` values:
WP Codebox's generated MU-plugin loader. Use this for sandbox runtime
substrate, not user-visible plugins.

For local plugins in a monorepo, declare `sourceRoot` and `sourceSubpath` to
mount a plugin subdirectory while allowing readonly staging to follow symlinks
elsewhere inside the declared root. A `sourceRoot` that does not contain the
plugin directory is ignored, so prepared plugin copies stay authoritative; a
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.

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

Expand Down
2 changes: 2 additions & 0 deletions packages/cli/src/commands/recipe-runtime-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,7 @@ function preparedExtraPluginMounts(plugins: PreparedExtraPlugin[]): MountSpec[]
return plugins.map((plugin) => ({
type: "directory",
source: plugin.source,
...(plugin.sourceRoot !== undefined ? { sourceRoot: plugin.sourceRoot } : {}),
target: plugin.target,
mode: "readonly",
...(plugin.metadata?.phase === "pre-install" ? { phase: "pre-install" as const } : {}),
Expand All @@ -486,6 +487,7 @@ async function mountPreparedExtraPlugins(runtime: Runtime, plugins: PreparedExtr
await phaseExecutor.operation(`extra-plugin.drop-in:${plugin.slug}`, runtime.mount({
type: "file",
source: join(plugin.source, "db.php"),
...(plugin.sourceRoot !== undefined ? { sourceRoot: plugin.sourceRoot } : {}),
target: "/wordpress/wp-content/db.php",
mode: "readonly",
phase: "pre-install",
Expand Down
89 changes: 59 additions & 30 deletions packages/cli/src/recipe-sources.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { createHash } from "node:crypto"
import { copyFile, cp, lstat, mkdir, mkdtemp, readdir, readFile, rename, rm, stat, unlink, writeFile } from "node:fs/promises"
import { copyFile, cp, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rename, rm, stat, unlink, writeFile } from "node:fs/promises"
import { tmpdir } from "node:os"
import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path"
import { fileURLToPath } from "node:url"
import { compileSourcePackage, composerManagedHostCommandConfig, composerManagedHostEnv, normalizeReviewerSafePath, sourcePackagePathAllowed, type WorkspaceRecipeSourcePackage } from "@automattic/wp-codebox-core"
import { compileSourcePackage, composerManagedHostCommandConfig, composerManagedHostEnv, normalizeReviewerSafePath, pathIsWithinRoot, sourcePackagePathAllowed, type WorkspaceRecipeSourcePackage } from "@automattic/wp-codebox-core"
import type { MountSpec, WorkspaceRecipe, WorkspaceRecipeDependencyOverlay, WorkspaceRecipeExtraPlugin, WorkspaceRecipeExtraTheme, WorkspaceRecipeRuntimeOverlay, WorkspaceRecipeStagedFile, WorkspaceRecipeWorkspace, WorkspaceRecipeWorkspacePreload, WorkspaceRecipeWorkspacePreloadRepository } from "@automattic/wp-codebox-core"
import { executeManagedHostCommand, resolvePluginEntrypointContract, resolveThemeEntrypointContract } from "@automattic/wp-codebox-core"
import { collectPreparedSourceCleanupPaths, DEFAULT_PREPARED_SOURCE_EXCLUDE_NAMES, localPreparedSourceProvenance, prepareLocalSourceStageSync, SANDBOX_WORKSPACE_ROOT, type PreparedSourceProvenance } from "@automattic/wp-codebox-core/internals"
Expand Down Expand Up @@ -59,12 +59,14 @@ export interface RecipeSourceProvenance {

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

export interface PreparedExtraPlugin {
source: string
sourceRoot?: string
slug: string
target: string
pluginFile: string
Expand Down Expand Up @@ -303,13 +305,21 @@ export async function prepareExtraPlugins(plugins: readonly WorkspaceRecipeExtra
const sourceRootRef = sourceRef === BUNDLED_MDI_NATIVE_SOURCE ? BUNDLED_MDI_NATIVE_ARCHIVE : recipeExtraPluginSourceRoot(plugin, recipeDirectory)
const sourceSubpath = recipeExtraPluginSourceSubpath(plugin, recipeDirectory)
const resolved = await prepareRecipeSource(sourceRootRef, recipeDirectory, slug, plugin.sha256, options)
const pluginResolved = sourceSubpath ? { ...resolved, source: join(resolved.source, sourceSubpath) } : resolved
const pluginResolved = {
...resolved,
source: sourceSubpath ? join(resolved.source, sourceSubpath) : resolved.source,
...(recipeExtraPluginDeclaresContainmentRoot(plugin, sourceRootRef) ? { sourceRoot: resolved.source } : {}),
}
if (pluginResolved.sourceRoot !== undefined) {
await assertExtraPluginSourceWithinRoot(pluginResolved.source, pluginResolved.sourceRoot)
}
const pluginFile = await resolveRecipeExtraPluginFile(plugin, recipeDirectory)
const loadAs = plugin.loadAs ?? "plugin"
const prepared = await prepareComposerAutoloadForPlugin(pluginResolved, slug, sourceRef, plugin.composer, resolved.source)
await assertPreparedPluginFileExists(prepared.source, pluginFile.slice(slug.length + 1), sourceRef)
preparedPlugins.push({
source: prepared.source,
...(prepared.sourceRoot !== undefined ? { sourceRoot: prepared.sourceRoot } : {}),
slug,
target: pluginTarget(slug, loadAs),
pluginFile,
Expand Down Expand Up @@ -422,15 +432,18 @@ async function prepareComposerAutoloadForPlugin(prepared: PreparedExternalSource
}

const stagingRoot = await mkdtemp(join(tmpdir(), `wp-codebox-plugin-${slug}-`))
const stagedRoot = prepareLocalSourceStageSync({
source: copyRoot,
targetRoot: stagingRoot,
targetName: slug,
cleanupRoot: false,
}).source
const sourceSubpath = relative(copyRoot, prepared.source).replace(/\\/g, "/")
const stagedSource = sourceSubpath ? join(stagedRoot, sourceSubpath) : stagedRoot
try {
const sourceRoot = prepared.sourceRoot === undefined ? copyRoot : await realpath(prepared.sourceRoot)
const pluginSource = prepared.sourceRoot === undefined ? prepared.source : await realpath(prepared.source)
const stagedRoot = prepareLocalSourceStageSync({
source: sourceRoot,
targetRoot: stagingRoot,
targetName: slug,
cleanupRoot: false,
verbatimSymlinks: prepared.sourceRoot !== undefined,
}).source
const stagedSource = join(stagedRoot, relative(sourceRoot, pluginSource))
if (prepared.sourceRoot !== undefined) await assertExtraPluginSourceWithinRoot(stagedSource, stagedRoot)
await executeManagedHostCommand({
...composerManagedHostCommandConfig({
cwd: stagedSource,
Expand All @@ -441,21 +454,21 @@ async function prepareComposerAutoloadForPlugin(prepared: PreparedExternalSource
})
await materializeComposerPathRepositoryPackages(stagedSource, stagedRoot)
await writeComposerInstalledPackageAutoloader(stagedSource)
return {
...prepared,
source: stagedSource,
...(prepared.sourceRoot !== undefined ? { sourceRoot: stagedRoot } : {}),
cleanupPaths: [...prepared.cleanupPaths, stagingRoot],
provenance: {
...prepared.provenance,
localPathCategory: "temporary-composer-autoload",
},
}
} catch (error) {
await rm(stagingRoot, { recursive: true, force: true })
const detail = error instanceof Error && "stderr" in error && typeof error.stderr === "string" && error.stderr.trim() ? error.stderr.trim() : error instanceof Error ? error.message : String(error)
throw new Error(`Recipe extra plugin source requires Composer autoload but could not be prepared: ${sourceRef}: ${detail}`)
}

return {
...prepared,
source: stagedSource,
cleanupPaths: [...prepared.cleanupPaths, stagingRoot],
provenance: {
...prepared.provenance,
localPathCategory: "temporary-composer-autoload",
},
}
}

export async function materializeComposerPathRepositoryPackages(pluginSource: string, stagedSourceRoot: string): Promise<void> {
Expand Down Expand Up @@ -958,10 +971,15 @@ async function preserveComposerDependencyReference(consumer: PreparedExtraPlugin

if (!stagedConsumers.has(consumer)) {
const stagingRoot = await mkdtemp(join(tmpdir(), `wp-codebox-dependency-consumer-${consumer.slug}-`))
const stagedSource = join(stagingRoot, basename(consumer.source))
await cp(consumer.source, stagedSource, { recursive: true })
consumer.source = stagedSource
const copyRoot = await realpath(consumer.sourceRoot ?? consumer.source)
const stagedRoot = join(stagingRoot, basename(copyRoot))
const sourceSubpath = relative(copyRoot, await realpath(consumer.source))
const stagedSource = join(stagedRoot, sourceSubpath)
consumer.cleanupPaths.push(stagingRoot)
await cp(copyRoot, stagedRoot, { recursive: true, verbatimSymlinks: consumer.sourceRoot !== undefined })
if (consumer.sourceRoot !== undefined) await assertExtraPluginSourceWithinRoot(stagedSource, stagedRoot)
consumer.source = stagedSource
if (consumer.sourceRoot !== undefined) consumer.sourceRoot = stagedRoot
stagedConsumers.add(consumer)
}

Expand Down Expand Up @@ -2038,17 +2056,15 @@ function resolveExternalSourceSubpath(ref: RecipeExternalSourceRef, inputName: s
return ""
}

const relativePath = relative(resolve(recipeDirectory, sourceRoot), resolve(recipeDirectory, sourceRef))
if (!relativePath || relativePath.startsWith("..") || isAbsolute(relativePath)) {
if (!externalSourceRootContainsSource(ref, inputName, sourceRoot, recipeDirectory)) {
return ""
}

return normalizeReviewerSafePath(relativePath)
const relativePath = relative(resolve(recipeDirectory, sourceRoot), resolve(recipeDirectory, sourceRef))
return relativePath ? normalizeReviewerSafePath(relativePath) : ""
}

function externalSourceRootContainsSource(ref: RecipeExternalSourceRef, inputName: string, sourceRoot: string, recipeDirectory: string): boolean {
const relativePath = relative(resolve(recipeDirectory, sourceRoot), resolve(recipeDirectory, resolveExternalSourceRef(ref, inputName)))
return !relativePath.startsWith("..") && !isAbsolute(relativePath)
return pathIsWithinRoot(resolve(recipeDirectory, resolveExternalSourceRef(ref, inputName)), resolve(recipeDirectory, sourceRoot))
}

function normalizeExternalSourceSubpath(value: string, inputName: string): string {
Expand All @@ -2075,6 +2091,19 @@ export function recipeExtraPluginSourceRoot(plugin: WorkspaceRecipeExtraPlugin,
return resolveExternalSourceRoot(plugin, "extra_plugins", recipeDirectory)
}

// A declared sourceRoot widens the readonly symlink boundary only when it is the
// root the source actually resolves through; otherwise the source stays authoritative.
export function recipeExtraPluginDeclaresContainmentRoot(plugin: WorkspaceRecipeExtraPlugin, sourceRoot: string): boolean {
return plugin.sourceRoot !== undefined && plugin.sourceRoot === sourceRoot
}

export async function assertExtraPluginSourceWithinRoot(source: string, sourceRoot: string): Promise<void> {
const [resolvedSource, resolvedRoot] = await Promise.all([realpath(source), realpath(sourceRoot)])
if (!pathIsWithinRoot(resolvedSource, resolvedRoot)) {
throw new Error("Plugin sourceRoot must contain the mount source after resolving symlinks.")
}
}

export function recipeExtraPluginSourceSubpath(plugin: WorkspaceRecipeExtraPlugin, recipeDirectory: string): string {
return resolveExternalSourceSubpath(plugin, "extra_plugins", recipeDirectory)
}
Expand Down
24 changes: 20 additions & 4 deletions packages/cli/src/recipe-validation.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { readFileSync } from "node:fs"
import { lstat, readFile, stat } from "node:fs/promises"
import { dirname, join, resolve } from "node:path"
import { BROWSER_PROBE_CHROMIUM_PROFILE_IDS, RUNTIME_BACKED_FUZZ_SUITE_RUNNER_CAPABILITIES, RUNTIME_PHP_WASM_BUNDLED_EXTENSIONS, assertFixtureImportDeterministicIdsSupported, assertWorkspaceRecipeJsonSchema, browserEnvironment, commandArgValue, normalizeRuntimeBackendKind, normalizeRuntimeMountTarget, parseCommandJson, resolveThemeEntrypointContract, safeArtifactRelativePath, validateBrowserInteractionScript, validateRuntimePolicy, validateSourcePackage, workspaceRecipeRuntimeCollectedArtifacts, type MountSpec, type RuntimeAssetSpec, type RuntimePolicy, type RuntimePreviewSpec, type WorkspaceRecipe, type WorkspaceRecipeDeclaredArtifact, type WorkspaceRecipeDependencyOverlay, type WorkspaceRecipeDistribution, type WorkspaceRecipeDistributionStartupProbe, type WorkspaceRecipeFixtureDatabase, type WorkspaceRecipeFuzzCasePhase, type WorkspaceRecipeMount, type WorkspaceRecipePluginRuntime, type WorkspaceRecipePluginRuntimeHealthProbe, type WorkspaceRecipeProbe, type WorkspaceRecipeRuntimeBackendPackage, type WorkspaceRecipeRuntimeOverlay, type WorkspaceRecipeSiteSeed } from "@automattic/wp-codebox-core"
import { BROWSER_PROBE_CHROMIUM_PROFILE_IDS, RUNTIME_BACKED_FUZZ_SUITE_RUNNER_CAPABILITIES, RUNTIME_PHP_WASM_BUNDLED_EXTENSIONS, assertFixtureImportDeterministicIdsSupported, assertWorkspaceRecipeJsonSchema, browserEnvironment, commandArgValue, normalizeRuntimeBackendKind, normalizeRuntimeMountTarget, parseCommandJson, pathIsWithinRoot, resolveThemeEntrypointContract, safeArtifactRelativePath, validateBrowserInteractionScript, validateRuntimePolicy, validateSourcePackage, workspaceRecipeRuntimeCollectedArtifacts, type MountSpec, type RuntimeAssetSpec, type RuntimePolicy, type RuntimePreviewSpec, type WorkspaceRecipe, type WorkspaceRecipeDeclaredArtifact, type WorkspaceRecipeDependencyOverlay, type WorkspaceRecipeDistribution, type WorkspaceRecipeDistributionStartupProbe, type WorkspaceRecipeFixtureDatabase, type WorkspaceRecipeFuzzCasePhase, type WorkspaceRecipeMount, type WorkspaceRecipePluginRuntime, type WorkspaceRecipePluginRuntimeHealthProbe, type WorkspaceRecipeProbe, type WorkspaceRecipeRuntimeBackendPackage, type WorkspaceRecipeRuntimeOverlay, type WorkspaceRecipeSiteSeed } from "@automattic/wp-codebox-core"
import { commandValidationDescriptorFor, effectivePolicyCommandsFor, type CommandArgValidationDescriptor } from "@automattic/wp-codebox-core/contracts"
import { composerPackageVendorPath, evaluateRecipeSourcePolicy, isComposerPackageName, pluginTarget, recipeExtraPluginSlug, recipeExtraPluginSource, recipeExtraPluginSourceRoot, recipeExtraPluginSourceSubpath, recipeExtraPlugins, recipeExtraThemeSlug, recipeExtraThemeSource, recipeExtraThemeSourceRoot, recipeExtraThemeSourceSubpath, recipeExtraThemes, recipeSource, resolveRecipeExtraPluginFile } from "./recipe-sources.js"
import { assertExtraPluginSourceWithinRoot, composerPackageVendorPath, recipeExtraPluginDeclaresContainmentRoot, evaluateRecipeSourcePolicy, isComposerPackageName, pluginTarget, recipeExtraPluginSlug, recipeExtraPluginSource, recipeExtraPluginSourceRoot, recipeExtraPluginSourceSubpath, recipeExtraPlugins, recipeExtraThemeSlug, recipeExtraThemeSource, recipeExtraThemeSourceRoot, recipeExtraThemeSourceSubpath, recipeExtraThemes, recipeSource, resolveRecipeExtraPluginFile } from "./recipe-sources.js"
import { loadConfiguredRuntimeOverlayDescriptors, registeredRuntimeOverlayDescriptors, runtimeOverlayDescriptor, runtimeOverlayTarget } from "./runtime-overlay-registry.js"
import { assertHostNodeHeapRequirement } from "./host-node-heap.js"
import { isSmtpSinkRecipeOperation } from "./smtp-sink-recipe-operations.js"
Expand Down Expand Up @@ -699,7 +699,13 @@ export async function validateWorkspaceRecipeSemantics(recipe: WorkspaceRecipe,
continue
}
const bundledMdiNative = sourceRef === "wp-codebox:mdi-native"
const sourceRoot = bundledMdiNative ? source.resolvedUrl : recipeExtraPluginSourceRoot(plugin, recipeDirectory)
let sourceRoot: string
try {
sourceRoot = bundledMdiNative ? source.resolvedUrl : recipeExtraPluginSourceRoot(plugin, recipeDirectory)
} catch (error) {
addIssue("invalid-source-root", `${path}.sourceRoot`, error instanceof Error ? error.message : String(error))
continue
}
let sourceSubpath = ""
try {
sourceSubpath = recipeExtraPluginSourceSubpath(plugin, recipeDirectory)
Expand All @@ -711,6 +717,16 @@ export async function validateWorkspaceRecipeSemantics(recipe: WorkspaceRecipe,
const pluginSource = source.type === "local" ? (bundledMdiNative ? source.resolvedUrl : resolve(recipeDirectory, sourceRef)) : undefined
const sourceRootPath = resolve(recipeDirectory, sourceRoot)
const pluginMountedSource = source.type === "local" ? resolve(sourceRootPath, sourceSubpath) : undefined
if (recipeExtraPluginDeclaresContainmentRoot(plugin, sourceRoot) && pluginMountedSource && !localZipSource) {
try {
await assertExtraPluginSourceWithinRoot(pluginMountedSource, sourceRootPath)
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") {
addIssue("invalid-source-root", `${path}.sourceRoot`, error instanceof Error ? error.message : String(error))
continue
}
}
}
let slug: string
try {
slug = recipeExtraPluginSlug(plugin)
Expand All @@ -731,7 +747,7 @@ export async function validateWorkspaceRecipeSemantics(recipe: WorkspaceRecipe,
if (sourceRoot !== sourceRef && !localZipSource) {
await validateExistingDirectory(resolve(recipeDirectory, sourceRoot), `${path}.sourceRoot`, addIssue)
}
if (pluginMountedSource && !pluginMountedSource.startsWith(`${sourceRootPath}/`) && pluginMountedSource !== sourceRootPath) {
if (pluginMountedSource && !pathIsWithinRoot(pluginMountedSource, sourceRootPath)) {
addIssue("invalid-source-subdir", `${path}.${plugin.sourceSubdir !== undefined ? "sourceSubdir" : "sourceSubpath"}`, "Plugin source subdirectory must stay inside the source root.")
continue
}
Expand Down
11 changes: 4 additions & 7 deletions packages/runtime-core/src/agent-task-recipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import type { TaskInput } from "./task-input.js"
import { isPlainObject, stringList, stripUndefined } from "./object-utils.js"
import type { WorkspaceRecipe, WorkspaceRecipeComponentManifest, WorkspaceRecipeComponentManifestEntry, WorkspaceRecipeExtraPlugin, WorkspaceRecipeMount, WorkspaceRecipeStagedFile } from "./runtime-contracts.js"
import { resolvePluginEntrypointContract, sanitizePluginSlug } from "./component-contracts.js"
import { prepareRecipeSourcePackageSync } from "./recipe-source-packages.js"
import { prepareRecipePluginSourceSync, prepareRecipeSourcePackageSync } from "./recipe-source-packages.js"
import { workspacePreloadsFromTaskInputs } from "./workspace-preload-artifacts.js"

const AGENT_RUNTIME_ENV = { WP_AGENT_RUNTIME: "1" }
Expand Down Expand Up @@ -770,7 +770,8 @@ function componentPlugins(contracts: Array<Record<string, unknown>> | undefined,
const originalSource = stringValue(contract.original_source || contract.originalSource || contract.original_path || contract.originalPath)
const sourceSubpath = stringValue(contract.sourceSubpath || contract.source_subpath)
if (!slug || !source) return []
const preparedSource = prepareComponentPluginSource(sourceRoot || source, originalSource || sourceRoot, sourceSubpath, slug, artifactsRoot)
const prepared = prepareRecipePluginSourceSync({ source, sourceRoot: sourceRoot || undefined, originalSource: originalSource || undefined, sourceSubpath, slug, artifactsRoot, packageRootName: "prepared-plugins" })
const preparedSource = prepared.source
const entrypoint = resolvePluginEntrypointContract({
source: preparedSource,
slug,
Expand All @@ -779,7 +780,7 @@ function componentPlugins(contracts: Array<Record<string, unknown>> | undefined,
})
const loadAs = stringValue(contract.loadAs) === "plugin" ? "plugin" : "mu-plugin"
return [{
source: preparedSource,
...prepared,
slug,
pluginFile: entrypoint.pluginFile,
activate: Boolean(contract.activate),
Expand All @@ -803,10 +804,6 @@ function componentPlugins(contracts: Array<Record<string, unknown>> | undefined,
})
}

function prepareComponentPluginSource(source: string, originalSource: string, sourceSubpath: string, slug: string, artifactsRoot: string): string {
return prepareRecipeSourcePackageSync({ source, originalSource, sourceSubpath, slug, artifactsRoot, packageRootName: "prepared-plugins" })
}

function sandboxToolPolicy(input: AgentTaskRunInput, taskInput: TaskInput): SandboxToolPolicySnapshot {
const inputPolicy = objectValue(input.sandbox_tool_policy) ?? {}
const taskPolicy = objectValue(taskInput.sandbox_tool_policy) ?? {}
Expand Down
Loading
Loading