1use 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
68pub const DEFAULT_DIR: &str = "templates_tenants";
70
71#[derive(Debug, Clone, Copy, PartialEq, Eq)]
73pub enum Reload {
74 Always,
77 Every(Duration),
81 Never,
85}
86
87impl Default for Reload {
88 fn default() -> Self {
89 Self::Every(Duration::from_secs(5))
90 }
91}
92
93static TICK: AtomicU64 = AtomicU64::new(0);
99
100fn tick() -> u64 {
101 TICK.fetch_add(1, Ordering::Relaxed)
102}
103
104struct Entry {
106 tera: Arc<Tera>,
107 fingerprint: u64,
109 checked: Instant,
111 used: AtomicU64,
116}
117
118const OWNER_FILE: &str = ".rcms-owner";
121
122const ORPHANED_DIR: &str = ".orphaned";
125
126#[derive(Debug, PartialEq, Eq)]
128pub enum Claim {
129 NoOverrides,
131 Owned,
133 Adopted,
135 MovedAside { previous_owner: String, to: PathBuf },
138}
139
140pub struct TenantTemplates {
143 base: Arc<Tera>,
144 root: PathBuf,
145 global_dir: Option<PathBuf>,
150 reload: Reload,
151 capacity: usize,
152 cache: RwLock<HashMap<String, Entry>>,
153}
154
155impl TenantTemplates {
156 #[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 capacity: 64,
170 cache: RwLock::new(HashMap::new()),
171 }
172 }
173
174 #[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 #[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 #[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 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 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 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 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 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 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 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 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 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
377fn 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 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
417fn 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 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
462fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
492#[serde(rename_all = "lowercase")]
493pub enum Source {
494 Override,
496 Global,
498}
499
500#[derive(Debug, Clone, serde::Serialize)]
502pub struct TemplateEntry {
503 pub name: String,
504 pub source: Source,
505 pub bytes: u64,
506}
507
508#[derive(Debug)]
510pub enum EditError {
511 BadName(String),
513 Invalid(String),
516 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
532pub 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 #[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 #[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 #[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 #[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 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 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 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 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 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 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
717fn 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
754fn 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
770pub async fn database_birth(
783 pool: &rustango::sql::Pool,
784) -> Result<Option<String>, rustango::sql::ExecError> {
785 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 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
800pub fn install(tt: Arc<TenantTemplates>) {
802 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#[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 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 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 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 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 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 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 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 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 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 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 fn store(s: &Scratch) -> TenantTemplates {
1006 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 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 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 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 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 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 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 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 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 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 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 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 #[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 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 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 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 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 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 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 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"); let _ = tt.for_tenant("t2"); 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 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 #[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 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 #[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 #[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}