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