laravel-template-engine 0.5.0

Templates for emails, documents and notifications that your team edits, stored in the database
Documentation
//! The sandbox templates render in: only the type's data and the allowed filters, within limits.

use std::cell::Cell;
use std::io;
use std::sync::Arc;
use std::time::{Duration, Instant};

use minijinja::value::Rest;
use minijinja::{AutoEscape, Environment, Error, ErrorKind, UndefinedBehavior, Value};

use crate::config::TemplateEngineConfig;
use crate::filters;

/// How a filter argument is checked when the template gives it as a constant.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ArgKind {
    /// Text, such as `"%d.%m.%Y"`.
    Text,
    /// A number, such as `2`.
    Number,
    /// Anything.
    Any,
}

/// What a filter's input should be, for the checks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputKind {
    /// A number.
    Number,
    /// A date, or text holding one.
    Date,
    /// Anything.
    Any,
}

type FilterFn = dyn Fn(Value, &[Value]) -> Result<Value, String> + Send + Sync;

/// A filter an application adds for its templates, on top of the built-in ones.
///
/// ```
/// use laravel_template_engine::{ArgKind, Filter, Value};
///
/// let sku = Filter::new("sku", "Formats a product code", |value: Value, _args: &[Value]| {
///     Ok(Value::from(format!("SKU-{value}")))
/// });
/// let shout = Filter::new("shout", "Adds exclamation marks", |value: Value, args: &[Value]| {
///     let count = args.first().and_then(|n| n.as_usize()).unwrap_or(1);
///     Ok(Value::from(format!("{value}{}", "!".repeat(count))))
/// })
/// .arg("count", ArgKind::Number, false);
/// ```
#[derive(Clone)]
pub struct Filter {
    pub(crate) spec: FilterSpec,
    pub(crate) run: Arc<FilterFn>,
}

impl Filter {
    /// A filter called `name` that runs `run` with the value and the arguments.
    pub fn new<F>(name: &'static str, description: &'static str, run: F) -> Self
    where
        F: Fn(Value, &[Value]) -> Result<Value, String> + Send + Sync + 'static,
    {
        let spec = FilterSpec {
            name,
            description,
            example: "",
            args: Vec::new(),
            input: InputKind::Any,
        };
        Self {
            spec,
            run: Arc::new(run),
        }
    }

    /// Declares the next argument, so the checks know how many there may be.
    #[must_use]
    pub fn arg(mut self, name: &'static str, kind: ArgKind, required: bool) -> Self {
        self.spec.args.push(Arg { name, kind, required });
        self
    }

    /// An example of the filter in use, for the syntax cheat sheet.
    #[must_use]
    pub fn example(mut self, example: &'static str) -> Self {
        self.spec.example = example;
        self
    }
}

impl std::fmt::Debug for Filter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Filter")
            .field("name", &self.spec.name)
            .finish_non_exhaustive()
    }
}

/// A filter argument.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Arg {
    /// Its name, for the cheat sheet.
    pub name: &'static str,
    /// What it should be.
    pub kind: ArgKind,
    /// Whether it must be given.
    pub required: bool,
}

/// What templates may use a filter for, and how.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FilterSpec {
    /// The name, such as `money`.
    pub name: &'static str,
    /// What it does.
    pub description: &'static str,
    /// An example.
    pub example: &'static str,
    /// The arguments.
    pub args: Vec<Arg>,
    /// What its input should be.
    pub input: InputKind,
}

impl FilterSpec {
    pub(crate) fn min_args(&self) -> usize {
        self.args.iter().filter(|a| a.required).count()
    }

    /// `usize::MAX` when the last argument repeats, as `plural`'s forms do.
    pub(crate) fn max_args(&self) -> usize {
        if self.name == "plural" {
            usize::MAX
        } else {
            self.args.len()
        }
    }
}

/// The tests templates may use, as in `{% if order.note is defined %}`.
pub(crate) const TESTS: &[&str] = &[
    "defined",
    "undefined",
    "none",
    "odd",
    "even",
    "divisibleby",
    "number",
    "string",
    "startingwith",
    "endingwith",
    "true",
    "false",
];

/// The functions templates may call.
pub(crate) const FUNCTIONS: &[&str] = &["range"];

/// The most items `range` may make.
const MAX_RANGE: isize = 10_000;

/// The limits of one render.
#[derive(Debug, Clone, Copy)]
pub(crate) struct Limits {
    pub fuel: u64,
    pub max_output: usize,
    pub timeout: Duration,
    pub recursion: usize,
}

impl Limits {
    pub(crate) fn from_config(config: &TemplateEngineConfig) -> Self {
        Self {
            fuel: config.fuel,
            max_output: config.max_output,
            timeout: Duration::from_millis(config.timeout_ms),
            recursion: (config.max_depth * 2 + 10).min(500),
        }
    }
}

/// One render's environment: the language, the currency, the filters and the limits.
#[derive(Clone)]
pub(crate) struct Sandbox {
    pub locale: String,
    pub currency: String,
    pub custom: Arc<Vec<Filter>>,
    pub limits: Limits,
}

/// How a template's output is escaped.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Escape {
    /// HTML: values are escaped, the template's own markup isn't.
    Html,
    /// Plain text, such as a subject.
    None,
}

impl Sandbox {
    pub(crate) fn environment(&self) -> Environment<'static> {
        let mut env = Environment::empty();
        env.set_undefined_behavior(UndefinedBehavior::Strict);
        env.set_fuel(Some(self.limits.fuel));
        env.set_recursion_limit(self.limits.recursion);
        env.set_auto_escape_callback(|name| {
            if name.to_ascii_lowercase().ends_with(".html") {
                AutoEscape::Html
            } else {
                AutoEscape::None
            }
        });

        filters::register(&mut env, &self.locale, &self.currency);
        for filter in self.custom.iter() {
            let run = filter.run.clone();
            env.add_filter(filter.spec.name, move |value: Value, args: Rest<Value>| {
                run(value, &args).map_err(|message| Error::new(ErrorKind::InvalidOperation, message))
            });
        }

        env.add_test("defined", minijinja::tests::is_defined);
        env.add_test("undefined", minijinja::tests::is_undefined);
        env.add_test("none", minijinja::tests::is_none);
        env.add_test("odd", minijinja::tests::is_odd);
        env.add_test("even", minijinja::tests::is_even);
        env.add_test("divisibleby", minijinja::tests::is_divisibleby);
        env.add_test("number", minijinja::tests::is_number);
        env.add_test("string", minijinja::tests::is_string);
        env.add_test("startingwith", minijinja::tests::is_startingwith);
        env.add_test("endingwith", minijinja::tests::is_endingwith);
        env.add_test("true", minijinja::tests::is_true);
        env.add_test("false", minijinja::tests::is_false);

        env.add_function("range", |lower: isize, upper: Option<isize>, step: Option<isize>| {
            let (start, end) = upper.map_or((0, lower), |upper| (lower, upper));
            let step = step.unwrap_or(1);
            if step == 0 {
                return Err(Error::new(ErrorKind::InvalidOperation, "range's step can't be 0"));
            }
            if (end - start) / step > MAX_RANGE {
                return Err(Error::new(
                    ErrorKind::InvalidOperation,
                    format!("range can't make more than {MAX_RANGE} numbers"),
                ));
            }
            minijinja::functions::range(lower, upper, Some(step))
        });
        env
    }

    /// Renders `source` with `data`. `name` ends in `.html` for HTML escaping.
    pub(crate) fn render(&self, name: &str, source: &str, data: &Value, escape: Escape) -> Result<String, String> {
        let env = self.environment();
        let name = match escape {
            Escape::Html => format!("{name}.html"),
            Escape::None => format!("{name}.txt"),
        };
        let template = env.template_from_named_str(&name, source).map_err(|e| describe(&e))?;

        let tripped = Cell::new(None);
        let mut buffer = Vec::new();
        let writer = LimitedWriter {
            out: &mut buffer,
            max: self.limits.max_output,
            deadline: Instant::now() + self.limits.timeout,
            tripped: &tripped,
        };
        let result = template.render_captured_to(data.clone(), writer);
        if let Some(limit) = tripped.take() {
            return Err(limit);
        }
        result.map_err(|e| describe(&e))?;
        String::from_utf8(buffer).map_err(|e| e.to_string())
    }
}

/// A render error with its line, in words for the person editing the template.
pub(crate) fn describe(error: &Error) -> String {
    let message = match error.kind() {
        ErrorKind::OutOfFuel => "the template does too much work, for example a loop that runs too long".to_owned(),
        _ => error
            .detail()
            .map_or_else(|| error.kind().to_string(), ToOwned::to_owned),
    };
    match error.line() {
        Some(line) => format!("line {line}: {message}"),
        None => message,
    }
}

struct LimitedWriter<'a> {
    out: &'a mut Vec<u8>,
    max: usize,
    deadline: Instant,
    tripped: &'a Cell<Option<String>>,
}

impl io::Write for LimitedWriter<'_> {
    fn write(&mut self, chunk: &[u8]) -> io::Result<usize> {
        if self.out.len() + chunk.len() > self.max {
            self.tripped.set(Some(format!(
                "the result is longer than the limit of {} bytes",
                self.max
            )));
            return Err(io::Error::other("output limit"));
        }
        if Instant::now() > self.deadline {
            self.tripped
                .set(Some("the template takes too long to render".to_owned()));
            return Err(io::Error::other("time limit"));
        }
        self.out.extend_from_slice(chunk);
        Ok(chunk.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

/// Converts JSON into template values. `serde_json`'s `arbitrary_precision`, which Laravel Rust
/// turns on, would otherwise give templates numbers as maps.
pub(crate) fn to_value(json: &serde_json::Value) -> Value {
    match json {
        serde_json::Value::Null => Value::from(()),
        serde_json::Value::Bool(b) => Value::from(*b),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                Value::from(i)
            } else if let Some(u) = n.as_u64() {
                Value::from(u)
            } else {
                Value::from(n.as_f64().unwrap_or(f64::NAN))
            }
        }
        serde_json::Value::String(s) => Value::from(s.as_str()),
        serde_json::Value::Array(items) => Value::from(items.iter().map(to_value).collect::<Vec<_>>()),
        serde_json::Value::Object(map) => {
            let map: std::collections::BTreeMap<String, Value> =
                map.iter().map(|(key, value)| (key.clone(), to_value(value))).collect();
            Value::from(map)
        }
    }
}