Debian Codegraph @

src/validator.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 //! Building a JSON Schema validator.
2 //! The main idea is to create a tree from the input JSON Schema. This tree will contain
3 //! everything needed to perform such validation in runtime.
4 use crate::{
5 error::{error, no_error, ErrorIterator},
6 evaluation::{Annotations, ErrorDescription, Evaluation, EvaluationNode},
7 node::SchemaNode,
8 paths::LazyLocation,
9 thread::ThreadBound,
10 Draft, ValidationError, ValidationOptions,
11 };
12 use serde_json::Value;
13
14 /// Tracks `(node_id, instance_ptr)` pairs to detect cycles in circular `$ref` chains.
15 #[derive(Default)]
16 pub(crate) struct ValidationContext {
17 validating: Vec<(usize, usize)>,
18 }
19
20 impl ValidationContext {
21 pub(crate) fn new() -> Self {
22 Self::default()
23 }
24
25 /// Returns `true` if cycle detected, `false` otherwise (and adds pair to stack).
26 #[inline]
27 pub(crate) fn enter(&mut self, node_id: usize, instance: &Value) -> bool {
28 let key = (node_id, std::ptr::from_ref::<Value>(instance) as usize);
29 if self.validating.contains(&key) {
30 return true;
31 }
32 self.validating.push(key);
33 false
34 }
35
36 #[inline]
37 pub(crate) fn exit(&mut self, node_id: usize, instance: &Value) {
38 let popped = self.validating.pop();
39 debug_assert_eq!(
40 popped,
41 Some((node_id, std::ptr::from_ref::<Value>(instance) as usize)),
42 "ValidationContext::exit called out of order"
43 );
44 }
45 }
46
47 /// The Validate trait represents a predicate over some JSON value. Some validators are very simple
48 /// predicates such as "a value which is a string", whereas others may be much more complex,
49 /// consisting of several other validators composed together in various ways.
50 ///
51 /// Much of the time all an application cares about is whether the predicate returns true or false,
52 /// in that case the `is_valid` function is sufficient. Sometimes applications will want more
53 /// detail about why a schema has failed, in which case the `validate` method can be used to
54 /// iterate over the errors produced by this validator. Finally, applications may be interested in
55 /// annotations produced by schemas over valid results, in this case the `evaluate` method can be used
56 /// to obtain this information.
57 ///
58 /// If you are implementing `Validate` it is often sufficient to implement `validate` and
59 /// `is_valid`. `evaluate` is only necessary for validators which compose other validators. See the
60 /// documentation for `evaluate` for more information.
61 ///
62 /// All methods accept a `ValidationContext` parameter for cycle detection in circular `$ref`
63 /// chains. Simple validators that don't recurse into child schemas can ignore this parameter.
64 pub(crate) trait Validate: ThreadBound {
65 fn iter_errors<'i>(
66 &self,
67 instance: &'i Value,
68 location: &LazyLocation,
69 ctx: &mut ValidationContext,
70 ) -> ErrorIterator<'i> {
71 match self.validate(instance, location, ctx) {
72 Ok(()) => no_error(),
73 Err(err) => error(err),
74 }
75 }
76
77 fn is_valid(&self, instance: &Value, ctx: &mut ValidationContext) -> bool;
78
79 fn validate<'i>(
80 &self,
81 instance: &'i Value,
82 location: &LazyLocation,
83 ctx: &mut ValidationContext,
84 ) -> Result<(), ValidationError<'i>>;
85
86 fn evaluate(
87 &self,
88 instance: &Value,
89 location: &LazyLocation,
90 ctx: &mut ValidationContext,
91 ) -> EvaluationResult {
92 let errors: Vec<ErrorDescription> = self
93 .iter_errors(instance, location, ctx)
94 .map(|e| ErrorDescription::from_validation_error(&e))
95 .collect();
96 if errors.is_empty() {
97 EvaluationResult::valid_empty()
98 } else {
99 EvaluationResult::invalid_empty(errors)
100 }
101 }
102 }
103
104 /// The result of evaluating a validator against an instance. This is a "partial" result because it does not include information about
105 /// where the error or annotation occurred.
106 #[derive(PartialEq)]
107 pub(crate) enum EvaluationResult {
108 Valid {
109 /// Annotations produced by this validator
110 annotations: Option<Annotations>,
111 /// Children evaluation nodes
112 children: Vec<EvaluationNode>,
113 },
114 Invalid {
115 /// Errors which caused this schema to be invalid
116 errors: Vec<ErrorDescription>,
117 /// Children evaluation nodes
118 children: Vec<EvaluationNode>,
119 /// Potential annotations that should be reported as dropped on failure
120 annotations: Option<Annotations>,
121 },
122 }
123
124 impl EvaluationResult {
125 /// Create an empty `EvaluationResult` which is valid
126 pub(crate) fn valid_empty() -> EvaluationResult {
127 EvaluationResult::Valid {
128 annotations: None,
129 children: Vec::new(),
130 }
131 }
132
133 /// Create an empty `EvaluationResult` which is invalid
134 pub(crate) fn invalid_empty(errors: Vec<ErrorDescription>) -> EvaluationResult {
135 EvaluationResult::Invalid {
136 errors,
137 children: Vec::new(),
138 annotations: None,
139 }
140 }
141
142 /// Set the annotation that will be returned for the current validator. If this
143 /// `EvaluationResult` is invalid then this method does nothing
144 pub(crate) fn annotate(&mut self, new_annotations: Annotations) {
145 match self {
146 Self::Valid { annotations, .. } | Self::Invalid { annotations, .. } => {
147 *annotations = Some(new_annotations);
148 }
149 }
150 }
151
152 /// Set the error that will be returned for the current validator. If this
153 /// `EvaluationResult` is valid then this method converts this application into
154 /// `EvaluationResult::Invalid`
155 pub(crate) fn mark_errored(&mut self, error: ErrorDescription) {
156 match self {
157 Self::Invalid { errors, .. } => errors.push(error),
158 Self::Valid {
159 annotations,
160 children,
161 } => {
162 *self = Self::Invalid {
163 errors: vec![error],
164 children: std::mem::take(children),
165 annotations: annotations.take(),
166 }
167 }
168 }
169 }
170
171 pub(crate) fn from_children(children: Vec<EvaluationNode>) -> EvaluationResult {
172 if children.iter().any(|node| !node.valid) {
173 EvaluationResult::Invalid {
174 errors: Vec::new(),
175 children,
176 annotations: None,
177 }
178 } else {
179 EvaluationResult::Valid {
180 annotations: None,
181 children,
182 }
183 }
184 }
185 }
186
187 impl From<EvaluationNode> for EvaluationResult {
188 fn from(node: EvaluationNode) -> Self {
189 if node.valid {
190 EvaluationResult::Valid {
191 annotations: None,
192 children: vec![node],
193 }
194 } else {
195 EvaluationResult::Invalid {
196 errors: Vec::new(),
197 children: vec![node],
198 annotations: None,
199 }
200 }
201 }
202 }
203
204 /// A compiled JSON Schema validator.
205 ///
206 /// This structure represents a JSON Schema that has been parsed and compiled into
207 /// an efficient internal representation for validation. It contains the root node
208 /// of the schema tree and the configuration options used during compilation.
209 #[derive(Clone, Debug)]
210 pub struct Validator {
211 pub(crate) root: SchemaNode,
212 pub(crate) draft: Draft,
213 }
214
215 impl Validator {
216 /// Create a default [`ValidationOptions`] for configuring JSON Schema validation.
217 ///
218 /// Use this to set the draft version and other validation parameters.
219 ///
220 /// # Example
221 ///
222 /// ```rust
223 /// # use jsonschema::Draft;
224 /// # let schema = serde_json::json!({});
225 /// let validator = jsonschema::options()
226 /// .with_draft(Draft::Draft7)
227 /// .build(&schema);
228 /// ```
229 #[must_use]
230 pub fn options() -> ValidationOptions {
231 ValidationOptions::default()
232 }
233 /// Create a default [`ValidationOptions`] configured for async validation.
234 ///
235 /// Use this to set the draft version and other validation parameters when working
236 /// with schemas that require async reference resolution.
237 ///
238 /// # Example
239 ///
240 /// ```rust
241 /// # use serde_json::json;
242 /// # use jsonschema::Draft;
243 /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
244 /// let schema = json!({
245 /// "$ref": "https://example.com/schema.json"
246 /// });
247 ///
248 /// let validator = jsonschema::async_options()
249 /// .with_draft(Draft::Draft202012)
250 /// .build(&schema)
251 /// .await?;
252 /// # Ok(())
253 /// # }
254 /// ```
255 ///
256 /// For sync validation, use [`options()`](crate::options()) instead.
257 #[cfg(feature = "resolve-async")]
258 #[must_use]
259 pub fn async_options() -> ValidationOptions<std::sync::Arc<dyn referencing::AsyncRetrieve>> {
260 ValidationOptions::default()
261 }
262 /// Create a validator using the default options.
263 ///
264 /// # Errors
265 ///
266 /// Returns an error if the supplied `schema` is invalid for the selected draft or references cannot be resolved.
267 pub fn new(schema: &Value) -> Result<Validator, ValidationError<'static>> {
268 Self::options().build(schema)
269 }
270 /// Create a validator using the default async options.
271 #[cfg(feature = "resolve-async")]
272 ///
273 /// # Errors
274 ///
275 /// Returns an error if the supplied `schema` is invalid for the selected draft or references cannot be resolved.
276 pub async fn async_new(schema: &Value) -> Result<Validator, ValidationError<'static>> {
277 Self::async_options().build(schema).await
278 }
279 /// Validate `instance` against `schema` and return the first error if any.
280 ///
281 /// # Errors
282 ///
283 /// Returns the first [`ValidationError`] describing why `instance` does not satisfy the schema.
284 #[inline]
285 pub fn validate<'i>(&self, instance: &'i Value) -> Result<(), ValidationError<'i>> {
286 let mut ctx = ValidationContext::new();
287 self.root.validate(instance, &LazyLocation::new(), &mut ctx)
288 }
289 /// Run validation against `instance` and return an iterator over [`ValidationError`] in the error case.
290 #[inline]
291 #[must_use]
292 pub fn iter_errors<'i>(&'i self, instance: &'i Value) -> ErrorIterator<'i> {
293 let mut ctx = ValidationContext::new();
294 self.root
295 .iter_errors(instance, &LazyLocation::new(), &mut ctx)
296 }
297 /// Run validation against `instance` but return a boolean result instead of an iterator.
298 /// It is useful for cases, where it is important to only know the fact if the data is valid or not.
299 /// This approach is much faster, than [`Validator::validate`].
300 #[must_use]
301 #[inline]
302 pub fn is_valid(&self, instance: &Value) -> bool {
303 let mut ctx = ValidationContext::new();
304 self.root.is_valid(instance, &mut ctx)
305 }
306 /// Evaluate the schema and expose structured output formats.
307 #[must_use]
308 #[inline]
309 pub fn evaluate(&self, instance: &Value) -> Evaluation {
310 let mut ctx = ValidationContext::new();
311 let root = self
312 .root
313 .evaluate_instance(instance, &LazyLocation::new(), &mut ctx);
314 Evaluation::new(root)
315 }
316 /// The [`Draft`] which was used to build this validator.
317 #[must_use]
318 pub fn draft(&self) -> Draft {
319 self.draft
320 }
321 }
322
323 #[cfg(test)]
324 mod tests {
325 use crate::{
326 error::ValidationError,
327 keywords::custom::Keyword,
328 paths::{LazyLocation, Location},
329 thread::ThreadBound,
330 types::JsonType,
331 Validator,
332 };
333 use fancy_regex::Regex;
334 use num_cmp::NumCmp;
335 use serde_json::{json, Map, Value};
336 use std::sync::LazyLock;
337
•338 //disabled, file missing #[cfg(not(target_arch = "wasm32"))]
339 //fn load(path: &str, idx: usize) -> Value {
340 // use std::{fs::File, io::Read, path::Path};
341 // let path = Path::new(path);
342 // let mut file = File::open(path).unwrap();
343 // let mut content = String::new();
344 // file.read_to_string(&mut content).ok().unwrap();
345 // let data: Value = serde_json::from_str(&content).unwrap();
346 // let case = &data.as_array().unwrap()[idx];
347 // case.get("schema").unwrap().clone()
348 //}
349
350 #[test]
351 fn only_keyword() {
352 // When only one keyword is specified
353 let schema = json!({"type": "string"});
354 let validator = crate::validator_for(&schema).unwrap();
355 let value1 = json!("AB");
356 let value2 = json!(1);
357 // And only this validator
358 assert_eq!(validator.root.validators().len(), 1);
359 assert!(validator.validate(&value1).is_ok());
360 assert!(validator.validate(&value2).is_err());
361 }
362
•363 //disabled, file missing #[test]
364 //#[cfg(not(target_arch = "wasm32"))]
365 //fn validate_ref() {
366 // let schema = load("tests/suite/tests/draft7/ref.json", 1);
367 // let value = json!({"bar": 3});
368 // let validator = crate::validator_for(&schema).unwrap();
369 // assert!(validator.validate(&value).is_ok());
370 // let value = json!({"bar": true});
371 // assert!(validator.validate(&value).is_err());
372 //}
373
374 #[test]
375 fn wrong_schema_type() {
376 let schema = json!([1]);
377 let validator = crate::validator_for(&schema);
378 assert!(validator.is_err());
379 }
380
381 #[test]
382 fn multiple_errors() {
383 let schema = json!({"minProperties": 2, "propertyNames": {"minLength": 3}});
384 let value = json!({"a": 3});
385 let validator = crate::validator_for(&schema).unwrap();
386 let errors: Vec<_> = validator.iter_errors(&value).collect();
387 assert_eq!(errors.len(), 2);
388 assert_eq!(
389 errors[0].to_string(),
390 r#"{"a":3} has less than 2 properties"#
391 );
392 assert_eq!(errors[1].to_string(), r#""a" is shorter than 3 characters"#);
393 }
394
395 #[test]
396 fn custom_keyword_definition() {
397 /// Define a custom validator that verifies the object's keys consist of
398 /// only ASCII representable characters.
399 /// NOTE: This could be done with `propertyNames` + `pattern` but will be slower due to
400 /// regex usage.
401 struct CustomObjectValidator;
402 impl Keyword for CustomObjectValidator {
403 fn validate<'i>(
404 &self,
405 instance: &'i Value,
406 location: &LazyLocation,
407 ) -> Result<(), ValidationError<'i>> {
408 for key in instance.as_object().unwrap().keys() {
409 if !key.is_ascii() {
410 return Err(ValidationError::custom(
411 Location::new(),
412 location.into(),
413 instance,
414 "Key is not ASCII",
415 ));
416 }
417 }
418 Ok(())
419 }
420
421 fn is_valid(&self, instance: &Value) -> bool {
422 for (key, _value) in instance.as_object().unwrap() {
423 if !key.is_ascii() {
424 return false;
425 }
426 }
427 true
428 }
429 }
430
431 fn custom_object_type_factory<'a>(
432 _: &'a Map<String, Value>,
433 schema: &'a Value,
434 path: Location,
435 ) -> Result<Box<dyn Keyword>, ValidationError<'a>> {
436 const EXPECTED: &str = "ascii-keys";
437 if schema.as_str() == Some(EXPECTED) {
438 Ok(Box::new(CustomObjectValidator))
439 } else {
440 Err(ValidationError::constant_string(
441 Location::new(),
442 path,
443 schema,
444 EXPECTED,
445 ))
446 }
447 }
448
449 // Define a JSON schema that enforces the top level object has ASCII keys and has at least 1 property
450 let schema =
451 json!({ "custom-object-type": "ascii-keys", "type": "object", "minProperties": 1 });
452 let validator = crate::options()
453 .with_keyword("custom-object-type", custom_object_type_factory)
454 .build(&schema)
455 .unwrap();
456
457 // Verify schema validation detects object with too few properties
458 let instance = json!({});
459 assert!(validator.validate(&instance).is_err());
460 assert!(!validator.is_valid(&instance));
461
462 // Verify validator succeeds on a valid custom-object-type
463 let instance = json!({ "a" : 1 });
464 assert!(validator.validate(&instance).is_ok());
465 assert!(validator.is_valid(&instance));
466
467 // Verify validator detects invalid custom-object-type
468 let instance = json!({ "å" : 1 });
469 let error = validator.validate(&instance).expect_err("Should fail");
470 assert_eq!(error.to_string(), "Key is not ASCII");
471 assert!(!validator.is_valid(&instance));
472 }
473
474 #[test]
475 fn custom_format_and_override_keyword() {
476 /// Check that a string has some number of digits followed by a dot followed by exactly 2 digits.
477 fn currency_format_checker(s: &str) -> bool {
478 static CURRENCY_RE: LazyLock<Regex> = LazyLock::new(|| {
479 Regex::new("^(0|([1-9]+[0-9]*))(\\.[0-9]{2})$").expect("Invalid regex")
480 });
481 CURRENCY_RE.is_match(s).expect("Invalid regex")
482 }
483 /// A custom keyword validator that overrides "minimum"
484 /// so that "minimum" may apply to "currency"-formatted strings as well.
485 struct CustomMinimumValidator {
486 limit: f64,
487 limit_val: Value,
488 with_currency_format: bool,
489 location: Location,
490 }
491
492 impl Keyword for CustomMinimumValidator {
493 fn validate<'i>(
494 &self,
495 instance: &'i Value,
496 location: &LazyLocation,
497 ) -> Result<(), ValidationError<'i>> {
498 if self.is_valid(instance) {
499 Ok(())
500 } else {
501 Err(ValidationError::minimum(
502 self.location.clone(),
503 location.into(),
504 instance,
505 self.limit_val.clone(),
506 ))
507 }
508 }
509
510 fn is_valid(&self, instance: &Value) -> bool {
511 match instance {
512 // Numeric comparison should happen just like original behavior
513 Value::Number(instance) => {
514 if let Some(item) = instance.as_u64() {
515 !NumCmp::num_lt(item, self.limit)
516 } else if let Some(item) = instance.as_i64() {
517 !NumCmp::num_lt(item, self.limit)
518 } else {
519 let item = instance.as_f64().expect("Always valid");
520 !NumCmp::num_lt(item, self.limit)
521 }
522 }
523 // String comparison should cast currency-formatted
524 Value::String(instance) => {
525 if self.with_currency_format && currency_format_checker(instance) {
526 // all preconditions for minimum applying are met
527 let value = instance
528 .parse::<f64>()
529 .expect("format validated by regex checker");
530 !NumCmp::num_lt(value, self.limit)
531 } else {
532 true
533 }
534 }
535 // In all other cases, the "minimum" keyword should not apply
536 _ => true,
537 }
538 }
539 }
540
541 /// Build a validator that overrides the standard `minimum` keyword
542 fn custom_minimum_factory<'a>(
543 parent: &'a Map<String, Value>,
544 schema: &'a Value,
545 location: Location,
546 ) -> Result<Box<dyn Keyword>, ValidationError<'a>> {
547 let limit = if let Value::Number(limit) = schema {
548 limit.as_f64().expect("Always valid")
549 } else {
550 return Err(ValidationError::single_type_error(
551 // There is no metaschema definition for a custom keyword, hence empty `schema` pointer
552 Location::new(),
553 location,
554 schema,
555 JsonType::Number,
556 ));
557 };
558 let with_currency_format = parent
559 .get("format")
560 .is_some_and(|format| format == "currency");
561 Ok(Box::new(CustomMinimumValidator {
562 limit,
563 limit_val: schema.clone(),
564 with_currency_format,
565 location,
566 }))
567 }
568
569 // Schema includes both the custom format and the overridden keyword
570 let schema = json!({ "minimum": 2, "type": "string", "format": "currency" });
571 let validator = crate::options()
572 .with_format("currency", currency_format_checker)
573 .with_keyword("minimum", custom_minimum_factory)
574 .with_keyword("minimum-2", custom_minimum_factory)
575 .should_validate_formats(true)
576 .build(&schema)
577 .expect("Invalid schema");
578
579 // Control: verify schema validation rejects non-string types
580 let instance = json!(15);
581 assert!(validator.validate(&instance).is_err());
582 assert!(!validator.is_valid(&instance));
583
584 // Control: verify validator rejects ill-formatted strings
585 let instance = json!("not a currency");
586 assert!(validator.validate(&instance).is_err());
587 assert!(!validator.is_valid(&instance));
588
589 // Verify validator allows properly formatted strings that conform to custom keyword
590 let instance = json!("3.00");
591 assert!(validator.validate(&instance).is_ok());
592 assert!(validator.is_valid(&instance));
593
594 // Verify validator rejects properly formatted strings that do not conform to custom keyword
595 let instance = json!("1.99");
596 assert!(validator.validate(&instance).is_err());
597 assert!(!validator.is_valid(&instance));
598
599 // Define another schema that applies "minimum" to an integer to ensure original behavior
600 let schema = json!({ "minimum": 2, "type": "integer" });
601 let validator = crate::options()
602 .with_format("currency", currency_format_checker)
603 .with_keyword("minimum", custom_minimum_factory)
604 .build(&schema)
605 .expect("Invalid schema");
606
607 // Verify schema allows integers greater than 2
608 let instance = json!(3);
609 assert!(validator.validate(&instance).is_ok());
610 assert!(validator.is_valid(&instance));
611
612 // Verify schema rejects integers less than 2
613 let instance = json!(1);
614 assert!(validator.validate(&instance).is_err());
615 assert!(!validator.is_valid(&instance));
616
617 // Invalid `minimum` value
618 let schema = json!({ "minimum": "foo" });
619 let error = crate::options()
620 .with_keyword("minimum", custom_minimum_factory)
621 .build(&schema)
622 .expect_err("Should fail");
623 assert_eq!(error.to_string(), "\"foo\" is not of type \"number\"");
624 }
625
626 #[test]
627 fn test_validator_is_send_and_sync() {
628 fn assert_send_sync<T: ThreadBound>() {}
629 assert_send_sync::<Validator>();
630 }
631
632 #[test]
633 fn test_validator_clone() {
634 let schema = json!({"type": "string", "minLength": 3});
635 let validator = crate::validator_for(&schema).expect("Valid schema");
636
637 // Clone the validator
638 let cloned = validator.clone();
639
640 // Both validators should work independently
641 assert!(validator.is_valid(&json!("hello")));
642 assert!(!validator.is_valid(&json!("hi")));
643
644 assert!(cloned.is_valid(&json!("hello")));
645 assert!(!cloned.is_valid(&json!("hi")));
646
647 // Verify they validate the same way
648 assert_eq!(
649 validator.is_valid(&json!("test")),
650 cloned.is_valid(&json!("test"))
651 );
652 }
653 }