Skip to content

Rule sandboxing and isolation boundaries

A sandbox driver is the component that executes the PHP source registered for a custom_rule handler. Choosing a driver determines where that code runs, which checks precede it, and what can happen when it takes too long. A timeout result alone does not tell you whether the code was interrupted.

We reuse the mechanism described in Custom rule evaluation: a graph names an installed handler; your application registers its source and supplies a driver. The engine passes candidate context, arguments, edge and node information, presentation data and evaluation time to that driver. A plugin that implements another rule type runs under its own extension contract; configuring a sandbox driver does not wrap every plugin or callback in the application.

Choose a boundary that matches the code you run

Section titled “Choose a boundary that matches the code you run”

The common contract is SandboxDriverInterface::execute(string $code, array $context): SandboxResult. A successful evaluation returns a boolean decision in allowed and no errorCode. A failed evaluation returns an error code; the application must not treat that as a normal business decision.

Driver or mode Where the rule executes How the time limit works What your application and environment still provide
FiberTimeoutDriver The application PHP process, through evaluated source with token and invocation checks. Default timeout: 50 ms. Checks elapsed time after execution returns. It cannot preempt arbitrary PHP execution. Trusted, bounded code. This mode supplies no operating-system process, memory or network isolation.
PHPDisabledFunctionsDriver A separate PHP CLI process, with token checks, configured disabled functions, a PHP memory limit and a temporary-directory open_basedir. Defaults: 50 ms and 16M. The parent supervises elapsed time and terminates the supervised process when the deadline is exceeded. A usable PHP CLI executable, process creation and a writable temporary base directory. Process privileges and stronger operating-system controls belong to deployment.
DockerIsolatedDriver(command: …) A command supplied by your application. That command may launch a container or another isolated worker. Default timeout: 200 ms. The same bounded process transport supervises the command. The trusted launcher creates and configures the isolation and handles container/descendant cleanup. The driver itself does not invoke Docker automatically.
DockerIsolatedDriver(executor: …) A callable in the application process. Checks elapsed time after the callable returns. Any real isolation must be supplied by the callable’s implementation. Its name does not make the callable a container.

For a small handler written and controlled by your application, the same-process mode can avoid process startup cost. Choose the PHP subprocess when its separate process and PHP restrictions fit the requirement, and check the whole engine path against its performance budgets. Use the command mode when your integration already provides a launcher with the required operating-system controls and lifecycle handling.

Fiber evaluates inside the application process. The PHP driver supervises a separate PHP child over pipes. The command form of DockerIsolatedDriver delegates the worker boundary and its cleanup to a trusted launcher supplied by your application.

The token checks in the built-in Fiber and PHP drivers restrict the source to the supported rule surface. They reject, among other constructs, forbidden function calls, dynamic calls, includes and object creation. They are not a proof that arbitrary hostile PHP is safe. The Fiber implementation still evaluates in the same process, and its recognition of a few obvious infinite-loop forms does not make its timeout preemptive.

Observe the difference between detection and interruption

Section titled “Observe the difference between detection and interruption”

A controlled comparison makes the time boundary visible without executing hostile code. Both modes below receive the same trusted finite arithmetic loop, with no files, network access, waiting or spawned work:

$code = <<<'PHP'
$total = 0;
for ($i = 0; $i < 30000000; ++$i) {
$total = ($total + $i) % 97;
}
return $total >= 0;
PHP;

The loop is deliberately more work than a small rule should perform. It eventually returns a boolean. The comparison gives each driver a 50 ms deadline and calls the driver directly:

$result = $driver->execute($code, ['context' => []]);

This call examines the driver’s behavior. It does not go through the engine’s separate rule and navigation budgets.

The complete sandbox-comparison.php constructs both real drivers, measures elapsed time around each call and checks that the PHP driver’s temporary files have been removed. In one PHP CLI run with a one-CPU container limit, it returned:

{"mode":"fiber","budget_ms":50,"allowed":false,"error_code":"SANDBOX_TIMEOUT","elapsed_ms":162.2}
{"mode":"php_process","budget_ms":50,"allowed":false,"error_code":"SANDBOX_TIMEOUT","elapsed_ms":51.2}
{"temporary_files_remaining":0}

The status is the same; the mechanisms differ. Fiber finished the finite loop and then discarded the boolean result because the elapsed time exceeded its limit. The PHP call returned close to its deadline. On that timeout path, the parent terminates the supervised process instead of waiting for the rule’s boolean result.

These numbers describe this run, not promised latency or a benchmark. Startup, scheduling and cleanup affect elapsed time, and another machine may finish the loop sooner. The useful distinction is where supervision occurs: an after-return check observes work already done; an external supervisor can stop the process it manages. A driver timeout cannot roll back external side effects that have already happened.

The download runs as php sandbox-comparison.php beside your existing application’s vendor/autoload.php. It uses a private temporary directory and a finite workload. Keep timing experiments bounded in the same way.

To configure the subprocess driver, supply its constructor options and pass it to ExecKernelFactory::build(). The following example registers a handler named minimum_reviews: publication is allowed when the application supplies at least the configured number of completed reviews.

use ExecKernel\Infrastructure\Engine\ExecKernelFactory;
use ExecKernel\Infrastructure\Sandbox\PHPDisabledFunctionsDriver;
$driver = new PHPDisabledFunctionsDriver(
timeoutMs: 200,
memoryLimit: '16M',
phpBinary: PHP_BINARY,
);
$engine = (new ExecKernelFactory())->build(
customRules: [
'minimum_reviews' => 'return $api->context->get("reviewCount", 0) >= $args["minimum"];',
],
sandboxDriver: $driver,
);

phpBinary must identify the PHP CLI executable. The downloadable program uses PHP_BINARY because that program itself runs under PHP CLI. The timeout covers the supervised subprocess operation, including startup and communication; memoryLimit is passed to the child PHP interpreter. The optional openBasedir constructor argument selects the writable base under which the driver creates its private temporary directory. The child’s actual open_basedir is set to that per-call directory.

The graph refers to the registered handler by name:

{
"edge_id": 10,
"rule": "custom_rule",
"params": {
"handler": "minimum_reviews",
"args": {"minimum": 2}
}
}

In the complete example, edge 10 goes from review node 1 to terminal 2. ArrayGraphLoader also receives allowedCustomHandlers: ['minimum_reviews']. The allowlist admits the name during loading; the factory registration supplies its source; the driver executes it. All three have distinct jobs.

The handler reads reviewCount from candidate context and minimum from its arguments. It returns true or false and emits no output. The built-in drivers treat printed output or a non-boolean return, including integer 1, as an invalid return. No driver is selected automatically when you register source without sandboxDriver.

Account for the engine’s separate performance budget

Section titled “Account for the engine’s separate performance budget”

A driver that completes within its own deadline has not necessarily satisfied the engine. As explained in Execution budgets and circuit breakers, the engine measures evaluation and navigation independently. In this version, PerformanceBudget::CUSTOM_RULE_MAX_MS is fixed at 2 ms; the general rule evaluation budget is 50 ms.

Process startup and communication are part of the time the engine sees. Changing the driver’s timeout from 50 to 200 ms does not raise those engine budgets. Factory has no parameter for increasing the fixed custom-rule budget.

The complete sandbox-engine.php runs the review example with the normal engine stopwatch. It accepts fiber or php as its mode:

Terminal window
php sandbox-engine.php fiber
php sandbox-engine.php php

The Fiber run with reviewCount: 2 produced:

{
"mode": "fiber",
"preview": "pending",
"current_node": 2,
"result_type": "terminal"
}

The preview is pending because a normal view defers execution of a custom handler. Choosing the edge runs the handler and, in this run, produces the terminal result.

The PHP-process run produced:

{
"mode": "php",
"preview": "pending",
"error_code": "EK-PERF-002",
"exception": "UserRuleTooSlowException",
"state_changed": false
}

Here the subprocess completed, but the measured evaluation exceeded 2 ms. The engine rejected the operation and the original state stayed unchanged. This is EK-PERF-002, not the driver’s SANDBOX_TIMEOUT.

That consequence belongs in the choice of integration. Measure the actual driver path in the environment where the application runs. If a necessary process boundary cannot meet the fixed budget, increasing the driver timeout does not make this custom_rule path viable. Your application can instead obtain an external decision through a trusted service before calling the engine, validate that result and supply the resulting fact as context for a built-in condition. That changes where and when the decision is made; it requires the application to control the fact’s authority and freshness. A plugin rule also needs its own execution design and remains subject to applicable engine budgets.

DockerIsolatedDriver is a transport to a trusted execution component. In command mode it writes a JSON object with code and context to the command’s standard input, then reads a JSON object from standard output.

This is a configuration fragment for a launcher your application has already installed. $launcherPath is a trusted executable path supplied by application configuration, not a path accepted from a request. $launcherWorkingDirectory is the trusted directory in which that launcher must run:

use ExecKernel\Infrastructure\Sandbox\DockerIsolatedDriver;
$driver = new DockerIsolatedDriver(
command: [$launcherPath],
timeoutMs: 200,
workingDirectory: $launcherWorkingDirectory,
env: [],
);

The command must consume its input, run the evaluation under the intended controls and emit a result such as:

{"allowed":true,"errorCode":null}

A normal false decision is {"allowed":false,"errorCode":null}. An execution failure carries a supported error code and must not grant the choice.

The transport bounds declarative input to 1 MiB and combined subprocess output/error streams to 64 KiB. It uses the explicit environment plus a default PATH rather than implicitly inheriting the application’s environment. For a successful command result it requires a zero exit status, no non-whitespace stderr and a valid JSON object; duplicate JSON keys are rejected.

These checks validate transport and results. The launcher owns the worker’s permissions, accessible files, network access and resource controls. It also owns cleanup of any descendants or containers: the transport terminates the process it supervises, not an arbitrary process tree or a container identified elsewhere. A working command does not establish those isolation guarantees by itself.

The executor constructor option is different: it invokes a callable and normalizes its returned array or SandboxResult. If both executor and command are supplied, the callable path takes precedence. An elapsed-time check after that callable returns has the same preemption limitation as other same-process checks.

Handle a failure without treating it as “false”

Section titled “Handle a failure without treating it as “false””

At the driver boundary, these are the meaningful outcomes:

Driver result Meaning Normal mapping through custom_rule
allowed: true, no error The predicate allows the edge. The engine continues its remaining checks.
allowed: false, no error The predicate rejects the edge normally. A blocked condition, ultimately ForbiddenEdgeException with EK-SEC-NAV-002.
SANDBOX_INVALID_RETURN The handler or launcher did not produce the required result. SandboxInvalidReturnException, EK-RULE-022.
SANDBOX_TIMEOUT, SANDBOX_SECURITY_VIOLATION or SANDBOX_RUNTIME_ERROR Execution failed rather than returning a business decision. SandboxRuntimeException, EK-RULE-021.
SANDBOX_INTERNAL_FAILURE, or no configured driver The execution component is unavailable or failed internally. SandboxDriverUnavailableException, EK-FATAL-003.

The engine checks elapsed budgets around both successful and failed evaluations. A budget exception can therefore take precedence over a driver’s error; the direct driver table is not a promise that every engine call exposes that exact error unchanged.

Keep the known session state after a definite local rejection and use an appropriate technical-error response when evaluation failed. Do not retry a timed-out handler by silently changing to a weaker execution mode. The PHP driver itself does not fall back to in-process execution when it cannot start its subprocess.

Finally, send only the data the rule needs. The sandbox receives the session’s candidate context; it is not a secret store and the driver contract does not automatically remove sensitive fields. Security policies and credential management shows how your application keeps credentials in configuration and restricts admitted context before rule execution.