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;
#[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
}
}
#[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,
}
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,
})
}
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()
}
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)
);
}
}