| 1 | // Copyright 2026 Deno Land Inc. Apache-2.0 license. |
| 2 | |
| 3 | // Asset download and cache maintenance execute outside the Actor execution |
| 4 | // domain. |
| 5 | #![allow(clippy::disallowed_methods, clippy::disallowed_types)] |
| 6 | |
| 7 | use crate::bucket::Bucket; |
| 8 | use crate::js; |
| 9 | use crate::protocol::{ |
| 10 | asset_blob_key, AssetEntry, AssetIndex, AssetManifestRef, DeployPointer, Manifest, |
| 11 | RunWorkerFirst, |
| 12 | }; |
| 13 | use anyhow::{anyhow, Context}; |
| 14 | use axum::body::Body; |
| 15 | use axum::http::{HeaderMap, HeaderValue, StatusCode}; |
| 16 | use axum::response::Response; |
| 17 | use futures_util::StreamExt; |
| 18 | use percent_encoding::percent_decode_str; |
| 19 | use rand::RngCore; |
| 20 | use sha2::{Digest, Sha256}; |
| 21 | use std::collections::HashMap; |
| 22 | use std::path::{Path, PathBuf}; |
| 23 | use std::sync::Arc; |
| 24 | use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt}; |
| 25 | use tokio::sync::Mutex; |
| 26 | use tokio_util::io::ReaderStream; |
| 27 | |
| 28 | const DEFAULT_ASSET_CACHE_BYTES: u64 = 512 * 1024 * 1024; |
| 29 | |
| 30 | #[derive(Clone)] |
| 31 | pub struct AssetResolver { |
| 32 | inner: Arc<AssetResolverInner>, |
| 33 | } |
| 34 | |
| 35 | /// Where a resolver can look for a NEWER deployment's asset index than the |
| 36 | /// one this process booted with. During a rolling restart an upgraded node |
| 37 | /// serves HTML whose content-hashed asset paths an un-restarted node has |
| 38 | /// never heard of; the blobs are content-addressed and fleet-visible, so |
| 39 | /// only the index is stale. denoland/celld#161. |
| 40 | pub struct FallbackSource { |
| 41 | /// The pointer this deployment was loaded from (`deploy/current.json`, |
| 42 | /// or the script-scoped pointer for a service). |
| 43 | pub pointer_key: String, |
| 44 | /// The deployment prefix loaded at boot; a pointer naming another |
| 45 | /// prefix names a newer deployment. |
| 46 | pub boot_prefix: String, |
| 47 | } |
| 48 | |
| 49 | /// The newest foreign index this resolver has adopted, plus the throttle |
| 50 | /// that keeps a miss storm from becoming a pointer-GET storm. Guarded by a |
| 51 | /// std mutex that is NEVER held across I/O: the refresh runs in a spawned |
| 52 | /// task, so a degraded bucket cannot stall the miss path — before this |
| 53 | /// rule, one slow pointer GET head-of-line-blocked every Worker-bound |
| 54 | /// request whose path missed the index. |
| 55 | /// What one refresh pass concluded about the pointer. |
| 56 | enum Adoption { |
| 57 | /// The pointer names the booted deployment: any adoption is withdrawn. |
| 58 | Booted, |
| 59 | /// The pointer names the deployment already adopted. |
| 60 | Unchanged, |
| 61 | /// The pointer names a deployment this resolver now adopts. Boxed: |
| 62 | /// an index can be large, and the other variants carry nothing. |
| 63 | Newer { |
| 64 | prefix: String, |
| 65 | index: Box<AssetIndex>, |
| 66 | }, |
| 67 | } |
| 68 | |
| 69 | #[derive(Default)] |
| 70 | struct FallbackState { |
| 71 | checked: Option<std::time::Instant>, |
| 72 | refreshing: bool, |
| 73 | prefix: Option<String>, |
| 74 | index: Option<Arc<AssetIndex>>, |
| 75 | } |
| 76 | |
| 77 | /// How long a pointer observation stays fresh. A newer deployment's assets |
| 78 | /// become servable within this bound after its pointer lands, which is far |
| 79 | /// inside the window a rolling restart leaves a node un-upgraded. |
| 80 | const FALLBACK_CHECK_MS: u64 = 5_000; |
| 81 | |
| 82 | struct AssetResolverInner { |
| 83 | bucket: Bucket, |
| 84 | index: AssetIndex, |
| 85 | asset_only: bool, |
| 86 | fallback: Option<FallbackSource>, |
| 87 | fallback_state: std::sync::Mutex<FallbackState>, |
| 88 | cache_root: PathBuf, |
| 89 | cache_max_bytes: u64, |
| 90 | download_locks: Mutex<HashMap<String, Arc<Mutex<()>>>>, |
| 91 | cleanup_lock: Mutex<()>, |
| 92 | header_rules: Vec<HeaderRule>, |
| 93 | redirect_rules: Vec<RedirectRule>, |
| 94 | } |
| 95 | |
| 96 | enum Route { |
| 97 | Asset { |
| 98 | path: String, |
| 99 | entry: AssetEntry, |
| 100 | status: StatusCode, |
| 101 | }, |
| 102 | Redirect { |
| 103 | location: String, |
| 104 | status: StatusCode, |
| 105 | }, |
| 106 | Missing, |
| 107 | } |
| 108 | |
| 109 | #[derive(Clone, Copy)] |
| 110 | enum RequestedRange { |
| 111 | Full, |
| 112 | Partial { start: u64, end: u64 }, |
| 113 | Unsatisfiable, |
| 114 | } |
| 115 | |
| 116 | struct RulePattern { |
| 117 | host: Option<regex::Regex>, |
| 118 | path: regex::Regex, |
| 119 | } |
| 120 | |
| 121 | struct HeaderRule { |
| 122 | pattern: RulePattern, |
| 123 | operations: Vec<HeaderOperation>, |
| 124 | } |
| 125 | |
| 126 | enum HeaderOperation { |
| 127 | Set(String, String), |
| 128 | Remove(String), |
| 129 | } |
| 130 | |
| 131 | struct RedirectRule { |
| 132 | pattern: RulePattern, |
| 133 | destination: String, |
| 134 | status: u16, |
| 135 | } |
| 136 | |
| 137 | impl AssetResolver { |
| 138 | pub async fn load( |
| 139 | bucket: &Bucket, |
| 140 | prefix: &str, |
| 141 | reference: &AssetManifestRef, |
| 142 | asset_only: bool, |
| 143 | fallback: Option<FallbackSource>, |
| 144 | ) -> anyhow::Result<Self> { |
| 145 | if reference.index != "assets.json" { |
| 146 | return Err(anyhow!("unsupported asset index name: {}", reference.index)); |
| 147 | } |
| 148 | let key = format!("{prefix}/{}", reference.index); |
| 149 | let (bytes, _) = bucket.get(&key).await?.with_context(|| { |
| 150 | format!( |
| 151 | "read {}://{}/{key}: no such key", |
| 152 | bucket.scheme(), |
| 153 | bucket.name |
| 154 | ) |
| 155 | })?; |
| 156 | let sha256 = format!("{:x}", Sha256::digest(&bytes)); |
| 157 | if sha256 != reference.sha256 { |
| 158 | return Err(anyhow!("asset index checksum mismatch")); |
| 159 | } |
| 160 | let index: AssetIndex = serde_json::from_slice(&bytes).context("decode asset index")?; |
| 161 | validate_index(&index, reference)?; |
| 162 | let header_rules = parse_header_rules(index.config.headers.as_deref().unwrap_or(""))?; |
| 163 | let redirect_rules = parse_redirect_rules(index.config.redirects.as_deref().unwrap_or(""))?; |
| 164 | let cache_root = std::env::var_os("CELLD_ASSET_CACHE_DIR") |
| 165 | .map(PathBuf::from) |
| 166 | .unwrap_or_else(|| std::env::temp_dir().join("celld").join("asset-cache")); |
| 167 | std::fs::create_dir_all(&cache_root) |
| 168 | .with_context(|| format!("create asset cache directory {}", cache_root.display()))?; |
| 169 | let cache_max_bytes = |
| 170 | crate::env_vars::with_default("CELLD_ASSET_CACHE_BYTES", DEFAULT_ASSET_CACHE_BYTES)?; |
| 171 | Ok(Self { |
| 172 | inner: Arc::new(AssetResolverInner { |
| 173 | bucket: bucket.clone(), |
| 174 | index, |
| 175 | asset_only, |
| 176 | fallback, |
| 177 | fallback_state: std::sync::Mutex::new(FallbackState::default()), |
| 178 | cache_root, |
| 179 | cache_max_bytes, |
| 180 | download_locks: Mutex::new(HashMap::new()), |
| 181 | cleanup_lock: Mutex::new(()), |
| 182 | header_rules, |
| 183 | redirect_rules, |
| 184 | }), |
| 185 | }) |
| 186 | } |
| 187 | |
| 188 | pub fn binding_name(&self) -> Option<&str> { |
| 189 | self.inner.index.config.binding.as_deref() |
| 190 | } |
| 191 | |
| 192 | pub fn asset_only(&self) -> bool { |
| 193 | self.inner.asset_only |
| 194 | } |
| 195 | |
| 196 | pub fn should_run_worker_first(&self, encoded_path: &str) -> bool { |
| 197 | let Some(path) = decode_path(encoded_path) else { |
| 198 | return false; |
| 199 | }; |
| 200 | match &self.inner.index.config.run_worker_first { |
| 201 | RunWorkerFirst::Bool(value) => *value, |
| 202 | RunWorkerFirst::Routes(rules) => { |
| 203 | let excluded = rules |
| 204 | .iter() |
| 205 | .filter_map(|rule| rule.strip_prefix('!')) |
| 206 | .any(|rule| route_pattern_matches(rule, &path)); |
| 207 | !excluded |
| 208 | && rules |
| 209 | .iter() |
| 210 | .filter(|rule| !rule.starts_with('!')) |
| 211 | .any(|rule| route_pattern_matches(rule, &path)) |
| 212 | } |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | pub async fn ingress_response( |
| 217 | &self, |
| 218 | encoded_path: &str, |
| 219 | query: Option<&str>, |
| 220 | head: bool, |
| 221 | request_headers: &HeaderMap, |
| 222 | ) -> anyhow::Result<Option<Response>> { |
| 223 | let include_not_found = |
| 224 | self.inner.asset_only || self.navigation_prefers_asset_serving(request_headers); |
| 225 | let host = request_headers |
| 226 | .get("host") |
| 227 | .and_then(|value| value.to_str().ok()) |
| 228 | .map(strip_port); |
| 229 | self.response( |
| 230 | encoded_path, |
| 231 | query, |
| 232 | host, |
| 233 | head, |
| 234 | request_headers, |
| 235 | include_not_found, |
| 236 | ) |
| 237 | .await |
| 238 | } |
| 239 | |
| 240 | async fn response( |
| 241 | &self, |
| 242 | encoded_path: &str, |
| 243 | query: Option<&str>, |
| 244 | host: Option<&str>, |
| 245 | head: bool, |
| 246 | request_headers: &HeaderMap, |
| 247 | include_not_found: bool, |
| 248 | ) -> anyhow::Result<Option<Response>> { |
| 249 | let Some(path) = decode_path(encoded_path) else { |
| 250 | return Ok(None); |
| 251 | }; |
| 252 | let mut selected = None; |
| 253 | for rule in &self.inner.redirect_rules { |
| 254 | let Some(captures) = rule.pattern.matches(host, &path) else { |
| 255 | continue; |
| 256 | }; |
| 257 | let destination = substitute(&rule.destination, &captures); |
| 258 | if rule.status == 200 { |
| 259 | let boundary = destination.find(['?', '#']).unwrap_or(destination.len()); |
| 260 | let destination_path = &destination[..boundary]; |
| 261 | if !destination_path.starts_with('/') { |
| 262 | return Err(anyhow!("asset proxy destination must be a local path")); |
| 263 | } |
| 264 | selected = Some(route(&self.inner.index, destination_path, true)); |
| 265 | } else { |
| 266 | let status = StatusCode::from_u16(rule.status) |
| 267 | .context("invalid static asset redirect status")?; |
| 268 | return Ok(Some( |
| 269 | Response::builder() |
| 270 | .status(status) |
| 271 | .header("location", destination) |
| 272 | .body(Body::empty())?, |
| 273 | )); |
| 274 | } |
| 275 | break; |
| 276 | } |
| 277 | let routed = match selected { |
| 278 | Some(routed) => routed, |
| 279 | None => { |
| 280 | let mut routed = route(&self.inner.index, &path, false); |
| 281 | if matches!(routed, Route::Missing) { |
| 282 | if let Some(fresh) = self.newer_deployment_route(&path) { |
| 283 | routed = fresh; |
| 284 | } |
| 285 | } |
| 286 | if matches!(routed, Route::Missing) && include_not_found { |
| 287 | routed = not_found_route(&self.inner.index, &path); |
| 288 | } |
| 289 | routed |
| 290 | } |
| 291 | }; |
| 292 | match routed { |
| 293 | Route::Missing => Ok(None), |
| 294 | Route::Redirect { |
| 295 | mut location, |
| 296 | status, |
| 297 | } => { |
| 298 | if let Some(query) = query.filter(|value| !value.is_empty()) { |
| 299 | location.push('?'); |
| 300 | location.push_str(query); |
| 301 | } |
| 302 | Ok(Some( |
| 303 | Response::builder() |
| 304 | .status(status) |
| 305 | .header("location", location) |
| 306 | .body(Body::empty())?, |
| 307 | )) |
| 308 | } |
| 309 | Route::Asset { |
| 310 | path: resolved_path, |
| 311 | entry, |
| 312 | status, |
| 313 | } => { |
| 314 | let etag = format!("\"{}\"", entry.sha256); |
| 315 | if request_headers |
| 316 | .get("if-none-match") |
| 317 | .and_then(|value| value.to_str().ok()) |
| 318 | .is_some_and(|value| etag_matches(value, &etag)) |
| 319 | { |
| 320 | let mut response = Response::builder() |
| 321 | .status(StatusCode::NOT_MODIFIED) |
| 322 | .header("etag", etag) |
| 323 | .body(Body::empty())?; |
| 324 | self.apply_headers(response.headers_mut(), host, &path)?; |
| 325 | return Ok(Some(response)); |
| 326 | } |
| 327 | let requested_range = if status == StatusCode::OK { |
| 328 | requested_range(request_headers, entry.bytes, &etag) |
| 329 | } else { |
| 330 | RequestedRange::Full |
| 331 | }; |
| 332 | if matches!(requested_range, RequestedRange::Unsatisfiable) { |
| 333 | let mut response = Response::builder() |
| 334 | .status(StatusCode::RANGE_NOT_SATISFIABLE) |
| 335 | .header("content-range", format!("bytes */{}", entry.bytes)) |
| 336 | .header("accept-ranges", "bytes") |
| 337 | .header("etag", etag) |
| 338 | .body(Body::empty())?; |
| 339 | self.apply_headers(response.headers_mut(), host, &path)?; |
| 340 | return Ok(Some(response)); |
| 341 | } |
| 342 | let (response_status, start, content_length) = match requested_range { |
| 343 | RequestedRange::Partial { start, end } => { |
| 344 | (StatusCode::PARTIAL_CONTENT, start, end - start + 1) |
| 345 | } |
| 346 | RequestedRange::Full | RequestedRange::Unsatisfiable => { |
| 347 | (status, 0, entry.bytes) |
| 348 | } |
| 349 | }; |
| 350 | let mut builder = Response::builder() |
| 351 | .status(response_status) |
| 352 | .header("content-length", content_length) |
| 353 | .header("accept-ranges", "bytes") |
| 354 | .header("etag", &etag); |
| 355 | if let RequestedRange::Partial { start, end } = requested_range { |
| 356 | builder = builder.header( |
| 357 | "content-range", |
| 358 | format!("bytes {start}-{end}/{}", entry.bytes), |
| 359 | ); |
| 360 | } |
| 361 | if !request_headers.contains_key("authorization") |
| 362 | && !request_headers.contains_key("range") |
| 363 | { |
| 364 | builder = builder.header("cache-control", "public, max-age=0, must-revalidate"); |
| 365 | } |
| 366 | if let Some(content_type) = &entry.content_type { |
| 367 | builder = builder.header( |
| 368 | "content-type", |
| 369 | HeaderValue::from_str(content_type) |
| 370 | .context("invalid asset content type")?, |
| 371 | ); |
| 372 | } |
| 373 | let body = if head { |
| 374 | Body::empty() |
| 375 | } else { |
| 376 | let mut file = self.open_asset(&resolved_path, &entry).await?; |
| 377 | if start > 0 { |
| 378 | file.seek(std::io::SeekFrom::Start(start)) |
| 379 | .await |
| 380 | .context("seek asset cache file")?; |
| 381 | } |
| 382 | let stream = ReaderStream::new(file.take(content_length)) |
| 383 | .map(|result| result.map_err(std::io::Error::other)); |
| 384 | Body::from_stream(stream) |
| 385 | }; |
| 386 | let mut response = builder.body(body)?; |
| 387 | self.apply_headers(response.headers_mut(), host, &path)?; |
| 388 | Ok(Some(response)) |
| 389 | } |
| 390 | } |
| 391 | } |
| 392 | |
| 393 | pub async fn binding_response( |
| 394 | &self, |
| 395 | url: &str, |
| 396 | method: &str, |
| 397 | headers: &[(String, String)], |
| 398 | ) -> anyhow::Result<js::HttpResponse> { |
| 399 | if !matches!(method, "GET" | "HEAD") { |
| 400 | return Ok(js::HttpResponse { |
| 401 | status: StatusCode::METHOD_NOT_ALLOWED.as_u16(), |
| 402 | body: b"Method not allowed".to_vec(), |
| 403 | stream: None, |
| 404 | headers: vec![("content-type".into(), "text/plain; charset=utf-8".into())], |
| 405 | websocket: None, |
| 406 | write_position: None, |
| 407 | observed_position: None, |
| 408 | }); |
| 409 | } |
| 410 | let path = url::Url::parse(url).context("invalid assets binding URL")?; |
| 411 | let mut request_headers = HeaderMap::new(); |
| 412 | for (name, value) in headers { |
| 413 | let Ok(name) = name.parse::<axum::http::HeaderName>() else { |
| 414 | continue; |
| 415 | }; |
| 416 | let Ok(value) = HeaderValue::from_str(value) else { |
| 417 | continue; |
| 418 | }; |
| 419 | request_headers.append(name, value); |
| 420 | } |
| 421 | let response = match self |
| 422 | .response( |
| 423 | path.path(), |
| 424 | path.query(), |
| 425 | path.host_str(), |
| 426 | method == "HEAD", |
| 427 | &request_headers, |
| 428 | true, |
| 429 | ) |
| 430 | .await? |
| 431 | { |
| 432 | Some(response) => response, |
| 433 | None => Response::builder() |
| 434 | .status(StatusCode::NOT_FOUND) |
| 435 | .header("content-type", "text/plain; charset=utf-8") |
| 436 | .body(Body::from("Not found"))?, |
| 437 | }; |
| 438 | let (parts, body) = response.into_parts(); |
| 439 | Ok(js::HttpResponse { |
| 440 | status: parts.status.as_u16(), |
| 441 | body: Vec::new(), |
| 442 | stream: Some(Box::pin(body.into_data_stream().map(|chunk| { |
| 443 | chunk |
| 444 | .map(|bytes| bytes.to_vec()) |
| 445 | .map_err(|error| format!("asset response stream: {error}")) |
| 446 | }))), |
| 447 | headers: parts |
| 448 | .headers |
| 449 | .iter() |
| 450 | .map(|(name, value)| { |
| 451 | ( |
| 452 | name.as_str().to_string(), |
| 453 | value.to_str().unwrap_or_default().to_string(), |
| 454 | ) |
| 455 | }) |
| 456 | .collect(), |
| 457 | websocket: None, |
| 458 | write_position: None, |
| 459 | observed_position: None, |
| 460 | }) |
| 461 | } |
| 462 | |
| 463 | fn apply_headers( |
| 464 | &self, |
| 465 | headers: &mut HeaderMap, |
| 466 | host: Option<&str>, |
| 467 | path: &str, |
| 468 | ) -> anyhow::Result<()> { |
| 469 | let mut custom = std::collections::HashSet::new(); |
| 470 | for rule in &self.inner.header_rules { |
| 471 | let Some(captures) = rule.pattern.matches(host, path) else { |
| 472 | continue; |
| 473 | }; |
| 474 | for operation in &rule.operations { |
| 475 | match operation { |
| 476 | HeaderOperation::Remove(name) => { |
| 477 | headers.remove(name); |
| 478 | custom.insert(name.clone()); |
| 479 | } |
| 480 | HeaderOperation::Set(name, value) => { |
| 481 | let value = substitute(value, &captures); |
| 482 | if custom.insert(name.clone()) { |
| 483 | headers.remove(name); |
| 484 | } |
| 485 | let combined = match headers.get(name).and_then(|value| value.to_str().ok()) |
| 486 | { |
| 487 | Some(previous) => format!("{previous}, {value}"), |
| 488 | None => value, |
| 489 | }; |
| 490 | headers.insert( |
| 491 | name.parse::<axum::http::HeaderName>() |
| 492 | .context("invalid custom asset header name")?, |
| 493 | HeaderValue::from_str(&combined) |
| 494 | .context("invalid custom asset header value")?, |
| 495 | ); |
| 496 | } |
| 497 | } |
| 498 | } |
| 499 | } |
| 500 | Ok(()) |
| 501 | } |
| 502 | |
| 503 | /// A route from a NEWER deployment's index, when the fleet pointer has |
| 504 | /// moved past the one this process booted with. Best-effort: every |
| 505 | /// failure keeps the booted behavior, so the fallback can make an asset |
| 506 | /// appear but never disappear. The lock never crosses I/O — the refresh |
| 507 | /// runs in a spawned task on the host runtime and the triggering miss |
| 508 | /// routes against the last adopted snapshot, so a degraded bucket |
| 509 | /// degrades only the fallback, never the miss path. One refresh per |
| 510 | /// `FALLBACK_CHECK_MS`, and the `refreshing` latch keeps a refresh that |
| 511 | /// outlives the interval from stacking a second one behind it |
| 512 | /// (denoland/celld#161). |
| 513 | fn newer_deployment_route(&self, path: &str) -> Option<Route> { |
| 514 | self.inner.fallback.as_ref()?; |
| 515 | let (snapshot, refresh_due) = { |
| 516 | let mut state = self.inner.fallback_state.lock().unwrap(); |
| 517 | let due = !state.refreshing |
| 518 | && state.checked.is_none_or(|at| { |
| 519 | at.elapsed() >= std::time::Duration::from_millis(FALLBACK_CHECK_MS) |
| 520 | }); |
| 521 | if due { |
| 522 | state.refreshing = true; |
| 523 | state.checked = Some(std::time::Instant::now()); |
| 524 | } |
| 525 | (state.index.clone(), due) |
| 526 | }; |
| 527 | if refresh_due { |
| 528 | let resolver = self.clone(); |
| 529 | crate::asyncrt::op_handle().spawn(async move { |
| 530 | resolver.refresh_fallback().await; |
| 531 | }); |
| 532 | } |
| 533 | let index = snapshot?; |
| 534 | match route(&index, path, false) { |
| 535 | Route::Missing => None, |
| 536 | found => Some(found), |
| 537 | } |
| 538 | } |
| 539 | |
| 540 | /// One refresh pass: read the pointer, adopt a newer deployment's |
| 541 | /// checksum-validated index, clear the adoption when the pointer moved |
| 542 | /// BACK to the booted deployment — a rollback must withdraw the rolled- |
| 543 | /// back assets, not pin them until restart. |
| 544 | async fn refresh_fallback(&self) { |
| 545 | let Some(source) = self.inner.fallback.as_ref() else { |
| 546 | return; |
| 547 | }; |
| 548 | let adopted = self.inner.fallback_state.lock().unwrap().prefix.clone(); |
| 549 | let outcome = self.adopt_newer_index(source, adopted.as_deref()).await; |
| 550 | let mut state = self.inner.fallback_state.lock().unwrap(); |
| 551 | state.refreshing = false; |
| 552 | match outcome { |
| 553 | Ok(Adoption::Newer { prefix, index }) => { |
| 554 | state.prefix = Some(prefix); |
| 555 | state.index = Some(Arc::new(*index)); |
| 556 | } |
| 557 | Ok(Adoption::Booted) => { |
| 558 | state.prefix = None; |
| 559 | state.index = None; |
| 560 | } |
| 561 | Ok(Adoption::Unchanged) => {} |
| 562 | Err(error) => { |
| 563 | tracing::warn!(%error, "asset version-skew fallback refresh failed"); |
| 564 | } |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | /// Read the pointer and, when it names a deployment this resolver has |
| 569 | /// not adopted, load and validate that deployment's asset index with |
| 570 | /// the same gates the boot path applies. |
| 571 | async fn adopt_newer_index( |
| 572 | &self, |
| 573 | source: &FallbackSource, |
| 574 | adopted: Option<&str>, |
| 575 | ) -> anyhow::Result<Adoption> { |
| 576 | let bucket = &self.inner.bucket; |
| 577 | let (bytes, _) = bucket |
| 578 | .get(&source.pointer_key) |
| 579 | .await? |
| 580 | .with_context(|| format!("read {}", source.pointer_key))?; |
| 581 | let pointer: DeployPointer = |
| 582 | serde_json::from_slice(&bytes).context("decode deploy pointer")?; |
| 583 | if pointer.prefix == source.boot_prefix { |
| 584 | return Ok(Adoption::Booted); |
| 585 | } |
| 586 | if Some(pointer.prefix.as_str()) == adopted { |
| 587 | return Ok(Adoption::Unchanged); |
| 588 | } |
| 589 | let manifest_key = format!("{}/manifest.json", pointer.prefix); |
| 590 | let (bytes, _) = bucket |
| 591 | .get(&manifest_key) |
| 592 | .await? |
| 593 | .with_context(|| format!("read {manifest_key}"))?; |
| 594 | let manifest: Manifest = |
| 595 | serde_json::from_slice(&bytes).context("decode deployment manifest")?; |
| 596 | crate::protocol::validate_required_features(&manifest.required_features)?; |
| 597 | let Some(reference) = manifest.assets else { |
| 598 | // The newer deployment has no assets: adopt an empty index so |
| 599 | // the pointer is not re-fetched for every miss until it moves. |
| 600 | return Ok(Adoption::Newer { |
| 601 | prefix: pointer.prefix, |
| 602 | index: Box::default(), |
| 603 | }); |
| 604 | }; |
| 605 | let index_key = format!("{}/{}", pointer.prefix, reference.index); |
| 606 | let (bytes, _) = bucket |
| 607 | .get(&index_key) |
| 608 | .await? |
| 609 | .with_context(|| format!("read {index_key}"))?; |
| 610 | let sha256 = format!("{:x}", Sha256::digest(&bytes)); |
| 611 | if sha256 != reference.sha256 { |
| 612 | return Err(anyhow!("fallback asset index checksum mismatch")); |
| 613 | } |
| 614 | let index: AssetIndex = serde_json::from_slice(&bytes).context("decode asset index")?; |
| 615 | validate_index(&index, &reference)?; |
| 616 | Ok(Adoption::Newer { |
| 617 | prefix: pointer.prefix, |
| 618 | index: Box::new(index), |
| 619 | }) |
| 620 | } |
| 621 | |
| 622 | fn navigation_prefers_asset_serving(&self, headers: &HeaderMap) -> bool { |
| 623 | if headers |
| 624 | .get("sec-fetch-mode") |
| 625 | .and_then(|value| value.to_str().ok()) |
| 626 | != Some("navigate") |
| 627 | { |
| 628 | return false; |
| 629 | } |
| 630 | let config = &self.inner.index.config; |
| 631 | if config |
| 632 | .compatibility_flags |
| 633 | .iter() |
| 634 | .any(|flag| flag == "assets_navigation_has_no_effect") |
| 635 | { |
| 636 | return false; |
| 637 | } |
| 638 | config |
| 639 | .compatibility_flags |
| 640 | .iter() |
| 641 | .any(|flag| flag == "assets_navigation_prefers_asset_serving") |
| 642 | || config |
| 643 | .compatibility_date |
| 644 | .as_deref() |
| 645 | .is_some_and(|date| date >= "2025-04-01") |
| 646 | } |
| 647 | |
| 648 | async fn open_asset( |
| 649 | &self, |
| 650 | resolved_path: &str, |
| 651 | entry: &AssetEntry, |
| 652 | ) -> anyhow::Result<tokio::fs::File> { |
| 653 | let cache_path = cache_path(&self.inner.cache_root, &entry.sha256)?; |
| 654 | if let Some(file) = valid_cached_file(&cache_path, entry.bytes).await? { |
| 655 | touch_cache_file(cache_path.clone()); |
| 656 | return Ok(file); |
| 657 | } |
| 658 | |
| 659 | let lock = { |
| 660 | let mut locks = self.inner.download_locks.lock().await; |
| 661 | locks |
| 662 | .entry(entry.sha256.clone()) |
| 663 | .or_insert_with(|| Arc::new(Mutex::new(()))) |
| 664 | .clone() |
| 665 | }; |
| 666 | let _guard = lock.lock().await; |
| 667 | if let Some(file) = valid_cached_file(&cache_path, entry.bytes).await? { |
| 668 | touch_cache_file(cache_path.clone()); |
| 669 | return Ok(file); |
| 670 | } |
| 671 | |
| 672 | let parent = cache_path |
| 673 | .parent() |
| 674 | .context("asset cache path has no parent")?; |
| 675 | tokio::fs::create_dir_all(parent) |
| 676 | .await |
| 677 | .with_context(|| format!("create asset cache shard {}", parent.display()))?; |
| 678 | let mut random = rand::rngs::OsRng; |
| 679 | let temporary = parent.join(format!(".{}.{}.tmp", std::process::id(), random.next_u64())); |
| 680 | let key = asset_blob_key(&entry.sha256) |
| 681 | .ok_or_else(|| anyhow!("invalid asset digest for {resolved_path}"))?; |
| 682 | let (body, _) = self |
| 683 | .inner |
| 684 | .bucket |
| 685 | .get(&key) |
| 686 | .await |
| 687 | .with_context(|| format!("read asset {resolved_path}"))? |
| 688 | .with_context(|| { |
| 689 | format!( |
| 690 | "asset {resolved_path} missing from {}://{}/{key}", |
| 691 | self.inner.bucket.scheme(), |
| 692 | self.inner.bucket.name |
| 693 | ) |
| 694 | })?; |
| 695 | if body.len() as u64 != entry.bytes { |
| 696 | return Err(anyhow!("asset {resolved_path} has the wrong bucket size")); |
| 697 | } |
| 698 | let mut file = tokio::fs::OpenOptions::new() |
| 699 | .create_new(true) |
| 700 | .write(true) |
| 701 | .open(&temporary) |
| 702 | .await |
| 703 | .with_context(|| format!("create asset cache file {}", temporary.display()))?; |
| 704 | let write = async { |
| 705 | file.write_all(&body).await?; |
| 706 | file.sync_all().await?; |
| 707 | anyhow::Ok(()) |
| 708 | } |
| 709 | .await; |
| 710 | if let Err(error) = write { |
| 711 | drop(file); |
| 712 | let _ = tokio::fs::remove_file(&temporary).await; |
| 713 | return Err(error); |
| 714 | } |
| 715 | drop(file); |
| 716 | let actual = format!("{:x}", Sha256::digest(&body)); |
| 717 | if actual != entry.sha256 { |
| 718 | let _ = tokio::fs::remove_file(&temporary).await; |
| 719 | return Err(anyhow!( |
| 720 | "asset {resolved_path} checksum mismatch: expected {}, got {actual}", |
| 721 | entry.sha256 |
| 722 | )); |
| 723 | } |
| 724 | if valid_cached_file(&cache_path, entry.bytes).await?.is_some() { |
| 725 | let _ = tokio::fs::remove_file(&temporary).await; |
| 726 | } else { |
| 727 | tokio::fs::rename(&temporary, &cache_path) |
| 728 | .await |
| 729 | .with_context(|| { |
| 730 | format!( |
| 731 | "publish asset cache file {} -> {}", |
| 732 | temporary.display(), |
| 733 | cache_path.display() |
| 734 | ) |
| 735 | })?; |
| 736 | } |
| 737 | let file = tokio::fs::File::open(&cache_path) |
| 738 | .await |
| 739 | .with_context(|| format!("open asset cache file {}", cache_path.display()))?; |
| 740 | touch_cache_file(cache_path); |
| 741 | let resolver = self.clone(); |
| 742 | tokio::spawn(async move { |
| 743 | if let Err(error) = resolver.cleanup_cache().await { |
| 744 | tracing::warn!( |
| 745 | event = "asset_cache_cleanup_failed", |
| 746 | %error, |
| 747 | "could not enforce the local asset cache bound" |
| 748 | ); |
| 749 | } |
| 750 | }); |
| 751 | Ok(file) |
| 752 | } |
| 753 | |
| 754 | async fn cleanup_cache(&self) -> anyhow::Result<()> { |
| 755 | let _guard = self.inner.cleanup_lock.lock().await; |
| 756 | let root = self.inner.cache_root.clone(); |
| 757 | let limit = self.inner.cache_max_bytes; |
| 758 | tokio::task::spawn_blocking(move || cleanup_cache_files(&root, limit)) |
| 759 | .await |
| 760 | .context("join asset cache cleanup")? |
| 761 | } |
| 762 | } |
| 763 | |
| 764 | impl RulePattern { |
| 765 | fn parse(value: &str, allow_absolute: bool) -> anyhow::Result<Self> { |
| 766 | let (host, path) = if value.starts_with("https://") { |
| 767 | if !allow_absolute { |
| 768 | return Err(anyhow!( |
| 769 | "absolute URLs are not supported in _redirects sources" |
| 770 | )); |
| 771 | } |
| 772 | let url = url::Url::parse(value).context("invalid absolute asset rule URL")?; |
| 773 | if url.scheme() != "https" || url.port().is_some() || url.query().is_some() { |
| 774 | return Err(anyhow!( |
| 775 | "absolute asset rules require an HTTPS host without a port" |
| 776 | )); |
| 777 | } |
| 778 | ( |
| 779 | Some(compile_rule_component( |
| 780 | url.host_str().context("asset rule URL has no host")?, |
| 781 | '.', |
| 782 | )?), |
| 783 | url.path().to_string(), |
| 784 | ) |
| 785 | } else { |
| 786 | if !value.starts_with('/') { |
| 787 | return Err(anyhow!("asset rule paths must begin with '/'")); |
| 788 | } |
| 789 | (None, value.to_string()) |
| 790 | }; |
| 791 | Ok(Self { |
| 792 | host, |
| 793 | path: compile_rule_component(&path, '/')?, |
| 794 | }) |
| 795 | } |
| 796 | |
| 797 | fn matches(&self, host: Option<&str>, path: &str) -> Option<HashMap<String, String>> { |
| 798 | let mut values = HashMap::new(); |
| 799 | if let Some(pattern) = &self.host { |
| 800 | let captures = pattern.captures(host?)?; |
| 801 | collect_captures(pattern, &captures, &mut values); |
| 802 | } |
| 803 | let captures = self.path.captures(path)?; |
| 804 | collect_captures(&self.path, &captures, &mut values); |
| 805 | Some(values) |
| 806 | } |
| 807 | } |
| 808 | |
| 809 | fn compile_rule_component(value: &str, delimiter: char) -> anyhow::Result<regex::Regex> { |
| 810 | let mut expression = String::from("^"); |
| 811 | let mut characters = value.chars().peekable(); |
| 812 | let mut captures = std::collections::HashSet::new(); |
| 813 | while let Some(character) = characters.next() { |
| 814 | if character == '*' { |
| 815 | if !captures.insert("splat".to_string()) { |
| 816 | return Err(anyhow!("asset rules may contain only one splat")); |
| 817 | } |
| 818 | expression.push_str("(?P<splat>.*)"); |
| 819 | continue; |
| 820 | } |
| 821 | if character == ':' |
| 822 | && characters |
| 823 | .peek() |
| 824 | .is_some_and(|next| next.is_ascii_alphabetic()) |
| 825 | { |
| 826 | let mut name = String::new(); |
| 827 | while characters |
| 828 | .peek() |
| 829 | .is_some_and(|next| next.is_ascii_alphanumeric() || *next == '_') |
| 830 | { |
| 831 | name.push(characters.next().unwrap()); |
| 832 | } |
| 833 | if !captures.insert(name.clone()) { |
| 834 | return Err(anyhow!("asset rule placeholder {name:?} is duplicated")); |
| 835 | } |
| 836 | expression.push_str(&format!( |
| 837 | "(?P<{name}>[^{delimiter}]+)", |
| 838 | delimiter = regex::escape(&delimiter.to_string()) |
| 839 | )); |
| 840 | continue; |
| 841 | } |
| 842 | expression.push_str(®ex::escape(&character.to_string())); |
| 843 | } |
| 844 | expression.push('$'); |
| 845 | regex::Regex::new(&expression).context("compile asset routing rule") |
| 846 | } |
| 847 | |
| 848 | fn collect_captures( |
| 849 | pattern: ®ex::Regex, |
| 850 | captures: ®ex::Captures<'_>, |
| 851 | values: &mut HashMap<String, String>, |
| 852 | ) { |
| 853 | for name in pattern.capture_names().flatten() { |
| 854 | if let Some(value) = captures.name(name) { |
| 855 | values.insert(name.to_string(), value.as_str().to_string()); |
| 856 | } |
| 857 | } |
| 858 | } |
| 859 | |
| 860 | fn substitute(template: &str, captures: &HashMap<String, String>) -> String { |
| 861 | let mut result = String::with_capacity(template.len()); |
| 862 | let mut characters = template.chars().peekable(); |
| 863 | while let Some(character) = characters.next() { |
| 864 | if character != ':' |
| 865 | || !characters |
| 866 | .peek() |
| 867 | .is_some_and(|next| next.is_ascii_alphabetic()) |
| 868 | { |
| 869 | result.push(character); |
| 870 | continue; |
| 871 | } |
| 872 | let mut name = String::new(); |
| 873 | while characters |
| 874 | .peek() |
| 875 | .is_some_and(|next| next.is_ascii_alphanumeric() || *next == '_') |
| 876 | { |
| 877 | name.push(characters.next().unwrap()); |
| 878 | } |
| 879 | if let Some(value) = captures.get(&name) { |
| 880 | result.push_str(value); |
| 881 | } else { |
| 882 | result.push(':'); |
| 883 | result.push_str(&name); |
| 884 | } |
| 885 | } |
| 886 | result |
| 887 | } |
| 888 | |
| 889 | fn parse_header_rules(value: &str) -> anyhow::Result<Vec<HeaderRule>> { |
| 890 | let mut rules: Vec<HeaderRule> = Vec::new(); |
| 891 | let mut current: Option<usize> = None; |
| 892 | for (line_number, line) in value.lines().enumerate() { |
| 893 | if line.len() > 2_000 { |
| 894 | return Err(anyhow!( |
| 895 | "_headers line {} exceeds 2,000 characters", |
| 896 | line_number + 1 |
| 897 | )); |
| 898 | } |
| 899 | let trimmed = line.trim(); |
| 900 | if trimmed.is_empty() || trimmed.starts_with('#') { |
| 901 | continue; |
| 902 | } |
| 903 | if line.starts_with(char::is_whitespace) { |
| 904 | let index = current.context("_headers contains an operation before its URL pattern")?; |
| 905 | if let Some(name) = trimmed.strip_prefix("! ") { |
| 906 | let name = parse_custom_header_name(name)?; |
| 907 | rules[index].operations.push(HeaderOperation::Remove(name)); |
| 908 | } else { |
| 909 | let (name, value) = trimmed |
| 910 | .split_once(':') |
| 911 | .context("_headers operation is missing ':'")?; |
| 912 | let name = parse_custom_header_name(name)?; |
| 913 | HeaderValue::from_str(value.trim()).context("invalid _headers value")?; |
| 914 | rules[index] |
| 915 | .operations |
| 916 | .push(HeaderOperation::Set(name, value.trim().to_string())); |
| 917 | } |
| 918 | continue; |
| 919 | } |
| 920 | if rules.len() >= 100 { |
| 921 | return Err(anyhow!("_headers exceeds 100 rules")); |
| 922 | } |
| 923 | rules.push(HeaderRule { |
| 924 | pattern: RulePattern::parse(trimmed, true) |
| 925 | .with_context(|| format!("invalid _headers rule on line {}", line_number + 1))?, |
| 926 | operations: Vec::new(), |
| 927 | }); |
| 928 | current = Some(rules.len() - 1); |
| 929 | } |
| 930 | Ok(rules) |
| 931 | } |
| 932 | |
| 933 | fn parse_custom_header_name(value: &str) -> anyhow::Result<String> { |
| 934 | let name = value |
| 935 | .trim() |
| 936 | .parse::<axum::http::HeaderName>() |
| 937 | .context("invalid _headers name")? |
| 938 | .as_str() |
| 939 | .to_string(); |
| 940 | if matches!( |
| 941 | name.as_str(), |
| 942 | "connection" | "content-length" | "transfer-encoding" |
| 943 | ) { |
| 944 | return Err(anyhow!("_headers cannot override {name}")); |
| 945 | } |
| 946 | Ok(name) |
| 947 | } |
| 948 | |
| 949 | fn parse_redirect_rules(value: &str) -> anyhow::Result<Vec<RedirectRule>> { |
| 950 | let mut rules = Vec::new(); |
| 951 | let mut static_rules = 0_usize; |
| 952 | let mut dynamic_rules = 0_usize; |
| 953 | for (line_number, line) in value.lines().enumerate() { |
| 954 | let line = line.trim(); |
| 955 | if line.is_empty() || line.starts_with('#') { |
| 956 | continue; |
| 957 | } |
| 958 | if line.len() > 1_000 { |
| 959 | return Err(anyhow!( |
| 960 | "_redirects line {} exceeds 1,000 characters", |
| 961 | line_number + 1 |
| 962 | )); |
| 963 | } |
| 964 | let parts = line.split_whitespace().collect::<Vec<_>>(); |
| 965 | if !(2..=3).contains(&parts.len()) { |
| 966 | return Err(anyhow!( |
| 967 | "invalid _redirects rule on line {}", |
| 968 | line_number + 1 |
| 969 | )); |
| 970 | } |
| 971 | let status = match parts.get(2) { |
| 972 | Some(value) => value.parse::<u16>().context("invalid _redirects status")?, |
| 973 | None => 302, |
| 974 | }; |
| 975 | if !matches!(status, 200 | 301 | 302 | 303 | 307 | 308) { |
| 976 | return Err(anyhow!("unsupported _redirects status {status}")); |
| 977 | } |
| 978 | if status == 200 && !parts[1].starts_with('/') { |
| 979 | return Err(anyhow!("_redirects proxy destinations must be local paths")); |
| 980 | } |
| 981 | if status != 200 |
| 982 | && !parts[1].starts_with('/') |
| 983 | && url::Url::parse(parts[1]) |
| 984 | .ok() |
| 985 | .is_none_or(|url| !matches!(url.scheme(), "http" | "https")) |
| 986 | { |
| 987 | return Err(anyhow!("invalid _redirects destination")); |
| 988 | } |
| 989 | let dynamic = parts[0].contains('*') || parts[0].contains(':'); |
| 990 | if dynamic { |
| 991 | dynamic_rules += 1; |
| 992 | } else { |
| 993 | static_rules += 1; |
| 994 | } |
| 995 | if static_rules > 2_000 || dynamic_rules > 100 || rules.len() >= 2_100 { |
| 996 | return Err(anyhow!("_redirects exceeds Cloudflare's rule limits")); |
| 997 | } |
| 998 | rules.push(RedirectRule { |
| 999 | pattern: RulePattern::parse(parts[0], false).with_context(|| { |
| 1000 | format!("invalid _redirects source on line {}", line_number + 1) |
| 1001 | })?, |
| 1002 | destination: parts[1].to_string(), |
| 1003 | status, |
| 1004 | }); |
| 1005 | } |
| 1006 | Ok(rules) |
| 1007 | } |
| 1008 | |
| 1009 | fn strip_port(host: &str) -> &str { |
| 1010 | let original = host; |
| 1011 | if let Some(host) = host.strip_prefix('[') { |
| 1012 | return host.split_once(']').map_or(original, |(host, _)| host); |
| 1013 | } |
| 1014 | host.rsplit_once(':') |
| 1015 | .filter(|(_, port)| port.bytes().all(|byte| byte.is_ascii_digit())) |
| 1016 | .map_or(host, |(host, _)| host) |
| 1017 | } |
| 1018 | |
| 1019 | #[cfg(all(test, celld_internal_tests))] |
| 1020 | mod internal_tests { |
| 1021 | include!(env!("CELLD_INTERNAL_ASSETS_TESTS")); |
| 1022 | } |
| 1023 | |
| 1024 | fn route(index: &AssetIndex, path: &str, include_not_found: bool) -> Route { |
| 1025 | let entries = &index.entries; |
| 1026 | let html = index |
| 1027 | .config |
| 1028 | .html_handling |
| 1029 | .as_deref() |
| 1030 | .unwrap_or("auto-trailing-slash"); |
| 1031 | |
| 1032 | // Non-HTML assets are never affected by trailing-slash canonicalization. |
| 1033 | if !path.ends_with(".html") { |
| 1034 | if let Some(entry) = entries.get(path) { |
| 1035 | return asset_route(path, entry, StatusCode::OK); |
| 1036 | } |
| 1037 | } |
| 1038 | |
| 1039 | if html != "none" { |
| 1040 | if let Some((asset_path, entry)) = html_asset(entries, path) { |
| 1041 | let canonical = canonical_html_path(&asset_path, html); |
| 1042 | if path != canonical { |
| 1043 | return Route::Redirect { |
| 1044 | location: canonical, |
| 1045 | status: StatusCode::TEMPORARY_REDIRECT, |
| 1046 | }; |
| 1047 | } |
| 1048 | return asset_route(&asset_path, entry, StatusCode::OK); |
| 1049 | } |
| 1050 | } else if let Some(entry) = entries.get(path) { |
| 1051 | return asset_route(path, entry, StatusCode::OK); |
| 1052 | } |
| 1053 | |
| 1054 | if !include_not_found { |
| 1055 | return Route::Missing; |
| 1056 | } |
| 1057 | not_found_route(index, path) |
| 1058 | } |
| 1059 | |
| 1060 | /// The `not_found_handling` tail of `route`, separated so the version-skew |
| 1061 | /// fallback can run between an exact miss and the not-found fabrication: a |
| 1062 | /// single-page application must serve a NEW deployment's hashed asset, not |
| 1063 | /// its own stale `/index.html`, when both are possible. |
| 1064 | fn not_found_route(index: &AssetIndex, path: &str) -> Route { |
| 1065 | let entries = &index.entries; |
| 1066 | match index.config.not_found_handling.as_deref() { |
| 1067 | Some("single-page-application") => entries |
| 1068 | .get("/index.html") |
| 1069 | .map(|entry| asset_route("/index.html", entry, StatusCode::OK)) |
| 1070 | .unwrap_or(Route::Missing), |
| 1071 | Some("404-page") => nearest_404(entries, path) |
| 1072 | .map(|(path, entry)| asset_route(&path, entry, StatusCode::NOT_FOUND)) |
| 1073 | .unwrap_or(Route::Missing), |
| 1074 | _ => Route::Missing, |
| 1075 | } |
| 1076 | } |
| 1077 | |
| 1078 | fn asset_route(path: &str, entry: &AssetEntry, status: StatusCode) -> Route { |
| 1079 | Route::Asset { |
| 1080 | path: path.to_string(), |
| 1081 | entry: entry.clone(), |
| 1082 | status, |
| 1083 | } |
| 1084 | } |
| 1085 | |
| 1086 | fn html_asset<'a>( |
| 1087 | entries: &'a std::collections::BTreeMap<String, AssetEntry>, |
| 1088 | path: &str, |
| 1089 | ) -> Option<(String, &'a AssetEntry)> { |
| 1090 | let mut candidates = Vec::with_capacity(3); |
| 1091 | if path.ends_with(".html") { |
| 1092 | candidates.push(path.to_string()); |
| 1093 | } else if path.ends_with("/index") { |
| 1094 | candidates.push(format!("{path}.html")); |
| 1095 | } else if path.ends_with('/') { |
| 1096 | candidates.push(format!("{path}index.html")); |
| 1097 | if path != "/" { |
| 1098 | candidates.push(format!("{}.html", path.trim_end_matches('/'))); |
| 1099 | } |
| 1100 | } else { |
| 1101 | candidates.push(format!("{path}.html")); |
| 1102 | candidates.push(format!("{path}/index.html")); |
| 1103 | } |
| 1104 | candidates |
| 1105 | .into_iter() |
| 1106 | .find_map(|candidate| entries.get(&candidate).map(|entry| (candidate, entry))) |
| 1107 | } |
| 1108 | |
| 1109 | fn canonical_html_path(asset_path: &str, html_handling: &str) -> String { |
| 1110 | if asset_path == "/index.html" { |
| 1111 | return "/".to_string(); |
| 1112 | } |
| 1113 | let base = if let Some(parent) = asset_path.strip_suffix("/index.html") { |
| 1114 | parent |
| 1115 | } else { |
| 1116 | asset_path.strip_suffix(".html").unwrap_or(asset_path) |
| 1117 | }; |
| 1118 | match html_handling { |
| 1119 | "force-trailing-slash" => format!("{}/", base.trim_end_matches('/')), |
| 1120 | "drop-trailing-slash" => { |
| 1121 | let value = base.trim_end_matches('/'); |
| 1122 | if value.is_empty() { |
| 1123 | "/".to_string() |
| 1124 | } else { |
| 1125 | value.to_string() |
| 1126 | } |
| 1127 | } |
| 1128 | _ if asset_path.ends_with("/index.html") => format!("{}/", base.trim_end_matches('/')), |
| 1129 | _ => base.trim_end_matches('/').to_string(), |
| 1130 | } |
| 1131 | } |
| 1132 | |
| 1133 | fn nearest_404<'a>( |
| 1134 | entries: &'a std::collections::BTreeMap<String, AssetEntry>, |
| 1135 | path: &str, |
| 1136 | ) -> Option<(String, &'a AssetEntry)> { |
| 1137 | let mut directory = if path.ends_with('/') { |
| 1138 | path.trim_end_matches('/').to_string() |
| 1139 | } else { |
| 1140 | path.rsplit_once('/') |
| 1141 | .map(|(parent, _)| parent.to_string()) |
| 1142 | .unwrap_or_default() |
| 1143 | }; |
| 1144 | loop { |
| 1145 | let candidate = if directory.is_empty() { |
| 1146 | "/404.html".to_string() |
| 1147 | } else { |
| 1148 | format!("{directory}/404.html") |
| 1149 | }; |
| 1150 | if let Some(entry) = entries.get(&candidate) { |
| 1151 | return Some((candidate, entry)); |
| 1152 | } |
| 1153 | if directory.is_empty() { |
| 1154 | return None; |
| 1155 | } |
| 1156 | directory = directory |
| 1157 | .rsplit_once('/') |
| 1158 | .map(|(parent, _)| parent.to_string()) |
| 1159 | .unwrap_or_default(); |
| 1160 | } |
| 1161 | } |
| 1162 | |
| 1163 | fn etag_matches(value: &str, etag: &str) -> bool { |
| 1164 | value.split(',').any(|candidate| { |
| 1165 | let candidate = candidate.trim(); |
| 1166 | candidate == "*" || candidate == etag || candidate.strip_prefix("W/") == Some(etag) |
| 1167 | }) |
| 1168 | } |
| 1169 | |
| 1170 | fn requested_range(headers: &HeaderMap, bytes: u64, etag: &str) -> RequestedRange { |
| 1171 | let Some(value) = headers.get("range").and_then(|value| value.to_str().ok()) else { |
| 1172 | return RequestedRange::Full; |
| 1173 | }; |
| 1174 | if headers |
| 1175 | .get("if-range") |
| 1176 | .and_then(|value| value.to_str().ok()) |
| 1177 | .is_some_and(|value| value.trim() != etag) |
| 1178 | { |
| 1179 | return RequestedRange::Full; |
| 1180 | } |
| 1181 | let Some(value) = value.strip_prefix("bytes=") else { |
| 1182 | return RequestedRange::Unsatisfiable; |
| 1183 | }; |
| 1184 | if value.contains(',') || bytes == 0 { |
| 1185 | return RequestedRange::Unsatisfiable; |
| 1186 | } |
| 1187 | let Some((start, end)) = value.split_once('-') else { |
| 1188 | return RequestedRange::Unsatisfiable; |
| 1189 | }; |
| 1190 | if start.is_empty() { |
| 1191 | let Ok(suffix) = end.parse::<u64>() else { |
| 1192 | return RequestedRange::Unsatisfiable; |
| 1193 | }; |
| 1194 | if suffix == 0 { |
| 1195 | return RequestedRange::Unsatisfiable; |
| 1196 | } |
| 1197 | let length = suffix.min(bytes); |
| 1198 | return RequestedRange::Partial { |
| 1199 | start: bytes - length, |
| 1200 | end: bytes - 1, |
| 1201 | }; |
| 1202 | } |
| 1203 | let Ok(start) = start.parse::<u64>() else { |
| 1204 | return RequestedRange::Unsatisfiable; |
| 1205 | }; |
| 1206 | if start >= bytes { |
| 1207 | return RequestedRange::Unsatisfiable; |
| 1208 | } |
| 1209 | let end = if end.is_empty() { |
| 1210 | bytes - 1 |
| 1211 | } else { |
| 1212 | let Ok(end) = end.parse::<u64>() else { |
| 1213 | return RequestedRange::Unsatisfiable; |
| 1214 | }; |
| 1215 | end.min(bytes - 1) |
| 1216 | }; |
| 1217 | if end < start { |
| 1218 | return RequestedRange::Unsatisfiable; |
| 1219 | } |
| 1220 | RequestedRange::Partial { start, end } |
| 1221 | } |
| 1222 | |
| 1223 | fn cache_path(root: &Path, sha256: &str) -> anyhow::Result<PathBuf> { |
| 1224 | asset_blob_key(sha256) |
| 1225 | .context("invalid asset cache digest") |
| 1226 | .map(|_| root.join(&sha256[..2]).join(sha256)) |
| 1227 | } |
| 1228 | |
| 1229 | async fn valid_cached_file( |
| 1230 | path: &Path, |
| 1231 | expected_bytes: u64, |
| 1232 | ) -> anyhow::Result<Option<tokio::fs::File>> { |
| 1233 | match tokio::fs::File::open(path).await { |
| 1234 | Ok(file) => { |
| 1235 | let metadata = file |
| 1236 | .metadata() |
| 1237 | .await |
| 1238 | .with_context(|| format!("stat asset cache file {}", path.display()))?; |
| 1239 | if metadata.len() == expected_bytes { |
| 1240 | Ok(Some(file)) |
| 1241 | } else { |
| 1242 | drop(file); |
| 1243 | let _ = tokio::fs::remove_file(path).await; |
| 1244 | Ok(None) |
| 1245 | } |
| 1246 | } |
| 1247 | Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), |
| 1248 | Err(error) => { |
| 1249 | Err(error).with_context(|| format!("open asset cache file {}", path.display())) |
| 1250 | } |
| 1251 | } |
| 1252 | } |
| 1253 | |
| 1254 | fn touch_cache_file(path: PathBuf) { |
| 1255 | tokio::task::spawn_blocking(move || { |
| 1256 | let times = std::fs::FileTimes::new().set_modified(std::time::SystemTime::now()); |
| 1257 | let _ = std::fs::File::options() |
| 1258 | .write(true) |
| 1259 | .open(path) |
| 1260 | .and_then(|file| file.set_times(times)); |
| 1261 | }); |
| 1262 | } |
| 1263 | |
| 1264 | fn cleanup_cache_files(root: &Path, limit: u64) -> anyhow::Result<()> { |
| 1265 | let mut files = Vec::new(); |
| 1266 | let mut total = 0_u64; |
| 1267 | for shard in |
| 1268 | std::fs::read_dir(root).with_context(|| format!("scan asset cache {}", root.display()))? |
| 1269 | { |
| 1270 | let shard = shard?; |
| 1271 | if !shard.file_type()?.is_dir() { |
| 1272 | continue; |
| 1273 | } |
| 1274 | for entry in std::fs::read_dir(shard.path())? { |
| 1275 | let entry = entry?; |
| 1276 | let name = entry.file_name(); |
| 1277 | let name = name.to_string_lossy(); |
| 1278 | if name.len() != 64 |
| 1279 | || !name |
| 1280 | .bytes() |
| 1281 | .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte)) |
| 1282 | { |
| 1283 | continue; |
| 1284 | } |
| 1285 | let metadata = entry.metadata()?; |
| 1286 | if !metadata.is_file() { |
| 1287 | continue; |
| 1288 | } |
| 1289 | total = total.saturating_add(metadata.len()); |
| 1290 | files.push(( |
| 1291 | metadata.modified().unwrap_or(std::time::UNIX_EPOCH), |
| 1292 | metadata.len(), |
| 1293 | entry.path(), |
| 1294 | )); |
| 1295 | } |
| 1296 | } |
| 1297 | if total <= limit { |
| 1298 | return Ok(()); |
| 1299 | } |
| 1300 | files.sort_by_key(|(modified, _, _)| *modified); |
| 1301 | for (_, bytes, path) in files { |
| 1302 | if total <= limit { |
| 1303 | break; |
| 1304 | } |
| 1305 | if std::fs::remove_file(&path).is_ok() { |
| 1306 | total = total.saturating_sub(bytes); |
| 1307 | } |
| 1308 | } |
| 1309 | Ok(()) |
| 1310 | } |
| 1311 | |
| 1312 | /// Report the same size-policy mismatch in the builder, managed agent, and serving node. |
| 1313 | pub(crate) fn validate_asset_file_size(path: &str, bytes: u64, limit: u64) -> anyhow::Result<()> { |
| 1314 | if bytes > limit { |
| 1315 | return Err(anyhow!( |
| 1316 | "asset {path:?} size ({bytes} bytes) exceeds CELLD_MAX_ASSET_FILE_BYTES ({limit} bytes)" |
| 1317 | )); |
| 1318 | } |
| 1319 | Ok(()) |
| 1320 | } |
| 1321 | |
| 1322 | fn validate_index(index: &AssetIndex, reference: &AssetManifestRef) -> anyhow::Result<()> { |
| 1323 | let max_file_bytes = crate::env_vars::max_asset_file_bytes()?; |
| 1324 | if index.schema_version != 1 { |
| 1325 | return Err(anyhow!( |
| 1326 | "unsupported asset index schema: {}", |
| 1327 | index.schema_version |
| 1328 | )); |
| 1329 | } |
| 1330 | if index.entries.len() != reference.file_count as usize { |
| 1331 | return Err(anyhow!("asset index file count mismatch")); |
| 1332 | } |
| 1333 | if index.entries.len() > 20_000 { |
| 1334 | return Err(anyhow!("asset index exceeds the file limit")); |
| 1335 | } |
| 1336 | let config = &index.config; |
| 1337 | if !matches!( |
| 1338 | config |
| 1339 | .html_handling |
| 1340 | .as_deref() |
| 1341 | .unwrap_or("auto-trailing-slash"), |
| 1342 | "auto-trailing-slash" | "force-trailing-slash" | "drop-trailing-slash" | "none" |
| 1343 | ) { |
| 1344 | return Err(anyhow!("unsupported asset HTML handling")); |
| 1345 | } |
| 1346 | if !matches!( |
| 1347 | config.not_found_handling.as_deref().unwrap_or("none"), |
| 1348 | "none" | "single-page-application" | "404-page" |
| 1349 | ) { |
| 1350 | return Err(anyhow!("unsupported asset not-found handling")); |
| 1351 | } |
| 1352 | if let Some(binding) = &config.binding { |
| 1353 | let valid = binding.len() <= 128 |
| 1354 | && binding |
| 1355 | .chars() |
| 1356 | .next() |
| 1357 | .is_some_and(|value| value == '_' || value == '$' || value.is_ascii_alphabetic()) |
| 1358 | && binding |
| 1359 | .chars() |
| 1360 | .skip(1) |
| 1361 | .all(|value| value == '_' || value == '$' || value.is_ascii_alphanumeric()); |
| 1362 | if !valid { |
| 1363 | return Err(anyhow!("invalid asset binding name")); |
| 1364 | } |
| 1365 | } |
| 1366 | if let RunWorkerFirst::Routes(routes) = &config.run_worker_first { |
| 1367 | if routes.is_empty() || routes.len() > 100 { |
| 1368 | return Err(anyhow!("invalid asset worker-first route count")); |
| 1369 | } |
| 1370 | let mut positive = false; |
| 1371 | let mut seen = std::collections::HashSet::new(); |
| 1372 | for route in routes { |
| 1373 | if route.starts_with('/') { |
| 1374 | positive = true; |
| 1375 | } else if !route.starts_with("!/") { |
| 1376 | return Err(anyhow!("invalid asset worker-first route: {route:?}")); |
| 1377 | } |
| 1378 | if route.len() > 100 || !seen.insert(route) { |
| 1379 | return Err(anyhow!("invalid asset worker-first route: {route:?}")); |
| 1380 | } |
| 1381 | } |
| 1382 | if !positive { |
| 1383 | return Err(anyhow!("asset worker-first routes require a positive rule")); |
| 1384 | } |
| 1385 | } |
| 1386 | let mut total = 0_u64; |
| 1387 | for (path, entry) in &index.entries { |
| 1388 | if !is_canonical_asset_path(path) || path == "/" || asset_blob_key(&entry.sha256).is_none() |
| 1389 | { |
| 1390 | return Err(anyhow!("invalid asset index entry: {path:?}")); |
| 1391 | } |
| 1392 | validate_asset_file_size(path, entry.bytes, max_file_bytes)?; |
| 1393 | if entry |
| 1394 | .content_type |
| 1395 | .as_deref() |
| 1396 | .is_some_and(|value| value.len() > 200 || value.contains(['\r', '\n'])) |
| 1397 | { |
| 1398 | return Err(anyhow!("invalid asset content type: {path:?}")); |
| 1399 | } |
| 1400 | total = total |
| 1401 | .checked_add(entry.bytes) |
| 1402 | .context("asset index byte count overflow")?; |
| 1403 | } |
| 1404 | if total != reference.total_bytes { |
| 1405 | return Err(anyhow!("asset index total byte count mismatch")); |
| 1406 | } |
| 1407 | if total > 1024 * 1024 * 1024 { |
| 1408 | return Err(anyhow!("asset index exceeds the deployment byte limit")); |
| 1409 | } |
| 1410 | Ok(()) |
| 1411 | } |
| 1412 | |
| 1413 | fn decode_path(path: &str) -> Option<String> { |
| 1414 | if !path.starts_with('/') || path.contains('\\') || path.contains('\0') { |
| 1415 | return None; |
| 1416 | } |
| 1417 | let decoded = percent_decode_str(path).decode_utf8().ok()?.into_owned(); |
| 1418 | if decoded.contains('\\') |
| 1419 | || decoded.contains('\0') |
| 1420 | || decoded.split('/').skip(1).any(|segment| { |
| 1421 | segment.is_empty() && decoded != "/" || segment == "." || segment == ".." |
| 1422 | }) |
| 1423 | { |
| 1424 | return None; |
| 1425 | } |
| 1426 | Some(decoded) |
| 1427 | } |
| 1428 | |
| 1429 | /// A stored path must survive request-path decoding unchanged. The deployer |
| 1430 | /// uses this same predicate because publishing an index with a second decoded |
| 1431 | /// spelling would make every node reject the complete deployment. |
| 1432 | pub(crate) fn is_canonical_asset_path(path: &str) -> bool { |
| 1433 | decode_path(path).as_deref() == Some(path) |
| 1434 | } |
| 1435 | |
| 1436 | fn route_pattern_matches(pattern: &str, path: &str) -> bool { |
| 1437 | let mut expression = String::from("^"); |
| 1438 | for part in pattern.split('*') { |
| 1439 | expression.push_str(®ex::escape(part)); |
| 1440 | expression.push_str(".*"); |
| 1441 | } |
| 1442 | if !pattern.ends_with('*') { |
| 1443 | expression.truncate(expression.len().saturating_sub(2)); |
| 1444 | expression.push('$'); |
| 1445 | } |
| 1446 | regex::Regex::new(&expression).is_ok_and(|pattern| pattern.is_match(path)) |
| 1447 | } |