Skip to main content

fetchlet_http/assets/
archive.rs

1use std::io::Read;
2
3use bytes::Bytes;
4use http::{HeaderName, HeaderValue, StatusCode};
5
6const MAGIC: &[u8; 4] = b"FLPK";
7const VERSION: u16 = 1;
8const HEADER_SIZE: usize = 80;
9const ENTRY_SIZE: usize = 64;
10const SET_SIZE: usize = 8;
11const PAIR_SIZE: usize = 16;
12const FLAG_BROTLI: u16 = 1;
13const FLAG_KEEP_QUERY: u16 = 2;
14
15/// A failure to read an asset archive.
16#[derive(Debug, thiserror::Error)]
17pub enum AssetArchiveError {
18    #[error("not an asset archive")]
19    Magic,
20    #[error("unsupported asset archive version {0}")]
21    Version(u16),
22    #[error("invalid asset archive: {0}")]
23    Invalid(&'static str),
24    #[error("could not read {path}: {source}")]
25    Read {
26        path: std::path::PathBuf,
27        source: std::io::Error,
28    },
29}
30
31/// Client assets packed by `writeAssetArchive` in `fetchlet/build`.
32///
33/// The archive is checked once in [`AssetArchive::new`]; lookups and reads
34/// then index into the same bytes. Embed it with
35/// `AssetArchive::new(Bytes::from_static(include_bytes!(...)))` or read a
36/// sidecar file with [`AssetArchive::open`].
37#[derive(Clone, Debug)]
38pub struct AssetArchive {
39    bytes: Bytes,
40    entries: Vec<Entry>,
41    header_sets: Vec<Vec<(HeaderName, HeaderValue)>>,
42}
43
44#[derive(Clone, Debug)]
45struct Entry {
46    path: std::ops::Range<usize>,
47    data: std::ops::Range<usize>,
48    raw_size: u64,
49    header_set: usize,
50    status: StatusCode,
51    brotli: bool,
52    keep_query: bool,
53    hash: [u8; 16],
54}
55
56/// One served path of an [`AssetArchive`].
57#[derive(Clone, Copy, Debug)]
58pub struct Asset<'a> {
59    archive: &'a AssetArchive,
60    entry: &'a Entry,
61}
62
63impl AssetArchive {
64    /// Check `bytes` and index its entries.
65    pub fn new(bytes: impl Into<Bytes>) -> Result<Self, AssetArchiveError> {
66        let bytes = bytes.into();
67        let invalid = AssetArchiveError::Invalid;
68        let header = bytes
69            .get(..HEADER_SIZE)
70            .ok_or(invalid("truncated header"))?;
71        if &header[..4] != MAGIC {
72            return Err(AssetArchiveError::Magic);
73        }
74        let version = u16_at(header, 4);
75        if version != VERSION {
76            return Err(AssetArchiveError::Version(version));
77        }
78        if u16_at(header, 6) != 0 || u32_at(header, 20) != 0 {
79            return Err(invalid("unknown header flags"));
80        }
81        let entry_count = u32_at(header, 8) as usize;
82        let set_count = u32_at(header, 12) as usize;
83        let pair_count = u32_at(header, 16) as usize;
84        let table = |offset: usize, count: usize, size: usize, what: &'static str| {
85            let start = u64_at(header, offset);
86            let length = (count as u64)
87                .checked_mul(size as u64)
88                .ok_or(invalid(what))?;
89            section(&bytes, start, length).ok_or(invalid(what))
90        };
91        let entry_table = table(24, entry_count, ENTRY_SIZE, "entry table out of bounds")?;
92        let set_table = table(32, set_count, SET_SIZE, "header set table out of bounds")?;
93        let pair_table = table(40, pair_count, PAIR_SIZE, "header pair table out of bounds")?;
94        let strings = section(&bytes, u64_at(header, 48), u64_at(header, 56))
95            .ok_or(invalid("string table out of bounds"))?;
96        let data = section(&bytes, u64_at(header, 64), u64_at(header, 72))
97            .ok_or(invalid("data out of bounds"))?;
98
99        let string = |offset: u32, length: u32| -> Option<std::ops::Range<usize>> {
100            let start = strings.start.checked_add(offset as usize)?;
101            let end = start.checked_add(length as usize)?;
102            (end <= strings.end).then_some(start..end)
103        };
104
105        let mut pairs = Vec::with_capacity(pair_count);
106        for index in 0..pair_count {
107            let record = &bytes[pair_table.start + index * PAIR_SIZE..][..PAIR_SIZE];
108            let name = string(u32_at(record, 0), u32_at(record, 4))
109                .ok_or(invalid("header name out of bounds"))?;
110            let value = string(u32_at(record, 8), u32_at(record, 12))
111                .ok_or(invalid("header value out of bounds"))?;
112            let name = HeaderName::from_bytes(&bytes[name.clone()])
113                .ok()
114                .filter(|parsed| parsed.as_str().as_bytes() == &bytes[name])
115                .ok_or(invalid("header name is not a lowercase token"))?;
116            if is_derived(&name) {
117                return Err(invalid("header set names a header the server derives"));
118            }
119            let value = HeaderValue::from_maybe_shared(bytes.slice(value))
120                .map_err(|_| invalid("invalid header value"))?;
121            pairs.push((name, value));
122        }
123
124        let mut header_sets = Vec::with_capacity(set_count);
125        for index in 0..set_count {
126            let record = &bytes[set_table.start + index * SET_SIZE..][..SET_SIZE];
127            let first = u32_at(record, 0) as usize;
128            let count = u32_at(record, 4) as usize;
129            let set = first
130                .checked_add(count)
131                .and_then(|end| pairs.get(first..end))
132                .ok_or(invalid("header set out of bounds"))?;
133            header_sets.push(set.to_vec());
134        }
135
136        let mut entries: Vec<Entry> = Vec::with_capacity(entry_count);
137        for index in 0..entry_count {
138            let record = &bytes[entry_table.start + index * ENTRY_SIZE..][..ENTRY_SIZE];
139            let path = string(u32_at(record, 0), u32_at(record, 4))
140                .ok_or(invalid("path out of bounds"))?;
141            let path_bytes = &bytes[path.clone()];
142            if std::str::from_utf8(path_bytes).is_err() || !path_bytes.starts_with(b"/") {
143                return Err(invalid("path is not an absolute UTF-8 path"));
144            }
145            if let Some(previous) = entries.last()
146                && &bytes[previous.path.clone()] >= path_bytes
147            {
148                return Err(invalid("paths are not sorted and unique"));
149            }
150            let stored = u64_at(record, 16);
151            let start = data.start as u64 + u64_at(record, 8);
152            let data_range = section(&bytes, start, stored)
153                .filter(|range| range.end <= data.end)
154                .ok_or(invalid("entry data out of bounds"))?;
155            let raw_size = u64_at(record, 24);
156            let header_set = u32_at(record, 32) as usize;
157            if header_set >= header_sets.len() {
158                return Err(invalid("entry names a missing header set"));
159            }
160            let status = StatusCode::from_u16(u16_at(record, 36))
161                .ok()
162                .filter(|status| !status.is_informational())
163                .ok_or(invalid("invalid status code"))?;
164            let flags = u16_at(record, 38);
165            if flags & !(FLAG_BROTLI | FLAG_KEEP_QUERY) != 0 {
166                return Err(invalid("unknown entry flags"));
167            }
168            let brotli = flags & FLAG_BROTLI != 0;
169            if !brotli && raw_size != stored {
170                return Err(invalid("identity entry sizes differ"));
171            }
172            let mut hash = [0; 16];
173            hash.copy_from_slice(&record[40..56]);
174            entries.push(Entry {
175                path,
176                data: data_range,
177                raw_size,
178                header_set,
179                status,
180                brotli,
181                keep_query: flags & FLAG_KEEP_QUERY != 0,
182                hash,
183            });
184        }
185
186        Ok(Self {
187            bytes,
188            entries,
189            header_sets,
190        })
191    }
192
193    /// Read and check an archive file, such as a sidecar next to the binary.
194    pub fn open(path: impl AsRef<std::path::Path>) -> Result<Self, AssetArchiveError> {
195        let path = path.as_ref();
196        let bytes = std::fs::read(path).map_err(|source| AssetArchiveError::Read {
197            path: path.to_owned(),
198            source,
199        })?;
200        Self::new(bytes)
201    }
202
203    /// The asset at a decoded URL path, such as `/assets/app.js`.
204    pub fn get(&self, path: &str) -> Option<Asset<'_>> {
205        self.entries
206            .binary_search_by(|entry| self.bytes[entry.path.clone()].cmp(path.as_bytes()))
207            .ok()
208            .map(|index| Asset {
209                archive: self,
210                entry: &self.entries[index],
211            })
212    }
213
214    /// The number of served paths.
215    pub fn len(&self) -> usize {
216        self.entries.len()
217    }
218
219    pub fn is_empty(&self) -> bool {
220        self.entries.is_empty()
221    }
222}
223
224impl<'a> Asset<'a> {
225    pub fn status(&self) -> StatusCode {
226        self.entry.status
227    }
228
229    /// The stored response headers, without the ones the server derives.
230    pub fn headers(&self) -> impl Iterator<Item = &'a (HeaderName, HeaderValue)> {
231        self.archive.header_sets[self.entry.header_set].iter()
232    }
233
234    /// Whether the stored bytes are Brotli-compressed.
235    pub fn is_brotli(&self) -> bool {
236        self.entry.brotli
237    }
238
239    /// Whether a redirect appends the request's query to its `Location`.
240    pub fn keeps_query(&self) -> bool {
241        self.entry.keep_query
242    }
243
244    /// The size of the asset after decompression.
245    pub fn raw_size(&self) -> u64 {
246        self.entry.raw_size
247    }
248
249    /// The first 16 bytes of the SHA-256 of the decompressed asset.
250    pub fn hash(&self) -> &'a [u8; 16] {
251        &self.entry.hash
252    }
253
254    /// The bytes as stored, compressed for Brotli entries.
255    pub fn stored(&self) -> Bytes {
256        self.archive.bytes.slice(self.entry.data.clone())
257    }
258
259    /// The decompressed bytes. Fails when the stored stream is corrupt or
260    /// does not decode to the recorded size.
261    pub fn decompressed(&self) -> std::io::Result<Bytes> {
262        let stored = self.stored();
263        if !self.entry.brotli {
264            return Ok(stored);
265        }
266        // The recorded size bounds the output; reserve at most 1 MiB up
267        // front so a corrupt size cannot allocate before decoding fails.
268        let capacity = usize::try_from(self.entry.raw_size.min(1 << 20)).unwrap_or(0);
269        let mut raw = Vec::with_capacity(capacity);
270        // Read one byte past the recorded size to detect a longer stream.
271        brotli_decompressor::Decompressor::new(&stored[..], 4096)
272            .take(self.entry.raw_size + 1)
273            .read_to_end(&mut raw)?;
274        if raw.len() as u64 != self.entry.raw_size {
275            return Err(std::io::Error::new(
276                std::io::ErrorKind::InvalidData,
277                "asset does not decode to its recorded size",
278            ));
279        }
280        Ok(Bytes::from(raw))
281    }
282}
283
284/// Headers the server sets from the representation it sends.
285pub(super) fn is_derived(name: &HeaderName) -> bool {
286    use http::header::*;
287    [
288        ACCEPT_RANGES,
289        CONTENT_ENCODING,
290        CONTENT_LENGTH,
291        CONTENT_RANGE,
292        ETAG,
293        TRANSFER_ENCODING,
294    ]
295    .contains(name)
296}
297
298/// A byte range of `bytes`, when it lies inside.
299fn section(bytes: &[u8], start: u64, length: u64) -> Option<std::ops::Range<usize>> {
300    let start = usize::try_from(start).ok()?;
301    let end = start.checked_add(usize::try_from(length).ok()?)?;
302    (end <= bytes.len()).then_some(start..end)
303}
304
305fn u16_at(bytes: &[u8], offset: usize) -> u16 {
306    u16::from_le_bytes(bytes[offset..offset + 2].try_into().unwrap())
307}
308
309fn u32_at(bytes: &[u8], offset: usize) -> u32 {
310    u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap())
311}
312
313fn u64_at(bytes: &[u8], offset: usize) -> u64 {
314    u64::from_le_bytes(bytes[offset..offset + 8].try_into().unwrap())
315}
316
317#[cfg(test)]
318mod tests {
319    use super::*;
320
321    /// One entry of an archive the tests write field by field.
322    struct EntrySpec {
323        path: &'static str,
324        data: Vec<u8>,
325        raw_size: u64,
326        set: u32,
327        status: u16,
328        flags: u16,
329    }
330
331    fn entry(path: &'static str, data: &[u8]) -> EntrySpec {
332        EntrySpec {
333            path,
334            data: data.to_vec(),
335            raw_size: data.len() as u64,
336            set: 0,
337            status: 200,
338            flags: 0,
339        }
340    }
341
342    /// An archive in the layout `writeAssetArchive` produces: header, entry,
343    /// header set and pair tables, strings, then data.
344    struct Spec {
345        entries: Vec<EntrySpec>,
346        sets: Vec<(u32, u32)>,
347        pairs: Vec<(&'static str, &'static str)>,
348    }
349
350    impl Spec {
351        fn new() -> Self {
352            Self {
353                entries: vec![entry("/a.txt", b"alpha"), entry("/b.txt", b"beta")],
354                sets: vec![(0, 1)],
355                pairs: vec![("content-type", "text/plain")],
356            }
357        }
358
359        fn write(&self) -> Vec<u8> {
360            let mut strings = Vec::new();
361            let mut string = |text: &str| {
362                let offset = strings.len() as u32;
363                strings.extend_from_slice(text.as_bytes());
364                (offset, text.len() as u32)
365            };
366            let mut data = Vec::new();
367            let mut entry_table = Vec::new();
368            for entry in &self.entries {
369                let (offset, length) = string(entry.path);
370                entry_table.extend_from_slice(&offset.to_le_bytes());
371                entry_table.extend_from_slice(&length.to_le_bytes());
372                entry_table.extend_from_slice(&(data.len() as u64).to_le_bytes());
373                entry_table.extend_from_slice(&(entry.data.len() as u64).to_le_bytes());
374                entry_table.extend_from_slice(&entry.raw_size.to_le_bytes());
375                entry_table.extend_from_slice(&entry.set.to_le_bytes());
376                entry_table.extend_from_slice(&entry.status.to_le_bytes());
377                entry_table.extend_from_slice(&entry.flags.to_le_bytes());
378                entry_table.extend_from_slice(&[7; 16]);
379                entry_table.extend_from_slice(&[0; 8]);
380                data.extend_from_slice(&entry.data);
381            }
382            let mut set_table = Vec::new();
383            for (first, count) in &self.sets {
384                set_table.extend_from_slice(&first.to_le_bytes());
385                set_table.extend_from_slice(&count.to_le_bytes());
386            }
387            let mut pair_table = Vec::new();
388            for (name, value) in &self.pairs {
389                for (offset, length) in [string(name), string(value)] {
390                    pair_table.extend_from_slice(&offset.to_le_bytes());
391                    pair_table.extend_from_slice(&length.to_le_bytes());
392                }
393            }
394
395            let mut bytes = vec![0; HEADER_SIZE];
396            bytes[..4].copy_from_slice(MAGIC);
397            bytes[4..6].copy_from_slice(&VERSION.to_le_bytes());
398            let counts = [self.entries.len(), self.sets.len(), self.pairs.len()];
399            for (index, count) in counts.into_iter().enumerate() {
400                bytes[8 + index * 4..][..4].copy_from_slice(&(count as u32).to_le_bytes());
401            }
402            for (offset, table) in [(24, &entry_table), (32, &set_table), (40, &pair_table)] {
403                let start = bytes.len() as u64;
404                put_u64(&mut bytes, offset, start);
405                bytes.extend_from_slice(table);
406            }
407            for (offset, section) in [(48, &strings), (64, &data)] {
408                let start = bytes.len() as u64;
409                put_u64(&mut bytes, offset, start);
410                put_u64(&mut bytes, offset + 8, section.len() as u64);
411                bytes.extend_from_slice(section);
412            }
413            bytes
414        }
415    }
416
417    fn reason(bytes: Vec<u8>) -> &'static str {
418        match AssetArchive::new(bytes) {
419            Err(AssetArchiveError::Invalid(reason)) => reason,
420            other => panic!("expected an invalid archive, got {other:?}"),
421        }
422    }
423
424    fn put_u64(bytes: &mut [u8], offset: usize, value: u64) {
425        bytes[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
426    }
427
428    #[test]
429    fn a_written_archive_reads_back() {
430        let archive = AssetArchive::new(Spec::new().write()).unwrap();
431        assert_eq!(archive.len(), 2);
432        assert!(!archive.is_empty());
433        let asset = archive.get("/b.txt").unwrap();
434        assert_eq!(asset.status(), StatusCode::OK);
435        assert_eq!(asset.stored(), "beta");
436        assert_eq!(asset.decompressed().unwrap(), "beta");
437        assert_eq!(asset.raw_size(), 4);
438        assert_eq!(asset.hash(), &[7; 16]);
439        assert!(!asset.is_brotli() && !asset.keeps_query());
440        let headers: Vec<_> = asset.headers().collect();
441        assert_eq!(headers.len(), 1);
442        assert_eq!(headers[0].0, http::header::CONTENT_TYPE);
443        assert!(archive.get("/c.txt").is_none());
444        assert!(archive.get("a.txt").is_none());
445    }
446
447    #[test]
448    fn an_empty_archive_has_no_entries() {
449        let spec = Spec {
450            entries: vec![],
451            sets: vec![],
452            pairs: vec![],
453        };
454        let archive = AssetArchive::new(spec.write()).unwrap();
455        assert!(archive.is_empty());
456        assert!(archive.get("/").is_none());
457    }
458
459    #[test]
460    fn redirects_keep_their_status_and_query_flag() {
461        let mut spec = Spec::new();
462        spec.pairs.push(("location", "/b.txt"));
463        spec.sets.push((1, 1));
464        spec.entries[0].data.clear();
465        spec.entries[0].raw_size = 0;
466        spec.entries[0].set = 1;
467        spec.entries[0].status = 308;
468        spec.entries[0].flags = FLAG_KEEP_QUERY;
469        let archive = AssetArchive::new(spec.write()).unwrap();
470        let redirect = archive.get("/a.txt").unwrap();
471        assert_eq!(redirect.status(), StatusCode::PERMANENT_REDIRECT);
472        assert!(redirect.keeps_query());
473        assert_eq!(redirect.headers().next().unwrap().1, "/b.txt");
474    }
475
476    #[test]
477    fn the_header_must_match_this_version() {
478        let mut bytes = Spec::new().write();
479        bytes[6] = 1;
480        assert_eq!(reason(bytes), "unknown header flags");
481        let mut bytes = Spec::new().write();
482        bytes[20] = 1;
483        assert_eq!(reason(bytes), "unknown header flags");
484        assert_eq!(reason(vec![0; HEADER_SIZE - 1]), "truncated header");
485    }
486
487    #[test]
488    fn tables_outside_the_archive_are_refused() {
489        for (offset, expected) in [
490            (24, "entry table out of bounds"),
491            (32, "header set table out of bounds"),
492            (40, "header pair table out of bounds"),
493            (48, "string table out of bounds"),
494            (64, "data out of bounds"),
495            (72, "data out of bounds"),
496        ] {
497            let mut bytes = Spec::new().write();
498            put_u64(&mut bytes, offset, u64::MAX);
499            assert_eq!(reason(bytes), expected, "offset {offset}");
500        }
501        // A count whose table size overflows is refused, not wrapped.
502        let mut bytes = Spec::new().write();
503        bytes[8..12].copy_from_slice(&u32::MAX.to_le_bytes());
504        assert_eq!(reason(bytes), "entry table out of bounds");
505    }
506
507    #[test]
508    fn header_pairs_must_be_lowercase_valid_and_not_derived() {
509        for (name, value, expected) in [
510            (
511                "Content-Type",
512                "text/plain",
513                "header name is not a lowercase token",
514            ),
515            ("bad name", "x", "header name is not a lowercase token"),
516            (
517                "etag",
518                "\"x\"",
519                "header set names a header the server derives",
520            ),
521            (
522                "content-length",
523                "5",
524                "header set names a header the server derives",
525            ),
526            ("x-value", "line\nbreak", "invalid header value"),
527        ] {
528            let mut spec = Spec::new();
529            spec.pairs = vec![(name, value)];
530            assert_eq!(reason(spec.write()), expected, "{name}");
531        }
532    }
533
534    #[test]
535    fn header_sets_must_lie_inside_the_pairs() {
536        for set in [(0, 2), (1, 1), (u32::MAX, 2)] {
537            let mut spec = Spec::new();
538            spec.sets = vec![set];
539            assert_eq!(reason(spec.write()), "header set out of bounds", "{set:?}");
540        }
541        let mut spec = Spec::new();
542        spec.entries[1].set = 1;
543        assert_eq!(reason(spec.write()), "entry names a missing header set");
544    }
545
546    #[test]
547    fn paths_must_be_absolute_sorted_and_unique() {
548        let mut spec = Spec::new();
549        spec.entries[0].path = "a.txt";
550        assert_eq!(reason(spec.write()), "path is not an absolute UTF-8 path");
551        let mut spec = Spec::new();
552        spec.entries.swap(0, 1);
553        assert_eq!(reason(spec.write()), "paths are not sorted and unique");
554        let mut spec = Spec::new();
555        spec.entries[1].path = "/a.txt";
556        assert_eq!(reason(spec.write()), "paths are not sorted and unique");
557    }
558
559    #[test]
560    fn entries_must_have_valid_status_flags_and_sizes() {
561        for status in [100, 99, 1000] {
562            let mut spec = Spec::new();
563            spec.entries[0].status = status;
564            assert_eq!(reason(spec.write()), "invalid status code", "{status}");
565        }
566        let mut spec = Spec::new();
567        spec.entries[0].flags = 4;
568        assert_eq!(reason(spec.write()), "unknown entry flags");
569        let mut spec = Spec::new();
570        spec.entries[0].raw_size = 6;
571        assert_eq!(reason(spec.write()), "identity entry sizes differ");
572    }
573
574    #[test]
575    fn entry_data_must_lie_inside_the_data_section() {
576        let mut bytes = Spec::new().write();
577        // The second entry's stored size, in the entry table after the header.
578        put_u64(&mut bytes, HEADER_SIZE + ENTRY_SIZE + 16, 100);
579        assert_eq!(reason(bytes), "entry data out of bounds");
580    }
581
582    #[test]
583    fn brotli_entries_must_decode_to_their_recorded_size() {
584        let mut spec = Spec::new();
585        // 0x06 is a complete Brotli stream: one empty last metablock.
586        for (entry, raw_size) in spec.entries.iter_mut().zip([0, 3]) {
587            entry.data = vec![0x06];
588            entry.raw_size = raw_size;
589            entry.flags = FLAG_BROTLI;
590        }
591        let archive = AssetArchive::new(spec.write()).unwrap();
592        let empty = archive.get("/a.txt").unwrap();
593        assert!(empty.is_brotli());
594        assert_eq!(empty.decompressed().unwrap(), "");
595        let short = archive.get("/b.txt").unwrap();
596        assert_eq!(
597            short.decompressed().unwrap_err().kind(),
598            std::io::ErrorKind::InvalidData
599        );
600    }
601
602    #[test]
603    fn the_server_derives_representation_headers() {
604        use http::header::*;
605        for name in [
606            ETAG,
607            CONTENT_LENGTH,
608            CONTENT_ENCODING,
609            CONTENT_RANGE,
610            ACCEPT_RANGES,
611            TRANSFER_ENCODING,
612        ] {
613            assert!(is_derived(&name), "{name}");
614        }
615        for name in [CONTENT_TYPE, CACHE_CONTROL, LOCATION, VARY] {
616            assert!(!is_derived(&name), "{name}");
617        }
618    }
619
620    #[test]
621    fn sections_reject_overflowing_ranges() {
622        let bytes = [0; 8];
623        assert_eq!(section(&bytes, 2, 6), Some(2..8));
624        assert_eq!(section(&bytes, 8, 0), Some(8..8));
625        assert_eq!(section(&bytes, 2, 7), None);
626        assert_eq!(section(&bytes, u64::MAX, 1), None);
627        assert_eq!(section(&bytes, 1, u64::MAX), None);
628    }
629
630    #[test]
631    fn opening_a_missing_file_names_it() {
632        let path = std::env::temp_dir().join("fetchlet-missing-archive.flpk");
633        match AssetArchive::open(&path) {
634            Err(AssetArchiveError::Read { path: named, .. }) => assert_eq!(named, path),
635            other => panic!("expected a read error, got {other:?}"),
636        }
637    }
638}