Skip to main content

rustango_cms/
path_prefix.rs

1//! Sites served under a path on the main domain (`example.com/acme/`)
2//! rather than on a host of their own.
3//!
4//! The framework sends a path-prefix tenant's requests to the host app
5//! with the prefix still on the path (`/acme/about`), but every CMS route,
6//! page path and link is written from the site's root. [`serve`] wraps the
7//! host's router so a site works the same under a prefix:
8//!
9//! - on the way in, the prefix comes off the path (`/acme/about` is served
10//!   as `/about`). The framework finds the tenant again in every handler
11//!   from the request, which no longer shows the prefix, so the site is
12//!   named in a header the host's resolver reads ([`tenant_header`]);
13//!   a copy sent by the client is always dropped first;
14//! - on the way out, it goes back on: redirects, cookie paths, and the
15//!   root-relative addresses in HTML, CSS, JavaScript and JSON (links,
16//!   pictures, forms, and the admin's own `/cms-admin/…` calls). Absolute
17//!   addresses (sitemap, feeds, robots.txt) carry it through
18//!   [`PREFIX_HEADER`].
19//!
20//! A host wires both halves:
21//!
22//! ```ignore
23//! rustango::manage::Cli::new()
24//!     .tenancy()
25//!     .tenant_header(rustango_cms::path_prefix::tenant_header())
26//!     .api(rustango_cms::path_prefix::serve(api))
27//! ```
28//!
29//! Sites on their own host pass through untouched.
30
31use std::convert::Infallible;
32use std::sync::LazyLock;
33
34use axum::body::Body;
35use axum::extract::FromRequestParts as _;
36use axum::http::{header, HeaderName, HeaderValue, Request, Response};
37use axum::Router;
38use regex::{Captures, Regex};
39use tower::ServiceExt as _;
40
41/// Names the site a stripped request belongs to, for the framework's
42/// resolver. Set only by [`serve`].
43pub const TENANT_HEADER: &str = "x-rcms-path-tenant";
44
45/// The prefix taken off the request (`/acme`). Set only by [`serve`];
46/// absolute addresses add it after the host.
47pub const PREFIX_HEADER: &str = "x-rcms-path-prefix";
48
49/// Largest response body rewritten; a bigger one is sent as it is.
50const MAX_REWRITE: usize = 32 * 1024 * 1024;
51
52/// The resolver that finds a stripped request's site, for
53/// `Cli::tenant_header`.
54#[must_use]
55pub fn tenant_header() -> rustango::tenancy::HeaderResolver {
56    rustango::tenancy::HeaderResolver::new(HeaderName::from_static(TENANT_HEADER))
57}
58
59/// The prefix [`serve`] took off this request, if any.
60#[must_use]
61pub fn of(headers: &axum::http::HeaderMap) -> Option<&str> {
62    headers.get(PREFIX_HEADER).and_then(|v| v.to_str().ok()).filter(|p| p.starts_with('/'))
63}
64
65/// `path` as the site sees it: without the prefix [`serve`] took off this
66/// request. For addresses the browser reports (`location.pathname`).
67#[must_use]
68pub fn site_path<'a>(headers: &axum::http::HeaderMap, path: &'a str) -> &'a str {
69    match of(headers).and_then(|p| path.strip_prefix(p)) {
70        Some("") => "/",
71        Some(rest) if rest.starts_with('/') => rest,
72        _ => path,
73    }
74}
75
76/// `router`, serving path-prefix sites from their prefix.
77///
78/// Its routes stay as they are, so merging other routes into it (the
79/// framework's admin and sign-in) works as before. A prefixed path matches
80/// none of them and reaches the fallback, which strips the prefix and asks
81/// `router` again.
82pub fn serve(router: Router) -> Router {
83    let inner = router.layer(axum::middleware::from_fn(drop_client_headers));
84    let again = inner.clone();
85    inner.fallback_service(tower::service_fn(move |req: Request<Body>| {
86        let router = again.clone();
87        async move { Ok::<_, Infallible>(handle(router, req).await) }
88    }))
89}
90
91/// Set on a request [`under_prefix`] stripped; a client can't send it.
92#[derive(Clone, Copy)]
93struct Stripped;
94
95/// Drop the private headers unless [`under_prefix`] set them.
96async fn drop_client_headers(mut req: Request<Body>, next: axum::middleware::Next) -> Response<Body> {
97    if req.extensions().get::<Stripped>().is_none() {
98        req.headers_mut().remove(TENANT_HEADER);
99        req.headers_mut().remove(PREFIX_HEADER);
100    }
101    next.run(req).await
102}
103
104async fn handle(router: Router, req: Request<Body>) -> Response<Body> {
105    let (mut parts, body) = req.into_parts();
106    // Only `serve` may name the site or the prefix.
107    parts.headers.remove(TENANT_HEADER);
108    parts.headers.remove(PREFIX_HEADER);
109    let prefix = match <rustango::extractors::Tenant>::from_request_parts(&mut parts, &()).await {
110        Ok(tenant) => tenant
111            .org
112            .path_prefix
113            .as_deref()
114            .map(|p| p.trim_end_matches('/'))
115            .filter(|p| !p.is_empty() && is_under(parts.uri.path(), p))
116            .map(|p| (p.to_owned(), tenant.org.slug.clone())),
117        Err(_) => None,
118    };
119    let req = Request::from_parts(parts, body);
120    match prefix {
121        Some((prefix, slug)) => under_prefix(router, req, &prefix, &slug).await,
122        None => into_response(router.oneshot(req).await),
123    }
124}
125
126/// Serve `req` from the site's root, as site `slug` at `prefix`.
127async fn under_prefix(router: Router, req: Request<Body>, prefix: &str, slug: &str) -> Response<Body> {
128    let (mut parts, body) = req.into_parts();
129    let (Ok(slug), Ok(value)) = (HeaderValue::from_str(slug), HeaderValue::from_str(prefix)) else {
130        return into_response(router.oneshot(Request::from_parts(parts, body)).await);
131    };
132    parts.uri = strip(&parts.uri, prefix);
133    parts.headers.insert(TENANT_HEADER, slug);
134    parts.headers.insert(PREFIX_HEADER, value);
135    parts.extensions.insert(Stripped);
136    let resp = into_response(router.oneshot(Request::from_parts(parts, body)).await);
137    restore(resp, prefix).await
138}
139
140fn into_response(r: Result<Response<Body>, Infallible>) -> Response<Body> {
141    match r {
142        Ok(r) => r,
143        Err(e) => match e {},
144    }
145}
146
147/// Is `path` the prefix itself or below it?
148fn is_under(path: &str, prefix: &str) -> bool {
149    path.strip_prefix(prefix).is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
150}
151
152/// `uri` without `prefix` (`/acme/about?x` → `/about?x`, `/acme` → `/`).
153fn strip(uri: &axum::http::Uri, prefix: &str) -> axum::http::Uri {
154    let rest = uri.path().strip_prefix(prefix).unwrap_or(uri.path());
155    let path = if rest.is_empty() { "/" } else { rest };
156    let pq = match uri.query() {
157        Some(q) => format!("{path}?{q}"),
158        None => path.to_owned(),
159    };
160    pq.parse().unwrap_or_else(|_| uri.clone())
161}
162
163/// The response with `prefix` put back on its addresses.
164async fn restore(resp: Response<Body>, prefix: &str) -> Response<Body> {
165    let (mut parts, body) = resp.into_parts();
166    if let Some(to) = parts.headers.get(header::LOCATION).and_then(|v| v.to_str().ok()) {
167        if let Ok(v) = HeaderValue::from_str(&location(to, prefix)) {
168            parts.headers.insert(header::LOCATION, v);
169        }
170    }
171    let cookies: Vec<HeaderValue> = parts
172        .headers
173        .get_all(header::SET_COOKIE)
174        .iter()
175        .map(|v| v.to_str().ok().map(|c| cookie_path(c, prefix)).and_then(|c| HeaderValue::from_str(&c).ok()).unwrap_or_else(|| v.clone()))
176        .collect();
177    if !cookies.is_empty() {
178        parts.headers.remove(header::SET_COOKIE);
179        for c in cookies {
180            parts.headers.append(header::SET_COOKIE, c);
181        }
182    }
183    let rewritable = parts.headers.get(header::CONTENT_ENCODING).is_none()
184        && parts
185            .headers
186            .get(header::CONTENT_TYPE)
187            .and_then(|v| v.to_str().ok())
188            .is_some_and(|t| {
189                let t = t.to_ascii_lowercase();
190                ["text/html", "text/css", "javascript", "application/json"].iter().any(|k| t.contains(k))
191            });
192    if !rewritable {
193        return Response::from_parts(parts, body);
194    }
195    let Ok(bytes) = axum::body::to_bytes(body, MAX_REWRITE).await else {
196        // Too big (or broken): nothing is left to send but an error.
197        return Response::from_parts(parts, Body::empty());
198    };
199    let out = match std::str::from_utf8(&bytes) {
200        Ok(text) => Body::from(rewrite(text, prefix)),
201        Err(_) => Body::from(bytes),
202    };
203    parts.headers.remove(header::CONTENT_LENGTH);
204    Response::from_parts(parts, out)
205}
206
207/// A redirect target with the prefix, and so is its `next=`.
208fn location(to: &str, prefix: &str) -> String {
209    if !is_root_relative(to) {
210        return to.to_owned();
211    }
212    let (path, query) = to.split_once('?').map_or((to, None), |(p, q)| (p, Some(q)));
213    let query = query.map(|q| {
214        q.split('&')
215            .map(|pair| match pair.split_once('=') {
216                Some(("next", v)) => {
217                    let decoded = rustango::url_codec::url_decode(v);
218                    if is_root_relative(&decoded) {
219                        format!("next={}", rustango::url_codec::url_encode(&format!("{prefix}{decoded}")))
220                    } else {
221                        pair.to_owned()
222                    }
223                }
224                _ => pair.to_owned(),
225            })
226            .collect::<Vec<_>>()
227            .join("&")
228    });
229    match query {
230        Some(q) => format!("{prefix}{path}?{q}"),
231        None => format!("{prefix}{path}"),
232    }
233}
234
235fn is_root_relative(url: &str) -> bool {
236    url.starts_with('/') && !url.starts_with("//") && !url.starts_with("/\\")
237}
238
239/// A `Set-Cookie` value scoped under the prefix (`Path=/` → `Path=/acme`).
240fn cookie_path(cookie: &str, prefix: &str) -> String {
241    cookie
242        .split(';')
243        .map(|attr| {
244            let t = attr.trim_start();
245            let lead = &attr[..attr.len() - t.len()];
246            match t.get(..5).filter(|n| n.eq_ignore_ascii_case("path=")).map(|_| &t[5..]) {
247                Some("/") => format!("{lead}Path={prefix}"),
248                Some(path) if is_root_relative(path) => format!("{lead}Path={prefix}{path}"),
249                _ => attr.to_owned(),
250            }
251        })
252        .collect::<Vec<_>>()
253        .join(";")
254}
255
256/// Root-relative addresses, one alternative each, matched in one pass so
257/// none is prefixed twice:
258///
259/// - `srcset` values, every candidate;
260/// - URL attributes (`href`, `src`, `action`, `formaction`, `poster`,
261///   `data-*`);
262/// - CSS `url(/…)`;
263/// - quoted strings naming a CMS address (`"/cms-admin/…"`,
264///   `'/__media__/…'`, …) in scripts and JSON.
265static ADDRESSES: LazyLock<Regex> = LazyLock::new(|| {
266    Regex::new(concat!(
267        r#"(?P<ss>\s(?i:srcset)\s*=\s*["'])(?P<ssv>[^"']*)"#,
268        r#"|(?P<attr>\s(?i:href|src|action|formaction|poster|data-[a-z0-9_-]+)\s*=\s*["'])(?:/|&#x2[fF];|&#47;)(?P<an>&#x2[fF];|&#47;|[^/\\])"#,
269        r#"|(?P<url>url\(\s*["']?)/(?P<un>[^/\\])"#,
270        r#"|(?P<lit>["'`])/(?P<seg>(?:cms-admin|__media__|__cms[a-z_-]*|api|members|forms|login|logout|admin|feed|sitemap)(?:[/?#.'"`]|$))"#,
271    ))
272    .expect("valid address pattern")
273});
274
275/// `/`, as written or as an HTML escape (Tera escapes it in attributes).
276fn is_slash(s: &str) -> bool {
277    s == "/" || s == "&#47;" || s.eq_ignore_ascii_case("&#x2f;")
278}
279
280fn unescape_slashes(s: &str) -> String {
281    s.replace("&#x2F;", "/").replace("&#x2f;", "/").replace("&#47;", "/")
282}
283
284/// `text` with `prefix` put on its root-relative addresses.
285fn rewrite(text: &str, prefix: &str) -> String {
286    ADDRESSES
287        .replace_all(text, |c: &Captures<'_>| {
288            if let (Some(lead), Some(value)) = (c.name("ss"), c.name("ssv")) {
289                let candidates: Vec<String> = value
290                    .as_str()
291                    .split(',')
292                    .map(|cand| {
293                        let t = cand.trim_start();
294                        if is_root_relative(&unescape_slashes(t)) {
295                            format!("{}{prefix}{t}", &cand[..cand.len() - t.len()])
296                        } else {
297                            cand.to_owned()
298                        }
299                    })
300                    .collect();
301                format!("{}{}", lead.as_str(), candidates.join(","))
302            } else if let (Some(lead), Some(next)) = (c.name("attr"), c.name("an")) {
303                // `//host/…` (escaped or not) is another site: left alone.
304                if is_slash(next.as_str()) {
305                    return c[0].to_owned();
306                }
307                // Keeps the template's escaping: `&#x2F;about` stays escaped.
308                let slash = &c[0][lead.len()..c[0].len() - next.len()];
309                format!("{}{prefix}{slash}{}", lead.as_str(), next.as_str())
310            } else if let (Some(lead), Some(next)) = (c.name("url"), c.name("un")) {
311                format!("{}{prefix}/{}", lead.as_str(), next.as_str())
312            } else if let (Some(quote), Some(seg)) = (c.name("lit"), c.name("seg")) {
313                format!("{}{prefix}/{}", quote.as_str(), seg.as_str())
314            } else {
315                c[0].to_owned()
316            }
317        })
318        .into_owned()
319}
320
321#[cfg(test)]
322mod tests {
323    use super::*;
324
325    #[test]
326    fn the_prefix_comes_off_the_request_path() {
327        let s = |u: &str| strip(&u.parse().unwrap(), "/acme").to_string();
328        assert_eq!(s("/acme"), "/");
329        assert_eq!(s("/acme/"), "/");
330        assert_eq!(s("/acme/about?x=1"), "/about?x=1");
331        assert!(is_under("/acme/x", "/acme"));
332        assert!(is_under("/acme", "/acme"));
333        assert!(!is_under("/acmeco/x", "/acme"));
334    }
335
336    #[test]
337    fn html_addresses_get_the_prefix_once() {
338        let html = r#"<a href="/">Home</a><a href='/about'>A</a><a href="//cdn.x/y">C</a><a href="https://x/y">X</a>
339<img src="/__media__/raw/5" srcset="/__media__/r/5-w400.webp 400w, /__media__/r/5-w800.webp 800w">
340<form action="/forms/submit/3"></form><div style="background:url('/__media__/raw/2')"></div>
341<a href="&#x2F;work&#x2F;x">E</a><a href="&#x2F;&#x2F;cdn.x&#x2F;y">P</a>
342<script>fetch(`/cms-admin/search?q=${q}`); const u = "/__media__/raw/" + id; const p = "/about";</script>"#;
343        let out = rewrite(html, "/acme");
344        for want in [
345            r#"href="/acme/""#,
346            r#"href='/acme/about'"#,
347            // Tera escapes `/` in attributes; the escaping is kept.
348            r#"href="/acme&#x2F;work&#x2F;x""#,
349            r#"href="&#x2F;&#x2F;cdn.x&#x2F;y""#,
350            r#"href="//cdn.x/y""#,
351            r#"href="https://x/y""#,
352            r#"src="/acme/__media__/raw/5""#,
353            r#"srcset="/acme/__media__/r/5-w400.webp 400w, /acme/__media__/r/5-w800.webp 800w""#,
354            r#"action="/acme/forms/submit/3""#,
355            "url('/acme/__media__/raw/2')",
356            "fetch(`/acme/cms-admin/search?q=${q}`)",
357            r#""/acme/__media__/raw/" + id"#,
358            // A page path in a script is not a CMS address: left alone.
359            r#"const p = "/about""#,
360        ] {
361            assert!(out.contains(want), "missing {want}\n{out}");
362        }
363        assert!(!out.contains("/acme/acme"), "{out}");
364    }
365
366    #[test]
367    fn json_addresses_get_the_prefix() {
368        let out = rewrite(r#"{"url":"/cms-admin/pages/4/edit","thumb":"/__media__/r/4.webp","path":"/news"}"#, "/acme");
369        assert_eq!(out, r#"{"url":"/acme/cms-admin/pages/4/edit","thumb":"/acme/__media__/r/4.webp","path":"/news"}"#);
370    }
371
372    #[test]
373    fn redirects_and_their_next_get_the_prefix() {
374        assert_eq!(location("/login?next=%2Fcms-admin%2F", "/acme"), "/acme/login?next=%2Facme%2Fcms-admin%2F");
375        assert_eq!(location("/cms-admin/pages", "/acme"), "/acme/cms-admin/pages");
376        assert_eq!(location("https://x.example/a", "/acme"), "https://x.example/a");
377        assert_eq!(location("//evil.example/a", "/acme"), "//evil.example/a");
378    }
379
380    #[test]
381    fn a_reported_path_loses_the_prefix() {
382        let mut h = axum::http::HeaderMap::new();
383        assert_eq!(site_path(&h, "/acme/about"), "/acme/about");
384        h.insert(PREFIX_HEADER, HeaderValue::from_static("/acme"));
385        assert_eq!(site_path(&h, "/acme/about"), "/about");
386        assert_eq!(site_path(&h, "/acme"), "/");
387        assert_eq!(site_path(&h, "/acmeco/x"), "/acmeco/x");
388    }
389
390    /// What the host's router saw, as a page linking to its root.
391    fn site() -> Router {
392        use axum::routing::get;
393        let seen = |headers: axum::http::HeaderMap, uri: axum::http::Uri| async move {
394            let named = headers.get(TENANT_HEADER).map(|v| v.to_str().unwrap_or("").to_owned()).unwrap_or_default();
395            axum::response::Html(format!(r#"<p>{uri} {named}</p><a href="/about">About</a>"#))
396        };
397        Router::new()
398            .route("/about", get(seen))
399            .route("/go", get(|| async { axum::response::Redirect::to("/login?next=%2Fcms-admin%2F") }))
400    }
401
402    async fn body_of(resp: Response<Body>) -> String {
403        String::from_utf8(axum::body::to_bytes(resp.into_body(), 1 << 20).await.unwrap().to_vec()).unwrap()
404    }
405
406    #[tokio::test]
407    async fn a_prefixed_request_is_served_from_the_site_root() {
408        let req = Request::get("/acme/about?x=1").body(Body::empty()).unwrap();
409        let out = body_of(under_prefix(site(), req, "/acme", "acme").await).await;
410        assert!(out.contains("<p>/about?x=1 acme</p>"), "{out}");
411        assert!(out.contains(r#"href="/acme/about""#), "{out}");
412
413        let req = Request::get("/acme/go").body(Body::empty()).unwrap();
414        let resp = under_prefix(site(), req, "/acme", "acme").await;
415        assert_eq!(resp.headers()[header::LOCATION], "/acme/login?next=%2Facme%2Fcms-admin%2F");
416    }
417
418    #[tokio::test]
419    async fn a_client_cannot_name_the_site() {
420        // No tenant here: the request passes through, minus the header.
421        let req = Request::get("/about").header(TENANT_HEADER, "other").body(Body::empty()).unwrap();
422        let out = body_of(handle(site(), req).await).await;
423        assert!(out.contains("<p>/about </p>"), "{out}");
424        assert!(out.contains(r#"href="/about""#), "untouched: {out}");
425    }
426
427    #[tokio::test]
428    async fn the_host_routes_stay_and_ignore_a_client_header() {
429        // Matched directly, not through the fallback: still no header.
430        let req = Request::get("/about").header(TENANT_HEADER, "other").header(PREFIX_HEADER, "/x").body(Body::empty()).unwrap();
431        let out = body_of(into_response(serve(site()).oneshot(req).await)).await;
432        assert!(out.contains("<p>/about </p>"), "{out}");
433        // Routes merged in later don't collide with a catch-all.
434        let merged = serve(site()).merge(Router::new().route("/login", axum::routing::get(|| async { "login" })));
435        let req = Request::get("/login").body(Body::empty()).unwrap();
436        assert_eq!(body_of(into_response(merged.oneshot(req).await)).await, "login");
437    }
438
439    #[test]
440    fn cookies_are_scoped_under_the_prefix() {
441        assert_eq!(cookie_path("a=1; Path=/; HttpOnly", "/acme"), "a=1; Path=/acme; HttpOnly");
442        assert_eq!(cookie_path("a=1; path=/cms-admin", "/acme"), "a=1; Path=/acme/cms-admin");
443        assert_eq!(cookie_path("a=1; HttpOnly", "/acme"), "a=1; HttpOnly");
444    }
445}