Skip to main content

publet_core/cbor/
decode.rs

1//! Validating decoder for the Section 4.1 profile.
2//!
3//! Validation happens during parsing rather than as a second pass, so the
4//! first violation is reported with its offset and no partially-normalized
5//! value is ever constructed.
6
7use std::collections::BTreeMap;
8
9use unicode_normalization::{UnicodeNormalization as _, is_nfc};
10
11use super::Value;
12use crate::CanonError;
13
14/// Maximum object size, from Section 4.5.
15pub const MAX_OBJECT_BYTES: usize = 1024 * 1024;
16
17/// Default nesting limit.
18///
19/// Not a protocol constant. Object schemas nest a handful of levels, so a
20/// generous ceiling still refuses the stack exhaustion that hostile input
21/// would otherwise cause.
22pub const DEFAULT_MAX_DEPTH: usize = 64;
23
24/// Decode canonical CBOR, rejecting anything outside the profile.
25///
26/// # Errors
27///
28/// Returns [`CanonError`] naming the violated rule, with the byte offset at
29/// which it was detected.
30///
31/// # Example
32///
33/// ```
34/// use publet_core::cbor::{Value, decode};
35///
36/// // {"a": 1}
37/// assert_eq!(
38///     decode(&[0xa1, 0x61, b'a', 0x01])?.get("a"),
39///     Some(&Value::Uint(1)),
40/// );
41/// # Ok::<(), publet_core::CanonError>(())
42/// ```
43///
44/// # Example: each rule names itself
45///
46/// ```
47/// use publet_core::cbor::decode;
48///
49/// let rule = |bytes: &[u8]| decode(bytes).unwrap_err().rule();
50/// assert_eq!(rule(&[0x18, 0x01]), "shortest-form integers");      // 1 in two bytes
51/// assert_eq!(rule(&[0x9f, 0x01, 0xff]), "no indefinite length");   // [_ 1]
52/// assert_eq!(rule(&[0xf9, 0x3e, 0x00]), "no floating point");      // 1.5
53/// assert_eq!(rule(&[0xa1, 0x01, 0x02]), "text map keys");          // {1: 2}
54/// assert_eq!(rule(&[0x01, 0x02]), "single top-level item");        // 1, then 2
55/// ```
56pub fn decode(input: &[u8]) -> Result<Value, CanonError> {
57    decode_with_limit(input, MAX_OBJECT_BYTES, DEFAULT_MAX_DEPTH)
58}
59
60/// Decode with explicit size and nesting limits.
61///
62/// # Errors
63///
64/// As [`decode`], and [`CanonError::TooLarge`] if `input` exceeds `max_bytes`.
65///
66/// # Example
67///
68/// ```
69/// use publet_core::CanonError;
70/// use publet_core::cbor::{DEFAULT_MAX_DEPTH, decode_with_limit};
71///
72/// // Three bytes is over a two-byte limit, whatever they hold.
73/// assert!(matches!(
74///     decode_with_limit(&[0x82, 0x01, 0x02], 2, DEFAULT_MAX_DEPTH),
75///     Err(CanonError::TooLarge { size: 3, limit: 2 }),
76/// ));
77///
78/// // [[[]]] nests deeper than one level.
79/// assert!(matches!(
80///     decode_with_limit(&[0x81, 0x81, 0x80], 1024, 1),
81///     Err(CanonError::TooDeep { .. }),
82/// ));
83/// ```
84pub fn decode_with_limit(
85    input: &[u8],
86    max_bytes: usize,
87    max_depth: usize,
88) -> Result<Value, CanonError> {
89    if input.len() > max_bytes {
90        return Err(CanonError::TooLarge {
91            size: input.len(),
92            limit: max_bytes,
93        });
94    }
95    let mut p = Parser {
96        input,
97        pos: 0,
98        max_depth,
99    };
100    let value = p.item(0)?;
101    let remaining = input.len().saturating_sub(p.pos);
102    if remaining > 0 {
103        return Err(CanonError::TrailingData { count: remaining });
104    }
105    Ok(value)
106}
107
108struct Parser<'a> {
109    input: &'a [u8],
110    pos: usize,
111    max_depth: usize,
112}
113
114/// The argument of a CBOR head, plus how many extra bytes encoded it.
115struct Head {
116    major: u8,
117    arg: u64,
118    /// Offset of the initial byte, for error reporting.
119    offset: usize,
120}
121
122impl Parser<'_> {
123    fn byte(&mut self) -> Result<u8, CanonError> {
124        let b = self
125            .input
126            .get(self.pos)
127            .copied()
128            .ok_or(CanonError::Truncated {
129                offset: self.pos,
130                needed: 1,
131            })?;
132        self.pos += 1;
133        Ok(b)
134    }
135
136    fn take(&mut self, n: usize) -> Result<&[u8], CanonError> {
137        let end = self.pos.checked_add(n).ok_or(CanonError::Truncated {
138            offset: self.pos,
139            needed: n,
140        })?;
141        let slice = self.input.get(self.pos..end).ok_or(CanonError::Truncated {
142            offset: self.pos,
143            needed: end.saturating_sub(self.input.len()),
144        })?;
145        self.pos = end;
146        Ok(slice)
147    }
148
149    /// Read a head, enforcing shortest-form argument encoding.
150    fn head(&mut self) -> Result<Head, CanonError> {
151        let offset = self.pos;
152        let initial = self.byte()?;
153        let major = initial >> 5;
154        let info = initial & 0x1f;
155
156        // Major type 7 reuses additional information 25, 26 and 27 for half,
157        // single and double precision floats. They must be reported as
158        // floats, not as non-shortest integers, so they are caught before
159        // the argument is read and the shortest-form rule is applied.
160        if major == 7 {
161            if matches!(info, 25..=27) {
162                return Err(CanonError::Float { offset });
163            }
164            if info == 31 {
165                return Err(CanonError::IndefiniteLength { offset });
166            }
167            let arg = if info == 24 {
168                // RFC 8949 Section 3.3: a simple value below 32 must use the
169                // one-byte form. Accepting `f8 16` would give null a second
170                // encoding, and the same object a second identifier.
171                let value = self.byte()?;
172                if value < 32 {
173                    return Err(CanonError::NonShortestInteger {
174                        offset,
175                        value: u64::from(value),
176                        used: 1,
177                    });
178                }
179                u64::from(value)
180            } else if info <= 23 {
181                u64::from(info)
182            } else {
183                return Err(CanonError::Unsupported {
184                    offset,
185                    detail: "reserved simple value",
186                });
187            };
188            return Ok(Head { major, arg, offset });
189        }
190
191        let (arg, extra) = match info {
192            0..=23 => (u64::from(info), 0usize),
193            24 => (u64::from(self.byte()?), 1),
194            25 => {
195                let b = self.take(2)?;
196                let mut buf = [0u8; 2];
197                buf.copy_from_slice(b);
198                (u64::from(u16::from_be_bytes(buf)), 2)
199            }
200            26 => {
201                let b = self.take(4)?;
202                let mut buf = [0u8; 4];
203                buf.copy_from_slice(b);
204                (u64::from(u32::from_be_bytes(buf)), 4)
205            }
206            27 => {
207                let b = self.take(8)?;
208                let mut buf = [0u8; 8];
209                buf.copy_from_slice(b);
210                (u64::from_be_bytes(buf), 8)
211            }
212            31 => return Err(CanonError::IndefiniteLength { offset }),
213            _ => {
214                return Err(CanonError::Unsupported {
215                    offset,
216                    detail: "reserved additional information",
217                });
218            }
219        };
220
221        // Shortest form: the argument must not fit in a smaller encoding.
222        let minimal = match arg {
223            0..=23 => 0usize,
224            24..=0xff => 1,
225            0x100..=0xffff => 2,
226            0x1_0000..=0xffff_ffff => 4,
227            _ => 8,
228        };
229        if extra != minimal {
230            return Err(CanonError::NonShortestInteger {
231                offset,
232                value: arg,
233                used: extra,
234            });
235        }
236
237        Ok(Head { major, arg, offset })
238    }
239
240    fn text_at(&mut self, head: &Head) -> Result<String, CanonError> {
241        let start = self.pos;
242        let len = usize::try_from(head.arg).map_err(|_| CanonError::Truncated {
243            offset: start,
244            needed: usize::MAX,
245        })?;
246        let raw = self.take(len)?;
247        let s = std::str::from_utf8(raw).map_err(|_| CanonError::InvalidUtf8 { offset: start })?;
248        if !is_nfc(s) {
249            return Err(CanonError::NotNfc {
250                offset: start,
251                text: s.nfc().collect(),
252            });
253        }
254        Ok(s.to_owned())
255    }
256
257    fn item(&mut self, depth: usize) -> Result<Value, CanonError> {
258        if depth > self.max_depth {
259            return Err(CanonError::TooDeep {
260                offset: self.pos,
261                limit: self.max_depth,
262            });
263        }
264        let head = self.head()?;
265        match head.major {
266            0 => Ok(Value::Uint(head.arg)),
267            1 => Ok(Value::Nint(head.arg)),
268            2 => {
269                let len = usize::try_from(head.arg).map_err(|_| CanonError::Truncated {
270                    offset: self.pos,
271                    needed: usize::MAX,
272                })?;
273                Ok(Value::Bytes(self.take(len)?.to_vec()))
274            }
275            3 => Ok(Value::Text(self.text_at(&head)?)),
276            4 => {
277                let len = usize::try_from(head.arg).map_err(|_| CanonError::Truncated {
278                    offset: self.pos,
279                    needed: usize::MAX,
280                })?;
281                let mut items = Vec::new();
282                items
283                    .try_reserve(len.min(1024))
284                    .map_err(|_| CanonError::TooLarge {
285                        size: len,
286                        limit: MAX_OBJECT_BYTES,
287                    })?;
288                for _ in 0..len {
289                    items.push(self.item(depth + 1)?);
290                }
291                Ok(Value::Array(items))
292            }
293            5 => self.map(&head, depth),
294            6 => Err(CanonError::Unsupported {
295                offset: head.offset,
296                detail: "tags are not part of the profile",
297            }),
298            7 => Self::simple(&head),
299            _ => Err(CanonError::Unsupported {
300                offset: head.offset,
301                detail: "unknown major type",
302            }),
303        }
304    }
305
306    fn map(&mut self, head: &Head, depth: usize) -> Result<Value, CanonError> {
307        let len = usize::try_from(head.arg).map_err(|_| CanonError::Truncated {
308            offset: self.pos,
309            needed: usize::MAX,
310        })?;
311        let mut out: BTreeMap<String, Value> = BTreeMap::new();
312        let mut previous: Option<String> = None;
313
314        for _ in 0..len {
315            let key_offset = self.pos;
316            let key_head = self.head()?;
317            if key_head.major != 3 {
318                return Err(CanonError::NonTextKey { offset: key_offset });
319            }
320            let key = self.text_at(&key_head)?;
321
322            // Order is checked against the preceding key rather than by
323            // sorting afterwards, so that the offset in the error points at
324            // the key that broke the ordering.
325            if let Some(prev) = &previous {
326                match key.as_bytes().cmp(prev.as_bytes()) {
327                    std::cmp::Ordering::Less => {
328                        return Err(CanonError::UnsortedKeys {
329                            offset: key_offset,
330                            previous: prev.clone(),
331                            current: key,
332                        });
333                    }
334                    std::cmp::Ordering::Equal => {
335                        return Err(CanonError::DuplicateKey {
336                            offset: key_offset,
337                            key,
338                        });
339                    }
340                    std::cmp::Ordering::Greater => {}
341                }
342            }
343
344            let value = self.item(depth + 1)?;
345            previous = Some(key.clone());
346            out.insert(key, value);
347        }
348        Ok(Value::Map(out))
349    }
350
351    fn simple(head: &Head) -> Result<Value, CanonError> {
352        match head.arg {
353            20 => Ok(Value::Bool(false)),
354            21 => Ok(Value::Bool(true)),
355            22 => Ok(Value::Null),
356            23 => Err(CanonError::Unsupported {
357                offset: head.offset,
358                detail: "undefined is not part of the profile",
359            }),
360            // Floats are rejected in `head`, before their argument is read.
361            _ => Err(CanonError::Unsupported {
362                offset: head.offset,
363                detail: "simple value outside the profile",
364            }),
365        }
366    }
367}