Skip to main content

hyperlane_plugin_static_files/
fn.rs

1use super::*;
2
3/// Computes the cache shard index for a canonical file path using `XxHash3_64`.
4///
5/// # Arguments
6///
7/// - `&Path` - Canonical file path.
8///
9/// # Returns
10///
11/// - `usize` - Shard index in `0..STATIC_CACHE_SHARDS`.
12pub(crate) fn static_cache_shard_index(path: &Path) -> usize {
13    let mut hasher: XxHash3_64 = XxHash3_64::default();
14    hasher.write(path.as_os_str().as_encoded_bytes());
15    (hasher.finish() as usize) & (STATIC_CACHE_SHARDS - 1)
16}
17
18/// Percent-decodes a URL path segment while rejecting NUL bytes (`%00`) and invalid UTF-8.
19///
20/// # Arguments
21///
22/// - `&str` - Raw URL path slice.
23///
24/// # Returns
25///
26/// - `Option<String>` - Decoded UTF-8 relative path, or `None` if malformed or contains NUL/backslash.
27pub(crate) fn percent_decode_path(raw: &str) -> Option<String> {
28    let bytes: &[u8] = raw.as_bytes();
29    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
30    let mut i: usize = 0;
31    while i < bytes.len() {
32        let b: u8 = bytes[i];
33        if b == 0 || b == b'\\' {
34            return None;
35        }
36        if b == b'%' {
37            if i + 2 >= bytes.len() {
38                return None;
39            }
40            let hi: u8 = hex_nibble(bytes[i + 1])?;
41            let lo: u8 = hex_nibble(bytes[i + 2])?;
42            let decoded: u8 = (hi << 4) | lo;
43            if decoded == 0 || decoded == b'\\' {
44                return None;
45            }
46            out.push(decoded);
47            i += 3;
48        } else {
49            out.push(b);
50            i += 1;
51        }
52    }
53    String::from_utf8(out).ok()
54}
55
56/// Converts an ASCII hex digit byte into its 4-bit value.
57///
58/// # Arguments
59///
60/// - `u8` - ASCII byte.
61///
62/// # Returns
63///
64/// - `Option<u8>` - 4-bit value `0..=15`, or `None` when not hex.
65pub(crate) fn hex_nibble(byte: u8) -> Option<u8> {
66    match byte {
67        b'0'..=b'9' => Some(byte - b'0'),
68        b'a'..=b'f' => Some(byte - b'a' + 10),
69        b'A'..=b'F' => Some(byte - b'A' + 10),
70        _ => None,
71    }
72}
73
74/// Safely joins an untrusted relative URL path onto a canonicalized `root_dir`, rejecting traversal and dotfiles.
75///
76/// # Arguments
77///
78/// - `&Path` - Canonicalized root directory.
79/// - `&str` - Raw URL relative path (after stripping mount prefix).
80/// - `bool` - Whether hidden dotfiles/dotdirs (segments beginning with `.`) are permitted.
81///
82/// # Returns
83///
84/// - `Option<PathBuf>` - Validated filesystem path inside `root_dir`, or `None` on traversal/escape.
85pub fn resolve_safe_path(
86    root_dir: &Path,
87    relative_url: &str,
88    allow_dotfiles: bool,
89) -> Option<PathBuf> {
90    let decoded: String = percent_decode_path(relative_url)?;
91    let trimmed: &str = decoded.trim_start_matches('/');
92    let mut candidate: PathBuf = root_dir.to_path_buf();
93    for component in Path::new(trimmed).components() {
94        match component {
95            Component::Normal(seg) => {
96                let seg_str: &str = seg.to_str()?;
97                if seg_str.is_empty() || (!allow_dotfiles && seg_str.starts_with('.')) {
98                    return None;
99                }
100                candidate.push(seg);
101            }
102            Component::CurDir => {}
103            Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
104        }
105    }
106    Some(candidate)
107}
108
109/// Resolves the MIME `Content-Type` string for `path` using Hyperlane's [`FileExtension`] table.
110///
111/// # Arguments
112///
113/// - `&Path` - Target file path.
114///
115/// # Returns
116///
117/// - `&'static str` - Canonical MIME type (defaults to `application/octet-stream`).
118pub fn mime_for_path(path: &Path) -> &'static str {
119    let path_str: &str = path.to_str().unwrap_or_default();
120    let ext: String = FileExtension::get_extension_name(path_str);
121    if ext.is_empty() {
122        return APPLICATION_OCTET_STREAM;
123    }
124    let parsed: FileExtension = FileExtension::parse(ext.to_ascii_lowercase());
125    let mime: &'static str = parsed.get_content_type();
126    if mime.is_empty() {
127        APPLICATION_OCTET_STREAM
128    } else {
129        mime
130    }
131}
132
133/// Computes a deterministic strong `ETag` from file byte length and modification timestamp.
134///
135/// # Arguments
136///
137/// - `u64` - File size in bytes.
138/// - `u64` - Modification timestamp in milliseconds since Unix epoch.
139///
140/// # Returns
141///
142/// - `String` - Quoted strong ETag (for example `"\"400-18f123ab\""`).
143pub(crate) fn compute_file_etag(size: u64, modified_ms: u64) -> String {
144    format!("\"{size:x}-{modified_ms:x}\"")
145}
146
147/// Extracts modification time in milliseconds since Unix epoch from filesystem [`Metadata`].
148///
149/// # Arguments
150///
151/// - `&Metadata` - File metadata.
152///
153/// # Returns
154///
155/// - `u64` - Modification timestamp in milliseconds, or `0` if unavailable.
156pub(crate) fn metadata_modified_ms(meta: &Metadata) -> u64 {
157    meta.modified()
158        .ok()
159        .and_then(|ts: SystemTime| ts.duration_since(UNIX_EPOCH).ok())
160        .map(|dur: Duration| dur.as_millis() as u64)
161        .unwrap_or(0)
162}
163
164/// Checks whether an `If-None-Match` header matches `etag` (handling `*`, comma lists, and `W/` weak prefixes).
165///
166/// # Arguments
167///
168/// - `&str` - Incoming `If-None-Match` header value.
169/// - `&str` - Resource strong `ETag`.
170///
171/// # Returns
172///
173/// - `bool` - `true` when the client validator matches (`304 Not Modified`).
174pub fn if_none_match_matches(header: &str, etag: &str) -> bool {
175    let trimmed: &str = header.trim();
176    if trimmed == "*" {
177        return true;
178    }
179    trimmed.split(',').any(|token: &str| {
180        let candidate: &str = token.trim();
181        let normalized: &str = candidate.strip_prefix("W/").unwrap_or(candidate);
182        normalized == etag
183    })
184}
185
186/// Parses a single RFC 9110 byte `Range` header (`bytes=start-end`, `bytes=start-`, `bytes=-suffix`).
187///
188/// # Arguments
189///
190/// - `&str` - Raw `Range` header value.
191/// - `usize` - Total resource length in bytes.
192///
193/// # Returns
194///
195/// - `Option<(usize, usize)>` - Inclusive `(start, end)` byte offsets, or `None` when unsatisfiable/invalid.
196pub fn parse_byte_range(header: &str, total_len: usize) -> Option<(usize, usize)> {
197    if total_len == 0 {
198        return None;
199    }
200    let trimmed: &str = header.trim();
201    let spec: &str = trimmed.strip_prefix(RANGE_BYTES_PREFIX)?;
202    if spec.contains(',') {
203        return None;
204    }
205    let (start_str, end_str): (&str, &str) = spec.split_once('-')?;
206    let start_str: &str = start_str.trim();
207    let end_str: &str = end_str.trim();
208    if start_str.is_empty() {
209        let suffix: usize = end_str.parse::<usize>().ok()?;
210        if suffix == 0 {
211            return None;
212        }
213        let start: usize = total_len.saturating_sub(suffix);
214        return Some((start, total_len - 1));
215    }
216    let start: usize = start_str.parse::<usize>().ok()?;
217    if start >= total_len {
218        return None;
219    }
220    let end: usize = if end_str.is_empty() {
221        total_len - 1
222    } else {
223        end_str.parse::<usize>().ok()?.min(total_len - 1)
224    };
225    if start > end {
226        return None;
227    }
228    Some((start, end))
229}
230
231/// Reports whether `accept_encoding` permits `token` without `q=0`.
232///
233/// # Arguments
234///
235/// - `&str` - Incoming `Accept-Encoding` header value.
236/// - `&str` - Target encoding token (`"br"` or `"gzip"`).
237///
238/// # Returns
239///
240/// - `bool` - `true` when accepted.
241pub(crate) fn accepts_encoding(accept_encoding: &str, token: &str) -> bool {
242    for part in accept_encoding.split(',') {
243        let mut segments: Split<'_, char> = part.trim().split(';');
244        let coding: &str = segments.next().unwrap_or_default().trim();
245        if !coding.eq_ignore_ascii_case(token) {
246            continue;
247        }
248        let mut rejected: bool = false;
249        for param in segments {
250            let trimmed: &str = param.trim();
251            if let Some(qval) = trimmed
252                .strip_prefix("q=")
253                .or_else(|| trimmed.strip_prefix("Q="))
254                && qval.trim().parse::<f32>().ok() == Some(0.0)
255            {
256                rejected = true;
257            }
258        }
259        if !rejected {
260            return true;
261        }
262    }
263    false
264}