Skip to main content

sail_cache/
pack.rs

1//! Reply packs: the signed replies a release ships for its pinned vstd
2//! (ADR 0062).
3//!
4//! A pack is one file holding ordinary signed shared entries (ADR 0017),
5//! each exactly as [`sign_entry`] builds it. A
6//! pack adds no trust of its own. A reader looks an entry up by its key and
7//! then applies every check of
8//! [`verify_entry`](crate::shared::verify_entry) against the keys it trusts
9//! for that pack. One file rather than a directory keeps a release archive
10//! small, and lets the release index bind the whole store with one digest.
11//!
12//! **Format.** The line [`MAGIC`], then one record per entry, in ascending
13//! key order: the 32 key bytes, the entry length as a little-endian `u32`,
14//! and the entry bytes. A key appears once. Nothing may follow the last
15//! record.
16
17use std::collections::{BTreeMap, HashMap};
18
19use sail_key::QueryKey;
20
21use crate::DiskCache;
22use crate::Effort;
23use crate::shared::{
24    MAX_ENTRY_BYTES, PublishOptions, PublishReport, SecretKey, eligible, now_unix, sign_entry,
25};
26
27/// The first line of every pack.
28pub const MAGIC: &[u8] = b"sail-reply-pack-v1\n";
29
30/// The largest pack a reader accepts: 256 MiB.
31pub const MAX_PACK_BYTES: u64 = 256 * 1024 * 1024;
32
33/// A parsed pack: its bytes and where each entry lies in them.
34#[derive(Debug)]
35pub struct Pack {
36    data: Vec<u8>,
37    entries: HashMap<[u8; 32], (usize, usize)>,
38}
39
40impl Pack {
41    /// Parses `data` as a pack.
42    ///
43    /// Returns `None` for anything malformed: a wrong first line, a
44    /// truncated record, an entry over [`MAX_ENTRY_BYTES`], keys out of
45    /// order or repeated, trailing bytes, or a pack over
46    /// [`MAX_PACK_BYTES`].
47    #[must_use]
48    pub fn parse(data: Vec<u8>) -> Option<Self> {
49        if data.len() as u64 > MAX_PACK_BYTES || !data.starts_with(MAGIC) {
50            return None;
51        }
52        let mut entries = HashMap::new();
53        let mut at = MAGIC.len();
54        let mut previous: Option<[u8; 32]> = None;
55        while at < data.len() {
56            let key: [u8; 32] = data.get(at..at.checked_add(32)?)?.try_into().ok()?;
57            at += 32;
58            let length: [u8; 4] = data.get(at..at.checked_add(4)?)?.try_into().ok()?;
59            at += 4;
60            let length = u32::from_le_bytes(length);
61            if u64::from(length) > MAX_ENTRY_BYTES {
62                return None;
63            }
64            let length = usize::try_from(length).ok()?;
65            let end = at.checked_add(length)?;
66            data.get(at..end)?;
67            if previous.is_some_and(|p| p >= key) {
68                return None;
69            }
70            previous = Some(key);
71            entries.insert(key, (at, end));
72            at = end;
73        }
74        Some(Self { data, entries })
75    }
76
77    /// The entry bytes stored for `key`, unchecked: the caller verifies them.
78    #[must_use]
79    pub fn get(&self, key: &QueryKey) -> Option<&[u8]> {
80        let &(start, end) = self.entries.get(&key.0)?;
81        self.data.get(start..end)
82    }
83
84    /// The number of entries.
85    #[must_use]
86    pub fn len(&self) -> usize {
87        self.entries.len()
88    }
89
90    /// Whether the pack holds no entry.
91    #[must_use]
92    pub fn is_empty(&self) -> bool {
93        self.entries.is_empty()
94    }
95}
96
97/// Builds a pack of `disk`'s exportable entries, each signed with `secret`.
98///
99/// It selects exactly what `publish` would export (the same eligibility
100/// and serving policy). Entries are written in ascending key order. The
101/// report's `published` counts the entries in the pack, and `failed`
102/// counts entries left out because they are too large for a record.
103#[must_use]
104pub fn build(
105    disk: &DiskCache,
106    secret: &SecretKey,
107    options: &PublishOptions,
108    unknown_ok: &dyn Fn(Option<&Effort>) -> bool,
109) -> (Vec<u8>, PublishReport) {
110    let now = now_unix();
111    let mut signed = BTreeMap::new();
112    let mut report = PublishReport::default();
113    eligible(disk, options, unknown_ok, &mut report, |e, r| {
114        let data = sign_entry(
115            secret,
116            &e.key,
117            &e.reply,
118            &e.meta.command,
119            &e.solver,
120            e.meta.effort.as_ref(),
121            now,
122        );
123        if data.len() as u64 > MAX_ENTRY_BYTES || u32::try_from(data.len()).is_err() {
124            r.failed += 1;
125            return;
126        }
127        signed.insert(e.key.0, data);
128    });
129    let mut out = MAGIC.to_vec();
130    for (key, data) in &signed {
131        out.extend_from_slice(key);
132        out.extend_from_slice(&u32::try_from(data.len()).unwrap_or(u32::MAX).to_le_bytes());
133        out.extend_from_slice(data);
134    }
135    report.published = signed.len() as u64;
136    (out, report)
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    fn record(out: &mut Vec<u8>, key: [u8; 32], entry: &[u8]) {
144        out.extend_from_slice(&key);
145        out.extend_from_slice(&u32::try_from(entry.len()).unwrap_or(0).to_le_bytes());
146        out.extend_from_slice(entry);
147    }
148
149    #[test]
150    fn parses_records_and_finds_each_key() {
151        let mut data = MAGIC.to_vec();
152        record(&mut data, [1; 32], b"one");
153        record(&mut data, [2; 32], b"");
154        record(&mut data, [3; 32], b"three");
155        let pack = Pack::parse(data);
156        let Some(pack) = pack else {
157            unreachable!("a well-formed pack parses")
158        };
159        assert_eq!(pack.len(), 3);
160        assert_eq!(pack.get(&QueryKey([1; 32])), Some(&b"one"[..]));
161        assert_eq!(pack.get(&QueryKey([2; 32])), Some(&b""[..]));
162        assert_eq!(pack.get(&QueryKey([3; 32])), Some(&b"three"[..]));
163        assert_eq!(pack.get(&QueryKey([4; 32])), None);
164        assert!(Pack::parse(MAGIC.to_vec()).is_some_and(|p| p.is_empty()));
165    }
166
167    #[test]
168    fn refuses_every_malformed_pack() {
169        let mut good = MAGIC.to_vec();
170        record(&mut good, [1; 32], b"one");
171        record(&mut good, [2; 32], b"two");
172        assert!(Pack::parse(good.clone()).is_some());
173        // Wrong first line.
174        let mut bad = good.clone();
175        bad[0] = b'x';
176        assert!(Pack::parse(bad).is_none());
177        // Truncated anywhere inside a record (a cut between records is a
178        // shorter, well-formed pack).
179        let boundary = MAGIC.len() + 32 + 4 + 3;
180        for cut in (MAGIC.len() + 1..good.len()).filter(|&cut| cut != boundary) {
181            assert!(Pack::parse(good[..cut].to_vec()).is_none(), "cut at {cut}");
182        }
183        // Trailing bytes.
184        let mut bad = good.clone();
185        bad.push(0);
186        assert!(Pack::parse(bad).is_none());
187        // Repeated and out-of-order keys.
188        let mut bad = MAGIC.to_vec();
189        record(&mut bad, [2; 32], b"two");
190        record(&mut bad, [2; 32], b"two");
191        assert!(Pack::parse(bad).is_none());
192        let mut bad = MAGIC.to_vec();
193        record(&mut bad, [2; 32], b"two");
194        record(&mut bad, [1; 32], b"one");
195        assert!(Pack::parse(bad).is_none());
196        // An entry length over the entry limit.
197        let mut bad = MAGIC.to_vec();
198        bad.extend_from_slice(&[1; 32]);
199        bad.extend_from_slice(&u32::MAX.to_le_bytes());
200        assert!(Pack::parse(bad).is_none());
201    }
202}