Skip to main content

rustango_cms/
tenant_templates.rs

1//! Per-tenant template overrides, resolved from disk with fallback to
2//! the global set.
3//!
4//! A multisite needs tenants to differ in appearance without differing
5//! in code. The render path already picks its template by name from the
6//! page-type row (`render.rs` → `tera.render(&pt.default_template, …)`),
7//! so *selection* was already data-driven; what was missing was
8//! per-tenant template *content*.
9//!
10//! ## Layout
11//!
12//! ```text
13//! {base_dir}/
14//!   templates/                 <- global set, the existing public glob
15//!     base.html
16//!     landing_page.html
17//!   templates_admin/           <- already outside the glob (host chrome)
18//!   templates_tenants/         <- this module
19//!     acme/
20//!       base.html              <- wins over templates/base.html
21//!     globex/
22//!       landing_page.html      <- wins; its base.html falls back to global
23//! ```
24//!
25//! Tenant directories sit **outside** the global glob deliberately. The
26//! glob would otherwise load every tenant's files into every instance
27//! under names like `templates_tenants/acme/base.html` — harmless but
28//! wasteful, and the same trap the host's `templates_admin/` already
29//! avoids.
30//!
31//! ## Why one Tera per tenant, and not name prefixes
32//!
33//! `{% extends %}` and `{% include %}` resolve by template **name**,
34//! within one Tera instance, when inheritance chains are built. Prefixing
35//! a tenant's templates into the shared instance therefore does *not*
36//! give it its own base: `{% extends "base.html" %}` inside
37//! `templates_tenants/acme/page.html` would still resolve to the global
38//! `base.html`. Making prefixes work means rewriting every inheritance
39//! reference at load time — fragile, and it breaks the ability to copy a
40//! template from the global set into a tenant folder unchanged.
41//!
42//! Giving each tenant its own instance makes the override natural:
43//! overlay the tenant's files onto a clone of the global set, so a name
44//! either resolves to the tenant's copy or falls through to the global
45//! one, and inheritance follows the same rule.
46//!
47//! ## Cost
48//!
49//! Building a tenant instance is `base.clone()` plus a parse of that
50//! tenant's own files. The clone is the measured cost —
51//! ~2.4 ms for a full corpus (the same deep-copy that made the page
52//! editor spend 423 ms/request before it was memoized), so instances are
53//! cached, and the cache is bounded.
54//!
55//! Hand [`TenantTemplates::new`] a Tera holding only the **public**
56//! templates where you can. A clone of an instance that also carries the
57//! admin corpus is far larger, and the public render path never extends
58//! an admin template.
59
60use std::collections::HashMap;
61use std::path::{Path, PathBuf};
62use std::sync::atomic::{AtomicU64, Ordering};
63use std::sync::{Arc, RwLock};
64use std::time::{Duration, Instant, SystemTime};
65
66use tera::Tera;
67
68/// Default directory name, a sibling of `templates/`.
69pub const DEFAULT_DIR: &str = "templates_tenants";
70
71/// How eagerly to notice that a tenant's files changed on disk.
72#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum Reload {
74    /// Fingerprint the tenant directory on every lookup. Development:
75    /// edit a file, reload the browser, see it.
76    Always,
77    /// Fingerprint at most this often. Production default — a template
78    /// drop is picked up within the interval with no restart, without
79    /// paying a directory walk per request.
80    Every(Duration),
81    /// Never re-check. The instance is built once per process, so a
82    /// template change needs a restart. Cheapest, and appropriate when
83    /// templates only ever change via a deploy that restarts anyway.
84    Never,
85}
86
87impl Default for Reload {
88    fn default() -> Self {
89        Self::Every(Duration::from_secs(5))
90    }
91}
92
93/// Monotonic counter standing in for a clock in the LRU ordering.
94///
95/// A logical tick, not a timestamp: eviction only needs *which entry was
96/// touched last*, and a counter gives that exactly, with no dependence on
97/// clock resolution — two hits inside the same nanosecond still order.
98static TICK: AtomicU64 = AtomicU64::new(0);
99
100fn tick() -> u64 {
101    TICK.fetch_add(1, Ordering::Relaxed)
102}
103
104/// One cached tenant instance.
105struct Entry {
106    tera: Arc<Tera>,
107    /// Fingerprint of the tenant directory when this was built.
108    fingerprint: u64,
109    /// When the fingerprint was last recomputed (for [`Reload::Every`]).
110    checked: Instant,
111    /// LRU ordering. Atomic so a cache *hit* can record recency while
112    /// holding only a read lock — the reason this is not an `Instant`
113    /// field: the hot path must not need the write lock, and an LRU that
114    /// cannot observe hits evicts the busiest tenant first.
115    used: AtomicU64,
116}
117
118/// The file in a tenant's override directory naming its owner.
119/// Not `.html`, so it is never loaded as a template or listed as one.
120const OWNER_FILE: &str = ".rcms-owner";
121
122/// Where [`TenantTemplates::claim`] moves a directory that belongs to a
123/// purged tenant. Dot-prefixed, so no slug can resolve to it.
124const ORPHANED_DIR: &str = ".orphaned";
125
126/// What [`TenantTemplates::claim`] found.
127#[derive(Debug, PartialEq, Eq)]
128pub enum Claim {
129    /// The tenant has no override directory.
130    NoOverrides,
131    /// The directory is marked for this tenant.
132    Owned,
133    /// The directory had no marker, and now carries this tenant's.
134    Adopted,
135    /// The directory belonged to an earlier tenant with the same slug and
136    /// was moved to `to`.
137    MovedAside { previous_owner: String, to: PathBuf },
138}
139
140/// Resolves a Tera instance per tenant, overlaying that tenant's
141/// templates onto the global set.
142pub struct TenantTemplates {
143    base: Arc<Tera>,
144    root: PathBuf,
145    /// Where the *global* templates live on disk. Only the editor needs
146    /// this — the renderer gets the global set from `base`, already
147    /// compiled. Supplying it lets the editor show what a name currently
148    /// falls back to, and seed a new override from it.
149    global_dir: Option<PathBuf>,
150    reload: Reload,
151    capacity: usize,
152    cache: RwLock<HashMap<String, Entry>>,
153}
154
155impl TenantTemplates {
156    /// `base` is the global set — ideally public templates only, see the
157    /// module docs on cost. `root` is the directory holding one
158    /// subdirectory per tenant slug.
159    #[must_use]
160    pub fn new(base: Arc<Tera>, root: impl Into<PathBuf>) -> Self {
161        Self {
162            base,
163            root: root.into(),
164            global_dir: None,
165            reload: Reload::default(),
166            // Mirrors the framework's `max_cached_scoped_pools`: past the
167            // cap the long tail rebuilds per lookup rather than the
168            // process holding an unbounded number of compiled corpora.
169            capacity: 64,
170            cache: RwLock::new(HashMap::new()),
171        }
172    }
173
174    /// Point the admin editor at the global template directory, so it
175    /// can show the fallback a tenant would inherit and seed new
176    /// overrides from it.
177    #[must_use]
178    pub fn with_global_dir(mut self, dir: impl Into<PathBuf>) -> Self {
179        self.global_dir = Some(dir.into());
180        self
181    }
182
183    #[must_use]
184    pub fn with_reload(mut self, reload: Reload) -> Self {
185        self.reload = reload;
186        self
187    }
188
189    #[must_use]
190    pub fn with_capacity(mut self, capacity: usize) -> Self {
191        self.capacity = capacity.max(1);
192        self
193    }
194
195    /// This tenant's cached instance, if it has one that isn't due a
196    /// re-check — no filesystem access. `None` means ask
197    /// [`Self::for_tenant`], which may touch the disk.
198    #[must_use]
199    pub fn cached(&self, slug: &str) -> Option<Arc<Tera>> {
200        let cache = self.cache.read().ok()?;
201        let e = cache.get(slug)?;
202        if self.due(e) {
203            return None;
204        }
205        e.used.store(tick(), Ordering::Relaxed);
206        Some(Arc::clone(&e.tera))
207    }
208
209    /// The instance to render this tenant's pages with.
210    ///
211    /// A tenant with no directory gets the global set back directly — no
212    /// clone, no cache entry, so the common "tenant hasn't customised
213    /// anything" case costs nothing.
214    #[must_use]
215    pub fn for_tenant(&self, slug: &str) -> Arc<Tera> {
216        let Some(dir) = self.tenant_dir(slug) else {
217            return Arc::clone(&self.base);
218        };
219
220        // Fast path: a cached instance that we are not due to re-check.
221        if let Ok(cache) = self.cache.read() {
222            if let Some(e) = cache.get(slug) {
223                if !self.due(e) {
224                    e.used.store(tick(), Ordering::Relaxed);
225                    return Arc::clone(&e.tera);
226                }
227            }
228        }
229
230        let fingerprint = fingerprint(&dir);
231
232        // Re-check path: the fingerprint may be unchanged, in which case
233        // the cached instance stands and only its timestamps move.
234        if let Ok(mut cache) = self.cache.write() {
235            if let Some(e) = cache.get_mut(slug) {
236                if e.fingerprint == fingerprint {
237                    e.checked = Instant::now();
238                    e.used.store(tick(), Ordering::Relaxed);
239                    return Arc::clone(&e.tera);
240                }
241            }
242        }
243
244        let tera = Arc::new(self.build(&dir));
245
246        if let Ok(mut cache) = self.cache.write() {
247            if cache.len() >= self.capacity && !cache.contains_key(slug) {
248                Self::evict_lru(&mut cache);
249            }
250            cache.insert(
251                slug.to_owned(),
252                Entry {
253                    tera: Arc::clone(&tera),
254                    fingerprint,
255                    checked: Instant::now(),
256                    used: AtomicU64::new(tick()),
257                },
258            );
259        }
260        tera
261    }
262
263    /// Whether this entry is due a fingerprint re-check.
264    fn due(&self, e: &Entry) -> bool {
265        match self.reload {
266            Reload::Always => true,
267            Reload::Never => false,
268            Reload::Every(d) => e.checked.elapsed() >= d,
269        }
270    }
271
272    fn evict_lru(cache: &mut HashMap<String, Entry>) {
273        // O(n) over a small n, which beats pulling in an LRU crate for
274        // a map that holds tens of entries.
275        if let Some(oldest) = cache
276            .iter()
277            .min_by_key(|(_, e)| e.used.load(Ordering::Relaxed))
278            .map(|(k, _)| k.clone())
279        {
280            cache.remove(&oldest);
281        }
282    }
283
284    /// The directory for a slug, if it exists and the slug is safe.
285    ///
286    /// Slugs come from the tenant registry rather than a request, but a
287    /// path is still built from them, so a slug that could climb out of
288    /// `root` is refused rather than trusted.
289    fn tenant_dir(&self, slug: &str) -> Option<PathBuf> {
290        if slug.is_empty()
291            || slug.starts_with('.')
292            || slug.contains('/')
293            || slug.contains('\\')
294        {
295            return None;
296        }
297        let dir = self.root.join(slug);
298        dir.is_dir().then_some(dir)
299    }
300
301    /// Bind a tenant's override directory to `owner`, the identity of the
302    /// tenant database it belongs to.
303    ///
304    /// Overrides live on disk, keyed by slug, and a purged tenant's slug
305    /// can be reused: without this the next tenant given that slug renders
306    /// through the old customer's files. The directory carries an owner
307    /// marker; a directory marked for another owner is moved aside, not
308    /// deleted, and dropped from the cache. An unmarked directory predates
309    /// the marker and is adopted.
310    ///
311    /// # Errors
312    /// Filesystem failures reading or writing the marker, or moving a
313    /// stale directory aside.
314    pub fn claim(&self, slug: &str, owner: &str) -> std::io::Result<Claim> {
315        let Some(dir) = self.tenant_dir(slug) else {
316            return Ok(Claim::NoOverrides);
317        };
318        let marker = dir.join(OWNER_FILE);
319        match std::fs::read_to_string(&marker) {
320            Ok(found) if found.trim() == owner => Ok(Claim::Owned),
321            Ok(found) => {
322                let aside_root = self.root.join(ORPHANED_DIR);
323                std::fs::create_dir_all(&aside_root)?;
324                let stamp = SystemTime::now()
325                    .duration_since(SystemTime::UNIX_EPOCH)
326                    .map_or(0, |d| d.as_secs());
327                let aside = aside_root.join(format!("{slug}-{stamp}"));
328                std::fs::rename(&dir, &aside)?;
329                if let Ok(mut cache) = self.cache.write() {
330                    cache.remove(slug);
331                }
332                Ok(Claim::MovedAside { previous_owner: found.trim().to_owned(), to: aside })
333            }
334            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
335                std::fs::write(&marker, owner)?;
336                Ok(Claim::Adopted)
337            }
338            Err(e) => Err(e),
339        }
340    }
341
342    /// Overlay a tenant's files onto a clone of the global set.
343    fn build(&self, dir: &Path) -> Tera {
344        let mut tera = (*self.base).clone();
345        let mut overrides: Vec<(String, String)> = Vec::new();
346        collect(dir, dir, &mut overrides);
347
348        // Sorted so a build is deterministic regardless of directory
349        // iteration order — two processes given the same files produce
350        // the same instance.
351        overrides.sort_by(|a, b| a.0.cmp(&b.0));
352
353        for (name, body) in overrides {
354            if let Err(e) = tera.add_raw_template(&name, &body) {
355                // One malformed template must not cost the tenant every
356                // other page: log it and leave the global version in
357                // place for that name.
358                tracing::warn!(
359                    target: "rustango_cms::tenant_templates",
360                    template = %name, error = %e,
361                    "tenant template failed to parse; falling back to the global one",
362                );
363            }
364        }
365        if let Err(e) = tera.build_inheritance_chains() {
366            tracing::error!(
367                target: "rustango_cms::tenant_templates",
368                error = %e,
369                "tenant template inheritance is broken; serving the global set",
370            );
371            return (*self.base).clone();
372        }
373        tera
374    }
375}
376
377/// Recursively collect `(template name, body)` for a tenant directory.
378///
379/// Names are relative to the tenant's own directory and `/`-separated,
380/// so `acme/blocks/hero.html` registers as `blocks/hero.html` — the same
381/// name the global set uses. That is what lets a template be copied from
382/// the global folder into a tenant folder and work unmodified.
383fn collect(root: &Path, dir: &Path, out: &mut Vec<(String, String)>) {
384    let Ok(entries) = std::fs::read_dir(dir) else {
385        return;
386    };
387    for entry in entries.flatten() {
388        let path = entry.path();
389        // Same rule as the editor: a path that resolves outside `root`
390        // is not this tenant's template, however it got there. Without
391        // this a symlink would still be *rendered*, so the write guard
392        // alone would close the door and leave a window.
393        if !contained(root, &path) {
394            continue;
395        }
396        if path.is_dir() {
397            collect(root, &path, out);
398            continue;
399        }
400        if path.extension().and_then(|e| e.to_str()) != Some("html") {
401            continue;
402        }
403        let Ok(rel) = path.strip_prefix(root) else {
404            continue;
405        };
406        let name = rel
407            .components()
408            .filter_map(|c| c.as_os_str().to_str())
409            .collect::<Vec<_>>()
410            .join("/");
411        if let Ok(body) = std::fs::read_to_string(&path) {
412            out.push((name, body));
413        }
414    }
415}
416
417/// Cheap content fingerprint for a tenant directory.
418///
419/// Hashes each file's relative name, length and mtime rather than its
420/// bytes — enough to notice an edit, a rename, an addition or a removal
421/// without reading the files, which is the point of checking often.
422///
423/// Same reasoning as `cms_asset_version()`, which fingerprints the
424/// bundled assets plus the override's mtime and length.
425fn fingerprint(dir: &Path) -> u64 {
426    let mut files: Vec<(String, u64, u64)> = Vec::new();
427    let mut names: Vec<(String, String)> = Vec::new();
428    collect_meta(dir, dir, &mut names);
429    for (name, _) in &names {
430        let path = dir.join(name);
431        let (len, mtime) = std::fs::metadata(&path)
432            .map(|m| {
433                (
434                    m.len(),
435                    m.modified()
436                        .ok()
437                        .and_then(|t| t.duration_since(SystemTime::UNIX_EPOCH).ok())
438                        .map_or(0, |d| d.as_nanos() as u64),
439                )
440            })
441            .unwrap_or((0, 0));
442        files.push((name.clone(), len, mtime));
443    }
444    files.sort();
445
446    // FNV-1a, 64-bit. A validator, not a security primitive.
447    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
448    let mut eat = |bytes: &[u8]| {
449        for b in bytes {
450            h ^= u64::from(*b);
451            h = h.wrapping_mul(0x0000_0100_0000_01b3);
452        }
453    };
454    for (name, len, mtime) in &files {
455        eat(name.as_bytes());
456        eat(&len.to_le_bytes());
457        eat(&mtime.to_le_bytes());
458    }
459    h
460}
461
462/// Like [`collect`] but names only — no file reads.
463fn collect_meta(root: &Path, dir: &Path, out: &mut Vec<(String, String)>) {
464    let Ok(entries) = std::fs::read_dir(dir) else {
465        return;
466    };
467    for entry in entries.flatten() {
468        let path = entry.path();
469        if !contained(root, &path) {
470            continue;
471        }
472        if path.is_dir() {
473            collect_meta(root, &path, out);
474            continue;
475        }
476        if path.extension().and_then(|e| e.to_str()) != Some("html") {
477            continue;
478        }
479        if let Ok(rel) = path.strip_prefix(root) {
480            let name = rel
481                .components()
482                .filter_map(|c| c.as_os_str().to_str())
483                .collect::<Vec<_>>()
484                .join("/");
485            out.push((name, String::new()));
486        }
487    }
488}
489
490/// Where a template a tenant renders actually came from.
491#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
492#[serde(rename_all = "lowercase")]
493pub enum Source {
494    /// The tenant has its own copy in `templates_tenants/<slug>/`.
495    Override,
496    /// Inherited from the global set.
497    Global,
498}
499
500/// One row in the editor's listing.
501#[derive(Debug, Clone, serde::Serialize)]
502pub struct TemplateEntry {
503    pub name: String,
504    pub source: Source,
505    pub bytes: u64,
506}
507
508/// Why a write was refused.
509#[derive(Debug)]
510pub enum EditError {
511    /// The name is not a template path this may write.
512    BadName(String),
513    /// The body is not valid Tera. Carries the parse error, so the
514    /// editor can show the author what is wrong.
515    Invalid(String),
516    /// The editor is not configured (no tenant-template root).
517    NotConfigured,
518    Io(std::io::Error),
519}
520
521impl std::fmt::Display for EditError {
522    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
523        match self {
524            Self::BadName(n) => write!(f, "`{n}` is not a valid template name"),
525            Self::Invalid(e) => write!(f, "{e}"),
526            Self::NotConfigured => write!(f, "per-tenant templates are not configured"),
527            Self::Io(e) => write!(f, "{e}"),
528        }
529    }
530}
531
532/// Validate a template name supplied by an editor.
533///
534/// Everything here is a request parameter, so nothing is trusted: the
535/// name must be relative, must stay inside the tenant's directory, and
536/// must be a template rather than an arbitrary file. Without the
537/// extension check this endpoint would happily write `../../.ssh/config`.
538///
539/// # Errors
540/// [`EditError::BadName`] with the offending value.
541pub fn safe_name(name: &str) -> Result<String, EditError> {
542    let n = name.trim().trim_start_matches('/');
543    let bad = n.is_empty()
544        || !n.ends_with(".html")
545        || n.contains('\\')
546        || n.starts_with('.')
547        || n.split('/').any(|seg| seg.is_empty() || seg == "." || seg == "..")
548        || std::path::Path::new(n).is_absolute();
549    if bad {
550        return Err(EditError::BadName(name.to_owned()));
551    }
552    Ok(n.to_owned())
553}
554
555impl TenantTemplates {
556    /// The tenant's own override directory, whether or not it exists.
557    #[must_use]
558    pub fn dir_for(&self, slug: &str) -> Option<PathBuf> {
559        if slug.is_empty() || slug.contains('/') || slug.contains('\\') || slug.starts_with('.') {
560            return None;
561        }
562        Some(self.root.join(slug))
563    }
564
565    /// Every template this tenant renders: its own overrides, plus the
566    /// global names it inherits. Sorted, overrides marked.
567    #[must_use]
568    pub fn list_for(&self, slug: &str) -> Vec<TemplateEntry> {
569        let mut seen: HashMap<String, TemplateEntry> = HashMap::new();
570
571        if let Some(g) = &self.global_dir {
572            let mut names = Vec::new();
573            collect_meta(g, g, &mut names);
574            for (name, _) in names {
575                let bytes = std::fs::metadata(g.join(&name)).map(|m| m.len()).unwrap_or(0);
576                seen.insert(name.clone(), TemplateEntry { name, source: Source::Global, bytes });
577            }
578        }
579        if let Some(dir) = self.dir_for(slug).filter(|d| d.is_dir()) {
580            let mut names = Vec::new();
581            collect_meta(&dir, &dir, &mut names);
582            for (name, _) in names {
583                let bytes = std::fs::metadata(dir.join(&name)).map(|m| m.len()).unwrap_or(0);
584                seen.insert(name.clone(), TemplateEntry { name, source: Source::Override, bytes });
585            }
586        }
587        let mut out: Vec<TemplateEntry> = seen.into_values().collect();
588        out.sort_by(|a, b| a.name.cmp(&b.name));
589        out
590    }
591
592    /// The tenant's override body for `name`, if it has one.
593    #[must_use]
594    pub fn read_override(&self, slug: &str, name: &str) -> Option<String> {
595        let name = safe_name(name).ok()?;
596        let dir = self.dir_for(slug)?;
597        let path = dir.join(name);
598        if !contained(&dir, &path) {
599            return None;
600        }
601        std::fs::read_to_string(path).ok()
602    }
603
604    /// The global body for `name` — what the tenant inherits today, and
605    /// the sensible starting point for a new override.
606    #[must_use]
607    pub fn read_global(&self, name: &str) -> Option<String> {
608        let name = safe_name(name).ok()?;
609        std::fs::read_to_string(self.global_dir.as_ref()?.join(name)).ok()
610    }
611
612    /// Create or replace a tenant's override.
613    ///
614    /// The body is parsed before anything is written, so a syntax error
615    /// is reported to the author instead of being discovered by the next
616    /// visitor. (The renderer's per-template fallback still exists, but
617    /// it is a safety net, not the place to find out.)
618    ///
619    /// # Errors
620    /// [`EditError`] for a rejected name, invalid Tera, or an I/O failure.
621    pub fn write_override(&self, slug: &str, name: &str, body: &str) -> Result<(), EditError> {
622        let name = safe_name(name)?;
623        let dir = self.dir_for(slug).ok_or(EditError::NotConfigured)?;
624
625        self.validate(slug, &name, body)?;
626
627        let path = dir.join(&name);
628        // Contained before anything is created (#770): checked after, a
629        // symlinked subdirectory let the write create directories outside
630        // the tenant's folder even though the file itself was refused. The
631        // tenant root is the one directory safe to create first — the check
632        // needs it to exist.
633        std::fs::create_dir_all(&dir).map_err(EditError::Io)?;
634        if !contained(&dir, &path) {
635            return Err(EditError::BadName(name));
636        }
637        if let Some(parent) = path.parent() {
638            std::fs::create_dir_all(parent).map_err(EditError::Io)?;
639        }
640        std::fs::write(&path, body).map_err(EditError::Io)?;
641        Ok(())
642    }
643
644    /// Check a candidate body the way the renderer will actually load it.
645    ///
646    /// Parsing it against an empty Tera is not enough — and is actively
647    /// wrong. A template that opens `{% extends "_base.html" %}` is
648    /// perfectly valid, but in isolation the parent is "not loaded" and
649    /// it looks broken. So the probe is a clone of the global set plus
650    /// this tenant's other overrides: the same instance `build` makes,
651    /// with the candidate swapped in.
652    ///
653    /// That also makes the check *stronger* than syntax alone — it
654    /// catches extending or including a template that does not exist,
655    /// which is the mistake an author is most likely to make when
656    /// copying a template between tenants.
657    ///
658    /// # Errors
659    /// [`EditError::Invalid`] carrying the parse or inheritance error.
660    pub fn validate(&self, slug: &str, name: &str, body: &str) -> Result<(), EditError> {
661        let mut probe = (*self.base).clone();
662
663        if let Some(dir) = self.dir_for(slug).filter(|d| d.is_dir()) {
664            let mut existing = Vec::new();
665            collect(&dir, &dir, &mut existing);
666            existing.sort_by(|a, b| a.0.cmp(&b.0));
667            for (n, b) in existing {
668                // Skip the one being replaced, and ignore failures in the
669                // others: they are already live, and reporting a
670                // *different* file's problem here would be baffling.
671                if n == name {
672                    continue;
673                }
674                let _ = probe.add_raw_template(&n, &b);
675            }
676        }
677
678        probe
679            .add_raw_template(name, body)
680            .and_then(|()| probe.build_inheritance_chains())
681            .map_err(|e| EditError::Invalid(chain(&e)))
682    }
683
684    /// Drop a tenant's override, reverting that name to the global one.
685    ///
686    /// # Errors
687    /// [`EditError`] for a rejected name or an I/O failure. Deleting a
688    /// name the tenant never overrode is a no-op, not an error — the
689    /// end state the caller asked for is the one they get.
690    pub fn delete_override(&self, slug: &str, name: &str) -> Result<(), EditError> {
691        let name = safe_name(name)?;
692        let dir = self.dir_for(slug).ok_or(EditError::NotConfigured)?;
693        let path = dir.join(&name);
694        if !path.exists() {
695            return Ok(());
696        }
697        if !contained(&dir, &path) {
698            return Err(EditError::BadName(name));
699        }
700        std::fs::remove_file(&path).map_err(EditError::Io)?;
701        // Tidy empty parents left behind by a nested override, stopping
702        // at the tenant's own directory.
703        let mut p = path.parent().map(std::path::Path::to_path_buf);
704        while let Some(cur) = p {
705            if cur == dir || !cur.starts_with(&dir) {
706                break;
707            }
708            if std::fs::remove_dir(&cur).is_err() {
709                break;
710            }
711            p = cur.parent().map(std::path::Path::to_path_buf);
712        }
713        Ok(())
714    }
715
716    /// Validate a whole set of templates together, then write them all,
717    /// or nothing.
718    ///
719    /// A theme's templates refer to each other — `home.html` extends a
720    /// `_base.html` that is in the same set — so checking them one by one
721    /// against what is on disk would reject a perfectly good set. The
722    /// probe is the global set plus this tenant's other overrides plus the
723    /// whole new set, built once.
724    ///
725    /// # Errors
726    /// [`EditError`] for a rejected name, invalid Tera anywhere in the
727    /// set, or an I/O failure.
728    pub fn write_set(&self, slug: &str, files: &[(String, String)]) -> Result<usize, EditError> {
729        let dir = self.dir_for(slug).ok_or(EditError::NotConfigured)?;
730        let mut named = Vec::with_capacity(files.len());
731        for (name, body) in files {
732            named.push((safe_name(name)?, body.as_str()));
733        }
734
735        let mut probe = (*self.base).clone();
736        if dir.is_dir() {
737            let mut existing = Vec::new();
738            collect(&dir, &dir, &mut existing);
739            for (n, b) in existing {
740                if !named.iter().any(|(m, _)| *m == n) {
741                    let _ = probe.add_raw_template(&n, &b);
742                }
743            }
744        }
745        probe
746            .add_raw_templates(named.iter().map(|(n, b)| (n.as_str(), *b)))
747            .map_err(|e| EditError::Invalid(chain(&e)))?;
748
749        std::fs::create_dir_all(&dir).map_err(EditError::Io)?;
750        for (name, body) in &named {
751            let path = dir.join(name);
752            if let Some(parent) = path.parent() {
753                std::fs::create_dir_all(parent).map_err(EditError::Io)?;
754            }
755            if !contained(&dir, path.parent().unwrap_or(&dir)) {
756                return Err(EditError::BadName(name.clone()));
757            }
758            std::fs::write(&path, body).map_err(EditError::Io)?;
759        }
760        Ok(named.len())
761    }
762
763    /// Where a tenant's previous set of overrides is kept. Outside every
764    /// tenant directory: a slug never starts with a dot.
765    fn snapshot_dir(&self, slug: &str) -> Option<PathBuf> {
766        self.dir_for(slug)?;
767        Some(self.root.join(".previous").join(slug))
768    }
769
770    /// Keep a copy of the tenant's current overrides, replacing any
771    /// earlier copy, so a later [`Self::restore_snapshot`] can bring them
772    /// back.
773    ///
774    /// # Errors
775    /// [`EditError::NotConfigured`] or an I/O failure.
776    pub fn snapshot(&self, slug: &str) -> Result<(), EditError> {
777        let dir = self.dir_for(slug).ok_or(EditError::NotConfigured)?;
778        let snap = self.snapshot_dir(slug).ok_or(EditError::NotConfigured)?;
779        if snap.exists() {
780            std::fs::remove_dir_all(&snap).map_err(EditError::Io)?;
781        }
782        std::fs::create_dir_all(&snap).map_err(EditError::Io)?;
783        if dir.is_dir() {
784            let mut files = Vec::new();
785            collect(&dir, &dir, &mut files);
786            for (name, body) in files {
787                let path = snap.join(&name);
788                if let Some(parent) = path.parent() {
789                    std::fs::create_dir_all(parent).map_err(EditError::Io)?;
790                }
791                std::fs::write(path, body).map_err(EditError::Io)?;
792            }
793        }
794        Ok(())
795    }
796
797    /// Whether [`Self::snapshot`] has kept a copy for this tenant.
798    #[must_use]
799    pub fn has_snapshot(&self, slug: &str) -> bool {
800        self.snapshot_dir(slug).is_some_and(|d| d.is_dir())
801    }
802
803    /// Swap the tenant's overrides with the kept copy: the previous set
804    /// becomes live, and the current one becomes the copy, so restoring
805    /// twice gets back to where you started.
806    ///
807    /// # Errors
808    /// [`EditError::NotConfigured`] when there is no copy, or an I/O
809    /// failure.
810    pub fn restore_snapshot(&self, slug: &str) -> Result<(), EditError> {
811        let dir = self.dir_for(slug).ok_or(EditError::NotConfigured)?;
812        let snap = self
813            .snapshot_dir(slug)
814            .filter(|d| d.is_dir())
815            .ok_or(EditError::NotConfigured)?;
816        let swap = self.root.join(".previous").join(format!("{slug}.swap"));
817        if swap.exists() {
818            std::fs::remove_dir_all(&swap).map_err(EditError::Io)?;
819        }
820        if dir.exists() {
821            std::fs::rename(&dir, &swap).map_err(EditError::Io)?;
822        } else {
823            std::fs::create_dir_all(&swap).map_err(EditError::Io)?;
824        }
825        std::fs::rename(&snap, &dir).map_err(EditError::Io)?;
826        std::fs::rename(&swap, &snap).map_err(EditError::Io)?;
827        Ok(())
828    }
829}
830
831/// Whether `path` really lives inside `root`, symlinks resolved.
832///
833/// [`safe_name`] is lexical — it rejects `..` in the *name*, which is
834/// enough to stop a crafted request escaping. It cannot see a symlink
835/// already sitting on disk: a link at
836/// `templates_tenants/acme/peek.html` pointing at another tenant's file
837/// let `acme` both read and **overwrite** it, because every string
838/// involved looked perfectly ordinary.
839///
840/// Templates arrive by rsync or git, and a symlink is easy to miss in a
841/// diff, so the check has to be on the resolved path rather than the
842/// name. Resolves the deepest existing ancestor (the leaf may not exist
843/// yet, on a create) and re-appends the rest.
844fn contained(root: &Path, path: &Path) -> bool {
845    let Ok(root_real) = root.canonicalize() else {
846        return false;
847    };
848    let mut probe = path.to_path_buf();
849    let mut tail: Vec<std::ffi::OsString> = Vec::new();
850    loop {
851        if let Ok(real) = probe.canonicalize() {
852            let mut full = real;
853            for seg in tail.iter().rev() {
854                full.push(seg);
855            }
856            return full.starts_with(&root_real);
857        }
858        let Some(name) = probe.file_name().map(std::ffi::OsStr::to_owned) else {
859            return false;
860        };
861        tail.push(name);
862        if !probe.pop() {
863            return false;
864        }
865    }
866}
867
868/// Flatten a Tera error and its causes into one line.
869///
870/// Tera puts the actual problem in `source()` — the top-level message is
871/// usually just "Failed to parse 'x.html'", which tells an author
872/// nothing.
873fn chain(e: &tera::Error) -> String {
874    let mut msg = e.to_string();
875    let mut src = std::error::Error::source(e);
876    while let Some(s) = src {
877        msg.push_str(": ");
878        msg.push_str(&s.to_string());
879        src = std::error::Error::source(s);
880    }
881    msg
882}
883
884/// The instance the admin editor operates on.
885///
886/// Registered by the host at boot. A `OnceLock` rather than a field on
887/// `AdminState` so wiring the editor does not change the admin router's
888/// signature for every existing host.
889/// The identity [`TenantTemplates::claim`] binds a directory to: when the
890/// tenant's database had its first migration applied. It does not change
891/// for the life of the database and is new for any database provisioned
892/// later, a purged slug's successor included. `None` before any migration.
893///
894/// # Errors
895/// Driver / query failures.
896pub async fn database_birth(
897    pool: &rustango::sql::Pool,
898) -> Result<Option<String>, rustango::sql::ExecError> {
899    // `applied_at` is TIMESTAMPTZ, DATETIME or TEXT by dialect; read it as
900    // text on each.
901    let as_text = match pool.dialect().name() {
902        "postgres" => "CAST(MIN(applied_at) AS TEXT)",
903        "mysql" => "CAST(MIN(applied_at) AS CHAR)",
904        _ => "MIN(applied_at)",
905    };
906    // The framework's migration ledger (its name is not re-exported).
907    let sql = format!("SELECT {as_text} FROM __rustango_migrations__");
908    let rows: Vec<(Option<String>,)> = rustango::sql::raw_query_pool(&sql, Vec::new(), pool).await?;
909    Ok(rows.into_iter().next().and_then(|r| r.0))
910}
911
912static INSTALLED: std::sync::OnceLock<Arc<TenantTemplates>> = std::sync::OnceLock::new();
913
914/// Make this instance available to the admin template editor.
915pub fn install(tt: Arc<TenantTemplates>) {
916    // Set once; a second install would be silently lost otherwise (#697).
917    if INSTALLED.set(tt).is_err() {
918        tracing::error!(target: "rustango_cms", "install: tenant templates are already installed; this set is ignored");
919    }
920}
921
922/// The installed instance, if the host configured one.
923#[must_use]
924pub fn installed() -> Option<Arc<TenantTemplates>> {
925    INSTALLED.get().cloned()
926}
927
928#[cfg(test)]
929mod tests {
930    use super::*;
931    use std::sync::atomic::{AtomicU32, Ordering};
932
933    static N: AtomicU32 = AtomicU32::new(0);
934
935    /// A scratch directory that removes itself. Avoids a `tempfile`
936    /// dev-dependency for a handful of tests.
937    struct Scratch(PathBuf);
938    impl Scratch {
939        fn new() -> Self {
940            let p = std::env::temp_dir().join(format!(
941                "rcms-tt-{}-{}",
942                std::process::id(),
943                N.fetch_add(1, Ordering::Relaxed),
944            ));
945            std::fs::create_dir_all(&p).expect("scratch");
946            Self(p)
947        }
948        fn write(&self, rel: &str, body: &str) {
949            let path = self.0.join(rel);
950            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
951            std::fs::write(path, body).unwrap();
952        }
953    }
954    impl Drop for Scratch {
955        fn drop(&mut self) {
956            let _ = std::fs::remove_dir_all(&self.0);
957        }
958    }
959
960    /// The global set: a base with a block, and a page that fills it.
961    fn global() -> Arc<Tera> {
962        let mut t = Tera::default();
963        t.add_raw_templates(vec![
964            ("base.html", "GLOBAL-BASE[{% block body %}{% endblock %}]"),
965            ("page.html", "{% extends \"base.html\" %}{% block body %}global-page{% endblock %}"),
966            ("only_global.html", "only-global"),
967        ])
968        .unwrap();
969        t.build_inheritance_chains().unwrap();
970        Arc::new(t)
971    }
972
973    fn render(t: &Tera, name: &str) -> String {
974        t.render(name, &tera::Context::new()).expect("render")
975    }
976
977    #[test]
978    fn a_tenant_without_a_directory_gets_the_global_set_itself() {
979        // Not a clone: the common case (tenant has customised nothing)
980        // must cost neither memory nor a cache slot.
981        let s = Scratch::new();
982        let base = global();
983        let tt = TenantTemplates::new(Arc::clone(&base), &s.0);
984        let got = tt.for_tenant("nobody");
985        assert!(Arc::ptr_eq(&got, &base), "should hand back the global Arc");
986        assert_eq!(tt.cache.read().unwrap().len(), 0, "no cache entry either");
987    }
988
989    #[test]
990    fn a_tenant_template_wins_over_the_global_one_of_the_same_name() {
991        let s = Scratch::new();
992        s.write("acme/page.html", "acme-page");
993        let tt = TenantTemplates::new(global(), &s.0);
994        assert_eq!(render(&tt.for_tenant("acme"), "page.html"), "acme-page");
995    }
996
997    #[test]
998    fn anything_the_tenant_has_not_overridden_falls_back() {
999        let s = Scratch::new();
1000        s.write("acme/page.html", "acme-page");
1001        let tt = TenantTemplates::new(global(), &s.0);
1002        let t = tt.for_tenant("acme");
1003        assert_eq!(render(&t, "only_global.html"), "only-global");
1004    }
1005
1006    #[test]
1007    fn extends_resolves_to_the_tenants_base_not_the_global_one() {
1008        // The whole reason this is one instance per tenant rather than
1009        // name prefixes in a shared one. The tenant's page says
1010        // `{% extends "base.html" %}` — unmodified, copy-pasteable — and
1011        // must get the tenant's base.
1012        let s = Scratch::new();
1013        s.write("acme/base.html", "ACME-BASE[{% block body %}{% endblock %}]");
1014        let tt = TenantTemplates::new(global(), &s.0);
1015        let out = render(&tt.for_tenant("acme"), "page.html");
1016        assert_eq!(out, "ACME-BASE[global-page]", "got {out}");
1017
1018        // And a tenant that overrode nothing still gets the global base.
1019        assert_eq!(render(&tt.for_tenant("other"), "page.html"), "GLOBAL-BASE[global-page]");
1020    }
1021
1022    #[test]
1023    fn nested_directories_keep_the_name_the_global_set_uses() {
1024        // `acme/blocks/hero.html` must register as `blocks/hero.html`,
1025        // or a copied template's `{% include %}` would not match.
1026        let s = Scratch::new();
1027        s.write("acme/blocks/hero.html", "acme-hero");
1028        s.write("acme/page.html", "{% include \"blocks/hero.html\" %}");
1029        let tt = TenantTemplates::new(global(), &s.0);
1030        assert_eq!(render(&tt.for_tenant("acme"), "page.html"), "acme-hero");
1031    }
1032
1033    #[test]
1034    fn non_html_files_are_ignored() {
1035        let s = Scratch::new();
1036        s.write("acme/page.html", "acme-page");
1037        s.write("acme/README.md", "not a template");
1038        s.write("acme/style.css", "body{}");
1039        let tt = TenantTemplates::new(global(), &s.0);
1040        let t = tt.for_tenant("acme");
1041        assert_eq!(render(&t, "page.html"), "acme-page");
1042        assert!(t.get_template_names().all(|n| n.ends_with(".html")));
1043    }
1044
1045    #[test]
1046    fn a_repeat_lookup_reuses_the_built_instance() {
1047        let s = Scratch::new();
1048        s.write("acme/page.html", "acme-page");
1049        let tt = TenantTemplates::new(global(), &s.0).with_reload(Reload::Never);
1050        let a = tt.for_tenant("acme");
1051        let b = tt.for_tenant("acme");
1052        assert!(Arc::ptr_eq(&a, &b), "should not rebuild on every request");
1053    }
1054
1055    #[test]
1056    fn an_edit_is_picked_up_without_a_restart() {
1057        // The point of the whole design: drop a file, next request sees
1058        // it — no rebuild, no process restart.
1059        let s = Scratch::new();
1060        s.write("acme/page.html", "before");
1061        let tt = TenantTemplates::new(global(), &s.0).with_reload(Reload::Always);
1062        assert_eq!(render(&tt.for_tenant("acme"), "page.html"), "before");
1063
1064        s.write("acme/page.html", "after-and-longer");
1065        assert_eq!(render(&tt.for_tenant("acme"), "page.html"), "after-and-longer");
1066    }
1067
1068    #[test]
1069    fn a_new_file_is_noticed_not_just_a_changed_one() {
1070        let s = Scratch::new();
1071        s.write("acme/page.html", "acme-page");
1072        let tt = TenantTemplates::new(global(), &s.0).with_reload(Reload::Always);
1073        let _ = tt.for_tenant("acme");
1074
1075        s.write("acme/only_global.html", "acme-now-owns-this");
1076        assert_eq!(
1077            render(&tt.for_tenant("acme"), "only_global.html"),
1078            "acme-now-owns-this",
1079        );
1080    }
1081
1082    #[test]
1083    fn reload_never_does_not_notice_an_edit() {
1084        // Documents the trade rather than leaving it implied.
1085        let s = Scratch::new();
1086        s.write("acme/page.html", "before");
1087        let tt = TenantTemplates::new(global(), &s.0).with_reload(Reload::Never);
1088        assert_eq!(render(&tt.for_tenant("acme"), "page.html"), "before");
1089        s.write("acme/page.html", "after-and-longer");
1090        assert_eq!(render(&tt.for_tenant("acme"), "page.html"), "before");
1091    }
1092
1093    #[test]
1094    fn a_malformed_tenant_template_falls_back_instead_of_breaking_the_site() {
1095        // One bad file must cost that page, not every page the tenant has.
1096        let s = Scratch::new();
1097        s.write("acme/page.html", "{% for x in %}broken");
1098        s.write("acme/only_global.html", "acme-fine");
1099        let tt = TenantTemplates::new(global(), &s.0);
1100        let t = tt.for_tenant("acme");
1101        assert_eq!(render(&t, "page.html"), "GLOBAL-BASE[global-page]");
1102        assert_eq!(render(&t, "only_global.html"), "acme-fine");
1103    }
1104
1105    #[test]
1106    fn a_slug_cannot_climb_out_of_the_root() {
1107        // Slugs come from the registry, not a request — but a path is
1108        // still built from them, so they are not trusted blindly.
1109        let s = Scratch::new();
1110        s.write("acme/page.html", "acme-page");
1111        let tt = TenantTemplates::new(global(), &s.0);
1112        for slug in ["..", ".", "", "../acme", "a/b", "a\\b"] {
1113            assert!(tt.tenant_dir(slug).is_none(), "slug {slug:?} must be refused");
1114        }
1115    }
1116
1117    // ---- editor CRUD ---------------------------------------------------
1118
1119    fn store(s: &Scratch) -> TenantTemplates {
1120        // A global dir the editor can read fallbacks from.
1121        s.write("_global/base.html", "GLOBAL-BASE[{% block body %}{% endblock %}]");
1122        s.write("_global/page.html", "{% extends \"base.html\" %}{% block body %}g{% endblock %}");
1123        TenantTemplates::new(global(), s.0.join("t")).with_global_dir(s.0.join("_global"))
1124    }
1125
1126    #[test]
1127    fn a_template_that_extends_a_global_parent_validates() {
1128        // The bug this exists for: validating against an empty Tera made
1129        // `{% extends "base.html" %}` look broken, because the parent was
1130        // "not loaded" — so every realistic template was rejected.
1131        let s = Scratch::new();
1132        let tt = store(&s);
1133        tt.write_override("acme", "page.html", "{% extends \"base.html\" %}{% block body %}a{% endblock %}")
1134            .expect("extending a global parent is valid");
1135        assert!(tt.read_override("acme", "page.html").unwrap().contains("{% block body %}a"));
1136    }
1137
1138    #[test]
1139    fn extending_a_parent_that_does_not_exist_is_refused() {
1140        // The check is stronger than syntax: a missing parent is the
1141        // mistake an author makes copying a template between tenants.
1142        let s = Scratch::new();
1143        let tt = store(&s);
1144        let err = tt
1145            .write_override("acme", "page.html", "{% extends \"nope.html\" %}")
1146            .expect_err("must refuse");
1147        assert!(matches!(err, EditError::Invalid(_)), "{err}");
1148        assert!(err.to_string().contains("nope.html"), "{err}");
1149        assert!(tt.read_override("acme", "page.html").is_none(), "nothing written");
1150    }
1151
1152    #[test]
1153    fn a_syntax_error_is_refused_with_a_useful_message() {
1154        let s = Scratch::new();
1155        let tt = store(&s);
1156        let err = tt.write_override("acme", "x.html", "{% for a in %}").expect_err("must refuse");
1157        // The top-level Tera message is just "Failed to parse"; the cause
1158        // carries the detail, so the chain must be flattened.
1159        assert!(err.to_string().len() > "Failed to parse 'x.html'".len(), "{err}");
1160    }
1161
1162    #[test]
1163    fn a_tenants_own_base_is_used_when_validating_its_other_templates() {
1164        // acme overrides base.html; a page extending "base.html" must
1165        // validate against *acme's* base, not only the global one.
1166        let s = Scratch::new();
1167        let tt = store(&s);
1168        tt.write_override("acme", "base.html", "A[{% block body %}{% endblock %}]").unwrap();
1169        tt.write_override("acme", "page.html", "{% extends \"base.html\" %}{% block body %}x{% endblock %}")
1170            .expect("valid against the tenant's own base");
1171    }
1172
1173    #[test]
1174    fn listing_marks_overrides_and_includes_inherited_names() {
1175        let s = Scratch::new();
1176        let tt = store(&s);
1177        tt.write_override("acme", "page.html", "own").unwrap();
1178        let rows = tt.list_for("acme");
1179        let by: HashMap<&str, Source> = rows.iter().map(|e| (e.name.as_str(), e.source)).collect();
1180        assert_eq!(by.get("page.html"), Some(&Source::Override));
1181        assert_eq!(by.get("base.html"), Some(&Source::Global), "inherited names are listed too");
1182    }
1183
1184    #[test]
1185    fn deleting_an_override_reverts_to_the_global_one() {
1186        let s = Scratch::new();
1187        let tt = store(&s);
1188        tt.write_override("acme", "page.html", "own").unwrap();
1189        assert!(tt.read_override("acme", "page.html").is_some());
1190        tt.delete_override("acme", "page.html").unwrap();
1191        assert!(tt.read_override("acme", "page.html").is_none());
1192        // The global file is untouched — reverting is not deleting.
1193        assert!(tt.read_global("page.html").is_some(), "global must survive");
1194    }
1195
1196    #[test]
1197    fn deleting_something_never_overridden_is_not_an_error() {
1198        let s = Scratch::new();
1199        let tt = store(&s);
1200        tt.delete_override("acme", "page.html").expect("no-op, not a failure");
1201    }
1202
1203    #[test]
1204    fn a_name_that_escapes_the_tenant_directory_is_refused() {
1205        // Without this the editor would write anywhere the process can
1206        // reach. `..` in any position is the whole game.
1207        for bad in ["../../evil.html", "a/../../b.html", "..", "../x.html",
1208                    ".hidden.html", "notatemplate.txt", "", "x.html/"] {
1209            assert!(safe_name(bad).is_err(), "{bad:?} must be refused");
1210        }
1211        for ok in ["page.html", "blocks/hero.html", "a/b/c.html", "/page.html"] {
1212            assert!(safe_name(ok).is_ok(), "{ok:?} must be allowed");
1213        }
1214    }
1215
1216    #[test]
1217    fn an_absolute_looking_name_is_confined_not_escaped() {
1218        // A leading `/` is stripped as a convenience — an author may
1219        // type `/page.html`. The property that matters is not that
1220        // scary-looking names are *rejected*, but that whatever survives
1221        // resolves INSIDE the tenant's own directory.
1222        let s = Scratch::new();
1223        let tt = store(&s);
1224        let name = safe_name("/etc/passwd.html").expect("stripped to a relative name");
1225        assert_eq!(name, "etc/passwd.html");
1226
1227        tt.write_override("acme", "/etc/passwd.html", "x").unwrap();
1228        assert!(
1229            s.0.join("t/acme/etc/passwd.html").exists(),
1230            "must land under the tenant, as an oddly-named template",
1231        );
1232        assert!(
1233            !std::path::Path::new("/etc/passwd.html").exists(),
1234            "and must not have touched the real filesystem root",
1235        );
1236    }
1237
1238    #[test]
1239    fn every_accepted_name_resolves_inside_the_tenant_directory() {
1240        // Belt and braces over `safe_name`: assert the *resolved path*,
1241        // not just the string, for anything the validator lets through.
1242        let s = Scratch::new();
1243        let tt = store(&s);
1244        let dir = tt.dir_for("acme").unwrap();
1245        for candidate in ["page.html", "/page.html", "a/b/c.html", "/etc/passwd.html"] {
1246            let name = safe_name(candidate).expect("accepted");
1247            let path = dir.join(&name);
1248            assert!(
1249                path.starts_with(&dir),
1250                "{candidate:?} resolved to {path:?}, outside {dir:?}",
1251            );
1252        }
1253    }
1254
1255    #[test]
1256    fn a_refused_write_leaves_no_file_behind() {
1257        let s = Scratch::new();
1258        let tt = store(&s);
1259        assert!(tt.write_override("acme", "../escape.html", "x").is_err());
1260        assert!(!s.0.join("escape.html").exists(), "must not write outside");
1261    }
1262
1263    #[test]
1264    fn a_nested_override_and_its_empty_parents_are_cleaned_up() {
1265        let s = Scratch::new();
1266        let tt = store(&s);
1267        tt.write_override("acme", "blocks/deep/hero.html", "h").unwrap();
1268        assert!(s.0.join("t/acme/blocks/deep/hero.html").exists());
1269        tt.delete_override("acme", "blocks/deep/hero.html").unwrap();
1270        assert!(!s.0.join("t/acme/blocks").exists(), "empty dirs tidied");
1271        assert!(s.0.join("t/acme").exists(), "but not the tenant's own dir");
1272    }
1273
1274    #[test]
1275    fn an_edit_through_the_store_is_visible_to_the_renderer() {
1276        // Editor and renderer must share one instance, or a save would
1277        // write files a different cache is serving from.
1278        let s = Scratch::new();
1279        let tt = store(&s).with_reload(Reload::Always);
1280        tt.write_override("acme", "page.html", "{% extends \"base.html\" %}{% block body %}EDITED{% endblock %}")
1281            .unwrap();
1282        let out = tt.for_tenant("acme").render("page.html", &tera::Context::new()).unwrap();
1283        assert_eq!(out, "GLOBAL-BASE[EDITED]");
1284    }
1285
1286    #[test]
1287    fn the_renderable_set_includes_overrides_globals_and_baked_templates() {
1288        // What the page-type picker offers. It must come from the Tera
1289        // instance, not a directory listing: a host can register a
1290        // template in code that has no file to stat, and the renderer
1291        // will happily resolve it.
1292        let s = Scratch::new();
1293        let tt = store(&s);
1294        tt.write_override("acme", "own.html", "own").unwrap();
1295        let names: Vec<String> = tt
1296            .for_tenant("acme")
1297            .get_template_names()
1298            .map(str::to_owned)
1299            .collect();
1300        assert!(names.iter().any(|n| n == "own.html"), "tenant override: {names:?}");
1301        assert!(names.iter().any(|n| n == "page.html"), "baked/global: {names:?}");
1302    }
1303
1304    #[test]
1305    fn a_name_the_tenant_cannot_render_is_absent_from_the_set() {
1306        // The page-type assignment checks membership of this set before
1307        // saving, so a name missing here is a name that would 500 every
1308        // page of that type.
1309        let s = Scratch::new();
1310        let tt = store(&s);
1311        let names: Vec<String> = tt
1312            .for_tenant("acme")
1313            .get_template_names()
1314            .map(str::to_owned)
1315            .collect();
1316        assert!(!names.iter().any(|n| n == "does_not_exist.html"));
1317    }
1318
1319    /// Not an assertion — a measurement, run on demand:
1320    /// `cargo test --features sqlite --lib cost_of -- --ignored --nocapture`
1321    #[test]
1322    #[ignore = "measurement, not a pass/fail check"]
1323    fn cost_of_the_tenant_template_layer() {
1324        use std::time::Instant;
1325        let s = Scratch::new();
1326        // A corpus with some bulk, closer to a real global set than the
1327        // three-template fixture.
1328        let mut base = Tera::default();
1329        for i in 0..60 {
1330            base.add_raw_template(&format!("bulk/t{i}.html"), "{% block b %}{% endblock %}x")
1331                .unwrap();
1332        }
1333        base.add_raw_template("base.html", "B[{% block body %}{% endblock %}]").unwrap();
1334        base.build_inheritance_chains().unwrap();
1335        let base = Arc::new(base);
1336
1337        for n in [1usize, 5, 20] {
1338            let slug = format!("t{n}");
1339            for i in 0..n {
1340                s.write(&format!("{slug}/f{i}.html"), "{% extends \"base.html\" %}{% block body %}y{% endblock %}");
1341            }
1342            let tt = TenantTemplates::new(Arc::clone(&base), &s.0);
1343
1344            let t0 = Instant::now();
1345            let _ = tt.for_tenant(&slug);
1346            let cold = t0.elapsed();
1347
1348            let t1 = Instant::now();
1349            for _ in 0..10_000 { let _ = tt.for_tenant(&slug); }
1350            let hit = t1.elapsed() / 10_000;
1351
1352            let dir = tt.dir_for(&slug).unwrap();
1353            let t2 = Instant::now();
1354            for _ in 0..1_000 { let _ = fingerprint(&dir); }
1355            let fp = t2.elapsed() / 1_000;
1356
1357            println!(
1358                "  {n:>2} override(s): cold build {:>8.3?} | cached hit {:>8.3?} | fingerprint {:>8.3?}",
1359                cold, hit, fp
1360            );
1361        }
1362
1363        let tt = TenantTemplates::new(Arc::clone(&base), &s.0);
1364        let t = Instant::now();
1365        for _ in 0..10_000 { let _ = tt.for_tenant("no-such-tenant"); }
1366        println!("   no overrides: {:>8.3?} per call (returns the global Arc)", t.elapsed() / 10_000);
1367    }
1368
1369    // ---- cross-tenant isolation ---------------------------------------
1370
1371    /// Two tenants under one root, with a symlink planted in the first.
1372    fn two_tenants(s: &Scratch) -> TenantTemplates {
1373        s.write("_global/base.html", "GLOBAL-BASE[{% block body %}{% endblock %}]");
1374        s.write("t/acme/own.html", "acme-own");
1375        s.write("t/other/secret.html", "OTHER-TENANT-SECRET");
1376        std::os::unix::fs::symlink(
1377            s.0.join("t/other/secret.html"),
1378            s.0.join("t/acme/peek.html"),
1379        )
1380        .expect("symlink");
1381        TenantTemplates::new(global(), s.0.join("t")).with_global_dir(s.0.join("_global"))
1382    }
1383
1384    #[test]
1385    fn a_symlink_out_of_the_tenant_directory_cannot_be_read() {
1386        // Demonstrated against a running server before this guard
1387        // existed: `safe_name` is lexical, so a link whose *name* is
1388        // ordinary sailed straight through and leaked another tenant's
1389        // template.
1390        let s = Scratch::new();
1391        let tt = two_tenants(&s);
1392        assert!(tt.read_override("acme", "peek.html").is_none(), "must not read through the link");
1393        assert_eq!(tt.read_override("acme", "own.html").as_deref(), Some("acme-own"));
1394    }
1395
1396    #[test]
1397    fn a_symlink_out_of_the_tenant_directory_cannot_be_written_through() {
1398        // The worse half: the same link allowed an *overwrite* of the
1399        // other tenant's file.
1400        let s = Scratch::new();
1401        let tt = two_tenants(&s);
1402        let err = tt
1403            .write_override("acme", "peek.html", "OVERWRITTEN")
1404            .expect_err("must refuse");
1405        assert!(matches!(err, EditError::BadName(_)), "{err}");
1406        assert_eq!(
1407            std::fs::read_to_string(s.0.join("t/other/secret.html")).unwrap(),
1408            "OTHER-TENANT-SECRET",
1409            "the other tenant's file must be untouched",
1410        );
1411    }
1412
1413    #[test]
1414    fn a_symlink_out_of_the_tenant_directory_cannot_be_deleted_through() {
1415        let s = Scratch::new();
1416        let tt = two_tenants(&s);
1417        assert!(tt.delete_override("acme", "peek.html").is_err());
1418        assert!(s.0.join("t/other/secret.html").exists(), "target must survive");
1419    }
1420
1421    #[test]
1422    fn an_escaping_symlink_is_neither_listed_nor_rendered() {
1423        // Guarding the writes alone would close the door and leave a
1424        // window: the link would still be picked up by the walk, so the
1425        // tenant would *render* another tenant's template.
1426        let s = Scratch::new();
1427        let tt = two_tenants(&s);
1428        let names: Vec<String> = tt.list_for("acme").into_iter().map(|e| e.name).collect();
1429        assert!(names.iter().any(|n| n == "own.html"), "{names:?}");
1430        assert!(!names.iter().any(|n| n == "peek.html"), "escaping link listed: {names:?}");
1431
1432        let rendered: Vec<String> = tt
1433            .for_tenant("acme")
1434            .get_template_names()
1435            .map(str::to_owned)
1436            .collect();
1437        assert!(!rendered.iter().any(|n| n == "peek.html"), "escaping link loaded: {rendered:?}");
1438    }
1439
1440    #[test]
1441    fn a_symlink_that_stays_inside_the_tenant_is_still_fine() {
1442        // The rule is containment, not "no symlinks" — a link within the
1443        // tenant's own tree is harmless and refusing it would be
1444        // surprising.
1445        let s = Scratch::new();
1446        let tt = two_tenants(&s);
1447        std::os::unix::fs::symlink(s.0.join("t/acme/own.html"), s.0.join("t/acme/alias.html"))
1448            .expect("symlink");
1449        assert_eq!(tt.read_override("acme", "alias.html").as_deref(), Some("acme-own"));
1450    }
1451
1452    #[test]
1453    fn one_tenant_cannot_reach_another_by_name_alone() {
1454        // The lexical guard, kept honest alongside the resolved one.
1455        let s = Scratch::new();
1456        let tt = two_tenants(&s);
1457        for name in ["../other/secret.html", "/../other/secret.html", "..%2Fother.html"] {
1458            assert!(
1459                tt.read_override("acme", name).is_none(),
1460                "{name:?} must not resolve",
1461            );
1462        }
1463    }
1464
1465    #[test]
1466    fn the_cache_is_bounded_and_evicts_the_least_recently_used() {
1467        let s = Scratch::new();
1468        for i in 0..4 {
1469            s.write(&format!("t{i}/page.html"), &format!("tenant-{i}"));
1470        }
1471        let tt = TenantTemplates::new(global(), &s.0)
1472            .with_reload(Reload::Never)
1473            .with_capacity(2);
1474        let _ = tt.for_tenant("t0");
1475        let _ = tt.for_tenant("t1");
1476        let _ = tt.for_tenant("t0"); // t0 is now the more recently used
1477        let _ = tt.for_tenant("t2"); // evicts t1
1478
1479        let cache = tt.cache.read().unwrap();
1480        assert_eq!(cache.len(), 2, "cache must stay bounded");
1481        assert!(cache.contains_key("t0"), "recently used survives");
1482        assert!(!cache.contains_key("t1"), "least recently used evicted");
1483    }
1484
1485    #[test]
1486    fn an_evicted_tenant_still_renders_correctly() {
1487        // Eviction is a cost, never a correctness change.
1488        let s = Scratch::new();
1489        s.write("t0/page.html", "zero");
1490        s.write("t1/page.html", "one");
1491        let tt = TenantTemplates::new(global(), &s.0).with_capacity(1);
1492        assert_eq!(render(&tt.for_tenant("t0"), "page.html"), "zero");
1493        assert_eq!(render(&tt.for_tenant("t1"), "page.html"), "one");
1494        assert_eq!(render(&tt.for_tenant("t0"), "page.html"), "zero");
1495    }
1496
1497    /// A successor tenant on a reused slug never renders the
1498    /// previous owner's overrides.
1499    #[test]
1500    fn a_reused_slug_does_not_inherit_the_old_overrides() {
1501        let s = Scratch::new();
1502        s.write("acme/page.html", "OLD-CUSTOMER");
1503        let tt = TenantTemplates::new(global(), &s.0);
1504
1505        assert_eq!(tt.claim("acme", "db-born-1").expect("claim"), Claim::Adopted);
1506        assert_eq!(tt.claim("acme", "db-born-1").expect("claim"), Claim::Owned);
1507        assert_eq!(render(&tt.for_tenant("acme"), "page.html"), "OLD-CUSTOMER");
1508
1509        // Purged and re-provisioned: same slug, new database.
1510        match tt.claim("acme", "db-born-2").expect("claim") {
1511            Claim::MovedAside { previous_owner, to } => {
1512                assert_eq!(previous_owner, "db-born-1");
1513                assert!(to.join("page.html").is_file(), "kept, not deleted");
1514            }
1515            other => panic!("expected the old directory moved aside, got {other:?}"),
1516        }
1517        assert_eq!(
1518            render(&tt.for_tenant("acme"), "page.html"),
1519            "GLOBAL-BASE[global-page]",
1520            "the cached old instance is gone too"
1521        );
1522        assert_eq!(tt.claim("acme", "db-born-2").expect("claim"), Claim::NoOverrides);
1523        assert!(tt.tenant_dir(".orphaned").is_none(), "the aside directory is no tenant's");
1524    }
1525
1526    #[test]
1527    fn the_owner_marker_is_not_a_template() {
1528        let s = Scratch::new();
1529        s.write("acme/page.html", "MINE");
1530        let tt = TenantTemplates::new(global(), &s.0);
1531        tt.claim("acme", "db").expect("claim");
1532        assert_eq!(render(&tt.for_tenant("acme"), "page.html"), "MINE");
1533        assert!(tt.for_tenant("acme").get_template(OWNER_FILE).is_err());
1534    }
1535
1536    #[cfg(feature = "sqlite")]
1537    #[tokio::test]
1538    async fn database_birth_is_the_first_applied_migration() {
1539        let pool = rustango::sql::Pool::connect("sqlite::memory:").await.expect("pool");
1540        rustango::sql::raw_execute_pool(
1541            &pool,
1542            "CREATE TABLE __rustango_migrations__ (name TEXT PRIMARY KEY, applied_at TEXT NOT NULL)",
1543            Vec::new(),
1544        )
1545        .await
1546        .expect("ledger");
1547        assert_eq!(database_birth(&pool).await.expect("empty"), None);
1548        for (name, at) in [("0002_b", "2026-02-01T00:00:00+00:00"), ("0001_a", "2026-01-01T00:00:00+00:00")] {
1549            rustango::sql::raw_execute_pool(
1550                &pool,
1551                &format!("INSERT INTO __rustango_migrations__ VALUES ('{name}', '{at}')"),
1552                Vec::new(),
1553            )
1554            .await
1555            .expect("row");
1556        }
1557        assert_eq!(
1558            database_birth(&pool).await.expect("birth").as_deref(),
1559            Some("2026-01-01T00:00:00+00:00")
1560        );
1561    }
1562
1563    /// The async render path takes a cached instance without
1564    /// touching the disk, and falls back to `for_tenant` when one is due.
1565    #[test]
1566    fn cached_serves_only_an_instance_not_due_a_check() {
1567        let s = Scratch::new();
1568        s.write("acme/page.html", "MINE");
1569        let never = TenantTemplates::new(global(), &s.0).with_reload(Reload::Never);
1570        assert!(never.cached("acme").is_none(), "nothing built yet");
1571        let built = never.for_tenant("acme");
1572        let hit = never.cached("acme").expect("cached after a build");
1573        assert!(Arc::ptr_eq(&built, &hit));
1574
1575        let always = TenantTemplates::new(global(), &s.0).with_reload(Reload::Always);
1576        let _ = always.for_tenant("acme");
1577        assert!(always.cached("acme").is_none(), "always due: re-check on the blocking pool");
1578    }
1579
1580    /// A symlink out of the tenant's folder can't be used to create
1581    /// directories outside it, not just files.
1582    #[cfg(unix)]
1583    #[test]
1584    fn a_symlinked_subdirectory_creates_nothing_outside() {
1585        let s = Scratch::new();
1586        let outside = Scratch::new();
1587        std::fs::create_dir_all(s.0.join("acme")).unwrap();
1588        std::os::unix::fs::symlink(&outside.0, s.0.join("acme/evil")).unwrap();
1589        let tt = TenantTemplates::new(global(), &s.0);
1590        assert!(tt.write_override("acme", "evil/new/x.html", "x").is_err());
1591        assert!(!outside.0.join("new").exists(), "no directory was created outside");
1592    }
1593}