Skip to main content

rustango_cms/
router.rs

1//! Public axum router that the host app mounts.
2//!
3//! Two flavours, each with a cache-enabled variant:
4//!
5//! - [`router`] — fallback-style. The CMS resolver is the router's
6//!   `.fallback()`, so any unmatched path renders as a page. Simple
7//!   and correct **for non-tenancy apps**.
8//! - [`router_at`] — explicit-prefix style. Mounts the CMS at a
9//!   non-root prefix via `nest(prefix, /{*path})`. Required when
10//!   composing with rustango's tenancy admin — see note below.
11//!
12//! ## Caching
13//!
14//! Both have `_cached` variants that wrap the router with
15//! [`rustango::cache_page::CachePageLayer`] — a tower layer that
16//! caches successful GET responses on a `(prefix, method, path,
17//! Host, vary-on)` key and emits the matching `Cache-Control` /
18//! `Vary` headers. GET-only, 200-only; the layer respects a
19//! response's own `Cache-Control: no-store` so individual handlers
20//! can opt out.
21//!
22//! By default entries expire on TTL only, so editors see stale content
23//! for up to the TTL after a save. To purge on save, build a
24//! [`crate::cache_invalidate::BoxedCacheInvalidator`] over the same
25//! cache and pass it to [`crate::admin::router_with_invalidator`]; the
26//! admin then drops the affected keys after each page mutation.
27//!
28//! Per-tenant scoping is automatic via the layer's built-in `Host`-
29//! header partitioning. Vary on `cookie` / `accept-language` etc.
30//! via the layer's `vary_on(...)` method when building via
31//! [`PublicRouter`].
32//!
33//! ## Don't use [`router`] with `rustango` tenancy
34//!
35//! Rustango's tenancy [`server::Builder`] used to attach its own
36//! admin as `Router::fallback_service(tenant_admin)` on the merged
37//! user router. Axum semantics: that override silenced any
38//! `.fallback()` set by the user's router. As of rustango 0.31 the
39//! tenant admin mounts via explicit routes for `routes.admin_url`
40//! only, so [`router`] is allowed to claim site root — see
41//! `examples/cms_demo`.
42//!
43//! [`server::Builder`]: rustango::server::Builder
44
45use std::sync::Arc;
46use std::time::Duration;
47
48use axum::extract::State;
49use axum::http::{StatusCode, Uri};
50use axum::response::{IntoResponse, Redirect, Response};
51use axum::routing::get;
52use axum::Router;
53use rustango::cache::BoxedCache;
54use rustango::cache_page::CachePageLayer;
55use rustango::extractors::Tenant;
56use tera::Tera;
57
58use crate::locale_mode::{resolve_request_locale, LocaleMode};
59use crate::render::{render_negotiated, render_with_route};
60use crate::resolver::{resolve_path, resolve_routable};
61
62/// State shared with the page-rendering handler. Carries the Tera
63/// instance, URL mount prefix, and the locale-resolution mode
64/// (path vs. query). HTTP-level caching is layered onto the
65/// router after construction via [`CachePageLayer`]; the handler
66/// itself is stateless w.r.t. the cache.
67#[derive(Clone)]
68pub(crate) struct PublicState {
69    pub(crate) tera: Arc<Tera>,
70    pub(crate) url_prefix: String,
71    locale_mode: LocaleMode,
72    /// Optional mailer + from-addr for form-submission notifications.
73    /// When `None`, submissions don't email
74    /// anyone — the data still lands in `cms_form_entry`.
75    pub(crate) mailer: Option<Arc<dyn rustango::email::Mailer>>,
76    pub(crate) mailer_from: Arc<String>,
77    /// When the router runs a page cache (`_cached` variants),
78    /// the same backend + TTL are shared here so the render path can
79    /// cache the menu-eligible tree query. `None` for the uncached
80    /// variants (the render path then queries live every time).
81    pub(crate) fragment_cache: Option<(BoxedCache, Duration)>,
82    /// Per-tenant template overrides, when the host configured a
83    /// directory for them. `None` — the default — renders every tenant
84    /// from the global set, exactly as before.
85    pub(crate) tenant_templates: Option<Arc<crate::tenant_templates::TenantTemplates>>,
86}
87
88impl PublicState {
89    fn new(tera: Arc<Tera>, url_prefix: String) -> Self {
90        Self {
91            tera,
92            url_prefix,
93            locale_mode: LocaleMode::default(),
94            mailer: None,
95            mailer_from: Arc::new(String::new()),
96            fragment_cache: None,
97            tenant_templates: None,
98        }
99    }
100
101    /// The Tera this tenant should render with: its own overrides
102    /// layered on the global set, or the global set itself.
103    ///
104    /// A cached instance comes straight back; resolving one walks the
105    /// tenant's directory and may rebuild a Tera, so that runs on the
106    /// blocking pool rather than a runtime worker.
107    pub(crate) async fn tera_for(&self, slug: &str) -> Arc<Tera> {
108        let Some(tt) = self.tenant_templates.as_ref() else {
109            return Arc::clone(&self.tera);
110        };
111        if let Some(cached) = tt.cached(slug) {
112            return cached;
113        }
114        let (tt, owned) = (Arc::clone(tt), slug.to_owned());
115        rustango::__private_runtime::tokio::task::spawn_blocking(move || tt.for_tenant(&owned))
116            .await
117            .unwrap_or_else(|_| Arc::clone(&self.tera))
118    }
119    fn with_fragment_cache(mut self, cache: BoxedCache, ttl: Duration) -> Self {
120        self.fragment_cache = Some((cache, ttl));
121        self
122    }
123    fn with_locale_mode(mut self, mode: LocaleMode) -> Self {
124        self.locale_mode = mode;
125        self
126    }
127    /// The configured locale-URL mode — read by the sitemap handler to
128    /// emit per-locale `<url>` entries + hreflang alternates.
129    pub(crate) fn locale_mode(&self) -> LocaleMode {
130        self.locale_mode
131    }
132    fn with_mailer(
133        mut self,
134        mailer: Arc<dyn rustango::email::Mailer>,
135        from: impl Into<String>,
136    ) -> Self {
137        self.mailer = Some(mailer);
138        self.mailer_from = Arc::new(from.into());
139        self
140    }
141}
142
143/// Apply the framework's `CachePageLayer` to `router` with the
144/// supplied backend + TTL. Used by the `_cached` shortcuts and
145/// `PublicRouter::build` to produce the layered router.
146///
147/// Varies on `Accept-Language` AND the persisted locale cookie
148/// (#i18n): the renderer resolves the active locale from path / `?lang=`
149/// (both already in the cache key via path+query) / the `rcms_locale`
150/// cookie / `Accept-Language`, so the cache must key on each input or a
151/// cached response could be served in the wrong language. Varying on the
152/// raw `Cookie` header would fragment the cache by the rotating CSRF
153/// token, so a `map_request` layer first distills just the locale cookie
154/// into a synthetic `x-rcms-locale` request header and the cache keys on
155/// that. (Trade-off: bare-URL responses fragment by chosen locale +
156/// header; explicit path/`?lang=` URLs cache per-URL as before. The
157/// default un-cached `router()` is unaffected.)
158fn apply_cache_layer(router: Router, cache: BoxedCache, ttl: Duration) -> Router {
159    router
160        .layer(
161            CachePageLayer::new(cache)
162                .timeout(ttl)
163                .key_prefix("rcms:page")
164                .vary_on(["accept-language", "x-rcms-locale", "x-rcms-accept"]),
165        )
166        // Outermost: run before the cache layer so the synthetic headers
167        // are present when the cache key is computed.
168        .layer(axum::middleware::map_request(inject_locale_cookie_header))
169        .layer(axum::middleware::map_request(inject_accept_kind_header))
170}
171
172/// Distill `Accept` into a synthetic `x-rcms-accept` request header so
173/// the page cache keys on the *negotiated representation*.
174///
175/// Without this, an anonymous `Accept: application/json` request to an
176/// API-view page stores a JSON body under a key an anonymous browser
177/// request then reads — cross-representation cache poisoning. (Bounded,
178/// since the cache layer skips requests carrying `Cookie`/
179/// `Authorization`, but bot / CDN / first-visit traffic is exposed.)
180///
181/// Deliberately *not* `vary_on(["accept"])`: every browser family sends
182/// a different `Accept` string, which would fragment the cache several
183/// times over for a feature only a couple of page types use. The header
184/// is stamped **only** for an explicit JSON preference, so HTML and
185/// wildcard callers keep sharing one key — and every
186/// [`crate::page_view::PageViewKind`] resolves those two to the same
187/// body, so collapsing them is provably safe.
188async fn inject_accept_kind_header(mut req: axum::extract::Request) -> axum::extract::Request {
189    let accept = crate::page_view::parse_accept(
190        req.headers()
191            .get(axum::http::header::ACCEPT)
192            .and_then(|v| v.to_str().ok()),
193    );
194    if accept == crate::page_view::Accept::Json {
195        req.headers_mut().insert(
196            axum::http::HeaderName::from_static("x-rcms-accept"),
197            axum::http::HeaderValue::from_static("json"),
198        );
199    }
200    req
201}
202
203/// Distill the `rcms_locale` cookie into an `x-rcms-locale` request
204/// header so [`apply_cache_layer`]'s page cache can key on the chosen
205/// locale without fragmenting on the whole (CSRF-bearing) `Cookie`
206/// header. No-op when the cookie is absent/malformed.
207async fn inject_locale_cookie_header(mut req: axum::extract::Request) -> axum::extract::Request {
208    let code = crate::locale_mode::locale_cookie_value(
209        req.headers()
210            .get(axum::http::header::COOKIE)
211            .and_then(|v| v.to_str().ok()),
212    );
213    if let Some(code) = code {
214        if let Ok(hv) = axum::http::HeaderValue::from_str(&code) {
215            req.headers_mut()
216                .insert(axum::http::HeaderName::from_static("x-rcms-locale"), hv);
217        }
218    }
219    req
220}
221
222/// Builder for the public CMS router. Use when you need to combine
223/// mount-prefix, response caching, and/or path-based locale resolution
224/// — the free [`router`] / [`router_at`] / `*_cached` functions are
225/// shortcuts for common combinations and don't expose every knob.
226///
227/// ```no_run
228/// use std::sync::Arc;
229/// use std::time::Duration;
230/// use rustango_cms::{LocaleMode, PublicRouter};
231/// # let tera = Arc::new(tera::Tera::default());
232/// # let cache: rustango::cache::BoxedCache = Arc::new(rustango::cache::NullCache);
233/// let router = PublicRouter::new(tera)
234///     .at("/p")
235///     .cached(cache, Duration::from_secs(60))
236///     .locale_mode(LocaleMode::PathOrQuery)
237///     .build();
238/// ```
239pub struct PublicRouter {
240    tera: Arc<Tera>,
241    prefix: String,
242    cache: Option<(BoxedCache, Duration)>,
243    locale_mode: LocaleMode,
244    mailer: Option<(Arc<dyn rustango::email::Mailer>, String)>,
245    /// Pairs of `(URL prefix, filesystem root)` to mount as
246    /// static-file handlers. Stacked: every entry becomes a route
247    /// taking a wildcard path.
248    static_dirs: Vec<(String, std::path::PathBuf)>,
249    /// Single-file entries baked from `include_bytes!`. Each
250    /// triple is `(URL path, bytes, content-type)`.
251    static_files: Vec<(String, &'static [u8], &'static str)>,
252    /// Directory holding one subdirectory of template overrides per
253    /// tenant slug. `None` renders every tenant from the global set.
254    tenant_templates: Option<Arc<crate::tenant_templates::TenantTemplates>>,
255}
256
257impl PublicRouter {
258    /// Start a builder bound to the given Tera instance, mounted at
259    /// the root with no cache and query-mode locale resolution.
260    #[must_use]
261    pub fn new(tera: Arc<Tera>) -> Self {
262        Self {
263            tera,
264            prefix: String::new(),
265            cache: None,
266            locale_mode: LocaleMode::default(),
267            mailer: None,
268            static_dirs: Vec::new(),
269            static_files: Vec::new(),
270            tenant_templates: None,
271        }
272    }
273
274    /// Mount a filesystem directory as a static-file server at
275    /// `url_prefix`. Files under `fs_root` become reachable at
276    /// `{url_prefix}/{relative path}`. `fs_root` is anchored to the
277    /// process's current working directory (matches what a host's
278    /// `Path::new("./static")` would resolve to).
279    ///
280    /// Stacks: call multiple times to expose multiple dirs (e.g.
281    /// `/static/` for app assets + `/admin-static/` for shared
282    /// chrome).
283    ///
284    /// # Path-traversal safety
285    /// The handler rejects any request whose normalized path
286    /// escapes `fs_root` — `../` segments, absolute paths, and
287    /// embedded `..` after URL-decode all 404. Files outside the
288    /// root are never served.
289    #[must_use]
290    pub fn static_dir(
291        mut self,
292        url_prefix: impl Into<String>,
293        fs_root: impl Into<std::path::PathBuf>,
294    ) -> Self {
295        self.static_dirs.push((url_prefix.into(), fs_root.into()));
296        self
297    }
298
299    /// Serve a single static file from baked bytes. Pair with
300    /// `include_bytes!("…")` to embed asset bytes directly in the
301    /// binary — useful for `favicon.ico`, a small logo, or a brand
302    /// stylesheet that ships with the host.
303    #[must_use]
304    pub fn static_file(
305        mut self,
306        url_path: impl Into<String>,
307        bytes: &'static [u8],
308        content_type: &'static str,
309    ) -> Self {
310        self.static_files
311            .push((url_path.into(), bytes, content_type));
312        self
313    }
314
315    /// Wire a mailer for form-submission notifications.
316    /// Each \`cms_form_settings.notify_emails\` recipient gets a copy
317    /// of every submission to that page. `from_addr` is the `From:`
318    /// stamped on every notification.
319    #[must_use]
320    pub fn with_form_mailer(
321        mut self,
322        mailer: Arc<dyn rustango::email::Mailer>,
323        from_addr: impl Into<String>,
324    ) -> Self {
325        self.mailer = Some((mailer, from_addr.into()));
326        self
327    }
328
329    /// Mount the CMS under `prefix` instead of the root. Same shape
330    /// as [`router_at`].
331    #[must_use]
332    pub fn at(mut self, prefix: impl Into<String>) -> Self {
333        self.prefix = prefix.into();
334        self
335    }
336
337    /// Layer [`rustango::cache_page::CachePageLayer`] onto the built
338    /// router. `cache` is the storage backend (any
339    /// [`rustango::cache::BoxedCache`] — `InMemoryCache`,
340    /// `RedisCache`, …); `ttl` is the per-entry expiration. Cache
341    /// invalidation is TTL-based — admin edits don't surgically drop
342    /// affected keys; editors see stale content for up to `ttl`
343    /// seconds after a save.
344    #[must_use]
345    pub fn cached(mut self, cache: BoxedCache, ttl: Duration) -> Self {
346        self.cache = Some((cache, ttl));
347        self
348    }
349
350    /// Pick how the router recognizes the request's locale code.
351    /// See [`LocaleMode`] for the trade-offs.
352    #[must_use]
353    pub fn locale_mode(mut self, mode: LocaleMode) -> Self {
354        self.locale_mode = mode;
355        self
356    }
357
358    /// Let each tenant override templates from its own directory.
359    ///
360    /// `root` holds one subdirectory per tenant slug; a name found there
361    /// wins over the global set and anything absent falls through, so a
362    /// tenant only stores what differs. Keep `root` **outside** the glob
363    /// this router's Tera was built from, or every tenant's files land in
364    /// every instance.
365    ///
366    /// Templates become deploy artifacts rather than code: dropping a
367    /// file changes a site with no rebuild, and — depending on
368    /// [`Reload`](crate::tenant_templates::Reload) — no restart either.
369    ///
370    /// ```no_run
371    /// # use std::sync::Arc; use tera::Tera;
372    /// # use rustango_cms::{PublicRouter, tenant_templates::{TenantTemplates, Reload}};
373    /// # let tera = Arc::new(Tera::default());
374    /// let overrides = TenantTemplates::new(Arc::clone(&tera), "./templates_tenants")
375    ///     .with_reload(Reload::Every(std::time::Duration::from_secs(30)));
376    /// let router = PublicRouter::new(tera).tenant_templates(overrides).build();
377    /// ```
378    #[must_use]
379    pub fn tenant_templates(mut self, tt: crate::tenant_templates::TenantTemplates) -> Self {
380        self.tenant_templates = Some(Arc::new(tt));
381        self
382    }
383
384    /// Like [`tenant_templates`](Self::tenant_templates) but takes an
385    /// already-shared instance, so the same one can also be handed to
386    /// [`crate::tenant_templates::install`] for the admin editor —
387    /// otherwise the editor would be writing files a *different* cache
388    /// is serving from.
389    #[must_use]
390    pub fn tenant_templates_shared(
391        mut self,
392        tt: Arc<crate::tenant_templates::TenantTemplates>,
393    ) -> Self {
394        self.tenant_templates = Some(tt);
395        self
396    }
397
398    /// Finalize the builder into an axum [`Router`].
399    #[must_use]
400    pub fn build(self) -> Router {
401        let mut state =
402            PublicState::new(self.tera, self.prefix.clone()).with_locale_mode(self.locale_mode);
403        state.tenant_templates = self.tenant_templates;
404        if let Some((mailer, from)) = self.mailer {
405            state = state.with_mailer(mailer, from);
406        }
407        // #316 — share the page-cache backend with the render path so
408        // the menu-tree query is cached too. Cloned before the layer
409        // below consumes `self.cache` (BoxedCache is an Arc; cheap).
410        if let Some((cache, ttl)) = &self.cache {
411            state = state.with_fragment_cache(cache.clone(), *ttl);
412        }
413        let cms_router = if self.prefix.is_empty() {
414            fallback_router(state)
415        } else {
416            explicit_router(&self.prefix, state)
417        };
418        let cms_router = if let Some((cache, ttl)) = self.cache {
419            apply_cache_layer(cms_router, cache, ttl)
420        } else {
421            cms_router
422        };
423
424        // #254 — stack static routes BEFORE the CMS fallback so a
425        // hit on `/static/css/styles.css` doesn't fall through to
426        // the slug resolver. Each `static_dir` becomes a wildcard
427        // route `{prefix}/{*path}`; each `static_file` is an exact
428        // GET route.
429        let mut router = Router::new();
430        for (url_prefix, fs_root) in self.static_dirs {
431            let trimmed = url_prefix.trim_end_matches('/').to_owned();
432            let pattern = format!("{trimmed}/{{*path}}");
433            let root = Arc::new(fs_root);
434            router = router.route(
435                &pattern,
436                axum::routing::get({
437                    let root = root.clone();
438                    move |path: axum::extract::Path<String>| {
439                        let root = root.clone();
440                        // canonicalize + read are blocking file I/O; a
441                        // large asset must not hold a runtime worker (#727).
442                        async move {
443                            rustango::__private_runtime::tokio::task::spawn_blocking(move || {
444                                serve_static_path(&root, &path.0)
445                            })
446                            .await
447                            .unwrap_or_else(|_| not_found())
448                        }
449                    }
450                }),
451            );
452        }
453        for (url_path, bytes, ct) in self.static_files {
454            router = router.route(
455                &url_path,
456                axum::routing::get(move || async move { serve_static_bytes(bytes, ct) }),
457            );
458        }
459        router.merge(cms_router)
460    }
461}
462
463/// Serve a single file relative to `fs_root`. Rejects `..` traversal
464/// + absolute paths + symlinks that escape the root. Returns 404 on
465/// any miss (file absent, traversal attempt, IO error).
466fn serve_static_path(fs_root: &std::path::Path, requested: &str) -> Response {
467    // Reject anything that looks like a traversal attempt up front —
468    // URL-decoded `..` segments, absolute paths, embedded NULs. The
469    // canonicalize step below is the real defense, but bailing early
470    // keeps the error consistent across platforms.
471    if requested.is_empty() || requested.contains('\0') {
472        return not_found();
473    }
474    for seg in requested.split('/') {
475        if seg == ".." || seg.starts_with('/') {
476            return not_found();
477        }
478    }
479    let candidate = fs_root.join(requested);
480    // Canonicalize both root + candidate, then confirm the candidate
481    // is INSIDE the root. Symlink-escape lands on the wrong side of
482    // the prefix check and 404s.
483    let canon_root = match fs_root.canonicalize() {
484        Ok(p) => p,
485        Err(_) => return not_found(),
486    };
487    let canon = match candidate.canonicalize() {
488        Ok(p) => p,
489        Err(_) => return not_found(),
490    };
491    if !canon.starts_with(&canon_root) {
492        return not_found();
493    }
494    let bytes = match std::fs::read(&canon) {
495        Ok(b) => b,
496        Err(_) => return not_found(),
497    };
498    let ct = mime_guess::from_path(&canon)
499        .first_or_octet_stream()
500        .essence_str()
501        .to_owned();
502    static_response(bytes, &ct)
503}
504
505fn serve_static_bytes(bytes: &'static [u8], content_type: &'static str) -> Response {
506    static_response(bytes.to_vec(), content_type)
507}
508
509fn static_response(bytes: Vec<u8>, content_type: &str) -> Response {
510    use axum::http::header;
511    // 1 hour cache by default — shorter than image renditions
512    // (immutable, content-addressed) since static assets at a
513    // stable URL change with deploys, not with content hashes.
514    (
515        axum::http::StatusCode::OK,
516        [
517            (
518                header::CONTENT_TYPE,
519                axum::http::HeaderValue::from_str(content_type).unwrap_or_else(|_| {
520                    axum::http::HeaderValue::from_static("application/octet-stream")
521                }),
522            ),
523            (
524                header::CACHE_CONTROL,
525                axum::http::HeaderValue::from_static("public, max-age=3600"),
526            ),
527        ],
528        bytes,
529    )
530        .into_response()
531}
532
533fn not_found() -> Response {
534    (axum::http::StatusCode::NOT_FOUND, "Not Found").into_response()
535}
536
537/// Build the CMS router using axum's `.fallback()` for page
538/// rendering. Use only when the CMS is the sole surface — see the
539/// module docs for the tenancy gotcha.
540pub fn router(tera: Arc<Tera>) -> Router {
541    fallback_router(PublicState::new(tera, String::new()))
542}
543
544/// Like [`router`], wrapped in [`rustango::cache_page::CachePageLayer`].
545/// GET responses are cached for `ttl` keyed on
546/// `(method, path, Host, vary-on)`; admin edits propagate after the
547/// TTL elapses (no manual invalidation).
548pub fn router_cached(tera: Arc<Tera>, cache: BoxedCache, ttl: Duration) -> Router {
549    apply_cache_layer(
550        fallback_router(PublicState::new(tera, String::new())),
551        cache,
552        ttl,
553    )
554}
555
556/// Build the CMS router mounted under an explicit URL prefix.
557///
558/// Registers `{prefix}` + `{prefix}/{*path}` as **explicit** routes
559/// (not a fallback), which survives a downstream
560/// `Router::fallback_service(...)` such as the one rustango's
561/// tenancy admin attaches.
562///
563/// Pass `"/p"`, `"/site"`, `"/pages"`, etc. Passing `""` (empty
564/// prefix) is allowed and mounts the wildcard at the root.
565///
566/// The prefix is exposed to templates via the `url_prefix` Tera
567/// variable so breadcrumb / sibling links can be built without
568/// hard-coding the host's URL layout.
569pub fn router_at(prefix: &str, tera: Arc<Tera>) -> Router {
570    explicit_router(prefix, PublicState::new(tera, prefix.to_owned()))
571}
572
573/// Like [`router_at`], wrapped in [`rustango::cache_page::CachePageLayer`].
574/// See [`router_cached`] for the trade-off (TTL-based invalidation).
575pub fn router_at_cached(prefix: &str, tera: Arc<Tera>, cache: BoxedCache, ttl: Duration) -> Router {
576    apply_cache_layer(
577        explicit_router(prefix, PublicState::new(tera, prefix.to_owned())),
578        cache,
579        ttl,
580    )
581}
582
583fn fallback_router(state: PublicState) -> Router {
584    crate::perf::instrument(fallback_router_inner(state))
585}
586
587fn fallback_router_inner(state: PublicState) -> Router {
588    Router::new()
589        .route("/sitemap.xml", get(crate::sitemap::handle_sitemap))
590        // Advertises the sitemap above and keeps crawlers out of
591        // the admin. Only honoured at the origin root by crawlers,
592        // but mounted alongside the sitemap in both routers so the
593        // two never disagree about where they exist.
594        .route("/robots.txt", get(crate::robots::handle_robots))
595        // #187 — sitemap shards for tenants > 50k URLs.
596        .route("/sitemap/{n}", get(crate::sitemap::handle_sitemap_shard))
597        .route("/feed/{kind}/rss.xml", get(crate::feed::handle_feed_rss))
598        .route("/feed/{kind}/atom.xml", get(crate::feed::handle_feed_atom))
599        // #76 — password-prompt page for view-restricted pages.
600        .route(
601            "/__cms-view-password",
602            get(handle_view_password_form).post(handle_view_password_submit),
603        )
604        // #544 FB-11 — public form-submission endpoint.
605        .route(
606            "/forms/submit/{form_id}",
607            axum::routing::post(crate::forms::submit::handle_form_submit)
608                .layer(axum::extract::DefaultBodyLimit::max(crate::forms::submit::MAX_SUBMISSION_BYTES)),
609        )
610        // #543 FB-10 — public form runtime (paging, validation, conditional logic).
611        .route("/forms/runtime.js", get(serve_form_runtime_js))
612        // standard form styles (auto-linked; replaceable per-form).
613        .route("/forms/forms.css", get(serve_form_css))
614        // default analytics — CDN-/cache-proof collection.
615        .route(
616            crate::analytics::COLLECT_PATH,
617            axum::routing::post(crate::analytics::collect::handle_collect),
618        )
619        .route(
620            crate::analytics::WS_PATH,
621            get(crate::analytics::ws::handle_ws),
622        )
623        .route(
624            crate::analytics::BEACON_JS_PATH,
625            get(crate::analytics::serve_beacon_js),
626        )
627        .fallback(get(handle_page_request))
628        // #689 — seed a tenant provisioned after boot on its first request.
629        .layer(axum::middleware::from_fn(crate::seed::lazy_seed_layer))
630        .with_state(state)
631}
632
633/// Serve the cacheable public form runtime.
634async fn serve_form_runtime_js() -> impl IntoResponse {
635    // Unversioned public URL: the 1-hour static policy, not immutable (#696).
636    serve_static_bytes(include_str!("forms/runtime.js").as_bytes(), "text/javascript; charset=utf-8")
637}
638
639/// Serve the standard, replaceable public form stylesheet.
640async fn serve_form_css() -> impl IntoResponse {
641    serve_static_bytes(include_str!("forms/forms.css").as_bytes(), "text/css; charset=utf-8")
642}
643
644fn explicit_router(prefix: &str, state: PublicState) -> Router {
645    let inner = Router::new()
646        .route("/sitemap.xml", get(crate::sitemap::handle_sitemap))
647        // Advertises the sitemap above and keeps crawlers out of
648        // the admin. Only honoured at the origin root by crawlers,
649        // but mounted alongside the sitemap in both routers so the
650        // two never disagree about where they exist.
651        .route("/robots.txt", get(crate::robots::handle_robots))
652        // #187 — sitemap shards for tenants > 50k URLs.
653        .route("/sitemap/{n}", get(crate::sitemap::handle_sitemap_shard))
654        .route("/feed/{kind}/rss.xml", get(crate::feed::handle_feed_rss))
655        .route("/feed/{kind}/atom.xml", get(crate::feed::handle_feed_atom))
656        .route(
657            "/__cms-view-password",
658            get(handle_view_password_form).post(handle_view_password_submit),
659        )
660        // #544 FB-11 — public form-submission endpoint.
661        .route(
662            "/forms/submit/{form_id}",
663            axum::routing::post(crate::forms::submit::handle_form_submit)
664                .layer(axum::extract::DefaultBodyLimit::max(crate::forms::submit::MAX_SUBMISSION_BYTES)),
665        )
666        // #543 FB-10 — public form runtime.
667        .route("/forms/runtime.js", get(serve_form_runtime_js))
668        .route("/forms/forms.css", get(serve_form_css))
669        // default analytics — CDN-/cache-proof collection.
670        .route(
671            crate::analytics::COLLECT_PATH,
672            axum::routing::post(crate::analytics::collect::handle_collect),
673        )
674        .route(
675            crate::analytics::WS_PATH,
676            get(crate::analytics::ws::handle_ws),
677        )
678        .route(
679            crate::analytics::BEACON_JS_PATH,
680            get(crate::analytics::serve_beacon_js),
681        )
682        .route("/", get(handle_page_request))
683        .route("/{*path}", get(handle_page_request))
684        .layer(axum::middleware::from_fn(crate::seed::lazy_seed_layer))
685        .with_state(state);
686    if prefix.is_empty() {
687        return inner;
688    }
689    let trailing = format!("{prefix}/");
690    let bare = prefix.to_owned();
691    Router::new().nest(prefix, inner).route(
692        &trailing,
693        get(move || {
694            let bare = bare.clone();
695            async move { Redirect::permanent(&bare) }
696        }),
697    )
698}
699
700/// The request's bare hostname, lowercased and without the port.
701pub(crate) fn host_header(headers: &axum::http::HeaderMap) -> &str {
702    headers
703        .get(axum::http::header::HOST)
704        .and_then(|v| v.to_str().ok())
705        .map_or("", |h| h.split(':').next().unwrap_or(""))
706}
707
708/// The context the public router's hooks run with.
709fn hook_ctx<'a>(tenant: &'a Tenant, viewer: Option<&rustango::tenancy::auth::User>) -> crate::hooks::HookCtx<'a> {
710    crate::hooks::HookCtx::new(tenant.pool(), &tenant.org.slug, viewer.and_then(|u| u.id.get().copied()))
711}
712
713async fn handle_page_request(
714    tenant: Tenant,
715    State(state): State<PublicState>,
716    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
717    rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
718    headers: axum::http::HeaderMap,
719    uri: Uri,
720) -> Response {
721    // An admin (not a member session) gets the admin bar, and with "Show
722    // templates on the site" turned on, the template inspector.
723    let admin = if member.is_none() { session_user.as_ref() } else { None };
724    let inspect = admin.is_some_and(crate::template_inspector::wanted);
725    let bar = admin.map(|_| crate::admin_bar::Labels {
726        edit: crate::admin::tr(&headers, "Edit this page"),
727        admin: crate::admin::tr(&headers, "Admin"),
728        hide: crate::admin::tr(&headers, "Show or hide the admin bar"),
729        templates: crate::admin::tr(&headers, "Templates"),
730    });
731    crate::admin_bar::scope(
732        bar,
733        crate::template_inspector::scope(inspect, serve_page(tenant, state, session_user, member, headers, uri)),
734    )
735    .await
736}
737
738async fn serve_page(
739    tenant: Tenant,
740    state: PublicState,
741    session_user: Option<rustango::tenancy::auth::User>,
742    member: Option<rustango::tenancy::auth::User>,
743    headers: axum::http::HeaderMap,
744    uri: Uri,
745) -> Response {
746    // #members — the page-gating viewer is a public member (member
747    // cookie) OR an admin (tenant-session cookie); a member session
748    // takes precedence on public pages. Both are `Option<User>` from
749    // the same `rustango_users` table, so restriction checks (login /
750    // groups / permission) work identically for either.
751    let viewer = member.as_ref().or(session_user.as_ref());
752    let raw_path = uri.path();
753    // #553 — override-live redirect rules beat page resolution. The rule
754    // set is fragment-cached (and usually empty), so page views on
755    // rule-free tenants stay one-query — and none of the locale/page work
756    // below runs on a hit.
757    let _perf_t = crate::perf::start();
758    if let Some(resp) = crate::redirect::serve_override(
759        &tenant,
760        state.fragment_cache.as_ref().map(|(c, ttl)| (c, *ttl)),
761        raw_path,
762        uri.query(),
763    )
764    .await
765    {
766        crate::perf::mark("redirect_rules", _perf_t);
767        return resp;
768    }
769    crate::perf::mark("redirect_rules", _perf_t);
770    // Locale resolved from path / query per the
771    // configured mode. The resolver returns a stripped path so the
772    // canonical url_path used for the page lookup never carries the
773    // locale prefix.
774    let accept_language = headers
775        .get(axum::http::header::ACCEPT_LANGUAGE)
776        .and_then(|v| v.to_str().ok());
777    // Media-type preference for page types that serve a JSON view.
778    // Parsed once here and passed down; `render_inner` is the only thing
779    // that reads it, and only for those types.
780    let accept = crate::page_view::parse_accept(
781        headers
782            .get(axum::http::header::ACCEPT)
783            .and_then(|v| v.to_str().ok()),
784    );
785    // #i18n — persistence cookie keeps the chosen locale across links
786    // that don't carry it (bare nav paths, in-content links).
787    let cookie_code = crate::locale_mode::locale_cookie_value(
788        headers
789            .get(axum::http::header::COOKIE)
790            .and_then(|v| v.to_str().ok()),
791    );
792    let _perf_t = crate::perf::start();
793    let request_locale = resolve_request_locale(
794        tenant.pool(),
795        state.locale_mode,
796        raw_path,
797        uri.query(),
798        cookie_code.as_deref(),
799        accept_language,
800    )
801    .await;
802    crate::perf::mark("locale", _perf_t);
803    let locale_code = request_locale.code.clone();
804    let locale_explicit = request_locale.explicit;
805    let lookup_path = request_locale.stripped_path;
806
807    // Multi-site: which root does this hostname serve? With no `cms_site`
808    // rows this resolves to the conventional root and contributes an empty
809    // prefix, so the lookup below is byte-identical to what it always was.
810    let _perf_t = crate::perf::start();
811    let site_prefix = crate::site::prefix_for_host(tenant.pool(), host_header(&headers))
812        .await
813        .unwrap_or_default();
814    crate::perf::mark("site", _perf_t);
815    // Stored paths are tenant-absolute; the visitor's path is relative to
816    // the site root.
817    let lookup_path = crate::site::to_lookup_path(&site_prefix, &lookup_path);
818
819    let _perf_t = crate::perf::start();
820    let _resolved = resolve_path(&tenant, &lookup_path).await;
821    crate::perf::mark("resolve_path", _perf_t);
822    match _resolved {
823        Ok(Some(page)) => {
824            // #76 — per-page view restrictions. Walks ancestors for the
825            // nearest restriction; if found, enforces login / groups /
826            // password before delegating to the renderer. The
827            // unrestricted path stays a single resolve + render.
828            let _perf_t = crate::perf::start();
829            let _blocked =
830                crate::view_restriction_guard::enforce(&tenant, &page, viewer, &headers, raw_path)
831                    .await;
832            crate::perf::mark("view_restriction", _perf_t);
833            if let Some(blocked) = _blocked {
834                return styled_denial(&tenant, &state, blocked, locale_code.as_deref()).await;
835            }
836            // #107 — plugin `before_serve_page` hook. First handler
837            // to return `Some(Response)` short-circuits the renderer.
838            if let Some(resp) = crate::hooks::fire_before_serve_page(hook_ctx(&tenant, viewer), &page, &headers).await {
839                return resp;
840            }
841            // #401 — stash the per-page language-switcher data for the
842            // `language_switcher()` Tera fn. render_inner re-installs it
843            // in its await-free block (see stash_pending) so the
844            // thread-local lands on the thread that runs `tera.render`;
845            // this guard clears the stash after render regardless.
846            let _perf_t = crate::perf::start();
847            // Per-tenant overrides layered on the global set. Resolved
848            // here rather than inside render so the render path keeps
849            // taking a plain `&Tera` and stays testable without a cache.
850            let tera = state.tera_for(&tenant.org.slug).await;
851            // After `tera_for`: the stash is per-thread, and an `.await`
852            // between it and the render can move the task to another
853            // thread, stranding the entries for some other page's render.
854            let _switcher =
855                install_locale_switcher(&tenant, &state, &page, locale_code.as_deref()).await;
856            // `site_origin` for absolute canonical / og:image URLs. Stashed
857            // here, with no `.await` before the render reads it.
858            let _origin = crate::meta_tags::stash_site_origin(crate::sitemap::base_url(&headers));
859            let resp = render_negotiated(
860                &tenant,
861                &tera,
862                &page,
863                &state.url_prefix,
864                &site_prefix,
865                locale_code.as_deref(),
866                viewer,
867                accept,
868                state.fragment_cache.as_ref().map(|(c, ttl)| (c, *ttl)),
869            )
870            .await;
871            crate::perf::mark("render", _perf_t);
872            // Substitute the CMS-editable 500 page for render failures
873            // (the plain-text diagnostics are already tracing::error!'d
874            // inside render; visitors get the styled page instead).
875            let resp = if resp.status().is_server_error() {
876                crate::error_pages::respond(&tenant, &state, resp.status(), locale_code.as_deref())
877                    .await
878            } else {
879                resp
880            };
881            persist_locale(resp, locale_explicit, locale_code.as_deref())
882        }
883        Ok(None) => {
884            // #198 — routable_page: before falling through to
885            // redirects / 404, ask each ancestor's handler if it
886            // owns a route pattern that matches the suffix. First
887            // match wins; the renderer threads `route_name` +
888            // `route_captures` into the Tera ctx.
889            match resolve_routable(&tenant, &lookup_path).await {
890                Ok(Some((page, route_match))) => {
891                    if let Some(blocked) = crate::view_restriction_guard::enforce(
892                        &tenant, &page, viewer, &headers, raw_path,
893                    )
894                    .await
895                    {
896                        return styled_denial(&tenant, &state, blocked, locale_code.as_deref()).await;
897                    }
898                    if let Some(resp) = crate::hooks::fire_before_serve_page(hook_ctx(&tenant, viewer), &page, &headers).await {
899                        return resp;
900                    }
901                    let tera = state.tera_for(&tenant.org.slug).await;
902                    let _switcher =
903                        install_locale_switcher(&tenant, &state, &page, locale_code.as_deref())
904                            .await;
905                    let _origin =
906                        crate::meta_tags::stash_site_origin(crate::sitemap::base_url(&headers));
907                    let resp = render_with_route(
908                        &tenant,
909                        &tera,
910                        &page,
911                        &state.url_prefix,
912                        &site_prefix,
913                        locale_code.as_deref(),
914                        viewer,
915                        &route_match,
916                        accept,
917                        state.fragment_cache.as_ref().map(|(c, ttl)| (c, *ttl)),
918                    )
919                    .await;
920                    // A route whose record is missing answers a bare 404
921                    // (`RouteOutcome::NotFound`): serve the site's 404 page.
922                    let resp = if resp.status().is_server_error() || resp.status() == StatusCode::NOT_FOUND {
923                        crate::error_pages::respond(
924                            &tenant,
925                            &state,
926                            resp.status(),
927                            locale_code.as_deref(),
928                        )
929                        .await
930                    } else {
931                        resp
932                    };
933                    return persist_locale(resp, locale_explicit, locale_code.as_deref());
934                }
935                Ok(None) => {}
936                Err(e) => {
937                    tracing::error!(path = %raw_path, error = %e, "resolve_routable failed");
938                }
939            }
940            fallthrough_to_redirect(
941                &tenant,
942                &state,
943                raw_path,
944                uri.query(),
945                locale_code.as_deref(),
946            )
947            .await
948        }
949        Err(e) => {
950            tracing::error!(path = %raw_path, error = %e, "resolve_path failed");
951            crate::error_pages::respond(
952                &tenant,
953                &state,
954                StatusCode::INTERNAL_SERVER_ERROR,
955                locale_code.as_deref(),
956            )
957            .await
958        }
959    }
960}
961
962/// Attach locale-persistence headers to a page response. `Vary: Cookie`
963/// always (the rendered language depends on the `rcms_locale` cookie, so
964/// a shared/CDN cache must key on it); a `Set-Cookie` writing the chosen
965/// locale only when it was an EXPLICIT pick (`?lang=` / `/<code>/`), so a
966/// plain nav click — which resolves the locale *from* the cookie — never
967/// rewrites it. An explicit switch to the default locale still writes the
968/// cookie, overriding a stale non-default one.
969fn persist_locale(mut resp: Response, explicit: bool, code: Option<&str>) -> Response {
970    use axum::http::header::{HeaderValue, SET_COOKIE, VARY};
971    resp.headers_mut()
972        .append(VARY, HeaderValue::from_static("Cookie"));
973    if explicit {
974        if let Some(code) = code {
975            let cookie = format!(
976                "{}={code}; Path=/; SameSite=Lax; HttpOnly; Max-Age=31536000",
977                crate::locale_mode::LOCALE_COOKIE
978            );
979            if let Ok(hv) = HeaderValue::from_str(&cookie) {
980                resp.headers_mut().append(SET_COOKIE, hv);
981            }
982        }
983    }
984    resp
985}
986
987/// A signed-in visitor who may not see a restricted page gets the site's
988/// 403 page (an editor-made error page, else the styled fallback) instead
989/// of a bare text body; login and password redirects pass through.
990async fn styled_denial(
991    tenant: &Tenant,
992    state: &PublicState,
993    blocked: Response,
994    locale_code: Option<&str>,
995) -> Response {
996    if blocked.status() == StatusCode::FORBIDDEN {
997        crate::error_pages::respond(tenant, state, StatusCode::FORBIDDEN, locale_code).await
998    } else {
999        blocked
1000    }
1001}
1002
1003/// Fetch the active locales and stash the per-page language
1004/// switcher (the URL to *this* page in each locale, built per the
1005/// configured `LocaleMode`) for the `language_switcher()` Tera fn. The
1006/// stash is consumed and re-installed on the render thread inside
1007/// `render_inner`'s await-free block (so the thread-local survives
1008/// tokio's thread-hops across render's awaits); the returned guard
1009/// clears any un-consumed stash when it drops, so the caller must hold
1010/// it across the `render*` call. The final `stash_pending` runs after
1011/// this fn's only `.await`, and the caller polls the render future with
1012/// no intervening `.await`, so render's synchronous entry sees it.
1013pub(crate) async fn install_locale_switcher(
1014    tenant: &Tenant,
1015    state: &PublicState,
1016    page: &crate::page::Page,
1017    current_code: Option<&str>,
1018) -> crate::language_switcher::PendingGuard {
1019    use rustango::core::Column as _;
1020    use rustango::sql::FetcherPool as _;
1021    let locales: Vec<crate::locale::Locale> = crate::locale::Locale::objects()
1022        .where_(crate::locale::Locale::active.eq(true))
1023        .order_by(&[("sort_order", false)])
1024        .fetch(tenant.pool())
1025        .await
1026        .unwrap_or_default();
1027    let entries = crate::language_switcher::build(
1028        &locales,
1029        &state.url_prefix,
1030        &page.url_path,
1031        state.locale_mode,
1032        current_code,
1033    );
1034    crate::language_switcher::stash_pending(entries)
1035}
1036
1037/// When the slug resolver returns `None` (no published page at this
1038/// URL), consult the tenant's `cms_redirect` table before giving
1039/// up. Redirects hook into the 404 path: live pages always win, redirects fill in for
1040/// retired URLs.
1041///
1042/// On a redirect hit, the framework's
1043/// [`rustango::redirects::build_redirect_response`] emits the
1044/// 301/302 with `Location` carrying any incoming query string. Hit
1045/// count is bumped best-effort in the background; failure to
1046/// increment is logged and swallowed.
1047async fn fallthrough_to_redirect(
1048    tenant: &Tenant,
1049    state: &PublicState,
1050    raw_path: &str,
1051    query: Option<&str>,
1052    locale_code: Option<&str>,
1053) -> Response {
1054    match crate::redirect::find_for_path(tenant.pool(), raw_path).await {
1055        Ok(Some(row)) => {
1056            // #553 — a `to_page_id` destination resolves to the page's
1057            // CURRENT url_path (follows moves); `to_path` is the fallback.
1058            let to = crate::redirect::resolve_destination(tenant.pool(), &row).await;
1059            let rule = rustango::redirects::RedirectRule {
1060                to,
1061                permanent: row.is_permanent,
1062            };
1063            let resp = rustango::redirects::build_redirect_response(&rule, query);
1064            // #555 — record the hit in-memory (no per-request DB write);
1065            // the throttled flush persists the delta + last_hit_at.
1066            crate::redirect::record_hit(
1067                tenant.pool(),
1068                &tenant.org.slug,
1069                row.id.get().copied().unwrap_or_default(),
1070            );
1071            resp
1072        }
1073        // No exact rule, no live page — try #554 wildcard rules before
1074        // giving up. Non-override wildcards fill in for URLs with no
1075        // live page, exactly like exact non-override rules.
1076        Ok(None) => {
1077            let cache = state.fragment_cache.as_ref().map(|(c, ttl)| (c, *ttl));
1078            if let Some(resp) =
1079                crate::redirect::serve_wildcard(tenant, cache, raw_path, query).await
1080            {
1081                return resp;
1082            }
1083            if raw_path.trim_matches('/').is_empty() && crate::error_pages::site_is_empty(tenant.pool()).await {
1084                return crate::error_pages::empty_site_response();
1085            }
1086            crate::error_pages::respond(tenant, state, StatusCode::NOT_FOUND, locale_code).await
1087        }
1088        Err(e) => {
1089            tracing::warn!(path = %raw_path, error = %e, "redirect lookup failed");
1090            crate::error_pages::respond(tenant, state, StatusCode::NOT_FOUND, locale_code).await
1091        }
1092    }
1093}
1094
1095// =====================================================================
1096// #76 — view-restriction password prompt.
1097// =====================================================================
1098
1099#[derive(Debug, serde::Deserialize)]
1100struct PasswordPromptQuery {
1101    page: i64,
1102    #[serde(default)]
1103    next: Option<String>,
1104    #[serde(default)]
1105    error: Option<String>,
1106}
1107
1108#[derive(Debug, serde::Deserialize)]
1109struct PasswordSubmitForm {
1110    page: i64,
1111    password: String,
1112    #[serde(default)]
1113    next: Option<String>,
1114}
1115
1116async fn handle_view_password_form(
1117    tenant: Tenant,
1118    State(state): State<PublicState>,
1119    headers: axum::http::HeaderMap,
1120    axum::extract::Query(q): axum::extract::Query<PasswordPromptQuery>,
1121) -> Response {
1122    use rustango::core::Column as _;
1123    use rustango::sql::FetcherPool as _;
1124    let _ = &tenant;
1125    let page_rows: Vec<crate::page::Page> = crate::page::Page::objects()
1126        .where_(crate::page::Page::id.eq(q.page))
1127        .fetch(tenant.pool())
1128        .await
1129        .unwrap_or_default();
1130    let title = page_rows
1131        .first()
1132        .map(|p| p.title.clone())
1133        .unwrap_or_else(|| "Protected page".to_owned());
1134    let next = q.next.clone().unwrap_or_else(|| "/".to_owned());
1135    let error_msg = q.error.as_deref().unwrap_or("");
1136    let mut ctx = tera::Context::new();
1137    ctx.insert("page_id", &q.page);
1138    ctx.insert("page_title", &title);
1139    ctx.insert("next_path", &next);
1140    ctx.insert("error_message", &error_msg);
1141    // Seed the double-submit token on the GET so a host CSRF layer does not
1142    // reject the first POST (#677, same shape as the framework login).
1143    let (csrf_token, csrf_cookie) =
1144        rustango::forms::csrf::ensure_token(&headers, rustango::forms::csrf::CSRF_COOKIE);
1145    ctx.insert("csrf_token", &csrf_token);
1146    match state.tera.render("rcms/view_password.html", &ctx) {
1147        Ok(body) => {
1148            let mut resp = axum::response::Html(body).into_response();
1149            if let Some(v) = csrf_cookie.and_then(|c| axum::http::HeaderValue::from_str(&c).ok()) {
1150                resp.headers_mut().append(axum::http::header::SET_COOKIE, v);
1151            }
1152            resp
1153        }
1154        Err(e) => {
1155            tracing::error!(error = %e, "view-password template render failed");
1156            (StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response()
1157        }
1158    }
1159}
1160
1161async fn handle_view_password_submit(
1162    tenant: Tenant,
1163    axum::extract::Form(form): axum::extract::Form<PasswordSubmitForm>,
1164) -> Response {
1165    let Some(restriction) = crate::view_restriction::direct_for_page(tenant.pool(), form.page)
1166        .await
1167        .unwrap_or(None)
1168        .filter(|r| r.kind == crate::view_restriction::RestrictionKind::Password.as_str())
1169    else {
1170        return (
1171            StatusCode::BAD_REQUEST,
1172            "no password restriction on this page",
1173        )
1174            .into_response();
1175    };
1176    let _ = &tenant;
1177    let _ = &restriction.password_hash;
1178    // Verify the password against the stored argon2id hash.
1179    let ok =
1180        crate::passwords::verify(&form.password, &restriction.password_hash).await.unwrap_or(false);
1181    // A local path only — this form is reachable from any link (#728).
1182    let next = form
1183        .next
1184        .as_deref()
1185        .and_then(rustango::auth_decorators::safe_next)
1186        .unwrap_or_else(|| "/".to_owned());
1187    if !ok {
1188        let next_enc = crate::view_restriction_guard::url_encode_path(&next);
1189        return Redirect::to(&format!(
1190            "/__cms-view-password?page={}&next={next_enc}&error=Wrong+password",
1191            form.page
1192        ))
1193        .into_response();
1194    }
1195    // 7-day grant, expired on the server too; rotate the password to
1196    // revoke early.
1197    let cookie =
1198        crate::view_restriction_guard::grant_cookie(&tenant.org.slug, &restriction, form.page);
1199    let mut response = Redirect::to(&next).into_response();
1200    if let Ok(hv) = axum::http::HeaderValue::from_str(&cookie) {
1201        response
1202            .headers_mut()
1203            .append(axum::http::header::SET_COOKIE, hv);
1204    }
1205    response
1206}
1207
1208#[cfg(test)]
1209mod static_serve_tests {
1210    use super::*;
1211    use std::fs;
1212    use std::path::PathBuf;
1213
1214    /// Make a temporary directory for a single test. Files live
1215    /// under `target/tmp/<name>/` to avoid colliding across parallel
1216    /// runs while still being predictable to clean up.
1217    fn tempdir(name: &str) -> PathBuf {
1218        let mut p = std::env::temp_dir();
1219        p.push(format!("rustango_cms_static_{name}_{}", std::process::id()));
1220        let _ = fs::remove_dir_all(&p);
1221        fs::create_dir_all(&p).expect("create tempdir");
1222        p
1223    }
1224
1225    #[test]
1226    fn serves_existing_file_with_guessed_mime() {
1227        let dir = tempdir("hit");
1228        fs::write(dir.join("styles.css"), b"body{color:red}").unwrap();
1229        let resp = serve_static_path(&dir, "styles.css");
1230        assert_eq!(resp.status(), axum::http::StatusCode::OK);
1231        let ct = resp
1232            .headers()
1233            .get(axum::http::header::CONTENT_TYPE)
1234            .unwrap()
1235            .to_str()
1236            .unwrap();
1237        assert!(ct.starts_with("text/css"), "got `{ct}`");
1238        let cc = resp
1239            .headers()
1240            .get(axum::http::header::CACHE_CONTROL)
1241            .unwrap()
1242            .to_str()
1243            .unwrap();
1244        assert!(cc.contains("max-age=3600"));
1245    }
1246
1247    #[test]
1248    fn rejects_dotdot_traversal_in_segment() {
1249        let dir = tempdir("trav");
1250        fs::write(dir.join("ok.txt"), b"in-root").unwrap();
1251        // `..` segment — must 404 even if the file outside exists.
1252        let resp = serve_static_path(&dir, "../etc/passwd");
1253        assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1254    }
1255
1256    #[test]
1257    fn rejects_absolute_segment() {
1258        let dir = tempdir("abs");
1259        // Leading slash in a segment shouldn't escape — handler bails.
1260        let resp = serve_static_path(&dir, "/etc/passwd");
1261        assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1262    }
1263
1264    #[test]
1265    fn rejects_null_byte_in_path() {
1266        let dir = tempdir("null");
1267        let resp = serve_static_path(&dir, "ok\0.txt");
1268        assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1269    }
1270
1271    #[test]
1272    fn missing_file_is_404_not_500() {
1273        let dir = tempdir("miss");
1274        let resp = serve_static_path(&dir, "does-not-exist.css");
1275        assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1276    }
1277
1278    #[test]
1279    fn serves_static_bytes_with_supplied_content_type() {
1280        let resp = serve_static_bytes(b"<svg/>", "image/svg+xml");
1281        assert_eq!(resp.status(), axum::http::StatusCode::OK);
1282        assert_eq!(
1283            resp.headers()
1284                .get(axum::http::header::CONTENT_TYPE)
1285                .and_then(|v| v.to_str().ok()),
1286            Some("image/svg+xml"),
1287        );
1288    }
1289
1290    #[test]
1291    fn nested_subdir_is_served() {
1292        let dir = tempdir("nested");
1293        fs::create_dir_all(dir.join("css/sub")).unwrap();
1294        fs::write(dir.join("css/sub/x.css"), b"x{}").unwrap();
1295        let resp = serve_static_path(&dir, "css/sub/x.css");
1296        assert_eq!(resp.status(), axum::http::StatusCode::OK);
1297    }
1298
1299    #[test]
1300    fn empty_path_is_404() {
1301        let dir = tempdir("empty");
1302        let resp = serve_static_path(&dir, "");
1303        assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1304    }
1305}
1306
1307#[cfg(test)]
1308mod accept_cache_key_tests {
1309    use super::*;
1310    use axum::http::{HeaderValue, Request};
1311
1312    fn req_with_accept(accept: Option<&str>) -> axum::extract::Request {
1313        let mut b = Request::builder().uri("/some-page");
1314        if let Some(a) = accept {
1315            b = b.header(
1316                axum::http::header::ACCEPT,
1317                HeaderValue::from_str(a).unwrap(),
1318            );
1319        }
1320        b.body(axum::body::Body::empty()).unwrap()
1321    }
1322
1323    async fn stamped(accept: Option<&str>) -> Option<String> {
1324        let req = inject_accept_kind_header(req_with_accept(accept)).await;
1325        req.headers()
1326            .get("x-rcms-accept")
1327            .and_then(|v| v.to_str().ok())
1328            .map(str::to_owned)
1329    }
1330
1331    /// The cache keys on this header, so a JSON caller must be the only
1332    /// one that changes it. If a browser ever stamped it too, ordinary
1333    /// traffic would fragment the cache for no benefit.
1334    #[tokio::test]
1335    async fn only_an_explicit_json_preference_changes_the_cache_key() {
1336        assert_eq!(
1337            stamped(Some("application/json")).await.as_deref(),
1338            Some("json")
1339        );
1340        assert_eq!(
1341            stamped(Some("application/json, text/plain, */*"))
1342                .await
1343                .as_deref(),
1344            Some("json")
1345        );
1346
1347        // Everything else shares the header-absent key.
1348        let chrome = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,\
1349                      image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7";
1350        assert_eq!(stamped(Some(chrome)).await, None);
1351        assert_eq!(stamped(Some("*/*")).await, None);
1352        assert_eq!(stamped(None).await, None);
1353        // A page that prefers HTML but tolerates JSON is an HTML caller.
1354        assert_eq!(
1355            stamped(Some("application/json;q=0.1, text/html")).await,
1356            None
1357        );
1358        // An explicit refusal is not a request.
1359        assert_eq!(stamped(Some("application/json;q=0")).await, None);
1360    }
1361
1362    /// The poisoning scenario, stated as an assertion: a browser and a
1363    /// JSON client must not land on the same cache key for the same URL,
1364    /// or one gets the other's body.
1365    #[tokio::test]
1366    async fn a_browser_and_a_json_client_do_not_share_a_key() {
1367        let browser = stamped(Some("text/html,application/xhtml+xml,*/*;q=0.8")).await;
1368        let json = stamped(Some("application/json")).await;
1369        assert_ne!(
1370            browser, json,
1371            "browser and JSON callers must key differently or the page \
1372             cache will serve one the other's representation"
1373        );
1374    }
1375}