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
86 changes: 5 additions & 81 deletions packages/cli/src/recipe-sources.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,13 @@ import { fileURLToPath } from "node:url"
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"
import { applyRecipeSourceSubpath, collectPreparedSourceCleanupPaths, DEFAULT_PREPARED_SOURCE_EXCLUDE_NAMES, localPreparedSourceProvenance, localRecipeExtraPluginSource, normalizeExternalSourceSubpath, prepareLocalSourceStageSync, recipeExtraPluginSourceSubpath, resolveExternalSourceRef, resolveExternalSourceRoot, resolveExternalSourceSubpath, SANDBOX_WORKSPACE_ROOT, type PreparedSourceProvenance } from "@automattic/wp-codebox-core/internals"
import { BUNDLED_MDI_NATIVE_ARCHIVE_PATH } from "./mdi-native-archive.js"
import { registerRuntimeOverlayDescriptor, runtimeOverlayDescriptor } from "./runtime-overlay-registry.js"
import { evaluateSourcePolicy, evaluateZipSourcePolicy, sourcePolicySnapshot, type SourcePolicyIssue } from "./source-policy.js"
import { prepareLocalZipSource, prepareZipSource } from "./zip-source.js"

export { recipeExtraPluginSourceSubpath }
export { ALLOW_NETWORK_DOWNLOADS_ENV, ALLOWED_DOWNLOAD_HOSTS_ENV, allowedDownloadHosts, isSha256, maxDownloadBytes, maxExtractedBytes, maxExtractedFiles, MAX_DOWNLOAD_BYTES_ENV, MAX_EXTRACTED_BYTES_ENV, MAX_EXTRACTED_FILES_ENV, REQUIRE_SOURCE_SHA256_ENV, sourceSha256Required } from "./source-policy.js"

const PHP_AI_CLIENT_RUNTIME_OVERLAY_TARGET = "/wordpress/wp-includes/php-ai-client"
Expand Down Expand Up @@ -308,7 +309,7 @@ export async function prepareExtraPlugins(plugins: readonly WorkspaceRecipeExtra
const resolved = await prepareRecipeSource(sourceRootRef, recipeDirectory, slug, plugin.sha256, options)
const pluginResolved = {
...resolved,
source: sourceSubpath ? join(resolved.source, sourceSubpath) : resolved.source,
source: applyRecipeSourceSubpath(resolved.source, sourceSubpath),
...(recipeExtraPluginDeclaresContainmentRoot(plugin, sourceRootRef) ? { sourceRoot: resolved.source } : {}),
}
if (pluginResolved.sourceRoot !== undefined) {
Expand Down Expand Up @@ -1988,29 +1989,7 @@ export function recipeSourceProvenance(source: ParsedRecipeSource, recipeDirecto
* used in error messages and the input-specific fields (pluginFile/loadAs/
* composer for plugins, activate for themes) differ.
*/
interface RecipeExternalSourceRef {
source?: string
sourcePath?: string
sourceRoot?: string
sourceSubpath?: string
sourceSubdir?: string
originalSource?: string
slug?: string
mountSlug?: string
sha256?: string
}

function resolveExternalSourceRef(ref: RecipeExternalSourceRef, inputName: string): string {
if (ref.source !== undefined) {
return ref.source
}
if (ref.sourcePath !== undefined) {
return ref.sourcePath
}
throw new Error(`Recipe ${inputName} entries must include source or sourcePath`)
}

function resolveExternalSourceSlug(ref: RecipeExternalSourceRef, inputName: string): string {
function resolveExternalSourceSlug(ref: WorkspaceRecipeExtraPlugin | WorkspaceRecipeExtraTheme, inputName: string): string {
if (ref.mountSlug) {
return ref.mountSlug
}
Expand All @@ -2032,54 +2011,6 @@ function resolveExternalSourceSlug(ref: RecipeExternalSourceRef, inputName: stri
return basename(resolve(sourceRef))
}

function resolveExternalSourceRoot(ref: RecipeExternalSourceRef, inputName: string, recipeDirectory = "."): string {
if (ref.sourcePath) {
return ref.sourcePath
}

if (ref.sourceRoot && externalSourceRootContainsSource(ref, inputName, ref.sourceRoot, recipeDirectory)) {
return ref.sourceRoot
}

return ref.originalSource ?? resolveExternalSourceRef(ref, inputName)
}

function resolveExternalSourceSubpath(ref: RecipeExternalSourceRef, inputName: string, recipeDirectory: string): string {
const explicitSubpath = ref.sourceSubdir ?? ref.sourceSubpath
const declaredSourceRoot = ref.sourcePath ?? ref.sourceRoot
if (explicitSubpath && declaredSourceRoot && externalSourceRootContainsSource(ref, inputName, declaredSourceRoot, recipeDirectory)) {
return normalizeExternalSourceSubpath(explicitSubpath, inputName)
}

const sourceRoot = resolveExternalSourceRoot(ref, inputName, recipeDirectory)
const sourceRef = resolveExternalSourceRef(ref, inputName)
if (sourceRoot === sourceRef) {
return ""
}

if (!externalSourceRootContainsSource(ref, inputName, sourceRoot, recipeDirectory)) {
return ""
}
const relativePath = relative(resolve(recipeDirectory, sourceRoot), resolve(recipeDirectory, sourceRef))
return relativePath ? normalizeReviewerSafePath(relativePath) : ""
}

function externalSourceRootContainsSource(ref: RecipeExternalSourceRef, inputName: string, sourceRoot: string, recipeDirectory: string): boolean {
return pathIsWithinRoot(resolve(recipeDirectory, resolveExternalSourceRef(ref, inputName)), resolve(recipeDirectory, sourceRoot))
}

function normalizeExternalSourceSubpath(value: string, inputName: string): string {
const rootMarker = value.trim().replace(/\\/g, "/").replace(/\/+$/, "")
if (rootMarker === ".") {
return ""
}
const normalized = normalizeReviewerSafePath(value)
if (!normalized || normalized === "." || normalized.startsWith("../") || normalized.includes("/../") || isAbsolute(normalized)) {
throw new Error(`Recipe ${inputName} sourceSubdir/sourceSubpath must be a safe relative directory: ${value}`)
}
return normalized
}

export function recipeExtraPluginSlug(plugin: WorkspaceRecipeExtraPlugin): string {
return resolveExternalSourceSlug(plugin, "extra_plugins")
}
Expand All @@ -2105,10 +2036,6 @@ export async function assertExtraPluginSourceWithinRoot(source: string, sourceRo
}
}

export function recipeExtraPluginSourceSubpath(plugin: WorkspaceRecipeExtraPlugin, recipeDirectory: string): string {
return resolveExternalSourceSubpath(plugin, "extra_plugins", recipeDirectory)
}

export function normalizeRecipeExtraPluginSourceSubpath(value: string): string {
return normalizeExternalSourceSubpath(value, "extra_plugins")
}
Expand Down Expand Up @@ -2167,10 +2094,7 @@ export async function resolveRecipeExtraPluginFile(plugin: WorkspaceRecipeExtraP
const sourceRef = recipeExtraPluginSource(plugin)
const source = recipeSource(sourceRef, plugin.sha256)
if (source.type === "local") {
const sourceRoot = resolve(recipeDirectory, recipeExtraPluginSourceRoot(plugin, recipeDirectory))
const sourceSubpath = recipeExtraPluginSourceSubpath(plugin, recipeDirectory)
const pluginSource = sourceSubpath ? join(sourceRoot, sourceSubpath) : resolve(recipeDirectory, sourceRef)
return resolvePluginEntrypointContract({ source: pluginSource, slug, loadAs: plugin.loadAs }).pluginFile
return resolvePluginEntrypointContract({ source: localRecipeExtraPluginSource(plugin, recipeDirectory), slug, loadAs: plugin.loadAs }).pluginFile
}

return `${slug}/${slug}.php`
Expand Down
1 change: 1 addition & 0 deletions packages/runtime-core/src/internals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ export * from "./fanout-aggregation.js"
export * from "./fanout-execution.js"
export * from "./object-utils.js"
export * from "./prepared-source-staging.js"
export * from "./recipe-external-source-paths.js"
export * from "./redaction.js"
export * from "./runtime-action-adapter.js"
export * from "./status-taxonomy.js"
Expand Down
8 changes: 7 additions & 1 deletion packages/runtime-core/src/recipe-builders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export { RUNTIME_PACKAGE_DIAGNOSTIC_SCHEMA, RUNTIME_PACKAGE_RESULT_SCHEMA, RUNTI
import { normalizeSharedMounts } from "./mount-primitives.js"
import { DEFAULT_WORDPRESS_VERSION } from "./runtime-defaults.js"
import { resolvePluginEntrypointContract } from "./component-contracts.js"
import { localRecipeExtraPluginSource } from "./recipe-external-source-paths.js"

type JsonObject = Record<string, unknown>

Expand Down Expand Up @@ -154,7 +155,12 @@ function phpunitDependencyPlugins(mounts: readonly string[], plugins: readonly W
const plugin = plugins.find((candidate) => candidate.slug === slug || candidate.mountSlug === slug)
const loadAs = plugin?.loadAs === "mu-plugin" ? "mu-plugin" : "plugin"
const pluginFile = plugin
? resolvePluginEntrypointContract({ source: plugin.source ?? plugin.sourcePath ?? "", slug, pluginFile: plugin.pluginFile, loadAs }).pluginFile
? resolvePluginEntrypointContract({
source: plugin.pluginFile ? plugin.source ?? plugin.sourcePath ?? "" : localRecipeExtraPluginSource(plugin, "."),
slug,
pluginFile: plugin.pluginFile,
loadAs,
}).pluginFile
: `${slug}/${slug}.php`
return {
path: loadAs === "mu-plugin" ? `/wordpress/wp-content/mu-plugins/contained-runtime/${slug}` : path,
Expand Down
86 changes: 86 additions & 0 deletions packages/runtime-core/src/recipe-external-source-paths.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import { isAbsolute, join, relative, resolve } from "node:path"
import { pathIsWithinRoot } from "./file-tree-policy.js"
import { normalizeReviewerSafePath } from "./recipe-source-packages.js"
import type { WorkspaceRecipeExtraPlugin } from "./runtime-contracts.js"

interface RecipeExternalSourcePath {
source?: string
sourcePath?: string
sourceRoot?: string
sourceSubpath?: string
sourceSubdir?: string
originalSource?: string
}

export function resolveExternalSourceRef(ref: RecipeExternalSourcePath, inputName: string): string {
if (ref.source !== undefined) {
return ref.source
}
if (ref.sourcePath !== undefined) {
return ref.sourcePath
}
throw new Error(`Recipe ${inputName} entries must include source or sourcePath`)
}

export function resolveExternalSourceRoot(ref: RecipeExternalSourcePath, inputName: string, recipeDirectory = "."): string {
if (ref.sourcePath) {
return ref.sourcePath
}

if (ref.sourceRoot && externalSourceRootContainsSource(ref, inputName, ref.sourceRoot, recipeDirectory)) {
return ref.sourceRoot
}

return ref.originalSource ?? resolveExternalSourceRef(ref, inputName)
}

export function resolveExternalSourceSubpath(ref: RecipeExternalSourcePath, inputName: string, recipeDirectory: string, implicitRoot?: string): string {
const explicitSubpath = ref.sourceSubdir ?? ref.sourceSubpath
const declaredSourceRoot = ref.sourcePath ?? ref.sourceRoot ?? implicitRoot
if (explicitSubpath && declaredSourceRoot && externalSourceRootContainsSource(ref, inputName, declaredSourceRoot, recipeDirectory)) {
return normalizeExternalSourceSubpath(explicitSubpath, inputName)
}

const sourceRoot = resolveExternalSourceRoot(ref, inputName, recipeDirectory)
const sourceRef = resolveExternalSourceRef(ref, inputName)
if (sourceRoot === sourceRef || !externalSourceRootContainsSource(ref, inputName, sourceRoot, recipeDirectory)) {
return ""
}
const relativePath = relative(resolve(recipeDirectory, sourceRoot), resolve(recipeDirectory, sourceRef))
return relativePath ? normalizeReviewerSafePath(relativePath) : ""
}

function externalSourceRootContainsSource(ref: RecipeExternalSourcePath, inputName: string, sourceRoot: string, recipeDirectory: string): boolean {
return pathIsWithinRoot(resolve(recipeDirectory, resolveExternalSourceRef(ref, inputName)), resolve(recipeDirectory, sourceRoot))
}

export function normalizeExternalSourceSubpath(value: string, inputName: string): string {
const rootMarker = value.trim().replace(/\\/g, "/").replace(/\/+$/, "")
if (rootMarker === ".") {
return ""
}
const normalized = normalizeReviewerSafePath(value)
if (!normalized || normalized === "." || normalized.startsWith("../") || normalized.includes("/../") || isAbsolute(normalized)) {
throw new Error(`Recipe ${inputName} sourceSubdir/sourceSubpath must be a safe relative directory: ${value}`)
}
return normalized
}

export function recipeExtraPluginSourceSubpath(plugin: WorkspaceRecipeExtraPlugin, recipeDirectory: string): string {
// A bare source can be the root of a nested plugin. Preserve root inference
// for prepared sources carrying originalSource provenance.
const implicitRoot = plugin.originalSource === undefined ? plugin.source : undefined
return resolveExternalSourceSubpath(plugin, "extra_plugins", recipeDirectory, implicitRoot)
}

export function applyRecipeSourceSubpath(source: string, sourceSubpath: string): string {
return sourceSubpath ? join(source, sourceSubpath) : source
}

export function localRecipeExtraPluginSource(plugin: WorkspaceRecipeExtraPlugin, recipeDirectory: string): string {
const sourceSubpath = recipeExtraPluginSourceSubpath(plugin, recipeDirectory)
const source = sourceSubpath
? resolveExternalSourceRoot(plugin, "extra_plugins", recipeDirectory)
: resolveExternalSourceRef(plugin, "extra_plugins")
return applyRecipeSourceSubpath(resolve(recipeDirectory, source), sourceSubpath)
}
25 changes: 24 additions & 1 deletion tests/phpunit-project-autoload.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { corePhpunitRunCode, phpunitMultisitePreinstallCode, phpunitRunCode } fr
import { runPhpunitCommand } from "../packages/runtime-playground/src/wordpress-command-runners.js"
import { phpunitExecutionSemantics, requiresManagedMultisitePreinstall } from "../packages/runtime-playground/src/phpunit-command-semantics.js"
import { recipePolicy } from "../packages/cli/src/recipe-validation.js"
import { recipeExtraPluginSourceSubpath } from "../packages/cli/src/recipe-sources.js"
import { prepareRecipeExtraPlugins, recipeExtraPluginSourceSubpath } from "../packages/cli/src/recipe-sources.js"
import { recipeInputMountPathMap, rewriteInputMountPathArgs } from "../packages/cli/src/commands/recipe-runtime-setup.js"
import { wordpressRuntimeSpec } from "../scripts/test-kit.js"

Expand Down Expand Up @@ -934,6 +934,29 @@ assert.ok(managedModeCode.includes("dirname($dep_real) !== $plugin_root"), "depe
assert.ok(managedModeCode.includes("managed PHPUnit dependency path is not canonical"), "dependency loading rejects non-canonical sandbox paths")
assert.equal(managedModeCode.includes("glob($dep_real"), false, "dependency loading never scans for an arbitrary plugin header")

const dependencyRepo = mkdtempSync(join(tmpdir(), "wp-codebox-phpunit-dependency-"))
try {
const demoSource = join(dependencyRepo, "plugins", "demo")
mkdirSync(demoSource, { recursive: true })
writeFileSync(join(dependencyRepo, "root.php"), "<?php\n/* Plugin Name: Root Stub */\n")
writeFileSync(join(demoSource, "demo.php"), "<?php\n/* Plugin Name: Demo */\n")
const nestedDependencyRecipe = buildWordPressPhpunitRecipe({
pluginSlug: "demo-plugin",
extra_plugins: [{ source: dependencyRepo, sourceSubpath: "plugins/demo", slug: "demo" }],
dependencyMounts: ["/wordpress/wp-content/plugins/demo"],
})
assert.equal(
nestedDependencyRecipe.workflow.steps[0].args.find((arg) => arg.startsWith("dependency-plugins-json=")),
'dependency-plugins-json=[{"path":"/wordpress/wp-content/plugins/demo","pluginFile":"demo/demo.php","activate":true,"loadAs":"plugin"}]',
"PHPUnit resolves the entrypoint from the mounted subdirectory, not the repository root",
)
const [mountedPlugin] = await prepareRecipeExtraPlugins(nestedDependencyRecipe, dependencyRepo)
assert.equal(mountedPlugin.source, demoSource)
assert.equal(mountedPlugin.pluginFile, "demo/demo.php")
} finally {
rmSync(dependencyRepo, { recursive: true, force: true })
}

const explicitMuDependencyRecipe = buildWordPressPhpunitRecipe({
pluginSlug: "demo-plugin",
extra_plugins: [{ source: "/workspace/mu-dependency", slug: "mu-dependency", pluginFile: "bootstrap.php", activate: true, loadAs: "mu-plugin" }],
Expand Down
Loading