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
708async fn handle_page_request(
709    tenant: Tenant,
710    State(state): State<PublicState>,
711    rustango::extractors::SessionUser(session_user): rustango::extractors::SessionUser,
712    rustango::tenancy::member_auth::CurrentMember(member): rustango::tenancy::member_auth::CurrentMember,
713    headers: axum::http::HeaderMap,
714    uri: Uri,
715) -> Response {
716    // #members — the page-gating viewer is a public member (member
717    // cookie) OR an admin (tenant-session cookie); a member session
718    // takes precedence on public pages. Both are `Option<User>` from
719    // the same `rustango_users` table, so restriction checks (login /
720    // groups / permission) work identically for either.
721    let viewer = member.as_ref().or(session_user.as_ref());
722    let raw_path = uri.path();
723    // #553 — override-live redirect rules beat page resolution. The rule
724    // set is fragment-cached (and usually empty), so page views on
725    // rule-free tenants stay one-query — and none of the locale/page work
726    // below runs on a hit.
727    let _perf_t = crate::perf::start();
728    if let Some(resp) = crate::redirect::serve_override(
729        &tenant,
730        state.fragment_cache.as_ref().map(|(c, ttl)| (c, *ttl)),
731        raw_path,
732        uri.query(),
733    )
734    .await
735    {
736        crate::perf::mark("redirect_rules", _perf_t);
737        return resp;
738    }
739    crate::perf::mark("redirect_rules", _perf_t);
740    // Locale resolved from path / query per the
741    // configured mode. The resolver returns a stripped path so the
742    // canonical url_path used for the page lookup never carries the
743    // locale prefix.
744    let accept_language = headers
745        .get(axum::http::header::ACCEPT_LANGUAGE)
746        .and_then(|v| v.to_str().ok());
747    // Media-type preference for page types that serve a JSON view.
748    // Parsed once here and passed down; `render_inner` is the only thing
749    // that reads it, and only for those types.
750    let accept = crate::page_view::parse_accept(
751        headers
752            .get(axum::http::header::ACCEPT)
753            .and_then(|v| v.to_str().ok()),
754    );
755    // #i18n — persistence cookie keeps the chosen locale across links
756    // that don't carry it (bare nav paths, in-content links).
757    let cookie_code = crate::locale_mode::locale_cookie_value(
758        headers
759            .get(axum::http::header::COOKIE)
760            .and_then(|v| v.to_str().ok()),
761    );
762    let _perf_t = crate::perf::start();
763    let request_locale = resolve_request_locale(
764        tenant.pool(),
765        state.locale_mode,
766        raw_path,
767        uri.query(),
768        cookie_code.as_deref(),
769        accept_language,
770    )
771    .await;
772    crate::perf::mark("locale", _perf_t);
773    let locale_code = request_locale.code.clone();
774    let locale_explicit = request_locale.explicit;
775    let lookup_path = request_locale.stripped_path;
776
777    // Multi-site: which root does this hostname serve? With no `cms_site`
778    // rows this resolves to the conventional root and contributes an empty
779    // prefix, so the lookup below is byte-identical to what it always was.
780    let _perf_t = crate::perf::start();
781    let site_prefix = crate::site::prefix_for_host(tenant.pool(), host_header(&headers))
782        .await
783        .unwrap_or_default();
784    crate::perf::mark("site", _perf_t);
785    // Stored paths are tenant-absolute; the visitor's path is relative to
786    // the site root.
787    let lookup_path = crate::site::to_lookup_path(&site_prefix, &lookup_path);
788
789    let _perf_t = crate::perf::start();
790    let _resolved = resolve_path(&tenant, &lookup_path).await;
791    crate::perf::mark("resolve_path", _perf_t);
792    match _resolved {
793        Ok(Some(page)) => {
794            // #76 — per-page view restrictions. Walks ancestors for the
795            // nearest restriction; if found, enforces login / groups /
796            // password before delegating to the renderer. The
797            // unrestricted path stays a single resolve + render.
798            let _perf_t = crate::perf::start();
799            let _blocked =
800                crate::view_restriction_guard::enforce(&tenant, &page, viewer, &headers, raw_path)
801                    .await;
802            crate::perf::mark("view_restriction", _perf_t);
803            if let Some(blocked) = _blocked {
804                return styled_denial(&tenant, &state, blocked, locale_code.as_deref()).await;
805            }
806            // #107 — plugin `before_serve_page` hook. First handler
807            // to return `Some(Response)` short-circuits the renderer.
808            if let Some(resp) = crate::hooks::fire_before_serve_page(&page, &headers) {
809                return resp;
810            }
811            // #401 — stash the per-page language-switcher data for the
812            // `language_switcher()` Tera fn. render_inner re-installs it
813            // in its await-free block (see stash_pending) so the
814            // thread-local lands on the thread that runs `tera.render`;
815            // this guard clears the stash after render regardless.
816            let _perf_t = crate::perf::start();
817            // Per-tenant overrides layered on the global set. Resolved
818            // here rather than inside render so the render path keeps
819            // taking a plain `&Tera` and stays testable without a cache.
820            let tera = state.tera_for(&tenant.org.slug).await;
821            // After `tera_for`: the stash is per-thread, and an `.await`
822            // between it and the render can move the task to another
823            // thread, stranding the entries for some other page's render.
824            let _switcher =
825                install_locale_switcher(&tenant, &state, &page, locale_code.as_deref()).await;
826            // `site_origin` for absolute canonical / og:image URLs. Stashed
827            // here, with no `.await` before the render reads it.
828            let _origin = crate::meta_tags::stash_site_origin(crate::sitemap::base_url(&headers));
829            let resp = render_negotiated(
830                &tenant,
831                &tera,
832                &page,
833                &state.url_prefix,
834                &site_prefix,
835                locale_code.as_deref(),
836                viewer,
837                accept,
838                state.fragment_cache.as_ref().map(|(c, ttl)| (c, *ttl)),
839            )
840            .await;
841            crate::perf::mark("render", _perf_t);
842            // Substitute the CMS-editable 500 page for render failures
843            // (the plain-text diagnostics are already tracing::error!'d
844            // inside render; visitors get the styled page instead).
845            let resp = if resp.status().is_server_error() {
846                crate::error_pages::respond(&tenant, &state, resp.status(), locale_code.as_deref())
847                    .await
848            } else {
849                resp
850            };
851            persist_locale(resp, locale_explicit, locale_code.as_deref())
852        }
853        Ok(None) => {
854            // #198 — routable_page: before falling through to
855            // redirects / 404, ask each ancestor's handler if it
856            // owns a route pattern that matches the suffix. First
857            // match wins; the renderer threads `route_name` +
858            // `route_captures` into the Tera ctx.
859            match resolve_routable(&tenant, &lookup_path).await {
860                Ok(Some((page, route_match))) => {
861                    if let Some(blocked) = crate::view_restriction_guard::enforce(
862                        &tenant, &page, viewer, &headers, raw_path,
863                    )
864                    .await
865                    {
866                        return styled_denial(&tenant, &state, blocked, locale_code.as_deref()).await;
867                    }
868                    if let Some(resp) = crate::hooks::fire_before_serve_page(&page, &headers) {
869                        return resp;
870                    }
871                    let tera = state.tera_for(&tenant.org.slug).await;
872                    let _switcher =
873                        install_locale_switcher(&tenant, &state, &page, locale_code.as_deref())
874                            .await;
875                    let _origin =
876                        crate::meta_tags::stash_site_origin(crate::sitemap::base_url(&headers));
877                    let resp = render_with_route(
878                        &tenant,
879                        &tera,
880                        &page,
881                        &state.url_prefix,
882                        &site_prefix,
883                        locale_code.as_deref(),
884                        viewer,
885                        &route_match,
886                        accept,
887                        state.fragment_cache.as_ref().map(|(c, ttl)| (c, *ttl)),
888                    )
889                    .await;
890                    let resp = if resp.status().is_server_error() {
891                        crate::error_pages::respond(
892                            &tenant,
893                            &state,
894                            resp.status(),
895                            locale_code.as_deref(),
896                        )
897                        .await
898                    } else {
899                        resp
900                    };
901                    return persist_locale(resp, locale_explicit, locale_code.as_deref());
902                }
903                Ok(None) => {}
904                Err(e) => {
905                    tracing::error!(path = %raw_path, error = %e, "resolve_routable failed");
906                }
907            }
908            fallthrough_to_redirect(
909                &tenant,
910                &state,
911                raw_path,
912                uri.query(),
913                locale_code.as_deref(),
914            )
915            .await
916        }
917        Err(e) => {
918            tracing::error!(path = %raw_path, error = %e, "resolve_path failed");
919            crate::error_pages::respond(
920                &tenant,
921                &state,
922                StatusCode::INTERNAL_SERVER_ERROR,
923                locale_code.as_deref(),
924            )
925            .await
926        }
927    }
928}
929
930/// Attach locale-persistence headers to a page response. `Vary: Cookie`
931/// always (the rendered language depends on the `rcms_locale` cookie, so
932/// a shared/CDN cache must key on it); a `Set-Cookie` writing the chosen
933/// locale only when it was an EXPLICIT pick (`?lang=` / `/<code>/`), so a
934/// plain nav click — which resolves the locale *from* the cookie — never
935/// rewrites it. An explicit switch to the default locale still writes the
936/// cookie, overriding a stale non-default one.
937fn persist_locale(mut resp: Response, explicit: bool, code: Option<&str>) -> Response {
938    use axum::http::header::{HeaderValue, SET_COOKIE, VARY};
939    resp.headers_mut()
940        .append(VARY, HeaderValue::from_static("Cookie"));
941    if explicit {
942        if let Some(code) = code {
943            let cookie = format!(
944                "{}={code}; Path=/; SameSite=Lax; HttpOnly; Max-Age=31536000",
945                crate::locale_mode::LOCALE_COOKIE
946            );
947            if let Ok(hv) = HeaderValue::from_str(&cookie) {
948                resp.headers_mut().append(SET_COOKIE, hv);
949            }
950        }
951    }
952    resp
953}
954
955/// A signed-in visitor who may not see a restricted page gets the site's
956/// 403 page (an editor-made error page, else the styled fallback) instead
957/// of a bare text body; login and password redirects pass through.
958async fn styled_denial(
959    tenant: &Tenant,
960    state: &PublicState,
961    blocked: Response,
962    locale_code: Option<&str>,
963) -> Response {
964    if blocked.status() == StatusCode::FORBIDDEN {
965        crate::error_pages::respond(tenant, state, StatusCode::FORBIDDEN, locale_code).await
966    } else {
967        blocked
968    }
969}
970
971/// Fetch the active locales and stash the per-page language
972/// switcher (the URL to *this* page in each locale, built per the
973/// configured `LocaleMode`) for the `language_switcher()` Tera fn. The
974/// stash is consumed and re-installed on the render thread inside
975/// `render_inner`'s await-free block (so the thread-local survives
976/// tokio's thread-hops across render's awaits); the returned guard
977/// clears any un-consumed stash when it drops, so the caller must hold
978/// it across the `render*` call. The final `stash_pending` runs after
979/// this fn's only `.await`, and the caller polls the render future with
980/// no intervening `.await`, so render's synchronous entry sees it.
981pub(crate) async fn install_locale_switcher(
982    tenant: &Tenant,
983    state: &PublicState,
984    page: &crate::page::Page,
985    current_code: Option<&str>,
986) -> crate::language_switcher::PendingGuard {
987    use rustango::core::Column as _;
988    use rustango::sql::FetcherPool as _;
989    let locales: Vec<crate::locale::Locale> = crate::locale::Locale::objects()
990        .where_(crate::locale::Locale::active.eq(true))
991        .order_by(&[("sort_order", false)])
992        .fetch(tenant.pool())
993        .await
994        .unwrap_or_default();
995    let entries = crate::language_switcher::build(
996        &locales,
997        &state.url_prefix,
998        &page.url_path,
999        state.locale_mode,
1000        current_code,
1001    );
1002    crate::language_switcher::stash_pending(entries)
1003}
1004
1005/// When the slug resolver returns `None` (no published page at this
1006/// URL), consult the tenant's `cms_redirect` table before giving
1007/// up. Redirects hook into the 404 path: live pages always win, redirects fill in for
1008/// retired URLs.
1009///
1010/// On a redirect hit, the framework's
1011/// [`rustango::redirects::build_redirect_response`] emits the
1012/// 301/302 with `Location` carrying any incoming query string. Hit
1013/// count is bumped best-effort in the background; failure to
1014/// increment is logged and swallowed.
1015async fn fallthrough_to_redirect(
1016    tenant: &Tenant,
1017    state: &PublicState,
1018    raw_path: &str,
1019    query: Option<&str>,
1020    locale_code: Option<&str>,
1021) -> Response {
1022    match crate::redirect::find_for_path(tenant.pool(), raw_path).await {
1023        Ok(Some(row)) => {
1024            // #553 — a `to_page_id` destination resolves to the page's
1025            // CURRENT url_path (follows moves); `to_path` is the fallback.
1026            let to = crate::redirect::resolve_destination(tenant.pool(), &row).await;
1027            let rule = rustango::redirects::RedirectRule {
1028                to,
1029                permanent: row.is_permanent,
1030            };
1031            let resp = rustango::redirects::build_redirect_response(&rule, query);
1032            // #555 — record the hit in-memory (no per-request DB write);
1033            // the throttled flush persists the delta + last_hit_at.
1034            crate::redirect::record_hit(
1035                tenant.pool(),
1036                &tenant.org.slug,
1037                row.id.get().copied().unwrap_or_default(),
1038            );
1039            resp
1040        }
1041        // No exact rule, no live page — try #554 wildcard rules before
1042        // giving up. Non-override wildcards fill in for URLs with no
1043        // live page, exactly like exact non-override rules.
1044        Ok(None) => {
1045            let cache = state.fragment_cache.as_ref().map(|(c, ttl)| (c, *ttl));
1046            if let Some(resp) =
1047                crate::redirect::serve_wildcard(tenant, cache, raw_path, query).await
1048            {
1049                return resp;
1050            }
1051            crate::error_pages::respond(tenant, state, StatusCode::NOT_FOUND, locale_code).await
1052        }
1053        Err(e) => {
1054            tracing::warn!(path = %raw_path, error = %e, "redirect lookup failed");
1055            crate::error_pages::respond(tenant, state, StatusCode::NOT_FOUND, locale_code).await
1056        }
1057    }
1058}
1059
1060// =====================================================================
1061// #76 — view-restriction password prompt.
1062// =====================================================================
1063
1064#[derive(Debug, serde::Deserialize)]
1065struct PasswordPromptQuery {
1066    page: i64,
1067    #[serde(default)]
1068    next: Option<String>,
1069    #[serde(default)]
1070    error: Option<String>,
1071}
1072
1073#[derive(Debug, serde::Deserialize)]
1074struct PasswordSubmitForm {
1075    page: i64,
1076    password: String,
1077    #[serde(default)]
1078    next: Option<String>,
1079}
1080
1081async fn handle_view_password_form(
1082    tenant: Tenant,
1083    State(state): State<PublicState>,
1084    headers: axum::http::HeaderMap,
1085    axum::extract::Query(q): axum::extract::Query<PasswordPromptQuery>,
1086) -> Response {
1087    use rustango::core::Column as _;
1088    use rustango::sql::FetcherPool as _;
1089    let _ = &tenant;
1090    let page_rows: Vec<crate::page::Page> = crate::page::Page::objects()
1091        .where_(crate::page::Page::id.eq(q.page))
1092        .fetch(tenant.pool())
1093        .await
1094        .unwrap_or_default();
1095    let title = page_rows
1096        .first()
1097        .map(|p| p.title.clone())
1098        .unwrap_or_else(|| "Protected page".to_owned());
1099    let next = q.next.clone().unwrap_or_else(|| "/".to_owned());
1100    let error_msg = q.error.as_deref().unwrap_or("");
1101    let mut ctx = tera::Context::new();
1102    ctx.insert("page_id", &q.page);
1103    ctx.insert("page_title", &title);
1104    ctx.insert("next_path", &next);
1105    ctx.insert("error_message", &error_msg);
1106    // Seed the double-submit token on the GET so a host CSRF layer does not
1107    // reject the first POST (#677, same shape as the framework login).
1108    let (csrf_token, csrf_cookie) =
1109        rustango::forms::csrf::ensure_token(&headers, rustango::forms::csrf::CSRF_COOKIE);
1110    ctx.insert("csrf_token", &csrf_token);
1111    match state.tera.render("rcms/view_password.html", &ctx) {
1112        Ok(body) => {
1113            let mut resp = axum::response::Html(body).into_response();
1114            if let Some(v) = csrf_cookie.and_then(|c| axum::http::HeaderValue::from_str(&c).ok()) {
1115                resp.headers_mut().append(axum::http::header::SET_COOKIE, v);
1116            }
1117            resp
1118        }
1119        Err(e) => {
1120            tracing::error!(error = %e, "view-password template render failed");
1121            (StatusCode::INTERNAL_SERVER_ERROR, "template error").into_response()
1122        }
1123    }
1124}
1125
1126async fn handle_view_password_submit(
1127    tenant: Tenant,
1128    axum::extract::Form(form): axum::extract::Form<PasswordSubmitForm>,
1129) -> Response {
1130    let Some(restriction) = crate::view_restriction::direct_for_page(tenant.pool(), form.page)
1131        .await
1132        .unwrap_or(None)
1133        .filter(|r| r.kind == crate::view_restriction::RestrictionKind::Password.as_str())
1134    else {
1135        return (
1136            StatusCode::BAD_REQUEST,
1137            "no password restriction on this page",
1138        )
1139            .into_response();
1140    };
1141    let _ = &tenant;
1142    let _ = &restriction.password_hash;
1143    // Verify the password against the stored argon2id hash.
1144    let ok =
1145        crate::passwords::verify(&form.password, &restriction.password_hash).await.unwrap_or(false);
1146    // A local path only — this form is reachable from any link (#728).
1147    let next = form
1148        .next
1149        .as_deref()
1150        .and_then(rustango::auth_decorators::safe_next)
1151        .unwrap_or_else(|| "/".to_owned());
1152    if !ok {
1153        let next_enc = crate::view_restriction_guard::url_encode_path(&next);
1154        return Redirect::to(&format!(
1155            "/__cms-view-password?page={}&next={next_enc}&error=Wrong+password",
1156            form.page
1157        ))
1158        .into_response();
1159    }
1160    // 7-day grant, expired on the server too; rotate the password to
1161    // revoke early.
1162    let cookie =
1163        crate::view_restriction_guard::grant_cookie(&tenant.org.slug, &restriction, form.page);
1164    let mut response = Redirect::to(&next).into_response();
1165    if let Ok(hv) = axum::http::HeaderValue::from_str(&cookie) {
1166        response
1167            .headers_mut()
1168            .append(axum::http::header::SET_COOKIE, hv);
1169    }
1170    response
1171}
1172
1173#[cfg(test)]
1174mod static_serve_tests {
1175    use super::*;
1176    use std::fs;
1177    use std::path::PathBuf;
1178
1179    /// Make a temporary directory for a single test. Files live
1180    /// under `target/tmp/<name>/` to avoid colliding across parallel
1181    /// runs while still being predictable to clean up.
1182    fn tempdir(name: &str) -> PathBuf {
1183        let mut p = std::env::temp_dir();
1184        p.push(format!("rustango_cms_static_{name}_{}", std::process::id()));
1185        let _ = fs::remove_dir_all(&p);
1186        fs::create_dir_all(&p).expect("create tempdir");
1187        p
1188    }
1189
1190    #[test]
1191    fn serves_existing_file_with_guessed_mime() {
1192        let dir = tempdir("hit");
1193        fs::write(dir.join("styles.css"), b"body{color:red}").unwrap();
1194        let resp = serve_static_path(&dir, "styles.css");
1195        assert_eq!(resp.status(), axum::http::StatusCode::OK);
1196        let ct = resp
1197            .headers()
1198            .get(axum::http::header::CONTENT_TYPE)
1199            .unwrap()
1200            .to_str()
1201            .unwrap();
1202        assert!(ct.starts_with("text/css"), "got `{ct}`");
1203        let cc = resp
1204            .headers()
1205            .get(axum::http::header::CACHE_CONTROL)
1206            .unwrap()
1207            .to_str()
1208            .unwrap();
1209        assert!(cc.contains("max-age=3600"));
1210    }
1211
1212    #[test]
1213    fn rejects_dotdot_traversal_in_segment() {
1214        let dir = tempdir("trav");
1215        fs::write(dir.join("ok.txt"), b"in-root").unwrap();
1216        // `..` segment — must 404 even if the file outside exists.
1217        let resp = serve_static_path(&dir, "../etc/passwd");
1218        assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1219    }
1220
1221    #[test]
1222    fn rejects_absolute_segment() {
1223        let dir = tempdir("abs");
1224        // Leading slash in a segment shouldn't escape — handler bails.
1225        let resp = serve_static_path(&dir, "/etc/passwd");
1226        assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1227    }
1228
1229    #[test]
1230    fn rejects_null_byte_in_path() {
1231        let dir = tempdir("null");
1232        let resp = serve_static_path(&dir, "ok\0.txt");
1233        assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1234    }
1235
1236    #[test]
1237    fn missing_file_is_404_not_500() {
1238        let dir = tempdir("miss");
1239        let resp = serve_static_path(&dir, "does-not-exist.css");
1240        assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1241    }
1242
1243    #[test]
1244    fn serves_static_bytes_with_supplied_content_type() {
1245        let resp = serve_static_bytes(b"<svg/>", "image/svg+xml");
1246        assert_eq!(resp.status(), axum::http::StatusCode::OK);
1247        assert_eq!(
1248            resp.headers()
1249                .get(axum::http::header::CONTENT_TYPE)
1250                .and_then(|v| v.to_str().ok()),
1251            Some("image/svg+xml"),
1252        );
1253    }
1254
1255    #[test]
1256    fn nested_subdir_is_served() {
1257        let dir = tempdir("nested");
1258        fs::create_dir_all(dir.join("css/sub")).unwrap();
1259        fs::write(dir.join("css/sub/x.css"), b"x{}").unwrap();
1260        let resp = serve_static_path(&dir, "css/sub/x.css");
1261        assert_eq!(resp.status(), axum::http::StatusCode::OK);
1262    }
1263
1264    #[test]
1265    fn empty_path_is_404() {
1266        let dir = tempdir("empty");
1267        let resp = serve_static_path(&dir, "");
1268        assert_eq!(resp.status(), axum::http::StatusCode::NOT_FOUND);
1269    }
1270}
1271
1272#[cfg(test)]
1273mod accept_cache_key_tests {
1274    use super::*;
1275    use axum::http::{HeaderValue, Request};
1276
1277    fn req_with_accept(accept: Option<&str>) -> axum::extract::Request {
1278        let mut b = Request::builder().uri("/some-page");
1279        if let Some(a) = accept {
1280            b = b.header(
1281                axum::http::header::ACCEPT,
1282                HeaderValue::from_str(a).unwrap(),
1283            );
1284        }
1285        b.body(axum::body::Body::empty()).unwrap()
1286    }
1287
1288    async fn stamped(accept: Option<&str>) -> Option<String> {
1289        let req = inject_accept_kind_header(req_with_accept(accept)).await;
1290        req.headers()
1291            .get("x-rcms-accept")
1292            .and_then(|v| v.to_str().ok())
1293            .map(str::to_owned)
1294    }
1295
1296    /// The cache keys on this header, so a JSON caller must be the only
1297    /// one that changes it. If a browser ever stamped it too, ordinary
1298    /// traffic would fragment the cache for no benefit.
1299    #[tokio::test]
1300    async fn only_an_explicit_json_preference_changes_the_cache_key() {
1301        assert_eq!(
1302            stamped(Some("application/json")).await.as_deref(),
1303            Some("json")
1304        );
1305        assert_eq!(
1306            stamped(Some("application/json, text/plain, */*"))
1307                .await
1308                .as_deref(),
1309            Some("json")
1310        );
1311
1312        // Everything else shares the header-absent key.
1313        let chrome = "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,\
1314                      image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7";
1315        assert_eq!(stamped(Some(chrome)).await, None);
1316        assert_eq!(stamped(Some("*/*")).await, None);
1317        assert_eq!(stamped(None).await, None);
1318        // A page that prefers HTML but tolerates JSON is an HTML caller.
1319        assert_eq!(
1320            stamped(Some("application/json;q=0.1, text/html")).await,
1321            None
1322        );
1323        // An explicit refusal is not a request.
1324        assert_eq!(stamped(Some("application/json;q=0")).await, None);
1325    }
1326
1327    /// The poisoning scenario, stated as an assertion: a browser and a
1328    /// JSON client must not land on the same cache key for the same URL,
1329    /// or one gets the other's body.
1330    #[tokio::test]
1331    async fn a_browser_and_a_json_client_do_not_share_a_key() {
1332        let browser = stamped(Some("text/html,application/xhtml+xml,*/*;q=0.8")).await;
1333        let json = stamped(Some("application/json")).await;
1334        assert_ne!(
1335            browser, json,
1336            "browser and JSON callers must key differently or the page \
1337             cache will serve one the other's representation"
1338        );
1339    }
1340}