1use 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
41pub const TENANT_HEADER: &str = "x-rcms-path-tenant";
44
45pub const PREFIX_HEADER: &str = "x-rcms-path-prefix";
48
49const MAX_REWRITE: usize = 32 * 1024 * 1024;
51
52#[must_use]
55pub fn tenant_header() -> rustango::tenancy::HeaderResolver {
56 rustango::tenancy::HeaderResolver::new(HeaderName::from_static(TENANT_HEADER))
57}
58
59#[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#[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
76pub 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#[derive(Clone, Copy)]
93struct Stripped;
94
95async 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 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
126async 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
147fn is_under(path: &str, prefix: &str) -> bool {
149 path.strip_prefix(prefix).is_some_and(|rest| rest.is_empty() || rest.starts_with('/'))
150}
151
152fn 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
163async 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 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
207fn 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
239fn 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
256static 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*["'])(?:/|[fF];|/)(?P<an>[fF];|/|[^/\\])"#,
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
275fn is_slash(s: &str) -> bool {
277 s == "/" || s == "/" || s.eq_ignore_ascii_case("/")
278}
279
280fn unescape_slashes(s: &str) -> String {
281 s.replace("/", "/").replace("/", "/").replace("/", "/")
282}
283
284fn 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 if is_slash(next.as_str()) {
305 return c[0].to_owned();
306 }
307 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="/work/x">E</a><a href="//cdn.x/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 r#"href="/acme/work/x""#,
349 r#"href="//cdn.x/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 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 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 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 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 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}