| 1 | use crate::{ |
| 2 | compiler, |
| 3 | content_encoding::{ |
| 4 | ContentEncodingCheckType, ContentEncodingConverterType, |
| 5 | DEFAULT_CONTENT_ENCODING_CHECKS_AND_CONVERTERS, |
| 6 | }, |
| 7 | content_media_type::{ContentMediaTypeCheckType, DEFAULT_CONTENT_MEDIA_TYPE_CHECKS}, |
| 8 | keywords::{custom::KeywordFactory, format::Format}, |
| 9 | paths::Location, |
| 10 | retriever::DefaultRetriever, |
| 11 | thread::ThreadBound, |
| 12 | Keyword, ValidationError, Validator, |
| 13 | }; |
| 14 | use ahash::AHashMap; |
| 15 | use referencing::{Draft, Resource, Retrieve}; |
| 16 | use serde_json::Value; |
| 17 | use std::{fmt, marker::PhantomData, sync::Arc}; |
| 18 | |
| 19 | /// Configuration options for JSON Schema validation. |
| 20 | #[derive(Clone)] |
| 21 | pub struct ValidationOptions<R = Arc<dyn Retrieve>> { |
| 22 | pub(crate) draft: Option<Draft>, |
| 23 | content_media_type_checks: AHashMap<&'static str, Option<ContentMediaTypeCheckType>>, |
| 24 | content_encoding_checks_and_converters: |
| 25 | AHashMap<&'static str, Option<(ContentEncodingCheckType, ContentEncodingConverterType)>>, |
| 26 | pub(crate) base_uri: Option<String>, |
| 27 | /// Retriever for external resources |
| 28 | pub(crate) retriever: R, |
| 29 | /// Additional resources that should be addressable during validation. |
| 30 | pub(crate) resources: AHashMap<String, Resource>, |
| 31 | pub(crate) registry: Option<referencing::Registry>, |
| 32 | formats: AHashMap<String, Arc<dyn Format>>, |
| 33 | validate_formats: Option<bool>, |
| 34 | pub(crate) validate_schema: bool, |
| 35 | ignore_unknown_formats: bool, |
| 36 | keywords: AHashMap<String, Arc<dyn KeywordFactory>>, |
| 37 | pattern_options: PatternEngineOptions, |
| 38 | } |
| 39 | |
| 40 | impl Default for ValidationOptions<Arc<dyn Retrieve>> { |
| 41 | fn default() -> Self { |
| 42 | ValidationOptions { |
| 43 | draft: None, |
| 44 | content_media_type_checks: AHashMap::default(), |
| 45 | content_encoding_checks_and_converters: AHashMap::default(), |
| 46 | base_uri: None, |
| 47 | retriever: Arc::new(DefaultRetriever), |
| 48 | resources: AHashMap::default(), |
| 49 | registry: None, |
| 50 | formats: AHashMap::default(), |
| 51 | validate_formats: None, |
| 52 | validate_schema: true, |
| 53 | ignore_unknown_formats: true, |
| 54 | keywords: AHashMap::default(), |
| 55 | pattern_options: PatternEngineOptions::default(), |
| 56 | } |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | #[cfg(feature = "resolve-async")] |
| 61 | impl Default for ValidationOptions<Arc<dyn referencing::AsyncRetrieve>> { |
| 62 | fn default() -> Self { |
| 63 | ValidationOptions { |
| 64 | draft: None, |
| 65 | content_media_type_checks: AHashMap::default(), |
| 66 | content_encoding_checks_and_converters: AHashMap::default(), |
| 67 | base_uri: None, |
| 68 | retriever: Arc::new(DefaultRetriever), |
| 69 | resources: AHashMap::default(), |
| 70 | registry: None, |
| 71 | formats: AHashMap::default(), |
| 72 | validate_formats: None, |
| 73 | validate_schema: true, |
| 74 | ignore_unknown_formats: true, |
| 75 | keywords: AHashMap::default(), |
| 76 | pattern_options: PatternEngineOptions::default(), |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | impl<R> ValidationOptions<R> { |
| 82 | /// Return the draft version, or the default if not set. |
| 83 | pub(crate) fn draft(&self) -> Draft { |
| 84 | self.draft.unwrap_or_default() |
| 85 | } |
| 86 | /// Sets the JSON Schema draft version. |
| 87 | /// |
| 88 | /// ```rust |
| 89 | /// use jsonschema::Draft; |
| 90 | /// |
| 91 | /// let options = jsonschema::options() |
| 92 | /// .with_draft(Draft::Draft4); |
| 93 | /// ``` |
| 94 | /// |
| 95 | /// # Panics |
| 96 | /// |
| 97 | /// Panics if `Draft::Unknown` is provided. `Draft::Unknown` is internal-only |
| 98 | /// and represents custom meta-schemas that are resolved automatically from |
| 99 | /// the registry. |
| 100 | #[inline] |
| 101 | #[must_use] |
| 102 | pub fn with_draft(mut self, draft: Draft) -> Self { |
| 103 | assert!( |
| 104 | draft != Draft::Unknown, |
| 105 | "Draft::Unknown is internal-only and cannot be explicitly set. \ |
| 106 | Custom meta-schemas are resolved automatically when registered in the Registry." |
| 107 | ); |
| 108 | self.draft = Some(draft); |
| 109 | self |
| 110 | } |
| 111 | |
| 112 | pub(crate) fn get_content_media_type_check( |
| 113 | &self, |
| 114 | media_type: &str, |
| 115 | ) -> Option<ContentMediaTypeCheckType> { |
| 116 | if let Some(value) = self.content_media_type_checks.get(media_type) { |
| 117 | *value |
| 118 | } else { |
| 119 | DEFAULT_CONTENT_MEDIA_TYPE_CHECKS.get(media_type).copied() |
| 120 | } |
| 121 | } |
| 122 | /// Add support for a custom content media type validation. |
| 123 | /// |
| 124 | /// # Example |
| 125 | /// |
| 126 | /// ```rust |
| 127 | /// fn check_custom_media_type(instance_string: &str) -> bool { |
| 128 | /// instance_string.starts_with("custom:") |
| 129 | /// } |
| 130 | /// |
| 131 | /// let options = jsonschema::options() |
| 132 | /// .with_content_media_type("application/custom", check_custom_media_type); |
| 133 | /// ``` |
| 134 | #[must_use] |
| 135 | pub fn with_content_media_type( |
| 136 | mut self, |
| 137 | media_type: &'static str, |
| 138 | media_type_check: ContentMediaTypeCheckType, |
| 139 | ) -> Self { |
| 140 | self.content_media_type_checks |
| 141 | .insert(media_type, Some(media_type_check)); |
| 142 | self |
| 143 | } |
| 144 | /// Remove support for a specific content media type validation. |
| 145 | #[must_use] |
| 146 | pub fn without_content_media_type_support(mut self, media_type: &'static str) -> Self { |
| 147 | self.content_media_type_checks.insert(media_type, None); |
| 148 | self |
| 149 | } |
| 150 | |
| 151 | #[inline] |
| 152 | fn content_encoding_check_and_converter( |
| 153 | &self, |
| 154 | content_encoding: &str, |
| 155 | ) -> Option<(ContentEncodingCheckType, ContentEncodingConverterType)> { |
| 156 | if let Some(value) = self |
| 157 | .content_encoding_checks_and_converters |
| 158 | .get(content_encoding) |
| 159 | { |
| 160 | *value |
| 161 | } else { |
| 162 | DEFAULT_CONTENT_ENCODING_CHECKS_AND_CONVERTERS |
| 163 | .get(content_encoding) |
| 164 | .copied() |
| 165 | } |
| 166 | } |
| 167 | |
| 168 | pub(crate) fn content_encoding_check( |
| 169 | &self, |
| 170 | content_encoding: &str, |
| 171 | ) -> Option<ContentEncodingCheckType> { |
| 172 | if let Some((check, _)) = self.content_encoding_check_and_converter(content_encoding) { |
| 173 | Some(check) |
| 174 | } else { |
| 175 | None |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | pub(crate) fn get_content_encoding_convert( |
| 180 | &self, |
| 181 | content_encoding: &str, |
| 182 | ) -> Option<ContentEncodingConverterType> { |
| 183 | if let Some((_, converter)) = self.content_encoding_check_and_converter(content_encoding) { |
| 184 | Some(converter) |
| 185 | } else { |
| 186 | None |
| 187 | } |
| 188 | } |
| 189 | /// Add support for a custom content encoding. |
| 190 | /// |
| 191 | /// # Arguments |
| 192 | /// |
| 193 | /// * `encoding`: Name of the content encoding (e.g., "base64") |
| 194 | /// * `check`: Validates the input string (return `true` if valid) |
| 195 | /// * `converter`: Converts the input string, returning: |
| 196 | /// - `Err(ValidationError)`: For supported errors |
| 197 | /// - `Ok(None)`: If input is invalid |
| 198 | /// - `Ok(Some(content))`: If valid, with decoded content |
| 199 | /// |
| 200 | /// # Example |
| 201 | /// |
| 202 | /// ```rust |
| 203 | /// use jsonschema::ValidationError; |
| 204 | /// |
| 205 | /// fn check(s: &str) -> bool { |
| 206 | /// s.starts_with("valid:") |
| 207 | /// } |
| 208 | /// |
| 209 | /// fn convert(s: &str) -> Result<Option<String>, ValidationError<'static>> { |
| 210 | /// if s.starts_with("valid:") { |
| 211 | /// Ok(Some(s[6..].to_string())) |
| 212 | /// } else { |
| 213 | /// Ok(None) |
| 214 | /// } |
| 215 | /// } |
| 216 | /// |
| 217 | /// let options = jsonschema::options() |
| 218 | /// .with_content_encoding("custom", check, convert); |
| 219 | /// ``` |
| 220 | #[must_use] |
| 221 | pub fn with_content_encoding( |
| 222 | mut self, |
| 223 | encoding: &'static str, |
| 224 | check: ContentEncodingCheckType, |
| 225 | converter: ContentEncodingConverterType, |
| 226 | ) -> Self { |
| 227 | self.content_encoding_checks_and_converters |
| 228 | .insert(encoding, Some((check, converter))); |
| 229 | self |
| 230 | } |
| 231 | /// Remove support for a specific content encoding. |
| 232 | /// |
| 233 | /// # Example |
| 234 | /// |
| 235 | /// ```rust |
| 236 | /// let options = jsonschema::options() |
| 237 | /// .without_content_encoding_support("base64"); |
| 238 | /// ``` |
| 239 | #[must_use] |
| 240 | pub fn without_content_encoding_support(mut self, content_encoding: &'static str) -> Self { |
| 241 | self.content_encoding_checks_and_converters |
| 242 | .insert(content_encoding, None); |
| 243 | self |
| 244 | } |
| 245 | /// Establish an anchor for resolving relative schema references during validation. |
| 246 | /// |
| 247 | /// Relative URIs found within the schema will be interpreted against this base. |
| 248 | /// This is especially useful when validating schemas loaded from sources without an inherent base URL. |
| 249 | /// |
| 250 | /// # Example |
| 251 | /// |
| 252 | /// ```rust |
| 253 | /// # use serde_json::json; |
| 254 | /// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 255 | /// |
| 256 | /// let validator = jsonschema::options() |
| 257 | /// // Define a base URI for resolving relative references. |
| 258 | /// .with_base_uri("https://example.com/schemas/") |
| 259 | /// .build(&json!({ |
| 260 | /// "$id": "relative-schema.json", |
| 261 | /// "type": "object" |
| 262 | /// }))?; |
| 263 | /// |
| 264 | /// // Relative URIs in the schema will now resolve against "https://example.com/schemas/". |
| 265 | /// # Ok(()) |
| 266 | /// # } |
| 267 | /// ``` |
| 268 | #[inline] |
| 269 | #[must_use] |
| 270 | pub fn with_base_uri(mut self, base_uri: impl Into<String>) -> Self { |
| 271 | self.base_uri = Some(base_uri.into()); |
| 272 | self |
| 273 | } |
| 274 | /// Add a custom schema, allowing it to be referenced by the specified URI during validation. |
| 275 | /// |
| 276 | /// This enables the use of additional in-memory schemas alongside the main schema being validated. |
| 277 | /// |
| 278 | /// # Example |
| 279 | /// |
| 280 | /// ```rust |
| 281 | /// # use serde_json::json; |
| 282 | /// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 283 | /// use jsonschema::Resource; |
| 284 | /// |
| 285 | /// let extra = Resource::from_contents(json!({"minimum": 5})); |
| 286 | /// |
| 287 | /// let validator = jsonschema::options() |
| 288 | /// .with_resource("urn:minimum-schema", extra) |
| 289 | /// .build(&json!({"$ref": "urn:minimum-schema"}))?; |
| 290 | /// assert!(validator.is_valid(&json!(5))); |
| 291 | /// assert!(!validator.is_valid(&json!(4))); |
| 292 | /// # Ok(()) |
| 293 | /// # } |
| 294 | /// ``` |
| 295 | #[must_use] |
| 296 | pub fn with_resource(mut self, uri: impl Into<String>, resource: Resource) -> Self { |
| 297 | self.resources.insert(uri.into(), resource); |
| 298 | self |
| 299 | } |
| 300 | /// Add custom schemas, allowing them to be referenced by the specified URI during validation. |
| 301 | /// |
| 302 | /// This enables the use of additional in-memory schemas alongside the main schema being validated. |
| 303 | /// |
| 304 | /// # Example |
| 305 | /// |
| 306 | /// ```rust |
| 307 | /// # use serde_json::json; |
| 308 | /// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 309 | /// use jsonschema::Resource; |
| 310 | /// |
| 311 | /// let validator = jsonschema::options() |
| 312 | /// .with_resources([ |
| 313 | /// ( |
| 314 | /// "urn:minimum-schema", |
| 315 | /// Resource::from_contents(json!({"minimum": 5})), |
| 316 | /// ), |
| 317 | /// ( |
| 318 | /// "urn:maximum-schema", |
| 319 | /// Resource::from_contents(json!({"maximum": 10})), |
| 320 | /// ), |
| 321 | /// ].into_iter()) |
| 322 | /// .build(&json!({"$ref": "urn:minimum-schema"}))?; |
| 323 | /// assert!(validator.is_valid(&json!(5))); |
| 324 | /// assert!(!validator.is_valid(&json!(4))); |
| 325 | /// # Ok(()) |
| 326 | /// # } |
| 327 | /// ``` |
| 328 | #[must_use] |
| 329 | pub fn with_resources( |
| 330 | mut self, |
| 331 | pairs: impl Iterator<Item = (impl Into<String>, Resource)>, |
| 332 | ) -> Self { |
| 333 | for (uri, resource) in pairs { |
| 334 | self.resources.insert(uri.into(), resource); |
| 335 | } |
| 336 | self |
| 337 | } |
| 338 | /// Use external schema resources from the registry, making them accessible via references |
| 339 | /// during validation. |
| 340 | /// |
| 341 | /// # Example |
| 342 | /// |
| 343 | /// ```rust |
| 344 | /// # use serde_json::json; |
| 345 | /// # fn main() -> Result<(), Box<dyn std::error::Error>> { |
| 346 | /// use jsonschema::{Registry, Resource}; |
| 347 | /// |
| 348 | /// let registry = Registry::try_new( |
| 349 | /// "urn:name-schema", |
| 350 | /// Resource::from_contents(json!({"type": "string"})) |
| 351 | /// )?; |
| 352 | /// let schema = json!({ |
| 353 | /// "properties": { |
| 354 | /// "name": { "$ref": "urn:name-schema" } |
| 355 | /// } |
| 356 | /// }); |
| 357 | /// let validator = jsonschema::options() |
| 358 | /// .with_registry(registry) |
| 359 | /// .build(&schema)?; |
| 360 | /// assert!(validator.is_valid(&json!({ "name": "Valid String" }))); |
| 361 | /// assert!(!validator.is_valid(&json!({ "name": 123 }))); |
| 362 | /// # Ok(()) |
| 363 | /// # } |
| 364 | /// ``` |
| 365 | #[must_use] |
| 366 | pub fn with_registry(mut self, registry: referencing::Registry) -> Self { |
| 367 | self.registry = Some(registry); |
| 368 | self |
| 369 | } |
| 370 | /// Register a custom format validator. |
| 371 | /// |
| 372 | /// # Example |
| 373 | /// |
| 374 | /// ```rust |
| 375 | /// # use serde_json::json; |
| 376 | /// fn my_format(s: &str) -> bool { |
| 377 | /// // Your awesome format check! |
| 378 | /// s.ends_with("42!") |
| 379 | /// } |
| 380 | /// # fn foo() { |
| 381 | /// let schema = json!({"type": "string", "format": "custom"}); |
| 382 | /// let validator = jsonschema::options() |
| 383 | /// .with_format("custom", my_format) |
| 384 | /// .build(&schema) |
| 385 | /// .expect("Valid schema"); |
| 386 | /// |
| 387 | /// assert!(!validator.is_valid(&json!("foo"))); |
| 388 | /// assert!(validator.is_valid(&json!("foo42!"))); |
| 389 | /// # } |
| 390 | /// ``` |
| 391 | #[must_use] |
| 392 | pub fn with_format<N, F>(mut self, name: N, format: F) -> Self |
| 393 | where |
| 394 | N: Into<String>, |
| 395 | F: Fn(&str) -> bool + ThreadBound + 'static, |
| 396 | { |
| 397 | self.formats.insert(name.into(), Arc::new(format)); |
| 398 | self |
| 399 | } |
| 400 | pub(crate) fn get_format(&self, format: &str) -> Option<(&String, &Arc<dyn Format>)> { |
| 401 | self.formats.get_key_value(format) |
| 402 | } |
| 403 | /// Disable schema validation during compilation. |
| 404 | /// |
| 405 | /// Used internally to prevent infinite recursion when validating meta-schemas. |
| 406 | /// **Note**: Manually-crafted `ValidationError`s may still occur during compilation. |
| 407 | #[inline] |
| 408 | #[must_use] |
| 409 | pub(crate) fn without_schema_validation(mut self) -> Self { |
| 410 | self.validate_schema = false; |
| 411 | self |
| 412 | } |
| 413 | /// Set whether to validate formats. |
| 414 | /// |
| 415 | /// Default behavior depends on the draft version. This method overrides |
| 416 | /// the default, enabling or disabling format validation regardless of draft. |
| 417 | #[inline] |
| 418 | #[must_use] |
| 419 | pub fn should_validate_formats(mut self, yes: bool) -> Self { |
| 420 | self.validate_formats = Some(yes); |
| 421 | self |
| 422 | } |
| 423 | pub(crate) fn validate_formats(&self) -> Option<bool> { |
| 424 | self.validate_formats |
| 425 | } |
| 426 | /// Set whether to ignore unknown formats. |
| 427 | /// |
| 428 | /// By default, unknown formats are silently ignored. Set to `false` to report |
| 429 | /// unrecognized formats as validation errors. |
| 430 | #[must_use] |
| 431 | pub fn should_ignore_unknown_formats(mut self, yes: bool) -> Self { |
| 432 | self.ignore_unknown_formats = yes; |
| 433 | self |
| 434 | } |
| 435 | |
| 436 | pub(crate) const fn are_unknown_formats_ignored(&self) -> bool { |
| 437 | self.ignore_unknown_formats |
| 438 | } |
| 439 | /// Register a custom keyword validator. |
| 440 | /// |
| 441 | /// ## Example |
| 442 | /// |
| 443 | /// ```rust |
| 444 | /// # use jsonschema::{ |
| 445 | /// # paths::{LazyLocation, Location}, |
| 446 | /// # ErrorIterator, Keyword, ValidationError, |
| 447 | /// # }; |
| 448 | /// # use serde_json::{json, Map, Value}; |
| 449 | /// # use std::iter::once; |
| 450 | /// |
| 451 | /// struct MyCustomValidator; |
| 452 | /// |
| 453 | /// impl Keyword for MyCustomValidator { |
| 454 | /// fn validate<'i>( |
| 455 | /// &self, |
| 456 | /// instance: &'i Value, |
| 457 | /// location: &LazyLocation, |
| 458 | /// ) -> Result<(), ValidationError<'i>> { |
| 459 | /// // ... validate instance ... |
| 460 | /// if !instance.is_object() { |
| 461 | /// return Err(ValidationError::custom( |
| 462 | /// Location::new(), |
| 463 | /// location.into(), |
| 464 | /// instance, |
| 465 | /// "Boom!", |
| 466 | /// )); |
| 467 | /// } else { |
| 468 | /// Ok(()) |
| 469 | /// } |
| 470 | /// } |
| 471 | /// fn is_valid(&self, instance: &Value) -> bool { |
| 472 | /// // ... determine if instance is valid ... |
| 473 | /// true |
| 474 | /// } |
| 475 | /// } |
| 476 | /// |
| 477 | /// // You can create a factory function, or use a closure to create new validator instances. |
| 478 | /// fn custom_validator_factory<'a>( |
| 479 | /// parent: &'a Map<String, Value>, |
| 480 | /// value: &'a Value, |
| 481 | /// path: Location, |
| 482 | /// ) -> Result<Box<dyn Keyword>, ValidationError<'a>> { |
| 483 | /// Ok(Box::new(MyCustomValidator)) |
| 484 | /// } |
| 485 | /// |
| 486 | /// let validator = jsonschema::options() |
| 487 | /// .with_keyword("my-type", custom_validator_factory) |
| 488 | /// .with_keyword("my-type-with-closure", |_, _, _| Ok(Box::new(MyCustomValidator))) |
| 489 | /// .build(&json!({ "my-type": "my-schema"})) |
| 490 | /// .expect("A valid schema"); |
| 491 | /// |
| 492 | /// assert!(validator.is_valid(&json!({ "a": "b"}))); |
| 493 | /// ``` |
| 494 | #[must_use] |
| 495 | pub fn with_keyword<N, F>(mut self, name: N, factory: F) -> Self |
| 496 | where |
| 497 | N: Into<String>, |
| 498 | F: for<'a> Fn( |
| 499 | &'a serde_json::Map<String, Value>, |
| 500 | &'a Value, |
| 501 | Location, |
| 502 | ) -> Result<Box<dyn Keyword>, ValidationError<'a>> |
| 503 | + ThreadBound |
| 504 | + 'static, |
| 505 | { |
| 506 | self.keywords.insert(name.into(), Arc::new(factory)); |
| 507 | self |
| 508 | } |
| 509 | |
| 510 | pub(crate) fn get_keyword_factory(&self, name: &str) -> Option<&Arc<dyn KeywordFactory>> { |
| 511 | self.keywords.get(name) |
| 512 | } |
| 513 | } |
| 514 | |
| 515 | impl ValidationOptions<Arc<dyn referencing::Retrieve>> { |
| 516 | /// Build a JSON Schema validator using the current options. |
| 517 | /// |
| 518 | /// # Example |
| 519 | /// |
| 520 | /// ```rust |
| 521 | /// use serde_json::json; |
| 522 | /// |
| 523 | /// let schema = json!({"type": "string"}); |
| 524 | /// let validator = jsonschema::options() |
| 525 | /// .build(&schema) |
| 526 | /// .expect("A valid schema"); |
| 527 | /// |
| 528 | /// assert!(validator.is_valid(&json!("Hello"))); |
| 529 | /// assert!(!validator.is_valid(&json!(42))); |
| 530 | /// ``` |
| 531 | /// |
| 532 | /// # Errors |
| 533 | /// |
| 534 | /// Returns an error if `schema` is invalid for the selected draft or if referenced resources |
| 535 | /// cannot be retrieved or resolved. |
| 536 | pub fn build(&self, schema: &Value) -> Result<Validator, ValidationError<'static>> { |
| 537 | compiler::build_validator(self, schema) |
| 538 | } |
| 539 | pub(crate) fn draft_for(&self, contents: &Value) -> Result<Draft, ValidationError<'static>> { |
| 540 | // Preference: |
| 541 | // - Explicitly set |
| 542 | // - Autodetected (with registry resolution for custom meta-schemas) |
| 543 | // - Default |
| 544 | if let Some(draft) = self.draft { |
| 545 | Ok(draft) |
| 546 | } else { |
| 547 | let default = Draft::default(); |
| 548 | let detected = default.detect(contents); |
| 549 | |
| 550 | // If detected draft is Unknown (custom meta-schema), try to resolve it |
| 551 | if detected == Draft::Unknown { |
| 552 | if let Some(registry) = &self.registry { |
| 553 | if let Some(meta_schema_uri) = contents |
| 554 | .as_object() |
| 555 | .and_then(|obj| obj.get("$schema")) |
| 556 | .and_then(|s| s.as_str()) |
| 557 | { |
| 558 | // Walk the meta-schema chain to find the underlying draft |
| 559 | return Self::resolve_draft_from_registry(meta_schema_uri, registry); |
| 560 | } |
| 561 | } |
| 562 | } |
| 563 | |
| 564 | Ok(detected) |
| 565 | } |
| 566 | } |
| 567 | |
| 568 | fn resolve_draft_from_registry( |
| 569 | uri: &str, |
| 570 | registry: &referencing::Registry, |
| 571 | ) -> Result<Draft, ValidationError<'static>> { |
| 572 | let uri = uri.trim_end_matches('#'); |
| 573 | crate::meta::walk_meta_schema_chain(uri, |current_uri| { |
| 574 | let resolver = registry.try_resolver(current_uri)?; |
| 575 | let resolved = resolver.lookup("")?; |
| 576 | Ok(resolved.contents().clone()) |
| 577 | }) |
| 578 | } |
| 579 | /// Set a retriever to fetch external resources. |
| 580 | #[must_use] |
| 581 | pub fn with_retriever(mut self, retriever: impl Retrieve + 'static) -> Self { |
| 582 | self.retriever = Arc::new(retriever); |
| 583 | self |
| 584 | } |
| 585 | /// Configure the regular expression engine used during validation for keywords like `pattern` |
| 586 | /// or `patternProperties`. |
| 587 | /// |
| 588 | /// The default engine is [fancy-regex](https://docs.rs/fancy-regex), which supports advanced |
| 589 | /// features (e.g., backreferences, look-around). Be aware that using these may lead to exponential |
| 590 | /// runtime due to backtracking. For simpler regexes without these features, [regex](https://docs.rs/regex) |
| 591 | /// provides linear time performance. |
| 592 | /// |
| 593 | /// # Example |
| 594 | /// |
| 595 | /// ```rust |
| 596 | /// use serde_json::json; |
| 597 | /// use jsonschema::PatternOptions; |
| 598 | /// |
| 599 | /// let schema = json!({"type": "string"}); |
| 600 | /// |
| 601 | /// // Set backtracking limit to 20000. |
| 602 | /// let validator = jsonschema::options() |
| 603 | /// .with_pattern_options( |
| 604 | /// PatternOptions::fancy_regex() |
| 605 | /// .backtrack_limit(20000) |
| 606 | /// ) |
| 607 | /// .build(&schema) |
| 608 | /// .expect("A valid schema"); |
| 609 | /// ``` |
| 610 | #[must_use] |
| 611 | #[allow(clippy::needless_pass_by_value)] |
| 612 | pub fn with_pattern_options<E>(mut self, options: PatternOptions<E>) -> Self { |
| 613 | self.pattern_options = options.inner; |
| 614 | self |
| 615 | } |
| 616 | pub(crate) fn pattern_options(&self) -> PatternEngineOptions { |
| 617 | self.pattern_options |
| 618 | } |
| 619 | } |
| 620 | |
| 621 | #[cfg(feature = "resolve-async")] |
| 622 | impl ValidationOptions<Arc<dyn referencing::AsyncRetrieve>> { |
| 623 | /// Build a JSON Schema validator using the current async options. |
| 624 | /// |
| 625 | /// # Errors |
| 626 | /// |
| 627 | /// Returns an error if `schema` is invalid for the selected draft or if referenced resources |
| 628 | /// cannot be retrieved or resolved. |
| 629 | pub async fn build(&self, schema: &Value) -> Result<Validator, ValidationError<'static>> { |
| 630 | compiler::build_validator_async(self, schema).await |
| 631 | } |
| 632 | #[must_use] |
| 633 | pub fn with_retriever( |
| 634 | self, |
| 635 | retriever: impl referencing::AsyncRetrieve + 'static, |
| 636 | ) -> ValidationOptions<Arc<dyn referencing::AsyncRetrieve>> { |
| 637 | ValidationOptions { |
| 638 | draft: self.draft, |
| 639 | retriever: Arc::new(retriever), |
| 640 | content_media_type_checks: self.content_media_type_checks, |
| 641 | content_encoding_checks_and_converters: self.content_encoding_checks_and_converters, |
| 642 | base_uri: None, |
| 643 | resources: self.resources, |
| 644 | registry: self.registry, |
| 645 | formats: self.formats, |
| 646 | validate_formats: self.validate_formats, |
| 647 | validate_schema: self.validate_schema, |
| 648 | ignore_unknown_formats: self.ignore_unknown_formats, |
| 649 | keywords: self.keywords, |
| 650 | pattern_options: self.pattern_options, |
| 651 | } |
| 652 | } |
| 653 | #[allow(clippy::unused_async)] |
| 654 | pub(crate) async fn draft_for( |
| 655 | &self, |
| 656 | contents: &Value, |
| 657 | ) -> Result<Draft, ValidationError<'static>> { |
| 658 | // Preference: |
| 659 | // - Explicitly set |
| 660 | // - Autodetected |
| 661 | // - Default |
| 662 | if let Some(draft) = self.draft { |
| 663 | Ok(draft) |
| 664 | } else { |
| 665 | let default = Draft::default(); |
| 666 | Ok(default.detect(contents)) |
| 667 | } |
| 668 | } |
| 669 | /// Set a retriever to fetch external resources. |
| 670 | pub(crate) fn with_blocking_retriever( |
| 671 | self, |
| 672 | retriever: impl Retrieve + 'static, |
| 673 | ) -> ValidationOptions<Arc<dyn Retrieve>> { |
| 674 | ValidationOptions { |
| 675 | draft: self.draft, |
| 676 | retriever: Arc::new(retriever), |
| 677 | content_media_type_checks: self.content_media_type_checks, |
| 678 | content_encoding_checks_and_converters: self.content_encoding_checks_and_converters, |
| 679 | base_uri: None, |
| 680 | resources: self.resources, |
| 681 | registry: self.registry, |
| 682 | formats: self.formats, |
| 683 | validate_formats: self.validate_formats, |
| 684 | validate_schema: self.validate_schema, |
| 685 | ignore_unknown_formats: self.ignore_unknown_formats, |
| 686 | keywords: self.keywords, |
| 687 | pattern_options: self.pattern_options, |
| 688 | } |
| 689 | } |
| 690 | } |
| 691 | |
| 692 | impl fmt::Debug for ValidationOptions { |
| 693 | fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 694 | fmt.debug_struct("CompilationConfig") |
| 695 | .field("draft", &self.draft) |
| 696 | .field("content_media_type", &self.content_media_type_checks.keys()) |
| 697 | .field( |
| 698 | "content_encoding", |
| 699 | &self.content_encoding_checks_and_converters.keys(), |
| 700 | ) |
| 701 | .finish() |
| 702 | } |
| 703 | } |
| 704 | |
| 705 | /// Configuration for how regular expressions are handled in schema keywords like `pattern` and `patternProperties`. |
| 706 | #[derive(Debug, Clone)] |
| 707 | pub struct PatternOptions<E> { |
| 708 | inner: PatternEngineOptions, |
| 709 | _marker: PhantomData<E>, |
| 710 | } |
| 711 | |
| 712 | #[derive(Debug, Clone, Copy, Hash, PartialEq, Eq)] |
| 713 | pub(crate) enum PatternEngineOptions { |
| 714 | FancyRegex { |
| 715 | backtrack_limit: Option<usize>, |
| 716 | size_limit: Option<usize>, |
| 717 | dfa_size_limit: Option<usize>, |
| 718 | }, |
| 719 | Regex { |
| 720 | size_limit: Option<usize>, |
| 721 | dfa_size_limit: Option<usize>, |
| 722 | }, |
| 723 | } |
| 724 | |
| 725 | /// Marker for using the `fancy-regex` engine that includes advanced features like lookarounds. |
| 726 | pub struct FancyRegex; |
| 727 | /// Marker for using the `regex` engine, that has fewer features than `fancy-regex` but guarantees |
| 728 | /// linear time performance. |
| 729 | pub struct Regex; |
| 730 | |
| 731 | impl PatternOptions<FancyRegex> { |
| 732 | /// Create a pattern configuration based on the `fancy-regex` engine. |
| 733 | #[must_use] |
| 734 | pub fn fancy_regex() -> PatternOptions<FancyRegex> { |
| 735 | PatternOptions { |
| 736 | inner: PatternEngineOptions::FancyRegex { |
| 737 | backtrack_limit: None, |
| 738 | size_limit: None, |
| 739 | dfa_size_limit: None, |
| 740 | }, |
| 741 | _marker: PhantomData, |
| 742 | } |
| 743 | } |
| 744 | /// Limit for how many times backtracking should be attempted for fancy regexes (where |
| 745 | /// backtracking is used). If this limit is exceeded, execution returns an error. |
| 746 | /// This is for preventing a regex with catastrophic backtracking to run for too long. |
| 747 | /// |
| 748 | /// Default is `1_000_000` (1 million). |
| 749 | #[must_use] |
| 750 | pub fn backtrack_limit(mut self, limit: usize) -> Self { |
| 751 | if let PatternEngineOptions::FancyRegex { |
| 752 | ref mut backtrack_limit, |
| 753 | .. |
| 754 | } = self.inner |
| 755 | { |
| 756 | *backtrack_limit = Some(limit); |
| 757 | } |
| 758 | self |
| 759 | } |
| 760 | /// Set the approximate size limit, in bytes, of the compiled regex. |
| 761 | #[must_use] |
| 762 | pub fn size_limit(mut self, limit: usize) -> Self { |
| 763 | if let PatternEngineOptions::FancyRegex { |
| 764 | ref mut size_limit, .. |
| 765 | } = self.inner |
| 766 | { |
| 767 | *size_limit = Some(limit); |
| 768 | } |
| 769 | self |
| 770 | } |
| 771 | /// Set the approximate capacity, in bytes, of the cache of transitions used by the lazy DFA. |
| 772 | #[must_use] |
| 773 | pub fn dfa_size_limit(mut self, limit: usize) -> Self { |
| 774 | if let PatternEngineOptions::FancyRegex { |
| 775 | ref mut dfa_size_limit, |
| 776 | .. |
| 777 | } = self.inner |
| 778 | { |
| 779 | *dfa_size_limit = Some(limit); |
| 780 | } |
| 781 | self |
| 782 | } |
| 783 | } |
| 784 | |
| 785 | impl PatternOptions<Regex> { |
| 786 | /// Create a pattern configuration based on the `regex` engine. |
| 787 | #[must_use] |
| 788 | pub fn regex() -> PatternOptions<Regex> { |
| 789 | PatternOptions { |
| 790 | inner: PatternEngineOptions::Regex { |
| 791 | size_limit: None, |
| 792 | dfa_size_limit: None, |
| 793 | }, |
| 794 | _marker: PhantomData, |
| 795 | } |
| 796 | } |
| 797 | /// Set the approximate size limit, in bytes, of the compiled regex. |
| 798 | #[must_use] |
| 799 | pub fn size_limit(mut self, limit: usize) -> Self { |
| 800 | if let PatternEngineOptions::Regex { |
| 801 | ref mut size_limit, .. |
| 802 | } = self.inner |
| 803 | { |
| 804 | *size_limit = Some(limit); |
| 805 | } |
| 806 | self |
| 807 | } |
| 808 | /// Set the approximate capacity, in bytes, of the cache of transitions used by the lazy DFA. |
| 809 | #[must_use] |
| 810 | pub fn dfa_size_limit(mut self, limit: usize) -> Self { |
| 811 | if let PatternEngineOptions::Regex { |
| 812 | ref mut dfa_size_limit, |
| 813 | .. |
| 814 | } = self.inner |
| 815 | { |
| 816 | *dfa_size_limit = Some(limit); |
| 817 | } |
| 818 | self |
| 819 | } |
| 820 | } |
| 821 | |
| 822 | impl Default for PatternEngineOptions { |
| 823 | fn default() -> Self { |
| 824 | PatternEngineOptions::FancyRegex { |
| 825 | backtrack_limit: None, |
| 826 | size_limit: None, |
| 827 | dfa_size_limit: None, |
| 828 | } |
| 829 | } |
| 830 | } |
| 831 | |
| 832 | #[cfg(test)] |
| 833 | mod tests { |
| 834 | use super::*; |
| 835 | use referencing::{Registry, Resource}; |
| 836 | use serde_json::json; |
| 837 | |
| 838 | fn custom(s: &str) -> bool { |
| 839 | s.ends_with("42!") |
| 840 | } |
| 841 | |
| 842 | #[test] |
| 843 | fn custom_format() { |
| 844 | let schema = json!({"type": "string", "format": "custom"}); |
| 845 | let validator = crate::options() |
| 846 | .with_format("custom", custom) |
| 847 | .should_validate_formats(true) |
| 848 | .build(&schema) |
| 849 | .expect("Valid schema"); |
| 850 | assert!(!validator.is_valid(&json!("foo"))); |
| 851 | assert!(validator.is_valid(&json!("foo42!"))); |
| 852 | } |
| 853 | |
| 854 | #[test] |
| 855 | fn with_registry() { |
| 856 | let registry = Registry::try_new( |
| 857 | "urn:name-schema", |
| 858 | Resource::from_contents(json!({"type": "string"})), |
| 859 | ) |
| 860 | .expect("Invalid URI"); |
| 861 | let schema = json!({ |
| 862 | "properties": { |
| 863 | "name": { "$ref": "urn:name-schema" } |
| 864 | } |
| 865 | }); |
| 866 | let validator = crate::options() |
| 867 | .with_registry(registry) |
| 868 | .build(&schema) |
| 869 | .expect("Invalid schema"); |
| 870 | assert!(validator.is_valid(&json!({ "name": "Valid String" }))); |
| 871 | assert!(!validator.is_valid(&json!({ "name": 123 }))); |
| 872 | } |
| 873 | |
| 874 | #[test] |
| 875 | fn test_fancy_regex_options_builder() { |
| 876 | let options = PatternOptions::fancy_regex() |
| 877 | .backtrack_limit(1_000_000) |
| 878 | .size_limit(10_000) |
| 879 | .dfa_size_limit(5000); |
| 880 | |
| 881 | if let PatternEngineOptions::FancyRegex { |
| 882 | backtrack_limit, |
| 883 | size_limit, |
| 884 | dfa_size_limit, |
| 885 | } = options.inner |
| 886 | { |
| 887 | assert_eq!(backtrack_limit, Some(1_000_000)); |
| 888 | assert_eq!(size_limit, Some(10_000)); |
| 889 | assert_eq!(dfa_size_limit, Some(5000)); |
| 890 | } else { |
| 891 | panic!("Expected FancyRegex variant"); |
| 892 | } |
| 893 | } |
| 894 | |
| 895 | #[test] |
| 896 | #[should_panic(expected = "Draft::Unknown is internal-only and cannot be explicitly set")] |
| 897 | fn with_draft_rejects_unknown() { |
| 898 | let _options = crate::options().with_draft(Draft::Unknown); |
| 899 | } |
| 900 | |
| 901 | #[test] |
| 902 | fn custom_meta_schema_allowed_when_draft_overridden() { |
| 903 | let schema = json!({ |
| 904 | "$schema": "json-schema:///custom/meta", |
| 905 | "type": "string" |
| 906 | }); |
| 907 | |
| 908 | crate::options() |
| 909 | .with_draft(Draft::Draft7) |
| 910 | .build(&schema) |
| 911 | .expect("Explicit draft override should bypass custom meta-schema registry checks"); |
| 912 | } |
| 913 | |
| 914 | #[test] |
| 915 | fn test_regex_options_builder() { |
| 916 | let options = PatternOptions::regex() |
| 917 | .size_limit(20_000) |
| 918 | .dfa_size_limit(8000); |
| 919 | |
| 920 | if let PatternEngineOptions::Regex { |
| 921 | size_limit, |
| 922 | dfa_size_limit, |
| 923 | } = options.inner |
| 924 | { |
| 925 | assert_eq!(size_limit, Some(20_000)); |
| 926 | assert_eq!(dfa_size_limit, Some(8000)); |
| 927 | } else { |
| 928 | panic!("Expected Regex variant"); |
| 929 | } |
| 930 | } |
| 931 | |
| 932 | #[test] |
| 933 | fn test_validate_against_definition() { |
| 934 | // Root schema with multiple definitions |
| 935 | let root_schema = json!({ |
| 936 | "$id": "https://example.com/root", |
| 937 | "definitions": { |
| 938 | "User": { |
| 939 | "type": "object", |
| 940 | "properties": { |
| 941 | "name": {"type": "string"}, |
| 942 | "age": {"type": "integer", "minimum": 0} |
| 943 | }, |
| 944 | "required": ["name"] |
| 945 | }, |
| 946 | "Product": { |
| 947 | "type": "object", |
| 948 | "properties": { |
| 949 | "id": {"type": "integer"}, |
| 950 | "title": {"type": "string"} |
| 951 | }, |
| 952 | "required": ["id", "title"] |
| 953 | } |
| 954 | } |
| 955 | }); |
| 956 | |
| 957 | // Create a schema that references the specific definition |
| 958 | let user_schema = json!({"$ref": "https://example.com/root#/definitions/User"}); |
| 959 | |
| 960 | // Build validator with the root schema registered as a resource |
| 961 | let validator = crate::options() |
| 962 | .with_resource( |
| 963 | "https://example.com/root", |
| 964 | Resource::from_contents(root_schema), |
| 965 | ) |
| 966 | .build(&user_schema) |
| 967 | .expect("Valid schema"); |
| 968 | |
| 969 | // Valid user |
| 970 | assert!(validator.is_valid(&json!({"name": "Alice", "age": 30}))); |
| 971 | assert!(validator.is_valid(&json!({"name": "Bob"}))); |
| 972 | |
| 973 | // Invalid: missing required field |
| 974 | assert!(!validator.is_valid(&json!({"age": 25}))); |
| 975 | |
| 976 | // Invalid: wrong type for age |
| 977 | assert!(!validator.is_valid(&json!({"name": "Charlie", "age": "thirty"}))); |
| 978 | } |
| 979 | } |