Skip to main content

ostrya_core/
dirtree.rs

1//! Dirtree objects: the sorted lists of child files and subdirectories.
2//!
3//! Wire form `(a(say)a(sayay))`: file entries (name, content checksum) and
4//! directory entries (name, dirtree checksum, dirmeta checksum). Both lists
5//! are sorted by name with byte-wise comparison; the sort order is mandatory
6//! for reproducible checksums, so it is validated on both paths. Each entry
7//! name is validated as a single path component (not `.` or `..`, no `/`,
8//! non-empty; UTF-8 is enforced by the string decoder): this is the
9//! path-traversal defense.
10//!
11//! No name may appear in both lists: the two entries would claim the same
12//! checkout path. This is checked on the write path and when materializing an
13//! owned [`DirTree`] (via [`DirTree::parse`]). The borrowed [`DirTreeRef`]
14//! iterators stay per-list and allocation-free, matching the tool, which reads
15//! such an object without a cross-list check (`ostree fsck` accepts it and
16//! `ostree ls` lists both entries) and aborts only when it later resolves the
17//! name as a directory.
18//!
19//! [`DirTreeRef`] is the borrowed read-path view: `parse` validates the
20//! container framing, and the entry-level checks (name, checksum length,
21//! sort order) run as entries are visited, which is why the iterators yield
22//! `Result`. After an error an iterator is exhausted. A full dirtree walk
23//! borrows the object buffer throughout.
24
25use ostrya_gvariant::{ArrayIter, GvDecode, GvEncode, GvType, Slice};
26
27use crate::checksum::Checksum;
28use crate::error::{Error, Result};
29use crate::valiter::ValidatedIter;
30
31/// An owned dirtree object. Both lists must be name-sorted (byte-wise,
32/// strictly increasing) and no name may appear in both lists; `serialize`
33/// validates this.
34#[derive(Debug, Clone, PartialEq, Eq, Default)]
35pub struct DirTree {
36    /// (file name, content checksum), name-sorted.
37    pub files: Vec<(String, Checksum)>,
38    /// (dir name, dirtree checksum, dirmeta checksum), name-sorted.
39    pub dirs: Vec<(String, Checksum, Checksum)>,
40}
41
42/// The path-traversal defense for one entry name.
43fn check_name(name: &str) -> Result<()> {
44    if name.is_empty() {
45        return Err(Error::InvalidDirTree("empty entry name"));
46    }
47    if name == "." || name == ".." {
48        return Err(Error::InvalidDirTree("entry name is a directory traversal"));
49    }
50    if name.contains('/') {
51        return Err(Error::InvalidDirTree("entry name contains a slash"));
52    }
53    Ok(())
54}
55
56/// Validate one visited name against the previous one: valid component,
57/// byte-wise strictly increasing (which rejects duplicates).
58fn check_entry<'a>(prev: &mut Option<&'a str>, name: &'a str) -> Result<()> {
59    check_name(name)?;
60    if let Some(prev) = prev
61        && *prev >= name
62    {
63        return Err(Error::InvalidDirTree("entry names are not sorted"));
64    }
65    *prev = Some(name);
66    Ok(())
67}
68
69fn entry_checksum(bytes: &[u8]) -> Result<Checksum> {
70    Checksum::from_ay(bytes).map_err(|_| Error::InvalidDirTree("entry checksum is not 32 bytes"))
71}
72
73impl DirTree {
74    /// Parse a serialized dirtree object into an owned, structurally sound
75    /// tree: the per-list checks run as entries are collected, then the
76    /// cross-list duplicate-name check runs over the materialized lists.
77    pub fn parse(data: &[u8]) -> Result<DirTree> {
78        let tree = DirTreeRef::parse(data)?.to_owned()?;
79        tree.check_no_shared_names()?;
80        Ok(tree)
81    }
82
83    /// Serialize to normal-form bytes; their SHA-256 is the object identity.
84    pub fn serialize(&self) -> Result<Vec<u8>> {
85        self.validate()?;
86        Ok(ostrya_gvariant::encode_to_vec(self)?)
87    }
88
89    fn validate(&self) -> Result<()> {
90        let mut prev = None;
91        for (name, _) in &self.files {
92            check_entry(&mut prev, name)?;
93        }
94        let mut prev = None;
95        for (name, _, _) in &self.dirs {
96            check_entry(&mut prev, name)?;
97        }
98        self.check_no_shared_names()
99    }
100
101    /// No name may appear in both lists. Both lists are name-sorted by the
102    /// time this runs (validated per list above, or by `to_owned` on the read
103    /// path), so a merge-style walk finds any shared name without allocating.
104    fn check_no_shared_names(&self) -> Result<()> {
105        let mut files = self.files.iter().map(|(n, _)| n.as_str());
106        let mut dirs = self.dirs.iter().map(|(n, _, _)| n.as_str());
107        let (mut f, mut d) = (files.next(), dirs.next());
108        while let (Some(fname), Some(dname)) = (f, d) {
109            match fname.cmp(dname) {
110                std::cmp::Ordering::Less => f = files.next(),
111                std::cmp::Ordering::Greater => d = dirs.next(),
112                std::cmp::Ordering::Equal => {
113                    return Err(Error::InvalidDirTree(
114                        "a name appears in both the file and directory lists",
115                    ));
116                }
117            }
118        }
119        Ok(())
120    }
121}
122
123impl GvType for DirTree {
124    const SIGNATURE: &'static str = "(a(say)a(sayay))";
125    // Every member is alignment-1 (strings and byte arrays).
126    const ALIGNMENT: usize = 1;
127    const FIXED_SIZE: Option<usize> = None;
128}
129
130/// The encode path is purely mechanical: sort and cross-list validation runs in
131/// [`DirTree::serialize`], the only caller. The owned entry vectors encode
132/// directly, since `String` and `Checksum` are themselves encodable.
133impl GvEncode for DirTree {
134    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
135        (Slice(&self.files), Slice(&self.dirs)).encode(out)
136    }
137}
138
139/// A borrowed view of a serialized dirtree object.
140#[derive(Clone, Copy)]
141pub struct DirTreeRef<'a> {
142    files: ArrayIter<'a, (&'a str, &'a [u8])>,
143    dirs: ArrayIter<'a, (&'a str, &'a [u8], &'a [u8])>,
144}
145
146impl<'a> DirTreeRef<'a> {
147    /// Parse the slice covering exactly a serialized dirtree object.
148    pub fn parse(data: &'a [u8]) -> Result<DirTreeRef<'a>> {
149        let (files, dirs) = GvDecode::decode(data)?;
150        Ok(DirTreeRef { files, dirs })
151    }
152
153    /// Iterate file entries, validating each as visited.
154    pub fn files(&self) -> impl Iterator<Item = Result<(&'a str, Checksum)>> + use<'a> {
155        ValidatedIter::new(
156            self.files,
157            None,
158            |prev: &mut Option<&'a str>, (name, csum): (&'a str, &'a [u8])| {
159                check_entry(prev, name)?;
160                Ok((name, entry_checksum(csum)?))
161            },
162        )
163    }
164
165    /// Iterate directory entries, validating each as visited.
166    pub fn dirs(&self) -> impl Iterator<Item = Result<(&'a str, Checksum, Checksum)>> + use<'a> {
167        ValidatedIter::new(
168            self.dirs,
169            None,
170            |prev: &mut Option<&'a str>, (name, tree, meta): (&'a str, &'a [u8], &'a [u8])| {
171                check_entry(prev, name)?;
172                Ok((name, entry_checksum(tree)?, entry_checksum(meta)?))
173            },
174        )
175    }
176
177    /// Collect into an owned [`DirTree`].
178    pub fn to_owned(&self) -> Result<DirTree> {
179        let mut owned = DirTree::default();
180        for item in self.files() {
181            let (name, checksum) = item?;
182            owned.files.push((name.to_owned(), checksum));
183        }
184        for item in self.dirs() {
185            let (name, tree, meta) = item?;
186            owned.dirs.push((name.to_owned(), tree, meta));
187        }
188        Ok(owned)
189    }
190}
191
192#[cfg(test)]
193mod tests {
194    use super::*;
195    use ostrya_gvariant::{Type, Value, to_bytes};
196
197    fn csum(byte: u8) -> Checksum {
198        Checksum::from_bytes([byte; 32])
199    }
200
201    fn sample() -> DirTree {
202        DirTree {
203            files: vec![("a.txt".to_owned(), csum(1)), ("b.txt".to_owned(), csum(2))],
204            dirs: vec![("sub".to_owned(), csum(3), csum(4))],
205        }
206    }
207
208    #[test]
209    fn round_trips_through_the_view() {
210        let tree = sample();
211        let bytes = tree.serialize().unwrap();
212        let view = DirTreeRef::parse(&bytes).unwrap();
213        let files: Vec<_> = view.files().map(Result::unwrap).collect();
214        assert_eq!(files, [("a.txt", csum(1)), ("b.txt", csum(2))]);
215        let dirs: Vec<_> = view.dirs().map(Result::unwrap).collect();
216        assert_eq!(dirs, [("sub", csum(3), csum(4))]);
217        assert_eq!(view.to_owned().unwrap(), tree);
218        assert_eq!(DirTree::parse(&bytes).unwrap().serialize().unwrap(), bytes);
219    }
220
221    #[test]
222    fn serialize_rejects_unsorted_and_invalid_names() {
223        for (files, expected) in [
224            (
225                vec![("b".to_owned(), csum(1)), ("a".to_owned(), csum(2))],
226                "entry names are not sorted",
227            ),
228            (
229                vec![("a".to_owned(), csum(1)), ("a".to_owned(), csum(2))],
230                "entry names are not sorted",
231            ),
232            (vec![(String::new(), csum(1))], "empty entry name"),
233            (
234                vec![("..".to_owned(), csum(1))],
235                "entry name is a directory traversal",
236            ),
237            (
238                vec![("a/b".to_owned(), csum(1))],
239                "entry name contains a slash",
240            ),
241        ] {
242            let tree = DirTree {
243                files,
244                dirs: Vec::new(),
245            };
246            assert_eq!(tree.serialize(), Err(Error::InvalidDirTree(expected)));
247        }
248    }
249
250    /// Serialize an arbitrary dirtree through the `Value` tree, bypassing the
251    /// struct's validation.
252    fn craft(files: &[(&str, &[u8])]) -> Vec<u8> {
253        let ty = Type::parse("(a(say)a(sayay))").unwrap();
254        let value = Value::Tuple(vec![
255            Value::Array(
256                files
257                    .iter()
258                    .map(|(name, checksum)| {
259                        Value::Tuple(vec![
260                            Value::Str((*name).to_owned()),
261                            Value::Bytes(checksum.to_vec()),
262                        ])
263                    })
264                    .collect(),
265            ),
266            Value::Array(Vec::new()),
267        ]);
268        to_bytes(&ty, &value).unwrap()
269    }
270
271    #[test]
272    fn view_validates_entries_as_visited_and_fuses_on_error() {
273        let bytes = craft(&[("b", &[1; 32]), ("a", &[2; 32])]);
274        let view = DirTreeRef::parse(&bytes).unwrap();
275        let mut files = view.files();
276        assert!(files.next().unwrap().is_ok());
277        assert_eq!(
278            files.next().unwrap(),
279            Err(Error::InvalidDirTree("entry names are not sorted"))
280        );
281        assert!(files.next().is_none(), "iterator fuses after an error");
282
283        let bytes = craft(&[("a", &[1; 31])]);
284        let view = DirTreeRef::parse(&bytes).unwrap();
285        assert_eq!(
286            view.files().next().unwrap(),
287            Err(Error::InvalidDirTree("entry checksum is not 32 bytes"))
288        );
289
290        let bytes = craft(&[("a/../b", &[1; 32])]);
291        assert_eq!(
292            DirTreeRef::parse(&bytes).unwrap().to_owned(),
293            Err(Error::InvalidDirTree("entry name contains a slash"))
294        );
295    }
296
297    /// Serialize an arbitrary dirtree with both lists populated, bypassing the
298    /// struct's validation.
299    fn craft2(files: &[(&str, &[u8])], dirs: &[(&str, &[u8], &[u8])]) -> Vec<u8> {
300        let ty = Type::parse("(a(say)a(sayay))").unwrap();
301        let value = Value::Tuple(vec![
302            Value::Array(
303                files
304                    .iter()
305                    .map(|(name, c)| {
306                        Value::Tuple(vec![
307                            Value::Str((*name).to_owned()),
308                            Value::Bytes(c.to_vec()),
309                        ])
310                    })
311                    .collect(),
312            ),
313            Value::Array(
314                dirs.iter()
315                    .map(|(name, t, m)| {
316                        Value::Tuple(vec![
317                            Value::Str((*name).to_owned()),
318                            Value::Bytes(t.to_vec()),
319                            Value::Bytes(m.to_vec()),
320                        ])
321                    })
322                    .collect(),
323            ),
324        ]);
325        to_bytes(&ty, &value).unwrap()
326    }
327
328    #[test]
329    fn rejects_a_name_shared_across_file_and_dir_lists() {
330        let shared = Error::InvalidDirTree("a name appears in both the file and directory lists");
331
332        // Writer: minting such an object fails.
333        let tree = DirTree {
334            files: vec![("x".to_owned(), csum(1))],
335            dirs: vec![("x".to_owned(), csum(2), csum(3))],
336        };
337        assert_eq!(tree.serialize(), Err(shared.clone()));
338
339        // Owned read path: materializing the crafted object fails the same way.
340        let bytes = craft2(&[("x", &[1; 32])], &[("x", &[2; 32], &[3; 32])]);
341        assert_eq!(DirTree::parse(&bytes), Err(shared));
342
343        // Borrowed traversal stays per-list: each list yields the shared name
344        // with no cross-list check, matching what the tool reads.
345        let view = DirTreeRef::parse(&bytes).unwrap();
346        assert_eq!(view.files().next().unwrap().unwrap().0, "x");
347        assert_eq!(view.dirs().next().unwrap().unwrap().0, "x");
348    }
349
350    #[test]
351    fn distinct_names_across_lists_are_accepted() {
352        // A file and a directory with different names round-trip cleanly.
353        let bytes = craft2(&[("a", &[1; 32])], &[("b", &[2; 32], &[3; 32])]);
354        let tree = DirTree::parse(&bytes).unwrap();
355        assert_eq!(tree.files.len(), 1);
356        assert_eq!(tree.dirs.len(), 1);
357        assert_eq!(tree.serialize().unwrap(), bytes);
358    }
359}