chadtmiller.com/monolith
An atproto PDS
0
0
//! A reader of CBOR (`spec/webauthn/rfc8949.txt`), as far as WebAuthn's
//! attestation objects, COSE keys and extensions need: one well-formed,
//! valid item at a time (§5.3), with its length, so that a caller may say
//! what may follow it. Text is UTF-8, a map has no key twice, and an item
//! nests at most `DEPTH` deep; anything else is refused. Integers' and
//! lengths' arguments need not be in their shortest form, and lengths may
//! be indefinite, as RFC 8949 allows both.
/// A CBOR data item.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum Value {
/// An unsigned integer (major type 0).
Uint(u64),
/// A negative integer, -1 - n (major type 1), by its n.
Neg(u64),
Bytes(Vec<u8>),
Text(String),
Array(Vec<Value>),
/// A map's pairs, in the order given.
Map(Vec<(Value, Value)>),
Tag(u64, Box<Value>),
/// A simple value: `false` 20, `true` 21, `null` 22, `undefined` 23.
Simple(u8),
/// A float, by the bits of its encoding, with their width.
Float(u64, u8),
}
/// How deep an item nests, at most.
const DEPTH: usize = 16;
/// Why bytes are refused: they are no item, or one not valid.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct Malformed;
/// The item at the start of `bytes`, and how many bytes it takes.
pub(crate) fn item(bytes: &[u8]) -> Result<(Value, usize), Malformed> {
let mut r = Reader { bytes, at: 0 };
let v = r.value(0)?;
Ok((v, r.at))
}
/// `bytes`, if they are one item and nothing after it.
pub(crate) fn one(bytes: &[u8]) -> Result<Value, Malformed> {
match item(bytes)? {
(v, n) if n == bytes.len() => Ok(v),
_ => Err(Malformed),
}
}
struct Reader<'b> {
bytes: &'b [u8],
at: usize,
}
/// An item's head: its major type, and its argument, or none for an
/// indefinite length (additional information 31).
struct Head {
major: u8,
info: u8,
arg: Option<u64>,
}
impl Reader<'_> {
fn take(&mut self, n: usize) -> Result<&[u8], Malformed> {
let end = self.at.checked_add(n).ok_or(Malformed)?;
let b = self.bytes.get(self.at..end).ok_or(Malformed)?;
self.at = end;
Ok(b)
}
fn head(&mut self) -> Result<Head, Malformed> {
let first = self.take(1)?[0];
let (major, info) = (first >> 5, first & 0x1f);
let wide = |b: &[u8]| b.iter().fold(0u64, |n, &x| (n << 8) | u64::from(x));
let arg = match info {
0..=23 => Some(u64::from(info)),
24 => Some(wide(self.take(1)?)),
25 => Some(wide(self.take(2)?)),
26 => Some(wide(self.take(4)?)),
27 => Some(wide(self.take(8)?)),
28..=30 => return Err(Malformed),
_ => None,
};
Ok(Head { major, info, arg })
}
/// A length, as an index: one longer than what is left is refused.
fn len(&self, n: u64) -> Result<usize, Malformed> {
usize::try_from(n)
.ok()
.filter(|n| *n <= self.bytes.len() - self.at)
.ok_or(Malformed)
}
/// Whether the next byte is the "break" stop code, taken if it is.
fn stop(&mut self) -> Result<bool, Malformed> {
match self.bytes.get(self.at) {
Some(0xff) => {
self.at += 1;
Ok(true)
}
Some(_) => Ok(false),
None => Err(Malformed),
}
}
/// A byte or text string's bytes: definite, or indefinite, of definite
/// chunks of the same major type.
fn string(&mut self, major: u8, arg: Option<u64>) -> Result<Vec<u8>, Malformed> {
if let Some(n) = arg {
let n = self.len(n)?;
return Ok(self.take(n)?.to_vec());
}
let mut out = Vec::new();
while !self.stop()? {
let h = self.head()?;
let (true, Some(n)) = (h.major == major, h.arg) else {
return Err(Malformed);
};
let n = self.len(n)?;
let chunk = self.take(n)?;
// Each chunk of a text string is text on its own (§3.2.3).
if major == 3 && std::str::from_utf8(chunk).is_err() {
return Err(Malformed);
}
out.extend_from_slice(chunk);
}
Ok(out)
}
fn value(&mut self, depth: usize) -> Result<Value, Malformed> {
if depth > DEPTH {
return Err(Malformed);
}
let h = self.head()?;
Ok(match (h.major, h.arg) {
(0, Some(n)) => Value::Uint(n),
(1, Some(n)) => Value::Neg(n),
(2, arg) => Value::Bytes(self.string(2, arg)?),
(3, arg) => {
Value::Text(String::from_utf8(self.string(3, arg)?).map_err(|_| Malformed)?)
}
(4, arg) => {
let mut items = Vec::new();
match arg {
Some(n) => {
for _ in 0..n {
items.push(self.value(depth + 1)?);
}
}
None => {
while !self.stop()? {
items.push(self.value(depth + 1)?);
}
}
}
Value::Array(items)
}
(5, arg) => {
let mut pairs: Vec<(Value, Value)> = Vec::new();
loop {
let more = match arg {
Some(n) => (pairs.len() as u64) < n,
None => !self.stop()?,
};
if !more {
break;
}
let k = self.value(depth + 1)?;
let v = self.value(depth + 1)?;
if pairs.iter().any(|(seen, _)| *seen == k) {
return Err(Malformed);
}
pairs.push((k, v));
}
Value::Map(pairs)
}
(6, Some(tag)) => Value::Tag(tag, Box::new(self.value(depth + 1)?)),
(7, Some(n)) => match h.info {
0..=23 => Value::Simple(h.info),
// A one-byte simple value below 32 is not well-formed (§3.3).
24 if n >= 32 => Value::Simple(n as u8),
25 => Value::Float(n, 2),
26 => Value::Float(n, 4),
27 => Value::Float(n, 8),
_ => return Err(Malformed),
},
// An indefinite length where none may be, or "break" where an item is.
_ => return Err(Malformed),
})
}
}
impl Value {
/// The value of a map's key `k`, if it is a map with that key.
pub fn get(&self, k: &Value) -> Option<&Value> {
match self {
Value::Map(pairs) => pairs.iter().find(|(key, _)| key == k).map(|(_, v)| v),
_ => None,
}
}
/// Whether it is a map whose keys are exactly `keys`, in any order.
pub fn keyed_exactly(&self, keys: &[Value]) -> bool {
match self {
Value::Map(pairs) => {
pairs.len() == keys.len() && keys.iter().all(|k| pairs.iter().any(|(p, _)| p == k))
}
_ => false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn hex(s: &str) -> Vec<u8> {
::hex::decode(s).unwrap()
}
/// RFC 8949's examples (Appendix A), and what is not well-formed (Appendix F).
#[test]
fn items() {
assert_eq!(one(&hex("00")), Ok(Value::Uint(0)));
assert_eq!(one(&hex("1903e8")), Ok(Value::Uint(1000)));
assert_eq!(one(&hex("1bffffffffffffffff")), Ok(Value::Uint(u64::MAX)));
assert_eq!(one(&hex("20")), Ok(Value::Neg(0)));
assert_eq!(one(&hex("3863")), Ok(Value::Neg(99)));
assert_eq!(one(&hex("4401020304")), Ok(Value::Bytes(vec![1, 2, 3, 4])));
assert_eq!(one(&hex("62c3bc")), Ok(Value::Text("ü".into())));
assert_eq!(
one(&hex("a201020304")),
Ok(Value::Map(vec![
(Value::Uint(1), Value::Uint(2)),
(Value::Uint(3), Value::Uint(4))
]))
);
assert_eq!(
one(&hex("5f42010243030405ff")),
Ok(Value::Bytes(vec![1, 2, 3, 4, 5]))
);
assert_eq!(
one(&hex("7f657374726561646d696e67ff")),
Ok(Value::Text("streaming".into()))
);
assert_eq!(
one(&hex("bf61610161629f0203ffff")),
Ok(Value::Map(vec![
(Value::Text("a".into()), Value::Uint(1)),
(
Value::Text("b".into()),
Value::Array(vec![Value::Uint(2), Value::Uint(3)])
),
]))
);
assert_eq!(one(&hex("f4")), Ok(Value::Simple(20)));
assert_eq!(one(&hex("f8ff")), Ok(Value::Simple(255)));
assert_eq!(one(&hex("f93c00")), Ok(Value::Float(0x3c00, 2)));
assert_eq!(
one(&hex("c11a514b67b0")),
Ok(Value::Tag(1, Box::new(Value::Uint(1363896240))))
);
// An item, and what follows it.
assert_eq!(item(&hex("0001")), Ok((Value::Uint(0), 1)));
for bad in [
"",
"18",
"1c",
"1f",
"3f",
"5f01ff",
"5f4201ff",
"7f4101ff",
"8201",
"9f01",
"a10102 03",
"a2010201 03",
"a20102 0103",
"ff",
"f801",
"fc",
"62c328",
"5b00000000ffffffff",
"0001",
] {
assert_eq!(one(&hex(&bad.replace(' ', ""))), Err(Malformed), "{bad}");
}
// A map with a key twice.
assert_eq!(one(&hex("a201020103")), Err(Malformed));
// Nested past its depth.
let deep = format!("{}00", "81".repeat(DEPTH + 1));
assert_eq!(one(&hex(&deep)), Err(Malformed));
let fine = format!("{}00", "81".repeat(DEPTH));
assert!(one(&hex(&fine)).is_ok());
}
}