durable-workflow 4.28.0

Rust client and worker SDK for Durable Workflow Cloud and self-hosted Server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
//! Authenticated Avro Value protection for application-held keys.

use std::{collections::BTreeMap, sync::OnceLock};

use apache_avro::{from_avro_datum, to_avro_datum, types::Value as Datum, Schema};
use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
use chacha20poly1305::{
    aead::{Aead, KeyInit, Payload},
    XChaCha20Poly1305, XNonce,
};
use zeroize::Zeroizing;

use crate::{
    decode_avro_value_blob, encode_avro_value, AvroValue, PayloadEnvelope, StrictAvroDatumReader,
};

use crate::payload_protection::Boundary;

use crate::client_payload::PROTECTED_VALUE_V1_HEADER as HEADER;
const PLAIN_HEADER: [u8; 10] = [0xc3, 0x01, 0xe2, 0xa3, 0x3d, 0xff, 0x55, 0x80, 0x22, 0x37];
const VERSION: i32 = 1;
const ALGORITHM: &str = "xchacha20poly1305-ietf";
const NONCE_LEN: usize = 24;
const TAG_LEN: usize = 16;

/// Scope established by the application or protocol admission.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ProtectionContext<'a> {
    namespace: &'a str,
    namespace_len: u32,
    boundary: Boundary,
}

impl<'a> ProtectionContext<'a> {
    pub fn new(namespace: &'a str, boundary: Boundary) -> Result<Self, ProtectionError> {
        let namespace_len =
            u32::try_from(namespace.len()).map_err(|_| ProtectionError::InvalidContext)?;
        if namespace_len == 0 {
            return Err(ProtectionError::InvalidContext);
        }
        Ok(Self {
            namespace,
            namespace_len,
            boundary,
        })
    }

    fn aad(self, key_id: &str) -> Vec<u8> {
        let mut aad = b"durable-workflow.payload-protection\0\x01".to_vec();
        for (len, text) in [
            (ALGORITHM.len() as u32, ALGORITHM),
            (key_id.len() as u32, key_id),
            (self.namespace_len, self.namespace),
            (
                self.boundary.wire_name().len() as u32,
                self.boundary.wire_name(),
            ),
        ] {
            aad.extend_from_slice(&len.to_be_bytes());
            aad.extend_from_slice(text.as_bytes());
        }
        aad
    }
}

/// Stable failures contain no application values, key IDs, or raw wire data.
#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
#[non_exhaustive]
pub enum ProtectionError {
    #[error("payload_envelope_unsupported")]
    EnvelopeUnsupported,
    #[error("payload_key_unavailable")]
    KeyUnavailable,
    #[error("payload_authentication_failed")]
    AuthenticationFailed,
    #[error("payload_plaintext_invalid")]
    PlaintextInvalid,
    #[error("payload_protection_required")]
    ProtectionRequired,
    #[error("payload_protection_boundary_unsupported")]
    BoundaryUnsupported,
    #[error("payload_protection_invalid_prepared_command")]
    InvalidPreparedCommand,
    #[error("payload_protection_invalid_context")]
    InvalidContext,
    #[error("payload_protection_invalid_key_configuration")]
    InvalidKeyConfiguration,
    #[error("payload_protection_unavailable")]
    Unavailable,
}

/// A process-local keyring. A missing active key makes this configuration read-only.
pub struct PayloadProtection {
    keys: BTreeMap<String, XChaCha20Poly1305>,
    active_key_id: Option<String>,
    allow_plaintext: bool,
}

impl std::fmt::Debug for PayloadProtection {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PayloadProtection")
            .finish_non_exhaustive()
    }
}

impl PayloadProtection {
    pub fn new(
        keys: impl IntoIterator<Item = (String, [u8; 32])>,
        active_key_id: Option<String>,
    ) -> Result<Self, ProtectionError> {
        let mut ciphers = BTreeMap::new();
        for (id, key) in keys {
            let key = Zeroizing::new(key);
            if !valid_key_id(&id) || ciphers.contains_key(&id) {
                return Err(ProtectionError::InvalidKeyConfiguration);
            }
            let cipher = XChaCha20Poly1305::new_from_slice(key.as_ref())
                .map_err(|_| ProtectionError::InvalidKeyConfiguration)?;
            ciphers.insert(id, cipher);
        }
        if active_key_id
            .as_ref()
            .is_some_and(|id| !ciphers.contains_key(id))
        {
            return Err(ProtectionError::KeyUnavailable);
        }
        Ok(Self {
            keys: ciphers,
            active_key_id,
            allow_plaintext: false,
        })
    }

    /// Permit reads of historical plain Avro Value envelopes during migration.
    pub fn allow_plaintext_reads(mut self) -> Self {
        self.allow_plaintext = true;
        self
    }

    pub(crate) fn plaintext_reads_enabled(&self) -> bool {
        self.allow_plaintext
    }

    pub(crate) fn can_write(&self) -> bool {
        self.active_key_id.is_some()
    }

    /// Protect once at admission. Retain the returned envelope across retries.
    pub fn protect(
        &self,
        value: &AvroValue,
        context: ProtectionContext<'_>,
    ) -> Result<PayloadEnvelope, ProtectionError> {
        let key_id = self
            .active_key_id
            .as_deref()
            .ok_or(ProtectionError::KeyUnavailable)?;
        let mut nonce = [0; NONCE_LEN];
        getrandom::fill(&mut nonce).map_err(|_| ProtectionError::Unavailable)?;
        self.protect_with_nonce(value, context, key_id, nonce)
    }

    fn protect_with_nonce(
        &self,
        value: &AvroValue,
        context: ProtectionContext<'_>,
        key_id: &str,
        nonce: [u8; NONCE_LEN],
    ) -> Result<PayloadEnvelope, ProtectionError> {
        let cipher = self
            .keys
            .get(key_id)
            .ok_or(ProtectionError::KeyUnavailable)?;
        let blob = Zeroizing::new(
            encode_avro_value(value)
                .map_err(|_| ProtectionError::PlaintextInvalid)?
                .blob,
        );
        let plain = Zeroizing::new(
            BASE64
                .decode(blob.as_bytes())
                .map_err(|_| ProtectionError::PlaintextInvalid)?,
        );
        let ciphertext = cipher
            .encrypt(
                &XNonce::from(nonce),
                Payload {
                    msg: plain.as_slice(),
                    aad: &context.aad(key_id),
                },
            )
            .map_err(|_| ProtectionError::Unavailable)?;
        let datum = Datum::Record(vec![
            ("dw_protected".into(), Datum::Int(VERSION)),
            ("alg".into(), Datum::String(ALGORITHM.into())),
            ("key_id".into(), Datum::String(key_id.into())),
            ("nonce".into(), Datum::Bytes(nonce.to_vec())),
            ("ciphertext".into(), Datum::Bytes(ciphertext)),
        ]);
        let mut wire = HEADER.to_vec();
        let mut body = to_avro_datum(schema()?, datum).map_err(|_| ProtectionError::Unavailable)?;
        wire.append(&mut body);
        Ok(PayloadEnvelope {
            codec: "avro".into(),
            blob: BASE64.encode(wire),
        })
    }

    pub fn open(
        &self,
        envelope: &PayloadEnvelope,
        context: ProtectionContext<'_>,
    ) -> Result<AvroValue, ProtectionError> {
        self.open_with_policy(envelope, context, self.allow_plaintext)
    }

    pub(crate) fn open_strict(
        &self,
        envelope: &PayloadEnvelope,
        context: ProtectionContext<'_>,
    ) -> Result<AvroValue, ProtectionError> {
        self.open_with_policy(envelope, context, false)
    }

    fn open_with_policy(
        &self,
        envelope: &PayloadEnvelope,
        context: ProtectionContext<'_>,
        allow_plaintext: bool,
    ) -> Result<AvroValue, ProtectionError> {
        if envelope.codec != "avro" {
            return Err(ProtectionError::EnvelopeUnsupported);
        }
        let wire = Zeroizing::new(
            BASE64
                .decode(envelope.blob.as_bytes())
                .map_err(|_| ProtectionError::EnvelopeUnsupported)?,
        );
        if wire.starts_with(&PLAIN_HEADER) {
            if !allow_plaintext {
                return Err(ProtectionError::ProtectionRequired);
            }
            return decode_avro_value_blob(&envelope.blob)
                .map_err(|_| ProtectionError::PlaintextInvalid);
        }
        let body = wire
            .strip_prefix(&HEADER)
            .ok_or(ProtectionError::EnvelopeUnsupported)?;
        let mut reader = StrictAvroDatumReader::new(body);
        let datum = from_avro_datum(schema()?, &mut reader, None)
            .map_err(|_| ProtectionError::EnvelopeUnsupported)?;
        if reader.truncated || reader.remaining() != 0 {
            return Err(ProtectionError::EnvelopeUnsupported);
        }
        let Datum::Record(fields) = datum else {
            return Err(ProtectionError::EnvelopeUnsupported);
        };
        let [(_, Datum::Int(VERSION)), (_, Datum::String(alg)), (_, Datum::String(key_id)), (_, Datum::Bytes(nonce)), (_, Datum::Bytes(ciphertext))] =
            fields.as_slice()
        else {
            return Err(ProtectionError::EnvelopeUnsupported);
        };
        let nonce = <[u8; NONCE_LEN]>::try_from(nonce.as_slice())
            .map_err(|_| ProtectionError::EnvelopeUnsupported)?;
        if alg != ALGORITHM || !valid_key_id(key_id) || ciphertext.len() < TAG_LEN {
            return Err(ProtectionError::EnvelopeUnsupported);
        }
        let cipher = self
            .keys
            .get(key_id)
            .ok_or(ProtectionError::KeyUnavailable)?;
        let plain = Zeroizing::new(
            cipher
                .decrypt(
                    &XNonce::from(nonce),
                    Payload {
                        msg: ciphertext,
                        aad: &context.aad(key_id),
                    },
                )
                .map_err(|_| ProtectionError::AuthenticationFailed)?,
        );
        if !plain.starts_with(&PLAIN_HEADER) {
            return Err(ProtectionError::PlaintextInvalid);
        }
        let encoded = Zeroizing::new(BASE64.encode(plain.as_slice()));
        decode_avro_value_blob(&encoded).map_err(|_| ProtectionError::PlaintextInvalid)
    }
}

fn schema() -> Result<&'static Schema, ProtectionError> {
    static SCHEMA: OnceLock<Option<Schema>> = OnceLock::new();
    SCHEMA
        .get_or_init(|| Schema::parse_str(include_str!("../schema/protected-value-v1.avsc")).ok())
        .as_ref()
        .ok_or(ProtectionError::Unavailable)
}

fn valid_key_id(id: &str) -> bool {
    (1..=128).contains(&id.len())
        && id
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || b"._:-".contains(&byte))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::Value;

    fn unhex<const N: usize>(text: &str) -> [u8; N] {
        assert_eq!(text.len(), N * 2);
        std::array::from_fn(|index| {
            u8::from_str_radix(&text[index * 2..index * 2 + 2], 16).unwrap()
        })
    }

    #[test]
    fn accepted_vector_has_exact_aad_wire_and_plaintext() {
        let vectors: Value =
            serde_json::from_str(include_str!("../schema/protected-value-v1-vectors.json"))
                .unwrap();
        let vector = &vectors["vectors"][0];
        let key_id = vector["key_id"].as_str().unwrap();
        let key = unhex(vector["key_hex"].as_str().unwrap());
        let nonce = unhex(vector["nonce_hex"].as_str().unwrap());
        let expected = AvroValue::from_serialize(&vector["value_json"]).unwrap();
        let scope = ProtectionContext::new(
            vector["namespace"].as_str().unwrap(),
            Boundary::WorkflowInput,
        )
        .unwrap();
        let aad = scope.aad(key_id);
        let expected_aad = vector["aad_hex"].as_str().unwrap();
        assert_eq!(aad.len() * 2, expected_aad.len());
        for (index, value) in aad.iter().enumerate() {
            assert_eq!(
                *value,
                u8::from_str_radix(&expected_aad[index * 2..index * 2 + 2], 16).unwrap()
            );
        }
        let protection =
            PayloadProtection::new([(key_id.to_string(), key)], Some(key_id.to_string())).unwrap();
        let encrypted = protection
            .protect_with_nonce(&expected, scope, key_id, nonce)
            .unwrap();
        assert_eq!(
            encrypted.blob,
            vector["outer_single_object_base64"].as_str().unwrap()
        );
        assert_eq!(protection.open(&encrypted, scope).unwrap(), expected);
        let wrong_boundary = ProtectionContext::new(
            vector["namespace"].as_str().unwrap(),
            Boundary::ActivityInput,
        )
        .unwrap();
        assert_eq!(
            protection.open(&encrypted, wrong_boundary),
            Err(ProtectionError::AuthenticationFailed)
        );
        let wrong_namespace = ProtectionContext::new("tenant-b", Boundary::WorkflowInput).unwrap();
        assert_eq!(
            protection.open(&encrypted, wrong_namespace),
            Err(ProtectionError::AuthenticationFailed)
        );
        let missing = PayloadProtection::new([], None).unwrap();
        assert_eq!(
            missing.open(&encrypted, scope),
            Err(ProtectionError::KeyUnavailable)
        );
    }

    #[test]
    fn rotation_and_migration_reads_never_fall_back_from_a_protected_frame() {
        let scope = ProtectionContext::new("orders", Boundary::SignalInput).unwrap();
        let value = AvroValue::Array(vec![
            AvroValue::Long(i64::MAX),
            AvroValue::Null,
            AvroValue::String("λ".into()),
        ]);
        let original =
            PayloadProtection::new([("old".into(), [7; 32])], Some("old".into())).unwrap();
        let saved = original.protect(&value, scope).unwrap();
        let rotation = PayloadProtection::new(
            [("old".into(), [7; 32]), ("new".into(), [8; 32])],
            Some("new".into()),
        )
        .unwrap();
        assert_eq!(rotation.open(&saved, scope).unwrap(), value);
        let fresh = rotation.protect(&value, scope).unwrap();
        assert_ne!(fresh.blob, rotation.protect(&value, scope).unwrap().blob);

        let plain = encode_avro_value(&value).unwrap();
        assert_eq!(
            rotation.open(&plain, scope),
            Err(ProtectionError::ProtectionRequired)
        );
        let reader = PayloadProtection::new([("new".into(), [8; 32])], None)
            .unwrap()
            .allow_plaintext_reads();
        assert_eq!(reader.open(&plain, scope).unwrap(), value);
        assert_eq!(reader.open(&fresh, scope).unwrap(), value);
        assert_eq!(
            reader.open(&saved, scope),
            Err(ProtectionError::KeyUnavailable)
        );
        assert!(matches!(
            reader.protect(&value, scope),
            Err(ProtectionError::KeyUnavailable)
        ));
        let mut tampered = BASE64.decode(&fresh.blob).unwrap();
        *tampered.last_mut().unwrap() ^= 1;
        let tampered = PayloadEnvelope {
            codec: "avro".into(),
            blob: BASE64.encode(tampered),
        };
        assert_eq!(
            reader.open(&tampered, scope),
            Err(ProtectionError::AuthenticationFailed)
        );
    }
}