1use serde_json::{Map, Value};
8
9const ANNOTATION_KEYWORDS: &[&str] = &[
11 "$schema",
12 "$id",
13 "$comment",
14 "title",
15 "description",
16 "default",
17 "examples",
18 "format",
19 "readOnly",
20 "writeOnly",
21 "deprecated",
22];
23
24const SUPPORTED_KEYWORDS: &[&str] = &[
26 "type",
27 "properties",
28 "required",
29 "additionalProperties",
30 "items",
31 "enum",
32 "const",
33 "minimum",
34 "maximum",
35 "exclusiveMinimum",
36 "exclusiveMaximum",
37 "minLength",
38 "maxLength",
39 "minItems",
40 "maxItems",
41];
42
43pub fn check_supported(schema: &Value) -> Result<(), Vec<String>> {
47 let mut errors = Vec::new();
48 check_schema(schema, "", &mut errors);
49 if errors.is_empty() {
50 Ok(())
51 } else {
52 Err(errors)
53 }
54}
55
56fn check_schema(schema: &Value, pointer: &str, errors: &mut Vec<String>) {
57 let Some(object) = schema.as_object() else {
58 if !schema.is_boolean() {
59 errors.push(format!(
60 "{}: schema must be an object or boolean",
61 at(pointer)
62 ));
63 }
64 return;
65 };
66 for (keyword, value) in object {
67 if ANNOTATION_KEYWORDS.contains(&keyword.as_str()) {
68 continue;
69 }
70 if !SUPPORTED_KEYWORDS.contains(&keyword.as_str()) {
71 errors.push(format!(
72 "{}: unsupported schema keyword '{keyword}'",
73 at(pointer)
74 ));
75 continue;
76 }
77 match keyword.as_str() {
78 "properties" => match value.as_object() {
79 Some(properties) => {
80 for (name, child) in properties {
81 check_schema(
82 child,
83 &format!("{pointer}/properties/{}", escape(name)),
84 errors,
85 );
86 }
87 }
88 None => errors.push(format!("{}: properties must be an object", at(pointer))),
89 },
90 "additionalProperties" | "items" => {
91 check_schema(value, &format!("{pointer}/{keyword}"), errors);
92 }
93 "required" => {
94 if !value
95 .as_array()
96 .is_some_and(|names| names.iter().all(Value::is_string))
97 {
98 errors.push(format!(
99 "{}: required must be an array of strings",
100 at(pointer)
101 ));
102 }
103 }
104 "type" => {
105 let valid = match value {
106 Value::String(name) => is_type_name(name),
107 Value::Array(names) => names
108 .iter()
109 .all(|name| name.as_str().is_some_and(is_type_name)),
110 _ => false,
111 };
112 if !valid {
113 errors.push(format!("{}: type is not a JSON Schema type", at(pointer)));
114 }
115 }
116 "enum" if !value.is_array() => {
117 errors.push(format!("{}: enum must be an array", at(pointer)));
118 }
119 "minimum" | "maximum" | "exclusiveMinimum" | "exclusiveMaximum"
120 if !value.is_number() =>
121 {
122 errors.push(format!("{}: {keyword} must be a number", at(pointer)));
123 }
124 "minLength" | "maxLength" | "minItems" | "maxItems" if value.as_u64().is_none() => {
125 errors.push(format!(
126 "{}: {keyword} must be a non-negative integer",
127 at(pointer)
128 ));
129 }
130 _ => {}
131 }
132 }
133}
134
135fn is_type_name(name: &str) -> bool {
136 matches!(
137 name,
138 "null" | "boolean" | "object" | "array" | "number" | "integer" | "string"
139 )
140}
141
142pub fn validate(schema: &Value, value: &Value) -> Result<(), Vec<String>> {
148 let mut errors = Vec::new();
149 validate_at(schema, value, "", &mut errors);
150 if errors.is_empty() {
151 Ok(())
152 } else {
153 Err(errors)
154 }
155}
156
157fn validate_at(schema: &Value, value: &Value, pointer: &str, errors: &mut Vec<String>) {
158 let object = match schema {
159 Value::Bool(true) => return,
160 Value::Bool(false) => {
161 errors.push(format!("{}: no value is allowed here", at(pointer)));
162 return;
163 }
164 Value::Object(object) => object,
165 _ => {
166 errors.push(format!("{}: schema is not an object", at(pointer)));
167 return;
168 }
169 };
170 for keyword in object.keys() {
171 if !ANNOTATION_KEYWORDS.contains(&keyword.as_str())
172 && !SUPPORTED_KEYWORDS.contains(&keyword.as_str())
173 {
174 errors.push(format!(
175 "{}: unsupported schema keyword '{keyword}'",
176 at(pointer)
177 ));
178 }
179 }
180 if let Some(types) = object.get("type") {
181 let allowed: Vec<&str> = match types {
182 Value::String(name) => vec![name.as_str()],
183 Value::Array(names) => names.iter().filter_map(Value::as_str).collect(),
184 _ => Vec::new(),
185 };
186 if !allowed.iter().any(|name| has_type(value, name)) {
187 errors.push(format!(
188 "{}: expected {}, got {}",
189 at(pointer),
190 allowed.join(" or "),
191 type_of(value)
192 ));
193 return;
194 }
195 }
196 if let Some(expected) = object.get("const")
197 && !json_equal(expected, value)
198 {
199 errors.push(format!("{}: must equal {expected}", at(pointer)));
200 }
201 if let Some(Value::Array(options)) = object.get("enum")
202 && !options.iter().any(|option| json_equal(option, value))
203 {
204 errors.push(format!(
205 "{}: must be one of {}",
206 at(pointer),
207 Value::Array(options.clone())
208 ));
209 }
210 match value {
211 Value::Object(fields) => validate_object(object, fields, pointer, errors),
212 Value::Array(items) => {
213 if let Some(minimum) = object.get("minItems").and_then(Value::as_u64)
214 && (items.len() as u64) < minimum
215 {
216 errors.push(format!("{}: needs at least {minimum} items", at(pointer)));
217 }
218 if let Some(maximum) = object.get("maxItems").and_then(Value::as_u64)
219 && (items.len() as u64) > maximum
220 {
221 errors.push(format!("{}: allows at most {maximum} items", at(pointer)));
222 }
223 if let Some(item_schema) = object.get("items") {
224 for (index, item) in items.iter().enumerate() {
225 validate_at(item_schema, item, &format!("{pointer}/{index}"), errors);
226 }
227 }
228 }
229 Value::String(text) => {
230 let length = text.chars().count() as u64;
231 if let Some(minimum) = object.get("minLength").and_then(Value::as_u64)
232 && length < minimum
233 {
234 errors.push(format!(
235 "{}: needs at least {minimum} characters",
236 at(pointer)
237 ));
238 }
239 if let Some(maximum) = object.get("maxLength").and_then(Value::as_u64)
240 && length > maximum
241 {
242 errors.push(format!(
243 "{}: allows at most {maximum} characters",
244 at(pointer)
245 ));
246 }
247 }
248 Value::Number(_) => validate_number(object, value, pointer, errors),
249 Value::Null | Value::Bool(_) => {}
250 }
251}
252
253fn validate_object(
254 schema: &Map<String, Value>,
255 fields: &Map<String, Value>,
256 pointer: &str,
257 errors: &mut Vec<String>,
258) {
259 if let Some(Value::Array(required)) = schema.get("required") {
260 for name in required.iter().filter_map(Value::as_str) {
261 if !fields.contains_key(name) {
262 errors.push(format!(
263 "{}: missing required property '{name}'",
264 at(pointer)
265 ));
266 }
267 }
268 }
269 let properties = schema.get("properties").and_then(Value::as_object);
270 for (name, field) in fields {
271 let child = format!("{pointer}/{}", escape(name));
272 match properties.and_then(|properties| properties.get(name)) {
273 Some(property) => validate_at(property, field, &child, errors),
274 None => {
275 if let Some(additional) = schema.get("additionalProperties") {
276 if additional == &Value::Bool(false) {
277 errors.push(format!("{}: unknown property '{name}'", at(pointer)));
278 } else {
279 validate_at(additional, field, &child, errors);
280 }
281 }
282 }
283 }
284 }
285}
286
287fn validate_number(
288 schema: &Map<String, Value>,
289 value: &Value,
290 pointer: &str,
291 errors: &mut Vec<String>,
292) {
293 let checks = [
294 ("minimum", std::cmp::Ordering::Less, false, "at least"),
295 ("maximum", std::cmp::Ordering::Greater, false, "at most"),
296 (
297 "exclusiveMinimum",
298 std::cmp::Ordering::Less,
299 true,
300 "greater than",
301 ),
302 (
303 "exclusiveMaximum",
304 std::cmp::Ordering::Greater,
305 true,
306 "less than",
307 ),
308 ];
309 for (keyword, violates, exclusive, wording) in checks {
310 let Some(bound) = schema.get(keyword) else {
311 continue;
312 };
313 let Some(order) = compare_numbers(value, bound) else {
314 continue;
315 };
316 if order == violates || (exclusive && order == std::cmp::Ordering::Equal) {
317 errors.push(format!("{}: must be {wording} {bound}", at(pointer)));
318 }
319 }
320}
321
322fn compare_numbers(left: &Value, right: &Value) -> Option<std::cmp::Ordering> {
324 if let (Some(left), Some(right)) = (left.as_i64(), right.as_i64()) {
325 return Some(left.cmp(&right));
326 }
327 if let (Some(left), Some(right)) = (left.as_u64(), right.as_u64()) {
328 return Some(left.cmp(&right));
329 }
330 left.as_f64()?.partial_cmp(&right.as_f64()?)
331}
332
333fn has_type(value: &Value, name: &str) -> bool {
334 match name {
335 "null" => value.is_null(),
336 "boolean" => value.is_boolean(),
337 "object" => value.is_object(),
338 "array" => value.is_array(),
339 "string" => value.is_string(),
340 "number" => value.is_number(),
341 "integer" => {
342 value.is_i64()
343 || value.is_u64()
344 || value.as_f64().is_some_and(|number| number.fract() == 0.0)
345 }
346 _ => false,
347 }
348}
349
350fn type_of(value: &Value) -> &'static str {
351 match value {
352 Value::Null => "null",
353 Value::Bool(_) => "boolean",
354 Value::Number(_) => "number",
355 Value::String(_) => "string",
356 Value::Array(_) => "array",
357 Value::Object(_) => "object",
358 }
359}
360
361fn json_equal(left: &Value, right: &Value) -> bool {
363 match (left, right) {
364 (Value::Number(_), Value::Number(_)) => {
365 compare_numbers(left, right) == Some(std::cmp::Ordering::Equal)
366 }
367 (Value::Array(left), Value::Array(right)) => {
368 left.len() == right.len() && left.iter().zip(right).all(|(a, b)| json_equal(a, b))
369 }
370 (Value::Object(left), Value::Object(right)) => {
371 left.len() == right.len()
372 && left
373 .iter()
374 .all(|(key, a)| right.get(key).is_some_and(|b| json_equal(a, b)))
375 }
376 _ => left == right,
377 }
378}
379
380fn at(pointer: &str) -> &str {
381 if pointer.is_empty() { "input" } else { pointer }
382}
383
384fn escape(name: &str) -> String {
385 name.replace('~', "~0").replace('/', "~1")
386}
387
388#[cfg(test)]
389mod tests {
390 use super::*;
391 use serde_json::json;
392
393 fn schema() -> Value {
394 json!({
395 "type": "object",
396 "properties": {
397 "count": {"type": "integer", "minimum": 1, "maximum": 10},
398 "label": {"type": "string", "minLength": 2, "maxLength": 3},
399 "mode": {"enum": ["fast", "safe"]},
400 "tags": {"type": "array", "items": {"type": "string"}, "maxItems": 2},
401 "note": {"type": ["string", "null"]}
402 },
403 "required": ["count"],
404 "additionalProperties": false
405 })
406 }
407
408 #[test]
409 fn accepts_conforming_input() {
410 let value = json!({"count": 3, "label": "ab", "mode": "safe", "tags": ["x"], "note": null});
411 assert_eq!(validate(&schema(), &value), Ok(()));
412 }
413
414 #[test]
415 fn rejects_each_violation_independently() {
416 let cases = [
417 json!({}),
418 json!({"count": 0}),
419 json!({"count": 11}),
420 json!({"count": 1.5}),
421 json!({"count": "1"}),
422 json!({"count": 1, "label": "a"}),
423 json!({"count": 1, "label": "abcd"}),
424 json!({"count": 1, "mode": "slow"}),
425 json!({"count": 1, "tags": [1]}),
426 json!({"count": 1, "tags": ["a", "b", "c"]}),
427 json!({"count": 1, "note": 4}),
428 json!({"count": 1, "extra": true}),
429 json!([]),
430 ];
431 for case in cases {
432 assert!(validate(&schema(), &case).is_err(), "accepted {case}");
433 }
434 }
435
436 #[test]
437 fn counts_unicode_scalars_for_length() {
438 let schema = json!({"type": "string", "maxLength": 2});
439 assert_eq!(validate(&schema, &json!("😀😀")), Ok(()));
440 assert!(validate(&schema, &json!("😀😀😀")).is_err());
441 }
442
443 #[test]
444 fn compares_large_integers_exactly() {
445 let schema = json!({"type": "integer", "maximum": 9007199254740993_u64});
446 assert_eq!(validate(&schema, &json!(9007199254740993_u64)), Ok(()));
447 assert!(validate(&schema, &json!(9007199254740994_u64)).is_err());
448 }
449
450 #[test]
451 fn rejects_unsupported_keywords() {
452 let schema =
453 json!({"type": "object", "properties": {"a": {"type": "string", "pattern": "x"}}});
454 assert!(check_supported(&schema).is_err());
455 assert!(validate(&schema, &json!({"a": "y"})).is_err());
456 assert_eq!(
457 check_supported(&json!({"type": "string", "description": "d"})),
458 Ok(())
459 );
460 }
461}