diff --git a/docs/recipe-contract.md b/docs/recipe-contract.md index b0a2bfc4..2330f6eb 100644 --- a/docs/recipe-contract.md +++ b/docs/recipe-contract.md @@ -94,6 +94,82 @@ Recipe bootstrap entries override these defaults. Use `bootstrapIniEntries`, not runtime `iniEntries`, for opcache settings that must apply at PHP startup. The defaults do not affect the choice of Playground runner. +## Host Process Execution + +`runtime.hostProcess` controls where PHP process functions run: `exec()`, +`shell_exec()`, `system()`, `passthru()`, `popen()` and `proc_open()`. + +- `none` is the default, and omitting the field means the same. Playground's + sandboxed spawn handler stays in place. It runs only php-wasm's own `php`, + `ls` and `pwd`, and every other command exits 127. Host processes are + unavailable. +- `shell` installs a spawn handler that runs each command on the host: + - String commands go through `/bin/sh -c `. + - Argv commands (`proc_open([...])`) run directly, as in native PHP. + - stdin, stdout, stderr and the exit status are streamed. + - Command strings are never parsed, filtered or allowlisted. + - Codebox's own sandbox PHP binary, `/internal/shared/bin/php`, used by + PHPUnit process isolation, still runs inside php-wasm. That binary does not + exist on the host. + +```json +{ "runtime": { "backend": "wordpress-playground", "hostProcess": "shell" } } +``` + +The PHPUnit recipe builder accepts the same option as `hostProcess: "shell"`. + +When `shell` is on, PHP and host commands share these paths: + +- **Temp directory.** Each run creates a host directory, + `/wp-codebox-host-process-*`, and mounts it into PHP at the same + absolute path. + - PHP's `sys_temp_dir` points at it, so `sys_get_temp_dir()` and `tempnam()` + return paths the host command can open unchanged. + - Host commands get the same path in `TMPDIR`. + - The directory is removed when the runtime is disposed. + - PHP's virtual `/tmp` is not shared, so pass `sys_get_temp_dir()` paths to + host commands, not literal `/tmp` paths. +- **Working directory.** A command's working directory is PHP's working + directory, or the `proc_open()` `$cwd`, translated through the run's mounts. + - `/wordpress` maps to the WordPress directory, and each recipe mount maps to + its host source. + - Unmapped virtual paths fall back to the shared temp directory. +- **Environment.** Host commands get: + - the host `PATH`, `HOME`, `USER`, `LOGNAME`, `SHELL`, `LANG`, `LC_*` and + `TZ`; + - the run's `runtimeEnv` and distribution env (`DB_*` and similar); + - resolved `secretEnv` targets; + - `TMPDIR`. + + An explicit `proc_open()` `$env` overrides these. PHP sees the same `PATH` + and `TMPDIR` through `getenv()`. + +Known limitation: php-wasm's `popen()` path does not propagate exit codes, for +any spawn handler. This path is used by `exec()`, `system()`, `passthru()` and +`shell_exec()`, so their `$result_code` is not the host status, but their output +is. `proc_open()` with `proc_close()` returns the host exit status. + +**Trust boundary.** `shell` lets the code under test run arbitrary host commands +with the privileges of the WP Codebox process: + +- the host user; +- the host filesystem outside the mounts; +- the host network, regardless of `policy.network`; +- any secrets passed to the run. + +Enable it only for trusted review and gate runs on disposable or CI hosts. +Never enable it for untrusted plugins, agent-authored code or shared +multi-tenant hosts. + +Every run with the capability on records it: + +- a `runtime.host-process-execution` lifecycle event; +- a `hostProcessExecution` block in the bundle `metadata.json`, with schema + `wp-codebox/host-process-execution/v1`. It holds the mode, the shared temp + directory, the working-directory mappings and the forwarded environment + variable names. Values are never recorded. +- a `host-process-execution` entry in `files/review.json` `riskFlags`. + ## Stable Field Names Recipe field names are case-sensitive. The current recipe schema accepts these diff --git a/packages/cli/src/commands/recipe-build.ts b/packages/cli/src/commands/recipe-build.ts index 92d89238..2ab425e7 100644 --- a/packages/cli/src/commands/recipe-build.ts +++ b/packages/cli/src/commands/recipe-build.ts @@ -1,5 +1,5 @@ import { readFile, writeFile } from "node:fs/promises" -import { buildGenericAbilityRuntimeRunRecipe, buildRuntimePackageRunRecipe, buildWordPressBenchRecipe, buildWordPressPhpunitRecipe, compileRecipeTemplate, type GenericAbilityRuntimeRunOptions, type RecipeTemplateInput, type RuntimePackageRunRecipeOptions, type RuntimeWorkerCount, type RuntimeWordPressInstallMode, type WorkspaceRecipe, type WorkspaceRecipeExtraPlugin, type WorkspaceRecipeMount, type WorkspaceRecipePHPWasmExtensionManifest, type WorkspaceRecipeRuntimeBackendPackage, type WorkspaceRecipeRuntimeService, type WorkspaceRecipeStep } from "@automattic/wp-codebox-core" +import { buildGenericAbilityRuntimeRunRecipe, buildRuntimePackageRunRecipe, buildWordPressBenchRecipe, buildWordPressPhpunitRecipe, compileRecipeTemplate, type GenericAbilityRuntimeRunOptions, type RecipeTemplateInput, type RuntimeHostProcessMode, type RuntimePackageRunRecipeOptions, type RuntimeWorkerCount, type RuntimeWordPressInstallMode, type WorkspaceRecipe, type WorkspaceRecipeExtraPlugin, type WorkspaceRecipeMount, type WorkspaceRecipePHPWasmExtensionManifest, type WorkspaceRecipeRuntimeBackendPackage, type WorkspaceRecipeRuntimeService, type WorkspaceRecipeStep } from "@automattic/wp-codebox-core" interface RecipeBuildOptions { recipeType: "phpunit" | "bench" | "template" | "generic-ability-runtime-run" | "runtime-package-run" @@ -14,6 +14,7 @@ interface WordPressPhpunitBuilderOptions { workers?: RuntimeWorkerCount databaseType?: "sqlite" | "mysql" | "mdi-native" wordpressInstallMode?: RuntimeWordPressInstallMode + hostProcess?: RuntimeHostProcessMode extensions?: WorkspaceRecipePHPWasmExtensionManifest[] backendPackage?: WorkspaceRecipeRuntimeBackendPackage mounts?: WorkspaceRecipeMount[] @@ -87,6 +88,7 @@ function buildRecipe(recipeType: RecipeBuildOptions["recipeType"], options: Word workers: workerCountOrUndefined(phpunitOptions.workers), databaseType: phpunitOptions.databaseType, wordpressInstallMode: phpunitOptions.wordpressInstallMode, + hostProcess: phpunitOptions.hostProcess, extensions: Array.isArray(phpunitOptions.extensions) ? phpunitOptions.extensions : [], backendPackage: phpunitOptions.backendPackage, mounts: Array.isArray(phpunitOptions.mounts) ? phpunitOptions.mounts : [], diff --git a/packages/cli/src/commands/recipe-run.ts b/packages/cli/src/commands/recipe-run.ts index 8e5d38ba..aacb3217 100644 --- a/packages/cli/src/commands/recipe-run.ts +++ b/packages/cli/src/commands/recipe-run.ts @@ -288,6 +288,7 @@ export async function runRecipe(options: RecipeRunOptions, interruption?: Recipe assets: resolveRecipeRuntimeAssets(recipe, recipeDirectory), extensions: resolveRecipeRuntimeExtensionManifests(recipe, recipeDirectory), bundledExtensions: recipe.runtime?.bundledExtensions, + ...(recipe.runtime?.hostProcess && recipe.runtime.hostProcess !== "none" ? { hostProcess: recipe.runtime.hostProcess } : {}), } const effectivePreview = effectiveRecipePreview(recipe.runtime?.preview, options) const runtimeCreateSpec = { diff --git a/packages/cli/src/recipe-validation.ts b/packages/cli/src/recipe-validation.ts index c57060ba..f7ffa927 100644 --- a/packages/cli/src/recipe-validation.ts +++ b/packages/cli/src/recipe-validation.ts @@ -1,7 +1,7 @@ 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, 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 { BROWSER_PROBE_CHROMIUM_PROFILE_IDS, RUNTIME_BACKED_FUZZ_SUITE_RUNNER_CAPABILITIES, RUNTIME_HOST_PROCESS_MODES, 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 { 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" @@ -154,6 +154,7 @@ export function validateWorkspaceRecipeShape(recipe: WorkspaceRecipe, recipePath validateRecipeRuntimeAssets(recipe.runtime?.assets, recipePath) validateRecipeRuntimeExtensions(recipe.runtime?.extensions, recipePath) validateRecipeRuntimeBundledExtensions(recipe.runtime?.bundledExtensions, recipePath) + validateRecipeRuntimeHostProcess(recipe.runtime?.hostProcess, recipePath) validateRecipeRuntimeWordPressInstallMode(recipe.runtime?.wordpressInstallMode, recipePath) validateRecipeRuntimePreview(recipe.runtime?.preview, recipePath) if (recipe.runtime?.hostNodeHeap) assertHostNodeHeapRequirement(recipe.runtime.hostNodeHeap) @@ -421,6 +422,13 @@ function validateRecipeRuntimeBundledExtensions(extensions: NonNullable["wordpressInstallMode"] | undefined, recipePath: string): void { if (mode === undefined) { return diff --git a/packages/runtime-core/src/recipe-builders.ts b/packages/runtime-core/src/recipe-builders.ts index 159fe171..c4f5a272 100644 --- a/packages/runtime-core/src/recipe-builders.ts +++ b/packages/runtime-core/src/recipe-builders.ts @@ -1,4 +1,5 @@ import type { RuntimePreviewSpec, RuntimeWorkerCount, RuntimeWordPressInstallMode, WorkspaceRecipe, WorkspaceRecipeExtraPlugin, WorkspaceRecipeMount, WorkspaceRecipePHPWasmExtensionManifest, WorkspaceRecipeRuntimeBackendPackage, WorkspaceRecipeRuntimeService, WorkspaceRecipeStep } from "./runtime-contracts.js" +import type { RuntimeHostProcessMode } from "./runtime-neutral-contracts.js" import { commandArg, commandJsonArg, commandStringListArg } from "./command-codecs.js" export { buildRuntimePackageRunRecipe, CODEBOX_RUN_RUNTIME_PACKAGE_ABILITY, RUNTIME_PACKAGE_ARTIFACT_DECLARATION_SCHEMA, RUNTIME_PACKAGE_EXECUTION_INPUT_SCHEMA, RUNTIME_PACKAGE_EXECUTION_RESULT_SCHEMA, RUNTIME_PACKAGE_OUTPUT_PROJECTION_SCHEMA, runtimePackageExecutionInput, type RuntimePackageArtifactDeclaration, type RuntimePackageExecutionInput, type RuntimePackageOutputProjection, type RuntimePackageRunRecipeOptions } from "./runtime-package-execution.js" export { RUNTIME_PACKAGE_DIAGNOSTIC_SCHEMA, RUNTIME_PACKAGE_RESULT_SCHEMA, RUNTIME_PACKAGE_TASK_SCHEMA, normalizeRuntimePackageResult, normalizeRuntimePackageTask, validateRuntimePackageTask, type RuntimePackageDiagnostic, type RuntimePackageResult, type RuntimePackageTask } from "./runtime-package-contracts.js" @@ -19,6 +20,8 @@ export interface WordPressPhpunitRecipeOptions { workers?: RuntimeWorkerCount databaseType?: "sqlite" | "mysql" | "mdi-native" wordpressInstallMode?: RuntimeWordPressInstallMode + /** Opt-in host shell for PHP process execution in trusted runs. Defaults to sandboxed. */ + hostProcess?: RuntimeHostProcessMode blueprint?: unknown extensions?: WorkspaceRecipePHPWasmExtensionManifest[] backendPackage?: WorkspaceRecipeRuntimeBackendPackage @@ -98,6 +101,7 @@ export function buildWordPressPhpunitRecipe(options: WordPressPhpunitRecipeOptio ...(options.phpVersion ? { phpVersion: options.phpVersion } : {}), ...(options.workers !== undefined ? { workers: options.workers } : {}), ...(options.wordpressInstallMode ? { wordpressInstallMode: options.wordpressInstallMode } : {}), + ...(options.hostProcess && options.hostProcess !== "none" ? { hostProcess: options.hostProcess } : {}), blueprint: blueprintWithMultisite( blueprintWithWpConfigDefines(options.blueprint ?? { steps: [] }, options.wpConfigDefines ?? {}, "rewrite-wp-config"), (options.multisite ?? false) && options.databaseType !== "mysql", diff --git a/packages/runtime-core/src/recipe-schema.ts b/packages/runtime-core/src/recipe-schema.ts index 65328c66..0213b980 100644 --- a/packages/runtime-core/src/recipe-schema.ts +++ b/packages/runtime-core/src/recipe-schema.ts @@ -161,6 +161,10 @@ export function createWorkspaceRecipeJsonSchema(options: WorkspaceRecipeJsonSche description: "Allowlisted PHP extensions bundled with the Playground runtime.", items: { enum: ["intl", "redis", "memcached", "xdebug"] }, }, + hostProcess: { + enum: ["none", "shell"], + description: "Host process execution for PHP exec()/proc_open(). none (default) keeps Playground's sandboxed spawn handler. shell runs commands through the host /bin/sh -c with the run environment and a shared per-run temp directory; enable only for trusted review and gate runs.", + }, backendPackage: { $ref: "#/$defs/runtimeBackendPackage" }, stack: { $ref: "#/$defs/runtimeStack" }, hostNodeHeap: { diff --git a/packages/runtime-core/src/runtime-contracts.ts b/packages/runtime-core/src/runtime-contracts.ts index f0499133..4b71efe6 100644 --- a/packages/runtime-core/src/runtime-contracts.ts +++ b/packages/runtime-core/src/runtime-contracts.ts @@ -3,7 +3,7 @@ import type { RuntimePolicy } from "./runtime-policy.js" import { SANDBOX_WORKSPACE_ROOT } from "./runtime-action-adapter.js" import type { ArtifactFileDigest, ArtifactManifestFile, ArtifactSpec, ArtifactViewerMetadata } from "./artifact-manifest.js" import type { HostToolDefinition, HostToolRegistry } from "./host-tool-registry.js" -import type { BackendNeutralRuntimeProvenance, RuntimePHPWasmBundledExtension, RuntimePHPWasmExtensionManifest, RuntimeWorkerCount, RuntimeWordPressAssetSpec, RuntimeWordPressDatabaseSetupContract, RuntimeWordPressEnvironmentSpec, RuntimeWordPressInstallModeContract, RuntimeWordPressProvenance } from "./runtime-neutral-contracts.js" +import type { BackendNeutralRuntimeProvenance, RuntimeHostProcessMode, RuntimePHPWasmBundledExtension, RuntimePHPWasmExtensionManifest, RuntimeWorkerCount, RuntimeWordPressAssetSpec, RuntimeWordPressDatabaseSetupContract, RuntimeWordPressEnvironmentSpec, RuntimeWordPressInstallModeContract, RuntimeWordPressProvenance } from "./runtime-neutral-contracts.js" import type { RUNTIME_EPISODE_ACTION_SCHEMA, RUNTIME_EPISODE_OBSERVATION_SCHEMA, @@ -740,6 +740,7 @@ export interface WorkspaceRecipe { assets?: RuntimeAssetSpec extensions?: WorkspaceRecipePHPWasmExtensionManifest[] bundledExtensions?: RuntimePHPWasmBundledExtension[] + hostProcess?: RuntimeHostProcessMode backendPackage?: WorkspaceRecipeRuntimeBackendPackage stack?: WorkspaceRecipeRuntimeStack overlays?: WorkspaceRecipeRuntimeOverlay[] diff --git a/packages/runtime-core/src/runtime-neutral-contracts.ts b/packages/runtime-core/src/runtime-neutral-contracts.ts index 17178153..201b2ecf 100644 --- a/packages/runtime-core/src/runtime-neutral-contracts.ts +++ b/packages/runtime-core/src/runtime-neutral-contracts.ts @@ -75,6 +75,13 @@ export interface RuntimePHPWasmExtensionManifest { export const RUNTIME_PHP_WASM_BUNDLED_EXTENSIONS = ["intl", "redis", "memcached", "xdebug"] as const export type RuntimePHPWasmBundledExtension = typeof RUNTIME_PHP_WASM_BUNDLED_EXTENSIONS[number] +/** + * Host process execution for PHP `exec()`/`proc_open()` and friends. + * `none` (default) keeps the sandboxed spawn handler; `shell` runs commands + * through the host `/bin/sh -c` for trusted runs. See docs/recipe-contract.md. + */ +export const RUNTIME_HOST_PROCESS_MODES = ["none", "shell"] as const +export type RuntimeHostProcessMode = typeof RUNTIME_HOST_PROCESS_MODES[number] export interface RuntimeWordPressEnvironmentSpec extends BackendNeutralEnvironmentSpec { blueprint?: unknown @@ -85,6 +92,7 @@ export interface RuntimeWordPressEnvironmentSpec extends BackendNeutralEnvironme databaseSetup?: RuntimeWordPressDatabaseSetupContract extensions?: RuntimePHPWasmExtensionManifest[] bundledExtensions?: RuntimePHPWasmBundledExtension[] + hostProcess?: RuntimeHostProcessMode } export type BackendNeutralReplayStatus = "metadata-only" | "partial-replay" | "replayable-runtime-state" | "runtime-state-artifact" | "not-replayable" | (string & {}) @@ -141,9 +149,18 @@ export function normalizeRuntimeWordPressEnvironmentSpec(input: unknown): Runtim databaseSetup: optionalString(value.databaseSetup, "environment.databaseSetup") as RuntimeWordPressDatabaseSetupContract | undefined, extensions: normalizeRuntimePHPWasmExtensionManifests(value.extensions), bundledExtensions: normalizeRuntimePHPWasmBundledExtensions(value.bundledExtensions), + hostProcess: normalizeRuntimeHostProcessMode(value.hostProcess), }) } +function normalizeRuntimeHostProcessMode(value: unknown): RuntimeHostProcessMode | undefined { + if (value === undefined) return undefined + if (!RUNTIME_HOST_PROCESS_MODES.includes(value as RuntimeHostProcessMode)) { + throw new Error(`environment.hostProcess must be one of: ${RUNTIME_HOST_PROCESS_MODES.join(", ")}.`) + } + return value as RuntimeHostProcessMode +} + function normalizeRuntimeWorkerCount(value: unknown): RuntimeWorkerCount | undefined { if (value === undefined) return undefined if (value === "auto") return value diff --git a/packages/runtime-playground/src/artifact-bundle-builder.ts b/packages/runtime-playground/src/artifact-bundle-builder.ts index ab3d9dc5..2a90c41c 100644 --- a/packages/runtime-playground/src/artifact-bundle-builder.ts +++ b/packages/runtime-playground/src/artifact-bundle-builder.ts @@ -65,6 +65,7 @@ import { buildReplayableWordPressSiteBlueprint, buildReplayableWordPressSiteLimi import { runtimeSnapshotPayload, type RuntimeSnapshotArtifact } from "./runtime-snapshot.js" import { previewReviewerAccess } from "./preview-reviewer-access.js" import { artifactJsonLines, writeRedactedArtifactFile } from "./artifact-bundle-writer.js" +import { HOST_PROCESS_EXECUTION_EVENT, HOST_PROCESS_EXECUTION_SCHEMA } from "./host-process-execution.js" export interface ArtifactBundleBuilderSource { artifactRoot: string @@ -97,6 +98,18 @@ export interface ArtifactBundleBuilderSource { recordArtifactsCollected(bundleId: string, createdAt: string, spec: ArtifactSpec): void } +/** + * Records that PHP process execution reached the host shell. The startup event + * carries the shared paths; the environment spec is the fallback when the + * runtime never booted. + */ +function hostProcessExecutionReceipt(source: ArtifactBundleBuilderSource): Record | undefined { + if (source.spec.environment.hostProcess !== "shell") return undefined + const event = [...source.events].reverse().find((candidate) => candidate.type === HOST_PROCESS_EXECUTION_EVENT) + const evidence = event?.data?.evidence + return evidence && typeof evidence === "object" ? evidence as Record : { schema: HOST_PROCESS_EXECUTION_SCHEMA, enabled: true, mode: "shell", booted: false } +} + export class ArtifactBundleBuilder { constructor(private readonly source: ArtifactBundleBuilderSource) {} @@ -345,6 +358,10 @@ export class ArtifactBundleBuilder { spec, artifacts: artifactFiles, } + const hostProcessExecution = hostProcessExecutionReceipt(source) + if (hostProcessExecution) { + metadata.hostProcessExecution = hostProcessExecution + } source.recordArtifactsCollected(bundleId, createdAt, spec) const review = buildArtifactReview({ artifactId: bundleId, @@ -402,6 +419,9 @@ export class ArtifactBundleBuilder { await writeFile(testResultsPath, artifactJson(testResults)) await writeRedactedArtifact(redactor, previewEvidencePath, source.artifactRoot, artifactJson(previewEvidence)) await writeFile(previewSessionEvidencePath, previewSessionEvidenceJson) + if (hostProcessExecution) { + review.riskFlags.push("host-process-execution") + } const redaction = redactor.summary() if (redaction.total > 0) { review.redaction = redaction diff --git a/packages/runtime-playground/src/host-process-execution.ts b/packages/runtime-playground/src/host-process-execution.ts new file mode 100644 index 00000000..0ed18e07 --- /dev/null +++ b/packages/runtime-playground/src/host-process-execution.ts @@ -0,0 +1,118 @@ +import { resolveRuntimeSecretEnvTargets, type RuntimeCreateSpec } from "@automattic/wp-codebox-core" +import { existsSync } from "node:fs" +import { mkdtemp, realpath, rm } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { fileURLToPath } from "node:url" +import type { HostProcessPathMapping, HostProcessWorkerOptions } from "./host-process-spawn-handler.js" + +export const HOST_PROCESS_EXECUTION_SCHEMA = "wp-codebox/host-process-execution/v1" as const +export const HOST_PROCESS_EXECUTION_EVENT = "runtime.host-process-execution" as const + +/** Host environment names forwarded to host commands so tools resolve as they do natively. */ +const HOST_BASE_ENV_NAMES = ["PATH", "HOME", "USER", "LOGNAME", "SHELL", "LANG", "LC_ALL", "LC_CTYPE", "TZ"] as const + +export interface HostProcessExecutionEvidence { + schema: typeof HOST_PROCESS_EXECUTION_SCHEMA + enabled: true + mode: "shell" + shell: "/bin/sh -c" + trust: "host-process-execution-enabled" + sharedPaths: { + /** Per-run host temp directory, mounted at the same path inside PHP and used as sys_temp_dir and TMPDIR. */ + tempDirectory: string + /** VFS paths whose host directories back the host command working directory. */ + workingDirectoryMappings: HostProcessPathMapping[] + } + /** Names only: values may include run secrets. */ + environmentNames: string[] +} + +export interface HostProcessExecution { + workerOptions: HostProcessWorkerOptions + evidence: HostProcessExecutionEvidence + /** Identity mount for the per-run temp directory. */ + tempMount: { hostPath: string; vfsPath: string } + /** PHP ini entries that point PHP's temp dir at the shared directory. */ + iniEntries: Record + /** Environment exposed to PHP so getenv() and proc_open($env) agree with host commands. */ + phpEnv: Record + dispose(): Promise +} + +export function hostProcessExecutionEnabled(spec: RuntimeCreateSpec): boolean { + return spec.environment.hostProcess === "shell" +} + +/** + * Prepares opt-in host process execution for one runtime. Returns undefined + * when the capability is off, which keeps Playground's sandboxed spawn handler. + */ +export async function prepareHostProcessExecution( + spec: RuntimeCreateSpec, + mounts: Array<{ source: string; target: string }>, + options: { wordpressDirectory?: string; distributionEnv?: Record } = {}, +): Promise { + if (!hostProcessExecutionEnabled(spec)) return undefined + + // Identity mounts need the canonical host path (for example /private/var on macOS). + const tempDirectory = await realpath(await mkdtemp(join(tmpdir(), "wp-codebox-host-process-"))) + const pathMappings: HostProcessPathMapping[] = [ + { vfsPath: tempDirectory, hostPath: tempDirectory }, + ...(options.wordpressDirectory ? [{ vfsPath: "/wordpress", hostPath: options.wordpressDirectory }] : []), + ...mounts.map((mount) => ({ vfsPath: mount.target, hostPath: mount.source })), + ] + const hostBase: Record = {} + for (const name of HOST_BASE_ENV_NAMES) { + const value = process.env[name] + if (typeof value === "string") hostBase[name] = value + } + const runEnv: Record = { + ...stringEnv(options.distributionEnv), + ...(spec.runtimeEnv ?? {}), + ...resolveRuntimeSecretEnvTargets(spec.secretEnv ?? {}, spec.secretEnvTargets), + } + const env = { ...hostBase, ...runEnv, TMPDIR: tempDirectory } + + return { + workerOptions: { + mode: "shell", + module: hostProcessSpawnHandlerModuleUrl(), + env, + tempDirectory, + pathMappings, + }, + evidence: { + schema: HOST_PROCESS_EXECUTION_SCHEMA, + enabled: true, + mode: "shell", + shell: "/bin/sh -c", + trust: "host-process-execution-enabled", + sharedPaths: { tempDirectory, workingDirectoryMappings: pathMappings }, + environmentNames: Object.keys(env).sort(), + }, + tempMount: { hostPath: tempDirectory, vfsPath: tempDirectory }, + iniEntries: { sys_temp_dir: tempDirectory }, + phpEnv: { + ...(hostBase.PATH ? { PATH: hostBase.PATH } : {}), + TMPDIR: tempDirectory, + }, + async dispose() { + await rm(tempDirectory, { recursive: true, force: true }) + }, + } +} + +/** Playground workers import the handler by URL; source checkouts run the `.ts` module. */ +function hostProcessSpawnHandlerModuleUrl(): string { + const compiled = new URL("./host-process-spawn-handler.js", import.meta.url) + return existsSync(fileURLToPath(compiled)) ? compiled.href : new URL("./host-process-spawn-handler.ts", import.meta.url).href +} + +function stringEnv(values: Record | undefined): Record { + const env: Record = {} + for (const [name, value] of Object.entries(values ?? {})) { + if (value === null || ["string", "number", "boolean"].includes(typeof value)) env[name] = value === null ? "" : String(value) + } + return env +} diff --git a/packages/runtime-playground/src/host-process-spawn-handler.ts b/packages/runtime-playground/src/host-process-spawn-handler.ts new file mode 100644 index 00000000..3ca8d715 --- /dev/null +++ b/packages/runtime-playground/src/host-process-spawn-handler.ts @@ -0,0 +1,174 @@ +import { spawn, type ChildProcess } from "node:child_process" +import { EventEmitter } from "node:events" +import { existsSync } from "node:fs" +import { constants as osConstants } from "node:os" +import { posix } from "node:path" + +/** + * Host process execution for PHP `exec()`, `proc_open()` and friends. + * + * This module is loaded inside Playground worker threads (by module URL), so it + * must only depend on Node built-ins and receive structured-cloneable options. + */ + +/** Codebox-internal sandbox PHP binary used by the PHPUnit process-isolation adapter. */ +export const SANDBOXED_PHP_BINARY = "/internal/shared/bin/php" + +export interface HostProcessPathMapping { + /** Absolute path inside the PHP virtual filesystem. */ + vfsPath: string + /** Host directory backing that VFS path. */ + hostPath: string +} + +/** Structured-cloneable options passed from the runtime to Playground workers. */ +export interface HostProcessWorkerOptions { + mode: "shell" + /** File URL of this module, imported by Playground worker threads. */ + module: string + /** Environment for host commands: run env, PATH and TMPDIR. */ + env: Record + /** Per-run host temp directory, identity-mounted inside PHP and used as sys_temp_dir. */ + tempDirectory: string + /** VFS-to-host mappings used to resolve the PHP working directory on the host. */ + pathMappings: HostProcessPathMapping[] +} + +type SpawnHandler = (command: string | string[], args?: string[], options?: { cwd?: string; env?: Record }) => unknown + +export interface HostShellSpawnHandlerOptions extends Omit { + /** Sandboxed handler that keeps running Codebox's own sandbox PHP binary inside php-wasm. */ + sandboxed?: SpawnHandler +} + +/** + * Creates a php-wasm spawn handler that runs commands through the host shell. + * + * String commands run as `/bin/sh -c `, argv commands run directly, + * matching native PHP. The handler never parses or filters commands; the only + * routing rule keeps Codebox's internal sandbox PHP binary (a VFS-only path) + * on the sandboxed handler so PHPUnit process isolation keeps working. + */ +export function createHostShellSpawnHandler(options: HostShellSpawnHandlerOptions): SpawnHandler { + return (command, args = [], spawnOptions = {}) => { + const argv = Array.isArray(command) ? command : args.length > 0 ? [command, ...args] : undefined + const commandLine = Array.isArray(command) ? command.join(" ") : command + if (options.sandboxed && runsSandboxedPhpBinary(argv, commandLine)) { + return options.sandboxed(command, args, spawnOptions) + } + + const file = argv ? argv[0]! : "/bin/sh" + const fileArgs = argv ? argv.slice(1) : ["-c", commandLine] + return new HostShellProcess(file, fileArgs, { + cwd: resolveHostWorkingDirectory(spawnOptions.cwd, options), + env: hostProcessEnvironment(options.env, spawnOptions.env, options.tempDirectory), + }) + } +} + +export function resolveHostWorkingDirectory(vfsCwd: string | undefined, options: Pick): string { + if (!vfsCwd || !vfsCwd.startsWith("/")) return options.tempDirectory + const cwd = posix.normalize(vfsCwd) + let best: HostProcessPathMapping | undefined + for (const mapping of options.pathMappings) { + const vfsPath = posix.normalize(mapping.vfsPath).replace(/\/+$/, "") || "/" + if (cwd !== vfsPath && !cwd.startsWith(vfsPath === "/" ? "/" : `${vfsPath}/`)) continue + if (!best || vfsPath.length > posix.normalize(best.vfsPath).replace(/\/+$/, "").length) best = { vfsPath, hostPath: mapping.hostPath } + } + if (!best) return options.tempDirectory + const hostPath = posix.join(best.hostPath, posix.relative(best.vfsPath, cwd)) + return existsSync(hostPath) ? hostPath : options.tempDirectory +} + +function hostProcessEnvironment(base: Record, fromPhp: Record | undefined, tempDirectory: string): Record { + const environment: Record = { ...base } + for (const [name, value] of Object.entries(fromPhp ?? {})) { + // PHP often forwards getenv(); Emscripten's synthetic defaults are not host values. + if (EMSCRIPTEN_DEFAULT_ENV[name] === value || (name === "PATH" && value === "/")) continue + environment[name] = value + } + if (!environment.PATH) environment.PATH = "/usr/local/bin:/usr/bin:/bin" + environment.TMPDIR = tempDirectory + return environment +} + +const EMSCRIPTEN_DEFAULT_ENV: Record = { + USER: "web_user", + LOGNAME: "web_user", + HOME: "/home/web_user", + PWD: "/", + _: "./this.program", +} + +function runsSandboxedPhpBinary(argv: string[] | undefined, commandLine: string): boolean { + if (argv) { + if (argv[0] === SANDBOXED_PHP_BINARY) return true + if (argv[0] !== "/bin/sh" || argv[1] !== "-c") return false + commandLine = argv[2] ?? "" + } + return /^\s*(?:exec\s+)?(['"]?)\/internal\/shared\/bin\/php\1(?:\s|$)/.test(commandLine) +} + +/** + * Adapts a Node child process to the php-wasm spawn contract: `spawn` is + * emitted before `exit`, and `exit` waits until stdout and stderr have been + * fully delivered so PHP never loses trailing output. + */ +class HostShellProcess extends EventEmitter { + readonly stdout = new EventEmitter() + readonly stderr = new EventEmitter() + readonly stdin: NonNullable | ClosedStdin + readonly pid: number + private readonly child: ChildProcess + + constructor(file: string, args: string[], options: { cwd: string; env: Record }) { + super() + this.child = spawn(file, args, { cwd: options.cwd, env: options.env, stdio: ["pipe", "pipe", "pipe"] }) + this.pid = this.child.pid ?? nextSyntheticPid++ + this.stdin = this.child.stdin ?? new ClosedStdin() + // A command may exit without reading stdin; PHP's late writes must not crash the worker. + this.child.stdin?.on("error", () => undefined) + this.child.stdout?.on("data", (chunk: Buffer) => this.stdout.emit("data", new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength))) + this.child.stderr?.on("data", (chunk: Buffer) => this.stderr.emit("data", new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength))) + + let spawned = false + let exited = false + this.child.once("spawn", () => { + spawned = true + this.emit("spawn", true) + }) + this.child.once("error", (error: NodeJS.ErrnoException) => { + if (spawned || exited) return + // Native PHP forks first and the child exits 127 when exec fails. + exited = true + setTimeout(() => { + this.emit("spawn", true) + this.stderr.emit("data", new TextEncoder().encode(`${file}: ${error.message}\n`)) + this.emit("exit", 127) + }) + }) + this.child.once("close", (code: number | null, signal: NodeJS.Signals | null) => { + if (exited) return + exited = true + this.emit("exit", code ?? (signal ? 128 + (osConstants.signals[signal] ?? 0) : 1)) + }) + } + + get killed(): boolean { + return this.child.killed + } + + kill(signal?: NodeJS.Signals | number): boolean { + return this.child.kill(signal) + } +} + +class ClosedStdin extends EventEmitter { + closed = true + write(): boolean { + return false + } + end(): void {} +} + +let nextSyntheticPid = 900_000 diff --git a/packages/runtime-playground/src/playground-cli-runner.ts b/packages/runtime-playground/src/playground-cli-runner.ts index e3380d43..2e4a3601 100644 --- a/packages/runtime-playground/src/playground-cli-runner.ts +++ b/packages/runtime-playground/src/playground-cli-runner.ts @@ -16,6 +16,8 @@ import { phpEnvAssignments, phpLiteral, phpWpConfigDefineAssignments } from "./p import { stageReadonlyPlaygroundMounts, type ReadonlyMountStaging } from "./mount-materialization.js" import { acquirePlaygroundArchiveReference, isCustomPlaygroundWordPressArchive, maintainPlaygroundCustomArchiveCache, playgroundWordPressArchiveCacheDirectory, withPlaygroundArchiveCacheLock, type PlaygroundArchiveReference, type PlaygroundCustomArchiveCacheDiagnostic, type PlaygroundCustomArchiveCacheMaintenance } from "./playground-wordpress-archive-cache.js" import { databaseBootstrapWpConfig } from "./database-bootstrap.js" +import { prepareHostProcessExecution, type HostProcessExecution } from "./host-process-execution.js" +import type { HostProcessWorkerOptions } from "./host-process-spawn-handler.js" const DEFAULT_RUNTIME_PHP_INI_ENTRIES = { memory_limit: "512M" } @@ -45,6 +47,8 @@ export interface PlaygroundCliModule { redis?: boolean memcached?: boolean xdebug?: boolean + /** Opt-in host shell spawn handler, read by the patched Playground CLI workers. */ + wpCodeboxHostProcess?: HostProcessWorkerOptions }): Promise } @@ -80,6 +84,7 @@ export async function startPlaygroundCliServer(spec: RuntimeCreateSpec, mounts: let cacheMaintenance: PlaygroundCustomArchiveCacheMaintenance | undefined let cacheMaintenanceDiagnostics: PlaygroundCustomArchiveCacheDiagnostic[] = [] let usesArchiveCache = false + let hostProcess: HostProcessExecution | undefined try { if (spec.preview?.port) { await assertPreviewPortAvailable(spec.preview.port) @@ -98,6 +103,10 @@ export async function startPlaygroundCliServer(spec: RuntimeCreateSpec, mounts: materialization: readonlyMountStaging.phaseResult, }) const stagedMounts = readonlyMountStaging.mounts + hostProcess = await prepareHostProcessExecution(spec, stagedMounts, { + wordpressDirectory, + distributionEnv: distributionEnv(recipeDistribution(spec)?.env), + }) const preinstallMounts = stagedMounts.filter((mount) => mount.phase === "pre-install") const postinstallMounts = stagedMounts.filter((mount) => mount.phase !== "pre-install") if (usesArchiveCache) { @@ -145,17 +154,18 @@ export async function startPlaygroundCliServer(spec: RuntimeCreateSpec, mounts: }, }, stagedMounts, { bootstrapIniEntries: bootstrapIniEntries ?? {}, - phpIniEntries: pluginRuntimePhpIniEntries(spec), + phpIniEntries: { ...pluginRuntimePhpIniEntries(spec), ...hostProcess?.iniEntries }, wordpressDirectory, wordpressArchivePath: wordpressStartupAsset?.localPath, wordpressArchiveUrl: wordpressStartupAsset?.wp, wordpressInstallMode, - sharedPhpIniContent: phpIniContent(bootstrapIniEntries ?? {}, "/internal/wp-codebox/auto_prepend_file.php"), + sharedPhpIniContent: phpIniContent({ ...bootstrapIniEntries, ...hostProcess?.iniEntries }, "/internal/wp-codebox/auto_prepend_file.php"), + hostProcess, }) }, Boolean(spec.preview?.port)) : await startPlaygroundCliWithDynamicPortRetry(async (port) => { const { runCLI } = options.cliModule ?? (await import("@wp-playground/cli")) as unknown as PlaygroundCliModule const localAssetServer = wordpressStartupAsset?.localPath ? await serveLocalStartupAsset(wordpressStartupAsset.localPath) : undefined - const bootstrapSharedMounts = await pluginRuntimeBootstrapSharedMounts(spec, requestWorkerEndpoint) + const bootstrapSharedMounts = await pluginRuntimeBootstrapSharedMounts(spec, requestWorkerEndpoint, hostProcess?.iniEntries) const customDropInDefines = customDropInBootstrapDefines(spec) try { return await runCLI({ @@ -172,9 +182,10 @@ export async function startPlaygroundCliServer(spec: RuntimeCreateSpec, mounts: vfsPath: mount.target, })), ], - ...(wordpressDirectory || bootstrapSharedMounts.length > 0 || preinstallMounts.length > 0 ? { + ...(wordpressDirectory || bootstrapSharedMounts.length > 0 || preinstallMounts.length > 0 || hostProcess ? { "mount-before-install": [ ...bootstrapSharedMounts, + ...(hostProcess ? [hostProcess.tempMount] : []), ...preinstallMounts.map((mount) => ({ hostPath: mount.source, vfsPath: mount.target })), ...(wordpressDirectory ? [{ hostPath: wordpressDirectory, vfsPath: "/wordpress" }] : []), ], @@ -186,8 +197,9 @@ export async function startPlaygroundCliServer(spec: RuntimeCreateSpec, mounts: ...customDropInDefines, ...(spec.environment.extensions?.length ? { phpExtension: spec.environment.extensions.map((extension) => extension.manifest) } : {}), ...playgroundBundledExtensionOptions(spec), - phpIniEntries: pluginRuntimePhpIniEntries(spec), - phpEnv: runtimePhpEnvironment(spec), + phpIniEntries: { ...pluginRuntimePhpIniEntries(spec), ...hostProcess?.iniEntries }, + phpEnv: hostProcess ? { ...runtimePhpEnvironment(spec), ...hostProcess.phpEnv } : runtimePhpEnvironment(spec), + ...(hostProcess ? { wpCodeboxHostProcess: hostProcess.workerOptions } : {}), "site-url": playgroundRuntimeSiteUrl(spec), blueprint: playgroundCliBlueprint(spec), }) @@ -208,8 +220,10 @@ export async function startPlaygroundCliServer(spec: RuntimeCreateSpec, mounts: upstreamUrl: server.serverUrl, lease: proxiedServer.previewLease ? previewLeaseDetail(proxiedServer.previewLease) : undefined, }) + const runHostProcess = hostProcess return { ...proxiedServer, + ...(runHostProcess ? { hostProcessExecution: runHostProcess.evidence } : {}), get previewProxyDiagnostics() { return proxiedServer.previewProxyDiagnostics }, @@ -217,6 +231,7 @@ export async function startPlaygroundCliServer(spec: RuntimeCreateSpec, mounts: try { await proxiedServer[Symbol.asyncDispose]() } finally { + await runHostProcess?.dispose().catch(() => undefined) await archiveReference?.release().catch(() => undefined) if (usesArchiveCache) { await automaticPlaygroundCustomArchiveCacheMaintenance(true) @@ -230,6 +245,7 @@ export async function startPlaygroundCliServer(spec: RuntimeCreateSpec, mounts: error: errorDetail(error), }) + await hostProcess?.dispose().catch(() => undefined) await archiveReference?.release().catch(() => undefined) if (usesArchiveCache) { await automaticPlaygroundCustomArchiveCacheMaintenance(true) @@ -358,12 +374,12 @@ export function shouldUseProgrammaticPlaygroundRunner(spec: RuntimeCreateSpec, o && (Boolean(runtimeBootstrapPhpIniEntries(spec)) || Boolean(spec.environment.extensions?.length)) } -async function pluginRuntimeBootstrapSharedMounts(spec: RuntimeCreateSpec, requestWorkerEndpoint?: { route: string; token: string; payloadDirectory: string }): Promise> { - const iniEntries = runtimeBootstrapPhpIniEntries(spec) +async function pluginRuntimeBootstrapSharedMounts(spec: RuntimeCreateSpec, requestWorkerEndpoint?: { route: string; token: string; payloadDirectory: string }, hostProcessIniEntries?: Record): Promise> { + const iniEntries = { ...runtimeBootstrapPhpIniEntries(spec), ...hostProcessIniEntries } const directory = join(spec.artifactsDirectory ?? "artifacts", "playground-internal-shared") await mkdir(directory, { recursive: true }) // Mount before PHP initializes so php-wasm's opcache-enabled defaults never apply. - await writeFile(join(directory, "php.ini"), phpIniContent(iniEntries ?? {}), "utf8") + await writeFile(join(directory, "php.ini"), phpIniContent(iniEntries), "utf8") await writeFile(join(directory, "wp-codebox-auto-prepend.php"), runtimeAutoPrependPhp(spec), "utf8") if (requestWorkerEndpoint) await writeFile(join(directory, "request-worker.php"), requestWorkerPhp(requestWorkerEndpoint.token), "utf8") const wpConfig = databaseBootstrapWpConfig(spec) diff --git a/packages/runtime-playground/src/playground-runtime.ts b/packages/runtime-playground/src/playground-runtime.ts index d617e389..438fe405 100644 --- a/packages/runtime-playground/src/playground-runtime.ts +++ b/packages/runtime-playground/src/playground-runtime.ts @@ -20,6 +20,7 @@ import { bootstrapPhpCode } from "./php-bootstrap.js" import { observeHttpResponse as observeHttpResponseArtifact, observeWordPressState as observeWordPressStateArtifact } from "./observation-artifacts.js" import { PlaygroundCommandCrashError, assertPlaygroundResponseOk, errorMessage, terminalizeOnPhpWasmRuntimeRejection, type PlaygroundRunResponse } from "./playground-command-errors.js" import { startPlaygroundCliServer, type PlaygroundCliModule } from "./playground-cli-runner.js" +import { HOST_PROCESS_EXECUTION_EVENT } from "./host-process-execution.js" import type { PlaygroundCliServer } from "./preview-server.js" import { collectPlaygroundArtifacts } from "./runtime-artifact-helpers.js" import { materializePlaygroundMountsFromVfs, materializePlaygroundStagedFiles } from "./mount-materialization.js" @@ -1936,6 +1937,10 @@ echo json_encode(array('command' => 'inspect-mounted-inputs', 'mounts' => $inspe cliModule: this.backendOptions.cliModule, }) server.hostHttpTransport = installHostHttpTransportRoute(server, this.spec.policy.network) + if (server.hostProcessExecution) { + // Trust receipt: PHP process execution reaches the host shell for this run. + this.recordEvent(HOST_PROCESS_EXECUTION_EVENT, { evidence: server.hostProcessExecution }) + } return server } diff --git a/packages/runtime-playground/src/preview-server.ts b/packages/runtime-playground/src/preview-server.ts index f05323c9..0cff5cd7 100644 --- a/packages/runtime-playground/src/preview-server.ts +++ b/packages/runtime-playground/src/preview-server.ts @@ -4,6 +4,7 @@ import { createServer as createNetServer } from "node:net" import { Transform } from "node:stream" import type { PreviewLease } from "@automattic/wp-codebox-core" import { createPreviewProxyRequestTrace, isPreviewProxyServiceWorkerRegistrationRequest, isPreviewProxyServiceWorkerRequest, recordPreviewProxyRequest, snapshotPreviewProxyRequestTrace, type PlaygroundPreviewProxyRequestOutcome, type PlaygroundPreviewProxyRequestTrace } from "./preview-proxy-request-trace.js" +import type { HostProcessExecutionEvidence } from "./host-process-execution.js" export interface PlaygroundServerRunResponse { exitCode?: number @@ -26,6 +27,8 @@ export interface PlaygroundCliServer { previewRoutes?: PlaygroundPreviewRouteRegistry previewProxyDiagnostics?: PlaygroundPreviewProxyDiagnostics hostHttpTransport?: { url: string; token: string } + /** Present only when the runtime opted into host process execution. */ + hostProcessExecution?: HostProcessExecutionEvidence [Symbol.asyncDispose](): Promise } diff --git a/packages/runtime-playground/src/programmatic-playground-runner.ts b/packages/runtime-playground/src/programmatic-playground-runner.ts index 28e4b84e..f01de88b 100644 --- a/packages/runtime-playground/src/programmatic-playground-runner.ts +++ b/packages/runtime-playground/src/programmatic-playground-runner.ts @@ -11,18 +11,22 @@ import { assertPhpWasmExternalExtensionsSupported } from "./php-wasm-preflight.j import { phpEnvAssignments } from "./php-snippets.js" import type { PlaygroundCliServer, PlaygroundServerRunResponse } from "./preview-server.js" import { databaseBootstrapWpConfig } from "./database-bootstrap.js" +import type { HostProcessExecution } from "./host-process-execution.js" +import { createHostShellSpawnHandler } from "./host-process-spawn-handler.js" const { createNodeFsMountHandler, loadNodeRuntime } = PHPWasmNode as unknown as { createNodeFsMountHandler(localPath: string): unknown - loadNodeRuntime(phpVersion: AllPHPVersion, options?: { followSymlinks?: boolean; emscriptenOptions?: { processId?: number }; extensions?: Array }): Promise + loadNodeRuntime(phpVersion: AllPHPVersion, options?: { followSymlinks?: boolean; emscriptenOptions?: { processId?: number; ENV?: Record }; extensions?: Array }): Promise } const { PHP, proxyFileSystem, sandboxedSpawnHandlerFactory } = PHPWasmUniversal as unknown as { PHP: new (runtimeId: number) => ProgrammaticPHP & { exit(): void } proxyFileSystem(parent: ProgrammaticPHP, child: ProgrammaticPHP, paths: string[]): Promise - sandboxedSpawnHandlerFactory(getChild: () => Promise<{ php: ProgrammaticPHP; reap(): void }>): unknown + sandboxedSpawnHandlerFactory(getChild: () => Promise<{ php: ProgrammaticPHP; reap(): void }>): SandboxedSpawnHandler } +type SandboxedSpawnHandler = Parameters[0]["sandboxed"] & {} + type AllPHPVersion = "8.5" | "8.4" | "8.3" | "8.2" | "8.1" | "8.0" | "7.4" | "5.2" interface ProgrammaticPHP { @@ -52,6 +56,8 @@ export interface ProgrammaticPlaygroundStartupOptions { wordpressArchiveUrl?: string wordpressInstallMode?: "install-from-existing-files" | "install-from-existing-files-if-needed" | "do-not-attempt-installing" sharedPhpIniContent: string + /** Opt-in host shell spawn handler; omitted keeps the sandboxed handler. */ + hostProcess?: HostProcessExecution } export async function startProgrammaticPlaygroundServer(spec: RuntimeCreateSpec, mounts: MountSpec[], options: ProgrammaticPlaygroundStartupOptions): Promise { @@ -68,17 +74,17 @@ export async function startProgrammaticPlaygroundServer(spec: RuntimeCreateSpec, const wordPressZip = await wordpressArchiveFile(options) let spawningPhp: ProgrammaticPHP const requestHandler = await bootWordPressAndRequestHandler({ - createPhpRuntime: () => loadNodeRuntime(phpVersion, programmaticNodeRuntimeOptions(spec, nextProcessId++)), + createPhpRuntime: () => loadNodeRuntime(phpVersion, programmaticNodeRuntimeOptions(spec, nextProcessId++, options.hostProcess?.phpEnv)), maxPhpInstances: 1, phpVersion, siteUrl: playgroundRuntimeSiteUrl(spec) ?? "http://127.0.0.1", documentRoot: "/wordpress", sapiName: "cli", - spawnHandler: () => sandboxedSpawnHandlerFactory(async () => { + spawnHandler: () => withHostProcess(options.hostProcess, sandboxedSpawnHandlerFactory(async () => { // The request handler has one slot, already occupied by the parent. // A child needs its own PHP runtime, but must see the parent's VFS. const parent = spawningPhp - const child = new PHP(await loadNodeRuntime(phpVersion, programmaticNodeRuntimeOptions(spec, nextProcessId++))) + const child = new PHP(await loadNodeRuntime(phpVersion, programmaticNodeRuntimeOptions(spec, nextProcessId++, options.hostProcess?.phpEnv))) try { await proxyFileSystem(parent, child, [ "/internal/shared", @@ -90,7 +96,7 @@ export async function startProgrammaticPlaygroundServer(spec: RuntimeCreateSpec, child.exit() throw error } - }), + })), wordpressInstallMode: options.wordpressInstallMode ?? "install-from-existing-files", ...(wordPressZip ? { wordPressZip } : {}), constants: playgroundWpConfigConstants(spec.environment.blueprint), @@ -111,6 +117,9 @@ export async function startProgrammaticPlaygroundServer(spec: RuntimeCreateSpec, for (const mount of preinstallMounts) { await mountHostDirectory(programmaticPhp, mount.target, mount.source) } + if (options.hostProcess) { + await mountHostDirectory(programmaticPhp, options.hostProcess.tempMount.vfsPath, options.hostProcess.tempMount.hostPath) + } }, }) @@ -160,14 +169,20 @@ async function wordpressArchiveFile(options: ProgrammaticPlaygroundStartupOption return new File([await response.arrayBuffer()], basename(new URL(options.wordpressArchiveUrl).pathname) || "wordpress.zip") } -export function programmaticNodeRuntimeOptions(spec: RuntimeCreateSpec, processId: number): { followSymlinks: true; emscriptenOptions: { processId: number }; extensions?: Array } { +function withHostProcess(hostProcess: HostProcessExecution | undefined, sandboxed: SandboxedSpawnHandler): SandboxedSpawnHandler { + if (!hostProcess) return sandboxed + const { env, tempDirectory, pathMappings } = hostProcess.workerOptions + return createHostShellSpawnHandler({ env, tempDirectory, pathMappings, sandboxed }) +} + +export function programmaticNodeRuntimeOptions(spec: RuntimeCreateSpec, processId: number, env?: Record): { followSymlinks: true; emscriptenOptions: { processId: number; ENV?: Record }; extensions?: Array } { const extensions = [ ...(spec.environment.bundledExtensions ?? []), ...(spec.environment.extensions?.map((extension) => ({ source: { format: "manifest" as const, manifestUrl: extension.manifest } })) ?? []), ] return { followSymlinks: true, - emscriptenOptions: { processId }, + emscriptenOptions: { processId, ...(env ? { ENV: env } : {}) }, ...(extensions && extensions.length > 0 ? { extensions } : {}), } } diff --git a/patches/@wp-playground+cli+3.1.46.patch b/patches/@wp-playground+cli+3.1.46.patch index 7cacb358..46d90afd 100644 --- a/patches/@wp-playground+cli+3.1.46.patch +++ b/patches/@wp-playground+cli+3.1.46.patch @@ -1,24 +1,27 @@ diff --git a/node_modules/@wp-playground/cli/run-cli-DKYOp4UU.js b/node_modules/@wp-playground/cli/run-cli-DKYOp4UU.js -index e22c476..ed7c114 100644 +index e22c476..7e3ab5f 100644 --- a/node_modules/@wp-playground/cli/run-cli-DKYOp4UU.js +++ b/node_modules/@wp-playground/cli/run-cli-DKYOp4UU.js -@@ -536,6 +536,7 @@ class Yt { +@@ -536,6 +536,8 @@ class Yt { mountsBeforeWpInstall: this.args["mount-before-install"] || [], mountsAfterWpInstall: this.args.mount || [], processId: t.processId, + environmentVariables: this.args.phpEnv, ++ wpCodeboxHostProcess: this.args.wpCodeboxHostProcess, followSymlinks: this.args.followSymlinks === !0, trace: this.args.experimentalTrace === !0, extensions: Ve( -@@ -777,6 +778,7 @@ class er { +@@ -777,6 +779,8 @@ class er { mountsBeforeWpInstall: this.args["mount-before-install"] || [], mountsAfterWpInstall: this.args.mount || [], processId: t.processId, + environmentVariables: this.args.phpEnv, ++ wpCodeboxHostProcess: this.args.wpCodeboxHostProcess, followSymlinks: this.args.followSymlinks === !0, trace: this.args.experimentalTrace === !0, extensions: Ve(this.args), diff --git a/node_modules/@wp-playground/cli/worker-thread-v1.cjs b/node_modules/@wp-playground/cli/worker-thread-v1.cjs +index 4c193ec..9c11d32 100644 --- a/node_modules/@wp-playground/cli/worker-thread-v1.cjs +++ b/node_modules/@wp-playground/cli/worker-thread-v1.cjs @@ -1,3 +1,3 @@ @@ -27,6 +30,7 @@ diff --git a/node_modules/@wp-playground/cli/worker-thread-v1.cjs b/node_modules +`)},phpIniEntries:{"openssl.cafile":"/internal/shared/ca-bundle.crt","curl.cainfo":"/internal/shared/ca-bundle.crt",allow_url_fopen:"1",disable_functions:""},dataSqlPath:y,constants:f});const a=n.consumeAPI(t);await a.applyPostInstallMountsToAllWorkers(),a[n.releaseApiProxy](),p()}catch(a){throw h(a),a}}async bootRequestHandler(e){if(this.bootedRequestHandler)throw new Error("Playground already booted");this.bootedRequestHandler=!0;try{const t=await u.bootRequestHandler({siteUrl:e.siteUrl,phpVersion:e.phpVersion,maxPhpInstances:1,createPhpRuntime:R(e,this.fileLockManager),onPHPInstanceCreated:async o=>{await i.mountResources(o,e.mountsBeforeWpInstall),this.bootedWordPress&&await i.mountResources(o,e.mountsAfterWpInstall)},sapiName:"cli",cookieStore:!1,pathAliases:e.pathAliases,spawnHandler:()=>n.sandboxedSpawnHandlerFactory(()=>{let o=e;return this.bootedWordPress||(o={...e,mountsAfterWpInstall:[]}),v(o,this.fileLockManager)})});this.__internal_setRequestHandler(t);const s=await t.getPrimaryPhp();await this.setPrimaryPHP(s),p()}catch(t){throw h(t),t}}async mountAfterWordPressInstall(e){this.bootedWordPress=!0,await i.mountResources(this.__internal_getPHP(),e)}async dispose(){await this[Symbol.asyncDispose]()}}function R(r,e){return async()=>await g.loadNodeRuntime(r.phpVersion||I.RecommendedPHPVersion,{fileLockManager:e,emscriptenOptions:{processId:r.processId,trace:r.trace?H:void 0,nativeInternalDirPath:r.nativeInternalDirPath},followSymlinks:r.followSymlinks,extensions:r.extensions})}async function v(r,e){const t=await i.spawnWorkerThread("v1"),s=n.consumeAPI(t.phpPort);const channel=new P.MessageChannel;return await n.exposeSyncAPI(Object.fromEntries(["lockWholeFile", "lockFileByteRange", "findFirstConflictingByteRangeLock", "releaseLocksForProcess", "releaseLocksOnFdClose"].map(method => [method, (...args) => e[method](...args)])),channel.port1),await s.useFileLockManager(channel.port2),await s.bootRequestHandler({...r,processId:t.processId}),await s.mountAfterWordPressInstall(r.mountsAfterWpInstall),{php:s,reap:()=>{channel.port1.close();try{s.dispose()}catch{}try{t.worker.terminate()}catch{}}}}process.on("unhandledRejection",r=>{k.logger.error("Unhandled rejection:",r)});const l=new P.MessageChannel,[p,h]=n.exposeAPI(new w(new b.EmscriptenDownloadMonitor),void 0,l.port1);P.parentPort?.postMessage({command:"worker-script-initialized",phpPort:l.port2},[l.port2]);exports.PlaygroundCliBlueprintV1Worker=w; //# sourceMappingURL=worker-thread-v1.cjs.map diff --git a/node_modules/@wp-playground/cli/worker-thread-v1.js b/node_modules/@wp-playground/cli/worker-thread-v1.js +index 93b7099..77350c7 100644 --- a/node_modules/@wp-playground/cli/worker-thread-v1.js +++ b/node_modules/@wp-playground/cli/worker-thread-v1.js @@ -1,6 +1,6 @@ @@ -37,7 +41,45 @@ diff --git a/node_modules/@wp-playground/cli/worker-thread-v1.js b/node_modules/ import { sprintf as H } from "@php-wasm/util"; import { RecommendedPHPVersion as k } from "@wp-playground/common"; import { bootWordPress as R, bootRequestHandler as q } from "@wp-playground/wordpress"; -@@ -125,6 +125,7 @@ +@@ -79,6 +79,7 @@ class F extends b { + throw new Error("Playground already booted"); + this.bootedRequestHandler = !0; + try { ++ const wpCodeboxHostProcess = e.wpCodeboxHostProcess ? await import(e.wpCodeboxHostProcess.module) : void 0; + const t = await q({ + siteUrl: e.siteUrl, + phpVersion: e.phpVersion, +@@ -93,7 +94,7 @@ class F extends b { + sapiName: "cli", + cookieStore: !1, + pathAliases: e.pathAliases, +- spawnHandler: () => W(() => { ++ spawnHandler: () => wpCodeboxSpawnHandler(e, wpCodeboxHostProcess, W(() => { + let s = e; + return this.bootedWordPress || (s = { + ...e, +@@ -102,7 +103,7 @@ class F extends b { + s, + this.fileLockManager + ); +- }) ++ })) + }); + this.__internal_setRequestHandler(t); + const o = await t.getPrimaryPhp(); +@@ -119,12 +120,19 @@ class F extends b { + await this[Symbol.asyncDispose](); + } + } ++function wpCodeboxSpawnHandler(e, hostProcessModule, sandboxed) { ++ if (!hostProcessModule || e.wpCodeboxHostProcess?.mode !== "shell") ++ return sandboxed; ++ const { env, tempDirectory, pathMappings } = e.wpCodeboxHostProcess; ++ return hostProcessModule.createHostShellSpawnHandler({ env, tempDirectory, pathMappings, sandboxed }); ++} + function V(r, e) { + return async () => await w( + r.phpVersion || k, { fileLockManager: e, emscriptenOptions: { @@ -45,7 +87,7 @@ diff --git a/node_modules/@wp-playground/cli/worker-thread-v1.js b/node_modules/ processId: r.processId, trace: r.trace ? x : void 0, nativeInternalDirPath: r.nativeInternalDirPath -@@ -138,12 +139,19 @@ +@@ -138,12 +146,19 @@ async function C(r, e) { const t = await M("v1"), o = h( t.phpPort ); @@ -67,7 +109,7 @@ diff --git a/node_modules/@wp-playground/cli/worker-thread-v1.js b/node_modules/ try { o.dispose(); } catch { -@@ -157,6 +165,8 @@ +@@ -157,6 +172,8 @@ async function C(r, e) { } process.on("unhandledRejection", (r) => { S.error("Unhandled rejection:", r); @@ -77,6 +119,7 @@ diff --git a/node_modules/@wp-playground/cli/worker-thread-v1.js b/node_modules/ const i = new _(), [c, p] = y( new F(new f()), diff --git a/node_modules/@wp-playground/cli/worker-thread-v2.cjs b/node_modules/@wp-playground/cli/worker-thread-v2.cjs +index 0a1477e..45ab900 100644 --- a/node_modules/@wp-playground/cli/worker-thread-v2.cjs +++ b/node_modules/@wp-playground/cli/worker-thread-v2.cjs @@ -1,4 +1,4 @@ @@ -86,9 +129,48 @@ diff --git a/node_modules/@wp-playground/cli/worker-thread-v2.cjs b/node_modules +`)},phpIniEntries:P(e.networking??!0),createPhpRuntime:A(e,this.fileLockManager),onPHPInstanceCreated:async n=>{await i.mountResources(n,e.mountsBeforeWpInstall),this.bootedWordPress&&await i.mountResources(n,e.mountsAfterWpInstall)},sapiName:"cli",cookieStore:!1,pathAliases:e.pathAliases,spawnHandler:()=>o.sandboxedSpawnHandlerFactory(()=>{let n=e;return this.bootedWordPress||(n={...e,mountsAfterWpInstall:[]}),v(n,this.fileLockManager)})});this.__internal_setRequestHandler(t);const s=await t.getPrimaryPhp();await this.setPrimaryPHP(s),w()}catch(t){throw m(t),t}}async mountAfterWordPressInstall(e){this.bootedWordPress=!0,await i.mountResources(this.__internal_getPHP(),e)}async dispose(){await this[Symbol.asyncDispose]()}}function A(r,e){return async()=>await k.loadNodeRuntime(r.phpVersion||H.RecommendedPHPVersion,{fileLockManager:e,emscriptenOptions:{processId:r.processId,trace:r.trace?_:void 0,nativeInternalDirPath:r.nativeInternalDirPath},followSymlinks:r.followSymlinks,extensions:r.extensions})}async function v(r,e){const t=await i.spawnWorkerThread("v2"),s=o.consumeAPI(t.phpPort),n=new c.MessageChannel;return await o.exposeSyncAPI(Object.fromEntries(["lockWholeFile", "lockFileByteRange", "findFirstConflictingByteRangeLock", "releaseLocksForProcess", "releaseLocksOnFdClose"].map(method => [method, (...args) => e[method](...args)])),n.port1),await s.useFileLockManager(n.port2),await s.bootRequestHandler({...r,processId:t.processId}),await s.mountAfterWordPressInstall(r.mountsAfterWpInstall),{php:s,reap:()=>{n.port1.close();try{s.dispose()}catch{}try{t.worker.terminate()}catch{}}}}process.on("unhandledRejection",r=>{R.logger.error("Unhandled rejection:",r)});const l=new c.MessageChannel,[w,m]=o.exposeAPI(new f(new q.EmscriptenDownloadMonitor),void 0,l.port1);c.parentPort?.postMessage({command:"worker-script-initialized",phpPort:l.port2},[l.port2]);exports.PlaygroundCliBlueprintV2Worker=f; //# sourceMappingURL=worker-thread-v2.cjs.map diff --git a/node_modules/@wp-playground/cli/worker-thread-v2.js b/node_modules/@wp-playground/cli/worker-thread-v2.js +index fb79a59..826dc99 100644 --- a/node_modules/@wp-playground/cli/worker-thread-v2.js +++ b/node_modules/@wp-playground/cli/worker-thread-v2.js -@@ -136,6 +136,7 @@ +@@ -83,6 +83,7 @@ class L extends W { + throw new Error("Playground already booted"); + this.bootedRequestHandler = !0; + try { ++ const wpCodeboxHostProcess = e.wpCodeboxHostProcess ? await import(e.wpCodeboxHostProcess.module) : void 0; + const t = await M({ + siteUrl: e.siteUrl, + phpVersion: e.phpVersion, +@@ -104,7 +105,7 @@ class L extends W { + sapiName: "cli", + cookieStore: !1, + pathAliases: e.pathAliases, +- spawnHandler: () => R(() => { ++ spawnHandler: () => wpCodeboxSpawnHandler(e, wpCodeboxHostProcess, R(() => { + let o = e; + return this.bootedWordPress || (o = { + ...e, +@@ -113,7 +114,7 @@ class L extends W { + o, + this.fileLockManager + ); +- }) ++ })) + }); + this.__internal_setRequestHandler(t); + const n = await t.getPrimaryPhp(); +@@ -130,12 +131,19 @@ class L extends W { + await this[Symbol.asyncDispose](); + } + } ++function wpCodeboxSpawnHandler(e, hostProcessModule, sandboxed) { ++ if (!hostProcessModule || e.wpCodeboxHostProcess?.mode !== "shell") ++ return sandboxed; ++ const { env, tempDirectory, pathMappings } = e.wpCodeboxHostProcess; ++ return hostProcessModule.createHostShellSpawnHandler({ env, tempDirectory, pathMappings, sandboxed }); ++} + function V(r, e) { + return async () => await I( + r.phpVersion || x, { fileLockManager: e, emscriptenOptions: { @@ -96,7 +178,7 @@ diff --git a/node_modules/@wp-playground/cli/worker-thread-v2.js b/node_modules/ processId: r.processId, trace: r.trace ? C : void 0, nativeInternalDirPath: r.nativeInternalDirPath -@@ -149,12 +150,13 @@ +@@ -149,12 +157,13 @@ async function j(r, e) { const t = await F("v2"), n = P( t.phpPort ), o = new m(); @@ -112,7 +194,7 @@ diff --git a/node_modules/@wp-playground/cli/worker-thread-v2.js b/node_modules/ try { n.dispose(); } catch { -@@ -168,6 +170,8 @@ +@@ -168,6 +177,8 @@ async function j(r, e) { } process.on("unhandledRejection", (r) => { E.error("Unhandled rejection:", r); diff --git a/patches/README.md b/patches/README.md index 09f1fd28..844d8036 100644 --- a/patches/README.md +++ b/patches/README.md @@ -17,6 +17,14 @@ file-lock manager. This lets an isolated WordPress bootstrap open the shared SQLite database without timing out on file-lock requests. Remove these changes when upstream handles both mounts and file-lock forwarding for child workers. +The same patch threads the opt-in `wpCodeboxHostProcess` runCLI option through +`bootRequestHandler` in the ESM worker threads (`worker-thread-v1.js` and +`worker-thread-v2.js`). When the option is set (`runtime.hostProcess: "shell"`), +the worker imports Codebox's `host-process-spawn-handler.js` by URL. It then +installs a host `/bin/sh -c` spawn handler that wraps the sandboxed one. Without +the option the released sandboxed spawn handler is installed unchanged. Remove +this when Playground lets callers supply a spawn handler factory to CLI workers. + The manual `build-php-wasm-mysqli-poll-overlay.yml` workflow carries the C-level `select()` wrapper and Asyncify imports from WordPress Playground PR [#4170](https://github.com/WordPress/wordpress-playground/pull/4170). It diff --git a/tests/host-process-spawn-handler.test.ts b/tests/host-process-spawn-handler.test.ts new file mode 100644 index 00000000..b9cea553 --- /dev/null +++ b/tests/host-process-spawn-handler.test.ts @@ -0,0 +1,94 @@ +import assert from "node:assert/strict" +import { EventEmitter } from "node:events" +import { mkdtemp, mkdir, realpath, rm } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" + +import { createHostShellSpawnHandler, resolveHostWorkingDirectory } from "../packages/runtime-playground/src/host-process-spawn-handler.js" +import { prepareHostProcessExecution } from "../packages/runtime-playground/src/host-process-execution.js" +import { normalizeRuntimeWordPressEnvironmentSpec, type RuntimeCreateSpec } from "../packages/runtime-core/src/index.js" + +const root = await realpath(await mkdtemp(join(tmpdir(), "wp-codebox-host-spawn-"))) +const source = join(root, "plugin") +await mkdir(join(source, "tests"), { recursive: true }) + +interface ChildLike extends EventEmitter { + stdout: EventEmitter + stderr: EventEmitter + stdin: { write(data: string | Uint8Array): unknown; end(): void } +} + +try { + const sandboxedCalls: unknown[][] = [] + const handler = createHostShellSpawnHandler({ + env: { PATH: process.env.PATH ?? "/usr/bin:/bin", DB_NAME: "runtime-db", HOME: "/host-home" }, + tempDirectory: root, + pathMappings: [{ vfsPath: "/wordpress/wp-content/plugins/fixture", hostPath: source }], + sandboxed: (...args) => { + sandboxedCalls.push(args) + return "sandboxed" + }, + }) + + // Shell semantics, the run environment and the mapped working directory reach the host. + const shell = await run(handler('{ echo hi; false; echo "exit:$?"; } | tail -c 100; echo "$DB_NAME $HOME $TMPDIR"; pwd', [], { + cwd: "/wordpress/wp-content/plugins/fixture/tests", + env: { HOME: "/home/web_user", PATH: "/" }, + }) as ChildLike) + assert.deepEqual(shell.events, ["spawn", "exit"], "spawn is emitted before exit") + assert.equal(shell.code, 0) + assert.equal(shell.stdout, `hi\nexit:1\nruntime-db /host-home ${root}\n${join(source, "tests")}\n`) + + // stdin, stderr and non-zero exit status stream through. + const piped = handler("cat; echo err >&2; exit 7", [], {}) as ChildLike + piped.stdin.write("from-stdin") + piped.stdin.end() + const pipedResult = await run(piped) + assert.deepEqual([pipedResult.stdout, pipedResult.stderr, pipedResult.code], ["from-stdin", "err\n", 7]) + + // A missing binary behaves like a native fork whose exec failed. + const missing = await run(handler(["/nonexistent/wp-codebox-binary"], [], {}) as ChildLike) + assert.deepEqual(missing.events, ["spawn", "exit"]) + assert.equal(missing.code, 127) + + // Codebox's sandbox PHP binary for PHPUnit process isolation stays in php-wasm. + assert.equal(handler("'/internal/shared/bin/php' -d memory_limit=-1 -f /tmp/job.php", [], {}), "sandboxed") + assert.equal(handler(["/internal/shared/bin/php", "-f", "/tmp/job.php"], [], {}), "sandboxed") + assert.equal(sandboxedCalls.length, 2) + + assert.equal(resolveHostWorkingDirectory("/somewhere/unmapped", { tempDirectory: root, pathMappings: [] }), root) + assert.equal(resolveHostWorkingDirectory(undefined, { tempDirectory: root, pathMappings: [] }), root) + + // Off by default; on prepares an identity-mounted per-run temp dir that is removed with the run. + assert.equal(normalizeRuntimeWordPressEnvironmentSpec({ kind: "wordpress", version: "latest", hostProcess: "shell" }).hostProcess, "shell") + assert.throws(() => normalizeRuntimeWordPressEnvironmentSpec({ kind: "wordpress", version: "latest", hostProcess: "mysql" }), /hostProcess must be one of: none, shell/) + const spec = { backend: "wordpress-playground", environment: { version: "latest" }, runtimeEnv: { DB_NAME: "runtime-db" }, secretEnv: { PASS: "secret" }, secretEnvTargets: { DB_PASSWORD: "PASS" } } as unknown as RuntimeCreateSpec + assert.equal(await prepareHostProcessExecution(spec, []), undefined) + const prepared = await prepareHostProcessExecution({ ...spec, environment: { version: "latest", hostProcess: "shell" } } as RuntimeCreateSpec, [{ source, target: "/wordpress/wp-content/plugins/fixture" }]) + assert.ok(prepared) + assert.equal(prepared.tempMount.hostPath, prepared.tempMount.vfsPath) + assert.equal(prepared.iniEntries.sys_temp_dir, prepared.tempMount.hostPath) + assert.equal(prepared.workerOptions.env.DB_PASSWORD, "secret") + assert.ok(prepared.evidence.environmentNames.includes("DB_PASSWORD")) + assert.doesNotMatch(JSON.stringify(prepared.evidence), /secret/, "evidence records names, never values") + await prepared.dispose() + await assert.rejects(realpath(prepared.tempMount.hostPath), /ENOENT/) +} finally { + await rm(root, { recursive: true, force: true }) +} + +async function run(child: ChildLike): Promise<{ events: string[], code: number, stdout: string, stderr: string }> { + const events: string[] = [] + let stdout = "" + let stderr = "" + child.stdout.on("data", (chunk: Uint8Array) => { stdout += Buffer.from(chunk).toString() }) + child.stderr.on("data", (chunk: Uint8Array) => { stderr += Buffer.from(chunk).toString() }) + child.on("spawn", () => events.push("spawn")) + const code = await new Promise((resolve) => child.on("exit", (exitCode: number) => { + events.push("exit") + resolve(exitCode) + })) + return { events, code, stdout, stderr } +} + +console.log("host process spawn handler ok") diff --git a/tests/playground-host-process-execution.integration.test.ts b/tests/playground-host-process-execution.integration.test.ts new file mode 100644 index 00000000..8ae41850 --- /dev/null +++ b/tests/playground-host-process-execution.integration.test.ts @@ -0,0 +1,131 @@ +import assert from "node:assert/strict" +import { execFile } from "node:child_process" +import { cp, mkdir, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { promisify } from "node:util" + +import { buildWordPressPhpunitRecipe } from "../packages/runtime-core/src/recipe-builders.js" + +// End-to-end proof for runtime.hostProcess (issue #2635): with `shell`, PHP's +// exec() reaches the host /bin/sh -c and shares PHP's temp dir; without it, +// Playground's sandboxed spawn handler keeps host processes unavailable. +const execFileAsync = promisify(execFile) +const root = await mkdtemp(join(tmpdir(), "wp-codebox-host-process-")) +const plugin = join(root, "plugin") +const harness = join(root, "harness") +const pipeline = '{ echo hi; false; echo "exit:$?"; } | tail -c 100' +const nativePipeline = await execFileAsync("/bin/sh", ["-c", pipeline]) + +try { + await cp("tests/fixtures/phpunit-playground-harness", harness, { recursive: true }) + await execFileAsync("composer", ["install", "--no-interaction", "--prefer-dist"], { cwd: harness, timeout: 300_000, maxBuffer: 2 * 1024 * 1024 }) + await mkdir(join(plugin, "tests"), { recursive: true }) + await writeFile(join(plugin, "host-process-fixture.php"), "\ntests\n") + + // Enabled: both acceptance commands return the native-shell result. + await writeFile(join(plugin, "tests", "HostProcessTest.php"), `assertSame(${phpString(nativePipeline.stdout)}, implode("\\n", $output) . "\\n"); + $this->assertSame('exit:1', $last); + // php-wasm's popen() path (exec/system/shell_exec) drops exit codes for + // every spawn handler; proc_open() carries the host status end to end. + $process = proc_open(${phpString(pipeline)}, array(array('pipe', 'r'), array('pipe', 'w'), array('pipe', 'w')), $pipes); + fclose($pipes[0]); + $this->assertSame(${phpString(nativePipeline.stdout)}, stream_get_contents($pipes[1])); + $this->assertSame(0, proc_close($process)); + } + public function test_proc_open_streams_stdin_stdout_stderr_and_status(): void { + $process = proc_open('cat; echo to-stderr >&2; exit 7', array(array('pipe', 'r'), array('pipe', 'w'), array('pipe', 'w')), $pipes); + fwrite($pipes[0], 'from-stdin'); + fclose($pipes[0]); + $this->assertSame('from-stdin', stream_get_contents($pipes[1])); + $this->assertSame("to-stderr\\n", stream_get_contents($pipes[2])); + $this->assertSame(7, proc_close($process)); + } + public function test_host_command_reads_file_php_wrote_to_temp_dir(): void { + $path = tempnam(sys_get_temp_dir(), 'wpcb'); + $payload = 'written-by-php-' . bin2hex(random_bytes(8)); + file_put_contents($path, $payload); + $this->assertSame($payload, exec('cat ' . escapeshellarg($path))); + $this->assertSame(sys_get_temp_dir(), exec('printf %s "$TMPDIR"')); + unlink($path); + } +} +`) + const enabled = await runRecipe("enabled", "shell") + assert.equal(enabled.output.success, true, enabled.stdout) + assert.equal(enabled.evidence.status, "passed", enabled.diagnostic) + assert.equal(enabled.evidence.summary.passed, 3, enabled.diagnostic) + const metadata = JSON.parse(await readFile(join(enabled.runtimeDirectory, "metadata.json"), "utf8")) as { hostProcessExecution?: { enabled?: boolean, mode?: string, sharedPaths?: { tempDirectory?: string } } } + assert.equal(metadata.hostProcessExecution?.enabled, true, "run evidence must record host process execution") + assert.equal(metadata.hostProcessExecution?.mode, "shell") + const review = JSON.parse(await readFile(join(enabled.runtimeDirectory, "files/review.json"), "utf8")) as { riskFlags?: string[] } + assert.ok(review.riskFlags?.includes("host-process-execution"), "review receipt must flag host process execution") + const tempDirectory = metadata.hostProcessExecution?.sharedPaths?.tempDirectory + assert.ok(tempDirectory, "evidence must name the shared temp directory") + await assert.rejects(stat(tempDirectory), /ENOENT/, "the per-run host temp directory is removed with the run") + + // Disabled (default): the same pipeline stays inside the sandbox and fails. + await writeFile(join(plugin, "tests", "HostProcessTest.php"), `assertNotSame(array('hi', 'exit:1'), $output); + $process = proc_open(${phpString(pipeline)}, array(array('pipe', 'r'), array('pipe', 'w'), array('pipe', 'w')), $pipes); + fclose($pipes[0]); + $this->assertSame('', stream_get_contents($pipes[1])); + $this->assertSame(127, proc_close($process)); + } +} +`) + const disabled = await runRecipe("disabled") + assert.equal(disabled.output.success, true, disabled.stdout) + assert.equal(disabled.evidence.status, "passed", disabled.diagnostic) + const disabledMetadata = JSON.parse(await readFile(join(disabled.runtimeDirectory, "metadata.json"), "utf8")) as Record + assert.equal(disabledMetadata.hostProcessExecution, undefined) +} finally { + await rm(root, { recursive: true, force: true }) +} + +async function runRecipe(name: string, hostProcess?: "shell") { + const recipePath = join(root, `${name}-recipe.json`) + const artifactsPath = join(root, `${name}-artifacts`) + const recipe = buildWordPressPhpunitRecipe({ + pluginSlug: "host-process-fixture", + ...(hostProcess ? { hostProcess } : {}), + extra_plugins: [{ source: plugin, slug: "host-process-fixture", activate: false }], + dependencyMounts: ["/wordpress/wp-content/plugins/host-process-fixture"], + mounts: [{ source: join(harness, "vendor"), target: "/wp-codebox-vendor", mode: "readonly" }], + }) + assert.equal(recipe.runtime?.hostProcess, hostProcess) + await writeFile(recipePath, `${JSON.stringify(recipe)}\n`) + let stdout: string + try { + stdout = (await execFileAsync(process.execPath, ["packages/cli/dist/index.js", "recipe-run", "--recipe", recipePath, "--artifacts", artifactsPath, "--json"], { + cwd: process.cwd(), timeout: 300_000, maxBuffer: 2 * 1024 * 1024, + })).stdout + } catch (error) { + assert(error && typeof error === "object" && "stdout" in error && typeof error.stdout === "string", String(error)) + stdout = error.stdout + } + const runtime = JSON.parse(await readFile(join(artifactsPath, "latest-runtime.json"), "utf8")) as { paths?: { runtimeDirectory?: string } } + assert.ok(runtime.paths?.runtimeDirectory, stdout) + const runtimeDirectory = join(artifactsPath, runtime.paths.runtimeDirectory) + const diagnostic = await readFile(join(runtimeDirectory, "files/phpunit/.pg-test-result.txt"), "utf8").catch((error) => String(error)) + const evidence = JSON.parse(await readFile(join(runtimeDirectory, "files/test-results.json"), "utf8").catch(() => "{}")) as { status?: string, summary: { passed?: number } } + return { output: JSON.parse(stdout) as { success?: boolean }, stdout, runtimeDirectory, diagnostic: `${stdout}\n${diagnostic}`, evidence: { summary: {}, ...evidence } } +} + +function phpString(value: string): string { + return `'${value.replaceAll("\\", "\\\\").replaceAll("'", "\\'")}'` +} + +console.log("playground host process execution integration ok")