Skip to content
Durable Workflowrust

Module payload_protection

Source
Expand description

Logical payload boundaries and application-held protection keys.

§Protect workflow payloads and rotate keys

Enable the SDK’s payload-protection Cargo feature. Pass a key ring to the client with ClientBuilder::payload_protection. A worker uses the key ring of the client it receives. Use separate clients for protected workloads and workloads using ordinary Avro.

Use Rust SDK 4.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 create an example Cargo binary project.

cargo new protected-order
cd protected-order
cargo add [email protected] --features payload-protection
cargo add base64
cargo add tokio --features macros,rt-multi-thread,signal,time

Run the local example with a development WORKFLOW_TOKEN. In a deployment, set a worker credential for the worker and a caller credential for workflow commands and results. Generate the first key once, then share the same key ring with both processes through your application’s secret distribution.

export SERVER_URL=http://localhost:8080
export WORKFLOW_NAMESPACE=default
export WORKFLOW_PROTECTION_KEY_V1="$(openssl rand -base64 32)"
export WORKFLOW_PROTECTION_ACTIVE_KEY=v1

Save the program as src/main.rs.

use base64::{engine::general_purpose::STANDARD, Engine as _};
use durable_workflow::{payload_protection::PayloadProtection, AvroValue, Client, Worker};
use std::{env, error::Error, sync::Arc, time::Duration};

const ORDER_TYPE: &str = "example.protected-order";
const ORDER_QUEUE: &str = "rust-protected-order";

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    let mut keys = Vec::new();
    for (id, variable) in [
        ("v1", "WORKFLOW_PROTECTION_KEY_V1"),
        ("v2", "WORKFLOW_PROTECTION_KEY_V2"),
    ] {
        if let Ok(encoded) = env::var(variable) {
            let key: [u8; 32] = STANDARD
                .decode(encoded)?
                .try_into()
                .map_err(|_| "Payload protection keys must be 32 bytes.")?;
            keys.push((id.to_owned(), key));
        }
    }
    let protection =
        PayloadProtection::new(keys, Some(env::var("WORKFLOW_PROTECTION_ACTIVE_KEY")?))?;
    let client = Client::builder(env::var("SERVER_URL")?)
        .token(Some(env::var("WORKFLOW_TOKEN")?))
        .namespace(env::var("WORKFLOW_NAMESPACE").unwrap_or_else(|_| "default".to_owned()))
        .payload_protection(Arc::new(protection))
        .build()?;

    let mut args = env::args().skip(1);
    let role = args.next().ok_or("Use worker, start, or finish.")?;
    let id = args
        .next()
        .unwrap_or_else(|| "rust-payload-rotation".to_owned());
    match role.as_str() {
        "worker" => {
            let mut worker = Worker::new(client, ORDER_QUEUE).poll_timeout(Duration::from_secs(1));
            worker.register_workflow_avro_value(ORDER_TYPE, |ctx, input| async move {
                let AvroValue::Array(values) = input else {
                    return Err(durable_workflow::Error::Codec(
                        "Expected order arguments.".into(),
                    ));
                };
                let [AvroValue::String(order)] = values.as_slice() else {
                    return Err(durable_workflow::Error::Codec(
                        "Expected an order name.".into(),
                    ));
                };
                let signal = ctx.wait_signal_avro_value("approve").await?;
                let [AvroValue::Long(quantity)] = signal.as_slice() else {
                    return Err(durable_workflow::Error::Codec(
                        "Expected a quantity.".into(),
                    ));
                };
                Ok(AvroValue::Array(vec![
                    AvroValue::String(order.to_owned()),
                    AvroValue::Long(*quantity),
                ]))
            });
            worker.declare_workflow_signals(ORDER_TYPE, &["approve"])?;
            worker
                .run_until(async {
                    let _ = tokio::signal::ctrl_c().await;
                })
                .await?;
        }
        "start" => {
            client
                .start_workflow(ORDER_TYPE, ORDER_QUEUE, &id, ("private order λ",))
                .await?;
            for _ in 0..60 {
                if client.describe_workflow(&id).await?.status.as_deref() == Some("waiting") {
                    println!("{id} is waiting");
                    return Ok(());
                }
                tokio::time::sleep(Duration::from_millis(500)).await;
            }
            return Err("The workflow did not reach its signal wait.".into());
        }
        "finish" => {
            client
                .signal_workflow_with_request_id(&id, "approve", (7_i64,), "approve-once")
                .await?;
            for _ in 0..60 {
                let run = client.describe_workflow(&id).await?;
                if run.is_completed() {
                    println!(
                        "{:?}",
                        run.output_avro_value.ok_or("Missing workflow result.")?
                    );
                    return Ok(());
                }
                tokio::time::sleep(Duration::from_millis(500)).await;
            }
            return Err("The workflow did not complete.".into());
        }
        _ => return Err("Use worker, start, or finish.".into()),
    }
    Ok(())
}

Run cargo run -- worker in one terminal with v1 active, then start the workflow in another terminal with the same keys. Pick a fresh workflow ID for each repetition and use it for both caller commands.

cargo run -- start rust-payload-rotation

When the caller confirms the workflow is waiting, stop the worker with Ctrl+C. Keep the original key, generate v2 once and distribute it to both terminals, then set v2 as the active write key.

export WORKFLOW_PROTECTION_KEY_V2="$(openssl rand -base64 32)"
export WORKFLOW_PROTECTION_ACTIVE_KEY=v2
# Worker terminal, with both keys and v2 active
cargo run -- worker

# Caller terminal, with both keys and v2 active
cargo run -- finish rust-payload-rotation

The replacement worker opens the original input with v1, resumes the workflow after the signal and writes the result with v2. The caller prints Array([String("private order λ"), Long(7)]).

In production, give every caller and worker both keys before changing the active key. Rotation preserves retained ciphertext. Keep old keys until dependent histories, external objects and backups needed for restore are removed or expire. A missing key produces payload_key_unavailable.

§Protection boundaries

Protection covers durable workflow and ordinary activity arguments and results, recorded side-effect results, and application signal, update, and worker-backed query values. Child runs and continue-as-new inherit protection. External payload storage receives encrypted bytes. Operators can see the protected envelope and its public key ID without access to the key.

Workflow IDs, type and command names, queues, namespaces, searchable fields, memo and application error text remain visible. Keep sensitive data out of these fields and logs. Activity heartbeat details, checkpoints, managed ingress and server-side projections have separate contracts and lie outside this scope. To recover an ambiguous signal or update response, retain the prepared command before sending and retry with its original request ID and envelope.

Structs§

PayloadProtection
A process-local keyring. A missing active key makes this configuration read-only.
PreparedPayloadCommand
Store this record durably before submitting a command whose reply may be lost. It contains the selected target, caller request ID, and encrypted wire input.
ProtectionContext
Scope established by the application or protocol admission.

Enums§

Boundary
The logical payload boundary authenticated with the owning namespace.
ProtectionError
Stable failures contain no application values, key IDs, or raw wire data.