protify 0.1.4

A Rust-first protobuf framework to generate packages from rust code, with validation included
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
mod cel_trait;
pub use cel_trait::*;

use super::*;

/// A rule that defines CEL-based validation
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CelRule {
	/// The id of this specific rule. It should be unique in the scope of its message.
	pub id: FixedStr,
	/// The error message to display in case the rule fails validation.
	pub message: FixedStr,
	/// The CEL expression that must be used to perform the validation check.
	pub expression: FixedStr,
}

impl From<CelProgramInner> for CelRule {
	#[inline]
	fn from(value: CelProgramInner) -> Self {
		value.rule
	}
}

impl From<CelProgram> for CelRule {
	fn from(value: CelProgram) -> Self {
		value.inner.rule.clone()
	}
}

impl From<CelRule> for OptionValue {
	fn from(value: CelRule) -> Self {
		Self::Message(
			[
				(FixedStr::Static("id"), Self::String(value.id)),
				(FixedStr::Static("message"), Self::String(value.message)),
				(
					FixedStr::Static("expression"),
					Self::String(value.expression),
				),
			]
			.into_iter()
			.collect(),
		)
	}
}

/// A struct that holds the data to initialize and execute a CEL program. It can be created from a [`CelRule`].
///
/// The program is compiled once and reused afterwards. This type can be cheaply cloned (from something like a Lazy static) to reuse it in multiple locations.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(from = "CelRule", into = "CelRule"))]
pub struct CelProgram {
	pub(crate) inner: Arc<CelProgramInner>,
}

impl CelProgram {
	/// Accesses the [`CelRule`] for this program.
	#[must_use]
	#[inline]
	pub fn rule(&self) -> &CelRule {
		&self.inner.rule
	}
}

#[cfg(not(feature = "cel"))]
#[derive(Debug, PartialEq, Eq, Hash)]
pub(crate) struct CelProgramInner {
	pub(crate) rule: CelRule,
}

#[cfg(not(feature = "cel"))]
#[derive(PartialEq, Eq, Debug, Clone, Error)]
#[error("")]
pub struct CelError;

#[cfg(feature = "cel")]
pub use cel_impls::*;

#[cfg(feature = "cel")]
mod cel_impls {
	use super::*;

	use ::cel::{Context, ExecutionError, Program, Value, objects::ValueType};
	use chrono::Utc;
	use core::convert::Infallible;
	use std::sync::OnceLock;

	#[derive(Debug)]
	pub(crate) struct CelProgramInner {
		pub(crate) rule: CelRule,
		program: OnceLock<Program>,
	}

	impl Hash for CelProgramInner {
		fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
			self.rule.hash(state);
		}
	}

	impl Eq for CelProgramInner {}

	impl PartialEq for CelProgramInner {
		#[inline]
		fn eq(&self, other: &Self) -> bool {
			self.rule == other.rule
		}
	}

	impl CelProgramInner {
		#[inline]
		fn get_program(&self) -> &Program {
			self.program
				.get_or_init(|| self.compile_program())
		}

		#[inline(never)]
		#[cold]
		fn compile_program(&self) -> Program {
			Program::compile(&self.rule.expression).unwrap_or_else(|e| {
				panic!(
					"Failed to compile CEL program with id `{}`: {e}",
					self.rule.id
				)
			})
		}
	}

	fn initialize_context<'a, T>(value: T) -> Result<Context<'a>, CelError>
	where
		T: TryIntoCel,
	{
		let mut ctx = Context::default();

		ctx.add_variable_from_value("this", value.__try_into_cel()?);
		#[cfg(all(feature = "chrono", any(feature = "std", feature = "chrono-wasm")))]
		ctx.add_variable_from_value("now", Value::Timestamp(Utc::now().into()));

		Ok(ctx)
	}

	pub(crate) struct ProgramsExecutionCtx<'a, T> {
		pub programs: &'a [CelProgram],
		pub value: T,
		pub ctx: &'a mut ValidationCtx,
	}

	impl<T> ProgramsExecutionCtx<'_, T>
	where
		T: TryIntoCel,
	{
		pub(crate) fn execute_programs(self) -> ValidationResult {
			let Self {
				programs,
				value,
				ctx,
			} = self;

			let mut is_valid = IsValid::Yes;

			let cel_ctx = match initialize_context(value) {
				Ok(cel_ctx) => cel_ctx,
				Err(e) => {
					let _ = ctx.add_cel_error_violation(e);
					return Err(FailFast);
				}
			};

			for program in programs {
				match program.execute(&cel_ctx) {
					Ok(was_successful) => {
						if !was_successful {
							is_valid &= ctx.add_cel_violation(&program.inner.rule)?;
						}
					}
					Err(e) => is_valid &= ctx.add_cel_error_violation(e)?,
				};
			}

			Ok(is_valid)
		}
	}

	#[inline(never)]
	#[cold]
	pub(crate) fn test_programs<T>(programs: &[CelProgram], value: T) -> Result<(), Vec<CelError>>
	where
		T: TryIntoCel,
	{
		let mut errors: Vec<CelError> = Vec::new();

		let ctx = match initialize_context(value) {
			Ok(ctx) => ctx,
			Err(e) => {
				errors.push(e);
				return Err(errors);
			}
		};

		for program in programs {
			if let Err(e) = program.execute(&ctx) {
				errors.push(e);
			}
		}

		if errors.is_empty() {
			Ok(())
		} else {
			Err(errors)
		}
	}

	impl From<CelRule> for CelProgram {
		#[inline]
		fn from(value: CelRule) -> Self {
			Self::new(value)
		}
	}

	impl CelProgram {
		/// Creates a new program from a [`CelRule`].
		#[must_use]
		#[inline]
		pub fn new(rule: CelRule) -> Self {
			Self {
				inner: Arc::new(CelProgramInner {
					rule,
					program: OnceLock::new(),
				}),
			}
		}

		/// Accesses the CEL program, compiling it on the first access.
		///
		/// # Panics
		///
		/// Panics if the program failed to compile.
		#[inline]
		#[must_use]
		pub fn get_program(&self) -> &Program {
			self.inner.get_program()
		}

		/// Executes the program with the given [`Context`].
		///
		/// # Panics
		///
		/// Panics if the program failed to compile.
		pub fn execute(&self, ctx: &Context) -> Result<bool, CelError> {
			let program = self.get_program();

			let result = program
				.execute(ctx)
				.map_err(|e| CelError::ExecutionError {
					rule_id: self.inner.rule.id.clone(),
					source: Box::new(e),
				})?;

			if let Value::Bool(result) = result {
				Ok(result)
			} else {
				Err(CelError::NonBooleanResult {
					rule_id: self.inner.rule.id.clone(),
					value: result.type_of(),
				})
			}
		}
	}

	impl CelError {
		/// Returns the rule id of the given error, if the error has a rule source and is not
		/// a generic conversion error.
		#[must_use]
		#[inline]
		pub fn rule_id(&self) -> Option<&str> {
			match self {
				Self::ConversionError(_) => None,
				Self::NonBooleanResult { rule_id, .. } | Self::ExecutionError { rule_id, .. } => {
					Some(rule_id.as_ref())
				}
			}
		}

		// This is for runtime errors. If we get a CEL error we log the actual error while
		// producing a generic error message
		#[must_use]
		#[inline(never)]
		#[cold]
		pub(crate) fn into_violation(
			self,
			field_context: Option<&FieldContext>,
			parent_elements: &[FieldPathElement],
		) -> Violation {
			// We try to provide more context for this variant
			// since it lacks a program id
			if matches!(self, Self::ConversionError(_)) {
				let mut item_path = String::new();

				for name in parent_elements
					.iter()
					.filter_map(|e| e.field_name.as_ref())
				{
					if !item_path.is_empty() {
						item_path.push('.');
					}
					item_path.push_str(name);
				}

				if let Some(field_name) = field_context.map(|fc| &fc.name) {
					if !item_path.is_empty() {
						item_path.push('.');
					}
					item_path.push_str(field_name);
				}

				if item_path.is_empty() {
					item_path.push_str("unknown");
				}

				// A conversion error is due to user input so we don't assign a great priority to it
				log::trace!("Cel execution failure for item at location `{item_path}`: {self}");
			} else {
				// Caused from a malformed CEL expression, so
				// it has higher priority
				log::error!("{self}");
			}

			create_violation_core(
				self.rule_id().map(|s| s.to_string()),
				field_context,
				parent_elements,
				CEL_VIOLATION,
				"internal server error".to_string(),
			)
		}
	}

	/// Represents runtime errors that can occur with CEL programs.
	#[non_exhaustive]
	#[derive(Debug, Clone, Error)]
	pub enum CelError {
		#[error(
			"Expected CEL program with id `{rule_id}` to return a boolean result, got `{value:?}`"
		)]
		NonBooleanResult { rule_id: FixedStr, value: ValueType },
		#[error("Failed to inject value in CEL program: {0}")]
		ConversionError(String),
		#[error("Failed to execute CEL program with id `{rule_id}`: {source}")]
		ExecutionError {
			rule_id: FixedStr,
			source: Box<ExecutionError>,
		},
	}

	const fn partial_eq_value_type(input: ValueType, other: ValueType) -> bool {
		match input {
			ValueType::List => matches!(other, ValueType::List),
			ValueType::Map => matches!(other, ValueType::Map),
			ValueType::Function => matches!(other, ValueType::Function),
			ValueType::Int => matches!(other, ValueType::Int),
			ValueType::UInt => matches!(other, ValueType::UInt),
			ValueType::Float => matches!(other, ValueType::Float),
			ValueType::String => matches!(other, ValueType::String),
			ValueType::Bytes => matches!(other, ValueType::Bytes),
			ValueType::Bool => matches!(other, ValueType::Bool),
			ValueType::Duration => matches!(other, ValueType::Duration),
			ValueType::Timestamp => matches!(other, ValueType::Timestamp),
			ValueType::Opaque => matches!(other, ValueType::Opaque),
			ValueType::Null => matches!(other, ValueType::Null),
		}
	}

	impl PartialEq for CelError {
		fn eq(&self, other: &Self) -> bool {
			match self {
				Self::NonBooleanResult { rule_id, value } => {
					if let Self::NonBooleanResult {
						rule_id: other_rule_id,
						value: other_value,
					} = other
					{
						rule_id == other_rule_id && partial_eq_value_type(*value, *other_value)
					} else {
						false
					}
				}
				Self::ConversionError(err) => {
					if let Self::ConversionError(other_err) = other {
						err == other_err
					} else {
						false
					}
				}
				Self::ExecutionError { rule_id, source } => {
					if let Self::ExecutionError {
						rule_id: other_rule_id,
						source: other_source,
					} = other
					{
						rule_id == other_rule_id && source == other_source
					} else {
						false
					}
				}
			}
		}
	}

	impl From<Infallible> for CelError {
		#[inline]
		fn from(value: Infallible) -> Self {
			match value {}
		}
	}
}