1 //! Handling for data represented as CBOR. Cryptographic objects are encoded following COSE.
2
3 mod dice;
4 mod field_value;
5 mod publickey;
6 pub(crate) mod rkp;
7
8 use ciborium::{de::from_reader, value::Value};
9 use std::io::Read;
10
11 type CiboriumError = ciborium::de::Error<std::io::Error>;
12
13 /// Decodes the provided binary CBOR-encoded value and returns a
14 /// ciborium::Value struct wrapped in Result.
value_from_bytes(mut bytes: &[u8]) -> Result<Value, CiboriumError>15 fn value_from_bytes(mut bytes: &[u8]) -> Result<Value, CiboriumError> {
16 let value = from_reader(bytes.by_ref())?;
17 // Ciborium tries to read one Value, but doesn't care if there is trailing data. We do.
18 if !bytes.is_empty() {
19 return Err(CiboriumError::Semantic(Some(0), "unexpected trailing data".to_string()));
20 }
21 Ok(value)
22 }
23
24 #[cfg(test)]
serialize(value: Value) -> Vec<u8>25 fn serialize(value: Value) -> Vec<u8> {
26 let mut data = Vec::new();
27 ciborium::ser::into_writer(&value, &mut data).unwrap();
28 data
29 }
30
31 #[cfg(test)]
32 mod tests {
33 use super::*;
34 use anyhow::Result;
35
36 #[test]
value_from_bytes_valid_succeeds() -> Result<()>37 fn value_from_bytes_valid_succeeds() -> Result<()> {
38 let bytes = [0x82, 0x04, 0x02]; // [4, 2]
39 let val = value_from_bytes(&bytes)?;
40 let array = val.as_array().unwrap();
41 assert_eq!(array.len(), 2);
42 Ok(())
43 }
44
45 #[test]
value_from_bytes_truncated_fails()46 fn value_from_bytes_truncated_fails() {
47 let bytes = [0x82, 0x04];
48 assert!(value_from_bytes(&bytes).is_err());
49 }
50
51 #[test]
value_from_bytes_trailing_bytes_fails()52 fn value_from_bytes_trailing_bytes_fails() {
53 let bytes = [0x82, 0x04, 0x02, 0x00];
54 assert!(value_from_bytes(&bytes).is_err());
55 }
56 }
57