use crate::{
decode_wire_avro_value, encode_typed_envelope, validate_payload_codec, ActivityTask, AvroValue,
Boundary, Client, HistoryEvent, QueryTask, Result, Worker, WorkflowTask, DEFAULT_CODEC,
};
use serde_json::Value;
#[cfg(feature = "payload-protection")]
use crate::{
argument_vector_contracts,
client_payload::{exact_inline, PROTECTED_VALUE_V1_HEADER},
payload_protection::{ProtectionContext, ProtectionError},
Error, BASE64,
};
#[cfg(feature = "payload-protection")]
use base64::Engine as _;
pub(super) const PROTECTED_QUERY_TASKS: &str = "protected_query_tasks_v1";
pub(super) const PROTECTED_UPDATE_TASKS: &str = "protected_update_tasks_v1";
pub(super) const PROTECTED_SIGNAL_VALIDATION: &str = "protected_signal_validation_v1";
impl Worker {
pub(super) fn check_protected_worker_configuration(&self) -> Result<()> {
#[cfg(feature = "payload-protection")]
if let Some(protection) = &self.client.payload_protection {
if !protection.can_write() {
return Err(ProtectionError::KeyUnavailable.into());
}
if self.client.local_activities_enabled
|| self.client.worker_sessions_enabled
|| self.cooperative_cancellation_enabled
|| self.nexus_cooperative_cancellation_enabled
{
return Err(ProtectionError::BoundaryUnsupported.into());
}
}
Ok(())
}
pub(super) fn worker_needs_update_validation(&self) -> bool {
self.has_update_validators()
|| (self.client.protection_enabled() && !self.updates.is_empty())
|| self.worker_uses_protected_signals()
}
pub(super) fn worker_uses_protected_signals(&self) -> bool {
self.client.protection_enabled() && self.signals.values().any(|names| !names.is_empty())
}
pub(super) fn check_protected_signal_offer(&self, _task: &Value) -> Result<()> {
#[cfg(feature = "payload-protection")]
{
let name = _task["signal_name"].as_str().unwrap_or_default();
let workflow_type = _task["workflow_type"].as_str().unwrap_or_default();
let offer = &_task["protected_signal"];
if !self.client.protection_enabled()
|| _task["namespace"].as_str() != Some(self.client.namespace.as_str())
|| _task["lease_owner"].as_str() != Some(self.worker_id.as_str())
|| _task["payload_codec"] != DEFAULT_CODEC
|| _task.get("protected_update").is_some()
|| _task.get("update_arguments").is_some()
|| !offer["contract"].is_object()
|| !self
.signals
.get(workflow_type)
.is_some_and(|names| names.iter().any(|declared| declared == name))
{
return Err(ProtectionError::AuthenticationFailed.into());
}
self.client.check_protected_command(
_task.get("signal_arguments"),
offer,
name,
Boundary::SignalInput,
)
}
#[cfg(not(feature = "payload-protection"))]
{
Err(crate::Error::UpdateValidationUnavailable(
"protected signal validation requires payload protection".into(),
))
}
}
pub(super) fn check_protected_query_offer(&self, _task: &Value) -> Result<()> {
#[cfg(feature = "payload-protection")]
if self.client.protection_enabled() {
let input = _task.get("query_arguments");
let Some(protected) = _task.get("protected_query") else {
return if input.is_some_and(is_protected_value) {
Err(ProtectionError::EnvelopeUnsupported.into())
} else {
Ok(())
};
};
self.client.check_protected_command(
input,
protected,
_task["query_name"].as_str().unwrap_or_default(),
Boundary::QueryInput,
)?;
let expected_build = protected.get("build").and_then(Value::as_str);
let expected_fingerprint = protected.get("fingerprint").and_then(Value::as_str);
if expected_build
.is_some_and(|build| self.client.worker_build_id.as_deref() != Some(build))
|| expected_fingerprint.is_some_and(|fingerprint| {
self.workflows
.get(_task["workflow_type"].as_str().unwrap_or_default())
.and_then(|workflow| workflow.definition_fingerprint.as_deref())
!= Some(fingerprint)
})
{
return Err(ProtectionError::AuthenticationFailed.into());
}
}
Ok(())
}
pub(crate) fn check_protected_update_offer(
&self,
_task: &Value,
_name: &str,
_has_validator: bool,
) -> Result<bool> {
#[cfg(feature = "payload-protection")]
if self.client.protection_enabled() {
let input = _task.get("update_arguments");
let Some(protected) = _task.get("protected_update") else {
return if input.is_some_and(is_protected_value) {
Err(ProtectionError::EnvelopeUnsupported.into())
} else {
Ok(false)
};
};
self.client
.assert_protected_response_namespace(_task.get("namespace"))?;
if _task["lease_owner"].as_str() != Some(self.worker_id.as_str()) {
return Err(ProtectionError::AuthenticationFailed.into());
}
if protected.get("require_validator").and_then(Value::as_bool) != Some(_has_validator) {
return Err(ProtectionError::AuthenticationFailed.into());
}
self.client
.check_protected_command(input, protected, _name, Boundary::UpdateInput)?;
return Ok(true);
}
Ok(false)
}
}
impl Client {
pub(super) fn project_workflow_claim(&self, task: &mut WorkflowTask) -> Result<()> {
if !self.protection_enabled() {
return Ok(());
}
self.project_required_input(&mut task.arguments, Boundary::WorkflowInput)?;
project_optional(self, task.signal_arguments.as_mut(), Boundary::SignalInput)?;
for event in &mut task.history_events {
project_history_event(self, event)?;
}
Ok(())
}
pub(super) fn project_activity_claim(&self, task: &mut ActivityTask) -> Result<()> {
if self.protection_enabled() {
self.project_required_input(&mut task.arguments, Boundary::ActivityInput)?;
}
Ok(())
}
pub(super) fn project_query_claim(
&self,
task: &mut QueryTask,
boundary: Boundary,
) -> Result<()> {
if !self.protection_enabled() {
return Ok(());
}
self.project_required_input(&mut task.workflow_arguments, Boundary::WorkflowInput)?;
self.project_required_input(&mut task.query_arguments, boundary)?;
for event in &mut task.history_events {
project_history_event(self, event)?;
}
if let Some(export) = task.history_export.as_mut() {
for event in items(export, "history_events") {
let event_type = event
.get("event_type")
.or_else(|| event.get("type"))
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
if let Some(payload) = event.get_mut("payload") {
project_history_payload(self, &event_type, payload)?;
}
}
for signal in items(export, "signals") {
project_optional(self, signal.get_mut("arguments"), Boundary::SignalInput)?;
}
for activity in items(export, "activities") {
project_optional(self, activity.get_mut("arguments"), Boundary::ActivityInput)?;
project_optional(self, activity.get_mut("result"), Boundary::ActivityResult)?;
}
}
Ok(())
}
fn project_required_input(&self, value: &mut Option<Value>, boundary: Boundary) -> Result<()> {
match value.as_mut().filter(|value| !value.is_null()) {
Some(value) => project_payload(self, value, boundary),
None => self.require_protected_worker_value(),
}
}
fn require_protected_worker_value(&self) -> Result<()> {
#[cfg(feature = "payload-protection")]
if self.protection_enabled() {
return Err(ProtectionError::ProtectionRequired.into());
}
Ok(())
}
pub(super) fn confirm_worker_checkpoint_is_supported(&self, details: &Value) -> Result<()> {
if !details.is_null()
&& !details
.as_object()
.is_some_and(|details| details.is_empty())
{
self.refuse_unsupported_protected_boundary()?;
}
Ok(())
}
pub(super) fn seal_worker_payload(
&self,
value: &AvroValue,
codec: &str,
boundary: Boundary,
) -> Result<Value> {
validate_payload_codec(codec)?;
self.encode_client_payload(value, boundary)
}
pub(super) fn seal_workflow_commands(&self, commands: &mut [Value]) -> Result<()> {
if !self.protection_enabled() {
return Ok(());
}
for command in commands {
let kind = command["type"].as_str().unwrap_or_default();
let slot = match kind {
"complete_workflow" => Some(("result", Boundary::WorkflowResult)),
"complete_update" => Some(("result", Boundary::UpdateResult)),
"record_side_effect" => Some(("result", Boundary::SideEffectResult)),
"schedule_activity" => Some(("arguments", Boundary::ActivityInput)),
"start_child_workflow" | "continue_as_new" => {
Some(("arguments", Boundary::WorkflowInput))
}
"record_local_activity"
| "prepare_local_activity"
| "signal_external_workflow"
| "start_service_operation" => {
self.refuse_unsupported_protected_boundary()?;
None
}
"fail_update" => {
command["message"] = Value::String("Protected update failed.".into());
None
}
_ => None,
};
if command.get("workflow_stream").is_some()
|| ["/exception/details", "/failure/details"]
.iter()
.any(|pointer| {
command
.pointer(pointer)
.is_some_and(|value| !value.is_null())
})
{
self.refuse_unsupported_protected_boundary()?;
}
if let Some((field, boundary)) = slot {
let value = decode_wire_avro_value(&command[field], DEFAULT_CODEC)?;
let sealed = self.encode_client_payload(&value, boundary)?;
command[field] = if boundary == Boundary::SideEffectResult {
sealed["blob"].clone()
} else {
sealed
};
}
}
Ok(())
}
pub(super) fn worker_query_projection(&self, _value: Value) -> Value {
if self.protection_enabled() {
Value::Null
} else {
_value
}
}
#[cfg(feature = "payload-protection")]
fn check_protected_command(
&self,
input: Option<&Value>,
metadata: &Value,
name: &str,
boundary: Boundary,
) -> Result<()> {
let protection = self
.payload_protection
.as_ref()
.ok_or(ProtectionError::ProtectionRequired)?;
if !metadata.is_object() || name.is_empty() {
return Err(ProtectionError::EnvelopeUnsupported.into());
}
let local = argument_vector_contracts(&[name.into()]);
match metadata.get("contract") {
Some(contract) if contract.is_null() || contract == &local[0] => {}
_ => return Err(ProtectionError::AuthenticationFailed.into()),
}
let envelope = exact_inline(input.ok_or(ProtectionError::ProtectionRequired)?)?;
let context = ProtectionContext::new(&self.namespace, boundary)?;
if !matches!(
protection.open_strict(&envelope, context)?,
AvroValue::Array(_)
) {
return Err(Error::Codec(
"protected_command_arguments_not_a_list".into(),
));
}
Ok(())
}
}
fn items<'a>(document: &'a mut Value, key: &str) -> impl Iterator<Item = &'a mut Value> {
document
.get_mut(key)
.and_then(Value::as_array_mut)
.into_iter()
.flatten()
}
fn project_history_event(client: &Client, event: &mut HistoryEvent) -> Result<()> {
project_history_payload(client, &event.event_type, &mut event.payload)
}
fn project_history_payload(client: &Client, kind: &str, payload: &mut Value) -> Result<()> {
use Boundary::*;
let fields: &[(&str, Boundary)] = match kind {
"WorkflowStarted" => &[("arguments", WorkflowInput), ("input", WorkflowInput)],
"ActivityScheduled" => &[("arguments", ActivityInput)],
"ActivityCompleted" => &[("result", ActivityResult), ("output", ActivityResult)],
"ChildRunCompleted" | "WorkflowCompleted" => {
&[("result", WorkflowResult), ("output", WorkflowResult)]
}
"SignalReceived" | "SignalApplied" => &[
("value", SignalInput),
("input", SignalInput),
("arguments", SignalInput),
],
"UpdateAccepted" | "UpdateRejected" | "UpdateApplied" => {
&[("arguments", UpdateInput), ("result", UpdateResult)]
}
"UpdateCompleted" => &[("result", UpdateResult)],
"SideEffectRecorded" => &[("result", SideEffectResult)],
_ => &[],
};
for (field, boundary) in fields {
project_optional(client, payload.get_mut(*field), *boundary)?;
}
if matches!(
kind,
"ActivityScheduled" | "ActivityStarted" | "ActivityCompleted"
) {
project_optional(
client,
payload.pointer_mut("/activity/arguments"),
ActivityInput,
)?;
}
if kind == "ActivityCompleted" {
project_optional(
client,
payload.pointer_mut("/activity/result"),
ActivityResult,
)?;
}
Ok(())
}
fn project_optional(client: &Client, value: Option<&mut Value>, boundary: Boundary) -> Result<()> {
if let Some(value) = value.filter(|value| !value.is_null()) {
project_payload(client, value, boundary)?;
}
Ok(())
}
fn project_payload(client: &Client, value: &mut Value, boundary: Boundary) -> Result<()> {
let envelope = match value.as_str() {
Some(blob) => serde_json::json!({"codec": DEFAULT_CODEC, "blob": blob}),
None => value.clone(),
};
let plain = client.decode_client_payload(&envelope, boundary)?;
#[cfg(feature = "payload-protection")]
if matches!(
boundary,
Boundary::WorkflowInput
| Boundary::ActivityInput
| Boundary::SignalInput
| Boundary::UpdateInput
| Boundary::QueryInput
) && !matches!(plain, AvroValue::Array(_))
&& is_protected_value(&envelope)
{
return Err(Error::Codec("protected_worker_arguments_not_a_list".into()));
}
*value = encode_typed_envelope(&plain, DEFAULT_CODEC)?;
Ok(())
}
#[cfg(feature = "payload-protection")]
fn is_protected_value(value: &Value) -> bool {
value
.get("blob")
.and_then(Value::as_str)
.is_some_and(|blob| {
BASE64
.decode(blob)
.is_ok_and(|wire| wire.starts_with(&PROTECTED_VALUE_V1_HEADER))
})
}