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
717/// Whether `path` really lives inside `root`, symlinks resolved.
718///
719/// [`safe_name`] is lexical — it rejects `..` in the *name*, which is
720/// enough to stop a crafted request escaping. It cannot see a symlink
721/// already sitting on disk: a link at
722/// `templates_tenants/acme/peek.html` pointing at another tenant's file
723/// let `acme` both read and **overwrite** it, because every string
724/// involved looked perfectly ordinary.
725///
726/// Templates arrive by rsync or git, and a symlink is easy to miss in a
727/// diff, so the check has to be on the resolved path rather than the
728/// name. Resolves the deepest existing ancestor (the leaf may not exist
729/// yet, on a create) and re-appends the rest.
730fn contained(root: &Path, path: &Path) -> bool {
731    let Ok(root_real) = root.canonicalize() else {
732        return false;
733    };
734    let mut probe = path.to_path_buf();
735    let mut tail: Vec<std::ffi::OsString> = Vec::new();
736    loop {
737        if let Ok(real) = probe.canonicalize() {
738            let mut full = real;
739            for seg in tail.iter().rev() {
740                full.push(seg);
741            }
742            return full.starts_with(&root_real);
743        }
744        let Some(name) = probe.file_name().map(std::ffi::OsStr::to_owned) else {
745            return false;
746        };
747        tail.push(name);
748        if !probe.pop() {
749            return false;
750        }
751    }
752}
753
754/// Flatten a Tera error and its causes into one line.
755///
756/// Tera puts the actual problem in `source()` — the top-level message is
757/// usually just "Failed to parse 'x.html'", which tells an author
758/// nothing.
759fn chain(e: &tera::Error) -> String {
760    let mut msg = e.to_string();
761    let mut src = std::error::Error::source(e);
762    while let Some(s) = src {
763        msg.push_str(": ");
764        msg.push_str(&s.to_string());
765        src = std::error::Error::source(s);
766    }
767    msg
768}
769
770/// The instance the admin editor operates on.
771///
772/// Registered by the host at boot. A `OnceLock` rather than a field on
773/// `AdminState` so wiring the editor does not change the admin router's
774/// signature for every existing host.
775/// The identity [`TenantTemplates::claim`] binds a directory to: when the
776/// tenant's database had its first migration applied. It does not change
777/// for the life of the database and is new for any database provisioned
778/// later, a purged slug's successor included. `None` before any migration.
779///
780/// # Errors
781/// Driver / query failures.
782pub async fn database_birth(
783    pool: &rustango::sql::Pool,
784) -> Result<Option<String>, rustango::sql::ExecError> {
785    // `applied_at` is TIMESTAMPTZ, DATETIME or TEXT by dialect; read it as
786    // text on each.
787    let as_text = match pool.dialect().name() {
788        "postgres" => "CAST(MIN(applied_at) AS TEXT)",
789        "mysql" => "CAST(MIN(applied_at) AS CHAR)",
790        _ => "MIN(applied_at)",
791    };
792    // The framework's migration ledger (its name is not re-exported).
793    let sql = format!("SELECT {as_text} FROM __rustango_migrations__");
794    let rows: Vec<(Option<String>,)> = rustango::sql::raw_query_pool(&sql, Vec::new(), pool).await?;
795    Ok(rows.into_iter().next().and_then(|r| r.0))
796}
797
798static INSTALLED: std::sync::OnceLock<Arc<TenantTemplates>> = std::sync::OnceLock::new();
799
800/// Make this instance available to the admin template editor.
801pub fn install(tt: Arc<TenantTemplates>) {
802    // Set once; a second install would be silently lost otherwise (#697).
803    if INSTALLED.set(tt).is_err() {
804        tracing::error!(target: "rustango_cms", "install: tenant templates are already installed; this set is ignored");
805    }
806}
807
808/// The installed instance, if the host configured one.
809#[must_use]
810pub fn installed() -> Option<Arc<TenantTemplates>> {
811    INSTALLED.get().cloned()
812}
813
814#[cfg(test)]
815mod tests {
816    use super::*;
817    use std::sync::atomic::{AtomicU32, Ordering};
818
819    static N: AtomicU32 = AtomicU32::new(0);
820
821    /// A scratch directory that removes itself. Avoids a `tempfile`
822    /// dev-dependency for a handful of tests.
823    struct Scratch(PathBuf);
824    impl Scratch {
825        fn new() -> Self {
826            let p = std::env::temp_dir().join(format!(
827                "rcms-tt-{}-{}",
828                std::process::id(),
829                N.fetch_add(1, Ordering::Relaxed),
830            ));
831            std::fs::create_dir_all(&p).expect("scratch");
832            Self(p)
833        }
834        fn write(&self, rel: &str, body: &str) {
835            let path = self.0.join(rel);
836            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
837            std::fs::write(path, body).unwrap();
838        }
839    }
840    impl Drop for Scratch {
841        fn drop(&mut self) {
842            let _ = std::fs::remove_dir_all(&self.0);
843        }
844    }
845
846    /// The global set: a base with a block, and a page that fills it.
847    fn global() -> Arc<Tera> {
848        let mut t = Tera::default();
849        t.add_raw_templates(vec![
850            ("base.html", "GLOBAL-BASE[{% block body %}{% endblock %}]"),
851            ("page.html", "{% extends \"base.html\" %}{% block body %}global-page{% endblock %}"),
852            ("only_global.html", "only-global"),
853        ])
854        .unwrap();
855        t.build_inheritance_chains().unwrap();
856        Arc::new(t)
857    }
858
859    fn render(t: &Tera, name: &str) -> String {
860        t.render(name, &tera::Context::new()).expect("render")
861    }
862
863    #[test]
864    fn a_tenant_without_a_directory_gets_the_global_set_itself() {
865        // Not a clone: the common case (tenant has customised nothing)
866        // must cost neither memory nor a cache slot.
867        let s = Scratch::new();
868        let base = global();
869        let tt = TenantTemplates::new(Arc::clone(&base), &s.0);
870        let got = tt.for_tenant("nobody");
871        assert!(Arc::ptr_eq(&got, &base), "should hand back the global Arc");
872        assert_eq!(tt.cache.read().unwrap().len(), 0, "no cache entry either");
873    }
874
875    #[test]
876    fn a_tenant_template_wins_over_the_global_one_of_the_same_name() {
877        let s = Scratch::new();
878        s.write("acme/page.html", "acme-page");
879        let tt = TenantTemplates::new(global(), &s.0);
880        assert_eq!(render(&tt.for_tenant("acme"), "page.html"), "acme-page");
881    }
882
883    #[test]
884    fn anything_the_tenant_has_not_overridden_falls_back() {
885        let s = Scratch::new();
886        s.write("acme/page.html", "acme-page");
887        let tt = TenantTemplates::new(global(), &s.0);
888        let t = tt.for_tenant("acme");
889        assert_eq!(render(&t, "only_global.html"), "only-global");
890    }
891
892    #[test]
893    fn extends_resolves_to_the_tenants_base_not_the_global_one() {
894        // The whole reason this is one instance per tenant rather than
895        // name prefixes in a shared one. The tenant's page says
896        // `{% extends "base.html" %}` — unmodified, copy-pasteable — and
897        // must get the tenant's base.
898        let s = Scratch::new();
899        s.write("acme/base.html", "ACME-BASE[{% block body %}{% endblock %}]");
900        let tt = TenantTemplates::new(global(), &s.0);
901        let out = render(&tt.for_tenant("acme"), "page.html");
902        assert_eq!(out, "ACME-BASE[global-page]", "got {out}");
903
904        // And a tenant that overrode nothing still gets the global base.
905        assert_eq!(render(&tt.for_tenant("other"), "page.html"), "GLOBAL-BASE[global-page]");
906    }
907
908    #[test]
909    fn nested_directories_keep_the_name_the_global_set_uses() {
910        // `acme/blocks/hero.html` must register as `blocks/hero.html`,
911        // or a copied template's `{% include %}` would not match.
912        let s = Scratch::new();
913        s.write("acme/blocks/hero.html", "acme-hero");
914        s.write("acme/page.html", "{% include \"blocks/hero.html\" %}");
915        let tt = TenantTemplates::new(global(), &s.0);
916        assert_eq!(render(&tt.for_tenant("acme"), "page.html"), "acme-hero");
917    }
918
919    #[test]
920    fn non_html_files_are_ignored() {
921        let s = Scratch::new();
922        s.write("acme/page.html", "acme-page");
923        s.write("acme/README.md", "not a template");
924        s.write("acme/style.css", "body{}");
925        let tt = TenantTemplates::new(global(), &s.0);
926        let t = tt.for_tenant("acme");
927        assert_eq!(render(&t, "page.html"), "acme-page");
928        assert!(t.get_template_names().all(|n| n.ends_with(".html")));
929    }
930
931    #[test]
932    fn a_repeat_lookup_reuses_the_built_instance() {
933        let s = Scratch::new();
934        s.write("acme/page.html", "acme-page");
935        let tt = TenantTemplates::new(global(), &s.0).with_reload(Reload::Never);
936        let a = tt.for_tenant("acme");
937        let b = tt.for_tenant("acme");
938        assert!(Arc::ptr_eq(&a, &b), "should not rebuild on every request");
939    }
940
941    #[test]
942    fn an_edit_is_picked_up_without_a_restart() {
943        // The point of the whole design: drop a file, next request sees
944        // it — no rebuild, no process restart.
945        let s = Scratch::new();
946        s.write("acme/page.html", "before");
947        let tt = TenantTemplates::new(global(), &s.0).with_reload(Reload::Always);
948        assert_eq!(render(&tt.for_tenant("acme"), "page.html"), "before");
949
950        s.write("acme/page.html", "after-and-longer");
951        assert_eq!(render(&tt.for_tenant("acme"), "page.html"), "after-and-longer");
952    }
953
954    #[test]
955    fn a_new_file_is_noticed_not_just_a_changed_one() {
956        let s = Scratch::new();
957        s.write("acme/page.html", "acme-page");
958        let tt = TenantTemplates::new(global(), &s.0).with_reload(Reload::Always);
959        let _ = tt.for_tenant("acme");
960
961        s.write("acme/only_global.html", "acme-now-owns-this");
962        assert_eq!(
963            render(&tt.for_tenant("acme"), "only_global.html"),
964            "acme-now-owns-this",
965        );
966    }
967
968    #[test]
969    fn reload_never_does_not_notice_an_edit() {
970        // Documents the trade rather than leaving it implied.
971        let s = Scratch::new();
972        s.write("acme/page.html", "before");
973        let tt = TenantTemplates::new(global(), &s.0).with_reload(Reload::Never);
974        assert_eq!(render(&tt.for_tenant("acme"), "page.html"), "before");
975        s.write("acme/page.html", "after-and-longer");
976        assert_eq!(render(&tt.for_tenant("acme"), "page.html"), "before");
977    }
978
979    #[test]
980    fn a_malformed_tenant_template_falls_back_instead_of_breaking_the_site() {
981        // One bad file must cost that page, not every page the tenant has.
982        let s = Scratch::new();
983        s.write("acme/page.html", "{% for x in %}broken");
984        s.write("acme/only_global.html", "acme-fine");
985        let tt = TenantTemplates::new(global(), &s.0);
986        let t = tt.for_tenant("acme");
987        assert_eq!(render(&t, "page.html"), "GLOBAL-BASE[global-page]");
988        assert_eq!(render(&t, "only_global.html"), "acme-fine");
989    }
990
991    #[test]
992    fn a_slug_cannot_climb_out_of_the_root() {
993        // Slugs come from the registry, not a request — but a path is
994        // still built from them, so they are not trusted blindly.
995        let s = Scratch::new();
996        s.write("acme/page.html", "acme-page");
997        let tt = TenantTemplates::new(global(), &s.0);
998        for slug in ["..", ".", "", "../acme", "a/b", "a\\b"] {
999            assert!(tt.tenant_dir(slug).is_none(), "slug {slug:?} must be refused");
1000        }
1001    }
1002
1003    // ---- editor CRUD ---------------------------------------------------
1004
1005    fn store(s: &Scratch) -> TenantTemplates {
1006        // A global dir the editor can read fallbacks from.
1007        s.write("_global/base.html", "GLOBAL-BASE[{% block body %}{% endblock %}]");
1008        s.write("_global/page.html", "{% extends \"base.html\" %}{% block body %}g{% endblock %}");
1009        TenantTemplates::new(global(), s.0.join("t")).with_global_dir(s.0.join("_global"))
1010    }
1011
1012    #[test]
1013    fn a_template_that_extends_a_global_parent_validates() {
1014        // The bug this exists for: validating against an empty Tera made
1015        // `{% extends "base.html" %}` look broken, because the parent was
1016        // "not loaded" — so every realistic template was rejected.
1017        let s = Scratch::new();
1018        let tt = store(&s);
1019        tt.write_override("acme", "page.html", "{% extends \"base.html\" %}{% block body %}a{% endblock %}")
1020            .expect("extending a global parent is valid");
1021        assert!(tt.read_override("acme", "page.html").unwrap().contains("{% block body %}a"));
1022    }
1023
1024    #[test]
1025    fn extending_a_parent_that_does_not_exist_is_refused() {
1026        // The check is stronger than syntax: a missing parent is the
1027        // mistake an author makes copying a template between tenants.
1028        let s = Scratch::new();
1029        let tt = store(&s);
1030        let err = tt
1031            .write_override("acme", "page.html", "{% extends \"nope.html\" %}")
1032            .expect_err("must refuse");
1033        assert!(matches!(err, EditError::Invalid(_)), "{err}");
1034        assert!(err.to_string().contains("nope.html"), "{err}");
1035        assert!(tt.read_override("acme", "page.html").is_none(), "nothing written");
1036    }
1037
1038    #[test]
1039    fn a_syntax_error_is_refused_with_a_useful_message() {
1040        let s = Scratch::new();
1041        let tt = store(&s);
1042        let err = tt.write_override("acme", "x.html", "{% for a in %}").expect_err("must refuse");
1043        // The top-level Tera message is just "Failed to parse"; the cause
1044        // carries the detail, so the chain must be flattened.
1045        assert!(err.to_string().len() > "Failed to parse 'x.html'".len(), "{err}");
1046    }
1047
1048    #[test]
1049    fn a_tenants_own_base_is_used_when_validating_its_other_templates() {
1050        // acme overrides base.html; a page extending "base.html" must
1051        // validate against *acme's* base, not only the global one.
1052        let s = Scratch::new();
1053        let tt = store(&s);
1054        tt.write_override("acme", "base.html", "A[{% block body %}{% endblock %}]").unwrap();
1055        tt.write_override("acme", "page.html", "{% extends \"base.html\" %}{% block body %}x{% endblock %}")
1056            .expect("valid against the tenant's own base");
1057    }
1058
1059    #[test]
1060    fn listing_marks_overrides_and_includes_inherited_names() {
1061        let s = Scratch::new();
1062        let tt = store(&s);
1063        tt.write_override("acme", "page.html", "own").unwrap();
1064        let rows = tt.list_for("acme");
1065        let by: HashMap<&str, Source> = rows.iter().map(|e| (e.name.as_str(), e.source)).collect();
1066        assert_eq!(by.get("page.html"), Some(&Source::Override));
1067        assert_eq!(by.get("base.html"), Some(&Source::Global), "inherited names are listed too");
1068    }
1069
1070    #[test]
1071    fn deleting_an_override_reverts_to_the_global_one() {
1072        let s = Scratch::new();
1073        let tt = store(&s);
1074        tt.write_override("acme", "page.html", "own").unwrap();
1075        assert!(tt.read_override("acme", "page.html").is_some());
1076        tt.delete_override("acme", "page.html").unwrap();
1077        assert!(tt.read_override("acme", "page.html").is_none());
1078        // The global file is untouched — reverting is not deleting.
1079        assert!(tt.read_global("page.html").is_some(), "global must survive");
1080    }
1081
1082    #[test]
1083    fn deleting_something_never_overridden_is_not_an_error() {
1084        let s = Scratch::new();
1085        let tt = store(&s);
1086        tt.delete_override("acme", "page.html").expect("no-op, not a failure");
1087    }
1088
1089    #[test]
1090    fn a_name_that_escapes_the_tenant_directory_is_refused() {
1091        // Without this the editor would write anywhere the process can
1092        // reach. `..` in any position is the whole game.
1093        for bad in ["../../evil.html", "a/../../b.html", "..", "../x.html",
1094                    ".hidden.html", "notatemplate.txt", "", "x.html/"] {
1095            assert!(safe_name(bad).is_err(), "{bad:?} must be refused");
1096        }
1097        for ok in ["page.html", "blocks/hero.html", "a/b/c.html", "/page.html"] {
1098            assert!(safe_name(ok).is_ok(), "{ok:?} must be allowed");
1099        }
1100    }
1101
1102    #[test]
1103    fn an_absolute_looking_name_is_confined_not_escaped() {
1104        // A leading `/` is stripped as a convenience — an author may
1105        // type `/page.html`. The property that matters is not that
1106        // scary-looking names are *rejected*, but that whatever survives
1107        // resolves INSIDE the tenant's own directory.
1108        let s = Scratch::new();
1109        let tt = store(&s);
1110        let name = safe_name("/etc/passwd.html").expect("stripped to a relative name");
1111        assert_eq!(name, "etc/passwd.html");
1112
1113        tt.write_override("acme", "/etc/passwd.html", "x").unwrap();
1114        assert!(
1115            s.0.join("t/acme/etc/passwd.html").exists(),
1116            "must land under the tenant, as an oddly-named template",
1117        );
1118        assert!(
1119            !std::path::Path::new("/etc/passwd.html").exists(),
1120            "and must not have touched the real filesystem root",
1121        );
1122    }
1123
1124    #[test]
1125    fn every_accepted_name_resolves_inside_the_tenant_directory() {
1126        // Belt and braces over `safe_name`: assert the *resolved path*,
1127        // not just the string, for anything the validator lets through.
1128        let s = Scratch::new();
1129        let tt = store(&s);
1130        let dir = tt.dir_for("acme").unwrap();
1131        for candidate in ["page.html", "/page.html", "a/b/c.html", "/etc/passwd.html"] {
1132            let name = safe_name(candidate).expect("accepted");
1133            let path = dir.join(&name);
1134            assert!(
1135                path.starts_with(&dir),
1136                "{candidate:?} resolved to {path:?}, outside {dir:?}",
1137            );
1138        }
1139    }
1140
1141    #[test]
1142    fn a_refused_write_leaves_no_file_behind() {
1143        let s = Scratch::new();
1144        let tt = store(&s);
1145        assert!(tt.write_override("acme", "../escape.html", "x").is_err());
1146        assert!(!s.0.join("escape.html").exists(), "must not write outside");
1147    }
1148
1149    #[test]
1150    fn a_nested_override_and_its_empty_parents_are_cleaned_up() {
1151        let s = Scratch::new();
1152        let tt = store(&s);
1153        tt.write_override("acme", "blocks/deep/hero.html", "h").unwrap();
1154        assert!(s.0.join("t/acme/blocks/deep/hero.html").exists());
1155        tt.delete_override("acme", "blocks/deep/hero.html").unwrap();
1156        assert!(!s.0.join("t/acme/blocks").exists(), "empty dirs tidied");
1157        assert!(s.0.join("t/acme").exists(), "but not the tenant's own dir");
1158    }
1159
1160    #[test]
1161    fn an_edit_through_the_store_is_visible_to_the_renderer() {
1162        // Editor and renderer must share one instance, or a save would
1163        // write files a different cache is serving from.
1164        let s = Scratch::new();
1165        let tt = store(&s).with_reload(Reload::Always);
1166        tt.write_override("acme", "page.html", "{% extends \"base.html\" %}{% block body %}EDITED{% endblock %}")
1167            .unwrap();
1168        let out = tt.for_tenant("acme").render("page.html", &tera::Context::new()).unwrap();
1169        assert_eq!(out, "GLOBAL-BASE[EDITED]");
1170    }
1171
1172    #[test]
1173    fn the_renderable_set_includes_overrides_globals_and_baked_templates() {
1174        // What the page-type picker offers. It must come from the Tera
1175        // instance, not a directory listing: a host can register a
1176        // template in code that has no file to stat, and the renderer
1177        // will happily resolve it.
1178        let s = Scratch::new();
1179        let tt = store(&s);
1180        tt.write_override("acme", "own.html", "own").unwrap();
1181        let names: Vec<String> = tt
1182            .for_tenant("acme")
1183            .get_template_names()
1184            .map(str::to_owned)
1185            .collect();
1186        assert!(names.iter().any(|n| n == "own.html"), "tenant override: {names:?}");
1187        assert!(names.iter().any(|n| n == "page.html"), "baked/global: {names:?}");
1188    }
1189
1190    #[test]
1191    fn a_name_the_tenant_cannot_render_is_absent_from_the_set() {
1192        // The page-type assignment checks membership of this set before
1193        // saving, so a name missing here is a name that would 500 every
1194        // page of that type.
1195        let s = Scratch::new();
1196        let tt = store(&s);
1197        let names: Vec<String> = tt
1198            .for_tenant("acme")
1199            .get_template_names()
1200            .map(str::to_owned)
1201            .collect();
1202        assert!(!names.iter().any(|n| n == "does_not_exist.html"));
1203    }
1204
1205    /// Not an assertion — a measurement, run on demand:
1206    /// `cargo test --features sqlite --lib cost_of -- --ignored --nocapture`
1207    #[test]
1208    #[ignore = "measurement, not a pass/fail check"]
1209    fn cost_of_the_tenant_template_layer() {
1210        use std::time::Instant;
1211        let s = Scratch::new();
1212        // A corpus with some bulk, closer to a real global set than the
1213        // three-template fixture.
1214        let mut base = Tera::default();
1215        for i in 0..60 {
1216            base.add_raw_template(&format!("bulk/t{i}.html"), "{% block b %}{% endblock %}x")
1217                .unwrap();
1218        }
1219        base.add_raw_template("base.html", "B[{% block body %}{% endblock %}]").unwrap();
1220        base.build_inheritance_chains().unwrap();
1221        let base = Arc::new(base);
1222
1223        for n in [1usize, 5, 20] {
1224            let slug = format!("t{n}");
1225            for i in 0..n {
1226                s.write(&format!("{slug}/f{i}.html"), "{% extends \"base.html\" %}{% block body %}y{% endblock %}");
1227            }
1228            let tt = TenantTemplates::new(Arc::clone(&base), &s.0);
1229
1230            let t0 = Instant::now();
1231            let _ = tt.for_tenant(&slug);
1232            let cold = t0.elapsed();
1233
1234            let t1 = Instant::now();
1235            for _ in 0..10_000 { let _ = tt.for_tenant(&slug); }
1236            let hit = t1.elapsed() / 10_000;
1237
1238            let dir = tt.dir_for(&slug).unwrap();
1239            let t2 = Instant::now();
1240            for _ in 0..1_000 { let _ = fingerprint(&dir); }
1241            let fp = t2.elapsed() / 1_000;
1242
1243            println!(
1244                "  {n:>2} override(s): cold build {:>8.3?} | cached hit {:>8.3?} | fingerprint {:>8.3?}",
1245                cold, hit, fp
1246            );
1247        }
1248
1249        let tt = TenantTemplates::new(Arc::clone(&base), &s.0);
1250        let t = Instant::now();
1251        for _ in 0..10_000 { let _ = tt.for_tenant("no-such-tenant"); }
1252        println!("   no overrides: {:>8.3?} per call (returns the global Arc)", t.elapsed() / 10_000);
1253    }
1254
1255    // ---- cross-tenant isolation ---------------------------------------
1256
1257    /// Two tenants under one root, with a symlink planted in the first.
1258    fn two_tenants(s: &Scratch) -> TenantTemplates {
1259        s.write("_global/base.html", "GLOBAL-BASE[{% block body %}{% endblock %}]");
1260        s.write("t/acme/own.html", "acme-own");
1261        s.write("t/other/secret.html", "OTHER-TENANT-SECRET");
1262        std::os::unix::fs::symlink(
1263            s.0.join("t/other/secret.html"),
1264            s.0.join("t/acme/peek.html"),
1265        )
1266        .expect("symlink");
1267        TenantTemplates::new(global(), s.0.join("t")).with_global_dir(s.0.join("_global"))
1268    }
1269
1270    #[test]
1271    fn a_symlink_out_of_the_tenant_directory_cannot_be_read() {
1272        // Demonstrated against a running server before this guard
1273        // existed: `safe_name` is lexical, so a link whose *name* is
1274        // ordinary sailed straight through and leaked another tenant's
1275        // template.
1276        let s = Scratch::new();
1277        let tt = two_tenants(&s);
1278        assert!(tt.read_override("acme", "peek.html").is_none(), "must not read through the link");
1279        assert_eq!(tt.read_override("acme", "own.html").as_deref(), Some("acme-own"));
1280    }
1281
1282    #[test]
1283    fn a_symlink_out_of_the_tenant_directory_cannot_be_written_through() {
1284        // The worse half: the same link allowed an *overwrite* of the
1285        // other tenant's file.
1286        let s = Scratch::new();
1287        let tt = two_tenants(&s);
1288        let err = tt
1289            .write_override("acme", "peek.html", "OVERWRITTEN")
1290            .expect_err("must refuse");
1291        assert!(matches!(err, EditError::BadName(_)), "{err}");
1292        assert_eq!(
1293            std::fs::read_to_string(s.0.join("t/other/secret.html")).unwrap(),
1294            "OTHER-TENANT-SECRET",
1295            "the other tenant's file must be untouched",
1296        );
1297    }
1298
1299    #[test]
1300    fn a_symlink_out_of_the_tenant_directory_cannot_be_deleted_through() {
1301        let s = Scratch::new();
1302        let tt = two_tenants(&s);
1303        assert!(tt.delete_override("acme", "peek.html").is_err());
1304        assert!(s.0.join("t/other/secret.html").exists(), "target must survive");
1305    }
1306
1307    #[test]
1308    fn an_escaping_symlink_is_neither_listed_nor_rendered() {
1309        // Guarding the writes alone would close the door and leave a
1310        // window: the link would still be picked up by the walk, so the
1311        // tenant would *render* another tenant's template.
1312        let s = Scratch::new();
1313        let tt = two_tenants(&s);
1314        let names: Vec<String> = tt.list_for("acme").into_iter().map(|e| e.name).collect();
1315        assert!(names.iter().any(|n| n == "own.html"), "{names:?}");
1316        assert!(!names.iter().any(|n| n == "peek.html"), "escaping link listed: {names:?}");
1317
1318        let rendered: Vec<String> = tt
1319            .for_tenant("acme")
1320            .get_template_names()
1321            .map(str::to_owned)
1322            .collect();
1323        assert!(!rendered.iter().any(|n| n == "peek.html"), "escaping link loaded: {rendered:?}");
1324    }
1325
1326    #[test]
1327    fn a_symlink_that_stays_inside_the_tenant_is_still_fine() {
1328        // The rule is containment, not "no symlinks" — a link within the
1329        // tenant's own tree is harmless and refusing it would be
1330        // surprising.
1331        let s = Scratch::new();
1332        let tt = two_tenants(&s);
1333        std::os::unix::fs::symlink(s.0.join("t/acme/own.html"), s.0.join("t/acme/alias.html"))
1334            .expect("symlink");
1335        assert_eq!(tt.read_override("acme", "alias.html").as_deref(), Some("acme-own"));
1336    }
1337
1338    #[test]
1339    fn one_tenant_cannot_reach_another_by_name_alone() {
1340        // The lexical guard, kept honest alongside the resolved one.
1341        let s = Scratch::new();
1342        let tt = two_tenants(&s);
1343        for name in ["../other/secret.html", "/../other/secret.html", "..%2Fother.html"] {
1344            assert!(
1345                tt.read_override("acme", name).is_none(),
1346                "{name:?} must not resolve",
1347            );
1348        }
1349    }
1350
1351    #[test]
1352    fn the_cache_is_bounded_and_evicts_the_least_recently_used() {
1353        let s = Scratch::new();
1354        for i in 0..4 {
1355            s.write(&format!("t{i}/page.html"), &format!("tenant-{i}"));
1356        }
1357        let tt = TenantTemplates::new(global(), &s.0)
1358            .with_reload(Reload::Never)
1359            .with_capacity(2);
1360        let _ = tt.for_tenant("t0");
1361        let _ = tt.for_tenant("t1");
1362        let _ = tt.for_tenant("t0"); // t0 is now the more recently used
1363        let _ = tt.for_tenant("t2"); // evicts t1
1364
1365        let cache = tt.cache.read().unwrap();
1366        assert_eq!(cache.len(), 2, "cache must stay bounded");
1367        assert!(cache.contains_key("t0"), "recently used survives");
1368        assert!(!cache.contains_key("t1"), "least recently used evicted");
1369    }
1370
1371    #[test]
1372    fn an_evicted_tenant_still_renders_correctly() {
1373        // Eviction is a cost, never a correctness change.
1374        let s = Scratch::new();
1375        s.write("t0/page.html", "zero");
1376        s.write("t1/page.html", "one");
1377        let tt = TenantTemplates::new(global(), &s.0).with_capacity(1);
1378        assert_eq!(render(&tt.for_tenant("t0"), "page.html"), "zero");
1379        assert_eq!(render(&tt.for_tenant("t1"), "page.html"), "one");
1380        assert_eq!(render(&tt.for_tenant("t0"), "page.html"), "zero");
1381    }
1382
1383    /// A successor tenant on a reused slug never renders the
1384    /// previous owner's overrides.
1385    #[test]
1386    fn a_reused_slug_does_not_inherit_the_old_overrides() {
1387        let s = Scratch::new();
1388        s.write("acme/page.html", "OLD-CUSTOMER");
1389        let tt = TenantTemplates::new(global(), &s.0);
1390
1391        assert_eq!(tt.claim("acme", "db-born-1").expect("claim"), Claim::Adopted);
1392        assert_eq!(tt.claim("acme", "db-born-1").expect("claim"), Claim::Owned);
1393        assert_eq!(render(&tt.for_tenant("acme"), "page.html"), "OLD-CUSTOMER");
1394
1395        // Purged and re-provisioned: same slug, new database.
1396        match tt.claim("acme", "db-born-2").expect("claim") {
1397            Claim::MovedAside { previous_owner, to } => {
1398                assert_eq!(previous_owner, "db-born-1");
1399                assert!(to.join("page.html").is_file(), "kept, not deleted");
1400            }
1401            other => panic!("expected the old directory moved aside, got {other:?}"),
1402        }
1403        assert_eq!(
1404            render(&tt.for_tenant("acme"), "page.html"),
1405            "GLOBAL-BASE[global-page]",
1406            "the cached old instance is gone too"
1407        );
1408        assert_eq!(tt.claim("acme", "db-born-2").expect("claim"), Claim::NoOverrides);
1409        assert!(tt.tenant_dir(".orphaned").is_none(), "the aside directory is no tenant's");
1410    }
1411
1412    #[test]
1413    fn the_owner_marker_is_not_a_template() {
1414        let s = Scratch::new();
1415        s.write("acme/page.html", "MINE");
1416        let tt = TenantTemplates::new(global(), &s.0);
1417        tt.claim("acme", "db").expect("claim");
1418        assert_eq!(render(&tt.for_tenant("acme"), "page.html"), "MINE");
1419        assert!(tt.for_tenant("acme").get_template(OWNER_FILE).is_err());
1420    }
1421
1422    #[cfg(feature = "sqlite")]
1423    #[tokio::test]
1424    async fn database_birth_is_the_first_applied_migration() {
1425        let pool = rustango::sql::Pool::connect("sqlite::memory:").await.expect("pool");
1426        rustango::sql::raw_execute_pool(
1427            &pool,
1428            "CREATE TABLE __rustango_migrations__ (name TEXT PRIMARY KEY, applied_at TEXT NOT NULL)",
1429            Vec::new(),
1430        )
1431        .await
1432        .expect("ledger");
1433        assert_eq!(database_birth(&pool).await.expect("empty"), None);
1434        for (name, at) in [("0002_b", "2026-02-01T00:00:00+00:00"), ("0001_a", "2026-01-01T00:00:00+00:00")] {
1435            rustango::sql::raw_execute_pool(
1436                &pool,
1437                &format!("INSERT INTO __rustango_migrations__ VALUES ('{name}', '{at}')"),
1438                Vec::new(),
1439            )
1440            .await
1441            .expect("row");
1442        }
1443        assert_eq!(
1444            database_birth(&pool).await.expect("birth").as_deref(),
1445            Some("2026-01-01T00:00:00+00:00")
1446        );
1447    }
1448
1449    /// The async render path takes a cached instance without
1450    /// touching the disk, and falls back to `for_tenant` when one is due.
1451    #[test]
1452    fn cached_serves_only_an_instance_not_due_a_check() {
1453        let s = Scratch::new();
1454        s.write("acme/page.html", "MINE");
1455        let never = TenantTemplates::new(global(), &s.0).with_reload(Reload::Never);
1456        assert!(never.cached("acme").is_none(), "nothing built yet");
1457        let built = never.for_tenant("acme");
1458        let hit = never.cached("acme").expect("cached after a build");
1459        assert!(Arc::ptr_eq(&built, &hit));
1460
1461        let always = TenantTemplates::new(global(), &s.0).with_reload(Reload::Always);
1462        let _ = always.for_tenant("acme");
1463        assert!(always.cached("acme").is_none(), "always due: re-check on the blocking pool");
1464    }
1465
1466    /// A symlink out of the tenant's folder can't be used to create
1467    /// directories outside it, not just files.
1468    #[cfg(unix)]
1469    #[test]
1470    fn a_symlinked_subdirectory_creates_nothing_outside() {
1471        let s = Scratch::new();
1472        let outside = Scratch::new();
1473        std::fs::create_dir_all(s.0.join("acme")).unwrap();
1474        std::os::unix::fs::symlink(&outside.0, s.0.join("acme/evil")).unwrap();
1475        let tt = TenantTemplates::new(global(), &s.0);
1476        assert!(tt.write_override("acme", "evil/new/x.html", "x").is_err());
1477        assert!(!outside.0.join("new").exists(), "no directory was created outside");
1478    }
1479}