Skip to main content

ostrya_core/
xattr.rs

1//! Extended-attribute sets.
2//!
3//! The storage form is GVariant `a(ayay)`: an array of (name-bytes,
4//! value-bytes), sorted by name with byte-wise comparison. A stored name
5//! carries its namespace prefix and a single terminating NUL, with a non-empty
6//! prefix and no interior NUL, matching the form the tool writes.
7//! Canonicalization -- the sort plus the reject-duplicate and name-form checks
8//! -- is applied before every serialization and hash, because the xattr bytes
9//! feed the object checksum.
10
11use ostrya_gvariant::{ArrayIter, GvDecode, GvEncode, GvType, encode_to_vec, write_array};
12
13use crate::error::{Error, Result};
14use crate::valiter::ValidatedIter;
15
16/// A canonical, sorted xattr set.
17///
18/// The set is canonical, so equal sets hold equal bytes in equal order and
19/// hashing agrees with equality: a set serves as a lookup key.
20#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
21pub struct Xattrs(Vec<(Vec<u8>, Vec<u8>)>);
22
23impl Xattrs {
24    /// The empty xattr set.
25    pub fn empty() -> Xattrs {
26        Xattrs(Vec::new())
27    }
28
29    /// Build a canonical set from arbitrary (name, value) pairs: sort by name,
30    /// then reject duplicate names and names not in stored NUL-terminated form.
31    pub fn new(pairs: impl IntoIterator<Item = (Vec<u8>, Vec<u8>)>) -> Result<Xattrs> {
32        let mut pairs: Vec<(Vec<u8>, Vec<u8>)> = pairs.into_iter().collect();
33        pairs.sort_by(|a, b| a.0.cmp(&b.0));
34        for window in pairs.windows(2) {
35            if window[0].0 == window[1].0 {
36                return Err(Error::InvalidXattrs("duplicate xattr name"));
37            }
38        }
39        for (name, _) in &pairs {
40            check_name(name)?;
41        }
42        Ok(Xattrs(pairs))
43    }
44
45    /// Whether the set has no entries.
46    pub fn is_empty(&self) -> bool {
47        self.0.is_empty()
48    }
49
50    /// The number of entries.
51    pub fn len(&self) -> usize {
52        self.0.len()
53    }
54
55    /// Iterate entries in canonical order.
56    pub fn iter(&self) -> impl Iterator<Item = (&[u8], &[u8])> {
57        self.0.iter().map(|(n, v)| (n.as_slice(), v.as_slice()))
58    }
59
60    /// Serialize as normal-form GVariant `a(ayay)`.
61    pub fn to_gvariant(&self) -> Result<Vec<u8>> {
62        Ok(encode_to_vec(&self)?)
63    }
64
65    /// Parse normal-form GVariant `a(ayay)`, requiring the on-disk canonical
66    /// order: names strictly increasing (which rejects both unsorted input and
67    /// duplicates) and non-empty.
68    pub fn from_gvariant(bytes: &[u8]) -> Result<Xattrs> {
69        XattrsRef::parse(bytes)?.to_owned()
70    }
71}
72
73/// Encode the canonical set as `a(ayay)` directly from the owned entries, so a
74/// caller that holds an [`Xattrs`] (a dirmeta or file header) can splice it into
75/// a larger tuple without first collecting a slice of borrowed pairs.
76impl GvType for &Xattrs {
77    const SIGNATURE: &'static str = "a(ayay)";
78    const ALIGNMENT: usize = 1;
79    const FIXED_SIZE: Option<usize> = None;
80}
81
82impl GvEncode for &Xattrs {
83    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
84        // Each element is (ayay): a two-member tuple of byte arrays.
85        type Entry<'e> = (&'e [u8], &'e [u8]);
86        write_array(
87            out,
88            <Entry as GvType>::ALIGNMENT,
89            <Entry as GvType>::FIXED_SIZE.is_some(),
90            self.0.len(),
91            |out, i| {
92                let (name, value) = &self.0[i];
93                (name.as_slice(), value.as_slice()).encode(out)
94            },
95        )
96    }
97}
98
99/// Validate a stored xattr name: non-empty, ending in a single NUL, with no
100/// interior NUL and a non-empty prefix. Confirmed by reading the
101/// `user.ostreemeta` blob of a committed file, where the name `user.demo` is
102/// followed by one `\0`.
103fn check_name(name: &[u8]) -> Result<()> {
104    let Some((&last, rest)) = name.split_last() else {
105        return Err(Error::InvalidXattrs("empty xattr name"));
106    };
107    if last != 0 {
108        return Err(Error::InvalidXattrs(
109            "xattr name is missing its terminating NUL",
110        ));
111    }
112    if rest.is_empty() {
113        return Err(Error::InvalidXattrs("xattr name is empty before its NUL"));
114    }
115    if rest.contains(&0) {
116        return Err(Error::InvalidXattrs("xattr name has an interior NUL"));
117    }
118    Ok(())
119}
120
121/// A borrowed view of a serialized `a(ayay)` xattr set.
122///
123/// `parse` validates the array framing; the canonical-order checks (names
124/// strictly increasing, non-empty) run as entries are visited, which is why
125/// [`iter`](XattrsRef::iter) yields `Result`. After an error the iterator is
126/// exhausted.
127#[derive(Clone, Copy)]
128pub struct XattrsRef<'a> {
129    entries: ArrayIter<'a, (&'a [u8], &'a [u8])>,
130}
131
132impl<'a> XattrsRef<'a> {
133    /// Wrap the slice covering exactly a serialized `a(ayay)`.
134    pub fn parse(data: &'a [u8]) -> Result<XattrsRef<'a>> {
135        Ok(XattrsRef {
136            entries: ArrayIter::decode(data)?,
137        })
138    }
139
140    /// Iterate (name, value) entries, validating canonical order as visited.
141    pub fn iter(&self) -> impl Iterator<Item = Result<(&'a [u8], &'a [u8])>> + use<'a> {
142        ValidatedIter::new(
143            self.entries,
144            None,
145            |prev: &mut Option<&'a [u8]>, (name, value): (&'a [u8], &'a [u8])| {
146                check_name(name)?;
147                if let Some(prev) = prev
148                    && *prev >= name
149                {
150                    return Err(Error::InvalidXattrs("xattr names are not strictly sorted"));
151                }
152                *prev = Some(name);
153                Ok((name, value))
154            },
155        )
156    }
157
158    /// Collect into an owned, canonical [`Xattrs`].
159    pub fn to_owned(&self) -> Result<Xattrs> {
160        let mut pairs = Vec::new();
161        for item in self.iter() {
162            let (name, value) = item?;
163            pairs.push((name.to_vec(), value.to_vec()));
164        }
165        Ok(Xattrs(pairs))
166    }
167}
168
169#[cfg(test)]
170mod tests {
171    use ostrya_gvariant::Slice;
172
173    use super::*;
174
175    #[test]
176    fn new_sorts_by_name() {
177        let x = Xattrs::new([
178            (b"user.z\0".to_vec(), b"1".to_vec()),
179            (b"security.selinux\0".to_vec(), b"2".to_vec()),
180            (b"user.a\0".to_vec(), b"3".to_vec()),
181        ])
182        .unwrap();
183        let names: Vec<&[u8]> = x.iter().map(|(n, _)| n).collect();
184        assert_eq!(
185            names,
186            vec![
187                b"security.selinux\0".as_slice(),
188                b"user.a\0".as_slice(),
189                b"user.z\0".as_slice()
190            ]
191        );
192    }
193
194    #[test]
195    fn new_rejects_duplicate_and_empty_names() {
196        assert!(matches!(
197            Xattrs::new([
198                (b"user.a\0".to_vec(), b"1".to_vec()),
199                (b"user.a\0".to_vec(), b"2".to_vec()),
200            ]),
201            Err(Error::InvalidXattrs("duplicate xattr name"))
202        ));
203        assert!(matches!(
204            Xattrs::new([(Vec::new(), b"1".to_vec())]),
205            Err(Error::InvalidXattrs("empty xattr name"))
206        ));
207    }
208
209    #[test]
210    fn new_requires_terminating_nul_and_no_interior_nul() {
211        // A name taken straight from listxattr(2) output lacks the stored NUL.
212        assert_eq!(
213            Xattrs::new([(b"user.demo".to_vec(), b"v".to_vec())]),
214            Err(Error::InvalidXattrs(
215                "xattr name is missing its terminating NUL"
216            ))
217        );
218        // An interior NUL is not part of a real xattr name.
219        assert_eq!(
220            Xattrs::new([(b"user.\0demo\0".to_vec(), b"v".to_vec())]),
221            Err(Error::InvalidXattrs("xattr name has an interior NUL"))
222        );
223        // A lone NUL has an empty name before it.
224        assert_eq!(
225            Xattrs::new([(b"\0".to_vec(), b"v".to_vec())]),
226            Err(Error::InvalidXattrs("xattr name is empty before its NUL"))
227        );
228    }
229
230    #[test]
231    fn from_gvariant_rejects_names_without_terminating_nul() {
232        // Encode an a(ayay) whose single name lacks the stored NUL.
233        let raw: Vec<(&[u8], &[u8])> = vec![(b"user.demo", b"v")];
234        let bytes = encode_to_vec(&Slice(&raw)).unwrap();
235        assert_eq!(
236            Xattrs::from_gvariant(&bytes),
237            Err(Error::InvalidXattrs(
238                "xattr name is missing its terminating NUL"
239            ))
240        );
241    }
242
243    #[test]
244    fn gvariant_round_trips_and_reencodes_identically() {
245        let x = Xattrs::new([
246            (b"security.capability\0".to_vec(), vec![0x01, 0x00, 0x00]),
247            (b"user.mime_type\0".to_vec(), b"text/plain".to_vec()),
248        ])
249        .unwrap();
250        let bytes = x.to_gvariant().unwrap();
251        let decoded = Xattrs::from_gvariant(&bytes).unwrap();
252        assert_eq!(decoded, x);
253        assert_eq!(decoded.to_gvariant().unwrap(), bytes);
254    }
255
256    #[test]
257    fn empty_set_serializes_to_empty_array() {
258        let bytes = Xattrs::empty().to_gvariant().unwrap();
259        assert!(bytes.is_empty());
260        assert_eq!(Xattrs::from_gvariant(&bytes).unwrap(), Xattrs::empty());
261    }
262
263    #[test]
264    fn from_gvariant_rejects_unsorted_bytes() {
265        // Encode an out-of-order a(ayay) directly, bypassing canonicalization.
266        let unsorted: Vec<(&[u8], &[u8])> = vec![(b"user.z\0", b"1"), (b"user.a\0", b"2")];
267        let bytes = encode_to_vec(&Slice(&unsorted)).unwrap();
268        assert!(matches!(
269            Xattrs::from_gvariant(&bytes),
270            Err(Error::InvalidXattrs("xattr names are not strictly sorted"))
271        ));
272    }
273
274    #[test]
275    fn view_validates_as_visited_and_fuses_on_error() {
276        let unsorted: Vec<(&[u8], &[u8])> = vec![(b"user.z\0", b"1"), (b"user.a\0", b"2")];
277        let bytes = encode_to_vec(&Slice(&unsorted)).unwrap();
278        let view = XattrsRef::parse(&bytes).unwrap();
279        let mut iter = view.iter();
280        assert_eq!(iter.next().unwrap(), Ok((&b"user.z\0"[..], &b"1"[..])));
281        assert_eq!(
282            iter.next().unwrap(),
283            Err(Error::InvalidXattrs("xattr names are not strictly sorted"))
284        );
285        assert!(iter.next().is_none(), "iterator fuses after an error");
286    }
287}