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
76 changes: 76 additions & 0 deletions docs/recipe-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 <command>`.
- 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,
`<os tmpdir>/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
Expand Down
4 changes: 3 additions & 1 deletion packages/cli/src/commands/recipe-build.ts
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -14,6 +14,7 @@ interface WordPressPhpunitBuilderOptions {
workers?: RuntimeWorkerCount
databaseType?: "sqlite" | "mysql" | "mdi-native"
wordpressInstallMode?: RuntimeWordPressInstallMode
hostProcess?: RuntimeHostProcessMode
extensions?: WorkspaceRecipePHPWasmExtensionManifest[]
backendPackage?: WorkspaceRecipeRuntimeBackendPackage
mounts?: WorkspaceRecipeMount[]
Expand Down Expand Up @@ -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 : [],
Expand Down
1 change: 1 addition & 0 deletions packages/cli/src/commands/recipe-run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down
10 changes: 9 additions & 1 deletion packages/cli/src/recipe-validation.ts
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -421,6 +422,13 @@ function validateRecipeRuntimeBundledExtensions(extensions: NonNullable<Workspac
}
}

function validateRecipeRuntimeHostProcess(mode: unknown, recipePath: string): void {
if (mode === undefined) return
if (!RUNTIME_HOST_PROCESS_MODES.includes(mode as typeof RUNTIME_HOST_PROCESS_MODES[number])) {
throw new Error(`Recipe runtime hostProcess must be one of: ${RUNTIME_HOST_PROCESS_MODES.join(", ")}: ${recipePath}`)
}
}

function validateRecipeRuntimeWordPressInstallMode(mode: NonNullable<WorkspaceRecipe["runtime"]>["wordpressInstallMode"] | undefined, recipePath: string): void {
if (mode === undefined) {
return
Expand Down
4 changes: 4 additions & 0 deletions packages/runtime-core/src/recipe-builders.ts
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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
Expand Down Expand Up @@ -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",
Expand Down
4 changes: 4 additions & 0 deletions packages/runtime-core/src/recipe-schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand Down
3 changes: 2 additions & 1 deletion packages/runtime-core/src/runtime-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -740,6 +740,7 @@ export interface WorkspaceRecipe {
assets?: RuntimeAssetSpec
extensions?: WorkspaceRecipePHPWasmExtensionManifest[]
bundledExtensions?: RuntimePHPWasmBundledExtension[]
hostProcess?: RuntimeHostProcessMode
backendPackage?: WorkspaceRecipeRuntimeBackendPackage
stack?: WorkspaceRecipeRuntimeStack
overlays?: WorkspaceRecipeRuntimeOverlay[]
Expand Down
17 changes: 17 additions & 0 deletions packages/runtime-core/src/runtime-neutral-contracts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 & {})
Expand Down Expand Up @@ -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
Expand Down
Loading
Loading