blob: 4d308c1b0a8236c87b6a4e557019f5f830889180 [file] [log] [blame]
Alice Wangfacc2b82023-10-05 14:05:47 +00001// 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
Alice Wang5dddeea2023-10-13 12:56:22 +000017#![cfg_attr(not(feature = "std"), no_std)]
18
19extern crate alloc;
20
Alice Wangdd29c5d2023-12-07 09:56:23 +000021use alloc::string::String;
Alice Wangfacc2b82023-10-05 14:05:47 +000022use alloc::vec::Vec;
Alice Wangdd29c5d2023-12-07 09:56:23 +000023use ciborium::value::{Integer, Value};
Alice Wang5fb76c52024-01-05 13:16:13 +000024use coset::{CborSerializable, CoseError, CoseKey, Label, Result};
Alice Wangdd29c5d2023-12-07 09:56:23 +000025use log::error;
Alice Wangfacc2b82023-10-05 14:05:47 +000026use serde::{de::DeserializeOwned, Serialize};
27
28/// Serializes the given data to a CBOR-encoded byte vector.
Alice Wang5dddeea2023-10-13 12:56:22 +000029pub fn serialize<T: ?Sized + Serialize>(v: &T) -> Result<Vec<u8>> {
Alice Wangfacc2b82023-10-05 14:05:47 +000030 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.
Alice Wang5dddeea2023-10-13 12:56:22 +000037pub fn deserialize<T: DeserializeOwned>(mut data: &[u8]) -> Result<T> {
Alice Wangfacc2b82023-10-05 14:05:47 +000038 let res = ciborium::from_reader(&mut data)?;
39 if data.is_empty() {
40 Ok(res)
41 } else {
42 Err(CoseError::ExtraneousData)
43 }
44}
Alice Wangdd29c5d2023-12-07 09:56:23 +000045
Alice Wang5fb76c52024-01-05 13:16:13 +000046/// Parses the given CBOR-encoded byte slice as a value array.
47pub fn parse_value_array(data: &[u8], context: &'static str) -> Result<Vec<Value>> {
48 value_to_array(Value::from_slice(data)?, context)
49}
50
Alice Wangdd29c5d2023-12-07 09:56:23 +000051/// Converts the provided value `v` to a value array.
52pub 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.
57pub 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.
62pub 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.
67pub 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`.
76pub 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.
85pub 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`.
91pub 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`.
103pub 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.
119pub 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.
127pub 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}