Skip to main content

umbral_core/
templates.rs

1//! Server-side HTML rendering via minijinja.
2//!
3//! Templates live under one or more directories on disk. At boot,
4//! `App::build()` assembles an ordered search list:
5//!
6//! 1. The project-level directory configured via
7//!    `AppBuilder::templates_dir` (default `./templates`).
8//! 2. Each registered plugin's `Plugin::templates_dirs()` contributions,
9//!    in topological dependency order.
10//!
11//! The first directory that contains a given template name wins. This
12//! makes cross-plugin `{% extends "base.html" %}` work automatically —
13//! the extends lookup searches every directory the same way a direct
14//! render call does. Plugin A can extend `base.html` from plugin B as
15//! long as B's directory appears in the search list.
16//!
17//! When two directories both provide a template with the same name, the
18//! first-match-wins policy applies and a `tracing::warn!` is emitted at
19//! boot so the collision is visible in the log. First-match-wins across
20//! all template directories. Silently-overridden templates are a
21//! well-known footgun, so the warning is non-optional.
22//!
23//! Rendering goes through one ambient accessor, [`render`], which reads
24//! the engine the App builder published into an `OnceLock` during build.
25//!
26//! ```ignore
27//! let html = umbral::templates::render("articles_list.html", &context!(articles))?;
28//! ```
29//!
30//! ## Autoescape
31//!
32//! Any template whose name ends in `.html` or `.htm` renders with
33//! autoescape on. Text templates (`.txt`) render verbatim. The autoescape
34//! callback extension whitelist MUST stay in sync with the loader's
35//! `load_directory` filter (currently `html | htm | txt`).
36//!
37//! ## v1 scope
38//!
39//! - One project-level templates directory (default `./templates/`,
40//!   relative to the binary's cwd) plus per-plugin directories.
41//! - Jinja2-compatible syntax via minijinja: `{% extends %}`, `{% block %}`,
42//!   `{% if %}`, `{% for %}`, `{{ value }}`, the standard filter set.
43//! - Autoescape for any template whose name ends in `.html` or `.htm`.
44//! - Init is best-effort: if no directory exists the engine boots empty.
45//!   Calls to [`render`] then return `TemplateError::Missing`.
46//!
47//! ## Deferred
48//!
49//! - Custom filters and tests registered through `Plugin::on_ready`.
50//! - Hot reload in development via `minijinja-autoreload`.
51
52use std::collections::HashSet;
53use std::future::Future;
54use std::path::{Path, PathBuf};
55use std::pin::Pin;
56use std::sync::Arc;
57use std::sync::OnceLock;
58
59use minijinja::{AutoEscape, Environment};
60use syntect::highlighting::ThemeSet;
61use syntect::html::{ClassStyle, ClassedHTMLGenerator, css_for_theme_with_class_style};
62use syntect::parsing::SyntaxSet;
63use syntect::util::LinesWithEndings;
64
65tokio::task_local! {
66    /// Per-request ambient user value, set by a session-aware layer
67    /// (typically `umbral_sessions::UserContextLayer<U>`) and read by
68    /// [`render`] to expose the current `user` in
69    /// templates. `None` means an anonymous request.
70    ///
71    /// Outside the layer's scope, `try_with` returns `Err(AccessError)`
72    /// and `render` skips the merge — explicit ctx behaviour is
73    /// preserved when no layer is installed.
74    pub static CURRENT_USER: Option<minijinja::Value>;
75
76    /// Per-request CSRF token, set by `umbral-security`'s middleware and
77    /// read by [`render`] to inject `csrf_token` / `csrf_input` into
78    /// every template, for the `{% csrf_token %}` ergonomic. Outside
79    /// the middleware's scope nothing is injected (a template that
80    /// references `{{ csrf_token }}` then renders it empty under the
81    /// engine's lenient-undefined behaviour).
82    pub static CURRENT_CSRF: Option<String>;
83
84    /// Lazy counterpart to `CURRENT_USER`: a resolver that produces the
85    /// user value on first access, memoized. Set by an auth middleware that
86    /// wants per-request laziness (resolve only if a template reads `user`).
87    pub static CURRENT_USER_LAZY: LazyUser;
88}
89
90type UserFut = Pin<Box<dyn Future<Output = minijinja::Value> + Send>>;
91type UserResolver = Arc<dyn Fn() -> UserFut + Send + Sync>;
92
93/// A lazily-resolved, per-request template `user`. The `resolver` runs at
94/// most once (guarded by the `OnceCell`); resolution happens synchronously
95/// from inside minijinja's sync render via `block_in_place`.
96///
97/// The lazy value is injected into the template context as a minijinja `Object`
98/// proxy ([`LazyUserProxy`]). Minijinja calls `get_value` on the proxy only
99/// when the template actually accesses an attribute on `user`, so requests that
100/// never render `user` skip resolution entirely.
101#[derive(Clone)]
102pub struct LazyUser {
103    cell: Arc<tokio::sync::OnceCell<minijinja::Value>>,
104    resolver: UserResolver,
105}
106
107impl LazyUser {
108    pub fn new<F, Fut>(resolver: F) -> Self
109    where
110        F: Fn() -> Fut + Send + Sync + 'static,
111        Fut: Future<Output = minijinja::Value> + Send + 'static,
112    {
113        Self {
114            cell: Arc::new(tokio::sync::OnceCell::new()),
115            resolver: Arc::new(move || Box::pin(resolver())),
116        }
117    }
118
119    /// Resolve (memoized) from a synchronous context. Requires a multi-thread
120    /// tokio runtime; on a current-thread runtime or outside any runtime it
121    /// logs and returns the anonymous value so callers fall back cleanly.
122    fn resolve_blocking(&self) -> minijinja::Value {
123        use tokio::runtime::{Handle, RuntimeFlavor};
124        let Ok(handle) = Handle::try_current() else {
125            return anonymous_user_value();
126        };
127        if handle.runtime_flavor() == RuntimeFlavor::CurrentThread {
128            tracing::warn!(
129                "umbral::templates: lazy `user` needs a multi-thread runtime; rendering anonymous"
130            );
131            return anonymous_user_value();
132        }
133        let cell = self.cell.clone();
134        let resolver = self.resolver.clone();
135        tokio::task::block_in_place(move || {
136            handle.block_on(async move { cell.get_or_init(|| resolver()).await.clone() })
137        })
138    }
139
140    /// Wrap this `LazyUser` in a minijinja `Value` proxy that resolves on
141    /// first attribute access from inside the synchronous render loop.
142    fn into_proxy_value(self) -> minijinja::Value {
143        minijinja::Value::from_object(LazyUserProxy(self))
144    }
145}
146
147/// A minijinja Object proxy that defers resolution of the user until the
148/// template actually accesses an attribute (e.g. `{{ user.is_staff }}`).
149/// Minijinja calls `get_value` for attribute access — we resolve there, not
150/// at context-merge time.
151struct LazyUserProxy(LazyUser);
152
153impl std::fmt::Debug for LazyUserProxy {
154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        f.write_str("LazyUserProxy")
156    }
157}
158
159impl std::fmt::Display for LazyUserProxy {
160    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
161        // `{{ user }}` — resolve (memoized) and delegate to the resolved
162        // value's own Display so bare rendering is faithful. Uses the same
163        // `resolve_blocking` path as `get_value` to ensure at-most-once
164        // resolution and the same current-thread / no-runtime fallback.
165        let resolved = self.0.resolve_blocking();
166        std::fmt::Display::fmt(&resolved, f)
167    }
168}
169
170impl minijinja::value::Object for LazyUserProxy {
171    fn get_value(self: &Arc<Self>, key: &minijinja::Value) -> Option<minijinja::Value> {
172        let resolved = self.0.resolve_blocking();
173        resolved.get_item(key).ok()
174    }
175
176    fn is_true(self: &Arc<Self>) -> bool {
177        // `{% if user %}` — resolve (memoized) and delegate to the resolved
178        // value's truthiness so the proxy faithfully represents whether the
179        // resolved value is truthy. Uses the same `resolve_blocking` path as
180        // `get_value` so resolution is still at most once per request.
181        self.0.resolve_blocking().is_true()
182    }
183}
184
185/// Scope a lazy `user` resolver for the duration of `fut`.
186pub async fn with_current_user_lazy<F: Future>(lazy: LazyUser, fut: F) -> F::Output {
187    CURRENT_USER_LAZY.scope(lazy, fut).await
188}
189
190/// Run `fut` with the ambient template user value scoped to `user`
191/// for its duration. Intended for the session-aware layer in
192/// `umbral-sessions`; downstream handler code reads the value
193/// transparently through [`render`].
194pub async fn with_current_user<F: std::future::Future>(
195    user: Option<minijinja::Value>,
196    fut: F,
197) -> F::Output {
198    CURRENT_USER.scope(user, fut).await
199}
200
201/// Run `fut` with the ambient CSRF token scoped for its duration.
202/// Intended for the CSRF middleware in `umbral-security`; downstream
203/// handler code reads the value transparently through [`render`]
204/// (as `{{ csrf_token }}` / `{{ csrf_input }}`) or [`current_csrf`].
205pub async fn with_current_csrf<F: std::future::Future>(token: Option<String>, fut: F) -> F::Output {
206    CURRENT_CSRF.scope(token, fut).await
207}
208
209/// Read the ambient CSRF token, if a middleware has scoped one for
210/// this request. Non-template consumers (e.g. the admin's login form
211/// builder) use this to embed the same token the middleware minted,
212/// instead of minting their own.
213pub fn current_csrf() -> Option<String> {
214    CURRENT_CSRF.try_with(|t| t.clone()).ok().flatten()
215}
216
217/// Watched template directories captured at `init` time. Stored
218/// separately so the dev-mode render path can rebuild the environment
219/// from the same sources without re-publishing the OnceLock.
220static WATCHED_DIRS: OnceLock<Vec<PathBuf>> = OnceLock::new();
221use serde::Serialize;
222
223static ENGINE: OnceLock<Environment<'static>> = OnceLock::new();
224
225/// A plugin-contributed mutation of the template [`Environment`]: adds
226/// custom filters, functions, or globals at engine-build time
227/// (feature #67 - custom template tags/filters). Returned by
228/// `Plugin::template_registrars` and stored process-wide so the dev-mode
229/// hot-reload rebuild re-applies it.
230///
231/// It is `Fn` (not `FnOnce`) on purpose: in dev mode the engine is
232/// rebuilt on every template edit, so each registrar runs once per build.
233/// Make it owned and `'static` (no borrows of the plugin) so it survives
234/// in the [`REGISTRARS`] handle past `App::build`.
235pub type TemplateRegistrar = Box<dyn Fn(&mut Environment<'static>) + Send + Sync>;
236
237/// Plugin-contributed [`TemplateRegistrar`]s captured at `init_with` time.
238/// Stored separately from [`ENGINE`] so the dev-mode rebuild path (which
239/// goes through [`build_env`]) re-applies them without the App builder.
240static REGISTRARS: OnceLock<Vec<TemplateRegistrar>> = OnceLock::new();
241
242/// Register the built-in default 404/500 templates into an environment.
243///
244/// Called from `init` before any disk directories are scanned. The names
245/// use the `__umbral__/` prefix so they can never collide with a user's
246/// `templates/` directory (slashes aren't meaningful to the engine's name
247/// lookup — `__umbral__/default_404.html` is just a unique string key).
248///
249/// Because the user's disk directories are added after this call and
250/// first-match-wins is enforced by the `seen` set, a user who places a
251/// file named `__umbral__/default_404.html` in their own templates dir will
252/// silently replace the built-in — which is the intended escape hatch.
253/// (Callers who want a cleaner opt-out should use
254/// `App::builder().disable_default_error_pages()` instead.)
255/// gaps2 #21 — register the `img` MiniJinja filter that turns a URL
256/// into a fully-formed, performance-correct `<img>` tag.
257///
258/// Filter signature:
259///   `{{ url | img(alt="…", width=N, height=N, class="…") }}`
260///
261/// Output shape:
262///   `<img src="<url>" alt="<alt>" loading="lazy" decoding="async"
263///        width="<w>" height="<h>" class="<class>">`
264///
265/// Why this set of attributes:
266/// - `loading="lazy"` — the gap's primary ask. Browsers defer
267///   off-viewport image fetches until they're about to be needed,
268///   shrinking LCP + initial bandwidth.
269/// - `decoding="async"` — lets the browser decode the image off
270///   the main thread; prevents render-blocking decode work on
271///   slower devices.
272/// - explicit `width`/`height` (when provided) reserves layout
273///   space immediately so lazy-loading doesn't cause CLS
274///   (cumulative layout shift). Omitted if either is missing.
275/// - empty `alt=""` default is screen-reader-friendly for
276///   decorative images. Callers SHOULD pass a real `alt` for
277///   meaningful content images.
278///
279/// What's NOT included on day one (deferred to a later slice):
280/// - `srcset` for responsive resolutions — needs the on-the-fly
281///   resize handler (gap 21 Option C) before the filter knows
282///   real asset dimensions.
283/// - `<picture>` with `webp`/`avif` sources — same blocker; the
284///   transcode endpoint has to exist first.
285///
286/// Output is wrapped in `minijinja::value::Value::from_safe_string`
287/// so MiniJinja's autoescape doesn't double-escape the `<` / `>`
288/// characters — the attribute values themselves still go through
289/// `html_escape` so a hostile alt-text can't break out of the
290/// attribute quote.
291/// True when `url` is safe to place in an `<img src>`: a relative URL
292/// (no scheme) or an `http`/`https` absolute URL. Any other scheme
293/// (`javascript:`, `data:`, `vbscript:`, …) is rejected. Fails closed:
294/// a malformed scheme (embedded control chars, spaces) is also rejected.
295fn url_scheme_is_safe(url: &str) -> bool {
296    let trimmed = url.trim();
297    // A URL scheme is the run before the first ':' — but only if no
298    // '/', '?', '#' appears first (those mean a relative path/query).
299    let mut scheme_end = None;
300    for (i, c) in trimmed.char_indices() {
301        match c {
302            ':' => {
303                scheme_end = Some(i);
304                break;
305            }
306            '/' | '?' | '#' => break,
307            _ => {}
308        }
309    }
310    let Some(end) = scheme_end else {
311        return true; // no scheme → relative URL → safe
312    };
313    let scheme = &trimmed[..end];
314    // A real scheme is alpha then [a-z0-9+.-]*. Anything else is suspicious.
315    let mut chars = scheme.chars();
316    let well_formed = matches!(chars.next(), Some(c) if c.is_ascii_alphabetic())
317        && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '.' | '-'));
318    if !well_formed {
319        return false;
320    }
321    let lower = scheme.to_ascii_lowercase();
322    lower == "http" || lower == "https"
323}
324
325fn register_img_filter(env: &mut Environment<'static>) {
326    env.add_filter(
327        "img",
328        |url: String,
329         kwargs: minijinja::value::Kwargs|
330         -> Result<minijinja::Value, minijinja::Error> {
331            let alt: String = kwargs.get::<Option<String>>("alt")?.unwrap_or_default();
332            let width: Option<i64> = kwargs.get("width")?;
333            let height: Option<i64> = kwargs.get("height")?;
334            let class: Option<String> = kwargs.get("class")?;
335            // Accept the extras even when the call doesn't pass them
336            // — kwargs.get returns Ok(None) for absent keys but
337            // .assert_all_used() at the end will catch a typo'd
338            // `alt_text` so the user gets a clear error instead of
339            // silent drop. Matches the rest of the framework's
340            // strict-input posture.
341            kwargs.assert_all_used()?;
342
343            // Defense-in-depth: never emit a `javascript:` / `data:` /
344            // other non-http(s) scheme into `src`. Not a live XSS (browsers
345            // don't run JS from `<img src>` and the value is HTML-escaped),
346            // but a hostile stored URL has no business here. A disallowed
347            // scheme neutralises to an empty src (broken image) rather than
348            // erroring the whole page on user data.
349            let url = if url_scheme_is_safe(&url) {
350                url
351            } else {
352                String::new()
353            };
354
355            let mut out = String::with_capacity(url.len() + 128);
356            out.push_str("<img src=\"");
357            html_escape_into(&mut out, &url);
358            out.push_str("\" alt=\"");
359            html_escape_into(&mut out, &alt);
360            out.push_str("\" loading=\"lazy\" decoding=\"async\"");
361            if let Some(w) = width {
362                out.push_str(" width=\"");
363                out.push_str(&w.to_string());
364                out.push('"');
365            }
366            if let Some(h) = height {
367                out.push_str(" height=\"");
368                out.push_str(&h.to_string());
369                out.push('"');
370            }
371            if let Some(c) = class {
372                if !c.is_empty() {
373                    out.push_str(" class=\"");
374                    html_escape_into(&mut out, &c);
375                    out.push('"');
376                }
377            }
378            out.push('>');
379            Ok(minijinja::Value::from_safe_string(out))
380        },
381    );
382}
383
384/// features.md #4 — register the `markdown` filter that turns a
385/// CommonMark + GFM string into sanitized HTML.
386///
387/// Filter signature: `{{ body | markdown }}`.
388///
389/// Pipeline:
390/// 1. `pulldown-cmark` parses the input with GFM extensions on
391///    (tables, strikethrough, task lists, footnotes) and renders to
392///    HTML.
393/// 2. `ammonia` sanitizes that HTML — strips `<script>`, inline event
394///    handlers (`onerror=`, `onclick=`), `javascript:` URLs, and any
395///    tag/attribute outside its safe allowlist. This is the security
396///    boundary: user-supplied markdown (plugin bodies, usage docs,
397///    reviews) is rendered, never trusted.
398/// 3. The result is wrapped in `Value::from_safe_string` so MiniJinja's
399///    autoescape emits the generated tags as markup instead of
400///    re-escaping them into `&lt;...&gt;`.
401///
402/// Why sanitize after rendering rather than trusting the parser: raw
403/// HTML embedded in a markdown source (`<script>...`) passes straight
404/// through pulldown-cmark by design. ammonia is the layer that makes
405/// "render whatever the user typed" safe.
406///
407/// Deferred (separate slices): syntax highlighting on fenced code
408/// blocks (ammonia strips the `language-*` class today) and a
409/// configurable allowlist for embeds — see the gap entries.
410/// Register the global `static()` template function so templates can
411/// write `{{ static("admin/admin.css") }}` and get back a URL prefixed
412/// with the configured `static_url`.
413///
414/// `static_url` is captured into the closure when the environment is
415/// built (rather than read per-call) — the value is fixed for the
416/// process at `App::build()` time, and minijinja functions can't reach
417/// the ambient `Settings` directly. The dev-mode render path rebuilds
418/// the env per render via [`build_env`], so a `static_url` change would
419/// be picked up there too; in practice it never changes at runtime.
420///
421/// Resolution joins `static_url` and the argument with exactly one
422/// slash: a leading slash on the argument (`static("/admin/x")`) is
423/// trimmed so the result never double-slashes. With the default
424/// `static_url = "/static/"`, `static("admin/admin.css")` yields
425/// `"/static/admin/admin.css"`; with a CDN origin
426/// `static_url = "https://cdn.example.com/s/"` it yields
427/// `"https://cdn.example.com/s/admin/admin.css"`.
428/// A generated URL, returned to the template as SAFE unless it contains a character that
429/// could break out of the attribute it lands in (gaps3 #66).
430///
431/// `static()` and `media_url()` used to return a plain `String`, which minijinja
432/// autoescapes in HTML context — so `{{ static('css/app.css') }}` rendered as
433/// `href="&#x2f;static&#x2f;css&#x2f;app.css"`. Browsers decode `&#x2f;` back to `/`, so
434/// the stylesheet still loaded and the pages still looked right; it was working by
435/// accident, and any reader of the page source would reasonably conclude static serving
436/// was broken.
437///
438/// Marking the URL safe is what fixes it — but marking it *unconditionally* safe would be
439/// an XSS hole: `media_url(key)` takes a key that came from an uploaded filename, i.e.
440/// from a user, and a key containing `"` closes the `href` attribute. So a URL carrying
441/// any HTML-special character stays escaped. The path a template author writes by hand
442/// (`css/app.css`) never contains one; a hostile filename does, and it keeps its armour.
443pub fn safe_url(url: String) -> minijinja::Value {
444    if url.contains(['<', '>', '"', '\'', '&']) {
445        minijinja::Value::from(url)
446    } else {
447        minijinja::Value::from_safe_string(url)
448    }
449}
450
451fn register_static_function(env: &mut Environment<'static>, static_url: String) {
452    env.add_function("static", move |path: String| -> minijinja::Value {
453        // Route through the manifest-aware resolver so a `--hashed`
454        // collect makes `{{ static("css/app.css") }}` emit the
455        // content-hashed URL. The captured `static_url` is the fixed
456        // prefix; the manifest lookup is the only per-call ambient read.
457        if let Some(hashed) = crate::static_files::manifest_lookup(&path) {
458            return safe_url(join_static_url(&static_url, hashed));
459        }
460        safe_url(join_static_url(&static_url, &path))
461    });
462}
463
464/// Join a `static_url` prefix and an asset path with exactly one slash.
465///
466/// `static_url` is normalised to end in a slash by [`crate::settings`];
467/// the asset path may or may not lead with one, so its leading slash is
468/// trimmed before the join. With `static_url = "/static/"`,
469/// `join_static_url(.., "admin/admin.css")` yields
470/// `"/static/admin/admin.css"`.
471fn join_static_url(static_url: &str, path: &str) -> String {
472    format!("{}{}", static_url, path.trim_start_matches('/'))
473}
474
475/// Resolve an asset path against the ambient `static_url`, mirroring the
476/// `static()` template global outside a minijinja render.
477///
478/// Plugins that build their own minijinja [`Environment`] (the admin
479/// engine, for one) call this to register an equivalent `static()`
480/// function so their templates can write `{{ static("admin/admin.css") }}`
481/// and resolve through the same unified static pipeline URL as the core
482/// engine. Reads `static_url` from ambient [`crate::settings`], defaulting
483/// to `/static/` when settings aren't initialised yet (bare unit tests).
484pub fn resolve_static_url(path: &str) -> String {
485    let static_url = crate::settings::get_opt()
486        .map(|s| s.static_url.clone())
487        .unwrap_or_else(|| "/static/".to_string());
488
489    // Manifest cache-busting (hashed static-file storage): when
490    // `collectstatic --hashed` has run, a `staticfiles.json` maps the
491    // logical path the template wrote (`css/app.css`) to its
492    // content-hashed name (`css/app.<hash>.css`). Resolving to the hashed
493    // URL lets the asset carry far-future cache headers — the hash in the
494    // name changes whenever the bytes do, so a stale cache can never mask
495    // a new build. When no manifest is loaded (no `--hashed` run), the
496    // lookup misses and we serve the plain path exactly as before.
497    if let Some(hashed) = crate::static_files::manifest_lookup(path) {
498        return join_static_url(&static_url, hashed);
499    }
500
501    join_static_url(&static_url, path)
502}
503
504/// Register the global `media_url()` template function so a template can
505/// write `{{ media_url(plugin.logo) }}` and get back the public URL for a
506/// stored file/image KEY, resolved through the ambient
507/// [`crate::storage::Storage`] backend.
508///
509/// Mirrors the `static()` global ([`register_static_function`]) but for
510/// user-uploaded media instead of developer-shipped assets:
511/// `ImageField` / `FileField` serialize as the bare storage key, so
512/// `{{ media_url(plugin.logo) }}` (where `plugin.logo` is the key string)
513/// resolves to the storage backend's public URL.
514///
515/// - An empty key yields the empty string (the surrounding `{% if %}`
516///   guard skips the markup).
517/// - With no `Storage` backend registered, the raw key falls through
518///   unchanged.
519/// - A `None`/optional field serializes to null, which the template's
520///   `{% if %}` guard handles before the helper is ever called.
521fn register_media_url_function(env: &mut Environment<'static>) {
522    env.add_function("media_url", |key: String| -> minijinja::Value {
523        if key.is_empty() {
524            return minijinja::Value::from("");
525        }
526        let url = crate::storage::storage_opt()
527            .map(|s| s.url(&key))
528            .unwrap_or(key);
529        // NOTE: `key` is an uploaded filename — user-controlled. `safe_url` keeps the
530        // escaping on any URL carrying an HTML-special character, so a hostile name
531        // cannot break out of the attribute.
532        safe_url(url)
533    });
534}
535
536/// Register the `{{ querystring_with(current_query, key, value) }}` global
537/// (gaps/features #65 — template pagination). Rebuilds a querystring
538/// replacing one key while preserving every other parameter, the fiddly bit
539/// behind a pagination nav that has to carry `?sort=name` across every
540/// `?page=N` link. Backed by [`crate::pagination::querystring_with`] so the
541/// encode/replace logic stays in one place and is unit-tested there. The
542/// returned string has no leading `?`; the template prepends one.
543fn register_querystring_with_function(env: &mut Environment<'static>) {
544    env.add_function(
545        "querystring_with",
546        // `value` is a `minijinja::Value`, not a `String`: the nav passes
547        // `page.next_page_number` / `item.n`, which are integers, and
548        // minijinja does NOT auto-coerce an int arg into a `String`
549        // parameter — it'd raise a type error at render. Accepting `Value`
550        // and stringifying covers ints, strings, and bools uniformly.
551        |current_query: String, key: String, value: minijinja::Value| -> String {
552            crate::pagination::querystring_with(&current_query, &key, &value.to_string())
553        },
554    );
555}
556
557fn register_markdown_filter(env: &mut Environment<'static>) {
558    env.add_filter("markdown", |input: String| -> minijinja::Value {
559        minijinja::Value::from_safe_string(render_markdown(&input))
560    });
561}
562
563/// Register the `{{ highlight_styles() }}` global: emits the generated
564/// `base16-ocean.dark` token stylesheet wrapped in a `<style>` block, for a
565/// base template to drop into `<head>` once. The CSS is a safe string
566/// (generated by syntect from a fixed theme, no user input), so it is
567/// marked safe to skip minijinja autoescape.
568fn register_highlight_styles_function(env: &mut Environment<'static>) {
569    env.add_function("highlight_styles", || -> minijinja::Value {
570        minijinja::Value::from_safe_string(format!("<style>{}</style>", highlight_css()))
571    });
572}
573
574/// features.md #67 — `{{ now() }}` / `{{ now("%Y-%m-%d") }}`. Renders the
575/// current UTC time, optionally via a chrono `strftime` format string.
576/// With no argument it emits RFC 3339 (e.g. `2026-06-13T10:30:00+00:00`).
577/// The reference built-in tag for the custom-tag surface.
578fn register_now_function(env: &mut Environment<'static>) {
579    env.add_function("now", |fmt: Option<String>| -> String {
580        let now = chrono::Utc::now();
581        match fmt {
582            Some(f) if !f.is_empty() => now.format(&f).to_string(),
583            _ => now.to_rfc3339(),
584        }
585    });
586}
587
588/// features.md #67 — `{{ price | currency }}` / `{{ price | currency("EUR") }}`.
589/// Formats a number as money: two decimals, thousands grouping, and a
590/// leading symbol for the common ISO codes (USD/EUR/GBP/JPY); an unknown
591/// code falls back to `1,234.56 CODE`. The reference built-in filter.
592fn register_currency_filter(env: &mut Environment<'static>) {
593    env.add_filter("currency", |amount: f64, code: Option<String>| -> String {
594        let code = code.unwrap_or_else(|| "USD".to_string());
595        let symbol = match code.as_str() {
596            "USD" | "AUD" | "CAD" | "NZD" => "$",
597            "EUR" => "€",
598            "GBP" => "£",
599            "JPY" | "CNY" => "¥",
600            "KES" => "KSh ",
601            _ => "",
602        };
603        // Sign goes outside the symbol: -$12.40, not $-12.40.
604        let sign = if amount < 0.0 { "-" } else { "" };
605        let body = group_thousands(amount.abs());
606        if symbol.is_empty() {
607            format!("{sign}{body} {code}")
608        } else {
609            format!("{sign}{symbol}{body}")
610        }
611    });
612}
613
614/// Format a float with two decimals and comma thousands separators on the
615/// integer part: `1234567.5 -> "1,234,567.50"`, `-12.4 -> "-12.40"`.
616fn group_thousands(amount: f64) -> String {
617    let negative = amount.is_sign_negative() && amount != 0.0;
618    let formatted = format!("{:.2}", amount.abs());
619    let (int_part, frac_part) = formatted.split_once('.').unwrap_or((&formatted, "00"));
620
621    let mut grouped = String::new();
622    let digits: Vec<char> = int_part.chars().collect();
623    for (i, ch) in digits.iter().enumerate() {
624        if i > 0 && (digits.len() - i) % 3 == 0 {
625            grouped.push(',');
626        }
627        grouped.push(*ch);
628    }
629    format!("{}{grouped}.{frac_part}", if negative { "-" } else { "" })
630}
631
632/// features.md #4 — register the `sanitize` filter: clean a string of
633/// HTML (e.g. the output of the admin's RTE widget, which stores
634/// HTML rather than markdown) down to ammonia's safe allowlist and
635/// hand it to the template as a safe string.
636///
637/// `{{ body | sanitize }}` is the display companion to the `rte`
638/// widget the way `{{ body | markdown }}` is to the `markdown` widget:
639/// the stored value is HTML, so it's sanitized — never trusted — before
640/// it reaches the page. A value tampered with via the REST write path
641/// (which doesn't go through the editor) is made safe here.
642fn register_sanitize_filter(env: &mut Environment<'static>) {
643    env.add_filter("sanitize", |input: String| -> minijinja::Value {
644        minijinja::Value::from_safe_string(sanitize_html(&input))
645    });
646}
647
648/// Clean `input` HTML down to ammonia's safe allowlist (strips
649/// `<script>`, event handlers, `javascript:` URLs, etc.). The
650/// non-markdown sibling of [`render_markdown`] — use it on stored HTML
651/// (the RTE widget's output).
652pub fn sanitize_html(input: &str) -> String {
653    ammonia::clean(input)
654}
655
656/// The class prefix syntect token spans carry (`hl-keyword`, `hl-string`,
657/// `hl-source`, …). Shared by the highlighter and the generated
658/// stylesheet so the two never drift.
659const HL_PREFIX: &str = "hl-";
660
661fn hl_class_style() -> ClassStyle {
662    ClassStyle::SpacedPrefixed { prefix: HL_PREFIX }
663}
664
665/// The bundled syntect syntax set, loaded once. The load parses a binary
666/// dump and is expensive, so it is cached for the life of the process.
667fn syntax_set() -> &'static SyntaxSet {
668    static SYNTAX_SET: OnceLock<SyntaxSet> = OnceLock::new();
669    SYNTAX_SET.get_or_init(SyntaxSet::load_defaults_newlines)
670}
671
672/// The `base16-ocean.dark` token stylesheet, generated once from syntect's
673/// bundled theme with the `hl-` class prefix. This is the single source of
674/// truth for token colors — the markdown highlighter emits matching
675/// classes. Returns `""` only if syntect cannot generate the CSS (it
676/// always can for a bundled theme), so callers never need to handle an
677/// error.
678pub fn highlight_css() -> &'static str {
679    static HIGHLIGHT_CSS: OnceLock<String> = OnceLock::new();
680    HIGHLIGHT_CSS
681        .get_or_init(|| {
682            let themes = ThemeSet::load_defaults();
683            match themes.themes.get("base16-ocean.dark") {
684                Some(theme) => {
685                    css_for_theme_with_class_style(theme, hl_class_style()).unwrap_or_default()
686                }
687                None => String::new(),
688            }
689        })
690        .as_str()
691}
692
693/// Return `true` iff every character in a fence info token is safe to
694/// embed verbatim in a `class="language-…"` HTML attribute value.
695///
696/// A legitimate language token is just a word: `rust`, `c++`, `c#`,
697/// `shell`, `text/plain`, etc. It never needs `<`, `>`, `"`, `'`, `=`,
698/// backticks, or whitespace. Rejecting those characters closes the
699/// class-injection vector that would otherwise let a hostile fence like
700/// `` ```<script>alert(1)</script> `` survive ammonia's pass (ammonia
701/// allows `class` on `<code>` but does not filter the attribute VALUE).
702fn fence_lang_is_safe(lang: &str) -> bool {
703    !lang.is_empty()
704        && lang.len() <= 64
705        && lang.chars().all(|c| {
706            c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '_' | '.' | '#' | '/' | '@')
707        })
708}
709
710/// Render one fenced code block to safe HTML. `lang` is the fence info
711/// token (`Some("rust")`) or `None` for an unlabelled / indented block.
712/// With a known language the body is syntect-highlighted into `hl-` token
713/// spans; otherwise — or on any highlighter error — it falls back to a
714/// plain escaped block that still carries `class="language-…"` so the
715/// `md-enhance.js` label keeps working. Never panics, never drops the
716/// user's code.
717fn highlight_code_block(lang: Option<&str>, src: &str) -> String {
718    // Validate the lang token before touching it. A hostile fence info
719    // string (e.g. `<script>alert(1)</script>`) must never land in the
720    // `class="language-…"` attribute value even after HTML-escaping,
721    // because ammonia re-parses the tree and may not re-escape `<`/`>`
722    // that appear inside attribute values of allowed elements. Treating
723    // an unsafe token as `None` produces a plain unlabelled code block
724    // (still safe and still readable) rather than a class-injection path.
725    let lang = lang.filter(|l| fence_lang_is_safe(l));
726
727    let ss = syntax_set();
728    let syntax = lang.and_then(|l| {
729        ss.find_syntax_by_token(l)
730            .or_else(|| ss.find_syntax_by_extension(l))
731    });
732    if let Some(syntax) = syntax {
733        let mut generator =
734            ClassedHTMLGenerator::new_with_class_style(syntax, ss, hl_class_style());
735        let mut ok = true;
736        for line in LinesWithEndings::from(src) {
737            if generator
738                .parse_html_for_line_which_includes_newline(line)
739                .is_err()
740            {
741                ok = false;
742                break;
743            }
744        }
745        if ok {
746            // `finalize()` returns safe `<span class="hl-…">` markup —
747            // pass it through unescaped.
748            return wrap_code_block(lang, &generator.finalize());
749        }
750    }
751    // Fallback: escape the raw text so it is inert, then wrap.
752    let mut escaped = String::with_capacity(src.len());
753    html_escape_into(&mut escaped, src);
754    wrap_code_block(lang, &escaped)
755}
756
757/// Wrap inner code HTML (token spans, or escaped plain text) in
758/// `<pre><code class="language-…">` so the md-enhance frame + language
759/// label attach. The language token is HTML-escaped before it lands in the
760/// class value (it comes straight from the fence info string).
761fn wrap_code_block(lang: Option<&str>, inner: &str) -> String {
762    let mut out = String::with_capacity(inner.len() + 48);
763    out.push_str("<pre><code");
764    if let Some(l) = lang {
765        out.push_str(" class=\"language-");
766        html_escape_into(&mut out, l);
767        out.push('"');
768    }
769    out.push('>');
770    out.push_str(inner);
771    out.push_str("</code></pre>");
772    out
773}
774
775/// Render CommonMark + GFM `input` to sanitized HTML. Pulled out of the
776/// filter closure so it's unit-testable and reusable by any future
777/// Rust-side caller (e.g. a REST endpoint that returns pre-rendered
778/// HTML).
779pub fn render_markdown(input: &str) -> String {
780    use pulldown_cmark::{CodeBlockKind, Event, Options, Parser, Tag, TagEnd, html};
781
782    let mut options = Options::empty();
783    options.insert(Options::ENABLE_TABLES);
784    options.insert(Options::ENABLE_STRIKETHROUGH);
785    options.insert(Options::ENABLE_TASKLISTS);
786    options.insert(Options::ENABLE_FOOTNOTES);
787
788    let parser = Parser::new_ext(input, options);
789
790    // Rewrite the event stream: replace each code block with a single
791    // pre-highlighted Html event. The fence info token selects the syntect
792    // syntax; everything else passes through unchanged.
793    let mut events: Vec<Event> = Vec::new();
794    let mut in_code = false;
795    let mut code_lang: Option<String> = None;
796    let mut code_buf = String::new();
797    for event in parser {
798        match event {
799            Event::Start(Tag::CodeBlock(kind)) => {
800                in_code = true;
801                code_buf.clear();
802                code_lang = match kind {
803                    CodeBlockKind::Fenced(info) => {
804                        info.split_whitespace().next().map(str::to_string)
805                    }
806                    CodeBlockKind::Indented => None,
807                };
808            }
809            Event::End(TagEnd::CodeBlock) => {
810                in_code = false;
811                let highlighted = highlight_code_block(code_lang.as_deref(), &code_buf);
812                events.push(Event::Html(highlighted.into()));
813            }
814            Event::Text(text) if in_code => code_buf.push_str(&text),
815            other => events.push(other),
816        }
817    }
818
819    let mut rendered = String::new();
820    html::push_html(&mut rendered, events.into_iter());
821
822    // Sanitize. `pre`/`code`/`span` are already default-allowed tags, so we
823    // widen the allowlist by exactly one inert attribute — `class` on those
824    // three — letting syntect's `hl-` token spans and the `language-*` label
825    // survive. style / on* handlers / javascript: URLs stay stripped: this is
826    // the whole "safely" surface. Built per call: ammonia::Builder isn't Sync
827    // (boxed attribute_filter), so it can't be a shared static without a Mutex
828    // that would serialize rendering; this costs the same as ammonia::clean.
829    let mut cleaner = ammonia::Builder::default();
830    cleaner.add_tag_attributes("pre", &["class"]);
831    cleaner.add_tag_attributes("code", &["class"]);
832    cleaner.add_tag_attributes("span", &["class"]);
833    cleaner.clean(&rendered).to_string()
834}
835
836/// Tiny HTML attribute-value escape — covers the four characters
837/// that can break out of a double-quoted attribute context.
838/// Centralised here because the framework doesn't otherwise need
839/// to ship an html_escape crate dep just for the img filter.
840fn html_escape_into(out: &mut String, s: &str) {
841    for ch in s.chars() {
842        match ch {
843            '&' => out.push_str("&amp;"),
844            '<' => out.push_str("&lt;"),
845            '>' => out.push_str("&gt;"),
846            '"' => out.push_str("&quot;"),
847            '\'' => out.push_str("&#39;"),
848            c => out.push(c),
849        }
850    }
851}
852
853fn register_default_templates(
854    env: &mut Environment<'static>,
855    seen: &mut std::collections::HashSet<String>,
856) {
857    let entries = [
858        (
859            crate::errors::DEFAULT_404_TEMPLATE_NAME,
860            crate::errors::DEFAULT_404_HTML,
861        ),
862        (
863            crate::errors::DEFAULT_500_TEMPLATE_NAME,
864            crate::errors::DEFAULT_500_HTML,
865        ),
866    ];
867    for (name, source) in entries {
868        if seen.contains(name) {
869            continue; // already provided by user — skip
870        }
871        // These are compile-time constants so they're `&'static str`; we can
872        // add them without cloning via `add_template` (non-owned variant).
873        if env.add_template(name, source).is_ok() {
874            seen.insert(name.to_string());
875        }
876    }
877}
878
879/// Publish the template engine into the process-wide ambient handle.
880///
881/// `dirs` is the ordered list of directories to search — the first
882/// entry is searched first (highest priority). Typically this is:
883/// `[app_templates_dir, plugin_a_dir, plugin_b_dir, ...]`.
884///
885/// For each directory in order, every `.html` / `.htm` / `.txt` file is
886/// registered under its path-relative-to-that-dir name. If a name was
887/// already registered by an earlier directory, the later file is skipped
888/// and a `tracing::warn!` is emitted so the collision is visible.
889///
890/// If none of the directories exist, init succeeds with an empty engine.
891/// This is the right default for binaries that don't render HTML.
892///
893/// Returns the list of template names that collided (appeared in more
894/// than one directory). The caller (`App::build`) logs these via tracing.
895/// Tests can inspect the returned list to assert collision detection
896/// without needing a tracing subscriber.
897pub fn init(dirs: &[PathBuf]) -> Result<Vec<String>, TemplateError> {
898    let (env, collisions) = build_env(dirs)?;
899
900    for name in &collisions {
901        tracing::warn!(
902            template = %name,
903            "umbral templates: template `{name}` is provided by multiple directories; \
904             the first-registered copy wins"
905        );
906    }
907
908    // Stash the dirs so the dev-mode render path can rebuild the env
909    // on demand without re-running the (more expensive) init flow.
910    let _ = WATCHED_DIRS.set(dirs.to_vec());
911
912    ENGINE
913        .set(env)
914        .map_err(|_| TemplateError::AlreadyInitialised)?;
915    Ok(collisions)
916}
917
918/// Like [`init`], but also installs plugin-contributed
919/// [`TemplateRegistrar`]s (feature #67). The registrars are stashed in
920/// the process-wide [`REGISTRARS`] handle *before* the engine is built so
921/// [`build_env`] applies them — both here and on every dev-mode rebuild.
922///
923/// Called by `App::build` with the flattened registrars from every
924/// plugin's `template_registrars()`, in topological order. The plain
925/// [`init`] stays the no-plugin entry point used by template unit tests.
926pub fn init_with(
927    dirs: &[PathBuf],
928    registrars: Vec<TemplateRegistrar>,
929) -> Result<Vec<String>, TemplateError> {
930    // Set even when empty so a second (errant) init can't smuggle in a
931    // different registrar set behind the already-published engine.
932    let _ = REGISTRARS.set(registrars);
933    init(dirs)
934}
935
936/// Build a fresh `Environment` from the given dirs. Shared by the
937/// init path and the dev-mode hot-reload path; both produce
938/// bit-identical engines from the same input.
939fn build_env(dirs: &[PathBuf]) -> Result<(Environment<'static>, Vec<String>), TemplateError> {
940    let mut env = Environment::new();
941    // Autoescape extensions MUST stay in sync with the loader
942    // whitelist in `load_directory` (currently `html | htm | txt`).
943    // If you add `.svg` or `.xml` to the loader, add them HERE too
944    // — `.svg` carries inline-script XSS risk and `.xml` is generally
945    // parsed by something downstream that wants attribute escaping.
946    // `.txt` stays `None` because plaintext rendering shouldn't HTML-
947    // escape (would replace `<` with `&lt;` in plain email bodies).
948    env.set_auto_escape_callback(|name| {
949        if name.ends_with(".html") || name.ends_with(".htm") {
950            AutoEscape::Html
951        } else {
952            AutoEscape::None
953        }
954    });
955
956    // gaps2 #21 — register the `img` filter for ergonomic, perf-
957    // forward image markup. `{{ url | img(alt="...", width=400,
958    // height=300) }}` expands to a fully-formed `<img>` with the
959    // hat-trick that catches LCP regressions out of the box:
960    // `loading="lazy"`, `decoding="async"`, explicit `width`/
961    // `height` to reserve layout space (no CLS), and an `alt`
962    // attribute that's empty rather than omitted (screen-reader-
963    // friendly default for purely decorative images). Optional
964    // `class="..."` flows through for Tailwind / scoped styling.
965    register_img_filter(&mut env);
966
967    // `{{ highlight_styles() }}` — the syntect token stylesheet for
968    // server-highlighted code, emitted once into <head> by a base template.
969    register_highlight_styles_function(&mut env);
970
971    // Unified static pipeline — `{{ static("admin/admin.css") }}`
972    // expands to `<static_url>admin/admin.css`. The `static_url` is read
973    // from ambient settings (defaulting to `/static/` when settings
974    // aren't initialised yet, e.g. in a bare template unit test) and
975    // captured into the function closure. See `register_static_function`.
976    let static_url = crate::settings::get_opt()
977        .map(|s| s.static_url.clone())
978        .unwrap_or_else(|| "/static/".to_string());
979    register_static_function(&mut env, static_url);
980
981    // `{{ media_url(plugin.logo) }}` resolves a stored file/image KEY
982    // through the ambient Storage backend's `url()`, the media-side
983    // companion to `static()`. ImageField/FileField serialize as the
984    // bare key; this turns it into the public URL. See
985    // `register_media_url_function`.
986    register_media_url_function(&mut env);
987
988    // features.md #4 — `{{ body | markdown }}` renders user-supplied
989    // CommonMark/GFM to sanitized HTML. The reusable "safely show a
990    // body/usage field" surface shared by the admin and end-user
991    // templates; pairs with `#[umbral(widget = "markdown")]` on the
992    // model field that captures the source.
993    register_markdown_filter(&mut env);
994
995    // features.md #4 — `{{ html | sanitize }}` cleans stored HTML (the
996    // `rte` admin widget's output) to a safe allowlist. The HTML-side
997    // companion to the markdown filter.
998    register_sanitize_filter(&mut env);
999
1000    // gaps2 #19 follow-up — render `None` / `Undefined` as the
1001    // empty string instead of the literal "none" / "undefined" tokens
1002    // MiniJinja defaults to. Bug screenshot 2026-06-10 01-08-30: an
1003    // `Option<String>` model field with `value=None` rendered into
1004    // `<input value="{{ form.phone }}">` produced `value="none"` on a
1005    // fresh form, which the user then has to manually clear before
1006    // typing. Every form with optional fields hit this footgun.
1007    //
1008    // Defining a custom formatter is the framework-level fix — every
1009    // template (admin, shop, plugins) inherits the new behaviour
1010    // automatically. Non-null/non-undefined values pass through the
1011    // default formatter unchanged so HTML escaping, number / bool /
1012    // string rendering, and safe-string handling stay identical.
1013    env.set_formatter(|out, state, value| {
1014        if value.is_none() || value.is_undefined() {
1015            return Ok(());
1016        }
1017        minijinja::escape_formatter(out, state, value)
1018    });
1019
1020    // features.md #67 — built-in example tags/filters. These ship as the
1021    // reference implementations for the custom-tag surface: `now()` for a
1022    // server-rendered timestamp, `currency` for money formatting. Plugins
1023    // add their own via `Plugin::template_registrars` (applied below).
1024    register_now_function(&mut env);
1025    register_currency_filter(&mut env);
1026
1027    // features #65 — `{{ querystring_with(base_query, "page", item.n) }}`
1028    // rebuilds the current querystring replacing one key, so the bundled
1029    // `_pagination.html` nav carries `?sort=...` filters across every
1030    // `?page=N` link. See `register_querystring_with_function`.
1031    register_querystring_with_function(&mut env);
1032
1033    // features.md #67 — plugin-contributed filters/functions. Applied
1034    // AFTER the built-ins so a plugin can deliberately override one by
1035    // re-registering the same name (minijinja's add_* overwrites). Runs
1036    // on every rebuild (dev hot-reload) because `Fn`, not `FnOnce`.
1037    if let Some(registrars) = REGISTRARS.get() {
1038        for registrar in registrars {
1039            registrar(&mut env);
1040        }
1041    }
1042
1043    let mut seen: HashSet<String> = HashSet::new();
1044    let mut collisions: Vec<String> = Vec::new();
1045
1046    // Register the built-in default error templates before scanning disk
1047    // directories. Because disk directories are first-match-wins and are
1048    // scanned after this call, a user template with the same name (unlikely,
1049    // since the `__umbral__/` prefix is reserved) would silently replace the
1050    // built-in. Callers who want a clean opt-out should use
1051    // `App::builder().disable_default_error_pages()`.
1052    register_default_templates(&mut env, &mut seen);
1053
1054    for dir in dirs {
1055        if dir.exists() {
1056            load_directory(&mut env, dir, dir, &mut seen, &mut collisions)?;
1057        }
1058    }
1059
1060    Ok((env, collisions))
1061}
1062
1063/// Render a template by name with a serde-serializable context value.
1064///
1065/// The name is the path relative to its templates directory, with
1066/// forward slashes regardless of host OS. `articles_list.html`,
1067/// `admin/base.html`, etc.
1068///
1069/// Returns `TemplateError::NotInitialised` if `App::build()` hasn't
1070/// run yet, `TemplateError::Missing` if the name doesn't match a
1071/// loaded template, and `TemplateError::Render` for any minijinja-
1072/// reported issue (syntax error, missing variable when strict undefined
1073/// is on, etc.).
1074pub fn render<C: Serialize>(name: &str, ctx: &C) -> Result<String, TemplateError> {
1075    // Dev-mode hot reload: when settings.environment == Dev, rebuild
1076    // the environment from disk on every render so template edits are
1077    // picked up without a server restart. This makes the dev loop —
1078    // edit `home.html`, hit reload, see the change — work without
1079    // `cargo run`-ing again. Production stays on the cached engine
1080    // for the fast path.
1081    //
1082    // Cost: one disk walk + minijinja parse per render in dev. For a
1083    // typical handler doing one render per request at ~10 RPS during
1084    // development, that's negligible. We chose this over per-file
1085    // stat checks because the per-render rebuild is dependency-free
1086    // and the staleness window is zero (a save followed instantly
1087    // by a reload always sees the new content).
1088    if dev_mode_active() {
1089        if let Some(dirs) = WATCHED_DIRS.get() {
1090            // Rebuild fresh; ignore collisions log here (init already
1091            // logged them once; we don't spam every render).
1092            match build_env(dirs) {
1093                Ok((env, _collisions)) => return render_with(&env, name, ctx),
1094                Err(e) => return Err(e),
1095            }
1096        }
1097    }
1098
1099    let env = ENGINE.get().ok_or(TemplateError::NotInitialised)?;
1100    render_with(env, name, ctx)
1101}
1102
1103/// Render an inline template source through the ambient-context path.
1104/// Test/bench helper only.
1105///
1106/// SECURITY (audit_2 core-templates-forms #3): this builds a fresh
1107/// `Environment`, whose minijinja default is `AutoEscape::None`. A no-escape
1108/// inline renderer that's `pub` (even `#[doc(hidden)]`) is an SSTI/XSS foot-gun
1109/// the moment any caller feeds it user data. We force `AutoEscape::Html` so
1110/// `{{ x }}` escapes exactly like a `.html` template rendered through
1111/// [`build_env`]; a caller that genuinely wants raw output opts in per value
1112/// with minijinja's `| safe`.
1113#[doc(hidden)]
1114pub fn render_str<C: Serialize>(src: &str, ctx: &C) -> Result<String, TemplateError> {
1115    let mut env = minijinja::Environment::new();
1116    env.set_auto_escape_callback(|_| AutoEscape::Html);
1117    env.add_template("__inline", src)
1118        .map_err(TemplateError::Render)?;
1119    render_with(&env, "__inline", ctx)
1120}
1121
1122/// True when the ambient settings say we're in Dev. Returns false if
1123/// settings haven't been initialised (production-style binaries that
1124/// never went through `App::build()`).
1125fn dev_mode_active() -> bool {
1126    crate::settings::get_opt()
1127        .map(|s| matches!(s.environment, crate::settings::Environment::Dev))
1128        .unwrap_or(false)
1129}
1130
1131/// Render a named template against the given env. Extracted so dev-mode
1132/// (fresh env per render) and prod (cached env) share one error mapping.
1133fn render_with<C: Serialize>(
1134    env: &Environment<'_>,
1135    name: &str,
1136    ctx: &C,
1137) -> Result<String, TemplateError> {
1138    let tmpl = env.get_template(name).map_err(|e| match e.kind() {
1139        minijinja::ErrorKind::TemplateNotFound => TemplateError::Missing(name.to_string()),
1140        _ => TemplateError::Render(e),
1141    })?;
1142    let merged = merge_ambient_context(ctx);
1143    tmpl.render(&merged).map_err(TemplateError::Render)
1144}
1145
1146/// Merge the ambient task-locals into a serializable template context:
1147/// `user` (from `CURRENT_USER`) and the CSRF pair `csrf_token` /
1148/// `csrf_input` (from `CURRENT_CSRF`). The handler's own keys always
1149/// win — the ambient injection is the default, not an override.
1150///
1151/// `user` is injected unconditionally (anonymous fallback below);
1152/// the CSRF pair only when a middleware actually scoped a token —
1153/// there is no meaningful fallback token, and rendering an empty
1154/// hidden input would make a form post a guaranteed-403 silently.
1155///
1156/// Most code should use [`render`], which calls this automatically.
1157/// Plugins that own a private MiniJinja environment can call this before
1158/// `Template::render` to get the same `{{ user }}`, `{{ csrf_token }}`,
1159/// and `{{ csrf_input }}` semantics as the framework renderer.
1160pub fn merge_ambient_context<C: Serialize>(ctx: &C) -> minijinja::Value {
1161    let ctx_value = minijinja::Value::from_serialize(ctx);
1162    merge_ambient_value(ctx_value)
1163}
1164
1165/// Same as [`merge_ambient_context`], but accepts an already-built
1166/// MiniJinja [`Value`](minijinja::Value). This is useful for private
1167/// plugin renderers that build context with `minijinja::context!`.
1168pub fn merge_ambient_value(ctx_value: minijinja::Value) -> minijinja::Value {
1169    let has = |key: &str| {
1170        ctx_value
1171            .get_attr(key)
1172            .map(|v| !v.is_undefined())
1173            .unwrap_or(false)
1174    };
1175
1176    let need_user = !has("user");
1177    let csrf = current_csrf();
1178    let need_csrf = csrf.is_some() && !(has("csrf_token") && has("csrf_input"));
1179
1180    if !need_user && !need_csrf {
1181        return ctx_value;
1182    }
1183
1184    // Build a fresh object that contains every original key plus the
1185    // ambient ones. minijinja's `Value::from_iter` over (key, value)
1186    // pairs produces a Map value; we walk the original keys and add
1187    // ours last.
1188    let mut pairs: Vec<(String, minijinja::Value)> = Vec::new();
1189    if let Ok(keys) = ctx_value.try_iter() {
1190        for key in keys {
1191            let key_str = key.to_string();
1192            if let Ok(v) = ctx_value.get_item(&key) {
1193                pairs.push((key_str, v));
1194            }
1195        }
1196    }
1197
1198    if need_user {
1199        // Resolve which `user` value should land in the rendered ctx:
1200        //   1. Task-local set by a middleware (AuthPlugin's
1201        //      `user_context_layer`) — the live request shape.
1202        //   2. Anonymous fallback `{ is_authenticated: false }` for
1203        //      callers WITHOUT a layer mounted AND for renders that
1204        //      happen outside the middleware's scope (notably the
1205        //      `render_500_middleware` recovery path — the
1206        //      user-context task-local has already dropped by the time
1207        //      the error layer renders, but the 500 template still
1208        //      needs `user.is_authenticated` to evaluate cleanly).
1209        //
1210        // The fallback is the same shape `serialize_anonymous` would
1211        // produce, kept in core so umbral-auth isn't a dependency of
1212        // the templates module.
1213        // Prefer the lazy channel (proxy defers resolution until attribute access),
1214        // then the eager task-local, then the anonymous fallback.
1215        let user_value = if let Ok(lazy) = CURRENT_USER_LAZY.try_with(|lazy| lazy.clone()) {
1216            lazy.into_proxy_value()
1217        } else if let Some(v) = CURRENT_USER.try_with(|u| u.clone()).ok().flatten() {
1218            v
1219        } else {
1220            anonymous_user_value()
1221        };
1222        pairs.push(("user".to_string(), user_value));
1223    }
1224
1225    if let Some(token) = csrf {
1226        if !has("csrf_token") {
1227            pairs.push((
1228                "csrf_token".to_string(),
1229                minijinja::Value::from(token.clone()),
1230            ));
1231        }
1232        if !has("csrf_input") {
1233            // Today's tokens are hex (signed mode adds `.` + hex sig),
1234            // so the escape is belt-and-braces against a future
1235            // token-shape change — not a live attack surface.
1236            let escaped = token
1237                .replace('&', "&amp;")
1238                .replace('"', "&quot;")
1239                .replace('<', "&lt;")
1240                .replace('>', "&gt;");
1241            pairs.push((
1242                "csrf_input".to_string(),
1243                minijinja::Value::from_safe_string(format!(
1244                    r#"<input type="hidden" name="csrf_token" value="{escaped}">"#
1245                )),
1246            ));
1247        }
1248    }
1249
1250    minijinja::Value::from_iter(pairs)
1251}
1252
1253/// Anonymous-user sentinel — the value `user` resolves to in
1254/// templates rendered outside an authenticated context (no auth
1255/// middleware, anonymous request, or the 500-rendering path
1256/// where the middleware's task-local has already dropped).
1257/// Carries only `{ is_authenticated: false }` — enough for
1258/// `{% if user.is_authenticated %}` / `{% if user.is_staff %}`
1259/// to evaluate to false without `umbral templates: undefined
1260/// value` errors that would otherwise mask the original failure.
1261fn anonymous_user_value() -> minijinja::Value {
1262    let mut map = serde_json::Map::new();
1263    map.insert(
1264        "is_authenticated".to_string(),
1265        serde_json::Value::Bool(false),
1266    );
1267    // is_staff / is_superuser default to false too so a template
1268    // gating on either doesn't accidentally render the privileged
1269    // branch when `user` is the anonymous fallback.
1270    map.insert("is_staff".to_string(), serde_json::Value::Bool(false));
1271    map.insert("is_superuser".to_string(), serde_json::Value::Bool(false));
1272    minijinja::Value::from_serialize(serde_json::Value::Object(map))
1273}
1274
1275/// Walk a directory recursively and register every `.html` / `.htm` /
1276/// `.txt` file as a template under its path-relative-to-root name.
1277/// Subdirectories are reachable via forward-slash names: `admin/base.html`.
1278///
1279/// `seen` tracks which names have already been registered across all
1280/// directories. When a name collision is detected (a later directory
1281/// ships a template with the same relative name as an earlier one),
1282/// the duplicate is skipped and the name is appended to `collisions`.
1283/// First-match-wins.
1284fn load_directory(
1285    env: &mut Environment<'static>,
1286    root: &Path,
1287    dir: &Path,
1288    seen: &mut HashSet<String>,
1289    collisions: &mut Vec<String>,
1290) -> Result<(), TemplateError> {
1291    for entry in std::fs::read_dir(dir)? {
1292        let entry = entry?;
1293        let path = entry.path();
1294        if path.is_dir() {
1295            load_directory(env, root, &path, seen, collisions)?;
1296            continue;
1297        }
1298        let Some(ext) = path.extension().and_then(|e| e.to_str()) else {
1299            continue;
1300        };
1301        if !matches!(ext, "html" | "htm" | "txt") {
1302            continue;
1303        }
1304        let rel: PathBuf = path
1305            .strip_prefix(root)
1306            .expect("walked path is rooted at the templates dir")
1307            .to_path_buf();
1308        // minijinja template names are forward-slashed regardless of OS;
1309        // the path display would emit `\` on Windows, so build the name
1310        // explicitly.
1311        let name: String = rel
1312            .components()
1313            .map(|c| c.as_os_str().to_string_lossy().to_string())
1314            .collect::<Vec<_>>()
1315            .join("/");
1316
1317        if seen.contains(&name) {
1318            // Collision: a higher-priority directory already registered
1319            // this name. Record it and skip; init will log after all
1320            // dirs are processed.
1321            if !collisions.contains(&name) {
1322                collisions.push(name.clone());
1323            }
1324            continue;
1325        }
1326
1327        let source = std::fs::read_to_string(&path)?;
1328        env.add_template_owned(name.clone(), source)
1329            .map_err(TemplateError::Render)?;
1330        seen.insert(name);
1331    }
1332    Ok(())
1333}
1334
1335/// Errors the template engine can produce. Narrow at v1: load-time IO,
1336/// engine-not-ready, missing template, render-time minijinja error.
1337#[derive(Debug)]
1338pub enum TemplateError {
1339    /// `App::build()` hasn't run yet, so the ambient engine isn't set.
1340    NotInitialised,
1341    /// `init` was called twice — a programming error in the framework
1342    /// itself, not the user. Surfaced as a `BuildError` if it ever fires.
1343    AlreadyInitialised,
1344    /// IO error reading a template file at boot.
1345    Io(std::io::Error),
1346    /// The requested template name isn't loaded.
1347    Missing(String),
1348    /// Any other minijinja error (syntax, render-time, etc.). The
1349    /// inner `minijinja::Error` carries the diagnostic (line / col /
1350    /// undefined name) so the caller can pass it through `Display`.
1351    Render(minijinja::Error),
1352}
1353
1354impl std::fmt::Display for TemplateError {
1355    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1356        match self {
1357            TemplateError::NotInitialised => write!(
1358                f,
1359                "umbral templates: engine not initialised — call App::build() first"
1360            ),
1361            TemplateError::AlreadyInitialised => {
1362                write!(f, "umbral templates: init called more than once")
1363            }
1364            TemplateError::Io(e) => write!(f, "umbral templates: io: {e}"),
1365            TemplateError::Missing(name) => write!(
1366                f,
1367                "umbral templates: no template named `{name}`; check the templates directory"
1368            ),
1369            TemplateError::Render(e) => write!(f, "umbral templates: {e}"),
1370        }
1371    }
1372}
1373
1374impl std::error::Error for TemplateError {}
1375
1376impl From<std::io::Error> for TemplateError {
1377    fn from(e: std::io::Error) -> Self {
1378        Self::Io(e)
1379    }
1380}
1381
1382#[cfg(test)]
1383mod tests {
1384    use super::*;
1385    use serde_json::json;
1386
1387    #[test]
1388    fn img_url_scheme_safety() {
1389        // Relative + http(s) are allowed.
1390        assert!(url_scheme_is_safe("/media/cat.png"));
1391        assert!(url_scheme_is_safe("cat.png"));
1392        assert!(url_scheme_is_safe("../up/cat.png"));
1393        assert!(url_scheme_is_safe("http://example.com/cat.png"));
1394        assert!(url_scheme_is_safe("https://example.com/cat.png"));
1395        assert!(url_scheme_is_safe("HTTPS://EXAMPLE.com/cat.png"));
1396        assert!(url_scheme_is_safe("?query=only"));
1397        assert!(url_scheme_is_safe("#fragment"));
1398        // Dangerous / non-http schemes are rejected.
1399        assert!(!url_scheme_is_safe("javascript:alert(1)"));
1400        assert!(!url_scheme_is_safe("  javascript:alert(1)"));
1401        assert!(!url_scheme_is_safe("JaVaScRiPt:alert(1)"));
1402        assert!(!url_scheme_is_safe(
1403            "data:text/html,<script>alert(1)</script>"
1404        ));
1405        assert!(!url_scheme_is_safe("vbscript:msgbox(1)"));
1406        assert!(!url_scheme_is_safe("mailto:a@b.com"));
1407        // Malformed scheme (embedded control char) fails closed.
1408        assert!(!url_scheme_is_safe("java\u{0}script:alert(1)"));
1409    }
1410
1411    #[test]
1412    fn img_filter_neutralises_javascript_url() {
1413        let mut env = minijinja::Environment::new();
1414        register_img_filter(&mut env);
1415        env.add_template("t", "{{ url | img }}").unwrap();
1416        let tmpl = env.get_template("t").unwrap();
1417        let out = tmpl
1418            .render(minijinja::context! { url => "javascript:alert(1)" })
1419            .unwrap();
1420        assert!(
1421            !out.contains("javascript:"),
1422            "javascript: URL must be neutralised; got {out}"
1423        );
1424        assert!(out.contains("src=\"\""), "expected empty src; got {out}");
1425    }
1426
1427    #[test]
1428    fn nested_template_names_are_relative_to_templates_root() {
1429        let tmp = tempfile::tempdir().expect("create temp dir");
1430        let templates = tmp.path().join("templates");
1431        std::fs::create_dir_all(templates.join("base")).expect("create base template dir");
1432        std::fs::create_dir_all(templates.join("content")).expect("create content template dir");
1433
1434        std::fs::write(
1435            templates.join("base").join("site.html"),
1436            "<main>{% block content %}{% endblock %}</main>",
1437        )
1438        .expect("write nested base template");
1439        std::fs::write(
1440            templates.join("content").join("contact.html"),
1441            r#"{% extends "base/site.html" %}{% block content %}<h1>{{ title }}</h1><p>Contact from nested content.</p>{% endblock %}"#,
1442        )
1443        .expect("write nested content template");
1444
1445        let (env, collisions) = build_env(&[templates]).expect("build template env");
1446        assert!(collisions.is_empty());
1447
1448        let rendered = render_with(
1449            &env,
1450            "content/contact.html",
1451            &json!({ "title": "Nested contact" }),
1452        )
1453        .expect("render nested template by relative name");
1454
1455        assert!(rendered.contains("<main>"));
1456        assert!(rendered.contains("<h1>Nested contact</h1>"));
1457        assert!(rendered.contains("Contact from nested content."));
1458    }
1459
1460    /// Render `{{ static(arg) }}` against an env whose `static()` was
1461    /// registered with the given `static_url`. Exercises the helper
1462    /// directly without needing the ambient `Settings` OnceLock (which
1463    /// can't be set under cargo's parallel test runner).
1464    fn render_static(static_url: &str, arg: &str) -> String {
1465        let mut env = Environment::new();
1466        register_static_function(&mut env, static_url.to_string());
1467        env.add_template("t.txt", "{{ static(arg) }}")
1468            .expect("add template");
1469        let tmpl = env.get_template("t.txt").expect("get template");
1470        tmpl.render(json!({ "arg": arg })).expect("render")
1471    }
1472
1473    #[test]
1474    fn static_helper_prepends_root_relative_url() {
1475        assert_eq!(
1476            render_static("/static/", "admin/admin.css"),
1477            "/static/admin/admin.css"
1478        );
1479    }
1480
1481    #[test]
1482    fn static_helper_prepends_cdn_origin() {
1483        assert_eq!(
1484            render_static("https://cdn.example.com/s/", "admin/admin.css"),
1485            "https://cdn.example.com/s/admin/admin.css"
1486        );
1487    }
1488
1489    #[test]
1490    fn static_helper_does_not_double_slash_on_leading_slash_arg() {
1491        assert_eq!(render_static("/static/", "/admin/x"), "/static/admin/x");
1492    }
1493
1494    #[test]
1495    fn highlight_css_contains_hl_rules() {
1496        let css = highlight_css();
1497        assert!(!css.is_empty(), "generated theme CSS should not be empty");
1498        assert!(
1499            css.contains(".hl-"),
1500            "theme CSS must target hl- classes: {css}"
1501        );
1502    }
1503
1504    #[test]
1505    fn fenced_rust_block_gets_syntect_token_spans() {
1506        let html = render_markdown("```rust\nfn main() {}\n```\n");
1507        assert!(
1508            html.contains("language-rust"),
1509            "keeps the language class for the md-enhance label: {html}"
1510        );
1511        assert!(
1512            html.contains("class=\"hl-"),
1513            "emits syntect hl- token spans: {html}"
1514        );
1515    }
1516
1517    #[test]
1518    fn script_in_code_fence_is_escaped_not_executed() {
1519        let html = render_markdown("```\n<script>alert(1)</script>\n```\n");
1520        assert!(!html.contains("<script>"), "no live script tag: {html}");
1521        assert!(
1522            html.contains("&lt;script&gt;"),
1523            "rendered as inert text: {html}"
1524        );
1525    }
1526
1527    #[test]
1528    fn prose_script_is_still_stripped() {
1529        let html = render_markdown("hello <script>alert(1)</script> world");
1530        assert!(!html.contains("<script>"), "prose script stripped: {html}");
1531    }
1532
1533    #[test]
1534    fn markdown_allows_class_but_not_style() {
1535        let html = render_markdown("<span class=\"x\" style=\"color:red\">hi</span>");
1536        assert!(html.contains("class=\"x\""), "class survives: {html}");
1537        assert!(!html.contains("style="), "style stripped: {html}");
1538    }
1539
1540    #[test]
1541    fn unknown_and_plain_fences_do_not_panic() {
1542        let unknown = render_markdown("```notalanguage\nx := 1\n```\n");
1543        let plain = render_markdown("```\nplain text\n```\n");
1544        assert!(
1545            unknown.contains("<pre><code"),
1546            "unknown lang block: {unknown}"
1547        );
1548        assert!(plain.contains("<pre><code"), "plain block: {plain}");
1549        assert!(
1550            unknown.contains("language-notalanguage"),
1551            "unknown lang still labelled: {unknown}"
1552        );
1553    }
1554
1555    /// Security: a hostile fence info token (e.g. `<script>alert(1)</script>`)
1556    /// must NOT appear as a live tag in the output. `wrap_code_block` HTML-escapes
1557    /// the lang token before inserting it into the class attribute value, and
1558    /// ammonia's builder only permits `class` on `<code>` — it does not allow
1559    /// arbitrary attributes or values. So a `<script>` info string is inert.
1560    ///
1561    /// Also asserts that the SAFE path — a plain `language-rust` class on
1562    /// the `<code>` element — still survives after the widened allowlist so
1563    /// the syntect token spans have a hook. This is the regression pin for
1564    /// gaps2 #36 sub-part (a).
1565    #[test]
1566    fn hostile_fence_info_string_is_escaped_and_language_class_survives() {
1567        // Hostile: info token that looks like a script injection.
1568        let hostile = render_markdown("```<script>alert(1)</script>\ncode\n```\n");
1569        assert!(
1570            !hostile.contains("<script>"),
1571            "live <script> from fence info must be stripped: {hostile}"
1572        );
1573        // The escaped form will appear inside a class value; ammonia lets
1574        // class through but the content is HTML-escaped so it is inert.
1575        assert!(
1576            hostile.contains("<pre><code"),
1577            "code block structure must survive: {hostile}"
1578        );
1579
1580        // Hostile: info token with a class-injection attempt.
1581        let class_inject = render_markdown("```evil\" onmouseover=\"alert(1)\ncode\n```\n");
1582        assert!(
1583            !class_inject.contains("onmouseover"),
1584            "event handler injected via fence info must not survive: {class_inject}"
1585        );
1586
1587        // Safe: the normal case — language-rust class must survive so
1588        // syntect hl- spans (server-side) and the md-enhance label both work.
1589        let safe = render_markdown("```rust\nfn ok() {}\n```\n");
1590        assert!(
1591            safe.contains("language-rust"),
1592            "language-rust class must survive sanitization (gaps2 #36a): {safe}"
1593        );
1594        assert!(
1595            safe.contains("class=\"hl-"),
1596            "syntect hl- token spans must survive sanitization: {safe}"
1597        );
1598    }
1599
1600    #[test]
1601    fn highlight_styles_global_emits_a_style_block() {
1602        let mut env = Environment::new();
1603        register_highlight_styles_function(&mut env);
1604        env.add_template("t", "{{ highlight_styles() }}")
1605            .expect("add template");
1606        let out = env
1607            .get_template("t")
1608            .expect("get template")
1609            .render(())
1610            .expect("render");
1611        assert!(out.starts_with("<style>"), "wraps in a style block: {out}");
1612        assert!(out.contains(".hl-"), "carries the token CSS: {out}");
1613        assert!(
1614            out.trim_end().ends_with("</style>"),
1615            "closes the style block: {out}"
1616        );
1617    }
1618}