Skip to content
Durable Workflowrust

durable_workflow/
client_payload.rs

1use crate::{
2    decode_wire_avro_value, decode_wire_value, encode_typed_envelope, AvroValue, Client, Result,
3    DEFAULT_CODEC,
4};
5use serde_json::Value;
6
7#[cfg(feature = "payload-protection")]
8use crate::payload_protection::{ProtectionContext, ProtectionError};
9#[cfg(feature = "payload-protection")]
10use crate::{PayloadEnvelope, WorkflowDescription};
11
12pub(crate) const PROTECTED_VALUE_V1_HEADER: [u8; 10] =
13    [0xc3, 0x01, 0x0b, 0xa7, 0x0c, 0x3f, 0xd6, 0xc3, 0x11, 0xca];
14
15/// The logical payload boundary authenticated with the owning namespace.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum Boundary {
18    WorkflowInput,
19    WorkflowResult,
20    ActivityInput,
21    ActivityResult,
22    SignalInput,
23    UpdateInput,
24    UpdateResult,
25    QueryInput,
26    QueryResult,
27    SideEffectResult,
28}
29
30#[cfg(feature = "payload-protection")]
31impl Boundary {
32    pub(crate) fn wire_name(self) -> &'static str {
33        match self {
34            Self::WorkflowInput => "workflow_input",
35            Self::WorkflowResult => "workflow_result",
36            Self::ActivityInput => "activity_input",
37            Self::ActivityResult => "activity_result",
38            Self::SignalInput => "signal_input",
39            Self::UpdateInput => "update_input",
40            Self::UpdateResult => "update_result",
41            Self::QueryInput => "query_input",
42            Self::QueryResult => "query_result",
43            Self::SideEffectResult => "side_effect_result",
44        }
45    }
46}
47
48impl Client {
49    pub(super) fn encode_client_payload(
50        &self,
51        value: &AvroValue,
52        _boundary: Boundary,
53    ) -> Result<Value> {
54        #[cfg(feature = "payload-protection")]
55        if let Some(protection) = &self.payload_protection {
56            let context = ProtectionContext::new(&self.namespace, _boundary)?;
57            return Ok(serde_json::to_value(protection.protect(value, context)?)?);
58        }
59        encode_typed_envelope(value, DEFAULT_CODEC)
60    }
61
62    pub(super) fn decode_client_payload(
63        &self,
64        value: &Value,
65        _boundary: Boundary,
66    ) -> Result<AvroValue> {
67        #[cfg(feature = "payload-protection")]
68        if let Some(protection) = &self.payload_protection {
69            let context = ProtectionContext::new(&self.namespace, _boundary)?;
70            let envelope = exact_inline(value)?;
71            return Ok(protection.open(&envelope, context)?);
72        }
73        decode_wire_avro_value(value, DEFAULT_CODEC)
74    }
75
76    pub(super) fn decode_client_json(&self, value: &Value, boundary: Boundary) -> Result<Value> {
77        if self.protection_enabled() {
78            return self.decode_client_payload(value, boundary)?.into_json();
79        }
80        decode_wire_value(value, DEFAULT_CODEC)
81    }
82
83    pub(super) fn protection_enabled(&self) -> bool {
84        #[cfg(feature = "payload-protection")]
85        {
86            self.payload_protection.is_some()
87        }
88        #[cfg(not(feature = "payload-protection"))]
89        {
90            false
91        }
92    }
93
94    // Operations with no ProtectedValue boundary must fail before HTTP.
95    pub(super) fn refuse_unsupported_protected_boundary(&self) -> Result<()> {
96        #[cfg(feature = "payload-protection")]
97        if self.protection_enabled() {
98            return Err(ProtectionError::BoundaryUnsupported.into());
99        }
100        Ok(())
101    }
102
103    pub(super) fn assert_protected_response_namespace(
104        &self,
105        _namespace: Option<&Value>,
106    ) -> Result<()> {
107        #[cfg(feature = "payload-protection")]
108        if self.protection_enabled()
109            && _namespace.is_some_and(|value| value.as_str() != Some(&self.namespace))
110        {
111            return Err(ProtectionError::AuthenticationFailed.into());
112        }
113        Ok(())
114    }
115
116    pub(super) fn assert_protected_result_receipt(
117        &self,
118        _receipt: &Value,
119        _require_envelope: bool,
120    ) -> Result<()> {
121        #[cfg(feature = "payload-protection")]
122        if self.protection_enabled() {
123            self.assert_protected_response_namespace(_receipt.get("namespace"))?;
124            let envelope = _receipt.get("result_envelope");
125            let has_plain_projection = _receipt
126                .get("result")
127                .into_iter()
128                .chain(_receipt.pointer("/control_plane/result"))
129                .any(|value| !safe_projection(value));
130            if (_require_envelope && !envelope.is_some_and(Value::is_object))
131                || (has_plain_projection && !self.is_migration_envelope(envelope))
132            {
133                return Err(ProtectionError::ProtectionRequired.into());
134            }
135        }
136        Ok(())
137    }
138
139    pub(super) fn decode_workflow_description(
140        &self,
141        description: &mut crate::WorkflowDescription,
142    ) -> Result<()> {
143        #[cfg(feature = "payload-protection")]
144        if self.protection_enabled() {
145            return self.decode_protected_workflow_description(description);
146        }
147        description.decode_payloads()
148    }
149
150    #[cfg(feature = "payload-protection")]
151    fn decode_protected_workflow_description(
152        &self,
153        description: &mut WorkflowDescription,
154    ) -> Result<()> {
155        self.assert_protected_response_namespace(description.raw.get("namespace"))?;
156        let input = description
157            .raw
158            .get("input_envelope")
159            .filter(|value| !value.is_null());
160        let output = description
161            .output_envelope
162            .as_ref()
163            .filter(|value| !value.is_null());
164        let input_preview = description
165            .raw
166            .get("input")
167            .filter(|value| !value.is_null());
168        if (input_preview.is_some_and(|value| !safe_projection(value))
169            && !self.is_migration_envelope(input))
170            || (description
171                .output
172                .as_ref()
173                .is_some_and(|value| !safe_projection(value))
174                && !self.is_migration_envelope(output))
175        {
176            return Err(ProtectionError::ProtectionRequired.into());
177        }
178        if let Some(input) = input {
179            self.decode_client_payload(input, Boundary::WorkflowInput)?;
180        } else if input_preview.is_some() {
181            return Err(ProtectionError::ProtectionRequired.into());
182        }
183        if let Some(output) = output {
184            let value = self.decode_client_payload(output, Boundary::WorkflowResult)?;
185            description.output = Some(value.clone().into_json()?);
186            description.output_avro_value = Some(value);
187        } else if description.is_completed() {
188            return Err(ProtectionError::ProtectionRequired.into());
189        }
190        Ok(())
191    }
192
193    #[cfg(feature = "payload-protection")]
194    fn is_migration_envelope(&self, value: Option<&Value>) -> bool {
195        self.payload_protection
196            .as_ref()
197            .is_some_and(|protection| protection.plaintext_reads_enabled())
198            && value
199                .and_then(|value| exact_inline(value).ok())
200                .is_some_and(|envelope| crate::decode_avro_value(&envelope).is_ok())
201    }
202}
203
204#[cfg(feature = "payload-protection")]
205pub(super) fn exact_inline(value: &Value) -> Result<PayloadEnvelope> {
206    if !value.as_object().is_some_and(|fields| fields.len() == 2)
207        || value.get("codec").and_then(Value::as_str) != Some(DEFAULT_CODEC)
208    {
209        return Err(ProtectionError::EnvelopeUnsupported.into());
210    }
211    let blob = value
212        .get("blob")
213        .and_then(Value::as_str)
214        .ok_or(ProtectionError::EnvelopeUnsupported)?;
215    Ok(PayloadEnvelope {
216        codec: DEFAULT_CODEC.to_owned(),
217        blob: blob.to_owned(),
218    })
219}
220
221#[cfg(feature = "payload-protection")]
222fn safe_projection(value: &Value) -> bool {
223    value.is_null()
224        || (value.as_object().is_some_and(|fields| fields.len() == 2)
225            && value["$type"] == "protected"
226            && value["version"] == 1)
227}