Skip to main content

lean_ctx_cli/dashboard/
base_path.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Reverse-proxy subpath support for `lean-ctx dashboard --base-path` (#355).
3//!
4//! When the dashboard is mounted under a subpath (e.g. `/dashboard/`) by an
5//! nginx-style reverse proxy, two things must happen:
6//!
7//! 1. Every root-absolute URL in the served HTML/CSS/JS (`/static/…`, `/api/…`,
8//!    `/favicon…`) must be prefixed with the base path, otherwise the browser
9//!    resolves them against the origin root and bypasses the subpath.
10//! 2. The server must accept incoming requests **both with and without** the
11//!    prefix, so it works whether or not the reverse proxy strips it.
12//!
13//! All functions are pure and `base`-gated (empty base → exact no-op), so the
14//! default behaviour is byte-for-byte identical to a dashboard without a subpath.
15
16/// Normalizes a user-supplied base path into a canonical form: an empty string
17/// for "no prefix", otherwise a single leading slash and no trailing slash.
18///
19/// `""`/`"/"` → `""`, `"dashboard"`/`"/dashboard/"`/`"//dashboard//"` →
20/// `"/dashboard"`.
21pub fn normalize(input: &str) -> String {
22    let trimmed = input.trim().trim_matches('/');
23    if trimmed.is_empty() {
24        String::new()
25    } else {
26        format!("/{trimmed}")
27    }
28}
29
30/// Strips the base-path prefix from an incoming request path so downstream
31/// routing always sees a root-relative path. Requests that already arrive
32/// root-relative (proxy stripped the prefix, or direct local access) pass
33/// through unchanged.
34pub fn strip<'a>(path: &'a str, base: &str) -> &'a str {
35    if base.is_empty() {
36        return path;
37    }
38    if path == base {
39        return "/";
40    }
41    match path.strip_prefix(base) {
42        Some(rest) if rest.starts_with('/') => rest,
43        _ => path,
44    }
45}
46
47/// Prefixes every root-absolute asset/API/favicon URL in a served text body with
48/// the base path. Only the quote/paren-delimited forms that actually occur in the
49/// dashboard assets (`"/static/`, `'/api/`, `` `/api/ ``, `url(/static/`, …) are
50/// rewritten, so ordinary text is never touched. No-op when `base` is empty.
51pub fn rewrite_asset_urls(body: &str, base: &str) -> String {
52    if base.is_empty() {
53        return body.to_string();
54    }
55    // Root-absolute prefixes used by the dashboard. `/favicon` has no trailing
56    // slash on purpose (covers both `/favicon.svg` and `/favicon.ico`).
57    const PREFIXES: &[&str] = &["/static/", "/api/", "/favicon"];
58    // Delimiters that introduce a URL literal in HTML attributes, JS string and
59    // template literals, and CSS `url(...)`.
60    const DELIMS: &[char] = &['"', '\'', '`', '('];
61
62    let mut out = body.to_string();
63    for prefix in PREFIXES {
64        for &d in DELIMS {
65            let from = format!("{d}{prefix}");
66            if out.contains(&from) {
67                let to = format!("{d}{base}{prefix}");
68                out = out.replace(&from, &to);
69            }
70        }
71    }
72    out
73}
74
75#[cfg(test)]
76mod tests {
77    use super::*;
78
79    #[test]
80    fn normalize_canonicalizes() {
81        assert_eq!(normalize(""), "");
82        assert_eq!(normalize("/"), "");
83        assert_eq!(normalize("   "), "");
84        assert_eq!(normalize("dashboard"), "/dashboard");
85        assert_eq!(normalize("/dashboard"), "/dashboard");
86        assert_eq!(normalize("/dashboard/"), "/dashboard");
87        assert_eq!(normalize("//dashboard//"), "/dashboard");
88        assert_eq!(normalize("/lean/ctx"), "/lean/ctx");
89    }
90
91    #[test]
92    fn strip_empty_base_is_noop() {
93        assert_eq!(strip("/api/stats", ""), "/api/stats");
94        assert_eq!(strip("/", ""), "/");
95    }
96
97    #[test]
98    fn strip_removes_prefix() {
99        assert_eq!(strip("/dashboard", "/dashboard"), "/");
100        assert_eq!(strip("/dashboard/", "/dashboard"), "/");
101        assert_eq!(strip("/dashboard/api/stats", "/dashboard"), "/api/stats");
102        assert_eq!(
103            strip("/dashboard/static/style.css", "/dashboard"),
104            "/static/style.css"
105        );
106    }
107
108    #[test]
109    fn strip_accepts_already_rootrelative() {
110        // Reverse proxy already stripped the prefix (or direct local access).
111        assert_eq!(strip("/api/stats", "/dashboard"), "/api/stats");
112        assert_eq!(strip("/", "/dashboard"), "/");
113    }
114
115    #[test]
116    fn strip_does_not_match_partial_segment() {
117        // `/dashboardx` must NOT be treated as `/dashboard` + `x`.
118        assert_eq!(strip("/dashboardx/api", "/dashboard"), "/dashboardx/api");
119    }
120
121    #[test]
122    fn rewrite_empty_base_is_noop() {
123        let html = r#"<script src="/static/lib/api.js"></script>"#;
124        assert_eq!(rewrite_asset_urls(html, ""), html);
125    }
126
127    #[test]
128    fn rewrite_html_attributes() {
129        let html = r#"<link href="/static/style.css"><script src="/static/lib/api.js"></script><link rel="icon" href="/favicon.svg">"#;
130        let out = rewrite_asset_urls(html, "/dashboard");
131        assert!(out.contains(r#"href="/dashboard/static/style.css""#));
132        assert!(out.contains(r#"src="/dashboard/static/lib/api.js""#));
133        assert!(out.contains(r#"href="/dashboard/favicon.svg""#));
134        assert!(!out.contains(r#"href="/static/"#));
135    }
136
137    #[test]
138    fn rewrite_js_string_and_template_literals() {
139        let js = "fetch('/api/stats'); const u = `/api/search?q=${q}`; api('/api/pulse');";
140        let out = rewrite_asset_urls(js, "/dashboard");
141        assert!(out.contains("fetch('/dashboard/api/stats')"));
142        assert!(out.contains("`/dashboard/api/search?q=${q}`"));
143        assert!(out.contains("api('/dashboard/api/pulse')"));
144    }
145
146    #[test]
147    fn rewrite_css_url() {
148        let css = "src: url('/static/fonts/inter-variable.woff2');";
149        let out = rewrite_asset_urls(css, "/dashboard");
150        assert!(out.contains("url('/dashboard/static/fonts/inter-variable.woff2')"));
151    }
152
153    #[test]
154    fn rewrite_fetch_interceptor_guard() {
155        // The HTML interceptor checks `url.startsWith('/api/')`; after rewrite it
156        // must check the prefixed form so Bearer auth still attaches.
157        let js = "if (url.startsWith('/api/')) attachToken();";
158        let out = rewrite_asset_urls(js, "/dashboard");
159        assert!(out.contains("url.startsWith('/dashboard/api/')"));
160    }
161
162    #[test]
163    fn rewrite_does_not_double_prefix() {
164        let html = r#"<script src="/static/x.js"></script>"#;
165        let once = rewrite_asset_urls(html, "/dashboard");
166        // Re-running would double-prefix only if source already had the base; the
167        // canonical source never does, so a single pass is correct and stable.
168        assert_eq!(once.matches("/dashboard/static/x.js").count(), 1);
169        assert!(!once.contains("/dashboard/dashboard/"));
170    }
171}