Skip to main content

mas_templates/
lib.rs

1// Copyright 2026 Element Creations Ltd.
2// Copyright 2024, 2025 New Vector Ltd.
3// Copyright 2021-2024 The Matrix.org Foundation C.I.C.
4//
5// SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
6// Please see LICENSE files in the repository root for full details.
7
8#![deny(missing_docs)]
9#![allow(clippy::module_name_repetitions)]
10
11//! Templates rendering
12
13use std::{
14    collections::{BTreeMap, HashSet},
15    sync::Arc,
16};
17
18use anyhow::Context as _;
19use arc_swap::ArcSwap;
20use camino::{Utf8Path, Utf8PathBuf};
21use mas_i18n::Translator;
22use mas_router::UrlBuilder;
23use mas_spa::ViteManifest;
24use minijinja::{UndefinedBehavior, Value};
25use rand::Rng;
26use serde::Serialize;
27use thiserror::Error;
28use tokio::task::JoinError;
29use tracing::{debug, info};
30use walkdir::DirEntry;
31
32mod context;
33mod forms;
34mod functions;
35
36#[macro_use]
37mod macros;
38
39pub use self::{
40    context::{
41        AccountInactiveContext, ApiDocContext, AppContext, CompatLoginPolicyViolationContext,
42        CompatSsoContext, ConsentContext, DeviceConsentContext, DeviceLinkContext,
43        DeviceLinkFormField, DeviceNameContext, EmailRecoveryContext, EmailVerificationContext,
44        EmptyContext, ErrorContext, FormPostContext, IndexContext, LoginContext, LoginFormField,
45        NotFoundContext, PasswordRegisterContext, PolicyViolationContext, PostAuthContext,
46        PostAuthContextInner, RecoveryExpiredContext, RecoveryFinishContext,
47        RecoveryFinishFormField, RecoveryProgressContext, RecoveryStartContext,
48        RecoveryStartFormField, RegisterContext, RegisterFormField,
49        RegisterStepsDisplayNameContext, RegisterStepsDisplayNameFormField,
50        RegisterStepsEmailInUseContext, RegisterStepsRegistrationTokenContext,
51        RegisterStepsRegistrationTokenFormField, RegisterStepsVerifyEmailContext,
52        RegisterStepsVerifyEmailFormField, SiteBranding, SiteConfigExt, SiteFeatures,
53        TemplateContext, UpstreamExistingLinkContext, UpstreamRegister, UpstreamRegisterFormField,
54        UpstreamSuggestLink, WithCaptcha, WithCsrf, WithLanguage, WithOptionalSession, WithSession,
55    },
56    forms::{FieldError, FormError, FormField, FormState, ToFormState},
57};
58use crate::context::SampleIdentifier;
59
60/// Escape the given string for use in HTML
61///
62/// It uses the same crate as the one used by the minijinja templates
63#[must_use]
64pub fn escape_html(input: &str) -> String {
65    let mut out = String::with_capacity(input.len());
66    v_htmlescape::escape_string(input, &mut out);
67    out
68}
69
70/// Wrapper around [`minijinja::Environment`] helping rendering the various
71/// templates
72#[derive(Debug, Clone)]
73pub struct Templates {
74    environment: Arc<ArcSwap<minijinja::Environment<'static>>>,
75    translator: Arc<ArcSwap<Translator>>,
76    url_builder: UrlBuilder,
77    branding: SiteBranding,
78    features: SiteFeatures,
79    vite_manifest_path: Option<Utf8PathBuf>,
80    translations_path: Utf8PathBuf,
81    path: Utf8PathBuf,
82    /// Whether template rendering is in strict mode (for testing,
83    /// until this can be rolled out in production.)
84    strict: bool,
85}
86
87/// There was an issue while loading the templates
88#[derive(Error, Debug)]
89pub enum TemplateLoadingError {
90    /// I/O error
91    #[error(transparent)]
92    IO(#[from] std::io::Error),
93
94    /// Failed to read the assets manifest
95    #[error("failed to read the assets manifest")]
96    ViteManifestIO(#[source] std::io::Error),
97
98    /// Failed to deserialize the assets manifest
99    #[error("invalid assets manifest")]
100    ViteManifest(#[from] serde_json::Error),
101
102    /// Failed to load the translations
103    #[error("failed to load the translations")]
104    Translations(#[from] mas_i18n::LoadError),
105
106    /// Failed to traverse the filesystem
107    #[error("failed to traverse the filesystem")]
108    WalkDir(#[from] walkdir::Error),
109
110    /// Encountered non-UTF-8 path
111    #[error("encountered non-UTF-8 path")]
112    NonUtf8Path(#[from] camino::FromPathError),
113
114    /// Encountered non-UTF-8 path
115    #[error("encountered non-UTF-8 path")]
116    NonUtf8PathBuf(#[from] camino::FromPathBufError),
117
118    /// Encountered invalid path
119    #[error("encountered invalid path")]
120    InvalidPath(#[from] std::path::StripPrefixError),
121
122    /// Some templates failed to compile
123    #[error("could not load and compile some templates")]
124    Compile(#[from] minijinja::Error),
125
126    /// Could not join blocking task
127    #[error("error from async runtime")]
128    Runtime(#[from] JoinError),
129
130    /// There are essential templates missing
131    #[error("missing templates {missing:?}")]
132    MissingTemplates {
133        /// List of missing templates
134        missing: HashSet<String>,
135        /// List of templates that were loaded
136        loaded: HashSet<String>,
137    },
138}
139
140fn is_hidden(entry: &DirEntry) -> bool {
141    entry
142        .file_name()
143        .to_str()
144        .is_some_and(|s| s.starts_with('.'))
145}
146
147impl Templates {
148    /// Load the templates from the given config
149    ///
150    /// # Parameters
151    ///
152    /// - `vite_manifest_path`: None if we are rendering resources for
153    ///   reproducibility, in which case a dummy Vite manifest will be used.
154    ///
155    /// # Errors
156    ///
157    /// Returns an error if the templates could not be loaded from disk.
158    #[tracing::instrument(
159        name = "templates.load",
160        skip_all,
161        fields(%path),
162    )]
163    pub async fn load(
164        path: Utf8PathBuf,
165        url_builder: UrlBuilder,
166        vite_manifest_path: Option<Utf8PathBuf>,
167        translations_path: Utf8PathBuf,
168        branding: SiteBranding,
169        features: SiteFeatures,
170        strict: bool,
171    ) -> Result<Self, TemplateLoadingError> {
172        let (translator, environment) = Self::load_(
173            &path,
174            url_builder.clone(),
175            vite_manifest_path.as_deref(),
176            &translations_path,
177            branding.clone(),
178            features,
179            strict,
180        )
181        .await?;
182        Ok(Self {
183            environment: Arc::new(ArcSwap::new(environment)),
184            translator: Arc::new(ArcSwap::new(translator)),
185            path,
186            url_builder,
187            vite_manifest_path,
188            translations_path,
189            branding,
190            features,
191            strict,
192        })
193    }
194
195    async fn load_(
196        path: &Utf8Path,
197        url_builder: UrlBuilder,
198        vite_manifest_path: Option<&Utf8Path>,
199        translations_path: &Utf8Path,
200        branding: SiteBranding,
201        features: SiteFeatures,
202        strict: bool,
203    ) -> Result<(Arc<Translator>, Arc<minijinja::Environment<'static>>), TemplateLoadingError> {
204        let path = path.to_owned();
205        let span = tracing::Span::current();
206
207        // Read the assets manifest from disk
208        let vite_manifest = if let Some(vite_manifest_path) = vite_manifest_path {
209            let raw_vite_manifest = tokio::fs::read(vite_manifest_path)
210                .await
211                .map_err(TemplateLoadingError::ViteManifestIO)?;
212
213            Some(
214                serde_json::from_slice::<ViteManifest>(&raw_vite_manifest)
215                    .map_err(TemplateLoadingError::ViteManifest)?,
216            )
217        } else {
218            None
219        };
220
221        // Parse it
222
223        let translations_path = translations_path.to_owned();
224        let translator =
225            tokio::task::spawn_blocking(move || Translator::load_from_path(&translations_path))
226                .await??;
227        let translator = Arc::new(translator);
228
229        debug!(locales = ?translator.available_locales(), "Loaded translations");
230
231        let (loaded, mut env) = tokio::task::spawn_blocking(move || {
232            span.in_scope(move || {
233                let mut loaded: HashSet<_> = HashSet::new();
234                let mut env = minijinja::Environment::new();
235                // Don't allow use of undefined variables
236                env.set_undefined_behavior(if strict {
237                    UndefinedBehavior::Strict
238                } else {
239                    // For now, allow semi-strict, because we don't have total test coverage of
240                    // tests and some tests rely on if conditions against sometimes-undefined
241                    // variables
242                    UndefinedBehavior::SemiStrict
243                });
244                let root = path.canonicalize_utf8()?;
245                info!(%root, "Loading templates from filesystem");
246                for entry in walkdir::WalkDir::new(&root)
247                    .min_depth(1)
248                    .into_iter()
249                    .filter_entry(|e| !is_hidden(e))
250                {
251                    let entry = entry?;
252                    if entry.file_type().is_file() {
253                        let path = Utf8PathBuf::try_from(entry.into_path())?;
254                        let Some(ext) = path.extension() else {
255                            continue;
256                        };
257
258                        if ext == "html" || ext == "txt" || ext == "subject" {
259                            let relative = path.strip_prefix(&root)?;
260                            debug!(%relative, "Registering template");
261                            let template = std::fs::read_to_string(&path)?;
262                            env.add_template_owned(relative.as_str().to_owned(), template)?;
263                            loaded.insert(relative.as_str().to_owned());
264                        }
265                    }
266                }
267
268                Ok::<_, TemplateLoadingError>((loaded, env))
269            })
270        })
271        .await??;
272
273        env.add_global("branding", Value::from_object(branding));
274        env.add_global("features", Value::from_object(features));
275
276        self::functions::register(
277            &mut env,
278            url_builder,
279            vite_manifest,
280            Arc::clone(&translator),
281        );
282
283        let env = Arc::new(env);
284
285        let needed: HashSet<_> = TEMPLATES.into_iter().map(ToOwned::to_owned).collect();
286        debug!(?loaded, ?needed, "Templates loaded");
287        let missing: HashSet<_> = needed.difference(&loaded).cloned().collect();
288
289        if missing.is_empty() {
290            Ok((translator, env))
291        } else {
292            Err(TemplateLoadingError::MissingTemplates { missing, loaded })
293        }
294    }
295
296    /// Reload the templates on disk
297    ///
298    /// # Errors
299    ///
300    /// Returns an error if the templates could not be reloaded from disk.
301    #[tracing::instrument(
302        name = "templates.reload",
303        skip_all,
304        fields(path = %self.path),
305    )]
306    pub async fn reload(&self) -> Result<(), TemplateLoadingError> {
307        let (translator, environment) = Self::load_(
308            &self.path,
309            self.url_builder.clone(),
310            self.vite_manifest_path.as_deref(),
311            &self.translations_path,
312            self.branding.clone(),
313            self.features,
314            self.strict,
315        )
316        .await?;
317
318        // Swap them
319        self.environment.store(environment);
320        self.translator.store(translator);
321
322        Ok(())
323    }
324
325    /// Get the translator
326    #[must_use]
327    pub fn translator(&self) -> Arc<Translator> {
328        self.translator.load_full()
329    }
330}
331
332/// Failed to render a template
333#[derive(Error, Debug)]
334pub enum TemplateError {
335    /// Missing template
336    #[error("missing template {template:?}")]
337    Missing {
338        /// The name of the template being rendered
339        template: &'static str,
340
341        /// The underlying error
342        #[source]
343        source: minijinja::Error,
344    },
345
346    /// Failed to render the template
347    #[error("could not render template {template:?}")]
348    Render {
349        /// The name of the template being rendered
350        template: &'static str,
351
352        /// The underlying error
353        #[source]
354        source: minijinja::Error,
355    },
356}
357
358register_templates! {
359    /// Render the not found fallback page
360    pub fn render_not_found(WithLanguage<NotFoundContext>) { "pages/404.html" }
361
362    /// Render the frontend app
363    pub fn render_app(WithLanguage<AppContext>) { "app.html" }
364
365    /// Render the Swagger API reference
366    pub fn render_swagger(ApiDocContext) { "swagger/doc.html" }
367
368    /// Render the Swagger OAuth callback page
369    pub fn render_swagger_callback(ApiDocContext) { "swagger/oauth2-redirect.html" }
370
371    /// Render the login page
372    pub fn render_login(WithLanguage<WithCsrf<LoginContext>>) { "pages/login.html" }
373
374    /// Render the registration page
375    pub fn render_register(WithLanguage<WithCsrf<RegisterContext>>) { "pages/register/index.html" }
376
377    /// Render the password registration page
378    pub fn render_password_register(WithLanguage<WithCsrf<WithCaptcha<PasswordRegisterContext>>>) { "pages/register/password.html" }
379
380    /// Render the email verification page
381    pub fn render_register_steps_verify_email(WithLanguage<WithCsrf<RegisterStepsVerifyEmailContext>>) { "pages/register/steps/verify_email.html" }
382
383    /// Render the email in use page
384    pub fn render_register_steps_email_in_use(WithLanguage<RegisterStepsEmailInUseContext>) { "pages/register/steps/email_in_use.html" }
385
386    /// Render the display name page
387    pub fn render_register_steps_display_name(WithLanguage<WithCsrf<RegisterStepsDisplayNameContext>>) { "pages/register/steps/display_name.html" }
388
389    /// Render the registration token page
390    pub fn render_register_steps_registration_token(WithLanguage<WithCsrf<RegisterStepsRegistrationTokenContext>>) { "pages/register/steps/registration_token.html" }
391
392    /// Render the client consent page
393    pub fn render_consent(WithLanguage<WithCsrf<WithSession<ConsentContext>>>) { "pages/consent.html" }
394
395    /// Render the policy violation page
396    pub fn render_policy_violation(WithLanguage<WithCsrf<WithSession<PolicyViolationContext>>>) { "pages/policy_violation.html" }
397
398    /// Render the compatibility login policy violation page
399    pub fn render_compat_login_policy_violation(WithLanguage<WithCsrf<WithSession<CompatLoginPolicyViolationContext>>>) { "pages/compat_login_policy_violation.html" }
400
401    /// Render the legacy SSO login consent page
402    pub fn render_sso_login(WithLanguage<WithCsrf<WithSession<CompatSsoContext>>>) { "pages/sso.html" }
403
404    /// Render the home page
405    pub fn render_index(WithLanguage<WithCsrf<WithOptionalSession<IndexContext>>>) { "pages/index.html" }
406
407    /// Render the account recovery start page
408    pub fn render_recovery_start(WithLanguage<WithCsrf<RecoveryStartContext>>) { "pages/recovery/start.html" }
409
410    /// Render the account recovery start page
411    pub fn render_recovery_progress(WithLanguage<WithCsrf<RecoveryProgressContext>>) { "pages/recovery/progress.html" }
412
413    /// Render the account recovery finish page
414    pub fn render_recovery_finish(WithLanguage<WithCsrf<RecoveryFinishContext>>) { "pages/recovery/finish.html" }
415
416    /// Render the account recovery link expired page
417    pub fn render_recovery_expired(WithLanguage<WithCsrf<RecoveryExpiredContext>>) { "pages/recovery/expired.html" }
418
419    /// Render the account recovery link consumed page
420    pub fn render_recovery_consumed(WithLanguage<EmptyContext>) { "pages/recovery/consumed.html" }
421
422    /// Render the account recovery disabled page
423    pub fn render_recovery_disabled(WithLanguage<EmptyContext>) { "pages/recovery/disabled.html" }
424
425    /// Render the form used by the `form_post` response mode
426    pub fn render_form_post<#[sample(EmptyContext)] T: Serialize>(WithLanguage<FormPostContext<T>>) { "form_post.html" }
427
428    /// Render the HTML error page
429    pub fn render_error(ErrorContext) { "pages/error.html" }
430
431    /// Render the email recovery email (plain text variant)
432    pub fn render_email_recovery_txt(WithLanguage<EmailRecoveryContext>) { "emails/recovery.txt" }
433
434    /// Render the email recovery email (HTML text variant)
435    pub fn render_email_recovery_html(WithLanguage<EmailRecoveryContext>) { "emails/recovery.html" }
436
437    /// Render the email recovery subject
438    pub fn render_email_recovery_subject(WithLanguage<EmailRecoveryContext>) { "emails/recovery.subject" }
439
440    /// Render the email verification email (plain text variant)
441    pub fn render_email_verification_txt(WithLanguage<EmailVerificationContext>) { "emails/verification.txt" }
442
443    /// Render the email verification email (HTML text variant)
444    pub fn render_email_verification_html(WithLanguage<EmailVerificationContext>) { "emails/verification.html" }
445
446    /// Render the email verification subject
447    pub fn render_email_verification_subject(WithLanguage<EmailVerificationContext>) { "emails/verification.subject" }
448
449    /// Render the upstream link mismatch message
450    pub fn render_upstream_oauth2_link_mismatch(WithLanguage<WithCsrf<WithSession<UpstreamExistingLinkContext>>>) { "pages/upstream_oauth2/link_mismatch.html" }
451
452    /// Render the upstream suggest link message
453    pub fn render_upstream_oauth2_suggest_link(WithLanguage<WithCsrf<WithSession<UpstreamSuggestLink>>>) { "pages/upstream_oauth2/suggest_link.html" }
454
455    /// Render the upstream register screen
456    pub fn render_upstream_oauth2_do_register(WithLanguage<WithCsrf<UpstreamRegister>>) { "pages/upstream_oauth2/do_register.html" }
457
458    /// Render the device code link page
459    pub fn render_device_link(WithLanguage<WithCsrf<DeviceLinkContext>>) { "pages/device_link.html" }
460
461    /// Render the device code consent page
462    pub fn render_device_consent(WithLanguage<WithCsrf<WithSession<DeviceConsentContext>>>) { "pages/device_consent.html" }
463
464    /// Render the 'account deactivated' page
465    pub fn render_account_deactivated(WithLanguage<WithCsrf<AccountInactiveContext>>) { "pages/account/deactivated.html" }
466
467    /// Render the 'account locked' page
468    pub fn render_account_locked(WithLanguage<WithCsrf<AccountInactiveContext>>) { "pages/account/locked.html" }
469
470    /// Render the 'account logged out' page
471    pub fn render_account_logged_out(WithLanguage<WithCsrf<AccountInactiveContext>>) { "pages/account/logged_out.html" }
472
473    /// Render the automatic device name for OAuth 2.0 client
474    pub fn render_device_name(WithLanguage<DeviceNameContext>) { "device_name.txt" }
475}
476
477impl Templates {
478    /// Render all templates with the generated samples to check if they render
479    /// properly.
480    ///
481    /// Returns the renders in a map whose keys are template names
482    /// and the values are lists of renders (according to the list
483    /// of samples).
484    /// Samples are stable across re-runs and can be used for
485    /// acceptance testing.
486    ///
487    /// # Errors
488    ///
489    /// Returns an error if any of the templates fails to render
490    pub fn check_render<R: Rng + Clone>(
491        &self,
492        now: chrono::DateTime<chrono::Utc>,
493        rng: &R,
494    ) -> anyhow::Result<BTreeMap<(&'static str, SampleIdentifier), String>> {
495        check::all(self, now, rng)
496    }
497}
498
499#[cfg(test)]
500mod tests {
501    use rand::SeedableRng;
502
503    use super::*;
504
505    #[tokio::test]
506    async fn check_builtin_templates() {
507        #[expect(clippy::disallowed_methods)]
508        let now = chrono::Utc::now();
509        let rng = rand_chacha::ChaCha8Rng::from_seed([42; 32]);
510
511        let path = Utf8Path::new(env!("CARGO_MANIFEST_DIR")).join("../../templates/");
512        let url_builder = UrlBuilder::new("https://example.com/".parse().unwrap(), None, None);
513        let branding = SiteBranding::new("example.com");
514        let features = SiteFeatures {
515            password_login: true,
516            password_registration: true,
517            password_registration_email_required: true,
518            account_recovery: true,
519            login_with_email_allowed: true,
520        };
521        let vite_manifest_path =
522            Utf8Path::new(env!("CARGO_MANIFEST_DIR")).join("../../frontend/dist/manifest.json");
523        let translations_path =
524            Utf8Path::new(env!("CARGO_MANIFEST_DIR")).join("../../translations");
525
526        for use_real_vite_manifest in [true, false] {
527            let templates = Templates::load(
528                path.clone(),
529                url_builder.clone(),
530                // Check both renders against the real vite manifest and the 'dummy' vite manifest
531                // used for reproducible renders.
532                use_real_vite_manifest.then_some(vite_manifest_path.clone()),
533                translations_path.clone(),
534                branding.clone(),
535                features,
536                // Use strict mode in tests
537                true,
538            )
539            .await
540            .unwrap();
541
542            // Check the renders are deterministic, when given the same rng
543            let render1 = templates.check_render(now, &rng).unwrap();
544            let render2 = templates.check_render(now, &rng).unwrap();
545
546            assert_eq!(render1, render2);
547        }
548    }
549}