mas_templates/
lib.rs

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