1use axum::body::Body;
12use axum::extract::OriginalUri;
13use axum::http::{Method, StatusCode, header};
14use axum::response::{IntoResponse, Response};
15use include_dir::{Dir, include_dir};
16use percent_encoding::percent_decode_str;
17
18static CONSOLE: Dir<'static> = include_dir!("$OUT_DIR/console");
19
20pub fn console_is_stub() -> bool {
25 option_env!("WARATAH_CONSOLE_STUB").is_some()
26}
27
28pub fn console_missing_worker() -> bool {
34 option_env!("WARATAH_CONSOLE_MISSING_SW").is_some()
35}
36
37#[allow(clippy::unused_async)]
47pub(crate) async fn console_fallback(method: Method, OriginalUri(uri): OriginalUri) -> Response {
48 if method != Method::GET && method != Method::HEAD {
49 return StatusCode::NOT_FOUND.into_response();
50 }
51 let Some(path) = normalize_console_path(uri.path()) else {
52 return StatusCode::NOT_FOUND.into_response();
53 };
54 if is_api_path(&path) {
55 return StatusCode::NOT_FOUND.into_response();
56 }
57
58 let key = path.trim_start_matches('/');
59 if !key.is_empty()
60 && let Some(bytes) = console_file(key)
61 {
62 return file_response(key, bytes, &method);
63 }
64 if is_reserved_static(&path) {
67 return StatusCode::NOT_FOUND.into_response();
68 }
69
70 match console_file("index.html") {
71 Some(bytes) => file_response("index.html", bytes, &method),
72 None => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
73 }
74}
75
76fn console_file(key: &str) -> Option<&'static [u8]> {
77 CONSOLE.get_file(key).map(|file| file.contents())
78}
79
80fn is_api_path(path: &str) -> bool {
81 path == "/rdf4j"
82 || path.starts_with("/rdf4j/")
83 || path == "/waratah"
84 || path.starts_with("/waratah/")
85 || path == "/cors_proxy"
86 || path.starts_with("/cors_proxy/")
87 || path == "/jupyter"
88 || path.starts_with("/jupyter/")
89}
90
91fn is_reserved_static(path: &str) -> bool {
92 path == "/assets"
93 || path.starts_with("/assets/")
94 || path == "/sw.js"
95 || path == "/download"
96 || path.starts_with("/download/")
97}
98
99fn file_response(key: &str, bytes: &'static [u8], method: &Method) -> Response {
100 let body = if *method == Method::HEAD {
101 Body::empty()
102 } else {
103 Body::from(bytes)
104 };
105 Response::builder()
106 .status(StatusCode::OK)
107 .header(header::CONTENT_TYPE, mime_for(key))
108 .header(header::CACHE_CONTROL, cache_control(key))
109 .header(header::CONTENT_LENGTH, bytes.len().to_string())
110 .body(body)
111 .expect("console response headers are valid")
112}
113
114fn cache_control(key: &str) -> &'static str {
115 if key.starts_with("assets/") {
116 "public, max-age=31536000, immutable"
117 } else {
118 "no-cache"
120 }
121}
122
123fn mime_for(key: &str) -> &'static str {
124 match key.rsplit('.').next().unwrap_or("") {
125 "html" | "htm" => "text/html; charset=utf-8",
126 "js" | "mjs" => "application/javascript",
127 "css" => "text/css",
128 "json" | "map" => "application/json",
129 "png" => "image/png",
130 "jpg" | "jpeg" => "image/jpeg",
131 "gif" => "image/gif",
132 "webp" => "image/webp",
133 "svg" => "image/svg+xml",
134 "ico" => "image/x-icon",
135 "woff2" => "font/woff2",
136 "woff" => "font/woff",
137 "ttf" => "font/ttf",
138 "txt" => "text/plain; charset=utf-8",
139 "wasm" => "application/wasm",
140 _ => "application/octet-stream",
141 }
142}
143
144fn normalize_console_path(raw: &str) -> Option<String> {
148 if raw.contains('\0') {
149 return None;
150 }
151 let decoded = percent_decode_str(raw).decode_utf8().ok()?;
152 if decoded.contains('\0') || decoded.contains('\\') || !decoded.starts_with('/') {
153 return None;
154 }
155 let trimmed = decoded.trim_end_matches('/');
156 let path = if trimmed.is_empty() { "/" } else { trimmed };
157 if path.split('/').any(|segment| segment == "..") {
158 return None;
159 }
160 Some(path.to_string())
161}
162
163#[cfg(test)]
164mod tests {
165 use super::{cache_control, mime_for, normalize_console_path};
166
167 #[test]
168 fn cache_and_mime_follow_the_console_contract() {
169 assert_eq!(cache_control("index.html"), "no-cache");
170 assert_eq!(cache_control("sw.js"), "no-cache");
171 assert_eq!(cache_control("favicon.ico"), "no-cache");
172 assert_eq!(
173 cache_control("assets/index-abc.js"),
174 "public, max-age=31536000, immutable"
175 );
176 assert_eq!(
177 cache_control("assets/mark.woff2"),
178 "public, max-age=31536000, immutable"
179 );
180 assert_eq!(mime_for("sw.js"), "application/javascript");
181 assert_eq!(mime_for("assets/index-abc.js"), "application/javascript");
182 assert_eq!(mime_for("assets/index-abc.css"), "text/css");
183 assert_eq!(mime_for("assets/mark.woff2"), "font/woff2");
184 assert_eq!(mime_for("assets/mark.png"), "image/png");
185 assert_eq!(mime_for("favicon.ico"), "image/x-icon");
186 assert_eq!(mime_for("index.html"), "text/html; charset=utf-8");
187 }
188
189 #[test]
190 fn normalize_strips_a_trailing_slash_and_rejects_traversal() {
191 assert_eq!(normalize_console_path("/").as_deref(), Some("/"));
192 assert_eq!(
193 normalize_console_path("/sparql/").as_deref(),
194 Some("/sparql")
195 );
196 assert_eq!(normalize_console_path("///").as_deref(), Some("/"));
197 assert!(normalize_console_path("/assets/../../etc/passwd").is_none());
198 assert!(normalize_console_path("/assets/%2e%2e/secret.js").is_none());
199 assert!(normalize_console_path("/%2e%2e/%2e%2e/etc/passwd").is_none());
200 assert!(normalize_console_path("/foo%00bar").is_none());
201 assert!(normalize_console_path("/assets/..\\secret.js").is_none());
202 }
203}