Diffinery

homeflare/celldpublic

celld/crates/celld/assets.rs
1243 lines · 42.7 KBRaw History
1use crate::js;
2use crate::protocol::{asset_blob_key, AssetEntry, AssetIndex, AssetManifestRef, RunWorkerFirst};
3use anyhow::{anyhow, Context};
4use aws_sdk_s3::Client;
5use axum::body::Body;
6use axum::http::{HeaderMap, HeaderValue, StatusCode};
7use axum::response::Response;
8use futures_util::StreamExt;
9use percent_encoding::percent_decode_str;
10use rand::RngCore;
11use sha2::{Digest, Sha256};
12use std::collections::HashMap;
13use std::path::{Path, PathBuf};
14use std::sync::Arc;
15use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
16use tokio::sync::Mutex;
17use tokio_util::io::ReaderStream;
18
19const DEFAULT_ASSET_CACHE_BYTES: u64 = 512 * 1024 * 1024;
20
21#[derive(Clone)]
22pub struct AssetResolver {
23 inner: Arc<AssetResolverInner>,
24}
25
26struct AssetResolverInner {
27 client: Client,
28 bucket: String,
29 index: AssetIndex,
30 asset_only: bool,
31 cache_root: PathBuf,
32 cache_max_bytes: u64,
33 download_locks: Mutex<HashMap<String, Arc<Mutex<()>>>>,
34 cleanup_lock: Mutex<()>,
35 header_rules: Vec<HeaderRule>,
36 redirect_rules: Vec<RedirectRule>,
37}
38
39enum Route {
40 Asset {
41 path: String,
42 entry: AssetEntry,
43 status: StatusCode,
44 },
45 Redirect {
46 location: String,
47 status: StatusCode,
48 },
49 Missing,
50}
51
52#[derive(Clone, Copy)]
53enum RequestedRange {
54 Full,
55 Partial { start: u64, end: u64 },
56 Unsatisfiable,
57}
58
59struct RulePattern {
60 host: Option<regex::Regex>,
61 path: regex::Regex,
62}
63
64struct HeaderRule {
65 pattern: RulePattern,
66 operations: Vec<HeaderOperation>,
67}
68
69enum HeaderOperation {
70 Set(String, String),
71 Remove(String),
72}
73
74struct RedirectRule {
75 pattern: RulePattern,
76 destination: String,
77 status: u16,
78}
79
80impl AssetResolver {
81 pub async fn load(
82 client: &Client,
83 bucket: &str,
84 prefix: &str,
85 reference: &AssetManifestRef,
86 asset_only: bool,
87 ) -> anyhow::Result<Self> {
88 if reference.index != "assets.json" {
89 return Err(anyhow!("unsupported asset index name: {}", reference.index));
90 }
91 let key = format!("{prefix}/{}", reference.index);
92 let object = client
93 .get_object()
94 .bucket(bucket)
95 .key(&key)
96 .send()
97 .await
98 .with_context(|| format!("read s3://{bucket}/{key}"))?;
99 let bytes = object
100 .body
101 .collect()
102 .await
103 .context("read asset index body")?
104 .into_bytes();
105 let sha256 = format!("{:x}", Sha256::digest(&bytes));
106 if sha256 != reference.sha256 {
107 return Err(anyhow!("asset index checksum mismatch"));
108 }
109 let index: AssetIndex = serde_json::from_slice(&bytes).context("decode asset index")?;
110 validate_index(&index, reference)?;
111 let header_rules = parse_header_rules(index.config.headers.as_deref().unwrap_or(""))?;
112 let redirect_rules = parse_redirect_rules(index.config.redirects.as_deref().unwrap_or(""))?;
113 let cache_root = std::env::var_os("CELLD_ASSET_CACHE_DIR")
114 .map(PathBuf::from)
115 .unwrap_or_else(|| std::env::temp_dir().join("celld").join("asset-cache"));
116 std::fs::create_dir_all(&cache_root)
117 .with_context(|| format!("create asset cache directory {}", cache_root.display()))?;
118 let cache_max_bytes = std::env::var("CELLD_ASSET_CACHE_BYTES")
119 .ok()
120 .and_then(|value| value.parse::<u64>().ok())
121 .unwrap_or(DEFAULT_ASSET_CACHE_BYTES);
122 Ok(Self {
123 inner: Arc::new(AssetResolverInner {
124 client: client.clone(),
125 bucket: bucket.to_string(),
126 index,
127 asset_only,
128 cache_root,
129 cache_max_bytes,
130 download_locks: Mutex::new(HashMap::new()),
131 cleanup_lock: Mutex::new(()),
132 header_rules,
133 redirect_rules,
134 }),
135 })
136 }
137
138 pub fn binding_name(&self) -> Option<&str> {
139 self.inner.index.config.binding.as_deref()
140 }
141
142 pub fn asset_only(&self) -> bool {
143 self.inner.asset_only
144 }
145
146 pub fn should_run_worker_first(&self, encoded_path: &str) -> bool {
147 let Some(path) = decode_path(encoded_path) else {
148 return false;
149 };
150 match &self.inner.index.config.run_worker_first {
151 RunWorkerFirst::Bool(value) => *value,
152 RunWorkerFirst::Routes(rules) => {
153 let excluded = rules
154 .iter()
155 .filter_map(|rule| rule.strip_prefix('!'))
156 .any(|rule| route_pattern_matches(rule, &path));
157 !excluded
158 && rules
159 .iter()
160 .filter(|rule| !rule.starts_with('!'))
161 .any(|rule| route_pattern_matches(rule, &path))
162 }
163 }
164 }
165
166 pub async fn ingress_response(
167 &self,
168 encoded_path: &str,
169 query: Option<&str>,
170 head: bool,
171 request_headers: &HeaderMap,
172 ) -> anyhow::Result<Option<Response>> {
173 let include_not_found =
174 self.inner.asset_only || self.navigation_prefers_asset_serving(request_headers);
175 let host = request_headers
176 .get("host")
177 .and_then(|value| value.to_str().ok())
178 .map(strip_port);
179 self.response(
180 encoded_path,
181 query,
182 host,
183 head,
184 request_headers,
185 include_not_found,
186 )
187 .await
188 }
189
190 async fn response(
191 &self,
192 encoded_path: &str,
193 query: Option<&str>,
194 host: Option<&str>,
195 head: bool,
196 request_headers: &HeaderMap,
197 include_not_found: bool,
198 ) -> anyhow::Result<Option<Response>> {
199 let Some(path) = decode_path(encoded_path) else {
200 return Ok(None);
201 };
202 let mut selected = None;
203 for rule in &self.inner.redirect_rules {
204 let Some(captures) = rule.pattern.matches(host, &path) else {
205 continue;
206 };
207 let destination = substitute(&rule.destination, &captures);
208 if rule.status == 200 {
209 let boundary = destination.find(['?', '#']).unwrap_or(destination.len());
210 let destination_path = &destination[..boundary];
211 if !destination_path.starts_with('/') {
212 return Err(anyhow!("asset proxy destination must be a local path"));
213 }
214 selected = Some(route(&self.inner.index, destination_path, true));
215 } else {
216 let status = StatusCode::from_u16(rule.status)
217 .context("invalid static asset redirect status")?;
218 return Ok(Some(
219 Response::builder()
220 .status(status)
221 .header("location", destination)
222 .body(Body::empty())?,
223 ));
224 }
225 break;
226 }
227 match selected.unwrap_or_else(|| route(&self.inner.index, &path, include_not_found)) {
228 Route::Missing => Ok(None),
229 Route::Redirect {
230 mut location,
231 status,
232 } => {
233 if let Some(query) = query.filter(|value| !value.is_empty()) {
234 location.push('?');
235 location.push_str(query);
236 }
237 Ok(Some(
238 Response::builder()
239 .status(status)
240 .header("location", location)
241 .body(Body::empty())?,
242 ))
243 }
244 Route::Asset {
245 path: resolved_path,
246 entry,
247 status,
248 } => {
249 let etag = format!("\"{}\"", entry.sha256);
250 if request_headers
251 .get("if-none-match")
252 .and_then(|value| value.to_str().ok())
253 .is_some_and(|value| etag_matches(value, &etag))
254 {
255 let mut response = Response::builder()
256 .status(StatusCode::NOT_MODIFIED)
257 .header("etag", etag)
258 .body(Body::empty())?;
259 self.apply_headers(response.headers_mut(), host, &path)?;
260 return Ok(Some(response));
261 }
262 let requested_range = if status == StatusCode::OK {
263 requested_range(request_headers, entry.bytes, &etag)
264 } else {
265 RequestedRange::Full
266 };
267 if matches!(requested_range, RequestedRange::Unsatisfiable) {
268 let mut response = Response::builder()
269 .status(StatusCode::RANGE_NOT_SATISFIABLE)
270 .header("content-range", format!("bytes */{}", entry.bytes))
271 .header("accept-ranges", "bytes")
272 .header("etag", etag)
273 .body(Body::empty())?;
274 self.apply_headers(response.headers_mut(), host, &path)?;
275 return Ok(Some(response));
276 }
277 let (response_status, start, content_length) = match requested_range {
278 RequestedRange::Partial { start, end } => {
279 (StatusCode::PARTIAL_CONTENT, start, end - start + 1)
280 }
281 RequestedRange::Full | RequestedRange::Unsatisfiable => {
282 (status, 0, entry.bytes)
283 }
284 };
285 let mut builder = Response::builder()
286 .status(response_status)
287 .header("content-length", content_length)
288 .header("accept-ranges", "bytes")
289 .header("etag", &etag);
290 if let RequestedRange::Partial { start, end } = requested_range {
291 builder = builder.header(
292 "content-range",
293 format!("bytes {start}-{end}/{}", entry.bytes),
294 );
295 }
296 if !request_headers.contains_key("authorization")
297 && !request_headers.contains_key("range")
298 {
299 builder = builder.header("cache-control", "public, max-age=0, must-revalidate");
300 }
301 if let Some(content_type) = &entry.content_type {
302 builder = builder.header(
303 "content-type",
304 HeaderValue::from_str(content_type)
305 .context("invalid asset content type")?,
306 );
307 }
308 let body = if head {
309 Body::empty()
310 } else {
311 let mut file = self.open_asset(&resolved_path, &entry).await?;
312 if start > 0 {
313 file.seek(std::io::SeekFrom::Start(start))
314 .await
315 .context("seek asset cache file")?;
316 }
317 let stream = ReaderStream::new(file.take(content_length))
318 .map(|result| result.map_err(std::io::Error::other));
319 Body::from_stream(stream)
320 };
321 let mut response = builder.body(body)?;
322 self.apply_headers(response.headers_mut(), host, &path)?;
323 Ok(Some(response))
324 }
325 }
326 }
327
328 pub async fn binding_response(
329 &self,
330 url: &str,
331 method: &str,
332 headers: &[(String, String)],
333 ) -> anyhow::Result<js::HttpResponse> {
334 if !matches!(method, "GET" | "HEAD") {
335 return Ok(js::HttpResponse {
336 status: StatusCode::METHOD_NOT_ALLOWED.as_u16(),
337 body: b"Method not allowed".to_vec(),
338 stream: None,
339 headers: vec![("content-type".into(), "text/plain; charset=utf-8".into())],
340 ws: None,
341 write_position: None,
342 });
343 }
344 let path = url::Url::parse(url).context("invalid assets binding URL")?;
345 let encoded_path = path.path().to_string();
346 let query = path.query().map(str::to_string);
347 let host = path.host_str().map(str::to_string);
348 let mut request_headers = HeaderMap::new();
349 for (name, value) in headers {
350 let Ok(name) = name.parse::<axum::http::HeaderName>() else {
351 continue;
352 };
353 let Ok(value) = HeaderValue::from_str(value) else {
354 continue;
355 };
356 request_headers.append(name, value);
357 }
358 let response = match self
359 .response(
360 &encoded_path,
361 query.as_deref(),
362 host.as_deref(),
363 method == "HEAD",
364 &request_headers,
365 true,
366 )
367 .await?
368 {
369 Some(response) => response,
370 None => Response::builder()
371 .status(StatusCode::NOT_FOUND)
372 .header("content-type", "text/plain; charset=utf-8")
373 .body(Body::from("Not found"))?,
374 };
375 let (parts, body) = response.into_parts();
376 let body = axum::body::to_bytes(body, 25 * 1024 * 1024 + 1)
377 .await
378 .context("buffer assets binding response")?
379 .to_vec();
380 Ok(js::HttpResponse {
381 status: parts.status.as_u16(),
382 body,
383 stream: None,
384 headers: parts
385 .headers
386 .iter()
387 .map(|(name, value)| {
388 (
389 name.as_str().to_string(),
390 value.to_str().unwrap_or_default().to_string(),
391 )
392 })
393 .collect(),
394 ws: None,
395 write_position: None,
396 })
397 }
398
399 fn apply_headers(
400 &self,
401 headers: &mut HeaderMap,
402 host: Option<&str>,
403 path: &str,
404 ) -> anyhow::Result<()> {
405 let mut custom = std::collections::HashSet::new();
406 for rule in &self.inner.header_rules {
407 let Some(captures) = rule.pattern.matches(host, path) else {
408 continue;
409 };
410 for operation in &rule.operations {
411 match operation {
412 HeaderOperation::Remove(name) => {
413 headers.remove(name);
414 custom.insert(name.clone());
415 }
416 HeaderOperation::Set(name, value) => {
417 let value = substitute(value, &captures);
418 if custom.insert(name.clone()) {
419 headers.remove(name);
420 }
421 let combined = match headers.get(name).and_then(|value| value.to_str().ok())
422 {
423 Some(previous) => format!("{previous}, {value}"),
424 None => value,
425 };
426 headers.insert(
427 name.parse::<axum::http::HeaderName>()
428 .context("invalid custom asset header name")?,
429 HeaderValue::from_str(&combined)
430 .context("invalid custom asset header value")?,
431 );
432 }
433 }
434 }
435 }
436 Ok(())
437 }
438
439 fn navigation_prefers_asset_serving(&self, headers: &HeaderMap) -> bool {
440 if headers
441 .get("sec-fetch-mode")
442 .and_then(|value| value.to_str().ok())
443 != Some("navigate")
444 {
445 return false;
446 }
447 let config = &self.inner.index.config;
448 if config
449 .compatibility_flags
450 .iter()
451 .any(|flag| flag == "assets_navigation_has_no_effect")
452 {
453 return false;
454 }
455 config
456 .compatibility_flags
457 .iter()
458 .any(|flag| flag == "assets_navigation_prefers_asset_serving")
459 || config
460 .compatibility_date
461 .as_deref()
462 .is_some_and(|date| date >= "2025-04-01")
463 }
464
465 async fn open_asset(
466 &self,
467 resolved_path: &str,
468 entry: &AssetEntry,
469 ) -> anyhow::Result<tokio::fs::File> {
470 let cache_path = cache_path(&self.inner.cache_root, &entry.sha256)?;
471 if let Some(file) = valid_cached_file(&cache_path, entry.bytes).await? {
472 touch_cache_file(cache_path.clone());
473 return Ok(file);
474 }
475
476 let lock = {
477 let mut locks = self.inner.download_locks.lock().await;
478 locks
479 .entry(entry.sha256.clone())
480 .or_insert_with(|| Arc::new(Mutex::new(())))
481 .clone()
482 };
483 let _guard = lock.lock().await;
484 if let Some(file) = valid_cached_file(&cache_path, entry.bytes).await? {
485 touch_cache_file(cache_path.clone());
486 return Ok(file);
487 }
488
489 let parent = cache_path
490 .parent()
491 .context("asset cache path has no parent")?;
492 tokio::fs::create_dir_all(parent)
493 .await
494 .with_context(|| format!("create asset cache shard {}", parent.display()))?;
495 let mut random = rand::rngs::OsRng;
496 let temporary = parent.join(format!(".{}.{}.tmp", std::process::id(), random.next_u64()));
497 let key = asset_blob_key(&entry.sha256)
498 .ok_or_else(|| anyhow!("invalid asset digest for {resolved_path}"))?;
499 let object = self
500 .inner
501 .client
502 .get_object()
503 .bucket(&self.inner.bucket)
504 .key(&key)
505 .send()
506 .await
507 .with_context(|| {
508 format!(
509 "read asset {resolved_path} from s3://{}/{key}",
510 self.inner.bucket
511 )
512 })?;
513 if object.content_length().unwrap_or(-1) != entry.bytes as i64 {
514 return Err(anyhow!("asset {resolved_path} has the wrong bucket size"));
515 }
516 let mut file = tokio::fs::OpenOptions::new()
517 .create_new(true)
518 .write(true)
519 .open(&temporary)
520 .await
521 .with_context(|| format!("create asset cache file {}", temporary.display()))?;
522 let mut body = object.body;
523 let mut hasher = Sha256::new();
524 let mut bytes = 0_u64;
525 let download = async {
526 while let Some(chunk) = body.next().await {
527 let chunk = chunk.with_context(|| format!("read asset body {resolved_path}"))?;
528 bytes = bytes
529 .checked_add(chunk.len() as u64)
530 .context("asset body size overflow")?;
531 if bytes > entry.bytes {
532 return Err(anyhow!("asset {resolved_path} exceeds its declared size"));
533 }
534 hasher.update(&chunk);
535 file.write_all(&chunk).await?;
536 }
537 file.sync_all().await?;
538 anyhow::Ok(())
539 }
540 .await;
541 if let Err(error) = download {
542 drop(file);
543 let _ = tokio::fs::remove_file(&temporary).await;
544 return Err(error);
545 }
546 drop(file);
547 let actual = format!("{:x}", hasher.finalize());
548 if bytes != entry.bytes || actual != entry.sha256 {
549 let _ = tokio::fs::remove_file(&temporary).await;
550 return Err(anyhow!(
551 "asset {resolved_path} checksum mismatch: expected {}, got {actual}",
552 entry.sha256
553 ));
554 }
555 if valid_cached_file(&cache_path, entry.bytes).await?.is_some() {
556 let _ = tokio::fs::remove_file(&temporary).await;
557 } else {
558 tokio::fs::rename(&temporary, &cache_path)
559 .await
560 .with_context(|| {
561 format!(
562 "publish asset cache file {} -> {}",
563 temporary.display(),
564 cache_path.display()
565 )
566 })?;
567 }
568 let file = tokio::fs::File::open(&cache_path)
569 .await
570 .with_context(|| format!("open asset cache file {}", cache_path.display()))?;
571 touch_cache_file(cache_path);
572 let resolver = self.clone();
573 tokio::spawn(async move {
574 if let Err(error) = resolver.cleanup_cache().await {
575 tracing::warn!(
576 event = "asset_cache_cleanup_failed",
577 %error,
578 "could not enforce the local asset cache bound"
579 );
580 }
581 });
582 Ok(file)
583 }
584
585 async fn cleanup_cache(&self) -> anyhow::Result<()> {
586 let _guard = self.inner.cleanup_lock.lock().await;
587 let root = self.inner.cache_root.clone();
588 let limit = self.inner.cache_max_bytes;
589 tokio::task::spawn_blocking(move || cleanup_cache_files(&root, limit))
590 .await
591 .context("join asset cache cleanup")?
592 }
593}
594
595impl RulePattern {
596 fn parse(value: &str, allow_absolute: bool) -> anyhow::Result<Self> {
597 let (host, path) = if value.starts_with("https://") {
598 if !allow_absolute {
599 return Err(anyhow!(
600 "absolute URLs are not supported in _redirects sources"
601 ));
602 }
603 let url = url::Url::parse(value).context("invalid absolute asset rule URL")?;
604 if url.scheme() != "https" || url.port().is_some() || url.query().is_some() {
605 return Err(anyhow!(
606 "absolute asset rules require an HTTPS host without a port"
607 ));
608 }
609 (
610 Some(compile_rule_component(
611 url.host_str().context("asset rule URL has no host")?,
612 '.',
613 )?),
614 url.path().to_string(),
615 )
616 } else {
617 if !value.starts_with('/') {
618 return Err(anyhow!("asset rule paths must begin with '/'"));
619 }
620 (None, value.to_string())
621 };
622 Ok(Self {
623 host,
624 path: compile_rule_component(&path, '/')?,
625 })
626 }
627
628 fn matches(&self, host: Option<&str>, path: &str) -> Option<HashMap<String, String>> {
629 let mut values = HashMap::new();
630 if let Some(pattern) = &self.host {
631 let captures = pattern.captures(host?)?;
632 collect_captures(pattern, &captures, &mut values);
633 }
634 let captures = self.path.captures(path)?;
635 collect_captures(&self.path, &captures, &mut values);
636 Some(values)
637 }
638}
639
640fn compile_rule_component(value: &str, delimiter: char) -> anyhow::Result<regex::Regex> {
641 let mut expression = String::from("^");
642 let mut characters = value.chars().peekable();
643 let mut captures = std::collections::HashSet::new();
644 while let Some(character) = characters.next() {
645 if character == '*' {
646 if !captures.insert("splat".to_string()) {
647 return Err(anyhow!("asset rules may contain only one splat"));
648 }
649 expression.push_str("(?P<splat>.*)");
650 continue;
651 }
652 if character == ':'
653 && characters
654 .peek()
655 .is_some_and(|next| next.is_ascii_alphabetic())
656 {
657 let mut name = String::new();
658 while characters
659 .peek()
660 .is_some_and(|next| next.is_ascii_alphanumeric() || *next == '_')
661 {
662 name.push(characters.next().unwrap());
663 }
664 if !captures.insert(name.clone()) {
665 return Err(anyhow!("asset rule placeholder {name:?} is duplicated"));
666 }
667 expression.push_str(&format!(
668 "(?P<{name}>[^{delimiter}]+)",
669 delimiter = regex::escape(&delimiter.to_string())
670 ));
671 continue;
672 }
673 expression.push_str(&regex::escape(&character.to_string()));
674 }
675 expression.push('$');
676 regex::Regex::new(&expression).context("compile asset routing rule")
677}
678
679fn collect_captures(
680 pattern: &regex::Regex,
681 captures: &regex::Captures<'_>,
682 values: &mut HashMap<String, String>,
683) {
684 for name in pattern.capture_names().flatten() {
685 if let Some(value) = captures.name(name) {
686 values.insert(name.to_string(), value.as_str().to_string());
687 }
688 }
689}
690
691fn substitute(template: &str, captures: &HashMap<String, String>) -> String {
692 let mut result = String::with_capacity(template.len());
693 let mut characters = template.chars().peekable();
694 while let Some(character) = characters.next() {
695 if character != ':'
696 || !characters
697 .peek()
698 .is_some_and(|next| next.is_ascii_alphabetic())
699 {
700 result.push(character);
701 continue;
702 }
703 let mut name = String::new();
704 while characters
705 .peek()
706 .is_some_and(|next| next.is_ascii_alphanumeric() || *next == '_')
707 {
708 name.push(characters.next().unwrap());
709 }
710 if let Some(value) = captures.get(&name) {
711 result.push_str(value);
712 } else {
713 result.push(':');
714 result.push_str(&name);
715 }
716 }
717 result
718}
719
720fn parse_header_rules(value: &str) -> anyhow::Result<Vec<HeaderRule>> {
721 let mut rules: Vec<HeaderRule> = Vec::new();
722 let mut current: Option<usize> = None;
723 for (line_number, line) in value.lines().enumerate() {
724 if line.len() > 2_000 {
725 return Err(anyhow!(
726 "_headers line {} exceeds 2,000 characters",
727 line_number + 1
728 ));
729 }
730 let trimmed = line.trim();
731 if trimmed.is_empty() || trimmed.starts_with('#') {
732 continue;
733 }
734 if line.starts_with(char::is_whitespace) {
735 let index = current.context("_headers contains an operation before its URL pattern")?;
736 if let Some(name) = trimmed.strip_prefix("! ") {
737 let name = parse_custom_header_name(name)?;
738 rules[index].operations.push(HeaderOperation::Remove(name));
739 } else {
740 let (name, value) = trimmed
741 .split_once(':')
742 .context("_headers operation is missing ':'")?;
743 let name = parse_custom_header_name(name)?;
744 HeaderValue::from_str(value.trim()).context("invalid _headers value")?;
745 rules[index]
746 .operations
747 .push(HeaderOperation::Set(name, value.trim().to_string()));
748 }
749 continue;
750 }
751 if rules.len() >= 100 {
752 return Err(anyhow!("_headers exceeds 100 rules"));
753 }
754 rules.push(HeaderRule {
755 pattern: RulePattern::parse(trimmed, true)
756 .with_context(|| format!("invalid _headers rule on line {}", line_number + 1))?,
757 operations: Vec::new(),
758 });
759 current = Some(rules.len() - 1);
760 }
761 Ok(rules)
762}
763
764fn parse_custom_header_name(value: &str) -> anyhow::Result<String> {
765 let name = value
766 .trim()
767 .parse::<axum::http::HeaderName>()
768 .context("invalid _headers name")?
769 .as_str()
770 .to_string();
771 if matches!(
772 name.as_str(),
773 "connection" | "content-length" | "transfer-encoding"
774 ) {
775 return Err(anyhow!("_headers cannot override {name}"));
776 }
777 Ok(name)
778}
779
780fn parse_redirect_rules(value: &str) -> anyhow::Result<Vec<RedirectRule>> {
781 let mut rules = Vec::new();
782 let mut static_rules = 0_usize;
783 let mut dynamic_rules = 0_usize;
784 for (line_number, line) in value.lines().enumerate() {
785 let line = line.trim();
786 if line.is_empty() || line.starts_with('#') {
787 continue;
788 }
789 if line.len() > 1_000 {
790 return Err(anyhow!(
791 "_redirects line {} exceeds 1,000 characters",
792 line_number + 1
793 ));
794 }
795 let parts = line.split_whitespace().collect::<Vec<_>>();
796 if !(2..=3).contains(&parts.len()) {
797 return Err(anyhow!(
798 "invalid _redirects rule on line {}",
799 line_number + 1
800 ));
801 }
802 let status = match parts.get(2) {
803 Some(value) => value.parse::<u16>().context("invalid _redirects status")?,
804 None => 302,
805 };
806 if !matches!(status, 200 | 301 | 302 | 303 | 307 | 308) {
807 return Err(anyhow!("unsupported _redirects status {status}"));
808 }
809 if status == 200 && !parts[1].starts_with('/') {
810 return Err(anyhow!("_redirects proxy destinations must be local paths"));
811 }
812 if status != 200
813 && !parts[1].starts_with('/')
814 && url::Url::parse(parts[1])
815 .ok()
816 .is_none_or(|url| !matches!(url.scheme(), "http" | "https"))
817 {
818 return Err(anyhow!("invalid _redirects destination"));
819 }
820 let dynamic = parts[0].contains('*') || parts[0].contains(':');
821 if dynamic {
822 dynamic_rules += 1;
823 } else {
824 static_rules += 1;
825 }
826 if static_rules > 2_000 || dynamic_rules > 100 || rules.len() >= 2_100 {
827 return Err(anyhow!("_redirects exceeds Cloudflare's rule limits"));
828 }
829 rules.push(RedirectRule {
830 pattern: RulePattern::parse(parts[0], false).with_context(|| {
831 format!("invalid _redirects source on line {}", line_number + 1)
832 })?,
833 destination: parts[1].to_string(),
834 status,
835 });
836 }
837 Ok(rules)
838}
839
840fn strip_port(host: &str) -> &str {
841 if host.starts_with('[') {
842 return host.find(']').map_or(host, |end| &host[1..end]);
843 }
844 host.rsplit_once(':')
845 .filter(|(_, port)| port.bytes().all(|byte| byte.is_ascii_digit()))
846 .map_or(host, |(host, _)| host)
847}
848
849fn route(index: &AssetIndex, path: &str, include_not_found: bool) -> Route {
850 let entries = &index.entries;
851 let html = index
852 .config
853 .html_handling
854 .as_deref()
855 .unwrap_or("auto-trailing-slash");
856
857 // Non-HTML assets are never affected by trailing-slash canonicalization.
858 if !path.ends_with(".html") {
859 if let Some(entry) = entries.get(path) {
860 return asset_route(path, entry, StatusCode::OK);
861 }
862 }
863
864 if html != "none" {
865 if let Some((asset_path, entry)) = html_asset(entries, path) {
866 let canonical = canonical_html_path(&asset_path, html);
867 if path != canonical {
868 return Route::Redirect {
869 location: canonical,
870 status: StatusCode::TEMPORARY_REDIRECT,
871 };
872 }
873 return asset_route(&asset_path, entry, StatusCode::OK);
874 }
875 } else if let Some(entry) = entries.get(path) {
876 return asset_route(path, entry, StatusCode::OK);
877 }
878
879 if !include_not_found {
880 return Route::Missing;
881 }
882 match index.config.not_found_handling.as_deref() {
883 Some("single-page-application") => entries
884 .get("/index.html")
885 .map(|entry| asset_route("/index.html", entry, StatusCode::OK))
886 .unwrap_or(Route::Missing),
887 Some("404-page") => nearest_404(entries, path)
888 .map(|(path, entry)| asset_route(&path, entry, StatusCode::NOT_FOUND))
889 .unwrap_or(Route::Missing),
890 _ => Route::Missing,
891 }
892}
893
894fn asset_route(path: &str, entry: &AssetEntry, status: StatusCode) -> Route {
895 Route::Asset {
896 path: path.to_string(),
897 entry: entry.clone(),
898 status,
899 }
900}
901
902fn html_asset<'a>(
903 entries: &'a std::collections::BTreeMap<String, AssetEntry>,
904 path: &str,
905) -> Option<(String, &'a AssetEntry)> {
906 let mut candidates = Vec::with_capacity(3);
907 if path.ends_with(".html") {
908 candidates.push(path.to_string());
909 } else if path.ends_with("/index") {
910 candidates.push(format!("{path}.html"));
911 } else if path.ends_with('/') {
912 candidates.push(format!("{path}index.html"));
913 if path != "/" {
914 candidates.push(format!("{}.html", path.trim_end_matches('/')));
915 }
916 } else {
917 candidates.push(format!("{path}.html"));
918 candidates.push(format!("{path}/index.html"));
919 }
920 candidates
921 .into_iter()
922 .find_map(|candidate| entries.get(&candidate).map(|entry| (candidate, entry)))
923}
924
925fn canonical_html_path(asset_path: &str, html_handling: &str) -> String {
926 if asset_path == "/index.html" {
927 return "/".to_string();
928 }
929 let base = if let Some(parent) = asset_path.strip_suffix("/index.html") {
930 parent
931 } else {
932 asset_path.strip_suffix(".html").unwrap_or(asset_path)
933 };
934 match html_handling {
935 "force-trailing-slash" => format!("{}/", base.trim_end_matches('/')),
936 "drop-trailing-slash" => {
937 let value = base.trim_end_matches('/');
938 if value.is_empty() {
939 "/".to_string()
940 } else {
941 value.to_string()
942 }
943 }
944 _ if asset_path.ends_with("/index.html") => format!("{}/", base.trim_end_matches('/')),
945 _ => base.trim_end_matches('/').to_string(),
946 }
947}
948
949fn nearest_404<'a>(
950 entries: &'a std::collections::BTreeMap<String, AssetEntry>,
951 path: &str,
952) -> Option<(String, &'a AssetEntry)> {
953 let mut directory = if path.ends_with('/') {
954 path.trim_end_matches('/').to_string()
955 } else {
956 path.rsplit_once('/')
957 .map(|(parent, _)| parent.to_string())
958 .unwrap_or_default()
959 };
960 loop {
961 let candidate = if directory.is_empty() {
962 "/404.html".to_string()
963 } else {
964 format!("{directory}/404.html")
965 };
966 if let Some(entry) = entries.get(&candidate) {
967 return Some((candidate, entry));
968 }
969 if directory.is_empty() {
970 return None;
971 }
972 directory = directory
973 .rsplit_once('/')
974 .map(|(parent, _)| parent.to_string())
975 .unwrap_or_default();
976 }
977}
978
979fn etag_matches(value: &str, etag: &str) -> bool {
980 value.split(',').any(|candidate| {
981 let candidate = candidate.trim();
982 candidate == "*" || candidate == etag || candidate.strip_prefix("W/") == Some(etag)
983 })
984}
985
986fn requested_range(headers: &HeaderMap, bytes: u64, etag: &str) -> RequestedRange {
987 let Some(value) = headers.get("range").and_then(|value| value.to_str().ok()) else {
988 return RequestedRange::Full;
989 };
990 if headers
991 .get("if-range")
992 .and_then(|value| value.to_str().ok())
993 .is_some_and(|value| value.trim() != etag)
994 {
995 return RequestedRange::Full;
996 }
997 let Some(value) = value.strip_prefix("bytes=") else {
998 return RequestedRange::Unsatisfiable;
999 };
1000 if value.contains(',') || bytes == 0 {
1001 return RequestedRange::Unsatisfiable;
1002 }
1003 let Some((start, end)) = value.split_once('-') else {
1004 return RequestedRange::Unsatisfiable;
1005 };
1006 if start.is_empty() {
1007 let Ok(suffix) = end.parse::<u64>() else {
1008 return RequestedRange::Unsatisfiable;
1009 };
1010 if suffix == 0 {
1011 return RequestedRange::Unsatisfiable;
1012 }
1013 let length = suffix.min(bytes);
1014 return RequestedRange::Partial {
1015 start: bytes - length,
1016 end: bytes - 1,
1017 };
1018 }
1019 let Ok(start) = start.parse::<u64>() else {
1020 return RequestedRange::Unsatisfiable;
1021 };
1022 if start >= bytes {
1023 return RequestedRange::Unsatisfiable;
1024 }
1025 let end = if end.is_empty() {
1026 bytes - 1
1027 } else {
1028 let Ok(end) = end.parse::<u64>() else {
1029 return RequestedRange::Unsatisfiable;
1030 };
1031 end.min(bytes - 1)
1032 };
1033 if end < start {
1034 return RequestedRange::Unsatisfiable;
1035 }
1036 RequestedRange::Partial { start, end }
1037}
1038
1039fn cache_path(root: &Path, sha256: &str) -> anyhow::Result<PathBuf> {
1040 asset_blob_key(sha256)
1041 .context("invalid asset cache digest")
1042 .map(|_| root.join(&sha256[..2]).join(sha256))
1043}
1044
1045async fn valid_cached_file(
1046 path: &Path,
1047 expected_bytes: u64,
1048) -> anyhow::Result<Option<tokio::fs::File>> {
1049 match tokio::fs::File::open(path).await {
1050 Ok(file) => {
1051 let metadata = file
1052 .metadata()
1053 .await
1054 .with_context(|| format!("stat asset cache file {}", path.display()))?;
1055 if metadata.len() == expected_bytes {
1056 Ok(Some(file))
1057 } else {
1058 drop(file);
1059 let _ = tokio::fs::remove_file(path).await;
1060 Ok(None)
1061 }
1062 }
1063 Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
1064 Err(error) => {
1065 Err(error).with_context(|| format!("open asset cache file {}", path.display()))
1066 }
1067 }
1068}
1069
1070fn touch_cache_file(path: PathBuf) {
1071 tokio::task::spawn_blocking(move || {
1072 let _ = filetime::set_file_mtime(path, filetime::FileTime::now());
1073 });
1074}
1075
1076fn cleanup_cache_files(root: &Path, limit: u64) -> anyhow::Result<()> {
1077 let mut files = Vec::new();
1078 let mut total = 0_u64;
1079 for shard in
1080 std::fs::read_dir(root).with_context(|| format!("scan asset cache {}", root.display()))?
1081 {
1082 let shard = shard?;
1083 if !shard.file_type()?.is_dir() {
1084 continue;
1085 }
1086 for entry in std::fs::read_dir(shard.path())? {
1087 let entry = entry?;
1088 let name = entry.file_name();
1089 let name = name.to_string_lossy();
1090 if name.len() != 64
1091 || !name
1092 .bytes()
1093 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
1094 {
1095 continue;
1096 }
1097 let metadata = entry.metadata()?;
1098 if !metadata.is_file() {
1099 continue;
1100 }
1101 total = total.saturating_add(metadata.len());
1102 files.push((
1103 metadata.modified().unwrap_or(std::time::UNIX_EPOCH),
1104 metadata.len(),
1105 entry.path(),
1106 ));
1107 }
1108 }
1109 if total <= limit {
1110 return Ok(());
1111 }
1112 files.sort_by_key(|(modified, _, _)| *modified);
1113 for (_, bytes, path) in files {
1114 if total <= limit {
1115 break;
1116 }
1117 if std::fs::remove_file(&path).is_ok() {
1118 total = total.saturating_sub(bytes);
1119 }
1120 }
1121 Ok(())
1122}
1123
1124fn validate_index(index: &AssetIndex, reference: &AssetManifestRef) -> anyhow::Result<()> {
1125 if index.schema_version != 1 {
1126 return Err(anyhow!(
1127 "unsupported asset index schema: {}",
1128 index.schema_version
1129 ));
1130 }
1131 if index.entries.len() != reference.file_count as usize {
1132 return Err(anyhow!("asset index file count mismatch"));
1133 }
1134 if index.entries.len() > 20_000 {
1135 return Err(anyhow!("asset index exceeds the file limit"));
1136 }
1137 let config = &index.config;
1138 if !matches!(
1139 config
1140 .html_handling
1141 .as_deref()
1142 .unwrap_or("auto-trailing-slash"),
1143 "auto-trailing-slash" | "force-trailing-slash" | "drop-trailing-slash" | "none"
1144 ) {
1145 return Err(anyhow!("unsupported asset HTML handling"));
1146 }
1147 if !matches!(
1148 config.not_found_handling.as_deref().unwrap_or("none"),
1149 "none" | "single-page-application" | "404-page"
1150 ) {
1151 return Err(anyhow!("unsupported asset not-found handling"));
1152 }
1153 if let Some(binding) = &config.binding {
1154 let valid = binding.len() <= 128
1155 && binding
1156 .chars()
1157 .next()
1158 .is_some_and(|value| value == '_' || value == '$' || value.is_ascii_alphabetic())
1159 && binding
1160 .chars()
1161 .skip(1)
1162 .all(|value| value == '_' || value == '$' || value.is_ascii_alphanumeric());
1163 if !valid {
1164 return Err(anyhow!("invalid asset binding name"));
1165 }
1166 }
1167 if let RunWorkerFirst::Routes(routes) = &config.run_worker_first {
1168 if routes.is_empty() || routes.len() > 100 {
1169 return Err(anyhow!("invalid asset worker-first route count"));
1170 }
1171 let mut positive = false;
1172 let mut seen = std::collections::HashSet::new();
1173 for route in routes {
1174 if route.starts_with('/') {
1175 positive = true;
1176 } else if !route.starts_with("!/") {
1177 return Err(anyhow!("invalid asset worker-first route: {route:?}"));
1178 }
1179 if route.len() > 100 || !seen.insert(route) {
1180 return Err(anyhow!("invalid asset worker-first route: {route:?}"));
1181 }
1182 }
1183 if !positive {
1184 return Err(anyhow!("asset worker-first routes require a positive rule"));
1185 }
1186 }
1187 let mut total = 0_u64;
1188 for (path, entry) in &index.entries {
1189 if decode_path(path).as_deref() != Some(path.as_str())
1190 || path == "/"
1191 || asset_blob_key(&entry.sha256).is_none()
1192 || entry.bytes > 25 * 1024 * 1024
1193 {
1194 return Err(anyhow!("invalid asset index entry: {path:?}"));
1195 }
1196 if entry
1197 .content_type
1198 .as_deref()
1199 .is_some_and(|value| value.len() > 200 || value.contains(['\r', '\n']))
1200 {
1201 return Err(anyhow!("invalid asset content type: {path:?}"));
1202 }
1203 total = total
1204 .checked_add(entry.bytes)
1205 .context("asset index byte count overflow")?;
1206 }
1207 if total != reference.total_bytes {
1208 return Err(anyhow!("asset index total byte count mismatch"));
1209 }
1210 if total > 1024 * 1024 * 1024 {
1211 return Err(anyhow!("asset index exceeds the deployment byte limit"));
1212 }
1213 Ok(())
1214}
1215
1216fn decode_path(path: &str) -> Option<String> {
1217 if !path.starts_with('/') || path.contains('\\') || path.contains('\0') {
1218 return None;
1219 }
1220 let decoded = percent_decode_str(path).decode_utf8().ok()?.into_owned();
1221 if decoded.contains('\\')
1222 || decoded.contains('\0')
1223 || decoded.split('/').skip(1).any(|segment| {
1224 segment.is_empty() && decoded != "/" || segment == "." || segment == ".."
1225 })
1226 {
1227 return None;
1228 }
1229 Some(decoded)
1230}
1231
1232fn route_pattern_matches(pattern: &str, path: &str) -> bool {
1233 let mut expression = String::from("^");
1234 for part in pattern.split('*') {
1235 expression.push_str(&regex::escape(part));
1236 expression.push_str(".*");
1237 }
1238 if !pattern.ends_with('*') {
1239 expression.truncate(expression.len().saturating_sub(2));
1240 expression.push('$');
1241 }
1242 regex::Regex::new(&expression).is_ok_and(|pattern| pattern.is_match(path))
1243}