Skip to main content

rustango_cms/forms/
submit.rs

1//! Form submissions: model, boot-time table ensure, and the public submit
2//! handler.
3//!
4//! The submission table is created at boot via `CREATE TABLE IF NOT EXISTS`
5//! (the framework's audit_log/cache pattern) because repo-wide
6//! `gen_migration` is blocked by pre-existing framework FK-snapshot drift.
7//! A fresh table name (`cms_form_entry`) sidesteps the dead legacy
8//! `cms_form_submission` table.
9//!
10//! Provenance: the source page is resolved from the `Referer` at submit;
11//! the embedding block's per-placement success override is resolved
12//! server-side from that page's stream JSON by the `_embed` block uuid
13//! (never trusted from a client field).
14
15use axum::extract::{Path, State};
16use axum::http::HeaderMap;
17use axum::response::{IntoResponse, Redirect, Response};
18use chrono::{DateTime, Utc};
19use rustango::core::Column as _;
20use rustango::core::Model as _;
21use rustango::extractors::Tenant;
22use rustango::sql::Auto;
23use rustango::sql::FetcherPool as _;
24use rustango::Model;
25use serde::{Deserialize, Serialize};
26
27use super::render::HONEYPOT_FIELD;
28use super::schema;
29
30/// One stored submission. New snippet-backed forms store here.
31#[derive(Model, Debug, Clone, Serialize, Deserialize)]
32#[rustango(table = "cms_form_entry", app = "cms")]
33pub struct FormEntry {
34    #[rustango(primary_key)]
35    pub id: Auto<i64>,
36    /// The form snippet (`cms_snippet`) this answers.
37    #[rustango(index)]
38    pub form_snippet_id: i64,
39    /// Snippet revision sequence at submit time (0 = unknown). Lets the
40    /// submissions admin resolve column drift across form edits.
41    pub form_version: i64,
42    /// Page the form was submitted from (provenance). 0 = unknown.
43    #[rustango(index)]
44    pub source_page_id: i64,
45    #[rustango(max_length = 512)]
46    pub source_url: String,
47    /// Answers keyed by field key. Multi-value fields hold a JSON array.
48    pub data_json: serde_json::Value,
49    #[rustango(max_length = 16)]
50    pub locale: String,
51    #[rustango(max_length = 64)]
52    pub ip: String,
53    #[rustango(auto_now_add)]
54    pub submitted_at: Auto<DateTime<Utc>>,
55}
56
57/// Create `cms_form_entry` if absent. Idempotent; called per tenant at boot.
58///
59/// # Errors
60/// Driver / DDL failures.
61pub async fn ensure_table(pool: &rustango::sql::Pool) -> Result<(), rustango::sql::ExecError> {
62    let ddl = rustango::migrate::ddl::create_table_if_not_exists_sql_with_dialect(
63        pool.dialect(),
64        &FormEntry::SCHEMA,
65    );
66    for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
67        rustango::sql::raw_execute_pool(pool, stmt, Vec::new()).await?;
68    }
69    Ok(())
70}
71
72/// `POST /forms/submit/{form_id}` — validate, store, notify, and redirect.
73/// The largest form submission accepted, uploads included. Set on
74/// the route itself, so a host that raises or disables axum's default body
75/// limit for its own upload routes doesn't let an anonymous visitor buffer
76/// an arbitrarily large file into memory here.
77pub const MAX_SUBMISSION_BYTES: usize = 10 * 1024 * 1024;
78
79pub(crate) async fn handle_form_submit(
80    State(state): State<crate::router::PublicState>,
81    tenant: Tenant,
82    headers: HeaderMap,
83    Path(form_id): Path<i64>,
84    req: axum::extract::Request,
85) -> Response {
86    use axum::extract::FromRequest as _;
87    let pool = tenant.pool();
88
89    // Load the form snippet → schema.
90    let snippet = match crate::snippet::Snippet::objects()
91        .where_(crate::snippet::Snippet::id.eq(form_id))
92        .where_(crate::snippet::Snippet::type_name.eq("form".to_owned()))
93        .first(pool)
94        .await
95    {
96        Ok(Some(s)) => s,
97        _ => return (axum::http::StatusCode::NOT_FOUND, "Unknown form.").into_response(),
98    };
99    let form = schema::parse(&snippet.data).unwrap_or_default();
100
101    // Parse the body. urlencoded (simple / no-JS forms) → `pairs`. multipart
102    // (forms with file uploads, fetch-submitted by the runtime so the
103    // X-CSRF-Token header is present) → text fields into `pairs`, files held
104    // in `pending_uploads` with their storage key in `file_answers`. Nothing
105    // is written until the submission is accepted (#656).
106    let content_type = headers
107        .get(axum::http::header::CONTENT_TYPE)
108        .and_then(|v| v.to_str().ok())
109        .unwrap_or("")
110        .to_owned();
111    let mut pairs: Vec<(String, String)> = Vec::new();
112    let mut file_answers: std::collections::HashMap<String, String> =
113        std::collections::HashMap::new();
114    let mut pending_uploads: Vec<(String, axum::body::Bytes)> = Vec::new();
115    if content_type.starts_with("multipart/form-data") {
116        let Ok(mut mp) = axum::extract::Multipart::from_request(req, &()).await else {
117            return (axum::http::StatusCode::BAD_REQUEST, "Bad upload.").into_response();
118        };
119        // A read error — the body over MAX_SUBMISSION_BYTES, or a torn
120        // upload — rejects the submission (#666). Read as "no more fields",
121        // it saved the rest of the form and dropped the file silently.
122        loop {
123            let field = match mp.next_field().await {
124                Ok(Some(f)) => f,
125                Ok(None) => break,
126                Err(e) => return (e.status(), "Upload rejected.").into_response(),
127            };
128            let name = field.name().unwrap_or("").to_owned();
129            if name.is_empty() {
130                continue;
131            }
132            let fname = field
133                .file_name()
134                .map(str::to_owned)
135                .filter(|f| !f.is_empty());
136            if let Some(fname) = fname {
137                let bytes = match field.bytes().await {
138                    Ok(b) => b,
139                    Err(e) => return (e.status(), "Upload rejected.").into_response(),
140                };
141                if !bytes.is_empty() {
142                    if let Some(key) = upload_key(&fname, &bytes) {
143                        file_answers.insert(name, key.clone());
144                        pending_uploads.push((key, bytes));
145                    }
146                }
147            } else {
148                match field.text().await {
149                    Ok(text) => pairs.push((name, text)),
150                    Err(e) => return (e.status(), "Upload rejected.").into_response(),
151                }
152            }
153        }
154    } else {
155        let bytes = axum::body::to_bytes(req.into_body(), 2 * 1024 * 1024)
156            .await
157            .unwrap_or_default();
158        pairs = serde_urlencoded::from_bytes(&bytes).unwrap_or_default();
159    }
160
161    // Honeypot — silently accept (200) without storing so bots get no signal.
162    let hp_filled = pairs
163        .iter()
164        .any(|(k, v)| k == HONEYPOT_FIELD && !v.trim().is_empty());
165
166    // Every value per key, for conditional-logic evaluation (FB-14): a
167    // checkbox group answers several. Field keys never start with `_`, so
168    // meta fields are excluded.
169    let mut vals: std::collections::HashMap<String, Vec<String>> = std::collections::HashMap::new();
170    for (k, v) in &pairs {
171        if !k.starts_with('_') {
172            vals.entry(k.clone()).or_default().push(v.clone());
173        }
174    }
175
176    // Collect answers keyed by field key, building arrays for multi-value.
177    // `refused` is the first question the submission failed on, so the
178    // visitor is sent back to it.
179    let mut answers = serde_json::Map::new();
180    let mut refused: Option<String> = None;
181    for field in form.fields() {
182        if !field.field_type.collects_value() || field.key.is_empty() {
183            continue;
184        }
185        // FB-14 — fields hidden by their rules are excused from required +
186        // validation (their stale value must not block the submit).
187        let visible = schema::is_visible(field, &vals);
188        // File fields carry their value in `file_answers` (saved to disk),
189        // not in the urlencoded pairs.
190        if matches!(field.field_type, schema::FieldType::File) {
191            match file_answers.get(&field.key) {
192                Some(key) => {
193                    answers.insert(field.key.clone(), serde_json::Value::String(key.clone()));
194                }
195                None => {
196                    if visible && field.required {
197                        refused.get_or_insert_with(|| field.key.clone());
198                    }
199                }
200            }
201            continue;
202        }
203        let values: Vec<&String> = pairs
204            .iter()
205            .filter(|(k, _)| k == &field.key)
206            .map(|(_, v)| v)
207            .filter(|v| !v.is_empty())
208            .collect();
209        if visible && field.required && values.is_empty() {
210            refused.get_or_insert_with(|| field.key.clone());
211        }
212        // FB-13 — server-side format/length enforcement (mirrors the
213        // client HTML5 attrs; rejects tampered POSTs).
214        if visible && values.iter().any(|v| schema::validate_value(field, v).is_some()) {
215            refused.get_or_insert_with(|| field.key.clone());
216        }
217        if field.field_type.is_multi_value() {
218            answers.insert(
219                field.key.clone(),
220                serde_json::Value::Array(
221                    values
222                        .into_iter()
223                        .map(|v| serde_json::Value::String(v.clone()))
224                        .collect(),
225                ),
226            );
227        } else if let Some(v) = values.first() {
228            answers.insert(field.key.clone(), serde_json::Value::String((*v).clone()));
229        }
230    }
231
232    // Source page (provenance) from the Referer.
233    let referer = headers
234        .get(axum::http::header::REFERER)
235        .and_then(|v| v.to_str().ok())
236        .unwrap_or("")
237        .to_owned();
238    let source_path = referer_path(&referer);
239    // The page's own url_path: no query, no language prefix (`/fr/…`), and
240    // relative to this host's site root — the same steps the renderer takes.
241    let (path_only, query) = match source_path.split_once('?') {
242        Some((p, q)) => (p.to_owned(), Some(q.to_owned())),
243        None => (source_path.clone(), None),
244    };
245    let cookie_header = headers
246        .get(axum::http::header::COOKIE)
247        .and_then(|v| v.to_str().ok());
248    let request_locale = crate::locale_mode::resolve_request_locale(
249        pool,
250        state.locale_mode(),
251        &path_only,
252        query.as_deref(),
253        crate::locale_mode::locale_cookie_value(cookie_header).as_deref(),
254        None,
255    )
256    .await;
257    let site_prefix = crate::site::prefix_for_host(pool, crate::router::host_header(&headers))
258        .await
259        .unwrap_or_default();
260    let lookup_path = if path_only.is_empty() {
261        String::new()
262    } else {
263        crate::site::to_lookup_path(&site_prefix, &request_locale.stripped_path)
264    };
265    let source_page_id = if lookup_path.is_empty() {
266        0
267    } else {
268        crate::page::Page::objects()
269            .where_(crate::page::Page::url_path.eq(lookup_path.clone()))
270            .first(pool)
271            .await
272            .ok()
273            .flatten()
274            .and_then(|p| p.id.get().copied())
275            .unwrap_or(0)
276    };
277
278    // Per-embed override (success redirect / message), resolved server-side
279    // from the source page's stream by the `_embed` block uuid.
280    let embed_id = pairs
281        .iter()
282        .find(|(k, _)| k == "_embed")
283        .map(|(_, v)| v.clone())
284        .unwrap_or_default();
285    // (The placement's thanks message is rendered with the form itself.)
286    let ovr_redirect = if source_page_id != 0 && !embed_id.is_empty() {
287        resolve_embed_redirect(pool, source_page_id, &embed_id).await
288    } else {
289        None
290    };
291
292    // Reject only on honeypot or a refused answer — redirect back with a
293    // flag naming the question, so the runtime can return to it.
294    if hp_filled || refused.is_some() {
295        let back = if source_path.is_empty() {
296            "/".to_owned()
297        } else {
298            strip_form_flags(&source_path)
299        };
300        let sep = if back.contains('?') { '&' } else { '?' };
301        let flag = if hp_filled {
302            format!("form_submitted={form_id}")
303        } else {
304            format!("form_error={form_id}:{}", refused.unwrap_or_default())
305        };
306        return Redirect::to(&format!("{back}{sep}{flag}")).into_response();
307    }
308
309    // Store.
310    let ip = headers
311        .get("x-forwarded-for")
312        .and_then(|v| v.to_str().ok())
313        .and_then(|s| s.split(',').next())
314        .unwrap_or("")
315        .trim()
316        .to_owned();
317    // FB-15 — record which version this answered (revision count = version),
318    // so the submissions admin can resolve schema drift across edits.
319    let form_version = crate::snippet::SnippetRevision::objects()
320        .where_(crate::snippet::SnippetRevision::snippet_id.eq(form_id))
321        .fetch(pool)
322        .await
323        .map(|v| v.len() as i64)
324        .unwrap_or(0);
325    // FB-17 — record the language the form was filled in: the page's
326    // (`/fr/…`, `?lang=`), else the visitor's chosen one (cookie).
327    let locale = request_locale.code.clone().unwrap_or_default();
328    let mut entry = FormEntry {
329        id: Auto::Unset,
330        form_snippet_id: form_id,
331        form_version,
332        source_page_id,
333        source_url: referer.chars().take(512).collect(),
334        data_json: serde_json::Value::Object(answers),
335        locale: locale.chars().take(16).collect(),
336        ip: ip.chars().take(64).collect(),
337        submitted_at: Auto::Unset,
338    };
339    // Only now, with the submission accepted, do its files reach disk
340    // (#656): written earlier, every honeypot hit or missing-required
341    // bounce left an upload no entry referred to.
342    let mut written: Vec<String> = Vec::new();
343    for (key, bytes) in &pending_uploads {
344        if write_upload(&tenant.org.slug, key, bytes).await {
345            written.push(key.clone());
346        }
347    }
348    if entry.insert_pool(pool).await.is_err() {
349        for key in &written {
350            remove_upload(&tenant.org.slug, key).await;
351        }
352        return (
353            axum::http::StatusCode::INTERNAL_SERVER_ERROR,
354            "Could not save your submission.",
355        )
356            .into_response();
357    }
358
359    // Notify. Everything goes through the notification outbox now: the
360    // recipients from this form's settings, plus any Slack / Teams /
361    // Telegram / webhook target subscribed to `form.submitted`.
362    //
363    // This used to be an email loop written right here, sending inside the
364    // request. That made the visitor wait on the mail server and turned a
365    // transient failure into a log line nobody reads — with the submission
366    // saved and the notification simply gone. Queue, then deliver off the
367    // request path, where a failure is a row someone can see and retry.
368    {
369        let mut msg = crate::notify::Notification::new(
370            crate::notify::events::FORM_SUBMITTED,
371            format!("New form submission: {}", snippet.title),
372        )
373        .summary(format!("A visitor submitted \"{}\".", snippet.title));
374        // Walk the SCHEMA, not the answers. `data_json` is a sorted map, so
375        // reading it directly hands the reader "email, message, name" — an
376        // alphabetised jumble of the form they actually filled in. The
377        // schema knows the order the questions were asked, and a
378        // notification is read like the form, top to bottom.
379        if let serde_json::Value::Object(map) = &entry.data_json {
380            let mut seen = std::collections::HashSet::new();
381            let render = |v: &serde_json::Value| match v {
382                serde_json::Value::String(s) => s.clone(),
383                other => other.to_string(),
384            };
385            for f in form.fields() {
386                if let Some(v) = map.get(&f.key) {
387                    seen.insert(f.key.clone());
388                    let label = if f.label.trim().is_empty() {
389                        f.key.clone()
390                    } else {
391                        f.label.clone()
392                    };
393                    msg = msg.field(label, render(v));
394                }
395            }
396            // Anything the schema no longer mentions still belongs in the
397            // notification — a field removed after this entry was queued is
398            // exactly when you want to see the value, not lose it.
399            for (k, v) in map {
400                if !seen.contains(k) {
401                    msg = msg.field(k.clone(), render(v));
402                }
403            }
404        }
405        if !entry.source_url.is_empty() {
406            msg = msg.url(entry.source_url.clone());
407        }
408        // A notification failure must never fail the submission — the entry
409        // is already stored, and losing the lead is far worse than a late
410        // alert.
411        match crate::notify::worker::enqueue(pool, &msg, form_id).await {
412            Ok(0) => {}
413            Ok(_) => crate::notify::worker::spawn_drain(
414                pool.clone(),
415                tenant.org.slug.clone(),
416                state.mailer.clone(),
417                state.mailer_from.as_str().to_owned(),
418            ),
419            Err(e) => tracing::warn!(
420                target: "rustango_cms::forms",
421                error = %e, form_id, "could not queue submission notifications"
422            ),
423        }
424    }
425
426    // Success precedence: embed redirect → form redirect → thanks on source.
427    if let Some(url) = ovr_redirect.filter(|u| is_safe_redirect(u)) {
428        return Redirect::to(&url).into_response();
429    }
430    if !form.settings.redirect_url.is_empty() && is_safe_redirect(&form.settings.redirect_url) {
431        return Redirect::to(&form.settings.redirect_url).into_response();
432    }
433    let back = if source_path_is_usable(&referer) {
434        strip_form_flags(&referer_path(&referer))
435    } else {
436        "/".to_owned()
437    };
438    let sep = if back.contains('?') { '&' } else { '?' };
439    Redirect::to(&format!("{back}{sep}form_submitted={form_id}")).into_response()
440}
441
442/// Reduce a Referer URL to its path (+query), dropping scheme/host so the
443/// redirect stays same-origin.
444fn referer_path(referer: &str) -> String {
445    if referer.is_empty() {
446        return String::new();
447    }
448    if let Some(rest) = referer.splitn(2, "://").nth(1) {
449        // strip host
450        match rest.find('/') {
451            Some(i) => rest[i..].to_owned(),
452            None => "/".to_owned(),
453        }
454    } else if referer.starts_with('/') {
455        referer.to_owned()
456    } else {
457        String::new()
458    }
459}
460
461/// `path` without an earlier `form_submitted` / `form_error` flag, so a
462/// second attempt from the result page doesn't carry both.
463fn strip_form_flags(path: &str) -> String {
464    let Some((base, query)) = path.split_once('?') else {
465        return path.to_owned();
466    };
467    let kept: Vec<&str> = query
468        .split('&')
469        .filter(|kv| {
470            let k = kv.split('=').next().unwrap_or("");
471            !kv.is_empty() && k != "form_submitted" && k != "form_error"
472        })
473        .collect();
474    if kept.is_empty() {
475        base.to_owned()
476    } else {
477        format!("{base}?{}", kept.join("&"))
478    }
479}
480
481fn source_path_is_usable(referer: &str) -> bool {
482    !referer_path(referer).is_empty()
483}
484
485/// Only allow same-origin (path-only) redirects to avoid open-redirects.
486fn is_safe_redirect(url: &str) -> bool {
487    rustango::auth_decorators::safe_next(url).is_some()
488}
489
490/// The success redirect set on the `form` block `embed_id` of the source
491/// page, if any. The block can sit in a code page type's stream (its
492/// extension) or in the fields of a page type made in the admin (its
493/// builder data), nested at any depth.
494async fn resolve_embed_redirect(
495    pool: &rustango::sql::Pool,
496    page_id: i64,
497    embed_id: &str,
498) -> Option<String> {
499    let page = crate::page::Page::objects()
500        .where_(crate::page::Page::id.eq(page_id))
501        .first(pool)
502        .await
503        .ok()??;
504    let mut documents: Vec<serde_json::Value> = Vec::new();
505    let handler = crate::page_type_model::PageType::objects()
506        .where_(crate::page_type_model::PageType::id.eq(page.page_type_id))
507        .first(pool)
508        .await
509        .ok()
510        .flatten()
511        .and_then(|pt| crate::page_type::find_handler(&pt.type_name));
512    if let Some(handler) = handler {
513        if let Ok(extension) = handler.load_extension(pool, page_id).await {
514            documents.push(extension);
515        }
516    }
517    if let Ok(Some(builder)) = crate::page_builder::model::data_for_page(pool, page_id).await {
518        documents.push(builder.data);
519    }
520    documents
521        .iter()
522        .find_map(|doc| find_embed(doc, embed_id))
523        .and_then(|block| block.get("success_redirect_url").and_then(serde_json::Value::as_str))
524        .filter(|url| !url.is_empty())
525        .map(str::to_owned)
526}
527
528/// The value of the `form` block with id `embed_id` anywhere under `value`.
529fn find_embed<'a>(value: &'a serde_json::Value, embed_id: &str) -> Option<&'a serde_json::Value> {
530    match value {
531        serde_json::Value::Object(obj) => {
532            if obj.get("id").and_then(serde_json::Value::as_str) == Some(embed_id)
533                && obj.get("type").and_then(serde_json::Value::as_str) == Some("form")
534            {
535                return obj.get("value");
536            }
537            obj.values().find_map(|v| find_embed(v, embed_id))
538        }
539        serde_json::Value::Array(items) => items.iter().find_map(|v| find_embed(v, embed_id)),
540        _ => None,
541    }
542}
543
544/// The storage key an upload is saved under in `./var/form-uploads/<slug>/`:
545/// a content hash plus the sanitized filename. `None` for a name that
546/// sanitizes to nothing. Pure — nothing is written.
547fn upload_key(filename: &str, bytes: &[u8]) -> Option<String> {
548    use sha2::{Digest, Sha256};
549    let safe = sanitize_upload_name(filename);
550    if safe.is_empty() {
551        return None;
552    }
553    let mut hasher = Sha256::new();
554    hasher.update(bytes);
555    let hex: String = hasher
556        .finalize()
557        .iter()
558        .take(8)
559        .fold(String::new(), |mut a, b| {
560            use std::fmt::Write as _;
561            let _ = write!(a, "{b:02x}");
562            a
563        });
564    Some(format!("{hex}-{safe}"))
565}
566
567fn upload_dir(slug: &str) -> std::path::PathBuf {
568    std::path::PathBuf::from("./var/form-uploads").join(sanitize_upload_name(slug))
569}
570
571/// Write an accepted upload under its [`upload_key`]. Async I/O: this runs
572/// inside an anonymous request. A failed write is logged and the
573/// submission is kept without the file.
574async fn write_upload(slug: &str, key: &str, bytes: &[u8]) -> bool {
575    let dir = upload_dir(slug);
576    let written = async {
577        rustango::__private_runtime::tokio::fs::create_dir_all(&dir).await?;
578        rustango::__private_runtime::tokio::fs::write(dir.join(key), bytes).await
579    }
580    .await;
581    if let Err(e) = written {
582        tracing::warn!(target: "rustango_cms::forms", error = %e, "form upload not stored; the submission is saved without it");
583        return false;
584    }
585    true
586}
587
588/// Remove an upload written for a submission that then failed to save.
589async fn remove_upload(slug: &str, key: &str) {
590    let _ = rustango::__private_runtime::tokio::fs::remove_file(upload_dir(slug).join(key)).await;
591}
592
593/// Reduce an untrusted filename to a safe basename (no path separators,
594/// only `[A-Za-z0-9._-]`, capped length). Used for both the filename and
595/// the tenant-slug path segment to keep uploads inside the upload dir.
596fn sanitize_upload_name(name: &str) -> String {
597    let base = name.rsplit(['/', '\\']).next().unwrap_or(name);
598    let cleaned: String = base
599        .chars()
600        .map(|c| {
601            if c.is_ascii_alphanumeric() || c == '.' || c == '-' || c == '_' {
602                c
603            } else {
604                '_'
605            }
606        })
607        .take(100)
608        .collect();
609    cleaned.trim_matches('.').to_owned()
610}
611
612#[cfg(test)]
613mod tests {
614    use super::*;
615
616    #[test]
617    fn sanitize_upload_name_strips_paths() {
618        assert_eq!(sanitize_upload_name("../../etc/passwd"), "passwd");
619        assert_eq!(
620            sanitize_upload_name("my report (1).pdf"),
621            "my_report__1_.pdf"
622        );
623        assert_eq!(sanitize_upload_name("..\\..\\win.ini"), "win.ini");
624    }
625
626    #[test]
627    fn finds_the_embed_in_a_stream_or_builder_fields() {
628        let builder = serde_json::json!({
629            "price": 32.0,
630            "order": [{ "id": "b1", "type": "form", "value": { "form": "3", "success_redirect_url": "/thanks" } }]
631        });
632        assert_eq!(find_embed(&builder, "b1").and_then(|v| v["success_redirect_url"].as_str()), Some("/thanks"));
633        let nested = serde_json::json!({ "body": [{ "id": "x", "type": "section", "value": { "inner": [
634            { "id": "b2", "type": "form", "value": { "success_redirect_url": "/deep" } } ] } }] });
635        assert_eq!(find_embed(&nested, "b2").and_then(|v| v["success_redirect_url"].as_str()), Some("/deep"));
636        assert!(find_embed(&nested, "missing").is_none());
637        // Another block type with the same id is not the embed.
638        let other = serde_json::json!([{ "id": "b3", "type": "text", "value": {} }]);
639        assert!(find_embed(&other, "b3").is_none());
640    }
641
642    #[test]
643    fn earlier_result_flags_are_dropped() {
644        assert_eq!(strip_form_flags("/c?form_error=name"), "/c");
645        assert_eq!(strip_form_flags("/c?lang=fr&form_submitted=1"), "/c?lang=fr");
646        assert_eq!(strip_form_flags("/c?form_error=1&form_error=2&x=1"), "/c?x=1");
647        assert_eq!(strip_form_flags("/c"), "/c");
648    }
649
650    #[test]
651    fn referer_path_strips_host() {
652        assert_eq!(referer_path("https://x.test/a/b?c=1"), "/a/b?c=1");
653        assert_eq!(referer_path("http://x.test"), "/");
654        assert_eq!(referer_path("/already/path"), "/already/path");
655        assert_eq!(referer_path(""), "");
656    }
657
658    #[test]
659    fn safe_redirect_blocks_offsite() {
660        assert!(is_safe_redirect("/thanks"));
661        assert!(!is_safe_redirect("//evil.test"));
662        assert!(!is_safe_redirect("https://evil.test"));
663        // Browsers read `/\host` and its encoded forms as `//host` (#728).
664        assert!(!is_safe_redirect("/\\evil.test"));
665        assert!(!is_safe_redirect("/%5Cevil.test"));
666        assert!(!is_safe_redirect("/%2Fevil.test"));
667    }
668}
669