| 1 | use crate::{ |
| 2 | content_encoding::{ContentEncodingCheckType, ContentEncodingConverterType}, |
| 3 | content_media_type::ContentMediaTypeCheckType, |
| 4 | ecma, |
| 5 | keywords::{ |
| 6 | self, |
| 7 | custom::{CustomKeyword, KeywordFactory}, |
| 8 | format::Format, |
| 9 | unevaluated_items::PendingItemsValidators, |
| 10 | unevaluated_properties::PendingPropertyValidators, |
| 11 | BoxedValidator, BuiltinKeyword, Keyword, |
| 12 | }, |
| 13 | node::{PendingSchemaNode, SchemaNode}, |
| 14 | options::{PatternEngineOptions, ValidationOptions}, |
| 15 | paths::{Location, LocationSegment}, |
| 16 | types::{JsonType, JsonTypeSet}, |
| 17 | validator::Validate, |
| 18 | ValidationError, Validator, |
| 19 | }; |
| 20 | use ahash::{AHashMap, AHashSet}; |
| 21 | use referencing::{ |
| 22 | uri, Draft, List, Registry, Resolved, Resolver, Resource, ResourceRef, Uri, Vocabulary, |
| 23 | VocabularySet, |
| 24 | }; |
| 25 | use serde_json::{Map, Value}; |
| 26 | use std::{borrow::Cow, cell::RefCell, iter::once, rc::Rc, sync::Arc}; |
| 27 | |
| 28 | const DEFAULT_SCHEME: &str = "json-schema"; |
| 29 | pub(crate) const DEFAULT_BASE_URI: &str = "json-schema:///"; |
| 30 | |
| 31 | /// Type alias for shared cache maps in compiler state. |
| 32 | type SharedCache<K, V> = Rc<RefCell<AHashMap<K, V>>>; |
| 33 | /// Type alias for shared sets in compiler state. |
| 34 | type SharedSet<T> = Rc<RefCell<AHashSet<T>>>; |
| 35 | |
| 36 | #[derive(Hash, PartialEq, Eq, Clone, Debug)] |
| 37 | pub(crate) struct LocationCacheKey { |
| 38 | pub(crate) base_uri: Arc<Uri<String>>, |
| 39 | location: Arc<str>, |
| 40 | dynamic_scope: List<Uri<String>>, |
| 41 | } |
| 42 | |
| 43 | #[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)] |
| 44 | struct PropertyValidatorsPendingKey { |
| 45 | schema_ptr: usize, |
| 46 | } |
| 47 | |
| 48 | impl PropertyValidatorsPendingKey { |
| 49 | fn new(schema: &Map<String, Value>) -> Self { |
| 50 | Self { |
| 51 | schema_ptr: std::ptr::from_ref(schema) as usize, |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | #[derive(Hash, PartialEq, Eq, Clone, Copy, Debug)] |
| 57 | struct ItemsValidatorsPendingKey { |
| 58 | schema_ptr: usize, |
| 59 | } |
| 60 | |
| 61 | impl ItemsValidatorsPendingKey { |
| 62 | fn new(schema: &Map<String, Value>) -> Self { |
| 63 | Self { |
| 64 | schema_ptr: std::ptr::from_ref(schema) as usize, |
| 65 | } |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | #[derive(Hash, PartialEq, Eq, Clone, Debug)] |
| 70 | pub(crate) struct AliasCacheKey { |
| 71 | uri: Arc<Uri<String>>, |
| 72 | dynamic_scope: List<Uri<String>>, |
| 73 | } |
| 74 | |
| 75 | /// Shared caches reused across every `Context` derived from a schema root. |
| 76 | #[derive(Debug, Clone)] |
| 77 | struct SharedContextState { |
| 78 | seen: SharedSet<Arc<Uri<String>>>, |
| 79 | location_nodes: SharedCache<LocationCacheKey, SchemaNode>, |
| 80 | alias_nodes: SharedCache<AliasCacheKey, SchemaNode>, |
| 81 | pending_nodes: SharedCache<LocationCacheKey, PendingSchemaNode>, |
| 82 | alias_placeholders: SharedCache<Arc<Uri<String>>, PendingSchemaNode>, |
| 83 | pending_property_validators: SharedCache<LocationCacheKey, PendingPropertyValidators>, |
| 84 | pending_property_validators_by_schema: |
| 85 | SharedCache<PropertyValidatorsPendingKey, PendingPropertyValidators>, |
| 86 | pending_items_validators: SharedCache<LocationCacheKey, PendingItemsValidators>, |
| 87 | pending_items_validators_by_schema: |
| 88 | SharedCache<ItemsValidatorsPendingKey, PendingItemsValidators>, |
| 89 | pattern_cache: SharedCache<Arc<str>, PatternCacheEntry>, |
| 90 | uri_buffer: Rc<RefCell<String>>, |
| 91 | } |
| 92 | |
| 93 | #[derive(Debug, Clone)] |
| 94 | struct PatternCacheEntry { |
| 95 | translated: Arc<str>, |
| 96 | fancy: Option<Arc<fancy_regex::Regex>>, |
| 97 | standard: Option<Arc<regex::Regex>>, |
| 98 | } |
| 99 | |
| 100 | impl SharedContextState { |
| 101 | fn new() -> Self { |
| 102 | Self { |
| 103 | seen: Rc::new(RefCell::new(AHashSet::new())), |
| 104 | location_nodes: Rc::new(RefCell::new(AHashMap::new())), |
| 105 | alias_nodes: Rc::new(RefCell::new(AHashMap::new())), |
| 106 | pending_nodes: Rc::new(RefCell::new(AHashMap::new())), |
| 107 | alias_placeholders: Rc::new(RefCell::new(AHashMap::new())), |
| 108 | pending_property_validators: Rc::new(RefCell::new(AHashMap::new())), |
| 109 | pending_property_validators_by_schema: Rc::new(RefCell::new(AHashMap::new())), |
| 110 | pending_items_validators: Rc::new(RefCell::new(AHashMap::new())), |
| 111 | pending_items_validators_by_schema: Rc::new(RefCell::new(AHashMap::new())), |
| 112 | pattern_cache: Rc::new(RefCell::new(AHashMap::new())), |
| 113 | uri_buffer: Rc::new(RefCell::new(String::new())), |
| 114 | } |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | /// Per-location view used while compiling schemas into validators. |
| 119 | #[derive(Debug, Clone)] |
| 120 | pub(crate) struct Context<'a> { |
| 121 | config: &'a ValidationOptions, |
| 122 | pub(crate) registry: &'a Registry, |
| 123 | resolver: Resolver<'a>, |
| 124 | vocabularies: VocabularySet, |
| 125 | location: Location, |
| 126 | pub(crate) draft: Draft, |
| 127 | shared: SharedContextState, |
| 128 | } |
| 129 | |
| 130 | impl<'a> Context<'a> { |
| 131 | pub(crate) fn new( |
| 132 | config: &'a ValidationOptions, |
| 133 | registry: &'a Registry, |
| 134 | resolver: Resolver<'a>, |
| 135 | vocabularies: VocabularySet, |
| 136 | draft: Draft, |
| 137 | location: Location, |
| 138 | ) -> Self { |
| 139 | Context { |
| 140 | config, |
| 141 | registry, |
| 142 | resolver, |
| 143 | location, |
| 144 | vocabularies, |
| 145 | draft, |
| 146 | shared: SharedContextState::new(), |
| 147 | } |
| 148 | } |
| 149 | pub(crate) fn draft(&self) -> Draft { |
| 150 | self.draft |
| 151 | } |
| 152 | pub(crate) fn config(&self) -> &ValidationOptions { |
| 153 | self.config |
| 154 | } |
| 155 | |
| 156 | /// Create a context for this schema. |
| 157 | pub(crate) fn in_subresource( |
| 158 | &'a self, |
| 159 | resource: ResourceRef<'_>, |
| 160 | ) -> Result<Context<'a>, referencing::Error> { |
| 161 | let resolver = self.resolver.in_subresource(resource)?; |
| 162 | Ok(Context { |
| 163 | config: self.config, |
| 164 | registry: self.registry, |
| 165 | resolver, |
| 166 | vocabularies: self.vocabularies.clone(), |
| 167 | draft: resource.draft(), |
| 168 | location: self.location.clone(), |
| 169 | shared: self.shared.clone(), |
| 170 | }) |
| 171 | } |
| 172 | pub(crate) fn as_resource_ref<'r>(&'a self, contents: &'r Value) -> ResourceRef<'r> { |
| 173 | self.draft.detect(contents).create_resource_ref(contents) |
| 174 | } |
| 175 | |
| 176 | #[inline] |
| 177 | pub(crate) fn new_at_location(&'a self, chunk: impl Into<LocationSegment<'a>>) -> Self { |
| 178 | let location = self.location.join(chunk); |
| 179 | Context { |
| 180 | config: self.config, |
| 181 | registry: self.registry, |
| 182 | resolver: self.resolver.clone(), |
| 183 | vocabularies: self.vocabularies.clone(), |
| 184 | location, |
| 185 | draft: self.draft, |
| 186 | shared: self.shared.clone(), |
| 187 | } |
| 188 | } |
| 189 | pub(crate) fn lookup(&'a self, reference: &str) -> Result<Resolved<'a>, referencing::Error> { |
| 190 | self.resolver.lookup(reference) |
| 191 | } |
| 192 | |
| 193 | pub(crate) fn location_cache_key(&self) -> LocationCacheKey { |
| 194 | LocationCacheKey { |
| 195 | base_uri: self.resolver.base_uri(), |
| 196 | location: self.location.as_arc(), |
| 197 | dynamic_scope: self.resolver.dynamic_scope(), |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | fn alias_cache_key(&self, alias: Arc<Uri<String>>) -> AliasCacheKey { |
| 202 | AliasCacheKey { |
| 203 | uri: alias, |
| 204 | dynamic_scope: self.resolver.dynamic_scope(), |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | pub(crate) fn base_uri(&self) -> Option<Arc<Uri<String>>> { |
| 209 | let base_uri = self.resolver.base_uri(); |
| 210 | if base_uri.scheme().as_str() == DEFAULT_SCHEME { |
| 211 | None |
| 212 | } else { |
| 213 | Some(base_uri) |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | pub(crate) fn absolute_location(&self, location: &Location) -> Option<Arc<Uri<String>>> { |
| 218 | let base = self.base_uri()?; |
| 219 | let mut buffer = self.shared.uri_buffer.borrow_mut(); |
| 220 | buffer.clear(); |
| 221 | uri::encode_to(location.as_str(), &mut buffer); |
| 222 | let resolved = base.with_fragment(Some(uri::EncodedString::new_or_panic(&buffer))); |
| 223 | buffer.clear(); |
| 224 | Some(Arc::new(resolved)) |
| 225 | } |
| 226 | |
| 227 | fn translated_pattern(&self, pattern: &str) -> Result<Arc<str>, ()> { |
| 228 | if let Some(entry) = self.shared.pattern_cache.borrow().get(pattern) { |
| 229 | return Ok(Arc::clone(&entry.translated)); |
| 230 | } |
| 231 | let translated = Arc::<str>::from(ecma::to_rust_regex(pattern)?); |
| 232 | self.shared.pattern_cache.borrow_mut().insert( |
| 233 | Arc::from(pattern), |
| 234 | PatternCacheEntry { |
| 235 | translated: Arc::clone(&translated), |
| 236 | fancy: None, |
| 237 | standard: None, |
| 238 | }, |
| 239 | ); |
| 240 | Ok(translated) |
| 241 | } |
| 242 | |
| 243 | fn is_known_keyword(&self, keyword: &str) -> bool { |
| 244 | self.draft.is_known_keyword(keyword) |
| 245 | } |
| 246 | pub(crate) fn supports_adjacent_validation(&self) -> bool { |
| 247 | !matches!(self.draft, Draft::Draft4 | Draft::Draft6 | Draft::Draft7) |
| 248 | } |
| 249 | pub(crate) fn supports_integer_valued_numbers(&self) -> bool { |
| 250 | !matches!(self.draft, Draft::Draft4) |
| 251 | } |
| 252 | pub(crate) fn validates_formats_by_default(&self) -> bool { |
| 253 | self.config.validate_formats().unwrap_or(matches!( |
| 254 | self.draft, |
| 255 | Draft::Draft4 | Draft::Draft6 | Draft::Draft7 |
| 256 | )) |
| 257 | } |
| 258 | pub(crate) fn are_unknown_formats_ignored(&self) -> bool { |
| 259 | self.config.are_unknown_formats_ignored() |
| 260 | } |
| 261 | pub(crate) fn with_resolver_and_draft( |
| 262 | &'a self, |
| 263 | resolver: Resolver<'a>, |
| 264 | draft: Draft, |
| 265 | vocabularies: VocabularySet, |
| 266 | location: Location, |
| 267 | ) -> Context<'a> { |
| 268 | Context { |
| 269 | config: self.config, |
| 270 | registry: self.registry, |
| 271 | resolver, |
| 272 | draft, |
| 273 | vocabularies, |
| 274 | location, |
| 275 | shared: self.shared.clone(), |
| 276 | } |
| 277 | } |
| 278 | pub(crate) fn get_content_media_type_check( |
| 279 | &self, |
| 280 | media_type: &str, |
| 281 | ) -> Option<ContentMediaTypeCheckType> { |
| 282 | self.config.get_content_media_type_check(media_type) |
| 283 | } |
| 284 | pub(crate) fn get_content_encoding_check( |
| 285 | &self, |
| 286 | content_encoding: &str, |
| 287 | ) -> Option<ContentEncodingCheckType> { |
| 288 | self.config.content_encoding_check(content_encoding) |
| 289 | } |
| 290 | |
| 291 | pub(crate) fn get_content_encoding_convert( |
| 292 | &self, |
| 293 | content_encoding: &str, |
| 294 | ) -> Option<ContentEncodingConverterType> { |
| 295 | self.config.get_content_encoding_convert(content_encoding) |
| 296 | } |
| 297 | pub(crate) fn get_keyword_factory(&self, name: &str) -> Option<&Arc<dyn KeywordFactory>> { |
| 298 | self.config.get_keyword_factory(name) |
| 299 | } |
| 300 | pub(crate) fn get_format(&self, format: &str) -> Option<(&String, &Arc<dyn Format>)> { |
| 301 | self.config.get_format(format) |
| 302 | } |
| 303 | pub(crate) fn is_circular_reference( |
| 304 | &self, |
| 305 | reference: &str, |
| 306 | ) -> Result<bool, referencing::Error> { |
| 307 | let uri = self |
| 308 | .resolver |
| 309 | .resolve_against(&self.resolver.base_uri().borrow(), reference)?; |
| 310 | Ok(self.shared.seen.borrow().contains(&*uri)) |
| 311 | } |
| 312 | pub(crate) fn mark_seen(&self, reference: &str) -> Result<(), referencing::Error> { |
| 313 | let uri = self |
| 314 | .resolver |
| 315 | .resolve_against(&self.resolver.base_uri().borrow(), reference)?; |
| 316 | self.shared.seen.borrow_mut().insert(uri); |
| 317 | Ok(()) |
| 318 | } |
| 319 | |
| 320 | pub(crate) fn lookup_recursive_reference(&self) -> Result<Resolved<'_>, referencing::Error> { |
| 321 | self.resolver.lookup_recursive_ref() |
| 322 | } |
| 323 | pub(crate) fn absolute_location_uri(&self) -> Result<Arc<Uri<String>>, referencing::Error> { |
| 324 | // Reuse the shared buffer to avoid allocations |
| 325 | let mut buffer = self.shared.uri_buffer.borrow_mut(); |
| 326 | buffer.clear(); |
| 327 | buffer.push('#'); |
| 328 | if !self.location.as_str().is_empty() { |
| 329 | uri::encode_to(self.location.as_str(), &mut buffer); |
| 330 | } |
| 331 | let result = self |
| 332 | .resolver |
| 333 | .resolve_against(&self.resolver.base_uri().borrow(), &buffer); |
| 334 | buffer.clear(); |
| 335 | result |
| 336 | } |
| 337 | |
| 338 | pub(crate) fn resolve_reference_uri( |
| 339 | &self, |
| 340 | reference: &str, |
| 341 | ) -> Result<Arc<Uri<String>>, referencing::Error> { |
| 342 | self.resolver |
| 343 | .resolve_against(&self.resolver.base_uri().borrow(), reference) |
| 344 | } |
| 345 | |
| 346 | pub(crate) fn cached_location_node(&self, key: &LocationCacheKey) -> Option<SchemaNode> { |
| 347 | self.shared.location_nodes.borrow().get(key).cloned() |
| 348 | } |
| 349 | |
| 350 | pub(crate) fn cache_location_node(&self, key: LocationCacheKey, node: SchemaNode) { |
| 351 | self.shared.location_nodes.borrow_mut().insert(key, node); |
| 352 | } |
| 353 | |
| 354 | pub(crate) fn cached_alias_node(&self, key: &AliasCacheKey) -> Option<SchemaNode> { |
| 355 | self.shared.alias_nodes.borrow().get(key).cloned() |
| 356 | } |
| 357 | |
| 358 | pub(crate) fn cache_alias_node(&self, key: AliasCacheKey, node: SchemaNode) { |
| 359 | self.shared.alias_nodes.borrow_mut().insert(key, node); |
| 360 | } |
| 361 | |
| 362 | pub(crate) fn cached_pending_location_node( |
| 363 | &self, |
| 364 | key: &LocationCacheKey, |
| 365 | ) -> Option<PendingSchemaNode> { |
| 366 | self.shared.pending_nodes.borrow().get(key).cloned() |
| 367 | } |
| 368 | |
| 369 | pub(crate) fn cache_pending_location_node( |
| 370 | &self, |
| 371 | key: LocationCacheKey, |
| 372 | node: PendingSchemaNode, |
| 373 | ) { |
| 374 | self.shared.pending_nodes.borrow_mut().insert(key, node); |
| 375 | } |
| 376 | |
| 377 | pub(crate) fn remove_pending_location_node(&self, key: &LocationCacheKey) { |
| 378 | self.shared.pending_nodes.borrow_mut().remove(key); |
| 379 | } |
| 380 | |
| 381 | pub(crate) fn get_pending_property_validators( |
| 382 | &self, |
| 383 | key: &LocationCacheKey, |
| 384 | ) -> Option<PendingPropertyValidators> { |
| 385 | self.shared |
| 386 | .pending_property_validators |
| 387 | .borrow() |
| 388 | .get(key) |
| 389 | .cloned() |
| 390 | } |
| 391 | |
| 392 | pub(crate) fn cache_pending_property_validators( |
| 393 | &self, |
| 394 | key: LocationCacheKey, |
| 395 | pending: PendingPropertyValidators, |
| 396 | ) { |
| 397 | self.shared |
| 398 | .pending_property_validators |
| 399 | .borrow_mut() |
| 400 | .insert(key, pending); |
| 401 | } |
| 402 | |
| 403 | pub(crate) fn remove_pending_property_validators(&self, key: &LocationCacheKey) { |
| 404 | self.shared |
| 405 | .pending_property_validators |
| 406 | .borrow_mut() |
| 407 | .remove(key); |
| 408 | } |
| 409 | |
| 410 | fn property_schema_key(schema: &Map<String, Value>) -> PropertyValidatorsPendingKey { |
| 411 | PropertyValidatorsPendingKey::new(schema) |
| 412 | } |
| 413 | |
| 414 | pub(crate) fn get_pending_property_validators_for_schema( |
| 415 | &self, |
| 416 | schema: &Map<String, Value>, |
| 417 | ) -> Option<PendingPropertyValidators> { |
| 418 | let key = Self::property_schema_key(schema); |
| 419 | self.shared |
| 420 | .pending_property_validators_by_schema |
| 421 | .borrow() |
| 422 | .get(&key) |
| 423 | .cloned() |
| 424 | } |
| 425 | |
| 426 | pub(crate) fn cache_pending_property_validators_for_schema( |
| 427 | &self, |
| 428 | schema: &Map<String, Value>, |
| 429 | pending: PendingPropertyValidators, |
| 430 | ) { |
| 431 | let key = Self::property_schema_key(schema); |
| 432 | self.shared |
| 433 | .pending_property_validators_by_schema |
| 434 | .borrow_mut() |
| 435 | .insert(key, pending); |
| 436 | } |
| 437 | |
| 438 | pub(crate) fn remove_pending_property_validators_for_schema( |
| 439 | &self, |
| 440 | schema: &Map<String, Value>, |
| 441 | ) { |
| 442 | let key = Self::property_schema_key(schema); |
| 443 | self.shared |
| 444 | .pending_property_validators_by_schema |
| 445 | .borrow_mut() |
| 446 | .remove(&key); |
| 447 | } |
| 448 | |
| 449 | fn items_schema_key(schema: &Map<String, Value>) -> ItemsValidatorsPendingKey { |
| 450 | ItemsValidatorsPendingKey::new(schema) |
| 451 | } |
| 452 | |
| 453 | pub(crate) fn get_pending_items_validators_for_schema( |
| 454 | &self, |
| 455 | schema: &Map<String, Value>, |
| 456 | ) -> Option<PendingItemsValidators> { |
| 457 | let key = Self::items_schema_key(schema); |
| 458 | self.shared |
| 459 | .pending_items_validators_by_schema |
| 460 | .borrow() |
| 461 | .get(&key) |
| 462 | .cloned() |
| 463 | } |
| 464 | |
| 465 | pub(crate) fn get_pending_items_validators( |
| 466 | &self, |
| 467 | key: &LocationCacheKey, |
| 468 | ) -> Option<PendingItemsValidators> { |
| 469 | self.shared |
| 470 | .pending_items_validators |
| 471 | .borrow() |
| 472 | .get(key) |
| 473 | .cloned() |
| 474 | } |
| 475 | |
| 476 | pub(crate) fn cached_alias_placeholder( |
| 477 | &self, |
| 478 | alias: &Arc<Uri<String>>, |
| 479 | ) -> Option<PendingSchemaNode> { |
| 480 | self.shared.alias_placeholders.borrow().get(alias).cloned() |
| 481 | } |
| 482 | |
| 483 | pub(crate) fn set_alias_placeholder(&self, alias: Arc<Uri<String>>, node: PendingSchemaNode) { |
| 484 | self.shared |
| 485 | .alias_placeholders |
| 486 | .borrow_mut() |
| 487 | .insert(alias, node); |
| 488 | } |
| 489 | |
| 490 | pub(crate) fn remove_alias_placeholder(&self, alias: &Arc<Uri<String>>) { |
| 491 | self.shared.alias_placeholders.borrow_mut().remove(alias); |
| 492 | } |
| 493 | |
| 494 | /// Get a cached compiled regex, or compile and cache it if not present. |
| 495 | pub(crate) fn get_or_compile_regex( |
| 496 | &self, |
| 497 | pattern: &str, |
| 498 | ) -> Result<Arc<fancy_regex::Regex>, ()> { |
| 499 | let translated = self.translated_pattern(pattern)?; |
| 500 | { |
| 501 | let cache = self.shared.pattern_cache.borrow(); |
| 502 | if let Some(entry) = cache.get(pattern) { |
| 503 | if let Some(regex) = &entry.fancy { |
| 504 | return Ok(Arc::clone(regex)); |
| 505 | } |
| 506 | } |
| 507 | } |
| 508 | |
| 509 | let (backtrack_limit, size_limit, dfa_size_limit) = match self.config.pattern_options() { |
| 510 | PatternEngineOptions::FancyRegex { |
| 511 | backtrack_limit, |
| 512 | size_limit, |
| 513 | dfa_size_limit, |
| 514 | } => (backtrack_limit, size_limit, dfa_size_limit), |
| 515 | PatternEngineOptions::Regex { .. } => (None, None, None), |
| 516 | }; |
| 517 | |
| 518 | let mut builder = fancy_regex::RegexBuilder::new(translated.as_ref()); |
| 519 | if let Some(limit) = backtrack_limit { |
| 520 | builder.backtrack_limit(limit); |
| 521 | } |
| 522 | if let Some(limit) = size_limit { |
| 523 | builder.delegate_size_limit(limit); |
| 524 | } |
| 525 | if let Some(limit) = dfa_size_limit { |
| 526 | builder.delegate_dfa_size_limit(limit); |
| 527 | } |
| 528 | let regex = Arc::new(builder.build().map_err(|_| ())?); |
| 529 | |
| 530 | if let Some(entry) = self.shared.pattern_cache.borrow_mut().get_mut(pattern) { |
| 531 | entry.fancy = Some(Arc::clone(®ex)); |
| 532 | } |
| 533 | |
| 534 | Ok(regex) |
| 535 | } |
| 536 | |
| 537 | /// Get a cached compiled standard regex, or compile and cache it if not present. |
| 538 | pub(crate) fn get_or_compile_standard_regex( |
| 539 | &self, |
| 540 | pattern: &str, |
| 541 | ) -> Result<Arc<regex::Regex>, ()> { |
| 542 | let translated = self.translated_pattern(pattern)?; |
| 543 | { |
| 544 | let cache = self.shared.pattern_cache.borrow(); |
| 545 | if let Some(entry) = cache.get(pattern) { |
| 546 | if let Some(regex) = &entry.standard { |
| 547 | return Ok(Arc::clone(regex)); |
| 548 | } |
| 549 | } |
| 550 | } |
| 551 | |
| 552 | let (size_limit, dfa_size_limit) = match self.config.pattern_options() { |
| 553 | PatternEngineOptions::Regex { |
| 554 | size_limit, |
| 555 | dfa_size_limit, |
| 556 | } => (size_limit, dfa_size_limit), |
| 557 | PatternEngineOptions::FancyRegex { .. } => (None, None), |
| 558 | }; |
| 559 | |
| 560 | let mut builder = regex::RegexBuilder::new(translated.as_ref()); |
| 561 | if let Some(limit) = size_limit { |
| 562 | builder.size_limit(limit); |
| 563 | } |
| 564 | if let Some(limit) = dfa_size_limit { |
| 565 | builder.dfa_size_limit(limit); |
| 566 | } |
| 567 | let regex = Arc::new(builder.build().map_err(|_| ())?); |
| 568 | |
| 569 | if let Some(entry) = self.shared.pattern_cache.borrow_mut().get_mut(pattern) { |
| 570 | entry.standard = Some(Arc::clone(®ex)); |
| 571 | } |
| 572 | |
| 573 | Ok(regex) |
| 574 | } |
| 575 | |
| 576 | /// Lookup a reference that is potentially recursive and return already |
| 577 | /// compiled nodes when available. |
| 578 | pub(crate) fn lookup_maybe_recursive( |
| 579 | &self, |
| 580 | reference: &str, |
| 581 | ) -> Result<Option<Box<dyn Validate>>, ValidationError<'static>> { |
| 582 | if self.is_circular_reference(reference)? { |
| 583 | let uri = self |
| 584 | .resolve_reference_uri(reference) |
| 585 | .map_err(ValidationError::from)?; |
| 586 | let key = self.alias_cache_key(Arc::clone(&uri)); |
| 587 | if let Some(node) = self.cached_alias_node(&key) { |
| 588 | return Ok(Some(Box::new(node))); |
| 589 | } |
| 590 | if let Some(node) = self.cached_alias_placeholder(&uri) { |
| 591 | return Ok(Some(Box::new(node))); |
| 592 | } |
| 593 | } |
| 594 | Ok(None) |
| 595 | } |
| 596 | |
| 597 | pub(crate) fn location(&self) -> &Location { |
| 598 | &self.location |
| 599 | } |
| 600 | |
| 601 | pub(crate) fn has_vocabulary(&self, vocabulary: &Vocabulary) -> bool { |
| 602 | if self.draft() < Draft::Draft201909 || vocabulary == &Vocabulary::Core { |
| 603 | true |
| 604 | } else { |
| 605 | self.vocabularies.contains(vocabulary) |
| 606 | } |
| 607 | } |
| 608 | } |
| 609 | |
| 610 | pub(crate) fn build_validator( |
| 611 | config: &ValidationOptions, |
| 612 | schema: &Value, |
| 613 | ) -> Result<Validator, ValidationError<'static>> { |
| 614 | let draft = config.draft_for(schema)?; |
| 615 | let resource_ref = draft.create_resource_ref(schema); |
| 616 | let resource = draft.create_resource(schema.clone()); |
| 617 | let base_uri = if let Some(base_uri) = config.base_uri.as_ref() { |
| 618 | uri::from_str(base_uri)? |
| 619 | } else { |
| 620 | uri::from_str(resource_ref.id().unwrap_or(DEFAULT_BASE_URI))? |
| 621 | }; |
| 622 | |
| 623 | // Build a registry & resolver needed for validator compilation |
| 624 | // Clone resources to drain them without mutating the original config |
| 625 | let pairs = collect_resource_pairs(base_uri.as_str(), resource, config.resources.clone()); |
| 626 | |
| 627 | let registry = if let Some(ref registry) = config.registry { |
| 628 | Arc::new(registry.clone().try_with_resources_and_retriever( |
| 629 | pairs, |
| 630 | &*config.retriever, |
| 631 | draft, |
| 632 | )?) |
| 633 | } else { |
| 634 | Arc::new( |
| 635 | Registry::options() |
| 636 | .draft(draft) |
| 637 | .retriever(Arc::clone(&config.retriever)) |
| 638 | .build(pairs)?, |
| 639 | ) |
| 640 | }; |
| 641 | let vocabularies = registry.find_vocabularies(draft, schema); |
| 642 | let resolver = registry.resolver(base_uri); |
| 643 | |
| 644 | let ctx = Context::new( |
| 645 | config, |
| 646 | ®istry, |
| 647 | resolver, |
| 648 | vocabularies, |
| 649 | draft, |
| 650 | Location::new(), |
| 651 | ); |
| 652 | |
| 653 | // Validate the schema itself |
| 654 | if config.validate_schema { |
| 655 | validate_schema(draft, schema)?; |
| 656 | } |
| 657 | |
| 658 | // Finally, compile the validator |
| 659 | let root = compile(&ctx, resource_ref).map_err(ValidationError::to_owned)?; |
| 660 | let draft = config.draft(); |
| 661 | Ok(Validator { root, draft }) |
| 662 | } |
| 663 | |
| 664 | #[cfg(feature = "resolve-async")] |
| 665 | pub(crate) async fn build_validator_async( |
| 666 | config: &ValidationOptions<Arc<dyn referencing::AsyncRetrieve>>, |
| 667 | schema: &Value, |
| 668 | ) -> Result<Validator, ValidationError<'static>> { |
| 669 | let draft = config.draft_for(schema).await?; |
| 670 | let resource_ref = draft.create_resource_ref(schema); |
| 671 | let resource = draft.create_resource(schema.clone()); |
| 672 | let base_uri = if let Some(base_uri) = config.base_uri.as_ref() { |
| 673 | uri::from_str(base_uri)? |
| 674 | } else { |
| 675 | uri::from_str(resource_ref.id().unwrap_or(DEFAULT_BASE_URI))? |
| 676 | }; |
| 677 | |
| 678 | // Clone resources to drain them without mutating the original config |
| 679 | let pairs = collect_resource_pairs(base_uri.as_str(), resource, config.resources.clone()); |
| 680 | |
| 681 | let registry = if let Some(ref registry) = config.registry { |
| 682 | Arc::new( |
| 683 | registry |
| 684 | .clone() |
| 685 | .try_with_resources_and_retriever_async(pairs, &*config.retriever, draft) |
| 686 | .await?, |
| 687 | ) |
| 688 | } else { |
| 689 | Arc::new( |
| 690 | Registry::options() |
| 691 | .async_retriever(Arc::clone(&config.retriever)) |
| 692 | .draft(draft) |
| 693 | .build(pairs) |
| 694 | .await?, |
| 695 | ) |
| 696 | }; |
| 697 | |
| 698 | let vocabularies = registry.find_vocabularies(draft, schema); |
| 699 | let resolver = registry.resolver(base_uri); |
| 700 | // HACK: `ValidationOptions` struct has a default type parameter as `Arc<dyn Retrieve>` and to |
| 701 | // avoid propagating types everywhere in `Context`, it is easier to just replace the |
| 702 | // retriever to one that implements `Retrieve`, as it is not used anymore anyway. |
| 703 | let config_with_blocking_retriever = config |
| 704 | .clone() |
| 705 | .with_blocking_retriever(crate::retriever::DefaultRetriever); |
| 706 | let ctx = Context::new( |
| 707 | &config_with_blocking_retriever, |
| 708 | ®istry, |
| 709 | resolver, |
| 710 | vocabularies, |
| 711 | draft, |
| 712 | Location::new(), |
| 713 | ); |
| 714 | |
| 715 | if config.validate_schema { |
| 716 | validate_schema(draft, schema)?; |
| 717 | } |
| 718 | |
| 719 | let root = compile(&ctx, resource_ref).map_err(ValidationError::to_owned)?; |
| 720 | let draft = config.draft(); |
| 721 | Ok(Validator { root, draft }) |
| 722 | } |
| 723 | |
| 724 | fn annotations_to_value(annotations: AHashMap<String, Value>) -> Arc<Value> { |
| 725 | let mut object = Map::with_capacity(annotations.len()); |
| 726 | for (key, value) in annotations { |
| 727 | object.insert(key, value); |
| 728 | } |
| 729 | Arc::new(Value::Object(object)) |
| 730 | } |
| 731 | |
| 732 | fn collect_resource_pairs( |
| 733 | base_uri: &str, |
| 734 | resource: Resource, |
| 735 | resources: AHashMap<String, Resource>, |
| 736 | ) -> impl IntoIterator<Item = (Cow<'_, str>, Resource)> { |
| 737 | once((Cow::Borrowed(base_uri), resource)).chain( |
| 738 | resources |
| 739 | .into_iter() |
| 740 | .map(|(uri, resource)| (Cow::Owned(uri), resource)), |
| 741 | ) |
| 742 | } |
| 743 | |
| 744 | fn validate_schema(draft: Draft, schema: &Value) -> Result<(), ValidationError<'static>> { |
| 745 | // Boolean schemas are always valid per the spec, skip validation |
| 746 | if schema.is_boolean() { |
| 747 | return Ok(()); |
| 748 | } |
| 749 | |
| 750 | // For objects, we can skip validation if they're empty (always valid) |
| 751 | if let Some(obj) = schema.as_object() { |
| 752 | if obj.is_empty() { |
| 753 | return Ok(()); |
| 754 | } |
| 755 | } |
| 756 | |
| 757 | let validator = crate::meta::validator_for_draft(draft); |
| 758 | if let Err(error) = validator.validate(schema) { |
| 759 | return Err(error.to_owned()); |
| 760 | } |
| 761 | Ok(()) |
| 762 | } |
| 763 | |
| 764 | /// Compile a JSON Schema instance to a tree of nodes. |
| 765 | pub(crate) fn compile<'a>( |
| 766 | ctx: &Context, |
| 767 | resource: ResourceRef<'a>, |
| 768 | ) -> Result<SchemaNode, ValidationError<'a>> { |
| 769 | let ctx = ctx.in_subresource(resource)?; |
| 770 | compile_with_internal(&ctx, resource, None) |
| 771 | } |
| 772 | |
| 773 | pub(crate) fn compile_with_alias<'a>( |
| 774 | ctx: &Context, |
| 775 | resource: ResourceRef<'a>, |
| 776 | alias: Arc<Uri<String>>, |
| 777 | ) -> Result<SchemaNode, ValidationError<'a>> { |
| 778 | compile_with_internal(ctx, resource, Some(alias)) |
| 779 | } |
| 780 | |
| 781 | #[allow(clippy::needless_pass_by_value)] |
| 782 | fn compile_with_internal<'a>( |
| 783 | ctx: &Context, |
| 784 | resource: ResourceRef<'a>, |
| 785 | alias: Option<Arc<Uri<String>>>, |
| 786 | ) -> Result<SchemaNode, ValidationError<'a>> { |
| 787 | // Check if this alias already has a cached node |
| 788 | if let Some(alias_key) = alias.as_ref() { |
| 789 | let scoped_key = ctx.alias_cache_key(Arc::clone(alias_key)); |
| 790 | if let Some(existing_alias) = ctx.cached_alias_node(&scoped_key) { |
| 791 | return Ok(existing_alias); |
| 792 | } |
| 793 | } |
| 794 | |
| 795 | // Check location-based cache |
| 796 | let key = ctx.location_cache_key(); |
| 797 | if let Some(existing) = ctx.cached_location_node(&key) { |
| 798 | return Ok(existing); |
| 799 | } |
| 800 | |
| 801 | // Check if there's a pending node (circular reference being compiled) |
| 802 | if let Some(pending) = ctx.cached_pending_location_node(&key) { |
| 803 | // If the node has already been initialized, reuse it. Otherwise, we rely on the |
| 804 | // in-flight compilation to finish initialization and continue compiling here. |
| 805 | if let Some(node) = pending.get() { |
| 806 | return Ok(node); |
| 807 | } |
| 808 | } |
| 809 | |
| 810 | // Create placeholder for circular reference detection |
| 811 | let placeholder = PendingSchemaNode::new(); |
| 812 | ctx.cache_pending_location_node(key.clone(), placeholder.clone()); |
| 813 | if let Some(alias_key) = alias.as_ref() { |
| 814 | ctx.set_alias_placeholder(Arc::clone(alias_key), placeholder.clone()); |
| 815 | } |
| 816 | |
| 817 | // Compile the schema |
| 818 | match compile_without_cache(ctx, resource) { |
| 819 | Ok(node) => { |
| 820 | // Initialize the placeholder with the compiled node |
| 821 | placeholder.initialize(&node); |
| 822 | |
| 823 | // Remove from pending cache and add to final cache |
| 824 | ctx.remove_pending_location_node(&key); |
| 825 | ctx.cache_location_node(key.clone(), node.clone()); |
| 826 | |
| 827 | if let Some(alias_key) = alias.as_ref() { |
| 828 | ctx.remove_alias_placeholder(alias_key); |
| 829 | let scoped_key = ctx.alias_cache_key(Arc::clone(alias_key)); |
| 830 | ctx.cache_alias_node(scoped_key, node.clone()); |
| 831 | } |
| 832 | Ok(node) |
| 833 | } |
| 834 | Err(err) => Err(err), |
| 835 | } |
| 836 | } |
| 837 | |
| 838 | fn compile_without_cache<'a>( |
| 839 | ctx: &Context, |
| 840 | resource: ResourceRef<'a>, |
| 841 | ) -> Result<SchemaNode, ValidationError<'a>> { |
| 842 | match resource.contents() { |
| 843 | Value::Bool(value) => match value { |
| 844 | true => Ok(SchemaNode::from_boolean(ctx, None)), |
| 845 | false => Ok(SchemaNode::from_boolean( |
| 846 | ctx, |
| 847 | Some( |
| 848 | keywords::boolean::FalseValidator::compile(ctx.location().clone()) |
| 849 | .expect("Should always compile"), |
| 850 | ), |
| 851 | )), |
| 852 | }, |
| 853 | Value::Object(schema) => { |
| 854 | // A schema could contain validation keywords along with annotations and we need to |
| 855 | // collect annotations separately |
| 856 | if !ctx.supports_adjacent_validation() { |
| 857 | // Older drafts ignore all other keywords if `$ref` is present |
| 858 | if let Some(reference) = schema.get("$ref") { |
| 859 | // Treat all keywords other than `$ref` as annotations |
| 860 | let annotations: AHashMap<String, Value> = schema |
| 861 | .iter() |
| 862 | .filter_map(|(k, v)| { |
| 863 | if k.as_str() == "$ref" { |
| 864 | None |
| 865 | } else { |
| 866 | Some((k.clone(), v.clone())) |
| 867 | } |
| 868 | }) |
| 869 | .collect(); |
| 870 | let annotations = if annotations.is_empty() { |
| 871 | None |
| 872 | } else { |
| 873 | Some(annotations_to_value(annotations)) |
| 874 | }; |
| 875 | return if let Some(validator) = |
| 876 | keywords::ref_::compile_ref(ctx, schema, reference) |
| 877 | { |
| 878 | let validators = vec![(BuiltinKeyword::Ref.into(), validator?)]; |
| 879 | Ok(SchemaNode::from_keywords(ctx, validators, annotations)) |
| 880 | } else { |
| 881 | // Infinite reference to the same location |
| 882 | Ok(SchemaNode::from_boolean(ctx, None)) |
| 883 | }; |
| 884 | } |
| 885 | } |
| 886 | |
| 887 | let mut validators = Vec::with_capacity(schema.len()); |
| 888 | let mut annotations = AHashMap::new(); |
| 889 | for (keyword, value) in schema { |
| 890 | // Check if this keyword is overridden, then check the standard definitions |
| 891 | if let Some(factory) = ctx.get_keyword_factory(keyword) { |
| 892 | let path = ctx.location().join(keyword); |
| 893 | let validator = CustomKeyword::new(factory.init(schema, value, path)?); |
| 894 | let validator: BoxedValidator = Box::new(validator); |
| 895 | validators.push((Keyword::custom(keyword), validator)); |
| 896 | } else if let Some((keyword, validator)) = keywords::get_for_draft(ctx, keyword) |
| 897 | .and_then(|(keyword, f)| f(ctx, schema, value).map(|v| (keyword, v))) |
| 898 | { |
| 899 | validators.push((keyword, validator.map_err(ValidationError::to_owned)?)); |
| 900 | } else if !ctx.is_known_keyword(keyword) { |
| 901 | // Treat all non-validation keywords as annotations |
| 902 | annotations.insert(keyword.clone(), value.clone()); |
| 903 | } |
| 904 | } |
| 905 | let annotations = if annotations.is_empty() { |
| 906 | None |
| 907 | } else { |
| 908 | Some(annotations_to_value(annotations)) |
| 909 | }; |
| 910 | Ok(SchemaNode::from_keywords(ctx, validators, annotations)) |
| 911 | } |
| 912 | _ => Err(ValidationError::multiple_type_error( |
| 913 | Location::new(), |
| 914 | ctx.location().clone(), |
| 915 | resource.contents(), |
| 916 | JsonTypeSet::empty() |
| 917 | .insert(JsonType::Boolean) |
| 918 | .insert(JsonType::Object), |
| 919 | )), |
| 920 | } |
| 921 | } |