PHP SDK guide

Payload protection and key rotation

A PHP client and worker can opt in to authenticated encryption of supported Avro payloads in one namespace.

Pass a PayloadProtection key ring to the SDK client. Workers use the key ring of the client they receive. Use separate clients for protected workloads and workloads using ordinary Avro. Keep the key ring in the application, scoped to its namespace.

Use PHP SDK 3.35.0 or later, PHP with ext-sodium, and Native Server 3.33.0 or later. The example uses protected_signal_validation_v1, advertised in Native Server's cluster info. Follow Client setup to install the SDK and start Server. Use the PHP CLI with pcntl to shut down the example worker gracefully.

Start with one key

Set WORKFLOW_TOKEN to a local development credential. In a deployment, use a worker credential in workers and a caller credential for workflow commands and result reads. Generate the first key once and distribute the same value to both terminals. In production, use a secret store to distribute keys.

export SERVER_URL=http://localhost:8080
export WORKFLOW_NAMESPACE=default
export WORKFLOW_PROTECTION_KEY_V1="$(php -r 'echo base64_encode(random_bytes(32));')"
export WORKFLOW_PROTECTION_ACTIVE_KEY=v1

Save this file as protected-order.php in the Composer project.

<?php

declare(strict_types=1);

use DurableWorkflow\Client;
use DurableWorkflow\PayloadProtection;
use DurableWorkflow\Worker;
use DurableWorkflow\Worker\WorkflowContext;

require __DIR__.'/vendor/autoload.php';

const ORDER_WORKFLOW = 'example.protected-order';
const ORDER_QUEUE = 'php-protected-order';

$keys = [];
foreach (['v1' => 'WORKFLOW_PROTECTION_KEY_V1', 'v2' => 'WORKFLOW_PROTECTION_KEY_V2'] as $id => $name) {
    $encoded = getenv($name);
    if ($encoded === false) {
        continue;
    }
    $key = base64_decode($encoded, true);
    if ($key === false || strlen($key) !== 32) {
        throw new InvalidArgumentException('Invalid workflow protection key.');
    }
    $keys[$id] = $key;
}

$client = new Client(
    getenv('SERVER_URL'),
    token: getenv('WORKFLOW_TOKEN'),
    namespace: getenv('WORKFLOW_NAMESPACE') ?: 'default',
    payloadProtection: new PayloadProtection($keys, getenv('WORKFLOW_PROTECTION_ACTIVE_KEY')),
);

$workflowId = $argv[2] ?? 'php-payload-rotation';
switch ($argv[1] ?? '') {
    case 'worker':
        $worker = new Worker($client, ORDER_QUEUE);
        $worker->registerWorkflow(
            ORDER_WORKFLOW,
            static function (WorkflowContext $context, string $order): array {
                $context->waitCondition(
                    fn (): bool => $context->signals('approve') !== [],
                    key: 'approved',
                );
                [$quantity] = $context->signals('approve')[0];

                return ['order' => $order, 'quantity' => $quantity];
            },
        );
        $worker->declareSignal(ORDER_WORKFLOW, 'approve', static fn (int $quantity): mixed => null);
        $worker->run(pollTimeoutSeconds: 1);
        break;

    case 'start':
        $client->startWorkflow(ORDER_WORKFLOW, $workflowId, ORDER_QUEUE, ['private order λ']);
        for ($attempt = 0; $attempt < 60; $attempt++) {
            if ($client->describeWorkflow($workflowId)->status === 'waiting') {
                echo "$workflowId is waiting\n";
                exit(0);
            }
            usleep(500_000);
        }
        throw new RuntimeException('The workflow did not reach its signal wait.');

    case 'finish':
        $client->signalWorkflow($workflowId, 'approve', [7], requestId: 'approve-once');
        echo json_encode($client->workflowResult($workflowId), JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE), "\n";
        break;

    default:
        throw new InvalidArgumentException('Use worker, start, or finish.');
}

In the worker terminal run php protected-order.php worker. In the caller terminal, start the workflow. Use a new ID for each repetition and pass the same ID to the start and finish commands.

php protected-order.php start php-payload-rotation

Rotate the key and resume

When the caller prints that the workflow is waiting, stop the worker with Ctrl+C. Keep WORKFLOW_PROTECTION_KEY_V1, generate the second key once, and make both keys available to both terminals. Set v2 active before restarting.

export WORKFLOW_PROTECTION_KEY_V2="$(php -r 'echo base64_encode(random_bytes(32));')"
export WORKFLOW_PROTECTION_ACTIVE_KEY=v2
# Worker terminal, with both keys and v2 active
php protected-order.php worker

# Caller terminal, with both keys and v2 active
php protected-order.php finish php-payload-rotation

The replacement worker opens the original workflow input with v1 and writes its result with v2. The caller prints {"order":"private order λ","quantity":7}. In production, distribute both keys to every caller and worker before changing the active writer. Retained payloads keep their original ciphertext and key IDs. Retain old keys until dependent histories, external objects, and backup copies needed for restore have expired or been removed. Missing keys produce payload_key_unavailable.

What receives protection

Protection covers durable workflow and ordinary activity inputs and results, recorded side-effect results, and application signal, update, and worker-backed query payloads. Child workflows and continue-as-new inherit protection. An external payload storage driver receives ciphertext. Operator tools can display a protected value and its public key ID.

Identifiers, type and command names, queues, namespaces, searchable fields, memo, and application error text remain visible. Keep sensitive data out of those fields and logs. Activity heartbeat details, checkpoints, managed ingress, and server-side projections have separate contracts and lie outside this scope. After an ambiguous signal or update response, retry a retained prepared command with its original request ID and envelope.