| 1 | //! Embedded, loopback-only browser client for the Runtime API. |
| 2 | |
| 3 | use codewhale_core::secret_eq::constant_time_eq; |
| 4 | use std::fs; |
| 5 | use std::io::Read as _; |
| 6 | use std::net::{IpAddr, SocketAddr}; |
| 7 | use std::path::{Component, Path as FsPath, PathBuf}; |
| 8 | use std::sync::{Arc, Mutex}; |
| 9 | use std::time::{Duration, Instant}; |
| 10 | |
| 11 | use base64::Engine as _; |
| 12 | use sha2::{Digest, Sha256}; |
| 13 | |
| 14 | use axum::Json; |
| 15 | use axum::body::Body; |
| 16 | use axum::extract::{ConnectInfo, Path, Request, State}; |
| 17 | use axum::http::{HeaderValue, Method, StatusCode, header}; |
| 18 | use axum::response::{IntoResponse, Response}; |
| 19 | use uuid::Uuid; |
| 20 | |
| 21 | use super::RuntimeApiState; |
| 22 | |
| 23 | const WEB_HTML: &str = include_str!("../runtime_web/index.html"); |
| 24 | const WEB_CSS: &str = include_str!("../runtime_web/styles.css"); |
| 25 | const WEB_JS: &str = include_str!("../runtime_web/app.mjs"); |
| 26 | const WEB_ICON: &[u8] = include_bytes!("../runtime_web/codewhale-192.png"); |
| 27 | pub(super) const WEB_DIST_ENV: &str = "CODEWHALE_WEB_DIST"; |
| 28 | const MAX_WEB_DIST_ASSET_BYTES: usize = 16 * 1024 * 1024; |
| 29 | // The nonce remains single-use and loopback-only, but it is handed to a |
| 30 | // person through the browser launcher or terminal. Two minutes proved too |
| 31 | // short when the launcher was delayed or did not open a tab. |
| 32 | pub(super) const BOOTSTRAP_TTL: Duration = Duration::from_secs(10 * 60); |
| 33 | const WEB_SESSION_TTL: Duration = Duration::from_secs(12 * 60 * 60); |
| 34 | const BOOTSTRAP_PREFIX: &str = "cwwb_"; |
| 35 | const WEB_SESSION_PREFIX: &str = "cwws_"; |
| 36 | pub(super) const WEB_REQUEST_HEADER: &str = "x-codewhale-web-request"; |
| 37 | pub(super) const WEB_STREAM_TICKET_QUERY: &str = "web_stream_ticket"; |
| 38 | pub(super) const WEB_SESSION_COOKIE_NAME: &str = "codewhale_web_session"; |
| 39 | const CONTENT_SECURITY_POLICY: &str = "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'; object-src 'none'"; |
| 40 | const APP_WEB_CONTENT_SECURITY_POLICY: &str = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; worker-src 'self'; font-src 'self'; img-src 'self' data: blob:; connect-src 'self'; media-src blob:; object-src 'none'; base-uri 'none'; form-action 'none'; frame-src 'self'; frame-ancestors 'none'"; |
| 41 | const PLUGIN_HOST_CONTENT_SECURITY_POLICY: &str = "default-src 'none'; script-src 'self' blob:; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob:; font-src 'self' data:; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-src 'none'; frame-ancestors 'self'; sandbox allow-scripts"; |
| 42 | const SVG_CONTENT_SECURITY_POLICY: &str = "default-src 'none'; style-src 'unsafe-inline'; sandbox"; |
| 43 | |
| 44 | #[derive(Clone)] |
| 45 | pub(super) struct RuntimeWebState { |
| 46 | bootstrap: Arc<Mutex<Option<BootstrapCapability>>>, |
| 47 | session_token: Arc<str>, |
| 48 | request_proof: Arc<Mutex<Option<String>>>, |
| 49 | stream_tickets: Arc<Mutex<Vec<BootstrapCapability>>>, |
| 50 | session_expires_at: Instant, |
| 51 | web_dist_dir: Option<Arc<PathBuf>>, |
| 52 | } |
| 53 | |
| 54 | struct BootstrapCapability { |
| 55 | nonce: String, |
| 56 | expires_at: Instant, |
| 57 | } |
| 58 | |
| 59 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 60 | pub(super) enum BootstrapError { |
| 61 | Invalid, |
| 62 | Expired, |
| 63 | NonLoopback, |
| 64 | } |
| 65 | |
| 66 | impl RuntimeWebState { |
| 67 | pub(super) fn new() -> (Self, String) { |
| 68 | Self::new_with_dist(configured_web_dist().ok().flatten()) |
| 69 | } |
| 70 | |
| 71 | pub(super) fn dist_dir(&self) -> Option<&FsPath> { |
| 72 | self.web_dist_dir.as_deref().map(PathBuf::as_path) |
| 73 | } |
| 74 | |
| 75 | pub(super) fn new_with_dist(web_dist_dir: Option<PathBuf>) -> (Self, String) { |
| 76 | Self::new_with_ttls_and_dist(BOOTSTRAP_TTL, WEB_SESSION_TTL, web_dist_dir) |
| 77 | } |
| 78 | |
| 79 | #[cfg(test)] |
| 80 | fn new_with_ttls(bootstrap_ttl: Duration, session_ttl: Duration) -> (Self, String) { |
| 81 | Self::new_with_ttls_and_dist(bootstrap_ttl, session_ttl, None) |
| 82 | } |
| 83 | |
| 84 | fn new_with_ttls_and_dist( |
| 85 | bootstrap_ttl: Duration, |
| 86 | session_ttl: Duration, |
| 87 | web_dist_dir: Option<PathBuf>, |
| 88 | ) -> (Self, String) { |
| 89 | let nonce = format!("{BOOTSTRAP_PREFIX}{}", Uuid::new_v4().simple()); |
| 90 | let session_token = format!( |
| 91 | "{WEB_SESSION_PREFIX}{}{}", |
| 92 | Uuid::new_v4().simple(), |
| 93 | Uuid::new_v4().simple() |
| 94 | ); |
| 95 | let validated_dist = web_dist_dir |
| 96 | .as_deref() |
| 97 | .and_then(|dir| validate_web_dist_dir(dir).ok()) |
| 98 | .map(Arc::new); |
| 99 | let state = Self { |
| 100 | bootstrap: Arc::new(Mutex::new(Some(BootstrapCapability { |
| 101 | nonce: nonce.clone(), |
| 102 | expires_at: Instant::now() + bootstrap_ttl, |
| 103 | }))), |
| 104 | session_token: session_token.into(), |
| 105 | request_proof: Arc::new(Mutex::new(None)), |
| 106 | stream_tickets: Arc::new(Mutex::new(Vec::new())), |
| 107 | session_expires_at: Instant::now() + session_ttl, |
| 108 | web_dist_dir: validated_dist, |
| 109 | }; |
| 110 | (state, nonce) |
| 111 | } |
| 112 | |
| 113 | pub(super) fn consume( |
| 114 | &self, |
| 115 | nonce: &str, |
| 116 | peer_ip: IpAddr, |
| 117 | ) -> Result<(String, String), BootstrapError> { |
| 118 | if !peer_ip.is_loopback() { |
| 119 | return Err(BootstrapError::NonLoopback); |
| 120 | } |
| 121 | if !valid_bootstrap_nonce(nonce) { |
| 122 | return Err(BootstrapError::Invalid); |
| 123 | } |
| 124 | |
| 125 | let mut slot = self |
| 126 | .bootstrap |
| 127 | .lock() |
| 128 | .unwrap_or_else(|poisoned| poisoned.into_inner()); |
| 129 | let Some(capability) = slot.as_ref() else { |
| 130 | return Err(BootstrapError::Invalid); |
| 131 | }; |
| 132 | if Instant::now() >= capability.expires_at { |
| 133 | *slot = None; |
| 134 | return Err(BootstrapError::Expired); |
| 135 | } |
| 136 | if !constant_time_eq(nonce.as_bytes(), capability.nonce.as_bytes()) { |
| 137 | return Err(BootstrapError::Invalid); |
| 138 | } |
| 139 | |
| 140 | let _capability = slot.take().expect("bootstrap capability checked above"); |
| 141 | let proof = format!( |
| 142 | "cwwr_{}{}", |
| 143 | Uuid::new_v4().simple(), |
| 144 | Uuid::new_v4().simple() |
| 145 | ); |
| 146 | *self.request_proof.lock().unwrap_or_else(|p| p.into_inner()) = Some(proof.clone()); |
| 147 | Ok((self.session_token.to_string(), proof)) |
| 148 | } |
| 149 | |
| 150 | pub(super) fn matches_request(&self, cookie_header: Option<&str>, proof: Option<&str>) -> bool { |
| 151 | self.matches_session_cookie(cookie_header) |
| 152 | && proof.is_some_and(|proof| { |
| 153 | self.request_proof |
| 154 | .lock() |
| 155 | .unwrap_or_else(|p| p.into_inner()) |
| 156 | .as_ref() |
| 157 | .is_some_and(|expected| constant_time_eq(proof.as_bytes(), expected.as_bytes())) |
| 158 | }) |
| 159 | } |
| 160 | |
| 161 | // Reconnects consume short-lived, single-use tickets. Retain up to 32 |
| 162 | // pending tickets so independent tabs do not replace each other's ticket; |
| 163 | // excess requests evict the oldest pending ticket. |
| 164 | pub(super) fn refresh_stream_ticket( |
| 165 | &self, |
| 166 | cookie_header: Option<&str>, |
| 167 | proof: Option<&str>, |
| 168 | ) -> Option<String> { |
| 169 | if !self.matches_request(cookie_header, proof) { |
| 170 | return None; |
| 171 | } |
| 172 | let ticket = format!( |
| 173 | "cwwt_{}{}", |
| 174 | Uuid::new_v4().simple(), |
| 175 | Uuid::new_v4().simple() |
| 176 | ); |
| 177 | let mut tickets = self |
| 178 | .stream_tickets |
| 179 | .lock() |
| 180 | .unwrap_or_else(|p| p.into_inner()); |
| 181 | let now = Instant::now(); |
| 182 | tickets.retain(|issued| now < issued.expires_at); |
| 183 | if tickets.len() == 32 { |
| 184 | tickets.remove(0); |
| 185 | } |
| 186 | tickets.push(BootstrapCapability { |
| 187 | nonce: ticket.clone(), |
| 188 | expires_at: now + super::mobile::STREAM_TICKET_TTL, |
| 189 | }); |
| 190 | Some(ticket) |
| 191 | } |
| 192 | |
| 193 | pub(super) fn consume_stream_ticket( |
| 194 | &self, |
| 195 | cookie_header: Option<&str>, |
| 196 | ticket: Option<&str>, |
| 197 | ) -> bool { |
| 198 | if !self.matches_session_cookie(cookie_header) { |
| 199 | return false; |
| 200 | } |
| 201 | let mut tickets = self |
| 202 | .stream_tickets |
| 203 | .lock() |
| 204 | .unwrap_or_else(|p| p.into_inner()); |
| 205 | let now = Instant::now(); |
| 206 | tickets.retain(|issued| now < issued.expires_at); |
| 207 | let Some(index) = tickets.iter().position(|issued| { |
| 208 | ticket |
| 209 | .is_some_and(|ticket| constant_time_eq(ticket.as_bytes(), issued.nonce.as_bytes())) |
| 210 | }) else { |
| 211 | return false; |
| 212 | }; |
| 213 | tickets.remove(index); |
| 214 | true |
| 215 | } |
| 216 | |
| 217 | pub(super) fn matches_session_cookie(&self, cookie_header: Option<&str>) -> bool { |
| 218 | let presented = cookie_value(cookie_header, WEB_SESSION_COOKIE_NAME).unwrap_or_default(); |
| 219 | let token_matches = constant_time_eq(presented.as_bytes(), self.session_token.as_bytes()); |
| 220 | token_matches & (Instant::now() < self.session_expires_at) |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | pub(super) fn bootstrap_url(addr: SocketAddr, nonce: &str) -> String { |
| 225 | format!("http://{addr}/__codewhale/bootstrap/{nonce}") |
| 226 | } |
| 227 | |
| 228 | pub(super) async fn exchange_bootstrap( |
| 229 | State(state): State<RuntimeApiState>, |
| 230 | ConnectInfo(peer): ConnectInfo<SocketAddr>, |
| 231 | Path(nonce): Path<String>, |
| 232 | ) -> Response { |
| 233 | let Some(web) = state.web.as_ref() else { |
| 234 | return not_found(); |
| 235 | }; |
| 236 | let (session_token, request_proof) = match web.consume(&nonce, peer.ip()) { |
| 237 | Ok(token) => token, |
| 238 | Err(BootstrapError::NonLoopback) => { |
| 239 | return secured_text(StatusCode::FORBIDDEN, "bootstrap unavailable"); |
| 240 | } |
| 241 | Err(BootstrapError::Invalid | BootstrapError::Expired) => { |
| 242 | return secured_text(StatusCode::UNAUTHORIZED, "bootstrap unavailable"); |
| 243 | } |
| 244 | }; |
| 245 | |
| 246 | let cookie = web_session_cookie(&session_token); |
| 247 | let mut response = (StatusCode::SEE_OTHER, "").into_response(); |
| 248 | response.headers_mut().insert( |
| 249 | header::LOCATION, |
| 250 | HeaderValue::from_str(&format!("/#p={request_proof}")).expect("hex request proof"), |
| 251 | ); |
| 252 | response.headers_mut().insert( |
| 253 | header::SET_COOKIE, |
| 254 | HeaderValue::from_str(&cookie).expect("percent-encoded Runtime cookie is a valid header"), |
| 255 | ); |
| 256 | secure_headers(&mut response, "text/plain; charset=utf-8"); |
| 257 | response |
| 258 | } |
| 259 | |
| 260 | pub(super) async fn refresh_stream_ticket( |
| 261 | State(state): State<RuntimeApiState>, |
| 262 | req: Request, |
| 263 | ) -> Response { |
| 264 | let Some(web) = state.web.as_ref() else { |
| 265 | return not_found(); |
| 266 | }; |
| 267 | if !super::auth::web_session_request_is_authorized(&req, &state, web) { |
| 268 | return super::auth::runtime_token_required_response(); |
| 269 | } |
| 270 | let ticket = web.refresh_stream_ticket( |
| 271 | req.headers() |
| 272 | .get(header::COOKIE) |
| 273 | .and_then(|v| v.to_str().ok()), |
| 274 | req.headers() |
| 275 | .get(WEB_REQUEST_HEADER) |
| 276 | .and_then(|v| v.to_str().ok()), |
| 277 | ); |
| 278 | let Some(ticket) = ticket else { |
| 279 | return super::auth::runtime_token_required_response(); |
| 280 | }; |
| 281 | let mut response = Json(serde_json::json!({"stream_ticket": ticket})).into_response(); |
| 282 | secure_headers(&mut response, "application/json"); |
| 283 | response |
| 284 | } |
| 285 | |
| 286 | pub(super) async fn web_page(State(state): State<RuntimeApiState>) -> Response { |
| 287 | let Some(web) = state.web.as_ref() else { |
| 288 | return not_found(); |
| 289 | }; |
| 290 | if let Some(dist_dir) = web.web_dist_dir.clone() { |
| 291 | return serve_dist_html_async(dist_dir, "index.html", APP_WEB_CONTENT_SECURITY_POLICY) |
| 292 | .await; |
| 293 | } |
| 294 | web_page_response() |
| 295 | } |
| 296 | |
| 297 | pub(super) async fn web_fallback(State(state): State<RuntimeApiState>, req: Request) -> Response { |
| 298 | let Some(dist_dir) = state.web.as_ref().and_then(|web| web.web_dist_dir.clone()) else { |
| 299 | return not_found(); |
| 300 | }; |
| 301 | serve_web_dist_request(dist_dir, req).await |
| 302 | } |
| 303 | |
| 304 | async fn serve_web_dist_request(dist_dir: Arc<PathBuf>, req: Request) -> Response { |
| 305 | if !matches!(*req.method(), Method::GET | Method::HEAD) { |
| 306 | return not_found(); |
| 307 | } |
| 308 | let raw_path = req.uri().path(); |
| 309 | if is_reserved_runtime_path(raw_path) { |
| 310 | return not_found(); |
| 311 | } |
| 312 | if raw_path == "/widget-host.html" { |
| 313 | return serve_widget_host(dist_dir).await; |
| 314 | } |
| 315 | let rel = raw_path.trim_start_matches('/'); |
| 316 | if rel.is_empty() || rel.eq_ignore_ascii_case("index.html") { |
| 317 | return serve_dist_html_async(dist_dir, "index.html", APP_WEB_CONTENT_SECURITY_POLICY) |
| 318 | .await; |
| 319 | } |
| 320 | if rel.eq_ignore_ascii_case("plugin-host.html") { |
| 321 | return serve_dist_html_async( |
| 322 | dist_dir, |
| 323 | "plugin-host.html", |
| 324 | PLUGIN_HOST_CONTENT_SECURITY_POLICY, |
| 325 | ) |
| 326 | .await; |
| 327 | } |
| 328 | let Some(clean_rel) = sanitize_dist_relative_path(rel) else { |
| 329 | return not_found(); |
| 330 | }; |
| 331 | // Refuse any other .html file from the generic static-asset branch so |
| 332 | // case-insensitive filesystems or arbitrary HTML files can never bypass |
| 333 | // the exact CSP assigned to index.html / plugin-host.html. |
| 334 | if clean_rel |
| 335 | .extension() |
| 336 | .and_then(|ext| ext.to_str()) |
| 337 | .is_some_and(|ext| ext.eq_ignore_ascii_case("html") || ext.eq_ignore_ascii_case("htm")) |
| 338 | { |
| 339 | return not_found(); |
| 340 | } |
| 341 | let is_immutable = rel.starts_with("static/"); |
| 342 | let is_spa_candidate = |
| 343 | clean_rel.extension().is_none() && !is_immutable && !rel.starts_with("assets/"); |
| 344 | let content_type = content_type_for_path(&clean_rel); |
| 345 | if let Some(content_type) = content_type { |
| 346 | let root = Arc::clone(&dist_dir); |
| 347 | let rel_path = clean_rel.clone(); |
| 348 | let bytes = tokio::task::spawn_blocking(move || read_confined_dist_file(&root, &rel_path)) |
| 349 | .await |
| 350 | .ok() |
| 351 | .flatten(); |
| 352 | if let Some(bytes) = bytes { |
| 353 | let csp = if content_type == "image/svg+xml" { |
| 354 | SVG_CONTENT_SECURITY_POLICY |
| 355 | } else { |
| 356 | CONTENT_SECURITY_POLICY |
| 357 | }; |
| 358 | let mut response = Response::new(Body::from(bytes)); |
| 359 | secure_headers_with_policy( |
| 360 | &mut response, |
| 361 | content_type, |
| 362 | csp, |
| 363 | if is_immutable { |
| 364 | "public, max-age=31536000, immutable" |
| 365 | } else { |
| 366 | "no-store" |
| 367 | }, |
| 368 | ); |
| 369 | if is_immutable { |
| 370 | response.headers_mut().insert( |
| 371 | header::ACCESS_CONTROL_ALLOW_ORIGIN, |
| 372 | HeaderValue::from_static("*"), |
| 373 | ); |
| 374 | } |
| 375 | return response; |
| 376 | } |
| 377 | return not_found(); |
| 378 | } |
| 379 | // Bounded SPA fallback: serve index.html only for extensionless app routes. |
| 380 | if is_spa_candidate { |
| 381 | return serve_dist_html_async(dist_dir, "index.html", APP_WEB_CONTENT_SECURITY_POLICY) |
| 382 | .await; |
| 383 | } |
| 384 | not_found() |
| 385 | } |
| 386 | |
| 387 | pub(super) fn configured_web_dist() -> Result<Option<PathBuf>, String> { |
| 388 | checked_web_dist(std::env::var_os(WEB_DIST_ENV)) |
| 389 | } |
| 390 | |
| 391 | pub(super) fn attached_web_dist_mismatch( |
| 392 | requested: Option<&FsPath>, |
| 393 | served: Option<&FsPath>, |
| 394 | ) -> Option<String> { |
| 395 | let requested = requested?; |
| 396 | if served == Some(requested) { |
| 397 | return None; |
| 398 | } |
| 399 | let serving = match served { |
| 400 | Some(dir) => format!("the app build at {}", dir.display()), |
| 401 | None => "the embedded client".to_string(), |
| 402 | }; |
| 403 | Some(format!( |
| 404 | "{WEB_DIST_ENV}={} was not applied: a Codewhale that is already running serves the web client, and it is serving {serving}. Quit the running Codewhale and start `codewhale web` again, or unset {WEB_DIST_ENV} to use what it serves.", |
| 405 | requested.display() |
| 406 | )) |
| 407 | } |
| 408 | |
| 409 | fn checked_web_dist(raw: Option<std::ffi::OsString>) -> Result<Option<PathBuf>, String> { |
| 410 | let Some(raw) = raw.filter(|raw| !raw.is_empty()) else { |
| 411 | return Ok(None); |
| 412 | }; |
| 413 | let dir = PathBuf::from(raw); |
| 414 | validate_web_dist_dir(&dir).map(Some).map_err(|reason| { |
| 415 | format!( |
| 416 | "{WEB_DIST_ENV}={} cannot be served: {reason}. Point it at a built web app directory, or unset it to use the embedded client.", |
| 417 | dir.display() |
| 418 | ) |
| 419 | }) |
| 420 | } |
| 421 | |
| 422 | fn validate_web_dist_dir(dir: &FsPath) -> Result<PathBuf, String> { |
| 423 | let meta = fs::symlink_metadata(dir).map_err(|error| format!("cannot read it ({error})"))?; |
| 424 | if meta.file_type().is_symlink() { |
| 425 | return Err("it is a symbolic link; give the real directory".to_string()); |
| 426 | } |
| 427 | if !meta.is_dir() { |
| 428 | return Err("it is not a directory".to_string()); |
| 429 | } |
| 430 | let canonical = |
| 431 | fs::canonicalize(dir).map_err(|error| format!("cannot resolve it ({error})"))?; |
| 432 | let index_meta = fs::symlink_metadata(canonical.join("index.html")) |
| 433 | .map_err(|error| format!("it has no readable index.html ({error})"))?; |
| 434 | if index_meta.file_type().is_symlink() { |
| 435 | return Err("its index.html is a symbolic link".to_string()); |
| 436 | } |
| 437 | if !index_meta.is_file() { |
| 438 | return Err("its index.html is not a file".to_string()); |
| 439 | } |
| 440 | Ok(canonical) |
| 441 | } |
| 442 | |
| 443 | fn is_reserved_runtime_path(path: &str) -> bool { |
| 444 | path == "/v1" |
| 445 | || path.starts_with("/v1/") |
| 446 | || path == "/api" |
| 447 | || path.starts_with("/api/") |
| 448 | || path == "/__codewhale" |
| 449 | || path.starts_with("/__codewhale/") |
| 450 | || path == "/health" |
| 451 | || path == "/mobile" |
| 452 | || path.starts_with("/mobile/") |
| 453 | } |
| 454 | |
| 455 | fn sanitize_dist_relative_path(rel: &str) -> Option<PathBuf> { |
| 456 | if rel.is_empty() |
| 457 | || rel.len() > 512 |
| 458 | || rel.contains('\\') |
| 459 | || rel.bytes().any(|b| b < 0x20 || b == 0x7f) |
| 460 | { |
| 461 | return None; |
| 462 | } |
| 463 | let mut out = PathBuf::new(); |
| 464 | for part in rel.split('/') { |
| 465 | if part.is_empty() || part == "." || part == ".." || part.starts_with('.') { |
| 466 | return None; |
| 467 | } |
| 468 | let mut comps = FsPath::new(part).components(); |
| 469 | match (comps.next(), comps.next()) { |
| 470 | (Some(Component::Normal(seg)), None) => out.push(seg), |
| 471 | _ => return None, |
| 472 | } |
| 473 | } |
| 474 | (!out.as_os_str().is_empty()).then_some(out) |
| 475 | } |
| 476 | |
| 477 | fn read_confined_dist_file(root: &FsPath, rel: &FsPath) -> Option<Vec<u8>> { |
| 478 | let mut current = root.to_path_buf(); |
| 479 | for component in rel.components() { |
| 480 | let Component::Normal(seg) = component else { |
| 481 | return None; |
| 482 | }; |
| 483 | current.push(seg); |
| 484 | let meta = fs::symlink_metadata(¤t).ok()?; |
| 485 | if meta.file_type().is_symlink() { |
| 486 | return None; |
| 487 | } |
| 488 | } |
| 489 | let meta = fs::symlink_metadata(¤t).ok()?; |
| 490 | if !meta.is_file() || meta.len() > MAX_WEB_DIST_ASSET_BYTES as u64 { |
| 491 | return None; |
| 492 | } |
| 493 | let canonical = fs::canonicalize(¤t).ok()?; |
| 494 | if !canonical.starts_with(root) { |
| 495 | return None; |
| 496 | } |
| 497 | let file = fs::File::open(&canonical).ok()?; |
| 498 | let mut buf = Vec::new(); |
| 499 | file.take(MAX_WEB_DIST_ASSET_BYTES as u64 + 1) |
| 500 | .read_to_end(&mut buf) |
| 501 | .ok()?; |
| 502 | if buf.len() > MAX_WEB_DIST_ASSET_BYTES { |
| 503 | return None; |
| 504 | } |
| 505 | Some(buf) |
| 506 | } |
| 507 | |
| 508 | fn widget_policy(document: &[u8]) -> Option<HeaderValue> { |
| 509 | let html = std::str::from_utf8(document).ok()?; |
| 510 | let (head, rest) = html.split_once("<script>")?; |
| 511 | let (bootstrap, _) = rest.split_once("</script>")?; |
| 512 | let digest = |
| 513 | base64::engine::general_purpose::STANDARD.encode(Sha256::digest(bootstrap.as_bytes())); |
| 514 | let script = format!("script-src 'sha256-{digest}';"); |
| 515 | if !head.contains(&script) { |
| 516 | return None; |
| 517 | } |
| 518 | HeaderValue::from_str(&format!("default-src 'none'; {script} style-src 'unsafe-inline'; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-src 'none'; frame-ancestors 'self'; sandbox allow-scripts")).ok() |
| 519 | } |
| 520 | |
| 521 | async fn serve_widget_host(root: Arc<PathBuf>) -> Response { |
| 522 | let result = tokio::task::spawn_blocking(move || { |
| 523 | let bytes = read_confined_dist_file(&root, FsPath::new("widget-host.html"))?; |
| 524 | let policy = widget_policy(&bytes)?; |
| 525 | Some((bytes, policy)) |
| 526 | }) |
| 527 | .await; |
| 528 | let Ok(Some((bytes, policy))) = result else { |
| 529 | return not_found(); |
| 530 | }; |
| 531 | let mut response = Response::new(Body::from(bytes)); |
| 532 | secure_headers(&mut response, "text/html; charset=utf-8"); |
| 533 | response |
| 534 | .headers_mut() |
| 535 | .insert(header::CONTENT_SECURITY_POLICY, policy); |
| 536 | response |
| 537 | } |
| 538 | |
| 539 | async fn serve_dist_html_async( |
| 540 | root: Arc<PathBuf>, |
| 541 | file_name: &'static str, |
| 542 | csp: &'static str, |
| 543 | ) -> Response { |
| 544 | let bytes = |
| 545 | tokio::task::spawn_blocking(move || read_confined_dist_file(&root, FsPath::new(file_name))) |
| 546 | .await |
| 547 | .ok() |
| 548 | .flatten(); |
| 549 | let Some(bytes) = bytes else { |
| 550 | return not_found(); |
| 551 | }; |
| 552 | let mut response = Response::new(Body::from(bytes)); |
| 553 | secure_headers_with_policy(&mut response, "text/html; charset=utf-8", csp, "no-store"); |
| 554 | response |
| 555 | } |
| 556 | |
| 557 | fn content_type_for_path(path: &FsPath) -> Option<&'static str> { |
| 558 | let ext = path.extension()?.to_str()?.to_ascii_lowercase(); |
| 559 | match ext.as_str() { |
| 560 | "js" | "mjs" => Some("text/javascript; charset=utf-8"), |
| 561 | "css" => Some("text/css; charset=utf-8"), |
| 562 | "svg" => Some("image/svg+xml"), |
| 563 | "png" => Some("image/png"), |
| 564 | "jpg" | "jpeg" => Some("image/jpeg"), |
| 565 | "webp" => Some("image/webp"), |
| 566 | "gif" => Some("image/gif"), |
| 567 | "ico" => Some("image/x-icon"), |
| 568 | "json" => Some("application/json; charset=utf-8"), |
| 569 | "webmanifest" => Some("application/manifest+json; charset=utf-8"), |
| 570 | "woff2" => Some("font/woff2"), |
| 571 | "woff" => Some("font/woff"), |
| 572 | "ttf" => Some("font/ttf"), |
| 573 | "wasm" => Some("application/wasm"), |
| 574 | "txt" => Some("text/plain; charset=utf-8"), |
| 575 | _ => None, |
| 576 | } |
| 577 | } |
| 578 | |
| 579 | fn web_page_response() -> Response { |
| 580 | secured_asset("text/html; charset=utf-8", WEB_HTML.to_owned()) |
| 581 | } |
| 582 | |
| 583 | pub(super) async fn web_styles(State(state): State<RuntimeApiState>) -> Response { |
| 584 | if state.web.is_none() { |
| 585 | return not_found(); |
| 586 | } |
| 587 | secured_asset("text/css; charset=utf-8", WEB_CSS) |
| 588 | } |
| 589 | |
| 590 | pub(super) async fn web_script(State(state): State<RuntimeApiState>) -> Response { |
| 591 | if state.web.is_none() { |
| 592 | return not_found(); |
| 593 | } |
| 594 | secured_asset("text/javascript; charset=utf-8", WEB_JS) |
| 595 | } |
| 596 | |
| 597 | pub(super) async fn web_icon(State(state): State<RuntimeApiState>) -> Response { |
| 598 | if state.web.is_none() { |
| 599 | return not_found(); |
| 600 | } |
| 601 | let mut response = Response::new(Body::from(WEB_ICON)); |
| 602 | secure_headers(&mut response, "image/png"); |
| 603 | response |
| 604 | } |
| 605 | |
| 606 | fn web_session_cookie(session_token: &str) -> String { |
| 607 | format!("{WEB_SESSION_COOKIE_NAME}={session_token}; HttpOnly; SameSite=Strict; Path=/") |
| 608 | } |
| 609 | |
| 610 | fn cookie_value<'a>(cookie_header: Option<&'a str>, name: &str) -> Option<&'a str> { |
| 611 | cookie_header.and_then(|cookie| { |
| 612 | cookie.split(';').find_map(|pair| { |
| 613 | let (key, value) = pair.trim().split_once('=')?; |
| 614 | (key == name).then_some(value.trim()) |
| 615 | }) |
| 616 | }) |
| 617 | } |
| 618 | |
| 619 | fn valid_bootstrap_nonce(value: &str) -> bool { |
| 620 | value.strip_prefix(BOOTSTRAP_PREFIX).is_some_and(|random| { |
| 621 | random.len() == 32 && random.bytes().all(|byte| byte.is_ascii_hexdigit()) |
| 622 | }) |
| 623 | } |
| 624 | |
| 625 | fn secured_asset(content_type: &'static str, body: impl IntoResponse) -> Response { |
| 626 | let mut response = body.into_response(); |
| 627 | secure_headers(&mut response, content_type); |
| 628 | response |
| 629 | } |
| 630 | |
| 631 | fn secured_text(status: StatusCode, body: &'static str) -> Response { |
| 632 | let mut response = (status, body).into_response(); |
| 633 | secure_headers(&mut response, "text/plain; charset=utf-8"); |
| 634 | response |
| 635 | } |
| 636 | |
| 637 | fn not_found() -> Response { |
| 638 | secured_text(StatusCode::NOT_FOUND, "not found") |
| 639 | } |
| 640 | |
| 641 | fn secure_headers(response: &mut Response, content_type: &'static str) { |
| 642 | secure_headers_with_policy(response, content_type, CONTENT_SECURITY_POLICY, "no-store"); |
| 643 | } |
| 644 | |
| 645 | fn secure_headers_with_policy( |
| 646 | response: &mut Response, |
| 647 | content_type: &'static str, |
| 648 | csp: &'static str, |
| 649 | cache_control: &'static str, |
| 650 | ) { |
| 651 | let headers = response.headers_mut(); |
| 652 | headers.insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type)); |
| 653 | headers.insert( |
| 654 | header::CACHE_CONTROL, |
| 655 | HeaderValue::from_static(cache_control), |
| 656 | ); |
| 657 | headers.insert( |
| 658 | header::CONTENT_SECURITY_POLICY, |
| 659 | HeaderValue::from_static(csp), |
| 660 | ); |
| 661 | headers.insert( |
| 662 | header::X_CONTENT_TYPE_OPTIONS, |
| 663 | HeaderValue::from_static("nosniff"), |
| 664 | ); |
| 665 | headers.insert( |
| 666 | header::REFERRER_POLICY, |
| 667 | HeaderValue::from_static("no-referrer"), |
| 668 | ); |
| 669 | headers.insert( |
| 670 | "permissions-policy", |
| 671 | HeaderValue::from_static("camera=(), microphone=(), geolocation=()"), |
| 672 | ); |
| 673 | } |
| 674 | |
| 675 | #[cfg(test)] |
| 676 | mod tests { |
| 677 | use super::*; |
| 678 | |
| 679 | #[test] |
| 680 | fn attaching_with_a_dist_the_running_owner_does_not_serve_is_refused() { |
| 681 | let asked = FsPath::new("/srv/app/dist"); |
| 682 | let other = FsPath::new("/srv/other/dist"); |
| 683 | assert_eq!(attached_web_dist_mismatch(None, None), None); |
| 684 | assert_eq!(attached_web_dist_mismatch(None, Some(other)), None); |
| 685 | assert_eq!(attached_web_dist_mismatch(Some(asked), Some(asked)), None); |
| 686 | let embedded = attached_web_dist_mismatch(Some(asked), None).expect("refused"); |
| 687 | assert!(embedded.contains("CODEWHALE_WEB_DIST=/srv/app/dist was not applied")); |
| 688 | assert!(embedded.contains("the embedded client")); |
| 689 | let different = attached_web_dist_mismatch(Some(asked), Some(other)).expect("refused"); |
| 690 | assert!(different.contains("the app build at /srv/other/dist")); |
| 691 | } |
| 692 | |
| 693 | #[test] |
| 694 | fn runtime_surface_hardening_web_proof_and_ticket_expiry() { |
| 695 | let (web, nonce) = RuntimeWebState::new(); |
| 696 | let (token, proof) = web.consume(&nonce, "127.0.0.1".parse().unwrap()).unwrap(); |
| 697 | let cookie = web_session_cookie(&token); |
| 698 | assert!(!cookie.contains(&proof)); |
| 699 | assert!(!web.matches_request(None, Some(&proof))); |
| 700 | assert!(!web.matches_request(Some(&cookie), Some(&token))); |
| 701 | assert!(web.matches_request(Some(&cookie), Some(&proof))); |
| 702 | let ticket = web |
| 703 | .refresh_stream_ticket(Some(&cookie), Some(&proof)) |
| 704 | .unwrap(); |
| 705 | assert!(!web.consume_stream_ticket(None, Some(&ticket))); |
| 706 | assert!(!web.consume_stream_ticket(Some(&cookie), Some("wrong-ticket"))); |
| 707 | web.stream_tickets.lock().unwrap()[0].expires_at = Instant::now(); |
| 708 | assert!(!web.consume_stream_ticket(Some(&cookie), Some(&ticket))); |
| 709 | let ticket = web |
| 710 | .refresh_stream_ticket(Some(&cookie), Some(&proof)) |
| 711 | .unwrap(); |
| 712 | let mut expired = web.clone(); |
| 713 | expired.session_expires_at = Instant::now(); |
| 714 | assert!(!expired.matches_request(Some(&cookie), Some(&proof))); |
| 715 | assert!(!expired.consume_stream_ticket(Some(&cookie), Some(&ticket))); |
| 716 | } |
| 717 | |
| 718 | #[tokio::test] |
| 719 | async fn runtime_surface_review_web_page_never_carries_the_request_proof() { |
| 720 | let (web, nonce) = RuntimeWebState::new(); |
| 721 | let (token, proof) = web.consume(&nonce, "127.0.0.1".parse().unwrap()).unwrap(); |
| 722 | let response = web_page_response(); |
| 723 | assert_eq!(response.headers()[header::CACHE_CONTROL], "no-store"); |
| 724 | assert!( |
| 725 | response.headers()[header::CONTENT_SECURITY_POLICY] |
| 726 | .to_str() |
| 727 | .unwrap() |
| 728 | .contains("frame-ancestors 'none'") |
| 729 | ); |
| 730 | let body = axum::body::to_bytes(response.into_body(), usize::MAX) |
| 731 | .await |
| 732 | .unwrap(); |
| 733 | let html = std::str::from_utf8(&body).unwrap(); |
| 734 | assert!(!html.contains(&proof)); |
| 735 | assert!(!html.contains(&token)); |
| 736 | assert!(!html.contains("codewhale-web-request")); |
| 737 | assert_eq!( |
| 738 | web.consume(&nonce, "127.0.0.1".parse().unwrap()), |
| 739 | Err(BootstrapError::Invalid) |
| 740 | ); |
| 741 | } |
| 742 | |
| 743 | #[test] |
| 744 | fn runtime_surface_review_web_tabs_keep_independent_bounded_tickets() { |
| 745 | let (web, nonce) = RuntimeWebState::new(); |
| 746 | let (token, proof) = web.consume(&nonce, "127.0.0.1".parse().unwrap()).unwrap(); |
| 747 | let cookie = web_session_cookie(&token); |
| 748 | let first = web |
| 749 | .refresh_stream_ticket(Some(&cookie), Some(&proof)) |
| 750 | .unwrap(); |
| 751 | let second = web |
| 752 | .refresh_stream_ticket(Some(&cookie), Some(&proof)) |
| 753 | .unwrap(); |
| 754 | assert!(web.consume_stream_ticket(Some(&cookie), Some(&first))); |
| 755 | assert!(web.consume_stream_ticket(Some(&cookie), Some(&second))); |
| 756 | assert!(!web.consume_stream_ticket(Some(&cookie), Some(&first))); |
| 757 | assert!(!web.consume_stream_ticket(Some(&cookie), Some(&second))); |
| 758 | let oldest = web |
| 759 | .refresh_stream_ticket(Some(&cookie), Some(&proof)) |
| 760 | .unwrap(); |
| 761 | for _ in 0..32 { |
| 762 | web.refresh_stream_ticket(Some(&cookie), Some(&proof)) |
| 763 | .unwrap(); |
| 764 | } |
| 765 | assert_eq!(web.stream_tickets.lock().unwrap().len(), 32); |
| 766 | assert!(!web.consume_stream_ticket(Some(&cookie), Some(&oldest))); |
| 767 | } |
| 768 | |
| 769 | #[test] |
| 770 | fn bootstrap_is_loopback_only_one_time_and_expires() { |
| 771 | let (state, nonce) = |
| 772 | RuntimeWebState::new_with_ttls(Duration::from_secs(60), Duration::from_secs(60)); |
| 773 | assert_eq!( |
| 774 | state.consume(&nonce, "192.0.2.4".parse().unwrap()), |
| 775 | Err(BootstrapError::NonLoopback) |
| 776 | ); |
| 777 | let (session_token, _) = state |
| 778 | .consume(&nonce, "127.0.0.1".parse().unwrap()) |
| 779 | .expect("valid loopback bootstrap"); |
| 780 | assert!(session_token.starts_with(WEB_SESSION_PREFIX)); |
| 781 | assert!(state.matches_session_cookie(Some(&format!( |
| 782 | "theme=dark; {WEB_SESSION_COOKIE_NAME}={session_token}" |
| 783 | )))); |
| 784 | assert_eq!( |
| 785 | state.consume(&nonce, "127.0.0.1".parse().unwrap()), |
| 786 | Err(BootstrapError::Invalid) |
| 787 | ); |
| 788 | |
| 789 | let (expired, expired_nonce) = |
| 790 | RuntimeWebState::new_with_ttls(Duration::ZERO, Duration::from_secs(60)); |
| 791 | assert_eq!( |
| 792 | expired.consume(&expired_nonce, "::1".parse().unwrap()), |
| 793 | Err(BootstrapError::Expired) |
| 794 | ); |
| 795 | } |
| 796 | |
| 797 | #[test] |
| 798 | fn web_session_survives_reload_then_expires_and_rejects_wrong_tokens() { |
| 799 | let (state, nonce) = |
| 800 | RuntimeWebState::new_with_ttls(Duration::from_secs(60), Duration::from_secs(60)); |
| 801 | let (session_token, _) = state |
| 802 | .consume(&nonce, "127.0.0.1".parse().unwrap()) |
| 803 | .expect("valid loopback bootstrap"); |
| 804 | let cookie = format!("{WEB_SESSION_COOKIE_NAME}={session_token}"); |
| 805 | assert!(state.matches_session_cookie(Some(&cookie))); |
| 806 | assert!( |
| 807 | state.matches_session_cookie(Some(&cookie)), |
| 808 | "the same process-local session remains valid across a page reload" |
| 809 | ); |
| 810 | assert!(!state.matches_session_cookie(Some( |
| 811 | "codewhale_web_session=cwws_0000000000000000000000000000000000000000000000000000000000000000" |
| 812 | ))); |
| 813 | |
| 814 | let (expired, _nonce) = |
| 815 | RuntimeWebState::new_with_ttls(Duration::from_secs(60), Duration::ZERO); |
| 816 | let expired_cookie = format!( |
| 817 | "{WEB_SESSION_COOKIE_NAME}={}", |
| 818 | expired.session_token.as_ref() |
| 819 | ); |
| 820 | assert!(!expired.matches_session_cookie(Some(&expired_cookie))); |
| 821 | } |
| 822 | |
| 823 | #[test] |
| 824 | fn bootstrap_rejects_malformed_or_wrong_capabilities_without_consuming() { |
| 825 | let (state, nonce) = RuntimeWebState::new(); |
| 826 | for invalid in ["", "cwwb_short", "cwwb_gggggggggggggggggggggggggggggggg"] { |
| 827 | assert_eq!( |
| 828 | state.consume(invalid, "127.0.0.1".parse().unwrap()), |
| 829 | Err(BootstrapError::Invalid) |
| 830 | ); |
| 831 | } |
| 832 | let mut wrong = nonce.clone(); |
| 833 | wrong.replace_range(wrong.len() - 1.., "0"); |
| 834 | if wrong == nonce { |
| 835 | wrong.replace_range(wrong.len() - 1.., "1"); |
| 836 | } |
| 837 | assert_eq!( |
| 838 | state.consume(&wrong, "127.0.0.1".parse().unwrap()), |
| 839 | Err(BootstrapError::Invalid) |
| 840 | ); |
| 841 | assert!( |
| 842 | state |
| 843 | .consume(&nonce, "127.0.0.1".parse().unwrap()) |
| 844 | .expect("valid bootstrap remains available") |
| 845 | .0 |
| 846 | .starts_with(WEB_SESSION_PREFIX) |
| 847 | ); |
| 848 | } |
| 849 | |
| 850 | #[test] |
| 851 | fn cookie_has_exact_security_attributes_without_the_runtime_bearer() { |
| 852 | let session_token = format!("{WEB_SESSION_PREFIX}{}", "01".repeat(16)); |
| 853 | let runtime_bearer = "cwrt_runtime_secret_never_in_browser_storage"; |
| 854 | let cookie = web_session_cookie(&session_token); |
| 855 | assert_eq!( |
| 856 | cookie, |
| 857 | format!("codewhale_web_session={session_token}; HttpOnly; SameSite=Strict; Path=/") |
| 858 | ); |
| 859 | assert!(!cookie.contains(runtime_bearer)); |
| 860 | assert!(!cookie.contains("Domain=")); |
| 861 | } |
| 862 | |
| 863 | #[test] |
| 864 | fn launcher_url_contains_only_the_one_time_capability() { |
| 865 | let token = "cwrt_runtime_secret_never_in_browser_arguments"; |
| 866 | let nonce = format!("{BOOTSTRAP_PREFIX}{}", "01".repeat(16)); |
| 867 | let url = bootstrap_url("127.0.0.1:7878".parse().unwrap(), &nonce); |
| 868 | assert!(url.ends_with(&nonce)); |
| 869 | assert!(!url.contains(token)); |
| 870 | assert!(!url.contains('?')); |
| 871 | assert!(!url.contains('#')); |
| 872 | } |
| 873 | |
| 874 | #[test] |
| 875 | fn embedded_client_keeps_runtime_bearer_private_and_has_no_unsafe_html_sink() { |
| 876 | for asset in [WEB_HTML, WEB_JS] { |
| 877 | assert!(!asset.contains("localStorage")); |
| 878 | assert!(!asset.contains("codewhale_runtime_token")); |
| 879 | assert!(!asset.contains("innerHTML")); |
| 880 | assert!(!asset.contains("http://")); |
| 881 | assert!(!asset.contains("https://")); |
| 882 | } |
| 883 | } |
| 884 | |
| 885 | #[test] |
| 886 | fn web_dist_path_confinement_and_mime_types() { |
| 887 | let dir = tempfile::tempdir().unwrap(); |
| 888 | let dist = dir.path().join("dist"); |
| 889 | fs::create_dir_all(dist.join("static")).unwrap(); |
| 890 | fs::write( |
| 891 | dist.join("index.html"), |
| 892 | "<!doctype html><div id=root></div>", |
| 893 | ) |
| 894 | .unwrap(); |
| 895 | fs::write( |
| 896 | dist.join("plugin-host.html"), |
| 897 | "<!doctype html><div id=plugin-root></div>", |
| 898 | ) |
| 899 | .unwrap(); |
| 900 | fs::write(dist.join("static/app-123.js"), "console.log('ok');").unwrap(); |
| 901 | fs::write(dist.join("static/app-123.css"), "body { color: #000; }").unwrap(); |
| 902 | fs::write(dist.join(".env"), "SECRET=1").unwrap(); |
| 903 | let outside = dir.path().join("secret.txt"); |
| 904 | fs::write(&outside, "top-secret").unwrap(); |
| 905 | |
| 906 | let root = validate_web_dist_dir(&dist).expect("valid dist dir"); |
| 907 | assert!(read_confined_dist_file(&root, FsPath::new("index.html")).is_some()); |
| 908 | assert!(read_confined_dist_file(&root, FsPath::new("plugin-host.html")).is_some()); |
| 909 | assert!(read_confined_dist_file(&root, FsPath::new("static/app-123.js")).is_some()); |
| 910 | |
| 911 | assert_eq!( |
| 912 | content_type_for_path(FsPath::new("static/app-123.js")), |
| 913 | Some("text/javascript; charset=utf-8") |
| 914 | ); |
| 915 | assert_eq!( |
| 916 | content_type_for_path(FsPath::new("static/app-123.css")), |
| 917 | Some("text/css; charset=utf-8") |
| 918 | ); |
| 919 | assert_eq!(content_type_for_path(FsPath::new("secret.pem")), None); |
| 920 | |
| 921 | for bad in [ |
| 922 | "../secret.txt", |
| 923 | "static/../../secret.txt", |
| 924 | ".env", |
| 925 | "a\\b.js", |
| 926 | "", |
| 927 | ] { |
| 928 | assert!( |
| 929 | sanitize_dist_relative_path(bad).is_none(), |
| 930 | "expected refusal for {bad:?}" |
| 931 | ); |
| 932 | } |
| 933 | |
| 934 | #[cfg(unix)] |
| 935 | { |
| 936 | std::os::unix::fs::symlink(&outside, dist.join("static/escape.js")).unwrap(); |
| 937 | assert!(read_confined_dist_file(&root, FsPath::new("static/escape.js")).is_none()); |
| 938 | } |
| 939 | |
| 940 | let missing = dir.path().join("no-index"); |
| 941 | fs::create_dir_all(&missing).unwrap(); |
| 942 | assert!(validate_web_dist_dir(&missing).is_err()); |
| 943 | } |
| 944 | |
| 945 | #[test] |
| 946 | fn invalid_web_dist_is_refused_with_the_reason() { |
| 947 | let dir = tempfile::tempdir().unwrap(); |
| 948 | assert_eq!(checked_web_dist(None), Ok(None)); |
| 949 | assert_eq!(checked_web_dist(Some(std::ffi::OsString::new())), Ok(None)); |
| 950 | |
| 951 | let absent = dir.path().join("absent"); |
| 952 | let error = checked_web_dist(Some(absent.clone().into_os_string())).unwrap_err(); |
| 953 | assert!(error.starts_with(WEB_DIST_ENV), "{error}"); |
| 954 | assert!(error.contains(&absent.display().to_string()), "{error}"); |
| 955 | assert!(error.contains("cannot read it"), "{error}"); |
| 956 | |
| 957 | let file = dir.path().join("file"); |
| 958 | fs::write(&file, "x").unwrap(); |
| 959 | let error = checked_web_dist(Some(file.into_os_string())).unwrap_err(); |
| 960 | assert!(error.contains("it is not a directory"), "{error}"); |
| 961 | |
| 962 | let empty = dir.path().join("empty"); |
| 963 | fs::create_dir_all(&empty).unwrap(); |
| 964 | let error = checked_web_dist(Some(empty.into_os_string())).unwrap_err(); |
| 965 | assert!(error.contains("no readable index.html"), "{error}"); |
| 966 | |
| 967 | let dist = dir.path().join("dist"); |
| 968 | fs::create_dir_all(&dist).unwrap(); |
| 969 | fs::write(dist.join("index.html"), "<!doctype html>").unwrap(); |
| 970 | assert_eq!( |
| 971 | checked_web_dist(Some(dist.clone().into_os_string())), |
| 972 | Ok(Some(fs::canonicalize(&dist).unwrap())) |
| 973 | ); |
| 974 | |
| 975 | #[cfg(unix)] |
| 976 | { |
| 977 | let link = dir.path().join("link"); |
| 978 | std::os::unix::fs::symlink(&dist, &link).unwrap(); |
| 979 | let error = checked_web_dist(Some(link.into_os_string())).unwrap_err(); |
| 980 | assert!(error.contains("symbolic link"), "{error}"); |
| 981 | |
| 982 | let linked_index = dir.path().join("linked-index"); |
| 983 | fs::create_dir_all(&linked_index).unwrap(); |
| 984 | std::os::unix::fs::symlink(dist.join("index.html"), linked_index.join("index.html")) |
| 985 | .unwrap(); |
| 986 | let error = checked_web_dist(Some(linked_index.into_os_string())).unwrap_err(); |
| 987 | assert!(error.contains("index.html is a symbolic link"), "{error}"); |
| 988 | } |
| 989 | } |
| 990 | |
| 991 | #[tokio::test] |
| 992 | async fn web_dist_router_serves_the_app_and_keeps_cors_to_static_build_assets() { |
| 993 | use tower::ServiceExt as _; |
| 994 | |
| 995 | let dir = tempfile::tempdir().unwrap(); |
| 996 | let dist = dir.path().join("dist"); |
| 997 | fs::create_dir_all(dist.join("static")).unwrap(); |
| 998 | fs::write(dist.join("index.html"), "<!doctype html>app-index").unwrap(); |
| 999 | fs::write(dist.join("plugin-host.html"), "<!doctype html>host").unwrap(); |
| 1000 | fs::write(dist.join("other.html"), "<!doctype html>other").unwrap(); |
| 1001 | fs::write(dist.join("static/app-abc.js"), "export const ok = true;").unwrap(); |
| 1002 | fs::write(dist.join("robots.txt"), "User-agent: *").unwrap(); |
| 1003 | |
| 1004 | let (web_state, _nonce) = RuntimeWebState::new_with_dist(Some(dist.clone())); |
| 1005 | let root = web_state.web_dist_dir.clone().expect("dist dir attached"); |
| 1006 | assert_eq!(web_state.dist_dir(), Some(root.as_path())); |
| 1007 | let app = axum::Router::new() |
| 1008 | .fallback(move |req: Request| serve_web_dist_request(Arc::clone(&root), req)) |
| 1009 | .layer(super::super::cors_layer(&[])); |
| 1010 | |
| 1011 | async fn send( |
| 1012 | app: &axum::Router, |
| 1013 | method: Method, |
| 1014 | path: &str, |
| 1015 | ) -> (StatusCode, axum::http::HeaderMap, String) { |
| 1016 | let request = axum::http::Request::builder() |
| 1017 | .method(method) |
| 1018 | .uri(path) |
| 1019 | .header(header::ORIGIN, "null") |
| 1020 | .body(Body::empty()) |
| 1021 | .unwrap(); |
| 1022 | let response = app.clone().oneshot(request).await.unwrap(); |
| 1023 | let (parts, body) = response.into_parts(); |
| 1024 | let bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap(); |
| 1025 | ( |
| 1026 | parts.status, |
| 1027 | parts.headers, |
| 1028 | String::from_utf8_lossy(&bytes).into_owned(), |
| 1029 | ) |
| 1030 | } |
| 1031 | |
| 1032 | let (status, headers, body) = send(&app, Method::GET, "/settings/plugins").await; |
| 1033 | assert_eq!(status, StatusCode::OK); |
| 1034 | assert_eq!(body, "<!doctype html>app-index"); |
| 1035 | assert_eq!( |
| 1036 | headers[header::CONTENT_SECURITY_POLICY], |
| 1037 | APP_WEB_CONTENT_SECURITY_POLICY |
| 1038 | ); |
| 1039 | assert_eq!(headers[header::CACHE_CONTROL], "no-store"); |
| 1040 | assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN)); |
| 1041 | |
| 1042 | let (status, headers, body) = send(&app, Method::GET, "/static/app-abc.js").await; |
| 1043 | assert_eq!(status, StatusCode::OK); |
| 1044 | assert_eq!(body, "export const ok = true;"); |
| 1045 | assert_eq!( |
| 1046 | headers[header::CACHE_CONTROL], |
| 1047 | "public, max-age=31536000, immutable" |
| 1048 | ); |
| 1049 | assert_eq!(headers[header::ACCESS_CONTROL_ALLOW_ORIGIN], "*"); |
| 1050 | assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_CREDENTIALS)); |
| 1051 | |
| 1052 | let (status, headers, body) = send(&app, Method::GET, "/plugin-host.html").await; |
| 1053 | assert_eq!(status, StatusCode::OK); |
| 1054 | assert_eq!(body, "<!doctype html>host"); |
| 1055 | assert_eq!( |
| 1056 | headers[header::CONTENT_SECURITY_POLICY], |
| 1057 | PLUGIN_HOST_CONTENT_SECURITY_POLICY |
| 1058 | ); |
| 1059 | let host_csp = headers[header::CONTENT_SECURITY_POLICY].to_str().unwrap(); |
| 1060 | assert!(host_csp.ends_with("; sandbox allow-scripts")); |
| 1061 | assert!(!host_csp.contains("allow-same-origin")); |
| 1062 | assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN)); |
| 1063 | |
| 1064 | let widget_path = dist.join("widget-host.html"); |
| 1065 | assert_eq!( |
| 1066 | send(&app, Method::HEAD, "/widget-host.html").await.0, |
| 1067 | StatusCode::NOT_FOUND |
| 1068 | ); |
| 1069 | let widget = r#"<meta http-equiv="Content-Security-Policy" content="script-src 'sha256-b+fA1MsbP5Wo7LtMy5HL8x+2N2N/lSxCmkQHl0Ay5SQ=';"><script>parent.postMessage("ready","*")</script>"#; |
| 1070 | fs::write(&widget_path, widget).unwrap(); |
| 1071 | for method in [Method::GET, Method::HEAD] { |
| 1072 | let (status, headers, body) = send(&app, method.clone(), "/widget-host.html").await; |
| 1073 | assert_eq!(status, StatusCode::OK); |
| 1074 | assert_eq!(body, if method == Method::HEAD { "" } else { widget }); |
| 1075 | assert_eq!( |
| 1076 | headers[header::CONTENT_LENGTH].to_str().unwrap(), |
| 1077 | widget.len().to_string() |
| 1078 | ); |
| 1079 | assert_eq!(headers[header::CONTENT_TYPE], "text/html; charset=utf-8"); |
| 1080 | assert_eq!(headers[header::CACHE_CONTROL], "no-store"); |
| 1081 | assert_eq!(headers[header::X_CONTENT_TYPE_OPTIONS], "nosniff"); |
| 1082 | assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN)); |
| 1083 | assert_eq!( |
| 1084 | headers[header::CONTENT_SECURITY_POLICY], |
| 1085 | "default-src 'none'; script-src 'sha256-b+fA1MsbP5Wo7LtMy5HL8x+2N2N/lSxCmkQHl0Ay5SQ='; style-src 'unsafe-inline'; connect-src 'none'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-src 'none'; frame-ancestors 'self'; sandbox allow-scripts" |
| 1086 | ); |
| 1087 | } |
| 1088 | fs::write(&widget_path, widget.replace("ready", "changed")).unwrap(); |
| 1089 | assert_eq!( |
| 1090 | send(&app, Method::GET, "/widget-host.html").await.0, |
| 1091 | StatusCode::NOT_FOUND |
| 1092 | ); |
| 1093 | |
| 1094 | let (status, headers, _) = send(&app, Method::GET, "/robots.txt").await; |
| 1095 | assert_eq!(status, StatusCode::OK); |
| 1096 | assert_eq!(headers[header::CACHE_CONTROL], "no-store"); |
| 1097 | assert!(!headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN)); |
| 1098 | |
| 1099 | for (method, path) in [ |
| 1100 | (Method::GET, "/nested/widget-host.html"), |
| 1101 | (Method::GET, "/Widget-Host.html"), |
| 1102 | (Method::POST, "/widget-host.html"), |
| 1103 | (Method::GET, "/other.html"), |
| 1104 | (Method::GET, "/v1/nope"), |
| 1105 | (Method::GET, "/api/x"), |
| 1106 | (Method::GET, "/__codewhale/bootstrap/x"), |
| 1107 | (Method::GET, "/missing.js"), |
| 1108 | (Method::GET, "/static/missing.js"), |
| 1109 | (Method::POST, "/settings"), |
| 1110 | (Method::POST, "/static/app-abc.js"), |
| 1111 | ] { |
| 1112 | let (status, headers, body) = send(&app, method.clone(), path).await; |
| 1113 | assert_eq!(status, StatusCode::NOT_FOUND, "{method} {path}"); |
| 1114 | assert!(!body.contains("app-index"), "{method} {path}"); |
| 1115 | assert!( |
| 1116 | !headers.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN), |
| 1117 | "{method} {path}" |
| 1118 | ); |
| 1119 | } |
| 1120 | } |
| 1121 | |
| 1122 | #[tokio::test] |
| 1123 | async fn web_dist_serves_index_plugin_host_assets_spa_fallback_and_preserves_bootstrap_cookie() |
| 1124 | { |
| 1125 | let dir = tempfile::tempdir().unwrap(); |
| 1126 | let dist = dir.path().join("dist"); |
| 1127 | fs::create_dir_all(dist.join("static")).unwrap(); |
| 1128 | fs::write( |
| 1129 | dist.join("index.html"), |
| 1130 | "<!doctype html><div id=\"root\">app</div>", |
| 1131 | ) |
| 1132 | .unwrap(); |
| 1133 | fs::write( |
| 1134 | dist.join("plugin-host.html"), |
| 1135 | "<!doctype html><div id=\"plugin-root\">host</div>", |
| 1136 | ) |
| 1137 | .unwrap(); |
| 1138 | fs::write(dist.join("static/app-abc.js"), "export const ok = true;").unwrap(); |
| 1139 | fs::write(dist.join("static/app-abc.css"), "body{margin:0}").unwrap(); |
| 1140 | |
| 1141 | let (web_state, nonce) = RuntimeWebState::new_with_dist(Some(dist.clone())); |
| 1142 | let (session_token, proof) = web_state |
| 1143 | .consume(&nonce, "127.0.0.1".parse().unwrap()) |
| 1144 | .expect("bootstrap succeeds with dist configured"); |
| 1145 | let cookie = web_session_cookie(&session_token); |
| 1146 | assert!(web_state.matches_request(Some(&cookie), Some(&proof))); |
| 1147 | |
| 1148 | let root = web_state.web_dist_dir.clone().expect("dist dir attached"); |
| 1149 | let index_resp = serve_dist_html_async( |
| 1150 | Arc::clone(&root), |
| 1151 | "index.html", |
| 1152 | APP_WEB_CONTENT_SECURITY_POLICY, |
| 1153 | ) |
| 1154 | .await; |
| 1155 | assert_eq!(index_resp.status(), StatusCode::OK); |
| 1156 | assert_eq!( |
| 1157 | index_resp.headers()[header::CONTENT_TYPE], |
| 1158 | "text/html; charset=utf-8" |
| 1159 | ); |
| 1160 | assert_eq!(index_resp.headers()[header::CACHE_CONTROL], "no-store"); |
| 1161 | assert!( |
| 1162 | index_resp.headers()[header::CONTENT_SECURITY_POLICY] |
| 1163 | .to_str() |
| 1164 | .unwrap() |
| 1165 | .contains("frame-src 'self'") |
| 1166 | ); |
| 1167 | |
| 1168 | let host_resp = serve_dist_html_async( |
| 1169 | Arc::clone(&root), |
| 1170 | "plugin-host.html", |
| 1171 | PLUGIN_HOST_CONTENT_SECURITY_POLICY, |
| 1172 | ) |
| 1173 | .await; |
| 1174 | assert_eq!(host_resp.status(), StatusCode::OK); |
| 1175 | assert_eq!(host_resp.headers()[header::CACHE_CONTROL], "no-store"); |
| 1176 | let host_csp = host_resp.headers()[header::CONTENT_SECURITY_POLICY] |
| 1177 | .to_str() |
| 1178 | .unwrap(); |
| 1179 | assert!(host_csp.contains("connect-src 'none'")); |
| 1180 | assert!(host_csp.contains("frame-ancestors 'self'")); |
| 1181 | |
| 1182 | assert!("Plugin-Host.html".eq_ignore_ascii_case("plugin-host.html")); |
| 1183 | assert!(content_type_for_path(FsPath::new("Plugin-Host.html")).is_none()); |
| 1184 | assert!(content_type_for_path(FsPath::new("other.html")).is_none()); |
| 1185 | assert_eq!( |
| 1186 | content_type_for_path(FsPath::new("favicon.svg")), |
| 1187 | Some("image/svg+xml") |
| 1188 | ); |
| 1189 | |
| 1190 | assert!(is_reserved_runtime_path("/v1/sessions")); |
| 1191 | assert!(is_reserved_runtime_path("/api/web/session")); |
| 1192 | assert!(is_reserved_runtime_path("/api")); |
| 1193 | assert!(is_reserved_runtime_path("/__codewhale/bootstrap/abc")); |
| 1194 | assert!(is_reserved_runtime_path("/health")); |
| 1195 | assert!(!is_reserved_runtime_path("/settings/plugins")); |
| 1196 | assert!(!is_reserved_runtime_path("/plugin-host.html")); |
| 1197 | } |
| 1198 | } |
| 1199 |