diff --git a/docs/recipe-contract.md b/docs/recipe-contract.md index 7f002f2c..3e165946 100644 --- a/docs/recipe-contract.md +++ b/docs/recipe-contract.md @@ -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. diff --git a/packages/cli/src/commands/recipe-runtime-setup.ts b/packages/cli/src/commands/recipe-runtime-setup.ts index 89e44fe5..792b1fa5 100644 --- a/packages/cli/src/commands/recipe-runtime-setup.ts +++ b/packages/cli/src/commands/recipe-runtime-setup.ts @@ -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 } : {}), @@ -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", diff --git a/packages/cli/src/recipe-sources.ts b/packages/cli/src/recipe-sources.ts index 5c163df4..ab6bbb5b 100644 --- a/packages/cli/src/recipe-sources.ts +++ b/packages/cli/src/recipe-sources.ts @@ -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" @@ -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 @@ -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, @@ -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, @@ -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 { @@ -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) } @@ -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 { @@ -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 { + 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) } diff --git a/packages/cli/src/recipe-validation.ts b/packages/cli/src/recipe-validation.ts index 74a1d862..4cf60fbb 100644 --- a/packages/cli/src/recipe-validation.ts +++ b/packages/cli/src/recipe-validation.ts @@ -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" @@ -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) @@ -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) @@ -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 } diff --git a/packages/runtime-core/src/agent-task-recipe.ts b/packages/runtime-core/src/agent-task-recipe.ts index 21c0f9a4..307ffb16 100644 --- a/packages/runtime-core/src/agent-task-recipe.ts +++ b/packages/runtime-core/src/agent-task-recipe.ts @@ -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" } @@ -770,7 +770,8 @@ function componentPlugins(contracts: Array> | 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, @@ -779,7 +780,7 @@ function componentPlugins(contracts: Array> | undefined, }) const loadAs = stringValue(contract.loadAs) === "plugin" ? "plugin" : "mu-plugin" return [{ - source: preparedSource, + ...prepared, slug, pluginFile: entrypoint.pluginFile, activate: Boolean(contract.activate), @@ -803,10 +804,6 @@ function componentPlugins(contracts: Array> | 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) ?? {} diff --git a/packages/runtime-core/src/generic-ability-runtime-run.ts b/packages/runtime-core/src/generic-ability-runtime-run.ts index b88aae8e..3953c467 100644 --- a/packages/runtime-core/src/generic-ability-runtime-run.ts +++ b/packages/runtime-core/src/generic-ability-runtime-run.ts @@ -5,7 +5,7 @@ import { providerRuntimeInvocationContract } from "./provider-runtime-contracts. import { DEFAULT_WORDPRESS_VERSION } from "./runtime-defaults.js" import type { WorkspaceRecipe, WorkspaceRecipeExtraPlugin, WorkspaceRecipeMount, WorkspaceRecipeRuntimeOverlay, WorkspaceRecipeStagedFile } from "./runtime-contracts.js" import { componentManifestForRuntimePlugins, runtimeDependencyPlanContract } from "./agent-task-recipe.js" -import { prepareRecipeSourcePackageSync } from "./recipe-source-packages.js" +import { prepareRecipePluginSourceSync } from "./recipe-source-packages.js" import { isPlainObject, stringList, stripUndefined } from "./object-utils.js" import { sandboxToolPolicyFromAllowedTools } from "./sandbox-tool-policy.js" import { runtimePresetById, type RuntimePresetDefinition, type RuntimePresetRegistryManifest } from "./runtime-preset-registry.js" @@ -21,6 +21,7 @@ export interface GenericAbilityRuntimeComponentContract { loadAs?: ComponentLoadMode activate?: boolean originalSource?: string + sourceRoot?: string sourceSubpath?: string metadata?: Record } @@ -220,12 +221,13 @@ function runtimePlugins(contracts: GenericAbilityRuntimeComponentContract[] | un const source = stringValue(contract.source) if (!source) return [] const slug = sanitizePluginSlug(stringValue(contract.slug) || slugFromPath(source)) - const preparedSource = prepareRecipeSourcePackageSync({ source, originalSource: contract.originalSource, sourceSubpath: contract.sourceSubpath, slug, artifactsRoot, packageRootName: "prepared-plugins" }) + const prepared = prepareRecipePluginSourceSync({ source, originalSource: contract.originalSource, sourceRoot: contract.sourceRoot, sourceSubpath: contract.sourceSubpath, slug, artifactsRoot, packageRootName: "prepared-plugins" }) + const preparedSource = prepared.source const loadAs = contract.loadAs === "mu-plugin" ? "mu-plugin" : "plugin" const entrypoint = resolvePluginEntrypointContract({ source: preparedSource, slug, pluginFile: contract.pluginFile, loadAs }) return [{ - source: preparedSource, + ...prepared, slug, pluginFile: entrypoint.pluginFile, activate: contract.activate ?? role === "provider", diff --git a/packages/runtime-core/src/prepared-source-staging.ts b/packages/runtime-core/src/prepared-source-staging.ts index ea3cac76..aa3e69c1 100644 --- a/packages/runtime-core/src/prepared-source-staging.ts +++ b/packages/runtime-core/src/prepared-source-staging.ts @@ -25,6 +25,7 @@ export interface PrepareLocalSourceStageOptions { recipeDirectory?: string cleanupRoot?: boolean excludeNames?: string[] + verbatimSymlinks?: boolean } export const DEFAULT_PREPARED_SOURCE_EXCLUDE_NAMES = namedFileTreeSkipPolicyNames("prepared-source") @@ -37,7 +38,7 @@ export function prepareLocalSourceStageSync(options: PrepareLocalSourceStageOpti if (resolve(source) !== resolve(target)) { rmSync(target, { recursive: true, force: true }) mkdirSync(root, { recursive: true }) - copyPreparedSourceFilteredSync(source, target, options.excludeNames) + copyPreparedSourceFilteredSync(source, target, options.excludeNames, options.verbatimSymlinks) } else { mkdirSync(target, { recursive: true }) } @@ -52,10 +53,11 @@ export function prepareLocalSourceStageSync(options: PrepareLocalSourceStageOpti } } -export function copyPreparedSourceFilteredSync(source: string, target: string, excludeNames: string[] = DEFAULT_PREPARED_SOURCE_EXCLUDE_NAMES): void { +export function copyPreparedSourceFilteredSync(source: string, target: string, excludeNames: string[] = DEFAULT_PREPARED_SOURCE_EXCLUDE_NAMES, verbatimSymlinks = false): void { const excluded = new Set(excludeNames) cpSync(source, target, { recursive: true, + verbatimSymlinks, filter: (entry: string) => !fileTreeEntryNameSkipped(basename(entry), excluded), }) } diff --git a/packages/runtime-core/src/recipe-source-packages.ts b/packages/runtime-core/src/recipe-source-packages.ts index 295a9bb3..9d1d7f63 100644 --- a/packages/runtime-core/src/recipe-source-packages.ts +++ b/packages/runtime-core/src/recipe-source-packages.ts @@ -1,8 +1,9 @@ import { spawnSync } from "node:child_process" -import { cpSync, existsSync, mkdirSync, readFileSync, statSync, rmSync, writeFileSync } from "node:fs" +import { cpSync, existsSync, mkdirSync, readFileSync, realpathSync, statSync, rmSync, writeFileSync } from "node:fs" import { homedir } from "node:os" import { isAbsolute, join, relative, resolve } from "node:path" import { safeArtifactRelativePath } from "./artifact-paths.js" +import { pathIsWithinRoot } from "./file-tree-policy.js" import type { ManagedHostCommandConfig } from "./managed-host-command.js" import { prepareLocalSourceStageSync, preparedSourcePath, preparedSourceRoot } from "./prepared-source-staging.js" import { SANDBOX_WORKSPACE_ROOT } from "./runtime-action-adapter.js" @@ -30,6 +31,7 @@ export interface PreparedRecipeSourcePackageOptions { slug: string artifactsRoot: string originalSource?: string + sourceRoot?: string sourceSubpath?: string packageRootName?: string composerInstallArgs?: string[] @@ -181,21 +183,41 @@ export function sourcePackageArtifactPath(path: string): string { } export function prepareRecipeSourcePackageSync(options: PreparedRecipeSourcePackageOptions): string { + return prepareRecipePluginSourceSync(options).source +} + +export function prepareRecipePluginSourceSync(options: PreparedRecipeSourcePackageOptions): { source: string; sourceRoot?: string } { const packageRootName = options.packageRootName ?? "prepared-source-packages" const source = options.source - const originalSource = options.originalSource || source + const declaredRoot = options.sourceRoot + const originalSource = declaredRoot ?? (options.originalSource || source) const sourceSubpath = options.sourceSubpath ? normalizeReviewerSafePath(options.sourceSubpath) : inferredSourceSubpath(source, originalSource) - if (!source) return source + const prepared = (source: string, root: string) => { + if (declaredRoot === undefined) return { source } + const sourceRoot = realpathSync(root) + const resolvedSource = realpathSync(source) + if (!pathIsWithinRoot(resolvedSource, sourceRoot)) { + throw new Error("Plugin sourceRoot must contain the mount source after resolving symlinks.") + } + return { source: resolvedSource, sourceRoot } + } + if (!source) return { source } + if (declaredRoot !== undefined) { + prepared(localSourcePath(source), localSourcePath(declaredRoot)) + } if (!options.artifactsRoot) { - return prepareRecipeSourcePackageWithoutArtifacts(source, originalSource, options.slug, sourceSubpath) + return prepared(prepareRecipeSourcePackageWithoutArtifacts(source, originalSource, options.slug, sourceSubpath), localSourcePath(originalSource)) } const preparedRoot = preparedSourceRoot(options.artifactsRoot, packageRootName) const preparedSource = preparedSourcePath(options.artifactsRoot, packageRootName, options.slug) - const preparedPluginSource = sourceSubpath ? join(preparedSource, sourceSubpath) : preparedSource - const copySource = localSourcePath(originalSource) - if (pathExists(copySource)) { + const localOriginal = localSourcePath(originalSource) + if (pathExists(localOriginal)) { + const copySource = declaredRoot === undefined ? localOriginal : realpathSync(localOriginal) + const originalPlugin = prepared(join(copySource, sourceSubpath), copySource) + const originalPluginSource = originalPlugin.source + const preparedPluginSource = join(preparedSource, declaredRoot === undefined ? sourceSubpath : relative(copySource, originalPluginSource)) if (resolve(copySource) !== resolve(preparedSource)) { prepareLocalSourceStageSync({ source: copySource, @@ -203,35 +225,36 @@ export function prepareRecipeSourcePackageSync(options: PreparedRecipeSourcePack targetRoot: preparedRoot, targetName: options.slug, cleanupRoot: false, + verbatimSymlinks: declaredRoot !== undefined, }) } else { mkdirSync(preparedSource, { recursive: true }) } - const originalPluginSource = join(copySource, sourceSubpath) + const result = prepared(preparedPluginSource, preparedSource) if (pathExists(join(originalPluginSource, "vendor", "autoload.php"))) { - preserveExistingComposerVendor(originalPluginSource, preparedPluginSource) + preserveExistingComposerVendor(originalPluginSource, preparedPluginSource, declaredRoot !== undefined) bridgePackageAutoloaderToComposerAutoload(preparedPluginSource) - return preparedPluginSource + return result } if (!pathExists(join(preparedPluginSource, "composer.json"))) { - preserveExistingComposerVendor(originalPluginSource, preparedPluginSource) - return preparedPluginSource + preserveExistingComposerVendor(originalPluginSource, preparedPluginSource, declaredRoot !== undefined) + return result } const installedSource = installComposerDependenciesForSourcePackageSync(preparedPluginSource, options.slug, preparedRoot, options.composerInstallArgs) bridgePackageAutoloaderToComposerAutoload(installedSource) - return installedSource + return prepared(installedSource, preparedSource) } - return prepareRecipeSourcePackageWithoutArtifacts(source, source, options.slug, "") + return { source: prepareRecipeSourcePackageWithoutArtifacts(source, source, options.slug, "") } } -function preserveExistingComposerVendor(originalPluginSource: string, preparedPluginSource: string): void { +function preserveExistingComposerVendor(originalPluginSource: string, preparedPluginSource: string, verbatimSymlinks: boolean): void { const originalVendor = join(originalPluginSource, "vendor") const preparedVendor = join(preparedPluginSource, "vendor") if (!pathExists(originalVendor)) return rmSync(preparedVendor, { recursive: true, force: true }) mkdirSync(preparedPluginSource, { recursive: true }) - cpSync(originalVendor, preparedVendor, { recursive: true }) + cpSync(originalVendor, preparedVendor, { recursive: true, verbatimSymlinks }) } export function bridgePackageAutoloaderToComposerAutoload(pluginSource: string): void { diff --git a/packages/runtime-core/src/runtime-contracts.ts b/packages/runtime-core/src/runtime-contracts.ts index f672c38f..a3bc1e67 100644 --- a/packages/runtime-core/src/runtime-contracts.ts +++ b/packages/runtime-core/src/runtime-contracts.ts @@ -856,6 +856,8 @@ export interface RuntimeInfo { export interface MountSpec { type: "directory" | "file" | (string & {}) source: string + /** Optional host containment boundary for readonly symlinks. Must contain the resolved source. */ + sourceRoot?: string target: string mode: "readonly" | "readwrite" captureArtifacts?: boolean diff --git a/packages/runtime-playground/src/mount-materialization.ts b/packages/runtime-playground/src/mount-materialization.ts index 4fbc253b..4759908d 100644 --- a/packages/runtime-playground/src/mount-materialization.ts +++ b/packages/runtime-playground/src/mount-materialization.ts @@ -2,8 +2,8 @@ import { createHash } from "node:crypto" import { constants } from "node:fs" import { cp, lstat, mkdir, mkdtemp, open, readdir, readFile, realpath, rename, rm, stat, writeFile } from "node:fs/promises" import { tmpdir } from "node:os" -import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path" -import { materializationPhaseResult, namedFileTreeSkipPolicy, namedFileTreeSkipPolicyNames, phpStringArrayLiteral, type MaterializationDiagnostic, type MaterializationPhaseResult, type MountSpec } from "@automattic/wp-codebox-core" +import { basename, dirname, isAbsolute, join, relative, resolve } from "node:path" +import { materializationPhaseResult, namedFileTreeSkipPolicy, namedFileTreeSkipPolicyNames, pathIsWithinRoot, phpStringArrayLiteral, type MaterializationDiagnostic, type MaterializationPhaseResult, type MountSpec } from "@automattic/wp-codebox-core" import type { PlaygroundCliServer } from "./preview-server.js" import { SKIPPED_CAPTURE_DIRECTORIES } from "./artifacts.js" import { withPlaygroundArchiveCacheLock } from "./playground-wordpress-archive-cache.js" @@ -80,19 +80,25 @@ export async function stageReadonlyPlaygroundMounts(mounts: MountSpec[]): Promis return { mount, diagnostics: [] } } const source = join(root, `${index}-${basename(mount.source) || "mount"}`) - const sourceRoot = await realpath(mount.source) + const resolvedSource = await realpath(mount.source) + const containmentRoot = mount.sourceRoot === undefined ? resolvedSource : await realpath(mount.sourceRoot) + if (!pathIsWithinRoot(resolvedSource, containmentRoot)) { + throw new Error(`Readonly mount sourceRoot must contain the mount source: ${mount.target}`) + } const diagnostics: MaterializationDiagnostic[] = [] const startedAt = Date.now() let preparation: ReadonlyMountPreparation if (mount.type === "file") { - await cp(mount.source, source, { dereference: true }) + await cp(resolvedSource, source, { dereference: true }) const sourceStat = await stat(source) preparation = { mode: "cache-miss", bytes: sourceStat.size, files: 1, elapsedMs: Date.now() - startedAt } } else { - preparation = await prepareReadonlyDirectory(mount, index, sourceRoot, source, diagnostics) + preparation = await prepareReadonlyDirectory(mount, index, { source: resolvedSource, containmentRoot }, source, diagnostics) } diagnostics.sort((left, right) => String(left.metadata?.path) < String(right.metadata?.path) ? -1 : String(left.metadata?.path) > String(right.metadata?.path) ? 1 : 0) - return { mount: { ...mount, source }, diagnostics, preparation } + const stagedMount = { ...mount, source } + delete stagedMount.sourceRoot + return { mount: stagedMount, diagnostics, preparation } })) const failedMount = stagedMountResults.find((result) => result.status === "rejected") if (failedMount?.status === "rejected") { @@ -120,9 +126,14 @@ export async function stageReadonlyPlaygroundMounts(mounts: MountSpec[]): Promis } } -async function prepareReadonlyDirectory(mount: MountSpec, mountIndex: number, sourceRoot: string, destination: string, diagnostics: MaterializationDiagnostic[]): Promise { +interface ReadonlyMountTree { + source: string + containmentRoot: string +} + +async function prepareReadonlyDirectory(mount: MountSpec, mountIndex: number, tree: ReadonlyMountTree, destination: string, diagnostics: MaterializationDiagnostic[]): Promise { const startedAt = Date.now() - const generation = await readonlyMountSourceGeneration(mount, mountIndex, sourceRoot, diagnostics) + const generation = await readonlyMountSourceGeneration(mount, mountIndex, tree, diagnostics) const cacheRoot = join(tmpdir(), "wp-codebox-readonly-mount-cache-v2") const cachePath = join(cacheRoot, generation.fingerprint) await mkdir(cacheRoot, { recursive: true, mode: 0o700 }) @@ -135,8 +146,8 @@ async function prepareReadonlyDirectory(mount: MountSpec, mountIndex: number, so const temporary = await mkdtemp(join(cacheRoot, ".prepare-")) try { const prepared = join(temporary, "tree") - await stageReadonlyDirectory(mount, mountIndex, sourceRoot, prepared, []) - const verified = await readonlyMountSourceGeneration(mount, mountIndex, sourceRoot, []) + await stageReadonlyDirectory(mount, mountIndex, tree, prepared, []) + const verified = await readonlyMountSourceGeneration(mount, mountIndex, tree, []) if (verified.fingerprint !== generation.fingerprint) { throw new Error(`Readonly mount source changed while preparing snapshot: ${mount.target}`) } @@ -164,7 +175,7 @@ async function prepareReadonlyDirectory(mount: MountSpec, mountIndex: number, so return { mode, bytes: generation.bytes, files: generation.files, elapsedMs: Date.now() - startedAt } } -async function readonlyMountSourceGeneration(mount: MountSpec, mountIndex: number, sourceRoot: string, diagnostics: MaterializationDiagnostic[]): Promise { +async function readonlyMountSourceGeneration(mount: MountSpec, mountIndex: number, { source, containmentRoot }: ReadonlyMountTree, diagnostics: MaterializationDiagnostic[]): Promise { const entries: string[] = [] let bytes = 0 let files = 0 @@ -196,7 +207,7 @@ async function readonlyMountSourceGeneration(mount: MountSpec, mountIndex: numbe addReadonlySymlinkDiagnostic(diagnostics, mount, mountIndex, relativePath, "dangling-target") continue } - if (!pathIsWithinRoot(sourceRoot, target)) { + if (!pathIsWithinRoot(target, containmentRoot)) { addReadonlySymlinkDiagnostic(diagnostics, mount, mountIndex, relativePath, "source-escape") continue } @@ -214,8 +225,8 @@ async function readonlyMountSourceGeneration(mount: MountSpec, mountIndex: numbe } } } - await visit(sourceRoot, "", new Set([sourceRoot])) - return { fingerprint: createHash("sha256").update(`${sourceRoot}\0${entries.join("\n")}`).digest("hex"), bytes, files } + await visit(source, "", new Set([source])) + return { fingerprint: createHash("sha256").update(`${source}\0${containmentRoot}\0${entries.join("\n")}`).digest("hex"), bytes, files } } async function directoryExists(path: string): Promise { @@ -237,7 +248,7 @@ async function retainReadonlyMountCache(cacheRoot: string, current: string): Pro } } -async function stageReadonlyDirectory(mount: MountSpec, mountIndex: number, sourceRoot: string, destination: string, diagnostics: MaterializationDiagnostic[]): Promise { +async function stageReadonlyDirectory(mount: MountSpec, mountIndex: number, { source, containmentRoot }: ReadonlyMountTree, destination: string, diagnostics: MaterializationDiagnostic[]): Promise { const visit = async (directory: string, stagedDirectory: string, relativeDirectory: string, ancestors: ReadonlySet): Promise => { await mkdir(stagedDirectory, { recursive: true }) const entries = await readdir(directory, { withFileTypes: true }) @@ -268,7 +279,7 @@ async function stageReadonlyDirectory(mount: MountSpec, mountIndex: number, sour addReadonlySymlinkDiagnostic(diagnostics, mount, mountIndex, relativePath, "dangling-target") continue } - if (!pathIsWithinRoot(sourceRoot, target)) { + if (!pathIsWithinRoot(target, containmentRoot)) { addReadonlySymlinkDiagnostic(diagnostics, mount, mountIndex, relativePath, "source-escape") continue } @@ -288,12 +299,7 @@ async function stageReadonlyDirectory(mount: MountSpec, mountIndex: number, sour } } - await visit(sourceRoot, destination, "", new Set([sourceRoot])) -} - -function pathIsWithinRoot(root: string, path: string): boolean { - const relativePath = relative(root, path) - return relativePath !== ".." && !relativePath.startsWith(`..${sep}`) && !isAbsolute(relativePath) + await visit(source, destination, "", new Set([source])) } function addReadonlySymlinkDiagnostic(diagnostics: MaterializationDiagnostic[], mount: MountSpec, mountIndex: number, path: string, reason: "dangling-target" | "source-escape" | "directory-cycle"): void { diff --git a/tests/generic-ability-runtime-run.test.ts b/tests/generic-ability-runtime-run.test.ts index 86af4e5b..063a7373 100644 --- a/tests/generic-ability-runtime-run.test.ts +++ b/tests/generic-ability-runtime-run.test.ts @@ -1,5 +1,5 @@ import assert from "node:assert/strict" -import { mkdir, readFile, writeFile } from "node:fs/promises" +import { mkdir, readFile, realpath, symlink, writeFile } from "node:fs/promises" import { join } from "node:path" import { runRecipeBuildCommand } from "../packages/cli/src/commands/recipe-build.js" @@ -80,6 +80,23 @@ await withTempDir("wp-codebox-generic-ability-runtime-run-", async (root) => { assert.equal(cliRecipe.inputs.extra_plugins.length, 2) assert.equal(cliRecipe.runtime.overlays[0].library, "example-runtime") + const packages = join(root, "packages") + await mkdir(packages) + await writeFile(join(packages, "lib.php"), " { + const nestedRecipe = buildGenericAbilityRuntimeRunRecipe({ + abilityId: "example/runtime-run", + artifactsPath, + components: [{ source: root, sourceRoot: root, sourceSubpath: "example-component", slug: "example-component" }], + }) + const plugin = nestedRecipe.inputs?.extra_plugins?.[0] + assert.ok(plugin?.sourceRoot) + assert.equal(plugin.sourceRoot, join(await realpath(artifactsPath), "prepared-plugins", "example-component")) + assert.equal(plugin.source, join(plugin.sourceRoot, "example-component")) + assert.equal(await readFile(join(plugin.source, "vendor-link", "lib.php"), "utf8"), " arg.startsWith("input=")) assert.ok(allowedToolsInputArg) diff --git a/tests/playground-readonly-mounts.test.ts b/tests/playground-readonly-mounts.test.ts index 24e9083b..cdb752d3 100644 --- a/tests/playground-readonly-mounts.test.ts +++ b/tests/playground-readonly-mounts.test.ts @@ -141,6 +141,40 @@ try { assert.equal((reused.phaseResult.metadata as { preparation: { mode: string; reused: number } }).preparation.reused, 1, "reuse evidence counts the cached mount") await reused[Symbol.asyncDispose]() + const monorepo = join(root, "monorepo") + const nestedPlugin = join(monorepo, "plugins", "myplug") + const library = join(monorepo, "packages", "lib") + await mkdir(nestedPlugin, { recursive: true }) + await mkdir(library, { recursive: true }) + await writeFile(join(library, "lib.php"), " ({ code, metadata })), + (includesLibrary ? ["escaping.php"] : ["escaping.php", "vendor-link"]).map((path) => ({ + code: "readonly-mount-symlink-skipped", + metadata: { mountIndex: 0, mountTarget: target, path, reason: "source-escape" }, + }))) + } + await assert.rejects(stageReadonlyPlaygroundMounts([ + { source: nestedPlugin, sourceRoot: library, target, mode: "readonly" }, + ]), /sourceRoot must contain the mount source/) + const cloneIsolationSource = join(root, "clone-isolation-source") await mkdir(cloneIsolationSource) await writeFile(join(cloneIsolationSource, "value.txt"), "canonical") diff --git a/tests/recipe-extra-plugin-nested-source.test.ts b/tests/recipe-extra-plugin-nested-source.test.ts index b12b2739..91779a8b 100644 --- a/tests/recipe-extra-plugin-nested-source.test.ts +++ b/tests/recipe-extra-plugin-nested-source.test.ts @@ -1,5 +1,5 @@ import assert from "node:assert/strict" -import { mkdir, stat, writeFile } from "node:fs/promises" +import { mkdir, stat, symlink, writeFile } from "node:fs/promises" import { join } from "node:path" import { validateWorkspaceRecipeSemantics } from "../packages/cli/src/recipe-validation.js" @@ -34,6 +34,7 @@ await withTempDir("wp-codebox-nested-extra-plugin-", async (recipeDirectory) => assert.equal(plugin.slug, "example-plugin") assert.equal(plugin.target, "/wordpress/wp-content/plugins/example-plugin") assert.equal(plugin.pluginFile, "example-plugin/example-plugin.php") + assert.equal(plugin.sourceRoot, undefined, "sourcePath alone does not widen symlink containment") assert.equal(plugin.metadata?.sourceRoot, "repo") assert.equal(plugin.metadata?.sourceSubpath, "packages/example-plugin") assert.equal((await stat(join(plugin.source, "example-plugin.php"))).isFile(), true) @@ -103,6 +104,9 @@ await withTempDir("wp-codebox-nested-extra-plugin-invalid-", async (recipeDirect await mkdir(join(repo, "plugins", "nested-plugin"), { recursive: true }) await writeFile(join(repo, "plugins", "nested-plugin", "nested-plugin.php"), " } ? Plugin : never : never): WorkspaceRecipe => ({ schema: "wp-codebox/workspace-recipe/v1", inputs: { extra_plugins: [extraPlugin] }, @@ -110,6 +114,11 @@ await withTempDir("wp-codebox-nested-extra-plugin-invalid-", async (recipeDirect }) const cases: Array<{ name: string, plugin: NonNullable["extra_plugins"][number], issue: string }> = [ + { + name: "symlinked sourceSubpath outside the root", + plugin: { source: "repo", sourceRoot: "repo", sourceSubpath: "escape", slug: "nested-plugin", pluginFile: "nested-plugin/nested-plugin.php" }, + issue: "invalid-source-root", + }, { name: "path traversal sourceSubdir", plugin: { sourcePath: "repo", sourceSubdir: "../outside", mountSlug: "nested-plugin", pluginFile: "nested-plugin/nested-plugin.php" },