Skip to main content

laravel_template_engine/
sandbox.rs

1//! The sandbox templates render in: only the type's data and the allowed filters, within limits.
2
3use std::cell::Cell;
4use std::io;
5use std::sync::Arc;
6use std::time::{Duration, Instant};
7
8use minijinja::value::Rest;
9use minijinja::{AutoEscape, Environment, Error, ErrorKind, UndefinedBehavior, Value};
10
11use crate::config::TemplateEngineConfig;
12use crate::filters;
13
14/// How a filter argument is checked when the template gives it as a constant.
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum ArgKind {
17    /// Text, such as `"%d.%m.%Y"`.
18    Text,
19    /// A number, such as `2`.
20    Number,
21    /// Anything.
22    Any,
23}
24
25/// What a filter's input should be, for the checks.
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum InputKind {
28    /// A number.
29    Number,
30    /// A date, or text holding one.
31    Date,
32    /// Anything.
33    Any,
34}
35
36type FilterFn = dyn Fn(Value, &[Value]) -> Result<Value, String> + Send + Sync;
37
38/// A filter an application adds for its templates, on top of the built-in ones.
39///
40/// ```
41/// use laravel_template_engine::{ArgKind, Filter, Value};
42///
43/// let sku = Filter::new("sku", "Formats a product code", |value: Value, _args: &[Value]| {
44///     Ok(Value::from(format!("SKU-{value}")))
45/// });
46/// let shout = Filter::new("shout", "Adds exclamation marks", |value: Value, args: &[Value]| {
47///     let count = args.first().and_then(|n| n.as_usize()).unwrap_or(1);
48///     Ok(Value::from(format!("{value}{}", "!".repeat(count))))
49/// })
50/// .arg("count", ArgKind::Number, false);
51/// ```
52#[derive(Clone)]
53pub struct Filter {
54    pub(crate) spec: FilterSpec,
55    pub(crate) run: Arc<FilterFn>,
56}
57
58impl Filter {
59    /// A filter called `name` that runs `run` with the value and the arguments.
60    pub fn new<F>(name: &'static str, description: &'static str, run: F) -> Self
61    where
62        F: Fn(Value, &[Value]) -> Result<Value, String> + Send + Sync + 'static,
63    {
64        let spec = FilterSpec {
65            name,
66            description,
67            example: "",
68            args: Vec::new(),
69            input: InputKind::Any,
70        };
71        Self {
72            spec,
73            run: Arc::new(run),
74        }
75    }
76
77    /// Declares the next argument, so the checks know how many there may be.
78    #[must_use]
79    pub fn arg(mut self, name: &'static str, kind: ArgKind, required: bool) -> Self {
80        self.spec.args.push(Arg { name, kind, required });
81        self
82    }
83
84    /// An example of the filter in use, for the syntax cheat sheet.
85    #[must_use]
86    pub fn example(mut self, example: &'static str) -> Self {
87        self.spec.example = example;
88        self
89    }
90}
91
92impl std::fmt::Debug for Filter {
93    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
94        f.debug_struct("Filter")
95            .field("name", &self.spec.name)
96            .finish_non_exhaustive()
97    }
98}
99
100/// A filter argument.
101#[derive(Debug, Clone, PartialEq, Eq)]
102pub struct Arg {
103    /// Its name, for the cheat sheet.
104    pub name: &'static str,
105    /// What it should be.
106    pub kind: ArgKind,
107    /// Whether it must be given.
108    pub required: bool,
109}
110
111/// What templates may use a filter for, and how.
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct FilterSpec {
114    /// The name, such as `money`.
115    pub name: &'static str,
116    /// What it does.
117    pub description: &'static str,
118    /// An example.
119    pub example: &'static str,
120    /// The arguments.
121    pub args: Vec<Arg>,
122    /// What its input should be.
123    pub input: InputKind,
124}
125
126impl FilterSpec {
127    pub(crate) fn min_args(&self) -> usize {
128        self.args.iter().filter(|a| a.required).count()
129    }
130
131    /// `usize::MAX` when the last argument repeats, as `plural`'s forms do.
132    pub(crate) fn max_args(&self) -> usize {
133        if self.name == "plural" {
134            usize::MAX
135        } else {
136            self.args.len()
137        }
138    }
139}
140
141/// The tests templates may use, as in `{% if order.note is defined %}`.
142pub(crate) const TESTS: &[&str] = &[
143    "defined",
144    "undefined",
145    "none",
146    "odd",
147    "even",
148    "divisibleby",
149    "number",
150    "string",
151    "startingwith",
152    "endingwith",
153    "true",
154    "false",
155];
156
157/// The functions templates may call.
158pub(crate) const FUNCTIONS: &[&str] = &["range"];
159
160/// The most items `range` may make.
161const MAX_RANGE: isize = 10_000;
162
163/// The limits of one render.
164#[derive(Debug, Clone, Copy)]
165pub(crate) struct Limits {
166    pub fuel: u64,
167    pub max_output: usize,
168    pub timeout: Duration,
169    pub recursion: usize,
170}
171
172impl Limits {
173    pub(crate) fn from_config(config: &TemplateEngineConfig) -> Self {
174        Self {
175            fuel: config.fuel,
176            max_output: config.max_output,
177            timeout: Duration::from_millis(config.timeout_ms),
178            recursion: (config.max_depth * 2 + 10).min(500),
179        }
180    }
181}
182
183/// One render's environment: the language, the currency, the filters and the limits.
184#[derive(Clone)]
185pub(crate) struct Sandbox {
186    pub locale: String,
187    pub currency: String,
188    pub custom: Arc<Vec<Filter>>,
189    pub limits: Limits,
190}
191
192/// How a template's output is escaped.
193#[derive(Debug, Clone, Copy, PartialEq, Eq)]
194pub(crate) enum Escape {
195    /// HTML: values are escaped, the template's own markup isn't.
196    Html,
197    /// Plain text, such as a subject.
198    None,
199}
200
201impl Sandbox {
202    pub(crate) fn environment(&self) -> Environment<'static> {
203        let mut env = Environment::empty();
204        env.set_undefined_behavior(UndefinedBehavior::Strict);
205        env.set_fuel(Some(self.limits.fuel));
206        env.set_recursion_limit(self.limits.recursion);
207        env.set_auto_escape_callback(|name| {
208            if name.to_ascii_lowercase().ends_with(".html") {
209                AutoEscape::Html
210            } else {
211                AutoEscape::None
212            }
213        });
214
215        filters::register(&mut env, &self.locale, &self.currency);
216        for filter in self.custom.iter() {
217            let run = filter.run.clone();
218            env.add_filter(filter.spec.name, move |value: Value, args: Rest<Value>| {
219                run(value, &args).map_err(|message| Error::new(ErrorKind::InvalidOperation, message))
220            });
221        }
222
223        env.add_test("defined", minijinja::tests::is_defined);
224        env.add_test("undefined", minijinja::tests::is_undefined);
225        env.add_test("none", minijinja::tests::is_none);
226        env.add_test("odd", minijinja::tests::is_odd);
227        env.add_test("even", minijinja::tests::is_even);
228        env.add_test("divisibleby", minijinja::tests::is_divisibleby);
229        env.add_test("number", minijinja::tests::is_number);
230        env.add_test("string", minijinja::tests::is_string);
231        env.add_test("startingwith", minijinja::tests::is_startingwith);
232        env.add_test("endingwith", minijinja::tests::is_endingwith);
233        env.add_test("true", minijinja::tests::is_true);
234        env.add_test("false", minijinja::tests::is_false);
235
236        env.add_function("range", |lower: isize, upper: Option<isize>, step: Option<isize>| {
237            let (start, end) = upper.map_or((0, lower), |upper| (lower, upper));
238            let step = step.unwrap_or(1);
239            if step == 0 {
240                return Err(Error::new(ErrorKind::InvalidOperation, "range's step can't be 0"));
241            }
242            if (end - start) / step > MAX_RANGE {
243                return Err(Error::new(
244                    ErrorKind::InvalidOperation,
245                    format!("range can't make more than {MAX_RANGE} numbers"),
246                ));
247            }
248            minijinja::functions::range(lower, upper, Some(step))
249        });
250        env
251    }
252
253    /// Renders `source` with `data`. `name` ends in `.html` for HTML escaping.
254    pub(crate) fn render(&self, name: &str, source: &str, data: &Value, escape: Escape) -> Result<String, String> {
255        let env = self.environment();
256        let name = match escape {
257            Escape::Html => format!("{name}.html"),
258            Escape::None => format!("{name}.txt"),
259        };
260        let template = env.template_from_named_str(&name, source).map_err(|e| describe(&e))?;
261
262        let tripped = Cell::new(None);
263        let mut buffer = Vec::new();
264        let writer = LimitedWriter {
265            out: &mut buffer,
266            max: self.limits.max_output,
267            deadline: Instant::now() + self.limits.timeout,
268            tripped: &tripped,
269        };
270        let result = template.render_captured_to(data.clone(), writer);
271        if let Some(limit) = tripped.take() {
272            return Err(limit);
273        }
274        result.map_err(|e| describe(&e))?;
275        String::from_utf8(buffer).map_err(|e| e.to_string())
276    }
277}
278
279/// A render error with its line, in words for the person editing the template.
280pub(crate) fn describe(error: &Error) -> String {
281    let message = match error.kind() {
282        ErrorKind::OutOfFuel => "the template does too much work, for example a loop that runs too long".to_owned(),
283        _ => error
284            .detail()
285            .map_or_else(|| error.kind().to_string(), ToOwned::to_owned),
286    };
287    match error.line() {
288        Some(line) => format!("line {line}: {message}"),
289        None => message,
290    }
291}
292
293struct LimitedWriter<'a> {
294    out: &'a mut Vec<u8>,
295    max: usize,
296    deadline: Instant,
297    tripped: &'a Cell<Option<String>>,
298}
299
300impl io::Write for LimitedWriter<'_> {
301    fn write(&mut self, chunk: &[u8]) -> io::Result<usize> {
302        if self.out.len() + chunk.len() > self.max {
303            self.tripped.set(Some(format!(
304                "the result is longer than the limit of {} bytes",
305                self.max
306            )));
307            return Err(io::Error::other("output limit"));
308        }
309        if Instant::now() > self.deadline {
310            self.tripped
311                .set(Some("the template takes too long to render".to_owned()));
312            return Err(io::Error::other("time limit"));
313        }
314        self.out.extend_from_slice(chunk);
315        Ok(chunk.len())
316    }
317
318    fn flush(&mut self) -> io::Result<()> {
319        Ok(())
320    }
321}
322
323/// Converts JSON into template values. `serde_json`'s `arbitrary_precision`, which Laravel Rust
324/// turns on, would otherwise give templates numbers as maps.
325pub(crate) fn to_value(json: &serde_json::Value) -> Value {
326    match json {
327        serde_json::Value::Null => Value::from(()),
328        serde_json::Value::Bool(b) => Value::from(*b),
329        serde_json::Value::Number(n) => {
330            if let Some(i) = n.as_i64() {
331                Value::from(i)
332            } else if let Some(u) = n.as_u64() {
333                Value::from(u)
334            } else {
335                Value::from(n.as_f64().unwrap_or(f64::NAN))
336            }
337        }
338        serde_json::Value::String(s) => Value::from(s.as_str()),
339        serde_json::Value::Array(items) => Value::from(items.iter().map(to_value).collect::<Vec<_>>()),
340        serde_json::Value::Object(map) => {
341            let map: std::collections::BTreeMap<String, Value> =
342                map.iter().map(|(key, value)| (key.clone(), to_value(value))).collect();
343            Value::from(map)
344        }
345    }
346}