Skip to main content

zenkey_model/
bundle.rs

1//! Bundles: the canonical contract with every schema artifact it lists
2//! (r3 §3.11, the r3.1 container).
3//!
4//! ```json
5//! {"contract": <canonical contract>,
6//!  "schemas": {"sha256:…": {"kind": "protobuf", "data": "<base64 FileDescriptorSet>"},
7//!              "sha256:…": {"kind": "jsonschema", "data": <JSON Schema document>},
8//!              "sha256:…": {"kind": "packed", "data": <packed document>}},
9//!  "extras": {}}
10//! ```
11//!
12//! Integrity is Merkle-style: the fingerprint is computed over the
13//! canonical contract, and the contract lists every schema's id, so
14//! verifying each schema against its id verifies the whole bundle. A bundle
15//! file is the JCS serialization of that object, so one contract revision
16//! always produces the same bytes. `extras` (`views.v1` documents, D18) are
17//! carried and hashed, never interpreted.
18
19use std::collections::{BTreeMap, BTreeSet};
20
21use base64::Engine as _;
22use serde_json::{Map, Value, json};
23use thiserror::Error;
24
25use crate::canonical::{FORMAT, Fingerprint, canonical, check_restrictions};
26use crate::contract::Contract;
27use crate::diag::Report;
28use crate::schema::{jcs, sha256_id};
29
30/// Why a bundle was refused.
31#[derive(Debug, Error)]
32pub enum BundleError {
33    #[error("not strict JSON: {0}")]
34    Json(#[from] serde_json::Error),
35    #[error("bundle shape: {0}")]
36    Shape(String),
37    #[error("the contract's format is {0:?}, not {FORMAT:?}")]
38    Format(String),
39    #[error("the canonical contract breaks the restrictions: {0}")]
40    Restrictions(String),
41    #[error("schema {0} is listed by the contract but missing from the bundle")]
42    MissingSchema(String),
43    #[error("schema {0} is in the bundle but not listed by the contract")]
44    UnlistedSchema(String),
45    #[error("schema {id}: kind {got:?} where the contract lists {want:?}")]
46    SchemaKind {
47        id: String,
48        got: String,
49        want: String,
50    },
51    #[error("schema {id}: its content hashes to {got}")]
52    SchemaHash { id: String, got: String },
53    #[error("extra {id}: its content hashes to {got}")]
54    ExtraHash { id: String, got: String },
55    #[error("the extras are not exactly the artifacts the contract references: {0}")]
56    Extras(String),
57    #[error("the bundle's fingerprint is {got}, not the expected {want}")]
58    Fingerprint { got: Fingerprint, want: Fingerprint },
59}
60
61impl BundleError {
62    /// A stable, implementation-neutral name for the refusal, as the
63    /// conformance fixtures spell it (`spec/conformance/bundles/`).
64    #[must_use]
65    pub fn tag(&self) -> &'static str {
66        match self {
67            Self::Json(_) => "json",
68            Self::Shape(_) => "shape",
69            Self::Format(_) => "format",
70            Self::Restrictions(_) => "restrictions",
71            Self::MissingSchema(_) => "missing_schema",
72            Self::UnlistedSchema(_) => "unlisted_schema",
73            Self::SchemaKind { .. } => "schema_kind",
74            Self::SchemaHash { .. } => "schema_hash",
75            Self::ExtraHash { .. } => "extra_hash",
76            Self::Extras(_) => "extras",
77            Self::Fingerprint { .. } => "fingerprint",
78        }
79    }
80}
81
82/// A bundle, in memory.
83#[derive(Debug, Clone, PartialEq)]
84pub struct Bundle {
85    /// The canonical contract.
86    pub contract: Value,
87    /// Schema artifacts by id: `{kind, data}`.
88    pub schemas: BTreeMap<String, Value>,
89    /// Extra artifacts by id (`views.v1` documents): `{media_type, data}`.
90    pub extras: BTreeMap<String, Value>,
91}
92
93impl Bundle {
94    /// Builds the bundle of a valid contract.
95    #[must_use]
96    pub fn build(c: &Contract) -> Self {
97        let schemas = c
98            .artifacts
99            .iter()
100            .map(|(id, a)| {
101                (
102                    id.clone(),
103                    json!({"kind": a.kind.as_str(), "data": a.data_value()}),
104                )
105            })
106            .collect();
107        Self {
108            contract: canonical(c),
109            schemas,
110            extras: BTreeMap::new(),
111        }
112    }
113
114    /// The fingerprint of the contract inside.
115    #[must_use]
116    pub fn fingerprint(&self) -> Fingerprint {
117        Fingerprint::of_bytes(&jcs(&self.contract))
118    }
119
120    /// The bundle's JSON value.
121    #[must_use]
122    pub fn to_value(&self) -> Value {
123        json!({
124            "contract": self.contract,
125            "schemas": Value::Object(self.schemas.clone().into_iter().collect::<Map<_, _>>()),
126            "extras": Value::Object(self.extras.clone().into_iter().collect::<Map<_, _>>()),
127        })
128    }
129
130    /// The bundle file's bytes: JCS of [`Self::to_value`].
131    #[must_use]
132    pub fn to_bytes(&self) -> Vec<u8> {
133        jcs(&self.to_value())
134    }
135
136    /// Parses and verifies a bundle file. On success the bundle is intact:
137    /// every listed schema is present and hashes to its id, and nothing
138    /// else is carried.
139    pub fn verify(bytes: &[u8]) -> Result<Self, BundleError> {
140        let text = std::str::from_utf8(bytes).map_err(|e| BundleError::Shape(e.to_string()))?;
141        let v = crate::strict::parse_json(text)?;
142        let top = v.as_object().ok_or_else(|| shape("not an object"))?;
143        for k in top.keys() {
144            if !matches!(k.as_str(), "contract" | "schemas" | "extras") {
145                return Err(shape(&format!("unknown member {k:?}")));
146            }
147        }
148        let contract = top
149            .get("contract")
150            .cloned()
151            .ok_or_else(|| shape("no `contract`"))?;
152        let format = contract.get("format").and_then(Value::as_str).unwrap_or("");
153        if format != FORMAT {
154            return Err(BundleError::Format(format.to_owned()));
155        }
156        let mut report = Report::default();
157        check_restrictions(&contract, &mut report);
158        if report.has_errors() {
159            return Err(BundleError::Restrictions(
160                report.to_string().trim().to_owned(),
161            ));
162        }
163        let obj = |k: &str| -> Result<BTreeMap<String, Value>, BundleError> {
164            match top.get(k) {
165                None => Ok(BTreeMap::new()),
166                Some(Value::Object(m)) => Ok(m.clone().into_iter().collect()),
167                Some(_) => Err(shape(&format!("`{k}` is not an object"))),
168            }
169        };
170        let schemas = obj("schemas")?;
171        let extras = obj("extras")?;
172
173        let listed = contract
174            .get("schemas")
175            .and_then(Value::as_array)
176            .ok_or_else(|| shape("the contract has no `schemas` list"))?;
177        let mut want: BTreeMap<String, String> = BTreeMap::new();
178        for s in listed {
179            let id = s
180                .get("id")
181                .and_then(Value::as_str)
182                .ok_or_else(|| shape("a schema without `id`"))?;
183            let kind = s
184                .get("kind")
185                .and_then(Value::as_str)
186                .ok_or_else(|| shape("a schema without `kind`"))?;
187            want.insert(id.to_owned(), kind.to_owned());
188        }
189        for id in schemas.keys() {
190            if !want.contains_key(id) {
191                return Err(BundleError::UnlistedSchema(id.clone()));
192            }
193        }
194        for (id, kind) in &want {
195            let entry = schemas
196                .get(id)
197                .ok_or_else(|| BundleError::MissingSchema(id.clone()))?;
198            let got_kind = entry.get("kind").and_then(Value::as_str).unwrap_or("");
199            if got_kind != kind {
200                return Err(BundleError::SchemaKind {
201                    id: id.clone(),
202                    got: got_kind.to_owned(),
203                    want: kind.clone(),
204                });
205            }
206            let data = entry
207                .get("data")
208                .ok_or_else(|| shape(&format!("schema {id} has no `data`")))?;
209            only_members(entry, &["kind", "data"], &format!("schema {id}"))?;
210            let got = match kind.as_str() {
211                "protobuf" => {
212                    let b64 = data
213                        .as_str()
214                        .ok_or_else(|| shape(&format!("schema {id}: data is not base64")))?;
215                    let bytes = base64::engine::general_purpose::STANDARD
216                        .decode(b64)
217                        .map_err(|e| shape(&format!("schema {id}: {e}")))?;
218                    sha256_id(&bytes)
219                }
220                // A packed document is hashed as a JSON Schema one (core §9.6).
221                "jsonschema" | "packed" => json_id(data),
222                other => return Err(shape(&format!("schema {id}: unknown kind {other:?}"))),
223            };
224            if &got != id {
225                return Err(BundleError::SchemaHash {
226                    id: id.clone(),
227                    got,
228                });
229            }
230        }
231        for (id, e) in &extras {
232            let data = e
233                .get("data")
234                .ok_or_else(|| shape(&format!("extra {id} has no `data`")))?;
235            only_members(e, &["media_type", "data"], &format!("extra {id}"))?;
236            if e.get("media_type").is_some_and(|m| !m.is_string()) {
237                return Err(shape(&format!("extra {id}: `media_type` is not a string")));
238            }
239            let got = json_id(data);
240            if &got != id {
241                return Err(BundleError::ExtraHash {
242                    id: id.clone(),
243                    got,
244                });
245            }
246        }
247        let referenced = referenced_extras(&contract);
248        let carried: BTreeSet<String> = extras.keys().cloned().collect();
249        if referenced != carried {
250            let missing: Vec<_> = referenced.difference(&carried).collect();
251            let unreferenced: Vec<_> = carried.difference(&referenced).collect();
252            return Err(BundleError::Extras(format!(
253                "missing {missing:?}, unreferenced {unreferenced:?}"
254            )));
255        }
256        Ok(Self {
257            contract,
258            schemas,
259            extras,
260        })
261    }
262
263    /// [`Self::verify`], then checks the fingerprint against the one the
264    /// caller expected (from a contract key or a descriptor).
265    pub fn verify_expecting(bytes: &[u8], want: &Fingerprint) -> Result<Self, BundleError> {
266        let b = Self::verify(bytes)?;
267        let got = b.fingerprint();
268        if &got != want {
269            return Err(BundleError::Fingerprint {
270                got,
271                want: want.clone(),
272            });
273        }
274        Ok(b)
275    }
276}
277
278fn shape(s: &str) -> BundleError {
279    BundleError::Shape(s.to_owned())
280}
281
282/// An entry carries no member besides `allowed`: nothing rides along
283/// unverified (spec §9.6, steps 9 and 10).
284fn only_members(entry: &Value, allowed: &[&str], what: &str) -> Result<(), BundleError> {
285    match entry.as_object() {
286        Some(m) => match m.keys().find(|k| !allowed.contains(&k.as_str())) {
287            Some(k) => Err(shape(&format!("{what}: unknown member {k:?}"))),
288            None => Ok(()),
289        },
290        None => Err(shape(&format!("{what} is not an object"))),
291    }
292}
293
294/// The id of a JSON document: the sha256 of its JCS bytes. A document
295/// holding a number outside ±(2^53−1) has no JCS bytes every implementation
296/// agrees on, so it has no id, and matches none (spec §9.6, step 9).
297fn json_id(data: &Value) -> String {
298    if crate::schema::unsafe_integer(data).is_some() {
299        return "none: a number outside ±(2^53−1)".to_owned();
300    }
301    sha256_id(&jcs(data))
302}
303
304/// The artifacts a canonical contract references as extras: every
305/// `views.document` annotation value (r3.3 D18), the only extra-carrying
306/// annotation in this version.
307fn referenced_extras(contract: &Value) -> BTreeSet<String> {
308    contract
309        .get("resources")
310        .and_then(Value::as_array)
311        .into_iter()
312        .flatten()
313        .filter_map(|r| r.get("annotations")?.get("views.document")?.as_str())
314        .map(str::to_owned)
315        .collect()
316}
317
318#[cfg(test)]
319mod tests {
320    use std::path::Path;
321
322    use super::*;
323    use crate::contract::load_str;
324
325    fn sample() -> Contract {
326        let src = r#"
327[interface]
328name = "t"
329major = 1
330minor = 0
331
332[resources."a"]
333kind = "operation"
334request = "google.protobuf.Empty"
335response = "google.protobuf.Timestamp"
336"#;
337        let l = load_str(src, Path::new("."), None);
338        l.contract.unwrap_or_else(|| panic!("{}", l.report))
339    }
340
341    #[test]
342    fn round_trip_and_tamper() {
343        let c = sample();
344        let b = Bundle::build(&c);
345        assert_eq!(b.schemas.len(), 2, "empty.proto and timestamp.proto");
346        let bytes = b.to_bytes();
347        let v = Bundle::verify_expecting(&bytes, &Fingerprint::of(&c)).unwrap();
348        assert_eq!(v, b);
349
350        let text = String::from_utf8(bytes).unwrap();
351        let tampered = text.replace("\"interactive_high\"", "\"real_time\"");
352        let err = Bundle::verify_expecting(tampered.as_bytes(), &Fingerprint::of(&c)).unwrap_err();
353        assert!(matches!(err, BundleError::Fingerprint { .. }), "{err}");
354
355        let mut v: Value = serde_json::from_str(&text).unwrap();
356        let id = b.schemas.keys().next().unwrap().clone();
357        v["schemas"][&id]["data"] = json!("AAAA");
358        let err = Bundle::verify(&jcs(&v)).unwrap_err();
359        assert!(matches!(err, BundleError::SchemaHash { .. }), "{err}");
360
361        v["schemas"].as_object_mut().unwrap().remove(&id);
362        let err = Bundle::verify(&jcs(&v)).unwrap_err();
363        assert!(matches!(err, BundleError::MissingSchema(_)), "{err}");
364
365        let dup = text.replacen("{\"contract\":", "{\"extras\":{},\"contract\":", 1);
366        assert!(matches!(
367            Bundle::verify(dup.as_bytes()),
368            Err(BundleError::Json(_))
369        ));
370    }
371
372    /// Nothing rides along unverified: an entry holds exactly its members.
373    #[test]
374    fn entries_hold_only_their_members() {
375        let b = Bundle::build(&sample());
376        let id = b.schemas.keys().next().unwrap().clone();
377        let mut v = b.to_value();
378        v["schemas"][&id]["sig"] = json!("x");
379        let err = Bundle::verify(&jcs(&v)).unwrap_err();
380        assert_eq!(err.tag(), "shape", "{err}");
381        let mut v = b.to_value();
382        v["schemas"][&id] = json!(3);
383        let err = Bundle::verify(&jcs(&v)).unwrap_err();
384        assert_eq!(err.tag(), "schema_kind", "{err}");
385    }
386}