1use std::{collections::BTreeMap, sync::OnceLock};
4
5use apache_avro::{from_avro_datum, to_avro_datum, types::Value as Datum, Schema};
6use base64::{engine::general_purpose::STANDARD as BASE64, Engine as _};
7use chacha20poly1305::{
8 aead::{Aead, KeyInit, Payload},
9 XChaCha20Poly1305, XNonce,
10};
11use zeroize::Zeroizing;
12
13use crate::{
14 decode_avro_value_blob, encode_avro_value, AvroValue, PayloadEnvelope, StrictAvroDatumReader,
15};
16
17use crate::payload_protection::Boundary;
18
19use crate::client_payload::PROTECTED_VALUE_V1_HEADER as HEADER;
20const PLAIN_HEADER: [u8; 10] = [0xc3, 0x01, 0xe2, 0xa3, 0x3d, 0xff, 0x55, 0x80, 0x22, 0x37];
21const VERSION: i32 = 1;
22const ALGORITHM: &str = "xchacha20poly1305-ietf";
23const NONCE_LEN: usize = 24;
24const TAG_LEN: usize = 16;
25
26#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub struct ProtectionContext<'a> {
29 namespace: &'a str,
30 namespace_len: u32,
31 boundary: Boundary,
32}
33
34impl<'a> ProtectionContext<'a> {
35 pub fn new(namespace: &'a str, boundary: Boundary) -> Result<Self, ProtectionError> {
36 let namespace_len =
37 u32::try_from(namespace.len()).map_err(|_| ProtectionError::InvalidContext)?;
38 if namespace_len == 0 {
39 return Err(ProtectionError::InvalidContext);
40 }
41 Ok(Self {
42 namespace,
43 namespace_len,
44 boundary,
45 })
46 }
47
48 fn aad(self, key_id: &str) -> Vec<u8> {
49 let mut aad = b"durable-workflow.payload-protection\0\x01".to_vec();
50 for (len, text) in [
51 (ALGORITHM.len() as u32, ALGORITHM),
52 (key_id.len() as u32, key_id),
53 (self.namespace_len, self.namespace),
54 (
55 self.boundary.wire_name().len() as u32,
56 self.boundary.wire_name(),
57 ),
58 ] {
59 aad.extend_from_slice(&len.to_be_bytes());
60 aad.extend_from_slice(text.as_bytes());
61 }
62 aad
63 }
64}
65
66#[derive(Clone, Copy, Debug, thiserror::Error, PartialEq, Eq)]
68#[non_exhaustive]
69pub enum ProtectionError {
70 #[error("payload_envelope_unsupported")]
71 EnvelopeUnsupported,
72 #[error("payload_key_unavailable")]
73 KeyUnavailable,
74 #[error("payload_authentication_failed")]
75 AuthenticationFailed,
76 #[error("payload_plaintext_invalid")]
77 PlaintextInvalid,
78 #[error("payload_protection_required")]
79 ProtectionRequired,
80 #[error("payload_protection_boundary_unsupported")]
81 BoundaryUnsupported,
82 #[error("payload_protection_invalid_prepared_command")]
83 InvalidPreparedCommand,
84 #[error("payload_protection_invalid_context")]
85 InvalidContext,
86 #[error("payload_protection_invalid_key_configuration")]
87 InvalidKeyConfiguration,
88 #[error("payload_protection_unavailable")]
89 Unavailable,
90}
91
92pub struct PayloadProtection {
94 keys: BTreeMap<String, XChaCha20Poly1305>,
95 active_key_id: Option<String>,
96 allow_plaintext: bool,
97}
98
99impl std::fmt::Debug for PayloadProtection {
100 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101 formatter
102 .debug_struct("PayloadProtection")
103 .finish_non_exhaustive()
104 }
105}
106
107impl PayloadProtection {
108 pub fn new(
109 keys: impl IntoIterator<Item = (String, [u8; 32])>,
110 active_key_id: Option<String>,
111 ) -> Result<Self, ProtectionError> {
112 let mut ciphers = BTreeMap::new();
113 for (id, key) in keys {
114 let key = Zeroizing::new(key);
115 if !valid_key_id(&id) || ciphers.contains_key(&id) {
116 return Err(ProtectionError::InvalidKeyConfiguration);
117 }
118 let cipher = XChaCha20Poly1305::new_from_slice(key.as_ref())
119 .map_err(|_| ProtectionError::InvalidKeyConfiguration)?;
120 ciphers.insert(id, cipher);
121 }
122 if active_key_id
123 .as_ref()
124 .is_some_and(|id| !ciphers.contains_key(id))
125 {
126 return Err(ProtectionError::KeyUnavailable);
127 }
128 Ok(Self {
129 keys: ciphers,
130 active_key_id,
131 allow_plaintext: false,
132 })
133 }
134
135 pub fn allow_plaintext_reads(mut self) -> Self {
137 self.allow_plaintext = true;
138 self
139 }
140
141 pub(crate) fn plaintext_reads_enabled(&self) -> bool {
142 self.allow_plaintext
143 }
144
145 pub(crate) fn can_write(&self) -> bool {
146 self.active_key_id.is_some()
147 }
148
149 pub fn protect(
151 &self,
152 value: &AvroValue,
153 context: ProtectionContext<'_>,
154 ) -> Result<PayloadEnvelope, ProtectionError> {
155 let key_id = self
156 .active_key_id
157 .as_deref()
158 .ok_or(ProtectionError::KeyUnavailable)?;
159 let mut nonce = [0; NONCE_LEN];
160 getrandom::fill(&mut nonce).map_err(|_| ProtectionError::Unavailable)?;
161 self.protect_with_nonce(value, context, key_id, nonce)
162 }
163
164 fn protect_with_nonce(
165 &self,
166 value: &AvroValue,
167 context: ProtectionContext<'_>,
168 key_id: &str,
169 nonce: [u8; NONCE_LEN],
170 ) -> Result<PayloadEnvelope, ProtectionError> {
171 let cipher = self
172 .keys
173 .get(key_id)
174 .ok_or(ProtectionError::KeyUnavailable)?;
175 let blob = Zeroizing::new(
176 encode_avro_value(value)
177 .map_err(|_| ProtectionError::PlaintextInvalid)?
178 .blob,
179 );
180 let plain = Zeroizing::new(
181 BASE64
182 .decode(blob.as_bytes())
183 .map_err(|_| ProtectionError::PlaintextInvalid)?,
184 );
185 let ciphertext = cipher
186 .encrypt(
187 &XNonce::from(nonce),
188 Payload {
189 msg: plain.as_slice(),
190 aad: &context.aad(key_id),
191 },
192 )
193 .map_err(|_| ProtectionError::Unavailable)?;
194 let datum = Datum::Record(vec![
195 ("dw_protected".into(), Datum::Int(VERSION)),
196 ("alg".into(), Datum::String(ALGORITHM.into())),
197 ("key_id".into(), Datum::String(key_id.into())),
198 ("nonce".into(), Datum::Bytes(nonce.to_vec())),
199 ("ciphertext".into(), Datum::Bytes(ciphertext)),
200 ]);
201 let mut wire = HEADER.to_vec();
202 let mut body = to_avro_datum(schema()?, datum).map_err(|_| ProtectionError::Unavailable)?;
203 wire.append(&mut body);
204 Ok(PayloadEnvelope {
205 codec: "avro".into(),
206 blob: BASE64.encode(wire),
207 })
208 }
209
210 pub fn open(
211 &self,
212 envelope: &PayloadEnvelope,
213 context: ProtectionContext<'_>,
214 ) -> Result<AvroValue, ProtectionError> {
215 self.open_with_policy(envelope, context, self.allow_plaintext)
216 }
217
218 pub(crate) fn open_strict(
219 &self,
220 envelope: &PayloadEnvelope,
221 context: ProtectionContext<'_>,
222 ) -> Result<AvroValue, ProtectionError> {
223 self.open_with_policy(envelope, context, false)
224 }
225
226 fn open_with_policy(
227 &self,
228 envelope: &PayloadEnvelope,
229 context: ProtectionContext<'_>,
230 allow_plaintext: bool,
231 ) -> Result<AvroValue, ProtectionError> {
232 if envelope.codec != "avro" {
233 return Err(ProtectionError::EnvelopeUnsupported);
234 }
235 let wire = Zeroizing::new(
236 BASE64
237 .decode(envelope.blob.as_bytes())
238 .map_err(|_| ProtectionError::EnvelopeUnsupported)?,
239 );
240 if wire.starts_with(&PLAIN_HEADER) {
241 if !allow_plaintext {
242 return Err(ProtectionError::ProtectionRequired);
243 }
244 return decode_avro_value_blob(&envelope.blob)
245 .map_err(|_| ProtectionError::PlaintextInvalid);
246 }
247 let body = wire
248 .strip_prefix(&HEADER)
249 .ok_or(ProtectionError::EnvelopeUnsupported)?;
250 let mut reader = StrictAvroDatumReader::new(body);
251 let datum = from_avro_datum(schema()?, &mut reader, None)
252 .map_err(|_| ProtectionError::EnvelopeUnsupported)?;
253 if reader.truncated || reader.remaining() != 0 {
254 return Err(ProtectionError::EnvelopeUnsupported);
255 }
256 let Datum::Record(fields) = datum else {
257 return Err(ProtectionError::EnvelopeUnsupported);
258 };
259 let [(_, Datum::Int(VERSION)), (_, Datum::String(alg)), (_, Datum::String(key_id)), (_, Datum::Bytes(nonce)), (_, Datum::Bytes(ciphertext))] =
260 fields.as_slice()
261 else {
262 return Err(ProtectionError::EnvelopeUnsupported);
263 };
264 let nonce = <[u8; NONCE_LEN]>::try_from(nonce.as_slice())
265 .map_err(|_| ProtectionError::EnvelopeUnsupported)?;
266 if alg != ALGORITHM || !valid_key_id(key_id) || ciphertext.len() < TAG_LEN {
267 return Err(ProtectionError::EnvelopeUnsupported);
268 }
269 let cipher = self
270 .keys
271 .get(key_id)
272 .ok_or(ProtectionError::KeyUnavailable)?;
273 let plain = Zeroizing::new(
274 cipher
275 .decrypt(
276 &XNonce::from(nonce),
277 Payload {
278 msg: ciphertext,
279 aad: &context.aad(key_id),
280 },
281 )
282 .map_err(|_| ProtectionError::AuthenticationFailed)?,
283 );
284 if !plain.starts_with(&PLAIN_HEADER) {
285 return Err(ProtectionError::PlaintextInvalid);
286 }
287 let encoded = Zeroizing::new(BASE64.encode(plain.as_slice()));
288 decode_avro_value_blob(&encoded).map_err(|_| ProtectionError::PlaintextInvalid)
289 }
290}
291
292fn schema() -> Result<&'static Schema, ProtectionError> {
293 static SCHEMA: OnceLock<Option<Schema>> = OnceLock::new();
294 SCHEMA
295 .get_or_init(|| Schema::parse_str(include_str!("../schema/protected-value-v1.avsc")).ok())
296 .as_ref()
297 .ok_or(ProtectionError::Unavailable)
298}
299
300fn valid_key_id(id: &str) -> bool {
301 (1..=128).contains(&id.len())
302 && id
303 .bytes()
304 .all(|byte| byte.is_ascii_alphanumeric() || b"._:-".contains(&byte))
305}
306
307#[cfg(test)]
308mod tests {
309 use super::*;
310 use serde_json::Value;
311
312 fn unhex<const N: usize>(text: &str) -> [u8; N] {
313 assert_eq!(text.len(), N * 2);
314 std::array::from_fn(|index| {
315 u8::from_str_radix(&text[index * 2..index * 2 + 2], 16).unwrap()
316 })
317 }
318
319 #[test]
320 fn accepted_vector_has_exact_aad_wire_and_plaintext() {
321 let vectors: Value =
322 serde_json::from_str(include_str!("../schema/protected-value-v1-vectors.json"))
323 .unwrap();
324 let vector = &vectors["vectors"][0];
325 let key_id = vector["key_id"].as_str().unwrap();
326 let key = unhex(vector["key_hex"].as_str().unwrap());
327 let nonce = unhex(vector["nonce_hex"].as_str().unwrap());
328 let expected = AvroValue::from_serialize(&vector["value_json"]).unwrap();
329 let scope = ProtectionContext::new(
330 vector["namespace"].as_str().unwrap(),
331 Boundary::WorkflowInput,
332 )
333 .unwrap();
334 let aad = scope.aad(key_id);
335 let expected_aad = vector["aad_hex"].as_str().unwrap();
336 assert_eq!(aad.len() * 2, expected_aad.len());
337 for (index, value) in aad.iter().enumerate() {
338 assert_eq!(
339 *value,
340 u8::from_str_radix(&expected_aad[index * 2..index * 2 + 2], 16).unwrap()
341 );
342 }
343 let protection =
344 PayloadProtection::new([(key_id.to_string(), key)], Some(key_id.to_string())).unwrap();
345 let encrypted = protection
346 .protect_with_nonce(&expected, scope, key_id, nonce)
347 .unwrap();
348 assert_eq!(
349 encrypted.blob,
350 vector["outer_single_object_base64"].as_str().unwrap()
351 );
352 assert_eq!(protection.open(&encrypted, scope).unwrap(), expected);
353 let wrong_boundary = ProtectionContext::new(
354 vector["namespace"].as_str().unwrap(),
355 Boundary::ActivityInput,
356 )
357 .unwrap();
358 assert_eq!(
359 protection.open(&encrypted, wrong_boundary),
360 Err(ProtectionError::AuthenticationFailed)
361 );
362 let wrong_namespace = ProtectionContext::new("tenant-b", Boundary::WorkflowInput).unwrap();
363 assert_eq!(
364 protection.open(&encrypted, wrong_namespace),
365 Err(ProtectionError::AuthenticationFailed)
366 );
367 let missing = PayloadProtection::new([], None).unwrap();
368 assert_eq!(
369 missing.open(&encrypted, scope),
370 Err(ProtectionError::KeyUnavailable)
371 );
372 }
373
374 #[test]
375 fn rotation_and_migration_reads_never_fall_back_from_a_protected_frame() {
376 let scope = ProtectionContext::new("orders", Boundary::SignalInput).unwrap();
377 let value = AvroValue::Array(vec![
378 AvroValue::Long(i64::MAX),
379 AvroValue::Null,
380 AvroValue::String("λ".into()),
381 ]);
382 let original =
383 PayloadProtection::new([("old".into(), [7; 32])], Some("old".into())).unwrap();
384 let saved = original.protect(&value, scope).unwrap();
385 let rotation = PayloadProtection::new(
386 [("old".into(), [7; 32]), ("new".into(), [8; 32])],
387 Some("new".into()),
388 )
389 .unwrap();
390 assert_eq!(rotation.open(&saved, scope).unwrap(), value);
391 let fresh = rotation.protect(&value, scope).unwrap();
392 assert_ne!(fresh.blob, rotation.protect(&value, scope).unwrap().blob);
393
394 let plain = encode_avro_value(&value).unwrap();
395 assert_eq!(
396 rotation.open(&plain, scope),
397 Err(ProtectionError::ProtectionRequired)
398 );
399 let reader = PayloadProtection::new([("new".into(), [8; 32])], None)
400 .unwrap()
401 .allow_plaintext_reads();
402 assert_eq!(reader.open(&plain, scope).unwrap(), value);
403 assert_eq!(reader.open(&fresh, scope).unwrap(), value);
404 assert_eq!(
405 reader.open(&saved, scope),
406 Err(ProtectionError::KeyUnavailable)
407 );
408 assert!(matches!(
409 reader.protect(&value, scope),
410 Err(ProtectionError::KeyUnavailable)
411 ));
412 let mut tampered = BASE64.decode(&fresh.blob).unwrap();
413 *tampered.last_mut().unwrap() ^= 1;
414 let tampered = PayloadEnvelope {
415 codec: "avro".into(),
416 blob: BASE64.encode(tampered),
417 };
418 assert_eq!(
419 reader.open(&tampered, scope),
420 Err(ProtectionError::AuthenticationFailed)
421 );
422 }
423}