Skip to main content

sail_api/
schema.rs

1//! A small JSON Schema checker for the subset sail's schemas use.
2//!
3//! Supported keywords: `type` (a name or a list of names), `const`, `enum`,
4//! `properties`, `required`, `additionalProperties: false`, `items`,
5//! `oneOf`, `minimum`, and `$ref` to `#/$defs/<name>`. Annotation keywords
6//! (`$schema`, `$id`, `title`, `description`) are ignored. Any other keyword
7//! is reported as unsupported, so a schema can never silently check less
8//! than it says.
9
10use serde_json::Value;
11
12const ANNOTATIONS: &[&str] = &["$schema", "$id", "title", "description", "$defs"];
13
14fn type_matches(name: &str, v: &Value) -> bool {
15    match name {
16        "null" => v.is_null(),
17        "boolean" => v.is_boolean(),
18        "string" => v.is_string(),
19        "integer" => v.is_i64() || v.is_u64(),
20        "number" => v.is_number(),
21        "array" => v.is_array(),
22        "object" => v.is_object(),
23        _ => false,
24    }
25}
26
27struct Checker<'a> {
28    root: &'a Value,
29    errors: Vec<String>,
30}
31
32fn resolve<'a>(root: &'a Value, reference: &str) -> Option<&'a Value> {
33    let name = reference.strip_prefix("#/$defs/")?;
34    root.get("$defs")?.get(name)
35}
36
37impl<'a> Checker<'a> {
38    fn fail(&mut self, path: &str, msg: impl std::fmt::Display) {
39        self.errors.push(format!(
40            "{}: {msg}",
41            if path.is_empty() { "$" } else { path }
42        ));
43    }
44
45    fn check(&mut self, schema: &'a Value, v: &Value, path: &str) {
46        let Some(obj) = schema.as_object() else {
47            self.fail(path, "schema is not an object");
48            return;
49        };
50        for (key, rule) in obj {
51            match key.as_str() {
52                k if ANNOTATIONS.contains(&k) => {}
53                "$ref" => match rule.as_str().and_then(|r| resolve(self.root, r)) {
54                    Some(target) => self.check(target, v, path),
55                    None => self.fail(path, format!("unresolvable $ref {rule}")),
56                },
57                "type" => {
58                    let names: Vec<&str> = match rule {
59                        Value::String(s) => vec![s.as_str()],
60                        Value::Array(a) => a.iter().filter_map(Value::as_str).collect(),
61                        _ => Vec::new(),
62                    };
63                    if !names.iter().any(|n| type_matches(n, v)) {
64                        self.fail(path, format!("expected type {rule}, got {v}"));
65                    }
66                }
67                "const" => {
68                    if rule != v {
69                        self.fail(path, format!("expected {rule}, got {v}"));
70                    }
71                }
72                "enum" => {
73                    if !rule.as_array().is_some_and(|a| a.contains(v)) {
74                        self.fail(path, format!("{v} is not one of {rule}"));
75                    }
76                }
77                "minimum" => {
78                    if let (Some(min), Some(n)) = (rule.as_f64(), v.as_f64())
79                        && n < min
80                    {
81                        self.fail(path, format!("{n} is below {min}"));
82                    }
83                }
84                "required" => {
85                    if let Some(o) = v.as_object() {
86                        for name in rule
87                            .as_array()
88                            .into_iter()
89                            .flatten()
90                            .filter_map(Value::as_str)
91                        {
92                            if !o.contains_key(name) {
93                                self.fail(path, format!("missing required field {name}"));
94                            }
95                        }
96                    }
97                }
98                "properties" => {
99                    if let (Some(props), Some(o)) = (rule.as_object(), v.as_object()) {
100                        for (name, sub) in props {
101                            if let Some(value) = o.get(name) {
102                                self.check(sub, value, &format!("{path}.{name}"));
103                            }
104                        }
105                    }
106                }
107                "additionalProperties" => {
108                    if rule == &Value::Bool(false)
109                        && let Some(o) = v.as_object()
110                    {
111                        let known = obj.get("properties").and_then(Value::as_object);
112                        for name in o.keys() {
113                            if !known.is_some_and(|k| k.contains_key(name)) {
114                                self.fail(path, format!("unexpected field {name}"));
115                            }
116                        }
117                    } else if rule != &Value::Bool(false) && rule != &Value::Bool(true) {
118                        self.fail(path, "unsupported additionalProperties schema");
119                    }
120                }
121                "items" => {
122                    if let Some(a) = v.as_array() {
123                        for (i, item) in a.iter().enumerate() {
124                            self.check(rule, item, &format!("{path}[{i}]"));
125                        }
126                    }
127                }
128                "oneOf" => self.one_of(rule, v, path),
129                other => self.fail(path, format!("unsupported schema keyword {other}")),
130            }
131        }
132    }
133
134    fn one_of(&mut self, rule: &'a Value, v: &Value, path: &str) {
135        let options = rule.as_array().map_or(&[][..], Vec::as_slice);
136        let matching = options
137            .iter()
138            .filter(|o| {
139                let mut sub = Checker {
140                    root: self.root,
141                    errors: Vec::new(),
142                };
143                sub.check(o, v, path);
144                sub.errors.is_empty()
145            })
146            .count();
147        if matching != 1 {
148            self.fail(
149                path,
150                format!("matches {matching} of the oneOf options, not 1"),
151            );
152        }
153    }
154}
155
156/// Checks `value` against `schema`. Returns every violation, with its path.
157#[must_use]
158pub fn validate(schema: &Value, value: &Value) -> Vec<String> {
159    let mut checker = Checker {
160        root: schema,
161        errors: Vec::new(),
162    };
163    checker.check(schema, value, "");
164    checker.errors
165}
166
167#[cfg(test)]
168mod tests {
169    use super::validate;
170    use serde_json::json;
171
172    #[test]
173    fn checks_the_supported_keywords() {
174        let schema = json!({
175            "type": "object",
176            "required": ["a", "b"],
177            "additionalProperties": false,
178            "properties": {
179                "a": {"type": ["integer", "null"], "minimum": 0},
180                "b": {"enum": ["x", "y"]},
181                "c": {"type": "array", "items": {"$ref": "#/$defs/d"}},
182                "e": {"oneOf": [{"type": "null"}, {"const": 1}]}
183            },
184            "$defs": {"d": {"type": "string"}}
185        });
186        assert_eq!(
187            validate(&schema, &json!({"a": 1, "b": "x", "c": ["s"], "e": 1})),
188            Vec::<String>::new()
189        );
190        assert_eq!(
191            validate(&schema, &json!({"a": null, "b": "y", "e": null})),
192            Vec::<String>::new()
193        );
194        let errors = validate(
195            &schema,
196            &json!({"a": -1, "b": "z", "c": [3], "e": 2, "f": 0}),
197        );
198        assert_eq!(errors.len(), 5, "{errors:?}");
199        assert_eq!(validate(&schema, &json!({})).len(), 2);
200        assert_eq!(validate(&json!({"format": "x"}), &json!(1)).len(), 1);
201        assert_eq!(
202            validate(&json!({"$ref": "#/$defs/missing"}), &json!(1)).len(),
203            1
204        );
205    }
206}