isis-report-lib 0.2.2

Tabular reports with hierarchical layouts: HTML, PDF, XLSX, CSV and plain text
Documentation
//! Jinja-compatible HTML rendering with bundled templates.
//!
//! `minijinja` provides the template language (macros, inheritance, imports
//! and autoescape). A custom `template_dir` is layered over the bundled
//! templates, so it can override `tabular.jinja` or add a new template.
//!
//! Report data is untrusted: templates render with HTML autoescape and the
//! only raw markup is the pre-built, escaped SVG returned by `fmt` for the
//! `sparkline` mask.

use std::collections::HashMap;
use std::path::{Component, Path, PathBuf};
use std::sync::LazyLock;

use minijinja::value::{Kwargs, Rest, Serde, Value as MjValue};
use minijinja::{AutoEscape, Environment, TemplateSource};
use regex::Regex;

use crate::error::{Error, Result};
use crate::formatting::{cell_style, format_value};
use crate::value::Value;

const BASE: &str = include_str!("../templates/base.jinja");
const TABULAR: &str = include_str!("../templates/tabular.jinja");
const SECTIONS: &str = include_str!("../templates/sections.jinja");
const TABULAR_SECTIONS: &str = include_str!("../templates/tabular_sections.jinja");

static BUNDLED: LazyLock<HashMap<&'static str, &'static str>> = LazyLock::new(|| {
    let mut templates = HashMap::new();
    templates.insert("base.jinja", BASE);
    templates.insert("tabular.jinja", TABULAR);
    templates.insert("sections.jinja", SECTIONS);
    templates.insert("tabular_sections.jinja", TABULAR_SECTIONS);
    templates
});

static ROOT_BLOCK_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r":root\s*\{([^}]*)\}").expect("valid root regex"));
static ROOT_VAR_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"--([\w-]+)\s*:\s*([^;]+);").expect("valid root var regex"));
static VAR_USE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"var\(\s*--([\w-]+)\s*(?:,\s*([^)]*))?\)").expect("valid var use regex"));
static LINK_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?i)<link\b[^>]*>").expect("valid link regex"));

/// Map physical `left`/`right` alignment to logical `start`/`end`.
pub fn text_align(value: Option<&str>) -> String {
    match value {
        Some("left") => "start".to_string(),
        Some("right") => "end".to_string(),
        Some(other) => other.to_string(),
        None => String::new(),
    }
}

fn from_mj(value: &MjValue) -> Value {
    if value.is_undefined() || value.is_none() {
        return Value::Null;
    }
    match serde_json::to_value(value) {
        Ok(json) => Value::from_json(json),
        Err(_) => Value::String(value.to_string()),
    }
}

fn to_mj(value: &Value) -> MjValue {
    MjValue::from(Serde(value))
}

fn template_error(name: &str, error: minijinja::Error) -> Error {
    Error::template(format!("Template {name:?} uses blocked constructs or invalid template: {error}"))
}

fn safe_join(base: &Path, name: &str) -> Option<PathBuf> {
    if name.is_empty() || name.starts_with('/') || name.starts_with('\\') {
        return None;
    }
    let mut path = base.to_path_buf();
    for component in Path::new(name).components() {
        match component {
            Component::Normal(component) => path.push(component),
            Component::CurDir => {}
            _ => return None,
        }
    }
    if path.is_file() {
        Some(path)
    } else {
        None
    }
}

fn build_env(template_dir: Option<&Path>, meta: &Value) -> Result<Environment<'static>> {
    if let Some(template_dir) = template_dir {
        if !template_dir.is_dir() {
            return Err(Error::TemplateDirNotFound(template_dir.to_path_buf()));
        }
    }
    let custom_dir = template_dir.map(Path::to_path_buf);
    let mut env = Environment::new();
    env.set_auto_escape_callback(|_| AutoEscape::Html);
    env.set_loader(move |name| {
        if let Some(dir) = &custom_dir {
            if let Some(path) = safe_join(dir, name) {
                let source = std::fs::read_to_string(&path).map_err(|error| {
                    minijinja::Error::new(
                        minijinja::ErrorKind::InvalidOperation,
                        format!("cannot read template {name:?}: {error}"),
                    )
                })?;
                return Ok(Some(TemplateSource::new(source)));
            }
        }
        Ok(BUNDLED.get(name).map(|source| TemplateSource::new(*source)))
    });

    let locale = meta.get("locale").and_then(Value::as_str).unwrap_or("pt-BR").to_string();
    let currency = meta.get("currency").and_then(Value::as_str).map(str::to_string);
    env.add_function(
        "fmt",
        move |value: MjValue, mask: Option<String>, kwargs: Kwargs| -> std::result::Result<MjValue, minijinja::Error> {
            let field = kwargs.get::<Option<MjValue>>("field")?.map(|field| from_mj(&field));
            let value = from_mj(&value);
            let mask = mask.unwrap_or_else(|| "str".to_string());
            let text = format_value(&value, &mask, &locale, currency.as_deref(), field.as_ref())
                .map_err(|error| minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, error.to_string()))?;
            Ok(if mask == "sparkline" {
                MjValue::from_safe_string(text)
            } else {
                MjValue::from(text)
            })
        },
    );
    env.add_function(
        "cellstyle",
        |value: MjValue, field: MjValue| -> std::result::Result<String, minijinja::Error> {
            if field.is_undefined() || field.is_none() {
                return Ok(String::new());
            }
            let value = from_mj(&value);
            let field = from_mj(&field);
            cell_style(&value, &field).map_err(|error| minijinja::Error::new(minijinja::ErrorKind::InvalidOperation, error.to_string()))
        },
    );
    env.add_function("text_align", |value: Option<String>| -> String { text_align(value.as_deref()) });
    env.add_function(
        "zip",
        |values: Rest<MjValue>| -> std::result::Result<Vec<Vec<MjValue>>, minijinja::Error> {
            let mut sequences: Vec<Vec<MjValue>> = Vec::new();
            for value in values.iter() {
                let mut items = Vec::new();
                for item in value.try_iter()? {
                    items.push(item);
                }
                sequences.push(items);
            }
            let length = sequences.iter().map(Vec::len).min().unwrap_or(0);
            let mut out = Vec::with_capacity(length);
            for index in 0..length {
                out.push(sequences.iter().map(|sequence| sequence[index].clone()).collect());
            }
            Ok(out)
        },
    );
    Ok(env)
}

/// Render the report HTML.
pub fn render_report_html(
    dataset: &Value,
    layout: &Value,
    meta: &Value,
    template_name: &str,
    template_dir: Option<&Path>,
    inline_css: bool,
) -> Result<String> {
    let env = build_env(template_dir, meta)?;
    let template = env
        .get_template(template_name)
        .map_err(|error| template_error(template_name, error))?;
    let context = minijinja::context! {
        dataset => to_mj(dataset),
        layout => to_mj(layout),
        meta => to_mj(meta),
    };
    let html = template.render(context).map_err(|error| template_error(template_name, error))?;
    if inline_css {
        inline_css_document(&html)
    } else {
        Ok(html)
    }
}

/// Resolve `var(--name[, fallback])` from the document's `:root` values.
pub fn resolve_css_vars(html: &str) -> String {
    let mut variables: HashMap<String, String> = HashMap::new();
    for block in ROOT_BLOCK_RE.captures_iter(html) {
        let Some(body) = block.get(1) else {
            continue;
        };
        for variable in ROOT_VAR_RE.captures_iter(body.as_str()) {
            let Some(name) = variable.get(1) else {
                continue;
            };
            let Some(value) = variable.get(2) else {
                continue;
            };
            variables.insert(name.as_str().to_string(), value.as_str().trim().to_string());
        }
    }
    VAR_USE_RE
        .replace_all(html, |captures: &regex::Captures<'_>| {
            let name = captures.get(1).map(|m| m.as_str()).unwrap_or_default();
            if let Some(value) = variables.get(name) {
                return value.clone();
            }
            captures
                .get(2)
                .map(|fallback| fallback.as_str().trim().to_string())
                .unwrap_or_else(|| captures.get(0).map(|m| m.as_str()).unwrap_or_default().to_string())
        })
        .to_string()
}

/// Inline the document stylesheet (email clients).
pub fn inline_css_document(html: &str) -> Result<String> {
    let without_links = LINK_RE.replace_all(html, "").to_string();
    let resolved = resolve_css_vars(&without_links);
    #[cfg(feature = "email")]
    {
        css_inline::inline(&resolved).map_err(|error| Error::message(format!("Inline CSS failed: {error}")))
    }
    #[cfg(not(feature = "email"))]
    {
        let _ = resolved;
        Err(Error::FeatureDisabled("Inline CSS requires the 'email' feature (css-inline)"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    fn value(value: serde_json::Value) -> Value {
        Value::from_json(value)
    }

    #[test]
    fn renders_simple_tabular_html() {
        let dataset = value(json!({
            "groups": [{"fields": {"company": "ACME"}, "details": {"orders": {"rows": [{"order": 750, "total": 4000}]}}}],
            "summary": null
        }));
        let layout = value(json!({
            "groups": {
                "header": [{"name": "company", "label": "Company", "format_mask": "str", "alignment": "left"}],
                "details": {"orders": [{"name": "order", "label": "Code", "format_mask": "int", "alignment": "right"}, {"name": "total", "label": "Total", "format_mask": "float", "alignment": "right"}]}
            }
        }));
        let meta =
            value(json!({"title": "Order", "sub_title": "2024", "mode": "exact", "direction": "ltr", "printed_at": "2024-01-01 10:00"}));
        let html = render_report_html(&dataset, &layout, &meta, "tabular.jinja", None, false).unwrap();
        assert!(html.contains("Order"));
        assert!(html.contains("ACME"));
        assert!(html.contains("750"));
        assert!(html.contains("4.000,00"));
    }

    #[test]
    fn resolves_css_variables_and_strips_links() {
        let html = r#"<html><head><link rel="stylesheet" href="http://x/y.css"><style>:root { --brand-color: #123456; }</style></head><body style="color: var(--brand-color, red)"></body></html>"#;
        let resolved = resolve_css_vars(html);
        assert!(resolved.contains("#123456"));
        assert!(!resolved.contains("red"));
    }

    #[test]
    fn missing_template_dir_fails() {
        let dataset = value(json!({"groups": []}));
        let layout = value(json!({"groups": {"header": []}}));
        let meta = value(json!({"title": "T"}));
        let error = render_report_html(&dataset, &layout, &meta, "tabular.jinja", Some(Path::new("does-not-exist")), false).unwrap_err();
        assert!(error.to_string().contains("Template directory not found"));
    }

    #[test]
    fn custom_template_dir_layers_over_bundled() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join("custom.jinja"), "<html><body>CUSTOM:{{ meta.title }}</body></html>").unwrap();
        let dataset = value(json!({"groups": []}));
        let layout = value(json!({"groups": {"header": []}}));
        let meta = value(json!({"title": "Hi"}));
        let html = render_report_html(&dataset, &layout, &meta, "custom.jinja", Some(dir.path()), false).unwrap();
        assert!(html.contains("CUSTOM:Hi"));
    }

    #[test]
    fn escapes_untrusted_values() {
        let payload = value(json!({
            "meta": {"title": "<b>T</b>"},
            "data": [{"a": "<script>alert(1)</script><img src=x onerror=alert(2)>"}]
        }));
        let html = crate::api::render_html(&payload, None, "tabular.jinja", false, None).unwrap();
        assert!(!html.contains("<script>alert(1)</script>"));
        assert!(!html.contains("<img src=x"));
        assert!(html.contains("&lt;script&gt;"));
        assert!(html.contains("&lt;img"));
    }

    #[test]
    fn template_injection_is_blocked() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(
            dir.path().join("evil.jinja"),
            "{{ ().__class__.__bases__ }}|{{ [].__class__ }}|{{ meta.title }}",
        )
        .unwrap();
        let payload = value(json!({"meta": {"title": "T"}, "data": []}));
        let error = crate::api::render_html(&payload, Some(dir.path()), "evil.jinja", false, None).unwrap_err();
        assert!(error.to_string().contains("blocked"), "{error}");
    }
}