Skip to main content

cddl_cat/
cbor.rs

1//! This module implements validation from [`ciborium::Value`].
2//!
3//! # Examples
4//!
5//! ```
6//! use cddl_cat::validate_cbor_bytes;
7//! use serde::Serialize;
8//!
9//! #[derive(Serialize)]
10//! struct PersonStruct {
11//!     name: String,
12//!     age: u32,
13//! }
14//!
15//! let input = PersonStruct {
16//!     name: "Bob".to_string(),
17//!     age: 43,
18//! };
19//! let mut cbor_bytes = Vec::new();
20//! ciborium::into_writer(&input, &mut cbor_bytes).unwrap();
21//! let cddl_input = "person = {name: tstr, age: int}";
22//!
23//! validate_cbor_bytes("person", cddl_input, &cbor_bytes).unwrap();
24//! ```
25//!
26//! If the caller wants to reuse the parsed CDDL IVT, replace
27//! `validate_cbor_bytes(...)` with:
28//! ```
29//! # use cddl_cat::validate_cbor_bytes;
30//! use cddl_cat::{cbor::validate_cbor, context::BasicContext, flatten::flatten_from_str};
31//! # use serde::Serialize;
32//! #
33//! # #[derive(Serialize)]
34//! # struct PersonStruct {
35//! #     name: String,
36//! #     age: u32,
37//! # }
38//! #
39//! # let input = PersonStruct {
40//! #     name: "Bob".to_string(),
41//! #     age: 43,
42//! # };
43//! # let mut cbor_bytes = Vec::new();
44//! # ciborium::into_writer(&input, &mut cbor_bytes).unwrap();
45//! # let cddl_input = "person = {name: tstr, age: int}";
46//!
47//! // Parse the CDDL text and flatten it into IVT form.
48//! let flat_cddl = flatten_from_str(cddl_input).unwrap();
49//! // Create a Context object to store the IVT
50//! let ctx = BasicContext::new(flat_cddl);
51//! // Look up the Rule we want to validate.
52//! let rule_def = &ctx.rules.get("person").unwrap();
53//! // Deserialize the CBOR bytes
54//! let cbor_value = ciborium::from_reader(cbor_bytes.as_slice()).unwrap();
55//! // Perform the validation.
56//! validate_cbor(&rule_def, &cbor_value, &ctx).unwrap();
57//! ```
58
59use std::collections::BTreeMap;
60use std::convert::TryFrom;
61
62use ciborium::Value as CBOR_Value;
63
64use crate::context::{BasicContext, LookupContext};
65use crate::flatten::flatten_from_str;
66use crate::ivt::RuleDef;
67use crate::util::{ValidateError, ValidateResult};
68use crate::validate::do_validate;
69use crate::value::Value;
70
71// These conversions seem obvious and pointless, but over time they may
72// diverge.  However, CDDL and CBOR were designed to work with one another, so
73// it's not surprising that they map almost perfectly.
74
75impl TryFrom<&CBOR_Value> for Value {
76    type Error = ValidateError;
77
78    fn try_from(value: &CBOR_Value) -> Result<Self, Self::Error> {
79        let result = match value {
80            CBOR_Value::Null => Value::Null,
81            CBOR_Value::Bool(b) => Value::Bool(*b),
82            CBOR_Value::Integer(i) => Value::Integer((*i).into()),
83            CBOR_Value::Float(f) => Value::from_float(*f),
84            CBOR_Value::Bytes(b) => Value::Bytes(b.clone()),
85            CBOR_Value::Text(t) => Value::Text(t.clone()),
86            CBOR_Value::Array(a) => {
87                let array: Result<_, _> = a.iter().map(Value::try_from).collect();
88                Value::Array(array?)
89            }
90            CBOR_Value::Map(m) => {
91                type MapTree = BTreeMap<Value, Value>;
92                let map: Result<MapTree, ValidateError> = m
93                    .iter()
94                    .map(|(k, v)| {
95                        // An iterator returning a 2-tuple can be used as (key, value)
96                        // when building a new map.
97                        Ok((Value::try_from(k)?, Value::try_from(v)?))
98                    })
99                    .collect();
100                Value::Map(map?)
101            }
102            _ => {
103                // cbor::Value has a few hidden internal variants.  We should
104                // never see them, but return an error if we do.
105                return Err(ValidateError::ValueError(
106                    "can't handle hidden cbor Value".into(),
107                ));
108            }
109        };
110        Ok(result)
111    }
112}
113
114// A variant that consumes the CBOR Value.
115impl TryFrom<CBOR_Value> for Value {
116    type Error = ValidateError;
117
118    fn try_from(value: CBOR_Value) -> Result<Self, Self::Error> {
119        Value::try_from(&value)
120    }
121}
122
123/// Validate already-parsed CBOR data against an already-parsed CDDL schema.
124pub fn validate_cbor(
125    rule_def: &RuleDef,
126    value: &CBOR_Value,
127    ctx: &dyn LookupContext,
128) -> ValidateResult {
129    let value = Value::try_from(value)?;
130    do_validate(&value, rule_def, ctx)
131}
132
133/// Validate CBOR-encoded data against a specified rule in a UTF-8 CDDL schema.
134pub fn validate_cbor_bytes(name: &str, cddl: &str, cbor: &[u8]) -> ValidateResult {
135    // Parse the CDDL text and flatten it into IVT form.
136    let flat_cddl = flatten_from_str(cddl)?;
137    let ctx = BasicContext::new(flat_cddl);
138
139    // Find the rule name that was requested
140    let rule_def: &RuleDef = ctx
141        .rules
142        .get(name)
143        .ok_or_else(|| ValidateError::MissingRule(name.into()))?;
144
145    // Deserialize the CBOR bytes
146    let cbor_value: CBOR_Value =
147        ciborium::from_reader(cbor).map_err(|e| ValidateError::ValueError(format!("{}", e)))?;
148
149    // Convert the CBOR tree into a Value tree for validation
150    let value = Value::try_from(cbor_value)?;
151    do_validate(&value, rule_def, &ctx)
152}