Skip to main content

zenkey_model/
validate.rs

1//! Checking a value against a JSON Schema type of a bundle (spec `core.md`
2//! §7.3), for tools that build a payload from JSON and were never compiled
3//! against the contract (#671).
4//!
5//! The subset is small on purpose (§7.3): `type`, `properties`,
6//! `required`, `additionalProperties`, `items`, `prefixItems`, `enum`,
7//! `const`, the numeric bounds, `minLength`/`maxLength`,
8//! `minItems`/`maxItems`, `$ref` and `oneOf`/`anyOf`, plus boolean
9//! schemas. None of them needs a regular-expression dialect, which is why
10//! the subset refuses `pattern`. This module implements those keywords as
11//! JSON Schema 2020-12 defines them, and nothing else: an annotation is
12//! ignored, and a keyword outside the subset cannot occur, because a
13//! contract that uses one does not load (E037).
14//!
15//! The core requires no owner to evaluate a schema (§5.1, "The request"),
16//! and a caller MUST NOT depend on a refusal of what the schema refuses: a
17//! writer sends only what its schema declares (§9.8). This is how a tool
18//! keeps that side of the rule before it sends.
19
20use std::collections::BTreeMap;
21
22use serde_json::Value;
23
24use crate::bundle::Bundle;
25
26/// One way a value fails its schema.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct Violation {
29    /// Where in the value, as a JSON pointer (`""` is the value itself).
30    pub at: String,
31    /// What the schema asked for there.
32    pub why: String,
33}
34
35impl std::fmt::Display for Violation {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        let at = if self.at.is_empty() { "/" } else { &self.at };
38        write!(f, "{at}: {}", self.why)
39    }
40}
41
42/// Checks `value` against the JSON Schema type `ty`, a canonical type
43/// reference of `bundle` (`{"kind": "jsonschema", "name", "schema"}`).
44/// `Err` lists every violation found, in the order met; a type that is not
45/// a JSON Schema type of the bundle, or a `$ref` that resolves to nothing,
46/// is one violation at the root.
47pub fn validate(bundle: &Bundle, ty: &Value, value: &Value) -> Result<(), Vec<Violation>> {
48    let at_root = |why: String| {
49        Err(vec![Violation {
50            at: String::new(),
51            why,
52        }])
53    };
54    if ty["kind"] != "jsonschema" {
55        return at_root(format!("{ty} is not a JSON Schema type"));
56    }
57    let docs = Docs::of(bundle);
58    let (Some(id), Some(name)) = (ty["schema"].as_str(), ty["name"].as_str()) else {
59        return at_root(format!("{ty} is not a type reference"));
60    };
61    let Some(doc) = bundle.schemas.get(id).map(|s| &s["data"]) else {
62        return at_root(format!("the bundle holds no schema {id}"));
63    };
64    let Some(schema) = doc.pointer(&format!("/$defs/{}", escape(name))) else {
65        return at_root(format!("{name} is not defined in its schema"));
66    };
67    let mut out = Vec::new();
68    Cx { docs: &docs }.check(schema, doc, value, "", &mut out, 0);
69    if out.is_empty() { Ok(()) } else { Err(out) }
70}
71
72/// Whether `value` satisfies `schema`, one schema position inside `doc`, a
73/// JSON Schema document of `bundle`: its `$ref`s resolve from `doc`, as
74/// [`resolve_ref`] says.
75///
76/// [`validate`] answers for a whole type; this answers for one position of
77/// it. A tool that builds a value asks it of each branch of a `oneOf`
78/// before it commits to one, because a value must match exactly one (#612,
79/// FJ8a's synthesis).
80#[must_use]
81pub fn satisfies<'b>(bundle: &'b Bundle, doc: &'b Value, schema: &Value, value: &Value) -> bool {
82    let docs = Docs::of(bundle);
83    let mut out = Vec::new();
84    Cx { docs: &docs }.check(schema, doc, value, "", &mut out, 0);
85    out.is_empty()
86}
87
88/// Resolves a `$ref` written in `doc`, one of `bundle`'s JSON Schema
89/// documents (§9.4): the file part names another of them by its stem (the
90/// last path segment, without `.json`), and an empty one names `doc`
91/// itself. Returns the schema it points at and the document holding it,
92/// from which that schema's own `$ref`s resolve.
93#[must_use]
94pub fn resolve_ref<'b>(
95    bundle: &'b Bundle,
96    doc: &'b Value,
97    r: &str,
98) -> Option<(&'b Value, &'b Value)> {
99    let docs = Docs::of(bundle);
100    Cx { docs: &docs }.resolve(r, doc)
101}
102
103/// The bundle's JSON Schema documents by artifact name, the stem a `$ref`'s
104/// file part names (§9.4).
105struct Docs<'b>(BTreeMap<&'b str, &'b Value>);
106
107impl<'b> Docs<'b> {
108    fn of(bundle: &'b Bundle) -> Self {
109        let names: BTreeMap<&str, &str> = bundle.contract["schemas"]
110            .as_array()
111            .into_iter()
112            .flatten()
113            .filter_map(|s| Some((s["id"].as_str()?, s["name"].as_str()?)))
114            .collect();
115        Self(
116            bundle
117                .schemas
118                .iter()
119                .filter(|(_, s)| s["kind"] == "jsonschema")
120                .filter_map(|(id, s)| Some((*names.get(id.as_str())?, &s["data"])))
121                .collect(),
122        )
123    }
124}
125
126struct Cx<'d, 'b> {
127    docs: &'d Docs<'b>,
128}
129
130/// How deep `$ref`s may nest while checking one value: a recursive type
131/// recurses with the value, so this bounds only a `$ref` cycle that
132/// consumes nothing (`{"$ref": "#"}`).
133const MAX_DEPTH: usize = 256;
134
135impl<'b> Cx<'_, 'b> {
136    #[allow(clippy::too_many_lines)]
137    fn check(
138        &self,
139        schema: &Value,
140        doc: &'b Value,
141        v: &Value,
142        at: &str,
143        out: &mut Vec<Violation>,
144        depth: usize,
145    ) {
146        let mut fail = |why: String| {
147            out.push(Violation {
148                at: at.to_owned(),
149                why,
150            });
151        };
152        match schema {
153            Value::Bool(true) => return,
154            Value::Bool(false) => return fail("no value is allowed here".to_owned()),
155            Value::Object(_) => {}
156            _ => return fail("the schema is not a schema".to_owned()),
157        }
158        if depth > MAX_DEPTH {
159            return fail("`$ref`s nest too deep".to_owned());
160        }
161        // `$ref` applies beside its siblings (2020-12).
162        if let Some(r) = schema.get("$ref").and_then(Value::as_str) {
163            match self.resolve(r, doc) {
164                Some((target, tdoc)) => self.check(target, tdoc, v, at, out, depth + 1),
165                None => {
166                    return out.push(Violation {
167                        at: at.to_owned(),
168                        why: format!("`$ref` {r:?} resolves to nothing"),
169                    });
170                }
171            }
172        }
173        let mut fail = |why: String| {
174            out.push(Violation {
175                at: at.to_owned(),
176                why,
177            });
178        };
179        if let Some(t) = schema.get("type") {
180            let names: Vec<&str> = match t {
181                Value::String(s) => vec![s.as_str()],
182                Value::Array(a) => a.iter().filter_map(Value::as_str).collect(),
183                _ => Vec::new(),
184            };
185            if !names.iter().any(|n| is_type(v, n)) {
186                fail(format!(
187                    "expected {}, found {}",
188                    names.join(" or "),
189                    type_name(v)
190                ));
191            }
192        }
193        if let Some(e) = schema.get("enum").and_then(Value::as_array)
194            && !e.iter().any(|x| same(x, v))
195        {
196            fail(format!("{v} is not one of {}", Value::Array(e.clone())));
197        }
198        if let Some(c) = schema.get("const")
199            && !same(c, v)
200        {
201            fail(format!("expected {c}, found {v}"));
202        }
203        if let Some(n) = v.as_f64().filter(|_| v.is_number()) {
204            let bound = |k: &str| schema.get(k).and_then(Value::as_f64);
205            if let Some(m) = bound("minimum")
206                && n < m
207            {
208                fail(format!("{v} is below the minimum {m}"));
209            }
210            if let Some(m) = bound("maximum")
211                && n > m
212            {
213                fail(format!("{v} is above the maximum {m}"));
214            }
215            if let Some(m) = bound("exclusiveMinimum")
216                && n <= m
217            {
218                fail(format!("{v} is not above {m}"));
219            }
220            if let Some(m) = bound("exclusiveMaximum")
221                && n >= m
222            {
223                fail(format!("{v} is not below {m}"));
224            }
225        }
226        let count = |k: &str| schema.get(k).and_then(Value::as_u64);
227        if let Value::String(s) = v {
228            // Lengths count code points, as JSON Schema does.
229            let n = s.chars().count() as u64;
230            if let Some(m) = count("minLength")
231                && n < m
232            {
233                fail(format!("{n} characters, fewer than {m}"));
234            }
235            if let Some(m) = count("maxLength")
236                && n > m
237            {
238                fail(format!("{n} characters, more than {m}"));
239            }
240        }
241        if let Value::Array(items) = v {
242            let n = items.len() as u64;
243            if let Some(m) = count("minItems")
244                && n < m
245            {
246                fail(format!("{n} items, fewer than {m}"));
247            }
248            if let Some(m) = count("maxItems")
249                && n > m
250            {
251                fail(format!("{n} items, more than {m}"));
252            }
253            let prefix = schema
254                .get("prefixItems")
255                .and_then(Value::as_array)
256                .map_or(&[][..], Vec::as_slice);
257            for (i, x) in items.iter().enumerate() {
258                let sub = prefix.get(i).or_else(|| schema.get("items"));
259                if let Some(sub) = sub {
260                    self.check(sub, doc, x, &format!("{at}/{i}"), out, depth);
261                }
262            }
263        }
264        if let Value::Object(m) = v {
265            let props = schema.get("properties").and_then(Value::as_object);
266            for r in schema
267                .get("required")
268                .and_then(Value::as_array)
269                .into_iter()
270                .flatten()
271                .filter_map(Value::as_str)
272            {
273                if !m.contains_key(r) {
274                    out.push(Violation {
275                        at: at.to_owned(),
276                        why: format!("the required property {r:?} is missing"),
277                    });
278                }
279            }
280            for (k, x) in m {
281                let at = format!("{at}/{}", escape(k));
282                match props.and_then(|p| p.get(k)) {
283                    Some(sub) => self.check(sub, doc, x, &at, out, depth),
284                    None => {
285                        if let Some(extra) = schema.get("additionalProperties") {
286                            self.check(extra, doc, x, &at, out, depth);
287                        }
288                    }
289                }
290            }
291        }
292        for (k, exactly_one) in [("oneOf", true), ("anyOf", false)] {
293            let Some(branches) = schema.get(k).and_then(Value::as_array) else {
294                continue;
295            };
296            let passing = branches
297                .iter()
298                .filter(|b| {
299                    let mut scratch = Vec::new();
300                    self.check(b, doc, v, at, &mut scratch, depth + 1);
301                    scratch.is_empty()
302                })
303                .count();
304            let ok = if exactly_one {
305                passing == 1
306            } else {
307                passing >= 1
308            };
309            if !ok {
310                out.push(Violation {
311                    at: at.to_owned(),
312                    why: format!(
313                        "`{k}`: {passing} of {} branches match, {}",
314                        branches.len(),
315                        if exactly_one {
316                            "one must"
317                        } else {
318                            "at least one must"
319                        }
320                    ),
321                });
322            }
323        }
324    }
325
326    /// Resolves a `$ref` from `doc`: the file part names an artifact by its
327    /// stem (§9.4: in a bundle, the last path segment, without `.json`),
328    /// and an empty one names `doc` itself.
329    fn resolve(&self, r: &str, doc: &'b Value) -> Option<(&'b Value, &'b Value)> {
330        let (file, ptr) = r.split_once('#').unwrap_or((r, ""));
331        let doc = if file.is_empty() {
332            doc
333        } else {
334            let base = file.rsplit('/').next().unwrap_or(file);
335            let stem = base.strip_suffix(".json").unwrap_or(base);
336            self.docs.0.get(stem).copied()?
337        };
338        Some((doc.pointer(ptr)?, doc))
339    }
340}
341
342/// Whether `v` is of the JSON Schema type `name`. An integer is any number
343/// with no fractional part, `1.0` included (2020-12).
344fn is_type(v: &Value, name: &str) -> bool {
345    match name {
346        "null" => v.is_null(),
347        "boolean" => v.is_boolean(),
348        "object" => v.is_object(),
349        "array" => v.is_array(),
350        "string" => v.is_string(),
351        "number" => v.is_number(),
352        "integer" => {
353            v.is_i64()
354                || v.is_u64()
355                || v.as_f64()
356                    .is_some_and(|f| f.is_finite() && f.fract() == 0.0)
357        }
358        _ => false,
359    }
360}
361
362fn type_name(v: &Value) -> &'static str {
363    match v {
364        Value::Null => "null",
365        Value::Bool(_) => "boolean",
366        Value::Number(n) if n.is_f64() => "number",
367        Value::Number(_) => "integer",
368        Value::String(_) => "string",
369        Value::Array(_) => "array",
370        Value::Object(_) => "object",
371    }
372}
373
374/// JSON Schema equality: numbers by value (`1` is `1.0`), everything else
375/// structurally.
376fn same(a: &Value, b: &Value) -> bool {
377    match (a, b) {
378        (Value::Number(x), Value::Number(y)) => match (x.as_i64(), y.as_i64()) {
379            (Some(i), Some(j)) => i == j,
380            _ => match (x.as_u64(), y.as_u64()) {
381                (Some(i), Some(j)) => i == j,
382                _ => x.as_f64() == y.as_f64(),
383            },
384        },
385        (Value::Array(x), Value::Array(y)) => {
386            x.len() == y.len() && x.iter().zip(y).all(|(a, b)| same(a, b))
387        }
388        (Value::Object(x), Value::Object(y)) => {
389            x.len() == y.len() && x.iter().all(|(k, a)| y.get(k).is_some_and(|b| same(a, b)))
390        }
391        _ => a == b,
392    }
393}
394
395/// A JSON pointer token (RFC 6901).
396fn escape(s: &str) -> String {
397    s.replace('~', "~0").replace('/', "~1")
398}
399
400#[cfg(test)]
401mod tests {
402    use serde_json::json;
403
404    use super::validate;
405    use crate::bundle::Bundle;
406
407    fn bundle(toml: &str, files: &[(&str, &str)]) -> Bundle {
408        // A directory per call: tests building the same contract run at
409        // once, and one truncating a file another reads made it read empty.
410        use std::sync::atomic::{AtomicU64, Ordering};
411        static NTH: AtomicU64 = AtomicU64::new(0);
412        let dir = std::env::temp_dir().join(format!(
413            "zk2-validate-{}-{}-{}",
414            std::process::id(),
415            toml.len(),
416            NTH.fetch_add(1, Ordering::Relaxed)
417        ));
418        std::fs::create_dir_all(&dir).unwrap();
419        for (name, text) in files {
420            std::fs::write(dir.join(name), text).unwrap();
421        }
422        let l = crate::contract::load_str(toml, &dir, None);
423        Bundle::build(&l.contract.unwrap_or_else(|| panic!("{}", l.report)))
424    }
425
426    fn status() -> Bundle {
427        bundle(
428            "[interface]\nname = \"m\"\nmajor = 1\nminor = 0\n\
429             [schemas]\njsonschema = [\"s.json\", \"common.json\"]\n\
430             [resources.status]\nkind = \"state\"\ntype = \"json:Status\"\n",
431            &[
432                (
433                    "s.json",
434                    r#"{"$defs": {"Status": {
435                        "type": "object",
436                        "properties": {
437                            "state": {"type": "string", "enum": ["up", "down"]},
438                            "since_ms": {"type": "integer", "minimum": 0},
439                            "label": {"type": "string", "maxLength": 3},
440                            "link": {"$ref": "common.json#/$defs/Link"},
441                            "hops": {"type": "array", "prefixItems": [{"type": "string"}],
442                                     "items": {"type": "integer"}, "maxItems": 3},
443                            "retries": {"anyOf": [{"type": "integer"}, {"type": "null"}]},
444                            "event": {"oneOf": [
445                                {"type": "object", "properties": {"up": {"const": true}}, "required": ["up"]},
446                                {"type": "object", "properties": {"down": {"const": true}}, "required": ["down"]}
447                            ]}
448                        },
449                        "required": ["state"],
450                        "additionalProperties": false
451                    }}}"#,
452                ),
453                (
454                    "common.json",
455                    r#"{"$defs": {"Link": {"type": "object",
456                        "properties": {"mbps": {"type": "number", "exclusiveMinimum": 0}},
457                        "required": ["mbps"]}}}"#,
458                ),
459            ],
460        )
461    }
462
463    fn check(b: &Bundle, v: serde_json::Value) -> Result<(), Vec<String>> {
464        let ty = crate::decode::type_of(b, "state", "status", "type").unwrap();
465        validate(b, ty, &v).map_err(|e| e.iter().map(ToString::to_string).collect())
466    }
467
468    #[test]
469    fn a_value_its_schema_declares_passes() {
470        let b = status();
471        let ok = json!({
472            "state": "up", "since_ms": 5.0, "label": "été", "link": {"mbps": 0.5},
473            "hops": ["a", 1, 2], "retries": null, "event": {"up": true}
474        });
475        assert_eq!(check(&b, ok), Ok(()));
476        assert_eq!(check(&b, json!({"state": "down"})), Ok(()));
477    }
478
479    #[test]
480    fn each_keyword_of_the_subset_refuses_what_it_refuses() {
481        let b = status();
482        let cases = [
483            (json!({}), "/: the required property \"state\" is missing"),
484            (
485                json!({"state": "sideways"}),
486                "/state: \"sideways\" is not one of",
487            ),
488            (
489                json!({"state": 1}),
490                "/state: expected string, found integer",
491            ),
492            (
493                json!({"state": "up", "since_ms": -1}),
494                "/since_ms: -1 is below the minimum 0",
495            ),
496            (
497                json!({"state": "up", "since_ms": 1.5}),
498                "/since_ms: expected integer, found number",
499            ),
500            (
501                json!({"state": "up", "label": "abcd"}),
502                "/label: 4 characters, more than 3",
503            ),
504            (
505                json!({"state": "up", "link": {}}),
506                "/link: the required property \"mbps\" is missing",
507            ),
508            (
509                json!({"state": "up", "link": {"mbps": 0}}),
510                "/link/mbps: 0 is not above 0",
511            ),
512            (
513                json!({"state": "up", "hops": [1]}),
514                "/hops/0: expected string, found integer",
515            ),
516            (
517                json!({"state": "up", "hops": ["a", "b"]}),
518                "/hops/1: expected integer, found string",
519            ),
520            (
521                json!({"state": "up", "hops": ["a", 1, 2, 3]}),
522                "/hops: 4 items, more than 3",
523            ),
524            (
525                json!({"state": "up", "retries": "x"}),
526                "/retries: `anyOf`: 0 of 2 branches match",
527            ),
528            (
529                json!({"state": "up", "event": {}}),
530                "/event: `oneOf`: 0 of 2 branches match",
531            ),
532            (
533                json!({"state": "up", "event": {"up": true, "down": true}}),
534                "/event: `oneOf`: 2 of 2",
535            ),
536            (
537                json!({"state": "up", "extra": 1}),
538                "/extra: no value is allowed here",
539            ),
540        ];
541        for (v, want) in cases {
542            let got = check(&b, v.clone()).expect_err(&v.to_string());
543            assert!(
544                got.iter().any(|g| g.starts_with(want)),
545                "{v}: {got:?}, want {want:?}"
546            );
547        }
548    }
549
550    /// One schema position at a time: each `oneOf` branch of `event` is
551    /// asked alone, and a `$ref` into another listed file resolves from the
552    /// document it is written in.
553    #[test]
554    fn one_position_is_asked_alone_and_refs_resolve_by_stem() {
555        let b = status();
556        let ty = crate::decode::type_of(&b, "state", "status", "type").unwrap();
557        let doc = &b.schemas[ty["schema"].as_str().unwrap()]["data"];
558        let (status, sdoc) = super::resolve_ref(&b, doc, "#/$defs/Status").expect("local");
559        let branches = status["properties"]["event"]["oneOf"].as_array().unwrap();
560        let up = json!({"up": true});
561        assert!(super::satisfies(&b, sdoc, &branches[0], &up));
562        assert!(!super::satisfies(&b, sdoc, &branches[1], &up));
563        let (link, ldoc) =
564            super::resolve_ref(&b, sdoc, "common.json#/$defs/Link").expect("by stem");
565        assert!(super::satisfies(&b, ldoc, link, &json!({"mbps": 1})));
566        assert!(!super::satisfies(&b, ldoc, link, &json!({})));
567        assert!(super::resolve_ref(&b, sdoc, "nowhere.json#/$defs/Link").is_none());
568    }
569
570    #[test]
571    fn a_type_that_is_not_json_schema_is_one_violation() {
572        let b = status();
573        let raw = json!({"kind": "raw", "media_type": "text/plain"});
574        let err = validate(&b, &raw, &json!("x")).unwrap_err();
575        assert_eq!(err.len(), 1);
576        assert_eq!(err[0].at, "");
577    }
578}