hyperlane-plugin-static-files 22.14.0

A high-performance static file server plugin for the Hyperlane framework with canonicalized path-traversal protection, built-in FileExtension MIME detection, 64-way sharded hot-file cache, precompressed .br/.gz sidecars, ETag/304 conditional validation, RFC 9110 Range 206/416 support, and SPA fallback.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
use super::*;

/// Computes the cache shard index for a normalized URL key using `XxHash3_64`.
///
/// # Arguments
///
/// - `&str` - Normalized relative URL path.
///
/// # Returns
///
/// - `usize` - Shard index in `0..STATIC_CACHE_SHARDS`.
#[inline]
pub(crate) fn static_cache_shard_index(key: &str) -> usize {
    let mut hasher: XxHash3_64 = XxHash3_64::default();
    hasher.write(key.as_bytes());
    (hasher.finish() as usize) & (STATIC_CACHE_SHARDS - 1)
}

/// Percent-decodes a URL path segment while rejecting NUL bytes (`%00`) and backslashes.
///
/// # Arguments
///
/// - `&str` - Raw URL path slice.
///
/// # Returns
///
/// - `Option<String>` - Decoded UTF-8 relative path, or `None` if malformed or contains NUL/backslash.
pub(crate) fn percent_decode_path(raw: &str) -> Option<String> {
    let bytes: &[u8] = raw.as_bytes();
    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
    let mut i: usize = 0;
    while i < bytes.len() {
        let b: u8 = bytes[i];
        if b == 0 || b == b'\\' {
            return None;
        }
        if b == b'%' {
            if i + 2 >= bytes.len() {
                return None;
            }
            let hi: u8 = hex_nibble(bytes[i + 1])?;
            let lo: u8 = hex_nibble(bytes[i + 2])?;
            let decoded: u8 = (hi << 4) | lo;
            if decoded == 0 || decoded == b'\\' {
                return None;
            }
            out.push(decoded);
            i += 3;
        } else {
            out.push(b);
            i += 1;
        }
    }
    String::from_utf8(out).ok()
}

/// Converts an ASCII hex digit byte into its 4-bit value.
///
/// # Arguments
///
/// - `u8` - ASCII byte.
///
/// # Returns
///
/// - `Option<u8>` - 4-bit value `0..=15`, or `None` when not hex.
#[inline]
pub(crate) fn hex_nibble(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

/// Validates every slash-separated segment of a decoded relative path for traversal and dotfiles.
///
/// # Arguments
///
/// - `&str` - Trimmed relative URL path without leading slashes.
/// - `bool` - Whether hidden dotfiles/dotdirs are permitted.
///
/// # Returns
///
/// - `bool` - `true` when every segment is safe.
#[inline]
pub(crate) fn is_safe_relative_segments(trimmed: &str, allow_dotfiles: bool) -> bool {
    if trimmed.is_empty() {
        return true;
    }
    for seg in trimmed.split('/') {
        if seg.is_empty() || seg == "." {
            continue;
        }
        if seg == ".." || (!allow_dotfiles && seg.starts_with('.')) {
            return false;
        }
    }
    true
}

/// Validates and percent-decodes `relative_url` without allocating when no `%` escape is present.
///
/// # Arguments
///
/// - `&'a str` - Raw relative URL path after stripping mount prefix.
/// - `bool` - Whether dotfiles are allowed.
///
/// # Returns
///
/// - `Option<Cow<'a, str>>` - Safe normalized relative path without leading slashes, or `None` on traversal/invalid bytes.
#[inline]
pub(crate) fn validate_and_decode_relative<'a>(
    relative_url: &'a str,
    allow_dotfiles: bool,
) -> Option<Cow<'a, str>> {
    let bytes: &[u8] = relative_url.as_bytes();
    let mut has_percent: bool = false;
    for &b in bytes {
        if b == 0 || b == b'\\' {
            return None;
        }
        if b == b'%' {
            has_percent = true;
        }
    }
    if !has_percent {
        let trimmed: &'a str = relative_url.trim_start_matches('/');
        if !is_safe_relative_segments(trimmed, allow_dotfiles) {
            return None;
        }
        return Some(Cow::Borrowed(trimmed));
    }
    let decoded: String = percent_decode_path(relative_url)?;
    let trimmed: &str = decoded.trim_start_matches('/');
    if !is_safe_relative_segments(trimmed, allow_dotfiles) {
        return None;
    }
    Some(Cow::Owned(trimmed.to_owned()))
}

/// Safely joins an untrusted relative URL path onto a canonicalized `root_dir`, rejecting traversal and dotfiles.
///
/// # Arguments
///
/// - `&Path` - Canonicalized root directory.
/// - `&str` - Raw URL relative path (after stripping mount prefix).
/// - `bool` - Whether hidden dotfiles/dotdirs (segments beginning with `.`) are permitted.
///
/// # Returns
///
/// - `Option<PathBuf>` - Validated filesystem path inside `root_dir`, or `None` on traversal/escape.
#[inline]
pub fn resolve_safe_path(
    root_dir: &Path,
    relative_url: &str,
    allow_dotfiles: bool,
) -> Option<PathBuf> {
    let safe_rel: Cow<'_, str> = validate_and_decode_relative(relative_url, allow_dotfiles)?;
    let rel_str: &str = safe_rel.as_ref();
    let mut candidate: PathBuf =
        PathBuf::with_capacity(root_dir.as_os_str().len() + rel_str.len() + 1);
    candidate.push(root_dir);
    if rel_str.is_empty() {
        return Some(candidate);
    }
    let has_special: bool = rel_str == "."
        || rel_str.starts_with("./")
        || rel_str.ends_with("/.")
        || rel_str.contains("/./")
        || rel_str.contains("//");
    if !has_special {
        candidate.push(rel_str);
        return Some(candidate);
    }
    for component in Path::new(rel_str).components() {
        match component {
            Component::Normal(seg) => {
                let seg_str: &str = seg.to_str()?;
                if seg_str.is_empty() || (!allow_dotfiles && seg_str.starts_with('.')) {
                    return None;
                }
                candidate.push(seg);
            }
            Component::CurDir => {}
            Component::ParentDir | Component::RootDir | Component::Prefix(_) => return None,
        }
    }
    Some(candidate)
}

/// Resolves the MIME `Content-Type` string for `path` using Hyperlane's [`FileExtension`] table without heap allocation.
///
/// # Arguments
///
/// - `&Path` - Target file path.
///
/// # Returns
///
/// - `&'static str` - Canonical MIME type (defaults to `application/octet-stream`).
#[inline]
pub fn mime_for_path(path: &Path) -> &'static str {
    let Some(ext_str) = path.extension().and_then(OsStr::to_str) else {
        return APPLICATION_OCTET_STREAM;
    };
    if ext_str.is_empty() {
        return APPLICATION_OCTET_STREAM;
    }
    let bytes: &[u8] = ext_str.as_bytes();
    let parsed: FileExtension = if !bytes.iter().any(|b: &u8| b.is_ascii_uppercase()) {
        FileExtension::parse(ext_str)
    } else if bytes.len() <= MIME_EXT_STACK_CAP {
        let mut stack_buf: [u8; MIME_EXT_STACK_CAP] = [0u8; MIME_EXT_STACK_CAP];
        for (dst, &src) in stack_buf.iter_mut().zip(bytes.iter()) {
            *dst = src.to_ascii_lowercase();
        }
        match from_utf8(&stack_buf[..bytes.len()]) {
            Ok(lower) => FileExtension::parse(lower),
            Err(_) => FileExtension::parse(ext_str.to_ascii_lowercase()),
        }
    } else {
        FileExtension::parse(ext_str.to_ascii_lowercase())
    };
    let mime: &'static str = parsed.get_content_type();
    if mime.is_empty() {
        APPLICATION_OCTET_STREAM
    } else {
        mime
    }
}

/// Appends lowercase hexadecimal digits for `value` into `buf` at `pos` and returns the new offset.
///
/// # Arguments
///
/// - `u64` - Unsigned integer to format in lowercase hex.
/// - `&mut [u8]` - Destination byte slice.
/// - `usize` - Starting write offset.
///
/// # Returns
///
/// - `usize` - Updated write offset.
#[inline]
pub(crate) fn write_hex_u64_compact(mut value: u64, buf: &mut [u8], pos: usize) -> usize {
    if value == 0 {
        buf[pos] = b'0';
        return pos + 1;
    }
    let mut tmp: [u8; 16] = [0u8; 16];
    let mut idx: usize = 16;
    while value > 0 {
        idx -= 1;
        tmp[idx] = HEX_DIGITS[(value & 0x0F) as usize];
        value >>= 4;
    }
    let slice: &[u8] = &tmp[idx..];
    buf[pos..pos + slice.len()].copy_from_slice(slice);
    pos + slice.len()
}

/// Computes a deterministic strong `ETag` from file byte length and modification timestamp.
///
/// # Arguments
///
/// - `u64` - File size in bytes.
/// - `u64` - Modification timestamp in milliseconds since Unix epoch.
///
/// # Returns
///
/// - `String` - Quoted strong ETag (for example `"\"400-18f123ab\""`).
#[inline]
pub(crate) fn compute_file_etag(size: u64, modified_ms: u64) -> String {
    let mut buf: [u8; ETAG_STACK_CAP] = [0u8; ETAG_STACK_CAP];
    buf[0] = b'"';
    let mut pos: usize = write_hex_u64_compact(size, &mut buf, 1);
    buf[pos] = b'-';
    pos = write_hex_u64_compact(modified_ms, &mut buf, pos + 1);
    buf[pos] = b'"';
    pos += 1;
    from_utf8(&buf[..pos]).unwrap_or_default().to_owned()
}

/// Extracts modification time in milliseconds since Unix epoch from filesystem [`Metadata`].
///
/// # Arguments
///
/// - `&Metadata` - File metadata.
///
/// # Returns
///
/// - `u64` - Modification timestamp in milliseconds, or `0` if unavailable.
#[inline]
pub(crate) fn metadata_modified_ms(meta: &Metadata) -> u64 {
    meta.modified()
        .ok()
        .and_then(|ts: SystemTime| ts.duration_since(UNIX_EPOCH).ok())
        .map(|dur: Duration| dur.as_millis() as u64)
        .unwrap_or(0)
}

/// Checks whether an `If-None-Match` header matches `etag` (handling `*`, comma lists, and `W/` weak prefixes).
///
/// # Arguments
///
/// - `&str` - Incoming `If-None-Match` header value.
/// - `&str` - Resource strong `ETag`.
///
/// # Returns
///
/// - `bool` - `true` when the client validator matches (`304 Not Modified`).
#[inline]
pub fn if_none_match_matches(header: &str, etag: &str) -> bool {
    let trimmed: &str = header.trim();
    if trimmed == ETAG_WILDCARD || trimmed == etag {
        return true;
    }
    trimmed.split(',').any(|token: &str| {
        let candidate: &str = token.trim();
        let normalized: &str = candidate
            .strip_prefix(WEAK_ETAG_PREFIX)
            .unwrap_or(candidate);
        normalized == etag
    })
}

/// Parses an ASCII unsigned decimal integer from `bytes` without allocating.
///
/// # Arguments
///
/// - `&[u8]` - Trimmed ASCII digit bytes.
///
/// # Returns
///
/// - `Option<usize>` - Parsed integer, or `None` on empty, non-digit, or overflow.
#[inline]
pub(crate) fn parse_ascii_usize(bytes: &[u8]) -> Option<usize> {
    if bytes.is_empty() {
        return None;
    }
    let mut acc: usize = 0;
    for &b in bytes {
        if !b.is_ascii_digit() {
            return None;
        }
        acc = acc.checked_mul(10)?.checked_add((b - b'0') as usize)?;
    }
    Some(acc)
}

/// Parses a single RFC 9110 byte `Range` header (`bytes=start-end`, `bytes=start-`, `bytes=-suffix`).
///
/// # Arguments
///
/// - `&str` - Raw `Range` header value.
/// - `usize` - Total resource length in bytes.
///
/// # Returns
///
/// - `Option<(usize, usize)>` - Inclusive `(start, end)` byte offsets, or `None` when unsatisfiable/invalid.
#[inline]
pub fn parse_byte_range(header: &str, total_len: usize) -> Option<(usize, usize)> {
    if total_len == 0 {
        return None;
    }
    let trimmed: &str = header.trim();
    let spec: &str = trimmed.strip_prefix(RANGE_BYTES_PREFIX)?;
    if spec.as_bytes().contains(&b',') {
        return None;
    }
    let (start_str, end_str): (&str, &str) = spec.split_once('-')?;
    let start_bytes: &[u8] = start_str.trim().as_bytes();
    let end_bytes: &[u8] = end_str.trim().as_bytes();
    if start_bytes.is_empty() {
        let suffix: usize = parse_ascii_usize(end_bytes)?;
        if suffix == 0 {
            return None;
        }
        let start: usize = total_len.saturating_sub(suffix);
        return Some((start, total_len - 1));
    }
    let start: usize = parse_ascii_usize(start_bytes)?;
    if start >= total_len {
        return None;
    }
    let end: usize = if end_bytes.is_empty() {
        total_len - 1
    } else {
        parse_ascii_usize(end_bytes)?.min(total_len - 1)
    };
    if start > end {
        return None;
    }
    Some((start, end))
}

/// Appends decimal digits for `value` into `buf` at `pos` and returns the new offset.
///
/// # Arguments
///
/// - `usize` - Unsigned integer to format.
/// - `&mut [u8]` - Destination byte slice.
/// - `usize` - Starting write offset.
///
/// # Returns
///
/// - `usize` - Updated write offset.
#[inline]
pub(crate) fn write_usize_decimal(mut value: usize, buf: &mut [u8], pos: usize) -> usize {
    if value == 0 {
        buf[pos] = b'0';
        return pos + 1;
    }
    let mut digits: [u8; 20] = [0u8; 20];
    let mut idx: usize = 20;
    while value > 0 {
        idx -= 1;
        digits[idx] = b'0' + (value % 10) as u8;
        value /= 10;
    }
    let slice: &[u8] = &digits[idx..];
    buf[pos..pos + slice.len()].copy_from_slice(slice);
    pos + slice.len()
}

/// Formats `bytes <start>-<end>/<total>` into a stack buffer without heap allocation.
///
/// # Arguments
///
/// - `usize` - Inclusive range start offset.
/// - `usize` - Inclusive range end offset.
/// - `usize` - Total entity length in bytes.
/// - `&mut [u8; CONTENT_RANGE_STACK_CAP]` - Stack destination buffer.
///
/// # Returns
///
/// - `&str` - Borrowed formatted `Content-Range` value.
#[inline]
pub(crate) fn format_content_range_stack(
    start: usize,
    end: usize,
    total: usize,
    buf: &mut [u8; CONTENT_RANGE_STACK_CAP],
) -> &str {
    let prefix: &[u8] = CONTENT_RANGE_BYTES_PREFIX.as_bytes();
    buf[..prefix.len()].copy_from_slice(prefix);
    let mut pos: usize = write_usize_decimal(start, buf, prefix.len());
    buf[pos] = b'-';
    pos = write_usize_decimal(end, buf, pos + 1);
    buf[pos] = b'/';
    pos = write_usize_decimal(total, buf, pos + 1);
    from_utf8(&buf[..pos]).unwrap_or_default()
}

/// Formats `bytes */<total>` into a stack buffer without heap allocation.
///
/// # Arguments
///
/// - `usize` - Total entity length in bytes.
/// - `&mut [u8; CONTENT_RANGE_STACK_CAP]` - Stack destination buffer.
///
/// # Returns
///
/// - `&str` - Borrowed formatted unsatisfiable `Content-Range` value.
#[inline]
pub(crate) fn format_unsatisfiable_range_stack(
    total: usize,
    buf: &mut [u8; CONTENT_RANGE_STACK_CAP],
) -> &str {
    let prefix: &[u8] = CONTENT_RANGE_UNSAT_PREFIX.as_bytes();
    buf[..prefix.len()].copy_from_slice(prefix);
    let pos: usize = write_usize_decimal(total, buf, prefix.len());
    from_utf8(&buf[..pos]).unwrap_or_default()
}

/// Parses `Accept-Encoding` into a two-bit sidecar acceptance mask (`ENCODING_MASK_BR | ENCODING_MASK_GZIP`) in one pass.
///
/// # Arguments
///
/// - `&str` - Incoming `Accept-Encoding` header value.
///
/// # Returns
///
/// - `u8` - Bitmask of accepted precompressed sidecar encodings.
#[inline]
pub(crate) fn accept_encoding_mask(accept_encoding: &str) -> u8 {
    let has_params: bool = accept_encoding.as_bytes().contains(&b';');
    let mut mask: u8 = 0;
    for part in accept_encoding.split(',') {
        if !has_params {
            let coding: &str = part.trim();
            if coding.eq_ignore_ascii_case(ENCODING_BR) {
                mask |= ENCODING_MASK_BR;
            } else if coding.eq_ignore_ascii_case(ENCODING_GZIP) {
                mask |= ENCODING_MASK_GZIP;
            }
            if mask == (ENCODING_MASK_BR | ENCODING_MASK_GZIP) {
                break;
            }
            continue;
        }
        let mut segments: Split<'_, char> = part.trim().split(';');
        let coding: &str = segments.next().unwrap_or_default().trim();
        let bit: u8 = if coding.eq_ignore_ascii_case(ENCODING_BR) {
            ENCODING_MASK_BR
        } else if coding.eq_ignore_ascii_case(ENCODING_GZIP) {
            ENCODING_MASK_GZIP
        } else {
            continue;
        };
        let mut rejected: bool = false;
        for param in segments {
            let trimmed: &str = param.trim();
            if let Some(qval) = trimmed
                .strip_prefix("q=")
                .or_else(|| trimmed.strip_prefix("Q="))
                && qval.trim().parse::<f32>().ok() == Some(0.0)
            {
                rejected = true;
            }
        }
        if !rejected {
            mask |= bit;
        }
    }
    mask
}

/// Borrows the last value of lowercase request header `name` without allocating.
///
/// # Arguments
///
/// - `&'a Request` - Incoming HTTP request.
/// - `&str` - Lowercase header key.
///
/// # Returns
///
/// - `Option<&'a str>` - Borrowed last header value, if present.
#[inline]
pub(crate) fn get_request_header_back_ref<'a>(request: &'a Request, name: &str) -> Option<&'a str> {
    request
        .get_headers()
        .get(name)
        .and_then(|values: &RequestHeadersValue| values.back())
        .map(String::as_str)
}