Skip to content
Durable Workflowpython

Protect workflow payloads

Pass PayloadProtection to a Python Client to seal supported application values before sending them to Server. A Worker uses its client's key ring to open task inputs and seal results. Both clients must use the same namespace. Keep a separate client for workloads that use ordinary Avro payloads.

Use Python SDK 2.27.0 or later and Native Server 3.33.0 or later. The example uses protected_signal_validation_v1, advertised in Native Server's cluster info. Start a local Native Server and install the SDK with its protection extra.

python -m pip install 'durable-workflow[protection]==2.27.0'
export SERVER_URL=http://localhost:8080
export WORKFLOW_NAMESPACE=default
export WORKFLOW_PROTECTION_KEY_V1="$(python -c 'import base64,secrets; print(base64.b64encode(secrets.token_bytes(32)).decode())')"
export WORKFLOW_PROTECTION_ACTIVE_KEY=v1

Set WORKFLOW_TOKEN in each process to its development credential. In a deployment, use a worker credential for the worker and a client credential for commands and reading results. Distribute the key ring through your secret store. Each key below is a base64-encoded random 32-byte value.

Start with one key

Save the following as protected_order.py.

import argparse
import asyncio
import base64
import os

from durable_workflow import Client, PayloadProtection, Worker, workflow

WORKFLOW_TYPE = "example.protected-order"
QUEUE = "python-protected-order"


@workflow.defn(name=WORKFLOW_TYPE)
class ProtectedOrder:
    def run(self, ctx, order: str):
        self.quantity = None
        yield ctx.wait_condition(lambda: self.quantity is not None, key="approved")
        return {"order": order, "quantity": self.quantity}

    @workflow.signal("approve")
    def approve(self, quantity: int) -> None:
        self.quantity = quantity


def protection() -> PayloadProtection:
    keys = {}
    for key_id, variable in (
        ("v1", "WORKFLOW_PROTECTION_KEY_V1"),
        ("v2", "WORKFLOW_PROTECTION_KEY_V2"),
    ):
        encoded = os.getenv(variable)
        if encoded:
            keys[key_id] = base64.b64decode(encoded, validate=True)
    return PayloadProtection(keys, active_key_id=os.environ["WORKFLOW_PROTECTION_ACTIVE_KEY"])


async def main(role: str, workflow_id: str) -> None:
    async with Client(
        os.environ["SERVER_URL"],
        token=os.environ["WORKFLOW_TOKEN"],
        namespace=os.environ.get("WORKFLOW_NAMESPACE", "default"),
        payload_protection=protection(),
    ) as client:
        if role == "worker":
            worker = Worker(client, task_queue=QUEUE, workflows=[ProtectedOrder], poll_timeout=1)
            await worker.run()
        elif role == "start":
            handle = await client.start_workflow(
                workflow_id=workflow_id,
                workflow_type=WORKFLOW_TYPE,
                task_queue=QUEUE,
                input=["private order λ"],
            )
            for _ in range(60):
                if (await handle.describe()).status == "waiting":
                    print(f"{workflow_id} is waiting")
                    return
                await asyncio.sleep(0.5)
            raise TimeoutError("The workflow did not reach its signal wait.")
        else:
            handle = client.get_workflow_handle(workflow_id)
            await handle.signal("approve", [7], request_id="approve-once")
            print(await handle.result())


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("role", choices=["worker", "start", "finish"])
    parser.add_argument("--workflow-id", default="python-payload-rotation")
    args = parser.parse_args()
    try:
        asyncio.run(main(args.role, args.workflow_id))
    except KeyboardInterrupt:
        pass

Start a worker in one terminal. In another terminal with the same connection and key configuration, start the workflow. Choose a new workflow ID on each repetition and pass it to both caller commands.

# Worker terminal
python protected_order.py worker

# Caller terminal
python protected_order.py start --workflow-id python-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 it available to both terminals. Set v2 active for each process before restarting.

export WORKFLOW_PROTECTION_KEY_V2="$(python -c 'import base64,secrets; print(base64.b64encode(secrets.token_bytes(32)).decode())')"
export WORKFLOW_PROTECTION_ACTIVE_KEY=v2
# Worker terminal, with both keys and v2 active
python protected_order.py worker

# Caller terminal, with both keys and v2 active
python protected_order.py finish --workflow-id python-payload-rotation

The replacement worker replays the old input using v1 and writes the result using v2. The caller prints {'order': 'private order λ', 'quantity': 7}. Distribute both keys to every caller and worker before changing the active key in a deployment. Retained payloads keep the key ID and ciphertext they were written with. Retain old keys through the lifetime of dependent history, external objects, and backups needed for restore. A missing key produces payload_key_unavailable.

What receives protection

The supported values include workflow and ordinary activity arguments and results, durable side-effect results, and application signal, update, and worker-backed query payloads. Child and continue-as-new runs inherit protection. An external payload storage driver receives already-encrypted bytes. Server, its database, and operator tools can hold or display the protected envelope and its public key ID without access to the key.

Workflow IDs, type and command names, namespace, task queue, searchable fields, memo and application error text remain visible. Keep sensitive values out of these fields and logs. Heartbeat details, checkpoints, managed ingress and server-side projections have separate contracts and lie outside this scope. For ambiguous responses to protected commands, retry the retained prepared command with its original request ID and envelope.