1 // Copyright 2023, The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 //! Utility functions for CBOR serialization/deserialization.
16
17 #![cfg_attr(not(feature = "std"), no_std)]
18
19 extern crate alloc;
20
21 use alloc::string::String;
22 use alloc::vec::Vec;
23 use ciborium::value::{Integer, Value};
24 use coset::{CborSerializable, CoseError, CoseKey, Label, Result};
25 use log::error;
26 use serde::{de::DeserializeOwned, Serialize};
27
28 /// Serializes the given data to a CBOR-encoded byte vector.
serialize<T: ?Sized + Serialize>(v: &T) -> Result<Vec<u8>>29 pub fn serialize<T: ?Sized + Serialize>(v: &T) -> Result<Vec<u8>> {
30 let mut data = Vec::new();
31 ciborium::into_writer(v, &mut data)?;
32 Ok(data)
33 }
34
35 /// Deserializes the given type from a CBOR-encoded byte slice, failing if any extra
36 /// data remains after the type has been read.
deserialize<T: DeserializeOwned>(mut data: &[u8]) -> Result<T>37 pub fn deserialize<T: DeserializeOwned>(mut data: &[u8]) -> Result<T> {
38 let res = ciborium::from_reader(&mut data)?;
39 if data.is_empty() {
40 Ok(res)
41 } else {
42 Err(CoseError::ExtraneousData)
43 }
44 }
45
46 /// Parses the given CBOR-encoded byte slice as a value array.
parse_value_array(data: &[u8], context: &'static str) -> Result<Vec<Value>>47 pub fn parse_value_array(data: &[u8], context: &'static str) -> Result<Vec<Value>> {
48 value_to_array(Value::from_slice(data)?, context)
49 }
50
51 /// Converts the provided value `v` to a value array.
value_to_array(v: Value, context: &'static str) -> Result<Vec<Value>>52 pub fn value_to_array(v: Value, context: &'static str) -> Result<Vec<Value>> {
53 v.into_array().map_err(|e| to_unexpected_item_error(&e, "array", context))
54 }
55
56 /// Converts the provided value `v` to a text string.
value_to_text(v: Value, context: &'static str) -> Result<String>57 pub fn value_to_text(v: Value, context: &'static str) -> Result<String> {
58 v.into_text().map_err(|e| to_unexpected_item_error(&e, "tstr", context))
59 }
60
61 /// Converts the provided value `v` to a map.
value_to_map(v: Value, context: &'static str) -> Result<Vec<(Value, Value)>>62 pub fn value_to_map(v: Value, context: &'static str) -> Result<Vec<(Value, Value)>> {
63 v.into_map().map_err(|e| to_unexpected_item_error(&e, "map", context))
64 }
65
66 /// Converts the provided value `v` to a number.
value_to_num<T: TryFrom<Integer>>(v: Value, context: &'static str) -> Result<T>67 pub fn value_to_num<T: TryFrom<Integer>>(v: Value, context: &'static str) -> Result<T> {
68 let num = v.into_integer().map_err(|e| to_unexpected_item_error(&e, "int", context))?;
69 num.try_into().map_err(|_| {
70 error!("The provided value '{num:?}' is not a valid number: {context}");
71 CoseError::OutOfRangeIntegerValue
72 })
73 }
74
75 /// Converts the provided value `v` to a byte array of length `N`.
value_to_byte_array<const N: usize>(v: Value, context: &'static str) -> Result<[u8; N]>76 pub fn value_to_byte_array<const N: usize>(v: Value, context: &'static str) -> Result<[u8; N]> {
77 let arr = value_to_bytes(v, context)?;
78 arr.try_into().map_err(|e| {
79 error!("The provided value '{context}' is not an array of length {N}: {e:?}");
80 CoseError::UnexpectedItem("bstr", "array of length {N}")
81 })
82 }
83
84 /// Converts the provided value `v` to bytes array.
value_to_bytes(v: Value, context: &'static str) -> Result<Vec<u8>>85 pub fn value_to_bytes(v: Value, context: &'static str) -> Result<Vec<u8>> {
86 v.into_bytes().map_err(|e| to_unexpected_item_error(&e, "bstr", context))
87 }
88
89 /// Builds a `CoseError::UnexpectedItem` error when the provided value `v` is not of the expected
90 /// type `expected_type` and logs the error message with the provided `context`.
to_unexpected_item_error( v: &Value, expected_type: &'static str, context: &'static str, ) -> CoseError91 pub fn to_unexpected_item_error(
92 v: &Value,
93 expected_type: &'static str,
94 context: &'static str,
95 ) -> CoseError {
96 let v_type = cbor_value_type(v);
97 assert!(v_type != expected_type);
98 error!("The provided value type '{v_type}' is not of type '{expected_type}': {context}");
99 CoseError::UnexpectedItem(v_type, expected_type)
100 }
101
102 /// Reads the type of the provided value `v`.
cbor_value_type(v: &Value) -> &'static str103 pub fn cbor_value_type(v: &Value) -> &'static str {
104 match v {
105 Value::Integer(_) => "int",
106 Value::Bytes(_) => "bstr",
107 Value::Float(_) => "float",
108 Value::Text(_) => "tstr",
109 Value::Bool(_) => "bool",
110 Value::Null => "nul",
111 Value::Tag(_, _) => "tag",
112 Value::Array(_) => "array",
113 Value::Map(_) => "map",
114 _ => "other",
115 }
116 }
117
118 /// Returns the value of the given label in the given COSE key as bytes.
get_label_value_as_bytes(key: &CoseKey, label: Label) -> Result<&[u8]>119 pub fn get_label_value_as_bytes(key: &CoseKey, label: Label) -> Result<&[u8]> {
120 let v = get_label_value(key, label)?;
121 Ok(v.as_bytes().ok_or_else(|| {
122 to_unexpected_item_error(v, "bstr", "Get label value in CoseKey as bytes")
123 })?)
124 }
125
126 /// Returns the value of the given label in the given COSE key.
get_label_value(key: &CoseKey, label: Label) -> Result<&Value>127 pub fn get_label_value(key: &CoseKey, label: Label) -> Result<&Value> {
128 Ok(&key
129 .params
130 .iter()
131 .find(|(k, _)| k == &label)
132 .ok_or(CoseError::UnexpectedItem("", "Label not found in CoseKey"))?
133 .1)
134 }
135