onelf-format 0.6.1

Binary format definitions for onelf
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
use std::collections::HashMap;
use std::io::{self, Cursor, Read, Write};
use std::path::PathBuf;

use crate::entry::{ENTRY_HEADER_SIZE, ENTRYPOINT_SIZE, Entry, EntryKind, EntryPoint};

/// Returns true if `name` is a single safe path component: non-empty,
/// not `.` or `..`, and free of `/` and NUL. Used to reject entry names
/// that would let a crafted package escape the extraction root.
pub fn is_safe_component(name: &str) -> bool {
    !name.is_empty() && name != "." && name != ".." && !name.contains('/') && !name.contains('\0')
}

/// Lexically check that a symlink placed at `link_rel` (a relative path
/// under the extraction root) with `target` still resolves inside the
/// root. Absolute targets and targets that walk above the root are
/// rejected. Purely lexical, so it cannot be defeated by filesystem
/// races. Shared by the runtime and the packer's extractor.
pub fn symlink_target_within_root(link_rel: &std::path::Path, target: &str) -> bool {
    use std::ffi::OsString;
    use std::path::Component;

    if target.is_empty() {
        return false;
    }
    let tpath = std::path::Path::new(target);
    if tpath.is_absolute() {
        return false;
    }
    let mut stack: Vec<OsString> = Vec::new();
    let mut walk = |path: &std::path::Path| -> bool {
        for c in path.components() {
            match c {
                Component::Normal(s) => stack.push(s.to_os_string()),
                Component::ParentDir => {
                    if stack.pop().is_none() {
                        return false;
                    }
                }
                Component::CurDir => {}
                _ => return false,
            }
        }
        true
    };
    // Begin at the directory containing the symlink, then apply target.
    let parent_ok = link_rel.parent().map(&mut walk).unwrap_or(true);
    parent_ok && walk(tpath)
}

/// Manifest version this build writes.
///
/// Version 2 added a BLAKE3 per payload block, so a reader can verify what
/// it serves without reassembling the whole entry. Version 3 added the two
/// structure hashes in the header: `prefix_hash` over the runtime ELF the
/// package prepends, and `footer_hash` over the file's footer. Together
/// they make the whole container verifiable, which version 1 and 2
/// manifests lack. Both remain readable; their hash fields read as zeros.
pub const MANIFEST_VERSION: u16 = 3;

/// Byte range of the `footer_hash` header field inside a serialized
/// version-3-or-later manifest. The manifest checksum is computed over the
/// manifest with this range zeroed, because the field is pinned by the
/// footer hash instead; see [`crate::footer::Footer::structure_hash`].
pub const FOOTER_HASH_RANGE: std::ops::Range<usize> = 82..114;

/// Manifest header size at [`MANIFEST_VERSION`]: the 50-byte version 1
/// header plus the two 32-byte structure hashes.
pub const MANIFEST_HEADER_SIZE: usize = 114;

/// Size of the version 1/2 header, which carried no structure hashes.
const V1_HEADER_SIZE: usize = 50;

#[derive(Debug, Clone)]
pub struct ManifestHeader {
    /// Manifest format version.
    pub version: u16,
    /// Total number of filesystem entries in the manifest.
    pub entry_count: u32,
    /// Size of the string table in bytes.
    pub string_table_size: u32,
    /// Number of entrypoints defined in this package.
    pub entrypoint_count: u16,
    /// Index of the default entrypoint to use when none is specified.
    pub default_entrypoint: u16,
    /// Number of library directory paths in the manifest.
    pub lib_dir_count: u16,
    /// Offset into the string table for the package name.
    pub name_offset: u16,
    /// Unique package identifier (BLAKE3 hash).
    pub package_id: [u8; 32],
    /// BLAKE3 over the runtime ELF prefix, the file bytes
    /// `[0, manifest_offset)`. Zero in manifests written before version 3.
    pub prefix_hash: [u8; 32],
    /// BLAKE3 over the file's footer with the manifest-derived layout
    /// fields zeroed, per [`crate::footer::Footer::structure_hash`]. Zero
    /// in manifests written before version 3.
    pub footer_hash: [u8; 32],
}

impl ManifestHeader {
    pub fn write_to<W: Write>(&self, w: &mut W) -> io::Result<()> {
        w.write_all(&self.version.to_le_bytes())?;
        w.write_all(&self.entry_count.to_le_bytes())?;
        w.write_all(&self.string_table_size.to_le_bytes())?;
        w.write_all(&self.entrypoint_count.to_le_bytes())?;
        w.write_all(&self.default_entrypoint.to_le_bytes())?;
        w.write_all(&self.lib_dir_count.to_le_bytes())?;
        w.write_all(&self.name_offset.to_le_bytes())?;
        w.write_all(&self.package_id)?;
        w.write_all(&self.prefix_hash)?;
        w.write_all(&self.footer_hash)?;
        Ok(())
    }

    pub fn read_from<R: Read>(r: &mut R) -> io::Result<Self> {
        let mut buf = [0u8; V1_HEADER_SIZE];
        r.read_exact(&mut buf)?;

        let mut package_id = [0u8; 32];
        package_id.copy_from_slice(&buf[18..50]);

        let mut header = ManifestHeader {
            version: u16::from_le_bytes(buf[0..2].try_into().unwrap()),
            entry_count: u32::from_le_bytes(buf[2..6].try_into().unwrap()),
            string_table_size: u32::from_le_bytes(buf[6..10].try_into().unwrap()),
            entrypoint_count: u16::from_le_bytes(buf[10..12].try_into().unwrap()),
            default_entrypoint: u16::from_le_bytes(buf[12..14].try_into().unwrap()),
            lib_dir_count: u16::from_le_bytes(buf[14..16].try_into().unwrap()),
            name_offset: u16::from_le_bytes(buf[16..18].try_into().unwrap()),
            package_id,
            prefix_hash: [0; 32],
            footer_hash: [0; 32],
        };

        // Version 3 extended the header with the structure hashes. Older
        // manifests simply have no such fields, which reads as zeros.
        if header.version >= 3 {
            let mut hashes = [0u8; 64];
            r.read_exact(&mut hashes)?;
            header.prefix_hash.copy_from_slice(&hashes[..32]);
            header.footer_hash.copy_from_slice(&hashes[32..]);
        }

        Ok(header)
    }
}

/// The xxh32 checksum a footer carries over `manifest`'s uncompressed
/// bytes: plain xxh32 for version 1/2 manifests, xxh32 with the
/// `footer_hash` header field zeroed from version 3 on, since that field
/// is pinned by [`crate::footer::Footer::structure_hash`] instead. The
/// packer, the runtime loader and `verify` must all agree on this, so it
/// lives here rather than at each call site.
///
/// Fails when `manifest` is too short to hold the header fields the
/// checksum depends on, which only a corrupt or crafted footer produces.
pub fn manifest_checksum(manifest: &[u8]) -> io::Result<[u8; 4]> {
    let truncated = || io::Error::new(io::ErrorKind::InvalidData, "manifest header truncated");
    let version = u16::from_le_bytes(
        manifest
            .get(..2)
            .ok_or_else(truncated)?
            .try_into()
            .expect("u16 version"),
    );
    if version < 3 {
        return Ok(xxhash_rust::xxh32::xxh32(manifest, 0).to_le_bytes());
    }
    if manifest.len() < MANIFEST_HEADER_SIZE {
        return Err(truncated());
    }
    let mut zeroed = manifest.to_vec();
    zeroed[FOOTER_HASH_RANGE].fill(0);
    Ok(xxhash_rust::xxh32::xxh32(&zeroed, 0).to_le_bytes())
}

#[derive(Debug, Clone)]
pub struct Manifest {
    /// Fixed-size header containing counts, offsets, and the package ID.
    pub header: ManifestHeader,
    /// Named executable entrypoints into the package.
    pub entrypoints: Vec<EntryPoint>,
    /// All filesystem entries (files, directories, symlinks) in the package.
    pub entries: Vec<Entry>,
    /// Library directory string table offsets: the bundle's library directories.
    pub lib_dir_offsets: Vec<u32>,
    /// Null-terminated string pool referenced by offset from entries and entrypoints.
    pub string_table: Vec<u8>,
}

impl Manifest {
    /// Serialize at [`MANIFEST_VERSION`].
    ///
    /// The version field is written from the constant rather than from
    /// `header`, because the body is always laid out in the current format.
    /// Trusting a caller-supplied version would let the header advertise
    /// version 1 while the blocks carry a version 2 hash, which a reader
    /// would then decode at the wrong width.
    pub fn serialize(&self) -> io::Result<Vec<u8>> {
        let mut buf = Vec::new();
        let header = ManifestHeader {
            version: MANIFEST_VERSION,
            ..self.header.clone()
        };
        header.write_to(&mut buf)?;
        for ep in &self.entrypoints {
            ep.write_to(&mut buf)?;
        }
        for entry in &self.entries {
            entry.write_to(&mut buf)?;
        }
        for &offset in &self.lib_dir_offsets {
            buf.write_all(&offset.to_le_bytes())?;
        }
        buf.write_all(&self.string_table)?;
        Ok(buf)
    }

    pub fn deserialize(data: &[u8]) -> io::Result<Self> {
        let total = data.len();
        let mut cursor = Cursor::new(data);
        let header = ManifestHeader::read_from(&mut cursor)?;

        if header.version == 0 || header.version > MANIFEST_VERSION {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                format!("unsupported manifest version: {}", header.version),
            ));
        }
        let version = header.version;

        // Clamp every speculative allocation to what the input can back,
        // so an oversized count in the header cannot request huge memory
        // before `read_exact` fails on the truncated data.
        let remaining = |c: &Cursor<&[u8]>| total.saturating_sub(c.position() as usize);

        let ep_cap = (header.entrypoint_count as usize).min(remaining(&cursor) / ENTRYPOINT_SIZE);
        let mut entrypoints = Vec::with_capacity(ep_cap);
        for _ in 0..header.entrypoint_count {
            entrypoints.push(EntryPoint::read_from(&mut cursor)?);
        }

        let entry_cap = (header.entry_count as usize).min(remaining(&cursor) / ENTRY_HEADER_SIZE);
        let mut entries = Vec::with_capacity(entry_cap);
        for _ in 0..header.entry_count {
            entries.push(Entry::read_from(&mut cursor, version)?);
        }

        let ld_cap = (header.lib_dir_count as usize).min(remaining(&cursor) / 4);
        let mut lib_dir_offsets = Vec::with_capacity(ld_cap);
        for _ in 0..header.lib_dir_count {
            let mut offset_buf = [0u8; 4];
            cursor.read_exact(&mut offset_buf)?;
            lib_dir_offsets.push(u32::from_le_bytes(offset_buf));
        }

        let st_size = header.string_table_size as usize;
        if st_size > remaining(&cursor) {
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "string table size exceeds remaining input",
            ));
        }
        let mut string_table = vec![0u8; st_size];
        cursor.read_exact(&mut string_table)?;

        let manifest = Manifest {
            header,
            entrypoints,
            entries,
            lib_dir_offsets,
            string_table,
        };
        manifest.validate()?;
        Ok(manifest)
    }

    /// Validate every cross-reference (parent, target_entry,
    /// default_entrypoint, string offsets) against its range. Rejects a
    /// crafted manifest before any consumer indexes it directly.
    fn validate(&self) -> io::Result<()> {
        let n = self.entries.len();
        let st = self.string_table.len() as u32;
        let bad = |msg: &'static str| io::Error::new(io::ErrorKind::InvalidData, msg);

        for (i, e) in self.entries.iter().enumerate() {
            // The packer writes every directory before its contents, so a
            // parent always precedes its children. Requiring that here is
            // what rules out a cycle, which would otherwise make every
            // path lookup walk the whole table.
            if e.parent != u32::MAX {
                let p = e.parent as usize;
                if p >= n {
                    return Err(bad("entry parent index out of range"));
                }
                if p >= i {
                    return Err(bad("entry parent does not precede it"));
                }
                if self.entries[p].kind != EntryKind::Dir {
                    return Err(bad("entry parent is not a directory"));
                }
            }
            if e.name > st {
                return Err(bad("entry name offset out of range"));
            }
            if e.symlink_target > st {
                return Err(bad("entry symlink_target offset out of range"));
            }
        }
        for ep in &self.entrypoints {
            if ep.target_entry as usize >= n {
                return Err(bad("entrypoint target_entry out of range"));
            }
            if ep.name > st || ep.args > st {
                return Err(bad("entrypoint string offset out of range"));
            }
        }
        if !self.entrypoints.is_empty()
            && self.header.default_entrypoint as usize >= self.entrypoints.len()
        {
            return Err(bad("default_entrypoint out of range"));
        }
        for &off in &self.lib_dir_offsets {
            if off > st {
                return Err(bad("lib_dir offset out of range"));
            }
            // Joined onto the package root and put on the library path, so
            // an absolute one or one climbing out would name a host
            // directory.
            let dir = self.get_string(off);
            let safe = !dir.is_empty()
                && std::path::Path::new(dir)
                    .components()
                    .all(|c| matches!(c, std::path::Component::Normal(_)))
                && !dir.contains('\0');
            if !safe {
                return Err(bad("lib_dir is not a relative path inside the package"));
            }
        }
        if self.header.name_offset as u32 > st {
            return Err(bad("name_offset out of range"));
        }
        Ok(())
    }

    /// Returns the package name, or empty string if unset.
    pub fn name(&self) -> &str {
        if self.header.name_offset > 0 {
            self.get_string(self.header.name_offset as u32)
        } else {
            ""
        }
    }

    /// Returns resolved library directory paths.
    pub fn lib_dirs(&self) -> Vec<&str> {
        self.lib_dir_offsets
            .iter()
            .map(|&offset| self.get_string(offset))
            .collect()
    }

    pub fn get_string(&self, offset: u32) -> &str {
        let start = offset as usize;
        let Some(tail) = self.string_table.get(start..) else {
            return "";
        };
        let end = tail.iter().position(|&b| b == 0).unwrap_or(tail.len());
        std::str::from_utf8(&tail[..end]).unwrap_or("")
    }

    /// Check if a top-level directory with the given name exists
    pub fn has_toplevel_dir(&self, name: &str) -> bool {
        use crate::entry::EntryKind;
        self.entries.iter().any(|e| {
            e.kind == EntryKind::Dir && e.parent == u32::MAX && self.get_string(e.name) == name
        })
    }

    /// Find the path to a lib directory if one exists
    /// Returns the path (e.g., "lib" or "overlayed/lib") or empty string if not found
    pub fn find_lib_dir(&self) -> String {
        use crate::entry::EntryKind;
        for (i, e) in self.entries.iter().enumerate() {
            if e.kind == EntryKind::Dir && self.get_string(e.name) == "lib" {
                return self.entry_path(i);
            }
        }
        String::new()
    }

    /// Reconstruct the full path for an entry by walking parent chain.
    ///
    /// The walk is bounded to the number of entries, so a crafted parent
    /// cycle terminates instead of looping forever, and an out-of-range
    /// parent index stops the walk instead of panicking.
    pub fn entry_path(&self, index: usize) -> String {
        let mut parts = Vec::new();
        let mut idx = index;
        for _ in 0..=self.entries.len() {
            let Some(entry) = self.entries.get(idx) else {
                break;
            };
            let name = self.get_string(entry.name);
            if name.is_empty() {
                break;
            }
            parts.push(name);
            if entry.parent == u32::MAX {
                break;
            }
            idx = entry.parent as usize;
        }
        parts.reverse();
        parts.join("/")
    }

    /// Like [`Manifest::entry_path`], but validates every component is a
    /// safe single path segment (no `..`, no absolute or embedded `/`,
    /// no NUL) and returns a relative [`PathBuf`]. Callers extracting to
    /// disk MUST use this and confirm the joined path stays under the
    /// target root. Errors on an unsafe component or out-of-range parent.
    pub fn validated_entry_path(&self, index: usize) -> io::Result<PathBuf> {
        let mut parts: Vec<&str> = Vec::new();
        let mut idx = index;
        for _ in 0..=self.entries.len() {
            let entry = self.entries.get(idx).ok_or_else(|| {
                io::Error::new(
                    io::ErrorKind::InvalidData,
                    "entry parent index out of range",
                )
            })?;
            let name = self.get_string(entry.name);
            if name.is_empty() {
                break;
            }
            if !is_safe_component(name) {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    format!("unsafe path component: {name:?}"),
                ));
            }
            parts.push(name);
            if entry.parent == u32::MAX {
                break;
            }
            if entry.parent as usize >= idx {
                return Err(io::Error::new(
                    io::ErrorKind::InvalidData,
                    "entry parent does not precede it",
                ));
            }
            idx = entry.parent as usize;
        }
        parts.reverse();
        let mut path = PathBuf::new();
        for part in parts {
            path.push(part);
        }
        Ok(path)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::entry::{Block, Entry, EntryKind};

    fn entry(name: u32, parent: u32) -> Entry {
        Entry {
            kind: EntryKind::Dir,
            parent,
            name,
            mode: 0o755,
            mtime_secs: 0,
            mtime_nsec: 0,
            content_hash: [0u8; 32],
            blocks: Vec::new(),
            symlink_target: 0,
        }
    }

    fn manifest(entries: Vec<Entry>, string_table: Vec<u8>) -> Manifest {
        Manifest {
            header: ManifestHeader {
                version: MANIFEST_VERSION,
                entry_count: entries.len() as u32,
                string_table_size: string_table.len() as u32,
                entrypoint_count: 0,
                default_entrypoint: 0,
                lib_dir_count: 0,
                name_offset: 0,
                package_id: [0u8; 32],
                prefix_hash: [0u8; 32],
                footer_hash: [0u8; 32],
            },
            entrypoints: Vec::new(),
            entries,
            lib_dir_offsets: Vec::new(),
            string_table,
        }
    }

    #[test]
    fn roundtrip_valid_manifest() {
        // string table: "\0a\0b\0" -> "a" at 1, "b" at 3
        let st = b"\0a\0b\0".to_vec();
        let m = manifest(vec![entry(1, u32::MAX), entry(3, 0)], st);
        let bytes = m.serialize().unwrap();
        let back = Manifest::deserialize(&bytes).unwrap();
        assert_eq!(back.entry_path(1), "a/b");
        assert_eq!(back.get_string(3), "b");
    }

    #[test]
    fn file_entry_with_blocks_roundtrips_byte_identical() {
        // A File entry carrying two payload blocks. The serialized block
        // count is derived from `blocks.len()` now that `num_blocks` is gone;
        // this asserts the derivation and a byte-identical re-serialize.
        let mut file = entry(1, u32::MAX);
        file.kind = EntryKind::File;
        file.blocks = vec![
            Block {
                payload_offset: 0,
                compressed_size: 10,
                original_size: 20,
                content_hash: [0u8; 32],
            },
            Block {
                payload_offset: 10,
                compressed_size: 5,
                original_size: 8,
                content_hash: [0u8; 32],
            },
        ];
        let m = manifest(vec![file], b"\0a\0".to_vec());

        let bytes = m.serialize().unwrap();
        let back = Manifest::deserialize(&bytes).unwrap();
        assert_eq!(back.entries[0].blocks.len(), 2);
        assert_eq!(back.entries[0].blocks[1].original_size, 8);
        // Re-serializing the decoded manifest must reproduce the exact bytes.
        assert_eq!(back.serialize().unwrap(), bytes);
    }

    /// Version 1 laid blocks out 24 bytes wide with no per-block hash.
    /// Packages already published in that format must keep decoding, and
    /// their blocks must report that they carry no hash.
    #[test]
    fn version_one_blocks_still_decode() {
        let mut file = entry(1, u32::MAX);
        file.kind = EntryKind::File;
        file.blocks = vec![Block {
            payload_offset: 7,
            compressed_size: 11,
            original_size: 13,
            content_hash: [0u8; 32],
        }];
        let m = manifest(vec![file], b"\0a\0".to_vec());

        // Hand-assemble the v1 encoding: the current writer only emits v3,
        // whose header carries the two structure hashes v1 lacked.
        let mut bytes = Vec::new();
        let header = &m.header;
        bytes.extend_from_slice(&1u16.to_le_bytes());
        bytes.extend_from_slice(&header.entry_count.to_le_bytes());
        bytes.extend_from_slice(&header.string_table_size.to_le_bytes());
        bytes.extend_from_slice(&header.entrypoint_count.to_le_bytes());
        bytes.extend_from_slice(&header.default_entrypoint.to_le_bytes());
        bytes.extend_from_slice(&header.lib_dir_count.to_le_bytes());
        bytes.extend_from_slice(&header.name_offset.to_le_bytes());
        bytes.extend_from_slice(&header.package_id);
        let e = &m.entries[0];
        bytes.push(e.kind as u8);
        bytes.extend_from_slice(&e.parent.to_le_bytes());
        bytes.extend_from_slice(&e.name.to_le_bytes());
        bytes.extend_from_slice(&e.mode.to_le_bytes());
        bytes.extend_from_slice(&e.mtime_secs.to_le_bytes());
        bytes.extend_from_slice(&e.mtime_nsec.to_le_bytes());
        bytes.extend_from_slice(&e.content_hash);
        bytes.extend_from_slice(&1u32.to_le_bytes());
        bytes.extend_from_slice(&e.symlink_target.to_le_bytes());
        let b = &e.blocks[0];
        bytes.extend_from_slice(&b.payload_offset.to_le_bytes());
        bytes.extend_from_slice(&b.compressed_size.to_le_bytes());
        bytes.extend_from_slice(&b.original_size.to_le_bytes());
        bytes.extend_from_slice(&m.string_table);

        let back = Manifest::deserialize(&bytes).expect("version 1 must decode");
        assert_eq!(back.header.version, 1);
        let block = &back.entries[0].blocks[0];
        assert_eq!(block.payload_offset, 7);
        assert_eq!(block.compressed_size, 11);
        assert_eq!(block.original_size, 13);
        assert!(!block.has_content_hash(), "v1 carries no per-block hash");
        // A pre-v3 manifest has no structure hashes; they read as zeros.
        assert_eq!(back.header.prefix_hash, [0u8; 32]);
        assert_eq!(back.header.footer_hash, [0u8; 32]);
    }

    #[test]
    fn structure_hashes_roundtrip_through_serialization() {
        let mut m = manifest(vec![entry(1, u32::MAX)], b"\0a\0".to_vec());
        m.header.prefix_hash = [1u8; 32];
        m.header.footer_hash = [2u8; 32];
        let bytes = m.serialize().unwrap();
        let back = Manifest::deserialize(&bytes).unwrap();
        assert_eq!(back.header.prefix_hash, [1u8; 32]);
        assert_eq!(back.header.footer_hash, [2u8; 32]);
        // Re-serializing the decoded manifest must reproduce the bytes.
        assert_eq!(back.serialize().unwrap(), bytes);
    }

    #[test]
    fn manifest_checksum_zeroes_the_footer_hash_field_from_v3() {
        let mut m = manifest(vec![entry(1, u32::MAX)], b"\0a\0".to_vec());
        m.header.prefix_hash = [3u8; 32];
        m.header.footer_hash = [4u8; 32];
        let bytes = m.serialize().unwrap();

        let mut zeroed = bytes.clone();
        zeroed[FOOTER_HASH_RANGE].fill(0);
        assert_eq!(
            manifest_checksum(&bytes).unwrap(),
            xxhash_rust::xxh32::xxh32(&zeroed, 0).to_le_bytes()
        );
        // The prefix hash is covered by the checksum, only footer_hash is
        // excluded.
        assert_ne!(
            manifest_checksum(&bytes).unwrap(),
            xxhash_rust::xxh32::xxh32(&bytes, 0).to_le_bytes()
        );

        // Version 1 bytes checksum plainly: the field does not exist there.
        let v1 = [0u8, 0, 1, 2, 3];
        assert_eq!(
            manifest_checksum(&v1).unwrap(),
            xxhash_rust::xxh32::xxh32(&v1, 0).to_le_bytes()
        );
    }

    /// A crafted footer can make the manifest decompress to anything, and
    /// the checksum runs before `deserialize` checks the length.
    #[test]
    fn manifest_checksum_refuses_truncated_headers() {
        assert!(manifest_checksum(&[]).is_err());
        assert!(manifest_checksum(&[3]).is_err());
        let mut short_v3 = vec![0u8; MANIFEST_HEADER_SIZE - 1];
        short_v3[0] = 3;
        assert!(manifest_checksum(&short_v3).is_err());
        short_v3.push(0);
        assert!(manifest_checksum(&short_v3).is_ok());
    }

    #[test]
    fn future_versions_are_refused() {
        let m = manifest(vec![entry(1, u32::MAX)], b"\0a\0".to_vec());
        let mut bytes = m.serialize().unwrap();
        bytes[0..2].copy_from_slice(&(MANIFEST_VERSION + 1).to_le_bytes());
        assert!(Manifest::deserialize(&bytes).is_err());
        bytes[0..2].copy_from_slice(&0u16.to_le_bytes());
        assert!(Manifest::deserialize(&bytes).is_err());
    }

    #[test]
    fn serialize_always_writes_the_current_version() {
        let mut m = manifest(vec![entry(1, u32::MAX)], b"\0a\0".to_vec());
        m.header.version = 1;
        let bytes = m.serialize().unwrap();
        assert_eq!(
            u16::from_le_bytes(bytes[0..2].try_into().unwrap()),
            MANIFEST_VERSION,
            "the body is written in the current format, so the header must say so"
        );
    }

    #[test]
    fn get_string_out_of_range_returns_empty() {
        let m = manifest(vec![entry(0, u32::MAX)], b"\0".to_vec());
        assert_eq!(m.get_string(9999), "");
    }

    #[test]
    fn oversized_entry_count_errors_without_panic() {
        let m = manifest(vec![entry(1, u32::MAX)], b"\0a\0".to_vec());
        let mut bytes = m.serialize().unwrap();
        // entry_count lives at header offset 2..6.
        bytes[2..6].copy_from_slice(&u32::MAX.to_le_bytes());
        assert!(Manifest::deserialize(&bytes).is_err());
    }

    #[test]
    fn oversized_string_table_errors() {
        let m = manifest(vec![entry(1, u32::MAX)], b"\0a\0".to_vec());
        let mut bytes = m.serialize().unwrap();
        // string_table_size lives at header offset 6..10.
        bytes[6..10].copy_from_slice(&u32::MAX.to_le_bytes());
        assert!(Manifest::deserialize(&bytes).is_err());
    }

    #[test]
    fn out_of_range_parent_rejected_at_deserialize() {
        let m = manifest(vec![entry(1, 5)], b"\0a\0".to_vec());
        let bytes = m.serialize().unwrap();
        assert!(Manifest::deserialize(&bytes).is_err());
    }

    #[test]
    fn parent_cycle_is_rejected() {
        // entries 0 and 1 point at each other. Deserializing refuses the
        // table, and a path lookup on it in memory errors rather than
        // returning a path that walked the cycle.
        let st = b"\0a\0b\0".to_vec();
        let m = manifest(vec![entry(1, 1), entry(3, 0)], st);
        assert!(Manifest::deserialize(&m.serialize().unwrap()).is_err());
        assert!(m.validated_entry_path(0).is_err());
        assert!(
            !m.entry_path(0).is_empty(),
            "the unvalidated walk still ends"
        );
    }

    #[test]
    fn a_lib_dir_leaving_the_package_is_rejected() {
        for (st, ok) in [
            (&b"\0lib\0"[..], true),
            (b"\0opt/app/lib\0", true),
            (b"\0/usr/lib\0", false),
            (b"\0../lib\0", false),
            (b"\0lib/../../x\0", false),
            (b"\0\0", false),
        ] {
            let mut m = manifest(vec![entry(0, u32::MAX)], st.to_vec());
            m.lib_dir_offsets = vec![1];
            m.header.lib_dir_count = 1;
            let back = Manifest::deserialize(&m.serialize().unwrap());
            assert_eq!(back.is_ok(), ok, "{:?}", String::from_utf8_lossy(st));
        }
    }

    #[test]
    fn a_file_cannot_be_a_parent() {
        let st = b"\0a\0b\0".to_vec();
        let mut file = entry(1, u32::MAX);
        file.kind = EntryKind::File;
        let m = manifest(vec![file, entry(3, 0)], st);
        assert!(Manifest::deserialize(&m.serialize().unwrap()).is_err());
    }

    #[test]
    fn unsafe_component_rejected() {
        // name ".." at offset 1.
        let m = manifest(vec![entry(1, u32::MAX)], b"\0..\0".to_vec());
        assert!(m.validated_entry_path(0).is_err());
    }

    #[test]
    fn safe_component_accepted() {
        let m = manifest(vec![entry(1, u32::MAX)], b"\0a\0".to_vec());
        assert_eq!(m.validated_entry_path(0).unwrap().to_str(), Some("a"));
    }

    #[test]
    fn is_safe_component_rules() {
        assert!(is_safe_component("lib"));
        assert!(!is_safe_component(""));
        assert!(!is_safe_component("."));
        assert!(!is_safe_component(".."));
        assert!(!is_safe_component("a/b"));
        assert!(!is_safe_component("a\0b"));
    }

    #[test]
    fn symlink_within_root_rules() {
        use std::path::Path;
        // Relative target that stays inside the root.
        assert!(symlink_target_within_root(
            Path::new("bin/app"),
            "../lib/x.so"
        ));
        assert!(symlink_target_within_root(Path::new("a/b/c"), "d"));
        // Absolute targets are refused.
        assert!(!symlink_target_within_root(
            Path::new("bin/app"),
            "/etc/passwd"
        ));
        // Walking above the root is refused.
        assert!(!symlink_target_within_root(
            Path::new("bin/app"),
            "../../etc/passwd"
        ));
        assert!(!symlink_target_within_root(Path::new("top"), "../escape"));
        // Empty target is refused.
        assert!(!symlink_target_within_root(Path::new("x"), ""));
    }
}

/// Helper for building a string table during packing.
#[derive(Debug, Default)]
pub struct StringTableBuilder {
    data: Vec<u8>,
    index: HashMap<String, u32>,
}

impl StringTableBuilder {
    pub fn new() -> Self {
        Self {
            data: Vec::new(),
            index: HashMap::new(),
        }
    }

    /// Add a string and return its offset in the table.
    pub fn add(&mut self, s: &str) -> u32 {
        if let Some(&offset) = self.index.get(s) {
            return offset;
        }
        let offset = self.data.len() as u32;
        self.data.extend_from_slice(s.as_bytes());
        self.data.push(0);
        self.index.insert(s.to_owned(), offset);
        offset
    }

    pub fn finish(self) -> Vec<u8> {
        self.data
    }

    /// Current size of the table in bytes, which is also the offset the
    /// next distinct string will be added at.
    pub fn len(&self) -> u32 {
        self.data.len() as u32
    }

    /// True before any string has been added. A table that has had even
    /// the empty string added is non-empty, since each entry contributes
    /// its terminating NUL.
    pub fn is_empty(&self) -> bool {
        self.data.is_empty()
    }
}