Skip to main content

rustango_cms/
error_pages.rs

1//! CMS-editable error pages (404/500/…).
2//!
3//! Editors create a page of the built-in **Error page** type, pick the
4//! HTTP status it serves (404/403/500/503) and compose its body from
5//! content blocks. The public router substitutes that page — rendered
6//! through the full pipeline (navbar via `auto_menu`, footer, theme,
7//! `_stream_html`) — for the previously plain-text error responses,
8//! keeping the real error status code on the wire.
9//!
10//! When no published Error page exists for a status (or the error page
11//! itself fails to render), `fallback_response` serves a bundled,
12//! fully self-contained HTML page — no Tera, no DB — so the error path
13//! can never recurse into another error.
14//!
15//! The extension table is created at boot via `CREATE TABLE IF NOT
16//! EXISTS` (same pattern as [`crate::forms::submit::ensure_table`])
17//! because repo-wide `gen_migration` is blocked by pre-existing
18//! framework FK-snapshot drift.
19
20use axum::http::StatusCode;
21use axum::response::{IntoResponse, Response};
22use rustango::core::Column as _;
23use rustango::core::Model as _;
24use rustango::extractors::Tenant;
25use rustango::sql::FetcherPool as _;
26use rustango::sql::{Auto, ExecError, Pool};
27use rustango::Model;
28use serde::{Deserialize, Serialize};
29use serde_json::{json, Value};
30
31use crate::page::Page;
32
33/// Registry `type_name` for the built-in Error page type.
34pub const TYPE_NAME: &str = "ErrorPage";
35
36/// Typed extension row for an Error page: the HTTP status it serves
37/// plus its block-stream body.
38#[derive(Model, Debug, Clone, Default, Serialize, Deserialize)]
39#[rustango(table = "cms_error_page", app = "cms")]
40pub struct ErrorPageExt {
41    #[rustango(primary_key)]
42    pub id: Auto<i64>,
43    /// Owning `cms_page` row — one extension row per page.
44    #[rustango(fk = "cms_page", on = "id", unique)]
45    pub page_id: i64,
46    /// HTTP status this page is served for: `"404"` / `"403"` /
47    /// `"500"` / `"503"`. Stored as text to match the Select widget's
48    /// form value round-trip.
49    #[rustango(max_length = 8, index)]
50    pub status_code: String,
51    /// Block-stream JSON (array of `{type, value}` objects).
52    pub body: Option<String>,
53}
54
55/// Create `cms_error_page` if absent. Idempotent; called per tenant at
56/// boot from [`crate::seed::ensure_seeded`].
57///
58/// # Errors
59/// Driver / DDL failures.
60pub async fn ensure_table(pool: &Pool) -> Result<(), ExecError> {
61    let ddl = rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect(
62        pool.dialect(),
63        &ErrorPageExt::SCHEMA,
64    );
65    for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
66        rustango::sql::raw_execute_pool(pool, stmt, Vec::new()).await?;
67    }
68    Ok(())
69}
70
71/// The built-in Error page type. Hand-rolled (not `#[derive(PageType)]`
72/// — the derive emits `::rustango_cms::` paths that don't resolve from
73/// inside this crate).
74#[derive(Default)]
75pub struct ErrorPage;
76
77#[async_trait::async_trait]
78impl crate::PageTypeHandler for ErrorPage {
79    fn app_label(&self) -> &'static str {
80        "cms"
81    }
82    fn type_name(&self) -> &'static str {
83        TYPE_NAME
84    }
85    fn verbose_name(&self) -> &'static str {
86        "Error page"
87    }
88    fn default_template(&self) -> &'static str {
89        "error_page.html"
90    }
91    fn icon(&self) -> Option<&'static str> {
92        Some("error")
93    }
94    fn description(&self) -> Option<&'static str> {
95        Some(
96            "Served in place of a plain error when a URL is missing (404) or the \
97             server fails (500). Tip: untick 'Allow search indexing' under Promote.",
98        )
99    }
100    fn is_leaf(&self) -> bool {
101        true
102    }
103
104    async fn widgets(&self, pool: &Pool, page_id: i64) -> Result<Vec<crate::Widget>, ExecError> {
105        let row = fetch_ext(pool, page_id).await?;
106        let (code, body) = row
107            .map(|r| (r.status_code, r.body.unwrap_or_default()))
108            .unwrap_or_else(|| ("404".to_owned(), String::new()));
109        Ok(vec![
110            crate::Widget::new(
111                crate::widget::WidgetKind::Select,
112                "status_code",
113                "Status code",
114            )
115            .with_options([
116                ("404", "404 — Not Found"),
117                ("403", "403 — Forbidden"),
118                ("500", "500 — Server Error"),
119                ("503", "503 — Service Unavailable"),
120            ])
121            .required()
122            .with_value(code)
123            .with_help("HTTP status this page is served for."),
124            crate::Widget::stream(
125                "body",
126                "Body",
127                [
128                    "heading",
129                    "paragraph",
130                    "image",
131                    "quote",
132                    "embed",
133                    "code",
134                    "raw_html",
135                ],
136            )
137            .with_value(body),
138        ])
139    }
140
141    async fn load_extension(&self, pool: &Pool, page_id: i64) -> Result<Value, ExecError> {
142        let row = fetch_ext(pool, page_id).await?;
143        Ok(match row {
144            // `body` stays a raw JSON string — `canonical_parsed` in the
145            // stream prerenderer parses either shape.
146            Some(r) => json!({ "status_code": r.status_code, "body": r.body }),
147            None => json!({ "status_code": "404", "body": Value::Null }),
148        })
149    }
150
151    async fn save_extension(
152        &self,
153        pool: &Pool,
154        page_id: i64,
155        form: &std::collections::HashMap<String, String>,
156    ) -> Result<(), ExecError> {
157        let status_code = form
158            .get("status_code")
159            .map(String::as_str)
160            .filter(|s| !s.trim().is_empty())
161            .unwrap_or("404")
162            .to_owned();
163        let body = form.get("body").filter(|s| !s.trim().is_empty()).cloned();
164        match fetch_ext(pool, page_id).await? {
165            Some(mut row) => {
166                row.status_code = status_code;
167                row.body = body;
168                row.save_pool(pool).await?;
169            }
170            None => {
171                let mut row = ErrorPageExt {
172                    id: Auto::Unset,
173                    page_id,
174                    status_code,
175                    body,
176                };
177                row.insert_pool(pool).await?;
178            }
179        }
180        Ok(())
181    }
182}
183
184crate::register_page_type!(ErrorPage);
185
186async fn fetch_ext(pool: &Pool, page_id: i64) -> Result<Option<ErrorPageExt>, ExecError> {
187    Ok(ErrorPageExt::objects()
188        .where_(ErrorPageExt::page_id.eq(page_id))
189        .fetch(pool)
190        .await?
191        .into_iter()
192        .next())
193}
194
195/// The tenant's `cms_page_type.id` for the built-in Error page type,
196/// if seeded. Used to exclude error pages from surfaces that walk the
197/// published tree (sitemap).
198pub(crate) async fn error_page_type_id(pool: &Pool) -> Option<i64> {
199    crate::page_type_model::PageType::objects()
200        .where_(crate::page_type_model::PageType::type_name.eq(TYPE_NAME.to_owned()))
201        .first(pool)
202        .await
203        .ok()
204        .flatten()
205        .and_then(|pt| pt.id.get().copied())
206}
207
208/// Find the published Error page configured for `code`, if any.
209/// Lowest `page_id` wins when several published pages claim the same
210/// status (deterministic, oldest-first).
211///
212/// # Errors
213/// Driver / query failures.
214pub async fn find_for_status(pool: &Pool, code: u16) -> Result<Option<Page>, ExecError> {
215    let mut exts: Vec<ErrorPageExt> = ErrorPageExt::objects()
216        .where_(ErrorPageExt::status_code.eq(code.to_string()))
217        .fetch(pool)
218        .await?;
219    exts.sort_by_key(|e| e.page_id);
220    for ext in exts {
221        let page = Page::objects()
222            .where_(Page::id.eq(ext.page_id))
223            // Served, as the resolver judges it: an archived error page
224            // still answers (#763).
225            .where_(Page::status.is_in(crate::resolver::served_statuses()))
226            .first(pool)
227            .await?
228            .filter(|p| crate::resolver::visible_now(p, chrono::Utc::now()));
229        if page.is_some() {
230            return Ok(page);
231        }
232    }
233    Ok(None)
234}
235
236/// Serve the error response for `status`: the editor-built Error page
237/// rendered through the full public pipeline when one exists and
238/// renders cleanly, else the static `fallback_response`.
239///
240/// The error page render is only accepted when it comes back `200 OK`
241/// — anything else (including a failure inside the error page itself)
242/// drops to the Tera-free fallback, so this path cannot recurse.
243pub(crate) async fn respond(
244    tenant: &Tenant,
245    state: &crate::router::PublicState,
246    status: StatusCode,
247    locale_code: Option<&str>,
248) -> Response {
249    match find_for_status(tenant.pool(), status.as_u16()).await {
250        Ok(Some(page)) => {
251            // Same stash-and-hold contract as handle_page_request: the
252            // guard must live across the render so the language
253            // switcher thread-local survives into `tera.render`.
254            let _switcher =
255                crate::router::install_locale_switcher(tenant, state, &page, locale_code).await;
256            let mut resp = crate::render::render(
257                tenant,
258                &state.tera,
259                &page,
260                &state.url_prefix,
261                // Error pages render from the tenant-absolute tree.
262                "",
263                locale_code,
264                None,
265                state.fragment_cache.as_ref().map(|(c, ttl)| (c, *ttl)),
266            )
267            .await;
268            if resp.status() == StatusCode::OK {
269                *resp.status_mut() = status;
270                resp.headers_mut().insert(
271                    axum::http::header::CACHE_CONTROL,
272                    axum::http::HeaderValue::from_static("no-store"),
273                );
274                return resp;
275            }
276            tracing::error!(
277                status = %status,
278                page_id = page.id.get().copied().unwrap_or_default(),
279                "error page failed to render; serving static fallback"
280            );
281        }
282        Ok(None) => {}
283        Err(e) => {
284            tracing::error!(status = %status, error = %e, "error page lookup failed");
285        }
286    }
287    fallback_response(status)
288}
289
290/// Bundled last-resort error page: fully self-contained HTML (no Tera,
291/// no DB, no assets) with the status code, a human title, and back /
292/// home links. English-only by design — it must not depend on anything
293/// that can fail.
294pub(crate) fn fallback_response(status: StatusCode) -> Response {
295    let code = status.as_u16();
296    let title = match code {
297        404 => "Page not found",
298        403 => "Access denied",
299        500 => "Something went wrong",
300        503 => "Service unavailable",
301        _ => status.canonical_reason().unwrap_or("Error"),
302    };
303    let detail = match code {
304        404 => "The page you're looking for doesn't exist or may have been moved.",
305        403 => "You don't have permission to view this page.",
306        503 => "The site is briefly down for maintenance. Please try again shortly.",
307        _ => "An unexpected error occurred. Please try again shortly.",
308    };
309    let html = format!(
310        r##"<!doctype html>
311<html lang="en">
312<head>
313<meta charset="utf-8">
314<meta name="viewport" content="width=device-width, initial-scale=1">
315<meta name="robots" content="noindex">
316<title>{code} — {title}</title>
317<style>
318:root{{--accent:#4f46e5;--accent2:#6366f1;--fg:#0b0b0c;--muted:#5d5d68;--bg:#ffffff;--line:#e6e6ea}}
319@media (prefers-color-scheme:dark){{:root{{--fg:#ececf2;--muted:#a2a6c2;--bg:#0e1016;--line:#262a40;--accent:#818cf8;--accent2:#a5b4fc}}}}
320*{{box-sizing:border-box}}
321body{{font:16px/1.65 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;color:var(--fg);background:var(--bg);margin:0;display:grid;min-height:100vh;place-items:center;position:relative;overflow-x:hidden}}
322body::before{{content:"";position:fixed;inset:0;z-index:-1;background:radial-gradient(55rem 30rem at 80% -10%,color-mix(in srgb,var(--accent) 12%,transparent),transparent 60%),radial-gradient(45rem 28rem at 0% 100%,color-mix(in srgb,var(--accent2) 9%,transparent),transparent 55%)}}
323.box{{max-width:640px;padding:56px 28px;text-align:center}}
324.code{{font-family:Georgia,"Times New Roman",serif;font-style:italic;font-weight:600;font-size:clamp(96px,20vw,160px);line-height:.9;letter-spacing:-.04em;margin:0;background:linear-gradient(120deg,var(--accent) 20%,var(--accent2) 60%,color-mix(in srgb,var(--accent2) 55%,var(--fg)) 95%);-webkit-background-clip:text;background-clip:text;color:transparent}}
325.rule{{width:72px;height:3px;border:0;margin:26px auto;border-radius:999px;background:linear-gradient(90deg,var(--accent),var(--accent2))}}
326h1{{font-family:Georgia,"Times New Roman",serif;font-weight:600;font-size:clamp(26px,4.5vw,34px);letter-spacing:-.015em;margin:0 0 12px}}
327p{{margin:0 auto 28px;color:var(--muted);max-width:44ch}}
328.actions{{display:flex;gap:12px;justify-content:center;flex-wrap:wrap}}
329.actions a{{display:inline-flex;align-items:center;gap:8px;font-weight:600;font-size:15px;padding:12px 22px;border-radius:999px;text-decoration:none;transition:transform .12s ease,box-shadow .15s}}
330.actions a:hover{{transform:translateY(-1px)}}
331.actions .primary{{background:var(--accent);color:#fff;box-shadow:0 8px 24px color-mix(in srgb,var(--accent) 35%,transparent)}}
332.actions .ghost{{border:1px solid color-mix(in srgb,var(--accent) 30%,var(--line));color:var(--fg)}}
333.actions .ghost:hover{{border-color:var(--accent);color:var(--accent)}}
334</style>
335</head>
336<body>
337<div class="box">
338<p class="code">{code}</p>
339<hr class="rule">
340<h1>{title}</h1>
341<p>{detail}</p>
342<div class="actions"><a class="primary" href="/">Go to homepage</a><a class="ghost" href="javascript:history.back()">&larr; Go back</a></div>
343</div>
344</body>
345</html>"##
346    );
347    (
348        status,
349        [
350            (axum::http::header::CONTENT_TYPE, "text/html; charset=utf-8"),
351            (axum::http::header::CACHE_CONTROL, "no-store"),
352        ],
353        html,
354    )
355        .into_response()
356}
357
358#[cfg(test)]
359mod tests {
360    use super::*;
361
362    #[test]
363    fn handler_registers_in_the_page_type_registry() {
364        let handler = crate::page_type::find_handler(TYPE_NAME)
365            .expect("ErrorPage should be inventory-registered");
366        assert_eq!(handler.default_template(), "error_page.html");
367        assert_eq!(handler.verbose_name(), "Error page");
368        assert!(handler.is_leaf(), "error pages must not accept children");
369        assert!(handler.is_creatable());
370        assert_eq!(handler.icon(), Some("error"));
371    }
372
373    async fn body_string(resp: Response) -> String {
374        let bytes = axum::body::to_bytes(resp.into_body(), usize::MAX)
375            .await
376            .expect("body");
377        String::from_utf8_lossy(&bytes).into_owned()
378    }
379
380    #[tokio::test]
381    async fn fallback_response_is_selfcontained_html_with_links() {
382        let resp = fallback_response(StatusCode::NOT_FOUND);
383        assert_eq!(resp.status(), StatusCode::NOT_FOUND);
384        let ct = resp
385            .headers()
386            .get(axum::http::header::CONTENT_TYPE)
387            .and_then(|v| v.to_str().ok())
388            .unwrap_or_default()
389            .to_owned();
390        assert!(ct.starts_with("text/html"), "content-type was {ct}");
391        let cc = resp
392            .headers()
393            .get(axum::http::header::CACHE_CONTROL)
394            .and_then(|v| v.to_str().ok())
395            .unwrap_or_default()
396            .to_owned();
397        assert_eq!(cc, "no-store");
398        let body = body_string(resp).await;
399        assert!(body.contains("404"));
400        assert!(body.contains("Page not found"));
401        assert!(body.contains("history.back()"), "back link present");
402        assert!(body.contains("href=\"/\""), "home link present");
403    }
404
405    #[tokio::test]
406    async fn fallback_titles_cover_wired_statuses() {
407        for (status, needle) in [
408            (StatusCode::INTERNAL_SERVER_ERROR, "Something went wrong"),
409            (StatusCode::FORBIDDEN, "Access denied"),
410            (StatusCode::SERVICE_UNAVAILABLE, "Service unavailable"),
411        ] {
412            let resp = fallback_response(status);
413            assert_eq!(resp.status(), status);
414            let body = body_string(resp).await;
415            assert!(body.contains(needle), "missing {needle:?}");
416        }
417    }
418
419    #[cfg(feature = "sqlite")]
420    mod db {
421        use super::super::*;
422        use crate::PageTypeHandler as _;
423
424        async fn mem_pool() -> Pool {
425            let pool = Pool::connect("sqlite::memory:")
426                .await
427                .expect("in-memory sqlite");
428            // cms_page + its FK parents (cms_page_type, cms_media) +
429            // our extension table, straight from each model's SCHEMA —
430            // sqlite enforces FK parent tables at insert time.
431            for schema in [
432                &crate::page_type_model::PageType::SCHEMA,
433                &crate::media::Media::SCHEMA,
434                &crate::theme::Theme::SCHEMA,
435                &Page::SCHEMA,
436            ] {
437                let ddl = rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect(
438                    pool.dialect(),
439                    schema,
440                );
441                for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
442                    rustango::sql::raw_execute_pool(&pool, stmt, Vec::new())
443                        .await
444                        .expect("ddl");
445                }
446            }
447            ensure_table(&pool).await.expect("cms_error_page ddl");
448            // Satisfy the `page_type_id` FK for test pages.
449            let mut pt = crate::page_type_model::PageType {
450                id: Auto::Unset,
451                app_label: "cms".to_owned(),
452                type_name: TYPE_NAME.to_owned(),
453                verbose_name: "Error page".to_owned(),
454                default_template: "error_page.html".to_owned(),
455                view_mode: "auto".to_owned(),
456                is_creatable: true,
457                allowed_parent_types: serde_json::json!([]),
458                allowed_child_types: serde_json::json!([]),
459                workflow: String::new(),
460                created_at: Auto::Unset,
461                updated_at: Auto::Unset,
462            };
463            pt.insert_pool(&pool).await.expect("insert page type");
464            pool
465        }
466
467        async fn mk_page(pool: &Pool, slug: &str, status: &str) -> i64 {
468            let mut page = Page {
469                id: Auto::Unset,
470                page_type_id: 1,
471                title: format!("Error {slug}"),
472                slug: slug.to_owned(),
473                path: format!("0001{slug}/"),
474                url_path: format!("/{slug}"),
475                preview_path: String::new(),
476                template_override: String::new(),
477                depth: 1,
478                parent_id: None,
479                locale_variant_of: None,
480                alias_of: None,
481                theme_id: None,
482                sort_order: 0,
483                status: status.to_owned(),
484                published_at: None,
485                last_published_at: None,
486                go_live_at: None,
487                expire_at: None,
488                seo_title: String::new(),
489                seo_description: String::new(),
490                robots_index: true,
491                sitemap_priority: 0.5,
492                show_in_menus: false,
493                og_title: String::new(),
494                og_description: String::new(),
495                og_image_media_id: None,
496                twitter_card: "summary_large_image".to_owned(),
497                notification_pre_published_sent: false,
498                created_at: Auto::Unset,
499                updated_at: Auto::Unset,
500            };
501            page.insert_pool(pool).await.expect("insert page");
502            page.id.get().copied().expect("page id")
503        }
504
505        #[tokio::test]
506        async fn find_for_status_returns_published_match_only() {
507            let pool = mem_pool().await;
508            // Draft 404 page — must NOT be served.
509            let draft_id = mk_page(&pool, "draft-404", "draft").await;
510            ErrorPageExt {
511                id: Auto::Unset,
512                page_id: draft_id,
513                status_code: "404".into(),
514                body: None,
515            }
516            .insert_pool(&pool)
517            .await
518            .expect("draft ext");
519            assert!(
520                find_for_status(&pool, 404).await.expect("query").is_none(),
521                "draft error pages must not serve"
522            );
523
524            // Published 404 page — served.
525            let live_id = mk_page(&pool, "live-404", "published").await;
526            ErrorPageExt {
527                id: Auto::Unset,
528                page_id: live_id,
529                status_code: "404".into(),
530                body: None,
531            }
532            .insert_pool(&pool)
533            .await
534            .expect("live ext");
535            let hit = find_for_status(&pool, 404).await.expect("query");
536            assert_eq!(
537                hit.and_then(|p| p.id.get().copied()),
538                Some(live_id),
539                "published 404 page should be found"
540            );
541            // Other statuses still miss.
542            assert!(find_for_status(&pool, 500).await.expect("query").is_none());
543
544            // #763 — an archived error page is served like any archived page.
545            let kept_id = mk_page(&pool, "kept-410", "archived").await;
546            ErrorPageExt {
547                id: Auto::Unset,
548                page_id: kept_id,
549                status_code: "410".into(),
550                body: None,
551            }
552            .insert_pool(&pool)
553            .await
554            .expect("archived ext");
555            let hit = find_for_status(&pool, 410).await.expect("query");
556            assert_eq!(hit.and_then(|p| p.id.get().copied()), Some(kept_id));
557        }
558
559        #[tokio::test]
560        async fn save_extension_roundtrips_through_load_extension() {
561            let pool = mem_pool().await;
562            let page_id = mk_page(&pool, "e500", "published").await;
563            let handler = ErrorPage;
564            let mut form = std::collections::HashMap::new();
565            form.insert("status_code".to_owned(), "500".to_owned());
566            form.insert(
567                "body".to_owned(),
568                r#"[{"type":"paragraph","value":"Oops."}]"#.to_owned(),
569            );
570            handler
571                .save_extension(&pool, page_id, &form)
572                .await
573                .expect("save");
574            let ext = handler.load_extension(&pool, page_id).await.expect("load");
575            assert_eq!(ext["status_code"], "500");
576            assert!(ext["body"].as_str().unwrap_or_default().contains("Oops."));
577
578            // Re-save flips the code in place (upsert, not a second row).
579            form.insert("status_code".to_owned(), "503".to_owned());
580            handler
581                .save_extension(&pool, page_id, &form)
582                .await
583                .expect("re-save");
584            let rows: Vec<ErrorPageExt> = ErrorPageExt::objects()
585                .where_(ErrorPageExt::page_id.eq(page_id))
586                .fetch(&pool)
587                .await
588                .expect("fetch");
589            assert_eq!(rows.len(), 1, "upsert must not duplicate");
590            assert_eq!(rows[0].status_code, "503");
591        }
592    }
593}